def test_ComputeInstancerCount(self): stage = Usd.Stage.Open('instancer.usda') unset = UsdGeom.PointInstancer.Get(stage, '/UnsetIndices') blocked = UsdGeom.PointInstancer.Get(stage, '/BlockedIndices') empty = UsdGeom.PointInstancer.Get(stage, '/EmptyIndices') timeSampled = UsdGeom.PointInstancer.Get(stage, '/TimeSampledIndices') timeSampledAndDefault = UsdGeom.PointInstancer.Get(stage, '/TimeSampledAndDefaultIndices') testTimeSamples = [ (unset, Usd.TimeCode.EarliestTime(), 0), (blocked, Usd.TimeCode.EarliestTime(), 0), (empty, Usd.TimeCode.EarliestTime(), 0), (timeSampled, Usd.TimeCode.EarliestTime(), 3), (timeSampledAndDefault, Usd.TimeCode.EarliestTime(), 5)] testDefaults = [ (unset, 0), (blocked, 0), (empty, 0), (timeSampled, 0), (timeSampledAndDefault, 4)] for (schema, timeCode, expected) in testTimeSamples: self.assertTrue(schema) self.assertEqual(schema.GetInstanceCount(timeCode), expected) for (schema, expected) in testDefaults: self.assertTrue(schema) self.assertEqual(schema.GetInstanceCount(), expected) invalid = UsdGeom.PointInstancer(Usd.Prim()) self.assertFalse(invalid) with self.assertRaises(RuntimeError): self.assertEqual(invalid.GetInstanceCount(), 0) with self.assertRaises(RuntimeError): self.assertEqual(invalid.GetInstanceCount( Usd.TimeCode.EarliestTime()), 0)
def test_ComputeCurveCount(self): stage = Usd.Stage.Open('basisCurves.usda') unset = UsdGeom.BasisCurves.Get(stage, '/UnsetVertexCounts') blocked = UsdGeom.BasisCurves.Get(stage, '/BlockedVertexCounts') empty = UsdGeom.BasisCurves.Get(stage, '/EmptyVertexCounts') timeSampled = UsdGeom.BasisCurves.Get(stage, '/TimeSampledVertexCounts') timeSampledAndDefault = UsdGeom.BasisCurves.Get( stage, '/TimeSampledAndDefaultVertexCounts') testTimeSamples = [(unset, Usd.TimeCode.EarliestTime(), 0), (blocked, Usd.TimeCode.EarliestTime(), 0), (empty, Usd.TimeCode.EarliestTime(), 0), (timeSampled, Usd.TimeCode.EarliestTime(), 3), (timeSampledAndDefault, Usd.TimeCode.EarliestTime(), 5)] testDefaults = [(unset, 0), (blocked, 0), (empty, 0), (timeSampled, 0), (timeSampledAndDefault, 4)] for (schema, timeCode, expected) in testTimeSamples: self.assertTrue(schema) self.assertEqual(schema.GetCurveCount(timeCode), expected) for (schema, expected) in testDefaults: self.assertTrue(schema) self.assertEqual(schema.GetCurveCount(), expected) invalid = UsdGeom.BasisCurves(Usd.Prim()) self.assertFalse(invalid) with self.assertRaises(RuntimeError): self.assertEqual(invalid.ComputeCurveCount(), 0) with self.assertRaises(RuntimeError): self.assertEqual( invalid.ComputeCurveCount(Usd.TimeCode.EarliestTime()), 0)
def getPrimFromSceneItem(item): if ufeUtils.ufeFeatureSetVersion() >= 2: rawItem = item.getRawAddress() prim = mayaUsd.ufe.getPrimFromRawItem(rawItem) return prim else: return Usd.Prim()
def test_PseudoRoot(self): for fmt in allFormats: s = Usd.Stage.CreateInMemory('PseudoRoot.%s' % fmt) w = s.DefinePrim('/World') p = s.GetPrimAtPath('/') self.assertTrue(p.IsPseudoRoot()) self.assertFalse(Usd.Prim().IsPseudoRoot()) self.assertFalse(w.IsPseudoRoot()) self.assertTrue(w.GetParent().IsPseudoRoot()) self.assertFalse(p.GetParent().IsPseudoRoot())
def test_Apply(self): s = Usd.Stage.CreateInMemory('AppliedSchemas.usd') root = s.DefinePrim('/hello') self.assertEqual([], root.GetAppliedSchemas()) # Check duplicates UsdGeom.MotionAPI.Apply(root) self.assertEqual(['MotionAPI'], root.GetAppliedSchemas()) UsdGeom.MotionAPI.Apply(root) self.assertEqual(['MotionAPI'], root.GetAppliedSchemas()) # Ensure duplicates aren't picked up UsdGeom.ModelAPI.Apply(root) self.assertEqual(['MotionAPI', 'GeomModelAPI'], root.GetAppliedSchemas()) # Verify that we get exceptions but don't crash when applying to the # null prim. with self.assertRaises(Tf.ErrorException): self.assertFalse(UsdGeom.MotionAPI.Apply(Usd.Prim())) with self.assertRaises(Tf.ErrorException): self.assertFalse(UsdGeom.ModelAPI.Apply(Usd.Prim()))
def ResetPrim(self, prim): self.beginResetModel() if prim is None: self.__valid = False self.__prim = Usd.Prim() else: self.__valid = True self.__prim = prim self.__listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.__OnObjectsChanged, self.__prim.GetStage()) if self.__prim: self.__primTree = self._GetPrimTree(prim) else: self.__primTree = [] self.endResetModel()
def createPrimAndAttributes(stage, primPath, mayaReferencePath, mayaNamespace, mayaAutoEdit): try: prim = stage.DefinePrim(primPath.path, 'MayaReference') except (Tf.ErrorException): return Usd.Prim() mayaReferenceAttr = prim.CreateAttribute('mayaReference', Sdf.ValueTypeNames.Asset) mayaReferenceAttr.Set(mayaReferencePath) mayaNamespaceAttr = prim.CreateAttribute('mayaNamespace', Sdf.ValueTypeNames.String) mayaNamespaceAttr.Set(mayaNamespace) mayaAutoEditAttr = prim.CreateAttribute('mayaAutoEdit', Sdf.ValueTypeNames.Bool) mayaAutoEditAttr.Set(mayaAutoEdit) return prim
def ResetPrim(self, prim): # type: (Usd.Prim) -> None """ Parameters ---------- prim : Usd.Prim """ self.beginResetModel() if prim is None: self._valid = False self._prim = Usd.Prim() else: self._valid = True self._prim = prim self._listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._OnObjectsChanged, self._prim.GetStage()) if self._prim: self._primTree = self._GetPrimTree(prim) else: self._primTree = [] self.endResetModel()
def test_USD_5045(self): # USD-5045 is github issue #753 from pxr import Usd nullPrim = Usd.Prim() with self.assertRaises(RuntimeError): nullPrim.IsDefined()
def test_AppliedSchemas(self): self.assertTrue(Usd.ModelAPI().IsAPISchema()) self.assertTrue(Usd.ClipsAPI().IsAPISchema()) self.assertTrue(Usd.CollectionAPI().IsAPISchema()) self.assertFalse(Usd.ModelAPI().IsAppliedAPISchema()) self.assertFalse(Usd.ClipsAPI().IsAppliedAPISchema()) self.assertTrue(Usd.CollectionAPI().IsAppliedAPISchema()) self.assertTrue(Usd.CollectionAPI().IsMultipleApplyAPISchema()) self.assertTrue(Usd.CollectionAPI().GetSchemaType() == Usd.SchemaType.MultipleApplyAPI) self.assertTrue(Usd.CollectionAPI().GetSchemaType() != Usd.SchemaType.SingleApplyAPI) self.assertTrue( Usd.ModelAPI().GetSchemaType() == Usd.SchemaType.NonAppliedAPI) self.assertTrue( Usd.ClipsAPI().GetSchemaType() == Usd.SchemaType.NonAppliedAPI) # Verify that we an exception but don't crash when applying to the # null prim. with self.assertRaises(Tf.ErrorException): self.assertFalse(Usd.CollectionAPI.Apply(Usd.Prim(), "root")) for fmt in allFormats: sessionLayer = Sdf.Layer.CreateNew("SessionLayer.%s" % fmt) s = Usd.Stage.CreateInMemory('AppliedSchemas.%s' % fmt, sessionLayer) s.SetEditTarget(Usd.EditTarget(s.GetRootLayer())) world = s.OverridePrim('/world') self.assertEqual([], world.GetAppliedSchemas()) rootCollAPI = Usd.CollectionAPI.Apply(world, "root") self.assertTrue(rootCollAPI) world = rootCollAPI.GetPrim() self.assertTrue(world) self.assertTrue(world.HasAPI(Usd.CollectionAPI)) # The schemaType that's passed into HasAPI must derive from # UsdAPISchemaBase and must not be UsdAPISchemaBase. with self.assertRaises(RuntimeError): world.HasAPI(Usd.Typed) with self.assertRaises(RuntimeError): world.HasAPI(Usd.APISchemaBase) with self.assertRaises(RuntimeError): world.HasAPI(Usd.ModelAPI) # Try calling HasAPI a random TfType that isn't a derivative of # SchemaBase. with self.assertRaises(RuntimeError): world.HasAPI(Sdf.ListOpType) self.assertEqual(['CollectionAPI:root'], world.GetAppliedSchemas()) # Switch the edit target to the session layer and test bug 156929 s.SetEditTarget(Usd.EditTarget(s.GetSessionLayer())) sessionCollAPI = Usd.CollectionAPI.Apply(world, "session") self.assertTrue(sessionCollAPI) self.assertEqual(['CollectionAPI:session', 'CollectionAPI:root'], world.GetAppliedSchemas()) self.assertTrue(world.HasAPI(Usd.CollectionAPI)) # Ensure duplicates aren't picked up anotherSessionCollAPI = Usd.CollectionAPI.Apply(world, "session") self.assertTrue(anotherSessionCollAPI) self.assertEqual(['CollectionAPI:session', 'CollectionAPI:root'], world.GetAppliedSchemas()) # Add a duplicate in the root layer and ensure that there are no # duplicates in the composed result. s.SetEditTarget(Usd.EditTarget(s.GetRootLayer())) rootLayerSessionCollAPI = Usd.CollectionAPI.Apply(world, "session") self.assertTrue(rootLayerSessionCollAPI) self.assertEqual(['CollectionAPI:session', 'CollectionAPI:root'], world.GetAppliedSchemas())
def test_GetAtPath(self): """Tests accessing UsdObjects of various types on the same stage as a prim.""" for fmt in allFormats: stage = Usd.Stage.CreateInMemory('GetAtPath.%s' % fmt) child = stage.DefinePrim("/Parent/Child") grandchild = stage.DefinePrim("/Parent/Child/Grandchild") sibling = stage.DefinePrim("/Parent/Sibling") x = sibling.CreateAttribute("x", Sdf.ValueTypeNames.Int) y = grandchild.CreateRelationship("y") # Double check axioms about prim validity self.assertFalse(Usd.Prim()) self.assertTrue(child) self.assertTrue(grandchild) self.assertTrue(sibling) self.assertTrue(y) self.assertTrue(x) self.assertFalse(stage.GetPrimAtPath(Sdf.Path.emptyPath)) # Test relative prim paths self.assertEqual(child.GetPrimAtPath("../Sibling"), sibling) self.assertEqual(child.GetPrimAtPath("Grandchild"), grandchild) self.assertEqual(child.GetPrimAtPath(".."), child.GetParent()) # Test absolute prim paths self.assertEqual(child.GetPrimAtPath("/Parent/Sibling"), sibling) self.assertEqual(child.GetPrimAtPath("../Sibling"), child.GetObjectAtPath("../Sibling")) # Test invalid paths self.assertFalse(child.GetPrimAtPath("../InvalidPath")) # Test relative propeties self.assertEqual(child.GetRelationshipAtPath("Grandchild.y"), y) self.assertEqual(child.GetAttributeAtPath("../Sibling.x"), x) self.assertEqual(child.GetPropertyAtPath("Grandchild.y"), y) self.assertEqual(child.GetPropertyAtPath("../Sibling.x"), x) # Test Absolute propeties self.assertEqual( child.GetRelationshipAtPath("/Parent/Child/Grandchild.y"), y) self.assertEqual(child.GetAttributeAtPath("/Parent/Sibling.x"), x) self.assertEqual( child.GetPropertyAtPath("/Parent/Child/Grandchild.y"), y) self.assertEqual(child.GetPropertyAtPath("/Parent/Sibling.x"), x) # Test invalid paths self.assertFalse(child.GetPropertyAtPath(".z")) self.assertFalse(child.GetRelationshipAtPath(".z")) self.assertFalse(child.GetAttributeAtPath(".z")) # Test valid paths but invalid types self.assertFalse(child.GetPrimAtPath("/Parent/Child/Grandchild.y")) self.assertFalse(child.GetPrimAtPath("/Parent/Sibling.x")) self.assertFalse( child.GetAttributeAtPath("/Parent/Child/Grandchild.y")) self.assertFalse(child.GetRelationshipAtPath("/Parent/Sibling.x")) self.assertFalse( child.GetAttributeAtPath("/Parent/Child/Grandchild")) self.assertFalse(child.GetRelationshipAtPath("/Parent/Sibling")) # Test that empty paths don't raise exceptions # NOTE-- this is intentionally different than SdfPrimSpec # for symmetry with UsdStage's API self.assertFalse(child.GetPrimAtPath(Sdf.Path.emptyPath)) self.assertFalse(child.GetObjectAtPath(Sdf.Path.emptyPath)) self.assertFalse(child.GetPropertyAtPath(Sdf.Path.emptyPath)) self.assertFalse(child.GetAttributeAtPath(Sdf.Path.emptyPath)) self.assertFalse(child.GetRelationshipAtPath(Sdf.Path.emptyPath)) # Verify type deduction self.assertTrue( isinstance(child.GetObjectAtPath("../Sibling"), Usd.Prim)) self.assertTrue( isinstance(child.GetObjectAtPath("../Sibling.x"), Usd.Attribute)) self.assertTrue( isinstance(child.GetObjectAtPath("Grandchild.y"), Usd.Relationship)) self.assertTrue( isinstance(child.GetPropertyAtPath("../Sibling.x"), Usd.Attribute)) self.assertTrue( isinstance(child.GetPropertyAtPath("Grandchild.y"), Usd.Relationship))
def TestAtCurTime(stage, bboxCache): p = stage.GetPrimAtPath("/parent/primWithLocalXform") assert bboxCache.ComputeWorldBound(p) == bboxCache.ComputeWorldBound(p) bboxCache.SetIncludedPurposes([UsdGeom.Tokens.default_]) print print "Untransformed bound:", p print bboxCache.ComputeUntransformedBound(p) print print bboxCache.ComputeUntransformedBound(p).ComputeAlignedRange() print # The baseline is predicated on TfDebug output. We do not care to clutter # it up with the duplicate computation that calling the UsdGeom.Imageable # API will induce, so here and below we disable TfDebug output while # testing Tf.Debug.SetDebugSymbolsByName("USDGEOM_BBOX", 0) db = UsdGeom.Imageable(p).ComputeUntransformedBound( bboxCache.GetTime(), UsdGeom.Tokens.default_) AssertBBoxesClose(bboxCache.ComputeUntransformedBound(p), db, "Untransformed") Tf.Debug.SetDebugSymbolsByName("USDGEOM_BBOX", 1) print print "Local bound:", p print bboxCache.ComputeLocalBound(p) print print bboxCache.ComputeLocalBound(p).ComputeAlignedRange() print Tf.Debug.SetDebugSymbolsByName("USDGEOM_BBOX", 0) db = UsdGeom.Imageable(p).ComputeLocalBound(bboxCache.GetTime(), UsdGeom.Tokens.default_) AssertBBoxesClose(bboxCache.ComputeLocalBound(p), db, "Local") Tf.Debug.SetDebugSymbolsByName("USDGEOM_BBOX", 1) print print "World bound:", p print bboxCache.ComputeWorldBound(p) print print bboxCache.ComputeWorldBound(p).ComputeAlignedRange() print Tf.Debug.SetDebugSymbolsByName("USDGEOM_BBOX", 0) db = UsdGeom.Imageable(p).ComputeWorldBound(bboxCache.GetTime(), UsdGeom.Tokens.default_) AssertBBoxesClose(bboxCache.ComputeWorldBound(p), db, "World") Tf.Debug.SetDebugSymbolsByName("USDGEOM_BBOX", 1) print pp = stage.GetPrimAtPath(str(p.GetPath()) + "/InvisibleChild") print "Invisible Bound:", pp print bboxCache.ComputeWorldBound(pp) print print bboxCache.ComputeWorldBound(pp).ComputeAlignedRange() print Tf.Debug.SetDebugSymbolsByName("USDGEOM_BBOX", 0) db = UsdGeom.Imageable(pp).ComputeWorldBound(bboxCache.GetTime(), UsdGeom.Tokens.default_) AssertBBoxesClose(bboxCache.ComputeWorldBound(pp), db, "Invis World") Tf.Debug.SetDebugSymbolsByName("USDGEOM_BBOX", 1) print print "Visit Guides:", p bboxCache.SetIncludedPurposes([UsdGeom.Tokens.guide]) assert bboxCache.GetIncludedPurposes() == [UsdGeom.Tokens.guide] print bboxCache.ComputeWorldBound(p) print print bboxCache.ComputeWorldBound(p).ComputeAlignedRange() print Tf.Debug.SetDebugSymbolsByName("USDGEOM_BBOX", 0) db = UsdGeom.Imageable(p).ComputeWorldBound(bboxCache.GetTime(), UsdGeom.Tokens.guide) AssertBBoxesClose(bboxCache.ComputeWorldBound(p), db, "World Guide") Tf.Debug.SetDebugSymbolsByName("USDGEOM_BBOX", 1) print print "Visit Render:", p bboxCache.SetIncludedPurposes([UsdGeom.Tokens.render]) assert bboxCache.GetIncludedPurposes() == [UsdGeom.Tokens.render] print bboxCache.ComputeWorldBound(p) print print bboxCache.ComputeWorldBound(p).ComputeAlignedRange() print Tf.Debug.SetDebugSymbolsByName("USDGEOM_BBOX", 0) db = UsdGeom.Imageable(p).ComputeWorldBound(bboxCache.GetTime(), UsdGeom.Tokens.render) AssertBBoxesClose(bboxCache.ComputeWorldBound(p), db, "World Render") Tf.Debug.SetDebugSymbolsByName("USDGEOM_BBOX", 1) print print "Visit Proxy:", p bboxCache.SetIncludedPurposes([UsdGeom.Tokens.proxy]) assert bboxCache.GetIncludedPurposes() == [UsdGeom.Tokens.proxy] print bboxCache.ComputeWorldBound(p) print print bboxCache.ComputeWorldBound(p).ComputeAlignedRange() print Tf.Debug.SetDebugSymbolsByName("USDGEOM_BBOX", 0) db = UsdGeom.Imageable(p).ComputeWorldBound(bboxCache.GetTime(), UsdGeom.Tokens.proxy) AssertBBoxesClose(bboxCache.ComputeWorldBound(p), db, "World Proxy") # Test multi-purpose bboxCache.SetIncludedPurposes( [UsdGeom.Tokens.default_, UsdGeom.Tokens.proxy, UsdGeom.Tokens.render]) assert bboxCache.GetIncludedPurposes() == [ UsdGeom.Tokens.default_, UsdGeom.Tokens.proxy, UsdGeom.Tokens.render ] db = UsdGeom.Imageable(p).ComputeWorldBound(bboxCache.GetTime(), UsdGeom.Tokens.default_, UsdGeom.Tokens.proxy, UsdGeom.Tokens.render) AssertBBoxesClose(bboxCache.ComputeWorldBound(p), db, "Multi-purpose") Tf.Debug.SetDebugSymbolsByName("USDGEOM_BBOX", 1) p = stage.GetPrimAtPath("/Rotated") print print "Visit Rotated:", p bboxCache.SetIncludedPurposes([UsdGeom.Tokens.default_]) assert bboxCache.GetIncludedPurposes() == [UsdGeom.Tokens.default_] print bboxCache.ComputeWorldBound(p) print print bboxCache.ComputeWorldBound(p).ComputeAlignedRange() print Tf.Debug.SetDebugSymbolsByName("USDGEOM_BBOX", 0) db = UsdGeom.Imageable(p).ComputeWorldBound(bboxCache.GetTime(), UsdGeom.Tokens.default_) AssertBBoxesClose(bboxCache.ComputeWorldBound(p), db, "Rotated") Tf.Debug.SetDebugSymbolsByName("USDGEOM_BBOX", 1) p = stage.GetPrimAtPath("/Rotated/Rotate135AndTranslate/Rot45") print print "Visit Rotated:", p bboxCache.SetIncludedPurposes([UsdGeom.Tokens.default_]) assert bboxCache.GetIncludedPurposes() == [UsdGeom.Tokens.default_] print bboxCache.ComputeWorldBound(p) print print bboxCache.ComputeWorldBound(p).ComputeAlignedRange() print Tf.Debug.SetDebugSymbolsByName("USDGEOM_BBOX", 0) db = UsdGeom.Imageable(p).ComputeWorldBound(bboxCache.GetTime(), UsdGeom.Tokens.default_) AssertBBoxesClose(bboxCache.ComputeWorldBound(p), db, "Rotated Twice") Tf.Debug.SetDebugSymbolsByName("USDGEOM_BBOX", 1) p = Usd.Prim() assert not p try: bboxCache.ComputeWorldBound(p) except RuntimeError: pass else: assert False, 'Failed to raise expected exception.' try: bboxCache.ComputeLocalBound(p) except RuntimeError: pass else: assert False, 'Failed to raise expected exception.' try: bboxCache.ComputeUntransformedBound(p) except RuntimeError: pass else: assert False, 'Failed to raise expected exception.'
def _test_Populate(self): """Tests for correctness in interpretation of inherited bindings, as computed through Populate().""" testFile = "populate.usda" stage = Usd.Stage.Open(testFile) rootPath = "/InheritedBindings" cache = UsdSkel.Cache() root = UsdSkel.Root(stage.GetPrimAtPath(rootPath)) print "Expect warnings about invalid skel:skeletonInstance targets" self.assertTrue(cache.Populate(root)) def _GetSkelQuery(path): return cache.GetSkelQuery(stage.GetPrimAtPath(path)) def _GetInheritedSkelQuery(path): return cache.GetInheritedSkelQuery(stage.GetPrimAtPath(path)) def _GetSkelPath(skelQuery): return skelQuery.GetSkeleton().GetPrim().GetPath() def _GetAnimPath(skelQuery): return skelQuery.GetAnimQuery().GetPrim().GetPath() skel = _GetSkelQuery(rootPath + "/Model1") self.assertEqual(_GetSkelPath(skel), Sdf.Path("/Skel1")) assert not skel.GetAnimQuery() # an animationSource does not itself define a skel binding. # bindings are associated with skel:skeleton rels only! skel = _GetSkelQuery(rootPath + "/Model1/A") assert not skel skel = _GetSkelQuery(rootPath + "/Model1/A/B") self.assertEqual(_GetSkelPath(skel), Sdf.Path("/Skel2")) self.assertEqual(_GetAnimPath(skel), Sdf.Path("/Anim1")) skel = _GetSkelQuery(rootPath + "/Model1/C") self.assertEqual(_GetSkelPath(skel), Sdf.Path("/Skel3")) self.assertEqual(_GetAnimPath(skel), Sdf.Path("/Anim2")) # Inherited skel queries? self.assertEqual( _GetSkelPath(_GetInheritedSkelQuery(rootPath + "/Model1/A/B/Gprim")), _GetSkelPath(_GetSkelQuery(rootPath + "/Model1/A/B"))) self.assertEqual( _GetSkelPath(_GetInheritedSkelQuery(rootPath + "/Model1/A/B")), _GetSkelPath(_GetSkelQuery(rootPath + "/Model1/A/B"))) # Scope with no bound skel. assert not _GetSkelQuery(rootPath + "/Model2") assert not cache.GetSkelQuery(Usd.Prim()) # Scope with a bound skel, but whose animation source is inactive. skel = _GetSkelQuery(rootPath + "/Model3/SkelWithInactiveAnim") self.assertEqual(_GetSkelPath(skel), Sdf.Path("/Skel1")) assert not skel.GetAnimQuery() # Inheritance of skel:xform? skel = _GetSkelQuery(rootPath + "/IndirectBindings/Instance") self.assertEqual(skel.GetPrim().GetPath(), Sdf.Path(rootPath + "/IndirectBindings/Instance")) indirectSkel = _GetSkelQuery(rootPath + "/IndirectBindings/Indirect") self.assertEqual(indirectSkel.GetPrim().GetPath(), Sdf.Path(rootPath + "/IndirectBindings/Instance")) self.assertEqual(_GetSkelPath(indirectSkel), Sdf.Path("/Skel1")) nestedSkel = _GetSkelQuery(rootPath + "/IndirectBindings/Indirect/Instance") self.assertEqual( nestedSkel.GetPrim().GetPath(), Sdf.Path(rootPath + "/IndirectBindings/Indirect/Instance")) self.assertEqual(_GetSkelPath(nestedSkel), Sdf.Path("/Skel2")) self.assertFalse(_GetSkelQuery(rootPath + "/IndirectBindings/Illegal")) def _GetSkinningQuery(path): return cache.GetSkinningQuery(stage.GetPrimAtPath(path)) # Make sure some scopes are not being treated as skinning targets. nonSkinnablePaths = (rootPath + "/Model1/NonRigidScope1", rootPath + "/Model1/NonRigidScope2", rootPath + "/Model1/RigidScopeParent") for path in nonSkinnablePaths: assert not _GetSkinningQuery(path) query = _GetSkinningQuery(rootPath + "/Model1/NonRigidScope1/A") assert query assert query.IsRigidlyDeformed() assert query.GetMapper() self.assertEquals(query.GetJointOrder(), Vt.TokenArray(["A", "B", "C"])) query = _GetSkinningQuery(rootPath + "/Model1/NonRigidScope1/B") assert query assert not query.IsRigidlyDeformed() assert not query.GetMapper() query = _GetSkinningQuery(rootPath + "/Model1/NonRigidScope2/A") assert query assert query.IsRigidlyDeformed() assert query.GetMapper() self.assertEquals(query.GetJointOrder(), Vt.TokenArray(["A", "B", "C"])) query = _GetSkinningQuery(rootPath + "/Model1/NonRigidScope2/B") assert query assert query.IsRigidlyDeformed() assert not query.GetMapper() # TODO: When adding support for rigid deformation of intermediate # xformables, Model1/RigidScopeParent/RigidScope should be treated # as being skinnable. assert _GetSkinningQuery(rootPath + "/Model1/RigidScopeParent/RigidScope/A") assert _GetSkinningQuery(rootPath + "/Model1/RigidScopeParent/RigidScope/B")
def createMayaReferencePrim( ufePathStr, mayaReferencePath, mayaNamespace, mayaReferencePrimName=mayaRefUtils.defaultMayaReferencePrimName(), groupPrim=None, variantSet=None, mayaAutoEdit=kDefaultEditAsMayaData): '''Create a Maya reference prim and optional group prim parented to the argument path. Optionally create a variant set and name and placed the edits inside that variant. Naming of Maya Reference prim is supported, otherwise default name is used. The group prim is optional. The variant set and name are optional Parameters: ----------- ufePathStr : str : Ufe PathString of parent prim to add Maya Reference mayaReferencePath : str : File path of Maya Reference (for attribute) mayaNamespace : str : Namespace (for attribute) mayaReferencePrimName : str [optional] : Name for the Maya Reference prim groupPrim : tuple(str,str,str) [optional] : The Group prim Name, Type & Kind to create Note: the name is optional and will be auto-computed if empty or not provided. Note: Type and Kind are both mandatory, but Kind is allowed to be empty string. variantSet : tuple(str,str) [optional] : The Variant Set Name and Variant Name to create Return: ------- The Usd prim of the newly created Maya Reference or an invalid prim if there is an error. ''' # Make sure the prim name is valid and doesn't already exist. parentPrim = mayaUsd.ufe.ufePathToPrim(ufePathStr) # There are special conditions when we are given the ProxyShape gateway node. ufePath = ufe.PathString.path(ufePathStr) isGateway = (ufePath.nbSegments() == 1) # Were we given a Group prim to create? groupPrimName = None groupPrimType = None groupPrimKind = None if groupPrim: if (len(groupPrim) == 2): groupPrimType, groupPrimKind = groupPrim elif (len(groupPrim) == 3): groupPrimName, groupPrimType, groupPrimKind = groupPrim # Make sure the input Group prim name doesn't exist already # and validate the input name. # Note: it is allowed to be input as empty in which case a default is used. if groupPrimName: checkGroupPrimName = mayaUsd.ufe.uniqueChildName( parentPrim, groupPrimName) if checkGroupPrimName != groupPrimName: errorMsgFormat = getMayaUsdLibString( 'kErrorGroupPrimExists') errorMsg = cmds.format(errorMsgFormat, stringArg=(groupPrimName, ufePathStr)) om.MGlobal.displayError(errorMsg) return Usd.Prim() groupPrimName = Tf.MakeValidIdentifier(checkGroupPrimName) # If the group prim was either not provided or empty we use a default name. if not groupPrimName: groupPrimName = getDefaultGroupPrimName(parentPrim, mayaNamespace) # When the input is a gateway we cannot have in variant unless group is also given. if isGateway and variantSet and not groupPrimName: errorMsg = getMayaUsdLibString('kErrorCannotAddToProxyShape') om.MGlobal.displayError(errorMsg) return Usd.Prim() # Make sure the input Maya Reference prim name doesn't exist already # and validate the input name. # Note: if we are given a group prim to create, then we know that the # Maya Reference prim name will be unique since it will be the # only child (of the newly created group prim). checkName = mayaUsd.ufe.uniqueChildName( parentPrim, mayaReferencePrimName) if groupPrim is None else mayaReferencePrimName if checkName != mayaReferencePrimName: errorMsgFormat = getMayaUsdLibString('kErrorMayaRefPrimExists') errorMsg = cmds.format(errorMsgFormat, stringArg=(mayaReferencePrimName, ufePathStr)) om.MGlobal.displayError(errorMsg) return Usd.Prim() validatedPrimName = Tf.MakeValidIdentifier(checkName) # Extract the USD path segment from the UFE path and append the Maya # reference prim to it. parentPath = str(ufePath.segments[1]) if ufePath.nbSegments() > 1 else '' stage = mayaUsd.ufe.getStage(ufePathStr) # Optionally insert a Group prim as a parent of the Maya reference prim. groupPrim = None if groupPrimName: groupPath = Sdf.AssetPath(parentPath + '/' + groupPrimName) try: groupPrim = stage.DefinePrim(groupPath.path, groupPrimType) except (Tf.ErrorException): groupPrim = Usd.Prim() if not groupPrim.IsValid(): errorMsgFormat = getMayaUsdLibString('kErrorCreatingGroupPrim') errorMsg = cmds.format(errorMsgFormat, stringArg=(ufePathStr)) om.MGlobal.displayError(errorMsg) return Usd.Prim() if groupPrimKind: model = Usd.ModelAPI(groupPrim) model.SetKind(groupPrimKind) if groupPrim: primPath = Sdf.AssetPath(groupPrim.GetPath().pathString + '/' + validatedPrimName) else: primPath = Sdf.AssetPath(parentPath + '/' + validatedPrimName) # Were we given a Variant Set to create? variantSetName = None variantName = None if variantSet and (len(variantSet) == 2): variantSetName, variantName = variantSet if variantSetName and variantName: validatedVariantSetName = Tf.MakeValidIdentifier(variantSetName) validatedVariantName = Tf.MakeValidIdentifier(variantName) # If we created a group prim add the variant set there, otherwise add it # to the prim that corresponds to the input ufe path. variantPrim = groupPrim if groupPrim else mayaUsd.ufe.ufePathToPrim( ufePathStr) vset = variantPrim.GetVariantSet(validatedVariantSetName) vset.AddVariant(validatedVariantName) vset.SetVariantSelection(validatedVariantName) with vset.GetVariantEditContext(): # Now all of our subsequent edits will go "inside" the # 'variantName' variant of 'variantSetName'. prim = createPrimAndAttributes(stage, primPath, mayaReferencePath, mayaNamespace, mayaAutoEdit) else: prim = createPrimAndAttributes(stage, primPath, mayaReferencePath, mayaNamespace, mayaAutoEdit) if prim is None or not prim.IsValid(): errorMsgFormat = getMayaUsdLibString('kErrorCreatingMayaRefPrim') errorMsg = cmds.format(errorMsgFormat, stringArg=(ufePathStr)) om.MGlobal.displayError(errorMsg) return Usd.Prim() return prim
def test_Errors(self): with self.assertRaises(Tf.CppException): Usd._UnsafeGetStageForTesting(Usd.Prim())
def testNullPrim(self): ''' Invalid prims raise an exception. ''' with self.assertRaises(Tf.ErrorException): Usd.PrimDefaultPredicate(Usd.Prim())