示例#1
0
 def BasicTest(path, elements):
     assert path.IsAbsolutePath() == testAbsolute[testIndex]
     assert path.IsPropertyPath() == testProperty[testIndex]
     prefixes = Sdf._PathElemsToPrefixes(path.IsAbsolutePath(), elements)
     assert path.GetPrefixes() == prefixes
     assert path == eval(repr(path))
     assert Sdf.Path.IsValidPathString(str(path))
示例#2
0
def _CheckPath(path, path2, parentPath, pathStr, pathElems, pathFlags, name, targetPath):
    # Check equality with another one constructed the same way
    assert path == path2

    # Check properties
    assert path.pathString == pathStr
    assert path.name == name
    assert path.pathElementCount == len(pathElems)
    assert path.targetPath == targetPath

    # Check queries
    assert path.IsAbsolutePath() == pathStr.startswith("/")
    assert path.IsPrimPath() == (((pathFlags & PrimType) or (path == Sdf.Path.reflexiveRelativePath)) != 0 )
    assert path.IsRootPrimPath() == ((pathFlags & PrimType) != 0 and (len(pathElems) is 1))
    assert path.IsPropertyPath() == ((pathFlags & PropertyType) != 0)
    if (pathFlags & NamespacedPropertyType) != 0:
        assert path.IsNamespacedPropertyPath() == ((pathFlags & NamespacedPropertyType) != 0)
    if (pathFlags & PrimPropertyType) != 0:
        assert path.IsPrimPropertyPath() == ((pathFlags & PrimPropertyType) != 0)
    if (pathFlags & RelationalAttributeType) != 0:
        assert path.IsRelationalAttributePath() == ((pathFlags & RelationalAttributeType) != 0)
        assert path.IsTargetPath() == ((pathFlags & TargetType) != 0)
        assert path.IsMapperPath() == ((pathFlags & MapperType) != 0)
        assert path.IsMapperArgPath() == ((pathFlags & MapperArgType) != 0)
        assert path.IsExpressionPath() == ((pathFlags & ExpressionType) != 0)

    if pathFlags & (TargetType | MapperType | MapperArgType):
        assert path.ContainsTargetPath()

    # Check path elements
    prefixes = Sdf._PathElemsToPrefixes(path.IsAbsolutePath(), pathElems)
    assert path.GetPrefixes() == prefixes

    # Check parent
    assert path.GetParentPath() == parentPath
    
    # Make sure all parent prefixes are recognized as prefixes, and that
    # each prefix (including terminal) is reconstructible from its string
    # element representation
    currPath = path
    while (parentPath != Sdf.Path.emptyPath) and (parentPath.name != Sdf.Path.parentPathElement):
        currElement = currPath.elementString
        reconPath = parentPath.AppendElementString(currElement)
        assert(path.HasPrefix(parentPath))
        assert reconPath == currPath
        currPath = parentPath
        parentPath = parentPath.GetParentPath()
示例#3
0
    def test_Basic(self):
        # ========================================================================
        # Test SdfPath creation and pathString
        # ========================================================================
        
        print '\nTest creating bad paths: warnings expected'
        
        # XXX: Here are a couple bad paths that are 
        # currently allowed...  add these to the test cases when they are properly 
        # disallowed
        #  ../../
        #  .rel[targ][targ].attr
        #  .attr[1, 2, 3].attr
        
        badPaths = '''
            DD/DDD.&ddf$
            DD[]/DDD
            DD[]/DDD.bar
            foo.prop/bar
            /foo.prop/bar.blah
            /foo.prop/bar.blah
            /foo//bar
            /foo/.bar
            /foo..bar
            /foo.bar.baz
            /.foo
            </foo.bar
            </Foo/Bar/>
            /Foo/Bar/
            /Foo.bar[targ]/Bar
            /Foo.bar[targ].foo.foo
            123
            123test
            /Foo:Bar
            /Foo.bar.mapper[/Targ.attr].arg:name:space
            '''.split()
        for badPath in badPaths:
            self.assertTrue(Sdf.Path(badPath).isEmpty)
            self.assertEqual(Sdf.Path(badPath), Sdf.Path())
            self.assertEqual(Sdf.Path(badPath), Sdf.Path.emptyPath)
            self.assertFalse(Sdf.Path.IsValidPathString(badPath))
        print '\tPassed'
        
        # Test lessthan
        self.assertTrue(Sdf.Path('aaa') < Sdf.Path('aab'))
        self.assertTrue(not Sdf.Path('aaa') < Sdf.Path())
        self.assertTrue(Sdf.Path('/') < Sdf.Path('/a'))
        
        # XXX test path from elements ['.prop'] when we have that wrapped?
        
        # ========================================================================
        # Test SdfPath other queries
        # ========================================================================
        
        print '\nTest scenepath queries'
        testPathStrings = [
            "/Foo/Bar.baz",
            "Foo",
            "Foo/Bar",
            "Foo.bar",
            "Foo/Bar.bar",
            ".bar",
            "/Some/Kinda/Long/Path/Just/To/Make/Sure",
            "Some/Kinda/Long/Path/Just/To/Make/Sure.property",
            "../Some/Kinda/Long/Path/Just/To/Make/Sure",
            "../../Some/Kinda/Long/Path/Just/To/Make/Sure.property",
            "/Foo/Bar.baz[targ].boom",
            "Foo.bar[targ].boom",
            ".bar[targ].boom",
            "Foo.bar[targ.attr].boom",
            "/A/B/C.rel3[/Blah].attr3",
            "A/B.rel2[/A/B/C.rel3[/Blah].attr3].attr2",
            "/A.rel1[/A/B.rel2[/A/B/C.rel3[/Blah].attr3].attr2].attr1"
        ]
        testAbsolute = [True, False, False, False, False, False, True, False, False, False, True, False, False, False, True, False, True]
        testProperty = [True, False, False, True, True, True, False, True, False, True, True, True, True, True, True, True, True]
        testElements = [
            ["Foo", "Bar", ".baz"],
            ["Foo"],
            ["Foo", "Bar"],
            ["Foo", ".bar"],
            ["Foo", "Bar", ".bar"],
            [".bar"],
            ["Some", "Kinda", "Long", "Path", "Just", "To", "Make", "Sure"],
            ["Some", "Kinda", "Long", "Path", "Just", "To", "Make", "Sure", ".property"],
            ["..", "Some", "Kinda", "Long", "Path", "Just", "To", "Make", "Sure"],
            ["..", "..", "Some", "Kinda", "Long", "Path", "Just", "To", "Make", "Sure", ".property"],
            ["Foo", "Bar", ".baz", "[targ]", ".boom"],
            ["Foo", ".bar", "[targ]", ".boom"],
            [".bar", "[targ]", ".boom"],
            ["Foo", ".bar", "[targ.attr]", ".boom"],
            ["A", "B", "C", ".rel3", "[/Blah]", ".attr3"],
            ["A", "B", ".rel2", "[/A/B/C.rel3[/Blah].attr3]", ".attr2"],
            ["A", ".rel1", "[/A/B.rel2[/A/B/C.rel3[/Blah].attr3].attr2]", ".attr1"]
        ]
        
        # Test IsAbsolutePath and IsPropertyPath
        def BasicTest(path, elements):
            assert path.IsAbsolutePath() == testAbsolute[testIndex]
            assert path.IsPropertyPath() == testProperty[testIndex]
            prefixes = Sdf._PathElemsToPrefixes(path.IsAbsolutePath(), elements)
            assert path.GetPrefixes() == prefixes
            assert path == eval(repr(path))
            assert Sdf.Path.IsValidPathString(str(path))
        
        testPaths = list()
        for testIndex in range(len(testPathStrings)):
            string = testPathStrings[testIndex]
        
            # Test path
            testPaths.append(Sdf.Path(string))
            BasicTest(testPaths[-1], testElements[testIndex])
        
            # If path is a property then try it with a namespaced name.
            if testProperty[testIndex]:
                testPaths.append(Sdf.Path(string + ':this:has:namespaces'))
                elements = list(testElements[testIndex])
                elements[-1] += ':this:has:namespaces'
                BasicTest(testPaths[-1], elements)
        
        print '\tPassed'
        
        # ========================================================================
        # Test SdfPath hashing
        # ========================================================================
        dict = {}
        for i in enumerate(testPaths):
            dict[i[1]] = i[0]
        for i in enumerate(testPaths):
            self.assertEqual(dict[i[1]], i[0])
        
        # ========================================================================
        # Test SdfPath <-> string conversion
        # ========================================================================
        
        self.assertEqual(Sdf.Path('foo'), 'foo')
        self.assertEqual('foo', Sdf.Path('foo'))
        
        self.assertNotEqual(Sdf.Path('foo'), 'bar')
        self.assertNotEqual('bar', Sdf.Path('foo'))
        
        # Test repr w/ quotes
        pathWithQuotes = Sdf.Path("b'\"")
        self.assertEqual( eval(repr(pathWithQuotes)), pathWithQuotes )
        
        # ========================================================================
        # Test SdfPath -> bool conversion
        # ========================================================================
        
        # Empty paths should evaluate to false, other paths should evaluate to true.
        self.assertTrue(Sdf.Path('/foo.bar[baz]'))
        self.assertTrue(Sdf.Path('/foo.bar'))
        self.assertTrue(Sdf.Path('/'))
        self.assertTrue(Sdf.Path('.'))
        self.assertTrue(not Sdf.Path())
        
        self.assertFalse(Sdf.Path(''))
        
        # ========================================================================
        # Test converting relative paths to absolute paths
        # ========================================================================
        print "Test converting relative paths to absolute paths"
        
        anchor = Sdf.Path("/A/B/E/F/G")
        relPath = Sdf.Path("../../../C/D")
        self.assertEqual(relPath.MakeAbsolutePath( anchor ), "/A/B/C/D")

        # Try too many ".."s for the base path
        self.assertEqual(relPath.MakeAbsolutePath( "/A" ), Sdf.Path.emptyPath)
        
        relPath = Sdf.Path("../../../..") 
        self.assertEqual(relPath.MakeAbsolutePath( anchor ), "/A")
        
        relPath = Sdf.Path("../../.radius")
        self.assertEqual(relPath.MakeAbsolutePath( anchor ), "/A/B/E.radius")
        
        relPath = Sdf.Path("..")
        self.assertEqual(relPath.MakeAbsolutePath( Sdf.Path( "../../A/B") ), Sdf.Path.emptyPath)
        
        # test passing a property path as the anchor
        self.assertEqual(relPath.MakeAbsolutePath( Sdf.Path( "/A/B.radius") ), Sdf.Path.emptyPath)
        
        # test on an absolute path
        self.assertEqual(anchor.MakeAbsolutePath( anchor ), anchor)
        print '\tPassed'
        
        # ========================================================================
        # Test converting absolute paths to relative paths
        # ========================================================================
        print "Test converting absolute paths to relative paths"
        
        anchor = Sdf.Path("/A/B/E/F/G")
        absPath = Sdf.Path("/A/B/C/D")
        self.assertEqual(absPath.MakeRelativePath( anchor ), "../../../C/D")
        
        absPath = Sdf.Path("/H/I/J")
        self.assertEqual(absPath.MakeRelativePath( anchor ), "../../../../../H/I/J")
        
        absPath = Sdf.Path("/A/B/E/F/G/H/I/J.radius")
        self.assertEqual(absPath.MakeRelativePath( anchor ), "H/I/J.radius")
        
        anchor = Sdf.Path("/A/B")
        absPath = Sdf.Path("/A.radius")
        self.assertEqual( absPath.MakeRelativePath( anchor ), "../.radius" )
        
        self.assertEqual(absPath.MakeRelativePath( Sdf.Path("H/I") ), "")
        
        # test passing a property path as the anchor
        self.assertEqual(absPath.MakeRelativePath( Sdf.Path( "/A/B.radius") ), "")
        
        print '\tPassed'
        
        # ========================================================================
        # Test converting sub-optimal relative paths to optimal relative paths
        # ========================================================================
        print "Test converting sub-optimal relative paths to optimal relative paths"
        
        anchor = Sdf.Path("/A/B/C")
        relPath = Sdf.Path("../../B/C/D")
        self.assertEqual(relPath.MakeRelativePath( anchor ), "D")
        
        relPath = Sdf.Path("../../../A")
        self.assertEqual(relPath.MakeRelativePath( anchor ), "../..")
        print '\tPassed'
        
        # ========================================================================
        # Test GetPrimPath
        # ========================================================================
        print "Test GetPrimPath"
        
        primPath = Sdf.Path("/A/B/C").GetPrimPath()
        self.assertEqual(primPath, Sdf.Path("/A/B/C"))
        
        primPath = Sdf.Path("/A/B/C.foo").GetPrimPath()
        self.assertEqual(primPath, Sdf.Path("/A/B/C"))
        primPath = Sdf.Path("/A/B/C.foo:bar:baz").GetPrimPath()
        self.assertEqual(primPath, Sdf.Path("/A/B/C"))
        
        primPath = Sdf.Path("/A/B/C.foo[target].bar").GetPrimPath()
        self.assertEqual(primPath, Sdf.Path("/A/B/C"))
        primPath = Sdf.Path("/A/B/C.foo[target].bar:baz").GetPrimPath()
        self.assertEqual(primPath, Sdf.Path("/A/B/C"))
        
        primPath = Sdf.Path("A/B/C.foo[target].bar").GetPrimPath()
        self.assertEqual(primPath, Sdf.Path("A/B/C"))
        primPath = Sdf.Path("A/B/C.foo[target].bar:baz").GetPrimPath()
        self.assertEqual(primPath, Sdf.Path("A/B/C"))
        
        primPath = Sdf.Path("../C.foo").GetPrimPath()
        self.assertEqual(primPath, Sdf.Path("../C"))
        primPath = Sdf.Path("../C.foo:bar:baz").GetPrimPath()
        self.assertEqual(primPath, Sdf.Path("../C"))
        
        primPath = Sdf.Path("../.foo[target].bar").GetPrimPath()
        self.assertEqual(primPath, Sdf.Path(".."))
        primPath = Sdf.Path("../.foo[target].bar:baz").GetPrimPath()
        self.assertEqual(primPath, Sdf.Path(".."))
        
        print '\tPassed'
        
        # ========================================================================
        # Test HasPrefix and ReplacePrefix
        # ========================================================================
        print "Test hasPrefix and replacePrefix"
        
        # Test HasPrefix
        self.assertFalse( Sdf.Path.emptyPath.HasPrefix('A') )
        self.assertFalse( Sdf.Path('A').HasPrefix( Sdf.Path.emptyPath ) )
        aPath = Sdf.Path("/Chars/Buzz_1/LArm.FB")
        self.assertEqual( aPath.HasPrefix( "/Chars/Buzz_1" ), True )
        self.assertEqual( aPath.HasPrefix( "Buzz_1" ), False )
        
        # Replace aPath's prefix and get a new path
        bPath = aPath.ReplacePrefix( "/Chars/Buzz_1", "/Chars/Buzz_2" )
        self.assertEqual( bPath, Sdf.Path("/Chars/Buzz_2/LArm.FB") )
        
        # Specify a bogus prefix to replace and get an empty path
        cPath = bPath.ReplacePrefix("/BadPrefix/Buzz_2", "/ReleasedChars/Buzz_2")
        self.assertEqual( cPath, bPath )
        
        # This formerly crashed due to a reference counting bug.
        p = Sdf.Path('/A/B.a[/C/D.a[/E/F.a]].a')
        p.ReplacePrefix('/E/F', '/X')
        p.ReplacePrefix('/E/F', '/X')
        p.ReplacePrefix('/E/F', '/X')
        p.ReplacePrefix('/E/F', '/X')
        
        # This formerly failed to replace due to an early out if the element count
        # was not longer than the element count of the prefix path we were replacing.
        p = Sdf.Path('/A.a[/B/C/D/E]') # Element count 3 [A, a, [/B/C/D/E] ]
        result = p.ReplacePrefix('/B/C/D/E', # Element count 4
                                 '/B/C/D/F')
        self.assertEqual(result, Sdf.Path('/A.a[/B/C/D/F]'))
        
        # Test replacing target paths.
        p = Sdf.Path('/A/B.a[/C/D.a[/A/F.a]].a')
        self.assertEqual(p.ReplacePrefix('/A', '/_', fixTargetPaths=False),
                         Sdf.Path('/_/B.a[/C/D.a[/A/F.a]].a'))
        self.assertEqual(p.ReplacePrefix('/A', '/_', fixTargetPaths=True),
                         Sdf.Path('/_/B.a[/C/D.a[/_/F.a]].a'))

        # ReplacePrefix with an empty old or new prefix returns an empty path.
        self.assertEqual(Sdf.Path("/A/B").ReplacePrefix(Sdf.Path.emptyPath, "/C"),
                         Sdf.Path.emptyPath)
        self.assertEqual(Sdf.Path("/A/B").ReplacePrefix("/A", Sdf.Path.emptyPath),
                         Sdf.Path.emptyPath)

        self.assertEqual(Sdf.Path.emptyPath.ReplacePrefix(Sdf.Path.emptyPath, "/C"),
                         Sdf.Path.emptyPath)
        self.assertEqual(Sdf.Path.emptyPath.ReplacePrefix("/A", Sdf.Path.emptyPath),
                         Sdf.Path.emptyPath)
        
        # ========================================================================
        # Test RemoveCommonSuffix
        # ========================================================================
        print "Test RemoveCommonSuffix"
        
        aPath = Sdf.Path('/A/B/C')
        bPath = Sdf.Path('/X/Y/Z')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('/A/B/C'))
        self.assertEqual(r2, Sdf.Path('/X/Y/Z'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('/A/B/C'))
        self.assertEqual(r2, Sdf.Path('/X/Y/Z'))
        
        aPath = Sdf.Path('A/B/C')
        bPath = Sdf.Path('X/Y/Z')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('A/B/C'))
        self.assertEqual(r2, Sdf.Path('X/Y/Z'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('A/B/C'))
        self.assertEqual(r2, Sdf.Path('X/Y/Z'))
        
        aPath = Sdf.Path('/A/B/C')
        bPath = Sdf.Path('/X/Y/C')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('/A/B'))
        self.assertEqual(r2, Sdf.Path('/X/Y'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('/A/B'))
        self.assertEqual(r2, Sdf.Path('/X/Y'))
        
        aPath = Sdf.Path('A/B/C')
        bPath = Sdf.Path('X/Y/C')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('A/B'))
        self.assertEqual(r2, Sdf.Path('X/Y'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('A/B'))
        self.assertEqual(r2, Sdf.Path('X/Y'))
        
        aPath = Sdf.Path('A/B/C')
        bPath = Sdf.Path('/X/Y/C')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('A/B'))
        self.assertEqual(r2, Sdf.Path('/X/Y'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('A/B'))
        self.assertEqual(r2, Sdf.Path('/X/Y'))
        
        aPath = Sdf.Path('/A/B/C')
        bPath = Sdf.Path('/X/B/C')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('/A'))
        self.assertEqual(r2, Sdf.Path('/X'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('/A'))
        self.assertEqual(r2, Sdf.Path('/X'))
        
        aPath = Sdf.Path('A/B/C')
        bPath = Sdf.Path('X/B/C')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('A'))
        self.assertEqual(r2, Sdf.Path('X'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('A'))
        self.assertEqual(r2, Sdf.Path('X'))
        
        aPath = Sdf.Path('A/B/C')
        bPath = Sdf.Path('/X/B/C')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('A'))
        self.assertEqual(r2, Sdf.Path('/X'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('A'))
        self.assertEqual(r2, Sdf.Path('/X'))
        
        aPath = Sdf.Path('/A/B/C')
        bPath = Sdf.Path('/A/B/C')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('/'))
        self.assertEqual(r2, Sdf.Path('/'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('/A'))
        self.assertEqual(r2, Sdf.Path('/A'))
        
        aPath = Sdf.Path('A/B/C')
        bPath = Sdf.Path('A/B/C')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('.'))
        self.assertEqual(r2, Sdf.Path('.'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('A'))
        self.assertEqual(r2, Sdf.Path('A'))
        
        aPath = Sdf.Path('A/B/C')
        bPath = Sdf.Path('/A/B/C')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('.'))
        self.assertEqual(r2, Sdf.Path('/'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('A'))
        self.assertEqual(r2, Sdf.Path('/A'))
        
        aPath = Sdf.Path('/A/B/C')
        bPath = Sdf.Path('/X/C')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('/A/B'))
        self.assertEqual(r2, Sdf.Path('/X'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('/A/B'))
        self.assertEqual(r2, Sdf.Path('/X'))
        
        aPath = Sdf.Path('A/B/C')
        bPath = Sdf.Path('X/C')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('A/B'))
        self.assertEqual(r2, Sdf.Path('X'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('A/B'))
        self.assertEqual(r2, Sdf.Path('X'))
        
        aPath = Sdf.Path('/A/B/C')
        bPath = Sdf.Path('/B/C')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('/A'))
        self.assertEqual(r2, Sdf.Path('/'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('/A/B'))
        self.assertEqual(r2, Sdf.Path('/B'))
        
        aPath = Sdf.Path('A/B/C')
        bPath = Sdf.Path('B/C')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('A'))
        self.assertEqual(r2, Sdf.Path('.'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('A/B'))
        self.assertEqual(r2, Sdf.Path('B'))
        
        aPath = Sdf.Path('/A/B/C')
        bPath = Sdf.Path('/C')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('/A/B'))
        self.assertEqual(r2, Sdf.Path('/'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('/A/B/C'))
        self.assertEqual(r2, Sdf.Path('/C'))
        
        aPath = Sdf.Path('A/B/C')
        bPath = Sdf.Path('C')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('A/B'))
        self.assertEqual(r2, Sdf.Path('.'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('A/B/C'))
        self.assertEqual(r2, Sdf.Path('C'))
        
        aPath = Sdf.Path('A/B/C')
        bPath = Sdf.Path('/C')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('A/B'))
        self.assertEqual(r2, Sdf.Path('/'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('A/B/C'))
        self.assertEqual(r2, Sdf.Path('/C'))
        
        aPath = Sdf.Path('/Lights/Lkey.shinesOn[/Chars/Buzz/Helmet].intensity')
        bPath = Sdf.Path('/Lights/Lkey.shinesOn[/Chars/Buzz].intensity')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('/Lights/Lkey.shinesOn[/Chars/Buzz/Helmet]'))
        self.assertEqual(r2, Sdf.Path('/Lights/Lkey.shinesOn[/Chars/Buzz]'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('/Lights/Lkey.shinesOn[/Chars/Buzz/Helmet]'))
        self.assertEqual(r2, Sdf.Path('/Lights/Lkey.shinesOn[/Chars/Buzz]'))
        
        aPath = Sdf.Path('Lights/Lkey.shinesOn[/Chars/Buzz/Helmet].intensity')
        bPath = Sdf.Path('Lights/Lkey.shinesOn[/Chars/Buzz].intensity')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('Lights/Lkey.shinesOn[/Chars/Buzz/Helmet]'))
        self.assertEqual(r2, Sdf.Path('Lights/Lkey.shinesOn[/Chars/Buzz]'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('Lights/Lkey.shinesOn[/Chars/Buzz/Helmet]'))
        self.assertEqual(r2, Sdf.Path('Lights/Lkey.shinesOn[/Chars/Buzz]'))
        
        aPath = Sdf.Path('/Lights/Lkey.shinesOn[/Chars/Buzz/Helmet].intensity')
        bPath = Sdf.Path('/Lights2/Lkey.shinesOn[/Chars/Buzz/Helmet].intensity')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('/Lights'))
        self.assertEqual(r2, Sdf.Path('/Lights2'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('/Lights'))
        self.assertEqual(r2, Sdf.Path('/Lights2'))
        
        aPath = Sdf.Path('Lights/Lkey.shinesOn[/Chars/Buzz/Helmet].intensity')
        bPath = Sdf.Path('Lights2/Lkey.shinesOn[/Chars/Buzz/Helmet].intensity')
        (r1, r2) = aPath.RemoveCommonSuffix(bPath)
        self.assertEqual(r1, Sdf.Path('Lights'))
        self.assertEqual(r2, Sdf.Path('Lights2'))
        (r1, r2) = aPath.RemoveCommonSuffix(bPath, stopAtRootPrim=True)
        self.assertEqual(r1, Sdf.Path('Lights'))
        self.assertEqual(r2, Sdf.Path('Lights2'))
        
        # ========================================================================
        # Test GetTargetPath
        # ========================================================================
        print "Test targetPath"
        
        aPath = Sdf.Path("/Lights/Lkey.shinesOn[/Chars/Buzz/Helmet].intensity")
        self.assertEqual( aPath.targetPath, Sdf.Path("/Chars/Buzz/Helmet") )
        
        aPath = Sdf.Path("/Lights/Lkey.shinesOn[../../Buzz/Helmet].intensity")
        self.assertEqual( aPath.targetPath, Sdf.Path("../../Buzz/Helmet") )
        
        aPath = Sdf.Path("/Lights/Lkey.shinesOn[/Chars/Buzz/Helmet].intensity")
        self.assertEqual( aPath.targetPath, Sdf.Path("/Chars/Buzz/Helmet") )
        
        aPath = Sdf.Path("/Lights/Lkey.shinesOn[/Chars/Buzz/Helmet.blah].intensity")
        self.assertEqual( aPath.targetPath, Sdf.Path("/Chars/Buzz/Helmet.blah") )
        
        # No target
        aPath = Sdf.Path.emptyPath
        self.assertEqual( aPath.targetPath, Sdf.Path.emptyPath )
        
        
        # ========================================================================
        # Test GetAllTargetPathsRecursively
        # ========================================================================
        print "Test GetAllTargetPathsRecursively"
        
        aPath = Sdf.Path("/Lights/Lkey.shinesOn[/Chars/Buzz/Helmet].intensity")
        self.assertEqual( aPath.GetAllTargetPathsRecursively(), 
                     [Sdf.Path("/Chars/Buzz/Helmet")] )
        
        aPath = Sdf.Path("/Lights/Lkey.shinesOn[../../Buzz/Helmet].intensity")
        self.assertEqual( aPath.GetAllTargetPathsRecursively(),
                     [Sdf.Path("../../Buzz/Helmet")] )
        
        aPath = Sdf.Path("/Lights/Lkey.shinesOn[/Chars/Buzz/Helmet].intensity")
        self.assertEqual( aPath.GetAllTargetPathsRecursively(),
                     [Sdf.Path("/Chars/Buzz/Helmet")] )
        
        aPath = Sdf.Path("/Lights/Lkey.shinesOn[/Chars/Buzz/Helmet.blah].intensity")
        self.assertEqual( aPath.GetAllTargetPathsRecursively(),
                     [Sdf.Path("/Chars/Buzz/Helmet.blah")] )
        
        aPath = Sdf.Path('/A/B.a[/C/D.a[/E/F.a]].a')
        self.assertEqual(aPath.GetAllTargetPathsRecursively(),
                    [Sdf.Path(x) for x in ['/C/D.a[/E/F.a]', '/E/F.a']])
        
        aPath = Sdf.Path('/A/B.a[/C/D.a[/E/F.a]].a[/A/B.a[/C/D.a]]')
        self.assertEqual(aPath.GetAllTargetPathsRecursively(),
                    [Sdf.Path(x) for x in ['/A/B.a[/C/D.a]', '/C/D.a', 
                                          '/C/D.a[/E/F.a]', '/E/F.a']])
        
        aPath = Sdf.Path('/No/Target/Paths')
        self.assertEqual(aPath.GetAllTargetPathsRecursively(), [])
        
        
        # =======================================================================
        # Test AppendChild
        # =======================================================================
        print "Test appendChild"
        
        aPath = Sdf.Path("/foo")
        self.assertEqual( aPath.AppendChild("bar"), Sdf.Path("/foo/bar") )
        aPath = Sdf.Path("foo")
        self.assertEqual( aPath.AppendChild("bar"), Sdf.Path("foo/bar") )
        
        aPath = Sdf.Path("/foo.prop")
        self.assertEqual( aPath.AppendChild("bar"), Sdf.Path.emptyPath )
        
        # =======================================================================
        # Test AppendProperty
        # =======================================================================
        print "Test appendProperty"
        
        aPath = Sdf.Path("/foo")
        self.assertEqual( aPath.AppendProperty("prop"), Sdf.Path("/foo.prop") )
        self.assertEqual( aPath.AppendProperty("prop:foo:bar"), Sdf.Path("/foo.prop:foo:bar") )
        
        aPath = Sdf.Path("/foo.prop")
        self.assertEqual( aPath.AppendProperty("prop2"), Sdf.Path.emptyPath )
        self.assertEqual( aPath.AppendProperty("prop2:foo:bar"), Sdf.Path.emptyPath )
        
        # =======================================================================
        # Test AppendPath
        # =======================================================================
        print "Test AppendPath"
        
        # append to empty path -> empty path
        with self.assertRaises(Tf.ErrorException):
            Sdf.Path().AppendPath( Sdf.Path() )

        with self.assertRaises(Tf.ErrorException):
            Sdf.Path().AppendPath( Sdf.Path('A') )
        
        # append to root/prim path
        assert Sdf.Path('/').AppendPath( Sdf.Path('A') ) == Sdf.Path('/A')
        assert Sdf.Path('/A').AppendPath( Sdf.Path('B') ) == Sdf.Path('/A/B')
        
        # append empty to root/prim path -> no change
        with self.assertRaises(Tf.ErrorException):
            Sdf.Path('/').AppendPath( Sdf.Path() )

        with self.assertRaises(Tf.ErrorException):
            Sdf.Path('/A').AppendPath( Sdf.Path() )
        
        # =======================================================================
        # Test AppendTarget
        # =======================================================================
        print "Test appendTarget"
        
        aPath = Sdf.Path("/foo.rel")
        self.assertEqual( aPath.AppendTarget("/Bar/Baz"), Sdf.Path("/foo.rel[/Bar/Baz]") )
        
        aPath = Sdf.Path("/foo")
        self.assertEqual( aPath.AppendTarget("/Bar/Baz"), Sdf.Path.emptyPath )
        
        # =======================================================================
        # Test AppendRelationalAttribute
        # =======================================================================
        print "Test appendRelationalAttribute"
        
        aPath = Sdf.Path("/foo.rel[/Bar/Baz]")
        self.assertEqual( aPath.AppendRelationalAttribute("attr"), Sdf.Path("/foo.rel[/Bar/Baz].attr") )
        self.assertEqual( aPath.AppendRelationalAttribute("attr:foo:bar"), Sdf.Path("/foo.rel[/Bar/Baz].attr:foo:bar") )
        
        aPath = Sdf.Path("/foo")
        self.assertEqual( aPath.AppendRelationalAttribute("attr"), Sdf.Path.emptyPath )
        self.assertEqual( aPath.AppendRelationalAttribute("attr:foo:bar"), Sdf.Path.emptyPath )
        
        # =======================================================================
        # Test GetParentPath and GetName
        # =======================================================================
        print "Test parentPath, name, and replaceName"
        
        self.assertEqual(Sdf.Path("/foo/bar/baz").GetParentPath(), Sdf.Path("/foo/bar"))
        self.assertEqual(Sdf.Path("/foo").GetParentPath(), Sdf.Path("/"))
        self.assertEqual(Sdf.Path.emptyPath.GetParentPath(), Sdf.Path.emptyPath)
        self.assertEqual(Sdf.Path("/foo/bar/baz.prop").GetParentPath(), Sdf.Path("/foo/bar/baz"))
        self.assertEqual(Sdf.Path("/foo/bar/baz.rel[/targ].attr").GetParentPath(), Sdf.Path("/foo/bar/baz.rel[/targ]"))
        self.assertEqual(Sdf.Path("/foo/bar/baz.rel[/targ]").GetParentPath(), Sdf.Path("/foo/bar/baz.rel"))
        self.assertEqual(Sdf.Path("../../..").GetParentPath(), Sdf.Path("../../../.."))
        self.assertEqual(Sdf.Path("..").GetParentPath(), Sdf.Path("../.."))
        self.assertEqual(Sdf.Path("../../../.prop").GetParentPath(), Sdf.Path("../../.."))
        self.assertEqual(Sdf.Path("../../../.rel[/targ]").GetParentPath(), Sdf.Path("../../../.rel"))
        self.assertEqual(Sdf.Path("../../../.rel[/targ].attr").GetParentPath(), Sdf.Path("../../../.rel[/targ]"))
        self.assertEqual(Sdf.Path("foo/bar/baz").GetParentPath(), Sdf.Path("foo/bar"))
        self.assertEqual(Sdf.Path("foo").GetParentPath(), Sdf.Path("."))
        self.assertEqual(Sdf.Path("foo/bar/baz.prop").GetParentPath(), Sdf.Path("foo/bar/baz"))
        self.assertEqual(Sdf.Path("foo/bar/baz.rel[/targ]").GetParentPath(), Sdf.Path("foo/bar/baz.rel"))
        self.assertEqual(Sdf.Path("foo/bar/baz.rel[/targ].attr").GetParentPath(), Sdf.Path("foo/bar/baz.rel[/targ]"))
        
        self.assertEqual(Sdf.Path("/foo/bar/baz").name, "baz")
        self.assertEqual(Sdf.Path("/foo").name, "foo")
        self.assertEqual(Sdf.Path.emptyPath.name, "")
        self.assertEqual(Sdf.Path("/foo/bar/baz.prop").name, "prop")
        self.assertEqual(Sdf.Path("/foo/bar/baz.prop:argle:bargle").name, "prop:argle:bargle")
        self.assertEqual(Sdf.Path("/foo/bar/baz.rel[/targ].attr").name, "attr")
        self.assertEqual(Sdf.Path("/foo/bar/baz.rel[/targ].attr:argle:bargle").name, "attr:argle:bargle")
        self.assertEqual(Sdf.Path("../../..").name, "..")
        self.assertEqual(Sdf.Path("../../.prop").name, "prop")
        self.assertEqual(Sdf.Path("../../.prop:argle:bargle").name, "prop:argle:bargle")
        self.assertEqual(Sdf.Path("../../.rel[/targ].attr").name, "attr")
        self.assertEqual(Sdf.Path("../../.rel[/targ].attr:argle:bargle").name, "attr:argle:bargle")
        self.assertEqual(Sdf.Path("foo/bar/baz").name, "baz")
        self.assertEqual(Sdf.Path("foo").name, "foo")
        self.assertEqual(Sdf.Path("foo/bar/baz.prop").name, "prop")
        self.assertEqual(Sdf.Path("foo/bar/baz.prop:argle:bargle").name, "prop:argle:bargle")
        self.assertEqual(Sdf.Path("foo/bar/baz.rel[/targ].attr").name, "attr")
        self.assertEqual(Sdf.Path("foo/bar/baz.rel[/targ].attr:argle:bargle").name, "attr:argle:bargle")
        
        self.assertEqual(Sdf.Path("/foo/bar/baz").ReplaceName('foo'), Sdf.Path("/foo/bar/foo"))
        self.assertEqual(Sdf.Path("/foo").ReplaceName('bar'), Sdf.Path("/bar"))
        self.assertEqual(Sdf.Path("/foo/bar/baz.prop").ReplaceName('attr'),
                    Sdf.Path("/foo/bar/baz.attr"))
        self.assertEqual(Sdf.Path("/foo/bar/baz.prop").ReplaceName('attr:argle:bargle'),
                    Sdf.Path("/foo/bar/baz.attr:argle:bargle"))
        self.assertEqual(Sdf.Path("/foo/bar/baz.prop:argle:bargle").ReplaceName('attr'),
                    Sdf.Path("/foo/bar/baz.attr"))
        self.assertEqual(Sdf.Path("/foo/bar/baz.prop:argle:bargle").ReplaceName('attr:foo:fa:raw'),
                    Sdf.Path("/foo/bar/baz.attr:foo:fa:raw"))
        self.assertEqual(Sdf.Path("/foo/bar/baz.rel[/targ].attr").ReplaceName('prop'),
                    Sdf.Path("/foo/bar/baz.rel[/targ].prop"))
        self.assertEqual(Sdf.Path("/foo/bar/baz.rel[/targ].attr").ReplaceName('prop:argle:bargle'),
                    Sdf.Path("/foo/bar/baz.rel[/targ].prop:argle:bargle"))
        self.assertEqual(Sdf.Path("/foo/bar/baz.rel[/targ].attr:argle:bargle").ReplaceName('prop'),
                    Sdf.Path("/foo/bar/baz.rel[/targ].prop"))
        self.assertEqual(Sdf.Path("/foo/bar/baz.rel[/targ].attr:argle:bargle").ReplaceName('prop:foo:fa:raw'),
                    Sdf.Path("/foo/bar/baz.rel[/targ].prop:foo:fa:raw"))
        self.assertEqual(Sdf.Path("../../..").ReplaceName('foo'), Sdf.Path("../../../../foo"))
        self.assertEqual(Sdf.Path("..").ReplaceName('foo'), Sdf.Path("../../foo"))
        self.assertEqual(Sdf.Path("../../../.prop").ReplaceName('attr'),
                    Sdf.Path("../../../.attr"))
        self.assertEqual(Sdf.Path("../../../.prop").ReplaceName('attr:argle:bargle'),
                    Sdf.Path("../../../.attr:argle:bargle"))
        self.assertEqual(Sdf.Path("../../../.rel[/targ].attr").ReplaceName('prop'),
                    Sdf.Path("../../../.rel[/targ].prop"))
        self.assertEqual(Sdf.Path("../../../.rel[/targ].attr").ReplaceName('prop:argle:bargle'),
                    Sdf.Path("../../../.rel[/targ].prop:argle:bargle"))
        self.assertEqual(Sdf.Path("foo/bar/baz").ReplaceName('foo'), Sdf.Path("foo/bar/foo"))
        self.assertEqual(Sdf.Path("foo").ReplaceName('bar'), Sdf.Path("bar"))
        self.assertEqual(Sdf.Path("foo/bar/baz.prop").ReplaceName('attr'),
                    Sdf.Path("foo/bar/baz.attr"))
        self.assertEqual(Sdf.Path("foo/bar/baz.prop").ReplaceName('attr:argle:bargle'),
                    Sdf.Path("foo/bar/baz.attr:argle:bargle"))
        self.assertEqual(Sdf.Path("foo/bar/baz.rel[/targ].attr").ReplaceName('prop'), 
                    Sdf.Path("foo/bar/baz.rel[/targ].prop"))
        self.assertEqual(Sdf.Path("foo/bar/baz.rel[/targ].attr").ReplaceName('prop:argle:bargle'), 
                    Sdf.Path("foo/bar/baz.rel[/targ].prop:argle:bargle"))
        
        with self.assertRaises(Tf.ErrorException):
            Sdf.Path('/foo/bar[target]').ReplaceName('xxx')

        # =======================================================================
        # Test GetConciseRelativePaths
        # =======================================================================
        print "Test GetConciseRelativePaths"
        
        aPath = Sdf.Path("/foo/bar")
        bPath = Sdf.Path("/foo/baz")
        cPath = Sdf.Path("/foo")
        
        # a typical assortment of paths
        self.assertEqual( Sdf.Path.GetConciseRelativePaths([aPath,bPath,cPath]),
                       [Sdf.Path("bar"), Sdf.Path("baz"), Sdf.Path("/foo")] )
        
        # test some property paths
        dPath = Sdf.Path("/foo/bar.a")
        ePath = Sdf.Path("/foo/bar.b")
        
        self.assertEqual( Sdf.Path.GetConciseRelativePaths([dPath, ePath]),
                        [Sdf.Path("bar.a"), Sdf.Path("bar.b")] )
        
        fPath = Sdf.Path("/baz/bar")
        
        self.assertEqual( Sdf.Path.GetConciseRelativePaths([aPath, fPath]),
                     [Sdf.Path("/foo/bar"), Sdf.Path("/baz/bar")] )
        
        # now give it two identical paths
        self.assertEqual( Sdf.Path.GetConciseRelativePaths([aPath, aPath]),
                     [Sdf.Path("bar"), Sdf.Path("bar")] )
        
        # give it root paths
        gPath = Sdf.Path("/bar")
        self.assertEqual( Sdf.Path.GetConciseRelativePaths([cPath, gPath]),
                     [Sdf.Path("/foo"), Sdf.Path("/bar")] )
        
        # now give it a relative path as an argument
        self.assertEqual( Sdf.Path.GetConciseRelativePaths([Sdf.Path("a")]),
                     [Sdf.Path("a")] )
        
        
        # =======================================================================
        # Test RemoveDescendentPaths
        # =======================================================================
        
        print "Test RemoveDescendentPaths"
        
        paths = [Sdf.Path(x) for x in
                 ['/a/b/c', '/q', '/a/b/c/d/e/f/g', '/r/s/t', '/a/b', 
                  '/q/r/s/t', '/x/y', '/a/b/d']]
        
        expected = [Sdf.Path(x) for x in ['/a/b', '/q', '/x/y', '/r/s/t']]
        
        result = Sdf.Path.RemoveDescendentPaths(paths)
        
        # ensure result is unique, then compare independent of order.
        self.assertEqual(len(result), len(set(result)))
        self.assertEqual(set(result), set(expected))
        
        
        # =======================================================================
        # Test RemoveAncestorPaths
        # =======================================================================
        
        print "Test RemoveAncestorPaths"
        
        paths = [Sdf.Path(x) for x in
                 ['/a/b/c', '/q', '/a/b/c/d/e/f/g', '/r/s/t', '/a/b', 
                  '/q/r/s/t', '/x/y', '/a/b/d']]
        
        expected = [Sdf.Path(x) for x in 
                    ['/a/b/c/d/e/f/g', '/a/b/d', '/q/r/s/t', '/r/s/t', '/x/y']]
        
        result = Sdf.Path.RemoveAncestorPaths(paths)
        
        # ensure result is unique, then compare independent of order.
        self.assertEqual(len(result), len(set(result)))
        self.assertEqual(set(result), set(expected))
        
        # ========================================================================
        # Test FindPrefixedRange and FindLongestPrefix
        # ========================================================================
        
        def testFindPrefixedRangeAndFindLongestPrefix():
            print "Test FindPrefixedRange and FindLongestPrefix"
        
            import random, time
            rgen = random.Random()
            seed = int(time.time())
            rgen.seed(seed)
            print 'random seed', seed
        
            letters = [chr(x) for x in range(ord('a'), ord('d')+1)]
            maxLen = 8
        
            paths = []
            for i in range(300):
                elems = [rgen.choice(letters) for i in range(rgen.randint(1, maxLen))]
                paths.append(Sdf.Path('/' + '/'.join(elems)))
            paths.append(Sdf.Path('/'))
        
            tests = []
            for i in range(300):
                elems = [rgen.choice(letters) for i in range(rgen.randint(1, maxLen))]
                tests.append(Sdf.Path('/' + '/'.join(elems)))
            tests.append(Sdf.Path('/'))
        
            paths.sort()
            tests.sort()
        
            # print '== paths', '='*64
            # print '\n'.join(map(str, paths))
        
            # print '== tests', '='*64
            # print '\n'.join(map(str, tests))
        
            def testFindPrefixedRange(p, paths):
                sl = Sdf.Path.FindPrefixedRange(paths, p)
                #print p, '>>', ', '.join([str(x) for x in paths[sl]])
                self.assertTrue(all([path.HasPrefix(p) for path in paths[sl]]))
                others = list(paths)
                del others[sl]
                self.assertTrue(not any([path.HasPrefix(p) for path in others[sl]]))
        
            def testFindLongestPrefix(p, paths):
                lp = Sdf.Path.FindLongestPrefix(paths, p)
                # should always have some prefix since '/' is in paths.
                self.assertTrue(p.HasPrefix(lp))
                # manually find longest prefix
                bruteLongest = Sdf.Path('/')
                for x in paths:
                    if (p.HasPrefix(x) and 
                        x.pathElementCount > bruteLongest.pathElementCount):
                        bruteLongest = x
                # bruteLongest should match.
                #print 'path:', p, 'lp:', lp, 'bruteLongest:', bruteLongest
                self.assertEqual(lp, bruteLongest, ('lp (%s) != bruteLongest (%s)' % 
                                            (lp, bruteLongest)))
        
            for testp in tests:
                testFindPrefixedRange(testp, paths)
                testFindLongestPrefix(testp, paths)
        
            # Do a few simple cases directly.
            paths = map(Sdf.Path, ['/a', '/a/b/c/d', '/b/a', '/b/c/d/e'])
            flp = Sdf.Path.FindLongestPrefix
            assert flp(paths, '/x') == None
            assert flp(paths, '/a') == Sdf.Path('/a')
            assert flp(paths, '/a/a/a') == Sdf.Path('/a')
            assert flp(paths, '/a/c/d/e/f') == Sdf.Path('/a')
            assert flp(paths, '/a/b/c/d') == Sdf.Path('/a/b/c/d')
            assert flp(paths, '/a/b/c/d/a/b/c/d') == Sdf.Path('/a/b/c/d')
            assert flp(paths, '/a/b/c/e/f/g') == Sdf.Path('/a')
            assert flp(paths, '/b') == None
            assert flp(paths, '/b/a/b/c/d/e') == Sdf.Path('/b/a')
            assert flp(paths, '/b/c/d/e/f/g') == Sdf.Path('/b/c/d/e')
            assert flp(paths, '/b/c/d/e') == Sdf.Path('/b/c/d/e')
            assert flp(paths, '/b/c/x/y/z') == None
        
        testFindPrefixedRangeAndFindLongestPrefix()
        
        Sdf._DumpPathStats()
        
        print '\tPassed'
        
        print 'Test SUCCEEDED'
示例#4
0
    def test_PrimvarsAPI(self):
        IsPrimvar = UsdGeom.Primvar.IsPrimvar

        # We'll put all our Primvar on a single mesh gprim
        stage = Usd.Stage.CreateInMemory('myTest.usda')
        gp = UsdGeom.Mesh.Define(stage, '/myMesh')
        gp_pv = UsdGeom.PrimvarsAPI(gp)

        nPasses = 3

        # Add three Primvars
        u1 = gp_pv.CreatePrimvar('u_1', Sdf.ValueTypeNames.FloatArray)
        self.assertFalse(u1.NameContainsNamespaces())
        self.assertEqual(UsdGeom.Primvar.StripPrimvarsName(u1.GetName()),
                         "u_1")
        # Make sure it's OK to manually specify the classifier namespace
        v1 = gp_pv.CreatePrimvar('primvars:v_1', Sdf.ValueTypeNames.FloatArray)
        self.assertEqual(UsdGeom.Primvar.StripPrimvarsName(v1.GetName()),
                         "v_1")
        noPrimvarsPrefixName = "noPrimvarPrefixName"
        self.assertEqual(
            UsdGeom.Primvar.StripPrimvarsName(noPrimvarsPrefixName),
            noPrimvarsPrefixName)
        self.assertFalse(v1.NameContainsNamespaces())
        _3dpmats = gp_pv.CreatePrimvar('projMats',
                                       Sdf.ValueTypeNames.Matrix4dArray,
                                       "constant", nPasses)

        # ensure we can create a primvar that contains namespaces!
        primvarName = 'skel:jointWeights'
        jointWeights = gp_pv.CreatePrimvar(primvarName,
                                           Sdf.ValueTypeNames.FloatArray)
        self.assertTrue(IsPrimvar(jointWeights))
        self.assertTrue(
            UsdGeom.Primvar.IsValidPrimvarName(jointWeights.GetName()))
        self.assertTrue(jointWeights.NameContainsNamespaces())
        self.assertEqual(primvarName, jointWeights.GetPrimvarName())

        # Ensure we cannot create a primvar named indices or any namespace
        # ending in indices
        with self.assertRaises(Tf.ErrorException):
            gp_pv.CreatePrimvar("indices", Sdf.ValueTypeNames.IntArray)
        with self.assertRaises(Tf.ErrorException):
            gp_pv.CreatePrimvar("multi:aggregate:indices",
                                Sdf.ValueTypeNames.IntArray)

        self.assertEqual(len(gp_pv.GetAuthoredPrimvars()), 4)
        # displayColor and displayOpacity are builtins, not authored
        self.assertEqual(len(gp_pv.GetPrimvars()), 6)

        # Now add some random properties, plus a "manually" created, namespaced
        # primvar, and reverify
        p = gp.GetPrim()
        p.CreateRelationship("myBinding")
        p.CreateAttribute("myColor", Sdf.ValueTypeNames.Color3f)
        p.CreateAttribute("primvars:some:overly:namespaced:Color",
                          Sdf.ValueTypeNames.Color3f)

        datas = gp_pv.GetAuthoredPrimvars()

        self.assertEqual(len(datas), 5)
        self.assertTrue(IsPrimvar(datas[0]))
        self.assertTrue(UsdGeom.Primvar.IsValidPrimvarName(datas[0].GetName()))
        self.assertTrue(
            UsdGeom.Primvar.IsPrimvarRelatedPropertyName(datas[0].GetName()))
        self.assertTrue(IsPrimvar(datas[1]))
        self.assertTrue(UsdGeom.Primvar.IsValidPrimvarName(datas[1].GetName()))
        self.assertTrue(
            UsdGeom.Primvar.IsPrimvarRelatedPropertyName(datas[1].GetName()))
        # For variety, test the explicit Attribute extractor
        self.assertTrue(IsPrimvar(datas[2].GetAttr()))
        self.assertTrue(
            UsdGeom.Primvar.IsValidPrimvarName(datas[2].GetAttr().GetName()))
        self.assertTrue(
            UsdGeom.Primvar.IsPrimvarRelatedPropertyName(
                datas[2].GetAttr().GetName()))
        self.assertFalse(IsPrimvar(p.GetAttribute("myColor")))
        self.assertFalse(UsdGeom.Primvar.IsValidPrimvarName("myColor"))
        self.assertFalse(
            UsdGeom.Primvar.IsPrimvarRelatedPropertyName("myColor"))
        # Here we're testing that the speculative constructor fails properly
        self.assertFalse(IsPrimvar(UsdGeom.Primvar(p.GetAttribute("myColor"))))
        self.assertFalse(
            UsdGeom.Primvar.IsValidPrimvarName(
                datas[0].GetIndicesAttr().GetName()))
        self.assertTrue(
            UsdGeom.Primvar.IsPrimvarRelatedPropertyName(
                datas[0].GetIndicesAttr().GetName()))
        # And here that the speculative constructor succeeds properly
        self.assertTrue(
            IsPrimvar(UsdGeom.Primvar(p.GetAttribute(v1.GetName()))))

        # Some of the same tests, exercising the bool-type operator
        # for UsdGeomPrimvar; Primvar provides the easiest way to get INvalid attrs!
        self.assertTrue(datas[0])
        self.assertTrue(datas[1])
        self.assertTrue(datas[2])
        self.assertFalse(UsdGeom.Primvar(p.GetAttribute("myColor")))
        self.assertFalse(UsdGeom.Primvar(p.GetAttribute("myBinding")))
        self.assertTrue(UsdGeom.Primvar(p.GetAttribute(v1.GetName())))

        # Same classification test through GprimSchema API
        self.assertTrue(gp_pv.HasPrimvar('u_1'))
        self.assertTrue(gp_pv.HasPrimvar('v_1'))
        self.assertTrue(gp_pv.HasPrimvar('projMats'))
        self.assertTrue(gp_pv.HasPrimvar('skel:jointWeights'))
        self.assertFalse(gp_pv.HasPrimvar('myColor'))
        self.assertFalse(gp_pv.HasPrimvar('myBinding'))

        # Test that the gpv's returned by GetPrimvars are REALLY valid,
        # and that the UsdAttribute metadata wrappers work
        self.assertEqual(datas[0].GetTypeName(),
                         Sdf.ValueTypeNames.Matrix4dArray)
        self.assertEqual(datas[3].GetTypeName(), Sdf.ValueTypeNames.FloatArray)
        self.assertEqual(datas[4].GetBaseName(), "v_1")

        # Now we'll add some extra configuration and verify that the
        # interrogative API works properly
        self.assertEqual(u1.GetInterpolation(),
                         UsdGeom.Tokens.constant)  # fallback
        self.assertFalse(u1.HasAuthoredInterpolation())
        self.assertFalse(u1.HasAuthoredElementSize())
        self.assertTrue(u1.SetInterpolation(UsdGeom.Tokens.vertex))
        self.assertTrue(u1.HasAuthoredInterpolation())
        self.assertEqual(u1.GetInterpolation(), UsdGeom.Tokens.vertex)

        self.assertFalse(v1.HasAuthoredInterpolation())
        self.assertFalse(v1.HasAuthoredElementSize())
        self.assertTrue(v1.SetInterpolation(UsdGeom.Tokens.uniform))
        self.assertTrue(v1.SetInterpolation(UsdGeom.Tokens.varying))
        self.assertTrue(v1.SetInterpolation(UsdGeom.Tokens.constant))
        self.assertTrue(v1.SetInterpolation(UsdGeom.Tokens.faceVarying))

        with self.assertRaises(Tf.ErrorException):
            v1.SetInterpolation("frobosity")
        # Should be the last good value set
        self.assertEqual(v1.GetInterpolation(), "faceVarying")

        self.assertTrue(_3dpmats.HasAuthoredInterpolation())
        self.assertTrue(_3dpmats.HasAuthoredElementSize())
        with self.assertRaises(Tf.ErrorException):
            _3dpmats.SetElementSize(0)
        # Failure to set shouldn't change the state...
        self.assertTrue(_3dpmats.HasAuthoredElementSize())
        self.assertTrue(_3dpmats.SetElementSize(nPasses))
        self.assertTrue(_3dpmats.HasAuthoredElementSize())

        # Make sure value Get/Set work
        self.assertEqual(u1.Get(), None)

        self.assertFalse(u1.IsIndexed())
        self.assertFalse(u1.GetIndicesAttr())
        self.assertEqual(u1.ComputeFlattened(), None)

        uVal = Vt.FloatArray([1.1, 2.1, 3.1])
        self.assertTrue(u1.Set(uVal))
        self.assertEqual(u1.Get(), uVal)

        # Make sure indexed primvars work
        self.assertFalse(u1.IsIndexed())
        indices = Vt.IntArray([0, 1, 2, 2, 1, 0])
        self.assertTrue(u1.SetIndices(indices))
        self.assertTrue(u1.IsIndexed())
        self.assertTrue(u1.GetIndicesAttr())

        self.assertEqual(u1.GetIndices(), indices)
        for a, b in zip(u1.ComputeFlattened(), [1.1, 2.1, 3.1, 3.1, 2.1, 1.1]):
            self.assertTrue(Gf.IsClose(a, b, 1e-5))
        self.assertNotEqual(u1.ComputeFlattened(), u1.Get())

        indicesWithInvalid = Vt.IntArray([0, 3, 2, 2, -1, 0])
        self.assertTrue(u1.SetIndices(indicesWithInvalid))
        self.assertTrue(u1.ComputeFlattened() is None)

        indicesWithInvalid = Vt.IntArray([4, 5, 6, 7, -1, 8])
        self.assertTrue(u1.SetIndices(indicesWithInvalid))
        self.assertTrue(u1.ComputeFlattened() is None)

        self.assertEqual(u1.GetUnauthoredValuesIndex(), -1)
        self.assertTrue(u1.SetUnauthoredValuesIndex(2))
        self.assertEqual(u1.GetUnauthoredValuesIndex(), 2)

        self.assertEqual(u1.GetTimeSamples(), [])
        self.assertFalse(u1.ValueMightBeTimeVarying())

        indicesAt1 = Vt.IntArray([1, 2, 0])
        indicesAt2 = Vt.IntArray([])

        uValAt1 = Vt.FloatArray([2.1, 3.1, 4.1])
        uValAt2 = Vt.FloatArray([3.1, 4.1, 5.1])

        self.assertTrue(u1.SetIndices(indicesAt1, 1.0))
        self.assertEqual(u1.GetIndices(1.0), indicesAt1)

        self.assertTrue(u1.Set(uValAt1, 1.0))
        self.assertEqual(u1.Get(1.0), uValAt1)

        self.assertEqual(u1.GetTimeSamples(), [1.0])
        self.assertFalse(u1.ValueMightBeTimeVarying())

        self.assertTrue(u1.SetIndices(indicesAt2, 2.0))
        self.assertEqual(u1.GetIndices(2.0), indicesAt2)

        self.assertTrue(u1.Set(uValAt2, 2.0))
        self.assertEqual(u1.Get(2.0), uValAt2)

        self.assertEqual(u1.GetTimeSamples(), [1.0, 2.0])
        self.assertEqual(u1.GetTimeSamplesInInterval(Gf.Interval(0.5, 1.5)),
                         [1.0])
        self.assertTrue(u1.ValueMightBeTimeVarying())

        # Add more time-samples to u1
        indicesAt0 = Vt.IntArray([])
        uValAt3 = Vt.FloatArray([4.1, 5.1, 6.1])

        self.assertTrue(u1.SetIndices(indicesAt0, 0.0))
        self.assertEqual(u1.GetTimeSamples(), [0.0, 1.0, 2.0])

        self.assertTrue(u1.Set(uValAt3, 3.0))
        self.assertEqual(u1.GetTimeSamples(), [0.0, 1.0, 2.0, 3.0])

        self.assertEqual(u1.GetTimeSamplesInInterval(Gf.Interval(1.5, 3.5)),
                         [2.0, 3.0])

        for a, b in zip(u1.ComputeFlattened(1.0), [3.1, 4.1, 2.1]):
            self.assertTrue(Gf.IsClose(a, b, 1e-5))

        self.assertNotEqual(u1.ComputeFlattened(1.0), u1.Get(1.0))

        self.assertTrue(len(u1.ComputeFlattened(2.0)) == 0)
        self.assertNotEqual(u1.ComputeFlattened(2.0), u1.Get(2.0))

        # Ensure that primvars with indices only authored at timeSamples
        # (i.e. no default) are recognized as such.
        u1Indices = u1.GetIndicesAttr()
        self.assertTrue(u1Indices)
        u1Indices.ClearDefault()
        self.assertTrue(u1.IsIndexed())

        # Finally, ensure the values returned by GetDeclarationInfo
        # (on new Primvar objects, to test the GprimSchema API)
        # is identical to the individual queries, and matches what we set above
        nu1 = gp_pv.GetPrimvar("u_1")
        (name, typeName, interpolation, elementSize) = nu1.GetDeclarationInfo()
        self.assertEqual(name, u1.GetBaseName())
        self.assertEqual(typeName, u1.GetTypeName())
        self.assertEqual(interpolation, u1.GetInterpolation())
        self.assertEqual(elementSize, u1.GetElementSize())

        self.assertEqual(name, "u_1")
        self.assertEqual(typeName, Sdf.ValueTypeNames.FloatArray)
        self.assertEqual(interpolation, UsdGeom.Tokens.vertex)
        self.assertEqual(elementSize, 1)

        nv1 = gp_pv.GetPrimvar("v_1")
        (name, typeName, interpolation, elementSize) = nv1.GetDeclarationInfo()
        self.assertEqual(name, v1.GetBaseName())
        self.assertEqual(typeName, v1.GetTypeName())
        self.assertEqual(interpolation, v1.GetInterpolation())
        self.assertEqual(elementSize, v1.GetElementSize())

        self.assertEqual(name, "v_1")
        self.assertEqual(typeName, Sdf.ValueTypeNames.FloatArray)
        self.assertEqual(interpolation, UsdGeom.Tokens.faceVarying)
        self.assertEqual(elementSize, 1)

        nmats = gp_pv.GetPrimvar('projMats')
        (name, typeName, interpolation,
         elementSize) = nmats.GetDeclarationInfo()
        self.assertEqual(name, _3dpmats.GetBaseName())
        self.assertEqual(typeName, _3dpmats.GetTypeName())
        self.assertEqual(interpolation, _3dpmats.GetInterpolation())
        self.assertEqual(elementSize, _3dpmats.GetElementSize())

        self.assertEqual(name, 'projMats')
        self.assertEqual(typeName, Sdf.ValueTypeNames.Matrix4dArray)
        self.assertEqual(interpolation, UsdGeom.Tokens.constant)
        self.assertEqual(elementSize, nPasses)

        # Custom builtins for gprim display primvars
        displayColor = gp.CreateDisplayColorPrimvar(UsdGeom.Tokens.vertex, 3)
        self.assertTrue(displayColor)
        declInfo = displayColor.GetDeclarationInfo()
        self.assertEqual(declInfo,
                         ('displayColor', Sdf.ValueTypeNames.Color3fArray,
                          UsdGeom.Tokens.vertex, 3))

        displayOpacity = gp.CreateDisplayOpacityPrimvar(
            UsdGeom.Tokens.constant)
        self.assertTrue(displayOpacity)
        declInfo = displayOpacity.GetDeclarationInfo()
        self.assertEqual(declInfo,
                         ('displayOpacity', Sdf.ValueTypeNames.FloatArray,
                          UsdGeom.Tokens.constant, 1))

        # Id primvar
        notId = gp_pv.CreatePrimvar('notId', Sdf.ValueTypeNames.FloatArray)
        self.assertFalse(notId.IsIdTarget())
        with self.assertRaises(Tf.ErrorException):
            notId.SetIdTarget(gp.GetPath())

        handleid = gp_pv.CreatePrimvar('handleid', Sdf.ValueTypeNames.String)

        # make sure we can still just set a string
        v = "handleid_value"
        self.assertTrue(handleid.Set(v))
        self.assertEqual(handleid.Get(), v)
        self.assertEqual(handleid.ComputeFlattened(), v)

        numPrimvars = len(gp_pv.GetPrimvars())

        # This check below ensures that the "indices" attributes belonging to
        # indexed primvars aren't considered to be primvars themselves.
        self.assertEqual(numPrimvars, 9)

        self.assertTrue(handleid.SetIdTarget(gp.GetPath()))
        # make sure we didn't increase the number of primvars (also that
        # GetPrimvars doesn't break when we have relationships)
        self.assertEqual(len(gp_pv.GetPrimvars()), numPrimvars)
        self.assertEqual(handleid.Get(), gp.GetPath())

        stringPath = '/my/string/path'
        self.assertTrue(handleid.SetIdTarget(stringPath))
        self.assertEqual(handleid.Get(), Sdf.Path(stringPath))

        p = Sdf.Path('/does/not/exist')
        self.assertTrue(handleid.SetIdTarget(p))
        self.assertEqual(handleid.Get(), p)

        handleid_array = gp_pv.CreatePrimvar('handleid_array',
                                             Sdf.ValueTypeNames.StringArray)
        self.assertTrue(handleid_array.SetIdTarget(gp.GetPath()))

        # Test BlockPrimvar API
        pv_blocking = gp_pv.CreatePrimvar('pvb', Sdf.ValueTypeNames.FloatArray)
        pvName = pv_blocking.GetName()
        pv_blocking.SetInterpolation(UsdGeom.Tokens.vertex)
        pv_val = Vt.FloatArray([1.1, 2.1, 3.1])
        pv_blocking.Set(pv_val)
        # Block a non-indexed primvar should also construct and block indices attr
        self.assertFalse(pv_blocking.IsIndexed())
        self.assertTrue(pv_blocking.HasAuthoredValue())
        self.assertTrue(pv_blocking.HasAuthoredInterpolation())
        gp_pv.BlockPrimvar(pvName)
        self.assertFalse(pv_blocking.HasAuthoredValue())
        self.assertTrue(pv_blocking.HasAuthoredInterpolation())
        self.assertFalse(pv_blocking.IsIndexed())
        self.assertTrue(
            pv_blocking.GetIndicesAttr().GetResolveInfo().ValueIsBlocked())
        # re-set pv_blocking
        pv_blocking.Set(pv_val)
        pv_indices = Vt.IntArray([0, 1, 2, 2, 1, 0])
        pv_blocking.SetIndices(pv_indices)

        self.assertTrue(pv_blocking.HasAuthoredValue())
        self.assertTrue(pv_blocking.HasAuthoredInterpolation())
        self.assertTrue(pv_blocking.IsIndexed())
        # Block primvar as well as indices Attr
        gp_pv.BlockPrimvar(pvName)
        self.assertFalse(pv_blocking.HasAuthoredValue())
        self.assertTrue(pv_blocking.HasAuthoredInterpolation())
        self.assertFalse(pv_blocking.IsIndexed())
        # re-set pv_blocking for further testing
        pv_blocking.Set(pv_val)
        pv_indices = Vt.IntArray([0, 1, 2, 2, 1, 0])
        pv_blocking.SetIndices(pv_indices)
        # test BlockPrimvar on a referenced prim
        weakLayer = Sdf.Layer.CreateAnonymous()
        stageWeak = Usd.Stage.Open(weakLayer)
        ovrMesh = stageWeak.OverridePrim('/myMesh')
        ovrMesh.GetReferences().AddReference(stage.GetRootLayer().identifier,
                                             '/myMesh')
        gp_pv_ovr = UsdGeom.PrimvarsAPI(ovrMesh)
        pv_blocking_ovr = gp_pv_ovr.GetPrimvar(pvName)
        self.assertTrue(pv_blocking_ovr.HasAuthoredValue())
        self.assertTrue(pv_blocking_ovr.HasAuthoredInterpolation())
        self.assertTrue(pv_blocking_ovr.IsIndexed())
        # should only block primvar and indices attr in the referenced prim
        gp_pv_ovr.BlockPrimvar(pvName)
        # ovr primvar will be blocked!
        self.assertFalse(pv_blocking_ovr.HasAuthoredValue())
        self.assertTrue(pv_blocking_ovr.HasAuthoredInterpolation())
        self.assertFalse(pv_blocking_ovr.IsIndexed())
        # stronger layer wont get affected and original prim should not be blocked
        self.assertTrue(pv_blocking.HasAuthoredValue())
        self.assertTrue(pv_blocking.HasAuthoredInterpolation())
        self.assertTrue(pv_blocking.IsIndexed())

        # Remove a few valid primvar names
        # without namespace
        p = gp.GetPrim()
        self.assertTrue(u1.IsIndexed())
        u1Name = u1.GetName()
        u1IndicesAttrName = u1.GetIndicesAttr().GetName()

        # can not remove a primvar across a reference arc
        weakLayer = Sdf.Layer.CreateAnonymous()
        stageWeak = Usd.Stage.Open(weakLayer)
        ovrMesh = stageWeak.OverridePrim('/myMesh')
        ovrMesh.GetReferences().AddReference(stage.GetRootLayer().identifier,
                                             '/myMesh')
        gp_pv_ovr = UsdGeom.PrimvarsAPI(ovrMesh)
        self.assertTrue(gp_pv_ovr.HasPrimvar(u1Name))
        self.assertFalse(gp_pv_ovr.RemovePrimvar(u1Name))
        self.assertTrue(gp_pv_ovr.GetPrim().HasAttribute(u1Name))
        # remove indexed primvar
        self.assertTrue(gp_pv.RemovePrimvar(u1Name))
        self.assertFalse(p.HasAttribute(u1Name))
        self.assertFalse(p.HasAttribute(u1IndicesAttrName))
        # with primvars namespace
        v1Name = v1.GetName()
        self.assertTrue(gp_pv.RemovePrimvar(v1Name))
        self.assertFalse(p.HasAttribute(v1Name))
        # primvar does not exists
        self.assertFalse(gp_pv.RemovePrimvar('does_not_exist'))
        self.assertFalse(gp_pv.RemovePrimvar('does_not_exist:does_not_exist'))
        # try to remove an invalid primvar with restricted tokens, "indices"
        with self.assertRaises(Tf.ErrorException):
            gp_pv.RemovePrimvar('indices')
        with self.assertRaises(Tf.ErrorException):
            gp_pv.RemovePrimvar('multi:aggregate:indices')

        # create Indices primvar using CreateIndexedPrimvar API
        uVal = Vt.FloatArray([1.1, 2.1, 3.1])
        indices = Vt.IntArray([0, 1, 2, 2, 1, 0])
        indexedPrimvar = gp_pv.CreateIndexedPrimvar(
            'indexedPrimvar', Sdf.ValueTypeNames.FloatArray, uVal, indices,
            UsdGeom.Tokens.vertex)
        self.assertTrue(indexedPrimvar.IsIndexed())
        self.assertTrue(indexedPrimvar.HasAuthoredValue())
        self.assertTrue(indexedPrimvar.HasAuthoredInterpolation())

        # mimic a Pixar production workflow of creating primvars
        # 1. show usage with CreatePrimvar
        # 2. show usage with CreateNonIndexedPrimvar
        # - create a primvar in base layer
        # - override this primvar in a stronger layer
        # - update primvar in base layer to use indices
        # - test if primvar has indices blocked in strong layer or not!

        # Create primvar in base layer using CreatePrimvar api and set value
        basePrimvar1 = gp_pv.CreatePrimvar('pv1',
                                           Sdf.ValueTypeNames.FloatArray)
        basePrimvar1.Set(uVal)
        # Create primvar in base layer using CreatePrimvar api and set value
        basePrimvar2 = gp_pv.CreatePrimvar('pv2',
                                           Sdf.ValueTypeNames.FloatArray)
        basePrimvar2.Set(uVal)
        # stronger layer
        strongLayer = Sdf.Layer.CreateAnonymous()
        strongStage = Usd.Stage.Open(strongLayer)
        # over Mesh prim and add reference
        oMesh = strongStage.OverridePrim('/myMesh')
        oMesh.GetReferences().AddReference(stage.GetRootLayer().identifier,
                                           '/myMesh')
        # over primvarsApi instance
        gp_pv_ovr = UsdGeom.PrimvarsAPI(oMesh)
        # override value for primvar
        oVal = Vt.FloatArray([2.2, 3.2, 4.2])
        # override pv1 using CreatePrimvar api
        oBasePrimvar1 = gp_pv_ovr.CreatePrimvar('pv1',
                                                Sdf.ValueTypeNames.FloatArray)
        oBasePrimvar1.Set(oVal)
        # override pv2 using CreateNonIndexedPrimvar api
        oBasePrimvar2 = gp_pv_ovr.CreateNonIndexedPrimvar(
            'pv2', Sdf.ValueTypeNames.FloatArray, oVal)
        # test indices attr missing on oBasePrimvar1
        self.assertFalse(oBasePrimvar1.GetIndicesAttr().IsValid())
        # test oBasePrimvar2's indices attribute has a block authored
        self.assertFalse(oBasePrimvar2.IsIndexed())
        self.assertTrue(
            oBasePrimvar2.GetIndicesAttr().GetResolveInfo().ValueIsBlocked())
        # update base (weaker) layer primvars to have an indices
        basePrimvar1.SetIndices(indices)
        basePrimvar2.SetIndices(indices)
        # ovr pv1 should now get indices
        self.assertTrue(oBasePrimvar1.IsIndexed())
        # ovr pv2 should still have the block for indices
        self.assertFalse(oBasePrimvar2.IsIndexed())
        self.assertTrue(
            oBasePrimvar2.GetIndicesAttr().GetResolveInfo().ValueIsBlocked())
示例#5
0
    def test_BasicListOpMetadata(self):
        '''Tests basic metadata API with supported list op types'''
        def _TestBasic(fieldName, listOp, expectedListOp):
            for fmt in allFormats:
                s = Usd.Stage.CreateNew("TestBasicListOpMetadata." + fmt)

                prim = s.OverridePrim('/Root')

                assert not prim.HasMetadata(fieldName)
                assert not prim.HasAuthoredMetadata(fieldName)
                self.assertEqual(prim.GetMetadata(fieldName), None)

                assert prim.SetMetadata(fieldName, listOp)
                assert prim.HasMetadata(fieldName)
                assert prim.HasAuthoredMetadata(fieldName)
                self.assertEqual(prim.GetMetadata(fieldName), expectedListOp)

                prim.ClearMetadata(fieldName)
                assert not prim.HasMetadata(fieldName)
                assert not prim.HasAuthoredMetadata(fieldName)
                self.assertEqual(prim.GetMetadata(fieldName), None)

                s.Close()

        # List ops are applied into a single explicit list op during
        # value resolution, so the expected list op isn't the same
        # as the given list op.

        # Sdf.IntListOp
        listOp = Sdf.IntListOp()
        listOp.addedItems = [-2147483648, 1, 2, 3, 2147483647]
        listOp.deletedItems = [-2147483648, 10, 20, 30, 2147483647]
        listOp.orderedItems = [2147483647, 3, 2, 1, -2147483648]

        expectedListOp = Sdf.IntListOp()
        expectedListOp.explicitItems = [2147483647, 3, 2, 1, -2147483648]
        _TestBasic('intListOpTest', listOp, expectedListOp)

        # Sdf.Int64ListOp
        listOp = Sdf.Int64ListOp()
        listOp.addedItems = [
            -9223372036854775808, 1, 2, 3, 9223372036854775807
        ]
        listOp.deletedItems = [
            -9223372036854775808, 10, 20, 30, 9223372036854775807
        ]
        listOp.orderedItems = [
            9223372036854775807, 3, 2, 1, -9223372036854775808
        ]

        expectedListOp = Sdf.Int64ListOp()
        expectedListOp.explicitItems = [
            9223372036854775807, 3, 2, 1, -9223372036854775808
        ]
        _TestBasic('int64ListOpTest', listOp, expectedListOp)

        # Sdf.UIntListOp
        listOp = Sdf.UIntListOp()
        listOp.addedItems = [1, 2, 3, 4294967295]
        listOp.deletedItems = [10, 20, 30, 4294967295]
        listOp.orderedItems = [4294967295, 3, 2, 1]

        expectedListOp = Sdf.UIntListOp()
        expectedListOp.explicitItems = [4294967295, 3, 2, 1]
        _TestBasic('uintListOpTest', listOp, expectedListOp)

        # Sdf.UInt64ListOp
        listOp = Sdf.UInt64ListOp()
        listOp.addedItems = [1, 2, 3, 18446744073709551615]
        listOp.deletedItems = [10, 20, 30, 18446744073709551615]
        listOp.orderedItems = [18446744073709551615, 3, 2, 1]

        expectedListOp = Sdf.UInt64ListOp()
        expectedListOp.explicitItems = [18446744073709551615, 3, 2, 1]
        _TestBasic('uint64ListOpTest', listOp, expectedListOp)

        # Sdf.StringListOp
        listOp = Sdf.StringListOp()
        listOp.addedItems = ["foo", "bar"]
        listOp.deletedItems = ["baz"]
        listOp.orderedItems = ["bar", "foo"]

        expectedListOp = Sdf.StringListOp()
        expectedListOp.explicitItems = ["bar", "foo"]
        _TestBasic('stringListOpTest', listOp, expectedListOp)

        # Sdf.TokenListOp
        listOp = Sdf.TokenListOp()
        listOp.addedItems = ["foo", "bar"]
        listOp.deletedItems = ["baz"]
        listOp.orderedItems = ["bar", "foo"]

        expectedListOp = Sdf.TokenListOp()
        expectedListOp.explicitItems = ["bar", "foo"]
        _TestBasic('tokenListOpTest', listOp, expectedListOp)
示例#6
0
    def test_ComposedListOpMetadata(self):
        '''Tests composition of list op-valued metadata fields'''
        def _TestComposition(fieldName, weakListOp, strongListOp,
                             expectedListOp):
            for fmt in allFormats:
                s = Usd.Stage.CreateNew("TestComposedListOpMetadata." + fmt)

                ref = s.OverridePrim('/Ref')
                ref.SetMetadata(fieldName, weakListOp)

                root = s.OverridePrim('/Root')
                root.SetMetadata(fieldName, strongListOp)
                root.GetReferences().AppendInternalReference('/Ref')

                self.assertEqual(root.GetMetadata(fieldName), expectedListOp)
                s.Close()

        # Sdf.IntListOp
        weakListOp = Sdf.IntListOp()
        weakListOp.explicitItems = [10, 20, 30]

        strongListOp = Sdf.IntListOp()
        strongListOp.addedItems = [-2147483648, 1, 2, 3, 2147483647]
        strongListOp.deletedItems = [-2147483648, 10, 20, 30, 2147483647]
        strongListOp.orderedItems = [2147483647, 3, 2, 1, -2147483648]

        expectedListOp = Sdf.IntListOp()
        expectedListOp.explicitItems = [2147483647, 3, 2, 1, -2147483648]
        _TestComposition('intListOpTest', weakListOp, strongListOp,
                         expectedListOp)

        # Sdf.Int64ListOp
        weakListOp = Sdf.Int64ListOp()
        weakListOp.explicitItems = [10, 20, 30]

        strongListOp = Sdf.Int64ListOp()
        strongListOp.addedItems = [
            -9223372036854775808, 1, 2, 3, 9223372036854775807
        ]
        strongListOp.deletedItems = [
            -9223372036854775808, 10, 20, 30, 9223372036854775807
        ]
        strongListOp.orderedItems = [
            9223372036854775807, 3, 2, 1, -9223372036854775808
        ]

        expectedListOp = Sdf.Int64ListOp()
        expectedListOp.explicitItems = [
            9223372036854775807, 3, 2, 1, -9223372036854775808
        ]
        _TestComposition('int64ListOpTest', weakListOp, strongListOp,
                         expectedListOp)

        # Sdf.UIntListOp
        weakListOp = Sdf.UIntListOp()
        weakListOp.explicitItems = [10, 20, 30]

        strongListOp = Sdf.UIntListOp()
        strongListOp.addedItems = [1, 2, 3, 4294967295]
        strongListOp.deletedItems = [10, 20, 30, 4294967295]
        strongListOp.orderedItems = [4294967295, 3, 2, 1]

        expectedListOp = Sdf.UIntListOp()
        expectedListOp.explicitItems = [4294967295, 3, 2, 1]
        _TestComposition('uintListOpTest', weakListOp, strongListOp,
                         expectedListOp)

        # Sdf.UInt64ListOp
        weakListOp = Sdf.UInt64ListOp()
        weakListOp.explicitItems = [10, 20, 30]

        strongListOp = Sdf.UInt64ListOp()
        strongListOp.addedItems = [1, 2, 3, 18446744073709551615]
        strongListOp.deletedItems = [10, 20, 30, 18446744073709551615]
        strongListOp.orderedItems = [18446744073709551615, 3, 2, 1]

        expectedListOp = Sdf.UInt64ListOp()
        expectedListOp.explicitItems = [18446744073709551615, 3, 2, 1]
        _TestComposition('uint64ListOpTest', weakListOp, strongListOp,
                         expectedListOp)

        # Sdf.StringListOp
        weakListOp = Sdf.StringListOp()
        weakListOp.explicitItems = ["baz"]

        strongListOp = Sdf.StringListOp()
        strongListOp.addedItems = ["foo", "bar"]
        strongListOp.deletedItems = ["baz"]
        strongListOp.orderedItems = ["bar", "foo"]

        expectedListOp = Sdf.StringListOp()
        expectedListOp.explicitItems = ["bar", "foo"]
        _TestComposition('stringListOpTest', weakListOp, strongListOp,
                         expectedListOp)

        # Sdf.TokenListOp
        weakListOp = Sdf.TokenListOp()
        weakListOp.explicitItems = ["baz"]

        strongListOp = Sdf.TokenListOp()
        strongListOp.addedItems = ["foo", "bar"]
        strongListOp.deletedItems = ["baz"]
        strongListOp.orderedItems = ["bar", "foo"]

        expectedListOp = Sdf.TokenListOp()
        expectedListOp.explicitItems = ["bar", "foo"]
        _TestComposition('tokenListOpTest', weakListOp, strongListOp,
                         expectedListOp)
示例#7
0
    def test_MutingSublayers(self):
        """Tests muting sublayers"""
        layer = self._LoadLayer(os.path.join(os.getcwd(),
                                             'sublayers/root.sdf'))
        sublayer = self._LoadLayer(
            os.path.join(os.getcwd(), 'sublayers/sublayer.sdf'))
        anonymousSublayer = Sdf.Layer.CreateAnonymous('.sdf')

        # Add a prim in an anonymous sublayer to the root layer for
        # testing purposes.
        Sdf.CreatePrimInLayer(anonymousSublayer, '/Root')
        layer.subLayerPaths.append(anonymousSublayer.identifier)

        # Create two Pcp.Caches for the same layer stack. This is to verify
        # that muting/unmuting a layer in one cache does not affect any
        # other that shares the same layers.
        pcp = self._LoadPcpCache(layer.identifier)
        pcp2 = self._LoadPcpCache(layer.identifier)

        (pi, err) = pcp.ComputePrimIndex('/Root')
        self.assertTrue(not err)
        self.assertEqual(pi.primStack, [
            layer.GetPrimAtPath('/Root'),
            sublayer.GetPrimAtPath('/Root'),
            anonymousSublayer.GetPrimAtPath('/Root')
        ])

        (pi2, err2) = pcp2.ComputePrimIndex('/Root')
        self.assertTrue(not err2)
        self.assertEqual(pi2.primStack, [
            layer.GetPrimAtPath('/Root'),
            sublayer.GetPrimAtPath('/Root'),
            anonymousSublayer.GetPrimAtPath('/Root')
        ])

        # Muting the cache's root layer is explicitly disallowed.
        with self.assertRaises(Tf.ErrorException):
            pcp.RequestLayerMuting([layer.identifier], [])

        # Mute sublayer and verify that change processing has occurred
        # and that it no longer appears in /Root's prim stack.
        pcp.RequestLayerMuting([sublayer.identifier], [])
        (pi, err) = pcp.ComputePrimIndex('/Root')
        self.assertTrue(not err)
        self.assertEqual(pi.primStack, [
            layer.GetPrimAtPath('/Root'),
            anonymousSublayer.GetPrimAtPath('/Root')
        ])

        (pi2, err2) = pcp2.ComputePrimIndex('/Root')
        self.assertTrue(not err2)
        self.assertEqual(pi2.primStack, [
            layer.GetPrimAtPath('/Root'),
            sublayer.GetPrimAtPath('/Root'),
            anonymousSublayer.GetPrimAtPath('/Root')
        ])

        # Unmute sublayer and verify that it comes back into /Root's
        # prim stack.
        pcp.RequestLayerMuting([], [sublayer.identifier])
        (pi, err) = pcp.ComputePrimIndex('/Root')
        self.assertTrue(not err)
        self.assertEqual(pi.primStack, [
            layer.GetPrimAtPath('/Root'),
            sublayer.GetPrimAtPath('/Root'),
            anonymousSublayer.GetPrimAtPath('/Root')
        ])

        (pi2, err2) = pcp2.ComputePrimIndex('/Root')
        self.assertTrue(not err2)
        self.assertEqual(pi2.primStack, [
            layer.GetPrimAtPath('/Root'),
            sublayer.GetPrimAtPath('/Root'),
            anonymousSublayer.GetPrimAtPath('/Root')
        ])

        # Mute sublayer and verify that change processing has occurred
        # and that it no longer appears in /Root's prim stack.
        pcp.RequestLayerMuting([anonymousSublayer.identifier], [])
        (pi, err) = pcp.ComputePrimIndex('/Root')
        self.assertTrue(not err)
        self.assertEqual(
            pi.primStack,
            [layer.GetPrimAtPath('/Root'),
             sublayer.GetPrimAtPath('/Root')])
        self.assertTrue(anonymousSublayer)

        (pi2, err2) = pcp2.ComputePrimIndex('/Root')
        self.assertTrue(not err2)
        self.assertEqual(pi2.primStack, [
            layer.GetPrimAtPath('/Root'),
            sublayer.GetPrimAtPath('/Root'),
            anonymousSublayer.GetPrimAtPath('/Root')
        ])

        # Unmute sublayer and verify that it comes back into /Root's
        # prim stack.
        pcp.RequestLayerMuting([], [anonymousSublayer.identifier])
        (pi, err) = pcp.ComputePrimIndex('/Root')
        self.assertTrue(not err)
        self.assertEqual(pi.primStack, [
            layer.GetPrimAtPath('/Root'),
            sublayer.GetPrimAtPath('/Root'),
            anonymousSublayer.GetPrimAtPath('/Root')
        ])

        (pi2, err2) = pcp2.ComputePrimIndex('/Root')
        self.assertTrue(not err2)
        self.assertEqual(pi2.primStack, [
            layer.GetPrimAtPath('/Root'),
            sublayer.GetPrimAtPath('/Root'),
            anonymousSublayer.GetPrimAtPath('/Root')
        ])
    def test_Basic(self):
        # There are a number of ways we could vary shading between wet and dry...
        # We're choosing the biggest hammer, which is to completely swap out
        # the surface shader (which is how it has been done in our pipeline)
        shadeVariations = ["Wet", "Dry"]

        # For each "base" we will have a Material, and a single Shader as the surface.
        # In reality there's likely be many more shading components/prims feeding
        # the surfaces.
        materialBases = ["Hair", "Skin", "Nails"]

        shadersPath = Sdf.Path("/ShadingDefs/Shaders")
        materialsPath = Sdf.Path("/ShadingDefs/Materials")

        def MakeSurfacePath(base, variant, prop=None):
            retval = shadersPath.AppendChild(base + variant + "Surface")
            if prop:
                retval = retval.AppendProperty(prop)
            return retval

        def MakeDisplacementPath(base, variant, prop=None):
            retval = shadersPath.AppendChild(base + variant + "Disp")
            if prop:
                retval = retval.AppendProperty(prop)
            return retval

        def MakePatternPath(base, variant, prop=None):
            retval = shadersPath.AppendChild(base + variant + "Pattern")
            if prop:
                retval = retval.AppendProperty(prop)
            return retval

        def MakeMaterialPath(base, prop=None):
            retval = materialsPath.AppendChild(base + "Material")
            if prop:
                retval = retval.AppendProperty(prop)
            return retval

        #def CreateTerminal(material, name, targetPath):
        #terminalRel = material.GetPrim().CreateRelationship("terminal:%s" % name)
        #terminalRel.SetTargets([targetPath,]);
        #return terminalRel

        def SetupShading(stage):
            # First create the shading prims
            UsdGeom.Scope.Define(stage, shadersPath)
            UsdGeom.Scope.Define(stage, materialsPath)
            # .. and as we create each surface, bind the associated material's variant to it
            allMaterials = []
            for material in materialBases:
                materialPrim = UsdShade.Material.Define(
                    stage, MakeMaterialPath(material))
                allMaterials.append(materialPrim.GetPrim())
                for variant in shadeVariations:
                    surface = UsdShade.Shader.Define(
                        stage, MakeSurfacePath(material, variant))
                    colorOut = surface.CreateOutput("out",
                                                    Sdf.ValueTypeNames.Color3f)

                    disp = UsdShade.Shader.Define(
                        stage, MakeDisplacementPath(material, variant))
                    dispOut = disp.CreateOutput('out',
                                                Sdf.ValueTypeNames.Vector3f)

                    pattern = UsdShade.Shader.Define(
                        stage, MakePatternPath(material, variant))
                    patternOut = pattern.CreateOutput(
                        "out", Sdf.ValueTypeNames.FloatArray)

                    with materialPrim.GetEditContextForVariant(variant):
                        surfaceOutput = materialPrim.CreateOutput(
                            "surface", colorOut.GetTypeName())
                        UsdShade.ConnectableAPI.ConnectToSource(
                            surfaceOutput,
                            UsdShade.ConnectableAPI(colorOut.GetPrim()),
                            colorOut.GetBaseName(),
                            UsdShade.AttributeType.Output)

                        displacementOutput = materialPrim.CreateOutput(
                            "displacement", dispOut.GetTypeName())
                        UsdShade.ConnectableAPI.ConnectToSource(
                            displacementOutput, dispOut)

                        patternOutput = materialPrim.CreateOutput(
                            "pattern", patternOut.GetTypeName())
                        UsdShade.ConnectableAPI.ConnectToSource(
                            patternOutput, patternOut)

                        # XXX: If we replace these terminals with UsdShadeOutput's, then
                        ## we can't have these point to prim paths.
                        #surfacePath = MakeSurfacePath(material, variant, 'out')
                        #CreateTerminal(materialPrim, "surface", surfacePath)

                        #dispPath = MakeDisplacementPath(material, variant, 'out')
                        #CreateTerminal(materialPrim, "displacement", dispPath)

                        #CreateTerminal(materialPrim, 'pattern',
                        #MakePatternPath(material, variant, 'out'))

            return allMaterials

        def ValidateMaterial(stage):
            hairPrim = stage.GetPrimAtPath(
                '/ModelShading/Materials/HairMaterial')
            hairMaterial = UsdShade.Material(hairPrim)
            self.assertTrue(hairMaterial)
            wetHairSurfPath = Sdf.Path(
                '/ModelShading/Shaders/HairWetSurface.out')
            wetHairDispPath = Sdf.Path('/ModelShading/Shaders/HairWetDisp.out')
            wetHairPatternPath = Sdf.Path(
                '/ModelShading/Shaders/HairWetPattern.out')

            connectedSurface = UsdShade.ConnectableAPI.GetConnectedSource(
                hairMaterial.GetOutput('surface'))
            connectedSurfacePath = connectedSurface[0].GetPath(
            ).AppendProperty(connectedSurface[1])
            self.assertEqual(connectedSurfacePath, wetHairSurfPath)

            connectedDisplacement = UsdShade.ConnectableAPI.GetConnectedSource(
                hairMaterial.GetOutput('displacement'))
            connectedDisplacementPath = connectedDisplacement[0].GetPath(
            ).AppendProperty(connectedDisplacement[1])
            self.assertEqual(connectedDisplacementPath, wetHairDispPath)

            connectedPattern = UsdShade.ConnectableAPI.GetConnectedSource(
                hairMaterial.GetOutput('pattern'))
            connectedPatternPath = connectedPattern[0].GetPath(
            ).AppendProperty(connectedPattern[1])
            self.assertEqual(connectedPatternPath, wetHairPatternPath)

            # change the root-level variantSet, which should in turn change the Material's
            self.assertTrue(rootPrim.GetVariantSets().SetSelection(
                "materialVariant", "Dry"))
            self.assertTrue(hairMaterial)
            dryHairSurfPath = Sdf.Path(
                '/ModelShading/Shaders/HairDrySurface.out')
            dryHairDispPath = Sdf.Path('/ModelShading/Shaders/HairDryDisp.out')
            dryHairPatternPath = Sdf.Path(
                '/ModelShading/Shaders/HairDryPattern.out')

            connectedSurface = UsdShade.ConnectableAPI.GetConnectedSource(
                hairMaterial.GetOutput('surface'))
            connectedSurfacePath = connectedSurface[0].GetPath(
            ).AppendProperty(connectedSurface[1])
            self.assertEqual(connectedSurfacePath, dryHairSurfPath)

            connectedDisplacement = UsdShade.ConnectableAPI.GetConnectedSource(
                hairMaterial.GetOutput('displacement'))
            connectedDisplacementPath = connectedDisplacement[0].GetPath(
            ).AppendProperty(connectedDisplacement[1])
            self.assertEqual(connectedDisplacementPath, dryHairDispPath)

            connectedPattern = UsdShade.ConnectableAPI.GetConnectedSource(
                hairMaterial.GetOutput('pattern'))
            connectedPatternPath = connectedPattern[0].GetPath(
            ).AppendProperty(connectedPattern[1])
            self.assertEqual(connectedPatternPath, dryHairPatternPath)

        fileName = "char_shading.usda"
        stage = Usd.Stage.CreateNew(fileName)

        # Create this prim first, since it's the "entrypoint" to the layer, and
        # we want it to appear at the top
        rootPrim = stage.DefinePrim("/ModelShading")

        # Next, create a tree that will "sit on top of ShadingDefs" to switch the
        # materials in concert
        allMaterials = SetupShading(stage)
        bindingVariantRoot = stage.OverridePrim("/MaterialBindingVariants")
        UsdShade.Material.CreateMasterMaterialVariant(bindingVariantRoot,
                                                      allMaterials)

        # Finally, this is how we stitch them together into an interface.
        # This is the root prim that a client would target to pull in shading
        refs = rootPrim.GetReferences()
        # XXX We need a better way of specifying self-references
        refs.AppendReference("./" + fileName, "/MaterialBindingVariants")
        refs.AppendReference("./" + fileName, "/ShadingDefs")

        stage.GetRootLayer().Save()

        # Now let's do some validation that it performs as expected
        ValidateMaterial(stage)

        # Now let's make a variation of the above in which we do the master variant
        # on a composed stage in which rootPrim is already referencing the ShadingDefs,
        # and operating on the composed Material prims
        fileName = "char_shading_compact.usda"
        stage = Usd.Stage.CreateNew(fileName)

        # Create this prim first, since it's the "entrypoint" to the layer, and
        # we want it to appear at the top
        rootPrim = stage.DefinePrim("/ModelShading")

        SetupShading(stage)
        # Reference the shading directly
        refs = rootPrim.GetReferences()
        refs.AppendReference("./" + fileName, "/ShadingDefs")

        # Now pick up the newly composed material prims
        allMaterials = [
            stage.GetPrimAtPath("/ModelShading/Materials/HairMaterial"),
            stage.GetPrimAtPath("/ModelShading/Materials/SkinMaterial"),
            stage.GetPrimAtPath("/ModelShading/Materials/NailsMaterial")
        ]

        UsdShade.Material.CreateMasterMaterialVariant(rootPrim, allMaterials)

        stage.GetRootLayer().Save()

        # Now let's do some validation that it performs as expected
        ValidateMaterial(stage)

        # TODO: move this into it's own test
        hairPrim = stage.GetPrimAtPath('/ModelShading/Materials/HairMaterial')
        hairMaterial = UsdShade.Material(hairPrim)
        interfaceInput = hairMaterial.CreateInput("myParam",
                                                  Sdf.ValueTypeNames.Float)
        interfaceInput.SetDocumentation("this is my float")
        interfaceInput.SetDisplayGroup("numbers")

        byName = hairMaterial.GetInput("myParam")
        self.assertTrue(byName
                        and (byName.GetDocumentation() == "this is my float")
                        and (byName.GetDisplayGroup() == "numbers"))

        plain = hairPrim.GetAttribute(byName.GetFullName())
        self.assertTrue(plain and (plain.GetTypeName() == "float"))
示例#9
0
    def test_CreateCollection(self):
        collection = UsdGeom.CollectionAPI.Create(root, "includes")
        (valid, reason) = collection.Validate()
        self.assertTrue(valid)

        collection.AddTarget(sphere.GetPath())
        collection.AddTarget(cube.GetPath(), [1, 3, 5])
        collection.AddTarget(cylinder.GetPath())
        collection.AddTarget(cone.GetPath(), [2, 4, 6, 8])

        self.assertEqual(collection.GetTargets(), [
            Sdf.Path('/CollectionTest/Geom/pSphere1'),
            Sdf.Path('/CollectionTest/Geom/pCube1'),
            Sdf.Path('/CollectionTest/Geom/pCylinder1'),
            Sdf.Path('/CollectionTest/Geom/pCone1')
        ])
        self.assertEqual(list(collection.GetTargetFaceCounts()), [0, 3, 0, 4])
        self.assertEqual(list(collection.GetTargetFaceIndices()),
                         [1, 3, 5, 2, 4, 6, 8])

        rootModel = Usd.ModelAPI(root)
        # Try invoking Create() with a schema object.
        # Also test re-creating an existing collection.
        sameCollection = UsdGeom.CollectionAPI.Create(rootModel, "includes")
        self.assertEqual(sameCollection.GetTargets(), [
            Sdf.Path('/CollectionTest/Geom/pSphere1'),
            Sdf.Path('/CollectionTest/Geom/pCube1'),
            Sdf.Path('/CollectionTest/Geom/pCylinder1'),
            Sdf.Path('/CollectionTest/Geom/pCone1')
        ])
        self.assertEqual(list(sameCollection.GetTargetFaceCounts()),
                         [0, 3, 0, 4])
        self.assertEqual(list(sameCollection.GetTargetFaceIndices()),
                         [1, 3, 5, 2, 4, 6, 8])

        # Call Create() with a new set of targets, targetFaceCounts and targetFaceIndices.
        collection = UsdGeom.CollectionAPI.Create(
            rootModel,
            "includes",
            targets=[
                Sdf.Path('/CollectionTest/Geom/pCylinder1'),
                Sdf.Path('/CollectionTest/Geom/pCone1')
            ],
            targetFaceCounts=[2, 5],
            targetFaceIndices=[0, 1, 0, 1, 2, 3, 4])
        self.assertEqual(collection.GetTargets(), [
            Sdf.Path('/CollectionTest/Geom/pCylinder1'),
            Sdf.Path('/CollectionTest/Geom/pCone1')
        ])
        self.assertEqual(list(collection.GetTargetFaceCounts()), [2, 5])
        self.assertEqual(list(collection.GetTargetFaceIndices()),
                         [0, 1, 0, 1, 2, 3, 4])
示例#10
0
    def test_ClearPayload(self):
        for fmt in allFormats:
            p = PayloadedScene(fmt)
            p.stage.Load()

            # We expect these prims to survive the edits below, so hold weak 
            # ptrs to them to verify this assumption.
            sad = p.stage.GetPrimAtPath("/Sad")
            baz = p.stage.GetPrimAtPath("/Foo/Baz")
            grizzly = p.stage.GetPrimAtPath("/Grizzly")
            intPayload = p.stage.GetPrimAtPath("/IntPayload")

            self.assertTrue(sad.HasAuthoredPayloads())
            self.assertTrue(baz.HasAuthoredPayloads())
            self.assertTrue(grizzly.HasAuthoredPayloads())
            self.assertTrue(intPayload.HasAuthoredPayloads())

            #
            # Try clearing the payload while the prim is unloaded.
            #
            self.assertTrue(sad.IsLoaded())
            self.assertTrue(sad.GetMetadata("payload"))
            sad.Unload()
            self.assertTrue(sad.GetMetadata("payload"))
            self.assertTrue(not sad.IsLoaded())
            self.assertTrue(sad.GetPayloads().ClearPayloads())
            self.assertTrue(not sad.HasAuthoredPayloads())
            self.assertEqual(sad.GetMetadata("payload"), None)
            # Assert that it's loaded because anything without a payload is
            # considered loaded.
            self.assertTrue(sad.IsLoaded())

            #
            # Unload this one while it's loaded.
            #
            self.assertTrue(baz.IsLoaded())
            self.assertTrue(baz.GetMetadata("payload"))
            self.assertTrue(baz.GetPayloads().ClearPayloads())
            self.assertTrue(not baz.HasAuthoredPayloads())
            self.assertEqual(baz.GetMetadata("payload"), None)
            # Again, assert that it's loaded because anything without a payload 
            # is considered loaded.
            self.assertTrue(baz.IsLoaded())

            #
            # Unload this one while it's loaded.
            #
            self.assertTrue(grizzly.IsLoaded())
            self.assertTrue(grizzly.GetMetadata("payload"))
            self.assertTrue(grizzly.GetPayloads().ClearPayloads())
            self.assertTrue(not grizzly.HasAuthoredPayloads())
            self.assertEqual(grizzly.GetMetadata("payload"), None)
            # Again, assert that it's loaded because anything without a payload 
            # is considered loaded.
            self.assertTrue(grizzly.IsLoaded())

            #
            # Unload this one while it's loaded.
            #
            self.assertTrue(intPayload.IsLoaded())
            self.assertTrue(intPayload.GetMetadata("payload"))
            self.assertTrue(intPayload.GetPayloads().ClearPayloads())
            self.assertTrue(not intPayload.HasAuthoredPayloads())
            self.assertEqual(intPayload.GetMetadata("payload"), None)
            # Again, assert that it's loaded because anything without a payload 
            # is considered loaded.
            self.assertTrue(intPayload.IsLoaded())

            # Set the list of payloads to explicitly empty from cleared
            # verifying that it is indeed set to explicit.empty list op
            self.assertTrue(intPayload.GetPayloads().SetPayloads([]))
            # XXX: Though there is payload metadata that is an explicit empty
            # payload list op, HasAuthoredPayloads still returns true as there
            # are no actual payloads for this prim. This is inconsistent with
            # explicit empty list op behavior of 
            # HasAuthoredReferences/Inherits/Specializes which only return 
            # whether metadata is present. This inconsistency should be fixed.
            self.assertTrue(not intPayload.HasAuthoredPayloads())
            explicitEmpty = Sdf.PayloadListOp()
            explicitEmpty.ClearAndMakeExplicit()
            self.assertEqual(intPayload.GetMetadata("payload"), explicitEmpty)
示例#11
0
    def test_Payloads(self):
        for fmt in allFormats:
            p = PayloadedScene(fmt)

            # These assertions will be used several times.
            def AssertBaseAssumptions():
                self.assertTrue(
                    not p.stage.GetPrimAtPath("/").HasAuthoredPayloads())
                self.assertTrue(
                    p.stage.GetPrimAtPath("/Sad").HasAuthoredPayloads())
                self.assertTrue(
                    p.stage.GetPrimAtPath("/Foo/Baz").HasAuthoredPayloads())
                self.assertTrue(
                    p.stage.GetPrimAtPath("/Grizzly").HasAuthoredPayloads())
                self.assertTrue(
                    p.stage.GetPrimAtPath("/IntPayload").HasAuthoredPayloads())
                self.assertEqual(
                    p.stage.GetPrimAtPath("/Foo/Baz").\
                        GetMetadata("payload").prependedItems,
                    [Sdf.Payload(p.payload2.GetRootLayer().identifier, "/Baz")])
                self.assertEqual(
                    p.stage.GetPrimAtPath("/Sad").\
                        GetMetadata("payload").prependedItems,
                    [Sdf.Payload(p.payload1.GetRootLayer().identifier, "/Sad")])
                self.assertEqual(
                    p.stage.GetPrimAtPath("/Grizzly").\
                        GetMetadata("payload").explicitItems,
                    [Sdf.Payload(p.payload5.GetRootLayer().identifier, "/Bear"),
                     Sdf.Payload(p.payload6.GetRootLayer().identifier, "/Adams")])
                self.assertEqual(
                    p.stage.GetPrimAtPath("/IntPayload").\
                        GetMetadata("payload").prependedItems,
                    [Sdf.Payload("", "/IntBase")])

            AssertBaseAssumptions()

            #
            # The following prims must be loaded to be reachable.
            #
            p.stage.Load()
            self.assertTrue(
                not p.stage.GetPrimAtPath("/Sad/Panda").HasAuthoredPayloads())
            self.assertTrue(
                p.stage.GetPrimAtPath("/Foo/Baz/Garply").HasAuthoredPayloads())
            self.assertEqual(
                p.stage.GetPrimAtPath("/Foo/Baz/Garply").\
                    GetMetadata("payload").explicitItems,
                [Sdf.Payload(p.payload3.GetRootLayer().identifier, "/Garply")])
            self.assertTrue(not p.stage.GetPrimAtPath("/Grizzly/Market").\
                                HasAuthoredPayloads())
            self.assertTrue(not p.stage.GetPrimAtPath("/Grizzly/Onis").\
                                HasAuthoredPayloads())
            self.assertTrue(not p.stage.GetPrimAtPath("/IntPayload/IntContents").\
                                HasAuthoredPayloads())

            #
            # We do not expect the previous assertions to change based on load
            # state.
            #
            AssertBaseAssumptions()
            p.stage.Unload()
            AssertBaseAssumptions()
示例#12
0
    def __init__(self, fmt):
        # Construct the following test case:
        #
        # stage.fmt         payload1.fmt
        #   /Sad  ---(P)---> /Sad
        #   |                /Sad/Panda
        #   |
        #   |                   
        #   /Foo                payload2.fmt
        #   /Foo/Baz ---(P)---> /Baz                   payload3.fmt
        #   |                   /Baz/Garply ---(P)---> /Garply
        #   |                                          /Garply/Qux
        #   |               payload4.fmt
        #   |                /Corge
        #   /Bar ---(P)--->  /Corge/Waldo
        #   |                /Corge/Waldo/Fred
        #   |
        #   |                   payload5.fmt
        #   /Grizzly ---(P)---> /Bear
        #   |            |      /Bear/Market
        #   |            |
        #   |            |      payload6.fmt
        #   |           (P)---> /Adams
        #   |                   /Adams/Onis
        #   |
        #   /IntBase
        #   /IntBase/IntContents
        #   |
        #   /IntPayload ---(P) ---> /IntBase
        #                           /IntBase/IntContents

        # Create payload1.fmt
        self.payload1 = Usd.Stage.CreateInMemory("payload1."+fmt)
        p = self.payload1.DefinePrim("/Sad/Panda", "Scope")

        # Create payload3.fmt
        self.payload3 = Usd.Stage.CreateInMemory("payload3."+fmt)
        p = self.payload3.DefinePrim("/Garply/Qux", "Scope")

        # Create payload2.fmt
        # Intentionally using the metadata API.
        self.payload2 = Usd.Stage.CreateInMemory("payload2."+fmt)
        p = self.payload2.DefinePrim("/Baz/Garply", "Scope")
        payloadListOp = Sdf.PayloadListOp()
        payloadListOp.explicitItems = [
            Sdf.Payload(self.payload3.GetRootLayer().identifier, "/Garply")]
        p.SetMetadata("payload", payloadListOp)

        # Create payload4.fmt
        self.payload4 = Usd.Stage.CreateInMemory("payload4."+fmt)
        p = self.payload4.DefinePrim("/Corge/Waldo/Fred", "Scope")

        # Create payload5.fmt
        self.payload5 = Usd.Stage.CreateInMemory("payload5."+fmt)
        p = self.payload5.DefinePrim("/Bear/Market", "Scope")

        # Create payload6.fmt
        self.payload6 = Usd.Stage.CreateInMemory("payload6."+fmt)
        p = self.payload6.DefinePrim("/Adams/Onis", "Scope")

        #
        # Create the scene that references payload1 and payload2
        #
        # Intentionally using the prim-payload API.
        self.stage = Usd.Stage.CreateInMemory("scene."+fmt)
        p = self.stage.DefinePrim("/Sad", "Scope")
        p.GetPayloads().AddPayload(
            Sdf.Payload(self.payload1.GetRootLayer().identifier, "/Sad"))

        # Intentionally using the overloaded prim-payload API.
        p = self.stage.DefinePrim("/Foo/Baz", "Scope")
        p.GetPayloads().AddPayload(
            self.payload2.GetRootLayer().identifier, "/Baz")

        # Create a sub-root payload.
        p = self.stage.DefinePrim("/Bar", "Scope")
        p.GetPayloads().AddPayload(
            self.payload4.GetRootLayer().identifier, "/Corge/Waldo")

        # Create a list of payloads.
        p = self.stage.DefinePrim("/Grizzly", "Scope")
        p.GetPayloads().SetPayloads([
            Sdf.Payload(self.payload5.GetRootLayer().identifier, "/Bear"),
            Sdf.Payload(self.payload6.GetRootLayer().identifier, "/Adams")])

        p = self.stage.DefinePrim("/IntBase/IntContents", "Scope")
        p = self.stage.DefinePrim("/IntPayload", "Scope")
        p.GetPayloads().AddInternalPayload("/IntBase")

        # Test expects initial state to be all unloaded.
        self.stage.Unload()
示例#13
0
    def test_InstancesWithPayloads(self):
        for fmt in allFormats:
            p = InstancedAndPayloadedScene(fmt)

            self.assertEqual(
                set(p.stage.FindLoadable()),
                set([Sdf.Path("/Sad"), Sdf.Path("/Sad_1"), 
                     Sdf.Path("/Foo/Baz"), Sdf.Path("/Foo/Baz_1"),
                     Sdf.Path("/Bar"), Sdf.Path("/Bar_1"),
                     Sdf.Path("/Grizzly"), Sdf.Path("/Grizzly_1"),
                     Sdf.Path("/IntPayload"), Sdf.Path("/IntPayload_1")]))

            sad = p.stage.GetPrimAtPath("/Sad")
            sad_1 = p.stage.GetPrimAtPath("/Sad_1")

            bar = p.stage.GetPrimAtPath("/Bar")
            bar_1 = p.stage.GetPrimAtPath("/Bar_1")

            grizzly = p.stage.GetPrimAtPath("/Grizzly")
            grizzly_1 = p.stage.GetPrimAtPath("/Grizzly_1")

            intPayload = p.stage.GetPrimAtPath("/IntPayload")
            intPayload_1 = p.stage.GetPrimAtPath("/IntPayload_1")

            # All instances should report that they have payloads authored
            # directly on them, but have not yet been loaded.
            self.assertTrue(sad.HasAuthoredPayloads())
            self.assertTrue(sad_1.HasAuthoredPayloads())
            self.assertTrue(not sad.IsLoaded())
            self.assertTrue(not sad_1.IsLoaded())

            self.assertTrue(bar.HasAuthoredPayloads())
            self.assertTrue(bar_1.HasAuthoredPayloads())
            self.assertTrue(not bar.IsLoaded())
            self.assertTrue(not bar_1.IsLoaded())

            self.assertTrue(grizzly.HasAuthoredPayloads())
            self.assertTrue(grizzly_1.HasAuthoredPayloads())
            self.assertTrue(not grizzly.IsLoaded())
            self.assertTrue(not grizzly_1.IsLoaded())

            self.assertTrue(intPayload.HasAuthoredPayloads())
            self.assertTrue(intPayload_1.HasAuthoredPayloads())
            self.assertTrue(not intPayload.IsLoaded())
            self.assertTrue(not intPayload_1.IsLoaded())

            # Since there is no composition arc to instanceable data
            # (due to the payloads not being loaded), these prims have no
            # master.
            self.assertTrue(not sad.GetMaster())
            self.assertTrue(not sad_1.GetMaster())

            self.assertTrue(not bar.GetMaster())
            self.assertTrue(not bar_1.GetMaster())

            self.assertTrue(not grizzly.GetMaster())
            self.assertTrue(not grizzly_1.GetMaster())

            self.assertTrue(not intPayload.GetMaster())
            self.assertTrue(not intPayload_1.GetMaster())

            # Instances should be independently loadable. This should
            # cause a master to be created for the loaded prim.
            sad.Load()
            self.assertTrue(sad.IsLoaded())
            self.assertTrue(not sad_1.IsLoaded())
            self.assertTrue(sad.GetMaster())
            self.assertTrue(not sad_1.GetMaster())

            bar.Load()
            self.assertTrue(bar.IsLoaded())
            self.assertTrue(not bar_1.IsLoaded())
            self.assertTrue(bar.GetMaster())
            self.assertTrue(not bar_1.GetMaster())

            grizzly.Load()
            self.assertTrue(grizzly.IsLoaded())
            self.assertTrue(not grizzly_1.IsLoaded())
            self.assertTrue(grizzly.GetMaster())
            self.assertTrue(not grizzly_1.GetMaster())

            intPayload.Load()
            self.assertTrue(intPayload.IsLoaded())
            self.assertTrue(not intPayload_1.IsLoaded())
            self.assertTrue(intPayload.GetMaster())
            self.assertTrue(not intPayload_1.GetMaster())

            # The master prim should not report that it has a loadable
            # payload. Its load state cannot be independently controlled.
            master = sad.GetMaster()
            self.assertTrue(not master.HasAuthoredPayloads())
            self.assertTrue(master not in p.stage.FindLoadable())
            self.assertEqual([prim.GetName() for prim in master.GetChildren()],
                             ["Panda"])

            master2 = bar.GetMaster()
            self.assertTrue(not master2.HasAuthoredPayloads())
            self.assertTrue(master2 not in p.stage.FindLoadable())
            self.assertEqual([prim.GetName() for prim in master2.GetChildren()],
                             ["Fred"])

            master3 = grizzly.GetMaster()
            self.assertTrue(not master3.HasAuthoredPayloads())
            self.assertTrue(master3 not in p.stage.FindLoadable())
            self.assertEqual([prim.GetName() for prim in master3.GetChildren()],
                             ["Onis", "Market"])

            master4 = intPayload.GetMaster()
            self.assertTrue(not master4.HasAuthoredPayloads())
            self.assertTrue(master4 not in p.stage.FindLoadable())
            self.assertEqual([prim.GetName() for prim in master4.GetChildren()],
                             ["IntContents"])

            # Loading the second instance will cause Usd to assign it to the
            # first instance's master.
            sad_1.Load()
            self.assertEqual(sad.GetMaster(), sad_1.GetMaster())

            sad.Unload()
            sad_1.Unload()
            self.assertTrue(not sad.IsLoaded())
            self.assertTrue(not sad_1.IsLoaded())
            self.assertTrue(not sad.GetMaster())
            self.assertTrue(not sad_1.GetMaster())
            self.assertTrue(not master)

            bar_1.Load()
            self.assertEqual(bar.GetMaster(), bar_1.GetMaster())

            bar.Unload()
            bar_1.Unload()
            self.assertTrue(not bar.IsLoaded())
            self.assertTrue(not bar_1.IsLoaded())
            self.assertTrue(not bar.GetMaster())
            self.assertTrue(not bar_1.GetMaster())
            self.assertTrue(not master2)

            grizzly_1.Load()
            self.assertEqual(grizzly.GetMaster(), grizzly_1.GetMaster())

            grizzly.Unload()
            grizzly_1.Unload()
            self.assertTrue(not grizzly.IsLoaded())
            self.assertTrue(not grizzly_1.IsLoaded())
            self.assertTrue(not grizzly.GetMaster())
            self.assertTrue(not grizzly_1.GetMaster())
            self.assertTrue(not master3)

            intPayload_1.Load()
            self.assertEqual(intPayload.GetMaster(), intPayload_1.GetMaster())

            intPayload.Unload()
            intPayload_1.Unload()
            self.assertTrue(not intPayload.IsLoaded())
            self.assertTrue(not intPayload_1.IsLoaded())
            self.assertTrue(not intPayload.GetMaster())
            self.assertTrue(not intPayload_1.GetMaster())
            self.assertTrue(not master4)

            # Loading the payload for an instanceable prim will cause
            # payloads nested in descendants of that prim's master to be 
            # loaded as well.
            baz = p.stage.GetPrimAtPath("/Foo/Baz")
            baz_1 = p.stage.GetPrimAtPath("/Foo/Baz_1")

            baz.Load()
            self.assertTrue(baz.IsLoaded())
            self.assertTrue(baz.GetMaster())

            master = baz.GetMaster()
            self.assertEqual(
                [prim.GetName() for prim in master.GetChildren()], ["Garply"])

            garply = master.GetChild("Garply")
            self.assertTrue(garply.HasAuthoredPayloads())
            self.assertTrue(garply.IsLoaded())
            self.assertTrue(garply.GetMaster())

            master = garply.GetMaster()
            self.assertEqual([prim.GetName() for prim in master.GetChildren()],
                             ["Qux"])

            baz_1.Load()
            self.assertEqual(baz.GetMaster(), baz_1.GetMaster())

            # Prims in masters cannot be individually (un)loaded.
            with self.assertRaises(Tf.ErrorException):
                garply.Unload()