def test_file_reference_remove_merge_namespace_parent(self): pm.openFile(self.masterFile, f=1) self.sphereRef1 = pm.FileReference(namespace='sphere1') pm.system.Namespace('sphere1').setCurrent() pm.system.Namespace.create('foobar') pm.system.Namespace('sphere1:foobar').setCurrent() pm.modeling.polyCube(n='testCube') self.tempRef1 = pm.system.createReference(self.sphereFile, namespace='foobar') pm.modeling.polyCube(n=':sphere1:foobar:foobar:bob') self.assertTrue(cmds.objExists(':sphere1:foobar:testCube')) self.assertTrue(cmds.objExists(':sphere1:foobar:foobar:bob')) self.assertFalse(cmds.objExists(':testCube')) self.assertFalse(cmds.objExists(':sphere1:testCube')) self.assertFalse(cmds.objExists(':sphere1:foobar1:testCube')) self.assertFalse(cmds.objExists(':sphere1:foobar:foobar:testCube')) self.assertFalse(cmds.objExists(':bob')) self.assertFalse(cmds.objExists(':sphere1:bob')) self.assertFalse(cmds.objExists(':sphere1:foobar:bob')) self.assertFalse(cmds.objExists(':sphere1:foobar1:bob')) pm.system.FileReference( self.tempRef1).remove(mergeNamespaceWithParent=1) self.assertTrue(cmds.objExists(':sphere1:foobar:testCube')) self.assertTrue(cmds.objExists(':sphere1:foobar:bob')) self.assertFalse(cmds.objExists(':testCube')) self.assertFalse(cmds.objExists(':sphere1:testCube')) self.assertFalse(cmds.objExists(':sphere1:foobar1:testCube')) self.assertFalse(cmds.objExists(':sphere1:foobar:foobar:testCube')) self.assertFalse(cmds.objExists(':bob')) self.assertFalse(cmds.objExists(':sphere1:bob')) self.assertFalse(cmds.objExists(':sphere1:foobar1:bob')) self.assertFalse(cmds.objExists(':sphere1:foobar:foobar:bob'))
def exportAsset(self, fileName=None, assetPath=None, unityPath=None, ignore=None): ''' Export Assets from a .ma animation file as .fbx. ''' pymelLogger.debug('exportAsset(): Starting...') exporter = Export.Export() if not os.path.isfile(fileName): msg = 'File does not exist: %s'%fileName pymelLogger.error(msg) raise Exception(msg) # Open the file pm.openFile(fileName, f=True) pymelLogger.debug('exportAsset(): Opened file: %s'%fileName) # Export the Asset results = None results = exporter.exportAsset(fileName=fileName, assetPath=assetPath, unityPath=unityPath, ignore=ignore) if not results: msg = 'exportAsset(): Nothing exported!' pymelLogger.error(msg) raise Exception(e) for each in results: pymelLogger.debug('Exported: %s'%os.path.basename(each)) pymelLogger.debug('exportAsset(): End.') return results
def open_renderTemplate(json_filepath, renderTemplate_descriptor, assembly_descriptor, animationFile_version): renderTemplate_directory = os.path.join(os.getenv('JOB'), "software", "maya", "scenes", "public") renderTemplate_filepath = find_latest_version(renderTemplate_descriptor, renderTemplate_directory) logging.debug(renderTemplate_filepath) pm.openFile(renderTemplate_filepath, force=True) assembly_root_path = os.path.join(os.getenv('JOB'), "software", "maya", "scenes", "public") assembly_filepath = find_latest_version(assembly_descriptor, assembly_root_path) if assembly_filepath is None: assembly_filepath = os.path.join( assembly_root_path, os.getenv('JOB_ASSET_NAME') + "_" + assembly_descriptor + "_" + "v" + str(animationFile_version) + ".ma") logging.debug("assembly_filepath:" + assembly_filepath) print "[ HA MESSAGE ] Save file: ", assembly_filepath pm.renameFile(assembly_filepath) return assembly_filepath
def open_file_by_path(self, path): # type: (str) -> None # todo add to recent files super(MayaEngine, self).open_file_by_path(path) # now open file in maya pm.openFile(path, force=True)
def open_file_and_export(self): """ Get the env. vars., open the file and export. """ #abc_command abc_command = self.export_dict.get('HELGA_ABC_COMMAND', None) #check if not (abc_command): #log self.logger.debug('HELGA_ABC_COMMAND is None. Not exporting.') return #maya_file maya_file = self.export_dict.get('HELGA_ABC_MAYA_FILE', None) #check if not (maya_file): #log self.logger.debug('HELGA_ABC_MAYA_FILE is None. Not exporting.') return #open file try: pm.openFile(maya_file) except: print('Error opening {0}'.format(maya_file)) #export abc try: pm.mel.eval(abc_command) except: print('Error exporting Alembic.\nAbc cmd: {0}'.format(abc_command))
def copyZoobeAnimations(self,zoobeChar): print 'Importing Zoobe Animations' if zoobeChar: sourceChar = 'source:' + zoobeChar fuseChar = self.name rigFile = os.path.join(CHARACTERS_PATH,self.name,'rigging',self.name + '.ma') zoobeCharFolder = os.path.join(ANIM_LIB_PATH,zoobeChar) if os.path.isdir(zoobeCharFolder): animFiles = [f for f in os.listdir(zoobeCharFolder) if (f.endswith('.ma') or f.endswith('.mb'))] animFile = '/home/zoobe/mixamo/testproject/incoming/animLib/violet/violet_angry_action_01.ma' #self.copyAnimation(animFile,sourceChar,fuseChar,0,300) for anim in animFiles: print animFile animPath = os.path.join(zoobeCharFolder,anim) print animPath pm.openFile(animPath,f=1) start = pm.playbackOptions(q=1,ast=1) end = pm.playbackOptions(q=1,aet=1) print start, end self.copyAnimation(animPath,sourceChar,fuseChar,start,end) print 'saving animation %s'%anim.split('.')[0] self.saveAnimation(anim.split('.')[0]) else: pm.warning('Did not find %s char folder'%zoobeChar)
def exportOgreMesh(self): print 'export mesh' rigFile = os.path.join(CHARACTERS_PATH,self.name,'rigging',self.name+ '.ma') pm.openFile(rigFile,f=1) options = "" options += " -outDir \"" + self.characterPath + "\"" options += " -all -lu pref -scale 1.00" options += " -mesh \"" + self.characterPath + self.name + "_basic.mesh" + "\"" # Various mesh options options += " -n -bn -v -t -tangents TANGENT -preventZeroTangent 100.0" # Material tab options # Material file path matPath = self.characterPath + 'materials/' options += " -mat \"" + matPath + self.name + "_std.material" + "\"" # Various material options texturePath = ASSETS_PATH + 'textures/characters\\\\' options += " -copyTex \"" + texturePath + "\"" if self.hasMorphs: options += " -blendShapes" pm.mel.eval( "ogreExport" + options) print ( "ogreExport" + options)
def test_file_reference_remove_force(self): pm.openFile(self.masterFile, f=1) self.sphereRef1 = pm.FileReference(namespace='sphere1') pm.system.Namespace('sphere1').setCurrent() pm.modeling.polyCube(n='testCube') pm.system.FileReference(self.sphereRef1).remove(force=True) self.assertFalse(pm.general.objExists('testCube'))
def batchExportDirectory(self, dir_list): # if dir_list is None: # path = QtWidgets.QFileDialog.getExistingDirectory(self,dir=pm.sceneName().dirname()) # dir_list = os.listdir(path) err_list = [] # for file_path in progressWin(dir_list,u"批量导出动画"): for file_path in dir_list: if not file_path.endswith(".ma") and not file_path.endswith(".mb"): continue pm.openFile(file_path, f=1) try: self.genereateAnim(False) except: print("=====================================\n") print(file_path + "\n") print("=====================================\n") import traceback traceback.print_exc() err_list.append(file_path) continue if err_list: QtWidgets.QMessageBox.warning( self, u"警告", u"下列文件输出失败\n%s" % u"\n".join(err_list)) else: QtWidgets.QMessageBox.information(self, u"恭喜你", u"输出成功")
def test_export_referenced_mesh(self): ref_cube, ref_joints, ref_skincluster = self.create_skinned_cube() ref_cube_name = ref_cube.nodeName() pm.skinPercent(ref_skincluster, ref_cube.vtx, transformValue=(ref_joints[2], 1.0)) with tempfile.TemporaryDirectory() as tempdir_name: # skin a cube and export it to a separate file ref_filename = os.path.join(tempdir_name, 'ref_test.ma') stuff = [ref_cube] + ref_joints pm.select(stuff, r=True) pm.exportSelected(ref_filename, type='mayaAscii', constructionHistory=True, force=True) # clean scene then reference in the file just exported self._clean_scene() file_reference = pm.createReference(ref_filename) ref_nodes = file_reference.nodes() ref_cube = [ r for r in ref_nodes if r.nodeName().endswith(ref_cube_name) ][0] # export the skin weights dest_filename = os.path.join(tempdir_name, 'test_weights.ma') skinio.export_skinned_mesh(ref_cube, dest_filename) # open the exported skin file pm.openFile(dest_filename, force=True) result_cube = skinutils.get_skinned_meshes_from_scene()[0] result_skincl = skinutils.get_skincluster(result_cube) result_joints = result_skincl.influenceObjects() result = skinutils.get_weighted_influences(result_cube.vtx[0]) expected = {result_joints[2]: 1.0} self.assertEqual(expected, result)
def setup(self): pCore.openFile(MAYA_TEST_FILES_DIR + "FindTagTypes.ma", f=True) self.Tag=mTag.GetExportTagFromSelected('GameRoot')[0] self.Tag.m_Delete() self.Tag=mTag.AddExportTag('GameRoot', 'Character', 'MRIG') self.Tag.AddLoopData('TestLoop',23,46) self.Tag.AddOverRides(Nodes=[pCore.PyNode('L_Leg')])
def check_out_file(self, **kwargs): if self.is_in_perforce() is None: pm.confirmDialog(message="File not in Perforce: " + str(self.path)) return None if not self.is_latest_revision(): if pm.confirmDialog( message= 'File not up to date, would you like to get latest revision and reopen', button=['Yes', 'No']) == 'Yes': print "getting latest" self.get_latest() pm.openFile(self.path, force=True) else: print "checking out older version" if self.is_checked_out(): message = "FILE is checked out: " + str(self.path) if kwargs.get('dialog'): pm.confirmDialog(message=message) return None command = "p4 edit -c default " + str(self.path) if pm.confirmDialog(message='Would you like to check out the file: ' + str(self.path), button=['Yes', 'No']) == 'Yes': print 'PERFORMING CHECKOUT' print self.perform_perforce_command(command) return
def btnOpenFile_click(self): """""" print('btnOpenFile_click') filename = self.leP4Filename.text().strip() if not self.p4: self.initP4() with self.p4.connect(): try: # p4 sync [-f -L -n -N -k -q -r] [-m max] [file[revRange] ...] # p4 sync [-L -n -N -q -s] [-m max] [file[revRange] ...] # p4 sync [-L -n -N -p -q] [-m max] [file[revRange] ...] # --parallel=threads=N[,batch=N][,batchsize=N][,min=N][,minsize=N] sync = self.p4.run('sync', filename) #print(sync) clientFile = sync[0]['clientFile'] self.leLocalFilename.setText(clientFile) pm.openFile(clientFile, o=1, f=1) print(self.p4.run_edit(clientFile)) self.btnOpenFile.setStyleSheet('background-color: green') except P4Exception: for w in self.p4.warnings: print(w) for e in self.p4.errors: print(e) except Exception as ex: print(ex.message)
def openScene(self, path): if os.path.isfile(path): pm.openFile(path.replace('\\', '/'), f=1) self.log('Open {0}'.format(path)) else: self.log('Invalid file name {0}'.format(path), logLevels.lWarning)
def _Load_ChairMAsset_Simple(force=True): _file = "\\\\SERVER9\\Maya-Tools\\testFiles\\eMetaData\\ChairMAsset_Simple.mb" if pCore.sceneName() == _file: if force: pCore.openFile(_file, f=True) else: pCore.openFile(_file, f=True)
def test_file_reference_remove_merge_namespace_root(self): pm.openFile(self.masterFile, f=1) self.sphereRef1 = pm.FileReference(namespace='sphere1') pm.system.Namespace('sphere1').setCurrent() pm.modeling.polyCube(n='testCube') pm.system.FileReference(self.sphereRef1).remove(mergeNamespaceWithRoot=1) self.assertIn('testCube', pm.system.namespaceInfo(':', ls=1))
def createFailedEdits(self): # Animate the zombieAttrs for transform in [x.getParent() for x in pm.ls(type='mesh')]: try: zombie = transform.attr('zombieAttr') except pm.MayaAttributeError: continue zombie.setKey(t=1, v=1) zombie.setKey(t=2, v=2) zombie.setKey(t=3, v=4) # want to create another successful edit, so we can tell just by number of edits # whether we got failed, successful, or both # failed = 1 # successful = 2 # both = 3 pm.setAttr(self.sphereRef1.namespace + ':pSphere1.rotate', (30, 0, 0)) self.masterFile = pm.saveAs(os.path.join(self.temp, 'master.ma'), f=1) # deleting the attr should give some failed ref edits in the master... pm.openFile(self.sphereFile, f=1) pm.SCENE.pSphere1.zombieAttr.delete() pm.saveFile(f=1) pm.openFile(self.masterFile, f=1) self.sphereRef1 = pm.FileReference(namespace='sphere1') self.sphereRef2 = pm.FileReference(namespace='sphere2') self.cubeRef1 = pm.FileReference(namespace='cube1') self.coneRef1 = pm.FileReference(namespace='cone1')
def open_file(self, file_to_open): # type: (dict) -> None # call super method to store file_to_open in context super(MayaEngine, self).open_file(file_to_open) # now open file in maya pm.openFile(file_to_open["path"], force=True)
def exportAnimation(self): exportFolder = ASSETS_PATH + 'characters/' + self.name + '_std/animations/' exportAnimationsPath = os.path.join(CHARACTERS_PATH ,self.name,'animation') animFiles = [] if os.path.isdir(exportAnimationsPath): animFiles = [f for f in sorted(os.listdir(exportAnimationsPath)) if f.endswith('.ma') or f.endswith('.ma') ] else: pm.warning('No animation files found, aborting!') return #self.logger.info('########### Exporting animations for OGRE ###########') for anim in animFiles: animFile = os.path.join(exportAnimationsPath,anim) pm.openFile(animFile,f=1) start = int(pm.playbackOptions(q=1,ast=1)) end = int(pm.playbackOptions(q=1,aet=1)) #ogreExport -all -outDir "P:/mixamo_character/assets/characters/EveBavaria_std/animations/" -skeletonClip "EveBavaria_action_unjured_walk_35" startEnd 0 34 frames sampleByFrames 1 -lu pref -scale 1.00 -skeletonAnims -skelBB -np bindPose cmd = 'ogreExport -all -outDir "'+ exportFolder + '"' cmd += ' -skeletonClip "' + anim.split('.')[0] + '"' if 'speak' in anim: cmd += ' startEnd 0 1' else: cmd += ' startEnd ' + str(start) + ' ' + str(end) cmd += ' frames sampleByFrames 1 -lu pref -scale 1.00 -skeletonAnims -skelBB -np bindPose' pm.mel.eval(cmd)
def test_failed_ref_edits(self): # Animate the zombieAttrs for transform in [x.getParent() for x in pm.ls(type='mesh')]: try: zombie = transform.attr('zombieAttr') except pm.MayaAttributeError: continue zombie.setKey(t=1, v=1) zombie.setKey(t=2, v=2) zombie.setKey(t=3, v=4) self.masterFile = pm.saveAs( os.path.join( self.temp, 'master.ma' ), f=1 ) pm.openFile(self.sphereFile, f=1) pm.SCENE.pSphere1.zombieAttr.delete() pm.saveFile(f=1) # deleting the attr should give some failed ref edits... pm.openFile(self.masterFile, f=1) sphereRefs = [x for x in pm.listReferences(recursive=True) if x.path.endswith('sphere.ma')] for ref in sphereRefs: print "testing failed ref edits on: %s" % ref self.assertEqual(1, len(pm.referenceQuery(ref,successfulEdits=False,failedEdits=True,es=True))) self.assertEqual(1, len(cmds.referenceQuery(str(ref.refNode), successfulEdits=False,failedEdits=True,es=True)))
def createFailedEdits(self): # Animate the zombieAttrs for transform in [x.getParent() for x in pm.ls(type='mesh')]: try: zombie = transform.attr('zombieAttr') except pm.MayaAttributeError: continue zombie.setKey(t=1, v=1) zombie.setKey(t=2, v=2) zombie.setKey(t=3, v=4) # want to create another successful edit, so we can tell just by number of edits # whether we got failed, successful, or both # failed = 1 # successful = 2 # both = 3 pm.setAttr(self.sphereRef1.namespace + ':pSphere1.rotate', (30,0,0)) self.masterFile = pm.saveAs(os.path.join(self.temp, 'master.ma'), f=1) # deleting the attr should give some failed ref edits in the master... pm.openFile(self.sphereFile, f=1) pm.SCENE.pSphere1.zombieAttr.delete() pm.saveFile(f=1) pm.openFile(self.masterFile, f=1) self.sphereRef1 = pm.FileReference(namespace='sphere1') self.sphereRef2 = pm.FileReference(namespace='sphere2') self.cubeRef1 = pm.FileReference(namespace='cube1') self.coneRef1 = pm.FileReference(namespace='cone1')
def shotOpen(partField, sequenceField, shotField, listBrunch): # Open LAST version of the shot codePart = partField.getText() codeSequence = sequenceField.getText() codeShot = shotField.getText() print 'dnaCore.shotOpen [INPUTS] = {3}: {0} E{1} SHOT_{2}'.format( codePart, codeSequence, codeShot, listBrunch[1].split('/')[0]) fullName = '{0}{1}{2}/{3}/SHOT_{4}/{5}E{3}_S{4}_001.mb'.format( rootScene, listBrunch[1], codePart, codeSequence, codeShot, listBrunch[2]) print 'FILE NAME: {0}{1}{2}/{3}/SHOT_{4}/{5}E{3}_S{4}_001.mb'.format( rootScene, listBrunch[1], codePart, codeSequence, codeShot, listBrunch[2]) if os.path.exists(fullName): # IF FILE EXISTS listExisted = glob.glob( '{0}{1}{2}/{3}/SHOT_{4}/{5}E{3}_S{4}_*.mb'.format( rootScene, listBrunch[1], codePart, codeSequence, codeShot, listBrunch[2])) # check existed version listVersions = [] print listExisted for i in listExisted: v = i.split('\\')[-1].split('.mb')[0].split('_')[-1] listVersions.append(v) versionCurrent = int( max(listVersions)) # create number for latest version fullName = '{0}{1}{2}/{3}/SHOT_{4}/{5}E{3}_S{4}_{6:03d}.mb'.format( rootScene, listBrunch[1], codePart, codeSequence, codeShot, listBrunch[2], versionCurrent) pm.openFile(fullName, f=1) pm.mel.addRecentFile(fullName, 'mayaBinary') else: pm.confirmDialog(title='Warning!', message='NO {2} FILE EXISTS FOR: E{0}_S{1}'.format( codeSequence, codeShot, listBrunch[1].split('/')[0]))
def start(*args): from maya import standalone standalone.initialize(name='python') from pymel import core core.openFile(args[0], f=True) result = None if args[1].endswith('.mel'): try: core.mel.eval('source \"%s\"' % args[1]) result = True except Exception as error: warnings.warn(str(error), Warning) result = False else: code_dirname = os.path.dirname(args[1]) code_name = os.path.splitext(os.path.basename(args[1]))[0] for module_loader, name, ispkg in pkgutil.iter_modules([code_dirname]): if name != code_name: continue loader = module_loader.find_module(name) try: module = loader.load_module(name) result = True except Exception as error: warnings.warn(str(error), Warning) result = False if not result: return if args[2] != 'None': core.saveAs(args[2], f=True, iv=True, pmt=True) standalone.uninitialize(name='python')
def export_maya_file(): ''' Test method to use headless maya to open and export a Maya file to FBX from outside of Maya ''' import os import sys environ_str = "" for key, value in os.environ.iteritems(): environ_str = environ_str + key + " : " + value + "; \n" path_str = "" for path in sys.path: path_str = path_str + path + "; \n" file = open(r"C:\Users\micahz\Documents\temp\log.txt", "w") file.writelines([sys.executable, "\n\n", environ_str, "\n", path_str]) file.close() import maya.standalone maya.standalone.initialize(name='python') import pymel.core as pm pm.loadPlugin("fbxmaya") pm.openFile( r"D:\v1\content\Robogore\Data\Levels\Cinematics\Gravcycle_Intro\Gravcycle_Rig.ma" ) pm.select(all=True) pm.mel.FBXExport(f=r"C:\Users\micahz\Documents\temp\headless_maya.fbx") maya.standalone.uninitialize()
def loadAnimFile(self, file_path, index): # NOTE 打开文件 pm.openFile(file_path, f=1) target = self.target_line.text() source = self.source_line.text() for hik_node in pm.ls(typ="HIKCharacterNode"): if source in str(hik_node): source = hik_node break else: err_msg = "%s - 找不到旧绑定 HIK角色 " % file_path self.error_list.append(err_msg) return # NOTE 导入 reference rig_path = self.rig_line.text() name, ext = os.path.splitext(os.path.basename(rig_path)) ref = pm.createReference(rig_path, r=1, namespace=name) target = "%s:%s" % (name, target) if ":" not in target else target if not pm.objExists(target): err_msg = "%s - 找不到新绑定 HIK角色 " % file_path self.error_list.append(err_msg) return # NOTE 重定向 pm.mel.hikSetCharacterInput(target, source) export_path = self.export_line.text() pm.renameFile(os.path.join(export_path, pm.sceneName().basename())) pm.saveFile(f=1)
def start_open_maya(self): self.print_info("start maya ok.") self.print_info("open maya file: " + self["cg_file"]) if self["cg_project"]: if os.path.exists(self["cg_project"]): workspacemel = os.path.join(self["cg_project"], "workspace.mel") if not os.path.exists(workspacemel): try: with open(workspacemel, "w"): '' except: pass if os.path.exists(workspacemel): pm.mel.eval('setProject "%s"' % (self["cg_project"])) # ignore some open maya errors. if os.path.exists(self["cg_file"]) and os.path.isfile(self["cg_file"]): try: # pm.openFile(options["cg_file"], force=1, ignoreVersion=1, prompt=0, loadReferenceDepth="all") pm.openFile(self["cg_file"], force=1, ignoreVersion=1, prompt=0) self.print_info("open maya file ok.") except: pass else: raise Exception("Dont Found the maya files error.")
def increment_and_save(current_file, entity_type="Asset", publish=0): scene_directory = pm.workspace.expandName(pm.workspace.fileRules["scene"]) file_name = scene_directory.rsplit("/", 1)[1][4:] # model_a if "Shot" == entity_type: file_name = scene_directory.rsplit("/", 1)[1] # Shot_### processed_file = None if current_file and publish: processed_file = "{}/{}_processed.{}.ma".format( scene_directory, file_name, str(int(current_file.split(".")[1][1:]) + 1).zfill(4)) elif current_file and not publish: pm.openFile(current_file, f=1) processed_file = current_file.replace("original", "processed").replace( "published", "scenes") # print ">> checked out" elif not current_file: directory = pm.util.common.path(scene_directory) files = directory.files(file_name + "_processed.*.ma") if files: latest_processed = max(files, key=get_version) old = max(files, key=get_version).split(".")[1] new = "{:04d}".format(int(old) + 1) version = ".{}.".format(new) processed_file = version.join(latest_processed.split(".")[::2]) else: processed_file = "{}/{}_processed.0001.ma".format( scene_directory, file_name) # print ">> new:", processed_file pm.saveAs(processed_file) return processed_file
def del_maya_lic_string(self): ''' Deletes the license info in the mayaAscii file. ''' logger.debug("Maya License String") # Get Scene Path filePath = pmc.sceneName() if filePath.splitext()[-1] == ".mb": logger.warning("Scene needs to be saved as .ma!") return False bakPath = filePath + ".bak" # Closing the scene to prevent crashes try: pmc.newFile() except RuntimeError as e: logger.error("Could not close scene!") logger.error(e) return False # Creating Backup file try: shutil.copy(filePath, bakPath) except IOError as e: logger.error("Could not create backup file!") logger.error(e) return False else: logger.info("Created Backup file") # transfering file content, line by line try: with open(bakPath, "r") as srcFile: with open(filePath, "w") as trgFile: for line in srcFile: if 'fileInfo "license" "student";' in line: logger.info("Student License String found") trgFile.write('fileInfo "license" "education";') else: trgFile.write(line) except IOError as e: logger.error( "An Error occurred while reading/writing the scene file") logger.error(e) return False # Reopening current scene try: pmc.openFile(filePath) except IOError as e: logger.error("Could not reopen current scene!") logger.error(e) return False except RuntimeError as e: logger.error(e) return False return True
def test_file_reference_remove_merge_namespace_root(self): pm.openFile(self.masterFile, f=1) self.sphereRef1 = pm.FileReference(namespace='sphere1') pm.system.Namespace('sphere1').setCurrent() pm.modeling.polyCube(n='testCube') pm.system.FileReference( self.sphereRef1).remove(mergeNamespaceWithRoot=1) self.assertIn('testCube', pm.system.namespaceInfo(':', ls=1))
def test_ik_bake(self): pm.openFile(r"C:\Users\micahz\Documents\rigging\rigging_test.ma", force=True) jnt = pm.ls(type='joint')[0] skeleton_dict = rigging.skeleton.get_skeleton_dict(jnt) ik_comp = rigging.ik.IK() self.assertTrue( ik_comp.rig(skeleton_dict, 'right', 'arm') ) self.assertTrue( ik_comp.bake_and_remove() )
def test_fk_remove(self): pm.openFile(r"C:\Users\micahz\Documents\rigging\rigging_test.ma", force=True) jnt = pm.ls(type='joint')[0] skeleton_dict = rigging.skeleton.get_skeleton_dict(jnt) fk_comp = rigging.fk.FK() self.assertTrue( fk_comp.rig(skeleton_dict, 'left', 'arm') ) self.assertTrue( fk_comp.remove() )
def openMayaFile(): global mayaFilePath global mayaProjectPath mayaProjectPath = os.path.abspath(mayaFilePath.rsplit('\\',2)[0]) print("Project path: {}\nFile path: {}\nWill open file now...".format(mayaProjectPath, mayaFilePath)) pc.mel.setProject(mayaProjectPath) pc.openFile(mayaFilePath, force=True)
def bdExportHIKAnim(fromFolder,toFolder,charName,charType): animFiles = [f for f in os.listdir(fromFolder) if (f.endswith('.ma') or f.endswith('.mb'))] for anim in animFiles: animFile = os.path.join(fromFolder,anim) pm.openFile(animFile,f=1) start = pm.playbackOptions(q=1,min=1) end = pm.playbackOptions(q=1,max=1)
def test_file_reference_remove_merge_namespace_parent(self): pm.openFile(self.masterFile, f=1) self.sphereRef1 = pm.FileReference(namespace='sphere1') pm.system.Namespace('sphere1').setCurrent() pm.system.Namespace.create('foobar') pm.system.Namespace('sphere1:foobar').setCurrent() pm.modeling.polyCube(n='testCube') self.tempRef1 = pm.system.createReference(self.sphereFile, namespace='foobar') pm.system.FileReference(self.tempRef1).remove(mergeNamespaceWithParent=1) self.assertIn('sphere1:testCube', pm.system.namespaceInfo('sphere1', ls=1))
def openAsset(): try: QtGui.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor) container = sandbox.get(pm.workspace.path)[0] except: container = None finally: QtGui.QApplication.restoreOverrideCursor() dialog = BrowserDialog(modal=True) dialog.setBrowseType(BrowserDialog.BrowseRevisions) dialog.setHintText("Select a revision.") dialog.setCwd(pm.workspace.path) dialog.setSelectedItem(container) if dialog.exec_() == QtGui.QDialog.Accepted: revision = dialog.selectedItem() if not revision: return container = revision.container work_root = sandbox.get_path(container) # set the project mayautils.setProject(work_root) # check if the user has saved if cmds.file(query=True, anyModified=True): result = pm.confirmDialog(title="Save Changes", message="Save changes to " + pm.sceneName() + "?", button=["Save", "Don't Save", "Cancel"], defaultButton="Save", cancelButton="Cancel", dismissString="Don't Save") if result == "Cancel": return elif result == "Save": cmds.file(save=True, force=True) else: # "Don"t Save" pass # get revision path tank_path = revision.system.vfs_full_paths[0] # tank_root, tank_filename = os.path.split(tank_path) # tank_filename, tank_ext = os.path.splitext(tank_filename) # # # remove "-v006-1451_96" from end of filename # tank_filename = re.sub(r"-v[0-9]+-[0-9_]+$", "", tank_filename) # # open revision pm.openFile(tank_path, force=True)
def open_(self, version, force=False): """The open action for Maya environment. Opens the given Version file, sets the workspace etc. It also updates the referenced Version on open. :returns: list of :class:`~oyProjectManager.models.version.Version` instances which are referenced in to the opened version and those need to be updated """ # store current workspace path previous_workspace_path = pm.workspace.path # set the project new_workspace = os.path.dirname(version.path) #self.create_workspace_file(workspace_path) #self.create_workspace_folders(workspace_path) pm.workspace.open(new_workspace) # check for unsaved changes logger.info("opening file: %s" % version.full_path) try: pm.openFile(version.full_path, f=force, loadReferenceDepth='none') except RuntimeError as e: # restore the previous workspace pm.workspace.open(previous_workspace_path) # raise the RuntimeError again # for the interface raise e # set the playblast folder self.set_playblast_file_name(version) self.append_to_recent_files(version.full_path) # replace_external_paths self.replace_external_paths(mode=1) # check the referenced assets for newer version to_update_list = self.check_referenced_versions() #for update_info in to_update_list: # version = update_info[0] self.update_references_list(version) return True, to_update_list
def copyAnimation(self,sourceAnim,sourceChar,fuseChar,start,end): rigFile = os.path.join(CHARACTERS_PATH,self.name,'rigging',self.name + '.ma') pm.openFile(rigFile,f=1) referenceAnim = pm.createReference(sourceAnim,namespace='source') pm.playbackOptions(e=1,ast=start,aet=end,min=start,max=end) pm.mel.eval('hikSetCurrentCharacter("' + fuseChar + '")') #pm.mel.eval('mayaHIKsetStanceInput( "' + fuseChar + '" )') #pm.mel.eval('HIKCharacterControlsTool()') pm.mel.eval('hikToggleLockDefinition') #self.logger.info('Characterized the skeleton') pm.mel.eval('mayaHIKsetCharacterInput( "' + fuseChar + '","' + sourceChar + '")') #pm.mel.eval('HIKCharacterControlsTool()') pm.mel.eval('hikBakeCharacter 0') referenceAnim.remove()
def test_file_reference_remove_merge_namespace_parent(self): pm.openFile(self.masterFile, f=1) self.sphereRef1 = pm.FileReference(namespace='sphere1') pm.system.Namespace('sphere1').setCurrent() pm.system.Namespace.create('foobar') pm.system.Namespace('sphere1:foobar').setCurrent() pm.modeling.polyCube(n='testCube') self.tempRef1 = pm.system.createReference(self.sphereFile, namespace='foobar') pm.modeling.polyCube(n=':sphere1:foobar:foobar:bob') self.assertTrue(cmds.objExists(':sphere1:foobar:testCube')) self.assertTrue(cmds.objExists(':sphere1:foobar:foobar:bob')) self.assertFalse(cmds.objExists(':testCube')) self.assertFalse(cmds.objExists(':sphere1:testCube')) self.assertFalse(cmds.objExists(':sphere1:foobar1:testCube')) self.assertFalse(cmds.objExists(':sphere1:foobar:foobar:testCube')) self.assertFalse(cmds.objExists(':bob')) self.assertFalse(cmds.objExists(':sphere1:bob')) self.assertFalse(cmds.objExists(':sphere1:foobar:bob')) self.assertFalse(cmds.objExists(':sphere1:foobar1:bob')) pm.system.FileReference(self.tempRef1).remove(mergeNamespaceWithParent=1) # Before maya 2018, there was a bug where removing the ref, which lives # in "sphere1:foobar:foobar", would also delete "sphere1:foobar" - # leaving just "sphere1:", where everything was moved into... if pymel.versions.current() < pymel.versions.v2018: # when it deletes sphere1:foobar, it tries to move sphere1:foobar:foobar # to sphere1:foobar... but apparently that causes a name conflict, # so it makes sphere1:foobar1 instead self.assertTrue(cmds.objExists(':sphere1:testCube')) self.assertTrue(cmds.objExists(':sphere1:foobar1:bob')) self.assertFalse(cmds.objExists(':testCube')) self.assertFalse(cmds.objExists(':sphere1:foobar:testCube')) self.assertFalse(cmds.objExists(':sphere1:foobar1:testCube')) self.assertFalse(cmds.objExists(':sphere1:foobar:foobar:testCube')) self.assertFalse(cmds.objExists(':bob')) self.assertFalse(cmds.objExists(':sphere1:bob')) self.assertFalse(cmds.objExists(':sphere1:foobar:bob')) self.assertFalse(cmds.objExists(':sphere1:foobar:foobar:bob')) else: self.assertTrue(cmds.objExists(':sphere1:foobar:testCube')) self.assertTrue(cmds.objExists(':sphere1:foobar:bob')) self.assertFalse(cmds.objExists(':testCube')) self.assertFalse(cmds.objExists(':sphere1:testCube')) self.assertFalse(cmds.objExists(':sphere1:foobar1:testCube')) self.assertFalse(cmds.objExists(':sphere1:foobar:foobar:testCube')) self.assertFalse(cmds.objExists(':bob')) self.assertFalse(cmds.objExists(':sphere1:bob')) self.assertFalse(cmds.objExists(':sphere1:foobar1:bob')) self.assertFalse(cmds.objExists(':sphere1:foobar:foobar:bob'))
def setUpClass(self): cwd = os.path.dirname(os.path.realpath(__file__)) # set project in tmp ddir self.projectPath = os.path.join(cwd, 'tmpProj') pm.mel.setProject(self.projectPath) # open mock file pm.openFile(os.path.join(cwd, 'mocks', 'mockController.ma'), f=1) self.cc = CharacterCrowd(createUI=False) self.item = pm.ls('main')[0] # clean out cache dir cacheDir = os.path.join( self.projectPath, 'cache', 'characterCrowd' ) shutil.rmtree(cacheDir)
def bdPerformPlayblast(self,folder,outFolder,characterRig, blastFormat, blastCompression, referenceCam): animDir = folder animFiles = [] for i in range(self.mayaFilesTableWidget.rowCount()): status = self.mayaFilesTableWidget.item(i,0).text() if status == 'Yes': animFiles.append(self.mayaFilesTableWidget.item(i,1).text()) #pm.mel.eval('setAllMainWindowComponentsVisible 0;') for f in sorted(animFiles): pathFile = animDir + '/' + f if outFolder == '': pathMovie = 'movies/' + f[:-3] else: pathMovie = outFolder + '/' +f[:-3] if os.path.isfile(pathFile): print pathFile else: print 'no file' return checkFileCallbackId = OM.MSceneMessage.addCheckFileCallback(OM.MSceneMessage.kBeforeReferenceCheck, self.bdReplaceRig) pm.newFile(f=1) pm.openFile(pathFile,f=1) #pm.mel.eval('setNamedPanelLayout "Four View"; updateToolbox();') ''' openWin = pm.lsUI(windows=1) for win in openWin: if 'MayaWindow' not in win.name() and WINDOW_NAME not in win.name() and 'scriptEditorPanel' not in win.name(): pm.deleteUI(win) ''' pm.setAttr("defaultResolution.width",1280) pm.setAttr("defaultResolution.height",720) OM.MMessage.removeCallback(checkFileCallbackId) self.bdSetCamera(referenceCam) print folder,outFolder,characterRig, blastFormat, blastCompression, referenceCam try: self.mayaFilesTableWidget.item(row,0).setBackground(QtGui.QColor(255,100,150)) self.mayaFilesTableWidget.item(row,1).setBackground(QtGui.QColor(255,100,150)) pm.playblast(format = blastFormat, filename = pathMovie,forceOverwrite=1,sequenceTime=0,clearCache=0,viewer=0,showOrnaments=1,fp=4,percent = 100,compression = blastCompression,quality=100, widthHeight= [1280, 720]) except: print "WTF!!!!!!!!!!!" progress = (float(animFiles.index(f) + 1.0) / float(len(animFiles)) ) * 100.0 self.progressBar.setValue(int(progress)) row = animFiles.index(f)
def open_scene(self, scene): """ Open maya scene. param scene: Path to maya scene file. """ scene = pm.openFile(scene, force=True) self.log.info("Open scene file: %s" % scene) return scene
def openMayaFile(self,filename,folder): f='' wipPath = self.wipFolderEdit.text() print filename, folder if folder == 'wip': f = os.path.abspath(os.path.join(wipPath,filename)) elif folder == 'preview': f = os.path.abspath(os.path.join(wipPath.replace('01_wip','03_preview'),filename)) if os.path.isfile(f): saveDlg = saveChangesDlg() #saveDlg.setFixedSize(800, 300) result = saveDlg.exec_() if result == 1: pm.saveFile() pm.openFile(f) elif result == 2: pm.openFile(f,f=1)
def bdPlayblastFolderVP2(folder,outFolder,codec, cleanName=0): animDir = folder animFiles = [os.path.splitext(f)[0] for f in sorted(os.listdir(animDir)) if f.endswith('.mb')] if not cleanName: lastVersions = [] temp = [] for f in animFiles: if '_v' in f: fileName = f[:-4] temp.append(fileName) temp1 = list(set(temp[:])) for t in temp1: lastVersions.append(t + '_v0' + str(temp.count(t))) animFiles = lastVersions for f in sorted(animFiles): pathFile = animDir + f + '.mb' if outFolder == '': pathMovie = 'movies/' + f else: pathMovie = outFolder + f if os.path.isfile(pathFile): print pathFile else: print 'no file' #checkFileCallbackId = OM.MSceneMessage.addCheckFileCallback(OM.MSceneMessage.kBeforeReferenceCheck, bdReplaceRig) pm.mel.eval('ActivateViewport20') pm.openFile(pathFile,f=1) pm.mel.eval('setCameraNamesVisibility 0') pm.select('zoo:body') pm.hyperShade(assign = 'zoo:cat_body_linkSHD') pm.select(cl=1) pm.setAttr("defaultResolution.width",1280) pm.setAttr("defaultResolution.height",720) bdSetCameraVP2('cam:cameraShape1') pm.playblast(format = 'avi', filename = pathMovie,forceOverwrite=1,sequenceTime=0,clearCache=0,viewer=0,showOrnaments=1,fp=4,percent = 100,compression=codec, quality=100, widthHeight= [1280, 720])
def shotOpen(partField, sequenceField, shotField, listBrunch): # Open LAST version of the shot codePart = partField.getText() codeSequence = sequenceField.getText() codeShot = shotField.getText() print 'dnaCore.shotOpen [INPUTS] = {3}: {0} E{1} SHOT_{2}'.format(codePart, codeSequence, codeShot, listBrunch[1].split('/')[0]) fullName = '{0}{1}{2}/{3}/SHOT_{4}/{5}E{3}_S{4}_001.mb'.format(rootScene, listBrunch[1], codePart, codeSequence, codeShot, listBrunch[2] ) print 'FILE NAME: {0}{1}{2}/{3}/SHOT_{4}/{5}E{3}_S{4}_001.mb'.format(rootScene, listBrunch[1], codePart, codeSequence, codeShot, listBrunch[2] ) if os.path.exists(fullName): # IF FILE EXISTS listExisted = glob.glob ('{0}{1}{2}/{3}/SHOT_{4}/{5}E{3}_S{4}_*.mb'.format(rootScene, listBrunch[1], codePart, codeSequence, codeShot, listBrunch[2] ) ) # check existed version listVersions = [] print listExisted for i in listExisted: v = i.split('\\')[-1].split('.mb')[0].split('_')[-1] listVersions.append(v) versionCurrent = int(max(listVersions))# create number for latest version fullName = '{0}{1}{2}/{3}/SHOT_{4}/{5}E{3}_S{4}_{6:03d}.mb'.format(rootScene, listBrunch[1], codePart, codeSequence, codeShot, listBrunch[2], versionCurrent) pm.openFile(fullName, f = 1) pm.mel.addRecentFile (fullName, 'mayaBinary') else: pm.confirmDialog (title = 'Warning!', message = 'NO {2} FILE EXISTS FOR: E{0}_S{1}'.format(codeSequence, codeShot, listBrunch[1].split('/')[0] ))
def openMayaFile(self,filename,folder): f='' wipPath = self.wipFolderEdit.text() print filename, folder if folder == 'wip': f = os.path.abspath(os.path.join(wipPath,filename)) elif folder == 'preview': f = os.path.abspath(os.path.join(wipPath.replace('01_wip','03_preview'),filename)) if os.path.isfile(f): saveDlg = saveChangesDlg() #saveDlg.setFixedSize(800, 300) result = saveDlg.exec_() if result == 1: pm.saveFile() pm.openFile(f) elif result == 2: pm.openFile(f,f=1) pm.optionVar(stringValueAppend=('RecentFilesList', currentFile)) pm.optionVar(stringValueAppend=('RecentFilesTypeList', 'mayaAscii'))
def importAnimation(self, speak=0,lib=1): print 'Importing Animation' rigFile = os.path.join(CHARACTERS_PATH,self.name,'rigging',self.name + '.ma') pm.openFile(rigFile,f=1) if lib: importAnimPath = ANIM_LIB_PATH else: fbxPath = os.path.split(self.fbxFile)[0] importAnimPath = fbxPath + '/' + 'animations/' animFiles = [f for f in os.listdir(importAnimPath) if f.endswith('.fbx')] #self.logger.info('########### Importing animations from library ############') for anim in animFiles: pm.mel.eval('FBXImportFillTimeline -v 1;') cmd = 'FBXImport -f "' + importAnimPath + anim+ '" -caller \"FBXMayaTranslator\" -importFormat \"fbx;v=0\"' pm.mel.eval(cmd) #self.logger.info('Imported %s ', (importAnimPath + anim)) #pm.importFile(importAnimPath + anim, type='FBX',mergeNamespacesOnClash=0,rpr=anim.split('.')[0],options = 'v=0;',loadReferenceDepth = 'all') start = pm.playbackOptions(q=1,ast=1) end = pm.playbackOptions(q=1,aet=1) pm.bakeResults( 'shadowJoint',t=(start,end), simulation=True ) self.saveAnimation(anim.split('.')[0]) pm.openFile(rigFile,f=1) if speak: #self.logger.info('Creating speak anims ') for anim in speakAnims: pm.openFile(rigFile,f=1) animationFile = os.path.join(CHARACTERS_PATH,self.name,'animation',anim + '.ma') #self.logger.info('%s created',animationFile) pm.saveAs(animationFile,f=1)
def bdReadCSV(csvFile,char): with open(csvFile,'rb') as file: contents = csv.reader(file) matrix = list() for row in contents: matrix.append(row) for r in matrix: if char.lower() in r[1].lower(): index = matrix.index(r) rigPath = matrix[index][3] rigFile = matrix[index][2] if os.path.isfile(rigPath + '/' + rigFile): pm.openFile(rigPath + '/' + rigFile,f=1) meshPath = matrix[index][7] meshFile = matrix[index][6] meshFilePath = meshPath + '/' + meshFile if os.path.isfile(meshFilePath + '.mesh'): os.rename(meshFilePath + '.mesh', meshFilePath + '_old.mesh') osMeshExport(meshPath,meshFile) else: pm.error('Didnt find the rig file %s'%rigFile)
def exportAnim(self, fileName=None, assetPath=None, unityPath=None, ignore=None): ''' Export rig and/or prop animation from a .ma animation file as .fbx. ''' pymelLogger.debug('exportAnim(): Starting...') exporter = Export.Export() #pdb.set_trace() if not os.path.isfile(fileName): msg = 'File does not exist: %s'%fileName pymelLogger.error(msg) raise Exception(msg) # Open the file pm.openFile(fileName, f=True) pymelLogger.debug('exportAnim(): Opened file: %s'%fileName) # Export the animation results = exporter.exportAnim(fileName=fileName, assetPath=assetPath, unityPath=unityPath, ignore=ignore) pymelLogger.debug('exportAnim(): End.') return results
def bdPlayblastFolder(folder,outFolder,characterRig,codec, camera, referenceCam='', cleanName=0): CHARACTER_RIG = characterRig print CHARACTER_RIG animDir = folder animFiles = [os.path.splitext(f)[0] for f in sorted(os.listdir(animDir)) if f.endswith('.ma')] if not cleanName: lastVersions = [] temp = [] for f in animFiles: if '_v' in f: fileName = f[:-4] temp.append(fileName) temp1 = list(set(temp[:])) for t in temp1: lastVersions.append(t + '_v0' + str(temp.count(t))) animFiles = lastVersions for f in sorted(animFiles): pathFile = animDir + f + '.ma' if outFolder == '': pathMovie = 'movies/' + f else: pathMovie = outFolder + f if os.path.isfile(pathFile): print pathFile else: print 'no file' checkFileCallbackId = OM.MSceneMessage.addCheckFileCallback(OM.MSceneMessage.kBeforeReferenceCheck, bdReplaceRig) pm.openFile(pathFile,f=1) pm.setAttr("defaultResolution.width",1280) pm.setAttr("defaultResolution.height",720) bdSetCamera(camera,referenceCam) pm.playblast(format = 'avi', filename = pathMovie,forceOverwrite=1,sequenceTime=0,clearCache=0,viewer=0,showOrnaments=1,fp=4,percent = 100,compression=codec,quality=100, widthHeight= [1280, 720]) OM.MMessage.removeCallback(checkFileCallbackId)
def transferAnimation( targetFile="", prefix=False, prefixName='ref:' ): """ Set the Target Scene and selected the controls to transfer. """ pm.select( pm.ls( sl=1 ), replace=True ) control_list = map( str, pm.ls( sl=1 ) ) if not control_list: mel.error( "No Controls Selected for Transfer!" ) startTime = pm.playbackOptions( query=True, animationStartTime=True ) minTime = pm.playbackOptions( query=True, minTime=True ) maxTime = pm.playbackOptions( query=True, maxTime=True ) endTime = pm.playbackOptions( query=True, animationEndTime=True ) tempPose = Pose() tempPose.capture() pm.copyKey( control_list, hierarchy=False ) pm.openFile( targetFile, force=False ) if _checkControls( control_list ): if prefix: tempPose.apply( alterNamespace=True, namespace=prefixName ) else: tempPose.apply() pm.pasteKey( control_list, option='replaceCompletely', copies=1, connect=1, timeOffset=0, floatOffset=0, valueOffset=0 ) pm.playbackOptions( minTime=minTime, ast=startTime, maxTime=maxTime, aet=endTime ) else: raise
def duplicateAssets(): path = pm.workspace.name + '/gfxlib/effects/' name = 'status_enhancement_' tempList = glob.glob(path + '*_t*_m.mb') for fl in tempList: path,filename = os.path.split(fl) #destFile = filename.replace('_m','_s') destFile = filename.replace('_m','_l') if(os.path.isfile(os.path.join(path,destFile))): pm.warning('File exists!') pm.openFile(os.path.join(path,destFile),f=1) else: shutil.copyfile(fl,os.path.join(path,destFile)) pm.openFile(os.path.join(path,destFile),f=1) modelGrp = pm.ls('model')[0] #modelGrp.scaleBy((0.5,0.5,0.5)) modelGrp.scaleBy((3.2,3.2,3.2)) pm.makeIdentity(modelGrp,apply=True,t=0,r=0,s=1) pm.saveAs(os.path.join(path,destFile),f=1) pm.mel.eval('rlExportGraphicsObjectNoBrowserN3')