Exemplo n.º 1
0
    def test_FindOrOpenDefaultResolverSearchPaths(self):
        # Set up test directory structure by exporting layers. We
        # don't use Sdf.Layer.CreateNew here to avoid populating the
        # layer registry.
        layerA_Orig = Sdf.Layer.CreateAnonymous()
        Sdf.CreatePrimInLayer(layerA_Orig, "/LayerA")
        layerA_Orig.Export("dir1/sub/searchPath.sdf")

        layerB_Orig = Sdf.Layer.CreateAnonymous()
        Sdf.CreatePrimInLayer(layerB_Orig, "/LayerB")
        layerB_Orig.Export("dir2/sub/searchPath.sdf")

        # This should fail since there is no searchPath.sdf layer in the
        # current directory and no context is bound.
        self.assertFalse(Sdf.Layer.FindOrOpen("sub/searchPath.sdf"))

        # Bind an Ar.DefaultResolverContext with dir1 as a search path.
        # Now sub/searchPath.sdf should be discovered in dir1/.
        ctx1 = Ar.DefaultResolverContext([os.path.abspath("dir1/")])
        with Ar.ResolverContextBinder(ctx1):
            layerA = Sdf.Layer.FindOrOpen("sub/searchPath.sdf")
            self.assertTrue(layerA)
            self.assertTrue(layerA.GetPrimAtPath("/LayerA"))
            self.assertEqual(layerA.identifier, "sub/searchPath.sdf")

        # Do the same as above, but with dir2 as the search path.
        # Now sub/searchPath.sdf should be discovered in dir2/.
        ctx2 = Ar.DefaultResolverContext([os.path.abspath("dir2/")])
        with Ar.ResolverContextBinder(ctx2):
            layerB = Sdf.Layer.FindOrOpen("sub/searchPath.sdf")
            self.assertTrue(layerB)
            self.assertTrue(layerB.GetPrimAtPath("/LayerB"))
            self.assertEqual(layerB.identifier, "sub/searchPath.sdf")

        # Note that layerB has the same identifier as layerA, but
        # different resolved paths.
        self.assertEqual(layerA.identifier, layerB.identifier)
        self.assertNotEqual(layerA.realPath, layerB.realPath)

        # Sdf.Layer.Find should fail since no context is bound.
        self.assertFalse(Sdf.Layer.Find("sub/searchPath.sdf"))

        # Binding the contexts from above will allow Sdf.Layer.Find
        # to find the right layers.
        with Ar.ResolverContextBinder(ctx1):
            self.assertEqual(Sdf.Layer.Find("sub/searchPath.sdf"), layerA)

        with Ar.ResolverContextBinder(ctx2):
            self.assertEqual(Sdf.Layer.Find("sub/searchPath.sdf"), layerB)

        # Anonymous layers should be discoverable regardless of context.
        anonLayerA = Sdf.Layer.CreateAnonymous()
        with Ar.ResolverContextBinder(ctx1):
            self.assertEqual(Sdf.Layer.Find(anonLayerA.identifier), anonLayerA)

        with Ar.ResolverContextBinder(ctx2):
            anonLayerB = Sdf.Layer.CreateAnonymous()
        self.assertEqual(Sdf.Layer.Find(anonLayerB.identifier), anonLayerB)
Exemplo n.º 2
0
    def test_USD_4712(self):
        # Test that activating a prim auto-includes payloads of new descendants
        # if the ancestors' payloads were already included.
        from pxr import Usd, Sdf
        l1 = Sdf.Layer.CreateAnonymous('.usd')
        l1.ImportFromString('''#usda 1.0
            (
                defaultPrim = "shot"
            )

            def "shot" {
                def "camera" {
                    def "cache"(
                        active = false
                    ){
                        def "cam" {
                        }
                    }
                }
            }

            def "cam_extra" {
                def "cache_payload" {}
            }

            def "cam" {
                def "cam_payload" {}
            }''')

        l2 = Sdf.Layer.CreateAnonymous()
        Sdf.CreatePrimInLayer(l2, '/cam_extra').specifier = Sdf.SpecifierDef
        Sdf.CreatePrimInLayer(
            l2, '/cam_extra/cache_payload').specifier = Sdf.SpecifierDef
        Sdf.CreatePrimInLayer(l2, '/cam').specifier = Sdf.SpecifierDef
        Sdf.CreatePrimInLayer(
            l2, '/cam/cam_payload').specifier = Sdf.SpecifierDef

        l1.GetPrimAtPath('/shot/camera/cache').payloadList.Prepend(
            Sdf.Payload(l2.identifier, '/cam_extra'))
        l1.GetPrimAtPath('/shot/camera/cache/cam').payloadList.Prepend(
            Sdf.Payload(l2.identifier, '/cam'))
        
        stage = Usd.Stage.Open(l1)
        stage.SetEditTarget(stage.GetSessionLayer())
        cachePrim = stage.GetPrimAtPath('/shot/camera/cache')
    
        # Activating the cachePrim should auto-load the cam payload since its
        # nearest loadable ancestor is loaded.
        cachePrim.SetActive(True)
        cachePayloadPrim = stage.GetPrimAtPath(
            '/shot/camera/cache/cache_payload')
        self.assertTrue(cachePayloadPrim.IsValid())
        cameraPayloadPrim = stage.GetPrimAtPath(
            '/shot/camera/cache/cam/cam_payload')
        self.assertTrue(cameraPayloadPrim.IsValid())
Exemplo n.º 3
0
        def _TestLayerReload(fmt):
            # First, test case where the reloaded layer is in the
            # stage's root LayerStack.
            with Tf.NamedTemporaryFile(suffix='.%s' % fmt) as l1name, \
                 Tf.NamedTemporaryFile(suffix='.%s' % fmt) as l2name:

                l1 = Sdf.Layer.CreateAnonymous()
                Sdf.CreatePrimInLayer(l1, '/foo')
                l1.Export(l1name.name)

                l2 = Sdf.Layer.CreateAnonymous()
                Sdf.CreatePrimInLayer(l2, '/bar')
                l2.Export(l2name.name)

                s = Usd.Stage.Open(l1name.name)
                assert s.GetPrimAtPath('/foo')
                assert not s.GetPrimAtPath('/bar')

                shutil.copyfile(l2name.name, l1name.name)
                # Force layer reload to avoid issues where mtime does not
                # change after file copy due to low resolution.
                s.GetRootLayer().Reload(force=True)

                assert not s.GetPrimAtPath('/foo')
                assert s.GetPrimAtPath('/bar')

            # Now test the case where the reloaded layer is in a referenced
            # LayerStack.
            with Tf.NamedTemporaryFile(suffix='.%s' % fmt) as rootLayerName, \
                 Tf.NamedTemporaryFile(suffix='.%s' % fmt) as refLayerName:

                refLayer = Sdf.Layer.CreateAnonymous()
                Sdf.CreatePrimInLayer(refLayer, '/foo/bar')
                refLayer.Export(refLayerName.name)

                rootLayer = Sdf.Layer.CreateAnonymous()
                rootPrim = Sdf.CreatePrimInLayer(rootLayer, '/foo')
                rootPrim.referenceList.Add(
                    Sdf.Reference(refLayerName.name, '/foo'))
                rootLayer.Export(rootLayerName.name)

                s = Usd.Stage.Open(rootLayerName.name)
                assert s.GetPrimAtPath('/foo/bar')

                del refLayer.GetPrimAtPath('/foo').nameChildren['bar']
                refLayer.Export(refLayerName.name)
                Sdf.Layer.Find(refLayerName.name).Reload(force=True)
                assert s.GetPrimAtPath('/foo')
                assert not s.GetPrimAtPath('/foo/bar')
Exemplo n.º 4
0
    def test_DefaultPrimBasics(self):
        # create a layer, set DefaultPrim, then reference it.
        for fmt in allFormats:
            targLyr = Sdf.Layer.CreateAnonymous('DefaultPrimBasics.' + fmt)

            def makePrim(name, attrDefault):
                primSpec = Sdf.CreatePrimInLayer(targLyr, name)
                primSpec.specifier = Sdf.SpecifierDef
                attr = Sdf.AttributeSpec(primSpec, 'attr',
                                         Sdf.ValueTypeNames.Double)
                attr.default = attrDefault

            makePrim('target1', 1.234)
            makePrim('target2', 2.345)

            targLyr.defaultPrim = 'target1'

            # create a new layer and reference the first.
            srcLyr = Sdf.Layer.CreateAnonymous('DefaultPrimBasics-new.' + fmt)
            srcPrimSpec = Sdf.CreatePrimInLayer(srcLyr, '/source')

            # create a stage with srcLyr.
            stage = Usd.Stage.Open(srcLyr)
            prim = stage.GetPrimAtPath('/source')
            self.assertTrue(prim)

            # author a prim-path-less reference to the targetLyr.
            prim.GetReferences().AddReference(targLyr.identifier)

            # should now pick up 'attr' from across the reference.
            self.assertEqual(prim.GetAttribute('attr').Get(), 1.234)
Exemplo n.º 5
0
    def __init__(self, prim, variantTuples, setAsDefaults=True):
        '''
        Create variant sets and variants that don't exist and get the
        variant contexts.

        Parameters
        ----------
        prim : Usd.Prim
        variantTuples: Iterable[Tuple[str, str]]
            iterable of tuples mapping variantSetName to variantName that can
            represent a hierarchy of nested variants.
        setAsDefaults : bool
            Set the variants in variantTuples as the default variant 
            in the editContext layer
        '''
        self.contexts = []
        self.setAsDefaults = setAsDefaults
        self.originalSelections = []
        self.prim = prim
        self.variantTuples = variantTuples

        self.stage = self.prim.GetStage()
        self.sessionLayer = self.stage.GetSessionLayer()
        self.spec = self.stage.GetEditTarget().GetLayer().GetPrimAtPath(
            prim.GetPath())
        if not self.spec:
            self.spec = Sdf.CreatePrimInLayer(
                self.stage.GetEditTarget().GetLayer(), prim.GetPrimPath())
Exemplo n.º 6
0
def main():
    """Run the main execution of the current script."""
    source = Sdf.Layer.CreateAnonymous()
    root = source.pseudoRoot

    prim = Sdf.PrimSpec(root, "SomePrim", Sdf.SpecifierDef)
    variant_set = Sdf.VariantSetSpec(prim, "SomeVariantSet")
    variant = Sdf.VariantSpec(variant_set, "SomeVariant")
    Sdf.PrimSpec(variant.primSpec, "InnerPrim", Sdf.SpecifierDef)

    destination = Sdf.Layer.CreateAnonymous()
    Sdf.CopySpec(source, "/SomePrim{SomeVariantSet=SomeVariant}", destination,
                 "/DestinationPrim")

    # XXX : Notice that we have to call `CreatePrimInLayer` here but
    # we didn't need to run it in the last example. That's because
    # in this example, the parent Prim path "/Another" doesn't
    # exist yet and has to be created before data can be copied to
    # "/Another/DestinationPrim".
    #
    # In the previous example, "/" is the parent of "/DestinationPrim".
    # And "/" always exists. So we didn't need to call
    # `CreatePrimInLayer`. But generally, you usually should.
    #
    destination_prim = "/Another/DestinationPrim"
    Sdf.CreatePrimInLayer(destination, destination_prim)
    Sdf.CopySpec(
        source,
        "/SomePrim{SomeVariantSet=SomeVariant}",
        destination,
        destination_prim,
    )

    print(destination.ExportToString())
Exemplo n.º 7
0
    def test_Basic(self):
        rootLayer = Sdf.Layer.FindOrOpen('bug70951/root.sdf')
        refLayer = Sdf.Layer.FindOrOpen('bug70951/JoyGroup.sdf')

        pcpCache = Pcp.Cache(Pcp.LayerStackIdentifier(rootLayer))

        # Compute the prim index for the Sim scope under JoyGroup. This index
        # should consist of two nodes: the direct node and the reference node.
        # Since there is no spec for the Sim scope in the root layer, the root node
        # should be marked as such.
        (primIndex, errors) = \
            pcpCache.ComputePrimIndex('/World/anim/chars/JoyGroup/Sim')
        self.assertEqual(len(errors), 0)
        self.assertEqual(primIndex.primStack,
                         [refLayer.GetPrimAtPath('/JoyGroup/Sim')])
        self.assertFalse(primIndex.rootNode.hasSpecs)

        # Now create an empty over for the Sim scope in the root layer and verify
        # that the prim index sees this new spec after change processing.
        with Pcp._TestChangeProcessor(pcpCache):
            emptyOver = \
                Sdf.CreatePrimInLayer(rootLayer, '/World/anim/chars/JoyGroup/Sim')
            self.assertTrue(emptyOver.IsInert())

        (primIndex, errors) = \
            pcpCache.ComputePrimIndex('/World/anim/chars/JoyGroup/Sim')
        self.assertEqual(len(errors), 0)
        self.assertEqual(primIndex.primStack, [
            rootLayer.GetPrimAtPath('/World/anim/chars/JoyGroup/Sim'),
            refLayer.GetPrimAtPath('/JoyGroup/Sim')
        ])
        self.assertTrue(primIndex.rootNode.hasSpecs)
Exemplo n.º 8
0
    def test_153956(self):
        from pxr import Sdf

        # Create a crate-backed .usd file and populate it with an
        # attribute connection. These files do not store specs for
        # targets/connections, so there will be an entry in the
        # connectionChildren list but no corresponding spec.
        layer = Sdf.Layer.CreateAnonymous(".usd")
        primSpec = Sdf.CreatePrimInLayer(layer, "/Test")
        attrSpec = Sdf.AttributeSpec(primSpec, "attr", Sdf.ValueTypeNames.Float)

        # -- Adding item to prependedItems list..."
        attrSpec.connectionPathList.prependedItems.append("/Test.prependedItem")

        # Transfer the contents of the crate-backed .usd file into an
        # memory-backed .usda file. These file *do* store specs for
        # targets/connections.
        newLayer = Sdf.Layer.CreateAnonymous(".usda")
        newLayer.TransferContent(layer)

        primSpec = newLayer.GetPrimAtPath("/Test")
        attrSpec = primSpec.properties["attr"]

        # Adding an item to the explicitItems list changes to listOp to
        # explicit mode, but does not clear any existing connectionChildren.
        attrSpec.connectionPathList.explicitItems.append("/Test.explicitItem")

        # Prior to the fix, this caused a failed verify b/c an entry exists in
        # the connectionChildren list for which there is no corresponding spec.
        primSpec.name = "Test2"
Exemplo n.º 9
0
    def test_EmptySublayerChanges(self):
        subLayer1 = Sdf.Layer.CreateAnonymous()
        primSpec = Sdf.CreatePrimInLayer(subLayer1, '/Test')

        rootLayer = Sdf.Layer.CreateAnonymous()
        rootLayer.subLayerPaths.append(subLayer1.identifier)

        layerStackId = Pcp.LayerStackIdentifier(rootLayer)
        pcp = Pcp.Cache(layerStackId)

        (pi, err) = pcp.ComputePrimIndex('/Test')
        self.assertFalse(err)
        self.assertEqual(pi.primStack, [primSpec])

        subLayer2 = Sdf.Layer.CreateAnonymous()
        self.assertTrue(subLayer2.empty)

        # Adding an empty sublayer should not require recomputing any
        # prim indexes or change their prim stacks.
        with Pcp._TestChangeProcessor(pcp):
            rootLayer.subLayerPaths.insert(0, subLayer2.identifier)

        pi = pcp.FindPrimIndex('/Test')
        self.assertTrue(pi)
        self.assertEqual(pi.primStack, [primSpec])

        # Same with deleting an empty sublayer.
        with Pcp._TestChangeProcessor(pcp):
            del rootLayer.subLayerPaths[0]

        pi = pcp.FindPrimIndex('/Test')
        self.assertTrue(pi)
        self.assertEqual(pi.primStack, [primSpec])
Exemplo n.º 10
0
        def _TestRemapping(fieldName):
            layer = Sdf.Layer.CreateAnonymous()
            srcPrimSpec = Sdf.CreatePrimInLayer(layer, "/Root/Instance")

            listOp = Sdf.PathListOp()
            listOp.explicitItems = ["/GlobalClass", "/Root/LocalClass"]
            srcPrimSpec.SetInfo(fieldName, listOp)

            # Copy the root prim spec. The paths in the listOp on the child
            # prim that are beneath the root will be remapped to the new
            # destination.
            self.assertTrue(Sdf.CopySpec(layer, "/Root", layer, "/RootCopy"))

            expectedListOp = Sdf.PathListOp()
            expectedListOp.explicitItems = \
                ["/GlobalClass", "/RootCopy/LocalClass"]
            self.assertEqual(
                layer.GetPrimAtPath("/RootCopy/Instance").GetInfo(fieldName),
                expectedListOp)

            # Copy the child prim spec on which the inherit or specializes
            # list is authored. Since the paths in the listOp are outside the
            # root of the copy operation, none of them will be remapped.
            self.assertTrue(
                Sdf.CopySpec(layer, "/Root/Instance", layer, "/InstanceCopy"))

            expectedListOp = listOp
            self.assertEqual(
                layer.GetPrimAtPath("/InstanceCopy").GetInfo(fieldName),
                expectedListOp)
Exemplo n.º 11
0
    def test_Basic(self):
        rootLayer = Sdf.Layer.FindOrOpen('bug90706/root.sdf')
        pcpCache = Pcp.Cache(Pcp.LayerStackIdentifier(rootLayer))

        (index, err) = pcpCache.ComputePrimIndex('/Sarah/EmptyPrim')
        self.assertTrue(index)
        self.assertEqual(len(err), 0)

        # This prim index should only contain the root node; the variant
        # arc to /Sarah{displayColor=red}EmptyPrim will have been culled
        # because there's no prim spec there.
        self.assertEqual(len(index.rootNode.children), 0)

        with Pcp._TestChangeProcessor(pcpCache):
            p = Sdf.CreatePrimInLayer(rootLayer,
                                      '/Sarah{displayColor=red}EmptyPrim')

        # The addition of the inert prim should have caused the prim index
        # to be blown, because it needs to be re-computed to accommodate the
        # no-longer-inert variant node.
        self.assertFalse(pcpCache.FindPrimIndex('/Sarah/EmptyPrim'))
        (index, err) = pcpCache.ComputePrimIndex('/Sarah/EmptyPrim')
        self.assertTrue(index)
        self.assertEqual(len(err), 0)

        # There should now be a variant arc for /Sarah{displayColor=red}EmptyPrim
        # in the local layer stack.
        self.assertEqual(len(index.rootNode.children), 1)
        self.assertEqual(index.rootNode.children[0].arcType,
                         Pcp.ArcTypeVariant)
        self.assertEqual(index.rootNode.children[0].layerStack,
                         index.rootNode.layerStack)
        self.assertEqual(index.rootNode.children[0].path,
                         '/Sarah{displayColor=red}EmptyPrim')
Exemplo n.º 12
0
def TestNewPayloadAutoLoading():
    print 'TestNewPayloadAutoLoading'
    
    # Test that switching a variant that introduces a payload causes the payload
    # to be included if the parent is loaded, and vice versa.
    rootLayer = Sdf.Layer.CreateAnonymous()
    payloadLayer = Sdf.Layer.CreateAnonymous()

    Sdf.CreatePrimInLayer(rootLayer, '/main')
    Sdf.CreatePrimInLayer(payloadLayer, '/parent/child')

    stage = Usd.Stage.Open(rootLayer)
    main = stage.GetPrimAtPath('/main')
    pvs = main.GetVariantSets().AddVariantSet('payload_vset')

    withPayload = pvs.AddVariant('with_payload')
    withoutPayload = pvs.AddVariant('without_payload')

    pvs.SetVariantSelection('with_payload')
    with pvs.GetVariantEditContext():
        main.GetPayloads().AddPayload(payloadLayer.identifier, '/parent')

    pvs.SetVariantSelection('without_payload')

    # Now open the stage load all, we shouldn't have /main/child.
    stage = Usd.Stage.Open(rootLayer, load=Usd.Stage.LoadAll)
    assert stage.GetPrimAtPath('/main')
    assert not stage.GetPrimAtPath('/main/child')

    # Switching the selection should cause the payload to auto-load.
    stage.GetPrimAtPath('/main').GetVariantSet(
        'payload_vset').SetVariantSelection('with_payload')
    main = stage.GetPrimAtPath('/main')
    assert main and main.IsLoaded()
    assert stage.GetPrimAtPath('/main/child')

    # Open the stage again, but with load-none.
    stage = Usd.Stage.Open(rootLayer, load=Usd.Stage.LoadNone)
    assert stage.GetPrimAtPath('/main')
    assert not stage.GetPrimAtPath('/main/child')

    # Switching the selection should NOT cause the payload to auto-load.
    stage.GetPrimAtPath('/main').GetVariantSet(
        'payload_vset').SetVariantSelection('with_payload')
    main = stage.GetPrimAtPath('/main')
    assert main and not main.IsLoaded()
    assert not stage.GetPrimAtPath('/main/child')
Exemplo n.º 13
0
    def test_156222(self):
        from pxr import Sdf, Usd

        # Test that removing all instances for a prototype prim and adding a new
        # instance with the same instancing key as the prototype causes the new
        # instance to be assigned to the prototype.
        l = Sdf.Layer.CreateAnonymous('.usda')
        Sdf.CreatePrimInLayer(l, '/Ref')

        # The bug is non-deterministic because of threaded composition,
        # but it's easier to reproduce with more instance prims.
        numInstancePrims = 50
        instancePrimPaths = [Sdf.Path('/Instance_{}'.format(i))
                             for i in range(numInstancePrims)]
        for path in instancePrimPaths:
            instancePrim = Sdf.CreatePrimInLayer(l, path)
            instancePrim.instanceable = True
            instancePrim.referenceList.Add(Sdf.Reference(primPath = '/Ref'))

        nonInstancePrim = Sdf.CreatePrimInLayer(l, '/NonInstance')
        nonInstancePrim.referenceList.Add(Sdf.Reference(primPath = '/Ref'))

        s = Usd.Stage.Open(l)
        self.assertEqual(len(s.GetPrototypes()), 1)

        # Check that the prototype prim is using one of the instanceable prim
        # index for its source.
        prototype = s.GetPrototypes()[0]
        prototypePath = prototype.GetPath()
        self.assertIn(prototype._GetSourcePrimIndex().rootNode.path,
                      instancePrimPaths)

        # In a single change block, uninstance all of the instanceable prims,
        # but mark the non-instance prim as instanceable.
        with Sdf.ChangeBlock():
            for path in instancePrimPaths:
                l.GetPrimAtPath(path).instanceable = False
            nonInstancePrim.instanceable = True

        # This should not cause a new prototype prim to be generated; instead, 
        # the prototype prim should now be using the newly-instanced prim index 
        # as its source.
        prototype = s.GetPrototypes()[0]
        self.assertEqual(prototype.GetPath(), prototypePath)
        self.assertEqual(prototype._GetSourcePrimIndex().rootNode.path,
                         nonInstancePrim.path)
Exemplo n.º 14
0
    def test_ReloadAfterSetIdentifier(self):
        layer = Sdf.Layer.CreateNew('TestReloadAfterSetIdentifier.sdf')

        # CreateNew creates a new empty layer on disk. Modifying it and
        # then reloading should reset the layer back to its original
        # empty state.
        prim = Sdf.CreatePrimInLayer(layer, '/test')
        self.assertTrue(layer.Reload())
        self.assertFalse(prim)

        # However, changing a layer's identifier does not immediately
        # save the layer under its new filename. Because of that, there's
        # nothing for Reload to reload from, so it does nothing.
        prim = Sdf.CreatePrimInLayer(layer, '/test')
        layer.identifier = 'TestReloadAfterSetIdentifier_renamed.sdf'
        self.assertFalse(layer.Reload())
        self.assertTrue(prim)
Exemplo n.º 15
0
 def test_CreatePrimInLayer(self):
     layer = Sdf.Layer.CreateAnonymous()
     self.assertFalse(layer.GetPrimAtPath("/root"))
     rootSpec = Sdf.CreatePrimInLayer(layer, '/root')
     # Must return new prim spec
     self.assertTrue(rootSpec)
     # Prim spec must match what we retrieve via namespace
     self.assertEqual(rootSpec, layer.GetPrimAtPath('/root'))
     with self.assertRaises(Tf.ErrorException):
         # Must fail with non-prim path
         Sdf.CreatePrimInLayer(layer, '/root.property')
     # Must be able to create variants
     variantSpec = Sdf.CreatePrimInLayer(layer, '/root{x=y}')
     self.assertTrue(variantSpec)
     self.assertEqual(variantSpec, layer.GetPrimAtPath('/root{x=y}'))
     # New variant names use prepend
     self.assertTrue('x' in rootSpec.variantSetNameList.prependedItems)
     self.assertTrue(len(rootSpec.variantSetNameList.addedItems) == 0)
Exemplo n.º 16
0
def _prepare_prim_specs_with_sdf(layer, paths):
    """Create PrimSpecs using a Sdf Layer."""
    for path in paths:
        prim_spec = Sdf.CreatePrimInLayer(layer, path)
        prim_spec.specifier = Sdf.SpecifierDef

    parent = layer.GetPrimAtPath("SomePrim/AnotherInnerPrim")
    for index in range(ITERATIONS):
        Sdf.PrimSpec(parent, "IndexedPrim{}".format(index), Sdf.SpecifierDef)
Exemplo n.º 17
0
    def test_InvalidLayerReloadChange(self):
        s = Usd.Stage.CreateNew('LayerReloadChange.usda')

        # Create a prim with a reference to a non-existent layer.
        # This should result in a composition error.
        prim = s.DefinePrim('/ModelReference')
        prim.GetReferences().AddReference(assetPath='./Model.usda',
                                          primPath='/Model')

        s.Save()

        # Create a new layer at the referenced path and reload the referencing
        # stage. This should cause the layer to be opened and a resync for the
        # referencing prim.
        try:
            layer = Sdf.Layer.CreateNew('Model.usda')
            Sdf.CreatePrimInLayer(layer, '/Model')

            class OnReload(object):
                def __init__(self, stage, fixture):
                    super(OnReload, self).__init__()
                    self.receivedNotice = False
                    self.fixture = fixture
                    self.stage = stage
                    self._key = Tf.Notice.Register(Usd.Notice.ObjectsChanged,
                                                   self._HandleChange, stage)

                def _HandleChange(self, notice, sender):
                    self.receivedNotice = True
                    self.fixture.assertEqual(notice.GetStage(), self.stage)
                    self.fixture.assertEqual(notice.GetResyncedPaths(),
                                             [Sdf.Path('/ModelReference')])
                    self.fixture.assertFalse(
                        notice.HasChangedFields('/ModelReference'))
                    self.fixture.assertEqual(
                        notice.GetChangedFields('/ModelReference'), [])
                    self.fixture.assertEqual(notice.GetChangedInfoOnlyPaths(),
                                             [])

            l = OnReload(s, self)
            s.Reload()

            # Should have received a resync notice and composed the referenced
            # /Model prim into /ModelReference.
            self.assertTrue(l.receivedNotice)
            self.assertEqual(
                s.GetPrimAtPath('/ModelReference').GetPrimStack()[1],
                layer.GetPrimAtPath('/Model'))

        finally:
            # Make sure to remove Model.usda so subsequent test runs don't
            # pick it up, otherwise test case won't work.
            try:
                os.remove('Model.usda')
            except:
                pass
Exemplo n.º 18
0
 def test_141718(self):
     from pxr import Sdf
     crateLayer = Sdf.Layer.CreateAnonymous('.usdc')
     prim = Sdf.CreatePrimInLayer(crateLayer, '/Prim')
     rel = Sdf.RelationshipSpec(prim, 'myRel', custom=False)
     rel.targetPathList.explicitItems.append('/Prim2')
     asciiLayer = Sdf.Layer.CreateAnonymous('.usda')
     asciiLayer.TransferContent(crateLayer)
     p = asciiLayer.GetPrimAtPath('/Prim')
     p.RemoveProperty(p.relationships['myRel'])
Exemplo n.º 19
0
            def _CreateLayers(rootLayerName):
                f = lambda base: base + '.' + fmt
                rootLayer = Sdf.Layer.CreateNew(f(rootLayerName))
                subLayer = Sdf.Layer.CreateNew(f(rootLayerName + '_sublayer'))
                anonLayer = Sdf.Layer.CreateAnonymous(f(rootLayerName + '_anon'))
                refLayer = Sdf.Layer.CreateNew(f(rootLayerName + '_reflayer'))

                # Author some scene description so all layers start as dirty.
                rootLayer.subLayerPaths.append(subLayer.identifier)
                rootLayer.subLayerPaths.append(anonLayer.identifier)

                primPath = "/" + rootLayerName
                subLayerPrim = Sdf.CreatePrimInLayer(subLayer, primPath)
                subLayerPrim.referenceList.Add(
                    Sdf.Reference(refLayer.identifier, primPath))
                Sdf.CreatePrimInLayer(refLayer, primPath)

                Sdf.CreatePrimInLayer(anonLayer, primPath)

                return rootLayer, subLayer, anonLayer, refLayer
Exemplo n.º 20
0
def as_sdf():
    """Run the main execution of the current script."""
    layer = Sdf.Layer.CreateAnonymous()
    prim_spec = Sdf.CreatePrimInLayer(layer, "/root")
    prim_spec.specifier = Sdf.SpecifierDef
    attribute_spec = Sdf.AttributeSpec(prim_spec, "some_name", Sdf.ValueTypeNames.Int)
    attribute_spec.custom = True
    attribute_spec.default = 8

    layer.SetTimeSample(attribute_spec.path, 10.5, 9)

    print(layer.ExportToString())
Exemplo n.º 21
0
    def test_InertPrimChanges(self):
        refLayer = Sdf.Layer.CreateAnonymous()
        refParentSpec = Sdf.PrimSpec(refLayer, 'Parent', Sdf.SpecifierDef)
        refChildSpec = Sdf.PrimSpec(refParentSpec, 'Child', Sdf.SpecifierDef)

        rootLayer = Sdf.Layer.CreateAnonymous()
        parentSpec = Sdf.PrimSpec(rootLayer, 'Parent', Sdf.SpecifierOver)
        parentSpec.referenceList.Add(
            Sdf.Reference(refLayer.identifier, '/Parent'))

        pcp = Pcp.Cache(Pcp.LayerStackIdentifier(rootLayer))

        # Adding an empty over to a prim that already exists (has specs)
        # is an insignificant change.
        (pi, err) = pcp.ComputePrimIndex('/Parent/Child')
        self.assertEqual(err, [])
        with Pcp._TestChangeProcessor(pcp) as cp:
            Sdf.CreatePrimInLayer(rootLayer, '/Parent/Child')
            self.assertEqual(cp.GetSignificantChanges(), [])
            self.assertEqual(cp.GetSpecChanges(), ['/Parent/Child'])
            self.assertEqual(cp.GetPrimChanges(), [])

        # Adding an empty over as the first spec for a prim is a
        # a significant change, even if we haven't computed a prim index
        # for that path yet.
        with Pcp._TestChangeProcessor(pcp) as cp:
            Sdf.CreatePrimInLayer(rootLayer, '/Parent/NewChild')
            self.assertEqual(cp.GetSignificantChanges(), ['/Parent/NewChild'])
            self.assertEqual(cp.GetSpecChanges(), [])
            self.assertEqual(cp.GetPrimChanges(), [])

        (pi, err) = pcp.ComputePrimIndex('/Parent/NewChild2')
        self.assertEqual(err, [])
        with Pcp._TestChangeProcessor(pcp) as cp:
            Sdf.CreatePrimInLayer(rootLayer, '/Parent/NewChild2')
            self.assertEqual(cp.GetSignificantChanges(), ['/Parent/NewChild2'])
            self.assertEqual(cp.GetSpecChanges(), [])
            self.assertEqual(cp.GetPrimChanges(), [])
Exemplo n.º 22
0
def main():
    """Run the main execution of the current script."""
    layer = Sdf.Layer.CreateAnonymous()

    message = "Plugin Metadata was not sourced correctly"
    primspec = Sdf.CreatePrimInLayer(layer, "/SomePrim")

    assert (
        "my_custom_double" in primspec.GetMetaDataInfoKeys()
    ), message

    assert layer.pseudoRoot.GetFallbackForInfo("another_metadata") == Vt.DoubleArray(
        [5, 13]
    ), message
Exemplo n.º 23
0
        def _setupStage():
            # Create a prim at root layer
            rootLayer = self._stage.GetRootLayer()
            Sdf.CreatePrimInLayer(rootLayer, "/root")

            # Create session layer with prim
            sessionLayer = self._stage.GetSessionLayer()
            Sdf.CreatePrimInLayer(sessionLayer, "/root/prim01")

            # Create anonymous sublayers
            sublayer01 = Sdf.Layer.CreateAnonymous()
            Sdf.CreatePrimInLayer(sublayer01, "/root/subprim01")
            sublayer02 = Sdf.Layer.CreateAnonymous()
            Sdf.CreatePrimInLayer(sublayer02, "/root/subprim02")

            # TODO easy way to add testing for recursive restoration
            # sublayer03 = Sdf.Layer.CreateAnonymous()
            # Sdf.CreatePrimInLayer(sublayer02, "/root/subprim02/subsubprim03")
            # sublayer02.subLayerPaths = [sublayer03.identifier]

            # Add sublayers to session layer
            sessionLayer.subLayerPaths = [
                sublayer01.identifier, sublayer02.identifier
            ]
Exemplo n.º 24
0
 def _TestRoundTrippingValue(self, typeName, value):
     # Create a layer with custom attribute of this type, set its value,
     # export it to a string, reimport it from a string and assert that it
     # round-tripped the value correctly.
     layer = Sdf.Layer.CreateAnonymous()
     prim = Sdf.CreatePrimInLayer(layer, '/test')
     attrSpec = Sdf.AttributeSpec(prim, 'testAttr',
                                  Sdf.ValueTypeNames.Find(typeName))
     attrSpec.default = value
     layerAsString = layer.ExportToString()
     # Now create a new layer and import it.
     layer = Sdf.Layer.CreateAnonymous()
     layer.ImportFromString(layerAsString)
     self.assertEqual(
         layer.GetAttributeAtPath('/test.testAttr').default, value)
Exemplo n.º 25
0
    def test_ReferenceRemapping(self):
        layer = Sdf.Layer.CreateAnonymous()
        srcPrimSpec = Sdf.CreatePrimInLayer(layer, "/Root/Child")
        srcPrimSpec.referenceList.explicitItems = [
            # External reference
            Sdf.Reference("./test.sdf", "/Ref"),
            # External sub-root reference
            Sdf.Reference("./test.sdf", "/Root/Ref"),
            # Internal reference
            Sdf.Reference("", "/Ref"),
            # Internal sub-root reference
            Sdf.Reference("", "/Root/Ref")
        ]

        # Copy the root prim spec and verify that the internal sub-root
        # references on the child prim that target a prim beneath /Root are
        # remapped to /RootCopy.
        self.assertTrue(Sdf.CopySpec(layer, "/Root", layer, "/RootCopy"))

        expectedListOp = Sdf.ReferenceListOp()
        expectedListOp.explicitItems = [
            Sdf.Reference("./test.sdf", "/Ref"),
            Sdf.Reference("./test.sdf", "/Root/Ref"),
            Sdf.Reference("", "/Ref"),
            Sdf.Reference("", "/RootCopy/Ref")
        ]

        self.assertEqual(
            layer.GetPrimAtPath("/RootCopy/Child").GetInfo("references"),
            expectedListOp)

        # Copy the child prim spec. Since all of the internal sub-root
        # references point outside the root of the copy operation, none
        # of them will be remapped.
        self.assertTrue(Sdf.CopySpec(layer, "/Root/Child", layer,
                                     "/ChildCopy"))

        expectedListOp = Sdf.ReferenceListOp()
        expectedListOp.explicitItems = [
            Sdf.Reference("./test.sdf", "/Ref"),
            Sdf.Reference("./test.sdf", "/Root/Ref"),
            Sdf.Reference("", "/Ref"),
            Sdf.Reference("", "/Root/Ref")
        ]

        self.assertEqual(
            layer.GetPrimAtPath("/ChildCopy").GetInfo("references"),
            expectedListOp)
Exemplo n.º 26
0
def getStage(usdFile, variantOverrides=None, loadAll=False, stageCache=None):
    '''
    Open a stage from a USD file path, optionally populating the session layer
    with variant overrides.

    Parameters
    ----------
    usdFile : str
    variantOverrides : Optional[Dict[str, Dict[str, str]]]
        Dict[primPath, Dict[variantSetName, selectedVariant]] as returned
        by `getVariantSelections()`
    loadAll : Optional[bool]
    stageCache : Optional[Usd.StageCache]

    Returns
    -------
    Usd.Stage
    '''
    # TODO: Implement PopulationMask support
    if stageCache is not None:
        assert isinstance(stageCache, Usd.StageCache)
        ctxArg = stageCache
    else:
        ctxArg = Usd.BlockStageCaches

    with Usd.StageCacheContext(ctxArg):
        loadSet = Usd.Stage.LoadAll if loadAll else Usd.Stage.LoadNone
        if variantOverrides:
            rootLayer = Sdf.Layer.FindOrOpen(usdFile)
            assert rootLayer
            sessionLayer = Sdf.Layer.CreateAnonymous()
            for primPath, variantSelections in variantOverrides.iteritems():
                sdfPath = Sdf.Path(primPath)
                primSpec = Sdf.CreatePrimInLayer(sessionLayer,
                                                 sdfPath.GetPrimPath())
                # FIXME: If any of these selections no longer exists or is
                # invalid it could result in a prim not being found when we
                # populate the asset manager. Either take performance hit to
                # check, or add a way to clean out stale selections.
                primSpec.variantSelections.update(variantSelections)
            stage = Usd.Stage.Open(rootLayer, sessionLayer, loadSet)
            stage.SetEditTarget(sessionLayer)
        else:
            stage = Usd.Stage.Open(usdFile, loadSet)
            assert stage
            stage.SetEditTarget(stage.GetSessionLayer())
    return stage
Exemplo n.º 27
0
    def test_CreatePrimInLayer(self):
        layer = Sdf.Layer.CreateAnonymous()

        self.assertTrue(Sdf.CreatePrimInLayer(layer, 'foo'))
        self.assertTrue(Sdf.CreatePrimInLayer(layer, 'foo/bar'))
        self.assertTrue(Sdf.CreatePrimInLayer(layer, 'foo/bar/baz'))
        self.assertTrue(layer.GetPrimAtPath('/foo'))
        self.assertTrue(layer.GetPrimAtPath('/foo/bar'))
        self.assertTrue(layer.GetPrimAtPath('/foo/bar/baz'))
        self.assertTrue(Sdf.CreatePrimInLayer(layer, '/boo'))
        self.assertTrue(Sdf.CreatePrimInLayer(layer, '/boo/bar'))
        self.assertTrue(Sdf.CreatePrimInLayer(layer, '/boo/bar/baz'))
        self.assertTrue(layer.GetPrimAtPath('/boo'))
        self.assertTrue(layer.GetPrimAtPath('/boo/bar'))
        self.assertTrue(layer.GetPrimAtPath('/boo/bar/baz'))
        self.assertEqual(Sdf.CreatePrimInLayer(layer, '.'),
                         layer.GetPrimAtPath('/'))
        with self.assertRaises(Tf.ErrorException):
            Sdf.CreatePrimInLayer(layer, '..')
        with self.assertRaises(Tf.ErrorException):
            Sdf.CreatePrimInLayer(layer, '../..')

        self.assertTrue(Sdf.JustCreatePrimInLayer(layer, 'goo'))
        self.assertTrue(Sdf.JustCreatePrimInLayer(layer, 'goo/bar'))
        self.assertTrue(Sdf.JustCreatePrimInLayer(layer, 'goo/bar/baz'))
        self.assertTrue(layer.GetPrimAtPath('/goo'))
        self.assertTrue(layer.GetPrimAtPath('/goo/bar'))
        self.assertTrue(layer.GetPrimAtPath('/goo/bar/baz'))
        self.assertTrue(Sdf.JustCreatePrimInLayer(layer, '/zoo'))
        self.assertTrue(Sdf.JustCreatePrimInLayer(layer, '/zoo/bar'))
        self.assertTrue(Sdf.JustCreatePrimInLayer(layer, '/zoo/bar/baz'))
        self.assertTrue(layer.GetPrimAtPath('/zoo'))
        self.assertTrue(layer.GetPrimAtPath('/zoo/bar'))
        self.assertTrue(layer.GetPrimAtPath('/zoo/bar/baz'))
        self.assertTrue(Sdf.JustCreatePrimInLayer(layer, '.'))
        with self.assertRaises(Tf.ErrorException):
            Sdf.JustCreatePrimInLayer(layer, '..')
        with self.assertRaises(Tf.ErrorException):
            Sdf.JustCreatePrimInLayer(layer, '../..')
Exemplo n.º 28
0
    def test_LayersWithEquivalentPaths(self):
        # Test that FindOrOpen and Find return the same layer when
        # given different paths that should point to the same location.
        if not os.path.isdir("eqPaths"):
            os.makedirs("eqPaths")

        # These paths should all be equivalent.
        testPaths = [
            "",
            os.getcwd(), "eqPaths/../.",
            os.path.join(os.getcwd(), "eqPaths/../.")
        ]

        # Iterate over all permutations of these paths calling FindOrOpen
        # or Find on each one and verifying that they all return the same
        # layer.
        i = 0
        for paths in itertools.permutations(testPaths):
            i += 1
            testLayerName = "FindOrOpenEqPaths_{}.sdf".format(i)
            testLayer = Sdf.Layer.CreateAnonymous()
            Sdf.CreatePrimInLayer(testLayer, "/TestLayer_{}".format(i))
            self.assertTrue(testLayer.Export(testLayerName))

            paths = [os.path.join(p, testLayerName) for p in paths]
            firstLayer = Sdf.Layer.FindOrOpen(paths[0])
            self.assertTrue(
                firstLayer,
                "Unable to open {} (from {})".format(paths[0], paths))

            for p in paths:
                testLayer = Sdf.Layer.FindOrOpen(p)
                self.assertTrue(testLayer,
                                "Unable to open {} (from {})".format(p, paths))
                self.assertEqual(
                    firstLayer, testLayer,
                    "Layer opened with {} not the same as layer opened "
                    "with {}".format(p, paths[0]))

                testLayer = Sdf.Layer.Find(p)
                self.assertTrue(testLayer,
                                "Unable to find {} (from {})".format(p, paths))
                self.assertEqual(
                    firstLayer, testLayer,
                    "Layer found with {} not the same as layer opened "
                    "with {}".format(p, paths[0]))
Exemplo n.º 29
0
    def test_Bug160419(self):
        for fmt in allFormats:
            payloadLayer = Sdf.Layer.CreateAnonymous("payload."+fmt)
            Sdf.CreatePrimInLayer(payloadLayer, "/Payload/Cube")

            rootLayer = Sdf.Layer.CreateAnonymous("root."+fmt)
            refPrim = Sdf.PrimSpec(rootLayer, "Ref", Sdf.SpecifierDef)
            refPrim = Sdf.PrimSpec(refPrim, "Child", Sdf.SpecifierDef)
            refPrim.payloadList.Prepend(
                Sdf.Payload(payloadLayer.identifier, "/Payload"))

            rootPrim = Sdf.PrimSpec(rootLayer, "Root", Sdf.SpecifierDef)
            rootPrim.referenceList.Prepend(
                Sdf.Reference(primPath="/Ref/Child"))

            stage = Usd.Stage.Open(rootLayer)
            self.assertEqual(set(stage.GetLoadSet()),
                             set([Sdf.Path("/Ref/Child"), Sdf.Path("/Root")]))
            self.assertTrue(stage.GetPrimAtPath("/Root").IsLoaded())
            self.assertTrue(stage.GetPrimAtPath("/Ref/Child").IsLoaded())
Exemplo n.º 30
0
    def test_DefaultPrimChangeProcessing(self):
        for fmt in allFormats:
            # create a layer, set DefaultPrim, then reference it.
            targLyr = Sdf.Layer.CreateAnonymous(
                'DefaultPrimChangeProcessing.' + fmt)

            def makePrim(name, attrDefault):
                primSpec = Sdf.CreatePrimInLayer(targLyr, name)
                primSpec.specifier = Sdf.SpecifierDef
                attr = Sdf.AttributeSpec(primSpec, 'attr',
                                         Sdf.ValueTypeNames.Double)
                attr.default = attrDefault

            makePrim('target1', 1.234)
            makePrim('target2', 2.345)

            targLyr.defaultPrim = 'target1'

            # create a new layer and reference the first.
            srcLyr = Sdf.Layer.CreateAnonymous(
                'DefaultPrimChangeProcessing-new.' + fmt)
            srcPrimSpec = Sdf.CreatePrimInLayer(srcLyr, '/source')
            srcPrimSpec.referenceList.Add(Sdf.Reference(targLyr.identifier))

            # create a stage with srcLyr.
            stage = Usd.Stage.Open(srcLyr)

            prim = stage.GetPrimAtPath('/source')
            self.assertEqual(prim.GetAttribute('attr').Get(), 1.234)

            # Clear defaultPrim.  This should issue a composition
            # error, and fail to pick up the attribute from the referenced prim.
            targLyr.ClearDefaultPrim()
            self.assertTrue(prim)
            self.assertFalse(prim.GetAttribute('attr'))

            # Change defaultPrim to other target.  This should pick up the reference
            # again, but to the new prim with the new attribute value.
            targLyr.defaultPrim = 'target2'
            self.assertTrue(prim)
            self.assertEqual(prim.GetAttribute('attr').Get(), 2.345)