def RefreshAnimationModuleList(self, _index = 1): pm.textScrollList(self.UIElements["animationModule_textScroll"], edit = True, removeAll = True) pm.symbolButton(self.UIElements["deleteModuleButton"], edit = True, enable = False) pm.symbolButton(self.UIElements["duplicateModuleButton"], edit = True, enable = False) selectedBlueprintModule = pm.textScrollList(self.UIElements["blueprintModule_textScroll"], query = True, selectItem = True) self.selectedBlueprintModule = self.blueprintModules[selectedBlueprintModule[0]] self.SetupActiveModuleControls() pm.namespace(setNamespace = self.selectedBlueprintModule) controlModuleNamespaces = pm.namespaceInfo(listOnlyNamespaces = True) pm.namespace(setNamespace = ":") if len(controlModuleNamespaces) != 0: for module in controlModuleNamespaces: moduleName = utils.StripAllNamespaces(module)[1] pm.textScrollList(self.UIElements["animationModule_textScroll"], edit = True, append = moduleName) pm.textScrollList(self.UIElements["animationModule_textScroll"], edit = True, selectIndexedItem = _index) pm.symbolButton(self.UIElements["deleteModuleButton"], edit = True, enable = True) pm.symbolButton(self.UIElements["duplicateModuleButton"], edit = True, enable = True) self.SetupModuleSpecificControls() self.previousBlueprintListEntry = selectedBlueprintModule
def assign_mtl_from_resources(obj_names, mtl_name, include_displacement=True, displacement_kw={}): if "." in mtl_name: mtl_name = mtl_name.split(".")[-2] mtl_full_name = "%s:%s" % (MTL_NS, mtl_name) if not pm.objExists(mtl_name) and not pm.objExists(mtl_full_name): base_dir = get_project_root_dir() mtl_path = os.path.join(base_dir, "resources", "%s.ma" % mtl_name) print('loading mtl from %s' % mtl_path) pm.importFile(mtl_path, namespace=TMP_NS) if not pm.system.namespace(exists=MTL_NS): pm.system.namespace(addNamespace=MTL_NS) mc.namespace(force=True, mv=(':' + TMP_NS, ':' + MTL_NS)) pm.namespace(removeNamespace=TMP_NS, mergeNamespaceWithRoot=True) mtl = pm.PyNode(mtl_full_name) print("Assigning shader...") for selection_string in obj_names: for obj in pm.ls(selection_string, type='transform'): name = obj.name() plant_sg_name = mtl.shadingGroups()[0].name() mc.sets(name, e=True, forceElement=plant_sg_name) if include_displacement: set_arnold_displacement_attrs(name, **displacement_kw)
def test_move_multiple_nodes(self): pm.namespace(set=':') test_cubes = [self.create_cube() for _ in range(5)] ns = self.create_namespace(':foo:bar') [self.assertEqual('', x.namespace()) for x in test_cubes] namespaceutils.move_nodes_to_namespace(test_cubes, ns) [self.assertEqual(ns, x.parentNamespace()) for x in test_cubes]
def test_noop_if_namespace_already_exists(self): pm.namespace(set=':') ns_foo = self.create_namespace('foo') namespaceutils.add_namespace_to_root('foo') expected = [ns_foo] result = pm.listNamespaces(recursive=True) self.assertListEqual(expected, result)
def getNamespaces(self): namespacesList = [] #Check if current namespace is root else set to scene root if not(pm.namespaceInfo(isRootNamespace = True)): #store current namespace currentNamespace = pm.namespaceInfo(currentNamespace = True) #Set to rootnamespace pm.namespace(setNamespace = ':') #Query namespaceList namespacesList = pm.namespaceInfo(listOnlyNamespaces = True, r = True) #Set back to old namespace pm.namespace(setNamespace = currentNamespace) #If namespace is root namespace else: #Query namespaceList namespacesList = pm.namespaceInfo(listOnlyNamespaces = True, r = False) #Rebuild namespaceList without UI and shared namespacesListTmp = [] for namespaceItem in namespacesList: if not(namespaceItem == 'UI' or namespaceItem == 'shared'): namespacesListTmp.append(namespaceItem) namespacesList = namespacesListTmp return namespacesList
def build_rig(self, *args): """ Builds the skeleton """ pm.namespace(setNamespace=":") self.deleteScriptJob() # temporary way of finding all modules all_modules = pm.ls(type="network") module_instances = [] for mod in all_modules: mod_moduleType = utils.getModuleMetaInfo(mod, "ModuleType") mod_namespace = utils.getModuleMetaInfo(mod, "Namespace") module = __import__(environ.BlueprintModulePath + mod_moduleType, {}, {}, [mod_moduleType]) reload(module) moduleClass = getattr(module, module.CLASS_NAME) module_instance = moduleClass(mod_namespace, self.find_parentModule()) module_information = module_instance.getJointInformation() # module_instances.append( module_information ) module_instances.append((module_instance, module_information)) for module in module_instances: module[0].lock_joints1(module[1]) for module in module_instances: module[0].lock_joints2(module[1][5])
def getNamespaces(self): namespacesList = [] #Check if current namespace is root else set to scene root if not (pm.namespaceInfo(isRootNamespace=True)): #store current namespace currentNamespace = pm.namespaceInfo(currentNamespace=True) #Set to rootnamespace pm.namespace(setNamespace=':') #Query namespaceList namespacesList = pm.namespaceInfo(listOnlyNamespaces=True, r=True) #Set back to old namespace pm.namespace(setNamespace=currentNamespace) #If namespace is root namespace else: #Query namespaceList namespacesList = pm.namespaceInfo(listOnlyNamespaces=True, r=False) #Rebuild namespaceList without UI and shared namespacesListTmp = [] for namespaceItem in namespacesList: if not (namespaceItem == 'UI' or namespaceItem == 'shared'): namespacesListTmp.append(namespaceItem) namespacesList = namespacesListTmp #append root namespacesList.append('root') return namespacesList
def testRetargets(): """ Test the retargets in the current scene. Returns: Joint: The newly created root skeleton. """ # Add a namespace for duplicate nodes DUP_NAMESPACE = 'DUP' if not pmc.namespace(exists=DUP_NAMESPACE): pmc.namespace(add=DUP_NAMESPACE) # Duplicate the bind skeleton root = getRootJoint() dupRoot = pmc.duplicate(root)[0] dupSkeleton = [dupRoot] + dupRoot.listRelatives(ad=True, type='joint') # Add a namespace to duplicates for joint in dupSkeleton: pmc.rename(joint, '%s:%s' % (DUP_NAMESPACE, joint.nodeName())) pmc.rename(dupRoot, dupRoot.nodeName().replace('1', '')) # Bind duplicates to targets for joint in dupSkeleton: rigJoint = pmc.PyNode(joint.nodeName().split(':')[-1]) for target in getRetargets(rigJoint): pmc.parentConstraint(joint, target, mo=True)
def test_move_one_node(self): pm.namespace(set=':') ns = self.create_namespace(':foo:bar') test_cube = self.create_cube() self.assertEqual('', test_cube.namespace()) namespaceutils.move_node_to_namespace(test_cube, ns) self.assertEqual(ns, test_cube.parentNamespace())
def rename_module(self, new_name): """ renames the entire modules namespace """ if new_name == self.userSpecifiedName: return # Rename the module name new_name = utils.moduleNamespace(new_name) pm.lockNode(self.module_container, lock=False, lockUnpublished=False) pm.namespace(setNamespace=":") pm.namespace(add=new_name) pm.namespace(setNamespace=":") pm.namespace(moveNamespace=[self.userSpecifiedName, new_name]) pm.namespace(removeNamespace=self.userSpecifiedName) self.userSpecifiedName = new_name self.module_container = self.userSpecifiedName + ":module_container" # change meta node attribute UserSpecifiedName utils.setModuleMetaInfo(self.module_container, "Namespace", self.userSpecifiedName) pm.lockNode(self.module_container, lock=True, lockUnpublished=True) return
def _updateNameSpaceList(self): """update namespace menu item""" # delete all items self._deleteNameSpaceList() # get current namespace current = pmc.namespaceInfo(currentNamespace=True) # get all namespace pmc.namespace(set=':') listNamespace = pmc.namespaceInfo(listOnlyNamespaces=True, recurse=True) pmc.namespace(set=current) if current == ':': current = self.rootNamespace # add root namespace listNamespace.append(self.rootNamespace) # add menuItem i = 1 for nameSpace in listNamespace: if nameSpace in ['UI', 'shared']: continue pmc.menuItem(label=nameSpace, parent=self.uiMain['namespaceOpM']) if nameSpace == current: self.uiMain['namespaceOpM'].setSelect(i) i=i+1
def installModule(self, module, *args): #1. Create Unique Module Name: name = BlueprintModuleName__UserSpecifiedName:objectName basename = "instance_" pm.namespace(setNamespace=":") namespace = pm.namespaceInfo(listOnlyNamespaces=True) #1a. search existing namespaces for all that have __UserSpecifiedName for i in range(len(namespace)): #index of first occurence, find __, if found if namespace[i].find("__") != -1: namespace[i] = namespace[i].partition("__")[2] #1b. create unique UserSpecifiedName (get hightest digit that exists and add 1) newSuffix = utils.findHeighestTrailingNumber(namespace, basename) + 1 userSpecName = basename + str(newSuffix) #import module mod = __import__("Blueprint." + module, {}, {}, [module]) reload(mod) #create class reference from string (without ()) moduleClass = getattr(mod, mod.CLASS_NAME) #with class reference, call constructor and istall method of this module moduleInstance = moduleClass(userSpecName) moduleInstance.install() moduleTransform = mod.CLASS_NAME + "__" + userSpecName + ":module_transform" pm.select(moduleTransform, replace=True) pm.setToolTo("moveSuperContext")
def test_searches_all_namespaces_if_ns_not_in_current(self): pm.namespace(set=':') ns = self.create_namespace(':foo') ns2 = self.create_namespace(':bar') pm.namespace(set=ns2) namespaceutils.set_namespace('foo') current_ns = pm.namespaceInfo(currentNamespace=True) self.assertEqual(ns, current_ns)
def test_not_root_with_leading_colon(self): pm.namespace(set=':') ns_bar = self.create_namespace('bar') pm.namespace(set=':bar') ns = namespaceutils.add_namespace_to_root(':foo') expected = [':bar', ':foo'] result = [str(x) for x in pm.listNamespaces(recursive=True)] self.assertListEqual(expected, result)
def test_dup_to_namespace(self): test_cube = self.create_cube() pm.namespace(add='foo') dups = namespaceutils.duplicate_to_namespace([test_cube], dup_namespace='foo') self.assertEqual(len(dups), 1) result = dups[0].name() expected = 'foo:' + test_cube.nodeName() self.assertEqual(expected, result)
def test_return_to_root(self): pm.namespace(set=':') ns = self.create_namespace(':foo') with namespaceutils.preserve_namespace(): pm.namespace(set=':foo') test_cube = self.create_cube() self.assertEqual(ns, test_cube.parentNamespace()) self.assertEqual(':', self.pm.namespaceInfo(currentNamespace=True))
def importRigFromReference(rigPath, cleanup=True): refFile = getRefFileFromPath(rigPath) if refFile: namespace = refFile.namespace refFile.importContents() if cleanup: pc.namespace(removeNamespace=namespace, mnr=True) pc.delete(pc.ls(type='unknown'))
def removeNamespace(obj=None): '''removes the namespace of the given or selected PyNode''' if not obj: obj = pc.ls(sl=True)[0] name = obj.name() nameParts = name.split(':') ns = ':'.join(nameParts[0:-1]) + ':' pc.namespace(mergeNamespaceWithRoot=True, removeNamespace=ns)
def test_same_ns_as_current(self): pm.namespace(set=':') ns = self.create_namespace(':foo') pm.namespace(set=ns) with namespaceutils.preserve_namespace(ns): test_cube = self.create_cube() self.assertEqual(ns, test_cube.parentNamespace()) self.assertEqual(ns, self.pm.namespaceInfo(currentNamespace=True))
def bdImportController(self, n): con = self.conList[n] animConName = self.bdGetConName() overrideColor = self.conColors[str(self.inputConSide.currentText())] conSize = self.inputConSize.text() selection = pm.ls(sl=True) selPos = [0, 0, 0] selRot = [0, 0, 0] if selection: selPos = selection[0].getTranslation(space='world') selRot = selection[0].getRotation(space='world') if not conSize: conSize = 1 if animConName != '': scriptPath = os.path.dirname(__file__) conFile = scriptPath + '/controllers/' + con + '.ma' conTransform = \ [f for f in pm.importFile(conFile, returnNewNodes=True, namespace='temp') if f.type() == 'transform'][0] # conTransform = pm.importFile( conFile,returnNewNodes=True,namespace='temp') sceneNS = pm.namespaceInfo(lon=True, r=True) importNS = [] for ns in sceneNS: if 'temp' in ns: importNS.append(ns) importNS.reverse() for ns in importNS: pm.namespace(rm=ns, mergeNamespaceWithRoot=True) print conTransform conTransform.rename(animConName) conTransformChidlren = conTransform.getChildren(ad=True, type='transform') for child in conTransformChidlren: child.rename( str(self.inputConSide.currentText()) + child.name()) scaleVector = om.MVector(1, 1, 1) * float(conSize) conTransform.setScale( [scaleVector.x, scaleVector.y, scaleVector.z]) pm.makeIdentity(conTransform, apply=True, t=0, r=0, s=1) for shape in conTransform.getChildren(): shape.overrideEnabled.set(1) shape.overrideColor.set(overrideColor) conTransformGrp = pm.group(conTransform, name=conTransform.name() + '_GRP') conTransformGrp.setPivots([0, 0, 0]) conTransformGrp.setTranslation(selPos, space='world') conTransformGrp.setRotation(selRot, space='world')
def cleanNamespace(ns='previous'): try: if pm.objExists(ns+':cameras'): pm.delete(ns+':cameras') if pm.namespace(ex=ns): pm.namespace(rm=ns) except: print traceback.format_exc()
def cleanOldSG(self): objName = self.objName_LE.text() engine_list = ['redShift', 'renderman', 'stingray'] for engine in engine_list: name_space = objName + "_" + engine + '_SG' if pm.namespace(exists=name_space): old_nodes = pm.ls(name_space + ":*") pm.delete(old_nodes) pm.namespace(removeNamespace=name_space)
def listAllNamespaces(self): """ List all namespaces except the UI and shared """ pc.namespace(set=":") nss = pc.namespaceInfo(listOnlyNamespaces=True) nss.remove('UI') nss.remove('shared') return(nss)
def deleteAsset(self, refNodes): namespace = refNodes[0].associatedNamespace(baseName=False) for ref in refNodes: pm.FileReference(ref).remove() # remove the namespace and any nodes that may still exist in it if pm.namespace(exists=namespace): pm.namespace(dnc=True, rm=namespace)
def delete_all_namespaces(): """ Delete all the namespaces in the scene and merge them with the root. """ namespaces = pm.listNamespaces(recursive=True, internal=False) for ns in reversed(namespaces): pm.namespace(removeNamespace=ns, mergeNamespaceWithRoot=True) print('{} name spaces removed'.format(len(namespaces)))
def test_all_the_things(self): parents = [self.create_transform_node() for x in range(2)] test_cubes = [self.create_cube() for _ in range(5)] [x.setParent(parents[0]) for x in test_cubes] pm.namespace(add='foo') dups = namespaceutils.duplicate_to_namespace(test_cubes, dup_namespace='foo', dup_parent=parents[1]) self.assertEqual(len(test_cubes), len(dups)) [self.assertEqual(parents[1], dup.getParent()) for dup in dups] [self.assertEqual(tc.nodeName(), dup.nodeName(stripNamespace=True)) for tc, dup in zip(test_cubes, dups)] [self.assertEqual(dup.parentNamespace(), 'foo') for dup in dups]
def test_if_multiple_matching_ns_take_first_nested_first(self): pm.namespace(set=':') ns_foo = self.create_namespace(':foo') ns_bar = self.create_namespace(':bar') ns_bar_foo = self.create_namespace(':bar:foo') ns_bar_foo_spam_foo = self.create_namespace(':bar:foo:spam:foo') pm.namespace(set=ns_bar) namespaceutils.set_namespace('foo') current_ns = pm.namespaceInfo(currentNamespace=True) self.assertEqual(ns_bar_foo, current_ns)
def save_offsets(*args): sel = pymel.selected() pymel.select('Offset_Proportions', replace=True) pymel.namespace(set=':') path = os.path.normpath(consts.RIG_PATH + '/Extraction_Shapes/Body_Offset_Shapes.fbx') path = path.replace('\\', '/') pymel.mel.eval('FBXExport -file "{}" -s'.format(path)) pymel.select(sel, replace=True)
def test_start_at_root_true(self): pm.namespace(set=':') ns_foo = self.create_namespace(':foo') ns_bar = self.create_namespace(':bar') ns_bar_foo = self.create_namespace(':bar:foo') ns_bar_foo_spam_foo = self.create_namespace(':bar:foo:spam:foo') pm.namespace(set=ns_bar) namespaceutils.set_namespace('foo', start_at_root=True) current_ns = pm.namespaceInfo(currentNamespace=True) self.assertEqual(ns_foo, current_ns)
def test_dup_to_both(self): parents = [self.create_transform_node() for x in range(2)] test_cube = self.create_cube() test_cube.setParent(parents[0]) pm.namespace(add='foo') dups = namespaceutils.duplicate_to_namespace([test_cube], dup_namespace='foo', dup_parent=parents[1]) self.assertEqual(len(dups), 1) self.assertEqual(parents[1], dups[0].getParent()) self.assertEqual(test_cube.nodeName(), dups[0].nodeName(stripNamespace=True)) self.assertEqual(dups[0].parentNamespace(), 'foo')
def bdImportController(self,n): con = self.conList[n] animConName = self.bdGetConName() overrideColor = self.conColors[str(self.inputConSide.currentText())] conSize = self.inputConSize.text() selection = pm.ls(sl = True) selPos = [0,0,0] selRot = [0,0,0] if selection: selPos = selection[0].getTranslation(space='world') selRot = selection[0].getRotation(space='world') if not conSize: conSize=1 if animConName != '': scriptPath = os.path.dirname(__file__) conFile = scriptPath + '/controllers/' + con + '.ma' conTransform = [f for f in pm.importFile(conFile,returnNewNodes=True,namespace='temp') if f.type()=='transform'][0] #conTransform = pm.importFile( conFile,returnNewNodes=True,namespace='temp') sceneNS = pm.namespaceInfo(lon=True,r=True) importNS = [] for ns in sceneNS: if 'temp' in ns: importNS.append(ns) importNS.reverse() for ns in importNS: pm.namespace( rm = ns,mergeNamespaceWithRoot=True) print conTransform conTransform.rename(animConName) conTransformChidlren = conTransform.getChildren(ad=True,type='transform') for child in conTransformChidlren : child.rename(str(self.inputConSide.currentText()) + child.name()) scaleVector = om.MVector(1,1,1) * float(conSize) conTransform.setScale([scaleVector.x,scaleVector.y,scaleVector.z]) pm.makeIdentity(conTransform,apply=True,t=0,r=0,s=1) for shape in conTransform.getChildren(): shape.overrideEnabled.set(1) shape.overrideColor.set(overrideColor) conTransformGrp = pm.group(conTransform,name=conTransform.name() + '_GRP') conTransformGrp.setPivots([0,0,0]) conTransformGrp.setTranslation(selPos,space='world') conTransformGrp.setRotation(selRot,space='world')
def mergeJoints(faceSkinPath): cmds.file(faceSkinPath, i=1, namespace='face') for j in pmc.ls('face:*', type='joint'): try: j.setParent(pmc.ls('Neck_??_Out_Jnt')[-1]) except: j.setParent(pmc.PyNode('Body_Out_Jnt')) pmc.disconnectAttr(j.getParent().s, j.inverseScale) pmc.namespace(removeNamespace='face', mergeNamespaceWithRoot=1)
def DoesBlueprintUserSpecifiedNameExist(_name): pm.namespace(setNamespace = ':') namespaces = pm.namespaceInfo(listOnlyNamespaces = True) names = [] for namespace in namespaces: if namespace.find('__') != -1: names.append(namespace.partition('__')[2]) return _name in names
def addToScene(self): """ Import the camera to the scene :return: """ item = self.getItem() componentPath = item.getPublishPath() pm.namespace(add=':cam') pm.importFile(componentPath, ns='cam') self.wrapData() self.renameToScene()
def removeNamespace(): sceneNS = pm.namespaceInfo(lon=True, r=True) importNS = [] mayaNS = set([u'UI', u'shared']) for ns in sceneNS: if ns not in mayaNS: importNS.append(ns) importNS.reverse() for ns in importNS: pm.namespace(rm=ns, mergeNamespaceWithRoot=True)
def removeNamespace(): sceneNS = pm.namespaceInfo(lon=True,r=True) importNS = [] mayaNS = set([u'UI', u'shared']) for ns in sceneNS: if ns not in mayaNS: importNS.append(ns) importNS.reverse() for ns in importNS: pm.namespace( rm = ns,mergeNamespaceWithRoot=True)
def _swapNamespace(self, *args): sel=pm.ls(sl=True) for arg in sel: i=0 namespaces=arg.split(':') for namespace in namespaces: if not namespace==namespaces[-1]: print namespace pm.namespace(mv=(namespace, ':'), force=True) pm.namespace(rm=namespace) arg.rename(namespaces[0])
def FindInstalledCharacters(): pm.namespace(setNamespace = ":") namespaces = pm.namespaceInfo(listOnlyNamespaces = True) characterNamespaces = [] for n in namespaces: if n.find("Character__") == 0: characterNamespaces.append(n) return characterNamespaces
def lock(self, *args): result = pm.confirmDialog( messageAlign='center', title='Lock Blueprints', message= 'Locking will convert modules to joints. This action can not bet undone. \n Modification to blueprint system can not be done after this.', button=['Accept', 'Cancel'], defaultButton='Accept', cancelButton='Cancel') if result != 'Accept': return moduleInfo = [] #store (module, userSpecifiedName) pairs #find all modules in scene and store them in moduleInfo list [moduleName, userSpecifiedName] pm.namespace(setNamespace=":") namespace = pm.namespaceInfo(listOnlyNamespaces=True) moduleNameInfo = utils.findAllModuleNames("/Modules/Blueprint") validModules = moduleNameInfo[0] validModuleNames = moduleNameInfo[1] for n in namespace: splitString = n.partition("__") if splitString[1] != "": module = splitString[0] userSpecifiedName = splitString[2] if module in validModuleNames: index = validModuleNames.index(module) moduleInfo.append([validModules[index], userSpecifiedName]) if len(moduleInfo) == 0: pm.confirmDialog(messageAlign='center', title='Lock Blueprints', message='No Blueprint Modules in scene', button=['Accept'], defaultButton='Accept') return print moduleInfo moduleInstances = [] #lock phase 1 - gather tranform/rotation info of joints for module in moduleInfo: mod = __import__('Blueprint.' + module[0], {}, {}, [module[0]]) reload(mod) moduleClass = getattr(mod, mod.CLASS_NAME) moduleInst = moduleClass(userSpecifiedName=module[1]) moduleInfo = moduleInst.lock_phase1() moduleInstances.append((moduleInst, moduleInfo)) print moduleInfo #lock phase 2 for module in moduleInstances: module[0].lock_phase2(module[1])
def delete_empty_namespaces(): ''' Remove all empty namespaces from bottom up to remove children namespaces first ''' namespace_list = [] for ns in pm.listNamespaces( recursive =True, internal =False): namespace_list.append(ns) # Reverse Iterate through the contents of the list to remove the deepest layers first for ns in reversed(namespace_list): if not pm.namespaceInfo(ns, ls=True): pm.namespace(removeNamespace = ns, mergeNamespaceWithRoot = True)
def FindInstalledBlueprintInstances(_characterNamespace): pm.namespace(setNamespace = _characterNamespace) moduleInstances = pm.namespaceInfo(listOnlyNamespaces = True) returnModuleInstances = [] for module in moduleInstances: returnModuleInstances.append(StripLeadingNamespace(module)[1]) pm.namespace(setNamespace = ":") return returnModuleInstances
def noNameSpaces(): pm.namespace(set=':') nameSpacesInScene = pm.namespaceInfo(listOnlyNamespaces=True, recurse=True, absoluteName=True) nameSpacesInScene.remove(':UI') nameSpacesInScene.remove(':shared') if nameSpacesInScene: return True return False
def add_nodes_to_namespace(namespace, nodes): """ Put target nodes under a namespace. If the namespace is not found then it will created @param namespace: The target namespace @param nodes: List of target PyNodes """ # Check if the namespace exists if not pm.namespace(exists=namespace): pm.namespace(add=namespace) # Put items under namespace for item in nodes: item.rename("%s:%s" % (namespace, item.nodeName()))
def delete_empty_namespaces(): """checks and deletes empty namespaces """ # only allow namespaces with DAG objects in it and no child namespaces empty_namespaces = [ ns for ns in pm.listNamespaces(recursive=True) if len(pm.ls(ns.listNodes(), dag=True, mat=True)) == 0 and len(ns.listNamespaces()) == 0 ] # remove all empty for ns in empty_namespaces: pm.namespace(rm=ns, mnr=1)
def delete_module(self, node): """deletes Module """ node = pm.PyNode(node) if node.hasAttr("MetaNode"): module_container = utils.getModuleMetaInfo(node, "ModuleContainer") else: return pm.lockNode(module_container, lock = False) module_namespace = utils.getModuleMetaInfo(node, "Namespace") pm.delete(module_container) pm.namespace(setNamespace = ":") pm.namespace(removeNamespace = module_namespace)
def IsModuleInstalled(self, _moduleName): pm.namespace(setNamespace = self.currentBlueprintModule) installedModules = pm.namespaceInfo(listOnlyNamespaces = True) pm.namespace(setNamespace = ":") if installedModules != None: for module in installedModules: installedModuleNameWithoutSuffix = utils.StripAllNamespaces(module)[1] installedModuleName = installedModuleNameWithoutSuffix.rpartition("_")[0] if installedModuleName == _moduleName: return True return False
def removeNamespaces(): """ Strips and removes all possible namespaces from scene. """ core_ns = sets.Set( ['UI', 'shared'] ) pm.namespace( set=':' ) root_ns = sets.Set( pm.namespaceInfo( lon=1 ) ) ns_list = list( root_ns.difference( core_ns ) ) print '// Clearning Namespaces:' count = _iter_namespace( ns_list ) print '//', count, 'namespaces removed.'
def __checkMatrixConstrain__(setNameSpace=True): # check the version of maya # if the version of maya is 2013 the decomposeMatrix does no longer exist if pmc.versions.current() < 201300: # check if the plug in decompose matrix is load pmc.loadPlugin('decomposeMatrix', quiet=True) else: # check if the plug in decompose matrix is load pmc.loadPlugin('matrixNodes', quiet=True) # choose the right namespace if setNameSpace: pmc.namespace(set=':')
def moduleNamespace(module_name): """ Checks to see if module namespace exists. If it does add a number to the end """ pm.namespace(setNamespace = ":") all_names = pm.namespaceInfo(listOnlyNamespaces = True) module_name = module_name # check to see if module namespace is in all namespaces if module_name in all_names: module_basename, module_number = stripTrailingNumber(module_name) highest_number = findHighestTrailingNumber(module_name, all_names) module_name = module_basename + str(highest_number) return module_name
def Import(): loadAlembic() directory = pm.workspace.path fileFilter = "Alembic Files (*.abc)" files = pm.fileDialog2(fileFilter=fileFilter, dialogStyle=1, fileMode=4, dir=directory) if files: for f in files: filename = os.path.splitext(os.path.basename(f))[0] groupname = filename + '_grp' newNodes = cmds.file(f, reference=True, namespace=filename, groupReference=True, groupName=groupname, returnNewNodes=True) refNode = pm.FileReference(f).refNode print refNode assets = set() new_namespace = 'assets' for node in newNodes: node = pm.PyNode(node) if node.hasAttr('assetid'): assetid = node.assetid.get() asset_name = assetid.split('/')[0] assets.add(asset_name) if len(assets) == 1: asset = list(assets)[0] i = 1 while pm.namespace(ex='{}_{}'.format(asset, (str(i).zfill(2)))): i+=1 new_namespace = '{}_{}'.format(asset, (str(i).zfill(2))) new_group = new_namespace + '_grp' ns = filename.replace('.', '_') pm.namespace(ren=(ns, new_namespace)) pm.rename(groupname, new_group) refNode.unlock() pm.rename(refNode, new_namespace + 'RN') refNode.lock() for node in newNodes: if node == '|NewReference': pm.rename('%s:grp' % filename)
def importFiles(self, i=-1): """Proceed the importation""" # check if user choose a group if self._grp: if pmc.objExists(self._grp.name()): hasGrp = True else: hasGrp = False # set namespace if need currentNamespace = pmc.namespaceInfo(currentNamespace=True) if self._nameSpace: pmc.namespace(set=self._nameSpace) # import each file if i>-1: fil = [self._files[i]] else: fil = self._files for f in fil: objs = pmc.importFile(f, groupReference=hasGrp, returnNewNodes=True) if objs: if self.verbose: print '\tINFO: Import file %s Done' % f else: if self.verbose: print '\tERROR: Could not import file %s' % f continue if not self._grp: continue # parenting for child in objs[0].getChildren(): child.setParent(self._grp) # delete main group pmc.delete(objs[0]) # reset to previous namespace pmc.namespace(set=currentNamespace)
def getNextAvailableNamespace(namespaceBase): """@brief Return the next available name space. @param namespaceBase Base of the namespace. (string) ex:NEMO01 """ for i in xrange(1, 1000) : newNamespace = "%s_%03d" % (namespaceBase, i) if not pm.namespace(exists=newNamespace) : return newNamespace
def InitializeBlueprintModuleList(self): pm.namespace(setNamespace = self.selectedCharacter) blueprintNamespaces = pm.namespaceInfo(listOnlyNamespaces = True) pm.namespace(setNamespace = ":") self.blueprintModules = {} if len(blueprintNamespaces) > 0: for namespace in blueprintNamespaces: blueprintModule = utils.StripLeadingNamespace(namespace)[1] userSpecifiedName = blueprintModule.partition("__")[2] pm.textScrollList(self.UIElements["blueprintModule_textScroll"], edit = True, append = userSpecifiedName) self.blueprintModules[userSpecifiedName] = namespace pm.textScrollList(self.UIElements["blueprintModule_textScroll"], edit = True, selectIndexedItem = 1) selectedBlueprintModule = pm.textScrollList(self.UIElements["blueprintModule_textScroll"], query = True, selectItem = True) self.selectedBlueprintModule = self.blueprintModules[selectedBlueprintModule[0]]
def alphaCmd(*arg): select_mesh=pm.selected() print pm.objExists('aiMatteSet:Matte' ) if pm.objExists('aiMatteSet:Matte' )==False: #pm.namespace(rm='aiMatteSet',deleteNamespaceContent =True) print "improt file" pm.importFile( "//ALFREDSTORAGE/Alfred_asset/Maya_Shared_Environment/scripts_Python_old/aiMatte.ma", type = "mayaAscii",namespace="aiMatteSet") else: pass nodes=pm.select(select_mesh) for node in select_mesh: shape = node.getShape() cmds.sets(addElement=shape,add='aiMatteSet:Matte') for i in range(0,100): if pm.namespace(exists='aiMatteSet'+str(i)): pm.namespace(rm='aiMatteSet'+str(i),deleteNamespaceContent =True) else: pass
def removeAdvancedShaders(): ''' ''' # remove layer try: layer = pm.nt.RenderLayer('advanced_shading') pm.editRenderLayerGlobals(crl='defaultRenderLayer') pm.delete(layer) except pm.MayaObjectError: pass # remove imported namespace try: pm.namespace(dnc=True, rm='SHADERS') except RuntimeError: pass # remove approxNode try: approxNode = pm.PyNode('mathildaSubdivApprox') pm.delete(approxNode) except pm.MayaObjectError: pass
def removeNamespace(self, namespace, force=False): ''' Removes namespace with all its content. ''' if namespace in self.listAllNamespaces(): pc.namespace(set=':'+namespace) pc.delete(pc.namespaceInfo(listNamespace=True)) pc.namespace(removeNamespace=':'+namespace, force=force) pc.namespace(set=":") else: print('Warning namespace %s could not be found.'%namespace)
def testSetNamespace(self): self.assertRaises(ValueError, set_namespace_active, '') pmc.namespace(add='before') pmc.namespace(add='after') pmc.namespace(set='before') self.assertEqual('before', pmc.namespaceInfo(cur=True)) with set_namespace_active(':after'): self.assertEqual('after', pmc.namespaceInfo(cur=True)) self.assertEqual('before', pmc.namespaceInfo(cur=True)) with set_namespace_active(':'): self.assertEqual(':', pmc.namespaceInfo(cur=True)) self.assertEqual('before', pmc.namespaceInfo(cur=True))
def superRename( object, newName, force=False ): print 'object:', object result = pm.rename( object, newName ) result = str( result ) if result == newName: print '// Result:', result else: nsList = pm.namespaceInfo( listOnlyNamespaces=True ) nodeList = pm.ls( '*' + newName ) if force: if newName in nsList: nsName = newName + 'NS' try: pm.namespace( add=nsName ) except RuntimeError: pass pm.namespace( force=True, moveNamespace=( newName, nsName ) ) pm.namespace( removeNamespace=newName ) mel.warning( 'Renamed namespace "%s" to "%s".' % ( newName, nsName ) ) if newName in nodeList: for n in nodeList: if n.type() == 'displayLayer': pm.rename( n, n + 'L' ) mel.warning( 'SuperRename: Forced DisplayLayer "%s" to "%s".' % ( newName, n + 'L' ) ) else: try: print n.nextName().split( '|' )[-1] r = pm.rename( n, n.nextName().split( '|' )[-1] ) except RuntimeError: # pass r = pm.rename( n, n + '100' ) except: pass mel.warning( 'SuperRename: Forced renamed "%s" to "%s".' % ( newName, r ) ) # renamed conflicting nodes, try again superRename( result, newName, force=False ) else: print '// Conflicts:' if newName in nsList: print '// (namespace)'.ljust( 10 ), newName if nodeList: for n in nodeList: print '// (%s)'.ljust( 10 ) % n.type(), n
def _iter_namespace( ns_list, level=0 ): count = 0 for ns in ns_list: count += 1 pm.namespace( set=':' ) pm.namespace( set=ns ) print '// ' + ' ' * level + '- ' + ns if pm.namespaceInfo( lon=1 ): count += _iter_namespace( pm.namespaceInfo( lon=1 ), ( level + 1 ) ) pm.namespace( set=':' ) for obj in pm.ls( ns + ':*' ): obj.rename( obj.replace( ns + ':', '' ) ) pm.namespace( rm=ns ) return count
def __init__(self): character = self.FindSelectedCharacter() if character == None: return niceName = character.partition("__")[2] result = pm.confirmDialog(title = "Delete Character", message = 'Are you sure you want to delete the character "%s"? \nCharacter deletion cannot be undone.' %niceName, button = ["Yes", "Cancel"], defaultButton = "Yes", cancelButton = "Cancel", dismissString = "Cancel") if result == "Cancel": return characterContainer = "%s:character_container" %character # Unlock and delete selected character pm.lockNode(characterContainer, lock = False, lockUnpublished = False) pm.delete(characterContainer) # Collect list of blueprints used by this character pm.namespace(setNamespace = character) blueprintNamespaces = pm.namespaceInfo(listOnlyNamespaces = True) # Loop through blueprint namespaces for blueprintNamespace in blueprintNamespaces: pm.namespace(setNamespace = ":") pm.namespace(setNamespace = blueprintNamespace) # Collect module namespaces within each blueprint moduleNamespaces = pm.namespaceInfo(listOnlyNamespaces = True) pm.namespace(setNamespace = ":") # Remove the module namespaces if moduleNamespaces != None: for moduleNamespace in moduleNamespaces: pm.namespace(removeNamespace = moduleNamespace) # Remove the blueprint namespaces pm.namespace(removeNamespace = blueprintNamespace) # Remove the character namespace pm.namespace(removeNamespace = character)