Hierarchy and Traversal#
USD Stages are organized in a hierarchy of Prims: there is a special root prim at /
and it may have N-number of direct Prim descendants, each of which can have their own tree of Prim descendants.
The path to a Prim is described by a string which starts with the root prim /
and contains the Prim name separated by the path separator /
until the last component is the desired Prim’s name.
For example /Car/Wheel/Tire
refers to the Tire
prim which has parent Wheel
and grandparent Car
. Car
’s parent is the special root prim /
.
In the tutorial, Defining Your First Prims, there is information on how to retrieve a Prim at a given path using stage_ref.GetPrimAtPath()
.
Here is a refresher, we’ll assume car.usda
has the /Car/Wheel/Tire
path:
from pxr import Usd
stage_ref = Usd.Stage.Open('car.usda')
prim_ref = stage_ref.GetPrimAtPath('/Car')
Now, if you want to get a specific child of a Prim, and you know the name, you can use prim_ref.GetChild(child_name)
:
from pxr import Usd
stage_ref = Usd.Stage.Open('car.usda')
prim_ref = stage_ref.GetPrimAtPath('/Car')
child_prim_ref = prim_ref.GetChild('Wheel')
# Prims can be cast as bool, so you can check if the prim exists by comparing
its bool() overload
if child_prim_ref:
print("/Car/Wheel exists") # this will execute
print(child_prim_ref.GetPath()) # prints ""/Car/Wheel"
If you want to get all the children of a Prim, you can use prim_ref.GetChildren()
which returns a list of prim references:
from pxr import Usd
stage_ref = Usd.Stage.Open('car.usda')
prim_ref = stage_ref.GetPrimAtPath('/Car')
# will return [Usd.Prim(</Car/Wheel>)]
children_refs = prim_ref.GetChildren()
If you want to traverse the entire stage, the stage_ref.Traverse() function is perfect for that, it returns an iterator:
from pxr import Usd
stage_ref = Usd.Stage.Open('car.usda')
for prim_ref in stage_ref.Traverse():
print(prim_ref.GetPath())
There are more advanced traversal methods described in the UsdStage documentation.