示例#1
0
文件: basic.py 项目: NicoMaya/pymel
def setupScriptPaths():
    """
    Add Maya-specific directories to sys.path
    """
    # Extra libraries
    #
    try:
        # Tkinter libraries are included in the zip, add that subfolder
        p = [p for p in sys.path if p.endswith('.zip')][0]
        sys.path.append( os.path.join(p,'lib-tk') )
    except:
        pass

    # Per-version prefs scripts dir (eg .../maya8.5/prefs/scripts)
    #
    prefsDir = cmds.internalVar( userPrefDir=True )
    sys.path.append( os.path.join( prefsDir, 'scripts' ) )

    # Per-version scripts dir (eg .../maya8.5/scripts)
    #
    scriptDir = cmds.internalVar( userScriptDir=True )
    sys.path.append( os.path.dirname(scriptDir) )

    # User application dir (eg .../maya/scripts)
    #
    appDir = cmds.internalVar( userAppDir=True )
    sys.path.append( os.path.join( appDir, 'scripts' ) )
示例#2
0
def loadConfig():
    """ Load config file

    Return:
        config(list): List of path module paths

    """
    configFilePath = os.path.normpath(os.path.join(
        cmds.internalVar(userScriptDir=True), 'rush.json'))

    defaultModulePath = os.path.normpath(os.path.join(
        cmds.internalVar(userScriptDir=True), 'rush', 'module'))

    config = [defaultModulePath]

    # Use only default module path if config file does not exist
    if not os.path.exists(configFilePath):
        print("Additional config file not found: %s" % configFilePath)
        return config

    # Open and load config file in use home dir and append it to the
    # config list
    try:
        f = open(configFilePath, 'r')
        extra_config = json.load(f)
        additionalPaths = extra_config["path"]
        f.close()
    except IOError:
        print("Failed to load config file")

    config.extend(additionalPaths)

    return config
示例#3
0
def mayaTools():
    
    #import custom maya setup script
    print cmds.internalVar(usd = True)
    print cmds.internalVar(upd = True)
    path = cmds.internalVar(usd = True)
    path = path + "mayaTools.txt"
    print path
    
    if os.path.exists(path):
        f = open(path, 'r')
        
        mayaToolsDir = f.readline()
        if not os.path.exists(mayaToolsDir):
            mayaToolsInstall_UI()
        
        path = mayaToolsDir + "/General/Scripts"
        pluginPath = mayaToolsDir + "/General/Plugins"
        
        #look in sys.path to see if path is in sys.path. if not, add it
        if not path in sys.path:
            sys.path.append(path)
            
            
        #run setup
        import customMayaMenu as cmm
        cmm.customMayaMenu()
        cmds.file(new = True, force = True)
    
    
    else:
        mayaToolsInstall_UI()
示例#4
0
 def __init__(self):
     # scripts
     scriptDir = cmds.internalVar(usd=1)
     scriptDir = scriptDir.partition('maya')
     scriptDir = os.path.join(scriptDir[0], scriptDir[1])
     self.rootPath = os.path.join(scriptDir, 'scripts')
     # prefs
     prefDir = cmds.internalVar(upd=1)
     # build paths
     self.iconPath = os.path.join(prefDir, 'icons')
     self.iconOn = os.path.join(self.iconPath, 'srv_mirSel_on_icon.xpm')
     self.iconOff = os.path.join(self.iconPath, 'srv_mirSel_off_icon.xpm')
     self.pairPath = os.path.join(self.rootPath, 'pairSelectList.txt')
示例#5
0
def defaultPath():
    # user = os.path.expanduser('~')
    # mainDir = user + '/maya/characterSets/'
    # proper directory query
    varPath = cmds.internalVar(userAppDir=True)
    mainDir = os.path.join(varPath, 'characterSets')
    return mainDir
示例#6
0
def UI():
	# check to see if the window exists
	if cmds.window('exampleUI', exists = True):
		cmds.deleteUI('exampleUI')
	#create the window
	window = cmds.window('exampleUI', title = 'exampleUI', w = 300, h = 300, mnb  = False, mxb = False, sizeable = False)
	#show window
	cmds.showWindow(window)
	# create a main layout
	mainLayout = cmds.columnLayout(h = 300, w = 300)
	# banner image
	imagePath = cmds.internalVar(userPrefDir = True) + 'icons' + '/test.jpg' # find the path to the image
	cmds.image(w = 300, h = 100, image = imagePath)
	cmds.separator(h = 15)# just a seperator
	# projects option menu
	projectsOptionMenu = cmds.optionMenu ( 'projectsOptionMenu', width = 300, changeCommand = populateCharacters, label = 'choose a project:     ') # change command needed to update character option menu based on what project is selected
	# create a character option menu
	characerOptionMenu = cmds.optionMenu ( 'characerOptionMenu', width = 300, label = 'choose a character: ')
	cmds.separator(h = 15) # just a seperator
	# create the build button
	cmds.button(label = 'build', w = 300, h = 50 ,c = build)
	# activate populate projects option menu
	populateProjects()
	# activate populate characaters option menu
	populateCharacters()
示例#7
0
def TappInstall_browse(*args):
    repoPath=cmds.fileDialog2(dialogStyle=1,fileMode=3)
    
    if repoPath:
        repoPath=repoPath[0].replace('\\','/')
        
        check=False
        #checking all subdirectories
        for name in os.listdir(repoPath):
            
            #confirm that this is the Tapp directory
            if name=='Tapp':
                check=True
        
        if check:
            #create the text file that contains the Tapp directory path
            path=cmds.internalVar(upd=True)+'Tapp.yml'
            
            f=open(path,'w')
            data='{launchWindowAtStartup: False, repositoryPath: \''+repoPath+'\'}'
            f.write(data)
            f.close()
    
            #run setup
            sys.path.append(repoPath)
            
            cmds.evalDeferred('import Tapp')
            
            #delete ui
            cmds.deleteUI('TappInstall_UI')
            
        else:
            cmds.warning('Selected directory is not the \'Tapp\' directory. Please try again')
示例#8
0
def exportAnim(namespace, exportFile) : 
	# ctrls
	set1 = mc.ls('%s:*_ctrl' % namespace)
	set2 = mc.ls('%s:*:*_ctrl' % namespace)
	set3 = mc.ls('%s:*:*:*_ctrl' % namespace)
	set4 = mc.ls('%s:*_Ctrl' % namespace)
	set5 = mc.ls('%s:*:*_Ctrl' % namespace)
	set6 = mc.ls('%s:*:*:*_Ctrl' % namespace)

	ctrls = set1+set2+set3+set4+set5+set6

	animFile = '%s/%s.anim' % (exportFile, namespace)

	# manage dirs 
	if not os.path.exists(exportFile) : 
		os.makedirs(exportFile)

	# export command 
	mc.select(ctrls)

	tempFile = '%s/temp.anim' % mc.internalVar(utd = True)
	mm.eval('file -force -options "precision=8;intValue=17;nodeNames=1;verboseUnits=0;whichRange=1;range=1:24;options=keys;hierarchy=none;controlPoints=0;shapes=0;helpPictures=0;useChannelBox=0;copyKeyCmd=-animation objects -option keys -hierarchy none -controlPoints 0 -shape 0 " -typ "animExport" -pr -es "%s";' % tempFile)

	fileUtils.copy(tempFile, animFile)
	os.remove(tempFile)

	# export selection controllers 
	exportFilePath = '%s/%s.txt' % (exportFile, namespace)
	fileUtils.writeFile(exportFilePath, str(ctrls))

	mc.select(cl = True)

	return True 
示例#9
0
def Tapp():
    path=cmds.internalVar(upd=True)+'Tapp.yml'

    if os.path.exists(path):
        f=open(path,'r')
        
        settings=f.read()
        
        #brute force from yaml to ast
        settings=settings.replace('{','{\'').replace(':','\':').replace(', ',', \'')
        settings=settings.replace('\n','')
        settings=settings.replace('true','True')
        settings=settings.replace('false','False')
        
        #compensate for drive letter
        settings=settings.replace('\':/',':/')
        
        settings=ast.literal_eval(settings)
             
        path=settings['repositoryPath']
        
        if os.path.exists(path):
            if not path in sys.path:
                sys.path.append(path)
            
            #run setup
            cmds.evalDeferred('import Tapp')
        else:
            TappInstall_UI()
    else:
        TappInstall_UI()
示例#10
0
 def __init__(self):
         self.userDir=os.path.expanduser("~")
         self.fileFilters=["ma","jpg","png","mb",'iff','tga','tif','PNG','JPG']
         self.userName=os.path.basename(self.userDir)
         self.minimeDir=os.path.normpath(os.path.join(self.userDir,"MiniMe"))
         self.favFile=os.path.join(self.minimeDir,"favorites.txt")
         self.ftpData= os.path.normpath(os.path.join(self.minimeDir,"ftp.db"))
         try:
                 self.prjDir = (cmds.workspace(fn=True)).replace("/","\\") #returns project directory for start up
                 self.defaultImage = cmds.internalVar(usd=True)+"notFound.jpg" # get path of image from script directory
         except Exception as e:
                 print e
         ##Check the MiniME setting folder exist if not create one then check
         ## if Favorite file exist if not create it, if it exist read it.
         if os.path.isdir(self.minimeDir):
                 ### "Mini Me Setting Directory Exist or not"
                 if os.path.isfile(self.favFile):
                         ### "Favorite file exists"
                         try:
                                 read_fav_file=open(self.favFile,"r")
                                 ### Load favorite dictioary from file
                                 self.favItems=eval(read_fav_file.read())
                                 if self.favItems is None:
                                         print "No favorites found in file."
                         except Exception as err:
                                 self.favItems={}
                                 print err
                         finally:
                                 read_fav_file.close()
                 else:
                         self.createFavFile()
         else:
                 print "Creating " + self.minimeDir
                 os.mkdir(self.minimeDir)
示例#11
0
    def _open(self):
        """open marking menu"""
        self._file_read = cmds.fileDialog2(fm=1, ff='menu_*.mel', dir=cmds.internalVar(umm=True))[0]
        self.ui.list_items.clear()
        self.ui.list_items.setCurrentRow(-1)
        self._data = []
        self._mel_block = open(self._file_read).readlines()
        i = 0

        while i < len(self._mel_block):
            if 'menuItem' in self._mel_block[i]:
                i += 1
                item = {"label": "", "command": [-1, ""], "language": [-1, "mel"], "icon": ""}
                include = True
                while '-' in self._mel_block[i]:
                    if '-label ' in self._mel_block[i]:
                        item["label"] = re.match('(.*)-label "(.*)"(.*)', self._mel_block[i]).group(2)
                    elif '-command ' in self._mel_block[i]:
                        item["command"] = [i, re.match('(.*)-command "(.*)"(.*)', self._mel_block[i]).group(2)]
                    elif '-sourceType ' in self._mel_block[i]:
                        item["language"] = [i, re.match('(.*)-sourceType "(.*)"(.*)', self._mel_block[i]).group(2)]
                    elif '-image ' in self._mel_block[i]:
                        item["icon"] = re.match('(.*)-image "(.*)"(.*)', self._mel_block[i]).group(2)
                    elif '-subMenu 1' in self._mel_block[i] or '-optionBox 1' in self._mel_block[i]:
                        include = False
                    i += 1
                if include:
                    self._data.append(item)
                    self.ui.list_items.addItem(item["label"])
            else:
                i += 1
示例#12
0
文件: qt.py 项目: Temujin2887/mlib
def getSettings(appName, unique=False, version=None):
	"""
	Helper to get a settings object for a given app-name
	It uses INI settings format for Maya, and registry format for stand-alone tools.
	Try to ensure that the appName provided is unique, as overlapping appNames
	will try to load/overwrite each others settings file/registry data.

	:param appName: string -- Application name to use when creating qtSettings ini file/registry entry.
	:return: QtCore.QSettings -- Settings object
	"""
	ukey = __name__ + '_QSettings'
	if not unique and (appName, version) in __main__.__dict__.setdefault(__name__+'_settings', {}):
		return __main__.__dict__[ukey][(appName, version)]

	if has_maya:
		settingsPath = os.path.join(cmds.internalVar(upd=True), 'mlib_settings', appName+'.ini')
		settingsPath = os.path.normpath(settingsPath)

		settings = QtCore.QSettings(settingsPath, QtCore.QSettings.IniFormat)
		settings.setParent(getMayaWindow())
	else:
		settings = QtCore.QSettings('MLib', appName)

	if not unique:
		__main__.__dict__[ukey][(appName, version)] = settings
	elif isinstance(unique, QtCore.QObject):
		settings.setParent(unique)

	if version is not None:
		if float(settings.value('__version__', version))<version:
			settings.clear()
		settings.setValue('__version__', version)
	return settings
示例#13
0
def gui():
	'''
	Gui element for getting the desired path.
	'''
	
	global mainCol
	
	if( cmds.window(win,q=True, ex=True) ):
		cmds.deleteUI(win)
		
	cmds.window( win, w=winWidth, h=winHeight)
	# mainCol = cmds.columnLayout()
	mainCol = cmds.rowColumnLayout( nc=1, w=winWidth, h=winHeight, cw=[1,winWidth+10])	
	# Get proper directory.
	# Focus on a directory in the maya folder
	scriptDir = cmds.internalVar(userAppDir=True)
	scriptDir = os.path.join(scriptDir, "testDir") # Result: C:/Documents and Settings/mclavan/My Documents/maya/scripts # 
	
	# Does the directory exists?
	# If it does then execute the script.
	if(os.path.exists(scriptDir)):
		print("Run Script")
		#print(scriptDir)
		#print(os.walk(scriptDir).next()[0])
		tabDirs = os.walk(scriptDir).next()[1]
		tdTab(scriptDir, tabDirs, mainCol )
		
	else:
		print("Directory doesn't exists.")
		
	cmds.showWindow(win)
def writeSelAttrFile():
    """
	Writes the selected attributes from the textScrollList to a file.
	"""
    # Let the user choose where the files is being saved to.
    # Starting point will be the maya folder.
    mayaFolder = cmds.internalVar(userAppDir=True)
    # File Dialog
    # sba will be the file extension.
    filePath = cmds.fileDialog(mode=1, directoryMask=mayaFolder + "*.sba")

    print("Choosen file: " + filePath)

    # Gather the attributes from the textScrollList
    selectedTSL = cmds.textScrollList("sbaKeyTSL", q=True, si=True)

    # Open File
    attrFile = open(filePath, "w")  # Will overwrite the file if it allready exists!

    # Loop through one element at a time writing it to a file.
    for item in selectedTSL:
        attrFile.write(item + "\n")

        # Close File
    attrFile.close()
def override_panels(custom_hs_cmd=None, custom_ne_cmd=None):
    # check if icons is in maya resources, if not, copy into userBitmapsDir
    user_icons_path = cmds.internalVar(userBitmapsDir=True)
    mtt_icons_path = os.path.join(os.path.dirname(__file__), 'icons')
    maya_icons = os.listdir(user_icons_path)

    for ico in MTT_ICONS_NAME:
        if ico not in maya_icons:
            source_file = os.path.join(mtt_icons_path, ico)
            destination_file = os.path.join(user_icons_path, ico)
            shutil.copy2(source_file, destination_file)

    # create MEL global proc
    cmd = mel.createMelWrapper(
        override_add_hypershade_panel, types=['string'], returnCmd=True)
    mel.eval(cmd)
    cmd = mel.createMelWrapper(
        override_add_node_editor_panel, types=['string'], returnCmd=True)
    mel.eval(cmd)

    # edit callback of scripted panel
    cmds.scriptedPanelType(
        'hyperShadePanel', edit=True,
        addCallback='override_add_hypershade_panel')

    cmds.scriptedPanelType(
        'nodeEditorPanel', edit=True,
        addCallback='override_add_node_editor_panel')

    # store custom cmd
    if custom_hs_cmd:
        cmds.optionVar(sv=[VAR_HS_CMD, custom_hs_cmd])
    if custom_ne_cmd:
        cmds.optionVar(sv=[VAR_NE_CMD, custom_hs_cmd])
示例#16
0
def	skinWeights(x=None, export=None, f=None, fileName=None):
# Import/export skin weights from/to a file
# x/export: 0 for import, 1 for export
# f/fileName: filename under default project directory

	x = x or export

	if not (f or fileName):
		raise Exception, "Missing argument: fileName"
		
	if fileName:
		f = fileName
	
	obj = cmds.ls(sl=1)
	if not obj:
		raise Exception, "No object selected"

	obj = obj[0]

	node = None
	for n in cmds.listHistory(obj, f=0, bf=1):
		if cmds.nodeType(n) == 'skinCluster':
			node = n
			break
	if not node:
		raise Exception, "no skin cluster found"

	mode = "r"
	if x:
		mode = "w"
	f = open(cmds.internalVar(uwd=1) + f, mode)

	allTransforms = cmds.skinPercent(node, cmds.ls(cmds.polyListComponentConversion(obj, tv=1), fl=1), q=1, t=None)

	for vertex in cmds.ls(cmds.polyListComponentConversion(obj,tv=1), fl=1):
		if x:
			transforms = cmds.skinPercent(node, vertex, ib=1e-010, q=1, t=None)
			weights = cmds.skinPercent(node, vertex, ib=1e-010, q=1, v=1)
			s = ""
			for i in range(len(transforms)):
				s += str(weights[i])+"@"+transforms[i]+" "
			f.write(s+"\n")
		else:
			weights = {}
			for t in allTransforms:
				weights[t] = float(0)

			readWeights = f.readline().strip().split(" ")

			for i in readWeights:
				w = i.split("@")
				if w[1] in weights:
					weights[w[1]] = float(w[0])

			w = []
			for i in weights.iteritems():
				w.append(i)
			cmds.skinPercent(node, vertex, tv=w)

	f.close()
示例#17
0
def setCurrentProject(projectName, *args):
    #get access to maya tools path
    toolsPath = cmds.internalVar(usd = True) + "mayaTools.txt"
    if os.path.exists(toolsPath):
	
	f = open(toolsPath, 'r')
	mayaToolsDir = f.readline()
	f.close()
	
	
    #re-write settings
    if os.path.exists(mayaToolsDir + "/General/Scripts/projectSettings.txt"):
	f = open(mayaToolsDir + "/General/Scripts/projectSettings.txt", 'r')
	oldSettings = cPickle.load(f)
	useSourceControl = oldSettings.get("UseSourceControl")
	f.close()
	
	#write out new settings
	settings = {}
	settings["UseSourceControl"] = useSourceControl
	settings["CurrentProject"] = projectName
	
	f = open(mayaToolsDir + "/General/Scripts/projectSettings.txt", 'w')
	cPickle.dump(settings, f)
	f.close()	    
示例#18
0
    def saveCopy(self, data):
        "Button callback to end the dialog"

        resName = self.currentResource
        if resName is None:
            return

        ext = os.path.splitext(resName)[1]
        if ext == '':
            ext = '.png'

        # Bring a file browser to select where to save the copy
        captionStr = stringTable['y_resourceBrowser.kPickIconCaption']
        iconDir = cmds.internalVar(userBitmapsDir=True)
        fileList = cmds.fileDialog2(caption=captionStr,
                                    fileMode=0,
                                    okCaption=captionStr,
                                    fileFilter='*' + ext,
                                    startingDirectory=iconDir)
        path = None
        if fileList is not None:
            if len(fileList) > 0 and fileList[0] != "":
                path = fileList[0]

        if path is not None:
            cmds.resourceManager(saveAs=(resName, path))
示例#19
0
文件: cookie.py 项目: pfleer/python
    def initUI(self):

        comboBox = QtGui.QComboBox()
        # comboBox.set
        # set directory for cookie images
        directory = mc.internalVar(uad=True) + "scripts/assets/cookie/"
        # save list of images in directory
        images = os.listdir(directory)
        # remove DS_Store
        images.pop(0)
        # populate combo box with image names
        comboBox.addItems(images)
        self.mainLayout.addWidget(comboBox)

        # make image preview area

        # make a create button
        create_btn = QtGui.QPushButton("Create")

        # connect button's click slot to create_cookie method
        create_btn.clicked.connect(self.create_cookie)

        # add the button to the main layout
        self.mainLayout.addWidget(create_btn)

        # make a create button
        replace_btn = QtGui.QPushButton("Replace")

        # connect button's click slot to create_cookie method
        replace_btn.clicked.connect(self.replace_cookie)

        # add the button to the main layout
        self.mainLayout.addWidget(replace_btn)
示例#20
0
def setupTools():
    
    path = cmds.internalVar(usd = True) + "mayaTools.txt"
    

    f = open(path, 'r')
    
    mayaToolsDir = f.readline()
    
    path = mayaToolsDir + "/General/Scripts"
    pluginPath = mayaToolsDir + "/General/Plugins"
    
    #look in sys.path to see if path is in sys.path. if not, add it
    if not path in sys.path:
        sys.path.append(path)
        
    #make sure MAYA_PLUG_IN_PATH has our plugin path
    pluginPaths = os.environ["MAYA_PLUG_IN_PATH"]
    pluginPaths = pluginPaths + ";" + pluginPath
    os.environ["MAYA_PLUG_IN_PATH"] = pluginPaths
        

    
    
    #setup menu item in main window
    import customMayaMenu as cmm
    cmm.customMayaMenu()
def readAttr():
    """
	Read attributes from a chosen file.
	"""

    # Get information from file
    # Starting at the maya folder and limiting to extension .sba
    mayaFolder = cmds.internalVar(userAppDir=True)
    # File Dialog
    # sba will be the file extension.
    filePath = cmds.fileDialog(mode=0, directoryMask=mayaFolder + "*.sba")

    print("Choosen file: " + filePath)

    # Open File
    attrFile = open(filePath, "r")  # Will overwrite the file if it allready exists!

    attrs = attrFile.readlines()

    # Close File
    attrFile.close()

    # loop through file content adding to the textScrollList
    for attr in attrs:
        # Check to see if the attribute allready exists in the textScrollList
        attr = attr.rstrip()
        # all the current tsl items
        allItemsTSL = cmds.textScrollList("sbaKeyTSL", q=True, allItems=True)
        if allItemsTSL and (attr in allItemsTSL):
            print(attr + " all ready exists in the list.")
        else:
            cmds.textScrollList("sbaKeyTSL", edit=True, append=attr)
def editCharacter(*args):
    
    if cmds.window("artEditCharacterUI", exists = True):
        cmds.deleteUI("artEditCharacterUI")
    
    window = cmds.window("artEditCharacterUI", w = 300, h = 400, title = "Edit Character", mxb = False, mnb = False, sizeable = False)
    mainLayout = cmds.columnLayout(w = 300, h = 400, rs = 5, co = ["both", 5])
    
    #banner image
    toolsPath = cmds.internalVar(usd = True) + "mayaTools.txt"
    if os.path.exists(toolsPath):
        
        f = open(toolsPath, 'r')
        mayaToolsDir = f.readline()
        f.close()
	
    cmds.image(w = 300, h = 50, image = mayaToolsDir + "/General/Icons/ART/artBanner300px.bmp", parent = mainLayout)
    
    cmds.text(label = "", h = 1, parent = mainLayout)
    optionMenu = cmds.optionMenu("artProjOptionMenu", label = "Project:", w =290, h = 40, cc = getProjCharacters, parent = mainLayout)
    textScrollList = cmds.textScrollList("artProjCharacterList", w = 290, h = 300, parent = mainLayout)
    button = cmds.button(w = 290, h = 40, label = "Edit Export File", c = editSelectedCharacter, ann = "Edit the character's skeleton settings, joint positions, or skin weights.", parent = mainLayout)
    button2 = cmds.button(w = 290, h = 40, label = "Edit Rig File", c = editSelectedCharacterRig, ann = "Edit the character's control rig that will be referenced in by animation.", parent = mainLayout)
    
    cmds.text(label = "", h = 1)
    
    
    cmds.showWindow(window)
    getProjects()
    getProjCharacters()
示例#23
0
def getPrefs():
    prefsFile = abspath(join(mc.internalVar(userPrefDir=True), cfgFile))
    if exists(prefsFile):
        with open(prefsFile) as prefsFileObj:
            prefsDict = json.load(prefsFileObj)
    else:
        prefsDict = {}
    return prefsDict
示例#24
0
def getSettings():

    settingsFile = cmds.internalVar(upd=True) + 'Tapp.yml'
    f = open(settingsFile, 'r')

    settings = uy.load(f)

    return settings
示例#25
0
文件: wendyUI.py 项目: jbltx/wendyUI
 def populateModifiersButtons(self, namespace, *args):
     iconPath = cmds.internalVar(upd = True) + "icons/wendyUI/"
     icons = os.listdir(iconPath)
     for icon in icons:
         if icon.partition("_")[0] == "mod":
             niceName = icon.partition(".")[0].partition("_")[2]
             print niceName
             self.widgets[niceName + "_button"] = cmds.symbolButton(w = 50, h = 50, image = (iconPath + icon), c= partial(self.runModifier, niceName), parent = self.widgets[namespace + "_modifiers_mainLayout"])
示例#26
0
    def __init__(self):
        print "mgo_maya version: " + MgoMaya.version
        self.accepted_shaders = ['aiStandard', 'VRayMtl', 'RedshiftArchitectural']
        self.accepted_renderers = ['vray', 'redshift', 'arnold']
        self.icons_path = cmds.internalVar(upd=True) + "icons/"

        if not cmds.pluginInfo('fbxmaya', q=True, l=True):
            cmds.loadPlugin('fbxmaya')
示例#27
0
 def importer(cls):
     """import from zip archive"""
     zip_file = zipfile.ZipFile(cmds.fileDialog2(fm=1, ff="*.zip")[0], "r")
     for f in zip_file.namelist():
         if f.find("markingMenus/") == 0:
             zip_file.extract(f, cmds.internalVar(upd=True))
         else:
             zip_file.extract(f, location)
     return cls.load()
示例#28
0
def UI():
    #check to see if window exists
    if cmds.window("mkProjects", exists=True):
        cmds.deleteUI("mkProjects")

    #main window
    window = cmds.window("mkProjects", title="Project Quick Load", width=400, 
                        height=300, mnb=False, mxb=False, sizeable=False)

    #main layout
    mainLayout = cmds.columnLayout(width=400, height=300)

    #banner image
    imagePath = path.join(cmds.internalVar(upd=True), 'icons', 'mkProjects.jpg')
    #load image
    cmds.image(width=400, height=100, image=imagePath)

    cmds.separator(height=15)
    cmds.textField('location', width=400, editable=False, 
        text=getDefaultProject())

    #create projects option menu
    projectsOptionMenu = cmds.optionMenu("projectsOptionMenu", width=400, 
        label="Choose a project: ", cc=populateScenes)

    #populate projects with maya default project location
    populateProjects()

    cmds.separator(height=15)
    rowLayout = cmds.rowLayout(nc=2)

    #List Control
    scenesList = cmds.textScrollList("scenesList", 
        allowMultiSelection=False, width=300, dcc=loadFile)
    populateScenes()

    colLayout = cmds.columnLayout()
    cmds.button(label="Set Location", width=95, height=30, c=setLocation)
    cmds.separator(height=5)
    cmds.button(label="Create Project", width=95, height=30, 
        c=cmds.ProjectWindow)
    cmds.separator(height=5)
    cmds.button(label="Open Project", width=95, height=30, c=openProject)
    cmds.separator(height=5)
    cmds.button(label="Open Scenes", width=95, height=30, c=openScenes)
    cmds.separator(height=5)
    cmds.button(label="Open Textures", width=95, height=30, c=openTextures)
    cmds.separator(height=5)
    cmds.button(label="Open Renders", width=95, height=30, c=openRenders)

    #open scene button
    cmds.separator(height=15, parent=mainLayout)
    cmds.button(label="Load File", width=400, height=50, parent=mainLayout, 
        c=loadFile)

    #show window
    cmds.showWindow(window)
示例#29
0
 def crashMABuildMenu(self, *args):
     tmp = m.internalVar(userTmpDir=True)
     # get .ma files from temp:
     mas = [
         (os.path.getmtime(tmp + ma), tmp + ma, ma)
         for ma in os.listdir(tmp)
         if os.path.splitext(ma)[1].lower() == ".ma"
     ]
     self.buildSortedPopup(self.ui["crashMAPop"], mas)
示例#30
0
def HdrlsLiveUI():	
	if cmds.window("HdrLightStudioLive", exists=True):
		cmds.deleteUI("HdrLightStudioLive")

	window = cmds.window("HdrLightStudioLive", w=300, h=350, mnb=False, mxb=False, sizeable=False, title="HDR Light Studio 4 Live")
	job1 = cmds.scriptJob(uiDeleted=[window, stopLiveSession])
	job2 = cmds.scriptJob(event=["quitApplication", stopLiveSession])

	#gfx that we need
	iconsPath = cmds.internalVar(upd=True) + "icons/"
	imageLogo = iconsPath + "HdrlsLogo.png"

	#create main layout
	mainLayout = cmds.columnLayout(w=300, h=350, columnOffset=["both", 5])

	#image logo location and image control
	cmds.separator(h=5)
	cmds.image(w=300, h=35, image=imageLogo)

	#renderer list
	cmds.separator(h=10)
	cmds.text(" Host Renderer")
	cmds.separator(h=2)
	exportFormatMenu = cmds.optionMenu("hostRendererMenu", w=300, changeCommand=hostRendererChanged)

	#text field for unavailable renderers
	cmds.separator(h=5)
	cmds.scrollField('rendererErrorText', text="Error will go here", w=300, h=70, visible=True, enable=False, ww=True)

	#environment hooks list
	cmds.separator(h=10)
	cmds.text(" Environment Hooks")
	cmds.separator(h=2)
	exportFormatMenu = cmds.optionMenu("envHooksMenu", w=300, changeCommand=envHookChanged)

	#refresh button for env hooks and sync to maya button to show in attribute editor
	cmds.separator(h=10)
	cmds.rowColumnLayout(nc=2, cw=[(1, 150), (2, 150)], columnOffset=[(1, "left", 15), (2, "right", 15)], parent=mainLayout)
	cmds.button(label="Refresh Env-Hooks", w=130, c=pushRefreshEnvHooks)
	cmds.button("syncToMaya", label="Show Hook In Maya", w=130, c=pushSyncMayaToEnvHooks)

	#Start/Stop Live Session
	cmds.separator(h=25)
	cmds.separator(h=25)
	cmds.button("initHdrls", label="Start Live", w=100, enable=True,c=pushStartLiveSession)
	cmds.button("exitHdrls", label="Stop Live", w=100, enable=True, c=pushExitLiveSession)
	cmds.separator(h=10, parent=mainLayout)

	#Version information
	cmds.text(HdrlsVersion.GetHdrlsScriptVersion(), parent=mainLayout, w=300, align="right", font="smallObliqueLabelFont")

	#populate initial lists
	populateHostRendererList()

	#show window
	cmds.showWindow(window)
示例#31
0
def UI():
    imagePath = cmds.internalVar(upd=True) + "/icons/FileIcon.jpg"

    if cmds.window("ExampleBatchUI", exists=True):
        cmds.deleteUI("ExampleBatchUI")

    window = cmds.window("ExampleBatchUI",
                         w=500,
                         h=280,
                         mnb=False,
                         mxb=False,
                         title="Example of Batch",
                         sizeable=False)

    # CREATE OUR MAIN LAYOUT
    mainLayout = cmds.columnLayout(w=500, h=280)

    # CREATE OUR ROW COLUMN LAYOUT
    cmds.separator(h=15)
    rowColumnLayout = cmds.rowColumnLayout(numberOfColumns=2,
                                           columnWidth=[(1, 450), (2, 50)],
                                           columnOffset=[(1, "both", 5),
                                                         (2, "both", 10)])

    # INPUT FIELD
    cmds.text(l="Text File : ", align="left")
    cmds.text(l="")

    inputField = cmds.textField("inputField", w=440)
    cmds.symbolButton(w=30,
                      h=30,
                      image=imagePath,
                      c=partial(browseFilePath, 3, None, "inputField"))
    # partial():give a callback function in button with target arguments

    # TEXT FILE FIELD
    cmds.separator(h=20, style="none")
    cmds.separator(h=20, style="none")

    cmds.text(l="InputDirectory : ", align="left")
    cmds.text(l="")

    textInputField = cmds.textField("textInputField", w=440)
    cmds.symbolButton(w=30,
                      h=30,
                      image=imagePath,
                      c=partial(browseFilePath, 1, "*.txt", "textInputField"))

    # OUTPUT FIELD
    cmds.separator(h=20, style="none")
    cmds.separator(h=20, style="none")

    cmds.text(l="OutputDirectory : ", align="left")
    cmds.text(l="")

    textInputField = cmds.textField("outputField", w=440)
    cmds.symbolButton(w=30,
                      h=30,
                      image=imagePath,
                      c=partial(browseFilePath, 3, None, "outputField"))

    # PROCESS BUTTON
    cmds.separator(h=20, style="none")
    cmds.separator(h=20, style="none")
    cmds.button("processButton",
                w=500,
                h=50,
                l="Process",
                parent=mainLayout,
                c=process)
    cmds.separator(h=15, parent=mainLayout)

    # SHOW WINDOW
    cmds.showWindow("ExampleBatchUI")
示例#32
0
#encoding:utf-8
#material converter
import maya.cmds as mc
import pymel.core as pm
import sys
import json
mc.about(windows=1)
scriptPath = mc.internalVar(usd=1)
AbcMatToolPath = scriptPath + r'AbcMatTool'

# if the systerm is windows,then use \\ replace /
if mc.about(windows=1):
    AbcMatToolPath = AbcMatToolPath.replace(r'/', '\\')
else:
    pass

if AbcMatToolPath not in sys.path:
    sys.path.insert(0, AbcMatToolPath)

try:
    import UI

except:
    mc.error(
        'the DW_MaterialManager folder is placed wrong,the right path is : {0}'
        .format(scriptPath))

reload(UI)
UI.UI()
示例#33
0
文件: Rush.py 项目: tws0002/rush
{
    background-color: rgb(42, 42, 42);
    border-style: solid;
    border-radius: 10px;
    padding: 4px;
    border-width: 5px;
    border-color: rgb(68, 68, 68);
    font-size: 16pt;
}
"""

kPluginCmdName = "rush2"
kVerboseFlag = "-v"
kVerboseLongFlag = "-verbose"

MAYA_SCRIPT_DIR = cmds.internalVar(userScriptDir=True)

# Define mel procedure to call the previous function
mel.eval("""
global proc callLastCommand(string $function)
{
    repeatLast -ac $function -acl "blah-blah....";
}
""")


def getCommandDict():
    """
    Load json files as dicrectory.
    key is command name, and its item is icon path.
    """
示例#34
0
 def get_data_folder():
     from maya import cmds
     return cmds.internalVar(userPrefDir=True)
    def __init__(self):

        #get access to our maya tools

        toolsPath = cmds.internalVar(usd=True) + "mayaTools.txt"

        if os.path.exists(toolsPath):

            f = open(toolsPath, 'r')

            self.mayaToolsDir = f.readline()

            f.close()

        #create a dictionary for our UI widgets

        self.widgets = {}

        #create window

        if cmds.window("addCharacter_UI", exists=True):

            cmds.deleteUI("addCharacter_UI")

        self.widgets["window"] = cmds.window("addCharacter_UI",
                                             title="Add Character",
                                             w=430,
                                             h=260,
                                             sizeable=True,
                                             mxb=False,
                                             mnb=False)

        #create the main layout

        main = cmds.columnLayout(w=430)

        #banner image

        cmds.image(w=430,
                   h=50,
                   image=self.mayaToolsDir +
                   "/General/Icons/ART/artBanner430px.bmp",
                   parent=main)

        self.widgets["formLayout"] = cmds.formLayout(w=430, h=260, parent=main)

        #create the widgets

        self.widgets["project"] = cmds.optionMenu(label="Project:",
                                                  w=200,
                                                  cc=self.findCharacterRigs)

        self.widgets["search"] = cmds.textFieldGrp(label="Search:",
                                                   cl2=["left", "left"],
                                                   ct2=["left", "left"],
                                                   cw2=[40, 160],
                                                   text="coming soon",
                                                   enable=False)

        self.widgets["characterList"] = cmds.textScrollList(
            allowMultiSelection=False,
            w=200,
            h=180,
            selectCommand=self.findCharacterThumbnail)

        self.widgets["thumbnailBorder"] = cmds.image(w=210,
                                                     h=210,
                                                     image="",
                                                     ebg=True,
                                                     bgc=[0, 0, 0])

        self.widgets["thumbnail"] = cmds.image(w=200, h=200, image="")

        self.widgets["addButton"] = cmds.button(label="Add",
                                                w=60,
                                                c=partial(
                                                    self.addCharacter, False))

        self.widgets["addButton2"] = cmds.button(label="Add and Close",
                                                 w=80,
                                                 c=partial(
                                                     self.addCharacter, True))

        self.widgets["cancelButton"] = cmds.button(label="Cancel",
                                                   w=60,
                                                   c=self.cancel)

        #attach widgets

        cmds.formLayout(self.widgets["formLayout"],
                        edit=True,
                        af=[(self.widgets["project"], 'top', 10),
                            (self.widgets["project"], 'left', 10)])

        cmds.formLayout(self.widgets["formLayout"],
                        edit=True,
                        af=[(self.widgets["search"], 'top', 40),
                            (self.widgets["search"], 'left', 10)])

        cmds.formLayout(self.widgets["formLayout"],
                        edit=True,
                        af=[(self.widgets["characterList"], 'top', 70),
                            (self.widgets["characterList"], 'left', 10)])

        cmds.formLayout(self.widgets["formLayout"],
                        edit=True,
                        af=[(self.widgets["thumbnailBorder"], 'top', 5),
                            (self.widgets["thumbnailBorder"], 'right', 5)])

        cmds.formLayout(self.widgets["formLayout"],
                        edit=True,
                        af=[(self.widgets["thumbnail"], 'top', 10),
                            (self.widgets["thumbnail"], 'right', 10)])

        cmds.formLayout(self.widgets["formLayout"],
                        edit=True,
                        af=[(self.widgets["addButton"], 'bottom', 10),
                            (self.widgets["addButton"], 'left', 215)])

        cmds.formLayout(self.widgets["formLayout"],
                        edit=True,
                        af=[(self.widgets["addButton2"], 'bottom', 10),
                            (self.widgets["addButton2"], 'left', 280)])

        cmds.formLayout(self.widgets["formLayout"],
                        edit=True,
                        af=[(self.widgets["cancelButton"], 'bottom', 10),
                            (self.widgets["cancelButton"], 'right', 5)])

        #show the window

        cmds.showWindow(self.widgets["window"])

        self.findProjects()

        #set favorite project if it exists

        settingsLocation = self.mayaToolsDir + "/General/Scripts/projectSettings.txt"

        if os.path.exists(settingsLocation):

            f = open(settingsLocation, 'r')

            settings = cPickle.load(f)

            favoriteProject = settings.get("FavoriteProject")

            try:

                cmds.optionMenu(self.widgets["project"],
                                edit=True,
                                v=favoriteProject)

            except:

                pass

            self.findCharacterRigs()
示例#36
0
import maya.cmds as cmds
import maya.OpenMaya as om
import os
import maya.mel as mm
import subprocess
import batchExportSettings
from batchExportSettings import ExportSettings
reload(batchExportSettings)

#Getting script Dirs
shelfDir = cmds.internalVar(ush=True).split(";", 1)[0]
scriptsDir = str(shelfDir.split("/shelfpath", 1)[0]) + "/scriptpath/"
settingsName = scriptsDir + "batchExport_Settings.txt"

#Import settings Class
settings = ExportSettings()


############### CREATES THE UI #################
def UI():
    settings.readFromFile(settingsName)

    #Icon path
    icon = scriptsDir + "Icons/menuIconFile.png"

    #Check to see if our window exists
    if cmds.window("batchExportUI", exists=True):
        cmds.deleteUI("batchExportUI")

#Create UI window
    window = cmds.window("batchExportUI",
示例#37
0
    from PySide2 import QtWidgets, QtCore
except ImportError:
    from PySide import QtCore
    import PySide.QtGui as QtWidgets

reload(oct_playblast_win)
reload(listMayaInfo)
reload(gridLayoutMethods)
reload(playBlastCMD)

# necessary global param
file_path = str(os.path.split(os.path.realpath(__file__))[0])
default_config = os.path.join(file_path,
                              'config\\oct_play_blast_settings.yaml')
default_hud_config = os.path.join(file_path, 'config\\HUD_config.yaml')
user_config = cmds.internalVar(
    userAppDir=True) + "oct_play_blast_settings.yaml"
user_hud_config = cmds.internalVar(userAppDir=True) + "HUD_config.yaml"
ffmpeg_path = cmds.internalVar(userAppDir=True) + "ffmpeg.exe"
proj_dic = {'proj': 0}  # record the item index of the window for changing
dep_dic = {'Layout': 0, 'Animation': 1, 'VFX': 2, 'Lighting': 3}
form_class, base_class = loadUiType.loadUiType(file_path +
                                               '\\ui\\oct_playBlast_ui.ui')


class OctPlayBlastMain(oct_playblast_win.OctPlayBlastWin):
    def __init__(self, parent=None):
        super(OctPlayBlastMain, self).__init__()
        self.setupUi(self)
        # private param
        self._config_data = self.read_config()
        self._hud_config_data = self.read_hud_config()
try:
    import PySide.QtCore as qc
    import PySide.QtGui as qg
    from PySide.QtGui import QPen, QColor, QBrush, QLinearGradient, QFont, QRadialGradient
    from HitchAnimationModule.Widgets import button
    import maya.utils as utils
    import maya.cmds as cmds
    CIRCULO = cmds.internalVar(
        usd=1) + 'HitchAnimationModule\Icons\circulo.png'
except:
    pass
#-------------------------------------------------------------------------------------------------#
NORMAL, DOWN, DISABLE = 1, 2, 3
INNER, OUTER = 1, 2


# -------------------------------------------------------------------------------------------------#
class Square_button_blue(qg.QPushButton):
    penTick = QPen(QColor(33, 213, 231), 2, qc.Qt.SolidLine)
    penborder = QPen(QColor(9, 10, 12), 3, qc.Qt.SolidLine)
    _glowPens = {}

    for index in range(1, 11):
        _glowPens[index] = [
            QPen(QColor(33, 213, 231, 5 * index), 2, qc.Qt.SolidLine),
            QPen(QColor(33, 213, 231, 10 * index), 2.5, qc.Qt.SolidLine),
            QPen(QColor(33, 213, 231, 15 * index), 3, qc.Qt.SolidLine),
            QPen(QColor(33, 213, 231, 25.5 * index), 6, qc.Qt.SolidLine)
        ]

    _pen_text = QPen(QColor(125, 200, 100), 1, qc.Qt.SolidLine)
示例#39
0
# IMPORT MAYA MODULES
# -------------------------------------------------------------------------------------------------------------
from maya import cmds

from tankers.pMaya.modules import MayaVariables as var

# -------------------------------------------------------------------------------------------------------------
# IMPORT MAYA MODULES
# -------------------------------------------------------------------------------------------------------------

NAMES = var.MAINVAR
ICONS = var.ICONS
VERSION = NAMES['mayaVersion']
RESX = 1280
RESY = 720
DIRECTORY = os.path.join(cmds.internalVar(usd=True), 'capture')
CAMSHAPE = 'template_renderCamShape'
CAMNAME = 'template_renderCam'

# # -------------------------------------------------------------------------------------------------------------
# # IMPORT QT MODULES
# # -------------------------------------------------------------------------------------------------------------
# import Qt # plugin module go with DAMGtool to make UI
# from Qt import QtWidgets, QtCore, QtGui

# -------------------------------------------------------------------------------------------------------------
# MAKE MAYA UNDERSTAND QT UI AS MAYA WINDOW,  FIX PLM_VERSION CONVENTION
# -------------------------------------------------------------------------------------------------------------
# We can configure the current level to make it disable certain logs when we don't want it.
logging.basicConfig()
logger = logging.getLogger(__file__)
示例#40
0
    def importWeights(self):
        """
        Imports skin weights back onto the asset geometry after having rebuilt the skeleton in rig pose. Then calls
        on ART_BuildProgressUI.preScript().

        .. seealso:: ART_BuildProgressUI.preScript()

        """

        meshes = utils.findAllSkinnableGeo()

        self.currentTask.setRange(0, len(meshes))
        self.currentTask.setValue(0)
        self.infoText.append("\n")
        self.infoText.append("|| IMPORTING SKIN WEIGHTS ||")

        for mesh in meshes:
            filePath = utils.returnFriendlyPath(os.path.join(cmds.internalVar(utd=True), mesh + ".WEIGHTS"))

            if os.path.exists(filePath):
                riggingUtils.import_skin_weights(filePath, mesh, True)

                # update progress and info
                self.infoText.append("    Imported Skin Weights for " + mesh)
                curVal = self.currentTask.value()
                self.currentTask.setValue(curVal + 1)

                # remove skin file
                os.remove(filePath)

            else:
                # update progress and info
                self.infoText.setTextColor(QtGui.QColor(236, 217, 0))
                self.infoText.append("    Could not import weights for " + mesh)
                self.infoText.setTextColor(QtGui.QColor(255, 255, 255))
                self.warnings += 1

                curVal = self.currentTask.value()
                self.currentTask.setValue(curVal + 1)

        # update main progress bar
        self.totalProgress.setValue(5)

        # call on the prescript
        self.preScript()

        # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
        # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
        # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
        # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
        # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
        # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
        #     def exportMeshes(self):
        #
        #         lodAttrs = utils.getLodData()
        #         exportData = utils.findExportMeshData()
        #
        #         self.currentTask.setRange(0, len(lodAttrs))
        #         self.currentTask.setValue(0)
        #
        #
        #         #save the file
        #         saveFile = cmds.file(q = True, sceneName = True)
        #
        #
        #         try:
        #             cmds.file(save = True)
        #         except Exception, e:
        #             cmds.error("Could not save file. Error: " + str(e))
        #             return
        #
        #
        #         #for each LOD
        #         for each in exportData:
        #             meshValue = each[1]
        #             pathValue = each[0]
        #             boneValue = each[2]
        #             poseData = each[3]
        #             utils.exportMesh(self.mainUI, meshValue, pathValue, boneValue, poseData)
        #
        #             #open the file
        #             cmds.file(saveFile, open = True, force = True)
        #
        #             #update UI
        #             self.infoText.setTextColor(QtGui.QColor(0,255,18))
        #             self.infoText.append("    SUCCESS: FBX file exported.")
        #             self.infoText.append("          " + str(pathValue))
        #             self.infoText.setTextColor(QtGui.QColor(255,255,255))
        #
        #             #update progress bar
        #             curVal = self.currentTask.value()
        #             self.currentTask.setValue(curVal + 1)
        #
        #         #update main progress bar
        #         self.totalProgress.setValue(7)
        #
        #         #run pre-script
        #         self.preScript()

        """
示例#41
0
    def exportWeights(self):
        """
        Exports all skin weights of meshes that have skinClusters to a .weights file (JSON). It also has
        functionality to deal with morph targets, making sure they are preserved when history on the meshes is deleted.

        .. seealso:: riggingUtils.export_skin_weights()

        """

        self.infoText.append("\n")
        self.infoText.append("|| EXPORTING SKIN WEIGHTS ||")

        # find meshes that are weighted
        weightedMeshes = []
        skinClusters = cmds.ls(type='skinCluster')

        for cluster in skinClusters:
            geometry = cmds.skinCluster(cluster, q=True, g=True)[0]
            geoTransform = cmds.listRelatives(geometry, parent=True)[0]
            weightedMeshes.append([geoTransform, cluster])

        # update progress bar
        numMeshes = len(weightedMeshes)
        self.currentTask.setRange(0, numMeshes)
        self.currentTask.setValue(0)

        # save out weights of meshes
        for mesh in weightedMeshes:
            filePath = utils.returnFriendlyPath(os.path.join(cmds.internalVar(utd=True), mesh[0] + ".WEIGHTS"))

            # export skin weights
            riggingUtils.export_skin_weights(filePath, mesh[0])

            # CHECK FOR MORPH TARGETS
            blendshapeList = []

            # find blendshapes
            skinCluster = riggingUtils.findRelatedSkinCluster(mesh[0])

            if skinCluster is not None:
                blendshapes = cmds.listConnections(skinCluster + ".input", source=True, type="blendShape")
                deleteShapes = []
                if blendshapes is not None:
                    for each in blendshapes:
                        attrs = cmds.listAttr(each, m=True, string="weight")
                        if attrs is not None:
                            for attr in attrs:

                                # if not, manually create shapes by toggling attrs and duplicating mesh
                                if not cmds.objExists(attr):
                                    cmds.setAttr(each + "." + attr, 1)
                                    dupe = cmds.duplicate(mesh[0])[0]

                                    # parent to world
                                    parent = cmds.listRelatives(dupe, parent=True)
                                    if parent is not None:
                                        cmds.parent(dupe, world=True)

                                    # rename the duplicate mesh to the blendshape name
                                    cmds.rename(dupe, attr)
                                    cmds.setAttr(each + "." + attr, 0)
                                    deleteShapes.append(attr)

                            # add the blendshape node name and its attrs to the master blendshape list
                            blendshapeList.append([each, attrs])

            # delete history of meshes
            cmds.delete(mesh[0], ch=True)

            # reapply blendshapes
            for item in blendshapeList:
                bshapeName = item[0]
                shapeList = item[1]

                i = 1
                for shape in shapeList:
                    if cmds.objExists(bshapeName):
                        cmds.blendShape(bshapeName, edit=True, t=(mesh[0], i, shape, 1.0))

                    else:
                        cmds.select([shape, mesh[0]], r=True)
                        cmds.blendShape(name=bshapeName)
                        cmds.select(clear=True)

            try:
                for each in deleteShapes:
                    cmds.delete(each)
            except:
                pass

            # update progress and info
            self.infoText.append("    Exported Skin Weights for " + mesh[0])
            curVal = self.currentTask.value()
            self.currentTask.setValue(curVal + 1)

        # update main progress bar
        self.totalProgress.setValue(1)
        self.infoText.append("\n")

        # rebuild the skeleton in rig pose
        self.rebuildSkeleton()
示例#42
0
    def copyReqFileToFolder(self):
        plugFileName = 'Kang_SimpExpNode'  # 修改這個

        #判斷版本,一律假設64bit
        mversion = str(
            maya.mel.eval(
                "float $mayaVersion = `getApplicationVersionAsFloat` ;"))
        strMversion = mversion.split('.')[0]
        #丟到有帶版本號的 script folder
        usd = cmds.internalVar(usd=True)
        usrFold = usd[:-8]
        custPlugFold = usrFold + "plug-ins/"
        cpyDestFolder = custPlugFold
        plgFod = self.thisScrptPth + '/MXSController/mll/maya' + strMversion + '/'

        plgDllFile = plgFod + plugFileName + '.mll'
        cpyDestDllFile = cpyDestFolder + plugFileName + '.mll'

        # 有可能會有版本衝突,先刪除
        try:
            os.remove(cpyDestDllFile)
        except:
            pass
        opRes = None
        if (os.path.isfile(cpyDestDllFile)):
            try:
                opRes = open(cpyDestDllFile, 'r')
            except:
                pass
        if (not opRes):  #檔存在的話就不用co了
            try:
                res = os.makedirs(cpyDestFolder)  #強制建Folder
            except:
                pass
            #Copy 所需的pyd files
            #import shutil
            shutil.copy2(plgDllFile, cpyDestDllFile)
        else:
            opRes.close()

        #臨時加入當前 plugin Folder
        sysplugFldPth = maya.mel.eval("$sr = `getenv MAYA_PLUG_IN_PATH`;")
        if (not (cpyDestFolder in sysplugFldPth)):
            maya.mel.eval("$str = `putenv MAYA_PLUG_IN_PATH \"" +
                          cpyDestFolder + "\"`;")

        #load
        try:
            cmds.unloadPlugin(plugFileName)
        except:
            pass
        if not cmds.pluginInfo((plugFileName + ".mll"), q=True, loaded=True):
            cmds.loadPlugin(plugFileName)
            #set autoloaded
            cmds.pluginInfo((plugFileName + ".mll"), e=True, autoload=True)

        #找尋maya.env檔,寫入
        usd = cmds.internalVar(usd=True)
        usrFold = usd[:-8]
        mayaEnvFilePath = usrFold + "Maya.env"
        if os.path.isfile(mayaEnvFilePath):
            # read all
            f = open(mayaEnvFilePath, 'r')
            allLines = []
            newAllLines = []
            line = f.readline()
            line = line.replace("\r", "")
            line = line.replace("\n", "")
            if (len(line)):
                allLines.append(line)
            while (line != ''):
                line = f.readline()
                if (len(line)):
                    line = line.replace("\r", "")
                    line = line.replace("\n", "")
                    allLines.append(line)
            f.close()
            if (len(allLines)):
                for li in allLines:  #li=allLines[0]
                    if ("MAYA_PLUG_IN_PATH" in li):
                        lnChk = li.replace(" ", "")
                        lnChk = li.replace("=", "")
                        ssrt = lnChk.split('MAYA_PLUG_IN_PATH')[1]
                        ssrt = ssrt.replace(" ", "")
                        if (not len(ssrt)):
                            li += cpyDestFolder
                        elif (not cpyDestFolder in li):
                            li += ';' + cpyDestFolder
                    li += "\r\n"
                    newAllLines.append(li)
            else:
                newAllLines.append("MAYA_PLUG_IN_PATH = " + cpyDestFolder)
            #write all
            f = open(mayaEnvFilePath, 'w')
            f.writelines(newAllLines)
            f.close()
        else:  #創一個新的
            f = open(mayaEnvFilePath, 'w+')
            f.write("MAYA_PLUG_IN_PATH=" + cpyDestFolder)
            f.close()
示例#43
0
def _getClipBoardFile():
    userPrefDir = cmds.internalVar(userPrefDir=True)
    return os.path.join(userPrefDir, 'ka_clipBoard.p')
def J_CFXWorkFlow_createHairNode(abcNode, hairData, JhairFile, groupNode):
    allCurveGroup = J_CFXWorkFlow_getCurveGroup(abcNode)
    for hairNodeItem in hairData['hairInfo']:
        hairState = 0
        hairSysNode = hairNodeItem['hairNode']
        if cmds.objExists(hairNodeItem['hairNode']):
            if cmds.objectType(hairNodeItem['hairNode']) == 'hairSystem':
                hairState = 1
        hairTranformName = hairNodeItem['hairNode'].replace('Shape',
                                                            '') + '_tr'
        hairSysNodeName = hairNodeItem['hairNode']
        if hairState == 0:
            trNode = cmds.createNode('transform',
                                     name=hairTranformName,
                                     parent=groupNode)
            hairSysNode = cmds.createNode('hairSystem',
                                          name=hairSysNodeName,
                                          parent=trNode)
            for groupItem in allCurveGroup:
                if groupItem.find(hairNodeItem['curveGroup']) > -1:
                    cmds.select(groupItem)
            mel.eval('J_assignHairSystem ' + hairSysNode + ';')
            cmds.connectAttr('time1.outTime', hairSysNode + '.currentTime')
            cmds.select(hairSysNodeName)

            #添加笔刷
            if hairNodeItem['hairBrush'] == 0:
                mel.eval('addPfxToHairSystem;')
            else:
                mel.eval('AssignBrushToHairSystem;')

            presetsPath = cmds.internalVar(
                userPresetsDir=True) + '/attrPresets/hairSystem/'
            if not os.path.exists(presetsPath):
                os.makedirs(presetsPath)
            shutil.copy(
                os.path.dirname(JhairFile) + '/hairPresets/' +
                hairSysNodeName.replace(':', '_') + '.mel', presetsPath)
            mel.eval('applyAttrPreset ' + hairSysNodeName + ' ' +
                     hairSysNodeName.replace(':', '_') + ' 1')
            cmds.setAttr((hairSysNodeName + '.simulationMethod'), 1)
            cmds.setAttr((hairSysNodeName + '.active'), 0)
            os.remove(presetsPath + hairSysNodeName.replace(':', '_') + '.mel')
            #导入材质
            J_CFXWorkFlow_importShader(hairNodeItem, JhairFile, 'mtoa',
                                       'aiHairShader')
            J_CFXWorkFlow_importShader(hairNodeItem, JhairFile, 'redShift',
                                       'rsHairShader')
            J_CFXWorkFlow_importShader(hairNodeItem, JhairFile, 'vray',
                                       'vrayHairShader')
        if hairState == 1:
            findFollicles = cmds.listConnections(hairSysNode,
                                                 type='follicle',
                                                 shapes=True)
            if (None != findFollicles):
                for item2 in findFollicles:
                    # findConnections=cmds.listConnections(item2,plugs=True,type='hairSystem',connections=True,destination=False)
                    # if findConnections is not None:
                    # if cmds.isConnected(findConnections[0],findConnections[1]):
                    # cmds.disconnectAttr(findConnections[0],findConnections[1])
                    # findConnections=cmds.listConnections(item2,plugs=True,type='hairSystem',connections=True,source=False)
                    # if findConnections is not None:
                    # if cmds.isConnected(findConnections[0],findConnections[1]):
                    # cmds.disconnectAttr(findConnections[0],findConnections[1])
                    cmds.setAttr((item2 + '.nodeState'), 2)
            for groupItem in allCurveGroup:
                if groupItem.find(hairNodeItem['curveGroup']) > -1:
                    cmds.select(groupItem)
            mel.eval('assignHairSystem ' + hairSysNode + ';')
            cmds.setAttr((hairSysNodeName + '.simulationMethod'), 1)
            cmds.setAttr((hairSysNodeName + '.active'), 0)
示例#45
0
文件: qt.py 项目: SlipKoR/mlib
            sys.modules[__name__ + '.phonon'] = phonon
        except:
            pass

        QtCore.Signal = QtCore.pyqtSignal
        QtCore.Slot = QtCore.pyqtSlot
        QtCore.Property = QtCore.pyqtProperty

        qt_lib = library
        break

try:
    #Try to load maya...
    import maya.cmds as cmds

    if cmds.internalVar(upd=True) is None:
        raise SystemError('Standalone uninitialized')

    import maya
    import maya.mel as mel
    import maya.OpenMaya as om
    import maya.OpenMayaUI as omUI

    has_maya = True
except (ImportError, SystemError, AttributeError):
    has_maya = False


def loadUiFile(ui_path, appname=None, manage_settings=True):
    """
	Load a designer UI xml file in
示例#46
0
import maya.cmds as cmds
import random

sc = cmds.internalVar(userScriptDir=True)


def tableChaise():

    tablewidthz = cmds.intSliderGrp(slider1, q=True, value=True)
    tableWidthx = cmds.intSliderGrp(slider2, q=True, value=True)
    tableHeight = cmds.intSliderGrp(slider3, q=True, value=True)
    #Roundness = cmds.intSliderGrp(slider4, q=True, value=True)

    #mesa
    table = cmds.polyCube(h=0.7, w=tableWidthx, depth=tablewidthz)
    rtable = cmds.ls(table[0])
    print(rtable)
    cmds.move(0, tableHeight / 2.0 - 0.3, 0)
    cmds.select(str(rtable[0]) + '.e[4:5]')
    cmds.select(str(rtable[0]) + '.e[8:9]', add=True)
    # cmds.select('table.e[4:5]')
    # cmds.select('table.e[8:9]', add=True)
    cmds.polyBevel3(offset=1, segments=3)
    cmds.polyBevel3(rtable[0], offset=0.1)

    #patas

    pataUno = cmds.polyCube(h=tableHeight, w=1, depth=1)
    cmds.move(-tableWidthx / 2.0 + 1, 0, tablewidthz / 2.0 - 1)
    cmds.polyBevel(offset=0.1)
示例#47
0
def main():
    createModFile()
    pluginsPrefsPath = cmds.internalVar(upd=True)+'pluginPrefs.mel'
    enableaPlugin(filename=pluginsPrefsPath)
    createShelfBtn()
示例#48
0
    def testBoundingBox(self):
        '''Test the Object3d bounding box interface.'''

        # Create a simple USD scene.  Default sphere radius is 1, so extents
        # are from (-1, -1, -1) to (1, 1, 1).
        usdFilePath = cmds.internalVar(utd=1) + '/testObject3d.usda'
        stage = Usd.Stage.CreateNew(usdFilePath)
        xform = stage.DefinePrim('/parent', 'Xform')
        sphere = stage.DefinePrim('/parent/sphere', 'Sphere')
        extentAttr = sphere.GetAttribute('extent')
        extent = extentAttr.Get()
        
        assertVectorAlmostEqual(self, extent[0], [-1]*3)
        assertVectorAlmostEqual(self, extent[1], [1]*3)

        # Move the sphere.  Its UFE bounding box should not be affected by
        # transformation hierarchy.
        UsdGeom.XformCommonAPI(xform).SetTranslate((7, 8, 9))

        # Save out the file, and bring it back into Maya under a proxy shape.
        stage.GetRootLayer().Save()

        proxyShape = cmds.createNode('mayaUsdProxyShape')
        cmds.setAttr('mayaUsdProxyShape1.filePath', usdFilePath, type='string')

        # MAYA-101766: loading a stage is done by the proxy shape compute.
        # Because we're a script, no redraw is done, so need to pull explicitly
        # on the outStageData (and simply discard the returned data), to get
        # the proxy shape compute to run, and thus the stage to load.  This
        # should be improved.  Without a loaded stage, UFE item creation
        # fails.  PPT, 31-10-2019.
        outStageData = nameToPlug('mayaUsdProxyShape1.outStageData')
        outStageData.asMDataHandle()

        proxyShapeMayaPath = cmds.ls(proxyShape, long=True)[0]
        proxyShapePathSegment = mayaUtils.createUfePathSegment(
            proxyShapeMayaPath)
        
        #######
        # Create a UFE scene item from the sphere prim.
        spherePathSegment = usdUtils.createUfePathSegment('/parent/sphere')
        spherePath = ufe.Path([proxyShapePathSegment, spherePathSegment])
        sphereItem = ufe.Hierarchy.createItem(spherePath)

        # Get its Object3d interface.
        object3d = ufe.Object3d.object3d(sphereItem)

        # Get its bounding box.
        ufeBBox = object3d.boundingBox()

        # Compare it to known extents.
        assertVectorAlmostEqual(self, ufeBBox.min.vector, [-1]*3)
        assertVectorAlmostEqual(self, ufeBBox.max.vector, [1]*3)

        #######
        # Create a UFE scene item from the parent Xform of the sphere prim.
        parentPathSegment = usdUtils.createUfePathSegment('/parent')
        parentPath = ufe.Path([proxyShapePathSegment, parentPathSegment])
        parentItem = ufe.Hierarchy.createItem(parentPath)

        # Get its Object3d interface.
        parentObject3d = ufe.Object3d.object3d(parentItem)

        # Get its bounding box.
        parentUFEBBox = parentObject3d.boundingBox()

        # Compare it to sphere's extents.
        assertVectorEqual(self, ufeBBox.min.vector, parentUFEBBox.min.vector)
        assertVectorEqual(self, ufeBBox.max.vector, parentUFEBBox.max.vector)


        #######
        # Remove the test file.
        os.remove(usdFilePath)
示例#49
0
def getClassList(config):
    """ Create and return a list of command classes

    Args:
        config (list): List of paths

    Return:
        commandClassList: list of classes

    """

    # Create a single list of module paths
    moduleList = []
    for path in config:
        logger.debug("Module path: %s " % path)
        pathList = getModulePath(path)
        if pathList is not None:
            moduleList.extend(pathList)

    # Create a list of module objects
    moduleObjectList = []
    for path in moduleList:
        m = loadModule(path)
        if m is not None:
            moduleObjectList.append(m)

    # Class only for the reload command
    class Reload(object):
        commandDict = {}

        def _reloadRush(self):
            try:
                cmds.unloadPlugin("Rush.py")
                cmds.loadPlugin("Rush.py")
            except:
                print "Failed to reload plugin"

        commandDict['reloadRush'] = "sphere.png"

    # Crate a list of classes
    commandClassList = [i.Commands for i in moduleObjectList]
    commandClassList.append(Reload)
    logger.debug("All command classes: %s" % str(commandClassList))

    # Create and write a list of all commands for the completer in main plugin
    cmdsDict = {}
    for c in commandClassList:
        module_path = c.__module__

        # Create temp dict for each command to store basic information
        # about the command
        tempDict = {}
        for cmd in c.commandDict:
            command_data = {}
            command_data[cmd] = {}
            command_data[cmd]['icon'] = c.commandDict[cmd]
            command_data[cmd]['path'] = module_path
            tempDict.update(command_data)

        cmdsDict.update(tempDict)

    outPath = os.path.normpath(
        os.path.join(cmds.internalVar(userScriptDir=True), "rushCmds.json"))
    saveCommands(outPath, cmdsDict)

    return commandClassList
示例#50
0
import os
import sys
import site
import maya.cmds as cmds

site.addsitedir(os.path.join(cmds.internalVar(uad=True), 'scripts'))
示例#51
0
import maya.cmds as cmds
示例#52
0
    def __init__(self):

        # logging
        self.logger = epic_logger.EpicLogger()
        self.logger.terminal(on_top=True)  # terminal
        self.start = time.time()

        #get access to our maya tools
        toolsPath = cmds.internalVar(usd=True) + "mayaTools.txt"
        if os.path.exists(toolsPath):

            f = open(toolsPath, 'r')
            self.mayaToolsDir = f.readline()
            f.close()

        self.widgets = {}

        if cmds.window("ART_RetargetTool_UI", exists=True):
            cmds.deleteUI("ART_RetargetTool_UI")

        self.widgets["window"] = cmds.window("ART_RetargetTool_UI",
                                             title="ART FBX Export Batcher",
                                             w=400,
                                             h=500,
                                             sizeable=False,
                                             mnb=False,
                                             mxb=False)

        #main layout
        self.widgets["layout"] = cmds.formLayout(w=400, h=500)

        #textField and browse button
        label = cmds.text(label="Directory to Batch:")

        self.widgets["textField"] = cmds.textField(w=300, text="")
        self.widgets["browse"] = cmds.button(w=70,
                                             label="Browse",
                                             c=self.browse)

        self.widgets["optionalPathCB"] = cmds.checkBox(
            l="Optional Batch Export Path",
            ann=
            "Check this if you want to export all of your files to a single location defined in the text field below."
        )
        self.widgets["ExportPathtextField"] = cmds.textField(
            w=300,
            text="",
            ann=
            "Where do you want to export your files to?  This is optional and only used if the checkbox above is on"
        )
        self.widgets["ExportPathbrowse"] = cmds.button(w=70,
                                                       label="Browse",
                                                       c=self.ExportPathbrowse)

        cmds.formLayout(self.widgets["layout"],
                        edit=True,
                        af=[(label, "left", 10), (label, "top", 10)])
        cmds.formLayout(self.widgets["layout"],
                        edit=True,
                        af=[(self.widgets["textField"], "left", 10),
                            (self.widgets["textField"], "top", 30)])
        cmds.formLayout(self.widgets["layout"],
                        edit=True,
                        af=[(self.widgets["browse"], "right", 10),
                            (self.widgets["browse"], "top", 30)])

        cmds.formLayout(self.widgets["layout"],
                        edit=True,
                        af=[(self.widgets["optionalPathCB"], "left", 10),
                            (self.widgets["optionalPathCB"], "top", 60)])
        cmds.formLayout(self.widgets["layout"],
                        edit=True,
                        af=[(self.widgets["ExportPathtextField"], "left", 10),
                            (self.widgets["ExportPathtextField"], "top", 80)])
        cmds.formLayout(self.widgets["layout"],
                        edit=True,
                        af=[(self.widgets["ExportPathbrowse"], "right", 10),
                            (self.widgets["ExportPathbrowse"], "top", 80)])

        # CUSTOM FILE SCRIPT
        self.widgets["frame"] = cmds.frameLayout(w=380,
                                                 h=100,
                                                 bs="etchedIn",
                                                 cll=False,
                                                 label="Advanced",
                                                 parent=self.widgets["layout"])
        cmds.formLayout(self.widgets["layout"],
                        edit=True,
                        af=[(self.widgets["frame"], "right", 10),
                            (self.widgets["frame"], "top", 110)])
        self.widgets["advancedForm"] = cmds.formLayout(
            w=380, h=100, parent=self.widgets["frame"])

        label2 = cmds.text("Custom File Script:",
                           parent=self.widgets["advancedForm"])
        self.widgets["scriptField"] = cmds.textField(
            w=280, text="", parent=self.widgets["advancedForm"])
        self.widgets["scriptBrowse"] = cmds.button(
            w=70,
            label="Browse",
            c=self.scriptBrowse,
            parent=self.widgets["advancedForm"])

        cmds.formLayout(self.widgets["advancedForm"],
                        edit=True,
                        af=[(label2, "left", 10), (label2, "top", 10)])
        cmds.formLayout(self.widgets["advancedForm"],
                        edit=True,
                        af=[(self.widgets["scriptField"], "left", 10),
                            (self.widgets["scriptField"], "top", 30)])
        cmds.formLayout(self.widgets["advancedForm"],
                        edit=True,
                        af=[(self.widgets["scriptBrowse"], "right", 10),
                            (self.widgets["scriptBrowse"], "top", 30)])

        # EXPORT AN FBX
        self.widgets["exportFBXCB"] = cmds.checkBox(
            label="Export an FBX?", v=True, parent=self.widgets["layout"])
        cmds.formLayout(self.widgets["layout"],
                        edit=True,
                        af=[(self.widgets["exportFBXCB"], "left", 16),
                            (self.widgets["exportFBXCB"], "top", 200)])

        # USE ANIM SEQ INFO
        self.widgets["useSequenceInfo"] = cmds.checkBox(
            label="Use Anim Sequence Info?",
            v=True,
            parent=self.widgets["layout"])
        cmds.formLayout(self.widgets["layout"],
                        edit=True,
                        af=[(self.widgets["useSequenceInfo"], "left", 16),
                            (self.widgets["useSequenceInfo"], "top", 220)])

        # EXPORT MORPHS
        self.widgets["exportMorphs"] = cmds.checkBox(
            label="Export Morphs?", v=True, parent=self.widgets["layout"])
        cmds.formLayout(self.widgets["layout"],
                        edit=True,
                        af=[(self.widgets["exportMorphs"], "left", 16),
                            (self.widgets["exportMorphs"], "top", 240)])

        # REMOVE ROOT ANIM
        self.widgets["removeRoot"] = cmds.checkBox(
            label="Remove root animation?",
            v=False,
            parent=self.widgets["layout"])
        cmds.formLayout(self.widgets["layout"],
                        edit=True,
                        af=[(self.widgets["removeRoot"], "left", 16),
                            (self.widgets["removeRoot"], "top", 260)])

        # DISABLE REDRAW
        self.widgets["disableRedraw"] = cmds.checkBox(
            label="Disable 3D viewport redraw",
            v=True,
            parent=self.widgets["layout"])
        cmds.formLayout(self.widgets["layout"],
                        edit=True,
                        af=[(self.widgets["disableRedraw"], "left", 16),
                            (self.widgets["disableRedraw"], "top", 280)])

        #process button
        self.widgets["process"] = cmds.button(w=380,
                                              h=50,
                                              label="BEGIN BATCH",
                                              c=self.process,
                                              parent=self.widgets["layout"])
        cmds.formLayout(self.widgets["layout"],
                        edit=True,
                        af=[(self.widgets["process"], "left", 10),
                            (self.widgets["process"], "top", 330)])
        cmds.formLayout(self.widgets["layout"],
                        edit=True,
                        af=[(self.widgets["process"], "left", 10),
                            (self.widgets["process"], "bottom", 360)])

        #progress bar
        text = cmds.text(label="File Progress: ",
                         parent=self.widgets["layout"])
        self.widgets["currentFileProgressBar"] = cmds.progressBar(
            w=250, parent=self.widgets["layout"])

        cmds.formLayout(self.widgets["layout"],
                        edit=True,
                        af=[(text, "left", 10), (text, "top", 390)])
        cmds.formLayout(self.widgets["layout"],
                        edit=True,
                        af=[(self.widgets["currentFileProgressBar"], "left",
                             110),
                            (self.widgets["currentFileProgressBar"], "top",
                             390)])

        text2 = cmds.text(label="Total Progress: ",
                          parent=self.widgets["layout"])
        self.widgets["progressBar"] = cmds.progressBar(
            w=250, parent=self.widgets["layout"])

        cmds.formLayout(self.widgets["layout"],
                        edit=True,
                        af=[(text2, "left", 10), (text2, "top", 420)])
        cmds.formLayout(self.widgets["layout"],
                        edit=True,
                        af=[(self.widgets["progressBar"], "left", 110),
                            (self.widgets["progressBar"], "top", 420)])

        #show window
        cmds.showWindow(self.widgets["window"])
示例#53
0
文件: __init__.py 项目: kthulhu/mrv
    # END safe access to variables

    def source_file_safely(script):
        try:
            maya.mel.eval('source "%s"' % script)
        except RuntimeError, e:
            log.error(str(e) + "- ignored")
        # END exception handling

    # END utility

    if not (init_mel | run_user_setup | autoload_plugins):
        return

    import maya.cmds as cmds
    prefsdir = make_path(cmds.internalVar(userPrefDir=1))

    if not prefsdir.isdir():
        log.warn("User Preferences directory did not exist: %s" % prefsdir)
        return
    # END check for existence

    # source actual MEL scripts
    sources = list()
    if init_mel:
        sources.append("createPreferencesOptVars.mel")
        sources.append("createGlobalOptVars.mel")
        sources.append(prefsdir + "/userPrefs.mel")
    # END option vars

    if autoload_plugins:
示例#54
0
def delete_layout(*args):
    userDir = cmds.internalVar(upd=True) + "frogger_fileManagerLayout.txt"
    if os.path.isfile(userDir):
        os.remove(userDir)
        print "Deleted saved layout for fileManager"
def J_CFXWorkFlow_hairOut():
    #创建缓存路径
    filePath = cmds.file(query=True, sceneName=True).replace(
        cmds.file(query=True, sceneName=True, shortName=True), '')
    cacheFileName = cmds.file(query=True, sceneName=True, shortName=True)[0:-3]
    if os.path.exists(filePath + cacheFileName + '_cache'):
        shutil.rmtree(filePath + cacheFileName + '_cache')
    os.makedirs(filePath + cacheFileName + '_cache')
    os.makedirs(filePath + cacheFileName + '_cache/presets/')
    os.makedirs(filePath + cacheFileName + '_cache/shaders/')

    #创建缓存路径
    #创建json文件记录节点信息
    outFile = open(
        (filePath + cacheFileName + '_cache/' + cacheFileName + '.jHair'), 'w')
    exportMaFile = filePath + cacheFileName + '_cache/' + cacheFileName + '.ma'
    hairData = {'hairInfo': []}
    curveGroups = []

    #abc输出
    runAbcString = 'AbcExport -j "-frameRange ' + str(
        cmds.playbackOptions(query=True, minTime=True)) + ' ' + str(
            cmds.playbackOptions(query=True,
                                 maxTime=True)) + ' -uvWrite -dataFormat hdf '
    #整理缓存节点
    mel.eval('convertHairSelection "hairSystems";')
    allHairNodes = cmds.ls(sl=True, type='hairSystem')
    if len(allHairNodes) < 1:
        cmds.confirmDialog(title=u'错误',
                           message=u'   未选中毛发节点        ',
                           button='666')
        return 'noHair'
    #场控帧速率
    hairData['currentUnit'] = cmds.currentUnit(query=True, time=True)

    for item in allHairNodes:
        newOutCurveGroup = item.replace(':', '_') + '_outCurve'
        while cmds.objExists(newOutCurveGroup):
            try:
                cmds.delete(newOutCurveGroup)
            except:
                newOutCurveGroup = newOutCurveGroup + '0'
        cmds.createNode('transform', name=newOutCurveGroup)
        follicleNodes = cmds.listConnections(item,
                                             type='follicle',
                                             destination=False,
                                             shapes=True)
        currentHairMessage = {'hairNode': '', 'curveGroup': '', 'shader': {}}
        if follicleNodes is not None:
            #生成输出曲线
            for follicleItem in follicleNodes:
                createOutCurveNode(item, follicleItem, newOutCurveGroup)
            #保存预设
            userPreFile = cmds.internalVar(
                userPresetsDir=True
            ) + 'attrPresets/hairSystem/' + item.replace(':',
                                                         '_') + '.mel'  #栓出原有预设
            if os.path.exists(userPreFile):
                os.remove(userPreFile)
            presetsPath = mel.eval('saveAttrPreset("' + item + '","' +
                                   item.replace(':', '_') + '",0)')
            if os.path.exists(filePath + cacheFileName + '_cache/presets/' +
                              item.replace(':', '_') + '.mel'):
                os.remove(filePath + cacheFileName + '_cache/presets/' +
                          item.replace(':', '_') + '.mel')
            shutil.move(presetsPath,
                        (filePath + cacheFileName + '_cache/presets/'))
            #输出abc
            if follicleNodes.count > 0:
                currentHairMessage['hairNode'] = item
                currentHairMessage['curveGroup'] = newOutCurveGroup
                curveGroups.append(newOutCurveGroup)
                #导出材质
                currentHairMessage['shader'] = J_exportHairShader(
                    filePath + cacheFileName + '_cache/shaders/', item)
                #导出材质
                hairData['hairInfo'].append(currentHairMessage)
                runAbcString += ' -root ' + newOutCurveGroup
        else:
            print('warning:%s has 0 follicle' % (item))

    outFile.write(json.dumps(hairData, encoding='utf-8', ensure_ascii=False))
    outFile.close()
    runAbcString += ' -file ' + filePath + cacheFileName + '_cache/' + cacheFileName + '_Hair.abc"'
    mel.eval(runAbcString)
示例#56
0
    def addToPath(path):
        import PMP.sysUtils
        return PMP.sysUtils.addToPath(path, verbose=VERBOSE)

    import maya.cmds as cmds
    from maya.cmds import *
    # So that standard python builtins, like 'open', are preserved
    from __builtin__ import *
    import maya.mel as mel
    from maya.mel import eval as meval
    import maya.OpenMaya as api

    # If executed by a normal maya startup, __file__ will not be defined...
    # ...but in that case, cmds.internalVar(userScriptDir=1) should work
    try:
        _thisModuleDir = cmds.internalVar(userScriptDir=1)
    except:
        _thisModuleDir = os.path.dirname(__file__)
    _thisModuleDir = os.path.realpath(_thisModuleDir)

    eclipseProjects = (os.path.join('pymelProject', 'pymel'),
                       os.path.join('pymelProject', 'pymel', 'tests'),
                       os.path.join('abxPickerProject', 'abxPicker'),
                       os.path.join('heatWeightProject',
                                    'src'), os.path.join('TempScripts', 'src'))
    # workspaces = (r"C:\Dev\Projects\eclipse\workspace",
    #               os.path.join(os.environ['USB_ROOT'], "HomeMirror", "iAudioApps", "eclipse", "workspace"))
    workspaces = [
        os.path.join(os.environ['PAUL_C_DRIVE'],
                     *("Dev/Projects/eclipse/workspace".split('/')))
    ]
示例#57
0
from PySide import QtGui as qg
from shiboken import wrapInstance as wrapI
import maya.cmds as cmds
import maya.OpenMaya as om
import maya.OpenMayaUI as omui
import os
from PySide.QtGui import QPen, QColor, QBrush, QLinearGradient

try:
    import maya.utils as utils
except:
    pass

#---------------------------------------------------------------------------------#
GlobalTweener = None
styleSheetLocation = os.path.join(cmds.internalVar(usd=1),
                                  'HitchAnimationModule', 'Tools', 'Tweener',
                                  'styleSheets', 'scheme.txt')
windowTitle = "AnimationTweener"
windowObject = "AnimationTweener"

print(styleSheetLocation)


#---------------------------------------------------------------------------------#
def deleteFromGlobal():
    mayaMainWindowPtr = omui.MQtUtil.mainWindow()
    mayaMainWindow = wrapI(
        long(mayaMainWindowPtr),
        qg.QMainWindow)  # Important that it's QMainWindow, and not QWidget
    # Go through main window's children to find any previous instances
示例#58
0
    cmds.group(n='IK_GRP')

    cmds.group('COG', 'COG_GRP', 'IK_GRP', n="RdM_AutoSPINE")
    cmds.select('Spine_1', hi=True)
    cmds.select('Spine_' + str(jointsNum), tgl=True)
    cmds.select('ReverseSpine_JJ', tgl=True)

    cmds.sets(n='BindThisToSpine')

    cmds.rename('Spine_' + str(jointsNum), 'Spine_ConnectToArms')

    cmds.select(cl=True)


#ImagesPaths
imagePath = cmds.internalVar(usd=True)
Path = imagePath + 'RdMTools/'
Icons = Path + 'icons/'

#Window

cmds.window("AutoSpine", width=250, title="AutoSpine", toolbox=True)
cmds.columnLayout(adjustableColumn=True)
cmds.separator(h=20)
locatorNum = cmds.intSliderGrp(l='Spine joints: ',
                               min=3,
                               max=10,
                               field=True,
                               v=5,
                               hlc=(0.8, 0.2, 0.5))
cmds.separator(h=10)
示例#59
0
    mc.rename(item,new_name+str(idx +1).zfill(4)) #新名字添加序列从1开始,.zfill(4)4位0001


mc.rename('item_####_grp',mc.ls(ls=True),10) #''命名格式,选择的物体,起始数字(待确认)

s=['S3_E11_Sc06_Cam003_Cam_s823e851.fbx']
''.join(s) #Result: S3_E11_Sc06_Cam003_Cam_s823e851.fbx

f='S:\QSJResources\Shot\GodGunStory\S3_E11\\'
f.replace('\\', '/') #Result: S:/QSJResources/Shot/GodGunStory/S3_E11/


allCam = mc.ls(long = True,type = "camera") #列出所有摄像机
allCam.sort(key=len, reverse=True) #按名称长度排列
renderCam = allCam[0].split('|')[1] #字符串按照|拆分开,并取第二位
renderCam2=''.join(renderCam) #连接每个字符串''中指定以什么方式连接(-,:,|)等

children = mc.listRelatives(obj,children=True, fullPath=True) or [] #获得物体的shape节点

maya_renderer = "%s/bin/Render.exe" % os.getenv("MAYA_LOCATION").replace('\\', '/')
#Result: C:/Program Files/Autodesk/Maya2016/bin/Render.exe

mc.internalVar(userAppDir=True)
# Result: u'C:/Users/Administrator/Documents/maya/'

pm.workspace.getcwd() #新
pm.workspace(query=1, dir=1) #老
# 获取当前文件所在目录,maya中会返回 Result: Path('D:/') ,转成str()可以去除u,Path等字符

mc.file(q=True, sn=1, shn=1) #获取当前maya的文件名
示例#60
0
import maya.cmds as cmds
import maya.mel as mel
import pymel.core as pymel

import os
import pickle

CLIPBOARD_FILE = os.path.join(cmds.internalVar(userPrefDir=True),
                              'ka_clipBoard.p')


def add(key, pyObject):
    """
    Adds item to the clipboard.

    Args:
        key (string): the key for the item being added to the clipBoardDict

        pyObject (object): item to be stored
    """

    clipBoardData = _getClipBoardData()
    clipBoardData[key] = pyObject
    pickle.dump(clipBoardData, open(_getClipBoardFile(), "wb"))
    return pyObject


def get(key, defaultValue=None):
    """
    Gets item from the clipboard.