def test_PrimIsLoaded(self): for fmt in allFormats: payloadStage = Usd.Stage.CreateInMemory("payload." + fmt) p = payloadStage.DefinePrim("/Payload", "Scope") stage = Usd.Stage.CreateInMemory("scene." + fmt) foo = stage.DefinePrim("/Foo") foo.SetPayload(payloadStage.GetRootLayer(), "/Payload") self.assertEqual(stage.GetLoadSet(), ["/Foo"]) stage.Unload("/Foo") x1 = list(Usd.PrimRange(foo, ~Usd.PrimIsLoaded)) self.assertEqual(x1, [foo]) x2 = list(Usd.PrimRange(foo, Usd.PrimIsLoaded)) self.assertEqual(x2, []) stage.Load("/Foo") x3 = list(Usd.PrimRange(foo, ~Usd.PrimIsLoaded)) self.assertEqual(x3, []) x4 = list(Usd.PrimRange(foo, Usd.PrimIsLoaded)) self.assertEqual(x4, [foo])
def test_PrimHasDefiningSpecifier(self): for fmt in allFormats: stageFile = 'testHasDefiningSpecifier.' + fmt stage = Usd.Stage.Open(stageFile) # In the case of nested overs and defs, the onus is # on the client to manually prune their results either by # restarting iteration upon hitting an over, or by iterating # through all prims. root = stage.GetPrimAtPath('/a1') actual = [] expected = [stage.GetPrimAtPath(x) for x in ['/a1', '/a1/a2']] for prim in Usd.PrimRange.AllPrims(root): if prim.HasDefiningSpecifier(): actual.append(prim) self.assertEqual(actual, expected) root = stage.GetPrimAtPath('/b1') actual = [] expected = [ stage.GetPrimAtPath(x) for x in ['/b1/b2', '/b1/b2/b3/b4/b5/b6'] ] for prim in Usd.PrimRange(root, Usd.PrimIsActive): if prim.HasDefiningSpecifier(): actual.append(prim) self.assertEqual(actual, expected) # Note that the over is not included in our traversal. root = stage.GetPrimAtPath('/c1') actual = list(Usd.PrimRange(root, Usd.PrimHasDefiningSpecifier)) expected = [ stage.GetPrimAtPath(x) for x in ['/c1', '/c1/c2', '/c1/c2/c3'] ] self.assertEqual(actual, expected)
def test_WithInstancing(self): for fmt in allFormats: refStage = Usd.Stage.CreateInMemory("reference." + fmt) refStage.DefinePrim("/Ref/Child") stage = Usd.Stage.CreateInMemory("scene." + fmt) root = stage.DefinePrim("/Root") i = stage.DefinePrim("/Root/Instance") i.GetReferences().AddReference(refStage.GetRootLayer().identifier, "/Ref") i.SetMetadata("instanceable", True) n = stage.DefinePrim("/Root/NonInstance") n.GetReferences().AddReference(refStage.GetRootLayer().identifier, "/Ref") nChild = stage.GetPrimAtPath('/Root/NonInstance/Child') master = stage.GetMasters()[0] masterChild = master.GetChild('Child') # A default traversal of a stage with instances should not descend into # instance masters self.assertEqual(list(Usd.PrimRange.Stage(stage)), [root, i, n, nChild]) self.assertEqual(list(Usd.PrimRange(stage.GetPseudoRoot())), [stage.GetPseudoRoot(), root, i, n, nChild]) # But the tree iterator should allow traversal of the masters if # explicitly specified. self.assertEqual(list(Usd.PrimRange(master)), [master, masterChild])
def test_PrimIsDefined(self): for fmt in allFormats: s = Usd.Stage.CreateInMemory('TestPrimIsDefined.' + fmt) pseudoRoot = s.GetPrimAtPath("/") foo = s.DefinePrim("/Foo", "Mesh") bar = s.OverridePrim("/Bar") faz = s.DefinePrim("/Foo/Faz", "Mesh") baz = s.DefinePrim("/Bar/Baz", "Mesh") # Change specifier so that /Bar is an over prim with no type. s.GetRootLayer().GetPrimAtPath( "/Bar").specifier = Sdf.SpecifierOver # Default tree iterator should not hit undefined prims. x = list(Usd.PrimRange(pseudoRoot)) self.assertEqual(x, [pseudoRoot, foo, faz]) # Create a tree iterator and ensure that /Bar and its descendants aren't # traversed by it. x = list(Usd.PrimRange(pseudoRoot, Usd.PrimIsDefined)) self.assertEqual(x, [pseudoRoot, foo, faz]) # When we ask for undefined prim rooted at /Bar, verify that bar and baz # are returned. x = list(Usd.PrimRange(bar, ~Usd.PrimIsDefined)) self.assertEqual(x, [bar, baz])
def main(): print("UsdSkelAppleFixup Begin.") # Create a new out usd file that sublayers the in usd file. All edits # will go to the out usd file. Start and end time is copied over. inFile = args.inusd outFile = args.outusd from pxr import Usd, UsdGeom, UsdSkel, Sdf dstLyr = Sdf.Layer.CreateNew(outFile) srcLyr = Sdf.Layer.FindOrOpen(inFile) stage = Usd.Stage.Open(dstLyr) stage.SetEditTarget(dstLyr) layerStack = dstLyr.subLayerPaths layerStack.insert(len(layerStack), inFile) start = int(srcLyr.startTimeCode) end = int(srcLyr.endTimeCode) stage.SetStartTimeCode(start) stage.SetEndTimeCode(end) # Find all the skinned meshes and copy over the animation source to them # The the skel, anim, and mesh prims. skelPrims = [ prim for prim in Usd.PrimRange(stage.GetPseudoRoot()) if prim.IsA(UsdSkel.Skeleton) ] meshPrims = [ prim for prim in Usd.PrimRange(stage.GetPseudoRoot()) if prim.IsA(UsdGeom.Mesh) ] for skelPrim in skelPrims: skelCache = UsdSkel.Cache() skel = UsdSkel.Skeleton(skelPrim) skelQuery = skelCache.GetSkelQuery(skel) skelAnimQuery = skelQuery.GetAnimQuery() skelAnim = UsdSkel.Animation(skelAnimQuery.GetPrim()) for mesh in meshPrims: rel = FindSkelBindingRel(stage, mesh) if rel: for target in rel.GetTargets(): if target == skelPrim.GetPath(): print("Copying the animationSource relationship to " + mesh.GetName()) # wire up the skeleton and animation source rels for temporary compatbility with Apple's expectations mesh.CreateRelationship( UsdSkel.Tokens.skelAnimationSource).AddTarget( skelAnim.GetPrim().GetPath()) mesh.CreateRelationship( UsdSkel.Tokens.skelSkeleton).AddTarget( skelPrim.GetPath()) dstLyr.Save()
def _ValidateInstanceDescendants(parentPath, expectedDescendantPaths): parent = s.GetPrimAtPath(parentPath) descendants = \ list(Usd.PrimRange(parent, Usd.TraverseInstanceProxies())) expectedDescendants = \ [s.GetPrimAtPath(p) for p in expectedDescendantPaths] self.assertEqual(expectedDescendants, descendants)
def _TraverseVariants(self, prim): from pxr import Usd if prim.IsInstanceProxy(): return True vSets = prim.GetVariantSets() vSetNames = vSets.GetNames() allVariantNames = [] for vSetName in vSetNames: vSet = vSets.GetVariantSet(vSetName) vNames = vSet.GetVariantNames() allVariantNames.append(vNames) import itertools allVariations = itertools.product(*allVariantNames) for variation in allVariations: self._Msg("Testing variation %s of prim <%s>" % (variation, prim.GetPath())) for (idx, sel) in enumerate(variation): vSets.SetSelection(vSetNames[idx], sel) for rule in self._rules: rule.ResetCaches() primRangeIt = iter( Usd.PrimRange(prim, Usd.TraverseInstanceProxies())) self._TraverseRange(primRangeIt, isStageRoot=False)
def iterFilteredChildPrims(self, startPrim): ''' Returns an iterator over the next child prims of `startPrim` that satisfy `self.primFilter(child)`. This will traverse down the prim tree from each immediate child of `startPrim` until a qualifying prim is found or that branch of the hierarchy is exhausted. Parameters ---------- startPrim : Usd.Prim Returns ------- Iterator[Usd.Prim] ''' primFilter = self.primFilter if primFilter is None: for child in startPrim.GetFilteredChildren(self.primPredicate): yield child return it = iter( Usd.PrimRange(startPrim, self.primPredicate).AllPrims(startPrim)) it.next() for child in it: if primFilter(child): yield child it.PruneChildren()
def BuildTree(self, startPrim): startItem = self._primPathToItemMap.get(startPrim.GetPath()) if not startItem: return # Add traversal of instances to predicate predicate = Usd.TraverseInstanceProxies( Usd.PrimIsActive & Usd.PrimIsDefined & ~Usd.PrimIsAbstract) childCount = len(startPrim.GetFilteredChildren(predicate)) first = startItem.childCount() last = first + childCount - 1 self.beginInsertRows(self.indexFromItem(startItem), first, last) prims = list(Usd.PrimRange(startPrim, predicate)) # Iterate through prims, but skip the startPrim for prim in prims[1:]: if not self.IsPrimBoundable(prim, predicate): continue parentPrim = prim.GetParent() parentItem = self._primPathToItemMap.get(parentPrim.GetPath()) if parentItem: primName = prim.GetName() primTypeName = prim.GetTypeName() primPath = prim.GetPath() hasUnloadedPayload = prim.HasPayload() # Use parentItem's import state to determine its child's # import state. (Note it is intentional that the parentItem's # data is tested to be equal to Checked or PartiallyChecked, # instead of just testing that it's *not* equal to Unchecked. # This is because when parentItem is the top-most root item, # its data is a header string instead of a CheckState). importState = Qt.Unchecked if parentItem.data(COL_IMPORT) == Qt.Checked or\ parentItem.data(COL_IMPORT) == Qt.PartiallyChecked: importState = Qt.PartiallyChecked # Retrieve variants from the prim. variants = [] variantSets = prim.GetVariantSets() for name in variantSets.GetNames(): variantSet = variantSets.GetVariantSet(name) variants.append(VariantInfo(\ name = name,\ choices = variantSet.GetVariantNames(),\ initialSelection = variantSet.GetVariantSelection(),\ enabled = False)) data = [primName, importState, primTypeName, variants] childItem = TreeItem(data, parentItem, primPath, hasUnloadedPayload) self._primPathToItemMap[primPath] = childItem self.endInsertRows()
def getPrimsToTranslate(cls, parentPrim, onlyTranslateVisible): prims = [] for prim in Usd.PrimRange(parentPrim): if prim.IsInstance(): for instancedPrim in prim.GetFilteredChildren( Usd.TraverseInstanceProxies()): prims.extend( cls._getPrimsToTranslate(instancedPrim, onlyTranslateVisible)) else: if prim.GetTypeName() != 'Mesh': continue if onlyTranslateVisible and UsdGeom.Imageable( prim).ComputeVisibility() == 'invisible': continue prims.extend(list(Usd.PrimRange(prim))) return prims
def test_PrimIsAbstract(self): for fmt in allFormats: s = Usd.Stage.CreateInMemory('TestPrimIsAbstract.' + fmt) group = s.DefinePrim("/Group", "Xform") c = s.CreateClassPrim("/class_Model") x1 = list(Usd.PrimRange(group, Usd.PrimIsAbstract)) self.assertEqual(x1, []) x2 = list(Usd.PrimRange(group, ~Usd.PrimIsAbstract)) self.assertEqual(x2, [group]) x3 = list(Usd.PrimRange(c, Usd.PrimIsAbstract)) self.assertEqual(x3, [c]) x4 = list(Usd.PrimRange(c, ~Usd.PrimIsAbstract)) self.assertEqual(x4, [])
def test_PrimIsInstanceOrMasterOrRoot(self): for fmt in allFormats: refStage = Usd.Stage.CreateInMemory("reference." + fmt) refStage.DefinePrim("/Ref/Child") stage = Usd.Stage.CreateInMemory("scene." + fmt) root = stage.DefinePrim("/Root") i = stage.DefinePrim("/Root/Instance") i.GetReferences().AddReference(refStage.GetRootLayer().identifier, "/Ref") i.SetMetadata("instanceable", True) n = stage.DefinePrim("/Root/NonInstance") n.GetReferences().AddReference(refStage.GetRootLayer().identifier, "/Ref") nChild = stage.GetPrimAtPath('/Root/NonInstance/Child') # Test Usd.PrimIsInstance self.assertEqual(list(Usd.PrimRange(i, Usd.PrimIsInstance)), [i]) self.assertEqual(list(Usd.PrimRange(i, ~Usd.PrimIsInstance)), []) self.assertEqual(list(Usd.PrimRange(n, Usd.PrimIsInstance)), []) self.assertEqual(list(Usd.PrimRange(n, ~Usd.PrimIsInstance)), [n, nChild]) self.assertEqual(list(Usd.PrimRange(root, Usd.PrimIsInstance)), []) self.assertEqual(list(Usd.PrimRange(root, ~Usd.PrimIsInstance)), [root, n, nChild])
def test_PrimIsModelOrGroup(self): for fmt in allFormats: s = Usd.Stage.CreateInMemory('TestPrimIsModelOrGroup.' + fmt) group = s.DefinePrim("/Group", "Xform") Usd.ModelAPI(group).SetKind('group') model = s.DefinePrim("/Group/Model", "Model") Usd.ModelAPI(model).SetKind('model') mesh = s.DefinePrim("/Group/Model/Sbdv", "Mesh") x1 = list(Usd.PrimRange(group, Usd.PrimIsModel)) self.assertEqual(x1, [group, model]) x2 = list(Usd.PrimRange(group, Usd.PrimIsGroup)) self.assertEqual(x2, [group]) x3 = list(Usd.PrimRange(group, ~Usd.PrimIsModel)) self.assertEqual(x3, []) x4 = list(Usd.PrimRange(mesh, ~Usd.PrimIsModel)) self.assertEqual(x4, [mesh]) x5 = list(Usd.PrimRange(group, Usd.PrimIsModel | Usd.PrimIsGroup)) self.assertEqual(x5, [group, model]) x6 = list(Usd.PrimRange(group, Usd.PrimIsModel & Usd.PrimIsGroup)) self.assertEqual(x6, [group])
def test_PrimIsActive(self): for fmt in allFormats: s = Usd.Stage.CreateInMemory('TestPrimIsActive.' + fmt) foo = s.DefinePrim("/Foo", "Mesh") bar = s.DefinePrim("/Foo/Bar", "Mesh") baz = s.DefinePrim("/Foo/Bar/Baz", "Mesh") baz.SetActive(False) # Create a tree iterator and ensure that /Bar and its descendants aren't # traversed by it. x1 = list(Usd.PrimRange(foo, Usd.PrimIsActive)) self.assertEqual(x1, [foo, bar]) # Test to make sure the predicate is checked on the iteration root. x2 = list(Usd.PrimRange(baz, Usd.PrimIsActive)) self.assertEqual(x2, []) x3 = list(Usd.PrimRange(baz, ~Usd.PrimIsActive)) self.assertEqual(x3, [baz]) x4 = list(Usd.PrimRange(bar, Usd.PrimIsActive)) self.assertEqual(x4, [bar])
def BuildTree(self, startPrim): startItem = self._primPathToItemMap.get(startPrim.GetPath()) if not startItem: return # Add traversal of instances to predicate predicate = Usd.TraverseInstanceProxies(Usd.PrimIsActive & Usd.PrimIsDefined & ~Usd.PrimIsAbstract) childCount = len(startPrim.GetFilteredChildren(predicate)) first = startItem.childCount() last = first + childCount - 1 self.beginInsertRows(self.indexFromItem(startItem), first, last) prims = list(Usd.PrimRange(startPrim, predicate)) # Iterate through prims, but skip the startPrim for prim in prims[1:]: if not self.IsPrimBoundable(prim, predicate): continue parentPrim = prim.GetParent() parentItem = self._primPathToItemMap.get(parentPrim.GetPath()) if parentItem: primName = prim.GetName() primTypeName = prim.GetTypeName() primPath = prim.GetPath() hasUnloadedPayload = prim.HasPayload() # Retrieve variants from the prim. variants = [] variantSets = prim.GetVariantSets() for name in variantSets.GetNames(): variantSet = variantSets.GetVariantSet(name) variants.append(VariantInfo(\ name = name,\ choices = variantSet.GetVariantNames(),\ initialSelection = variantSet.GetVariantSelection(),\ enabled = False)) data = [primName, Qt.Unchecked, primTypeName, variants] childItem = TreeItem(data, parentItem, primPath, hasUnloadedPayload) self._primPathToItemMap[primPath] = childItem self.endInsertRows()
def test_RoundTrip(self): for fmt in allFormats: stage = Usd.Stage.CreateInMemory('TestRoundTrip.' + fmt) prims = list(map(stage.DefinePrim, ['/foo', '/bar', '/baz'])) treeRange = Usd.PrimRange(stage.GetPseudoRoot()) tripped = Usd._TestPrimRangeRoundTrip(treeRange) self.assertEqual(treeRange, tripped) self.assertEqual(list(treeRange), list(tripped)) treeRange = Usd.PrimRange.PreAndPostVisit(stage.GetPseudoRoot()) tripped = Usd._TestPrimRangeRoundTrip(treeRange) self.assertEqual(treeRange, tripped) self.assertEqual(list(treeRange), list(tripped))
def ValidateExpectedInstances(stage, expectedInstances): """ Validate the expected instances and prototypes on the given stage. expectedInstances is a mapping from: prototype prim path -> list of expected instance prim paths """ for (prototypePath, instancePaths) in expectedInstances.items(): # Validate that all prims expected to be instances of the same prototype # are associated with the same prototype prim. prototype = stage.GetPrimAtPath(prototypePath) assert prototype, "Expected prototype <%s> does not exist" % prototypePath for p in instancePaths: prim = stage.GetPrimAtPath(p) assert prim, "Prim <%s> does not exist" % p assert prim.IsInstance(), "Prim <%s> is not an instance" % p assert prim.GetPrototype() == prototype, \ "Instance <%s> does not have expected prototype <%s>" % \ (p, prototype.GetPath()) # Validate that the prototype prim's source prim index is one of # the instance's prim indexes. prototypePrimIndexPath = prototype._GetSourcePrimIndex().rootNode.path instancePrimIndexPaths = [ stage.GetPrimAtPath(p)._GetSourcePrimIndex().rootNode.path for p in instancePaths ] assert prototypePrimIndexPath in instancePrimIndexPaths, \ "Prototype <%s> using unexpected prim index <%s>, expected " \ "one of %s" % (prototype.GetPath(), prototypePrimIndexPath, instancePrimIndexPaths) # Validate that we don't have any unexpected prototypes or instances. for prototype in stage.GetPrototypes(): assert str(prototype.GetPath()) in expectedInstances for root in [stage.GetPseudoRoot()] + stage.GetPrototypes(): for prim in Usd.PrimRange(root): if prim.IsInstance(): assert str(prim.GetPath()) in \ expectedInstances.get( str(prim.GetPrototype().GetPath()), []), \ "Found unexpected instance prim <%s> with prototype <%s>" %\ (prim.GetPath(), prim.GetPrototype().GetPath())
def GetPrimLoadability(prim): """Return a tuple of (isLoadable, isLoaded) for 'prim', according to the following rules: A prim is loadable if it is active, and either of the following are true: * prim has a payload * prim is a model group The latter is useful because loading is recursive on a UsdStage, and it is convenient to be able to (e.g.) load everything loadable in a set. A prim 'isLoaded' only if there are no unloaded prims beneath it, i.e. it is stating whether the prim is "fully loaded". This is a debatable definition, but seems useful for usdview's purposes.""" if not (prim.IsActive() and (prim.IsGroup() or prim.HasPayload())): return (False, True) # XXX Note that we are potentially traversing the entire stage here. # If this becomes a performance issue, we can cast this query into C++, # cache results, etc. for p in Usd.PrimRange(prim, Usd.PrimIsActive): if not p.IsLoaded(): return (True, False) return (True, True)
def getSelectedVariants(rootPrim): ''' Returns a mapping of all the currently selected variants below a certain prim in the stage. Parameters ---------- rootPrim : Usd.Prim Returns ------- Dict[str, Dict[str, str]] { primPath : { variantSetName : selectedVariantName }} ''' selections = {} it = iter(Usd.PrimRange(rootPrim)) for prim in it: if prim.HasVariantSets(): variants = getPrimVariants(prim) selections[str(prim.GetPath())] = dict(variants) # we shouldn't need to travel below component level. if Usd.ModelAPI(prim).GetKind() == Kind.Tokens.component: it.PruneChildren() return selections
def _get_flattened_mesh_attributes(stage, scene_path, time): """Return mesh attributes flattened into a single mesh.""" prim = stage.GetPrimAtPath(scene_path) if not prim: raise ValueError(f'No prim found at "{scene_path}".') mesh_prims = [x for x in Usd.PrimRange(prim).AllPrims(prim) if UsdGeom.Mesh(x)] cur_first_idx_faces = 0 cur_first_idx_uvs = 0 vertices, vertex_indices, face_vertex_counts, uvs, face_uvs_idx, face_normals, materials = [], [], [], [], [], [], [] for mesh_prim in mesh_prims: mesh = UsdGeom.Mesh(mesh_prim) mesh_vertices = mesh.GetPointsAttr().Get(time=time) mesh_vertex_indices = mesh.GetFaceVertexIndicesAttr().Get(time=time) mesh_st = mesh.GetPrimvar('st') if mesh_st: mesh_uvs = mesh_st.Get(time=time) mesh_uv_indices = mesh_st.GetIndices(time=time) mesh_uv_interpolation = mesh_st.GetInterpolation() mesh_face_normals = mesh.GetNormalsAttr().Get(time=time) if mesh_vertices: vertices.append(torch.tensor(mesh_vertices)) if mesh_vertex_indices: face_vertex_counts.append(torch.tensor(mesh.GetFaceVertexCountsAttr().Get(time=time))) vertex_indices.append(torch.tensor(mesh_vertex_indices) + cur_first_idx_faces) if vertices: cur_first_idx_faces += len(vertices[-1]) if mesh_face_normals: face_normals.append(torch.tensor(mesh_face_normals)) if mesh_st and mesh_uvs: uvs.append(torch.tensor(mesh_uvs)) if mesh_uv_interpolation in ['vertex', 'varying']: if not mesh_uv_indices: # for vertex and varying interpolation, length of mesh_uv_indices should match # length of mesh_vertex_indices mesh_uv_indices = list(range(len(mesh_uvs))) mesh_uv_indices = torch.tensor(mesh_uv_indices) + cur_first_idx_uvs face_uvs_idx.append(mesh_uv_indices[torch.tensor(mesh_vertex_indices)]) elif mesh_uv_interpolation == 'faceVarying': if not mesh_uv_indices: # for faceVarying interpolation, length of mesh_uv_indices should match # num_faces * face_size mesh_uv_indices = list(range(len(mesh_uvs))) face_uvs_idx.append(torch.tensor(mesh_uv_indices) + cur_first_idx_uvs) else: raise NotImplementedError(f'Interpolation type {mesh_uv_interpolation} is ' 'not currently supported') cur_first_idx_uvs += len(mesh_uvs) if not vertices: warnings.warn(f'Scene object at {scene_path} contains no vertices.', UserWarning) # Only import vertices if they are defined for the entire mesh if all([v is not None for v in vertices]) and len(vertices) > 0: vertices = torch.cat(vertices) else: vertices = None # Only import vertex index and counts if they are defined for the entire mesh if all([vi is not None for vi in vertex_indices]) and len(vertex_indices) > 0: face_vertex_counts = torch.cat(face_vertex_counts) vertex_indices = torch.cat(vertex_indices) else: face_vertex_counts = None vertex_indices = None # Only import UVs if they are defined for the entire mesh if not all([uv is not None for uv in uvs]) or len(uvs) == 0: if len(uvs) > 0: warnings.warn('UVs are missing for some child meshes for prim at ' f'{scene_path}. As a result, no UVs were imported.') uvs = None face_uvs_idx = None else: uvs = torch.cat(uvs) face_uvs_idx = torch.cat(face_uvs_idx) # Only import face_normals if they are defined for the entire mesh if not all([n is not None for n in face_normals]) or len(face_normals) == 0: if len(face_normals) > 0: warnings.warn('Face normals are missing for some child meshes for ' f'prim at {scene_path}. As a result, no Face Normals were imported.') face_normals = None else: face_normals = torch.cat(face_normals) return vertices, face_vertex_counts, vertex_indices, uvs, face_uvs_idx, face_normals, materials
def iterVariablePrims(stage, root=None, lastRunData=None): ''' Populate and yield a ``VariablePrimHelper`` for every asset prim with variants on a stage. Parameters ---------- stage : Usd.Stage A Valid stage with a session layer. May be modified. root : Optional[Usd.Prim] only yield helpers for prims that are children of this prim lastRunData : Optional[Dict[str, Dict[str, str]]] The last known defaults for prim variant selections as returned by `getLastRunData()`. This is external data that cannot be gathered from the stage, but allows us to make decisions about likely types of updates. Returns ------- Iterator[VariablePrimHelper] initialized data structure for prim information. ''' lastRunData = lastRunData or {} # type: Dict[str, Dict[str, str]] sessionLayer = stage.GetSessionLayer() if not root: root = stage.GetPseudoRoot() # Could pass UsdPrimIsModel predicate as an optimization if we are # confident that this will only be acting upon assets for prim in Usd.PrimRange(root): if not prim.HasVariantSets(): continue # before checking asset name, we author a variant selection for prims # that have variants but are missing a selection so that it we at # least get a version of what exists under each variant varSets = prim.GetVariantSets() for varSetName in varSets.GetNames(): varSet = varSets.GetVariantSet(varSetName) if not varSet.GetVariantSelection() and varSet.GetVariantNames(): varSet.SetVariantSelection(varSet.GetVariantNames()[0]) assetName = usdlib.utils.getAssetName(prim) if assetName is None: continue # This may not be the best long-term solution, but we want every # prim we're managing to have a PrimSpec in the session layer so we # can easily manage the "pinned" state of a variant selection. primPath = prim.GetPath() sessionPrimSpec = sessionLayer.GetPrimAtPath(primPath) if sessionPrimSpec is None: sessionPrimSpec = Sdf.CreatePrimInLayer(sessionLayer, primPath) item = VariablePrimHelper( prim, assetName=assetName, sessionPrimSpec=sessionPrimSpec, oldDefaultVariants=lastRunData.get(str(primPath), {}), initialSelections=dict(sessionPrimSpec.variantSelections)) yield item
def setCollisionGroupFranka(stage, prim_path, group_path, is_ghost): franka_prim = stage.GetPrimAtPath(prim_path) for p in Usd.PrimRange(franka_prim): set_collision_group(stage, p.GetPath(), group_path)