def test_ResolveWithDefaultAssetContext(self): assetFileName = 'test_Asset.txt' assetFilePath = os.path.abspath(assetFileName) with open(assetFilePath, 'w') as ofp: print('Garbage', file=ofp) testFileName = 'test_SiblingOfAsset.txt' testFilePath = os.path.abspath(testFileName) with open(testFilePath, 'w') as ofp: print('Garbage', file=ofp) # We use the non-absolute assetFileName to test the # cwd-anchoring behavior of CreateDefaultContextForAsset() context = Ar.GetResolver().CreateDefaultContextForAsset(assetFileName) with Ar.ResolverContextBinder(context): resolvedPath = Ar.GetResolver().Resolve(testFileName) self.assertPathsEqual(resolvedPath, testFilePath) # Make sure we get the same behavior using ConfigureResolverForAsset() Ar.GetResolver().ConfigureResolverForAsset(assetFileName) with Ar.ResolverContextBinder(Ar.GetResolver().CreateDefaultContext()): defaultResolvedPath = Ar.GetResolver().Resolve(testFileName) self.assertPathsEqual(defaultResolvedPath, testFilePath)
def test_ResolveWithContext(self): testDir = os.path.abspath('test3/test4') if os.path.isdir(testDir): shutil.rmtree(testDir) os.makedirs(testDir) testFileName = 'test_ResolveWithContext.txt' testFilePath = os.path.join(testDir, testFileName) with open(testFilePath, 'w') as ofp: print >> ofp, 'Garbage' resolver = Ar.GetResolver() context = Ar.DefaultResolverContext( [os.path.abspath('test3'), os.path.abspath('test3/test4')]) self.assertPathsEqual( '', resolver.Resolve('test4/test_ResolveWithContext.txt')) with Ar.ResolverContextBinder(context): self.assertPathsEqual( os.path.abspath('test3/test4/test_ResolveWithContext.txt'), resolver.Resolve('test4/test_ResolveWithContext.txt')) self.assertPathsEqual( os.path.abspath('test3/test4/test_ResolveWithContext.txt'), resolver.Resolve('test_ResolveWithContext.txt')) self.assertPathsEqual( '', resolver.Resolve('test4/test_ResolveWithContext.txt'))
def expandPath(path, parentPath=None, sdf_format_args=None): """ Expand and normalize a path that may have variables in it. :Parameters: path : `str` File path parentPath : `str` | None Parent file path this file is defined in relation to. Helps with asset resolution. sdf_format_args : `dict` | None Dictionary of key/value `str` pairs from a path's :SDF_FORMAT_ARGS: :Returns: Normalized path with variables expanded. :Rtype: `str` """ if resolver is not None: try: resolver.ConfigureResolverForAsset(path) context = resolver.CreateDefaultContextForAsset(path) with Ar.ResolverContextBinder(context): anchoredPath = path if parentPath is None else resolver.AnchorRelativePath( parentPath, path) resolved = resolver.Resolve(anchoredPath) except Exception: logger.warn( "Failed to resolve Asset path {} with parent {}".format( path, parentPath)) else: if resolved: return resolved # Return this best-attempt if all else fails. return os.path.expandvars(os.path.expanduser(os.path.normpath(path)))
def convert_to_usd(gltf_file, usd_file, fps, scale, arkit=False, verbose=False, use_euler_rotation=False): """Converts a glTF file to USD Arguments: gltf_file {str} -- path to glTF file usd_file {str} -- path to write USD file Keyword Arguments: verbose {bool} -- [description] (default: {False}) """ usd = GLTF2USD(gltf_file=gltf_file, usd_file=usd_file, fps=fps, scale=scale, verbose=verbose, use_euler_rotation=use_euler_rotation) if usd.stage: asset = usd.stage.GetRootLayer() usd.logger.info('Conversion complete!') asset.Save() usd.logger.info('created {}'.format(asset.realPath)) if usd_file.endswith('.usdz') or usd_file.endswith('.usdc'): usdc_file = '%s.%s' % (os.path.splitext(usd_file)[0], 'usdc') asset.Export(usdc_file, args=dict(format='usdc')) usd.logger.info('created {}'.format(usdc_file)) if usd_file.endswith('.usdz'): r = Ar.GetResolver() resolved_asset = r.Resolve(usdc_file) context = r.CreateDefaultContextForAsset(resolved_asset) success = check_usd_compliance(resolved_asset, arkit=args.arkit) with Ar.ResolverContextBinder(context): if arkit and not success: usd.logger.warning('USD is not ARKit compliant') return success = UsdUtils.CreateNewUsdzPackage( resolved_asset, usd_file) and success if success: usd.logger.info( 'created package {} with contents:'.format(usd_file)) zip_file = Usd.ZipFile.Open(usd_file) file_names = zip_file.GetFileNames() for file_name in file_names: usd.logger.info('\t{}'.format(file_name)) else: usd.logger.error('could not create {}'.format(usd_file))
def test_RefreshContext(self): resolver = Ar.GetResolver() self.writeVersionsDict( "refreshContext.json", { "Buzz" : "1" }) ctx = UsdResolverExample.ResolverContext("refreshContext.json") with Ar.ResolverContextBinder(ctx): self.assertEqual( resolver.Resolve("asset:Buzz/{$VERSION}/Buzz.usd"), Ar.ResolvedPath("asset:Buzz/1/Buzz.usd")) self.writeVersionsDict( "refreshContext.json", { "Buzz" : "latest" }) with Ar.ResolverContextBinder(ctx): self.assertEqual( resolver.Resolve("asset:Buzz/{$VERSION}/Buzz.usd"), Ar.ResolvedPath("asset:Buzz/1/Buzz.usd")) class _Listener(object): def __init__(self): self._key = Tf.Notice.RegisterGlobally( Ar.Notice.ResolverChanged, self._HandleNotice) self.receivedNotice = False def _HandleNotice(self, notice, sender): self.receivedNotice = True l = _Listener() resolver.RefreshContext(ctx) self.assertTrue(l.receivedNotice) with Ar.ResolverContextBinder(ctx): self.assertEqual( resolver.Resolve("asset:Buzz/{$VERSION}/Buzz.usd"), Ar.ResolvedPath("asset:Buzz/latest/Buzz.usd"))
def CheckCompliance(self, inputFile): from pxr import Sdf, Usd, UsdUtils if not Usd.Stage.IsSupportedFile(inputFile): _AddError("Cannot open file '%s' on a USD stage." % args.inputFile) return # Collect all warnings using a diagnostic delegate. delegate = UsdUtils.CoalescingDiagnosticDelegate() usdStage = Usd.Stage.Open(inputFile) stageOpenDiagnostics = delegate.TakeUncoalescedDiagnostics() for rule in self._rules: rule.CheckStage(usdStage) rule.CheckDiagnostics(stageOpenDiagnostics) with Ar.ResolverContextBinder(usdStage.GetPathResolverContext()): # This recursively computes all of inputFiles's external # dependencies. (allLayers, allAssets, unresolvedPaths) = \ UsdUtils.ComputeAllDependencies(Sdf.AssetPath(inputFile)) for rule in self._rules: rule.CheckUnresolvedPaths(unresolvedPaths) rule.CheckDependencies(usdStage, allLayers, allAssets) if self._rootPackageOnly: rootLayer = usdStage.GetRootLayer() if rootLayer.GetFileFormat().IsPackage(): packagePath = Ar.SplitPackageRelativePathInner( rootLayer.identifier)[0] self._CheckPackage(packagePath) else: self._AddError( "Root layer of the USD stage (%s) doesn't belong to " "a package, but 'rootPackageOnly' is True!" % Usd.Describe(usdStage)) else: # Process every package just once by storing them all in a set. packages = set() for layer in allLayers: if _IsPackageOrPackagedLayer(layer): packagePath = Ar.SplitPackageRelativePathInner( layer.identifier)[0] packages.add(packagePath) self._CheckLayer(layer) for package in packages: self._CheckPackage(package) # Traverse the entire stage and check every prim. from pxr import Usd # Author all variant switches in the session layer. usdStage.SetEditTarget(usdStage.GetSessionLayer()) allPrimsIt = iter( Usd.PrimRange.Stage(usdStage, Usd.TraverseInstanceProxies())) self._TraverseRange(allPrimsIt, isStageRoot=True)
def test_FindOrOpenDefaultResolverSearchPaths(self): # Set up test directory structure by exporting layers. We # don't use Sdf.Layer.CreateNew here to avoid populating the # layer registry. layerA_Orig = Sdf.Layer.CreateAnonymous() Sdf.CreatePrimInLayer(layerA_Orig, "/LayerA") layerA_Orig.Export("dir1/sub/searchPath.sdf") layerB_Orig = Sdf.Layer.CreateAnonymous() Sdf.CreatePrimInLayer(layerB_Orig, "/LayerB") layerB_Orig.Export("dir2/sub/searchPath.sdf") # This should fail since there is no searchPath.sdf layer in the # current directory and no context is bound. self.assertFalse(Sdf.Layer.FindOrOpen("sub/searchPath.sdf")) # Bind an Ar.DefaultResolverContext with dir1 as a search path. # Now sub/searchPath.sdf should be discovered in dir1/. ctx1 = Ar.DefaultResolverContext([os.path.abspath("dir1/")]) with Ar.ResolverContextBinder(ctx1): layerA = Sdf.Layer.FindOrOpen("sub/searchPath.sdf") self.assertTrue(layerA) self.assertTrue(layerA.GetPrimAtPath("/LayerA")) self.assertEqual(layerA.identifier, "sub/searchPath.sdf") # Do the same as above, but with dir2 as the search path. # Now sub/searchPath.sdf should be discovered in dir2/. ctx2 = Ar.DefaultResolverContext([os.path.abspath("dir2/")]) with Ar.ResolverContextBinder(ctx2): layerB = Sdf.Layer.FindOrOpen("sub/searchPath.sdf") self.assertTrue(layerB) self.assertTrue(layerB.GetPrimAtPath("/LayerB")) self.assertEqual(layerB.identifier, "sub/searchPath.sdf") # Note that layerB has the same identifier as layerA, but # different resolved paths. self.assertEqual(layerA.identifier, layerB.identifier) self.assertNotEqual(layerA.realPath, layerB.realPath) # Sdf.Layer.Find should fail since no context is bound. self.assertFalse(Sdf.Layer.Find("sub/searchPath.sdf")) # Binding the contexts from above will allow Sdf.Layer.Find # to find the right layers. with Ar.ResolverContextBinder(ctx1): self.assertEqual(Sdf.Layer.Find("sub/searchPath.sdf"), layerA) with Ar.ResolverContextBinder(ctx2): self.assertEqual(Sdf.Layer.Find("sub/searchPath.sdf"), layerB) # Anonymous layers should be discoverable regardless of context. anonLayerA = Sdf.Layer.CreateAnonymous() with Ar.ResolverContextBinder(ctx1): self.assertEqual(Sdf.Layer.Find(anonLayerA.identifier), anonLayerA) with Ar.ResolverContextBinder(ctx2): anonLayerB = Sdf.Layer.CreateAnonymous() self.assertEqual(Sdf.Layer.Find(anonLayerB.identifier), anonLayerB)
def expandPath(path, parentPath=None, sdf_format_args=None, extractedDir=None): """ Expand and normalize a path that may have variables in it. Do not use this for URLs with query strings. :Parameters: path : `str` File path parentPath : `str` | None Parent file path this file is defined in relation to. Helps with asset resolution. sdf_format_args : `dict` | None Dictionary of key/value `str` pairs from a path's :SDF_FORMAT_ARGS: extractedDir: `str` | None If the file is part of an extracted usdz archive, this is the path to the extracted dir of the archive. :Returns: Normalized path with variables expanded. :Rtype: `str` """ # Expand the ~ part of any path first. The asset resolver doesn't understand it. path = os.path.expanduser(os.path.normpath(path)) if resolver is not None: try: resolver.ConfigureResolverForAsset(path) context = resolver.CreateDefaultContextForAsset(path) with Ar.ResolverContextBinder(context): anchoredPath = path if parentPath is None else resolver.AnchorRelativePath(parentPath, path) resolved = resolver.Resolve(anchoredPath) # https://graphics.pixar.com/usd/docs/Usdz-File-Format-Specification.html#UsdzFileFormatSpecification-USDConstraints-AssetResolution # If resolving relative to the layer fails in a usdz archive, # try to resolve based on the archive's default layer path. if extractedDir and not os.path.exists(resolved): default_layer = os.path.join(extractedDir, 'defaultLayer.usd') anchoredPath = resolver.AnchorRelativePath(default_layer, path) resolved = resolver.Resolve(anchoredPath) except Exception: logger.warn("Failed to resolve Asset path %s with parent %s", path, parentPath) else: if resolved: return resolved # Return this best-attempt if all else fails. return QtCore.QDir.cleanPath(os.path.expandvars(path))
def __init__(self, inputFile, arkit=False, skipARKitRootLayerCheck=False, rootPackageOnly=False, skipVariants=False, verbose=False): self._arkit = arkit self._skipARKitRootLayerCheck = skipARKitRootLayerCheck self._rootPackageOnly = rootPackageOnly self._doVariants = not skipVariants self._verbose = verbose self._failedChecks = [] self._errors = [] self._violatedRules = set() self._checkedPackages = set() from pxr import Ar, Sdf, Usd, UsdUtils if not Usd.Stage.IsSupportedFile(inputFile): _AddError("Cannot open file '%s' on a USD stage." % args.inputFile) return # Collect all warnings using a diagnostic delegate. delegate = UsdUtils.CoalescingDiagnosticDelegate() usdStage = Usd.Stage.Open(inputFile) allDiagnostics = delegate.TakeUncoalescedDiagnostics() if self._arkit: for diag in allDiagnostics: # "_ReportErrors" is the name of the function that issues # warnings about unresolved references, sublayers and other # composition arcs. if '_ReportErrors' in diag.sourceFunction and \ 'usd/stage.cpp' in diag.sourceFileName: self._AddFailedCheck(diag.commentary, ruleNum=4) with Ar.ResolverContextBinder(usdStage.GetPathResolverContext()): # This recursively computes all of inputFiles's external # dependencies. (allLayerDeps, allAssetDeps, unresolvedPaths) = \ UsdUtils.ComputeAllDependencies(Sdf.AssetPath(inputFile)) self._CheckDependencies(usdStage, allLayerDeps, allAssetDeps, unresolvedPaths) self._CheckStage(usdStage, allLayerDeps)
def test_ResolveWithContext(self): resolver = Ar.GetResolver() self.writeVersionsDict( "resolveWithContext.json", { "Buzz" : "1" }) ctx = UsdResolverExample.ResolverContext("resolveWithContext.json") with Ar.ResolverContextBinder(ctx): self.assertEqual( resolver.Resolve("asset:Buzz/{$VERSION}/Buzz.usd"), Ar.ResolvedPath("asset:Buzz/1/Buzz.usd")) self.assertEqual( resolver.Resolve("asset:Woody/{$VERSION}/Woody.usd"), Ar.ResolvedPath("asset:Woody/latest/Woody.usd"))
def test_ResolveWithContext(self): context = ReplaceResolver.ReplaceResolverContext( [os.path.abspath(TestReplaceResolver.rootDir)]) context.AddReplacePair('component/c1_v1.usda', 'component/c1_v2.usda') context.AddReplacePair('assembly/b1_v1.usda', 'assembly/b1_v2.usda') with Ar.ResolverContextBinder(context): resolver = Ar.GetResolver() expectedPath = os.path.join(TestReplaceResolver.rootDir, 'component', 'c1_v2.usda') self.assertEqual(resolver.Resolve('component/c1_v1.usda'), os.path.abspath(expectedPath)) expectedPath = os.path.join(TestReplaceResolver.rootDir, 'assembly', 'b1_v2.usda') self.assertEqual(resolver.Resolve('assembly/b1_v1.usda'), os.path.abspath(expectedPath))
def test_ResolveWithCache(self): testDir = os.path.abspath('testResolveWithCache/sub') if os.path.isdir(testDir): shutil.rmtree(testDir) os.makedirs(testDir) with open('testResolveWithCache/test.txt', 'w') as ofp: print('Test 1', file=ofp) with open('testResolveWithCache/sub/test.txt', 'w') as ofp: print('Test 2', file=ofp) resolver = Ar.GetResolver() # Set up a context that will search in the test root directory # first, then the subdirectory. context = Ar.DefaultResolverContext([ os.path.abspath('testResolveWithCache'), os.path.abspath('testResolveWithCache/sub')]) with Ar.ResolverContextBinder(context): with Ar.ResolverScopedCache(): # Resolve should initially find the file in the test root # directory. self.assertPathsEqual( os.path.abspath('testResolveWithCache/test.txt'), resolver.Resolve('test.txt')) os.remove('testResolveWithCache/test.txt') # After removing the file from the test root directory, # Calling Resolve again will still return the same result # as before since a scoped cache is active. self.assertPathsEqual( os.path.abspath('testResolveWithCache/test.txt'), resolver.Resolve('test.txt')) # Once the caching scope is closed, Resolve should now return # the file from the subdirectory. self.assertPathsEqual( os.path.abspath('testResolveWithCache/sub/test.txt'), resolver.Resolve('test.txt'))
def reportModelInfo(stage): _resolveAr = Ar.GetResolver().Resolve @lru_cache def resolve(identifier): return _resolveAr(str(Path(identifier))) missing_info = set() incomplete_info = defaultdict(set) unresolved_ids = defaultdict(set) with Ar.ResolverContextBinder(stage.GetPathResolverContext()): for prim in stage.Traverse(predicate=Usd.PrimIsModel): model = Usd.ModelAPI(prim) if not (model.IsKind("component") or model.IsKind("assembly")): continue # only check for "important" kinds elif (info := model.GetAssetInfo()): if (missing := frozenset({"name", "identifier"} - set(info))): incomplete_info[missing].add(prim) elif not resolve(info['identifier'].path): unresolved_ids[info['identifier']].add(prim) continue
def main(): parser = argparse.ArgumentParser( description= 'Resolves an asset path using a fully configured USD Asset Resolver.') parser.add_argument( 'inputPath', help="An asset path to be resolved by the USD Asset Resolver.") parser.add_argument( '--configureAssetPath', help="Run ConfigureResolverForAsset on the given asset path.") parser.add_argument('--anchorPath', help="Run AnchorRelativePath on the given asset path.") args = parser.parse_args() exitCode = 0 from pxr import Ar, Usd resolver = Ar.GetResolver() try: resolverContext = _ConfigureAssetResolver(args, resolver) with Ar.ResolverContextBinder(resolverContext): inputPath = _AnchorRelativePath(args, resolver) resolved = resolver.Resolve(inputPath) except Exception as e: _Err("Failed to resolve '%s' - %s" % (args.inputPath, e)) exitCode = 1 if not resolved: _Err("Failed to resolve '%s'" % args.inputPath) exitCode = 1 else: print resolved return exitCode
def test_CreateContextFromString(self): resolver = Ar.GetResolver() self.writeVersionsDict( "createContextFromString.json", { "Buzz" : "1" }) ctx = resolver.CreateContextFromString( "asset", "createContextFromString.json") self.assertEqual( ctx, UsdResolverExample.ResolverContext("createContextFromString.json")) with Ar.ResolverContextBinder(ctx): self.assertEqual( resolver.Resolve("asset:Buzz/{$VERSION}/Buzz.usd"), Ar.ResolvedPath("asset:Buzz/1/Buzz.usd")) self.assertEqual( resolver.Resolve("asset:Woody/{$VERSION}/Woody.usd"), Ar.ResolvedPath("asset:Woody/latest/Woody.usd"))
def test(usdfile): print 'test'.center(40, '-') stage_ref = Usd.Stage.Open(usdfile) for prim_ref in stage_ref.Traverse(): print(prim_ref.GetPath()) if prim_ref.HasPayload(): print 'payloads'.center(40, '-') # this is apparently hacky, but it works, yah? payloads = prim_ref.GetMetadata("payload") # so there's lots of lists for x in dir(payloads): if x.endswith('Items'): print x, getattr(payloads, x) for payload in payloads.appendedItems: pathToResolve = payload.assetPath print 'assetPath:', pathToResolve primSpec = prim_ref.GetPrimStack()[0] # get the layer from the prim anchorPath = primSpec.layer.identifier with Ar.ResolverContextBinder( stage_ref.GetPathResolverContext()): resolver = Ar.GetResolver() # relative to layer path? pathToResolve = resolver.AnchorRelativePath( anchorPath, pathToResolve) print 'pathToResolve', pathToResolve # this should probably work, but no resolvedPath = resolver.Resolve(pathToResolve) print 'resolvedPath', resolvedPath if prim_ref.HasAuthoredPayloads(): payloads = prim_ref.GetPayloads() # print payloads """ There is currently no facility for listing the currently authored payloads on a prim... the problem is somewhat ill-defined, and requires some thought. """ # does this prim have variant sets? if prim_ref.HasVariantSets(): print 'variantsets'.center(30, '-') # list all the variant sets avalable on this prim sets = prim_ref.GetVariantSets() # you can't iterate over the sets. # you have to get the name and do a GetVariantSet(<<set name>>) # TypeError: 'VariantSets' object is not iterable # maybe USD 20? for varset in sets.GetNames(): print 'variant set name:', varset # get the variant set by name thisvarset = prim_ref.GetVariantSet(varset) # the available variants print thisvarset.GetVariantNames() # the current variant print thisvarset.GetVariantSelection() print varset # gotta get a clip on each prim and then test it for paths? clips = Usd.ClipsAPI(prim_ref) if clips.GetClipAssetPaths(): print 'CLIPS'.center(30, '-') # dict of clip info. full of everything # key is the clip *name* print clips.GetClips() # this is a good one - resolved asset paths too for path in clips.GetClipAssetPaths(): print path, type(path) print path.resolvedPath print 'end test'.center(40, '-')
def test(usdfile): print('test'.center(40, '-')) stage = Usd.Stage.Open(usdfile) print('GetUsedLayers'.center(40, '-')) # things that are in use, apparntly for x in stage.GetUsedLayers(includeClipLayers=True): print(x) # print(type(x)) # print(dir(x)) # print(x, x.GetFileFormat().GetFileExtensions()) # print('subLayerPaths', x.subLayerPaths) # # return print('stage.Traverse'.center(40, '-')) for prim in stage.Traverse(): print(prim.GetPath()) """Return a list of PrimSpecs that provide opinions for this prim (i.e. the prim's metadata fields, including composition metadata). specs are ordered from strongest to weakest opinion.""" # print(prim.GetPrimStack()) if prim.HasAuthoredReferences(): primSpec = stage.GetEditTarget().GetPrimSpecForScenePath( prim.GetPath()) if primSpec: print('primspec GetAssetInfo') print(primSpec.assetInfo) refList = primSpec.referenceList if refList: print('referenceList'.center(40, '-')) for ref in refList.GetAddedOrExplicitItems(): if ref.assetPath: print(' -', ref.assetPath) print(' -', ref.customData) print(' -', ref.layerOffset) refList = primSpec.payloadList if refList: print('payloadList'.center(40, '-')) for ref in refList.GetAddedOrExplicitItems(): if ref.assetPath: print(' -', ref.assetPath) refList = primSpec.specializesList if refList: print('specializesList'.center(40, '-')) for ref in refList.GetAddedOrExplicitItems(): if ref.assetPath: print(' -', ref.assetPath) refList = primSpec.inheritPathList if refList: print('inheritPathList'.center(40, '-')) for ref in refList.GetAddedOrExplicitItems(): if ref.assetPath: print(' -', ref.assetPath) print('done with primspec'.center(40, '-')) """ this doesn't quite work https://groups.google.com/d/msg/usd-interest/s4AM0v60uBI/sYltgp7OAgAJ """ if prim.HasPayload(): print('payloads'.center(40, '-')) # this is apparently hacky, but it works, yah? # https://groups.google.com/d/msg/usd-interest/s4AM0v60uBI/q-okjU2RCAAJ payloads = prim.GetMetadata("payload") # so there's lots of lists for x in dir(payloads): if x.endswith('Items'): print(x, getattr(payloads, x)) # query GetAddedOrExplicitItems for *all* entries, rather than rooting through each list? print('GetAddedOrExplicitItems') print(payloads.GetAddedOrExplicitItems()) for itemlist in [ payloads.appendedItems, payloads.explicitItems, payloads.addedItems, payloads.prependedItems, payloads.orderedItems ]: for payload in itemlist: pathToResolve = payload.assetPath print('assetPath:', pathToResolve) primSpec = prim.GetPrimStack()[0] # get the layer from the prim anchorPath = primSpec.layer.identifier with Ar.ResolverContextBinder( stage.GetPathResolverContext()): resolver = Ar.GetResolver() # relative to layer path? pathToResolve = resolver.AnchorRelativePath( anchorPath, pathToResolve) print('pathToResolve', pathToResolve) # this should probably work, but no resolvedPath = resolver.Resolve(pathToResolve) print('resolvedPath', resolvedPath) if prim.HasAuthoredPayloads(): payloads = prim.GetPayloads() # print(payloads) """ There is currently no facility for listing the currently authored payloads on a prim... the problem is somewhat ill-defined, and requires some thought. """ # does this prim have variant sets? if prim.HasVariantSets(): print('variantsets'.center(30, '-')) # list all the variant sets avalable on this prim sets = prim.GetVariantSets() # you can't iterate over the sets. # you have to get the name and do a GetVariantSet(<<set name>>) # TypeError: 'VariantSets' object is not iterable # maybe USD 20? for varset in sets.GetNames(): print('variant set name:', varset) # get the variant set by name thisvarset = prim.GetVariantSet(varset) # the available variants print(thisvarset.GetVariantNames()) # the current variant print(thisvarset.GetVariantSelection()) print(varset) # gotta get a clip on each prim and then test it for paths? clips = Usd.ClipsAPI(prim) if clips.GetClipAssetPaths(): print('CLIPS'.center(30, '-')) # dict of clip info. full of everything # key is the clip *name* print(clips.GetClips()) # this is a good one - resolved asset paths too for path in clips.GetClipAssetPaths(): print(path, type(path)) print(path.resolvedPath) print('GetClipPrimPath', clips.GetClipPrimPath()) mdlinfo = Usd.ModelAPI(prim) print('UsdModelAPI'.center(30, '-')) print(mdlinfo) print('GetAssetInfo', mdlinfo.GetAssetInfo()) print('GetAssetIdentifier', mdlinfo.GetAssetIdentifier()) print('GetKind', mdlinfo.GetKind()) print('GetPayloadAssetDependencies', mdlinfo.GetPayloadAssetDependencies()) primStack = prim.GetPrimStack() print('GetPrimStack'.center(30, '-')) for spec in primStack: print(spec) print('layer.realPath', spec.layer.realPath) print('path.pathString', spec.path.pathString) print('layer.identifier', spec.layer.identifier) print('GetPayloadList', spec.payloadList) print('--') print(prim.HasPayload()) print(prim.HasAuthoredPayloads()) print('end test'.center(40, '-'))
def walkStagePrims(self, usdfile): # print 'test'.center(40, '-') stage = Usd.Stage.Open(usdfile) for prim in stage.TraverseAll(): # print(prim.GetPath()) # from the docs: """Return a list of PrimSpecs that provide opinions for this prim (i.e. the prim's metadata fields, including composition metadata). specs are ordered from strongest to weakest opinion.""" primStack = prim.GetPrimStack() for spec in primStack: if spec.hasPayloads: payloadList = spec.payloadList for itemlist in [ payloadList.appendedItems, payloadList.explicitItems, payloadList.addedItems, payloadList.prependedItems, payloadList.orderedItems ]: if itemlist: for payload in itemlist: payload_path = payload.assetPath # print payload, payload_path with Ar.ResolverContextBinder( stage.GetPathResolverContext()): resolver = Ar.GetResolver() # we resolve the payload path relative to the primSpec layer path (layer.identifier) # far more likely to be correct. i hope resolvedpath = resolver.AnchorRelativePath( spec.layer.identifier, payload_path) # print 'payload resolvedpath', resolvedpath info = {} info['online'] = os.path.isfile( resolvedpath) info['path'] = resolvedpath info['type'] = 'payload' self.nodes[resolvedpath] = info if spec.layer.identifier != resolvedpath: if not [ spec.layer.identifier, resolvedpath, 'payload' ] in self.edges: self.edges.append([ spec.layer.identifier, resolvedpath, 'payload' ]) # the docs say there's a HasSpecializes method # no, there is not. at least in this build of houdini 18.0.453 # if spec.HasSpecializes: # let's just ignore specialize for the time being """ specializesList = spec.specializesList spec_paths = [] for itemlist in [specializesList.appendedItems, specializesList.explicitItems, specializesList.addedItems, specializesList.prependedItems, specializesList.orderedItems]: if itemlist: for specialize in itemlist: specialize_path = specialize.assetPath with Ar.ResolverContextBinder(stage.GetPathResolverContext()): resolver = Ar.GetResolver() resolvedpath = resolver.AnchorRelativePath(spec.layer.identifier, specialize_path) spec_paths.append(resolvedpath) ret.append(resolvedpath) if spec_paths: print 'specializesList', spec.specializesList """ # references operate the same to payloads if spec.hasReferences: reflist = spec.referenceList for itemlist in [ reflist.appendedItems, reflist.explicitItems, reflist.addedItems, reflist.prependedItems, reflist.orderedItems ]: if itemlist: for reference in itemlist: reference_path = reference.assetPath if reference_path: # print reference_path with Ar.ResolverContextBinder( stage.GetPathResolverContext()): resolver = Ar.GetResolver() # we resolve the payload path relative to the primSpec layer path (layer.identifier) # far more likely to be correct. i hope resolvedpath = resolver.AnchorRelativePath( spec.layer.identifier, reference_path) info = {} info['online'] = os.path.isfile( resolvedpath) info['path'] = resolvedpath info['type'] = 'reference' self.nodes[resolvedpath] = info if spec.layer.identifier != resolvedpath: if not [ spec.layer.identifier, resolvedpath, 'reference' ] in self.edges: self.edges.append([ spec.layer.identifier, resolvedpath, 'reference' ]) if spec.variantSets: for varset in spec.variantSets: thisvarset = prim.GetVariantSet(varset.name) current_variant_name = thisvarset.GetVariantSelection() current_variant = varset.variants[current_variant_name] for variant_name in varset.variants.keys(): variant = varset.variants[variant_name] # todo: put variant info onto layer # for key in variant.GetMetaDataInfoKeys(): # print key, variant.GetInfo(key) # variants that are linked to payloads # variants can have other mechanisms, but sometimes they're a payload payloads = variant.GetInfo('payload') for itemlist in [ payloads.appendedItems, payloads.explicitItems, payloads.addedItems, payloads.prependedItems, payloads.orderedItems ]: for payload in itemlist: pathToResolve = payload.assetPath anchorPath = variant.layer.identifier with Ar.ResolverContextBinder( stage.GetPathResolverContext()): resolver = Ar.GetResolver() resolvedpath = resolver.AnchorRelativePath( anchorPath, pathToResolve) if not [ anchorPath, resolvedpath, 'payload' ] in self.edges: self.edges.append([ anchorPath, resolvedpath, 'payload' ]) # def, over or class # print 'GetSpecifier', spec.specifier # component, # print 'GetKind', spec.kind # print '--' # clips - this seems to be the way to do things # clips are not going to be picked up by the stage layers inspection stuff # apparently they're expensive. whatever. # no prim stack shennanigans for us # gotta get a clip on each prim and then test it for paths? clips = Usd.ClipsAPI(prim) if clips.GetClipAssetPaths(): # print 'CLIPS'.center(30, '-') # dict of clip info. full of everything # key is the clip *name* clip_dict = clips.GetClips() # print clip_dict """ @todo: subframe handling integer frames: path/basename.###.usd subinteger frames: path/basename.##.##.usd. @todo: non-1 increments """ # don't use resolved path in case either the first or last file is missing from disk firstFile = str(clips.GetClipAssetPaths()[0].path) lastFile = str(clips.GetClipAssetPaths()[-1].path) firstFileNum = digitSearch.findall(firstFile)[-1] lastFileNum = digitSearch.findall(lastFile)[-1] digitRange = str(firstFileNum + '-' + lastFileNum) nodeName = '' firstFileParts = firstFile.split(firstFileNum) for i in range(len(firstFileParts) - 1): nodeName += str(firstFileParts[i]) nodeName += digitRange nodeName += firstFileParts[-1] allFilesFound = True for path in clips.GetClipAssetPaths(): if (path.resolvedPath == ''): allFilesFound = False break # TODO : make more efficient - looping over everything currently # TODO: validate presence of all files in the clip seq. bg thread? # GetClipSets seems to be crashing this houdini build - clips.GetClipSets() clip_sets = clips.GetClips().keys() # print 'GetClipManifestAssetPath', clips.GetClipManifestAssetPath().resolvedPath # this is a good one - resolved asset paths too for clipSet in clip_sets: for path in clips.GetClipAssetPaths(clipSet): # print path, type(path) # print path.resolvedPath pass # layer that hosts list clip # but this is the MANIFEST path # not really correct. it'll have to do for now. layer = clips.GetClipManifestAssetPath().resolvedPath if not nodeName in self.nodes: info = {} info['online'] = allFilesFound info['path'] = nodeName info['type'] = 'clip' self.nodes[nodeName] = info if not [layer, nodeName, 'clip'] in self.edges: self.edges.append([layer, nodeName, 'clip'])
def prim_traverse(usdfile): ret = [] stage = Usd.Stage.Open(usdfile) count = 1 for prim in stage.Traverse(): """ this doesn't quite work https://groups.google.com/d/msg/usd-interest/s4AM0v60uBI/sYltgp7OAgAJ """ if prim.HasPayload(): print('payloads'.center(40, '-')) # this is apparently hacky, but it works, yah? # https://groups.google.com/d/msg/usd-interest/s4AM0v60uBI/q-okjU2RCAAJ payloads = prim.GetMetadata("payload") # so there's lots of lists for x in dir(payloads): if x.endswith('Items'): print(x, getattr(payloads, x)) for itemlist in [ payloads.appendedItems, payloads.explicitItems, payloads.addedItems, payloads.prependedItems, payloads.orderedItems ]: for payload in itemlist: pathToResolve = payload.assetPath print('assetPath:', pathToResolve) primSpec = prim.GetPrimStack()[0] # get the layer from the prim anchorPath = primSpec.layer.identifier print('anchorPath', anchorPath) with Ar.ResolverContextBinder( stage.GetPathResolverContext()): resolver = Ar.GetResolver() # relative to layer path? NOPE # problem here is that the layer path is NOT # really what the payload path is relative to # and why it's better to go through the primstack - you can get a # proper anchor path pathToResolve = resolver.AnchorRelativePath( anchorPath, pathToResolve) print('pathToResolve', pathToResolve) # this should probably work, but no resolvedPath = resolver.Resolve(pathToResolve) print('resolvedPath', resolvedPath) # does this prim have variant sets? if prim.HasVariantSets(): print('variantsets'.center(30, '-')) # list all the variant sets avalable on this prim sets = prim.GetVariantSets() # you can't iterate over the sets. # you have to get the name and do a GetVariantSet(<<set name>>) # TypeError: 'VariantSets' object is not iterable # maybe USD 20? for varset in sets.GetNames(): print('variant set name:', varset) # get the variant set by name thisvarset = prim.GetVariantSet(varset) # the available variants print('variant names:', thisvarset.GetVariantNames()) # the current variant print('current variant:', thisvarset.GetVariantSelection()) print(varset) print(thisvarset.GetPrim()) # clips - this seems to be the way to do things # clips are not going to be picked up by the stage layers inspection stuff # apparently they're expensive. whatever. # no prim stack shennanigans for us # gotta get a clip on each prim and then test it for paths? clips = Usd.ClipsAPI(prim) if clips.GetClipAssetPaths(): print('CLIPS'.center(30, '-')) # dict of clip info. full of everything # key is the clip set *name* print(clips.GetClips()) # GetClipSets seems to be crashing this houdini build - clips.GetClipSets() clip_sets = clips.GetClips().keys() print('clip_sets', clip_sets) # this is a good one - resolved asset paths too for clipSet in clip_sets: print('CLIP_SET:', clipSet) for path in clips.GetClipAssetPaths(clipSet): print(path, type(path)) print('resolved path:', path.resolvedPath) ret.append(path.resolvedPath) print('GetClipTemplateAssetPath:', clips.GetClipTemplateAssetPath(clipSet)) print('GetClipAssetPaths:', clips.GetClipAssetPaths()) print('GetClipPrimPath', clips.GetClipPrimPath()) # from the docs: """Return a list of PrimSpecs that provide opinions for this prim (i.e. the prim's metadata fields, including composition metadata). specs are ordered from strongest to weakest opinion.""" primStack = prim.GetPrimStack() print('GetPrimStack'.center(30, '-')) for spec in primStack: # print(spec) # print('layer.realPath', spec.layer.realPath) print('path.pathString', spec.path.pathString) print('layer.identifier', spec.layer.identifier) print('layer.owner', spec.layer.owner) print('layer.subLayerPaths', spec.layer.subLayerPaths) print('specifier', spec.specifier) # if not spec.variantSets: if spec.hasPayloads: print('GetPayloadList'.center(80, '#')) payloadList = spec.payloadList print('GetPayloadList', payloadList) for itemlist in [ payloadList.appendedItems, payloadList.explicitItems, payloadList.addedItems, payloadList.prependedItems, payloadList.orderedItems ]: if itemlist: for payload in itemlist: payload_path = payload.assetPath print(payload, payload_path) with Ar.ResolverContextBinder( stage.GetPathResolverContext()): resolver = Ar.GetResolver() # we resolve the payload path relative to the primSpec layer path (layer.identifier) # far more likely to be correct. i hope resolvedpath = resolver.AnchorRelativePath( spec.layer.identifier, payload_path) print('payload resolvedpath', resolvedpath) ret.append(resolvedpath) # the docs say there's a HasSpecializes method # no, there is not. at least in this build of houdini 18.0.453 # if spec.HasSpecializes: # let's just ignore specialize for the time being """ specializesList = spec.specializesList spec_paths = [] for itemlist in [specializesList.appendedItems, specializesList.explicitItems, specializesList.addedItems, specializesList.prependedItems, specializesList.orderedItems]: if itemlist: for specialize in itemlist: specialize_path = specialize.assetPath with Ar.ResolverContextBinder(stage.GetPathResolverContext()): resolver = Ar.GetResolver() resolvedpath = resolver.AnchorRelativePath(spec.layer.identifier, specialize_path) spec_paths.append(resolvedpath) ret.append(resolvedpath) if spec_paths: print('specializesList', spec.specializesList) """ # references operate the same to payloads if spec.hasReferences: reflist = spec.referenceList print('referenceList', reflist) print('orderedItems', reflist.orderedItems) for itemlist in [ reflist.appendedItems, reflist.explicitItems, reflist.addedItems, reflist.prependedItems, reflist.orderedItems ]: if itemlist: for reference in itemlist: print('reference:', reference) reference_path = reference.assetPath with Ar.ResolverContextBinder( stage.GetPathResolverContext()): resolver = Ar.GetResolver() # we resolve the payload path relative to the primSpec layer path (layer.identifier) # far more likely to be correct. i hope resolvedpath = resolver.AnchorRelativePath( spec.layer.identifier, reference_path) print('reference resolvedpath', resolvedpath) ret.append(resolvedpath) # if spec.hasVariantSetNames: # print(dir(spec)) if spec.variantSets: print('variantSets', spec.variantSets) for varset in spec.variantSets: # SdfVariantSetSpec objects print(varset) # you can get a SdfPath from the variant path # https://groups.google.com/d/msg/usd-interest/Q1tjV88T1EI/_KGo3wzyBAAJ variantDefinitionPath = Sdf.Path(varset.path) print('---variantDefinitionPath') print('variantDefinitionPath', variantDefinitionPath) print(type(variantDefinitionPath)) print(dir(variantDefinitionPath)) print('pathString', variantDefinitionPath.pathString) print('GetParentPath', variantDefinitionPath.GetParentPath()) print( 'GetPrimOrPrimVariantSelectionPath', variantDefinitionPath. GetPrimOrPrimVariantSelectionPath()) print('GetPrimPath', variantDefinitionPath.GetPrimPath()) print('GetVariantSelection', variantDefinitionPath.GetVariantSelection()) print('isAbsolutePath', variantDefinitionPath.IsAbsolutePath()) print('IsPrimVariantSelectionPath', variantDefinitionPath.IsPrimVariantSelectionPath()) print('GetTargetPath', variantDefinitionPath.targetPath) pld = Sdf.Payload(variantDefinitionPath.pathString) print(pld) print(pld.assetPath) print(dir(pld)) print('---variantDefinitionPath') print('variant set name', varset.name) print('owner', varset.owner) print('isInert', varset.isInert) print('layer', varset.layer) # the available variants # dict with the variant name as a key nad a Sdf.Find object as the value print('variant', varset.variants) print('variant_names:', varset.variants.keys()) # SdfVariantSetSpec doesn't seem to know which is the current variant # but it's a short hop to get the variant set object # and perhaps this is the best of both worlds thisvarset = prim.GetVariantSet(varset.name) current_variant_name = thisvarset.GetVariantSelection() print('current variant name:', current_variant_name) current_variant = varset.variants[current_variant_name] for variant_name in varset.variants.keys(): variant = varset.variants[variant_name] print(variant.GetPrimStack()) print('variant:', variant) print('path:', variant.path) print('layer:', variant.layer) print('variant payload info:', variant.GetInfo('payload')) payloads = variant.GetInfo('payload') for itemlist in [ payloads.appendedItems, payloads.explicitItems, payloads.addedItems, payloads.prependedItems, payloads.orderedItems ]: for payload in itemlist: pathToResolve = payload.assetPath anchorPath = variant.layer.identifier print('anchorPath', anchorPath) with Ar.ResolverContextBinder( stage.GetPathResolverContext()): resolver = Ar.GetResolver() pathToResolve = resolver.AnchorRelativePath( anchorPath, pathToResolve) print('pathToResolve', pathToResolve) # print(type(current_variant)) # print(dir(current_variant)) # print('path', current_variant.path) # print('variantSets', current_variant.variantSets) # print('layer', current_variant.layer) # print('GetMetaDataInfoKeys', current_variant.GetMetaDataInfoKeys()) # print('variant payload info:', current_variant.GetInfo('payload')) # for key in current_variant.GetMetaDataInfoKeys(): print(key, current_variant.GetInfo(key)) # THIS IS WAAAY WRONG # it's just giving the layer path current_variant_path = current_variant.layer.realPath # the paths we are looking for are coming in as payloads # (because they can be dynamically loaded i guess) print(current_variant_path) x = thisvarset.GetVariantEditTarget() count += 1 if count > 1: print('count', count) raise RuntimeError("poo") # print('GetVariantNames', spec.GetVariantNames(varset)) # def, over or class print('GetSpecifier', spec.specifier) # component, print('GetInherits') inherits = prim.GetInherits().GetAllDirectInherits() if inherits: print(inherits) raise RuntimeError('poo') print('GetKind', spec.kind) print('--') print(prim.HasPayload()) print(prim.HasAuthoredPayloads()) return ret
def CreatePcpCache(rootLayerPath, context): with Ar.ResolverContextBinder(context): rootLayer = Sdf.Layer.FindOrOpen(rootLayerPath) lsid = Pcp.LayerStackIdentifier(rootLayer, pathResolverContext=context) return Pcp.Cache(lsid)
def main(): parser = argparse.ArgumentParser( description='Utility for creating a .usdz ' 'file containging USD assets and for inspecting existing .usdz files.') parser.add_argument('usdzFile', type=str, nargs='?', help='Name of the .usdz file to create or to inspect ' 'the contents of.') parser.add_argument('inputFiles', type=str, nargs='*', help='Files to include in the .usdz file.') parser.add_argument('-r', '--recurse', dest='recurse', action='store_true', help='If specified, files in sub-directories are ' 'recursively added to the package.') parser.add_argument( '-a', '--asset', dest='asset', type=str, help='Resolvable asset path pointing to the root layer ' 'of the asset to be isolated and copied into the ' 'package.') parser.add_argument("--arkitAsset", dest="arkitAsset", type=str, help="Similar to the --asset option, the --arkitAsset " "option packages all of the dependencies of the named " "scene file. Assets targeted at the initial usdz " "implementation in ARKit operate under greater " "constraints than usdz files for more general 'in " "house' uses, and this option attempts to ensure that " "these constraints are honored; this may involve more " "transformations to the data, which may cause loss of " "features such as VariantSets.") parser.add_argument( '-c', '--checkCompliance', dest='checkCompliance', action='store_true', help='Perform compliance checking ' 'of the input files. If the input asset or \"root\" ' 'layer fails any of the compliance checks, the package ' 'is not created and the program fails.') parser.add_argument( '-l', '--list', dest='listTarget', type=str, nargs='?', default=None, const='-', help='List contents of the specified usdz file. If ' 'a file-path argument is provided, the list is output ' 'to a file at the given path. If no argument is ' 'provided or if \'-\' is specified as the argument, the' ' list is output to stdout.') parser.add_argument( '-d', '--dump', dest='dumpTarget', type=str, nargs='?', default=None, const='-', help='Dump contents of the specified usdz file. If ' 'a file-path argument is provided, the contents are ' 'output to a file at the given path. If no argument is ' 'provided or if \'-\' is specified as the argument, the' ' contents are output to stdout.') parser.add_argument('-v', '--verbose', dest='verbose', action='store_true', help='Enable verbose mode, which causes messages ' 'regarding files being added to the package to be ' 'output to stdout.') args = parser.parse_args() usdzFile = args.usdzFile inputFiles = args.inputFiles if args.asset and args.arkitAsset: parser.error("Specify either --asset or --arkitAsset, not both.") elif (args.arkitAsset or args.asset) and len(inputFiles) > 0: parser.error("Specify either inputFiles or an asset (via --asset or " "--arkitAsset, not both.") # If usdzFile is not specified directly as an argument, check if it has been # specified as an argument to the --list or --dump options. In these cases, # output the list or the contents to stdout. if not usdzFile: if args.listTarget and args.listTarget != '-' and \ args.listTarget.endswith('.usdz') and \ os.path.exists(args.listTarget): usdzFile = args.listTarget args.listTarget = '-' elif args.dumpTarget and args.dumpTarget != '-' and \ args.dumpTarget.endswith('.usdz') and \ os.path.exists(args.dumpTarget): usdzFile = args.dumpTarget args.dumpTarget = '-' else: parser.error("No usdz file specified!") # Check if we're in package creation mode and verbose mode is enabled, # print some useful information. if (args.asset or args.arkitAsset or len(inputFiles) > 0): # Ensure that the usdz file has the right extension. if not usdzFile.endswith('.usdz'): usdzFile += '.usdz' if args.verbose: if os.path.exists(usdzFile): print("File at path '%s' already exists. Overwriting file." % usdzFile) if args.inputFiles: print('Creating package \'%s\' with files %s.' % (usdzFile, inputFiles)) if args.asset or args.arkitAsset: Tf.Debug.SetDebugSymbolsByName("USDUTILS_CREATE_USDZ_PACKAGE", 1) if not args.recurse: print('Not recursing into sub-directories.') else: if args.checkCompliance: parser.error( "--checkCompliance should only be specified when " "creatinga usdz package. Please use 'usdchecker' to check " "compliance of an existing .usdz file.") success = True if len(inputFiles) > 0: success = _CreateUsdzPackage(usdzFile, inputFiles, args.recurse, args.checkCompliance, args.verbose) and success elif args.asset: r = Ar.GetResolver() resolvedAsset = r.Resolve(args.asset) if args.checkCompliance: success = _CheckCompliance(resolvedAsset, arkit=False) and success context = r.CreateDefaultContextForAsset(resolvedAsset) with Ar.ResolverContextBinder(context): # Create the package only if the compliance check was passed. success = success and UsdUtils.CreateNewUsdzPackage( Sdf.AssetPath(args.asset), usdzFile) elif args.arkitAsset: r = Ar.GetResolver() resolvedAsset = r.Resolve(args.arkitAsset) if args.checkCompliance: success = _CheckCompliance(resolvedAsset, arkit=True) and success context = r.CreateDefaultContextForAsset(resolvedAsset) with Ar.ResolverContextBinder(context): # Create the package only if the compliance check was passed. success = success and UsdUtils.CreateNewARKitUsdzPackage( Sdf.AssetPath(args.arkitAsset), usdzFile) if args.listTarget or args.dumpTarget: if os.path.exists(usdzFile): zipFile = Usd.ZipFile.Open(usdzFile) if zipFile: if args.dumpTarget: if args.dumpTarget == usdzFile: _Err("The file into which to dump the contents of the " "usdz file '%s' must be different from the file " "itself." % usdzFile) return 1 _DumpContents(args.dumpTarget, zipFile) if args.listTarget: if args.listTarget == usdzFile: _Err("The file into which to list the contents of the " "usdz file '%s' must be different from the file " "itself." % usdzFile) return 1 _ListContents(args.listTarget, zipFile) else: _Err("Failed to open usdz file at path '%s'." % usdzFile) else: _Err("Can't find usdz file at path '%s'." % usdzFile) return 0 if success else 1
def main(): parser = argparse.ArgumentParser( description= 'Resolves an asset path using a fully configured USD Asset Resolver.') parser.add_argument( 'inputPath', help="An asset path to be resolved by the USD Asset Resolver.") if _HasConfigureResolverForAsset(): parser.add_argument( '--configureAssetPath', help="Run ConfigureResolverForAsset on the given asset path.") else: subparser = parser.add_mutually_exclusive_group() subparser.add_argument( '--createContextForAsset', help=("Run CreateDefaultContextForAsset with the given asset path " "to create the context used for resolution.")) subparser.add_argument( '--createContextFromString', action='append', help=( "Run CreateContextFromString with the given string to create " "the context used for resolution. This accepts strings like " "[<URI Scheme>:]<Configuration String> and may be specified " "multiple times.\n\n" "ex: usdresolve --createContextFromString 'config_primary' " "--createContextFromString 'my_uri_scheme:config_uri'")) if _HasCreateIdentifier(): parser.add_argument( '--anchorPath', help=("Run CreateIdentifier with the input path and this anchor " "asset path and resolve the result.\n\n" "ex: usdresolve --anchorPath /asset/asset.usd sublayer.usd")) else: parser.add_argument( '--anchorPath', help="Run AnchorRelativePath on the given asset path.") args = parser.parse_args() exitCode = 0 resolver = Ar.GetResolver() try: resolverContext = _ConfigureAssetResolver(args, resolver) with Ar.ResolverContextBinder(resolverContext): inputPath = _AnchorRelativePath(args, resolver) resolved = resolver.Resolve(inputPath) except Exception as e: _Err("Failed to resolve '%s' - %s" % (args.inputPath, e)) exitCode = 1 if not resolved: _Err("Failed to resolve '%s'" % args.inputPath) exitCode = 1 else: print(resolved) return exitCode
def main(): parser = argparse.ArgumentParser( description= '''Writes the tree structure of a USD file. The default is to inspect a single USD file. Use the --flatten argument to see the flattened (or composed) Stage tree. Special metadata "kind" and "active" are always shown if authored unless --simple is provided.''' ) parser.add_argument('inputPath') parser.add_argument('--unloaded', action='store_true', dest='unloaded', help='Do not load payloads') parser.add_argument('--attributes', '-a', action='store_true', dest='attributes', help='Display authored attributes') parser.add_argument( '--metadata', '-m', action='store_true', dest='metadata', help= 'Display authored metadata (active and kind are part of the label and not shown as individual items)' ) parser.add_argument( '--simple', '-s', action='store_true', dest='simple', help='Only display prim names: no specifier, kind or active state.') parser.add_argument( '--flatten', '-f', action='store_true', help='Compose the stage with the ' 'input file as root layer and write the flattened content.') parser.add_argument( '--flattenLayerStack', action='store_true', help='Flatten the layer stack with the given root layer. ' 'Unlike --flatten, this does not flatten composition arcs (such as references).' ) parser.add_argument('--mask', action='store', dest='populationMask', metavar='PRIMPATH[,PRIMPATH...]', help='Limit stage population to these prims, ' 'their descendants and ancestors. To specify ' 'multiple paths, either use commas with no spaces ' 'or quote the argument and separate paths by ' 'commas and/or spaces. Requires --flatten.') args = parser.parse_args() # split args.populationMask into paths. if args.populationMask: if not args.flatten: # You can only mask a stage, not a layer. _Err("%s: error: --mask requires --flatten" % parser.prog) return 1 args.populationMask = args.populationMask.replace(',', ' ').split() from pxr import Ar resolver = Ar.GetResolver() try: resolver.ConfigureResolverForAsset(args.inputPath) resolverContext = resolver.CreateDefaultContextForAsset(args.inputPath) with Ar.ResolverContextBinder(resolverContext): resolved = resolver.Resolve(args.inputPath) if not resolved or not os.path.exists(resolved): _Err('Cannot resolve inputPath %r' % resolved) return 1 PrintTree(args, resolved) except Exception as e: _Err("Failed to process '%s' - %s" % (args.inputPath, e)) return 1 return 0
def convert_to_usd(gltf_file, usd_file, fps, scale, arkit=False, verbose=False, use_euler_rotation=False, optimize_textures=False, generate_texture_transform_texture=True, scale_texture=False): """Converts a glTF file to USD Arguments: gltf_file {str} -- path to glTF file usd_file {str} -- path to write USD file Keyword Arguments: verbose {bool} -- [description] (default: {False}) """ temp_dir = tempfile.mkdtemp() temp_usd_file = os.path.join(temp_dir, ntpath.basename(usd_file)) try: usd = GLTF2USD(gltf_file=gltf_file, usd_file=temp_usd_file, fps=fps, scale=scale, verbose=verbose, use_euler_rotation=use_euler_rotation, optimize_textures=optimize_textures, generate_texture_transform_texture= generate_texture_transform_texture, scale_texture=scale_texture) if usd.stage: asset = usd.stage.GetRootLayer() gltf_asset = usd.gltf_loader.get_asset() if gltf_asset: gltf_metadata = {'creator': 'gltf2usd v{}'.format(__version__)} if gltf_asset.generator: gltf_metadata['gltf_generator'] = gltf_asset.generator if gltf_asset.version: gltf_metadata['gltf_version'] = gltf_asset.version if gltf_asset.minversion: gltf_metadata['gltf_minversion'] = gltf_asset.minversion if gltf_asset.copyright: gltf_metadata['gltf_copyright'] = gltf_asset.copyright if gltf_asset.extras: for key, value in gltf_asset.extras.items(): gltf_metadata['gltf_extras_{}'.format(key)] = value asset.customLayerData = gltf_metadata usd.logger.info('Conversion complete!') asset.Save() usd.logger.info('created {}'.format(asset.realPath)) if not os.path.isdir(os.path.dirname(usd_file)): os.makedirs(os.path.dirname(usd_file)) if temp_usd_file.endswith('.usdz') or temp_usd_file.endswith( '.usdc'): usdc_file = '%s.%s' % (os.path.splitext(temp_usd_file)[0], 'usdc') asset.Export(usdc_file, args=dict(format='usdc')) usd.logger.info('created {}'.format(usdc_file)) if temp_usd_file.endswith('.usdz'): #change to directory of the generated usd files to avoid issues with # relative paths with CreateNewUsdzPackage os.chdir(os.path.dirname(usdc_file)) temp_usd_file = ntpath.basename(temp_usd_file) r = Ar.GetResolver() resolved_asset = r.Resolve(ntpath.basename(usdc_file)) context = r.CreateDefaultContextForAsset(resolved_asset) success = check_usd_compliance(resolved_asset, arkit=args.arkit) with Ar.ResolverContextBinder(context): if arkit and not success: usd.logger.warning('USD is not ARKit compliant') return success = UsdUtils.CreateNewUsdzPackage( resolved_asset, temp_usd_file) and success if success: shutil.copyfile(temp_usd_file, usd_file) usd.logger.info( 'created package {} with contents:'.format( usd_file)) zip_file = Usd.ZipFile.Open(usd_file) file_names = zip_file.GetFileNames() for file_name in file_names: usd.logger.info('\t{}'.format(file_name)) else: usd.logger.error( 'could not create {}'.format(usd_file)) else: # Copy textures referenced in the Usda/Usdc files from the temp directory to the target directory temp_stage = Usd.Stage.Open(temp_usd_file) usd_uv_textures = [ x for x in temp_stage.Traverse() if x.IsA(UsdShade.Shader) and UsdShade.Shader(x).GetShaderId() == 'UsdUVTexture' ] for usd_uv_texture in usd_uv_textures: file_name = usd_uv_texture.GetAttribute( 'inputs:file').Get() if file_name: file_name = str(file_name).replace('@', '') if os.path.isfile(os.path.join(temp_dir, file_name)): shutil.copyfile( os.path.join(temp_dir, file_name), os.path.join(os.path.dirname(usd_file), file_name)) shutil.copyfile(temp_usd_file, usd_file) finally: shutil.rmtree(temp_dir)
parser.add_argument('--check', dest='check', action='store_true') parser.add_argument('--numFailedChecks', dest='numFailedChecks', default=0, type=int, action='store') parser.add_argument('--numErrors', dest='numErrors', default=0, type=int, action='store') args = parser.parse_args() context = Ar.GetResolver().CreateDefaultContextForAsset(args.assetPath) with Ar.ResolverContextBinder(context): if not args.arkit: assert UsdUtils.CreateNewUsdzPackage( Sdf.AssetPath(args.assetPath), args.usdzFile, args.rename if args.rename else '') else: assert UsdUtils.CreateNewARKitUsdzPackage( Sdf.AssetPath(args.assetPath), args.usdzFile, args.rename if args.rename else '') zipFile = Usd.ZipFile.Open(args.usdzFile) assert zipFile with stream(args.outfile, 'w') as ofp: for fileName in zipFile.GetFileNames(): print >> ofp, fileName
parser = argparse.ArgumentParser() parser.add_argument("resolverName", type=str, help=("Name of ArResolver subclass to test")) args = parser.parse_args() SetupPlugins() Ar.SetPreferredResolver(args.resolverName) r = Ar.GetResolver() # Call each method to see whether the corresponding virtual method # on the resolver is called. # This context manager calls ArResolver::BindContext when entered # and ArResolver::UnbindContext on exit. with Ar.ResolverContextBinder(Ar.ResolverContext()): pass r.CreateDefaultContext() r.CreateDefaultContextForAsset('foo') r.CreateContextFromString('foo') r.RefreshContext(Ar.ResolverContext()) r.GetCurrentContext() r.IsContextDependentPath('foo') # This context manager calls ArResolver::BeginCacheScope when entered # and ArResolver::EndCacheScope on exit. with Ar.ResolverScopedCache(): pass