Skip to content

usd_chunks.chunk_stage

USD I/O for chunks: layer management, stage synchronization and chunk serialization.

ChunkStageSync ⚓︎

Singleton that keeps a Chunk prim on the stage for every chunk in the scene.

It authors a Chunk prim whenever a Python chunk is added to the scene, then wires each inputs: attribute to the matching param via connect_usd_attr. That keeps the stage live, so any USD tool can save and capture the current param state.

clear_attr_connections ⚓︎

clear_attr_connections(attr)

Clear a chunk prim attr's connections in every layer that holds one.

A connection may have been authored while a different Edit Target was active (or before any Edit Target chunk ran at all); clearing only the current edit layer would silently no-op, leaving that original opinion composed in as a stale, seemingly-undeletable connection.

Parameters:

Name Type Description Default
attr Attribute

The attribute to clear.

required
Source code in usd_chunks/chunk_stage.py
def clear_attr_connections(self, attr: Usd.Attribute) -> None:
    """Clear a chunk prim attr's connections in every layer that holds one.

    A connection may have been authored while a different Edit Target was active (or before
    any Edit Target chunk ran at all); clearing only the current edit layer would silently
    no-op, leaving that original opinion composed in as a stale, seemingly-undeletable
    connection.

    Args:
        attr: The attribute to clear.
    """
    if not (self.initialized and self._stage):
        return
    chunk_utils.clear_connections_everywhere(self._stage, attr)

discarding_stage ⚓︎

discarding_stage()

Delete chunks inside this block without touching the stage they are on.

Deleting a chunk removes its prim, re-heals the exec chain around it and reconciles Edit Targets across the scene -- right for a chunk deleted from a stage that lives on, and wasted work, once per chunk, for a stage that is about to be thrown away whole. File > Open already tears down that way (_reloading); this is the same for any caller that owns the stage it is discarding, such as a script's Scene closing.

Source code in usd_chunks/chunk_stage.py
@contextlib.contextmanager
def discarding_stage(self):
    """Delete chunks inside this block without touching the stage they are on.

    Deleting a chunk removes its prim, re-heals the exec chain around it and reconciles
    Edit Targets across the scene -- right for a chunk deleted from a stage that lives
    on, and wasted work, once per chunk, for a stage that is about to be thrown away
    whole. File > Open already tears down that way (_reloading); this is the same for
    any caller that owns the stage it is discarding, such as a script's Scene closing.
    """
    was_reloading, was_discarding = self._reloading, self._discarding
    self._reloading = self._discarding = True
    try:
        yield
    finally:
        self._reloading, self._discarding = was_reloading, was_discarding

drop_vanished ⚓︎

drop_vanished()

Delete the chunks whose prims left the stage (see _prune_vanished).

Queued to run after the change that removed them has been handed round. A host's undo calls it as soon as the restore returns, so the graph it rebuilds next has no chunk without a prim; calling it again, or with nothing queued, does nothing. A prim that came back meanwhile (a redo before the queue ran) keeps its chunk.

Source code in usd_chunks/chunk_stage.py
def drop_vanished(self) -> None:
    """Delete the chunks whose prims left the stage (see _prune_vanished).

    Queued to run after the change that removed them has been handed round. A host's
    undo calls it as soon as the restore returns, so the graph it rebuilds next has no
    chunk without a prim; calling it again, or with nothing queued, does nothing. A prim
    that came back meanwhile (a redo before the queue ran) keeps its chunk.
    """
    self._drop_scheduled = False
    gone, self._vanished = getattr(self, "_vanished", []), []
    if not gone or not getattr(self, "_scene", None):
        return
    stage = self._scene.get_stage()
    live = {id(c) for c in self._scene.get_chunks()}
    gone = [(path, chunk) for path, chunk in gone
            if id(chunk) in live and not (stage and stage.GetPrimAtPath(Sdf.Path(path)).IsValid())]
    gone.sort(key=lambda item: item[0].count("/"), reverse=True)
    was_reloading = self._reloading
    self._reloading = True
    try:
        for path, chunk in gone:
            logger.info("chunk prim %s left the stage; dropping its chunk", path)
            chunk.request_delete()
    finally:
        self._reloading = was_reloading

initialize ⚓︎

initialize(stage, scene)

Start syncing a stage and scene: listen for chunk and stage changes and load its chunks.

Parameters:

Name Type Description Default
stage Stage

The stage to author chunk prims on.

required
scene SceneSender

The scene whose chunks are synced.

required
Source code in usd_chunks/chunk_stage.py
def initialize(self, stage: Usd.Stage, scene: chunk_scene.SceneSender) -> None:
    """Start syncing a stage and scene: listen for chunk and stage changes and load its chunks.

    Args:
        stage: The stage to author chunk prims on.
        scene: The scene whose chunks are synced.
    """
    self._stage = stage
    self._scene = scene
    # Chunks whose prims left the stage, deleted once the notice that said so is done.
    self._vanished: list = []
    self._drop_scheduled = False
    self._reloading = False
    self._discarding = False
    self._loaded_stage = None
    self._loaded_prim_paths: set[str] = _PathSet()
    _output_children_known.clear()
    self._chunk_prim_paths: dict[int, str] = _PathIndex()  # id(chunk) → current prim path
    # What USD has said changed since the last scan for new chunk prims, used to scope
    # that scan -- see _on_objects_changed and _scan_for_new_chunks. Resyncs are kept
    # apart from info-only changes because they justify different amounts of looking.
    self._pending_resyncs: set[Sdf.Path] = set()
    self._pending_info_changes: set[Sdf.Path] = set()
    # inputs: properties a running cook changed, for _adopt_cooked_inputs once it ends.
    self._cooked_inputs: set[str] = set()
    # id(chunk) -> where its prim composes from (chunk_utils.composition_sources), for
    # _adopt_resynced_inputs to tell a recomposed chunk from one merely resynced.
    self._sources: dict[int, tuple] = {}
    # id(chunk) of chunks whose path is tracked but whose prim is still being made, so
    # _prune_vanished does not take them for gone.
    self._defining: set[int] = set()
    # id(chunk) -> (chunk, input names) edited this solve, for _follow_composed.
    self._follow_pending: dict[int, tuple[core.ChunkBase, set[str]]] = {}
    chunk_cook.after_cook(_adopt_cooked_inputs)
    chunk_cook.after_cook(_sync_hook_gizmos)
    chunk_cook.after_cook(_warn_unit_mismatch)
    # Absolute, ./ or ../, and missing input files: the network's portability.
    chunk_cook.after_cook(asset_paths.check)
    chunk_cook.break_ties_with(branch_place)
    self._attr_changed_listener = NoticeConnection(
        self._on_attr_changed, ChunkNoticeAlias.ATTRIBUTE_CHANGED, globally=True
    )
    self._param_added_listener = NoticeConnection(
        self._on_param_added, ChunkNoticeAlias.PARAM_ADDED, globally=True
    )
    self._dependency_added_listener = NoticeConnection(
        self._on_dependency_added, ChunkNoticeAlias.DEPENDENCY_ADDED, globally=True
    )
    self._dependency_removed_listener = NoticeConnection(
        self._on_dependency_removed, ChunkNoticeAlias.DEPENDENCY_REMOVED, globally=True
    )
    self._objects_changed_listener = NoticeConnection(
        self._on_objects_changed, ChunkNoticeAlias.OBJECT_CHANGED, globally=True
    )
    self._chunk_deleted_listener = NoticeConnection(
        self._on_chunk_deleted, ChunkNoticeAlias.CHUNK_DELETED, globally=True
    )
    self._state_changed_listener = NoticeConnection(
        self._on_state_changed, ChunkNoticeAlias.STATE_CHANGED, globally=True
    )
    self._contents_changed_listener = NoticeConnection(
        self._on_contents_changed, ChunkNoticeAlias.STAGE_CONTENTS_CHANGED, globally=True
    )
    self._chunk_loaded_listener = NoticeConnection(
        self._on_chunk_loaded, ChunkNoticeAlias.CHUNK_LOADED, globally=True
    )

    saved_targets: dict[str, str] = {}
    if stage:
        self._loaded_stage = stage
        # Before load_chunks: rebuilding an Edit Target whose layer doesn't exist yet
        # overwrites its saved selection in USD (see snapshot_edit_target_selections).
        saved_targets = snapshot_edit_target_selections(stage)
        load_chunks(stage, scene, self._loaded_prim_paths)
    self.initialized = True
    if stage:
        restore_edit_target_selections(stage, scene, saved_targets)
        # Same reason as the in-load pass above: opening a file must not rewrite it.
        reconcile_edit_targets(stage, scene, protect_root_layer=True)

record_sources ⚓︎

record_sources(chunks, only_new=False)

Note where each chunk's prim composes from, for _adopt_resynced_inputs.

Parameters:

Name Type Description Default
chunks Iterable[ChunkBase]

The chunks to note.

required
only_new bool

Skip the chunks already noted.

False
Source code in usd_chunks/chunk_stage.py
def record_sources(self, chunks: Iterable[core.ChunkBase], only_new: bool = False) -> None:
    """Note where each chunk's prim composes from, for _adopt_resynced_inputs.

    Args:
        chunks: The chunks to note.
        only_new: Skip the chunks already noted.
    """
    if not self._stage:
        return
    for chunk in chunks:
        if only_new and id(chunk) in self._sources:
            continue
        if path := self._chunk_prim_paths.get(id(chunk)):
            self._sources[id(chunk)] = chunk_utils.composition_sources(
                self._stage.GetPrimAtPath(path))

reload_chunks ⚓︎

reload_chunks()

Reload Chunks: read the chunk modules again and rebuild the graph from the stage.

The stage already holds every chunk's prim, params and wires, so the chunks are dropped and loaded back from it, as File > Open does, with each module's file read afresh. Rebuilding chunks from their modules instead put every param back to its default and lost the wires.

The chunks' layers go before the layer manager starts over: it would otherwise forget them, and each reload left them in the stack. discarding_stage keeps taking them off from rescanning the stage, which found the chunks' prims and built them again mid-teardown.

Source code in usd_chunks/chunk_stage.py
def reload_chunks(self) -> None:
    """Reload Chunks: read the chunk modules again and rebuild the graph from the stage.

    The stage already holds every chunk's prim, params and wires, so the chunks are
    dropped and loaded back from it, as File > Open does, with each module's file read
    afresh. Rebuilding chunks from their modules instead put every param back to its
    default and lost the wires.

    The chunks' layers go before the layer manager starts over: it would otherwise
    forget them, and each reload left them in the stack. discarding_stage keeps taking
    them off from rescanning the stage, which found the chunks' prims and built them
    again mid-teardown.
    """
    if not self._scene or not self._stage:
        return
    stage = self._stage
    with self.discarding_stage(), chunk_registry.ChunkLayerManager().holding_deletes():
        self._teardown_chunks()
    chunk_registry.ChunkRegistry().unload_modules()
    self._loaded_stage = None  # the same stage: reload_for_stage would skip it
    self.reload_for_stage(stage)

reload_for_stage ⚓︎

reload_for_stage(stage)

Reinitialize for a newly opened stage (File > Open).

Safe to call from a deferred context (e.g. QTimer.singleShot) once the stage has fully settled.

Compares stage object identity, not the root layer's identifier string -- re-exporting to the same path and reloading (a common iteration workflow) gives a genuinely new Usd.Stage with the same file path, so comparing identifiers would wrongly skip the reset here, leaving the previous file's chunk objects (and their now-orphaned bookkeeping/positions) still registered and silently re-wrapped alongside the freshly loaded content.

Parameters:

Name Type Description Default
stage Stage

The new stage, or None when the host has dropped its stage.

required
Source code in usd_chunks/chunk_stage.py
def reload_for_stage(self, stage: Usd.Stage) -> None:
    """Reinitialize for a newly opened stage (File > Open).

    Safe to call from a deferred context (e.g. QTimer.singleShot) once the stage has fully
    settled.

    Compares stage *object identity*, not the root layer's identifier string --
    re-exporting to the same path and reloading (a common iteration workflow)
    gives a genuinely new Usd.Stage with the same file path, so comparing
    identifiers would wrongly skip the reset here, leaving the previous file's
    chunk objects (and their now-orphaned bookkeeping/positions) still registered
    and silently re-wrapped alongside the freshly loaded content.

    Args:
        stage: The new stage, or None when the host has dropped its stage.
    """
    if not self._scene:
        return
    if stage is None:
        # The host dropped its stage -- usdview clears it before opening the next file,
        # notifying twice (None, then the new stage). Drop the graph now instead of
        # waiting for the second notice: it belongs to a stage that no longer exists,
        # and usdview keeps pumping the Qt event loop across the gap (it even clears
        # the prim selection in there), so anything the previous graph still reacts to
        # -- a selection sync, a deferred rebuild, a click -- ran against no stage at all.
        self._teardown_chunks()
        self._loaded_stage = None
        self._stage = None
        return
    if stage is self._loaded_stage:
        return
    self._loaded_stage = stage
    self._stage = stage
    chunk_registry.ChunkLayerManager().initialize(stage)
    self._teardown_chunks()
    # Snapshot before load_chunks -- the load itself overwrites any selection whose layer
    # isn't back yet (see snapshot_edit_target_selections).
    saved_targets = snapshot_edit_target_selections(stage)
    load_chunks(stage, self._scene, self._loaded_prim_paths)
    # Re-apply Edit Target selections dropped during load (Menu rejected them before their
    # layers existed), then consolidate any chunk whose saved home doesn't match its
    # topology-resolved target (e.g. a file authored before Edit Target became position-based).
    restore_edit_target_selections(stage, self._scene, saved_targets)
    # protect_root_layer, exactly as initialize() above: opening a file must not rewrite
    # it. This is the path a host that hands over its stage after the plugin is up
    # (usdview, via signalStageReplaced) loads through, and unprotected it migrated
    # every chunk's bookkeeping out of the file's own root layer -- 34 Chunk specs down
    # to 6 on a measured open -- and re-cooked each one it moved, 36 executes for 8.
    # The file on disk survives until something saves that layer; the Sdf cache hands
    # the gutted layer to the next open of the same path in the same process either way.
    reconcile_edit_targets(stage, self._scene, protect_root_layer=True)

ParamClear ⚓︎

Bases: NamedTuple

What clear_param did, for the UI to tell the user.

Attributes:

Name Type Description

Parameters:

Name Type Description Default
layer ForwardRef('Sdf.Layer | None')
None
others ForwardRef('tuple[Sdf.Layer, ...]')
()
default_can_win ForwardRef('bool')
False

branch_place ⚓︎

branch_place(chunk)

Where chunk cooks among chunks no wire orders: as a View cooks them, a Merge's last input first.

A Merge's slots are on the stage, not in the DAG, so the cook queue cannot see them (chunk_cook.break_ties_with). Without this, two branches of a Merge cooked in the order they were made, and a Transform made before the Cube it moves found nothing to move once the scene was opened again. Every graph is walked once per shape of the graph.

Parameters:

Name Type Description Default
chunk ChunkBase

The chunk to place.

required

Returns:

Type Description
int

Its place; lower cooks first.

Source code in usd_chunks/chunk_stage.py
def branch_place(chunk: core.ChunkBase) -> int:
    """Where chunk cooks among chunks no wire orders: as a View cooks them, a Merge's last input first.

    A Merge's slots are on the stage, not in the DAG, so the cook queue cannot see them
    (chunk_cook.break_ties_with). Without this, two branches of a Merge cooked in the order
    they were made, and a Transform made before the Cube it moves found nothing to move
    once the scene was opened again. Every graph is walked once per shape of the graph.

    Args:
        chunk: The chunk to place.

    Returns:
        Its place; lower cooks first.
    """
    global _branch_places
    version = chunk_scheduler.shape_version()
    if _branch_places[0] != version:
        _branch_places = (version, {})
    places = _branch_places[1]
    place = places.get(id(chunk))
    if place is None:
        stage, scene = chunk.get_scene_stage(), chunk.get_scene()
        if stage is not None and scene is not None:
            _place_branches(stage, scene, places)
        place = places.setdefault(id(chunk), len(places))
    return place

can_clear_param ⚓︎

can_clear_param(param)

Whether clear_param has anything to clear, or to say about who still sets param.

Parameters:

Name Type Description Default
param ChunkCommon

The param or vector.

required

Returns:

Type Description
bool

True when any layer holds a value, wire or expression for param, or, for a param

bool

without an attr of its own, when its value is not its default.

Source code in usd_chunks/chunk_stage.py
def can_clear_param(param: core.ChunkCommon) -> bool:
    """Whether clear_param has anything to clear, or to say about who still sets param.

    Args:
        param: The param or vector.

    Returns:
        True when any layer holds a value, wire or expression for param, or, for a param
        without an attr of its own, when its value is not its default.
    """
    if _wire_attrs(param):
        return True
    if (attr := _own_storage_attr(param)) is not None:
        return bool(attr.GetPropertyStack(Usd.TimeCode.Default()))
    return not chunk_utils.values_match(param.raw_value, param.default_value)
chunk_matches_search(chunk, query, scope='both', typos=True)

Whether chunk's name and/or type (per scope) fuzzy-matches query.

Parameters:

Name Type Description Default
chunk ChunkBase

The chunk.

required
query str

The search text; an empty query always matches.

required
scope str

"both", "name" or "type".

'both'
typos bool

False to match a substring only.

True

Returns:

Type Description
bool

True on a match.

Source code in usd_chunks/chunk_stage.py
def chunk_matches_search(chunk: core.ChunkBase, query: str, scope: str = "both", typos: bool = True) -> bool:
    """Whether chunk's name and/or type (per scope) fuzzy-matches query.

    Args:
        chunk: The chunk.
        query: The search text; an empty query always matches.
        scope: "both", "name" or "type".
        typos: False to match a substring only.

    Returns:
        True on a match.
    """
    if not query.strip():
        return True
    candidates = []
    if scope in ("both", "name"):
        candidates.append(chunk.name)
    if scope in ("both", "type"):
        cfg = chunk.get_config()
        if cfg and cfg.module:
            candidates.append(cfg.module)
    return any(fuzzy_matches(query, c, typos=typos) for c in candidates)

chunk_prim_edit_context ⚓︎

chunk_prim_edit_context(chunk=None)

An edit context for authoring on chunk's prim: ports, connections, new child chunks.

Targets the layer chunk's bookkeeping belongs in, not the layer its cooked output goes to, so what is authored inside it is saved with the scene.

Parameters:

Name Type Description Default
chunk ChunkBase | None

The chunk whose prim is authored on.

None

Returns:

Type Description
EditContext

The edit context.

Source code in usd_chunks/chunk_stage.py
def chunk_prim_edit_context(chunk: core.ChunkBase | None = None) -> Usd.EditContext:
    """An edit context for authoring on chunk's prim: ports, connections, new child chunks.

    Targets the layer chunk's bookkeeping belongs in, not the layer its cooked output goes
    to, so what is authored inside it is saved with the scene.

    Args:
        chunk: The chunk whose prim is authored on.

    Returns:
        The edit context.
    """
    return ChunkStageSync()._chunk_prim_edit_context(chunk)

clear_attr_connections ⚓︎

clear_attr_connections(attr)

Remove attr's connections from every layer that has one, not just the edit target.

Source code in usd_chunks/chunk_stage.py
def clear_attr_connections(attr: Usd.Attribute) -> None:
    """Remove attr's connections from every layer that has one, not just the edit target."""
    ChunkStageSync().clear_attr_connections(attr)

clear_param ⚓︎

clear_param(param)

Clear param in the layer its edits go to now, as if it had never been edited there.

Its value, wire and expression text go from that one layer (param_storage_layer). Other layers that set it are left alone: the param takes their value, and they are returned so the UI can say so. With nothing left anywhere, the param lets go of its storage attr, so the next edit makes a new one, as on a new chunk.

A param whose attr cannot go (see _own_storage_attr) is set to its default, which is written into the shared attr. A field that brings its vector back to its default then clears the vector.

A wire the graph drew into the param goes too (see _wire_attrs).

Parameters:

Name Type Description Default
param ChunkCommon

The param or vector to clear.

required

Returns:

Type Description
ParamClear

Where it was cleared, and which layers still set it.

Source code in usd_chunks/chunk_stage.py
def clear_param(param: core.ChunkCommon) -> ParamClear:
    """Clear param in the layer its edits go to now, as if it had never been edited there.

    Its value, wire and expression text go from that one layer (param_storage_layer).
    Other layers that set it are left alone: the param takes their value, and they are
    returned so the UI can say so. With nothing left anywhere, the param lets go of its
    storage attr, so the next edit makes a new one, as on a new chunk.

    A param whose attr cannot go (see _own_storage_attr) is set to its default, which is
    written into the shared attr. A field that brings its vector back to its default then
    clears the vector.

    A wire the graph drew into the param goes too (see _wire_attrs).

    Args:
        param: The param or vector to clear.

    Returns:
        Where it was cleared, and which layers still set it.
    """
    wires = _wire_attrs(param)
    cleared = _clear_param(param)
    for attr in wires:
        clear_attr_connections(attr)
    # The wire went with the attr's specs, out of the param's sight: no write of its own
    # tells the hook, so the chunk's dependencies are brought in line here. The value set
    # above already cooked it with the old source above it, so a chunk that lost one
    # cooks again, now that it no longer sees what that source makes.
    if (
        (chunk := param.get_chunk()) is not None
        and _live_prim(chunk) is not None
        and _reconcile_after_param_wire(chunk)
    ):
        chunk.execute()
    return cleared

commit_order_from_stage ⚓︎

commit_order_from_stage(chunks, stage)

Order chunks for commit by what the stage says they read, not by DAG depth.

chunk_scheduler.commit_order sorts on DagNode depth, which only sees edges someone created with add_dependency. That covers exec wiring (load_chunks mirrors inputs:chunk into add_dependency) but NOT a param port: drag-to-connect authors an @Node.param@ expression, whose live link is a NoticeConnection rather than a DAG edge, so two chunks joined only by a param wire both sit at depth 0 and commit in arbitrary order.

The stage has both kinds of wire, and is already the authority the rest of the wiring code trusts (see exec_dependencies), so order from it instead.

A cycle can't be topologically ordered and must not drop anyone: the first chunk still waiting is emitted and the sort continues, so the result always contains every input chunk exactly once.

Parameters:

Name Type Description Default
chunks list[ChunkBase]

The chunks to order

required
stage Stage | None

The stage holding their chunk prims; None falls back to the depth-based ordering

required

Returns:

Type Description
list[ChunkBase]

list[core.ChunkBase]: The chunks, every chunk preceded by everything it reads from

Source code in usd_chunks/chunk_stage.py
def commit_order_from_stage(
    chunks: list[core.ChunkBase], stage: Usd.Stage | None
) -> list[core.ChunkBase]:
    """Order chunks for commit by what the stage says they read, not by DAG depth.

    chunk_scheduler.commit_order sorts on DagNode depth, which only sees edges someone
    created with add_dependency. That covers exec wiring (load_chunks mirrors inputs:chunk
    into add_dependency) but NOT a param port: drag-to-connect authors an @Node.param@
    expression, whose live link is a NoticeConnection rather than a DAG edge, so two
    chunks joined only by a param wire both sit at depth 0 and commit in arbitrary order.

    The stage has both kinds of wire, and is already the authority the rest of the wiring
    code trusts (see exec_dependencies), so order from it instead.

    A cycle can't be topologically ordered and must not drop anyone: the first chunk still
    waiting is emitted and the sort continues, so the result always contains every input
    chunk exactly once.

    Args:
        chunks (list[core.ChunkBase]): The chunks to order
        stage (Usd.Stage | None): The stage holding their chunk prims; None falls back to
            the depth-based ordering

    Returns:
        list[core.ChunkBase]: The chunks, every chunk preceded by everything it reads from
    """
    ordered = list(chunks)
    if stage is None:
        return chunk_scheduler.commit_order(ordered)

    by_path = {get_chunk_prim_path(c): c for c in ordered}
    deps: dict[int, set[int]] = {}
    for c in ordered:
        prim = stage.GetPrimAtPath(Sdf.Path(get_chunk_prim_path(c)))
        if not (prim and prim.IsValid()):
            deps[id(c)] = set()
            continue
        # Only chunks in this batch can be waited on -- a connection to something outside it
        # would otherwise never be satisfied and stall every dependant into the cycle path.
        deps[id(c)] = {
            id(src) for path in _connected_source_paths(prim)
            if (src := by_path.get(path)) is not None and src is not c
        }

    result: list[core.ChunkBase] = []
    done: set[int] = set()
    waiting = ordered
    while waiting:
        ready = [c for c in waiting if deps[id(c)] <= done]
        if not ready:
            ready = [waiting[0]]  # cycle -- break it at the first chunk still waiting
        result.extend(ready)
        done.update(id(c) for c in ready)
        ready_ids = {id(c) for c in ready}
        waiting = [c for c in waiting if id(c) not in ready_ids]
    return result

connect_exec ⚓︎

connect_exec(stage, scene, src_prim_path, dst_prim_path, input_name=_EXEC_INPUT, append=False)

Author a plain outputs:chunk -> inputs:chunk exec connection between two chunk prims.

For a caller that creates chunks directly (a chunk module wiring its own children, a test, a CLI) rather than via the node graph's drag-to-connect: view-driven execution (recook_for_view) mutes any chunk not reachable from its context's active view, so a programmatically created chunk that's never wired into the exec chain gets hidden the first time its context recooks, even though it authored real content. Mirrors the exec-only path of ChunkGraphView._author_connection; does not handle typed param connections.

Deliberately does NOT also trigger a recook the way _author_connection does for a live drag-to-connect: figuring out which view (if any) is safe to recook through from inside a headless caller, without touching mute/block state anywhere it doesn't have full information about, risks muting unrelated scene content, or the chunk just wired itself. Simpler and safer to author the connection correctly here and let the caller's own next real recook (a view switch, another wire, diving into the context) pick it up.

Parameters:

Name Type Description Default
stage Stage

The stage to author on.

required
scene SceneSender

The scene the chunks live in.

required
src_prim_path str

Prim path of the upstream chunk.

required
dst_prim_path str

Prim path of the downstream chunk.

required
input_name str

The exec slot on dst -- a merge's inputs:chunkN rather than the plain inputs:chunk, so rewiring something into the slot it came out of does not replace whatever branch is already in slot 0.

_EXEC_INPUT
append bool

Add src to the slot's existing wires instead of replacing them, for a slot that several wires stack on.

False

Returns:

Type Description
Attribute | None

The authored inputs:chunk attribute, or None if either prim couldn't be resolved.

Source code in usd_chunks/chunk_stage.py
def connect_exec(
    stage: Usd.Stage,
    scene: chunk_scene.SceneSender,
    src_prim_path: str,
    dst_prim_path: str,
    input_name: str = _EXEC_INPUT,
    append: bool = False,
) -> Usd.Attribute | None:
    """Author a plain outputs:chunk -> inputs:chunk exec connection between two chunk prims.

    For a caller that creates chunks directly (a chunk module wiring its own children, a
    test, a CLI) rather than via the node graph's drag-to-connect: view-driven execution
    (recook_for_view) mutes any chunk not reachable from its context's active view, so a
    programmatically created chunk that's never wired into the exec chain gets hidden the
    first time its context recooks, even though it authored real content. Mirrors the
    exec-only path of ChunkGraphView._author_connection; does not handle typed param
    connections.

    Deliberately does NOT also trigger a recook the way _author_connection does for a
    live drag-to-connect: figuring out which view (if any) is safe to recook through from
    inside a headless caller, without touching mute/block state anywhere it doesn't have
    full information about, risks muting unrelated scene content, or the chunk just wired
    itself. Simpler and safer to author the connection correctly here and let the caller's
    own next real recook (a view switch, another wire, diving into the context) pick it up.

    Args:
        stage: The stage to author on.
        scene: The scene the chunks live in.
        src_prim_path: Prim path of the upstream chunk.
        dst_prim_path: Prim path of the downstream chunk.
        input_name: The exec slot on dst -- a merge's inputs:chunkN rather than the plain
            inputs:chunk, so rewiring something into the slot it came out of does not
            replace whatever branch is already in slot 0.
        append: Add src to the slot's existing wires instead of replacing them, for a slot
            that several wires stack on.

    Returns:
        The authored inputs:chunk attribute, or None if either prim couldn't be resolved.
    """
    dst_prim = stage.GetPrimAtPath(Sdf.Path(dst_prim_path))
    if not dst_prim.IsValid():
        return None
    src_conn_path = Sdf.Path(f"{src_prim_path}.{_EXEC_OUTPUT}")
    dst_attr = dst_prim.GetAttribute(input_name)
    existing = list(dst_attr.GetConnections()) if dst_attr and dst_attr.IsValid() else []
    if append:
        wanted = existing if src_conn_path in existing else existing + [src_conn_path]
    else:
        wanted = [src_conn_path]
    if existing == wanted:
        # Already wired exactly this way: nothing changed, so there is nothing to reconcile.
        # A chunk module wiring its own children (AMD MaterialX Library) calls this on every
        # cook, and the reconcile below is not free. On a scene just opened from disk it
        # re-homes every chunk out of the file's root layer -- deleting the originals, from
        # the layer Sdf hands to the next open or save of that path -- and re-executes each
        # one it moves, which cascades a solve over everything downstream of it. That turned
        # a 60-chunk load into 566 module runs and left 7 chunk definitions in the file.
        # load_chunks guards its own reconcile against both (cook=False,
        # protect_root_layer=True); a re-entrant one from inside a cook bypassed them.
        return dst_attr
    if not (dst_attr and dst_attr.IsValid()):
        dst_attr = dst_prim.CreateAttribute(input_name, Sdf.ValueTypeNames.Token, custom=False)
        if not dst_attr.IsValid():
            return None
    dst_chunk = next((c for c in scene.get_chunks() if get_chunk_prim_path(c) == dst_prim_path), None)
    home = chunk_utils.get_attr_home_layer(dst_attr)
    target = home or chunk_utils.get_bookkeeping_layer(stage, dst_chunk)
    with Usd.EditContext(stage, target):
        dst_attr.SetConnections(wanted)
    reconcile_edit_targets(stage, scene)
    return dst_attr

copy_selected_chunks ⚓︎

copy_selected_chunks()

Store prim paths of selected non-view chunks for later paste.

Source code in usd_chunks/chunk_stage.py
def copy_selected_chunks() -> None:
    """Store prim paths of selected non-view chunks for later paste."""
    global _chunk_clipboard
    registry = chunk_registry.ChunkRegistry()
    if not (scene := registry.scene):
        return
    _chunk_clipboard = [
        get_chunk_prim_path(c)
        for c in scene.get_selected_chunks()
        if not is_terminal_chunk(c)
    ]

creating_at ⚓︎

creating_at(pos, loft=None)

Create chunks at pos (USD space) for the duration of the block.

The module globals are how a caller passes a position and a loft preference down into _define_prim, which is several frames below and has no argument for either. Doing that save/assign/restore by hand in every caller would mean one try/finally per call site, each an opportunity to forget the restore and leave every later chunk landing at someone else's mouse position.

Nesting works: the previous values come back rather than being cleared, so grouping (which creates a group, then materializes chunks inside it) does not lose the outer position when the inner block ends.

Parameters:

Name Type Description Default
pos tuple[float, float] | None

The node position new chunks get, in USD coordinates, or None for the default.

required
loft bool | None

Whether new chunks are lofted to their group's Params page; None leaves it unchanged.

None

Yields:

Type Description

None, with the position and loft preference in effect.

Source code in usd_chunks/chunk_stage.py
@contextlib.contextmanager
def creating_at(pos: tuple[float, float] | None, loft: bool | None = None):
    """Create chunks at `pos` (USD space) for the duration of the block.

    The module globals are how a caller passes a position and a loft preference down into
    _define_prim, which is several frames below and has no argument for either. Doing that
    save/assign/restore by hand in every caller would mean one try/finally per call site,
    each an opportunity to forget the restore and leave every later chunk landing at someone
    else's mouse position.

    Nesting works: the previous values come back rather than being cleared, so grouping
    (which creates a group, then materializes chunks inside it) does not lose the outer
    position when the inner block ends.

    Args:
        pos: The node position new chunks get, in USD coordinates, or None for the default.
        loft: Whether new chunks are lofted to their group's Params page; None leaves it
            unchanged.

    Yields:
        None, with the position and loft preference in effect.
    """
    global _create_node_pos, _loft_new_chunks
    previous_pos, previous_loft = _create_node_pos, _loft_new_chunks
    _create_node_pos = pos
    if loft is not None:
        _loft_new_chunks = loft
    try:
        yield
    finally:
        _create_node_pos = previous_pos
        _loft_new_chunks = previous_loft

delete_attr_specs ⚓︎

delete_attr_specs(prim, attr_name)

Remove attr_name from prim in every layer that has it, not just the edit target.

Source code in usd_chunks/chunk_stage.py
def delete_attr_specs(prim: Usd.Prim, attr_name: str) -> None:
    """Remove attr_name from prim in every layer that has it, not just the edit target."""
    sync = ChunkStageSync()
    if sync.initialized and sync._stage:
        sync._delete_stale_attr_specs(prim, attr_name)

exec_dependencies ⚓︎

exec_dependencies(chunk)

The chunks feeding this one's exec slots, read from the live stage.

The public way for a chunk module to ask "what is immediately upstream of me on the exec chain". chunk.get_dependencies() is not that question: the Python DAG also mirrors param wires, which mean a value flows rather than that one chunk precedes another.

The stage is the authority here, not the DAG: the node graph's drag-to-connect authors the USD connection directly and never calls add_dependency(). _author_prim relies on this, or export would chain chunks in scene.get_chunks() order instead of their real exec order. Every slot is read -- a merge's branches past the first are real inputs, and reconcile_dag_dependencies would otherwise remove edges it cannot see.

Parameters:

Name Type Description Default
chunk ChunkBase

The chunk to read the exec inputs of

required

Returns:

Name Type Description
list list

The upstream chunks, one per connected exec slot

Source code in usd_chunks/chunk_stage.py
def exec_dependencies(chunk: core.ChunkBase) -> list:
    """The chunks feeding this one's *exec* slots, read from the live stage.

    The public way for a chunk module to ask "what is immediately upstream of me on the
    exec chain". chunk.get_dependencies() is not that question: the Python DAG also
    mirrors param wires, which mean a value flows rather than that one chunk precedes
    another.

    The stage is the authority here, not the DAG: the node graph's drag-to-connect authors
    the USD connection directly and never calls add_dependency(). _author_prim relies on
    this, or export would chain chunks in scene.get_chunks() order instead of their real
    exec order. Every slot is read -- a merge's branches past the first are real inputs,
    and reconcile_dag_dependencies would otherwise remove edges it cannot see.

    Args:
        chunk (core.ChunkBase): The chunk to read the exec inputs of

    Returns:
        list: The upstream chunks, one per connected exec slot
    """
    prim = _live_prim(chunk)
    if prim is None:
        return []
    return _chunks_at(str(conn.GetPrimPath()) for conn in exec_input_connections(prim))

exec_downstream ⚓︎

exec_downstream(start, stage, scene)

Every chunk start's exec output reaches, following exec wires forward.

Parameters:

Name Type Description Default
start ChunkBase

The chunk to start from.

required
stage Stage

The stage.

required
scene SceneSender

The scene.

required

Returns:

Type Description
set[ChunkBase]

The downstream chunks. start itself is excluded, even when a cycle leads back to it.

Source code in usd_chunks/chunk_stage.py
def exec_downstream(
    start: core.ChunkBase,
    stage: Usd.Stage,
    scene: chunk_scene.SceneSender,
) -> set[core.ChunkBase]:
    """Every chunk start's exec output reaches, following exec wires forward.

    Args:
        start: The chunk to start from.
        stage: The stage.
        scene: The scene.

    Returns:
        The downstream chunks. start itself is excluded, even when a cycle leads back to it.
    """
    consumers = _exec_consumers(stage)
    prim_to_chunk = {get_chunk_prim_path(c): c for c in scene.get_chunks()}
    start_path = get_chunk_prim_path(start)
    seen = {start_path}
    frontier = [start_path]
    downstream: set = set()
    while frontier:
        for path in consumers.get(frontier.pop(), ()):
            if path in seen:
                continue
            seen.add(path)
            frontier.append(path)
            if (c := prim_to_chunk.get(path)) is not None:
                downstream.add(c)
    return downstream

exec_input_connections ⚓︎

exec_input_connections(prim)

Every exec connection target on prim, strongest branch first.

Source code in usd_chunks/chunk_stage.py
def exec_input_connections(prim: Usd.Prim) -> list[Sdf.Path]:
    """Every exec connection target on prim, strongest branch first."""
    return [conn for attr in iter_exec_inputs(prim) for conn in attr.GetConnections()]

exec_input_slots_for_prim ⚓︎

exec_input_slots_for_prim(prim)

How many positional exec input ports a chunk prim has.

1 for almost everything -- one inputs:chunk that several wires may stack on. Above 1 the slots mean different things and each gets its own port, which is what a Stage Expression Switch needs: slot 0 is the normal path and slot 1 the matched one, which is not a property a merge ordering can express.

A dynamic-slot chunk (has_dynamic_exec_inputs_prim) answers 1 here and is handled by that predicate instead: its slots grow with what is wired in, so a fixed count is the wrong question for it.

Takes the prim: the node graph builds ports from the stage and may have no chunk object. Read off the registry's discovery-time config rather than by importing the module: the config is parsed when chunks are found, so this costs a dict lookup and never triggers a module load while a scene is being built.

Parameters:

Name Type Description Default
prim Prim

The chunk prim.

required

Returns:

Type Description
int

The slot count, at least 1.

Source code in usd_chunks/chunk_stage.py
def exec_input_slots_for_prim(prim: Usd.Prim) -> int:
    """How many positional exec input ports a chunk prim has.

    1 for almost everything -- one inputs:chunk that several wires may stack on. Above 1
    the slots mean different things and each gets its own port, which is what a Stage
    Expression Switch needs: slot 0 is the normal path and slot 1 the matched one, which is
    not a property a merge ordering can express.

    A dynamic-slot chunk (has_dynamic_exec_inputs_prim) answers 1 here and is handled by
    that predicate instead: its slots grow with what is wired in, so a fixed count is the
    wrong question for it.

    Takes the prim: the node graph builds ports from the stage and may have no chunk
    object. Read off the registry's discovery-time config rather than by importing the
    module: the config is parsed when chunks are found, so this costs a dict lookup and
    never triggers a module load while a scene is being built.

    Args:
        prim: The chunk prim.

    Returns:
        The slot count, at least 1.
    """
    if not (prim and prim.IsValid()):
        return 1
    attr = prim.GetAttribute(_CHUNK_TYPE_ATTR)
    module_name = attr.Get() if attr and attr.IsValid() else None
    if not module_name:
        return 1
    module = chunk_registry.ChunkRegistry().get_chunk_module(str(module_name))
    cfg = getattr(module, "config", None) if module else None
    return max(1, int(getattr(cfg, "exec_inputs", 1) or 1)) if cfg else 1

exec_output_path ⚓︎

exec_output_path(chunk)

Return the outputs:chunk attribute path an exec connection to chunk must point at.

A ChunkGroup is its own prim root, so its exec output lives on the group prim itself (/Tab1/Group.outputs:chunk) -- NOT under the root it provides for its children, which is what _resolve_chunk_root returns and would give the nonexistent /Tab1/Group/Group.outputs:chunk.

Parameters:

Name Type Description Default
chunk ChunkBase

The upstream chunk being connected from

required

Returns:

Name Type Description
str str

The absolute outputs:chunk attribute path

Source code in usd_chunks/chunk_stage.py
def exec_output_path(chunk: core.ChunkBase) -> str:
    """Return the outputs:chunk attribute path an exec connection to chunk must point at.

    A ChunkGroup is its own prim root, so its exec output lives on the group prim itself
    (/Tab1/Group.outputs:chunk) -- NOT under the root it provides for its children, which is
    what _resolve_chunk_root returns and would give the nonexistent
    /Tab1/Group/Group.outputs:chunk.

    Args:
        chunk (core.ChunkBase): The upstream chunk being connected from

    Returns:
        str: The absolute outputs:chunk attribute path
    """
    if chunk.has_flag(ChunkFlags.GroupFlags.CONTEXT) and getattr(chunk, "prim_path", None):
        return f"{chunk.prim_path}.{_EXEC_OUTPUT}"
    return f"{_resolve_chunk_root(chunk)}/{chunk.name}.{_EXEC_OUTPUT}"

exec_tails ⚓︎

exec_tails(stage, scene, context=None)

Non-view chunks in context whose exec output nothing takes: the ends of the chains.

Wiring a view to a tail makes the view cook that tail's whole upstream chain. Used to auto-wire a default view.

Parameters:

Name Type Description Default
stage Stage

The stage.

required
scene SceneSender

The scene.

required
context ChunkBase | None

The context, or None for the top level.

None

Returns:

Type Description
list[ChunkBase]

The tail chunks.

Source code in usd_chunks/chunk_stage.py
def exec_tails(
    stage: Usd.Stage,
    scene: chunk_scene.SceneSender,
    context: core.ChunkBase | None = None,
) -> list[core.ChunkBase]:
    """Non-view chunks in context whose exec output nothing takes: the ends of the chains.

    Wiring a view to a tail makes the view cook that tail's whole upstream chain. Used to
    auto-wire a default view.

    Args:
        stage: The stage.
        scene: The scene.
        context: The context, or None for the top level.

    Returns:
        The tail chunks.
    """
    consumed = _exec_consumers(stage)
    return [
        c for c in scene.get_chunks()
        if not is_terminal_chunk(c) and is_node_in_context(c, context)
        and get_chunk_prim_path(c) not in consumed
    ]

exec_upstream ⚓︎

exec_upstream(chunk, seen=None)

chunk and everything upstream of it, following exec wires only.

Not view_cook_list, which follows param wires and lofts as well and answers "what has to cook for this view". This answers "which chunks make up this branch": suppressing a branch has to suppress the whole of it, not merely the chunk plugged into the slot -- the rest would carry on authoring into the composed stage.

Guarded against revisiting: a diamond (two branches sharing a source) would otherwise walk the shared part once per path, and a cycle would not terminate at all.

Parameters:

Name Type Description Default
chunk ChunkBase

The chunk to start from.

required
seen set | None

Chunks already visited; filled in and returned.

None

Returns:

Type Description
set

The chunks in the branch, chunk included.

Source code in usd_chunks/chunk_stage.py
def exec_upstream(chunk: core.ChunkBase, seen: set | None = None) -> set:
    """`chunk` and everything upstream of it, following exec wires only.

    Not view_cook_list, which follows param wires and lofts as well and answers "what has
    to cook for this view". This answers "which chunks make up this branch": suppressing a
    branch has to suppress the whole of it, not merely the chunk plugged into the slot --
    the rest would carry on authoring into the composed stage.

    Guarded against revisiting: a diamond (two branches sharing a source) would otherwise
    walk the shared part once per path, and a cycle would not terminate at all.

    Args:
        chunk: The chunk to start from.
        seen: Chunks already visited; filled in and returned.

    Returns:
        The chunks in the branch, `chunk` included.
    """
    seen = set() if seen is None else seen
    if any(c is chunk for c in seen):
        return seen
    seen.add(chunk)
    for dep in exec_dependencies(chunk):
        exec_upstream(dep, seen)
    return seen

export_chunks ⚓︎

export_chunks(scene, path, relative_paths=None)

Export the current chunk graph as one clean, portable USD layer.

Copies each chunk's already-composed, already-correctly-wired prim spec straight across from the live stage -- connections (inputs:chunk exec wiring, expression refs), values, node positions, everything, exactly as currently authored -- rather than re-deriving them from Python object state. The Python DAG (chunk.get_dependencies()) is empty for a graph wired live in the node graph, which authors the USD-level inputs:chunk connection directly and never calls add_dependency(), so re-deriving would chain chunks in iteration order instead of their real exec order.

UsdUtils.FlattenLayerStack resolves the live composition first -- chunk-prim bookkeeping can be split across several layers (chunk_utils.get_bookkeeping_layer, since it follows Edit Target) -- giving each prim/attr its correct final composed state to copy from, regardless of which layer(s) it's actually scattered across.

Only chunk prims themselves are copied -- reopening regenerates everything a chunk drives by re-running load_chunks' cook pass, not by replaying a content snapshot. Content that isn't reproduced by re-execution (an RBD Solver's bake) or that never went through a chunk at all does not round-trip through this.

The stage's up-axis and units are stamped onto the file as well. Sdf.CopySpec copies prim specs and nothing else, and those two are not prim data: they are stage metadata, resolved only from a stage's own root/session layer and never composed up from anything underneath. Without an opinion of its own the exported file falls back to USD's global default: a Z-up, centimetre scene would reopen Y-up in metres, with every chunk-authored prim lying on its side at a hundredth of its size.

Chunks that arrive by composition -- a sequence network sublayered into this file, or referenced in under a chunkgroup -- are not this file's to write out. Only the layers the chunk system owns are flattened (_owned_stage), so what gets copied for such a chunk is the sparse over this scene put on it, and a chunk with no local opinion at all is skipped rather than copied from a spec that does not exist locally. The root layer's foreign sublayers are carried onto the file so the sequence stays composed underneath those overs on reopen. This is what lets a shot tweak a sequence's network and save without inlining it.

Parameters:

Name Type Description Default
scene SceneSender

The scene to export.

required
path str | Path

The file to write.

required
relative_paths bool | None

Write the files the chunks read relative to path's folder where they sit under it, as USD search paths, so the network and its inputs move together (asset_paths). None: as the network's Stage Settings say, on if none.

None
Source code in usd_chunks/chunk_stage.py
def export_chunks(
    scene: chunk_scene.SceneSender, path: str | Path, relative_paths: bool | None = None,
) -> None:
    """Export the current chunk graph as one clean, portable USD layer.

    Copies each chunk's already-composed, already-correctly-wired prim spec straight across
    from the live stage -- connections (inputs:chunk exec wiring, expression refs), values,
    node positions, everything, exactly as currently authored -- rather than re-deriving
    them from Python object state. The Python DAG (chunk.get_dependencies()) is empty for a
    graph wired live in the node graph, which authors the USD-level inputs:chunk connection
    directly and never calls add_dependency(), so re-deriving would chain chunks in
    iteration order instead of their real exec order.

    UsdUtils.FlattenLayerStack resolves the live composition first -- chunk-prim bookkeeping
    can be split across several layers (chunk_utils.get_bookkeeping_layer, since it follows
    Edit Target) -- giving each prim/attr its correct final composed state to copy from,
    regardless of which layer(s) it's actually scattered across.

    Only chunk prims themselves are copied -- reopening regenerates everything a chunk
    drives by re-running load_chunks' cook pass, not by replaying a content snapshot.
    Content that isn't reproduced by re-execution (an RBD Solver's bake) or that never
    went through a chunk at all does not round-trip through this.

    The stage's up-axis and units are stamped onto the file as well. Sdf.CopySpec copies
    prim specs and nothing else, and those two are not prim data: they are stage
    metadata, resolved only from a stage's own root/session layer and never composed up
    from anything underneath. Without an opinion of its own the exported file falls back
    to USD's global default: a Z-up, centimetre scene would reopen Y-up in metres, with
    every chunk-authored prim lying on its side at a hundredth of its size.

    Chunks that arrive by composition -- a sequence network sublayered into this file, or
    referenced in under a chunkgroup -- are not this file's to write out. Only the layers
    the chunk system owns are flattened (_owned_stage), so what gets copied for such a
    chunk is the sparse `over` this scene put on it, and a chunk with no local opinion at
    all is skipped rather than copied from a spec that does not exist locally. The root
    layer's foreign sublayers are carried onto the file so the sequence stays composed
    underneath those overs on reopen. This is what lets a shot tweak a sequence's network
    and save without inlining it.

    Args:
        scene: The scene to export.
        path: The file to write.
        relative_paths: Write the files the chunks read relative to path's folder where
            they sit under it, as USD search paths, so the network and its inputs move
            together (asset_paths). None: as the network's Stage Settings say, on if none.
    """
    stage = scene.get_stage()
    if not stage:
        return
    # Nodes a script made are laid out first, rather than written in one long row.
    if hasattr(scene, "lay_out_scripted"):
        scene.lay_out_scripted()
    dst = saved_layer(scene, path, relative_paths)
    dst.Export(str(path))
    _reload_cached_layer(path)
    # Each chunk's result, kept for the next open of this file (open_cache).
    saved = Sdf.Layer.FindOrOpen(str(path))
    if saved is not None:
        open_cache.store(
            scene.get_chunks(), stage, saved, ChunkLayerManager().get_layer,
            chunk_cook.settled,
        )

export_network ⚓︎

export_network(scene, group, path)

Write one group's network to its own file, the way export_chunks writes a scene's.

The group goes at /chunks/ with its chunks beneath it, wiring rebased to the new root, and the exec input from the graph outside dropped. Built from export_chunks' own layer rather than a second copy of its rules, so a published network is exactly the group as a save would have written it: composed, sparse where it was composed in, arcs kept.

Parameters:

Name Type Description Default
scene SceneSender

The scene.

required
group ChunkBase

The chunkgroup to export.

required
path str | Path

The file to write.

required

Returns:

Type Description
str

The group's prim path in the file -- what a host references.

Raises:

Type Description
ValueError

There is no stage, or the group has nothing to export.

Source code in usd_chunks/chunk_stage.py
def export_network(scene: chunk_scene.SceneSender, group: core.ChunkBase, path: str | Path) -> str:
    """Write one group's network to its own file, the way export_chunks writes a scene's.

    The group goes at /chunks/<name> with its chunks beneath it, wiring rebased to the new
    root, and the exec input from the graph outside dropped. Built from export_chunks' own
    layer rather than a second copy of its rules, so a published network is exactly the
    group as a save would have written it: composed, sparse where it was composed in, arcs
    kept.

    Args:
        scene: The scene.
        group: The chunkgroup to export.
        path: The file to write.

    Returns:
        The group's prim path in the file -- what a host references.

    Raises:
        ValueError: There is no stage, or the group has nothing to export.
    """
    stage = scene.get_stage()
    if not stage:
        raise ValueError("no stage to export from")
    src_root = Sdf.Path(get_chunk_prim_path(group))
    dst_root = Sdf.Path(_CHUNKS_ROOT).AppendChild(src_root.name)
    whole = _export_layer(scene, Path(path))
    if whole.GetPrimAtPath(src_root) is None:
        raise ValueError(f"{src_root} has nothing to export")
    out = Sdf.Layer.CreateAnonymous()
    scope = Sdf.CreatePrimInLayer(out, Sdf.Path(_CHUNKS_ROOT))
    scope.specifier = Sdf.SpecifierDef
    scope.typeName = _CHUNKS_ROOT_TYPENAME
    Sdf.CopySpec(whole, src_root, out, dst_root)
    _rebase_paths_in_layer(out, src_root, dst_root)
    group_spec = out.GetPrimAtPath(dst_root)
    exec_in = group_spec.properties.get(chunk_naming.EXEC_INPUT)
    if exec_in is not None:
        exec_in.connectionPathList.ClearEdits()
    stamp_stage_metadata(out, stage)
    out.Export(str(path))
    _reload_cached_layer(path)
    return str(dst_root)

find_group_active_view ⚓︎

find_group_active_view(group, stage, scene)

The View a group's saved slot names, else its lowest-slot View (inert ones last).

Parameters:

Name Type Description Default
group ChunkBase

The group.

required
stage Stage

The stage.

required
scene SceneSender

The scene.

required

Returns:

Type Description
ChunkBase | None

The view chunk, or None if the group has no inner view.

Source code in usd_chunks/chunk_stage.py
def find_group_active_view(
    group: core.ChunkBase, stage: Usd.Stage, scene: chunk_scene.SceneSender
) -> core.ChunkBase | None:
    """The View a group's saved slot names, else its lowest-slot View (inert ones last).

    Args:
        group: The group.
        stage: The stage.
        scene: The scene.

    Returns:
        The view chunk, or None if the group has no inner view.
    """
    return _saved_view(stage, scene, group) or next(iter(_views_by_slot(stage, scene, group)), None)

find_output_chunk ⚓︎

find_output_chunk(stage, scene, context)

The Output of context's graph, or None if it has none.

A group's Output is its own, never the parent graph's (prim-path membership). For the top level (context None) the shallowest Output wins, so a group's inner Output is never taken for the file's.

Parameters:

Name Type Description Default
stage Stage

The stage.

required
scene SceneSender

The scene.

required
context ChunkBase | None

The graph to look in, or None for the top level.

required

Returns:

Type Description
ChunkBase | None

The Output chunk, or None.

Source code in usd_chunks/chunk_stage.py
def find_output_chunk(
    stage: Usd.Stage, scene: chunk_scene.SceneSender, context: core.ChunkBase | None
) -> core.ChunkBase | None:
    """The Output of context's graph, or None if it has none.

    A group's Output is its own, never the parent graph's (prim-path membership). For the
    top level (context None) the shallowest Output wins, so a group's inner Output is never
    taken for the file's.

    Args:
        stage: The stage.
        scene: The scene.
        context: The graph to look in, or None for the top level.

    Returns:
        The Output chunk, or None.
    """
    outputs = [c for c in scene.get_chunks() if is_output_chunk(c)]
    if context is not None:
        return next((c for c in outputs if is_node_in_context(c, context)), None)
    return min(outputs, key=lambda c: Sdf.Path(get_chunk_prim_path(c)).pathElementCount, default=None)

find_view_chunk_for_slot ⚓︎

find_view_chunk_for_slot(slot, stage, scene, context=None)

The view chunk assigned to slot, or None.

Each graph (tab or group) has its own slots, so a tab view and a group view can both be slot 1.

Parameters:

Name Type Description Default
slot int

The view slot.

required
stage Stage

The stage.

required
scene SceneSender

The scene.

required
context ChunkBase | None

The graph to look in; None looks everywhere.

None

Returns:

Type Description
ChunkBase | None

The view chunk, or None.

Source code in usd_chunks/chunk_stage.py
def find_view_chunk_for_slot(
    slot: int,
    stage: Usd.Stage,
    scene: chunk_scene.SceneSender,
    context: core.ChunkBase | None = None,
) -> core.ChunkBase | None:
    """The view chunk assigned to slot, or None.

    Each graph (tab or group) has its own slots, so a tab view and a group view can both be
    slot 1.

    Args:
        slot: The view slot.
        stage: The stage.
        scene: The scene.
        context: The graph to look in; None looks everywhere.

    Returns:
        The view chunk, or None.
    """
    for c in scene.get_chunks():
        if not is_view_chunk(c):
            continue
        if context is not None and not is_node_in_context(c, context):
            continue
        prim = stage.GetPrimAtPath(Sdf.Path(get_chunk_prim_path(c)))
        if prim.IsValid() and prim.GetAttribute("view:slot").Get() == slot:
            return c
    return None

flatten_without_chunks ⚓︎

flatten_without_chunks(stage)

Flatten the stage to a layer carrying the result but none of the recipe.

A Chunk prim left in a delivered file is not inert: open it anywhere usd_chunks is installed and the network reloads and re-cooks, overriding the very geometry the file was exported to carry. Stripping them is what makes the output plain USD that anyone can open with nothing installed.

FlattenLayerStack rather than Stage.Export, because it keeps references as references where Export inlines the referenced asset outright -- which stops mattering only while a network builds all its own geometry.

Shallowest path first, so removing a parent Chunk takes its children with it and the later lookup for those children simply finds nothing.

The stage's up-axis and units are stamped on as well (stamp_stage_metadata): flattening carries them only when the root layer itself authors them, which a new scene never has. The prims a Prune Prim pruned are left out (pruned_paths).

Source code in usd_chunks/chunk_stage.py
def flatten_without_chunks(stage):
    """Flatten the stage to a layer carrying the result but none of the recipe.

    A Chunk prim left in a delivered file is not inert: open it anywhere usd_chunks is
    installed and the network reloads and re-cooks, overriding the very geometry the
    file was exported to carry. Stripping them is what makes the output plain USD that
    anyone can open with nothing installed.

    FlattenLayerStack rather than Stage.Export, because it keeps references as
    references where Export inlines the referenced asset outright -- which stops
    mattering only while a network builds all its own geometry.

    Shallowest path first, so removing a parent Chunk takes its children with it and
    the later lookup for those children simply finds nothing.

    The stage's up-axis and units are stamped on as well (stamp_stage_metadata): flattening
    carries them only when the root layer itself authors them, which a new scene never has.
    The prims a Prune Prim pruned are left out (pruned_paths).
    """
    flat = UsdUtils.FlattenLayerStack(stage)
    strip_chunks(flat)
    remove_prim_specs(flat, pruned_paths(stage, layer_stack_ids(stage)))
    stamp_stage_metadata(flat, stage)
    return flat

fuzzy_matches ⚓︎

fuzzy_matches(term, candidate, threshold=0.6, typos=True)

Whether term matches candidate, tolerating small typos.

An exact case-insensitive substring always matches (the common case: the user typed the name or type correctly, or a meaningful fragment of it); otherwise difflib's typo-tolerant ratio decides.

Parameters:

Name Type Description Default
term str

What the user typed; blank matches everything.

required
candidate str

The text to match against.

required
threshold float

The minimum similarity ratio for a non-substring match.

0.6
typos bool

False to match a substring only.

True

Returns:

Type Description
bool

True on a match.

Source code in usd_chunks/chunk_stage.py
def fuzzy_matches(term: str, candidate: str, threshold: float = 0.6, typos: bool = True) -> bool:
    """Whether term matches candidate, tolerating small typos.

    An exact case-insensitive substring always matches (the common case: the user typed the
    name or type correctly, or a meaningful fragment of it); otherwise difflib's
    typo-tolerant ratio decides.

    Args:
        term: What the user typed; blank matches everything.
        candidate: The text to match against.
        threshold: The minimum similarity ratio for a non-substring match.
        typos: False to match a substring only.

    Returns:
        True on a match.
    """
    term = term.strip().lower()
    if not term:
        return True
    candidate = candidate.lower()
    if term in candidate:
        return True
    if not typos:
        return False
    # SequenceMatcher's ratio is normalised by combined length, so two short names sharing
    # a prefix score on the overlap alone: "haha" comes out 0.73 similar to "haha222" and
    # was being returned by a search for "haha222". Length is what separates the two cases
    # -- a typo is a character or two out of place, never a name three characters shorter.
    # Deliberate fragments ("trans" for "transform_scale") never reach this line; they have
    # already matched as a substring above.
    if abs(len(term) - len(candidate)) > _TYPO_SLACK:
        return False
    return difflib.SequenceMatcher(None, term, candidate).ratio() >= threshold

gate_to_branches ⚓︎

gate_to_branches(node, live)

Let the branches at live reach the stage and suppress every other input's.

The one implementation behind both gating chunks -- the Switch, picking a branch by index, and the Stage Expression Switch, picking it by what a variable says. They differ only in how that set is chosen, so the muting lives here once.

Suppression is a block plus a layer mute, never the DISABLED state, which belongs to the user: a chunk reaching in to set and clear it on chunks it does not own means every flip risks undoing theirs. A branch contributes because its layers are in the stage, not because it is wired, so cutting the connection instead would leave its prims composed exactly as before and gate nothing.

Parameters:

Name Type Description Default
node ChunkBase

The gating chunk.

required
live set[int]

Indices into the gate's exec dependencies (exec_dependencies) whose branches stay live.

required

Returns:

Type Description
tuple[set, set]

tuple[set, set]: the chunks kept live, and the chunks muted

Source code in usd_chunks/chunk_stage.py
def gate_to_branches(node: core.ChunkBase, live: set[int]) -> tuple[set, set]:
    """Let the branches at `live` reach the stage and suppress every other input's.

    The one implementation behind both gating chunks -- the Switch, picking a branch by
    index, and the Stage Expression Switch, picking it by what a variable says. They differ
    only in how that set is chosen, so the muting lives here once.

    Suppression is a **block** plus a layer mute, never the DISABLED state, which belongs to
    the user: a chunk reaching in to set and clear it on chunks it does not own means every
    flip risks undoing theirs. A branch contributes because its layers are in the stage, not
    because it is wired, so cutting the connection instead would leave its prims composed
    exactly as before and gate nothing.

    Args:
        node: The gating chunk.
        live: Indices into the gate's exec dependencies (exec_dependencies) whose branches
            stay live.

    Returns:
        tuple[set, set]: the chunks kept live, and the chunks muted
    """
    stage = node.get_scene_stage()
    inputs = exec_dependencies(node)

    # The live branches first, and they win: a chunk feeding two branches must stay live if
    # either of the ones it feeds is chosen. Without this a shared upstream -- the part of
    # the thread above the fork -- would be muted along with the branch not taken.
    keep = set()
    for i in live:
        if 0 <= i < len(inputs):
            keep |= exec_upstream(inputs[i])

    # Collected rather than applied one at a time: every mute is a full-stage recomposition,
    # so a gate that moves six branches would make six of them. set_chunks_muted does the
    # lot in one.
    to_mute = []
    for slot, dep in enumerate(inputs):
        if slot in live:
            continue
        for c in exec_upstream(dep):
            if c in keep:
                continue
            to_mute.append(c)

    # Un-mute only what this chunk muted itself. A live branch can hold another gate's
    # suppressed branch, and un-muting everything reachable switched that one back on.
    mine = _gate_record(node)
    to_unmute = [c for c in keep if get_chunk_prim_path(c) in mine]

    # Muted by an earlier evaluation and no longer upstream of this chunk at all: leaving it
    # blocked would strand a branch the user has already disconnected. Resolved against the
    # whole scene, since the record is transitive -- most of what it holds was never a
    # direct input -- and by prim path, since a name is unique only within one context.
    stranded = mine - {get_chunk_prim_path(c) for c in to_mute} - {get_chunk_prim_path(c) for c in keep}
    if stranded:
        by_path = {
            get_chunk_prim_path(c): c
            for c in chunk_registry.ChunkRegistry().scene.get_chunks()
        }
        for path in stranded:
            if (c := by_path.get(path)) is not None:
                to_unmute.append(c)

    muted, _unmuted = set_chunks_muted(stage, to_mute, to_unmute)

    if muted:
        _redefine_orphaned_ancestors(stage)

    if param := node.get_param(GATE_RECORD_PARAM):
        param.value = "\n".join(sorted(get_chunk_prim_path(c) for c in muted))
    return keep, muted

get_chunk_prim ⚓︎

get_chunk_prim(chunk)

Chunk's prim on the live stage, or None if the session has none for it yet.

Source code in usd_chunks/chunk_stage.py
def get_chunk_prim(chunk: core.ChunkBase) -> Usd.Prim | None:
    """Chunk's prim on the live stage, or None if the session has none for it yet."""
    sync = ChunkStageSync()
    if not sync.initialized or not sync._stage:
        return None
    prim_path = sync._chunk_prim_paths.get(id(chunk))
    if not prim_path:
        return None
    prim = sync._stage.GetPrimAtPath(Sdf.Path(prim_path))
    return prim if prim and prim.IsValid() else None

get_search_query ⚓︎

get_search_query(context)

The context's persisted Params-page search query.

An absent attribute means empty, as if nothing was ever typed.

Parameters:

Name Type Description Default
context ChunkBase

The context.

required

Returns:

Type Description
str

The query, "" if none.

Source code in usd_chunks/chunk_stage.py
def get_search_query(context: core.ChunkBase) -> str:
    """The context's persisted Params-page search query.

    An absent attribute means empty, as if nothing was ever typed.

    Args:
        context: The context.

    Returns:
        The query, "" if none.
    """
    stage = context.get_scene_stage()
    path = _context_own_prim_path(context)
    prim = stage.GetPrimAtPath(Sdf.Path(path)) if (stage and path) else None
    attr = prim.GetAttribute("filter:searchQuery") if (prim and prim.IsValid()) else None
    val = attr.Get() if (attr and attr.IsValid()) else None
    return val or ""

get_search_scope ⚓︎

get_search_scope(context)

The context's persisted search scope: one of "both", "name", "type".

An absent attribute, or an unrecognized stored value, means "both" (search name and type).

Parameters:

Name Type Description Default
context ChunkBase

The context.

required

Returns:

Type Description
str

The scope.

Source code in usd_chunks/chunk_stage.py
def get_search_scope(context: core.ChunkBase) -> str:
    """The context's persisted search scope: one of "both", "name", "type".

    An absent attribute, or an unrecognized stored value, means "both" (search name and
    type).

    Args:
        context: The context.

    Returns:
        The scope.
    """
    stage = context.get_scene_stage()
    path = _context_own_prim_path(context)
    prim = stage.GetPrimAtPath(Sdf.Path(path)) if (stage and path) else None
    attr = prim.GetAttribute("filter:searchScope") if (prim and prim.IsValid()) else None
    val = attr.Get() if (attr and attr.IsValid()) else None
    return val if val in _SEARCH_SCOPES else "both"

get_upstream_stage ⚓︎

get_upstream_stage(stage, scene, chunk)

A throwaway stage of every chunk layer except chunk itself and its real downstream.

The raw root layer is included too. It is for a read that must never be influenced by a downstream chunk's edit to the same prim -- e.g. Scatter reading a mesh a Transform wired after it also targets.

Unlike exec_with_hidden_view, this never mutates the real stage, mutes any real layer, or executes anything -- it's a pure composition of already-existing layers into a scratch root, discarded once the caller is done reading. That makes it safe to call unconditionally from inside a chunk's own execute() (reactive param changes included), which is where it's actually needed: a plain param edit never goes through recook_for_view at all, so nothing else protects that path. Chunks are included by "not downstream of me", not "reachable upstream of me" -- a mesh from an unwired sibling chunk (e.g. a Mesh chunk the user picked by path, never wired into the exec chain) still resolves correctly; only genuine downstream chunks are excluded.

Included layers keep their REAL relative strength order (read off the actual graph layers' subLayerPaths), not scene.get_chunks()'s iteration order. Two included chunks can both touch the same prim without conflicting with each other (e.g. whatever created a mesh, and a Transform rotating it, both authoring xformOp:transform on the same prim) -- the real order already correctly resolves that via the existing sort-key/view-driven ranking, and rebuilding it from scratch here would silently pick a different, wrong winner.

Parameters:

Name Type Description Default
stage Stage

The live stage.

required
scene SceneSender

The scene.

required
chunk ChunkBase

The chunk doing the read.

required

Inside a masked cook (skip_cook) the scratch stage is masked the same way, and what the chunk looks up on it is watched like the cook stage itself: it is where such a chunk does its reading.

Returns:

Type Description
Stage

The scratch stage.

Source code in usd_chunks/chunk_stage.py
def get_upstream_stage(stage: Usd.Stage, scene: chunk_scene.SceneSender, chunk: core.ChunkBase) -> Usd.Stage:
    """A throwaway stage of every chunk layer except `chunk` itself and its real downstream.

    The raw root layer is included too. It is for a read that must never be influenced by a
    downstream chunk's edit to the same prim -- e.g. Scatter reading a mesh a Transform wired
    *after* it also targets.

    Unlike exec_with_hidden_view, this never mutates the real stage, mutes any real layer, or
    executes anything -- it's a pure composition of already-existing layers into a scratch
    root, discarded once the caller is done reading. That makes it safe to call
    unconditionally from inside a chunk's own execute() (reactive param changes included),
    which is where it's actually needed: a plain param edit never goes through
    recook_for_view at all, so nothing else protects that path. Chunks are included by "not
    downstream of me", not "reachable upstream of me" -- a mesh from an unwired sibling chunk
    (e.g. a Mesh chunk the user picked by path, never wired into the exec chain) still
    resolves correctly; only genuine downstream chunks are excluded.

    Included layers keep their REAL relative strength order (read off the actual graph
    layers' subLayerPaths), not scene.get_chunks()'s iteration order. Two included chunks can
    both touch the same prim without conflicting with each other (e.g. whatever created a
    mesh, and a Transform rotating it, both authoring xformOp:transform on the same prim) --
    the real order already correctly resolves that via the existing sort-key/view-driven
    ranking, and rebuilding it from scratch here would silently pick a different, wrong
    winner.

    Args:
        stage: The live stage.
        scene: The scene.
        chunk: The chunk doing the read.

    Inside a masked cook (skip_cook) the scratch stage is masked the same way, and what the
    chunk looks up on it is watched like the cook stage itself: it is where such a chunk
    does its reading.

    Returns:
        The scratch stage.
    """
    lm = chunk_registry.ChunkLayerManager()
    # Which chunks are downstream is read off the chunk prims, which a cook stage (the
    # stage a module is handed in a masked cook) populates only in part.
    stage = scene.get_stage() or stage
    excluded = exec_downstream(chunk, stage, scene) | {chunk}
    excluded_ids = {layer.identifier for c in excluded if (layer := lm.get_layer(c)) is not None}
    layer_ids: list = []
    for g_layer in lm.graph_layers.values():
        for ident in g_layer.subLayerPaths:
            if ident in excluded_ids or ident in layer_ids:
                continue
            if stage.IsLayerMuted(ident):
                # A muted layer is one the real stage is currently showing nothing of: its
                # chunk is dormant -- blocked (outside the active view's cook set, e.g. just
                # disconnected) or explicitly disabled. Rebuilding the composition from raw
                # subLayerPaths would resurrect it here, so a dormant chunk's stale content
                # would keep driving everyone else's reads while invisible everywhere else.
                #
                # Disconnecting is exactly when this matters: while a chunk is still wired
                # downstream the exclusion above already covers it, and cutting it loose is
                # what would let it back in. A Prune shaken off a chain, say, must not leave
                # its orphaned "active = false" hiding geometry from the chunks it fed.
                continue
            layer_ids.append(ident)
    scratch_root = Sdf.Layer.CreateAnonymous()
    scratch_root.subLayerPaths = layer_ids + [stage.GetRootLayer().identifier]
    # A stage reads its up axis and units off its own root and session layers only, never a
    # sublayer, so the scratch root carries the live stage's values itself.
    for key in (UsdGeom.Tokens.upAxis, UsdGeom.Tokens.metersPerUnit):
        if stage.HasAuthoredMetadata(key):
            scratch_root.pseudoRoot.SetInfo(key, stage.GetMetadata(key))
    # The live stage's resolver context: a relative path is found from the network's folder.
    return skip_cook.open_for_reading(scratch_root, stage.GetPathResolverContext())

get_view_exec_sources ⚓︎

get_view_exec_sources(view_chunk, stage, scene)

Return the chunks wired into view_chunk's inputs:chunk.

Source code in usd_chunks/chunk_stage.py
def get_view_exec_sources(
    view_chunk: core.ChunkBase,
    stage: Usd.Stage,
    scene: chunk_scene.SceneSender,
) -> list[core.ChunkBase]:
    """Return the chunks wired into view_chunk's inputs:chunk."""
    prim_to_chunk = {get_chunk_prim_path(c): c for c in scene.get_chunks()}
    prim = stage.GetPrimAtPath(Sdf.Path(get_chunk_prim_path(view_chunk)))
    if not prim.IsValid():
        return []
    exec_in = prim.GetAttribute(_EXEC_INPUT)
    if not exec_in.IsValid():
        return []
    return [
        c for conn in exec_in.GetConnections()
        if (c := prim_to_chunk.get(str(conn.GetPrimPath()))) is not None
    ]

graph_driver ⚓︎

graph_driver(stage, scene, context, deliver=False)

What a graph cooks by: a View, an Output (standing for all its Outputs), or its chain's end.

Shown (deliver False): the View its saved slot names, else its Output, else its lowest-slot View (a file from before Outputs). Handed to its parent graph (deliver True): its Output, else its active View, else the end of its chain; one wired to nothing doesn't count, since it would cook nothing.

Parameters:

Name Type Description Default
stage Stage

The stage.

required
scene SceneSender

The scene.

required
context ChunkBase | None

The graph.

required
deliver bool

What the graph hands on, as its parent's recook cooks a group, not what it shows.

False

Returns:

Type Description
tuple[ChunkBase | None, bool]

(the driver or None, True when it is the chain's end standing in for a View).

Source code in usd_chunks/chunk_stage.py
def graph_driver(
    stage: Usd.Stage, scene: chunk_scene.SceneSender, context: core.ChunkBase | None, deliver: bool = False
) -> tuple[core.ChunkBase | None, bool]:
    """What a graph cooks by: a View, an Output (standing for all its Outputs), or its chain's end.

    Shown (deliver False): the View its saved slot names, else its Output, else its
    lowest-slot View (a file from before Outputs). Handed to its parent graph (deliver True):
    its Output, else its active View, else the end of its chain; one wired to nothing
    doesn't count, since it would cook nothing.

    Args:
        stage: The stage.
        scene: The scene.
        context: The graph.
        deliver: What the graph hands on, as its parent's recook cooks a group, not what it shows.

    Returns:
        (the driver or None, True when it is the chain's end standing in for a View).
    """
    if not deliver:
        if (view := _saved_view(stage, scene, context)) is not None:
            return view, False
        if outputs := graph_outputs(stage, scene, context):
            return outputs[-1], False
        # An inert View can't be made active, so it can't drive a graph that is shown.
        return next((v for v in _views_by_slot(stage, scene, context) if view_slot(stage, v)), None), False
    output = find_output_chunk(stage, scene, context)
    if output is not None and view_cook_list(output, stage, scene):
        return output, False
    view = find_group_active_view(context, stage, scene)
    if view is not None and view_cook_list(view, stage, scene):
        return view, False
    # No View (they don't survive a copy/paste): cook through the chain's end, as one there would.
    tails = exec_tails(stage, scene, context)
    return (tails[0], True) if tails else (None, False)

graph_outputs ⚓︎

graph_outputs(stage, scene, context)

Every Output of a graph, weakest layer first.

A shot sublayering its departments composes each department's Output into one graph. Delivering the graph cooks all of them, weakest first: implied edges (implied_sources) usually chain them already, but a stronger layer can wire a weaker chunk after its own and cut that chain, and the weaker department still delivers.

Parameters:

Name Type Description Default
stage Stage

The stage.

required
scene SceneSender

The scene.

required
context ChunkBase | None

The graph, or None for the top level (the shallowest Outputs).

required

Returns:

Type Description
list[ChunkBase]

The Outputs, weakest layer first; empty when the graph has none.

Source code in usd_chunks/chunk_stage.py
def graph_outputs(
    stage: Usd.Stage, scene: chunk_scene.SceneSender, context: core.ChunkBase | None
) -> list[core.ChunkBase]:
    """Every Output of a graph, weakest layer first.

    A shot sublayering its departments composes each department's Output into one graph.
    Delivering the graph cooks all of them, weakest first: implied edges (implied_sources)
    usually chain them already, but a stronger layer can wire a weaker chunk after its own
    and cut that chain, and the weaker department still delivers.

    Args:
        stage: The stage.
        scene: The scene.
        context: The graph, or None for the top level (the shallowest Outputs).

    Returns:
        The Outputs, weakest layer first; empty when the graph has none.
    """
    outputs = [c for c in scene.get_chunks() if is_output_chunk(c)]
    if context is not None:
        outputs = [c for c in outputs if is_node_in_context(c, context)]
    elif outputs:
        depth = min(Sdf.Path(get_chunk_prim_path(c)).pathElementCount for c in outputs)
        outputs = [c for c in outputs if Sdf.Path(get_chunk_prim_path(c)).pathElementCount == depth]
    if len(outputs) < 2:
        return outputs
    strength = _layer_strength(stage)

    def rank(output: core.ChunkBase) -> int:
        prim = stage.GetPrimAtPath(Sdf.Path(get_chunk_prim_path(output)))
        layer = chunk_utils.chunk_pass(prim) if prim and prim.IsValid() else None
        return strength.get(layer.identifier, len(strength)) if layer is not None else len(strength)

    return sorted(outputs, key=rank, reverse=True)

has_collapsible_body ⚓︎

has_collapsible_body(chunk)

Whether a chunk's node has a body of params to fold away.

Not a View or Output, nor a Merge or Dot (no body), nor a group (its double-click is its dive).

Source code in usd_chunks/chunk_stage.py
def has_collapsible_body(chunk) -> bool:
    """Whether a chunk's node has a body of params to fold away.

    Not a View or Output, nor a Merge or Dot (no body), nor a group (its double-click is
    its dive).
    """
    cfg = chunk.get_config()
    return not (is_terminal_chunk(chunk) or is_group_chunk(chunk)
                or is_subnet(chunk) or (cfg and cfg.module in _BODILESS))

has_dynamic_exec_inputs_prim ⚓︎

has_dynamic_exec_inputs_prim(prim)

Whether a chunk prim's exec input slots grow with what is wired in.

Such a chunk gets one numbered port (inputs:chunk, inputs:chunk1, ...) per branch wired in -- Merge and Switch, and whatever else declares config.dynamic_exec_inputs. See exec_input_slots_for_prim for the other kind, where the count is fixed and positional.

Takes the prim: the node graph builds ports from the stage and may have no chunk object. See exec_input_slots_for_prim for why this reads the registry's discovery-time config rather than importing the module.

Parameters:

Name Type Description Default
prim Prim

The chunk prim.

required

Returns:

Type Description
bool

True for a dynamic-slot chunk's prim.

Source code in usd_chunks/chunk_stage.py
def has_dynamic_exec_inputs_prim(prim: Usd.Prim) -> bool:
    """Whether a chunk prim's exec input slots grow with what is wired in.

    Such a chunk gets one numbered port (inputs:chunk, inputs:chunk1, ...) per branch wired
    in -- Merge and Switch, and whatever else declares config.dynamic_exec_inputs. See
    exec_input_slots_for_prim for the other kind, where the count is fixed and positional.

    Takes the prim: the node graph builds ports from the stage and may have no chunk
    object. See exec_input_slots_for_prim for why this reads the registry's discovery-time
    config rather than importing the module.

    Args:
        prim: The chunk prim.

    Returns:
        True for a dynamic-slot chunk's prim.
    """
    if not (prim and prim.IsValid()):
        return False
    attr = prim.GetAttribute(_CHUNK_TYPE_ATTR)
    module_name = attr.Get() if attr and attr.IsValid() else None
    if not module_name:
        return False
    module = chunk_registry.ChunkRegistry().get_chunk_module(str(module_name))
    cfg = getattr(module, "config", None) if module else None
    return bool(cfg and getattr(cfg, "dynamic_exec_inputs", False))

heal_exec_chain_on_delete ⚓︎

heal_exec_chain_on_delete(stage, deleted_path)

Rewire around a node about to be deleted so its exec chain survives.

For A -> X -> B, deleting X must leave A -> B (each successor B's inputs:chunk is repointed to X's predecessor A; cleared if X had none). Call while X's prim still exists -- its inputs:chunk predecessor is only readable before removal. Exec only (inputs/outputs:chunk); data/typed connections to X are left to drop with the prim.

Parameters:

Name Type Description Default
stage Stage

The stage to author on.

required
deleted_path str

Prim path of the node being deleted.

required
Source code in usd_chunks/chunk_stage.py
def heal_exec_chain_on_delete(stage: Usd.Stage, deleted_path: str) -> None:
    """Rewire around a node about to be deleted so its exec chain survives.

    For A -> X -> B, deleting X must leave A -> B (each successor B's inputs:chunk is
    repointed to X's predecessor A; cleared if X had none). Call while X's prim still exists
    -- its inputs:chunk predecessor is only readable before removal. Exec only
    (inputs/outputs:chunk); data/typed connections to X are left to drop with the prim.

    Args:
        stage: The stage to author on.
        deleted_path: Prim path of the node being deleted.
    """
    deleted = Sdf.Path(deleted_path)
    del_prim = stage.GetPrimAtPath(deleted)
    if not (del_prim and del_prim.IsValid()):
        return
    # The deleted node's PREDECESSOR is read from slot 0 only, on purpose: a successor has a
    # single input to inherit into, so it can be handed exactly one branch, and slot 0 is the
    # primary/strongest one. Deleting a merge therefore grafts its top branch onto whatever
    # came after it, rather than fanning all of them into a chunk that cannot express fan-in.
    exec_in = del_prim.GetAttribute(_EXEC_INPUT)
    pred_conns = list(exec_in.GetConnections()) if (exec_in and exec_in.IsValid()) else []
    out_path = f"{deleted_path}.{_EXEC_OUTPUT}"
    touched_dynamic = []
    prev_w = chunk_notice._usd_write_active
    chunk_notice._usd_write_active = True
    try:
        for prim in stage.Traverse():
            if prim.GetPath() == deleted or prim.GetTypeName() != _CHUNK_PRIM_TYPENAME:
                continue
            # SUCCESSORS, by contrast, must be found across every slot. A merge fed through
            # slot 2 is just as much a successor as one fed through slot 0, and skipping it
            # would leave that slot connected to a prim that is about to stop existing.
            for succ in iter_exec_inputs(prim):
                if not any(str(c) == out_path for c in succ.GetConnections()):
                    continue
                # Write to succ's OWN home layer (or the session layer as a last resort),
                # not wherever the stage's ambient edit target happens to be (the root
                # layer, since nothing here ever calls SetEditTarget) -- an interactively
                # wired connection almost always lives on the session layer, which is
                # stronger than root. Healing on root left the original, still-composed
                # session-layer opinion (pointing at the just-deleted node) in charge, so
                # the "healed" A->B edge was silently shadowed away by composition and
                # never actually took effect. Same pattern as _author_connection /
                # _author_raw_connection.
                home = chunk_utils.get_attr_home_layer(succ) or chunk_utils.get_bookkeeping_layer(stage, None)
                with Usd.EditContext(stage, home):
                    if pred_conns:
                        succ.SetConnections(pred_conns)
                    else:
                        succ.ClearConnections()
                if has_dynamic_exec_inputs_prim(prim):
                    touched_dynamic.append(prim)
    finally:
        chunk_notice._usd_write_active = prev_w
    # Suppressing notices above means opting out of the choke point that normally keeps the
    # dynamic-slot invariant (_reconcile_changed_exec_inputs), so restore it here instead: a
    # slot cleared because its branch was deleted has to compact like any other.
    for prim in touched_dynamic:
        normalize_merge_slots(stage, prim)
    # Healing rewrites inputs:chunk across the graph with notices suppressed -- every
    # memoised answer below the deleted node is now measured against an edge that is gone.
    invalidate_edit_layer_memo()

hold_asset_layers ⚓︎

hold_asset_layers(node, paths)

Open the files a chunk brings in and keep them open on it, until it brings in others.

network_target opens a file to ask whether it holds a network, and lets it go; the arc the chunk then authors opened it all over again -- every asset read twice on each cook, half a second of the bathroom scene's five-second open. Held here, the question and the arc share one read. The layers go when the chunk's files change, or with it.

Parameters:

Name Type Description Default
node

The Reference, Payload or Sublayer chunk.

required
paths Iterable[str]

The files it brings in.

required
Source code in usd_chunks/chunk_stage.py
def hold_asset_layers(node, paths: Iterable[str]) -> None:
    """Open the files a chunk brings in and keep them open on it, until it brings in others.

    network_target opens a file to ask whether it holds a network, and lets it go; the
    arc the chunk then authors opened it all over again -- every asset read twice on each
    cook, half a second of the bathroom scene's five-second open. Held here, the question
    and the arc share one read. The layers go when the chunk's files change, or with it.

    Args:
        node: The Reference, Payload or Sublayer chunk.
        paths: The files it brings in.
    """
    held = []
    for path in paths:
        try:
            layer = Sdf.Layer.FindOrOpen(path) if path else None
        except Tf.ErrorException:
            # No format plugin for it: the arc reports that, as it always has.
            layer = None
        if layer is not None:
            held.append(layer)
    node._held_asset_layers = tuple(held)

host_network ⚓︎

host_network(chunk, asset_path, prim_path, arc='reference', namespace='')

Make chunk the host of the network at prim_path in asset_path. See host_networks.

Source code in usd_chunks/chunk_stage.py
def host_network(chunk: core.ChunkBase, asset_path: str, prim_path: str,
                 arc: str = "reference", namespace: str = "") -> None:
    """Make chunk the host of the network at prim_path in asset_path. See host_networks."""
    host_networks(chunk, [(asset_path, prim_path)], arc, namespace)

host_networks ⚓︎

host_networks(chunk, targets, arc='reference', namespace='')

Make chunk the host of these networks, each an (asset path, prim path) pair.

Authors the arcs on chunk's own prim -- in its bookkeeping layer, since an arc is structure that must survive a cook and a save, not content -- and gives the chunk the flags a group has, so the composed-in children nest under it and cook as its subnet (recook_for_view recurses into a group's inner view). The children are then loaded straight away: the arc write lands while a cook has notices suppressed, and the rescan that would otherwise pick them up waits for the next unsuppressed stage change, which may be a while.

Several targets compose together under the one prim, first strongest -- the order a Sublayer chunk's list has, and what stacking those files as sublayers would do to their chunk prims too: a chunk both networks name is one chunk with the stronger file's opinions on top.

Idempotent: re-hosting the same targets rewrites the same arcs and loads nothing new.

Parameters:

Name Type Description Default
chunk ChunkBase

The hosting chunk.

required
targets list[tuple[str, str]]

(asset path, prim path) pairs, strongest first. An empty list unhosts.

required
arc str

"reference" or "payload": the kind the hosting chunk stands for. A payload host's network unloads with the stage's other payloads, and its arc on the prim is what a reader sees, so a Payload chunk must not quietly become a reference.

'reference'
namespace str

The scene root the network's prim paths resolve under; "" means the paths as written, which is the sequence-into-shot case. A network's chunks author absolute paths -- /Clock_01 -- so two hosts of the same room would fight over the same prims; with a namespace each host's chunks resolve their prim-path params under its root (ChunkParamBase.network_namespace), and /Clock_01 in the file is /bedroom/Clock_01 in the scene. The file and the params' stored text are untouched.

''

Raises:

Type Description
ValueError

arc is not "reference" or "payload".

Source code in usd_chunks/chunk_stage.py
def host_networks(chunk: core.ChunkBase, targets: list[tuple[str, str]],
                  arc: str = "reference", namespace: str = "") -> None:
    """Make chunk the host of these networks, each an (asset path, prim path) pair.

    Authors the arcs on chunk's own prim -- in its bookkeeping layer, since an arc is
    structure that must survive a cook and a save, not content -- and gives the chunk
    the flags a group has, so the composed-in children nest under it and cook as its
    subnet (recook_for_view recurses into a group's inner view). The children are then
    loaded straight away: the arc write lands while a cook has notices suppressed, and
    the rescan that would otherwise pick them up waits for the next unsuppressed stage
    change, which may be a while.

    Several targets compose together under the one prim, first strongest -- the order a
    Sublayer chunk's list has, and what stacking those files as sublayers would do to
    their chunk prims too: a chunk both networks name is one chunk with the stronger
    file's opinions on top.

    Idempotent: re-hosting the same targets rewrites the same arcs and loads nothing new.

    Args:
        chunk: The hosting chunk.
        targets: (asset path, prim path) pairs, strongest first. An empty list unhosts.
        arc: "reference" or "payload": the kind the hosting chunk stands for. A payload
            host's network unloads with the stage's other payloads, and its arc on the prim
            is what a reader sees, so a Payload chunk must not quietly become a reference.
        namespace: The scene root the network's prim paths resolve under; "" means the
            paths as written, which is the sequence-into-shot case. A network's chunks
            author absolute paths -- /Clock_01 -- so two hosts of the same room would fight
            over the same prims; with a namespace each host's chunks resolve their
            prim-path params under its root (ChunkParamBase.network_namespace), and
            /Clock_01 in the file is /bedroom/Clock_01 in the scene. The file and the
            params' stored text are untouched.

    Raises:
        ValueError: `arc` is not "reference" or "payload".
    """
    if arc not in ("reference", "payload"):
        raise ValueError(f"arc must be 'reference' or 'payload', not {arc!r}")
    if not targets:
        unhost_network(chunk)
        return
    stage = chunk.get_scene_stage()
    if not stage:
        return
    # The path first: get_chunk_prim_path answers a CONTEXT chunk from its prim_path, so
    # once the flags are on it needs the path to already be recorded.
    own_path = get_chunk_prim_path(chunk)
    prim = stage.GetPrimAtPath(Sdf.Path(own_path))
    if not prim.IsValid():
        return
    chunk.prim_path = own_path
    object.__setattr__(chunk, "_exec_prim_path", own_path)
    namespace = namespace.rstrip("/") if namespace else ""
    namespace_changed = getattr(chunk, "_network_namespace", "") != namespace
    object.__setattr__(chunk, "_network_namespace", namespace)
    for flag in (ChunkFlags.GroupFlags.CONTEXT, ChunkFlags.GroupFlags.COLLAPSABLE,
                 ChunkFlags.GroupFlags.LABELED):
        chunk.set_flag(flag)
    # The chunk is a group now. The scene's cached list of groups (get_contexts) is kept
    # until a chunk is added or removed, so it would go on leaving this one out.
    core.NameSyncedContainer.generation += 1
    if arc == "payload":
        arcs = [Sdf.Payload(asset, Sdf.Path(target)) for asset, target in targets]
        current = prim.GetMetadata("payload")
    else:
        arcs = [Sdf.Reference(asset, Sdf.Path(target)) for asset, target in targets]
        current = prim.GetMetadata("references")
    if current is not None and list(current.GetAddedOrExplicitItems()) == arcs:
        if namespace_changed:
            # Same network, new root: every prim path inside resolves somewhere else now,
            # and the content authored under the old root is only cleared by a re-cook.
            scene = _active_scene()
            inside = [c for c in (scene.get_chunks() if scene else [])
                      if get_chunk_prim_path(c).startswith(own_path + "/")]
            cooked = 0
            for c in sorted(inside, key=lambda c: get_chunk_prim_path(c).count("/")):
                if not c.is_blocked() and not is_group_chunk(c):
                    c.execute()
                    cooked += 1
            logger.info(
                "%s: network now under %r; re-cooked %d of %d inner chunks (%d blocked)",
                own_path, namespace or "/", cooked, len(inside),
                sum(1 for c in inside if c.is_blocked()),
            )
        return
    logger.info("%s hosts %s under %r", own_path, [asset for asset, _ in targets], namespace or "/")
    sync = ChunkStageSync()
    prev = chunk_notice._usd_write_active
    chunk_notice._usd_write_active = True
    try:
        with sync._chunk_prim_edit_context(chunk):
            if arc == "payload":
                prim.GetReferences().ClearReferences()
                prim.GetPayloads().SetPayloads(arcs)
            else:
                prim.GetPayloads().ClearPayloads()
                prim.GetReferences().SetReferences(arcs)
    finally:
        chunk_notice._usd_write_active = prev
    load_chunks(stage, sync._scene or _active_scene(), sync._loaded_prim_paths,
                prims=iter(prim.GetFilteredChildren(_LOAD_INCLUDE_INACTIVE)))

implied_sources ⚓︎

implied_sources(prim)

The chunks a chunk is fed by because of composition, not a wire.

A chunk with no exec input starts where everything weaker than it ends:

  • A shot sublayers its departments, each a chain ending in its Output, and nothing is wired between them. A first chunk in lighting.usda starts where layout.usda's chain ends, as if wired to what feeds layout's Output -- the nearest weaker layer beside it (its sibling Outputs) that brings one.
  • A network composed in by an arc (a reference, payload, inherit or variant authored in the chunk's own layer or a weaker one) cooks before it too, so a shot's chain can read the referenced house it builds on.

These edges are derived from composition on every read and never authored -- the same reading gives the cook order (view_cook_list), live change propagation (_wired_dependencies) and the load, and nothing is written to any file.

Parameters:

Name Type Description Default
prim Prim

A chunk prim.

required

Returns:

Type Description
list[str]

Prim paths of the chunks feeding those Outputs; empty for a chunk with an exec

list[str]

input, a terminal chunk, a chunk composed in by an arc itself, or one with nothing

list[str]

weaker to follow.

Source code in usd_chunks/chunk_stage.py
def implied_sources(prim: Usd.Prim) -> list[str]:
    """The chunks a chunk is fed by because of composition, not a wire.

    A chunk with no exec input starts where everything weaker than it ends:

    - A shot sublayers its departments, each a chain ending in its Output, and nothing is
      wired between them. A first chunk in lighting.usda starts where layout.usda's chain
      ends, as if wired to what feeds layout's Output -- the nearest weaker layer beside it
      (its sibling Outputs) that brings one.
    - A network composed in by an arc (a reference, payload, inherit or variant authored in the
      chunk's own layer or a weaker one) cooks before it too, so a shot's chain can read
      the referenced house it builds on.

    These edges are derived from composition on every read and never authored -- the same
    reading gives the cook order (view_cook_list), live change propagation
    (_wired_dependencies) and the load, and nothing is written to any file.

    Args:
        prim: A chunk prim.

    Returns:
        Prim paths of the chunks feeding those Outputs; empty for a chunk with an exec
        input, a terminal chunk, a chunk composed in by an arc itself, or one with nothing
        weaker to follow.
    """
    if not (prim and prim.IsValid()) or exec_input_connections(prim):
        return []
    if prim.GetAttribute(_CHUNK_TYPE_ATTR).Get() in ("view", "output"):
        return []
    # Cheapest first: with fewer than two Outputs beside it and no network brought in by an
    # arc there is nothing to chain -- nearly every graph -- so no layer is resolved at all.
    siblings = _output_children(prim.GetParent())
    stage = prim.GetStage()
    arc_outputs = _arc_network_outputs(stage)
    if len(siblings) < 2 and not arc_outputs:
        return []
    own = chunk_utils.chunk_pass(prim)
    if own is None:
        return []
    strength = _layer_strength(stage)
    own_rank = strength.get(own.identifier)
    if own_rank is None:
        return []
    ends = []
    weaker = []
    for output in siblings:
        layer = chunk_utils.chunk_pass(output)
        rank = strength.get(layer.identifier) if layer is not None else None
        if rank is not None and rank > own_rank:
            weaker.append((rank, output))
    if weaker:
        ends.append(min(weaker, key=lambda pair: pair[0])[1])
    for output, arc_layer in arc_outputs:
        rank = strength.get(arc_layer.identifier)
        if rank is not None and rank >= own_rank:
            ends.append(output)
    # Never one that already follows this chunk through a wire: a stronger layer wiring a
    # weaker chunk after its own (an `over` on its exec input) pushes that chunk later, and
    # waiting for it here would close a loop.
    own_path = str(prim.GetPath())
    sources: list[str] = []
    for end in ends:
        for conn in exec_input_connections(end):
            path = str(conn.GetPrimPath())
            if path not in sources and not _wired_after(stage, path, own_path):
                sources.append(path)
    return sources

initialize ⚓︎

initialize(stage, scene)

Start the layer manager and stage sync for a stage and scene, and follow stage replacement.

Parameters:

Name Type Description Default
stage Stage

The stage.

required
scene SceneSender

The scene.

required
Source code in usd_chunks/chunk_stage.py
def initialize(stage: Usd.Stage, scene: chunk_scene.SceneSender) -> None:
    """Start the layer manager and stage sync for a stage and scene, and follow stage replacement.

    Args:
        stage: The stage.
        scene: The scene.
    """
    ChunkLayerManager().initialize(stage)
    ChunkStageSync().initialize(stage, scene)
    scene.add_stage_replaced_listener(ChunkStageSync().reload_for_stage)

input_consumers ⚓︎

input_consumers(chunk)

The chunks with a typed input wired to this one's prim, in scene order.

The reverse of a param wire: USD keeps a connection only on the consumer's side, so this is read from an index of the scene's stage, kept until a wire changes. Exec inputs are not counted -- they say what cooks after what, not what feeds what.

Parameters:

Name Type Description Default
chunk ChunkBase

The chunk being read from

required

Returns:

Name Type Description
list list

The consuming chunks, without chunk itself

Source code in usd_chunks/chunk_stage.py
def input_consumers(chunk: core.ChunkBase) -> list:
    """The chunks with a typed input wired to this one's prim, in scene order.

    The reverse of a param wire: USD keeps a connection only on the consumer's side, so
    this is read from an index of the scene's stage, kept until a wire changes. Exec inputs
    are not counted -- they say what cooks after what, not what feeds what.

    Args:
        chunk (core.ChunkBase): The chunk being read from

    Returns:
        list: The consuming chunks, without chunk itself
    """
    stage = chunk.get_scene_stage()
    if not stage:
        return []
    own = {getattr(chunk, "_exec_prim_path", None), getattr(chunk, "prim_path", None),
           get_chunk_prim_path(chunk)}
    paths = set()
    for path in own:
        if path:
            paths |= input_consumer_paths(stage, str(path))
    sync = ChunkStageSync()
    found = sync._chunks_at(paths) if sync.initialized else _chunks_at(sorted(paths))
    return [c for c in found if c is not chunk]

is_chunk_lofted ⚓︎

is_chunk_lofted(chunk)

Whether chunk is lofted to its group, so its panel shows on the group's Params page.

An authored chunk:lofted (or, from an older file, chunk:pinned) always wins. Otherwise -- no authored value, which can mean the prim itself doesn't exist yet -- it falls back in order:

  1. Views and Outputs are wiring, never panels: not lofted.
  2. _loft_new_chunks, when a create/paste flow is deciding it right now. Set before the create notice is sent, so it is right whichever PARAM_ADDED listener runs first.
  3. Absent means not lofted.

Parameters:

Name Type Description Default
chunk ChunkBase

The chunk.

required

Returns:

Type Description
bool

True if the chunk is lofted.

Source code in usd_chunks/chunk_stage.py
def is_chunk_lofted(chunk: core.ChunkBase) -> bool:
    """Whether chunk is lofted to its group, so its panel shows on the group's Params page.

    An authored ``chunk:lofted`` (or, from an older file, ``chunk:pinned``) always wins.
    Otherwise -- no authored value, which can mean the prim itself doesn't exist yet -- it
    falls back in order:

    1. Views and Outputs are wiring, never panels: not lofted.
    2. _loft_new_chunks, when a create/paste flow is deciding it right now. Set before the
       create notice is sent, so it is right whichever PARAM_ADDED listener runs first.
    3. Absent means not lofted.

    Args:
        chunk: The chunk.

    Returns:
        True if the chunk is lofted.
    """
    stage = chunk.get_scene_stage()
    prim = stage.GetPrimAtPath(Sdf.Path(get_chunk_prim_path(chunk))) if stage else None
    if prim and prim.IsValid():
        for name in (_LOFTED_CHUNK_ATTR, _LEGACY_PINNED_ATTR):
            attr = prim.GetAttribute(name)
            if (val := attr.Get() if attr and attr.IsValid() else None) is not None:
                return bool(val)
    if is_terminal_chunk(chunk):
        return False
    if _loft_new_chunks is not None:
        return _loft_new_chunks
    return False

is_chunkgroup ⚓︎

is_chunkgroup(chunk)

Whether chunk is a chunkgroup proper -- the chunkgroup chunk type.

A chunkgroup is defined in USD and is a subnet you navigate into; a chunk is defined in python, and one that owns children (AMDMaterialXLibrary creating reference and bind_material) is reusing them as an implementation detail, not exposing a subnet to edit. Both carry GroupFlags.CONTEXT, so CONTEXT alone cannot tell them apart.

Navigation, and the UI that advertises it, keys on this. Containment and cooking key on is_group_chunk, so a chunk-in-chunk keeps hiding its children and running their code.

Parameters:

Name Type Description Default
chunk ChunkBase

The chunk.

required

Returns:

Type Description
bool

True for a chunkgroup.

Source code in usd_chunks/chunk_stage.py
def is_chunkgroup(chunk: core.ChunkBase) -> bool:
    """Whether chunk is a chunkgroup proper -- the `chunkgroup` chunk type.

    A chunkgroup is defined in USD and is a subnet you navigate into; a chunk is defined in
    python, and one that owns children (AMDMaterialXLibrary creating `reference` and
    `bind_material`) is reusing them as an implementation detail, not exposing a subnet to
    edit. Both carry GroupFlags.CONTEXT, so CONTEXT alone cannot tell them apart.

    Navigation, and the UI that advertises it, keys on this. Containment and cooking key on
    is_group_chunk, so a chunk-in-chunk keeps hiding its children and running their code.

    Args:
        chunk: The chunk.

    Returns:
        True for a chunkgroup.
    """
    cfg = chunk.get_config()
    return bool(cfg and cfg.module == "chunkgroup")

is_edit_target_chunk ⚓︎

is_edit_target_chunk(chunk)

Return True if chunk is an Edit Target chunk (chunks/usd/edit_target.py).

Source code in usd_chunks/chunk_stage.py
def is_edit_target_chunk(chunk: core.ChunkBase) -> bool:
    """Return True if chunk is an Edit Target chunk (chunks/usd/edit_target.py)."""
    cfg = chunk.get_config()
    return bool(cfg and cfg.module == "edit_target")

is_group_chunk ⚓︎

is_group_chunk(chunk)

Whether chunk owns child chunks: a CONTEXT chunk with a module.

This is about containment: whose children are hidden until entered, cook as a unit, and share a layer. It is true of a chunkgroup, and equally true of a chunk-in-chunk like AMDMaterialXLibrary, whose children are an implementation detail. For the narrower "is this a subnet the user may navigate into", see is_chunkgroup.

Parameters:

Name Type Description Default
chunk ChunkBase

The chunk.

required

Returns:

Type Description
bool

True for a chunk that contains others.

Source code in usd_chunks/chunk_stage.py
def is_group_chunk(chunk: core.ChunkBase) -> bool:
    """Whether chunk owns child chunks: a CONTEXT chunk with a module.

    This is about *containment*: whose children are hidden until entered, cook as a unit,
    and share a layer. It is true of a chunkgroup, and equally true of a chunk-in-chunk
    like AMDMaterialXLibrary, whose children are an implementation detail. For the
    narrower "is this a subnet the user may navigate into", see is_chunkgroup.

    Args:
        chunk: The chunk.

    Returns:
        True for a chunk that contains others.
    """
    cfg = chunk.get_config()
    return bool(chunk.has_flag(ChunkFlags.GroupFlags.CONTEXT) and cfg and cfg.module)

is_localisable ⚓︎

is_localisable(chunk)

Whether localise_network has anything to do for this chunk.

That is a network host, or a chunkgroup that references its network from a file (publish_network's result).

Parameters:

Name Type Description Default
chunk ChunkBase

The chunk.

required

Returns:

Type Description
bool

True if it can be localised.

Source code in usd_chunks/chunk_stage.py
def is_localisable(chunk: core.ChunkBase) -> bool:
    """Whether localise_network has anything to do for this chunk.

    That is a network host, or a chunkgroup that references its network from a file
    (publish_network's result).

    Args:
        chunk: The chunk.

    Returns:
        True if it can be localised.
    """
    if is_network_host(chunk):
        return True
    if not is_chunkgroup(chunk):
        return False
    stage = chunk.get_scene_stage()
    if not stage:
        return False
    prim = stage.GetPrimAtPath(Sdf.Path(get_chunk_prim_path(chunk)))
    return bool(prim and prim.IsValid() and _hosts_by_arc(prim))

is_merge_chunk ⚓︎

is_merge_chunk(chunk)

Whether chunk is specifically a Merge chunk (chunks/core/merge.py).

Narrower than has_dynamic_exec_inputs_prim: Merge's slot order also decides composition strength ("first input wins"), which is a Merge-only meaning that a dynamic-slot chunk with no such ranking (a Switch) does not share.

Parameters:

Name Type Description Default
chunk ChunkBase

The chunk.

required

Returns:

Type Description
bool

True for a Merge chunk.

Source code in usd_chunks/chunk_stage.py
def is_merge_chunk(chunk: core.ChunkBase) -> bool:
    """Whether chunk is specifically a Merge chunk (chunks/core/merge.py).

    Narrower than has_dynamic_exec_inputs_prim: Merge's slot order also decides composition
    strength ("first input wins"), which is a Merge-only meaning that a dynamic-slot chunk
    with no such ranking (a Switch) does not share.

    Args:
        chunk: The chunk.

    Returns:
        True for a Merge chunk.
    """
    cfg = chunk.get_config()
    return bool(cfg and cfg.module == "merge")

is_merge_prim ⚓︎

is_merge_prim(prim)

is_merge_chunk for a bare prim, when there is no live chunk object to ask.

Used where only the stage is at hand (slot compaction, cook ordering).

Parameters:

Name Type Description Default
prim Prim

The chunk prim.

required

Returns:

Type Description
bool

True for a Merge chunk's prim.

Source code in usd_chunks/chunk_stage.py
def is_merge_prim(prim: Usd.Prim) -> bool:
    """is_merge_chunk for a bare prim, when there is no live chunk object to ask.

    Used where only the stage is at hand (slot compaction, cook ordering).

    Args:
        prim: The chunk prim.

    Returns:
        True for a Merge chunk's prim.
    """
    if not (prim and prim.IsValid()):
        return False
    attr = prim.GetAttribute(_CHUNK_TYPE_ATTR)
    return bool(attr and attr.IsValid() and attr.Get() == "merge")

is_network_host ⚓︎

is_network_host(chunk)

Whether chunk brings a chunk network in by reference and hosts it as a subnet.

A Reference chunk pointed at a file whose target prim is a chunkgroup does not put that prim into the scene; it puts the reference arc on its OWN chunk prim (host_network), so the group's chunks compose in as its children and the node is the group -- dive in, and the network is there, as if it had been expanded in place. The chunk carries CONTEXT while it hosts (so containment and cooking treat it as a group, see is_group_chunk) and the arc on its prim is what tells it apart from a chunk that builds its own children (AMD MaterialX Library), which is CONTEXT too.

Parameters:

Name Type Description Default
chunk ChunkBase

The chunk.

required

Returns:

Type Description
bool

True for a chunk hosting a network.

Source code in usd_chunks/chunk_stage.py
def is_network_host(chunk: core.ChunkBase) -> bool:
    """Whether chunk brings a chunk network in by reference and hosts it as a subnet.

    A Reference chunk pointed at a file whose target prim is a chunkgroup does not put
    that prim into the scene; it puts the reference arc on its OWN chunk prim
    (host_network), so the group's chunks compose in as its children and the node is the
    group -- dive in, and the network is there, as if it had been expanded in place. The
    chunk carries CONTEXT while it hosts (so containment and cooking treat it as a group,
    see is_group_chunk) and the arc on its prim is what tells it apart from a chunk that
    builds its own children (AMD MaterialX Library), which is CONTEXT too.

    Args:
        chunk: The chunk.

    Returns:
        True for a chunk hosting a network.
    """
    if not is_group_chunk(chunk) or is_chunkgroup(chunk):
        return False
    stage = chunk.get_scene_stage()
    if not stage:
        return False
    prim = stage.GetPrimAtPath(Sdf.Path(get_chunk_prim_path(chunk)))
    return bool(prim and prim.IsValid() and _hosts_by_arc(prim))

is_node_in_context ⚓︎

is_node_in_context(chunk, context)

Whether chunk is a NODE in context's graph: its prim is a direct child of the context's root.

That matches how the graph rebuild picks nodes, and separates 'group as a node' from 'group as a container': a group is a node in its PARENT graph (its prim's parent is the parent root), and the group's inner chunks are nodes in the group's graph. get_context() would conflate the two, since it returns self for a context chunk.

Parameters:

Name Type Description Default
chunk ChunkBase

The chunk.

required
context ChunkBase | None

The context, or None for the top level (always True).

required

Returns:

Type Description
bool

True if chunk is a node of that graph.

Source code in usd_chunks/chunk_stage.py
def is_node_in_context(chunk: core.ChunkBase, context: core.ChunkBase | None) -> bool:
    """Whether chunk is a NODE in context's graph: its prim is a direct child of the context's root.

    That matches how the graph rebuild picks nodes, and separates 'group as a node' from
    'group as a container': a group is a node in its PARENT graph (its prim's parent is the
    parent root), and the group's inner chunks are nodes in the group's graph. get_context()
    would conflate the two, since it returns self for a context chunk.

    Args:
        chunk: The chunk.
        context: The context, or None for the top level (always True).

    Returns:
        True if chunk is a node of that graph.
    """
    if context is None:
        return True
    root = context.prim_path if getattr(context, "prim_path", None) else _CHUNKS_ROOT
    return str(Sdf.Path(get_chunk_prim_path(chunk)).GetParentPath()) == str(root)

is_output_chunk ⚓︎

is_output_chunk(chunk)

Return True if chunk is a graph's Output: what the graph delivers and cooks to.

Source code in usd_chunks/chunk_stage.py
def is_output_chunk(chunk: core.ChunkBase) -> bool:
    """Return True if chunk is a graph's Output: what the graph delivers and cooks to."""
    cfg = chunk.get_config()
    return bool(cfg and cfg.module == "output")

is_subnet ⚓︎

is_subnet(chunk)

Whether chunk is a graph the user may dive into.

That is a chunkgroup, or a chunk hosting a referenced network (is_network_host). This is what navigation keys on; is_group_chunk (containment and cooking) is wider and includes chunks whose children are an implementation detail.

Parameters:

Name Type Description Default
chunk ChunkBase

The chunk.

required

Returns:

Type Description
bool

True for a subnet.

Source code in usd_chunks/chunk_stage.py
def is_subnet(chunk: core.ChunkBase) -> bool:
    """Whether chunk is a graph the user may dive into.

    That is a chunkgroup, or a chunk hosting a referenced network (is_network_host). This is
    what navigation keys on; is_group_chunk (containment and cooking) is wider and includes
    chunks whose children are an implementation detail.

    Args:
        chunk: The chunk.

    Returns:
        True for a subnet.
    """
    return is_chunkgroup(chunk) or is_network_host(chunk)

is_terminal_chunk ⚓︎

is_terminal_chunk(chunk)

Return True for a chain-ending marker (a view or an Output), which has no content.

Read from the module's config, so any terminal chunk is never taken for a chain's tail, cooked, pinned or copied.

Source code in usd_chunks/chunk_stage.py
def is_terminal_chunk(chunk: core.ChunkBase) -> bool:
    """Return True for a chain-ending marker (a view or an Output), which has no content.

    Read from the module's config, so any terminal chunk is never taken for a chain's tail,
    cooked, pinned or copied.
    """
    cfg = chunk.get_config()
    return bool(cfg and cfg.terminal)

is_transient_param ⚓︎

is_transient_param(param)

Whether param is session state that is never recorded (ParamFlags.TRANSIENT).

A vector is transient when all of its components are: its own flags are group flags.

Source code in usd_chunks/chunk_stage.py
def is_transient_param(param) -> bool:
    """Whether param is session state that is never recorded (ParamFlags.TRANSIENT).

    A vector is transient when all of its components are: its own flags are group flags.
    """
    if isinstance(param, core.ChunkVectorBase):
        parts = param.get_my_params()
        return bool(parts) and all(is_transient_param(p) for p in parts)
    return isinstance(param, core.ChunkParamBase) and param.has_flag(ChunkFlags.ParamFlags.TRANSIENT)

is_view_chunk ⚓︎

is_view_chunk(chunk)

Return True if chunk is a view-type chunk.

Source code in usd_chunks/chunk_stage.py
def is_view_chunk(chunk: core.ChunkBase) -> bool:
    """Return True if chunk is a view-type chunk."""
    cfg = chunk.get_config()
    return bool(cfg and cfg.module == "view")

layer_label ⚓︎

layer_label(layer)

A layer as a user knows it: the chunk whose cook layer it is, or its file name.

A chunk's procedural layer is named anon:

:, which says nothing to anyone; the chunk it belongs to is what they put on the graph.

Parameters:

Name Type Description Default
layer Layer

The layer.

required

Returns:

Type Description
str

The chunk's name, or the layer's display name (its identifier when it has none).

Source code in usd_chunks/chunk_stage.py
def layer_label(layer: Sdf.Layer) -> str:
    """A layer as a user knows it: the chunk whose cook layer it is, or its file name.

    A chunk's procedural layer is named anon:<address>:<tag>, which says nothing to anyone;
    the chunk it belongs to is what they put on the graph.

    Args:
        layer: The layer.

    Returns:
        The chunk's name, or the layer's display name (its identifier when it has none).
    """
    lm = chunk_registry.ChunkLayerManager()
    scene = _chunk_mod.get_scene()
    if lm.initialized and scene is not None and chunk_registry.is_chunk_internal_layer(layer):
        for chunk in scene.get_chunks():
            if lm.get_layer(chunk) == layer:
                return chunk.name
    return layer.GetDisplayName() or layer.identifier

layer_stack_ids ⚓︎

layer_stack_ids(stage)

Identifiers of every layer FlattenLayerStack takes in: the stage's stack and the chunk layers in it, not what its references bring in.

Source code in usd_chunks/chunk_stage.py
def layer_stack_ids(stage) -> set[str]:
    """Identifiers of every layer FlattenLayerStack takes in: the stage's stack and the chunk
    layers in it, not what its references bring in."""
    return {layer.identifier for layer in stage.GetLayerStack(includeSessionLayers=True)}

load_chunks ⚓︎

load_chunks(stage, scene, loaded_prim_paths=None, prims=None)

Turn Chunk prims into chunks.

Parameters:

Name Type Description Default
stage Stage

The stage to read.

required
scene SceneSender

The scene to add the chunks to.

required
loaded_prim_paths set[str] | None

Prim paths already loaded, skipped and updated.

None
prims Generator | None

Narrows which prims are considered -- see ChunkStageSync._scan_for_new_chunks, which derives it from what USD reported changed. None considers the whole stage, which is what a file being opened wants.

None
Source code in usd_chunks/chunk_stage.py
def load_chunks(
    stage: Usd.Stage,
    scene: chunk_scene.SceneSender,
    loaded_prim_paths: set[str] | None = None,
    prims: Generator | None = None,
) -> None:
    """Turn Chunk prims into chunks.

    Args:
        stage: The stage to read.
        scene: The scene to add the chunks to.
        loaded_prim_paths: Prim paths already loaded, skipped and updated.
        prims: Narrows which prims are considered -- see ChunkStageSync._scan_for_new_chunks,
            which derives it from what USD reported changed. None considers the whole stage,
            which is what a file being opened wants.
    """
    if not stage:
        return

    with _loading_from_file():
        _load_chunks(stage, scene, loaded_prim_paths, prims)
    # Where each chunk now composes from, so a later resync can tell which ones changed. A
    # scan scoped to what just changed only made the new chunks: fingerprinting every chunk
    # on each one made building a network cost the square of its size.
    sync = ChunkStageSync()
    if sync.initialized and getattr(sync, "_stage", None) is stage:
        sync.record_sources(scene.get_chunks(), only_new=prims is not None)

localise_network ⚓︎

localise_network(host)

Turn a hosted network into a plain chunkgroup of this file.

The inverse of publish_network, and what "Allow Editing of Contents" means here. The composed subtree under the host prim -- the file's chunks with the shot's overrides on top -- is flattened and authored as local defs in the host's bookkeeping layer, the arc is dropped, and the host prim becomes a chunkgroup. The live objects are then rebuilt from the prims, since the host was a Reference (or Sublayer, Payload) chunk and its replacement is a chunkgroup; the same load path a reopened file takes, so the result is what saving and reopening would have given.

Parameters:

Name Type Description Default
host ChunkBase

The hosting chunk.

required

Returns:

Type Description
ChunkBase | None

The new chunkgroup, or None if there was nothing to localise.

Source code in usd_chunks/chunk_stage.py
def localise_network(host: core.ChunkBase) -> core.ChunkBase | None:
    """Turn a hosted network into a plain chunkgroup of this file.

    The inverse of publish_network, and what "Allow Editing of Contents" means here. The
    composed subtree under the host prim -- the file's chunks with the shot's overrides on
    top -- is flattened and authored as local defs in the host's bookkeeping layer, the arc
    is dropped, and the host prim becomes a chunkgroup. The live objects are then rebuilt
    from the prims, since the host was a Reference (or Sublayer, Payload) chunk and its
    replacement is a chunkgroup; the same load path a reopened file takes, so the result is
    what saving and reopening would have given.

    Args:
        host: The hosting chunk.

    Returns:
        The new chunkgroup, or None if there was nothing to localise.
    """
    if not is_localisable(host):
        return None
    scene = _active_scene()
    stage = host.get_scene_stage()
    if not (scene and stage):
        return None
    sync = ChunkStageSync()
    host_path = Sdf.Path(get_chunk_prim_path(host))
    already_a_group = is_chunkgroup(host)
    composed = Usd.Stage.OpenMasked(
        stage.GetRootLayer(), stage.GetSessionLayer(), stage.GetPathResolverContext(),
        Usd.StagePopulationMask([str(host_path)]),
    )
    flat = composed.Flatten(False)
    prev = chunk_notice._usd_write_active
    chunk_notice._usd_write_active = True
    try:
        with sync._chunk_prim_edit_context(host):
            layer = stage.GetEditTarget().GetLayer()
        Sdf.CreatePrimInLayer(layer, host_path)
        Sdf.CopySpec(flat, host_path, layer, host_path)
        spec = layer.GetPrimAtPath(host_path)
        spec.referenceList.ClearEdits()
        spec.payloadList.ClearEdits()
        spec.typeName = _CHUNK_PRIM_TYPENAME
        spec.specifier = Sdf.SpecifierDef
        for name in list(spec.properties.keys()):
            if name.startswith(_INPUTS_PREFIX) and name != chunk_naming.EXEC_INPUT:
                del spec.properties[name]
            elif name == chunk_naming.MODULE_HASH_ATTR:
                del spec.properties[name]
        chunk_type = spec.properties.get(_CHUNK_TYPE_ATTR) or Sdf.AttributeSpec(
            spec, _CHUNK_TYPE_ATTR, Sdf.ValueTypeNames.Token, Sdf.VariabilityUniform)
        chunk_type.default = "chunkgroup"
        # The arc and the host's own inputs: in every other owned layer too, or a stronger
        # one keeps the prim a Reference after this one says chunkgroup.
        for other in _owned_layers(stage):
            other_spec = other.GetPrimAtPath(host_path)
            if other_spec is None or other is layer:
                continue
            other_spec.referenceList.ClearEdits()
            other_spec.payloadList.ClearEdits()
            for name in list(other_spec.properties.keys()):
                if name.startswith(_INPUTS_PREFIX) and name != chunk_naming.EXEC_INPUT:
                    del other_spec.properties[name]
                elif name in (_CHUNK_TYPE_ATTR, chunk_naming.MODULE_HASH_ATTR):
                    del other_spec.properties[name]
    finally:
        chunk_notice._usd_write_active = prev
    invalidate_edit_layer_memo()
    if already_a_group:
        # A published chunkgroup taking its network back: the objects are the right kind
        # already, and their prims are now authored where they were composed.
        return host

    # Rebuild the objects from the prims: the host object is a Reference chunk, and what
    # the prim now describes is a chunkgroup. Deepest first, so a nested group goes before
    # its parent; under _reloading, so nothing is unauthored on the way out.
    inside = [
        c for c in scene.get_chunks()
        if get_chunk_prim_path(c).startswith(str(host_path) + "/")
    ]
    inside.sort(key=lambda c: get_chunk_prim_path(c).count("/"), reverse=True)
    was_reloading = sync._reloading
    sync._reloading = True
    try:
        for c in inside:
            c.request_delete()
        host.request_delete()
    finally:
        sync._reloading = was_reloading
    prim = stage.GetPrimAtPath(host_path)
    sync._loaded_prim_paths.discard(str(host_path))
    load_chunks(stage, scene, sync._loaded_prim_paths,
                prims=iter([prim] + list(Usd.PrimRange(prim, _LOAD_INCLUDE_INACTIVE))[1:]))
    return next((c for c in scene.get_chunks() if get_chunk_prim_path(c) == str(host_path)), None)

loft_param_to_context ⚓︎

loft_param_to_context(param, context)

Loft a param up to the context prim's public interface.

Creates inputs:{owner}_{param.name} on the context prim, connects the inner storage attribute to it, and re-binds the Python param to track the context attribute -- so reads and writes flow through the context prim interface.

The name is settled here, once, and then belongs to the group. It is deliberately not re-derived from the owning chunk later: the interface is what the CLI addresses by name, what expressions reference and what saved files record, so renaming an inner chunk must not silently change the group's published interface.

Parameters:

Name Type Description Default
param ChunkParamBase

The param to loft.

required
context ChunkBase

The group to publish it on.

required
Source code in usd_chunks/chunk_stage.py
@_editing_lofts()
def loft_param_to_context(param: core.ChunkParamBase, context: core.ChunkBase) -> None:
    """Loft a param up to the context prim's public interface.

    Creates ``inputs:{owner}_{param.name}`` on the context prim, connects the inner
    storage attribute to it, and re-binds the Python param to track the context
    attribute -- so reads and writes flow through the context prim interface.

    The name is settled here, once, and then belongs to the group. It is deliberately not
    re-derived from the owning chunk later: the interface is what the CLI addresses by
    name, what expressions reference and what saved files record, so renaming an inner
    chunk must not silently change the group's published interface.

    Args:
        param: The param to loft.
        context: The group to publish it on.
    """
    sync = ChunkStageSync()
    if not sync.initialized or not sync._stage:
        return
    if (row := _list_row(param)) is not None:
        _loft_row(sync._stage, param, context, *row)
        return
    param = _promoted_for_loft(param)
    if lofted_copy(param, context) is not None:
        return  # one copy per group: a second would be a control nothing reads

    stage = sync._stage

    if param._param_attr_path and not stage.GetAttributeAtPath(Sdf.Path(param._param_attr_path)):
        # Bound to an attr that has gone: a param at its default, unlofted, whose attr held
        # nothing but the loft. Let go of it, so the one below is made afresh.
        param._param_attr_path = None
        if param._usd_prop_connection:
            param._usd_prop_connection.disconnect()
            param._usd_prop_connection = None
    if not param._param_attr_path:
        # A param still at its default has no USD attr yet -- create it so there's something to
        # promote (Loft up right after creating a chunk is the common case).
        owner = param.get_chunk()
        if owner is not None and isinstance(param, core.ChunkVectorBase):
            sync._sync_vector_input(owner, param, force=True)
        elif owner is not None:
            sync._sync_param_input(owner, param, force=True)
    if not param._param_attr_path:
        logger.warning("loft_param_to_context: param %r has no USD attribute bound", param.name)
        return

    inner_attr = stage.GetAttributeAtPath(Sdf.Path(param._param_attr_path))
    if not (inner_attr and inner_attr.IsValid()):
        logger.warning("loft_param_to_context: attribute not found at %s", param._param_attr_path)
        return

    # OUTPUT-flagged params loft to outputs:name so a group can expose computed results, not
    # just inputs (data-out ports); everything else is a data-in port (inputs:name).
    prefix = "outputs:" if param.has_flag(ChunkFlags.ParamFlags.OUTPUT) else _INPUTS_PREFIX
    context_prim_path = Sdf.Path(context.prim_path if context.prim_path else _CHUNKS_ROOT)

    context_prim = stage.GetPrimAtPath(context_prim_path)
    if not (context_prim and context_prim.IsValid()):
        context_prim = stage.DefinePrim(context_prim_path)

    if not (context_prim and context_prim.IsValid()):
        logger.warning("loft_param_to_context: could not get/create context prim at %s", context.prim_path)
        return

    # Resolved against the prim, so the name is unique among what is already published.
    owner = param.get_chunk()
    lofted_name = _lofted_attr_name(context_prim, context, prefix, owner, param.name)
    attr_name = f"{prefix}{lofted_name}"
    context_attr_path = context_prim_path.AppendProperty(attr_name)

    context_attr = context_prim.CreateAttribute(attr_name, inner_attr.GetTypeName(), custom=True)
    if (val := param.value) is not None:
        context_attr.Set(val)
    inner_attr.SetConnections([context_attr_path])

    # Clone before any state changes so the context widget is fully enabled.
    # _param_attr_path and _driven_attr_paths are NO_COPY so the clone starts unbound;
    # we immediately wire it to the context attr.
    context_param = param.clone()
    # Named to match the attribute it fronts, before add_param -- which uniquifies names
    # itself, and would otherwise hand back base_color1 for a param bound to
    # inputs:Rim_base_color. That mismatch is what made the second loft a phantom control:
    # a distinct param in the panel, wired to somebody else's attribute.
    context_param.name = lofted_name
    # clone() carried param's own label over verbatim (e.g. "Prim Path"), which the widget
    # prefers over .name (get_label()) -- without this, every lofted param that shares its
    # inner param's label showed identically in the panel regardless of the qualifier baked
    # into .name, and there was no way to tell three lofted Prim Paths apart at a glance.
    # A one-time default the same as the name above: renaming this param afterwards (an
    # ordinary edit to its label, same as any param) is not overwritten by a later rename
    # of the source chunk.
    # No stored customData yet at this point -- a fresh loft always starts at the
    # generated default, same as the attribute name above.
    context_param.label = _lofted_label(owner, context, param.get_label())
    context_param._lofted = True
    context.add_param(context_param)
    # clone() carries over the source param's cached _chunk_parent (the inner chunk), and
    # add_param doesn't invalidate it -- so get_chunk() would keep returning the inner chunk
    # instead of the group this param now lives on. That broke lofting a group's own param up
    # again (the "loft to parent group" case): the Loft-up target resolver couldn't tell the
    # param sits on a group, so it re-lofted onto the same group. Clear it so it re-resolves.
    context_param._chunk_parent = None
    context_param._connect_param_attr(context_attr)

    _wire_loft_sync(param, context_param)
    _mirror_menu_items(param, context_param)
    _forward_button_click(param, context_param)

    # A rename (chunk_qt_widgets' "Rename..." on a lofted param, or any other code setting
    # .label) has to survive a save/reload -- without this it only lived in the Python
    # object for the rest of the session and _restore_lofted_params rebuilt the generated
    # default on the next load, silently discarding it. Scoped to the "label" attribute
    # specifically (its own AttributeSender), not the coarse PARAM_CHANGED the value-forward
    # callbacks above use, so this doesn't fire (and re-touch USD) on every value edit too.
    def _persist_lofted_label(_owner, _notice, _sender=None):
        if not context_param._param_attr_path:
            return
        target = stage.GetAttributeAtPath(Sdf.Path(context_param._param_attr_path))
        if not (target and target.IsValid()):
            return
        home = chunk_utils.get_attr_home_layer(target) or stage.GetSessionLayer()
        with Usd.EditContext(stage, home):
            chunk_utils.store_lofted_label(target, context_param.label)

    context_param._loft_label_persist = _persist_lofted_label  # strong-ref pin
    context_param.add_callback(
        _persist_lofted_label,
        sender=context_param.get_attribute_sender("label"),
        send_on_create=False,
        private=True,
    )

lofted_copy ⚓︎

lofted_copy(param, context)

The param on context that param is lofted to.

Parameters:

Name Type Description Default
param ChunkParamBase

The inner param.

required
context ChunkBase

The group it may be lofted to.

required

Returns:

Type Description
ChunkParamBase | None

The lofted param on context, or None when param is not lofted there.

Source code in usd_chunks/chunk_stage.py
def lofted_copy(param: core.ChunkParamBase, context: core.ChunkBase) -> core.ChunkParamBase | None:
    """The param on context that param is lofted to.

    Args:
        param: The inner param.
        context: The group it may be lofted to.

    Returns:
        The lofted param on context, or None when param is not lofted there.
    """
    sync = ChunkStageSync()
    if not (sync.initialized and sync._stage and param._param_attr_path):
        return None
    attr = sync._stage.GetAttributeAtPath(Sdf.Path(param._param_attr_path))
    if not (attr and attr.IsValid()):
        return None
    targets = {str(c) for c in attr.GetConnections()}
    return next((p for p in context.get_my_params()
                 if getattr(p, "_lofted", False) and p._param_attr_path in targets), None)

match_lofted_params ⚓︎

match_lofted_params(stage, contexts)

Bring each group's lofted params back in line with its attributes in USD.

An undo or redo of Loft up or Unloft changes only USD. A lofted param whose attribute is gone is dropped, and one whose attribute came back is made again, so the Params page shows what the stage has.

Parameters:

Name Type Description Default
stage Stage

The stage.

required
contexts Iterable[ChunkBase]

The groups to check.

required
Source code in usd_chunks/chunk_stage.py
def match_lofted_params(stage: Usd.Stage, contexts: Iterable[core.ChunkBase]) -> None:
    """Bring each group's lofted params back in line with its attributes in USD.

    An undo or redo of Loft up or Unloft changes only USD. A lofted param whose attribute
    is gone is dropped, and one whose attribute came back is made again, so the Params
    page shows what the stage has.

    Args:
        stage: The stage.
        contexts: The groups to check.
    """
    if _loft_edit_depth:
        return
    contexts = list(contexts)
    for context in contexts:
        for param in [p for p in context.get_my_params() if getattr(p, "_lofted", False)]:
            path = param._param_attr_path
            if not (path and stage.GetAttributeAtPath(Sdf.Path(path))):
                param.request_delete()
    _restore_lofted_on(stage, contexts)

nested_cook_keys ⚓︎

nested_cook_keys(chunks, stage, *, from_dag=False)

A sort key per chunk (by id) that orders a nested network upstream-first.

The key is the chunk's ancestor chain, outermost first, each level standing for how far down its own siblings' wiring that ancestor sits (its longest path from a sibling with no input, read from the stage's wires as in commit_order_from_stage). Siblings wired to nothing tie, and a tie goes to the shorter chain, so a chunk still comes before what is nested deeper beside it -- the outermost-first order load_chunks always cooked in.

What a plain depth sort missed is two groups wired one after the other: the downstream group's inner chunks are shallower than the upstream group's deepest ones, so they cooked first, against a stage without what the upstream group makes, and nothing cooked them again.

A wire from inside another group counts against the sibling holding its source. A cycle is broken rather than dropped: whatever is left takes the level after the last.

Parameters:

Name Type Description Default
chunks Iterable[ChunkBase]

The chunks to key; ancestors outside this set end the chain.

required
stage Stage

The stage holding their chunk prims.

required
from_dag bool

Read the wires from the chunks' DAG dependencies, not the stage. A load reads the stage, which is what the file says; a script sorting after every chunk it makes reads the DAG, which agrees and costs a small fraction of the time.

False

Returns:

Type Description
dict[int, tuple]

id(chunk) -> key tuple.

Source code in usd_chunks/chunk_stage.py
def nested_cook_keys(
    chunks: Iterable[core.ChunkBase], stage: Usd.Stage, *, from_dag: bool = False,
) -> dict[int, tuple]:
    """A sort key per chunk (by id) that orders a nested network upstream-first.

    The key is the chunk's ancestor chain, outermost first, each level standing for how far
    down its own siblings' wiring that ancestor sits (its longest path from a sibling with no
    input, read from the stage's wires as in commit_order_from_stage). Siblings wired to
    nothing tie, and a tie goes to the shorter chain, so a chunk still comes before what is
    nested deeper beside it -- the outermost-first order load_chunks always cooked in.

    What a plain depth sort missed is two groups wired one after the other: the downstream
    group's inner chunks are shallower than the upstream group's deepest ones, so they cooked
    first, against a stage without what the upstream group makes, and nothing cooked them
    again.

    A wire from inside another group counts against the sibling holding its source. A cycle
    is broken rather than dropped: whatever is left takes the level after the last.

    Args:
        chunks: The chunks to key; ancestors outside this set end the chain.
        stage: The stage holding their chunk prims.
        from_dag: Read the wires from the chunks' DAG dependencies, not the stage. A load
            reads the stage, which is what the file says; a script sorting after every chunk
            it makes reads the DAG, which agrees and costs a small fraction of the time.

    Returns:
        id(chunk) -> key tuple.
    """
    chunks = list(chunks)
    # Siblings by prim parentage, as hosting is decided (#408): get_context is the context
    # at or above a chunk -- a group's own self -- and the owner chain of a group need not
    # reach the one around it. Nested so, the groups' wiring was never compared at all.
    path_of = {id(c): get_chunk_prim_path(c) for c in chunks}
    by_prim_path = {path: c for c in chunks if (path := path_of[id(c)])}
    families: dict[str, list[core.ChunkBase]] = {}
    for c in chunks:
        families.setdefault(str(Sdf.Path(path_of[id(c)]).GetParentPath()), []).append(c)

    level: dict[int, int] = {}
    for family in families.values():
        by_path = {get_chunk_prim_path(c): c for c in family}
        inputs: dict[int, set[int]] = {}
        outputs: dict[int, list[core.ChunkBase]] = {id(c): [] for c in family}
        for c in family:
            found: set[int] = set()
            if from_dag:
                sources = _dag_source_paths(c)
            else:
                prim = stage.GetPrimAtPath(Sdf.Path(get_chunk_prim_path(c)))
                sources = _connected_source_paths(prim) if prim and prim.IsValid() else ()
            if sources:
                for source in sources:
                    path = Sdf.Path(source)
                    while path not in (Sdf.Path.absoluteRootPath, Sdf.Path.emptyPath):
                        if (sibling := by_path.get(str(path))) is not None:
                            if sibling is not c and id(sibling) not in found:
                                found.add(id(sibling))
                                outputs[id(sibling)].append(c)
                            break
                        path = path.GetParentPath()
            inputs[id(c)] = found
        waiting = {id(c): len(inputs[id(c)]) for c in family}
        ready = [c for c in family if not waiting[id(c)]]
        for c in ready:
            level[id(c)] = 0
        while ready:
            c = ready.pop()
            for down in outputs[id(c)]:
                level[id(down)] = max(level.get(id(down), 0), level[id(c)] + 1)
                waiting[id(down)] -= 1
                if not waiting[id(down)]:
                    ready.append(down)
        last = max((level[id(c)] for c in family if id(c) in level), default=-1)
        for c in family:
            if waiting[id(c)]:
                level[id(c)] = last + 1

    keys: dict[int, tuple] = {}
    for c in chunks:
        chain = []
        node = c
        while node is not None and id(node) in level:
            chain.append(level[id(node)])
            node = by_prim_path.get(str(Sdf.Path(path_of[id(node)]).GetParentPath()))
        keys[id(c)] = tuple(reversed(chain))
    return keys

network_target ⚓︎

network_target(asset_path, import_path='')

The prim path of the chunkgroup a referenced file offers, or None for scene content.

Resolved the way the Reference chunk resolves its target: the explicit import path, else the layer's defaultPrim, else its single root prim. A target is a network when it composes to a Chunk of type chunkgroup -- the shape export_chunks writes. That shape puts the group under a /chunks scope, so a target that is the scope itself stands for the first chunkgroup in it: pointing a Reference at a saved network file, with no import path, hosts the network it holds.

Composed, not read off the one layer's specs: a file may hold its network only through its own sublayers (a sequence file that stacks a layout file and a lighting file), and hosting composes the whole of it in anyway. Opened with a population mask of just the candidate paths, so asking a heavy asset file whether it is a network costs its chunk prims, not its geometry.

Parameters:

Name Type Description Default
asset_path str

The referenced file.

required
import_path str

The prim path the reference targets, or "" for the file's default.

''

Returns:

Type Description
str | None

The chunkgroup's prim path in the file, or None.

Source code in usd_chunks/chunk_stage.py
def network_target(asset_path: str, import_path: str = "") -> str | None:
    """The prim path of the chunkgroup a referenced file offers, or None for scene content.

    Resolved the way the Reference chunk resolves its target: the explicit import path,
    else the layer's defaultPrim, else its single root prim. A target is a network when
    it composes to a Chunk of type chunkgroup -- the shape export_chunks writes. That
    shape puts the group under a /chunks scope, so a target that is the scope itself
    stands for the first chunkgroup in it: pointing a Reference at a saved network file,
    with no import path, hosts the network it holds.

    Composed, not read off the one layer's specs: a file may hold its network only
    through its own sublayers (a sequence file that stacks a layout file and a lighting
    file), and hosting composes the whole of it in anyway. Opened with a population mask
    of just the candidate paths, so asking a heavy asset file whether it is a network
    costs its chunk prims, not its geometry.

    Args:
        asset_path: The referenced file.
        import_path: The prim path the reference targets, or "" for the file's default.

    Returns:
        The chunkgroup's prim path in the file, or None.
    """
    if not asset_path:
        return None
    # A network is a USD file. Opening anything else to ask -- a .mtlx a material Reference
    # points at -- ran its plugin's conversion and hundreds of change notices, then dropped
    # the layer for the reference to open it all again. A path whose format is unknown
    # (no extension, a resolver's own scheme) is still opened, as before.
    fmt = Sdf.FileFormat.FindByExtension(Sdf.FileFormat.GetFileExtension(asset_path))
    if fmt is not None and fmt.formatId not in _USD_FORMAT_IDS:
        return None
    try:
        layer = Sdf.Layer.FindOrOpen(asset_path)
    except Tf.ErrorException:
        # A file this USD build has no format plugin for (a .mtlx without the MaterialX
        # plugin). Not a network, and not this function's error to raise: the chunk
        # that goes on to reference the file reports it, as it always has.
        return None
    if layer is None:
        return None
    if import_path:
        candidates = [Sdf.Path(import_path)]
    elif layer.defaultPrim:
        candidates = [Sdf.Path.absoluteRootPath.AppendChild(layer.defaultPrim)]
    else:
        # The layer's own roots, plus the scope a network lives under, which the layer
        # may only get from a sublayer.
        candidates = [spec.path for spec in layer.rootPrims]
        if Sdf.Path(_CHUNKS_ROOT) not in candidates:
            candidates.append(Sdf.Path(_CHUNKS_ROOT))

    # The layer's own specs first: free, and the answer for every file export_chunks
    # wrote. Composition only when the layer stacks sublayers the answer could be in --
    # composing a big asset's default prim to learn it is not a network would cost that
    # asset's whole hierarchy on every cook of a plain Reference.
    def spec_is_group(prim_spec) -> bool:
        if prim_spec is None or prim_spec.typeName != _CHUNK_PRIM_TYPENAME:
            return False
        attr = prim_spec.attributes.get(_CHUNK_TYPE_ATTR)
        return attr is not None and attr.default == "chunkgroup"

    for path in candidates:
        spec = layer.GetPrimAtPath(path)
        if spec_is_group(spec):
            return str(path)
        if spec is not None and spec.typeName == _CHUNKS_ROOT_TYPENAME:
            for child in spec.nameChildren.values():
                if spec_is_group(child):
                    return str(child.path)
    if not layer.subLayerPaths:
        return None
    try:
        composed = Usd.Stage.OpenMasked(
            layer, Usd.StagePopulationMask([str(c) for c in candidates]), Usd.Stage.LoadNone
        )
    except Tf.ErrorException:
        return None

    def is_group(prim) -> bool:
        if not prim or not prim.IsValid() or prim.GetTypeName() != _CHUNK_PRIM_TYPENAME:
            return False
        return prim.GetAttribute(_CHUNK_TYPE_ATTR).Get() == "chunkgroup"

    for path in candidates:
        prim = composed.GetPrimAtPath(path)
        if is_group(prim):
            return str(path)
        if prim and prim.IsValid() and prim.GetTypeName() == _CHUNKS_ROOT_TYPENAME:
            for child in prim.GetFilteredChildren(_LOAD_INCLUDE_INACTIVE):
                if is_group(child):
                    return str(child.GetPath())
    return None

normalize_merge_slots ⚓︎

normalize_merge_slots(stage, prim)

Keep a dynamic-slot chunk's connected exec inputs in slots 0..N-1 with no gaps.

Applies to Merge, Switch and any other dynamic-slot chunk. Clearing a middle slot compacts the rest up, so slot order (which is what decides whose Merge opinion wins, or which branch a Switch's index N means) always matches the port order the user sees on the node, rather than drifting into a question about invisible attribute names.

Judged on the CONNECTED slots alone -- an exec attribute that exists but connects nothing is deliberately left in place. It has to be: this runs synchronously from the stage notice that CreateAttribute itself fires, so an authoring path which creates the attribute and then connects it (_author_connection does exactly that, and so does the numbered-slot branch of _on_dependency_added) would otherwise have the attribute deleted underneath it between the two statements, and would go on to call SetConnections on an invalid handle. The cost is that clearing the LAST slot can leave a connectionless inputs:chunkN behind; it is inert -- it carries no connection, _build_ports counts connections rather than attributes, and the next compaction sweeps it -- so it is preferable to breaking the authoring paths.

No-ops for anything without dynamic exec inputs, and for one already in shape, so it is safe to call on every exec-input change.

Parameters:

Name Type Description Default
stage Stage

The stage to author on.

required
prim Prim

The chunk prim.

required

Returns:

Name Type Description
bool bool

True if any slot was rewritten

Source code in usd_chunks/chunk_stage.py
def normalize_merge_slots(stage: Usd.Stage, prim: Usd.Prim) -> bool:
    """Keep a dynamic-slot chunk's connected exec inputs in slots 0..N-1 with no gaps.

    Applies to Merge, Switch and any other dynamic-slot chunk. Clearing a middle slot
    compacts the rest up, so slot order (which is what decides whose Merge opinion wins, or
    which branch a Switch's index N means) always matches the port order the user sees on
    the node, rather than drifting into a question about invisible attribute names.

    Judged on the CONNECTED slots alone -- an exec attribute that exists but connects nothing
    is deliberately left in place. It has to be: this runs synchronously from the stage
    notice that CreateAttribute itself fires, so an authoring path which creates the
    attribute and then connects it (_author_connection does exactly that, and so does the
    numbered-slot branch of _on_dependency_added) would otherwise have the attribute deleted
    underneath it between the two statements, and would go on to call SetConnections on an
    invalid handle. The cost is that clearing the LAST slot can leave a connectionless
    inputs:chunkN behind; it is inert -- it carries no connection, `_build_ports` counts
    connections rather than attributes, and the next compaction sweeps it -- so it is
    preferable to breaking the authoring paths.

    No-ops for anything without dynamic exec inputs, and for one already in shape, so it is
    safe to call on every exec-input change.

    Args:
        stage: The stage to author on.
        prim: The chunk prim.

    Returns:
        bool: True if any slot was rewritten
    """
    if not has_dynamic_exec_inputs_prim(prim):
        return False
    current = [(attr, list(attr.GetConnections())) for attr in iter_exec_inputs(prim)]
    live = [(attr, conns) for attr, conns in current if conns]
    desired_names = [exec_input_name(i) for i in range(len(live))]
    if [attr.GetName() for attr, _ in live] == desired_names:
        return False

    # Resolve each surviving branch's home layer BEFORE unauthoring anything, so a moved
    # connection is re-authored in the layer it was already living in rather than being
    # silently relocated (which could put it somewhere weaker than a spec left elsewhere).
    moves = [
        (
            desired_names[i],
            conns,
            chunk_utils.get_attr_home_layer(attr) or chunk_utils.get_bookkeeping_layer(stage, None),
        )
        for i, (attr, conns) in enumerate(live)
    ]

    prev_w = chunk_notice._usd_write_active
    chunk_notice._usd_write_active = True
    try:
        # Clear every slot first, then re-author. Renaming in place would have to worry about
        # a move landing on a slot that is still occupied by the branch below it.
        for attr, _ in current:
            _remove_attr_spec(stage, prim, attr.GetName())
        for name, conns, home in moves:
            with Usd.EditContext(stage, home):
                attr = prim.CreateAttribute(name, Sdf.ValueTypeNames.Token, custom=False)
                attr.SetConnections(conns)
    finally:
        chunk_notice._usd_write_active = prev_w
    # Slots moved with notices suppressed, so nothing else will drop the memoised
    # nearest-upstream-Edit-Target answers measured against the old wiring.
    invalidate_edit_layer_memo()
    return True

order_layers_like_the_views ⚓︎

order_layers_like_the_views(stage, scene, lm)

Rank chunk layers as each graph's recook for its view will, without cooking anything.

A load first sorts by wiring depth (sort_chunk_layers), which mixes a Merge's branches by length. A graph's recook for its active View, or its Output when none is active, keeps each branch together with the Merge's first input strongest. Ranked the same way here, a script opening the network gets the graph's result, and the graph's first recook moves nothing -- so every chunk can still skip its next cook. Inner graphs first, as a recook ranks a group's chunks in the group's own cook.

Parameters:

Name Type Description Default
stage

The stage.

required
scene

The scene.

required
lm ChunkLayerManager

The layer manager.

required
Source code in usd_chunks/chunk_stage.py
def order_layers_like_the_views(stage, scene, lm: ChunkLayerManager) -> None:
    """Rank chunk layers as each graph's recook for its view will, without cooking anything.

    A load first sorts by wiring depth (sort_chunk_layers), which mixes a Merge's branches by
    length. A graph's recook for its active View, or its Output when none is active, keeps
    each branch together with the Merge's first input strongest. Ranked the same way here, a
    script opening the network gets the graph's result, and the graph's first recook moves
    nothing -- so every chunk can still skip its next cook. Inner graphs first, as a recook
    ranks a group's chunks in the group's own cook.

    Args:
        stage: The stage.
        scene: The scene.
        lm: The layer manager.
    """
    if not lm.initialized:
        return
    root = scene.peek_root_context()
    contexts = sorted(scene.get_contexts(), key=lambda c: -get_chunk_prim_path(c).count("/"))
    for context in contexts:
        # The outermost graph as it is shown; a group as its parent's recook cooks it.
        driver, synthetic = graph_driver(stage, scene, context, deliver=context is not root)
        if driver is not None and not is_output_chunk(driver):
            cook_list = _cook_list(stage, scene, driver, None, synthetic)
        else:
            outputs = graph_outputs(stage, scene, context)
            cook_list = _cook_list(stage, scene, outputs[-1] if outputs else None, outputs)
        _rank_layers_by_cook_list(lm, scene, cook_list)

owning_group ⚓︎

owning_group(chunk)

The group chunk sits in: the one it is lofted to.

Not get_context() for a group, which answers the group itself.

Parameters:

Name Type Description Default
chunk ChunkBase

The chunk.

required

Returns:

Type Description
ChunkBase | None

The group, or None for the outermost one.

Source code in usd_chunks/chunk_stage.py
def owning_group(chunk: core.ChunkBase) -> core.ChunkBase | None:
    """The group chunk sits in: the one it is lofted to.

    Not get_context() for a group, which answers the group itself.

    Args:
        chunk: The chunk.

    Returns:
        The group, or None for the outermost one.
    """
    if chunk.has_flag(ChunkFlags.GroupFlags.CONTEXT):
        parent_ref = getattr(chunk, "_parent_context", None)
        return parent_ref() if parent_ref else None
    return chunk.get_context()

param_held_by ⚓︎

param_held_by(param)

The layer whose opinion on this param is stronger than where the param writes, or None.

The other side of param_override_source. There the param's own value sits over one composed in; here something sits over the param's own: an Override Chunk Prim's layer, or a department layer stronger than the one this chunk's prim is written in. An edit to the param still lands, in its home (chunk_utils.get_attr_home_layer), but the value composed -- and so the one the param shows and cooks with -- is the stronger one's. Without saying so the field just springs back.

Parameters:

Name Type Description Default
param ChunkParamBase

The param, or a vector part (its vector's attribute is the one asked about).

required

Returns:

Type Description
Layer | None

The stronger layer, or None.

Source code in usd_chunks/chunk_stage.py
def param_held_by(param: core.ChunkParamBase) -> Sdf.Layer | None:
    """The layer whose opinion on this param is stronger than where the param writes, or None.

    The other side of param_override_source. There the param's own value sits over one
    composed in; here something sits over the param's own: an Override Chunk Prim's layer,
    or a department layer stronger than the one this chunk's prim is written in. An edit
    to the param still lands, in its home (chunk_utils.get_attr_home_layer), but the value
    composed -- and so the one the param shows and cooks with -- is the stronger one's.
    Without saying so the field just springs back.

    Args:
        param: The param, or a vector part (its vector's attribute is the one asked about).

    Returns:
        The stronger layer, or None.
    """
    chunk = param.get_chunk()
    stage = param.get_scene_stage() if chunk else None
    if stage is None:
        return None
    owner = param.get_owner()
    target = owner if isinstance(owner, core.ChunkVectorBase) else param
    names = _param_object_path(chunk, target)
    return _input_held_by(chunk, stage, ":".join(names)) if names else None

param_locked_by ⚓︎

param_locked_by(param)

The locked layer an edit of param would land in, or None when it can be edited.

Where an edit goes is the same answer ChunkParamBase.data_changed acts on (chunk_utils.param_storage_layer): with the stage's edit target on a read-only department file, a layout chunk's param is locked; set it to a layer you can edit and the same edit is an override there.

Source code in usd_chunks/chunk_stage.py
def param_locked_by(param: core.ChunkParamBase) -> Sdf.Layer | None:
    """The locked layer an edit of param would land in, or None when it can be edited.

    Where an edit goes is the same answer ChunkParamBase.data_changed acts on
    (chunk_utils.param_storage_layer): with the stage's edit target on a read-only
    department file, a layout chunk's param is locked; set it to a layer you can edit and
    the same edit is an override there.
    """
    try:
        stage = param.get_scene_stage()
        path = getattr(param, "_param_attr_path", None)
        if stage is None or not path or getattr(param, "_var_selections", None):
            return None
        attr = stage.GetAttributeAtPath(Sdf.Path(path))
        if not attr:
            return None
        layer = chunk_utils.param_storage_layer(stage, attr, param.get_chunk())
    except (AttributeError, ReferenceError):
        return None
    return layer if chunk_utils.is_layer_locked(layer) else None

param_override_source ⚓︎

param_override_source(param)

The composed-in layer whose opinion this param's value overrides, or None.

A param on a chunk that arrived by composition (a hosted network, a sublayered sequence) shows the file's value until the shot writes its own; then the storage attr has an opinion in an owned layer sitting over one from a foreign layer or across an arc. That weaker opinion's layer is the answer -- what a UI names in "overrides seq.usda" and what revert_param_override puts back. A local opinion with nothing composed in beneath it is not an override, just a value.

Parameters:

Name Type Description Default
param ChunkParamBase

The param.

required

Returns:

Type Description
Layer | None

The overridden layer, or None.

Source code in usd_chunks/chunk_stage.py
def param_override_source(param: core.ChunkParamBase) -> Sdf.Layer | None:
    """The composed-in layer whose opinion this param's value overrides, or None.

    A param on a chunk that arrived by composition (a hosted network, a sublayered
    sequence) shows the file's value until the shot writes its own; then the storage
    attr has an opinion in an owned layer sitting over one from a foreign layer or across
    an arc. That weaker opinion's layer is the answer -- what a UI names in "overrides
    seq.usda" and what revert_param_override puts back. A local opinion with nothing
    composed in beneath it is not an override, just a value.

    Args:
        param: The param.

    Returns:
        The overridden layer, or None.
    """
    attr = _storage_attr(param)
    if attr is None:
        return None
    stage = attr.GetStage()
    local = False
    for spec in attr.GetPropertyStack(Usd.TimeCode.Default()):
        composed_in = spec.path != attr.GetPath() or chunk_utils.is_foreign_layer(spec.layer, stage)
        if composed_in:
            return spec.layer if local else None
        local = True
    return None

param_sdf_type ⚓︎

param_sdf_type(param)

The type a param's chunk-prim attribute is created with, or None if it has none.

From the value, or from the default while the value is a @Node.param@ expression -- the expression text is not the param's type, and a Slider wired to another chunk must still get a number attribute, or the first plain number typed into it after the wire is gone cannot be written.

Source code in usd_chunks/chunk_stage.py
def param_sdf_type(param: core.ChunkParamBase) -> Sdf.ValueTypeName | None:
    """The type a param's chunk-prim attribute is created with, or None if it has none.

    From the value, or from the default while the value is a @Node.param@ expression -- the
    expression text is not the param's type, and a Slider wired to another chunk must still
    get a number attribute, or the first plain number typed into it after the wire is gone
    cannot be written.
    """
    raw = getattr(param, "raw_value", None)
    is_expr = isinstance(raw, str) and chunk_utils.has_expression(raw)
    type_source = getattr(param, "default_value", None) if is_expr or raw is None else raw
    if ChunkFlags.ParamType.BUTTON in param.evaluate_type():
        # A button has no value. Its attribute exists only so Loft up can wire to it.
        return Sdf.ValueTypeNames.Bool
    # A ColorPicker holds an (r, g, b) tuple, and _SDF_TYPE_MAP is keyed by Python
    # type -- there is no tuple entry, so without this a colour param resolves to no
    # type at all and never gets a chunk-prim attr, leaving its value unable to
    # round-trip through USD.
    # Compared with ==: VECTOR | FLOAT_SLIDER also contains every bit of COLOR_PICKER, and
    # a wired Vector typed as a colour read back as a colour port once its chunk was gone.
    param_type = param.evaluate_type()
    if param_type == ChunkFlags.ParamType.COLOR_PICKER:
        return Sdf.ValueTypeNames.Color3f
    if isinstance(param, core.ChunkVectorBase):
        if ChunkFlags.ParamType.FLOAT in param_type:
            return _VECTOR_TYPE_MAP.get((float, param.length), (None, None))[0]
        return _sdf_vector_type(type_source)[0] if type_source else None
    sdf_type = _SDF_TYPE_MAP.get(type(type_source))
    if sdf_type is not None and ChunkFlags.ParamType.FLOAT in param_type:
        # A float slider can hold a whole number (Slider("x") starts at 0): still a float.
        return _SDF_TYPE_MAP[float]
    return sdf_type

params_are_bound ⚓︎

params_are_bound(chunk)

Whether any of this chunk's params still drives a real prim attribute.

For a chunk that builds its params from the prim it authors -- a Light, a Camera, anything on show_attribute -- this is the difference between a cook that landed and one that only looked like it did. Cooking against a muted layer composes no prim, so show_attribute binds nothing; a chunk that caches "already cooked this type at this path" would then never rebuild the binding, and every value it holds drives nothing.

Parameters:

Name Type Description Default
chunk ChunkBase

The chunk.

required

Returns:

Type Description
bool

True if some param has a driven attribute path.

Source code in usd_chunks/chunk_stage.py
def params_are_bound(chunk: core.ChunkBase) -> bool:
    """Whether any of this chunk's params still drives a real prim attribute.

    For a chunk that builds its params from the prim it authors -- a Light, a Camera,
    anything on show_attribute -- this is the difference between a cook that landed and one
    that only looked like it did. Cooking against a muted layer composes no prim, so
    show_attribute binds nothing; a chunk that caches "already cooked this type at this
    path" would then never rebuild the binding, and every value it holds drives nothing.

    Args:
        chunk: The chunk.

    Returns:
        True if some param has a driven attribute path.
    """
    return any(
        getattr(param, "_driven_attr_paths", None)
        for _, param in _iter_chunk_params(chunk)
    )

paste_chunks ⚓︎

paste_chunks()

Create duplicates of clipboard chunks, copying their input attribute values.

Source code in usd_chunks/chunk_stage.py
def paste_chunks() -> None:
    """Create duplicates of clipboard chunks, copying their input attribute values."""
    if not _chunk_clipboard:
        return
    registry = chunk_registry.ChunkRegistry()
    scene = registry.scene
    if not scene:
        return
    stage = scene.get_stage()
    if not stage:
        return

    prim_to_chunk = {get_chunk_prim_path(c): c for c in scene.get_chunks()}
    for prim_path in _chunk_clipboard:
        src_chunk = prim_to_chunk.get(prim_path)
        if src_chunk is None:
            continue
        cfg = src_chunk.get_config()
        if not cfg or not cfg.module:
            continue
        src_prim = stage.GetPrimAtPath(Sdf.Path(prim_path))
        if not src_prim.IsValid():
            continue
        new_chunks = _chunk_mod.create_chunks(cfg.module)
        if not new_chunks:
            continue
        new_chunk = new_chunks[0]
        new_prim_path = get_chunk_prim_path(new_chunk)
        new_prim = stage.GetPrimAtPath(Sdf.Path(new_prim_path))
        if not new_prim.IsValid():
            continue
        for attr in src_prim.GetAttributes():
            name = attr.GetName()
            if not name.startswith(_INPUTS_PREFIX) or name == _EXEC_INPUT:
                continue
            dst_attr = new_prim.GetAttribute(name)
            # dst_attr, when it exists, was just authored by create_chunks() -> _define_prim,
            # via the chunk's own current Edit Target -- update it there, not wherever
            # ambient happens to point. A fresh chunk only has attrs for values off their
            # default, so every value the user changed is missing here: skipping those
            # pasted a copy that had none of them. Made where a new bookkeeping attr goes.
            home = chunk_utils.get_attr_home_layer(dst_attr) if dst_attr.IsValid() else None
            with Usd.EditContext(stage, home or chunk_utils.get_bookkeeping_layer(stage, new_chunk)):
                if not dst_attr.IsValid():
                    dst_attr = new_prim.CreateAttribute(name, attr.GetTypeName(), custom=False)
                val = attr.Get()
                if val is not None:
                    dst_attr.Set(val)
                if attr.HasAuthoredConnections():
                    dst_attr.SetConnections(attr.GetConnections())
                # A wire into a number keeps its text beside the value, not in it.
                if text := chunk_utils.read_expression_text(attr):
                    chunk_utils.store_expression_text(dst_attr, text)
        _load_wire_inputs(new_prim, new_chunk)

pruned_paths ⚓︎

pruned_paths(stage, own_layer_ids)

The prims Prune Prim pruned that an export holding own_layer_ids can leave out.

A pruned prim is deactivated and flagged (PRUNED_KEY). One defined only in the layers given -- what the export writes, and the chunk layers it bakes into them -- can go from the written files altogether. One that also gets a def from somewhere else (a referenced asset) is left: dropping its inactive over would bring it back.

Parameters:

Name Type Description Default
stage

The stage the export writes from.

required
own_layer_ids

Identifiers of the layers whose content the export writes.

required

Returns:

Type Description
list[Path]

The paths, shallowest first.

Source code in usd_chunks/chunk_stage.py
def pruned_paths(stage, own_layer_ids) -> list[Sdf.Path]:
    """The prims Prune Prim pruned that an export holding own_layer_ids can leave out.

    A pruned prim is deactivated and flagged (PRUNED_KEY). One defined only in the layers
    given -- what the export writes, and the chunk layers it bakes into them -- can go
    from the written files altogether. One that also gets a `def` from somewhere else (a
    referenced asset) is left: dropping its inactive over would bring it back.

    Args:
        stage: The stage the export writes from.
        own_layer_ids: Identifiers of the layers whose content the export writes.

    Returns:
        The paths, shallowest first.
    """
    found = []
    it = iter(Usd.PrimRange(stage.GetPseudoRoot(), Usd.PrimAllPrimsPredicate))
    for prim in it:
        if (prim.GetCustomData() or {}).get(PRUNED_KEY):
            stack = prim.GetPrimStack()
            if all(spec.layer.identifier in own_layer_ids for spec in stack
                   if spec.specifier == Sdf.SpecifierDef):
                found.append(prim.GetPath())
            it.PruneChildren()  # what is under it goes with it
    return found

publish_edit_target ⚓︎

publish_edit_target(chunk, stage, layer)

Record the layer an Edit Target chunk targets, then re-home everything downstream to it.

The record is the _EDIT_TARGET_MARKER attr on the chunk's prim, read by nearest_upstream_edit_layer. This is the single entry point the Edit Target chunk's execute() calls, which keeps the marker format and the downstream migration owned by core, not the script.

The marker is updated in place at its existing home (get_attr_home_layer) so re-pointing the Edit Target repeatedly never leaves a stale stronger opinion shadowing the new one -- same discipline as set_chunk_lofted.

Parameters:

Name Type Description Default
chunk ChunkBase

The Edit Target chunk.

required
stage Stage

The stage.

required
layer Layer | None

The layer it targets, or None for none.

required
Source code in usd_chunks/chunk_stage.py
def publish_edit_target(chunk: core.ChunkBase, stage: Usd.Stage, layer: Sdf.Layer | None) -> None:
    """Record the layer an Edit Target chunk targets, then re-home everything downstream to it.

    The record is the _EDIT_TARGET_MARKER attr on the chunk's prim, read by
    nearest_upstream_edit_layer. This is the single entry point the Edit Target chunk's
    execute() calls, which keeps the marker format and the downstream migration owned by
    core, not the script.

    The marker is updated in place at its existing home (get_attr_home_layer) so re-pointing
    the Edit Target repeatedly never leaves a stale stronger opinion shadowing the new one --
    same discipline as set_chunk_lofted.

    Args:
        chunk: The Edit Target chunk.
        stage: The stage.
        layer: The layer it targets, or None for none.
    """
    if not (stage and chunk):
        return
    prim = stage.GetPrimAtPath(Sdf.Path(get_chunk_prim_path(chunk)))
    if not prim.IsValid():
        return
    ident = layer.identifier if layer else ""
    prev = chunk_notice._usd_write_active
    chunk_notice._usd_write_active = True
    try:
        attr = prim.GetAttribute(_EDIT_TARGET_MARKER)
        old_ident = attr.Get() if attr and attr.IsValid() else None
        home = chunk_utils.get_attr_home_layer(attr) if attr and attr.IsValid() else None
        target = home or chunk_utils.get_bookkeeping_layer(stage, chunk)
        with Usd.EditContext(stage, target):
            prim.CreateAttribute(_EDIT_TARGET_MARKER, Sdf.ValueTypeNames.String, custom=True).Set(ident)
    finally:
        chunk_notice._usd_write_active = prev
    # The marker this whole memo is a search for just moved, and the write above ran with
    # notices suppressed, so nothing else will drop it.
    invalidate_edit_layer_memo()
    # Only re-home downstream when the target actually changed. The Edit Target chunk
    # re-executes on every stage content change (its refresh callback), so reconciling
    # unconditionally here would run -- and thrash -- on every unrelated edit.
    # Or when the layer is one an asset brings in by arc and has only now become reachable:
    # the Payload or Reference bringing it in cooks upstream of this, so what is routed to
    # it was placed before it could be, with the marker unchanged since. Once, not on every
    # run -- reachable it stays, and the reconcile then has nothing to do.
    reachable = bool(layer is not None and not stage.HasLocalLayer(layer)
                     and chunk_utils.arc_edit_target(stage, layer) is not None)
    became_reachable = reachable and not getattr(chunk, "_arc_layer_reachable", False)
    chunk._arc_layer_reachable = reachable
    if old_ident != ident or became_reachable:
        # protect_root_layer while loading -- see _loading. This branch is taken on EVERY
        # open, because an anonymous layer's identifier is new in every process.
        reconcile_edit_targets(stage, _active_scene(), protect_root_layer=_loading)

publish_network ⚓︎

publish_network(group, path)

Write group's network to path and make group the host of that file.

The inverse of localise_network. After the write, the group prim references the file and its children's local specs are dropped from every owned layer, so the same chunks now compose in from the file and anything the shot does to them from here on is an override. The chunk objects are untouched: their prims still exist, composed rather than authored. The group prim's own bookkeeping (position, active view) stays local -- it is this graph's node.

Parameters:

Name Type Description Default
group ChunkBase

The chunkgroup to publish.

required
path str | Path

The file to write.

required
Source code in usd_chunks/chunk_stage.py
def publish_network(group: core.ChunkBase, path: str | Path) -> None:
    """Write group's network to path and make group the host of that file.

    The inverse of localise_network. After the write, the group prim references the file
    and its children's local specs are dropped from every owned layer, so the same chunks
    now compose in from the file and anything the shot does to them from here on is an
    override. The chunk objects are untouched: their prims still exist, composed rather than
    authored. The group prim's own bookkeeping (position, active view) stays local -- it is
    this graph's node.

    Args:
        group: The chunkgroup to publish.
        path: The file to write.
    """
    scene = _active_scene()
    stage = group.get_scene_stage()
    if not (scene and stage):
        return
    group_path = Sdf.Path(get_chunk_prim_path(group))
    target = export_network(scene, group, path)
    prev = chunk_notice._usd_write_active
    chunk_notice._usd_write_active = True
    try:
        with ChunkStageSync()._chunk_prim_edit_context(group):
            prim = stage.GetPrimAtPath(group_path)
            prim.GetReferences().SetReferences([Sdf.Reference(str(path), Sdf.Path(target))])
        for layer in _owned_layers(stage):
            spec = layer.GetPrimAtPath(group_path)
            if spec is None:
                continue
            for name in list(spec.nameChildren.keys()):
                del spec.nameChildren[name]
    finally:
        chunk_notice._usd_write_active = prev
    invalidate_edit_layer_memo()

push_chunk_values ⚓︎

push_chunk_values(stage, chunk)

Re-author every value chunk's params drive, e.g. a Light's inputs.

Needed after a chunk's layer comes back from being muted: USD refuses to author into a muted layer, so a value restored on load (or edited) while the chunk was gated off never landed, and the light would come back at its schema default.

Parameters:

Name Type Description Default
stage Stage

The stage to author on.

required
chunk ChunkBase

The chunk whose driven values to write.

required
Source code in usd_chunks/chunk_stage.py
def push_chunk_values(stage: Usd.Stage, chunk: core.ChunkBase) -> None:
    """Re-author every value chunk's params drive, e.g. a Light's inputs.

    Needed after a chunk's layer comes back from being muted: USD refuses to author into a
    muted layer, so a value restored on load (or edited) while the chunk was gated off
    never landed, and the light would come back at its schema default.

    Args:
        stage: The stage to author on.
        chunk: The chunk whose driven values to write.
    """
    for _, param in _iter_chunk_params(chunk):
        _push_driven_values(stage, param)
    for _, vector in _iter_chunk_vectors(chunk):
        _push_driven_values(stage, vector)

reached_by_graph_driver ⚓︎

reached_by_graph_driver(chunk, stage, scene)

Whether what drives chunk's graph reaches it, so that it is one the graph cooks.

The driver is graph_driver's. A graph with neither a view nor an Output is not view-driven at all (a script building one, a headless run), and everything in it cooks.

Parameters:

Name Type Description Default
chunk ChunkBase

The chunk.

required
stage Stage

The stage.

required
scene SceneSender

The scene.

required

Returns:

Type Description
bool

True if chunk is in its graph's cook set, or its graph is not view-driven.

Source code in usd_chunks/chunk_stage.py
def reached_by_graph_driver(
    chunk: core.ChunkBase, stage: Usd.Stage, scene: chunk_scene.SceneSender
) -> bool:
    """Whether what drives chunk's graph reaches it, so that it is one the graph cooks.

    The driver is graph_driver's. A graph with neither a view nor an Output is not
    view-driven at all (a script building one, a headless run), and everything in it cooks.

    Args:
        chunk: The chunk.
        stage: The stage.
        scene: The scene.

    Returns:
        True if chunk is in its graph's cook set, or its graph is not view-driven.
    """
    context = chunk.get_owner()
    while context is not None and not (
            isinstance(context, core.ChunkBase) and context.has_flag(ChunkFlags.GroupFlags.CONTEXT)):
        context = context.get_owner()
    views = [c for c in scene.get_chunks() if is_view_chunk(c) and is_node_in_context(c, context)]
    outputs = graph_outputs(stage, scene, context)
    if not views and not outputs:
        return True
    driver, _ = graph_driver(stage, scene, context)
    drivers = outputs if driver is None or is_output_chunk(driver) else [driver]
    return any(chunk in view_cook_list(d, stage, scene) for d in drivers)

reconcile_dag_dependencies ⚓︎

reconcile_dag_dependencies(chunk)

Make chunk's Python DAG dependencies match its live inputs:chunk connections.

The stage is the authority for chunk-level exec wiring: the node-graph UI's drag-to-connect authors inputs:chunk directly and never calls add_dependency(), so without this the Python DAG holds no edge at all for an interactively built graph and INPUT_CHANGED never fires between two chunks the user visibly wired together.

Adding the edge here also dirties the dependent, so an edge change propagates downstream exactly like a param change does.

Only chunk-level dependencies are touched. Param-level dependencies (added via the c_param.add_dependency(a_param) API) have no inputs:chunk counterpart and are left alone.

Parameters:

Name Type Description Default
chunk ChunkBase

The chunk whose inputs:chunk connections changed

required

Returns:

Name Type Description
bool bool

True if any dependency was added or removed

Source code in usd_chunks/chunk_stage.py
def reconcile_dag_dependencies(chunk: core.ChunkBase) -> bool:
    """Make chunk's Python DAG dependencies match its live inputs:chunk connections.

    The stage is the authority for chunk-level exec wiring: the node-graph UI's
    drag-to-connect authors inputs:chunk directly and never calls add_dependency(), so
    without this the Python DAG holds no edge at all for an interactively built graph and
    INPUT_CHANGED never fires between two chunks the user visibly wired together.

    Adding the edge here also dirties the dependent, so an edge change propagates downstream
    exactly like a param change does.

    Only chunk-level dependencies are touched. Param-level dependencies (added via the
    c_param.add_dependency(a_param) API) have no inputs:chunk counterpart and are left alone.

    Args:
        chunk (core.ChunkBase): The chunk whose inputs:chunk connections changed

    Returns:
        bool: True if any dependency was added or removed
    """
    live = _wired_dependencies(chunk)
    current = [dep for _, dep in chunk.get_dependencies() if isinstance(dep, core.ChunkBase)]

    live_ids = {id(dep) for dep in live}
    current_ids = {id(dep) for dep in current}

    changed = False
    for dep in current:
        if id(dep) not in live_ids:
            changed = chunk.remove_dependency(dep) or changed
    for dep in live:
        if id(dep) in current_ids:
            continue
        if _would_cycle(chunk, dep):
            logger.debug(
                "Skipping dependency %s -> %s: it would close a cycle, leaving the wire to "
                "settle as it does today", dep.name, chunk.name,
            )
            continue
        chunk.add_dependency(dep)
        changed = True
    return changed

reconcile_edit_targets ⚓︎

reconcile_edit_targets(stage, scene, roots=None, cook=True, protect_root_layer=False)

Move every chunk's bookkeeping to the Edit Target resolved for its exec-chain position.

For each regular (non-CONTEXT) chunk whose effective edit layer (_reconcile_destination) no longer matches where its bookkeeping prim lives, move the prim spec there and re-execute it so ChunkLayerManager.get_chunk_layer re-nests the chunk's driven content under the new target too (its graph layer reparents -- see chunk_registry.get_chunk_layer). A chunk already homed correctly moves nothing and is NOT re-executed, so on the common paths (creation authors bookkeeping into the right layer up front via _new_chunk_bookkeeping_layer) this is a cheap no-op and never oscillates. It does real work only when a target actually changes -- which is exactly when publish_edit_target gates its call on the marker having changed.

Idempotent, so safe after any structural change (attach/detach/delete of an exec wire, or an Edit Target changing its layer). CONTEXT chunks (Tab containers, groups) are structural scaffolding pinned to the session layer, not content, so they are left alone.

Parameters:

Name Type Description Default
stage Stage

The stage.

required
scene SceneSender

The scene.

required
roots list[ChunkBase] | None

Narrows the pass to those chunks and everything downstream of them. A change at one place in the graph can only move the target of chunks at or below it, so a caller that knows where the change happened (wiring an edge, an Edit Target picking a new layer) can say so and skip the rest. None visits the whole scene, which is what a load or a delete -- where the change is not localised to one chunk -- still wants. This matters because the pass is O(chunks) and every wire fires one: on a graph of any size, visiting the whole scene per edge would make building it quadratic.

None
cook bool

False migrates without re-running anything, for the one caller that is about to cook the whole graph anyway: loading. There the re-run is not just redundant but quadratic -- each migration would cascade a solve over everything downstream of it, once per chunk.

True
protect_root_layer bool

Never delete specs from the stage's root layer while migrating, so opening a file cannot empty the file's own layer.

False
Source code in usd_chunks/chunk_stage.py
def reconcile_edit_targets(
    stage: Usd.Stage,
    scene: chunk_scene.SceneSender,
    roots: list[core.ChunkBase] | None = None,
    cook: bool = True,
    protect_root_layer: bool = False,
) -> None:
    """Move every chunk's bookkeeping to the Edit Target resolved for its exec-chain position.

    For each regular (non-CONTEXT) chunk whose effective edit layer
    (_reconcile_destination) no longer matches where its bookkeeping prim lives, move
    the prim spec there and re-execute it so ChunkLayerManager.get_chunk_layer re-nests the
    chunk's driven content under the new target too (its graph layer reparents -- see
    chunk_registry.get_chunk_layer). A chunk already homed correctly moves nothing and is
    NOT re-executed, so on the common paths (creation authors bookkeeping into the right
    layer up front via _new_chunk_bookkeeping_layer) this is a cheap no-op and never
    oscillates. It does real work only when a target actually changes -- which is exactly
    when publish_edit_target gates its call on the marker having changed.

    Idempotent, so safe after any structural change (attach/detach/delete of an exec wire,
    or an Edit Target changing its layer). CONTEXT chunks (Tab containers, groups) are
    structural scaffolding pinned to the session layer, not content, so they are left alone.

    Args:
        stage: The stage.
        scene: The scene.
        roots: Narrows the pass to those chunks and everything downstream of them. A change
            at one place in the graph can only move the target of chunks at or below it, so
            a caller that knows where the change happened (wiring an edge, an Edit Target
            picking a new layer) can say so and skip the rest. None visits the whole scene,
            which is what a load or a delete -- where the change is not localised to one
            chunk -- still wants. This matters because the pass is O(chunks) and every wire
            fires one: on a graph of any size, visiting the whole scene per edge would make
            building it quadratic.
        cook: False migrates without re-running anything, for the one caller that is about
            to cook the whole graph anyway: loading. There the re-run is not just redundant
            but quadratic -- each migration would cascade a solve over everything downstream
            of it, once per chunk.
        protect_root_layer: Never delete specs from the stage's root layer while migrating,
            so opening a file cannot empty the file's own layer.
    """
    global _reconciling
    if _reconciling or not (stage and scene):
        return
    _reconciling = True
    try:
        affected = _chunks_downstream_of(roots) if roots is not None else None
        migratable = _migratable_layers(stage)
        if protect_root_layer:
            # Opening a file must not rewrite it. _migrate_chunk_bookkeeping moves a spec by
            # DELETING the original, and on a freshly opened file the original lives in that
            # file's own root layer -- so a load re-homing anything gutted the layer it had
            # just read. Sdf caches layers per process, so the emptied layer is what the next
            # Usd.Stage.Open of the same path gets: loading a network twice in one process
            # restored only the context the second time, while the file on disk stayed
            # correct. Excluding just the root layer keeps re-homing between the session and
            # anon layers, which is what settles the graph during a load.
            root = stage.GetRootLayer()
            migratable = [layer for layer in migratable if layer != root]
        for chunk in scene.get_chunks():
            if affected is not None and id(chunk) not in affected:
                continue
            if chunk.has_flag(ChunkFlags.GroupFlags.CONTEXT):
                continue
            prim_path = get_chunk_prim_path(chunk)
            prim = stage.GetPrimAtPath(Sdf.Path(prim_path))
            if not prim.IsValid():
                continue
            # A chunk composed in from a sequence file keeps its overrides in the host's
            # edit target (chunk_utils.host_edit_layer), not down its own -- the
            # sequence's -- Edit Target chain, so there is nothing of its to re-home.
            # Migrating would have carried a shot's override out of the shot file.
            if chunk_utils.is_composed_in(prim):
                continue
            if cook and _arc_cook_target_stale(stage, chunk, prim):
                # Its bookkeeping stays put (_reconcile_destination), so the move below never
                # re-runs it -- re-run here, so its cook re-nests in the arc layer.
                chunk.execute()
                migratable = _migratable_layers(stage)
                if protect_root_layer:
                    migratable = [layer for layer in migratable if layer != stage.GetRootLayer()]
            dst = _reconcile_destination(stage, chunk, prim)
            if dst is None:
                continue
            # Migration only moves opinions between layers, never changes what they
            # compose to, so the pass keeps the answers it has computed instead of
            # dropping them at the first move and re-walking the whole chain above the
            # chunk after it. The re-run below is outside the freeze -- that one can
            # author anything.
            with freeze_edit_layer_memo():
                moved = _migrate_chunk_bookkeeping(stage, prim_path, dst, migratable)
            if moved and cook:
                # The chunk moved layers -- re-run it so its driven content re-nests
                # under the new target (bookkeeping is hand-moved above; driven
                # content follows via ChunkLayerManager on execute).
                chunk.execute()
                # A cook can create and sublayer this chunk's procedural layer, so the
                # migratable set is stale from here on.
                migratable = _migratable_layers(stage)
                if protect_root_layer:
                    migratable = [layer for layer in migratable if layer != stage.GetRootLayer()]
    finally:
        _reconciling = False

recook_focus ⚓︎

recook_focus(stage, scene, context, view_chunk)

Establish the GLOBAL stage for the tab/graph the user is looking at.

The stage is shared by every context, but only the focused one should drive it. Root (context is None) is already a full global establish -- recook_for_view(None) touches every chunk and recurses into all groups. But a GROUP focus only manages its own children, so the parent tab's active view (and sibling groups) would stay unmuted and bleed through ("switch tabs, still see the previous view"). So when focusing a group, first mute + block everything OUTSIDE the group's subtree, then recook inside it -- leaving only the group's inner active view driving the stage.

Parameters:

Name Type Description Default
stage Stage

The stage.

required
scene SceneSender

The scene.

required
context ChunkBase | None

The focused context, or None for the top level.

required
view_chunk ChunkBase | None

The focused context's active view, or None.

required
Source code in usd_chunks/chunk_stage.py
def recook_focus(
    stage: Usd.Stage,
    scene: chunk_scene.SceneSender,
    context: core.ChunkBase | None,
    view_chunk: core.ChunkBase | None,
) -> None:
    """Establish the GLOBAL stage for the tab/graph the user is looking at.

    The stage is shared by every context, but only the focused one should drive it. Root
    (context is None) is already a full global establish -- recook_for_view(None) touches
    every chunk and recurses into all groups. But a GROUP focus only manages its own
    children, so the parent tab's active view (and sibling groups) would stay unmuted and
    bleed through ("switch tabs, still see the previous view"). So when focusing a group,
    first mute + block everything OUTSIDE the group's subtree, then recook inside it --
    leaving only the group's inner active view driving the stage.

    Args:
        stage: The stage.
        scene: The scene.
        context: The focused context, or None for the top level.
        view_chunk: The focused context's active view, or None.
    """
    # Its muting is a recook's too: while a chunk waits on a long job, it waits as well.
    if chunk_cook.hold_back(("recook_focus",), lambda: recook_focus(stage, scene, context, view_chunk)):
        return
    if context is not None:
        lm = chunk_registry.ChunkLayerManager()
        group_path = get_chunk_prim_path(context)
        inside_prefix = group_path + "/"
        # A focused group's own UPSTREAM must stay composed. The group's inner chunks
        # author on top of that content -- BindMaterial inside AMD MaterialX Library
        # binds a material onto a mesh that a Sublayer several nodes upstream is what
        # brings onto the stage at all. Muting it (as this loop otherwise does for
        # everything outside the group) means those inner chunks execute against a stage
        # where their target prims simply don't exist, so they author nothing -- and
        # since a chunk's execute() Clear()s its own layer first, whatever it authored
        # last time is destroyed in the process, and nothing re-executes it on the way
        # back out once its params haven't changed.
        #
        # Muting the group's upstream is not the point of this pass anyway -- it
        # exists to stop the parent tab's active view and UNRELATED sibling branches
        # bleeding through, and the group's own upstream is neither.
        # Every ANCESTOR's upstream, not just the focused group's. A group nested inside
        # another is fed by its parent's chain: focusing it, the parent's own upstream --
        # the Sublayer bringing the scene onto the stage two levels up -- must stay in this
        # set, or the inner chunks cook against a stage their targets are not on.
        upstream_keep: set = set()
        by_path = {get_chunk_prim_path(c): c for c in scene.get_chunks()}
        node: core.ChunkBase | None = context
        seen_ancestors: set = set()
        while node is not None:
            node_path = get_chunk_prim_path(node)
            if node_path in seen_ancestors:
                break  # a cycle would hang the focus; prim nesting should prevent it
            seen_ancestors.add(node_path)
            upstream_keep.update(
                get_chunk_prim_path(u) for u in view_cook_list(node, stage, scene)
            )
            parent_path = str(Sdf.Path(node_path).GetParentPath())
            node = by_path.get(parent_path)
        # An upstream GROUP authors nothing of its own -- all of its content lives in its
        # children's layers -- so keeping only the group's own (empty) layer keeps nothing at
        # all: with chunkgroup A -> chunkgroup B, diving into B would drop A's prims from
        # the stage, so B's inner chunks would cook against a stage their input isn't on.
        # A data wire hides this, because lofting/connecting the group's Description
        # authors a connection from the group prim DOWN to an inner chunk, which puts those
        # inner chunks into view_cook_list's node-level answer.
        keep_prefixes = tuple(u + "/" for u in upstream_keep)
        for c in scene.get_chunks():
            if is_terminal_chunk(c):
                continue
            cp = get_chunk_prim_path(c)
            # Keep the focused group itself and its descendants -- recook_for_view handles those.
            if cp == group_path or cp.startswith(inside_prefix):
                continue
            if cp in upstream_keep or (keep_prefixes and cp.startswith(keep_prefixes)):
                # Leave an upstream group's internals exactly as the parent context's cook
                # left them: whichever of its children that cook muted (outside the group's
                # own active view) stay muted, and the ones driving its output stay composed.
                continue
            # NEVER block a context/container (a tab or group). is_blocked() climbs the owner
            # chain, so blocking the focused group's ANCESTOR would propagate down and block the
            # focused inner tree itself -- nothing would cook. Container chunks author nothing of
            # their own; their leaf children are muted individually by this same loop.
            if c.has_flag(ChunkFlags.GroupFlags.CONTEXT):
                continue
            c.set_blocked(True)
            layer = lm.get_layer(c)
            if layer is not None:
                stage.MuteLayer(layer.identifier)
    recook_for_view(stage, scene, context, view_chunk)

recook_for_view ⚓︎

recook_for_view(stage, scene, context, view_chunk, _synthetic_tail=False, _force=False, _hidden=False)

Apply view-driven execution for one context.

With a view_chunk: reveal only its upstream tree (roots-first); every other non-view chunk in the context is blocked + muted (dormant, hidden). With view_chunk=None (no active view) the context cooks to its Output: a view is for looking, the Output is what the graph delivers. With neither, block + mute everything -- nothing cooks.

Blocking a chunk both hides its result (its layer is muted) and stops it reacting to param changes (see ChunkBase.value_changed) -- so being outside the active view's tree means "does not execute", live.

Of the revealed tree, only the chunks that are stale (chunk_cook.is_cook_stale) cook. Muting keeps a layer's content, so a chunk that already cooked on its current inputs comes back with that result, and running it again would redo the same work -- for an import that parses a mesh file, on every view switch and every wire. A chunk that cooks reaches everything downstream of it through the DAG while those are still muted, which marks them stale in turn, so a change upstream still recooks the whole chain below it.

Parameters:

Name Type Description Default
stage Stage

The stage.

required
scene SceneSender

The scene.

required
context ChunkBase | None

The context to recook, or None for the top level.

required
view_chunk ChunkBase | None

The active view, or None for none.

required
_synthetic_tail bool

True when view_chunk is a stand-in exec tail rather than a real view chunk (see the is_group_chunk branch). Real view chunks are markers excluded from their own cook_list by view_cook_list, but a synthetic tail is real content that must cook too, so it's appended back in rather than excluded.

False
_force bool

Cook every revealed chunk, stale or not. Set for the inside of a group that is itself stale: a change reached the group, and its inner chunks read what it brings in.

False
_hidden bool

The context is outside its parent's cook set, so it cooks nothing at all, Output or not.

False

A chunk whose cook fails does not stop the pass halfway, with the chunks below it still muted: nothing below it cooks (chunk_cook.cook_pass), the rest of the pass runs and shows their last results, and the first error is raised once it is done. While a chunk waits on a long job (chunk_cook.hold) the recook waits too, and runs after it; inside a change_block, once the block has ended and cooked.

Source code in usd_chunks/chunk_stage.py
def recook_for_view(
    stage: Usd.Stage,
    scene: chunk_scene.SceneSender,
    context: core.ChunkBase | None,
    view_chunk: core.ChunkBase | None,
    _synthetic_tail: bool = False,
    _force: bool = False,
    _hidden: bool = False,
) -> None:
    """Apply view-driven execution for one context.

    With a view_chunk: reveal only its upstream tree (roots-first); every other non-view
    chunk in the context is blocked + muted (dormant, hidden). With view_chunk=None (no active
    view) the context cooks to its Output: a view is for looking, the Output is what the
    graph delivers. With neither, block + mute everything -- nothing cooks.

    Blocking a chunk both hides its result (its layer is muted) and stops it reacting to
    param changes (see ChunkBase.value_changed) -- so being outside the active view's tree
    means "does not execute", live.

    Of the revealed tree, only the chunks that are stale (chunk_cook.is_cook_stale) cook.
    Muting keeps a layer's content, so a chunk that already cooked on its current inputs
    comes back with that result, and running it again would redo the same work -- for an
    import that parses a mesh file, on every view switch and every wire. A chunk that cooks
    reaches everything downstream of it through the DAG while those are still muted, which
    marks them stale in turn, so a change upstream still recooks the whole chain below it.

    Args:
        stage: The stage.
        scene: The scene.
        context: The context to recook, or None for the top level.
        view_chunk: The active view, or None for none.
        _synthetic_tail: True when view_chunk is a stand-in exec tail rather than a real
            view chunk (see the is_group_chunk branch). Real view chunks are markers excluded
            from their own cook_list by view_cook_list, but a synthetic tail is real content
            that must cook too, so it's appended back in rather than excluded.
        _force: Cook every revealed chunk, stale or not. Set for the inside of a group
            that is itself stale: a change reached the group, and its inner chunks read
            what it brings in.
        _hidden: The context is outside its parent's cook set, so it cooks nothing at all,
            Output or not.

    A chunk whose cook fails does not stop the pass halfway, with the chunks below it
    still muted: nothing below it cooks (chunk_cook.cook_pass), the rest of the pass runs
    and shows their last results, and the first error is raised once it is done. While a
    chunk waits on a long job (chunk_cook.hold) the recook waits too, and runs after it;
    inside a change_block, once the block has ended and cooked.
    """
    key = ("recook_for_view", id(context), _hidden)

    def later():
        recook_for_view(stage, scene, context, view_chunk, _synthetic_tail, _force, _hidden)
    if chunk_cook.hold_back(key, later) or chunk_cook.after_batch(key, later):
        return
    errors: list = []
    with chunk_cook.cook_pass():
        _recook_pass(stage, scene, context, view_chunk, _synthetic_tail, _force, _hidden, errors)
    if errors:
        raise errors[0]

remove_prim_specs ⚓︎

remove_prim_specs(layer, paths)

Remove the prim specs at paths from layer, with what is under them, in place.

Source code in usd_chunks/chunk_stage.py
def remove_prim_specs(layer: Sdf.Layer, paths) -> None:
    """Remove the prim specs at paths from layer, with what is under them, in place."""
    for path in sorted(paths, key=lambda p: p.pathElementCount):
        spec = layer.GetPrimAtPath(path)
        if not spec:
            continue
        parent = spec.nameParent or layer.pseudoRoot
        del parent.nameChildren[spec.name]

rename_context_prim_path ⚓︎

rename_context_prim_path(context, new_prim_path)

Move all chunk prims in context to a new root using Sdf.CopySpec, then remove the old specs.

Source code in usd_chunks/chunk_stage.py
def rename_context_prim_path(context: core.ChunkBase, new_prim_path: str | None) -> None:
    """Move all chunk prims in context to a new root using Sdf.CopySpec, then remove the old specs."""
    sync = ChunkStageSync()
    if not sync.initialized or not sync._stage:
        context.prim_path = new_prim_path
        return

    old_root = context.prim_path if context.prim_path else _CHUNKS_ROOT
    new_root = new_prim_path if new_prim_path else _CHUNKS_ROOT

    if old_root == new_root:
        context.prim_path = new_prim_path
        return

    stage = sync._stage
    chunk_objs = [c for c in context.get_my_params() if isinstance(c, core.ChunkBase)]

    # Use prim.GetPrimStack() to find the exact layers authoring each chunk prim,
    # rather than scanning GetLayerStack() which may not find anonymous sublayers.
    layer_chunks: dict = {}  # layer → [chunk_obj, ...]
    for chunk_obj in chunk_objs:
        prim = stage.GetPrimAtPath(Sdf.Path(f"{old_root}/{chunk_obj.name}"))
        if not (prim and prim.IsValid()):
            continue
        for spec in prim.GetPrimStack():
            layer_chunks.setdefault(spec.layer, []).append(chunk_obj)

    if not layer_chunks:
        context.prim_path = new_prim_path
        return

    old_write = chunk_notice._usd_write_active
    chunk_notice._usd_write_active = True
    try:
        for layer, to_copy in layer_chunks.items():
            with Sdf.ChangeBlock():
                # Ensure the new root container prim exists in this layer
                new_root_sdf = Sdf.Path(new_root)
                if not layer.GetPrimAtPath(new_root_sdf):
                    root_spec = Sdf.CreatePrimInLayer(layer, new_root_sdf)
                    root_spec.typeName = _CHUNK_PRIM_TYPENAME
                    root_spec.specifier = Sdf.SpecifierDef

                for chunk_obj in to_copy:
                    old_path = Sdf.Path(f"{old_root}/{chunk_obj.name}")
                    new_path = Sdf.Path(f"{new_root}/{chunk_obj.name}")
                    if layer.GetPrimAtPath(old_path):
                        Sdf.CopySpec(layer, old_path, layer, new_path)

                # Fix inputs:chunk connection paths in the copied specs
                for chunk_obj in to_copy:
                    new_path = Sdf.Path(f"{new_root}/{chunk_obj.name}")
                    new_spec = layer.GetPrimAtPath(new_path)
                    if not new_spec or _EXEC_INPUT not in new_spec.attributes:
                        continue
                    exec_attr_spec = new_spec.attributes[_EXEC_INPUT]
                    updated = [
                        Sdf.Path(new_root + str(conn)[len(old_root):])
                        if str(conn).startswith(old_root + "/") else conn
                        for conn in exec_attr_spec.connectionPathList.explicitItems
                    ]
                    exec_attr_spec.connectionPathList.explicitItems = updated

                # Remove old chunk specs
                for chunk_obj in to_copy:
                    old_path = Sdf.Path(f"{old_root}/{chunk_obj.name}")
                    old_spec = layer.GetPrimAtPath(old_path)
                    if not old_spec:
                        continue
                    parent_path = old_path.GetParentPath()
                    parent_spec = layer.GetPrimAtPath(parent_path) or layer.pseudoRoot
                    if old_path.name in parent_spec.nameChildren:
                        del parent_spec.nameChildren[old_path.name]

                # Remove the old root container prim if now empty
                old_root_spec = layer.GetPrimAtPath(Sdf.Path(old_root))
                if old_root_spec and not list(old_root_spec.nameChildren):
                    old_root_path = Sdf.Path(old_root)
                    old_root_parent = layer.GetPrimAtPath(old_root_path.GetParentPath()) or layer.pseudoRoot
                    if old_root_path.name in old_root_parent.nameChildren:
                        del old_root_parent.nameChildren[old_root_path.name]
    finally:
        chunk_notice._usd_write_active = old_write

    # Update path tracking in the sync singleton
    for chunk_obj in chunk_objs:
        old_tracked = f"{old_root}/{chunk_obj.name}"
        new_tracked = f"{new_root}/{chunk_obj.name}"
        sync._loaded_prim_paths.discard(old_tracked)
        sync._loaded_prim_paths.add(new_tracked)
        if sync._chunk_prim_paths.get(id(chunk_obj)) == old_tracked:
            sync._chunk_prim_paths.track(chunk_obj, new_tracked)

    context.prim_path = new_prim_path

    # Re-wire param attribute listeners to the new prim attributes
    for chunk_obj in chunk_objs:
        prim = stage.GetPrimAtPath(Sdf.Path(f"{new_root}/{chunk_obj.name}"))
        if prim and prim.IsValid():
            _load_wire_inputs(prim, chunk_obj)

restore_edit_target_selections ⚓︎

restore_edit_target_selections(stage, scene, saved=None)

After a load, re-apply each Edit Target chunk's stored selection.

A chunk.Menu rejects a value not in its menu_items, and on load the stored selection ("shot") is restored before the anon layer it names is recreated by the upstream Create Layer chunk -- so the Menu silently drops it and keeps the default ("Session Layer"). By the time the whole graph has loaded, every Layer chunk has run, so the layers (and therefore the menu items) exist; re-applying the stored value here restores the selection. The resulting value change re-publishes the marker and reconciles downstream via the normal path.

Runs strictly post-load -- NOT from the refresh callback mid-load -- so a chain of Edit Targets settles deterministically. Applied UPSTREAM-FIRST: re-applying a downstream Edit Target before an upstream one leaves the upstream still on its (rejected) default while the downstream's execute/reconcile cascade runs, which corrupts the upstream's selection. Ordering by how many Edit Targets sit upstream keeps each chain settling from its root out.

Parameters:

Name Type Description Default
stage Stage

The loaded stage.

required
scene SceneSender

The scene.

required
saved dict[str, str] | None

The pre-load snapshot from snapshot_edit_target_selections, and the only trustworthy source for these values: the Menu's rejection does not merely drop the value in memory, it writes the default back to USD, so a selection whose layer didn't exist yet at the moment its chunk was rebuilt is already gone from the stage by the time this runs. None falls back to reading the stage, which still covers any selection that happened to survive load.

None
Source code in usd_chunks/chunk_stage.py
def restore_edit_target_selections(
    stage: Usd.Stage, scene: chunk_scene.SceneSender, saved: dict[str, str] | None = None
) -> None:
    """After a load, re-apply each Edit Target chunk's stored selection.

    A chunk.Menu rejects a value not in its menu_items, and on load the stored selection
    ("shot") is restored before the anon layer it names is recreated by the upstream Create
    Layer chunk -- so the Menu silently drops it and keeps the default ("Session Layer"). By
    the time the whole graph has loaded, every Layer chunk has run, so the layers (and
    therefore the menu items) exist; re-applying the stored value here restores the selection.
    The resulting value change re-publishes the marker and reconciles downstream via the
    normal path.

    Runs strictly post-load -- NOT from the refresh callback mid-load -- so a chain of Edit
    Targets settles deterministically. Applied UPSTREAM-FIRST: re-applying a downstream Edit
    Target before an upstream one leaves the upstream still on its (rejected) default while
    the downstream's execute/reconcile cascade runs, which corrupts the upstream's selection.
    Ordering by how many Edit Targets sit upstream keeps each chain settling from its root out.

    Args:
        stage: The loaded stage.
        scene: The scene.
        saved: The pre-load snapshot from snapshot_edit_target_selections, and the only
            trustworthy source for these values: the Menu's rejection does not merely drop
            the value in memory, it writes the default back to USD, so a selection whose
            layer didn't exist yet at the moment its chunk was rebuilt is already gone from
            the stage by the time this runs. None falls back to reading the stage, which
            still covers any selection that happened to survive load.
    """
    if not (stage and scene):
        return
    edit_targets = [c for c in scene.get_chunks() if is_edit_target_chunk(c)]
    if not edit_targets:
        return
    et_paths = {get_chunk_prim_path(c) for c in edit_targets}

    def _upstream_et_count(chunk) -> int:
        start = Sdf.Path(get_chunk_prim_path(chunk))
        return sum(
            1 for path, _p, _unbranched in _iter_exec_upstream(stage, start)
            if str(path) in et_paths
        )

    # Resolve each stored selection BEFORE applying any of them. Applying one target's value
    # triggers an execute/reconcile cascade that can overwrite a *different* target's stored
    # inputs:edit_target attr, so re-reading per-iteration would pick up a corrupted value.
    # Resolve first, then apply.
    snapshot = []
    for chunk in edit_targets:
        prim_path = get_chunk_prim_path(chunk)
        prim = stage.GetPrimAtPath(Sdf.Path(prim_path))
        if not prim.IsValid():
            continue
        stored = (saved or {}).get(prim_path)
        if not stored:
            attr = prim.GetAttribute("inputs:edit_target")
            stored = attr.Get() if (attr and attr.IsValid()) else None
        param = chunk.get_param("edit_target")
        if param is not None and stored:
            snapshot.append((chunk, param, stored))

    # Apply upstream-first: each set's own publish_edit_target reconcile re-homes the
    # downstream part of the chain before the next (more-downstream) selection is applied,
    # so every target settles against an already-correct upstream.
    for chunk, param, stored in sorted(snapshot, key=lambda t: _upstream_et_count(t[0])):
        # Only re-apply once the stored selection is actually a valid menu item now (its
        # layer exists); a genuinely missing layer is left at whatever the Menu settled on.
        if param.value != stored and stored in getattr(param, "menu_items", []):
            param.value = stored

revert_param_override ⚓︎

revert_param_override(param)

Drop the shot's opinion on this param so the composed-in value shows through again.

Every owned-layer spec for the storage attr goes (an override can have been written under more than one edit target over its life); the param is then set to what now composes, which the write path sees as already authored and leaves alone.

Parameters:

Name Type Description Default
param ChunkParamBase

The param to revert.

required
Source code in usd_chunks/chunk_stage.py
def revert_param_override(param: core.ChunkParamBase) -> None:
    """Drop the shot's opinion on this param so the composed-in value shows through again.

    Every owned-layer spec for the storage attr goes (an override can have been written
    under more than one edit target over its life); the param is then set to what now
    composes, which the write path sees as already authored and leaves alone.

    Args:
        param: The param to revert.
    """
    attr = _storage_attr(param)
    if attr is None or param_override_source(param) is None:
        return
    _drop_specs(attr, [spec.layer for spec in _owned_specs(attr)])
    param.value = attr.Get()

save_scene ⚓︎

save_scene(scene, chunkgroup_path)

Save the scene: the same file export_chunks writes, under the name the Save Scene menu uses.

Only chunk prims are written. Reopening regenerates everything a chunk is responsible for by re-running it, so content that is not reproduced by re-execution needs an explicit re-run after reload -- a bake, the same as Houdini's File Cache.

Parameters:

Name Type Description Default
scene SceneSender

The scene to save.

required
chunkgroup_path str | Path

Where the chunk graph is written -- the file to reopen.

required
Source code in usd_chunks/chunk_stage.py
def save_scene(scene: chunk_scene.SceneSender, chunkgroup_path: str | Path) -> None:
    """Save the scene: the same file export_chunks writes, under the name the Save Scene menu uses.

    Only chunk prims are written. Reopening regenerates everything a chunk is responsible
    for by re-running it, so content that is not reproduced by re-execution needs an
    explicit re-run after reload -- a bake, the same as Houdini's File Cache.

    Args:
        scene: The scene to save.
        chunkgroup_path: Where the chunk graph is written -- the file to reopen.
    """
    export_chunks(scene, Path(chunkgroup_path))

saved_layer ⚓︎

saved_layer(scene, path, relative_paths=None)

The in-memory layer export_chunks writes to path, built and not written.

The chunk prims, their asset paths fitted to path's folder, and the stage's up-axis and units stamped. Building it changes nothing on the stage or in any of its layers, so autosave writes a quick save from it without the side effects of a save (laying out scripted nodes, reloading the file's cached layer, storing the open cache).

Parameters:

Name Type Description Default
scene SceneSender

The scene, which must have a stage.

required
path str | Path

The file the layer is meant for.

required
relative_paths bool | None

As for export_chunks.

None
Source code in usd_chunks/chunk_stage.py
def saved_layer(
    scene: chunk_scene.SceneSender, path: str | Path, relative_paths: bool | None = None,
) -> Sdf.Layer:
    """The in-memory layer export_chunks writes to path, built and not written.

    The chunk prims, their asset paths fitted to path's folder, and the stage's up-axis and
    units stamped. Building it changes nothing on the stage or in any of its layers, so
    autosave writes a quick save from it without the side effects of a save (laying out
    scripted nodes, reloading the file's cached layer, storing the open cache).

    Args:
        scene: The scene, which must have a stage.
        path: The file the layer is meant for.
        relative_paths: As for export_chunks.
    """
    stage = scene.get_stage()
    dst = _export_layer(scene, Path(path))
    if relative_paths is None:
        relative_paths = asset_paths.relative_paths_on(scene)
    asset_paths.rebase_saved(dst, scene, str(Path(path).resolve().parent), relative_paths)
    stamp_stage_metadata(dst, stage)
    return dst

sdf_type_for_param ⚓︎

sdf_type_for_param(param)

The USD type an attribute backing this param should have, or None if unmappable.

Typed from the param's DEFAULT rather than whatever it currently holds. A live value can be an unresolved expression string, or something that arrived over a wire, and an attribute's type is fixed for good once it is created -- so typing from the value in hand risks pinning a float param to String and failing every numeric write afterwards. The default is the one value that always reflects what the param actually is.

Parameters:

Name Type Description Default
param

The param.

required

Returns:

Type Description
ValueTypeName | None

The Sdf value type name, or None.

Source code in usd_chunks/chunk_stage.py
def sdf_type_for_param(param) -> Sdf.ValueTypeName | None:
    """The USD type an attribute backing this param should have, or None if unmappable.

    Typed from the param's DEFAULT rather than whatever it currently holds. A live value
    can be an unresolved expression string, or something that arrived over a wire, and an
    attribute's type is fixed for good once it is created -- so typing from the value in
    hand risks pinning a float param to String and failing every numeric write afterwards.
    The default is the one value that always reflects what the param actually is.

    Args:
        param: The param.

    Returns:
        The Sdf value type name, or None.
    """
    if param is None:
        return None
    try:
        if ChunkFlags.ParamType.COLOR_PICKER in param.evaluate_type():
            # A ColorPicker holds an (r, g, b) tuple; _SDF_TYPE_MAP is keyed by Python type
            # and has no tuple entry, so it needs saying explicitly.
            return Sdf.ValueTypeNames.Color3f
    except Exception:
        pass
    type_source = getattr(param, "default_value", None)
    if type_source is None:
        type_source = getattr(param, "raw_value", None)
    sdf_type, _ = _sdf_type_and_value(type_source)
    return sdf_type

search_chunks ⚓︎

search_chunks(chunks, query, scope='both')

The chunks a search finds: the ones whose text holds query, else the ones a typo away.

Typos only count when nothing holds the text, so "Mesh1" finds Mesh1 and not Mesh.

Parameters:

Name Type Description Default
chunks list

The chunks to search.

required
query str

The search text; an empty query matches every chunk.

required
scope str

"both", "name" or "type".

'both'

Returns:

Type Description
list

The matching chunks, in their order.

Source code in usd_chunks/chunk_stage.py
def search_chunks(chunks: list, query: str, scope: str = "both") -> list:
    """The chunks a search finds: the ones whose text holds query, else the ones a typo away.

    Typos only count when nothing holds the text, so "Mesh1" finds Mesh1 and not Mesh.

    Args:
        chunks: The chunks to search.
        query: The search text; an empty query matches every chunk.
        scope: "both", "name" or "type".

    Returns:
        The matching chunks, in their order.
    """
    exact = [c for c in chunks if chunk_matches_search(c, query, scope, typos=False)]
    return exact or [c for c in chunks if chunk_matches_search(c, query, scope)]

set_chunk_lofted ⚓︎

set_chunk_lofted(chunk, lofted)

Loft chunk to its group's Params page, or take it back down.

Written as chunk:lofted on the chunk prim, as chunk-prim bookkeeping: an existing spec is updated where it lives (chunk_utils.get_attr_home_layer), else it goes to chunk_utils.get_bookkeeping_layer, so toggling never leaves an older, stronger opinion in one layer shadowing a newer one in another. An older file's chunk:pinned is replaced by it. Then chunk_lofted_hook is told.

Parameters:

Name Type Description Default
chunk ChunkBase

The chunk.

required
lofted bool

The new state.

required
Source code in usd_chunks/chunk_stage.py
def set_chunk_lofted(chunk: core.ChunkBase, lofted: bool) -> None:
    """Loft chunk to its group's Params page, or take it back down.

    Written as ``chunk:lofted`` on the chunk prim, as chunk-prim bookkeeping: an existing
    spec is updated where it lives (chunk_utils.get_attr_home_layer), else it goes to
    chunk_utils.get_bookkeeping_layer, so toggling never leaves an older, stronger opinion
    in one layer shadowing a newer one in another. An older file's ``chunk:pinned`` is
    replaced by it. Then chunk_lofted_hook is told.

    Args:
        chunk: The chunk.
        lofted: The new state.
    """
    if _write_chunk_lofted(chunk, lofted) and chunk_lofted_hook is not None:
        chunk_lofted_hook(chunk, lofted)

set_chunks_muted ⚓︎

set_chunks_muted(stage, to_mute, to_unmute)

Block and unblock many chunks, changing the stage's mute state ONCE.

Every stage.MuteLayer / UnmuteLayer is a composition change, and composition changes are reported to everything watching the stage as a resync of / -- the whole stage, re-read. One per chunk would make a single shot change in a shot-gated graph cost several full-stage resyncs, and far more on the first switch, each one telling Hydra that every prim it holds may have changed.

A live viewport is where that lands: the renderer repopulates again and again for one logical change, and the prim browser walks a stage that is being recomposed underneath it -- a renderer can even miss content entirely until it is switched away and back, which is simply a repopulate done once, cleanly.

MuteAndUnmuteLayers does both lists in one operation, so the stage recomposes once and watchers get one resync however many branches the gate moved.

Blocking is the engine's own lever, deliberately not the DISABLED state: DISABLED belongs to the user, who sets it by hand and expects it to stay. ChunkLayerManager guards the two against each other, so a blocked layer is never un-muted by the disable path.

Parameters:

Name Type Description Default
stage Stage

The stage whose layer mute state changes.

required
to_mute

Chunks to block and mute.

required
to_unmute

Chunks to unblock and unmute.

required

Returns:

Type Description
tuple[set, set]

tuple[set, set]: the chunks actually muted, and those actually un-muted

Source code in usd_chunks/chunk_stage.py
def set_chunks_muted(stage: Usd.Stage, to_mute, to_unmute) -> tuple[set, set]:
    """Block and unblock many chunks, changing the stage's mute state ONCE.

    Every stage.MuteLayer / UnmuteLayer is a composition change, and composition changes
    are reported to everything watching the stage as a resync of `/` -- the whole stage,
    re-read. One per chunk would make a single shot change in a shot-gated graph cost
    several full-stage resyncs, and far more on the first switch, each one telling Hydra
    that every prim it holds may have changed.

    A live viewport is where that lands: the renderer repopulates again and again for one
    logical change, and the prim browser walks a stage that is being recomposed underneath
    it -- a renderer can even miss content entirely until it is switched away and back,
    which is simply a repopulate done once, cleanly.

    MuteAndUnmuteLayers does both lists in one operation, so the stage recomposes once and
    watchers get one resync however many branches the gate moved.

    Blocking is the engine's own lever, deliberately not the DISABLED state: DISABLED
    belongs to the user, who sets it by hand and expects it to stay. ChunkLayerManager
    guards the two against each other, so a blocked layer is never un-muted by the disable
    path.

    Args:
        stage: The stage whose layer mute state changes.
        to_mute: Chunks to block and mute.
        to_unmute: Chunks to unblock and unmute.

    Returns:
        tuple[set, set]: the chunks actually muted, and those actually un-muted
    """
    manager = chunk_registry.ChunkLayerManager()
    muted, unmuted = set(), set()
    mute_ids, unmute_ids = [], []

    for target in to_mute:
        # Never a context: is_blocked() climbs the owner chain, so blocking a container
        # would block its whole subtree, including branches the caller meant to keep.
        # Containers author nothing of their own; their leaves come through here one by one.
        if target.has_flag(ChunkFlags.GroupFlags.CONTEXT):
            continue
        target.set_blocked(True)
        muted.add(target)
        if stage is not None and (layer := manager.get_layer(target)) is not None:
            if not stage.IsLayerMuted(layer.identifier):
                mute_ids.append(layer.identifier)

    for target in to_unmute:
        if target.has_flag(ChunkFlags.GroupFlags.CONTEXT):
            continue
        target.set_blocked(False)
        unmuted.add(target)
        if stage is not None and (layer := manager.get_layer(target)) is not None:
            if stage.IsLayerMuted(layer.identifier):
                unmute_ids.append(layer.identifier)

    if stage is not None and (mute_ids or unmute_ids):
        # Not layer.SetMuted: that recomposes lazily and expires prims, which is the
        # "chunk layers disappear" bug the rest of the codebase avoids the same way.
        stage.MuteAndUnmuteLayers(mute_ids, unmute_ids)

    # After the recomposition, never during: a chunk coming back needs its prim on the
    # stage before its values have anywhere to go (see push_chunk_values).
    for target in unmuted:
        if stage is not None:
            push_chunk_values(stage, target)

    return muted, unmuted

set_param_default_in ⚓︎

set_param_default_in(param, layer)

Write param's default into layer, over the value, wire or expression others set.

For after clear_param, when other layers still set the param: an opinion in layer hides theirs without touching them.

Parameters:

Name Type Description Default
param ChunkCommon

The param or vector.

required
layer Layer

The layer it was cleared in (ParamClear.layer).

required
Source code in usd_chunks/chunk_stage.py
def set_param_default_in(param: core.ChunkCommon, layer: Sdf.Layer) -> None:
    """Write param's default into layer, over the value, wire or expression others set.

    For after clear_param, when other layers still set the param: an opinion in layer hides
    theirs without touching them.

    Args:
        param: The param or vector.
        layer: The layer it was cleared in (ParamClear.layer).
    """
    attr = _storage_attr(param)
    if attr is None:
        return
    prev = chunk_notice._usd_write_active
    chunk_notice._usd_write_active = True
    try:
        with Usd.EditContext(attr.GetStage(), layer):
            attr = attr.GetPrim().CreateAttribute(attr.GetName(), attr.GetTypeName(), custom=False)
            attr.Set(chunk_utils.as_attr_value(attr, param.default_value))
            if attr.HasAuthoredConnections():
                attr.SetConnections([])
            if attr.GetTypeName() != Sdf.ValueTypeNames.String and chunk_utils.read_expression_text(attr):
                attr.SetCustomDataByKey(chunk_utils.EXPR_TEXT_KEY, "")
    finally:
        chunk_notice._usd_write_active = prev
    invalidate_edit_layer_memo()
    _rebind(param, attr)

set_search_query ⚓︎

set_search_query(context, query)

Persist context's Params-page search query as filter:searchQuery on its own prim.

Defines the prim on demand: a plain tab context's own prim is never authored by _define_prim (it is added with send_added=False, so PARAM_ADDED never fires for it), and only exists as an implicit ancestor once a child chunk is added under it.

Parameters:

Name Type Description Default
context ChunkBase

The context.

required
query str

The search text.

required
Source code in usd_chunks/chunk_stage.py
def set_search_query(context: core.ChunkBase, query: str) -> None:
    """Persist context's Params-page search query as ``filter:searchQuery`` on its own prim.

    Defines the prim on demand: a plain tab context's own prim is never authored by
    _define_prim (it is added with send_added=False, so PARAM_ADDED never fires for it), and
    only exists as an implicit ancestor once a child chunk is added under it.

    Args:
        context: The context.
        query: The search text.
    """
    stage = context.get_scene_stage()
    path = _context_own_prim_path(context)
    if not stage or not path:
        return
    prev_w = chunk_notice._usd_write_active
    chunk_notice._usd_write_active = True
    try:
        prim = stage.GetPrimAtPath(Sdf.Path(path))
        if not prim.IsValid():
            prim = stage.DefinePrim(Sdf.Path(path), _CHUNK_PRIM_TYPENAME)
        # An UPDATE goes where the attribute already lives; only a first write picks a
        # layer. An Edit Target chunk moves the stage's target while the graph is live, so
        # re-resolving it on every write scattered one attribute's opinions across layers
        # and let the older, stronger one go on winning -- the toggle stopped responding
        # mid-session while the widget went on reporting what was clicked.
        #
        # The first write deliberately still follows the ambient target rather than the
        # bookkeeping layer set_chunk_lofted uses. A tab's filter state is part of the
        # document and has to land somewhere that exports; the session layer does not.
        # Pinning both halves to one answer breaks one of them in each direction.
        existing = prim.GetAttribute("filter:searchQuery")
        home = chunk_utils.get_attr_home_layer(existing) if existing and existing.IsValid() else None
        ctx = Usd.EditContext(stage, home) if home else contextlib.nullcontext()
        with ctx:
            prim.CreateAttribute("filter:searchQuery", Sdf.ValueTypeNames.String, custom=True).Set(query)
    finally:
        chunk_notice._usd_write_active = prev_w

set_search_scope ⚓︎

set_search_scope(context, scope)

Persist context's search scope as filter:searchScope on its own prim.

Parameters:

Name Type Description Default
context ChunkBase

The context.

required
scope str

"both", "name" or "type"; anything else is stored as "both".

required
Source code in usd_chunks/chunk_stage.py
def set_search_scope(context: core.ChunkBase, scope: str) -> None:
    """Persist context's search scope as ``filter:searchScope`` on its own prim.

    Args:
        context: The context.
        scope: "both", "name" or "type"; anything else is stored as "both".
    """
    if scope not in _SEARCH_SCOPES:
        scope = "both"
    stage = context.get_scene_stage()
    path = _context_own_prim_path(context)
    if not stage or not path:
        return
    prev_w = chunk_notice._usd_write_active
    chunk_notice._usd_write_active = True
    try:
        prim = stage.GetPrimAtPath(Sdf.Path(path))
        if not prim.IsValid():
            prim = stage.DefinePrim(Sdf.Path(path), _CHUNK_PRIM_TYPENAME)
        # An UPDATE goes where the attribute already lives; only a first write picks a
        # layer. An Edit Target chunk moves the stage's target while the graph is live, so
        # re-resolving it on every write scattered one attribute's opinions across layers
        # and let the older, stronger one go on winning -- the toggle stopped responding
        # mid-session while the widget went on reporting what was clicked.
        #
        # The first write deliberately still follows the ambient target rather than the
        # bookkeeping layer set_chunk_lofted uses. A tab's filter state is part of the
        # document and has to land somewhere that exports; the session layer does not.
        # Pinning both halves to one answer breaks one of them in each direction.
        existing = prim.GetAttribute("filter:searchScope")
        home = chunk_utils.get_attr_home_layer(existing) if existing and existing.IsValid() else None
        ctx = Usd.EditContext(stage, home) if home else contextlib.nullcontext()
        with ctx:
            prim.CreateAttribute("filter:searchScope", Sdf.ValueTypeNames.String, custom=True).Set(scope)
    finally:
        chunk_notice._usd_write_active = prev_w

snapshot_edit_target_selections ⚓︎

snapshot_edit_target_selections(stage)

Every Edit Target prim's stored selection, read straight off the stage before loading.

Must be called BEFORE load_chunks -- restore_edit_target_selections needs it.

Loading is itself destructive to these values. When a chunk.Menu is handed a value that isn't (yet) one of its menu_items, edit_target.py's refresh handler resets it to the default, and that reset is a param write, so it lands back in USD -- overwriting the saved selection with "Session Layer". Mid-load that happens routinely: an Edit Target pointing at "A" is rebuilt before the upstream Layer chunk has recreated layer A, so "A" isn't a menu item yet and the selection is destroyed on the way in.

Reading afterwards therefore can't recover it, however carefully -- by then USD holds "Session Layer" and the real answer exists only in the file on disk. This runs first, while the stage still has exactly what was saved, and needs no chunks to exist yet since it reads raw attrs off prims.

Parameters:

Name Type Description Default
stage Stage

The stage about to be loaded.

required

Returns:

Type Description
dict[str, str]

{prim path: selection}.

Source code in usd_chunks/chunk_stage.py
def snapshot_edit_target_selections(stage: Usd.Stage) -> dict[str, str]:
    """Every Edit Target prim's stored selection, read straight off the stage before loading.

    Must be called BEFORE load_chunks -- restore_edit_target_selections needs it.

    Loading is itself destructive to these values. When a chunk.Menu is handed a value that
    isn't (yet) one of its menu_items, edit_target.py's refresh handler resets it to the
    default, and that reset is a param write, so it lands back in USD -- overwriting the saved
    selection with "Session Layer". Mid-load that happens routinely: an Edit Target pointing
    at "A" is rebuilt before the upstream Layer chunk has recreated layer A, so "A"
    isn't a menu item yet and the selection is destroyed on the way in.

    Reading afterwards therefore can't recover it, however carefully -- by then USD holds
    "Session Layer" and the real answer exists only in the file on disk. This runs first,
    while the stage still has exactly what was saved, and needs no chunks to exist yet since
    it reads raw attrs off prims.

    Args:
        stage: The stage about to be loaded.

    Returns:
        {prim path: selection}.
    """
    saved: dict[str, str] = {}
    if not stage:
        return saved
    for prim in stage.Traverse():
        if prim.GetTypeName() != _CHUNK_PRIM_TYPENAME:
            continue
        type_attr = prim.GetAttribute(_CHUNK_TYPE_ATTR)
        if not (type_attr and type_attr.IsValid()) or type_attr.Get() != "edit_target":
            continue
        attr = prim.GetAttribute("inputs:edit_target")
        stored = attr.Get() if (attr and attr.IsValid()) else None
        if stored:
            saved[str(prim.GetPath())] = stored
    return saved

sort_chunk_layers ⚓︎

sort_chunk_layers(lm, chunks, keys=None)

Order chunk layers by their place in the wiring, for a graph with no View to do it.

Each chunk layer is placed when it is made, before it is wired, so placement alone leaves creation order and an upstream chunk's opinions win. A View re-sorts on every recook; this does the same for a load, or a script still building.

Ranked by nested_cook_keys, the order a load cooks in: a chunk wired after a chunkgroup sorts past every chunk inside it, however deep. By chain depth (layer_sort_key) it tied with the group's last chunk -- the DAG does not nest a group inside the one that holds it -- and which won came down to the order the layers were made, one way on a fresh build and the other after a reopen. The graph layers are ordered within their targets too, as a View's recook does: a nested group's chunks sit in one of their own.

Parameters:

Name Type Description Default
lm ChunkLayerManager

The layer manager.

required
chunks Iterable[ChunkBase]

The chunks whose layers to sort.

required
keys dict | None

Their nested_cook_keys, when the caller has them (a load reads them once from the stage). Otherwise read here, from the DAG: this runs after every chunk a script makes, and reading every chunk prim's wires each time was quadratic.

None
Source code in usd_chunks/chunk_stage.py
def sort_chunk_layers(lm: ChunkLayerManager, chunks: Iterable[core.ChunkBase], keys: dict | None = None) -> None:
    """Order chunk layers by their place in the wiring, for a graph with no View to do it.

    Each chunk layer is placed when it is made, before it is wired, so placement alone
    leaves creation order and an upstream chunk's opinions win. A View re-sorts on every
    recook; this does the same for a load, or a script still building.

    Ranked by nested_cook_keys, the order a load cooks in: a chunk wired after a chunkgroup
    sorts past every chunk inside it, however deep. By chain depth (layer_sort_key) it
    tied with the group's last chunk -- the DAG does not nest a group inside the one that
    holds it -- and which won came down to the order the layers were made, one way on a
    fresh build and the other after a reopen. The graph layers are ordered within their
    targets too, as a View's recook does: a nested group's chunks sit in one of their own.

    Args:
        lm: The layer manager.
        chunks: The chunks whose layers to sort.
        keys: Their nested_cook_keys, when the caller has them (a load reads them once from
            the stage). Otherwise read here, from the DAG: this runs after every chunk a
            script makes, and reading every chunk prim's wires each time was quadratic.
    """
    chunks = list(chunks)
    lm.follow_merged_graphs(chunks)
    if keys is None:
        keys = nested_cook_keys(chunks, lm.stage, from_dag=True)
    rank = {
        layer.identifier: keys[id(c)]
        for c in chunks
        if id(c) in keys and (layer := lm.get_layer(c)) is not None
    }
    # A snapshot: writing subLayerPaths can cascade into get_or_create_layer, which edits
    # graph_layers while this loop would still be reading it.
    _reorder_graph_layers_by_rank(list(lm.graph_layers.values()), rank)
    _reorder_graph_layers_in_targets(lm, rank)

stamp_stage_metadata ⚓︎

stamp_stage_metadata(dst, stage, keep_own=False)

Stamp the stage's up-axis and units onto the in-memory layer before it is written.

Read with the same UsdGeom API the live stage answers with, so the file carries the opinion from its first byte rather than being reopened and patched afterwards. Written straight onto the layer's pseudo-root: opening a stage over dst to set them composed the whole layer, which for an exported scene is everything in it.

Shared by every writer -- save, export_network, scene.export and the Export USD chunk -- since a file without them falls back to USD's global default whatever the scene was.

Parameters:

Name Type Description Default
dst Layer

The layer to stamp.

required
stage Stage

The stage to read them from.

required
keep_own bool

Keep a value dst already holds. For a sublayer: the stage never reads its values, so the stage's say nothing about what it was given (a Stage Settings chunk behind an Edit Target writes them there for its export).

False
Source code in usd_chunks/chunk_stage.py
def stamp_stage_metadata(dst: Sdf.Layer, stage: Usd.Stage, keep_own: bool = False) -> None:
    """Stamp the stage's up-axis and units onto the in-memory layer before it is written.

    Read with the same UsdGeom API the live stage answers with, so the file carries the
    opinion from its first byte rather than being reopened and patched afterwards. Written
    straight onto the layer's pseudo-root: opening a stage over `dst` to set them composed
    the whole layer, which for an exported scene is everything in it.

    Shared by every writer -- save, export_network, scene.export and the Export USD chunk --
    since a file without them falls back to USD's global default whatever the scene was.

    Args:
        dst: The layer to stamp.
        stage: The stage to read them from.
        keep_own: Keep a value dst already holds. For a sublayer: the stage never reads
            its values, so the stage's say nothing about what it was given (a Stage
            Settings chunk behind an Edit Target writes them there for its export).
    """
    root = dst.pseudoRoot
    for key, value in ((UsdGeom.Tokens.upAxis, UsdGeom.GetStageUpAxis(stage)),
                       (UsdGeom.Tokens.metersPerUnit, UsdGeom.GetStageMetersPerUnit(stage))):
        if not (keep_own and root.HasInfo(key)):
            root.SetInfo(key, value)

start_collapsed ⚓︎

start_collapsed(chunks)

Collapse new chunks before they are added, so their nodes start as a header.

A graph that branches stacks its nodes under each other, and full bodies make that stack tall: a node shows its header, exec ports and wired ports until it is opened. Set before the add, so the prim is written collapsed and the node is built that way rather than drawn open and then shut. Views, Outputs and groups are left as they are: the first two have no body, and a group's double-click is its dive. USD_CHUNKS_START_COLLAPSED=0 starts every node open instead. It is read on each call, so a script can flip it mid-session.

Parameters:

Name Type Description Default
chunks

The chunks about to be added.

required
Source code in usd_chunks/chunk_stage.py
def start_collapsed(chunks) -> None:
    """Collapse new chunks before they are added, so their nodes start as a header.

    A graph that branches stacks its nodes under each other, and full bodies make that
    stack tall: a node shows its header, exec ports and wired ports until it is opened.
    Set before the add, so the prim is written collapsed and the node is built that way
    rather than drawn open and then shut. Views, Outputs and groups are left as they are:
    the first two have no body, and a group's double-click is its dive.
    USD_CHUNKS_START_COLLAPSED=0 starts every node open instead. It is read on each call,
    so a script can flip it mid-session.

    Args:
        chunks: The chunks about to be added.
    """
    if os.environ.get("USD_CHUNKS_START_COLLAPSED", "").strip().lower() in ("0", "false", "no", "off"):
        return
    for chunk in chunks:
        if has_collapsible_body(chunk):
            chunk.set_state(ChunkFlags.State.COLLAPSED)

strip_chunks ⚓︎

strip_chunks(layer, only_paths=None)

Remove the Chunk prims from layer, in place, and everything that pointed at them.

Shared by scene.export() and the Export USD chunk, so both write the same plain USD.

Parameters:

Name Type Description Default
layer

The layer to clean.

required
only_paths

Strip just these chunk prim paths and leave every other chunk in place. None strips every Chunk prim in the layer.

None
Source code in usd_chunks/chunk_stage.py
def strip_chunks(layer, only_paths=None) -> None:
    """Remove the Chunk prims from `layer`, in place, and everything that pointed at them.

    Shared by scene.export() and the Export USD chunk, so both write the same plain USD.

    Args:
        layer: The layer to clean.
        only_paths: Strip just these chunk prim paths and leave every other chunk in
            place. None strips every Chunk prim in the layer.
    """
    if only_paths is None:
        tmp = Usd.Stage.Open(layer)
        candidates = (p.GetPath() for p in tmp.TraverseAll() if p.GetTypeName() == chunk_naming.CHUNK_PRIM_TYPENAME)
    else:
        candidates = (Sdf.Path(p) for p in only_paths)
    # Shallowest path first, so removing a parent Chunk takes its children with it and
    # the later lookup for those children simply finds nothing.
    chunk_paths = sorted(candidates, key=lambda p: p.pathElementCount)
    for path in chunk_paths:
        spec = layer.GetPrimAtPath(path)
        if not spec:
            continue  # already removed as child of a shallower Chunk
        parent = spec.nameParent
        if parent:
            del parent.nameChildren[spec.name]
        else:
            del layer.pseudoRoot.nameChildren[spec.name]

    # Chunks connect the attributes they drive to their own params (a camera's focalLength
    # to Camera.inputs:...:focalLength). The values are already flattened in, so the links
    # would only point at prims this file no longer has. That includes a chunk whose prim
    # sat in another layer and so was never in `chunk_paths`: any link into the chunk
    # scope that has nothing left to land on goes too.
    chunks_root = Sdf.Path(chunk_naming.CHUNKS_ROOT)

    def is_gone(target):
        if any(target.HasPrefix(c) for c in chunk_paths):
            return True
        return target.HasPrefix(chunks_root) and not layer.GetPrimAtPath(target.GetPrimPath())

    def drop_links_to_chunks(path):
        if not path.IsPropertyPath():
            return
        prop = layer.GetPropertyAtPath(path)
        links = prop.connectionPathList if isinstance(prop, Sdf.AttributeSpec) else prop.targetPathList
        items = list(links.GetAddedOrExplicitItems())
        kept = [t for t in items if not is_gone(t)]
        if len(kept) == len(items):
            return
        if kept:
            for target in set(items) - set(kept):
                links.RemoveItemEdits(target)
        else:
            links.ClearEdits()  # no `.connect = None` left behind

    # The scope the chunks hung under is recipe as well. Nothing lives AT /chunks, so once
    # its chunks are gone an empty `def Scope "chunks" {}` is the one trace of the network
    # left in a file whose whole point is to carry none -- and it is enough to make a
    # delivered asset look like it wants usd_chunks installed. A layer that only held
    # chunk bookkeeping also leaves `over`s behind: the ones that framed it (`over
    # "chunks"` / `over "ChunkGroup"`), and the bookkeeping of chunks defined in another
    # layer -- a chunkgroup's inner chunks write theirs into the Edit Target's layer, while
    # the group itself is in the session layer. Any subtree under /chunks with no `def` in
    # it is one of those. Something else parked there is a `def`, and stays.
    root = layer.GetPrimAtPath(chunks_root)
    is_scope = root and root.typeName in (chunk_naming.CHUNKS_ROOT_TYPENAME, "")
    if is_scope:
        _prune_over_only(root)
    # After the pruning, so links into what it removed go too.
    layer.Traverse(Sdf.Path.absoluteRootPath, drop_links_to_chunks)
    if is_scope and not root.nameChildren and (root.typeName or root.specifier == Sdf.SpecifierOver):
        del layer.pseudoRoot.nameChildren[root.name]
    if only_paths is None:
        _default_to_the_only_root(layer)

strongest_output ⚓︎

strongest_output(stage, scene, context)

The Output of a graph from its strongest layer, or None when it has none.

Source code in usd_chunks/chunk_stage.py
def strongest_output(
    stage: Usd.Stage, scene: chunk_scene.SceneSender, context: core.ChunkBase | None
) -> core.ChunkBase | None:
    """The Output of a graph from its strongest layer, or None when it has none."""
    outputs = graph_outputs(stage, scene, context)
    return outputs[-1] if outputs else None

suggest_location_from_file ⚓︎

suggest_location_from_file(param)

Fill a Reference or Payload chunk's primpath_location from its file_path.

Called when file_path changes: the location becomes /, made a valid prim name and unique on the stage. A location holding an expression is left alone. A network file is hosted, not placed: its location field is the namespace the network's prim paths resolve under, and the default is none -- the paths as the sequence wrote them. Suggesting / there would namespace every hosted network.

Only a location that still follows the file is replaced: an empty one, or the one this last suggested. One typed in, set by a script or loaded from a saved network is a choice, and a new file does not move it -- usdchunks run net.usda Reference.file_path=other.usd (and every run of a batch) swaps the asset, not where the network put it. A glob names no one file, so it suggests nothing either.

Parameters:

Name Type Description Default
param

The param that changed (file_path, or another param of the chunk).

required
Source code in usd_chunks/chunk_stage.py
def suggest_location_from_file(param) -> None:
    """Fill a Reference or Payload chunk's primpath_location from its file_path.

    Called when file_path changes: the location becomes /<file name>, made a valid prim
    name and unique on the stage. A location holding an expression is left alone. A
    network file is hosted, not placed: its location field is the namespace the
    network's prim paths resolve under, and the default is none -- the paths as the
    sequence wrote them. Suggesting /<file> there would namespace every hosted network.

    Only a location that still follows the file is replaced: an empty one, or the one this
    last suggested. One typed in, set by a script or loaded from a saved network is a
    choice, and a new file does not move it -- `usdchunks run net.usda
    Reference.file_path=other.usd` (and every run of a batch) swaps the asset, not where
    the network put it. A glob names no one file, so it suggests nothing either.

    Args:
        param: The param that changed (file_path, or another param of the chunk).
    """
    chunk = param.get_chunk()
    if param.name == "file_path" and param.value:
        path = param.value
    else:
        file_param = chunk.get_param("file_path") if chunk else None
        path = file_param.value if file_param else None
    if not path:
        return

    location = chunk.get_param("primpath_location") if chunk else None
    if not location or chunk_utils.has_expression(location.raw_value or ""):
        return

    import_param = chunk.get_param("import_primpath")
    # The chunk holds the file from here: its cook, straight after, reads the same one.
    hold_asset_layers(chunk, [path])
    if network_target(path, import_param.value if import_param else ""):
        if location.raw_value:
            location.value = ""
        return

    current = location.raw_value or ""
    if chunk_glob.is_pattern(path) or (current and current != _suggested_locations.get(chunk)):
        return
    suggestion = f"/{Tf.MakeValidIdentifier(Path(path).stem)}"
    # A file with the same name (a new version from another folder) keeps the location: the
    # prim already there is this chunk's own, not a clash.
    if suggestion != current:
        suggestion = chunk_utils.get_unique_path(param.get_scene_stage(), suggestion)
    location.value = _suggested_locations[chunk] = suggestion

unhost_network ⚓︎

unhost_network(chunk)

Drop a hosted network: clear the arc from chunk's prim and the group flags from the chunk.

The composed-in children disappear with the arc and the stage-change path tears their chunk objects down, the same as any prim vanishing from the stage.

Parameters:

Name Type Description Default
chunk ChunkBase

The hosting chunk.

required
Source code in usd_chunks/chunk_stage.py
def unhost_network(chunk: core.ChunkBase) -> None:
    """Drop a hosted network: clear the arc from chunk's prim and the group flags from the chunk.

    The composed-in children disappear with the arc and the stage-change path tears their
    chunk objects down, the same as any prim vanishing from the stage.

    Args:
        chunk: The hosting chunk.
    """
    stage = chunk.get_scene_stage()
    if not stage or not is_network_host(chunk):
        return
    own_path = get_chunk_prim_path(chunk)
    prim = stage.GetPrimAtPath(Sdf.Path(own_path))
    sync = ChunkStageSync()
    scene = _active_scene()
    # The children the arc composed in, gathered while their prims still tell us so; the
    # arc clear runs with notices suppressed, so the stage-change path will not see them go.
    inside = [c for c in (scene.get_chunks() if scene else [])
              if get_chunk_prim_path(c).startswith(own_path + "/")]
    prev = chunk_notice._usd_write_active
    chunk_notice._usd_write_active = True
    try:
        with sync._chunk_prim_edit_context(chunk):
            prim.GetReferences().ClearReferences()
            prim.GetPayloads().ClearPayloads()
    finally:
        chunk_notice._usd_write_active = prev
    was_reloading = sync._reloading
    sync._reloading = True
    try:
        for c in sorted(inside, key=lambda c: get_chunk_prim_path(c).count("/"), reverse=True):
            if not stage.GetPrimAtPath(Sdf.Path(get_chunk_prim_path(c))).IsValid():
                c.request_delete()
    finally:
        sync._reloading = was_reloading
    for flag in (ChunkFlags.GroupFlags.CONTEXT, ChunkFlags.GroupFlags.COLLAPSABLE,
                 ChunkFlags.GroupFlags.LABELED):
        chunk.unset_flag(flag)
    core.NameSyncedContainer.generation += 1  # not a group any more: see host_networks
    object.__setattr__(chunk, "_network_namespace", "")

unloft_param ⚓︎

unloft_param(context_param)

Remove a lofted param from its group. The inner param keeps its current value.

A copy lofted further up is removed first, and nothing is left connected to the group's attribute.

Parameters:

Name Type Description Default
context_param ChunkParamBase

The lofted param on the group.

required
Source code in usd_chunks/chunk_stage.py
@_editing_lofts()
def unloft_param(context_param: core.ChunkParamBase) -> None:
    """Remove a lofted param from its group. The inner param keeps its current value.

    A copy lofted further up is removed first, and nothing is left connected to the
    group's attribute.

    Args:
        context_param: The lofted param on the group.
    """
    sync = ChunkStageSync()
    if not (sync.initialized and sync._stage and getattr(context_param, "_lofted", False)):
        return
    stage = sync._stage
    context = context_param.get_chunk()
    attr_path = context_param._param_attr_path
    context_attr = stage.GetAttributeAtPath(Sdf.Path(attr_path)) if attr_path else None
    if context is None or not (context_attr and context_attr.IsValid()):
        return

    chunks = list(sync._scene.get_chunks()) if sync._scene else []

    # A copy lofted one level up is fed by this one, so it goes first. It sits on the group
    # this one is in, which for the top of a tab is the tab's own group: not in the scene's
    # chunks, so it is looked at as well.
    targets = {str(c) for c in context_attr.GetConnections()}
    outers = list(chunks)
    parent_ref = getattr(context, "_parent_context", None)
    if (parent := parent_ref() if parent_ref else None) is not None and parent not in outers:
        outers.append(parent)
    for outer in outers if targets else ():
        for upper in [p for p in outer.get_my_params()
                      if getattr(p, "_lofted", False) and p._param_attr_path in targets]:
            unloft_param(upper)

    _, inner = _find_lofted_inner(stage, context, attr_path)
    if inner is not None:
        sync.clear_attr_connections(stage.GetAttributeAtPath(Sdf.Path(inner._param_attr_path)))
        if hasattr(inner, "_loft_back"):
            del inner._loft_back  # drops the inner -> group sync callback

    # Break wires out of the lofted port: the attribute they read is about to go.
    expr = f"@{context.name}.{context_param.name}@"
    for chunk in chunks:
        for _, param in _iter_chunk_params(chunk):
            if isinstance(param.raw_value, str) and expr in param.raw_value:
                param.value = param.value
    root = stage.GetPrimAtPath(_CHUNKS_ROOT)
    for prim in Usd.PrimRange(root) if root else ():
        for attr in prim.GetAttributes():
            if any(str(c) == attr_path for c in attr.GetConnections()):
                sync.clear_attr_connections(attr)

    context_param.request_delete()
    sync._delete_stale_attr_specs(context_attr.GetPrim(), context_attr.GetName())
    owner = inner.get_chunk() if inner is not None else None
    if owner is not None and (hook := owner._module_hook(PARAM_UNLOFTED_HOOK)):
        hook(owner, inner)

unwire_param ⚓︎

unwire_param(param)

Drop a param's incoming wire and put it back to its default.

For a param the chunk has just hidden: a wire kept on it would come back, with possibly the wrong meaning, when the param is shown again. A param with no wire is left alone.

Parameters:

Name Type Description Default
param

The param, or None.

required
Source code in usd_chunks/chunk_stage.py
def unwire_param(param) -> None:
    """Drop a param's incoming wire and put it back to its default.

    For a param the chunk has just hidden: a wire kept on it would come back, with
    possibly the wrong meaning, when the param is shown again. A param with no wire is
    left alone.

    Args:
        param: The param, or None.
    """
    if param is None:
        return
    raw = getattr(param, "raw_value", None)
    if not (isinstance(raw, str) and chunk_utils.has_expression(raw)):
        return
    param.value = param.default_value
    if attr := param.get_usd_prop():
        clear_attr_connections(attr)

view_cook_list ⚓︎

view_cook_list(view_chunk, stage, scene)

The chunks feeding view_chunk, following ALL input connections backward.

This is the cook set for a view: view-driven execution runs only these chunks. For the exec-only branch, see exec_upstream. Follows both the exec wire (inputs:chunk) AND data connections (any inputs:* to a source prim), so a node feeding another purely via data (e.g. a Transform between a Scatter and an RBD solver that reads its points) is still cooked -- otherwise it would be blocked and its downstream would read empty/stale input.

Parameters:

Name Type Description Default
view_chunk ChunkBase

The view.

required
stage Stage

The stage.

required
scene SceneSender

The scene.

required

Returns:

Type Description
list[ChunkBase]

The chunks, roots first (a node's sources appear before it). The view chunk itself

list[ChunkBase]

is excluded.

Source code in usd_chunks/chunk_stage.py
def view_cook_list(
    view_chunk: core.ChunkBase,
    stage: Usd.Stage,
    scene: chunk_scene.SceneSender,
) -> list[core.ChunkBase]:
    """The chunks feeding view_chunk, following ALL input connections backward.

    This is the *cook set* for a view: view-driven execution runs only these chunks.
    For the exec-only branch, see exec_upstream. Follows both the exec wire (inputs:chunk)
    AND data connections (any inputs:* to a source prim), so a node feeding another purely
    via data (e.g. a Transform between a Scatter and an RBD solver that reads its points) is
    still cooked -- otherwise it would be blocked and its downstream would read empty/stale
    input.

    Args:
        view_chunk: The view.
        stage: The stage.
        scene: The scene.

    Returns:
        The chunks, roots first (a node's sources appear before it). The view chunk itself
        is excluded.
    """
    prim_to_chunk = {get_chunk_prim_path(c): c for c in scene.get_chunks()}
    view_path = get_chunk_prim_path(view_chunk)
    paths: list[str] = []
    _roots_first(stage, prim_to_chunk, view_path, set(), paths)
    return [c for path in paths if path != view_path and (c := prim_to_chunk.get(path)) is not None]

view_slot ⚓︎

view_slot(stage, view)

A View's slot.

Parameters:

Name Type Description Default
stage Stage

The stage.

required
view ChunkBase

The View.

required

Returns:

Type Description
int

The slot, or 0 for an inert View (made from the chunk menu, not given one yet).

Source code in usd_chunks/chunk_stage.py
def view_slot(stage: Usd.Stage, view: core.ChunkBase) -> int:
    """A View's slot.

    Args:
        stage: The stage.
        view: The View.

    Returns:
        The slot, or 0 for an inert View (made from the chunk menu, not given one yet).
    """
    prim = stage.GetPrimAtPath(Sdf.Path(get_chunk_prim_path(view)))
    return int(prim.GetAttribute("view:slot").Get() or 0) if prim and prim.IsValid() else 0