Example #1
0
    def import_file(self):
        """Import component file"""

        log.info("Importing file: %s" % self.file)

        temp_namespace = "temp"
        cmds.file(self.file, i=True, namespace=temp_namespace)

        # Collect component nodes
        nodes = self._collect_imported_nodes()
        for node in nodes:

            # Check for duplicates
            if node.count("|"):
                e = "Duplicate node detected %s in component %s" % (node, self.__class__.__name__)
                log.error(e)
                raise RuntimeError(e)

            # Rename
            clean_node = ":".join(node.split(":")[1:])
            try:
                cmds.rename(node, clean_node)
                self.nodes.append(clean_node)
            except:
                pass

        cmds.namespace(removeNamespace=temp_namespace, mergeNamespaceWithRoot=True, force=True)
def getCharacterInfo():
    cmds.namespace(set=":")
    namespaces = cmds.namespaceInfo(lon=True)
    characterName = []
    for name in namespaces: 
        """ TODO: """
        """ I need a global check for valid characters in the scene """
        characterContainer = (name + ":character_container")
        setupContainer = name.replace("Character__", "Export__")
        setupContainer = (setupContainer + ":Setup")

        if cmds.objExists (characterContainer):
            fullCharName = name
            tmpCharName = name.split("__")[1]
            tmpCharName = tmpCharName[:tmpCharName.rfind("_")]
            characterName = tmpCharName
            return (characterName, characterContainer, fullCharName, setupContainer)  
                  
        else:
            characterContainer = 'Character__tmp_1:character_container'
            fullCharName = name
            tmpCharName = name.split("__")[1]
            tmpCharName = tmpCharName[:tmpCharName.rfind("_")]
            characterName = tmpCharName

            return (characterName, characterContainer, fullCharName, setupContainer)
            # Warn no character in the scene
            #charConfirm = ("No character exists in this scene")
            #cmds.confirmDialog(messageAlign="center", title="Create Directory", message= charConfirm)
            characterName = 'Character__tmp'
            return characterName
Example #3
0
def process( call, *args):
	# Selection
	intialSelection = cmds.ls(selection=True, flatten=True)
	selections = intialSelection[:]
	# Input Values from UI
	inputName = ['placeholder'] # needs to be a list fed into it to work
	inputName[0] = cmds.textField("inputField", q=True, text = True)
	old = cmds.textField("replaceField", q=True, text = True)
	new = cmds.textField("withField", q=True, text = True)
	# Assign the Rename Class 
	D = Rename(selections, inputName )
	if old: # if there is data in the replaceField txt box, then run the replacement code
		for i in range( len (selections) ):
			findTxt = D.reFunction(D.getAfterNamespace(i), old)
			replacementName = D.getAfterNamespace(i)[ : findTxt [0][0] ] + new + D.getAfterNamespace(i)[ findTxt [0][1] : ]
			cmds.rename(selections[i], D.getNamespace(i) + replacementName)
	else:
		for i in range( len (selections) ):
			X = D.processNamespace(i)
			if X == ':': X = '::' # This prevents the root namespace from getting lost in the cutoff [:-1] use X[:-1] instead of D.processNamespace(i) [:-1]
			if cmds.namespace(exists = X [:-1] ) != True: # creates new namespace if doesn't already exist
				print ' creating new namespace'
				cmds.namespace(addNamespace = X [:-1] ) # create namespace if doesn't already exist
			cmds.rename( D.selection[i] , ':' + D.processNamespace(i) + D.processRename(i) )
			cmds.namespace(set = ':') # set namespace back to root so any new object created is under the root
	if call == 'NA':
		cmds.warning('no exit call, window stays open')
	elif call == 'exit':
		cmds.warning('exit called, closing rename window')
		cmds.evalDeferred('cmds.deleteUI("renameUI")')
		#cmds.deleteUI(window)
Example #4
0
File: am_maya.py Project: pixo/hk
def instanceAsset(namespace=""):
    """Find new namespace"""
    ns = namespace
    name = "%s:root" % ns

    i = 1
    while cmds.objExists(name):
        ns = "%s%d" % (namespace, i)
        name = "%s:root" % ns
        i += 1

    """Make instance"""
    cmds.namespace(add=ns)
    root = cmds.instance("%s:root" % namespace, name=name)[0]

    """Get model_grp path"""
    model_grp = "%s:root|%s:master_trs|%s:shot_trs|%s:aux_trs|%s:model_grp" % (
        ns,
        namespace,
        namespace,
        namespace,
        namespace,
    )

    """Lock attributes"""
    cmds.setAttr("%s.%s" % (root, "asset"), lock=True)
    cmds.setAttr("%s.%s" % (root, "texturever"), lock=True)
    cmds.setAttr("%s.inheritsTransform" % model_grp, 0)
Example #5
0
def searchCharsName():
    """检索当前场景中的所有角色名

    Description:
        根据绑定文件的命名规范与reference原则,从命名空间中就可获得角色名称

    Arguments:
        无

    Returns:
        allCharsNameList:所有角色名列表(无重复)
    """
    cmds.namespace(set = ":")
    allNamespace = cmds.namespaceInfo(listOnlyNamespaces = True)  #拿到所有根目录下的命名空间名称
    allCharsName = []
    
    for eachNamespace in allNamespace:
        #拿到带有_Char_的命名空间名称,从中拿到角色名
        
        if eachNamespace.find("_chr_") < 0:
            print "This Is Not A Char!"            
        else:
            namesapceWithChar = eachNamespace
            charName = namesapceWithChar.split("_")[2]  #charName存放角色名
            allCharsName.append(charName)

    allCharsNameList = cT.delDupFromList(allCharsName)  #调用函数去除list中的重复元素
    
    return allCharsNameList
Example #6
0
def doSwapAsset(arg=None):
    '''
    Button: Swap For Reference. 
    Swaps current selection for referenced asset.
    '''
    currentImageLibrary = getImageLibrary()
    currentAssetLibrary = getAssetLibrary()
    cmds.namespace(setNamespace=":")
    directory = getCategoryFolder()
    if not directory:
        return
    
    directory = directory.replace(currentImageLibrary, currentAssetLibrary)
    selected = cmds.textField("currentAssetTFD", query=True, text=True)
    if not selected:
        sys.stdout.write("Select an asset.\n")
        return
        
    assetDirectory = selected.partition("_")[0]
    filename = os.path.join(directory, assetDirectory, "%s.ma" % selected)
    if currentAssetLibrary == ddConstants.CHAR_ASSETLIBRARY:
        # due to character naming 'CHAR_character',
        #   assetDirectory needs to be more accurate
        char_patt = re.compile("^([A-Z]{3}_[a-zA-Z]+)\w*$")
        if char_patt.match(selected):
            assetDirectory = char_patt.search(selected).groups()[0]
        filename = os.path.join(directory, assetDirectory, "chesspiece", "published", "%s.ma" % selected)
    
    nodes = getSelectionList(topGrps=False)
    if nodes:
        ddSwapForReference.do(nodes=nodes, filename=filename)
	def installModule(self, module, *arg):
		basename = 'instance_'
	
		cmds.namespace(setNamespace=":")
		namespaces = cmds.namespaceInfo(listOnlyNamespaces=True)
		
		for i in range(len(namespaces)):
			if namespaces[i].find('__') != -1:
				namespaces[i] = namespaces[i].partition('__')[2]

		newSuffix = utils.findHighestTrailingNumber(namespaces, basename) + 1
		
		userSpecName = basename + str(newSuffix)
		
		hookObj = self.findHookObjectFromSelection()
	
		mod = __import__('Blueprint.'+ module,{},{},[module])
		reload(mod)
		
		moduleClass = getattr(mod, mod.CLASS_NAME)
		moduleInstance = moduleClass(userSpecName, hookObj)
		moduleInstance.install()
		
		#this is to make sure move tool is selected by default
		moduleTransform = mod.CLASS_NAME + '__' + userSpecName + ':module_transform'
		cmds.select(moduleTransform, replace=True)
		cmds.setToolTo('moveSuperContext')
    def buildScene(self):
        MayaCmds.file(new=True, force=True)

        MayaCmds.namespace(addNamespace='foo')
        MayaCmds.namespace(addNamespace='bar')
        MayaCmds.createNode('transform', name='foo:a')
        MayaCmds.createNode('transform', name='bar:a')
        MayaCmds.createNode('transform', name='a')
        MayaCmds.polyPlane(sx=1, sy=1, w=1, h=1, ch=0, n='foo:b')
        MayaCmds.polyPlane(sx=1, sy=1, w=1, h=1, ch=0, n='bar:b')
        MayaCmds.polyPlane(sx=1, sy=1, w=1, h=1, ch=0, n='b')
        MayaCmds.parent('foo:b', 'foo:a')
        MayaCmds.parent('bar:b', 'bar:a')
        MayaCmds.parent('b', 'a')

        MayaCmds.select('foo:b.vtx[0:8]')
        MayaCmds.setKeyframe(t=[1, 4])
        MayaCmds.scale(0.1, 0.1, 0.1, r=True)
        MayaCmds.setKeyframe(t=2)

        MayaCmds.select('bar:b.vtx[0:8]')
        MayaCmds.setKeyframe(t=[1, 4])
        MayaCmds.scale(2, 2, 2, r=True)
        MayaCmds.setKeyframe(t=2)

        MayaCmds.select('b.vtx[0:8]')
        MayaCmds.setKeyframe(t=[1, 4])
        MayaCmds.scale(5, 5, 5, r=True)
        MayaCmds.setKeyframe(t=2)
    def deleteNsContents(self, nameSpace):
        mc.namespace(set=":")
        mc.namespace(set=":"+nameSpace)
        if self.debug: print"current ns: ", mc.namespaceInfo(currentNamespace=True)
        nsContent = mc.namespaceInfo(ls=True, listOnlyDependencyNodes=True)

        if not nsContent:
            return

        for i in mc.namespaceInfo(ls=True, listOnlyDependencyNodes=True):
            
            delStr = i.split(":")[-1]
            
            try:
                print "deleting:", delStr
                #print mc.nodeType(i)
                mc.delete(i)
                self.count += 1

            except:
                if self.debug:print "can not delete: ", i
                pass

        if self.debug: print "renaming namespace: ", nameSpace
        self.setNsCleaned(nameSpace)
Example #10
0
def fixDoubleNamespaces():
    """Import all elements into existing hierarchy if it already exists. Then delete the namespace and fixReferences()"""
    namespaces = cmds.namespaceInfo(listOnlyNamespaces=True, recurse=True, fullName=True)
    namespacesTofix = list(set([i.split(':')[0] for i in namespaces if ':' in i]))  # Fix double namespaces

    for namespace in namespacesTofix:
        content = cmds.namespaceInfo(namespace, listNamespace=True, dagPath=True)
        tofixList = [i for i in content if cmds.ls(i.replace(namespace + ':', ''))]  # Check if nodes already exists with the same name if we remove the namespace

        tofix = {}
        for i in tofixList:  # Sort the elements by hierarchy level
            lenght = len(i.split('|'))
            try:
                tofix[lenght].append(i)
            except KeyError:
                tofix[lenght] = [i]

        for keys, values in reversed(sorted(tofix.iteritems())):
            for node in values:
                if isGroup(node):
                    childrens = cmds.listRelatives(node, children=True, fullPath=True) or []
                    for u in childrens:
                        upperGrp = node.replace(namespace + ':', '')
                        cmds.parent(u, upperGrp)  # parent each child to the original group
                    cmds.delete(node)  # then delete the empty group

        fixReferences()
        cmds.namespace(removeNamespace=namespace, mergeNamespaceWithRoot=True)
    return namespacesTofix
Example #11
0
def deleteNS():
    sel_namespace = cmds.ls(sl=True)[0]
    NS = sel_namespace.rsplit(':',1)[0]
    if not cmds.namespace(ex=NS):
        raise Exception('Namespace "'+NS+'" does not exist!')
    cmds.namespace(mv=[NS,':'],f=True)
    cmds.namespace(rm=NS)
Example #12
0
 def refreshAnimationModuleList(self, index=1):
     cmds.textScrollList(self.UIElements["animationModule_textScroll"], edit=True, removeAll=True)
     
     cmds.symbolButton(self.UIElements["deleteModuleButton"], edit=True, enable=False)
     cmds.symbolButton(self.UIElements["duplicateModuleButton"], edit=True, enable=False)
     
     selectedBlprnModule = cmds.textScrollList(self.UIElements["blueprintModule_textScroll"], q=True, selectItem=True)
     self.selectedBlueprintModule = self.blueprintModules[selectedBlprnModule[0]]
     
     self.setupActiveModuleControls()
     
     cmds.namespace(setNamespace=self.selectedBlueprintModule)
     controlModuleNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True)
     cmds.namespace(setNamespace=":")
     
     if controlModuleNamespaces != None:
         for module in controlModuleNamespaces:
             moduleName = utils.stripAllNamespaces(module)[1]
             cmds.textScrollList(self.UIElements["animationModule_textScroll"], edit=True, append=moduleName)
             
         cmds.textScrollList(self.UIElements["animationModule_textScroll"], edit=True, selectIndexedItem = index)
         
         cmds.symbolButton(self.UIElements["deleteModuleButton"], edit=True, enable=True)
         cmds.symbolButton(self.UIElements["duplicateModuleButton"], edit=True, enable=True)
         cmds.symbolButton(self.UIElements["zeroModulesButton"], edit=True, enable=True)
      
     self.setupModuleSpecificControls()    
     self.previousBlueprintListEntry = selectedBlprnModule
Example #13
0
 def __init__(self, dpUIinst, langDic, langName, userGuideName, rigType, CLASS_NAME, TITLE, DESCRIPTION, ICON):
     """ Initialize the module class creating a button in createGuidesLayout in order to be used to start the guide module.
     """
     # defining variables:
     self.dpUIinst = dpUIinst
     self.langDic = langDic
     self.langName = langName
     self.guideModuleName = CLASS_NAME
     self.title = TITLE
     self.description = DESCRIPTION
     self.icon = ICON
     self.userGuideName = userGuideName
     self.rigType = rigType
     # defining namespace:
     self.guideNamespace = self.guideModuleName + "__" + self.userGuideName
     # defining guideNamespace:
     cmds.namespace(setNamespace=":")
     self.namespaceExists = cmds.namespace(exists=self.guideNamespace)
     self.guideName = self.guideNamespace + ":Guide"
     self.moduleGrp = self.guideName+"_Base"
     self.radiusCtrl = self.moduleGrp+"_RadiusCtrl"
     self.annotation = self.moduleGrp+"_Ant"
     if not self.namespaceExists:
         cmds.namespace(add=self.guideNamespace)
         # create GUIDE for this module:
         self.createGuide()
     # create the Module layout in the mainUI - modulesLayoutA:        
     self.createModuleLayout()
     # update module instance info:
     self.updateModuleInstanceInfo()
Example #14
0
def importSkinByRef(ref, file, skip=[], **kwargs):
    """Import skin for every dag node in reference."""

    if not os.path.exists(file):
        rigUtils.log('Skin file not found - skipping: %s' % file)
        return

    rigUtils.log('Reading file: %s' % file)

    f = open(file, 'r')
    j = json.loads(f.read())
    f.close()

    cmds.namespace(set=ref)
    dagnodes = cmds.namespaceInfo(lod=True)
    cmds.namespace(set=':')

    skinned = []

    for dagnode in dagnodes:
        if skip:
            if dagnode in skip:
                continue
        if dagnode in j:
            dict = j[dagnode]
            try: skindict = dict['skinCluster']
            except: continue
            importSkin(skindict, dagnode, **kwargs)
            skinned.append(dagnode)

    return skinned
Example #15
0
	def _fixTheFuckingCores(self):
		"""
		This is used to clean sweep the static scenes and remove the duplicate Namespaces and reconnect the bases to the duplicates
		"""

		removedNameSpaces = []
		## Remove duplicate root core namespaces
		getAllNameSpaces = cmds.namespaceInfo(listOnlyNamespaces = True)
		for eachNS in getAllNameSpaces:
			if eachNS.endswith('1'):
				print 'Removing %s' % eachNS
				cmds.namespace(removeNamespace = eachNS, mergeNamespaceWithRoot = True)
				removedNameSpaces.append(eachNS.replace('1', '').replace('_CORE', ''))

		## Remove duplicate base cores
		for each in cmds.ls(type = 'core_archive'):
			if '1'in each:
				print 'Cleaned rootCore %s from scene...' % each
				cmds.delete(each)

		## Now find all geo with the core name in it and proceess it for reconnection
		for eachCore in removedNameSpaces:
			#print eachCore
			## Check child _hrc grps for processing
			getAllGeo = [eachGeo for eachGeo in cmds.ls('*%s*' % eachCore) if cmds.nodeType(eachGeo) == 'transform']
			for eachGeo in getAllGeo:
				self._reconnectDuplicates(eachGeo, '%s_CORE_Geoshader' % eachCore)

		coreLib.cleanupDeadCoreArchives()
Example #16
0
 def deleteModule(self, *args):
     """ Delete the Guide, ModuleLayout and Namespace.
     """
     # delete mirror preview:
     try:
         cmds.delete(self.moduleGrp[:self.moduleGrp.find(":")]+"_MirrorGrp")
     except:
         pass
     # delete the guide module:
     utils.clearNodeGrp(nodeGrpName=self.moduleGrp, attrFind='guideBase', unparent=True)
     # clear default 'dpAR_GuideMirror_Grp':
     utils.clearNodeGrp()
     # remove the namespaces:
     allNamespaceList = cmds.namespaceInfo(listOnlyNamespaces=True)
     if self.guideNamespace in allNamespaceList:
         cmds.namespace(moveNamespace=(self.guideNamespace, ':'), force=True)
         cmds.namespace(removeNamespace=self.guideNamespace, force=True)
     try:
         # delete the moduleFrameLayout from window UI:
         cmds.deleteUI(self.moduleFrameLayout)
         self.clearSelectedModuleLayout()
         # edit the footer A text:
         self.currentText = cmds.text("footerAText", query=True, label=True)
         cmds.text("footerAText", edit=True, label=str(int(self.currentText[:self.currentText.find(" ")]) - 1) +" "+ self.langDic[self.langName]['i005_footerA'])
     except:
         pass
     # clear module from instance list (clean dpUI list):
     delIndex = self.dpUIinst.moduleInstancesList.index(self)
     self.dpUIinst.moduleInstancesList.pop(delIndex)
Example #17
0
def namespaceList(current= None):
	"""
	"""
	if not current:
		cmds.namespace(set = ':')

	return cmds.namespaceInfo(lon= 1, r= 1, an= 1)
Example #18
0
	def _createNativeModel(self, name='Model', nativeObjects=[], referenced=False):
		name = 'Model' if not name else name
		# Create a "model" namespace and add the locator to it
		# TODO: Make this a context
		currentNamespace = cmds.namespaceInfo(currentNamespace=True)
		namespace = cmds.namespace(addNamespace=name)
		cmds.namespace(setNamespace=namespace)
		# Create the transform node then the shape node so the transform is properly named
		parent = cmds.createNode('transform', name='Model')
		#name = cmds.createNode('locator', name='{}Shape'.format(name), parent=parent)
		output = cross3d.SceneWrapper._asMOBject(parent)
		userProps = cross3d.UserProps(output)
		userProps['model'] = True
		if referenced:
			userProps['referenced'] = referenced
			# Create the Active_Resolution enum if it doesn't exist
#			cmds.addAttr(name, longName="Active_Resolution", attributeType="enum", enumName="Offloaded:")
#			userProps['Resolutions'] = OrderedDict(Offloaded='')
		cmds.namespace(setNamespace=currentNamespace)

		# Add each of nativeObjects to the model namespace
		if nativeObjects:
			for nativeObject in nativeObjects:
				nativeObject = cross3d.SceneWrapper._getTransformNode(nativeObject)
				objName = cross3d.SceneWrapper._mObjName(nativeObject)
#				cmds.parent(objName, cross3d.SceneWrapper._mObjName(nativeParent))
				nameInfo = cross3d.SceneWrapper._namespace(nativeObject)
				newName = '{namespace}:{name}'.format(namespace=namespace, name=nameInfo['name'])
				cmds.rename(objName, newName)
		nativeObjects.append(output)
		return output
Example #19
0
	def _removeNativeModels(self, models):
		""" Deletes provided native models.
			:param models: list of native models
			:return: <bool> success
		"""
		ret = True
		for model in models:
			nameInfo = cross3d.SceneWrapper._namespace(model)
			fullName = cross3d.SceneWrapper._mObjName(model)
			if cmds.referenceQuery(fullName, isNodeReferenced=True):
				# The model is referenced and we need to unload it.
				refNode = cmds.referenceQuery(fullName, referenceNode=True)
				filename = cmds.referenceQuery(refNode, filename=True)
				# If all nodes in the namespace are referenced, the namespace will be removed, otherwise
				# the namespace will still exist and contain all of those unreferenced nodes.
				cmds.file(filename, removeReference=True)
				# Remove nodes that were parented to referneced nodes
				leftovers = self.objects(wildcard='{refNode}fosterParent*'.format(refNode=refNode))
				if leftovers:
					self.removeObjects(leftovers)
			# Local node processing: check for unreferenced items in the namespace and remove them.
			namespace = nameInfo['namespace']
			if cmds.namespace(exists=namespace):
				cmds.namespace(removeNamespace=namespace, deleteNamespaceContent=True)
			if cmds.namespace(exists=namespace):
				print 'The namespace {ns} still exists the model {model} was not entirely removed.'.format(namespace, model=fullName)
				ret = False
		return ret
Example #20
0
def do(nodes=None):
    '''Builds the window.
    '''
    doCloseWindow()
    cmds.namespace(setNamespace=":")    

    window = cmds.window("textureManagerWIN", title="Texture Manager", sizeable=True, resizeToFitChildren=True, widthHeight=(800, 450))
    mainFL = cmds.formLayout("textureManagerFL", numberOfDivisions=100)

    displayShaderFL = cmds.formLayout("displayShaderFL", numberOfDivisions=100, parent=mainFL)
    displayShaderSL = cmds.textScrollList("displayShaderSL", allowMultiSelection=True, parent=displayShaderFL, selectCommand=partial(doSelectShaders))
    shadersMenu = cmds.popupMenu('displayShadersMenu', parent=displayShaderSL)

    displayTextureFL = cmds.formLayout("displayTextureFL", numberOfDivisions=100, parent=mainFL)
    displayTextureSL = cmds.textScrollList("displayTextureSL", allowMultiSelection=True, parent=displayTextureFL)

    showShadersForSelectionBTN = cmds.button("showShadersForSelectionBTN", label="Show Shaders For Selection", height=30, annotation="Show shaders for selected GEO or GRP", parent=mainFL, backgroundColor=[0.28, 0.337, 0.375], c=partial(doShowShadersForSelection))
    openShaderLibraryBTN = cmds.button("openShaderLibraryBTN", label="Open Shader Library", height=30, annotation="Open Shader Library", parent=mainFL, backgroundColor=[0.28, 0.337, 0.375], c=partial(doOpenShaderLibrary))
    refreshTexturesBTN = cmds.button("refreshTexturesBTN", label="Refresh", height=30, annotation="Refresh display", parent=mainFL, backgroundColor=[0.28, 0.337, 0.375], c=partial(doRefreshShadersDisplay))
    textureManagerHelpBTN = cmds.button("textureManagerHelpBTN", label="Help", height=30, annotation="Show instructions and other information.", parent=mainFL, backgroundColor=[0.28, 0.337, 0.375], c=partial(showTextureManagerHelp))
    currentNodesTFD = cmds.textField("currentNodesTFD", text="", visible=False, parent=mainFL)
    
    c1 = 25
    c2 = 50
    c3 = 75
    r1 = 50
    r2 = 89
    
    cmds.formLayout(mainFL, edit=True, 
        attachPosition=[ (displayShaderFL, "top", 15, 0), (displayShaderFL, "bottom", 4, r1), 
                         (displayTextureFL, "top", 4, r1), (displayTextureFL, "bottom", 6, r2),
                         (showShadersForSelectionBTN, "top", 6, r2), (showShadersForSelectionBTN, "bottom", 15, 100),
                         (openShaderLibraryBTN, "top", 6, r2), (openShaderLibraryBTN, "bottom", 15, 100),
                         (refreshTexturesBTN, "top", 6, r2), (refreshTexturesBTN, "bottom", 15, 100),
                         (textureManagerHelpBTN, "top", 6, r2), (textureManagerHelpBTN, "bottom", 15, 100),
                         
                         (displayShaderFL, "left", 12, 0), (displayShaderFL, "right", 12, 100),
                         (displayTextureFL, "left", 12, 0), (displayTextureFL, "right", 12, 100),
                         (showShadersForSelectionBTN, "left", 12, 0), (showShadersForSelectionBTN, "right", 3, c1),
                         (openShaderLibraryBTN, "left", 3, c1), (openShaderLibraryBTN, "right", 3, c2), 
                         (refreshTexturesBTN, "left", 3, c2), (refreshTexturesBTN, "right", 3, c3), 
                         (textureManagerHelpBTN, "left", 3, c3), (textureManagerHelpBTN, "right", 12, 100) ])
                        
    cmds.formLayout(displayShaderFL, edit=True,
        attachForm = [ (displayShaderSL, "top", 0), (displayShaderSL, "left", 0), 
                       (displayShaderSL, "right", 0), (displayShaderSL, "bottom", 0) ])

    cmds.formLayout(displayTextureFL, edit=True,
        attachForm = [ (displayTextureSL, "top", 0), (displayTextureSL, "left", 0), 
                       (displayTextureSL, "right", 0), (displayTextureSL, "bottom", 0) ])
                       
    window = cmds.window("textureManagerWIN", edit=True, widthHeight=(800, 464))
    
    # Initialize current node list
    doShowShadersForSelection()

    # Initialize shading engines list
    doBuildShadingEnginesList()
    
    cmds.showWindow(window)
Example #21
0
def iterNamespaces( namespace=':' ):
	'''
	iterates over all namespaces under and including the one given...  holy sH1t namespaces suck
	b4lls in maya
	'''
	if namespace.endswith( ':' ):
		namespace = namespace[ :-1 ]

	namespaces = [ namespace ]
	idx = 0

	while True:
		try:
			curNS = namespaces[ idx ]
		except IndexError: break

		idx += 1

		try:
			cmd.namespace( set=curNS )
		except RuntimeError: continue

		subs = cmd.namespaceInfo( listOnlyNamespaces=True )
		if subs is None:
			continue

		namespaces += subs

	return iter( namespaces )
Example #22
0
def doReferenceAsset(arg=None):
    '''
    Button: Reference Asset. 
    References the assets using namespaces.
    '''
    currentImageLibrary = getImageLibrary()
    currentAssetLibrary = getAssetLibrary()
    cmds.namespace(setNamespace=":")
    directory = getCategoryFolder()
    if not directory:
        return
    
    directory = directory.replace(currentImageLibrary, currentAssetLibrary)
    selected = cmds.textField("currentAssetTFD", query=True, text=True)
    if not selected:
        sys.stdout.write("Select an asset.\n")
        return
    
    assetDirectory = selected.partition("_")[0]
    filename = os.path.join(directory, assetDirectory, "%s.ma" % selected)
    if currentAssetLibrary == ddConstants.CHAR_ASSETLIBRARY:
        # due to character naming 'CHAR_character',
        #   assetDirectory needs to be more accurate
        char_patt = re.compile("^([A-Z]{3}_[a-zA-Z]+)\w*$")
        if char_patt.match(selected):
            assetDirectory = char_patt.search(selected).groups()[0]
        filename = os.path.join(directory, assetDirectory, "chesspiece", "published", "%s.ma" % selected)

    if os.path.isfile(filename):
        cmds.file(filename, reference=True, namespace=selected)
    else:
        sys.stdout.write("File not found: %s.\n" % filename)
        return

    deselectAllAssets()
    def testExportWithStripAndMerge(self):
        mayaFilePath = os.path.abspath('UsdExportStripNamespaces.ma')
        cmds.file(mayaFilePath, new=True, force=True)

        cmds.namespace(add=":foo")
        cmds.namespace(add=":bar")

        node1 = cmds.polyCube( sx=5, sy=5, sz=5, name="cube1" )
        cmds.namespace(set=":foo");
        node2 = cmds.polyCube( sx=5, sy=5, sz=5, name="cube2" )
        cmds.namespace(set=":bar");
        node3 = cmds.polyCube( sx=5, sy=5, sz=5, name="cube3" )
        cmds.namespace(set=":");

        usdFilePath = os.path.abspath('UsdExportStripNamespaces_EXPORTED.usda')

        cmds.usdExport(mergeTransformAndShape=True,
                       selection=False,
                       stripNamespaces=True,
                       file=usdFilePath,
                       shadingMode='none')

        stage = Usd.Stage.Open(usdFilePath)
        self.assertTrue(stage)

        expectedPrims = ("/cube1", "/cube2", "/cube3")

        for primPath in expectedPrims:
            prim = stage.GetPrimAtPath(primPath)
            self.assertTrue(prim.IsValid(), "Expect " + primPath)
Example #24
0
def renameAllNodeInNamespace( ns='' ) :

	# Remove every nodes that belong to the given namespace.
	# Input		: Namespace
	# Output	: Empty namespace
	
	nodes = mc.ls( '%s:*' % ns , l=True )
	mc.namespace( set=':' )

	if nodes :
		# If current namespace contains nodes,
		# delete them.
		for node in nodes :

			if mc.objExists( node ) :

				lockState = mc.lockNode( node , q=True )[0]

				if lockState :
					mc.lockNode( node , l=False )
				newName = addElementToName( node.split( ':' )[-1] , ns )
				print newName
				try :
					mc.rename( node , newName )
				except :
					pass
Example #25
0
	def rename_module_instance(self, new_name):

		if new_name == self.user_specified_name:
			return True

		if utils.does_blueprint_user_specified_name_exist(new_name):
			cmds.confirmDialog(
									title="Name Confilct",
									message="Name \""+new_name+"\" already exists, aborting rename",
									button=["Accept"],
									defaultButton="Accept"
								)
			return False

		else:

			new_namespace = self.module_name+"__"+new_name

			cmds.lockNode(self.container_name, lock=False, lockUnpublished=False)

			cmds.namespace(setNamespace=":")
			cmds.namespace(add=new_namespace)
			cmds.namespace(setNamespace=":")

			cmds.namespace(moveNamespace=[self.module_namespace, new_namespace])

			cmds.namespace(removeNamespace=self.module_namespace)

			self.module_namespace = new_namespace
			self.container_name = self.module_namespace+"::module_container"

			cmds.lockNode(self.container_name, lock=True, lockUnpublished=True)

			return True
Example #26
0
	def install_module(self,module,*args):
		
		basename = "instance_"
		
		cmds.namespace(setNamespace =":")
		namespaces = cmds.namespaceInfo(listOnlyNamespaces=True)

		for i in range(len(namespaces)):
			if namespaces[i].find("__") != -1:
				namespaces[i] = namespaces[i].partition("__")[2]

		new_suffix = utils.find_highest_trailing_number(namespaces, basename)+1

		user_specified_name = basename+str(new_suffix)

		hook_obj = self.find_hook_obj_from_selection()

		mod = __import__("blueprint."+module, {}, {}, [module])
		reload(mod)

		module_class = getattr(mod, mod.CLASS_NAME)
		module_instance = module_class(user_specified_name, hook_obj)
		module_instance.install()

		module_trans = mod.CLASS_NAME+"__"+user_specified_name+":module_transform"

		cmds.select(module_trans,replace=True)

		cmds.setToolTo("moveSuperContext")
Example #27
0
def removeAllNodeInNamespace( ns='' ) :

	# Remove every nodes that belong to the given namespace.
	# Input : namespace
	# Output : Nonde
	
	nodes = mc.ls( '%s:*' % ns )
	mc.namespace( set=':' )

	if nodes :
		# If current namespace contains nodes,
		# delete them.
		for node in nodes :

			if mc.objExists( node ) :

				lockState = mc.lockNode( node , q=True )[0]

				if lockState :
					mc.lockNode( node , l=False )
				
				try :
					newName = mc.rename( node , node.split( ':' )[-1] )
					print '%s has been renamed to %s' % ( node , newName )
				except :
					pass
					
				mc.lockNode( newName , l=lockState )
	def resolveNamespaceClashes(self, tempNamespace):
		returnNames = []
		
		cmds.namespace(setNamespace=tempNamespace)
		namespaces = cmds.namespaceInfo(listOnlyNamespaces=True)
		cmds.namespace(setNamespace=':')
		existingNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True)
		
		for i in range(len(namespaces)):
			namespaces[i] = namespaces[i].partition(tempNamespace+ ':')[2]
			
		for name in namespaces:
			newName = str(name)
			oldName = tempNamespace + ':' + name
			
			if name in existingNamespaces:
				highestSuffix = utils.findHighestTrailingNumber(existingNamespaces, name+'_')
				highestSuffix += 1
			
				newName = str(name) + '_' + str(highestSuffix)
			
			returnNames.append([oldName,newName])
			
		self.resolveNameChangeMirrorLinks(returnNames,tempNamespace)
		
		self.renameNamespaces(returnNames)
		
		return returnNames
def remove(namespaces = 'all'):
	if namespaces == 'all':
		namespaces = cmds.namespaceInfo(lon = 1)
		
	for namespace in namespaces:
		cmds.namespace(f=1,mv=(namespace,":"))
		if namespace.count("UI") <1 and namespace.count("uv") <1 and namespace.count("shared") <1:
			cmds.namespace(f=1,rm=str(namespace))
Example #30
0
 def removeNamespaces(self, *args):
     cmds.namespace(set=':')
     """ Move objects out of the character namespace """
     cmds.namespace(mv=(self.characterPrefix, ':'), f=True)
     cmds.namespace(rm=self.characterPrefix)
     
     cmds.namespace(mv=(self.exportPrefix, ':'), f=True)
     cmds.namespace(rm=self.exportPrefix)
Example #31
0
    def testExportWithClashStripping(self):
        mayaFilePath = os.path.abspath('UsdExportStripNamespaces.ma')
        cmds.file(mayaFilePath, new=True, force=True)

        node1 = cmds.polyCube(sx=5, sy=5, sz=5, name="cube1")
        cmds.namespace(add="foo")
        cmds.namespace(set="foo")
        node2 = cmds.polyCube(sx=5, sy=5, sz=5, name="cube1")
        cmds.namespace(set=":")

        usdFilePath = os.path.abspath('UsdExportStripNamespaces_EXPORTED.usda')

        errorRegexp = "Multiple dag nodes map to the same prim path" \
            ".+|cube1 - |foo:cube1.*"
        with self.assertRaisesRegexp(RuntimeError, errorRegexp) as cm:
            cmds.usdExport(mergeTransformAndShape=True,
                           selection=False,
                           stripNamespaces=True,
                           file=usdFilePath,
                           shadingMode='none')

        with self.assertRaisesRegexp(RuntimeError, errorRegexp) as cm:
            cmds.usdExport(mergeTransformAndShape=False,
                           selection=False,
                           stripNamespaces=True,
                           file=usdFilePath,
                           shadingMode='none')
Example #32
0
    def remove(self, container):
        """Remove an existing `container` from Maya scene

        Deprecated; this functionality is replaced by `api.remove()`

        Arguments:
            container (avalon-core:container-1.0): Which container
                to remove from scene.

        """

        from maya import cmds

        node = container["objectName"]

        # Assume asset has been referenced
        members = cmds.sets(node, query=True)
        reference_node = self._get_reference_node(members)

        assert reference_node, ("Imported container not supported; "
                                "container must be referenced.")

        self.log.info("Removing '%s' from Maya.." % container["name"])

        namespace = cmds.referenceQuery(reference_node, namespace=True)
        fname = cmds.referenceQuery(reference_node, filename=True)
        cmds.file(fname, removeReference=True)

        try:
            cmds.delete(node)
        except ValueError:
            # Already implicitly deleted by Maya upon removing reference
            pass

        try:
            # If container is not automatically cleaned up by May (issue #118)
            cmds.namespace(removeNamespace=namespace,
                           deleteNamespaceContent=True)
        except RuntimeError:
            pass
Example #33
0
def getAllNS():

    #set the current naemspace to world
    curNS = mc.namespaceInfo(cur=True)
    mc.namespace(set=":")

    #because maya can only list the child namespaces of the current set namespace, we have to recursively go through setting
    #and checking child namespaces

    #start by getting the worlds children
    namespaces = []
    childspaces = mc.namespaceInfo(lon=True)

    while childspaces:
        #move the current add spaces into the namespaces list (what we will return)
        namespaces.extend(childspaces)
        #create a list from the childspaces so that we can check for their children
        checkspaces = childspaces
        #empty the childspaces so all new children can be added to it for the next round
        childspaces = []
        #cycle through the current checkspaces and get their child namespaces
        for check in checkspaces:
            mc.namespace(set=(":" + check))
            grandchildspaces = mc.namespaceInfo(lon=True)
            if grandchildspaces:
                childspaces.extend(grandchildspaces)
                
    #remove default namespaces
    if namespaces.count('UI'): namespaces.remove('UI')
    if namespaces.count('shared'): namespaces.remove('shared')
      
    mc.namespace(set=(":" + curNS))
    namespaces.sort()
    return namespaces
Example #34
0
 def jobPinGuide(self, ctrlName, *args):
     """ Pin temporally the guide by scriptJob.
     """
     transformAttrList = ["tx", "ty", "tz", "rx", "ry", "rz", "sx", "sy", "sz", "v"]
     if cmds.objExists(ctrlName+".pinGuide"):
         # extracting namespace... need to find an ellegant way using message or stored attribute instead:
         nameSpaceName = None
         cmds.namespace(set=":")
         if ":" in ctrlName:
             if "|" in ctrlName:
                 nameSpaceName = ctrlName[ctrlName.rfind("|")+1:ctrlName.rfind(":")]
             else:
                 nameSpaceName = ctrlName[:ctrlName.rfind(":")]
         pcName = ctrlName+"_PinGuide_PaC"
         pinValue = cmds.getAttr(ctrlName+".pinGuide")
         if pinValue:
             if not cmds.objExists(pcName):
                 if cmds.objExists(self.dpUIinst.tempGrp):
                     if nameSpaceName:
                         cmds.namespace(set=nameSpaceName)
                     cmds.parentConstraint(self.dpUIinst.tempGrp, ctrlName, maintainOffset=True, name=pcName)
                     self.setPinnedGuideColor(ctrlName, True, "red")
         else:
             pConstList = cmds.listRelatives(ctrlName, children=True, type="parentConstraint")
             if pConstList:
                 for pConst in pConstList:
                     if "PinGuide" in pConst:
                         cmds.delete(pConst)
             self.setPinnedGuideColor(ctrlName, False, "red")
         
         for attr in transformAttrList:
             cmds.setAttr(ctrlName+"."+attr, lock=pinValue)
         cmds.namespace(set=":")
Example #35
0
	def installTemplate(self, templateAndPath, *args):
		cmds.file(templateAndPath, i=True, namespace="TEMPLATE_1")
		
		self.resolveNamespaceClashes("TEMPLATE_1")
		
		groupContainer = "TEMPLATE_1:Group_container"
		if cmds.objExists(groupContainer):
			self.resolveGroupNameClashes("TEMPLATE_1")
			
			
			cmds.lockNode(groupContainer, lock=False, lockUnpublished=False)
			
			oldGroupContainer = "Group_container"
			if cmds.objExists(oldGroupContainer):
				cmds.lockNode(oldGroupContainer, lock=False, lockUnpublished=False)
				
				nodeList = cmds.container(groupContainer, q=True, nodeList=True)
				utils.addNodeToContainer(oldGroupContainer, nodeList, force=True)
				
				
				cmds.delete(groupContainer)
			else:
				cmds.rename(groupContainer, oldGroupContainer)
				
			cmds.lockNode("Group_container", lock=True, lockUnpublished=True)
			
		cmds.namespace(setNamespace=":")
		cmds.namespace(moveNamespace=("TEMPLATE_1",":"), force=True)
		
		cmds.namespace(removeNamespace="TEMPLATE_1")
Example #36
0
def fixDoubleNamespaces():
    """Import all elements into existing hierarchy if it already exists. Then delete the namespace and fixReferences()"""
    namespaces = cmds.namespaceInfo(listOnlyNamespaces=True,
                                    recurse=True,
                                    fullName=True)
    namespacesTofix = list(
        set([i.split(':')[0] for i in namespaces
             if ':' in i]))  # Fix double namespaces

    for namespace in namespacesTofix:
        content = cmds.namespaceInfo(namespace,
                                     listNamespace=True,
                                     dagPath=True)
        tofixList = [
            i for i in content if cmds.ls(i.replace(namespace + ':', ''))
        ]  # Check if nodes already exists with the same name if we remove the namespace

        tofix = {}
        for i in tofixList:  # Sort the elements by hierarchy level
            lenght = len(i.split('|'))
            try:
                tofix[lenght].append(i)
            except KeyError:
                tofix[lenght] = [i]

        for keys, values in reversed(sorted(tofix.iteritems())):
            for node in values:
                if isGroup(node):
                    childrens = cmds.listRelatives(
                        node, children=True, fullPath=True) or []
                    for u in childrens:
                        upperGrp = node.replace(namespace + ':', '')
                        cmds.parent(
                            u, upperGrp
                        )  # parent each child to the original group
                    cmds.delete(node)  # then delete the empty group

        fixReferences()
        cmds.namespace(removeNamespace=namespace, mergeNamespaceWithRoot=True)
    return namespacesTofix
Example #37
0
    def refreshData(self, *_):
        self.__select = []
        cmds.namespace(set=":")
        self.shelf.cleanUp()
        self.motionLibBtnImport.setEnabled(False)
        self.motionLibCBProject.setCurrentText(config.getProject())
        if not self.motionLibCBCharactor.count(): return
        self.namespace = self.motionLibCBCharactor.currentText().split(
            "<")[-1].split(">")[0]
        self.path = config.getConfig('animLibPath') + self.getOrigChar(
            self.namespace.split(":")[-1])

        fileList = self.getFileList(self.path)
        exp = codecs.decode(self.motionLibLEFilter.text(), 'utf-8')
        itemList = []
        for f in fileList:
            if self.__match__(f, exp):
                found = False
                for ext in ['gif', 'png', 'jpg']:
                    iconPath = self.path + f + ext
                    if os.path.isfile(iconPath):
                        found = True
                        break
                if not found:
                    iconPath = config.getPath(config.kIcon, "motion.gif")
                itemList.append({
                    ui.QShelfView.kName: f,
                    ui.QShelfView.kData: f,
                    ui.QShelfView.kIcon: iconPath,
                    ui.QShelfView.kType: f
                })
        self.shelf.setup(*itemList)

        sels = os.popen("type \"%s\"\\__config__" % self.path).read()
        for sel in sels.split('&'):
            if not sel: continue
            self.__select.append("%s:%s" % (self.namespace, sel))
        if not self.__select: self.__select.append("%s:Main" % self.namespace)
        cmds.select(self.__select, r=True)
        self.__config = None
Example #38
0
 def remove_namespace(self, removeNS):
     # removeNS = "rp_1"
     mc.namespace(set=removeNS)
     objsInNs = mc.namespaceInfo(listNamespace=True)
     mc.delete(objsInNs)
     mc.namespace(set=":")
     mc.namespace(removeNamespace=removeNS)
Example #39
0
def test_reference_without_dag(taskfile_without_dagnodes, djprj, assettypinter,
                               mrefobjinter):
    cmds.file(new=True, force=True)
    cmds.namespace(add="foo")
    cmds.namespace(set="foo")
    assert cmds.namespaceInfo(absoluteName=True) == ":foo"

    tf = djprj.assettaskfiles[0]
    tfi = TaskFileInfo.create_from_taskfile(tf)
    refobj = mrefobjinter.create(typ="Asset", identifier=0)
    assettypinter.reference(refobj, tfi)

    # assert namespace is still the same
    assert cmds.namespaceInfo(absoluteName=True) == ":foo"
    refnode = cmds.referenceQuery(taskfile_without_dagnodes,
                                  referenceNode=True)
    ns = cmds.referenceQuery(refnode, namespace=True)
    ns = cmds.namespaceInfo(ns, fullName=True)
    # assert no group created
    content = cmds.namespaceInfo(ns, listOnlyDependencyNodes=True)
    assert not cmds.ls(content, type="jb_asset")
    assert cmds.getAttr("%s.taskfile_id" % refobj) == tf.pk

    # reference2
    refobj2 = mrefobjinter.create(typ="Asset", identifier=1)
    assettypinter.reference(refobj2, tfi)

    # assert namespace is still the same
    assert cmds.namespaceInfo(absoluteName=True) == ":foo"
    refnode2 = cmds.referenceQuery(taskfile_without_dagnodes + "{1}",
                                   referenceNode=True)
    ns2 = cmds.referenceQuery(refnode2, namespace=True)
    ns2 = cmds.namespaceInfo(ns2, fullName=True)
    assert refnode2 != refnode
    assert ns2 != ns
    # assert no group created
    content = cmds.namespaceInfo(ns, listOnlyDependencyNodes=True)
    assert not cmds.ls(content, type="jb_asset")
    assert cmds.getAttr("%s.taskfile_id" % refobj2) == tf.pk
Example #40
0
def moveNS(srcNS, dstNS):
    """
    Move all items from the source namespace to the destination namespace.
    @param srcNS: The source namespace
    @type srcNS: str
    @param dstNS: The destination namespace
    @type dstNS: str
    """
    # Check NS
    if not cmds.namespace(exists=srcNS):
        raise Exception('Source namespace "' + srcNS + '" does not exist!')

    # Check Destination NS
    if not cmds.namespace(exists=dstNS):
        # Create newNS
        dstNS = cmds.namespace(add=dstNS, f=True)

    # Move namespace
    cmds.namespace(mv=(srcNS, dstNS), f=True)

    # Return newNS
    return newNS
def getCharacterInfo():
    cmds.namespace(set=":")
    namespaces = cmds.namespaceInfo(lon=True)
    characterName = []
    for name in namespaces:
        characterContainer = (name + ":character_container")
        setupContainer = name.replace("Character__", "Export__")
        setupContainer = (setupContainer + ":Setup")
        if cmds.objExists(characterContainer):
            fullCharName = name
            tmpCharName = name.split("__")[1]
            tmpCharName = tmpCharName[:tmpCharName.rfind("_")]
            characterName = tmpCharName
            return (characterName, characterContainer, fullCharName,
                    setupContainer)

        else:
            # Warn no character in the scene
            charConfirm = ("No character exists in this scene")
            cmds.confirmDialog(messageAlign="center",
                               title="Create Directory",
                               message=charConfirm)
Example #42
0
def setLiveNS(namespace):
    '''
    Set the current namespace, this will cause all items created to be in this namespace.
    @note: this namespace does not need to exist, it will be created otherwise

    @param namespace: the namespace to create/set
    @type namespace: str
    '''
    namespace = cleanNS(namespace)
    # if setting to world
    if namespace == ":":
        mc.namespace(set=":")
    else:
        addNS(namespace)
        mc.namespace(set=":%s" % namespace)
    # confirm it
    curNS = mc.namespaceInfo(cur=True)
    if not curNS == namespace:
        raise NamespacerError('The namespace "%s" was not set, current namespace is "%s"'\
                              % (namespace, curNS))

    return True
Example #43
0
File: ns.py Project: kthulhu/mrv
	def delete( self, move_to_namespace = rootpath, autocreate=True ):
		"""Delete this namespace and move it's obejcts to the given move_to_namespace
		
		:param move_to_namespace: if None, the namespace to be deleted must be empty
			If Namespace, objects in this namespace will be moved there prior to namespace deletion
			move_to_namespace must exist
		:param autocreate: if True, move_to_namespace will be created if it does not exist yet
		:note: can handle sub-namespaces properly
		:raise RuntimeError:
		:todo: Implement undo !"""
		if self == self.rootpath:
			raise ValueError( "Cannot delete root namespace" )

		if not self.exists():					# its already gone - all fine
			return

		# assure we have a namespace type
		if move_to_namespace:
			move_to_namespace = self.__class__( move_to_namespace )

		# assure we do not loose the current namespace - the maya methods could easily fail
		previousns = Namespace.current( )
		cleanup = CallOnDeletion( None )
		if previousns != self:		# cannot reset future deleted namespace
			cleanup.callableobj = lambda : previousns.setCurrent()


		# recurse into children for deletion
		for childns in self.children( ):
			childns.delete( move_to_namespace = move_to_namespace )

		# make ourselves current
		self.setCurrent( )

		if move_to_namespace:
			self.moveNodes( move_to_namespace, autocreate=autocreate )

		# finally delete the namespace
		cmds.namespace( rm=self )
Example #44
0
def remove_namespaces(empty_first=True, defaults=('UI', 'shared')):
    """Remove namespaces from the current Maya scene.

    Args:
        empty_first: Remove nodes from the namespace before deleting it
        defaults: Namespaces to keep

    Returns:
        None
    """
    namespaces = [
        ns for ns in cmds.namespaceInfo(lon=True, r=True) if ns not in defaults
    ]
    namespaces.sort(key=lambda ns: ns.count(':'), reverse=True)
    for ns in namespaces:
        try:
            cmds.namespace(rm=ns, mnr=empty_first)
            LOG.debug('Removed namespace: `{0}`'.format(ns))
        except RuntimeError as e:
            LOG.exception(
                'Could not remove namespace, it might not be empty: {}'.format(
                    e))
Example #45
0
 def initialiseBlueprintModuleList(self):
     cmds.namespace(setNamespace=self.selectedCharacter)
     blueprintNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True)
     cmds.namespace(setNamespace=":")
     # Dictionary containing full names of blueprint modules
     self.blueprintModules = {}
     
     if len(blueprintNamespaces) > 0:
         for namespace in blueprintNamespaces:
             blueprintModule = utils.stripLeadingNamespace(namespace)[1]
             
             """ Add in to modify name displayed in module scroll list """
             #uSpecNameA = blueprintModule.partition("__")[0]
             #uSpecNameB = blueprintModule.partition("__")[2]
             #userSpecifiedName = (uSpecNameA + "_" + uSpecNameB)
             userSpecifiedName = blueprintModule.partition("__")[2]
             cmds.textScrollList(self.UIElements["blueprintModule_textScroll"], edit=True, append=userSpecifiedName)
             self.blueprintModules[userSpecifiedName] = namespace
             
     cmds.textScrollList(self.UIElements["blueprintModule_textScroll"], edit=True, selectIndexedItem=1)
     selectedBlprnModule = cmds.textScrollList(self.UIElements["blueprintModule_textScroll"], q=True, selectItem=True)
     self.selectedBlueprintModule = self.blueprintModules[selectedBlprnModule[0]]       
Example #46
0
def delete_asset():
    selection = cmds.ls(sl=1, long=1)
    namespaces_list = []

    for sel in selection:
        namespace = None
        relatives = cmds.listRelatives(sel, allDescendents=1)
        for relative in relatives:
            if cmds.referenceQuery(relative, isNodeReferenced=True):
                namespace = relative.split(':')[0]
                refFile = cmds.referenceQuery(relative, filename=True)
                break
        if [namespace, refFile] not in namespaces_list:
            namespaces_list.append([namespace, refFile])

    for namespace in namespaces_list:
        cmds.file(namespace[-1], removeReference=True)
        locator_name = namespace[0] + '_CTRL'
        if cmds.objExists(locator_name):
            cmds.delete(locator_name)
            if cmds.namespace(exists=namespace[0]):
                cmds.namespace(rm=namespace[0])
def basicBlock():
    blockHeight = cmds.intSliderGrp('blockHeight', q=True, v=True)
    blockWidth = cmds.intSliderGrp('blockWidth', q=True, v=True)
    blockDepth = cmds.intSliderGrp('blockDepth', q=True, v=True)
    rgb = cmds.colorSliderGrp('blockColour', q=True, rgbValue=True)

    #Creates the temporary namespace
    global nextBlockId
    nsTmp = "Block" + str(nextBlockId)
    nextBlockId = nextBlockId + 1
    createNamespace(nsTmp)

    cubeSizeX = blockWidth * 0.8
    cubeSizeZ = blockDepth * 0.8
    cubeSizeY = blockHeight * 0.32

    cmds.polyCube(h=cubeSizeY, w=cubeSizeX, d=cubeSizeZ)
    cmds.move((cubeSizeY / 2.0), moveY=True)
    for i in range(blockWidth):
        for j in range(blockDepth):
            cmds.polyCylinder(r=0.25, h=0.20)
            cmds.move((cubeSizeY + 0.10), moveY=True, a=True)
            cmds.move(((i * 0.8) - (cubeSizeX / 2.0) + 0.4),
                      moveX=True,
                      a=True)
            cmds.move(((j * 0.8) - (cubeSizeZ / 2.0) + 0.4),
                      moveZ=True,
                      a=True)

    myShader = cmds.shadingNode('lambert', asShader=True, name="blckMat")
    cmds.setAttr(nsTmp + ":blckMat.color",
                 rgb[0],
                 rgb[1],
                 rgb[2],
                 typ='double3')
    cmds.polyUnite((nsTmp + ":*"), n=nsTmp, ch=False)
    cmds.delete(ch=True)
    cmds.hyperShade(assign=(nsTmp + ":blckMat"))
    cmds.namespace(removeNamespace=":" + nsTmp, mergeNamespaceWithParent=True)
Example #48
0
    def _find(self):
        """
        :return: Empty namespaces
        :rtype: generator
        """
        # set namespace to root
        cmds.namespace(set=":")

        # get all namespaces
        namespaces = cmds.namespaceInfo(":",
                                        listOnlyNamespaces=True,
                                        recurse=True)
        namespaces.reverse()

        # loop namespaces
        for ns in namespaces:
            if ns in self.ignoreNamespaces:
                continue

            # yield empty namespaces
            if not cmds.namespaceInfo(ns, listOnlyDependencyNodes=True):
                yield ns
Example #49
0
    def remove(self, container):

        from maya import cmds

        namespace = container["namespace"]
        container_name = container["objectName"]

        container_content = cmds.sets(container_name, query=True)
        nodes = cmds.ls(container_content, long=True)

        nodes.append(container_name)

        self.log.info("Removing '%s' from Maya.." % container["name"])

        try:
            cmds.delete(nodes)
        except ValueError:
            pass

        cmds.namespace(removeNamespace=namespace, deleteNamespaceContent=True)

        return True
Example #50
0
def test_create_from_attributes_with_namespace():
    """Validate we can create a compound from attributes in a namespace."""
    cmds.namespace(addNamespace=":namespace_a")
    cmds.rename("a", ":namespace_a:a")
    cmds.rename("b", ":namespace_a:b")
    cmds.rename("c", ":namespace_a:c")
    cmds.rename("d", ":namespace_a:d")
    cmds.rename("e", ":namespace_a:e")

    compound = from_attributes([":namespace_a:b.translateX"],
                               [":namespace_a:d.translateX"])

    assert isinstance(compound, Compound)
    assert _ls() == {
        "namespace_a:a",
        "namespace_a:compound1:inputs",
        "namespace_a:compound1:b",
        "namespace_a:compound1:c",
        "namespace_a:compound1:d",
        "namespace_a:compound1:outputs",
        "namespace_a:e",
    }
    def mirrorLyt(self, *args):
        """
        Requires the lyt to be mirrored and
        added to a namespace.
        """
        asset_info = {}
        if len(cmds.ls(sl=True)) == 0:
            return
        sel = cmds.ls(sl=True)[0]
        if cmds.nodeType(sel) != 'dagContainer':
            return
        assetcontents = cmds.container(sel, q=True, nl=True)
        print sel
        print assetcontents

        # Find the Main_GRP
        for a in assetcontents:
            if 'Main_GRP' in a:
                maingrp = a
        print maingrp

        mmain = maingrp.replace('L_', 'R_')
        print mmain

        # Determine mirror namespace name
        tv = maingrp.partition(':')[0]
        mns = tv.replace('L_', 'R_')
        cmds.namespace(set=':')
        cmds.namespace(add=mns)
        cmds.namespace(set=mns)

        # Duplicate the Main_GRP
        nodedupe = cmds.duplicate(maingrp, ic=True, rc=True, un=True)

        mircon = cmds.container(n='FACE_LYT_01_AST')
        print mmain
        try:
            cmds.container(sel, edit=True, rn=mmain, force=True)
        except:
            pass

        cmds.container(mircon, edit=True, an=mmain, f=True)

        cmds.namespace(set=':')

        for n in nodedupe:
            cmds.container(mircon, edit=True, an=n, f=True)
            cmds.container(mircon, edit=True, an=n, f=True)
Example #52
0
 def deleteModule(self, *args):
     """ Delete the Guide, ModuleLayout and Namespace.
     """
     # delete mirror preview:
     try:
         cmds.delete(self.moduleGrp[:self.moduleGrp.find(":")] +
                     "_MirrorGrp")
     except:
         pass
     # delete the guide module:
     utils.clearNodeGrp(nodeGrpName=self.moduleGrp,
                        attrFind='guideBase',
                        unparent=True)
     # clear default 'dpAR_GuideMirror_Grp':
     utils.clearNodeGrp()
     # remove the namespaces:
     allNamespaceList = cmds.namespaceInfo(listOnlyNamespaces=True)
     if self.guideNamespace in allNamespaceList:
         cmds.namespace(moveNamespace=(self.guideNamespace, ':'),
                        force=True)
         cmds.namespace(removeNamespace=self.guideNamespace, force=True)
     try:
         # delete the moduleFrameLayout from window UI:
         cmds.deleteUI(self.moduleFrameLayout)
         self.clearSelectedModuleLayout()
         # edit the footer A text:
         self.currentText = cmds.text("footerAText", query=True, label=True)
         cmds.text(
             "footerAText",
             edit=True,
             label=str(
                 int(self.currentText[:self.currentText.find(" ")]) - 1) +
             " " + self.langDic[self.langName]['i005_footerA'])
     except:
         pass
     # clear module from instance list (clean dpUI list):
     delIndex = self.dpUIinst.moduleInstancesList.index(self)
     self.dpUIinst.moduleInstancesList.pop(delIndex)
Example #53
0
    def switch(cls, bsnodes, *args):
        '''切换缓存
            bsnodes传入类型为list
        '''
        _input_connect = {}
        _output_connect = {}
        _info = {}
        asset, namespace, node, path = args
        _texgrp = cls.get_texfile_grp(bsnodes[0])
        _abcgrp = cls.get_alembic_grp(bsnodes[0])
        for bsnode in bsnodes:
            # cls.get_connect_info(bsnode,_info)
            _input_connect = cls.get_blend_input(bsnode)
            _output_connect = cls.get_blend_output(bsnode)
        if _abcgrp:
            _ns = cls.get_alembic_namespace(_abcgrp)
            cmds.delete(_abcgrp)
            if _ns:
                cmds.namespace(rm=_ns, mnr=1)
        cls.import_alembic(asset, namespace, node, path)
        cls.connect_attr(_abcgrp, _texgrp)

        _dis_connect = {}
        for k, v in _input_connect.items():
            cmds.connectAttr(k, v)
            try:
                _k_p = k.split(".worldMesh")[0]
                _k = "{}_rendering.outMesh".format(_k_p)
                _v = v.split(".inputTargetGroup")[0].replace(
                    "inputTarget", "input") + ".inputGeometry"
                #print(_k,_v)
                cmds.connectAttr(k, _v)
                _dis_connect[k] = _v
            except:
                pass
        if _dis_connect:
            for k, v in _dis_connect.items():
                cmds.disconnectAttr(k, v)
Example #54
0
    def constructProxy(self):
        cmds.namespace(set=":")
        self.destructProxy()
        dags = cmds.ls(self.__select, dag=True, ap=True)
        self.grp = cmds.group(name="%s:Proxy" % self.namespace, empty=True)
        cmds.hide(self.grp)

        cmds.progressWindow(title=u"创建代理", status=u"生成中...")
        cmds.progressWindow(e=True, progress=0, max=len(dags))

        for dag in dags:
            cmds.progressWindow(e=True, step=1)
            if not dag.find("%s:Main" % self.namespace) == -1: continue
            shape = cmds.listRelatives(dag, shapes=True, fullPath=True)
            if not shape: continue
            shapeType = cmds.nodeType(shape[0])
            if shapeType == "nurbsCurve" or shapeType == "nurbsSurface":
                attrs = cmds.listAttr(dag, keyable=True)
                if not attrs: continue
                loc = cmds.spaceLocator(name=dag + "___Proxy")
                for attr in attrs:
                    if attr in [
                            u'visibility', u'translateX', u'translateY',
                            u'translateZ', u'rotateX', u'rotateY', u'rotateZ',
                            u'scaleX', u'scaleY', u'scaleZ'
                    ]:
                        continue
                    attrType = cmds.getAttr("%s.%s" % (dag, attr), type=True)
                    try:
                        cmds.addAttr(loc,
                                     ln=attr,
                                     keyable=True,
                                     attributeType=attrType)
                    except:
                        continue
                cmds.parent(loc, self.grp)

        cmds.progressWindow(endProgress=1)
Example #55
0
    def do_plant(self, pressPosition):
        view = omUI.M3dView.active3dView()
        worldPt = om.MPoint()
        worldVector = om.MVector()
        view.viewToWorld(int(pressPosition[0]), int(pressPosition[1]), worldPt,
                         worldVector)
        mSel = om.MSelectionList()
        mSel.add(self.lineEdit_2.text())
        mDagPath = om.MDagPath()
        mSel.getDagPath(0, mDagPath)
        fnMesh = om.MFnMesh(mDagPath)
        farclip = 1.0
        clickPos = om.MFloatPoint(worldPt.x, worldPt.y, worldPt.z)
        mCamPath = om.MDagPath()
        view.getCamera(mCamPath)
        cam_name = mCamPath.fullPathName()
        ratio_scale = mc.getAttr(cam_name + '.farClipPlane')

        clickDir = om.MFloatVector(worldVector.x * ratio_scale,
                                   worldVector.y * ratio_scale,
                                   worldVector.z * ratio_scale)
        currentHitFP = om.MFloatPoint()
        hit = fnMesh.closestIntersection(clickPos, clickDir, None, None, True,
                                         om.MSpace.kWorld, farclip, True, None,
                                         currentHitFP, None, None, None, None,
                                         None)
        if hit:
            tree_name = self.treeListWidget.currentItem().text()
            current_namespace = tree_name.split(':')[1].split('_')[1]
            dup_tree = mc.duplicate(tree_name)
            mc.move(currentHitFP.x, currentHitFP.y, currentHitFP.z, tree_name)

            new_namespace = self.get_namespace(current_namespace)

            mc.namespace(add=new_namespace)

            for i in dup_tree:
                mc.rename(i, "%s:%s" % (new_namespace, i))
Example #56
0
def create_empty(namespace=COMPOUND_DEFAULT_NAMESPACE):
    """
    Create a compound from nothing.

    :param str namespace: The desired namespace for the new compound.
    :return: A ``Component`` instance.
    :rtype: Compound
    """
    namespace = _utils_namespace.get_unique_namespace(namespace)

    # Create namespace if necessary
    if not cmds.namespace(exists=namespace):
        cmds.namespace(add=namespace)

    # Create bounds if necessary
    bound_inn_dagpath = "%s:%s" % (namespace, INPUT_NODE_NAME)
    bound_out_dagpath = "%s:%s" % (namespace, OUTPUT_NODE_NAME)
    if not cmds.objExists(bound_inn_dagpath):
        cmds.createNode("network", name=bound_inn_dagpath)
    if not cmds.objExists(bound_out_dagpath):
        cmds.createNode("network", name=bound_out_dagpath)

    return Compound(namespace)
Example #57
0
def importRef():
    """ import reference and try to remove namespace """
    cleanSharedReferenceNode()

    refs = mc.ls(type='reference')
    skipNodes = ['_UNKNOWN_REF_NODE_', 'sharedReferenceNode']
    skipNamespaces = ['UI', 'shared']

    for each in refs:
        try:
            if not each in skipNodes:
                fileName = mc.referenceQuery(each, filename=True)
                mc.file(fileName, importReference=True)

        except Exception as e:
            print e

    namespaces = mc.namespaceInfo(listOnlyNamespaces=True)

    for each in namespaces:
        if not each in skipNamespaces:
            mc.namespace(force=True, mv=(':%s' % each, ':'))
            mc.namespace(removeNamespace=each)
Example #58
0
def era_NameSpace(delNameSpace = 0):
    nameSpaces = list(set(mc.namespaceInfo(lon = True,r = True,sn = True)) - set(['UI','shared']) - set([mc.referenceQuery(r,ns = True,shn = True) for r in mc.ls(rf = True)]))
    print nameSpaces
    if nameSpaces:
        if delNameSpace:
            num = 0
            while(True):
                ns = list(set(mc.namespaceInfo(lon = True,r = True,sn = True)) - set(['UI','shared']) - set([mc.referenceQuery(r,ns = True,shn = True) for r in mc.ls(rf = True)]))
                if not ns:
                    break
                for n in ns:
                    if num > 10000:
                        return '脚本运行错误,请联系技术部人员解决。'
                    try:
                        mc.namespace( f = True,mv=[n,':'] )
                        mc.namespace( f = True,rm=n )
                    except RuntimeError:
                        num +=1
                        continue
                if num > 10000:
                    return '脚本运行错误,请联系技术部人员解决。'
        else:
            return era_SplitFlag().join(nameSpaces)
Example #59
0
    def install_module(self, module, *args):
        basename = "instance_"

        cmds.namespace(setNamespace=":")
        namespaces = cmds.namespaceInfo(listOnlyNamespaces=True)
        for i in range(len(namespaces)):
            if namespaces[i].find("__") != -1:
                namespaces[i] = namespaces[i].partition("__")[2]

        new_suffix = utils.find_highest_trailing_number(namespaces,
                                                        basename) + 1
        user_spec_name = basename + str(new_suffix)

        mod = __import__("Blueprint." + module, {}, {}, [module])
        reload(mod)

        module_class = getattr(mod, mod.CLASS_NAME)
        module_instance = module_class(user_spec_name)
        module_instance.install()

        module_transform = mod.CLASS_NAME + "__" + user_spec_name + ":module_transform"
        cmds.select(module_transform, replace=True)
        cmds.setToolTo("moveSuperContext")
Example #60
0
def namespace():
    """ clear namespace
    
    """
    NamespaceList = cmds.namespaceInfo(recurse=True, listOnlyNamespaces=True)
    if NamespaceList:
        NamespaceList.reverse()
        for NamespaceName in NamespaceList:
            if NamespaceName != 'shared' and NamespaceName != 'UI':
                cmds.namespace(setNamespace=NamespaceName)
                NamespaceList = cmds.namespaceInfo(recurse=True,
                                                   listOnlyNamespaces=True)
                NodeList = cmds.namespaceInfo(listOnlyDependencyNodes=True,
                                              dagPath=True)
                ParentNamespace = cmds.namespaceInfo(parent=True)
                cmds.namespace(setNamespace=':')
                if NamespaceList == None:
                    if NodeList == None:
                        try:
                            cmds.namespace(removeNamespace=NamespaceName)
                        except Exception as e:
                            logger.warning(e)
                    else:
                        IsNodeReferenced = False
                        for NodeName in NodeList:
                            if cmds.referenceQuery(
                                    NodeName, isNodeReferenced=True) == True:
                                IsNodeReferenced = True
                                break
                        if IsNodeReferenced == False:
                            try:
                                cmds.namespace(force=True,
                                               moveNamespace=(NamespaceName,
                                                              ParentNamespace))
                                cmds.namespace(removeNamespace=NamespaceName)
                            except Exception as e:
                                logger.warning(e)