def exportDynamicAssmblyRefUSD(self, location, destination, rangeTimeCode, motionSample): scenegraph_path = self.fetchNameSceneGraphPrim(dagnode_path) scenegraph_tree = self.fetchListUSDPrim(dagnode_path) scenegraph_data = self.fetchDataDynamicMayaXform(dagnode_path,rangeTimeCode,motionSample) # create a UsdStage if os.path.isfile(destination): stage = Usd.Stage.Open(destination) else: stage = Usd.Stage.CreateNew(destination) for prim_node in scenegraph_tree: gprim = Usd.ModelAPI(UsdGeom.Xform.Define(stage, prim_node)) prim = stage.GetPrimAtPath( scenegraph_path ) root_prim = stage.GetPrimAtPath( self.fetchNameUsdRoot(scenegraph_path)) # set USD default setting stage.SetStartTimeCode(rangeTimeCode[0]) stage.SetEndTimeCode(rangeTimeCode[1]) stage.SetDefaultPrim(root_prim) UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y) # set visibility rotateXYZ scale translate sampleTime data into specific prim for frameData in sorted(scenegraph_data.keys()): if scenegraph_data[frameData]["visibility"]: UsdGeom.Imageable(prim).MakeVisible(frameData) else: UsdGeom.Imageable(prim).MakeInvisible(frameData) rotateXYZ = scenegraph_data[frameData]["rotateXYZ"] UsdGeom.XformCommonAPI(prim).SetRotate(tuple(rotateXYZ),UsdGeom.XformCommonAPI.RotationOrderXYZ,frameData) scale = scenegraph_data[frameData]["scale"] UsdGeom.XformCommonAPI(prim).SetScale(tuple(scale),frameData) translate = scenegraph_data[frameData]["translate"] UsdGeom.XformCommonAPI(prim).SetTranslate(tuple(translate), frameData) # save UsdStage stage.GetRootLayer().Save()
def testPurposeBoundingBox(self): '''Bounding box of prims with guide, proxy, and render purpose.''' # Create a scene with prims of purposes other than default: guide, # proxy, and render. All must have a valid bounding box. The bounding # box is conditional to the proxy shape on the UFE path to the prim # having that purpose enabled: if the purpose is disabled, the bounding # box is invalid. import mayaUsd_createStageWithNewLayer proxyShapePath = mayaUsd_createStageWithNewLayer.createStageWithNewLayer( ) proxyShapePathSegment = mayaUtils.createUfePathSegment(proxyShapePath) stage = mayaUsd.lib.GetPrim(proxyShapePath).GetStage() usdPaths = ['/Cube1', '/Cube2', '/Cube3'] prims = [stage.DefinePrim(path, 'Cube') for path in usdPaths] purposes = [ UsdGeom.Tokens.proxy, UsdGeom.Tokens.guide, UsdGeom.Tokens.render ] for (prim, purpose) in zip(prims, purposes): imageable = UsdGeom.Imageable(prim) imageable.CreatePurposeAttr(purpose) # Create a UFE scene item for each prim, and get the bounding box using # the Object3d interface. for (prim, usdPath) in zip(prims, usdPaths): pathSegment = usdUtils.createUfePathSegment(usdPath) path = ufe.Path([proxyShapePathSegment, pathSegment]) item = ufe.Hierarchy.createItem(path) object3d = ufe.Object3d.object3d(item) # First turn off proxy, guide, render purposes on the proxy shape. # The bounding box should be invalid. purposeAttribs = [ 'drawProxyPurpose', 'drawGuidePurpose', 'drawRenderPurpose' ] for purposeAttrib in purposeAttribs: cmds.setAttr(proxyShapePath + '.' + purposeAttrib, 0) bbox = object3d.boundingBox() self.assertTrue(bbox.empty()) # Next, turn on each purpose in turn on the proxy shape. The # bounding box should be valid only if the prim's purpose matches # the proxy shape purpose. imageable = UsdGeom.Imageable(prim) primPurpose = imageable.GetPurposeAttr().Get() for (purpose, purposeAttrib) in zip(purposes, purposeAttribs): cmds.setAttr(proxyShapePath + '.' + purposeAttrib, 1) bbox = object3d.boundingBox() if primPurpose == purpose: assertVectorAlmostEqual(self, bbox.min.vector, [-1] * 3) assertVectorAlmostEqual(self, bbox.max.vector, [1] * 3) else: self.assertTrue(bbox.empty()) cmds.setAttr(proxyShapePath + '.' + purposeAttrib, 0)
def test_MakeVisible(self): testFile = "AllInvisible.usda" s = Usd.Stage.Open(testFile) bar2 = UsdGeom.Imageable(s.GetPrimAtPath("/foo/bar2")) thing1 = UsdGeom.Imageable(s.GetPrimAtPath("/foo/bar1/thing1")) thing2 = UsdGeom.Imageable(s.GetPrimAtPath("/foo/bar1/thing2")) thing1.MakeVisible() self.assertEqual(bar2.ComputeVisibility(), UsdGeom.Tokens.invisible) self.assertEqual(thing1.ComputeVisibility(), UsdGeom.Tokens.inherited) self.assertEqual(thing2.ComputeVisibility(), UsdGeom.Tokens.invisible)
def handle_visibility(self): actor_is_visible = usd_unreal.attributes.node.visibility.call_get_from_actor( self.actor) if self.original_prim and actor_is_visible == usd_unreal.attributes.node.visibility.get_from_usd( self.original_prim): return if actor_is_visible: UsdGeom.Imageable(self.get_override_prim()).MakeVisible() else: UsdGeom.Imageable(self.get_override_prim()).MakeInvisible()
def __defineStaticUSDPrimTransform__(self,dagnode_path): ''' Try to define static prim xform information. ''' scenegraph_path = self.fetchNameSceneGraphPrim(dagnode_path) scenegraph_data = self.fetchDataStaticMayaXform(dagnode_path) prim = self.__stage__.GetPrimAtPath( scenegraph_path ) if scenegraph_data["visibility"]: UsdGeom.Imageable(prim).MakeVisible() else: UsdGeom.Imageable(prim).MakeInvisible() rotateXYZ = scenegraph_data["rotateXYZ"] UsdGeom.XformCommonAPI(prim).SetRotate(tuple(rotateXYZ),UsdGeom.XformCommonAPI.RotationOrderXYZ) scale = scenegraph_data["scale"] UsdGeom.XformCommonAPI(prim).SetScale(tuple(scale)) translate = scenegraph_data["translate"] UsdGeom.XformCommonAPI(prim).SetTranslate(tuple(translate))
def testExportConnectedPlug(self): # tests issue #656 # here, visibility was connected to another plug that was not animated. cmds.file(os.path.abspath('visibility.ma'), open=True, force=True) usdFile = os.path.abspath('visibility.usda') cmds.usdExport(file=usdFile, exportVisibility=True, shadingMode='none') stage = Usd.Stage.Open(usdFile) p = stage.GetPrimAtPath('/driven') self.assertEqual( UsdGeom.Imageable(p).GetVisibilityAttr().Get(), 'invisible') p = stage.GetPrimAtPath('/invised') self.assertEqual( UsdGeom.Imageable(p).GetVisibilityAttr().Get(), 'invisible')
def __init__(self, stage, prim, dc, mp, world=None, group_path="", default_config=None, is_ghost=False): self.dc = dc self.mp = mp self.prim = prim self.stage = stage # get handle to the articulation for this franka self.ar = self.dc.get_articulation(prim.GetPath().pathString) self.is_ghost = is_ghost self.base = self.dc.get_articulation_root_body(self.ar) body_count = self.dc.get_articulation_body_count(self.ar) for bodyIdx in range(body_count): body = self.dc.get_articulation_body(self.ar, bodyIdx) self.dc.set_rigid_body_disable_gravity(body, True) exec_folder = os.path.abspath(carb.tokens.get_tokens_interface( ).resolve( "${app}/../exts/omni.isaac.motion_planning/resources/lula/lula_franka" )) self.rmp_handle = self.mp.registerRmp( exec_folder + "/urdf/lula_franka_gen.urdf", exec_folder + "/config/robot_descriptor.yaml", exec_folder + "/config/franka_rmpflow_common.yaml", prim.GetPath().pathString, "right_gripper", True, ) print("franka rmp handle", self.rmp_handle) if world is not None: self.world = world self.world.rmp_handle = self.rmp_handle self.world.register_parent(self.base, self.prim, "panda_link0") settings = omni.kit.settings.get_settings_interface() self.mp.setFrequency(self.rmp_handle, settings.get("/physics/timeStepsPerSecond"), True) self.end_effector = EndEffector(self.dc, self.mp, self.ar, self.rmp_handle) if default_config: self.mp.setDefaultConfig(self.rmp_handle, default_config) self.target_visibility = True if self.is_ghost: self.target_visibility = False self.imageable = UsdGeom.Imageable(self.prim)
def testExportImageable(self): """ Test that UsdGeomImageable.purpose is properly exported. """ newUsdFilePath = os.path.abspath('UsdAttrsNew.usda') cmds.usdExport(file=newUsdFilePath, shadingMode='none') newUsdStage = Usd.Stage.Open(newUsdFilePath) # Testing the exported purpose attributes geom1 = UsdGeom.Imageable(newUsdStage.GetPrimAtPath('/World/pCube1')) self.assertEqual(geom1.GetPurposeAttr().Get(), 'default') geom2 = UsdGeom.Imageable(newUsdStage.GetPrimAtPath('/World/pCube2')) self.assertEqual(geom2.GetPurposeAttr().Get(), 'render') geom3 = UsdGeom.Imageable(newUsdStage.GetPrimAtPath('/World/pCube3')) self.assertEqual(geom3.GetPurposeAttr().Get(), 'proxy') # Testing that there is no authored attribute geom4 = UsdGeom.Imageable(newUsdStage.GetPrimAtPath('/World/pCube4')) self.assertFalse(geom4.GetPurposeAttr().HasAuthoredValue())
def execute(self, context): obj = context.object prim = obj.hdusd.get_prim() im = UsdGeom.Imageable(prim) if im.ComputeVisibility() == 'invisible': im.MakeVisible() else: im.MakeInvisible() return {'FINISHED'}
def testExportedPrimvars(self): mayaFilePath = os.path.abspath('AlembicChaserPrimvars.ma') cmds.file(mayaFilePath, open=True, force=True) usdFilePath = os.path.abspath('out_primvars.usda') # Export to USD. cmds.usdExport(file=usdFilePath, chaser=['alembic'], chaserArgs=[ ('alembic', 'attrprefix', 'my'), ('alembic', 'primvarprefix', 'my=awesome_'), ]) stage = Usd.Stage.Open(usdFilePath) self.assertTrue(stage) prim = stage.GetPrimAtPath( '/AlembicChaserPrimvars/Geom/CubeTypedAttrs') self.assertTrue(prim) attr = prim.GetAttribute('userProperties:IntArrayAttr') self.assertTrue(attr) self.assertEqual(attr.Get(), Vt.IntArray([99, 98, 97, 96, 95, 94, 93, 92, 91, 90])) imageable = UsdGeom.Imageable(prim) self.assertTrue(imageable) primvar = imageable.GetPrimvar('awesome_ConstantIntPrimvar') self.assertTrue(primvar) self.assertEqual(primvar.Get(), 123) self.assertEqual(primvar.GetTypeName(), Sdf.ValueTypeNames.Int) self.assertEqual(primvar.GetInterpolation(), UsdGeom.Tokens.constant) primvar2 = imageable.GetPrimvar('awesome_UniformDoublePrimvar') self.assertTrue(primvar2) self.assertEqual(primvar2.Get(), 3.140) self.assertEqual(primvar2.GetTypeName(), Sdf.ValueTypeNames.Double) self.assertEqual(primvar2.GetInterpolation(), UsdGeom.Tokens.uniform) primvar3 = imageable.GetPrimvar('awesome_FaceVaryingIntPrimvar') self.assertTrue(primvar3) self.assertEqual(primvar3.Get(), 999) self.assertEqual(primvar3.GetTypeName(), Sdf.ValueTypeNames.Int) self.assertEqual(primvar3.GetInterpolation(), UsdGeom.Tokens.faceVarying) primvar4 = imageable.GetPrimvar('awesome_FloatArrayPrimvar') self.assertTrue(primvar4) self.assertEqual( primvar4.Get(), Vt.FloatArray([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8])) self.assertEqual(primvar4.GetTypeName(), Sdf.ValueTypeNames.FloatArray) self.assertEqual(primvar4.GetInterpolation(), UsdGeom.Tokens.vertex)
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): if self.layout_type not in {'DEFAULT', 'COMPACT'}: return for i in range(item.indent): layout.split(factor=0.1) items = data.items prim = data.get_prim(item) if not prim: return visible = UsdGeom.Imageable(prim).ComputeVisibility() != 'invisible' col = layout.column() if not prim.GetChildren(): icon = 'DOT' col.enabled = False elif len(items) > index + 1 and items[index + 1].indent > item.indent: icon = 'TRIA_DOWN' else: icon = 'TRIA_RIGHT' expand_op = col.operator(HDUSD_OP_usd_list_item_expand.bl_idname, text="", icon=icon, emboss=False, depress=False) expand_op.index = index col = layout.column() col.label(text=prim.GetName()) col.enabled = visible col = layout.column() col.alignment = 'RIGHT' col.label(text=prim.GetTypeName()) col.enabled = visible col = layout.column() col.alignment = 'RIGHT' if prim.GetTypeName() == 'Xform': icon = 'HIDE_OFF' if visible else 'HIDE_ON' else: col.enabled = False icon = 'NONE' visible_op = col.operator(HDUSD_OP_usd_list_item_show_hide.bl_idname, text="", icon=icon, emboss=False, depress=False) visible_op.index = index
def __init__(self, mainWindow, item): NodeContextMenuItem.__init__(self, mainWindow, item) from pxr import UsdGeom self._imageable = False self._isVisible = False for prim in self._currentNodes: imgbl = UsdGeom.Imageable(prim) if imgbl: self._imageable = True self._isVisible = (imgbl.ComputeVisibility( self._currentFrame) == UsdGeom.Tokens.inherited) break
def relocateWorldCenter(self,in_dagnode_path="|assets", out_dagnode_path="|assets|scn"): ''' Try to define static prim xform information. ''' if not cmds.objExists(in_dagnode_path) or not cmds.objExists(out_dagnode_path): return if not self.isDAGNodeBeMoved(in_dagnode_path): return scenegraph_path = self.fetchNameSceneGraphPrim(out_dagnode_path) scenegraph_data = self.fetchDataStaticMayaXform(in_dagnode_path) prim = self.__stage__.GetPrimAtPath( scenegraph_path ) if scenegraph_data["visibility"]: UsdGeom.Imageable(prim).MakeVisible() else: UsdGeom.Imageable(prim).MakeInvisible() rotateXYZ = scenegraph_data["rotateXYZ"] UsdGeom.XformCommonAPI(prim).SetRotate(tuple(rotateXYZ),UsdGeom.XformCommonAPI.RotationOrderXYZ) scale = scenegraph_data["scale"] UsdGeom.XformCommonAPI(prim).SetScale(tuple(scale)) translate = scenegraph_data["translate"] UsdGeom.XformCommonAPI(prim).SetTranslate(tuple(translate))
def __init__(self, appController, item): PrimContextMenuItem.__init__(self, appController, item) from pxr import UsdGeom self._imageable = False self._isVisible = False for prim in self._selectionDataModel.getPrims(): imgbl = UsdGeom.Imageable(prim) if imgbl: self._imageable = True self._isVisible = (imgbl.ComputeVisibility(self._currentFrame) == UsdGeom.Tokens.inherited) break
def create_ghost_franka(stage, env_path, franka_ghost_usd, ghost_robot, ghost_index): ghost_path = env_path + "/Ghost/robot_{}".format(ghost_index) ghostPrim = stage.DefinePrim(ghost_path, "Xform") ghostPrim.GetReferences().AddReference(franka_ghost_usd) set_translate(ghostPrim, Gf.Vec3d(0, 0, 0)) imageable = UsdGeom.Imageable( ghostPrim) # Hide the ghost franka when spawned if imageable: imageable.MakeInvisible() # set the ghost collision for this prim setCollisionGroupFranka(stage, ghost_path + "/Franka/panda", ghost_robot, True)
def makeVisible(self): if self.canChangeVis(): # It is in general not kosher to use an Sdf.ChangeBlock around # operations at the Usd API level. We have carefully arranged # (with insider knowledge) to have only "safe" mutations # happening inside the ChangeBlock. We do this because # UsdImaging updates itself independently for each # Usd.Notice.ObjectsChanged it receives. We hope to eliminate # the performance need for this by addressing bug #121992 from pxr import Sdf with Sdf.ChangeBlock(): UsdGeom.Imageable(self.prim).MakeVisible() self.visChanged()
def __init__(self): AttributesContainerBase.__init__(self) attribute = self.define_attribute("Visibility") self.visibility = attribute attribute.construct_usd_attribute = lambda usd_node: usd_node.GetVisibilityAttr( ) attribute.convert_unreal_to_usd = lambda visible: UsdGeom.Tokens.inherited if visible else UsdGeom.Tokens.invisible attribute.get_from_usd = lambda usd_node: UsdGeom.Imageable( usd_node).ComputeVisibility() != UsdGeom.Tokens.invisible attribute.get_from_actor = lambda actor: actor.hidden == False attribute.set_on_unreal_actor = lambda actor, value: actor.set_editor_property( "hidden", value != True)
def main(): """Run the main execution of the current script.""" stage = Usd.Stage.CreateInMemory() sphere = UsdGeom.Sphere.Define(stage, "/SomeSphere") sphere.AddTranslateOp().Set(Gf.Vec3d(20, 30, 40)) # Method #1: Compute at a certain time print( UsdGeom.Imageable(sphere).ComputeWorldBound(Usd.TimeCode(1), purpose1="default")) # Method #2: Compute using a cache cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), ["default", "render"]) print(cache.ComputeWorldBound(sphere.GetPrim()))
def test_SubsetRetrievalAndValidity(self): geom = UsdGeom.Imageable(sphere) self.assertTrue(geom) materialBindSubsets = UsdGeom.Subset.GetGeomSubsets( geom, elementType=UsdGeom.Tokens.face, familyName='materialBind') self.assertEqual(len(materialBindSubsets), 3) self.assertEqual(UsdGeom.Tokens.partition, UsdGeom.Subset.GetFamilyType(geom, 'materialBind')) (valid, reason) = UsdGeom.Subset.ValidateSubsets( materialBindSubsets, elementCount=16, familyType=UsdGeom.Tokens.partition) (valid, reason) = UsdGeom.Subset.ValidateFamily(geom, UsdGeom.Tokens.face, familyName='materialBind') self.assertTrue(valid) validFamilies = [ 'materialBind', 'validPartition', 'validNonOverlapping', 'validUnrestricted' ] for familyName in validFamilies: (valid, reason) = UsdGeom.Subset.ValidateFamily(geom, UsdGeom.Tokens.face, familyName=familyName) self.assertTrue( valid, "FaceSubset family '%s' was found to be " "invalid: %s" % (familyName, reason)) self.assertEqual(len(reason), 0) invalidFamilies = [ 'invalidIndices', 'badPartition1', 'badPartition2', 'badPartition3', 'invalidNonOverlapping', 'invalidUnrestricted' ] for familyName in invalidFamilies: (valid, reason) = UsdGeom.Subset.ValidateFamily(geom, UsdGeom.Tokens.face, familyName=familyName) print("Face-subset family '%s' should be invalid because: %s" % \ (familyName, reason)) self.assertFalse(valid) self.assertTrue(len(reason) > 0)
def getPrimsToTranslate(cls, parentPrim, onlyTranslateVisible): prims = [] for prim in Usd.PrimRange(parentPrim): if prim.IsInstance(): for instancedPrim in prim.GetFilteredChildren( Usd.TraverseInstanceProxies()): prims.extend( cls._getPrimsToTranslate(instancedPrim, onlyTranslateVisible)) else: if prim.GetTypeName() != 'Mesh': continue if onlyTranslateVisible and UsdGeom.Imageable( prim).ComputeVisibility() == 'invisible': continue prims.extend(list(Usd.PrimRange(prim))) return prims
def execute(self, context): if self.index == -1: return {'CANCELLED'} node = context.active_node usd_list = node.hdusd.usd_list items = usd_list.items item = items[self.index] prim = usd_list.get_prim(item) im = UsdGeom.Imageable(prim) if im.ComputeVisibility() == 'invisible': im.MakeVisible() else: im.MakeInvisible() return {'FINISHED'}
def test_Basic(self): usdFilePath = "Sphere.usda" stage = Usd.Stage.Open(usdFilePath) self.assertTrue(stage) sphere = stage.GetPrimAtPath('/Sphere/Mesh') mat1 = stage.GetPrimAtPath('/Sphere/Materials/initialShadingGroup') mat2= stage.GetPrimAtPath('/Sphere/Materials/lambert2SG') mat3= stage.GetPrimAtPath('/Sphere/Materials/lambert3SG') self.assertTrue(sphere and mat1 and mat2 and mat3) # Verify that the sphere mesh does not have an existing material face-set. geomSphere = UsdGeom.Imageable(sphere) materialBindSubsets = UsdShade.Material.GetMaterialBindFaceSubsets( geomSphere) self.assertEqual(len(materialBindSubsets), 0) faceIndices1 = Vt.IntArray((0, 1, 2, 3)) faceIndices2 = Vt.IntArray((4, 5, 6, 7, 8, 9, 10, 11)) faceIndices3 = Vt.IntArray((12, 13, 14, 15)) # Create a new family of subsets with familyName="materialBind" . subset1 = UsdShade.Material.CreateMaterialBindFaceSubset(geomSphere, 'subset1', faceIndices1) subset2 = UsdShade.Material.CreateMaterialBindFaceSubset(geomSphere, 'subset2', faceIndices2) subset3 = UsdShade.Material.CreateMaterialBindFaceSubset(geomSphere, 'subset3', faceIndices3) (valid, reason) = UsdGeom.Subset.ValidatePartition( [subset1, subset2, subset3], 16) self.assertTrue(valid) UsdShade.Material(mat1).Bind(subset1.GetPrim()) UsdShade.Material(mat2).Bind(subset2.GetPrim()) UsdShade.Material(mat3).Bind(subset3.GetPrim()) # Don't save the modified source stage. Export it into a # new layer for baseline diffing. stage.Export("SphereWithMaterialBind.usda", addSourceFileComment=False)
def setup_physics(self): stage = self.omni_kit.get_stage() # Add physics scene scene = PhysicsSchema.PhysicsScene.Define(stage, Sdf.Path("/World/Env/PhysicsScene")) # Set gravity vector scene.CreateGravityAttr().Set(Gf.Vec3f(0.0, 0.0, -981.0)) # Set physics scene to use cpu physics PhysxSchema.PhysxSceneAPI.Apply(stage.GetPrimAtPath("/World/Env/PhysicsScene")) physxSceneAPI = PhysxSchema.PhysxSceneAPI.Get(stage, "/World/Env/PhysicsScene") physxSceneAPI.CreatePhysxSceneEnableCCDAttr(True) physxSceneAPI.CreatePhysxSceneEnableStabilizationAttr(True) physxSceneAPI.CreatePhysxSceneEnableGPUDynamicsAttr(False) physxSceneAPI.CreatePhysxSceneBroadphaseTypeAttr("MBP") physxSceneAPI.CreatePhysxSceneSolverTypeAttr("TGS") # Create physics plane for the ground PhysicsSchemaTools.addGroundPlane( stage, "/World/Env/GroundPlane", "Z", 100.0, Gf.Vec3f(0, 0, self.height), Gf.Vec3f(1.0) ) # Hide the visual geometry imageable = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Env/GroundPlane/geom")) if imageable: imageable.MakeInvisible()
def draw(self, context): obj = context.object prim = obj.hdusd.get_prim() if not prim: return layout = self.layout layout.use_property_split = True layout.use_property_decorate = False split = layout.row(align=True).split(factor=0.4) col1 = split.column() col1.alignment = 'RIGHT' col2 = split.column() col1.label(text="Name") col2.label(text=prim.GetName()) col1.label(text="Path") col2.label(text=str(prim.GetPath())) col1.label(text="Type") col2.label(text=prim.GetTypeName()) if prim.GetTypeName() in GEOM_TYPES: visible = UsdGeom.Imageable(prim).ComputeVisibility() != 'invisible' icon = 'HIDE_OFF' if visible else 'HIDE_ON' col1.label(text="Visibility") col2.operator(HDUSD_OP_usd_object_show_hide.bl_idname, text="Hide" if visible else 'Show', icon='HIDE_OFF' if visible else 'HIDE_ON', emboss=True, depress=False) if not config.usd_mesh_assign_material_enabled: return if prim.GetTypeName() in 'Mesh': layout.prop(obj.hdusd, 'material')
def loadVis(self, inheritedVis, visHasBeenAuthored): if not (self.imageable and self.active): return inheritedVis time = self._appController._dataModel.currentFrame # If visibility-properties have changed on the stage, then # we must re-evaluate our variability before deciding whether # we can avoid re-reading our visibility visAttr = UsdGeom.Imageable(self.prim).GetVisibilityAttr() if visHasBeenAuthored: self.visVaries = visAttr.ValueMightBeTimeVarying() if not self.visVaries: self.vis = visAttr.Get(time) if self.visVaries: self.vis = visAttr.Get(time) self.computedVis = UsdGeom.Tokens.invisible \ if self.vis == UsdGeom.Tokens.invisible \ else inheritedVis self.emitDataChanged() return self.computedVis
def InvisRootPrims(stage): """Make all defined root prims of stage be invisible, at Usd.TimeCode.Default()""" from pxr import UsdGeom for p in stage.GetPseudoRoot().GetChildren(): UsdGeom.Imageable(p).MakeInvisible()
def removeVisibility(self): if self.canChangeVis(): UsdGeom.Imageable(self.prim).GetVisibilityAttr().Clear() self.visChanged()
def test_CreateGeomSubset(self): geom = UsdGeom.Imageable(sphere) self.assertTrue(geom) newSubset = UsdGeom.Subset.CreateGeomSubset(geom, 'testSubset', UsdGeom.Tokens.face, indices=Vt.IntArray()) # Indices are empty when unassigned. self.assertEqual(newSubset.GetIndicesAttr().Get(), Vt.IntArray()) self.assertEqual(UsdGeom.Subset.GetUnassignedIndices([newSubset], 16), Vt.IntArray(range(0, 16))) indices = [1, 2, 3, 4, 5] newSubset.GetIndicesAttr().Set(indices) self.assertEqual(list(newSubset.GetIndicesAttr().Get()), indices) # Check elementType self.assertEqual(newSubset.GetElementTypeAttr().Get(), UsdGeom.Tokens.face) # Check familyName self.assertEqual(newSubset.GetFamilyNameAttr().Get(), '') newSubset.GetFamilyNameAttr().Set('testFamily') self.assertEqual(newSubset.GetFamilyNameAttr().Get(), 'testFamily') # By default, a family of subsets is not tagged as a partition. self.assertEqual(UsdGeom.Subset.GetFamilyType(geom, 'testFamily'), UsdGeom.Tokens.unrestricted) # Ensure that there's only one subset belonging to 'testFamily'. testSubsets = UsdGeom.Subset.GetGeomSubsets(geom, UsdGeom.Tokens.face, 'testFamily') self.assertEqual(len(testSubsets), 1) # Calling CreateGeomSubset with the same subsetName will just update # info on the existing subset. newIndices = Vt.IntArray([0, 1, 2]) newerSubset = UsdGeom.Subset.CreateGeomSubset( geom, "testSubset", UsdGeom.Tokens.face, newIndices, familyName='testFamily', familyType=UsdGeom.Tokens.partition) self.assertEqual(newerSubset.GetPrim(), newSubset.GetPrim()) testSubsets = UsdGeom.Subset.GetGeomSubsets(geom, UsdGeom.Tokens.face, 'testFamily') # Count is still one as no new subset was created by the above call. self.assertEqual(len(testSubsets), 1) isTaggedAsPartition = ( UsdGeom.Tokens.partition == UsdGeom.Subset.GetFamilyType( geom, 'testFamily')) self.assertTrue(isTaggedAsPartition) self.assertEqual(UsdGeom.Subset.GetFamilyType(geom, 'testFamily'), UsdGeom.Tokens.partition) (valid, reason) = UsdGeom.Subset.ValidateSubsets( testSubsets, elementCount=16, familyType=UsdGeom.Tokens.partition) self.assertFalse(valid) # CreateUniqueGeomSubset will create a new subset always! unassignedIndices = UsdGeom.Subset.GetUnassignedIndices( testSubsets, 16) self.assertEqual(unassignedIndices, Vt.IntArray(range(3, 16))) anotherSubset = UsdGeom.Subset.CreateUniqueGeomSubset( geom, "testSubset", UsdGeom.Tokens.face, unassignedIndices, familyName='testFamily', familyType=UsdGeom.Tokens.partition) self.assertNotEqual(anotherSubset.GetPrim().GetName(), newSubset.GetPrim().GetName()) self.assertEqual(unassignedIndices, anotherSubset.GetIndicesAttr().Get()) # Verify that GetAssignedIndices still works if the provided element # count is less than the number of assigned indices (as per bug USD-5599) self.assertEqual( UsdGeom.Subset.GetUnassignedIndices([anotherSubset], 5), Vt.IntArray([0, 1, 2])) self.assertEqual( UsdGeom.Subset.GetUnassignedIndices([anotherSubset], 2), Vt.IntArray([0, 1])) testSubsets = UsdGeom.Subset.GetGeomSubsets(geom, UsdGeom.Tokens.face, familyName='testFamily') # Count is now two after the call to CreateUniqueGeomSubset. self.assertEqual(len(testSubsets), 2) (valid, reason) = UsdGeom.Subset.ValidateSubsets( testSubsets, elementCount=16, familyType=UsdGeom.Tokens.partition) self.assertTrue(valid) # Check total count. allGeomSubsets = UsdGeom.Subset.GetAllGeomSubsets( UsdGeom.Imageable(sphere)) self.assertEqual(len(allGeomSubsets), 21) # Check that invalid negative indices are ignored when getting # unassigned indices. invalidIndices = Vt.IntArray([-3, -2, 0, 1, 2]) invalidSubset = UsdGeom.Subset.CreateUniqueGeomSubset( geom, "testSubset", UsdGeom.Tokens.face, invalidIndices, familyName='testFamily', familyType=UsdGeom.Tokens.partition) invalidSubset.GetIndicesAttr().Set(invalidIndices) self.assertTrue(invalidSubset) self.assertEqual( UsdGeom.Subset.GetUnassignedIndices([invalidSubset], 5), Vt.IntArray([3, 4]))
def setVisible(self, visible): if self.canChangeVis(): UsdGeom.Imageable(self.prim).GetVisibilityAttr().Set( UsdGeom.Tokens.inherited if visible else UsdGeom.Tokens. invisible) self.visChanged()
def test_Basic(self): usdFilePath = "Sphere.usda" stage = Usd.Stage.Open(usdFilePath) self.assertTrue(stage) sphere = stage.GetPrimAtPath('/Sphere/Mesh') mat1 = UsdShade.Material.Get(stage, '/Sphere/Materials/initialShadingGroup') mat2 = UsdShade.Material.Get(stage, '/Sphere/Materials/lambert2SG') mat3 = UsdShade.Material.Get(stage, '/Sphere/Materials/lambert3SG') self.assertTrue(sphere and mat1 and mat2 and mat3) # Verify that the sphere mesh does not have an existing material face-set. geomSphere = UsdGeom.Imageable(sphere) materialBindSubsets = UsdShade.MaterialBindingAPI(sphere) \ .GetMaterialBindSubsets() self.assertEqual(len(materialBindSubsets), 0) faceIndices1 = Vt.IntArray((0, 1, 2, 3)) faceIndices2 = Vt.IntArray((4, 5, 6, 7, 8, 9, 10, 11)) faceIndices3 = Vt.IntArray((12, 13, 14, 15)) # Create a new family of subsets with familyName="materialBind" . subset1 = UsdShade.MaterialBindingAPI(sphere).CreateMaterialBindSubset( 'subset1', faceIndices1, UsdGeom.Tokens.face) # Default elementType is 'face' subset2 = UsdShade.MaterialBindingAPI(sphere).CreateMaterialBindSubset( 'subset2', faceIndices2) self.assertEqual(subset2.GetElementTypeAttr().Get(), UsdGeom.Tokens.face) (valid, reason) = UsdGeom.Subset.ValidateFamily(geomSphere, UsdGeom.Tokens.face, UsdShade.Tokens.materialBind) self.assertTrue(valid) (valid, reason) = UsdGeom.Subset.ValidateSubsets( [subset1, subset2], elementCount=16, familyType=UsdGeom.Tokens.nonOverlapping) self.assertTrue(valid) # Not quite a partition yet. (valid, reason) = UsdGeom.Subset.ValidateSubsets( [subset1, subset2], elementCount=16, familyType=UsdGeom.Tokens.partition) self.assertFalse(valid) # Add a subset that makes the family a partition. subset3 = UsdShade.MaterialBindingAPI(sphere).CreateMaterialBindSubset( 'subset3', faceIndices3) (valid, reason) = UsdGeom.Subset.ValidateSubsets( [subset1, subset2, subset3], elementCount=16, familyType=UsdGeom.Tokens.partition) self.assertTrue(valid) self.assertEqual( UsdShade.MaterialBindingAPI(sphere) \ .GetMaterialBindSubsetsFamilyType(),UsdGeom.Tokens.nonOverlapping) UsdShade.MaterialBindingAPI(sphere).SetMaterialBindSubsetsFamilyType( UsdGeom.Tokens.partition) (valid, reason) = UsdGeom.Subset.ValidateFamily(geomSphere, UsdGeom.Tokens.face, UsdShade.Tokens.materialBind) self.assertTrue(valid) UsdShade.MaterialBindingAPI(subset1.GetPrim()).Bind(mat1) UsdShade.MaterialBindingAPI(subset2.GetPrim()).Bind(mat2) UsdShade.MaterialBindingAPI(subset3.GetPrim()).Bind(mat3) # Don't save the modified source stage. Export it into a # new layer for baseline diffing. stage.Export("SphereWithMaterialBind.usda", addSourceFileComment=False)