def projSetAndOpenFile(self, projName, *args): global projRoot global workTypeId projPath = projRoot + '/' + projName + '/03-cg' workPath = projPath + '/' + ['1-scenes', '1-shots'][workTypeId - 1] if cmds.file(workPath, q= 1, ex= 1): hasMayaScene = 0 setProject = 0 for root, dirs, files in os.walk(workPath): for file in files: if file.endswith(".ma") or file.endswith(".mb"): hasMayaScene = 1 if hasMayaScene: fileName = cmds.fileDialog2(dir= (workPath), dialogStyle=2, fm=1) if fileName: setProject = 1 cmds.file(mf= 0) cmds.file(fileName[0], open= 1) print 'file opened.' cmds.deleteUI('ProjectLoader') if cmds.window('ProjectLoader', ex= 1) else None else: setProject = 1 if setProject: mel.eval('setProject \"' + projPath + '\"') cmds.workspace(fr= ['images', projPath.replace('1-project', '2-Render')]) cmds.workspace(fr= ['movie', projPath.replace('1-project', '2-Render')]) mel.eval('projectWindow;') # create project folders mel.eval('np_editCurrentProjectCallback;') # create project folders print 'project setted.' cmds.deleteUI('ProjectLoader') if cmds.window('ProjectLoader', ex= 1) else None else: sorryStr = 'Dose not exist \n' + workPath cmds.confirmDialog( title='Sorry', message=sorryStr, button=['Confirm'], defaultButton='Confirm', icon= 'information')
def __init__(self, intWinName, visWinName, buttonLabel): super(Key_RenderLauncher, self).__init__(intWinName, visWinName, buttonLabel) self.renderPathWin = 'key_SetRenderPath' self.rlPathTxtFld = self.intWinName + '_rlPathTxtFld' self.rlPathForm = self.intWinName + '_rlForm' self.rlBrwsPathBut = self.intWinName + '_rlBrwsPathBut' self.rlRenderBut = self.intWinName + '_rlRenderBut' self.advXfld = self.intWinName + 'rlAdvXFld' self.advYfld = self.intWinName + 'rlAdvYFld' self.advEndSubDCb = self.intWinName + '_advEndSubDCb' self.cpuIntFld = self.intWinName + '_cpuIntFld' self.subRndrLyrCB = self.intWinName + '_subRndrLyrCB' self.xDivisions = 2 self.yDivisions = 2 self.subdivide = False self.outputname = None self.outputpath = None # get the current working images directory self.currentWorkspace = os.path.realpath(cmds.workspace(query=True, rd=True)) self.currentImagePath = cmds.workspace(rte='images') self.imageFilePrefix = cmds.getAttr('defaultRenderGlobals.imageFilePrefix') self.uncompressedTifCb = self.intWinName + '_rl_uncompTifCb' self.render_exrCB = None version = mm.eval('getApplicationVersionAsFloat()') if version == 2011.0: self.renderer = 'maya2011' elif version == 2012.0: self.renderer = 'maya2012' else: self.renderer = 'maya2009' self.renderers = ['maya2009', 'maya2011', 'maya2012']
def get_texture_source_folder(alt_path=None): """ Return texture source folder :param alt_path: """ texture_source_folder = MTTSettings.TEXTURE_SOURCE_FOLDER if WS_KEY in MTTSettings.TEXTURE_SOURCE_FOLDER: ws = cmds.workspace(query=True, rootDirectory=True) texture_source_folder = MTTSettings.TEXTURE_SOURCE_FOLDER.replace(WS_KEY, ws) texture_source_folder = os.path.normpath(texture_source_folder) if not os.path.isdir(texture_source_folder): # if default folder not found, try in sourceimages folder if WS_KEY in MTTSettings.TEXTURE_SOURCE_FOLDER and alt_path: texture_source_folder = MTTSettings.TEXTURE_SOURCE_FOLDER.replace(WS_KEY, alt_path) texture_source_folder = os.path.normpath(texture_source_folder) if not os.path.isdir(texture_source_folder): # if another location doesn't exists, return workspace root texture_source_folder = cmds.workspace(q=1, rootDirectory=True) msg = ( 'You should change "textureSourceFolder" folder ' 'in mtt.json file') mtt_log(msg, msg_type='warning', verbose=False) return os.path.normpath(texture_source_folder)
def imgpath(img): imgfile = img.split("/")[-1] workspacepath = cmds.workspace(q=True,dir=True) imgfolder = cmds.workspace("images",q=True,fre=True) imgfullpath = os.path.join(workspacepath,imgfolder,imgfile) imgfullpath = fixpath(imgfullpath) return imgfullpath
def collect_playblasts(self, parent_item, project_root): """ Creates items for quicktime playblasts. Looks for a 'project_root' property on the parent item, and if such exists, look for movie files in a 'movies' subfolder. :param parent_item: Parent Item instance :param str project_root: The maya project root to search for playblasts """ movie_dir_name = None # try to query the file rule folder name for movies. This will give # us the directory name set for the project where movies will be # written if "movie" in cmds.workspace(fileRuleList=True): # this could return an empty string movie_dir_name = cmds.workspace(fileRuleEntry='movie') if not movie_dir_name: # fall back to the default movie_dir_name = "movies" # ensure the movies dir exists movies_dir = os.path.join(project_root, movie_dir_name) if not os.path.exists(movies_dir): return self.logger.info( "Processing movies folder: %s" % (movies_dir,), extra={ "action_show_folder": { "path": movies_dir } } ) # look for movie files in the movies folder for filename in os.listdir(movies_dir): # do some early pre-processing to ensure the file is of the right # type. use the base class item info method to see what the item # type would be. item_info = self._get_item_info(filename) if item_info["item_type"] != "file.video": continue movie_path = os.path.join(movies_dir, filename) # allow the base class to collect and create the item. it knows how # to handle movie files item = super(MayaSessionCollector, self)._collect_file( parent_item, movie_path ) # the item has been created. update the display name to include # the an indication of what it is and why it was collected item.name = "%s (%s)" % (item.name, "playblast")
def blastDir(forceTemp=False, brackets=False): ''' forceTemp = use get default function to force a specified location, otherwise standard maya locations are used ''' if not forceTemp: if os.name == 'nt': project = cmds.workspace(q=True, rd=True) scene = sceneName(full=True) if project in scene: if brackets: if '(' in project or ')' in project: project = project.replace('(', '__') project = project.replace(')', '__') # print project return project + 'movies/' else: message('Project likely not set', maya=True) return None # print project # print scene elif os.name == 'posix': project = cmds.workspace(q=True, rd=True).split('scenes/')[0] scene = sceneName(full=True) if project in scene: return project + 'movies/' else: message('Project likely not set', maya=True) # print None, '____' return None # print project, 'here' # print scene, 'here' else: return getPath() else: return getPath()
def win(*args): '''Window used to update the mesh ''' #if any windows are open that deal with updating the mesh, close them winList=['atom_meshUpdateWin', 'keyMeshdirDialogWin'] for win in winList: if cmds.window(win, ex=True): cmds.deleteUI(win) #create the window cmds.window('atom_meshUpdateWin', title = 'Atom Mesh Update') cmds.columnLayout(co=['both',5],adj=True, rs=5) path = os.path.join(cmds.workspace(query=True, o=True), 'scenes/anim/template_rig/CharactersWork/SantaPup/RIG/mesh_update_info') button_state = True #Test if the mesh_update_folder is the current path, this will usually be false if os.path.exists(path) != True: print path path = cmds.workspace(query=True, o=True) button_state=False print 'mesh_update_info folder not found. Browse to folder to continue.' cmds.textFieldButtonGrp('atom_meshUpdatePath_tfbg', label='Path:', tx=path, buttonLabel='Set Path', ct3=['left','both','left'], co3=[0,0,5],cl3=['left', 'center', 'center'], ad3=2, cw3=[35,100,80], bc='from atom import atom_updateMesh_lib\natom_updateMesh_lib.dirDialog()') cmds.button('atom_meshUpdate_button',l='Update Mesh', c ='from atom import atom_updateMesh_lib\natom_updateMesh_lib.updateMeshCMD()', en=button_state ) cmds.scriptJob(runOnce=True,uid=['atom_meshUpdateWin', 'from atom import atom_updateMesh_lib\natom_updateMesh_lib.deleteDirDialog()']) cmds.showWindow('atom_meshUpdateWin')
def _getFile(self,index): if self.__mode == 'save': file = QtGui.QFileDialog.getSaveFileName(self, 'save', str(cmds.workspace(q = True, dir = True)), self.__filter) else: file = QtGui.QFileDialog.getSaveFileName(self, 'save', str(cmds.workspace(q = True, dir = True)), self.__filter) self.setText(str(file))
def hw(*args, **kwargs): t0 = float(time.time()) try: verbose = kwargs["verbose"] except KeyError: verbose = False if cmds.optionVar(exists="checkmateVerbosity"): verbose = cmds.optionVar(query="checkmateVerbosity") else: pass scenefilename = cmds.file(query=True, sn=True, shn=True) root, ext = os.path.splitext(scenefilename) fullscenepath = cmds.file(query=True, sn=True, shn=False) fullscenedirname = os.path.dirname(fullscenepath) reportname = "".join([root, ext.replace(".", "_")]) img_dir = os.path.join(fullscenedirname, reportname) print "save HW rendered images to : %s" % img_dir # before we render, save render globals presets cmds.nodePreset(save=("defaultRenderQuality", "ttRestorePreviousDefaultRenderViewPreset")) cmds.nodePreset(save=("defaultRenderGlobals", "ttRestorePreviousDefaultRenderViewPreset")) cmds.nodePreset(save=("defaultResolution", "ttRestorePreviousDefaultRenderViewPreset")) # override the user settings cmds.setAttr("defaultRenderGlobals.imageFormat", 32) ext = ".png" # set resolution ot 320x240 cmds.setAttr("defaultResolution.width", 640) cmds.setAttr("defaultResolution.height", 480) cmds.setAttr("defaultResolution.deviceAspectRatio", (float(320) / float(240))) # set file format to png cmds.setAttr("defaultRenderGlobals.imageFormat", 32) ext = ".png" cmds.setAttr("defaultRenderGlobals.outFormatControl", 0) # default name.ext cmds.setAttr("defaultRenderGlobals.animation", False) # cmds.setAttr('defaultRenderGlobals.imageFilePrefix', "../<Camera>", type="string") cmds.setAttr("defaultRenderGlobals.imageFilePrefix", "<Camera>", type="string") cmds.workspace(fileRule=["images", img_dir]) print "save rendered images to : %s" % img_dir cmds.hwRender(currentFrame=True, cam="top", edgeAntiAliasing=[2, 4], fullRenderSupport=True) cmds.hwRender(currentFrame=True, cam="persp", edgeAntiAliasing=[2, 16], fullRenderSupport=True) cmds.hwRender(currentFrame=True, cam="front", edgeAntiAliasing=[2, 16], fullRenderSupport=True) cmds.hwRender(currentFrame=True, cam="side", edgeAntiAliasing=[2, 16], fullRenderSupport=True) # move rendererd images from the default project images dir to the report dir sourcedir = os.path.join(cmds.workspace(q=True, rd=True), cmds.workspace(fileRuleEntry="images")) targetdir = img_dir print "from : ", sourcedir print "to : ", targetdir # for img in ['side.png', 'front.png', 'persp.png', 'top.png'] : # os.rename(os.path.join(sourcedir, img), os.path.join(targetdir, img)) print "%-24s : %.6f seconds" % ("render.hw()", (float(time.time()) - t0)) return img_dir
def browse(folder,*args): if folder=='renderFolder': mc.textField(str(folder),edit=1,text=mc.fileDialog2(ds=2,dir=os.path.join(mc.workspace(q=1,rd=1),'scenes'),fm=3,okc="Set",cc="Cancel")[0].split('/')[-1]) else: mc.textField(str(folder),edit=1,text=mc.fileDialog2(ds=2,dir=os.path.join(mc.workspace(q=1,rd=1),'scenes'),fm=3,okc="Set",cc="Cancel")[0]) commitUI() UI()
def _export_ass(self): import mtoa.cmds.arnoldRender as ar filePath=cmds.file(q=True,sn=True) #getting fields for version shot_temp=self.parent.sgtk.templates["maya_shot_work"] shotgunFields=shot_temp.get_fields(filePath) #getting output path area_temp=self.parent.sgtk.templates['maya_ass_export_area'] path=area_temp.apply_fields(shotgunFields).replace('\\','/') #setting ass export path cmds.workspace(fileRule = ['ASS', path]) #account for renderlayers for layer in cmds.ls(type='renderLayer'): #discarding referenced layers if ':' not in layer: #checking whether layer needs to be rendered if cmds.getAttr(layer+'.renderable')==1: cmds.editRenderLayerGlobals( currentRenderLayer=layer ) try: ar.arnoldBatchRender('') except Exception, e: raise TankError("Failed to export Ass files: %s" % e)
def select_file(self): """ Maya Open Dialog to select file texture """ self.open_dialog_visible = True if MTTSettings.value('browserFirstStart'): image_dir = cmds.optionVar(query='MTT_browserStartFolder') else: image_dir = cmds.workspace(query=True, rootDirectory=True) + cmds.workspace( fileRuleEntry='sourceImages') MTTSettings.set_value('browserFirstStart', True) file_path = cmds.fileDialog2(fileMode=1, startingDirectory=image_dir, caption='Select a texture', okCaption='Select') if file_path: new_path = file_path[0] cmds.optionVar( sv=['MTT_browserStartFolder', os.path.dirname(new_path)]) if MTTSettings.value('forceRelativePath'): new_path = convert_to_relative_path(new_path) # relative_path = workspace(projectPath=new_path) # if relative_path != new_path: # new_path = '/%s' % relative_path self.line_edit.setText(new_path) self.open_dialog_visible = False self.close() self.editingFinished.emit() cmds.showWindow(WINDOW_NAME)
def setProject(self): """ Option: 'project' = Set maya project """ if self.options['project'] is None: self.log("\tUse current project.") else: self.log("\tOption 'project' detected: %s" % self.options['project']) mc.workspace(self.options['project'], o=True) mc.workspace(dir=self.options['project'])
def getDirRules(self): """ """ ruleDict = {} for rule in cmds.workspace(q= 1, frl= 1): ruleDict[rule] = cmds.workspace(rule, q= 1, fre= 1) return ruleDict
def getSourceImagesDir(): sourceImagesRule = cmds.workspace('sourceImages', query=True, fileRuleEntry=True) if sourceImagesRule != None: sourceImagesRule = sourceImagesRule.split(';') ret = [] for rule in sourceImagesRule: ret.append(cmds.workspace(expandName=rule)) return ret else: return [cmds.workspace(expandName='sourceimages')]
def findWorkSpace(set=False): ws='' d=os.path.dirname(mc.file(q=True,loc=True)) while ws=='' and d!=os.path.dirname(d): if 'workspace.mel' in iterable(os.listdir(d)): ws=d else: d=os.path.dirname(d) if set: mc.workspace(ws,o=True) return ws
def rlmAttrs():#custom renderLayerManager Attributes for tools using customAttr class rlm=customAttr('renderLayerManager') rlm.define('project',mc.workspace(q=1,rd=1)) rlm.define('shotName','SH01') rlm.define('enableAbsoluteRenderFolder',False) rlm.define('absoluteRenderFolder',os.path.join(mc.workspace(q=1,rd=1),'scenes')) rlm.define('enablePrefixRenderLayer',False) rlm.define('prefixRenderLayer','L') rlm.define('enableSingleFileName',False) rlm.define('singleFileName','custom') rlm.define('notes',' ')
def quick_set_proj(): ''' Sets the project to where the current file is located. ''' scene_path = cmds.file(q=True, sn=True) base_path = os.path.split(scene_path) # Setting Project and workspace # Find out how workspace and setting parent differ. mel.eval('setProject("%s")' % base_path[0]) cmds.workspace(dir=base_path[0])
def getProjectPath(self): #---------------------------- self.project_name = mc.workspace(q=True, sn=True) self.project_path = mc.workspace(q=True, fn=True) #- self.btn_getProject.setText(self.project_name) #---------------------------- self.tableModel.clear() for d in os.listdir(self.project_path): self.tableModel.insertRow([d, '']) self.tableView.openPersistentEditor(self.tableModel.index(self.tableModel.rowCount() - 1, 1)) self.tableView.setRowHeight(self.tableModel.rowCount() - 1, 25)
def process(self, context): workspace = cmds.workspace(rootDirectory=True, query=True) if not workspace: # Project has not been set. Files will # instead end up next to the working file. workspace = cmds.workspace(dir=True, query=True) # Maya returns forward-slashes by default normalised = os.path.normpath(workspace) context.set_data('workspace_dir', value=normalised) yield None, None
def _setAssetWorkspace(self, step = ''): """ Sets the workspace to the currently selected """ getItems = self._getCurrentAssetIndex() if getItems: for key, var in getItems.items(): finalPath = r'%s\assets\%s\%s\%s\work\maya' % (self.rootFolder, key, var, step) print finalPath.replace('\\', '/') try: cmds.workspace(finalPath.replace('\\', '/'), openWorkspace = True) except RuntimeError: cmds.warning('Path does not exist...')
def workspaceToDict(): """ Store workspace info to dict :return: Workspace info :rtype: dict """ wsDict = {'projectName': mc.workspace(q=True, fn=True).split('/')[-1], 'projectPath': mc.workspace(q=True, fn=True), 'fileRules': {}} fr = mc.workspace(q=True, fr=True) for n in range(0, len(fr), 2): wsDict['fileRules'][fr[n]] = fr[n+1] return wsDict
def SaveXMLFile(self): #fileDialog = QFileDialog(self.getMayaWindow()) #fileDialog.setAcceptMode(QFileDialog.AcceptSave) #fileDialog.fileSelected.connect(self.WriteXMLToFile) #fileDialog.show() #def WriteXMLToFile(self,fileName): rigNodeFound = False try: rigGuiNode = self.scene.sceneNodes["Rig"] rigNodeFound = True except KeyError: rigNodeFound = False try: mel.eval('error \"Rig Node Editor: No rig network exists to write to file.\";') except: return if rigNodeFound: rootElem = self.recursiveGetXML(rigGuiNode,True) rigName = rootElem.get('name') #define the most current rig definition file name and the rig definition folder #for older versions fileName = cmds.workspace(q=True,rd=True) + "rigDefinitions/" + rigName + ".xml" fileDirectory = cmds.workspace(q=True,rd=True) + "rigDefinitions/" + rigName + "/" currentFileExists = os.path.isfile(fileName) archiveFolderExists = os.path.isdir(fileDirectory) archiveFilesExist = False if archiveFolderExists: archiveFilesExist = len(os.listdir(fileDirectory)) > 0 versionExists = False versionFile = None #check archive file names to see if version already exists if archiveFilesExist: saveVersion = rootElem.get('version') versionSearchString = re.sub('\.','_',saveVersion) for file in os.listdir(fileDirectory): if versionSearchString in file: versionExists = True versionFile = file #check most recently saved file to see if version exists if currentFileExists: tree = xml.ElementTree() tree.parse(fileName) rigElem = tree.getroot() lastVersion = rigElem.get('version') saveVersion = rootElem.get('version') if lastVersion == saveVersion: versionExists = True versionFile = fileName self.FileSave(currentFileExists, archiveFolderExists, versionExists, versionFile, fileName, fileDirectory,rootElem)
def initialize(self): self.register("New Scene", self.newScene) self.register("Pre-Build", self.preBuild) self.register("Build", self.build) self.register("Post-Build", self.postBuild) self.register("Utils", ml_node.MlNode("utils")) self.register("Export Controls", self.exportControls, "utils", directory=str(cmds.workspace(q=True, dir=True))) self.register("Export Joints", self.exportJoints, "utils", directory=str(cmds.workspace(q=True, dir=True))) self.register("Mirror", self.mirror, "utils", side=common.LEFT) for node in ["exportControls", "exportJoints"]: self.getNodeByName(node).getAttributeByName("directory").setAttrType("dir") return True
def setProject(*args): #set the project to the value in the TFBG path = cmds.textFieldButtonGrp("TFBG", q=True, tx=True) if path: if os.path.isdir(path): mel.eval("setProject \""+path+"\"") cmds.workspace(q=True, fn=True) #closeUI cmds.deleteUI("projectWin") cmds.warning("You've set the the current project to: %s"%path) else: cmds.warning("The location in the text field doesn't exist! Try browsing using the button on the right!") else: cmds.warning("You haven't selected a path for the project folder!")
def saveFileDialog(self, *args): self.scenepath = os.path.join(cmds.workspace(q=True, rd=True), 'scenes') path = self.findPathFromName() if path == None: if os.path.exists(self.scenepath): print 'Defaulting to workspace /scenes' path = self.scenepath else: print 'Folder does not exist for filename, defaulting to workspace.' path = cmds.workspace(q=True, rd=True) SaveWin = SaveDialogue(self.SaveDialogue, 'Browse To Directory', 'S A V E', path, self) SaveWin.win()
def workspace_path(workspace=None): # Getter. if workspace is None: # TODO: get entities via memory, or scene info, and then finally take it # from the workspace. Prompt the user if there is more than one. return cmds.workspace(q=True, rootDirectory=True) or os.path.join(os.getcwd(), 'maya') # Setter: we try really hard to set the workspace. os.chdir(workspace) cmds.workspace(workspace, openWorkspace=True) cmds.workspace(dir=workspace) mel.eval('addRecentProject("%s");' % workspace) print '# Workspace set to:', workspace
def on_change_root_path(self, current_path): if current_path == SOURCEIMAGES_TAG: current_path = os.path.join( cmds.workspace(query=True, rootDirectory=True), cmds.workspace(fileRuleEntry='sourceImages') ) self.files_model.setRootPath(current_path) self.files_list.setRootIndex(self.files_model.index(current_path)) if self.path_edit: self.path_edit.setText(current_path) if self.parent_folder_btn: current_dir = QDir(current_path) self.parent_folder_btn.setEnabled(current_dir.cdUp())
def SundayAssetExportOptionsCurrentAssetDirectory(): currentAssetPath = cmds.workspace(q = True, rootDirectory = True) + cmds.workspace(fileRuleEntry = 'templates') + os.sep if platform.system() == 'Windows': subprocess.Popen([ 'explorer', currentAssetPath]) elif platform.system() == 'Linux': subprocess.call([ 'xdg-open', currentAssetPath]) else: subprocess.call([ 'open', '-R', currentAssetPath])
def __init__(self): # Initialize character type:name dictionary self.characters = { 'Humans' : ['Tom', 'Vincent', 'Joe', 'Bob', 'George', 'Ernest'], 'Pigeons': ['Rocky', 'Raggedy', 'Scrawny', 'Longbeak', 'Heavy', 'Boxy'] } # Path to current scene file scene_path = cmds.file(q=True, sceneName=True) # Try to extract sequence and shot number from maya scene name self.sequence, self.shot = utils.extract_context(scene_path) # If utils.extract_context failed set fields empty if self.sequence <= 0: self.sequence, self.shot = '', '' # Directory from which this script run # Can differ from the script location # in case when run from shortcut or command line self.cwd = os.getcwd().replace('\\', '/') # Project root directory self.project_path = cmds.workspace(q=True, rootDirectory=True) # Directory of this script self.app_dir = os.path.dirname(os.path.realpath(__file__)).replace("\\","/") # Define important file loacation with respect to project root self.envStr = 'Assets/Env/Master/env.ma' self.lightStr = 'Assets/Env/Light/light.ma' # Initilize UI self.ui()
def save(): # type: () -> NoReturn _cmds.workspace(saveWorkspace=True)
def expand_name(path): # type: (str) -> str return _cmds.workspace(expandName=path)
def update(): # type: () -> NoReturn _cmds.workspace(update=True)
import maya.cmds as cmds import sgtk projectPath = cmds.workspace(q=True, fullName=True) tk = sgtk.sgtk_from_path(projectPath) ctx = tk.context_from_path(projectPath) sg = tk.shotgun def getLatestShotFile(tk, ctx, publishedType=None, filetag=None, step=None): #return variable result = [] shot = sg.find_one('Shot', filters=[['id', 'is', ctx.entity['id']]]) #getting tank data tankfiles = sg.find('PublishedFile', filters=[['entity', 'is', shot]], fields=[ 'version_number', 'task', 'path', 'published_file_type', 'name', 'sg_step' ]) publishFiles = {} abcFiles = [] if publishedType and step: for f in tankfiles: if f['sg_step'] == step: if f['published_file_type']['name'] == publishedType:
def __entry(cls, entry, key, default_value): # type: (type, str, str, str) -> Any kwargs = {'{}Entry'.format(entry): key} value = _cmds.workspace(**kwargs) or default_value return cls(key, value)
def create(directory_path): # type: (str) -> NoReturn return _cmds.workspace(directory_path, newWorkspace=True)
import os import getpass,socket from stat import S_IREAD, S_IWRITE from datetime import date import maya.cmds as cmds import os.path projectDirectory = cmds.workspace(q=True, rd=True) report_path = projectDirectory.replace('/','\\') + '\\report.txt' vaccine_file_path = 'C:\\Users\\{}\\Documents\\maya\\scripts'.format(getpass.getuser()) def lock_file(vaccine_py,user_py): print('.............................................7') if os.path.isfile(vaccine_py): os.chmod(vaccine_py, S_IWRITE) os.unlink(vaccine_py) if os.path.isfile(user_py): os.chmod(user_py, S_IWRITE) os.unlink(user_py) open(vaccine_py, "w") open(user_py, 'w') os.chmod(vaccine_py, S_IREAD) os.chmod(user_py, S_IREAD) def scan(path): vaccine_pyc = path + '\\vaccine.pyc' vaccine_py = path + '\\vaccine.py' user_py = path + '\\userSetup.py' if not os.path.isdir(path): os.mkdir(path) lock_file(vaccine_py, user_py) return "Vaccine files not found. Patch succeeded" if not os.path.exists(vaccine_py):
def renderScene(self, sceneFileName, renderDir, PBRTPath, oiiotoolPath, pbrtDir, keepTempFiles, geometryFiles, animation=False, frame=1, verboseRender=0, verboseExport=False, renderSettings=None, commandLineParameters=None): projectDir = cmds.workspace(q=True, fn=True) imageDir = os.path.join(projectDir, "images") os.chdir(imageDir) sceneName = self.getScenePrefix() imagePrefix = cmds.getAttr("defaultRenderGlobals.imageFilePrefix") if imagePrefix is None: imagePrefix = sceneName writePartialResults = False writePartialResultsInterval = -1 blockSize = 32 threads = 0 extension = 'exr' if renderSettings: extension = getImageExtension(renderSettings) threads = cmds.getAttr("%s.%s" % (renderSettings, "threads")) if threads: print("Render Settings - Threads : %s" % threads) # pbrt version PBRTVersion = cmds.getAttr("%s.%s" % (renderSettings, "PBRTVersion")) print("Render Settings - Version : %s" % PBRTVersion) if animation: extensionPadding = cmds.getAttr( "defaultRenderGlobals.extensionPadding") logName = os.path.join( imageDir, imagePrefix + "." + str(frame).zfill(extensionPadding) + ".log") imageName = os.path.join( imageDir, imagePrefix + "." + str(frame).zfill(extensionPadding) + "." + extension) else: logName = os.path.join(imageDir, imagePrefix + ".log") imageName = os.path.join(imageDir, imagePrefix + "." + extension) imageNameLocal = os.path.relpath(imageName, imageDir) sceneFileNameLocal = os.path.relpath(sceneFileName, imageDir) args = [] if verboseRender >= 0: if PBRTVersion == "v3 Book": if verboseRender == 0: args.append('--quiet') else: args.append('--verbose') else: if verboseRender == 0: args.append('--quiet') elif verboseRender > 1: args.extend( ['--v', str(verboseRender - 2), '--logtostderr']) if threads: args.extend(['--nthreads', str(threads)]) if commandLineParameters: args.extend(commandLineParameters.split()) args.extend(['--outfile', imageNameLocal, sceneFileNameLocal]) if ' ' in pbrtDir: env = {"LD_LIBRARY_PATH": str("\"%s\"" % pbrtDir)} else: env = {"LD_LIBRARY_PATH": str(pbrtDir)} PBRTRender = Process(description='render an image', cmd=PBRTPath, args=args, env=env) #PBRTRender.echo = False PBRTRender.execute() PBRTRender.write_log_to_disk(logName, format='txt') print("Render execution returned : %s" % PBRTRender.status) if oiiotoolPath != "": self.resetImageDataWindow(imageName, oiiotoolPath) if not keepTempFiles: #Delete all of the temp file we just made os.chdir(renderDir) for geometryFile in list(set(geometryFiles)): try: print("Removing geometry : %s" % geometryFile) os.remove(geometryFile) except: print("Error removing temporary file : %s" % geometryFile) print("Removing PBRT scene description : %s" % sceneFileName) os.remove(sceneFileName) print("Removing PBRT render log : %s" % logName) os.remove(logName) else: print("Keeping temporary files") return imageName
def remove(self): # type: () -> NoReturn _cmds.workspace(removeVariableEntry=self.key) self._remove()
def getOutputPath(self): outputPath = cmds.workspace(fileRuleEntry="images") self.lineEdit_outputPath.setText(outputPath)
def doIt(self, argList): global renderSettings print("Rendering with %s..." % kPluginCmdName) # Create a render settings node createRenderSettingsNode() #Save the user's selection userSelection = cmds.ls(sl=True) print("Render Settings - Node : %s" % renderSettings) #Get the directories and other variables projectDir = cmds.workspace(q=True, fn=True) renderDir = os.path.join(projectDir, "renderData") pluginDir = os.path.dirname( os.path.abspath(inspect.getfile(inspect.currentframe()))) version = cmds.about(v=True).replace(" ", "-") # Get render settings pbrtPath = cmds.getAttr("%s.%s" % (renderSettings, "PBRTPath")) oiiotoolPath = cmds.getAttr("%s.%s" % (renderSettings, "oiiotoolPath")) pbrtDir = os.path.split(pbrtPath)[0] integrator = cmds.getAttr("%s.%s" % (renderSettings, "integrator")) sampler = cmds.getAttr("%s.%s" % (renderSettings, "sampler")) pixelSamples = cmds.getAttr("%s.%s" % (renderSettings, "samplerPixelSamples")) reconstructionFilter = cmds.getAttr("%s.%s" % (renderSettings, "filter")) keepTempFiles = cmds.getAttr("%s.%s" % (renderSettings, "keepTempFiles")) verboseRender = cmds.getAttr("%s.%s" % (renderSettings, "verboseRender")) verboseExport = cmds.getAttr("%s.%s" % (renderSettings, "verboseExport")) exportOnly = cmds.getAttr("%s.%s" % (renderSettings, "exportOnly")) commandLineParameters = cmds.getAttr( "%s.%s" % (renderSettings, "commandLineParameters")) print("Render Settings - PBRT Path : %s" % pbrtPath) print("Render Settings - Integrator : %s" % integrator) print("Render Settings - Sampler : %s" % sampler) print("Render Settings - Pixel Samples : %s" % pixelSamples) print("Render Settings - Filter : %s" % reconstructionFilter) print("Render Settings - Render Dir : %s" % renderDir) print("Render Settings - oiiotool Path : %s" % oiiotoolPath) print("Render Settings - Verbose Render : %s" % verboseRender) print("Render Settings - Verbose Export : %s" % verboseExport) print("Render Settings - Export Only : %s" % exportOnly) print("Render Settings - Keep Temp Files : %s" % keepTempFiles) print("Render Settings - Cmd Line Params : %s" % commandLineParameters) animation = self.isAnimation(exportOnly) print("Render Settings - Animation : %s" % animation) # Animation if animation: startFrame = int(cmds.getAttr("defaultRenderGlobals.startFrame")) endFrame = int(cmds.getAttr("defaultRenderGlobals.endFrame")) byFrame = int(cmds.getAttr("defaultRenderGlobals.byFrameStep")) print("Animation frame range : %d to %d, step %d" % (startFrame, endFrame, byFrame)) for frame in range(startFrame, endFrame + 1, byFrame): print("Rendering frame " + str(frame) + " - begin") self.exportAndRender(renderDir, renderSettings, pbrtPath, oiiotoolPath, pbrtDir, keepTempFiles, animation, frame, verboseRender, verboseExport, exportOnly, commandLineParameters) print("Rendering frame " + str(frame) + " - end") print("Animation finished") # Single frame else: imageName = self.exportAndRender(renderDir, renderSettings, pbrtPath, oiiotoolPath, pbrtDir, keepTempFiles, animation, None, verboseRender, verboseExport, exportOnly, commandLineParameters) # Display the render if imageName and not cmds.about(batch=True): PBRTRendererUI.showRender(imageName) # Select the objects that the user had selected before they rendered, or clear the selection if len(userSelection) > 0: cmds.select(userSelection) else: cmds.select(cl=True)
def getCurrentWorkspaceDir(): workSpaceDir = cmds.workspace(query=True, rootDirectory=True) return workSpaceDir
def show(self): #获取当前movie的地址 movieSpace = mc.workspace("movie", query=True, fileRuleEntry=True) moviePaht = mc.workspace(expandName=movieSpace) myScneName = mc.file(q=True, sn=True, shn=True).split('.')[0] if myScneName == '': myScneName = 'untitled' myMovieFullPath = os.path.join(moviePaht, myScneName) myMovieFullPath = os.path.abspath(myMovieFullPath) #删除以往的窗口 self.closeWin(self._windowName) #创建窗口 win = mc.window(self._windowName, title=u"OCT_QuickPlayAllBlast_zwz", menuBar=True, widthHeight=(350, 340), resizeToFitChildren=True, sizeable=True) mc.formLayout('formLyt', numberOfDivisions=100) one = mc.columnLayout('First_Set', parent='formLyt') mc.rowLayout('projectRow', numberOfColumns=3, columnAttach3=['left', 'left', 'left'], columnWidth3=[5, 320, 35], columnOffset3=[2, 2, 2], adjustableColumn3=True, parent='First_Set') mc.text(label=u'输出地址', w=68, parent='projectRow') self.uiTextMovieP = mc.textField('MovieAddress', text=myMovieFullPath, width=395, alwaysInvokeEnterCommandOnReturn=True, parent='projectRow') mc.rowLayout('oneRow', numberOfColumns=5, columnAttach5=['left', 'left', 'left', 'left', 'left'], columnWidth5=[5, 68, 70, 170, 80], columnOffset5=[2, 2, 10, 15, 24], adjustableColumn5=True, parent='First_Set') mc.text(label=u'开始帧:', w=68, parent='oneRow') self.uiTextStartF = mc.textField('startFrame', text=int(self.myStartFrameV), width=60, alwaysInvokeEnterCommandOnReturn=True, parent='oneRow') mc.text(label=u'结束帧:', w=68, parent='oneRow') self.uiTextEndF = mc.textField('endFrame', text=int(self.myEndFrameV), width=60, alwaysInvokeEnterCommandOnReturn=True, parent='oneRow') mc.button(label=u'设置', width=50, command=self.SetRenderStarFram_zwz, backgroundColor=(0.9, 0.5, 0), annotation=u"请输入帧数范围", parent='oneRow') mc.rowLayout('twoRow', numberOfColumns=5, columnAttach5=['left', 'left', 'left', 'left', 'left'], columnWidth5=[5, 68, 70, 170, 80], columnOffset5=[2, 2, 10, 15, 24], adjustableColumn5=True, parent='First_Set') mc.text(label=u'宽:', w=68, parent='twoRow') self.uiTextWidthR = mc.textField('RenderWidth', text=self.myRenderwidth, width=60, alwaysInvokeEnterCommandOnReturn=True, parent='twoRow') mc.text(label=u'高:', w=68, parent='twoRow') self.uiTextheightR = mc.textField('RenderHeight', text=self.myRenderheight, width=60, alwaysInvokeEnterCommandOnReturn=True, parent='twoRow') mc.button(label=u'设置', width=50, command=self.SetRenderWH_zwz, backgroundColor=(0.9, 0.5, 0), annotation=u"请输入渲染尺寸", parent='twoRow') self.uiRadioB_TexMG = mc.radioButtonGrp(numberOfRadioButtons=2, cal=[1, 'left'], cw3=[72, 180, 180], label=u' 贴图格式:', labelArray2=[u'jpg(图片一般清晰、文件小)', u'tif(图片清晰、文件大)',], sl=0, parent='First_Set') #mc.rowLayout('threeRow', numberOfColumns=6, columnAttach6=['left', 'left', 'left', 'left', 'left', 'left'], columnWidth6=[72, 98, 80, 80, 80, 80], columnOffset5=[2, 2, 10, 15, 24], adjustableColumn6=True, parent='First_Set') mc.rowLayout('threeRow', numberOfColumns=7, columnAttach6=['left', 'left', 'left', 'left', 'left', 'left'],columnWidth6=[72, 98, 80, 80, 80, 80],columnOffset5=[2, 2, 10, 15, 24],parent='First_Set') mc.text(label=u'显示模式:') self.uiCheckB_Nurbs = mc.checkBox("NurbsS_CBox", label='Nurbs Surface', v=False) self.uiCheckB_Fluids = mc.checkBox("Fluids_CBox", label='Fluids', v=False) self.uiCheckB_Dynamics = mc.checkBox("Dynamics_CBox", label='Dynamics', v=False) self.uiCheckB_nParticles = mc.checkBox("nParticles_CBox", label='nParticles', v=False) self.uiCheckB_Tex = mc.checkBox("Texture_CBox", label=u'贴图', v=False) self.uiCheckB_Locators = mc.checkBox("Locators_CBox", label=u'Locators', v=False) # mc.rowLayout('fourRow', numberOfColumns=3, columnAttach3=['left', 'left', 'left'], columnWidth3=[72, 98, 80], columnOffset3=[2, 2, 10], adjustableColumn3=True, parent='First_Set') # mc.text(label=u'灯光模式:') # self.uiCheckB_Nolight = mc.checkBox("NoLights", label='Use No Lights', v=False) # self.uiCheckB_TwoLight = mc.checkBox("Two_Lighting", label='Two Sided Lighting', v=True) self.uiRadioB_LightG = mc.radioButtonGrp(numberOfRadioButtons=3, cal=[1, 'left'], cw4=[72, 98, 80, 90], label=u' 灯光模式:', labelArray3=['Default Lighting', 'All Lights', 'No Lights'], sl=0, parent='First_Set') two = mc.frameLayout('Cameras_Set', label=u'请选择需要Play Blast的摄像机(面板可拉伸)', labelAlign='top', borderStyle='etchedOut', w=300, h=100, parent='formLyt') self.uiTextSCameras = mc.textScrollList('selectCameras', append=self.allCameras, aas=True, allowMultiSelection=True, h=100, parent='Cameras_Set') three = mc.columnLayout('Second_Set', parent='formLyt') mc.button('SetAll', label=u'Go', width=460, h=25, command=self.Make_it, backgroundColor=(0.2, 0.8, 0.3), parent='Second_Set') mc.button('CloseWin', label=u'正常退出', width=460, h=25, command=self.CorrectQuit, backgroundColor=(0.8, 0.2, 0.3), parent='Second_Set') mc.formLayout('formLyt', e=True, attachForm=[(one, 'top', 5), (one, 'left', 5), (two, 'right', 5), (two, 'top', 135), (two, 'left', 5), (three, 'left', 5), (three, 'bottom', 5)], attachControl=[(two, 'bottom', 1, three)], attachNone=[(three, 'top')], attachPosition=[(one, 'left', 0, 0), (one, 'top', 0, 0)]) mc.showWindow(win)
class k_cachefinder(): #阿诺德缓存 kassfiles = [] #有问题阿诺德节点 kerror_arnold = [] #abc缓存 kabcmeshfiles = [] #vray缓存 kvrmeshfiles = [] #vrayIES #kvrIESfiles=[] #VRaySettingsNode kvrsettfiles = [] #Vray全部的外部文件 #Maya cache缓存 kcacheFiles = [] #Maya cache xml数据 kcacheFilesx = [] #MR缓存 kmrcacheFiles = [] #贴图 kTexture = [] kmayaTex = [] kaiTex = [] kVpTex = [] #经典粒子缓存 kparcache = [] #Yeti毛发缓存 kYeticache = [] kYetitex = [] #shave毛发缓存 kshave_cache = [] #插件版本 mayaplugin_version = {} projectDir = cc.workspace(query=True, rootDirectory=True) def __init__(self): self.k_checkVRmeshfiles() self.k_checkabcfiles() self.k_checkassfiles() self.k_checkabcfiles() self.k_cachefiles() self.k_checkMRmeshfiles() self.k_checkTexfiles() self.k_checkDiskPcache() self.k_checkYeticache() self.k_checkShaveCache() #for x in self.kmayaTex: #print x #for y in self.kcacheFiles: #print y #print self.mayaplugin_version def k_checkYeticache(self): #缓存匹配公式 self.kexpo3 = r'(.*?)([\.]?)([%][0-9]*d)(\.fur)$' #贴图匹配公式 self.kexpo4 = r'(.*?)([\.]?)([%][0-9]*d)(\.png|\.tif|\.exr)$' self.kexpu4 = r'(.*)(\.png|\.tif|\.exr)$' #节点返回的路径存放地 为了不重复检查 pgYeti = [] if cc.pluginInfo("pgYetiMaya", q=1, l=1): yetis = cc.ls(type='pgYetiMaya') version = cc.pluginInfo("pgYetiMaya", q=1, v=1) self.mayaplugin_version.update({'Yeti': version}) for yeti in yetis: yeticache = cc.getAttr(yeti + '.cacheFileName') #判断是否绝对路径 if yeticache and not os.path.isabs(yeticache): yeticache = self.projectDir + yeticache #判断有无重复检查 if yeticache and not yeticache in pgYeti: pgYeti.append(yeticache) #获取 缓存名 与 路径 yeticache_name = os.path.basename(yeticache) yeticache_dir = os.path.dirname(yeticache) pattern = re.search(self.kexpo3, yeticache) if pattern: try: #返回路径下的所谓文件 yeticachefiles = os.listdir(yeticache_dir) for yeticachefile in yeticachefiles: #print yeticachefile #匹配 kexpc = r'%s%s([0-9]*)(\.fur)$' % ( pattern.group(1), pattern.group(2)) #判断是否在盘的根目录 防止出现E://xxxxx 这种情况 if yeticache_dir[-2:] == ':/': yeticachefilef = yeticache_dir + yeticachefile else: yeticachefilef = yeticache_dir + '/' + yeticachefile pattern2 = re.search(kexpc, yeticachefilef) if pattern2 and not yeticachefilef in self.kYeticache: self.kYeticache.append(yeticachefilef) print yeticachefilef except WindowsError: #print e.message pass else: #非序列的文件 if os.path.exists( yeticache ) and not yeticache in self.kYeticache: self.kYeticache.append(yeticache) print yeticache #pgYetiGraph为 yeti提供的mel yetiTexs = cc.pgYetiGraph(yeti, listNodes=True, type='texture') if yetiTexs: for yetiTex in yetiTexs: #获取yeti Graph里面的节点 及 参数 yetiTexfile = cc.pgYetiGraph(yeti, node=yetiTex, param='file_name', getParamValue=True) if yetiTexfile and not os.path.isabs(yetiTexfile): yetiTexfile = self.projectDir + yetiTexfile yetiTexfile = yetiTexfile.replace('\\', '/') if yetiTexfile: yetiTex_name = os.path.basename(yetiTexfile) yetiTex_dir = os.path.dirname(yetiTexfile) patternt = re.search(self.kexpo4, yetiTexfile) #匹配是否为序列格式 if patternt: try: YetiTexfiles = os.listdir(yetiTex_dir) for YetiTexfile in YetiTexfiles: #print yeticachefile kexpt = r'%s%s([0-9]*)(\.png|\.tif|\.exr)$' % ( patternt.group(1), patternt.group(2)) #判断是否在盘的根目录 防止出现E://xxxxx 这种情况 if yetiTex_dir[-2:] == ':/': YetiTexfilef = yetiTex_dir + YetiTexfile else: YetiTexfilef = yetiTex_dir + '/' + YetiTexfile #匹配完整路径格式 pattern = re.search( kexpt, YetiTexfilef) if pattern and not YetiTexfilef in self.kYetitex: self.kYetitex.append(YetiTexfilef) print YetiTexfilef except WindowsError: #print e.message pass else: if os.path.exists( yetiTexfile ) and not yetiTexfile in self.kYeticache: #匹配yeti支持的图片格式 patternt = re.search( self.kexpu4, yetiTexfile) if patternt and not yetiTexfile in self.kYetitex: self.kYeticache.append(yetiTexfile) print yetiTexfile def k_checkShaveCache(self): if cc.pluginInfo("shaveNode", q=1, l=1): version = cc.pluginInfo("shaveNode", q=1, v=1) self.mayaplugin_version.update({'shave': version}) #shaveGlobals=cc.ls(type='shaveGlobals') kshaveHairs = cc.ls(type='shaveHair') #if 'shaveGlobals' in shaveGlobals: #只返回指定的shaveGlobal节点内容 shaveStat = cc.getAttr('shaveGlobals.tmpDir') if shaveStat and not os.path.isabs(shaveStat): shaveStat = self.projectDir + shaveStat if shaveStat: shaveStat = shaveStat.replace('\\', '/') try: shaveStatfiles = os.listdir(shaveStat) for shaveStatfile in shaveStatfiles: # 针对文件内有多个shave节点 返回shave节点的名字匹配缓存名字 for kshaveHair in kshaveHairs: #将shave节点的:号改成_ (针对参考类型的shave节点) kshaveHair = kshaveHair.replace(':', '_') #匹配每个shave节点对应的缓存 kexpo = r'(shaveStatFile_)(%s)(\.?)([0-9]*)(.stat)$' % ( kshaveHair) pattern = re.search(kexpo, shaveStatfile) if pattern and not shaveStatfile in self.kshave_cache: self.kshave_cache.append(shaveStatfile) print shaveStatfile #匹配shave特定OBJ文件 kexpo2 = r'(shaveObjFile_)(.*?)(.obj)$' kexpo3 = r'(shaveInstance_)(.*?)(.obj)$' pattern2 = re.search(kexpo2, shaveStatfile) pattern3 = re.search(kexpo3, shaveStatfile) if pattern2 or pattern3 and not shaveStatfile in self.kshave_cache: self.kshave_cache.append(shaveStatfile) print shaveStatfile except: pass def k_checkDiskPcache(self): #获取缓存控制节点 dyns = cc.ls(type='dynGlobals') #它可能有多个 for dyn in dyns: if cc.getAttr(dyn + '.useParticleDiskCache'): #找出工程目录定义的粒子缓存 存放地址 parpath = cc.workspace(fre='particles') fparpath = self.projectDir + parpath #获取粒子缓存具体子目录 pcacheDir = cc.getAttr(dyn + '.cd') if pcacheDir: #获取最终目录位置 cachepath = fparpath + '/' + pcacheDir #列出目录里的的所有文件 try: cachepathfiles = os.listdir(cachepath) for cachepathfile in cachepathfiles: #分离后缀 查询后缀 是否为pdc格式 if os.path.splitext( cachepathfile )[-1] == '.pdc' and not cachepathfile in self.kparcache: self.kparcache.append(cachepathfile) #print cachepathfile except: pass def k_checkTexfiles(self): texfiles = cc.ls(type='file') for texfile in texfiles: #判断有无自定义属性 userAttrs = cc.listAttr(texfile, ud=1) if userAttrs: #获取有无UDIM模式 ktexmode = cc.getAttr(texfile + '.uvTilingMode') #如果无: if not ktexmode: for userAttr in userAttrs: #判断自定义内容是否 Tex 开头 if userAttr[:3] == 'Tex': #获取自定义属性的 内容 userTex = cc.getAttr(texfile + "." + userAttr) #添加入总数组 if userTex and not userTex in self.kmayaTex: if os.path.exists(userTex): #print texfile self.kmayaTex.append(userTex) #print userTex userTex_tx = os.path.splitext( userTex)[0] + '.tx' if os.path.exists( userTex_tx ) and not userTex_tx in self.kmayaTex: self.kmayaTex.append(userTex_tx) #print userTex_tx #有UDIM模式 else: for userAttr in userAttrs: #判断自定义内容是否 Tex 开头 if userAttr[:3] == 'Tex': userTex = cc.getAttr(texfile + "." + userAttr) #获取自定义内容 的UDIM贴图 k_getUDIMp = k.getFilePatternString( userTex, False, ktexmode) k_exudims = k.findAllFilesForPattern( k_getUDIMp, None) #添加贴图入总数组 for k_exudim in k_exudims: if k_exudim and not k_exudim in self.kmayaTex: #print texfile self.kmayaTex.append(k_exudim) #print k_exudim k_exudim_tx = os.path.splitext( k_exudim)[0] + '.tx' if os.path.exists( k_exudim_tx ) and not k_exudim_tx in self.kmayaTex: self.kmayaTex.append(k_exudim_tx) #print k_exudim_tx else: ktexfile = cc.getAttr(texfile + '.fileTextureName') ktexmode = cc.getAttr(texfile + '.uvTilingMode') if not ktexmode: if ktexfile and not os.path.isabs(ktexfile): ktexfile = self.projectDir + ktexfile ktexfile = ktexfile.replace('\\', '/') if ktexfile and not ktexfile in self.kmayaTex: if os.path.exists(ktexfile): #print texfile self.kmayaTex.append(ktexfile) #print ktexfile ktexfile_tx = os.path.splitext(ktexfile)[0] + '.tx' if os.path.exists( ktexfile_tx ) and not ktexfile_tx in self.kmayaTex: self.kmayaTex.append(ktexfile_tx) #print ktexfile_tx else: if ktexfile and not os.path.isabs(ktexfile): ktexfile = self.projectDir + ktexfile ktexfile = ktexfile.replace('\\', '/') #maya内部UDIM命令 k_getUDIMp = k.getFilePatternString( ktexfile, False, ktexmode) k_exudim = k.findAllFilesForPattern(k_getUDIMp, None) for ktexfile in k_exudim: if ktexfile and not ktexfile in self.kmayaTex: #print texfile self.kmayaTex.append(ktexfile) #print ktexfile ktexfile_tx = os.path.splitext(ktexfile)[0] + '.tx' if os.path.exists( ktexfile_tx ) and not ktexfile_tx in self.kmayaTex: self.kmayaTex.append(ktexfile_tx) #print ktexfile_tx #先判断插件有没开,防止找不到节点类型 if cc.pluginInfo("mtoa", q=1, l=1): aiTexfiles = cc.ls(type='aiImage') if aiTexfiles: for aiTexfile in aiTexfiles: #返回文件路径 aiTexfilesname = cc.getAttr(aiTexfile + '.filename') #判断是否为空 及 在总数组有无重复 及 文件是否存在 if aiTexfilesname and not aiTexfilesname in self.kaiTex: if os.path.exists(aiTexfilesname): #print aiTexfilesname self.kaiTex.append(aiTexfilesname) #判断此文件有无tx版本的路径 aiTexfilesname_tx = os.path.splitext( aiTexfilesname)[0] + '.tx' #判断文件是否存在 及 在总数组有无重复 if os.path.exists( aiTexfilesname_tx ) and not aiTexfilesname_tx in self.kaiTex: self.kaiTex.append(aiTexfilesname_tx) #print aiTexfilesname_tx #先判断插件有没开,防止找不到节点类型 if cc.pluginInfo("vrayformaya", q=1, l=1): Vptexfiles = cc.ls(type='VRayPtex') if Vptexfiles: for Vptexfile in Vptexfiles: #返回文件路径 Vptexfilename = cc.getAttr(Vptexfile + '.ptexFile') #判断是否为空 及 在总数组有无重复 及 文件是否存在 if Vptexfilename and not Vptexfilename in self.kVpTex: if os.path.exists(Vptexfilename): #print Vptexfilename self.kaiTex.append(Vptexfilename) #判断此文件有无tx版本的路径 Vptexfilename_tx = os.path.splitext( Vptexfilename)[0] + '.tx' #判断文件是否存在 及 在总数组有无重复 if os.path.exists( Vptexfilename_tx ) and not Vptexfilename_tx in self.kaiTex: self.kaiTex.append(Vptexfilename_tx) #print Vptexfilename_tx self.kTexture = list(set(self.kmayaTex + self.kaiTex + self.kVpTex)) def k_checkMRmeshfiles(self): if cc.pluginInfo("Mayatomr", q=1, l=1): version = cc.pluginInfo("Mayatomr", q=1, v=1) self.mayaplugin_version.update({'mentalray': version}) #检查mentalray隐藏的缓存节点 mrmeshs = cc.ls(type='mip_binaryproxy') for mrmesh in mrmeshs: kmrmesh = cc.getAttr(mrmesh + '.object_filename') if kmrmesh and not os.path.isabs(kmrmesh): kmrmesh = self.projectDir + kmrmesh kmrmesh = kmrmesh.replace('\\', '/') if kmrmesh and not kmrmesh in self.kmrcacheFiles: if os.path.exists(kmrmesh): self.kmrcacheFiles.append(kmrmesh) #检查mesh节点 mentalray栏内的缓存路径 mrmeshs = cc.ls(type='mesh') for mrmesh in mrmeshs: kmrmesh = '' try: kmrmesh = cc.getAttr(mrmesh + '.miProxyFile') except: pass if kmrmesh: if kmrmesh and not os.path.isabs(kmrmesh): kmrmesh = self.projectDir + kmrmesh kmrmesh = kmrmesh.replace('\\', '/') if kmrmesh and not kmrmesh in self.kmrcacheFiles: if os.path.exists(kmrmesh): self.kmrcacheFiles.append(kmrmesh) def k_checkVRmeshfiles(self): if cc.pluginInfo("vrayformaya", q=1, l=1): version = cc.pluginInfo("vrayformaya", q=1, v=1) self.mayaplugin_version.update({'Vray': version}) #kwp = cc.workspace(q =True, rootDirectory=True) #查询vray代理 kvrmeshs = cc.ls(type='VRayMesh') for kvrmesh in kvrmeshs: krvrmesh = cc.listConnections((kvrmesh + '.output'), s=0, d=1) if krvrmesh: vrmesh = cc.getAttr(kvrmesh + '.fileName') if vrmesh and not os.path.isabs(vrmesh): vrmesh = self.projectDir + vrmesh vrmesh = vrmesh.replace('\\', '/') if vrmesh and not vrmesh in self.kvrmeshfiles: if os.path.exists(vrmesh): self.kvrmeshfiles.append(vrmesh) #查询vray光子图 vrsettfiles = cc.ls(type="VRaySettingsNode") for vrsettfile in vrsettfiles: #causticsFile----散射图,fileName ----lightcache图 pmap_file ---photon map imap_fileName --- Irradiance map for k_stype in [ 'causticsFile', 'fileName', 'pmap_file', 'imap_fileName' ]: kvrsettfile = cc.getAttr(vrsettfile + '.' + k_stype) if kvrsettfile and not kvrsettfile in self.kvrsettfiles: if os.path.exists(kvrsettfile): self.kvrsettfiles.append(kvrsettfile) def k_checkabcfiles(self): if cc.pluginInfo("AbcImport", q=1, l=1): version = cc.pluginInfo("AbcImport", q=1, v=1) self.mayaplugin_version.update({'Abc': version}) kabcmeshs = cc.ls(type='AlembicNode') for kabcmesh in kabcmeshs: #确认abc节点有无输出, krabcmesh = cc.listConnections((kabcmesh + '.outPolyMesh'), s=0, d=1) kcabcmesh = cc.listConnections((kabcmesh + '.transOp'), s=0, d=1) if krabcmesh or kcabcmesh: abcfilepath = cc.getAttr(kabcmesh + '.abc_File') #判断是否为绝对路径 if abcfilepath and not os.path.isabs(abcfilepath): abcfilepath = self.projectDir + abcfilepath abcfilepath = abcfilepath.replace('\\', '/') if abcfilepath and not abcfilepath in self.kabcmeshfiles: if os.path.exists(abcfilepath): self.kabcmeshfiles.append(abcfilepath) def k_cachefiles(self): #用mel返回出 maya的缓存 ---流体,毛发缓存 刚体布料缓存 (ncache创建的缓存) cachefiles = cc.file(q=1, l=1) for cachefile in cachefiles: if cachefile and os.path.splitext( cachefile)[-1] == '.mcx' or os.path.splitext( cachefile)[-1] == '.mc' or os.path.splitext( cachefile)[-1] == '.xml': if not cachefile in self.kcacheFiles: self.kcacheFiles.append(cachefile) #print cachefile def k_checkassfiles(self): #maya节点返回的路径 kassdso = [] #记录文件夹内里的文件,避免重复对网络进行获取 kassfilepath = {} self.kexpo = r'(.*?)([\._])([#]*)([\.]?)([#]*)(\.ass\.gz|\.ass|\.obj|\.ply|\.asstoc)$' #self.kexpo2 = r'(.*?)([\._])([0-9#]*)([\.]?)([0-9#]*)(\.ass\.gz|\.ass|\.obj|\.ply)$' if cc.pluginInfo("mtoa", q=1, l=1): version = cc.pluginInfo("mtoa", q=1, v=1) self.mayaplugin_version.update({'Arnold': version}) kassmeshs = cc.ls(type='aiStandIn') for kassmesh in kassmeshs: #先判断是否无下游输出的节点 krassmesh = cc.listConnections(kassmesh, s=0, d=1) #kcassmesh=cc.listConnections((kassmesh+'.transOp'),s=0,d=1) if krassmesh: #print 'kassmesh '+str(kassmesh) assdsom = cc.getAttr(kassmesh + '.dso') #判断是否为绝对路径 if assdsom and not os.path.isabs(assdsom): assdso = self.projectDir + assdsom assdso = assdsom.replace('\\', '/') #获取 缓存名 与 路径 assmesh_getpath = os.path.basename(assdso) #print 'assdso '+str(assdso) assmeshpath = os.path.dirname(assdso) #print 'assmeshpath '+str(assmeshpath) #先判断有无重复检查 if assdsom and not assdsom in kassdso: kassdso.append(assdsom) #如果路径出现过 if assmeshpath in kassfilepath: #k_filterseq=[] #asspathfiles=os.listdir(assmeshpath) asspathfiles = kassfilepath[assmeshpath] #print 'asspathfiles '+str(asspathfiles) krseqfile = self.k_filterassfile( assdso, asspathfiles, kassmesh) #self.kassfiles.append(krseqfile) else: asspathfiles = [] #判断是否能根据文件夹 返回 文件夹里面的所有文件 try: asspathfiles = os.listdir(assmeshpath) except WindowsError: #print e.message pass #print 'asspathfiles '+str(asspathfiles) krseqfile = self.k_filterassfile( assdso, asspathfiles, kassmesh) #self.kassfiles.append(krseqfile) k_update = {assmeshpath: asspathfiles} kassfilepath.update(k_update) #print 'kseq '+str(kseq) # #print kassfilepath #执行过滤判断 assdso=节点返回的数据 asspathfiles=文件夹下的所有文件 kassmesh=maya节点名字 def k_filterassfile(self, assdso, asspathfiles, kassmesh): #根据节点返回的数据 获取文件名字 与 路径 assmesh_getpath = os.path.basename(assdso) assmeshpath = os.path.dirname(assdso) #print assdso for asspathfile in asspathfiles: #找出井号 #print 'asspathfile____ '+str(asspathfile) pattern = re.search(self.kexpo, assmesh_getpath) #pattern2 = re.search(self.kexpo2, assmesh_getpath) if pattern: # 找出#### #print pattern.groups() kwellnum = pattern.group(3) #print 'kwellnum '+str(kwellnum) k_NO = len(kwellnum) kexpc = r'%s%s([0-9]{%d})([\.]?)([#]*)(\.ass\.gz|\.ass|\.obj|\.ply|\.asstoc)$' % ( pattern.group(1), pattern.group(2), k_NO) kpattern = re.search(kexpc, asspathfile) if kpattern: kseq = kpattern.group() #k_filterseq.append(kseq) #判断是否在盘的根目录 防止出现E://xxxxx 这种情况 if assmeshpath[-2:] == ':/': kseqfile = assmeshpath + kseq else: kseqfile = assmeshpath + '/' + kseq if not kseqfile in self.kassfiles: if os.path.exists(kseqfile): self.kassfiles.append(kseqfile) #return kseqfile #print kseqfile else: #判断节点返回的数据 是否在 总的缓存数组里存在 kseqfile = assdso if not kseqfile in self.kassfiles: #print kseqfile #判断文件是否存在 #测试节点返回的路径是否存在 if os.path.exists(kseqfile): self.kassfiles.append(kseqfile) else: self.kerror_arnold.append(kassmesh)
def open(directory_path): # type: (str) -> NoReturn _cmds.workspace(directory_path, openWorkspace=True)
def getProject(rootDirectory=True): sDirectory = cmds.workspace(q=True, directory=True, rd=rootDirectory) return sDirectory
def root_directory(): # type: () -> str return _cmds.workspace(query=True, rootDirectory=True)
import os from functools import partial from pymel.core import * # ****************************************** G L O B A L S ****************************************** lookdevScenePath = os.path.abspath( '//merlin/3d4/skid/09_dev/toolScripts/lookdev/lookdevSetup/LookdevSetup.ma' ) hdri_folder = os.path.abspath('//Merlin/3d4/skid/04_asset/SkidLibrary/HDRI') hdri_files = os.listdir(hdri_folder) hdriTurnGrp = '|LookdevSetup:GRP_LookdevSetup|LookdevSetup:GRP_LIGHTING|LookdevSetup:GRP_HDRI' turnLocator = 'turn_locator' grpName = 'LookdevSetup:GRP_LookdevSetup' lookdevPreset = 'SKID_LookdevSetup' scenePath = cmds.workspace(sn=True, q=True) turnDurations = [8, 50, 100] # ****************************************** F U N C T I O N S ****************************************** def chooseHDRfile(item, *args): resolveHDRpath = os.path.join(hdri_folder, item) cmds.setAttr('LookdevSetup:PxrDomeLight_HDRI.lightColorMap', '%s' % resolveHDRpath, type='string') # ****************************************** I N T E R F A C E ******************************************
def setProject(sDirectory): cmds.workspace(dir=sDirectory)
def validate(self, settings, item): """ Validates the given item to check that it is ok to publish. Returns a boolean to indicate validity. :param settings: Dictionary of Settings. The keys are strings, matching the keys returned in the settings property. The values are `Setting` instances. :param item: Item to process :returns: True if item is valid, False otherwise. """ publisher = self.parent path = _session_path() # ---- ensure the session has been saved if not path: # the session still requires saving. provide a save button. # validation fails. error_msg = "The Maya session has not been saved." self.logger.error(error_msg, extra=_get_save_as_action()) raise Exception(error_msg) # ensure we have an updated project root project_root = cmds.workspace(q=True, rootDirectory=True) item.properties["project_root"] = project_root # log if no project root could be determined. if not project_root: self.logger.info("Your session is not part of a maya project.", extra={ "action_button": { "label": "Set Project", "tooltip": "Set the maya project", "callback": lambda: mel.eval('setProject ""') } }) # ---- check the session against any attached work template # get the path in a normalized state. no trailing separator, # separators are appropriate for current os, no double separators, # etc. path = sgtk.util.ShotgunPath.normalize(path) # if the session item has a known work template, see if the path # matches. if not, warn the user and provide a way to save the file to # a different path work_template_setting = settings.get("Work Template") work_template = publisher.get_template_by_name( work_template_setting.value) if work_template: item.properties["work_template"] = work_template self.logger.debug( "Work template configured as {}.".format(work_template)) else: self.logger.debug("No work template configured.") return False # ---- see if the version can be bumped post-publish # check to see if the next version of the work file already exists on # disk. if so, warn the user and provide the ability to jump to save # to that version now (next_version_path, version) = self._get_next_version_info(path, item) if next_version_path and os.path.exists(next_version_path): # determine the next available version_number. just keep asking for # the next one until we get one that doesn't exist. while os.path.exists(next_version_path): (next_version_path, version) = self._get_next_version_info( next_version_path, item) error_msg = "The next version of this file already exists on disk." self.logger.error( error_msg, extra={ "action_button": { "label": "Save to v%s" % (version, ), "tooltip": "Save to the next available version number, " "v%s" % (version, ), "callback": lambda: _save_session(next_version_path) } }) raise Exception(error_msg) # ---- populate the necessary properties and call base class validation # populate the publish template on the item if found publish_template_setting = settings.get("Publish Template") publish_template = publisher.engine.get_template_by_name( publish_template_setting.value) if publish_template: item.properties["publish_template"] = publish_template else: self.logger.debug("No published template configured.") return False # set the session path on the item for use by the base plugin validation # step. NOTE: this path could change prior to the publish phase. item.properties["path"] = path # run the base class validation return super(MayaSessionPublishPlugin, self).validate(settings, item)
def update(self, new_value): # type: (str) -> NoReturn _cmds.workspace(variable=(self.key, new_value)) self._update(new_value)
import maya.cmds as cmds import maya.mel as mel def getShader(geom): shapeNode = cmds.listRelatives(geom, children=True, shapes=True)[0] sg = cmds.listConnections(shapeNode, type="shadingEngine")[0] shader = cmds.listConnections(sg + ".surfaceShader")[0] return shader userSelection = cmds.ls(sl=True) cwd = cmds.workspace(q=True, directory=True) #out mitsuba file outFileName = cwd + "temporary.xml" outFile = open(outFileName, 'w+') outFile.write("<?xml version=\'1.0\' encoding=\'utf-8\'?>\n") outFile.write("\n") outFile.write("<scene version=\"0.4.0\">\n") outFile.write(" <integrator type=\"path\">\n") outFile.write(" </integrator>\n") outFile.write("\n") outFile.write(" <!-- Camera -->\n") cams = cmds.ls(type="camera") rCamShape = "" for cam in cams: isRenderable = cmds.getAttr(cam + ".renderable") if isRenderable:
def createProjectFiles(sProjectDir): lFiles = cmds.workspace(q=True, fileRuleList=True) for sFile in lFiles: sFileDir = cmds.workspace(fileRuleEntry=sFile) sFileDir = os.path.join(sProjectDir, sFileDir) files.createFolder(sFileDir)
def launch_workfiles_app(*args): workfiles.show(os.path.join(cmds.workspace(query=True, rootDirectory=True), cmds.workspace(fileRuleEntry="scene")), parent=self._parent)
def execute(self, operation, file_path, context, parent_action, file_version, read_only, **kwargs): """ Main hook entry point :param operation: String Scene operation to perform :param file_path: String File path to use if the operation requires it (e.g. open) :param context: Context The context the file operation is being performed in. :param parent_action: This is the action that this scene operation is being executed for. This can be one of: - open_file - new_file - save_file_as - version_up :param file_version: The version/revision of the file to be opened. If this is 'None' then the latest version should be opened. :param read_only: Specifies if the file should be opened read-only or not :returns: Depends on operation: 'current_path' - Return the current scene file path as a String 'reset' - True if scene was reset to an empty state, otherwise False all others - None """ if operation == "prepare_new": # get the app from the hook app = self.parent # now get work files settings so that we can work out what template we should be using to save with app_settings = sgtk.platform.find_app_settings( app.engine.name, app.name, app.sgtk, context, app.engine.instance_name) # get the template name from the settings template_name = app_settings[0]['settings']['template_work'] # using the template name get an template object template = app.sgtk.templates[template_name] # now use the context to resolve as many of the template fields as possible fields = context.as_template_fields(template) # The name of the shot entity = context.entity shotEntity = entity['name'] shotName = shotEntity.replace("_", "") fields['name'] = shotName # The version can't be resolved from context so we must add the value fields['version'] = 1 # now resolve the template path using the field values. file_path = template.apply_fields(fields) length = len(file_path) lengthNoExt = length - 2 resolved_path = file_path[0:lengthNoExt] + 'mb' #maya file path eng = sgtk.platform.current_engine() tk = eng.sgtk entityType = entity['type'] entityName = entity['name'] if entityType == 'Shot': template_maya = tk.templates['3Dshot_root'] elif entityType == 'Asset': template_maya = tk.templates['asset_root'] else: print "Could not find the entity type" shot_path_maya = tk.paths_from_template(template_maya, {entityType: entityName}) shot_path_maya_str = ''.join(shot_path_maya) #find workspace path #cmds.workspace(directory=shot_path_maya_str) #set workspace path cmds.workspace(shot_path_maya_str, openWorkspace=True) #cmds.workspace( entityName, newWorkspace=True) #cmds.workspace(saveWorkspace=True) #cmds.workspace(baseWorkspace='default') #save scene cmds.file(rename=resolved_path) cmds.file(save=True, type='mayaBinary') elif operation == "current_path": # return the current scene path return cmds.file(query=True, sceneName=True) elif operation == "open": # do new scene as Maya doesn't like opening # the scene it currently has open! cmds.file(new=True, force=True) cmds.file(file_path, open=True, force=True) elif operation == "save": # save the current scene: cmds.file(save=True) elif operation == "save_as": # first rename the scene as file_path: cmds.file(rename=file_path) # Maya can choose the wrong file type so # we should set it here explicitely based # on the extension maya_file_type = None if file_path.lower().endswith(".ma"): maya_file_type = "mayaAscii" elif file_path.lower().endswith(".mb"): maya_file_type = "mayaBinary" # save the scene: if maya_file_type: cmds.file(save=True, force=True, type=maya_file_type) else: cmds.file(save=True, force=True) elif operation == "reset": """ Reset the scene to an empty state """ while cmds.file(query=True, modified=True): # changes have been made to the scene res = QtGui.QMessageBox.question( None, "Save your scene?", "Your scene has unsaved changes. Save before proceeding?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Cancel) if res == QtGui.QMessageBox.Cancel: return False elif res == QtGui.QMessageBox.No: break else: scene_name = cmds.file(query=True, sn=True) if not scene_name: cmds.SaveSceneAs() else: cmds.file(save=True) # do new file: cmds.file(newFile=True, force=True) return True
def ChooseFolder(self): ShotTF = self.ShotTF StartFolder = cmds.workspace(query = True, directory = True) Folder = cmds.fileDialog2( dialogStyle=2, startingDirectory = StartFolder,fileMode=3) if not Folder == None: cmds.textField(ShotTF,edit = True,text = Folder[0])
def setUp(self): cmds.file(new=True, force=True) # To control where the rendered images are written, we force Maya to # use the test directory as the workspace. cmds.workspace(self._testDir, o=True)
def t3dPathset(): t3dbasepath = cmds.workspace(q=True, rd=True) + "data/UDKexport.t3d" filters = "Unreal Text (*.t3d)" t3dEPath = cmds.fileDialog2(dir=t3dbasepath, fm=0, ff=filters, cap="Set T3D Location") cmds.textField('t3dexportdir', e=True, fi=str(t3dEPath[0]))
class ChannelBox(QtWidgets.QWidget): icons = ICONS curPth = cmds.workspace(q=True, rd=True) curPthParts = curPth.split('/') curPthList = [f for f in os.listdir(curPth) if os.path.isdir(curPth + f)] bts = importBTS() def __init__(self, dock=True): if dock: parent = getDock(name='Channel Box', label='Channel Box') else: deleteDock() try: cmds.deleteUI('Channel Box') except: logger.debug('No previous UI exists') parent = QtWidgets.QDialog(parent=getMayaMainWindow()) parent.setObjectName('Channel Box') parent.setWindowTItle('Channel Box') dialogLayout = QtWidgets.QVBoxLayout(parent) super(ChannelBox, self).__init__(parent=parent) self.buildUI() if not dock: parent.show() def buildUI(self): self.layout = QtWidgets.QGridLayout(self) self.cb1 = cmds.channelBox('Channel Box') self.menuChannelBoxWhenRightClick() # Menu popup when right click in channel box: def menuChannelBoxWhenRightClick(self): cb1_popup = cmds.popupMenu(p=self.cb1, ctl=False, button=3) cmds.menuItem(l="Channels", c=partial(self.channelBoxCommand, "-channelEditor")) cmds.menuItem(d=True) cmds.menuItem(d=True) cmds.menuItem(parent=cb1_popup, l="Reset All Channels", c=partial(self.channelBoxCommand, "-setAllToZero")) cb1_menu_03 = cmds.menuItem(parent=cb1_popup, l="Channel Name", subMenu=True) cmds.setParent(cb1_menu_03, m=True) cmds.radioMenuItemCollection() cmds.menuItem('niceNameItem', l="Nice", rb=True, c=self.niceNameSet) cmds.menuItem('longNameItem', l="Long", rb=True, c=self.longNameSet) cmds.menuItem('shortNameItem', l="Short", rb=True, c=self.shortNameSet) cmds.setParent('..', m=True) cmds.menuItem(d=True) cmds.menuItem(l="Key Selected", c=partial(self.channelBoxCommand, "-keySelected")) cmds.menuItem(l="Key All", c=partial(self.channelBoxCommand, "-keyAll")) cmds.menuItem(l="Breakdown Selected", c=partial(self.channelBoxCommand, "-breakDownSelected")) cmds.menuItem(l="Breakdown All", c=partial(self.channelBoxCommand, "-breakDownAll")) cmds.menuItem(d=True) cmds.menuItem(l="Cut Selected", c=partial(self.channelBoxCommand, "-cutSelected")) cmds.menuItem(l="Copy Selected", c=partial(self.channelBoxCommand, "-copySelected")) cmds.menuItem(l="Paste Selected", c=partial(self.channelBoxCommand, "-pasteSelected")) cmds.menuItem(l="Delete Selected", c=partial(self.channelBoxCommand, "-deleteSelected")) cmds.menuItem(d=True) cmds.menuItem(l="Break Connections", c=partial(self.channelBoxCommand, "-breakConnection")) cmds.menuItem(d=True) cmds.menuItem(l="Lock Selected", c=partial(self.channelBoxCommand, "-lockSelected")) cmds.menuItem(l="Unlock Selected", c=partial(self.channelBoxCommand, "-unlockSelected")) cmds.menuItem(l="Hide Selected", c=partial(self.channelBoxCommand, "-hideSelected")) cmds.menuItem(l="Lock and Hide Selected", c=partial(self.channelBoxCommand, "-lockAndHideSelected")) cmds.menuItem(l="Show Hidden Channels", c=partial(self.channelBoxCommand, "-unhideHided")) cmds.menuItem(d=True) cmds.menuItem(l="Expressions...", c=partial(self.channelBoxCommand, "-expression")) cmds.menuItem(l="Set Driven Key", c=partial(self.channelBoxCommand, "-setDrivenKey")) cmds.menuItem(d=True) cmds.menuItem(l="Delete Attribute", c=partial(self.channelBoxCommand, "-deleteAttribute")) cmds.menuItem(d=True) cmds.menuItem(l="Setting", subMenu=True) cmds.setParent(m=True) cmds.menuItem(l="Slow", rb=True, c=self.speedSlowSet) cmds.menuItem(l="Normal", rb=True, c=self.speedNormalSet) cmds.menuItem(l="Fast", rb=True, c=self.speedFastSet) cmds.menuItem(d=True) cmds.menuItem('hyperCheckBox', l="Hyperbolic", checkBox=True, c=self.hyperbolicSet) cmds.menuItem(d=True) cmds.menuItem(l="Precision", c=self.precisionNumberUI) cmds.menuItem(d=True) cmds.menuItem(l="No Manips", rb=True, c="cmds.channelBox(self.myChannelBox, query=True, mnp=0)") cmds.menuItem(l="Invisible Manips", rb=True, c="cmds.channelBox(self.myChannelBox, query=True, mnp=1)") cmds.menuItem(l="Standard Manips", rb=True, c="cmds.channelBox(self.myChannelBox, query=True, mnp=2)") def warningPopup(self, message): cmds.confirmDialog(t='Warning', m=message, b='OK') cmds.warning(message) # Menu popup functions def precisionNumberUI(self, *args): if cmds.window('setPrecisionNumber', exists=True): cmds.deleteUI('setPrecisionNumber') cmds.window('setPrecisionNumber') cmds.columnLayout() cmds.intField('precisionNumber', w=195) cmds.text(l="", h=10) cmds.rowColumnLayout(nc=2, cw=[(1, 90), (2, 100)]) cmds.button(l="Ok", w=90, c=self.setPreNum) cmds.button(l="Close", w=90, c="cmds.deleteUI('setPrecisionNumber')") cmds.showWindow('setPrecisionNumber') def setPreNum(self, *args): newPreNum = cmds.intField('precisionNumber', query=True, value=True) if newPreNum <= 3: newWidth = 65 elif newPreNum <= 6: newWidth = 95 elif newPreNum <= 9: newWidth = 115 elif newPreNum <= 12: newWidth = 130 else: newWidth = 155 cmds.channelBox('Channel Box', edit=True, pre=newPreNum, fieldWidth=newWidth) cmds.deleteUI('setPrecisionNumber') def hyperbolicSet(self, *args): hyperbolicCheck = cmds.menuItem('hyperCheckBox', query=True, checkBox=True) if hyperbolicCheck == True: cmds.channelBox('Channel Box', e=True, hyp=True) if hyperbolicCheck == False: cmds.channelBox('Channel Box', e=True, hyp=False) def speedSlowSet(self, *args): cmds.channelBox(self.cb1, e=True, spd=0.1) def speedNormalSet(self, *args): cmds.channelBox(self.cb1, e=True, spd=1) def speedFastSet(self, *args): cmds.channelBox(self.cb1, e=True, spd=10) def niceNameSet(self, *args): cmds.channelBox(self.cb1, e=True, nn=True, ln=False) def longNameSet(self, *args): cmds.channelBox(self.cb1, e=True, nn=False, ln=True) def shortNameSet(self, *args): cmds.channelBox(self.cb1, e=True, nn=False, ln=False) def channelBoxCommand(self, operation, *args): channelSel = cmds.channelBox(self.cb1, query=True, sma=True) objSel = cmds.ls(sl=True) # reset default channels transformChannels = ["translateX", "translateY", "translateZ", "rotateX", "rotateY", "rotateZ"] scaleChannels = ["scaleX", "scaleY", "scaleZ", "visibility"] if (operation == "-channelEditor"): mel.eval("lockingKeyableWnd;") elif (operation == "-setAllToZero"): for obj in objSel: for channel in transformChannels: cmds.setAttr(obj + "." + channel, 0) for channel in scaleChannels: cmds.setAttr(obj + "." + channel, 1) # reset created channels for obj in objSel: createdChannels = [] allChannels = cmds.listAnimatable(obj) for channel in allChannels: attrName = channel.split(".")[-1] createdChannels.append(attrName) channels = list(set(createdChannels) - set(transformChannels) - set(scaleChannels)) for channel in channels: defaultValue = cmds.addItem(obj + "." + channel, query=True, dv=True) cmds.setAttr(obj + "." + channel, defaultValue) elif (operation == "-keySelected"): print 'Channel Box', channelSel, objSel for obj in objSel: for channel in channelSel: cmds.setKeyframe(obj + "." + channel) elif (operation == "-keyAll"): for obj in objSel: allChannels = cmds.listAnimatable(obj) cmds.select(obj) for channel in allChannels: cmds.setKeyframe(channel) elif (operation == "-breakDownSelected"): for obj in objSel: for channel in channelSel: cmds.setKeyframe(obj + "." + channel, breakdown=True) elif (operation == "-breakDownAll"): for obj in objSel: allChannels = cmds.listAnimatable(obj) cmds.select(obj) for channel in allChannels: cmds.setKeyframe(channel, breakdown=True) elif (operation == "-cutSelected") or (operation == "-deleteSelected"): for obj in objSel: for channel in channelSel: cmds.cutKey(obj, at=channel) elif (operation == "-copySelected"): for obj in objSel: for channel in channelSel: cmds.copyKey(obj, at=channel) elif (operation == "-pasteSelected"): for obj in objSel: for channel in channelSel: cmds.pasteKey(obj, connect=True, at=channel) elif (operation == "-breakConnection"): for obj in objSel: for channel in channelSel: attr = obj + "." + channel mel.eval("source channelBoxCommand; CBdeleteConnection \"%s\"" % attr) elif (operation == "-lockSelected"): for obj in objSel: for channel in channelSel: cmds.setAttr(obj + "." + channel, lock=True) elif (operation == "-unlockSelected"): for obj in objSel: for channel in channelSel: cmds.setAttr(obj + "." + channel, lock=False) elif (operation == "-hideSelected"): for obj in objSel: for channel in channelSel: cmds.setAttr(obj + "." + channel, keyable=False, channelBox=False) elif (operation == "-lockAndHideSelected"): for obj in objSel: for channel in channelSel: cmds.setAttr(obj + "." + channel, lock=True) cmds.setAttr(obj + "." + channel, keyable=False, channelBox=False) elif (operation == "-unhideHided"): # channelBoxChannels = transformChannels + scaleChannels for obj in objSel: # for channel in channelBoxChannels: # cmds.setAttr( obj + "." + channel, l=False, k=True ) # get locked channel lockChannels = cmds.listAttr(obj, locked=True) if lockChannels == None: message = "nothing is locked" self.warningPopup(message) break else: for channel in lockChannels: cmds.setAttr(obj + "." + channel, keyable=True, channelBox=True) elif (operation == "-showDefault"): for obj in objSel: defaultChannel = ["tx", "ty", "tz", "rx", "ry", "rz", "sx", "sy", "sz"] for channel in defaultChannel: cmds.setAttr(obj + "." + channel, k=True, cb=True) elif (operation == "-expression"): mel.eval('expressionEditor EE "" "";') elif (operation == "-unhideHided"): mel.eval('SetDrivenKeyOptions;') elif (operation == "-deleteAttribute"): for obj in objSel: for channel in channelSel: cmds.deleteAttr(obj, at=channel) elif (operation == "-about"): cmds.confirmDialog(t="About DAMG Controller Maker", m=("Thank you for using my script :D\n" "Made by Do Trinh - JimJim\n" "Please feel free to give your feedback\n" "Email me: [email protected]\n"), b="Close")
def bakeNonskins(objects, *args): # bake objects to world space. # create a locator constrained to each object, bake the constraints, then unparent objects, constrain to locators, and bake. print 'RUNNING bakeNonskins' locators = [] constraints = [] for x in range(0, len(objects)): loc = cmds.spaceLocator()[0] locators.append(loc) pc = cmds.parentConstraint(objects[x], loc) sc = cmds.scaleConstraint(objects[x], loc) constraints.append(pc) constraints.append(sc) # bake locators. mel.eval('setNamedPanelLayout "Single Perspective View"') perspPane = cmds.getPanel(vis=1) cmds.scriptedPanel('graphEditor1', e=1, rp=perspPane[0]) start = cmds.playbackOptions(q=1, min=1) end = cmds.playbackOptions(q=1, max=1) cmds.select(locators) cmds.bakeResults(simulation=1, cp=0, s=0, sb=1.0, t=(start, end)) # now, parent objects to world space, then constrain them to the locators in order. # need to delete all channel information first. # in order to run CBdeleteConnection, we need to source a particular MEL. mel.eval('source channelBoxCommand.mel;') for c in constraints: cmds.delete(c) chans = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'] objectsWorldSpace = [] for x in range(0, len(objects)): for ch in chans: melstr = 'CBdeleteConnection "' + objects[x] + '.' + ch + '";' mel.eval(melstr) # unlock channel, in case it's locked cmds.setAttr(objects[x] + '.' + ch, lock=0) # try to parent to world space. if this fails, it's already in world space. try: renamed = cmds.parent(objects[x], w=1)[0] objectsWorldSpace.append(renamed) except RuntimeError: objectsWorldSpace.append(objects[x]) # now apply constraints from the locator with the same index x. cmds.parentConstraint(locators[x], objectsWorldSpace[x]) cmds.scaleConstraint(locators[x], objectsWorldSpace[x]) # now bake out the constraints on objectsWorldSpace. cmds.select(objectsWorldSpace) cmds.bakeResults(simulation=1, cp=0, s=0, sb=1.0, t=(start, end)) for l in locators: cmds.delete(l) # now export objectsWorldSpace as FBX. mel.eval('FBXResetExport;') mel.eval('FBXExportCacheFile -v false;') mel.eval('FBXExportCameras -v true;') cacheDir = os.path.join(cmds.workspace(q=1, fn=1), 'data', 'FBX', os.path.splitext(cmds.file(q=1, sn=1, shn=1))[0], 'keyframes').replace('\\', '/') if not os.path.exists(cacheDir): os.makedirs(cacheDir) fbxFile = os.path.join( cacheDir, os.path.splitext(cmds.file(q=1, sn=1, shn=1))[0] + '_NONSKINS.fbx').replace('\\', '/') cmds.select(objectsWorldSpace) evalStr = 'FBXExport -f "' + fbxFile + '" -s' mel.eval(evalStr) print 'Exported non-skins to %s' % (fbxFile)