NVIDIA-Omniverse / OpenUSD-Code-Samples

Common code snippets for OpenUSD
Apache License 2.0
65 stars 17 forks source link

USD Stage Traversal For Reference/Instance/Proxies #10

Open cadop opened 1 year ago

cadop commented 1 year ago

The typical methods for traversing a stage don't work in some cases, like an external stage being referenced in the current stage.

I would be happy to open a PR with a few examples, if told where to put them (I guess in https://github.com/NVIDIA-Omniverse/OpenUSD-Code-Samples/tree/main/source/hierarchy-traversal)

A few examples would be nice:

cadop commented 1 year ago

For the first bullet, I made a script that does the traversal on the entire scene, and appends all the prims that are a mesh type:

def get_all_stage_mesh(stage):

    found_meshes = []

    # Traverse the scene graph and print the paths of prims, including instance proxies
    for x in Usd.PrimRange(stage.GetPseudoRoot(), Usd.TraverseInstanceProxies()):
        if x.IsA(UsdGeom.Mesh):
            found_meshes.append(x)
    return found_meshes
cadop commented 1 year ago

On the second bullet, there is a nice script from https://github.com/ColinKennedy/USD-Cookbook/blob/master/tricks/traverse_instanced_prims/README.md

def traverse_instanced_children(prim):
    """Get every Prim child beneath `prim`, even if `prim` is instanced.

    Important:
        If `prim` is instanced, any child that this function yields will
        be an instance proxy.

    Args:
        prim (`pxr.Usd.Prim`): Some Prim to check for children.

    Yields:
        `pxr.Usd.Prim`: The children of `prim`.

    """
    for child in prim.GetFilteredChildren(Usd.TraverseInstanceProxies()):
        yield child

        for subchild in traverse_instanced_children(child):
            yield subchild