def __exit__(s, err, val, trace): """ Remove those things from the scene """ cmds.fileInfo(rm=s.uid) if cmds.objExists(s.job): cmds.delete(s.job)
def stateFromFileInfo(): from fnmatch import fnmatch selInfo = m.fileInfo('onSaveSelection', q=1) if len(selInfo) != 0: sel = [] for i in selInfo[0].split('?'): if m.objExists(i): sel.append(i) if len(sel): m.select(sel) hilite = [] c1 = ['f[*','e[*','map[*','vtx[*','vtxFace[*'] c2 = ['facet','edge','puv','vertex','pvf'] for x in sel: if x.count('.'): parts = x.split('.') for i in range(5): if fnmatch(parts[1],c1[i]) and parts[0] not in hilite: hilite.append(parts[0]) mel.eval('doMenuComponentSelection("' + parts[0] + '", "' + c2[i] + '");') ctxInfo = m.fileInfo('onSaveCtx', q=1) if len(ctxInfo) != 0: print ('ctxInfo: ' + str(ctxInfo)) try: m.setToolTo(ctxInfo[0]) except: print 'could not set "' + ctxInfo[0] + '"!'
def write(v): ''' write qc date and qc value to file info ''' import time cmds.fileInfo('qc_date',time.ctime()) cmds.fileInfo('qc_value',str(v))
def convert_to_education(): print("file info: ", pm.FileInfo().items()) mc.fileInfo(rm="license") print("file info: ", pm.FileInfo().items()) # pm.FileInfo()['license'] = 'commercial' fileName = pm.sceneName() pm.saveFile()
def __enter__(s): s.job = cmds.scriptNode(n=s.uid, st=2, bs="") s.code = """ import maya.cmds as cmds uid = "%(uid)s" job = "%(job)s" if cmds.fileInfo(uid, q=True) == ["ok"]: def makepopup(): p = cmds.setParent(q=True) cmds.rowLayout(nc=2, ad2=2, p=p) cmds.columnLayout() %(image)s cmds.setParent("..") cmds.columnLayout(adj=True) cmds.text(al="left", hl=True, l=\"\"\"%(message)s\"\"\", h=70) cmds.button(l="Thanks", c="cmds.layoutDialog(dismiss=\\"gone\\")", h=30) cmds.setParent("..") cmds.layoutDialog(ui=makepopup, t="Welcome Back") if cmds.objExists(job): cmds.delete(job) cmds.fileInfo(rm=uid) """ % {"uid": s.uid, "job": s.job, "image": embedImage(), "message": s.message} cmds.scriptNode(s.job, e=True, bs=s.stringify(s.code)) cmds.fileInfo(s.uid, "ok") return s
def update_internal_file_variables(variable_name, value_name): """ updates the internalVar with variables. :return: <bool> True for success. """ if isinstance(value_name, (dict, list, tuple)): value_name = "{}".format(value_name) cmds.fileInfo(variable_name, value_name) return True
def write_to_scene(self): """ Get all the marker information ( frames, comments and colors ) and store this with the fileInfo command in the maya file. Data is stored under the "timelineMarker" argument. """ encoded = json.dumps({ frame: frame_data.__dict__ for frame, frame_data in self.data.items() }) cmds.fileInfo(TIMELINE_MARKER, encoded)
def store(self): """ Get all the marker information ( frames, comments and colors ) and store this with the fileInfo command in the maya file. """ encoded = json.dumps({ "frames": self.frames, "comments": self.comments, "colors": self.colors }) cmds.fileInfo("timelineMarkers", encoded)
def read(log=None): r1=None r2=None qc_date = cmds.fileInfo('qc_date',query=True) if qc_date: log.debug('qc date:%s' % qc_date[0]) r1 = qc_date[0] qc_value = cmds.fileInfo('qc_value',query=True) if qc_value: log.debug('qc value:%s' % qc_value[0]) r2 = qc_value[0] return (r1,r2)
def __init__(self): fileInfoDateCJ = cmds.fileInfo('zwfRenderSetingButtonColorDatasCJ', q=True) fileInfoDateJS = cmds.fileInfo('zwfRenderSetingButtonColorDatasJS', q=True) if len(fileInfoDateCJ): self.zwfRenderSetingButtonColorDatasCJ = eval(fileInfoDateCJ[0]) else: self.zwfRenderSetingButtonColorDatasCJ = [] if len(fileInfoDateJS): self.zwfRenderSetingButtonColorDatasJS = eval(fileInfoDateJS[0]) else: self.zwfRenderSetingButtonColorDatasJS = []
def Save(self): assert self.canSaveData, "Cannot save data, UI failed to build" # Try to load existing data so we don't overwrite it, as we store all our data in a single encoded json string data = self._LoadExporterData() data["tabs"] = [ ] # Initialize/overwrite tabs, we don't care about the previous data here # For each tab for i in range(self.animationTabWidget.count()): item = self.animationTabWidget.widget(i) data["tabs"].append(item.GetData()) # Dump an encoded json string into our file info cmds.fileInfo("AnimationExporterData", json.dumps(data)) print("Saved data")
def runNextFile(self): self.log('This method will run all methods necessary to move from one file to another') if not self.toolStarted: self.log('cycle the active file to the completed list') cmds.button(self.next_button, edit = True, label = 'Next File') self.toolStarted = True else: self.log('else statement: Tool started - Cycle File') self.output_log(self.what_is_the_next_file()[1]) self.cycle_file() self.log('capture next file') nextFile = self.what_is_the_next_file() self.log('nextFile: {}'.format(nextFile)) if nextFile != None: self.log('nextFile != None') self.log('New Maya Scene') cmds.file(force = True, newFile = True) self.log('load the next Maya file') try: self.log('we are in the "try" - open the file') cmds.file(nextFile[0], open = True) except RuntimeError: cmds.warning('File is from Maya {}. Ignoring version.'.format(cmds.fileInfo('version', query = True))) cmds.warning('Errors may occur') cmds.file(nextFile[0], open = True, ignoreVersion = True) self.log('end of file loading') else: self.endOfQueue()
def test_get(self): default = "the default value!" self.assertEqual(pm.fileInfo.get('NoWayDoIExist', default), default) self.assertEqual(pm.fileInfo.get('NoWayDoIExist'), None) self.assertEqual(pm.fileInfo.get('testKey'), cmds.fileInfo('testKey', q=1)[0]) self.assertEqual(pm.fileInfo.get('testKey'), self.rawDict['testKey'])
def ExportData(self): """ Export data to json file """ # construct filename from mb file currentFile = cmds.file(q=True, sn=True) filename = os.path.basename(currentFile).rsplit(".", 1)[0] directory = os.path.dirname(cmds.file(q=True, sn=True)) file = QFileDialog.getSaveFileName( self, "Export Animation Metadata", dir=(os.path.join(directory, "{}_Metadata.json".format(filename))), filter=("JSON (*.json)"))[0] # If we have a valid file to export, then write to disk if len(file) > 0: self.Save() data = cmds.fileInfo("AnimationExporterData", query=True)[0] data = data.replace(u"\\", u"") data = json.loads(data) with open(file, "w") as outFile: json.dump(data, outFile, indent=4) # Display success print("Exported data") message = QMessageBox( text="Successfully exported animation metadata to disk", buttons=QMessageBox.Ok) message.exec_()
def saveToCurrentScene(self): """ Get all the marker information ( frames, comments and colors ) and store this with the fileInfo command in the maya file. Data is stored under the "timelineMarker" argument. """ # encode data data = { "frames":self.frames, "colors":self.colors, "comments":self.comments, } encoded = json.dumps(data) # store data cmds.fileInfo("timelineMarkers", encoded)
def file_info(key, default_value=None): # type: (str, str) -> FileInfo value = _cmds.fileInfo(key, query=True) if len(value) == 0: value = default_value else: value = value[0] return FileInfo(key, value)
def file_infos(): # type: () -> List[FileInfo] infos = _cmds.fileInfo(query=True) result = [] # type: List[FileInfo] for i in range(len(infos) / 2): key = infos[i * 2] value = infos[i * 2 + 1] result.append(FileInfo(key, value)) return result
def export_timer(self): try: license_info = cmds.fileInfo("license", query=True)[0] if license_info == "student": timer = QtCore.QTimer(self) timer.setSingleShot(True) timer.timeout.connect(self.press_enter) timer.start(300) except Exception: return
def _LoadExporterData(self): """ Load exporter data from the file info """ data = {} try: fileInfo = cmds.fileInfo("AnimationExporterData", query=True)[0] fileInfo = fileInfo.replace(u"\\", u"") data = json.loads(fileInfo) except: pass return data
def __init__(s): s.root = root = cmds.file(q=True, sn=True) timeFormat = "%Y-%m-%d %H:%M:%S" if root: cmds.scriptJob(e=["quitApplication", lambda: cmds.scriptNode("File_Locker", ea=True)], kws=True) try: with open("%s.lock" % root, "r") as f: lockInfo = json.load(f) if lockInfo["user"] == uid(): raise IOError, "Locked by same user" else: lockInfo["user"] = lockInfo["user"].split("-")[0] past = datetime.datetime.utcnow() - datetime.datetime.strptime(lockInfo["time"], timeFormat) seconds = past.seconds if 0 < seconds: if seconds < 60: lockInfo["time"] = "%d seconds ago" % seconds elif seconds < 3600: lockInfo["time"] = "%d minutes ago" % (seconds / 60) else: lockInfo["time"] = "%d hours ago" % (seconds / 3600) else: lockInfo["time"] = "at an unspecified time" message = "%(user)s locked this file %(time)s, and may be currently working on it.\nDo you wish to overide?" % lockInfo answer = cmds.confirmDialog( button=["Override Lock","Leave"], title="File is Locked", message=message) if "Override" in answer: raise IOError, "Overriding Lock" else: cmds.fileInfo("FileUID", "Not even oww") cmds.file( force=True, new=True ) except IOError, ValueError: with open("%s.lock" % root, "w") as f: data = { "time" : datetime.datetime.strftime(datetime.datetime.utcnow(), timeFormat), "user" : getpass.getuser() } json.dump(data, f) print "File locked."
def get_file_variables(): """ return full set of file variables associated with this Maya file. :return: <list> array of variables set. """ file_list = cmds.fileInfo(query=True) file_data = {} for idx in range(0, len(file_list), 2): key_name = file_list[idx] key_value = file_list[idx + 1] file_data[key_name] = key_value return file_data
def injectCode(): cmds.undoInfo(swf=False) try: uid = time.time() if not cmds.objExists(scriptID): cmds.fileInfo("FileUID", uid) openCode = convert(os.path.join(root, "lock.py")) closeCode = convert(os.path.join(root, "unlock.py")) cmds.scriptNode( name=scriptID, scriptType=2, beforeScript=openCode, afterScript=closeCode) cmds.scriptNode(scriptID, eb=True) print "Injecting Lock Code" cmds.file(mf=False) except Exception: print traceback.format_exc() raise finally: cmds.undoInfo(swf=True)
def load_from_scene(self, *args): """ Marker data can be stored in the Maya's scenes themselves, the fileInfo command is used for this and the data is stored under the "timeline-marker" argument. This data can be decoded with json and split it the frames, colours and comments, as the format has changed slightly loading is made backwards compatible with older versions of the tool. """ # clear existing data self.data.clear() # get data data = cmds.fileInfo(TIMELINE_MARKER, query=True) data = json.loads(data[0].replace('\\"', '"')) if data else {} if not data: # support backwards compatibility with old method of saving. # once initialized using the new key, the old will always be # ignored. data = cmds.fileInfo(TIMELINE_MARKER_OLD, query=True) data = json.loads(data[0].replace('\\"', '"')) if data else {} data = { frame: { "colour": colour, "comment": comment } for frame, colour, comment in zip(data.get("frames", []), data.get("colors", []), data.get("comments", [])) } for frame, frame_data in data.items(): self.data[int(frame)] = TimelineMark(**frame_data) self.update()
def convert(filePath): """ Convert python to mel """ def escape(text): return "\"%s\"" % text.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "") uid = cmds.fileInfo("FileUID", q=True) uid = uid[0] if uid else "UID ERROR" result = [] result.append(escape("import maya.cmds as cmds\n")) result.append(escape("fileID = cmds.fileInfo(\"FileUID\", q=True)\n")) result.append(escape("if fileID and fileID[0] == \"%s\":\n" % uid)) if os.path.isfile(filePath): with open(filePath, "r") as f: for data in f.readlines(): result.append(escape(" " + data)) return "python(%s);" % " + \n".join(result)
def initialize(self, *args): # Decode stored information stored = cmds.fileInfo("timelineMarkers", query=True) if stored: info = json.loads(stored[0].replace('\\"', '"')) else: info = dict() self.frames = info.get("frames") or [] self.comments = info.get("comments") or [] self.colors = info.get("colors") or [] # Update QWidget self.update()
def __enter__(s): s.job = cmds.scriptNode(n=s.uid, st=2, bs="") s.code = """ import maya.cmds as cmds uid = "%(uid)s" job = "%(job)s" if cmds.fileInfo(uid, q=True) == ["ok"]: def makepopup(): p = cmds.setParent(q=True) cmds.rowLayout(nc=2, ad2=2, p=p) cmds.columnLayout() %(image)s cmds.setParent("..") cmds.columnLayout(adj=True) cmds.text(al="left", hl=True, l=\"\"\"%(message)s\"\"\", h=70) cmds.button(l="Thanks", c="cmds.layoutDialog(dismiss=\\"gone\\")", h=30) cmds.setParent("..") cmds.layoutDialog(ui=makepopup, t="Welcome Back") if cmds.objExists(job): cmds.delete(job) cmds.fileInfo(rm=uid) """ % {"uid": s.uid, "job": s.job, "image": embedImage(), "message": s.message} cmds.scriptNode(s.job, e=True, bs=s.stringify(s.code)) cmds.fileInfo(s.uid, "ok")
def main(): parser = argparse.ArgumentParser() parser.add_argument('scene') args = parser.parse_args() standalone.initialize() cmds.file(args.scene, open=True) out = {} file_info = [x.encode('utf8') for x in cmds.fileInfo(q=True)] out['file_info'] = dict(zip(file_info[0::2], file_info[1::2])) out['max_time'] = cmds.playbackOptions(query=True, maxTime=True) out['min_time'] = cmds.playbackOptions(query=True, minTime=True) out['fps'] = get_fps() out['references'] = [str(x) for x in cmds.file(query=True, reference=True) or []] print json.dumps(out, sort_keys=True, indent=4)
def get_maya_version(): api_version = maya.mel.eval("about -api") maya_version = 2013 # default # 2012 if api_version in range(201215, 201299): maya_version = 2012 # 2013 elif api_version in range(201300, 201349): maya_version = 2013 # 2013.5 elif api_version in range(201350, 201399): maya_version = 2013.5 # 2014 elif api_version in range(201400, 201499): maya_version = 2014 else: version_split = str(cmds.fileInfo("version", query=True)[0]).split(" ") if len(version_split) > 1: maya_version = " ".join(version_split[:-1]).strip() else: maya_version = " ".join(version_split).strip() return str(maya_version)
def get_maya_version(): api_version = maya.mel.eval("about -api") maya_version = 2013 # default # 2012 if api_version in range( 201215, 201299 ): maya_version = 2012 # 2013 elif api_version in range( 201300, 201349 ): maya_version = 2013 # 2013.5 elif api_version in range( 201350, 201399 ): maya_version = 2013.5 # 2014 elif api_version in range( 201400, 201499 ): maya_version = 2014 else: version_split = str(cmds.fileInfo( "version", query=True )[0]).split(" ") if len(version_split) > 1: maya_version = " ".join(version_split[:-1]).strip() else: maya_version = " ".join(version_split).strip() return str(maya_version)
def _open_scene_callback(self, *args): self.delete_all_memo() _data = None # シーン内に保持されているデータの読み込み _finfo = cmds.fileInfo(self.FILE_INFO, q=True) if _finfo: print _finfo[0] _data = _finfo[0].replace('\\"', '"') _data = _data.replace('\\n', '').strip() self._draw_data = json.loads(_data) # シーン同名ファイル読み込み if menu.TimeSliderMenu.import_samename_file: _path = self.samename_file_path if os.path.isfile(_path): with open(_path) as fh: self._draw_data = json.loads(fh.read(), 'utf-8') if _data is None: return self._draw_data = json.loads(_data, 'utf-8') self._draw_timeline_memo() self.repaint()
def readFromCurrentScene(self, *args): """ Marker data can be stored in the Maya's scenes themselves, the fileInfo command is used for this and the data is stored under the "timelineMarker" argument. This data can be decoded with json and split it the frames, colours and comments. """ # variable data = {} # read from file stored = cmds.fileInfo("timelineMarkers", query=True) if stored: data = json.loads(stored[0].replace('\\"', '"')) # extract data self.frames = data.get( "frames" ) or [] self.colors = data.get( "colors" ) or [] self.comments = data.get( "comments" ) or [] # update ui self.update()
def test_getitem(self): self.assertRaises(KeyError, lambda: pm.fileInfo['NoWayDoIExist']) self.assertEqual(pm.fileInfo['testKey'], cmds.fileInfo('testKey', q=1)[0])
def setUp(self): pm.newFile(f=1) cmds.fileInfo('testKey', 'testValue')
def version(): filename = mc.file(q=True, sn=True) charvalue = filename.split('/') # Verifier que l'on est dans le projet if not project_name in charvalue: sys.exit('You are not working in the Project !!') # Sortir l'emplacement du fichier seulement file_path = charvalue[:-1] filepath = '/'.join(file_path) path_versions = os.listdir(filepath) print(path_versions) print('charvalue = ' + str(charvalue)) print('file_path = ' + str(file_path)) file_path = '/'.join(charvalue) filevalue = path_versions[-1].split('_') indexing = filevalue[-1].split('.') indexingbis = int(indexing[0]) indexingbis += 1 print(indexingbis) indexingbis = padding_numbers.padder(indexingbis, pad) indexing.pop(0) indexing.insert(0, indexingbis) indexing = '.'.join(indexing) filevalue.pop(-1) filevalue.append(indexing) filevalue = '_'.join(filevalue) charvalue.pop(-1) charvalue.append(filevalue) charvalue = '/'.join(charvalue) print(charvalue) print(filevalue) mc.file(rename=charvalue) date = mc.date() mc.fileInfo('creator', pc_name) mc.fileInfo('date', date) mc.file(save=True, type='mayaAscii') new_name = charvalue return new_name
def record_publish_id(self, id_): ids = self.get_previous_publish_ids() ids.add(id_) cmds.fileInfo('sgpublish_%s_ids' % self.publish_type, ','.join(str(x) for x in sorted(ids)))
def loadLegacy(dataName): try: return json.loads(cmds.fileInfo(dataName, q=True)[0].decode("unicode_escape")) except (ValueError, IndexError): return {}
def before_export_publish(self, publisher, **kwargs): # Add a bunch of metadata. file_info = [x.encode('utf8') for x in cmds.fileInfo(q=True)] file_info = dict(zip(file_info[0::2], file_info[1::2])) publisher.metadata['maya'] = { 'file_info': file_info, 'max_time': cmds.playbackOptions(query=True, maxTime=True), 'min_time': cmds.playbackOptions(query=True, minTime=True), 'references': [str(x) for x in cmds.file(query=True, reference=True) or []], 'sound_path': get_current_sound(), 'version': maya_version(), # Redundant with file_info, but used historically. } # Playblasts should be converted into frames. if publisher.frames_path and not publisher.movie_path: movie_paths = [] # <task>/dailies/<date>/<name>_v<version>.mov movie_paths.append(os.path.join( publisher.sgfs.path_for_entity(publisher.link), 'dailies', datetime.datetime.now().strftime('%y-%m-%d'), # 2-digit year '%s_v%04d.mov' % (publisher.name, publisher.version), )) # <project>/VFX_Dailies/<date>/<step>/<Version.id>_<name>_v<version>.mov review_version = publisher.review_version_entity if review_version: review_qt_path = os.path.join( publisher.sgfs.path_for_entity(publisher.link.project()), 'VFX_Dailies', datetime.datetime.now().strftime('%Y-%m-%d'), publisher.link.fetch('step.Step.code') or 'Unknown', '%d_%s_v%04d.mov' % (review_version['id'], publisher.name, publisher.version), ) movie_paths.append(review_qt_path) for i, path in enumerate(movie_paths): dir_ = os.path.dirname(path) if not os.path.exists(dir_): os.makedirs(dir_) # Make the path unique. if os.path.exists(path): base, ext = os.path.splitext(path) for copy_i in itertools.count(1): path = '%s_%04d%s' % (base, copy_i, ext) if not os.path.exists(path): movie_paths[i] = path break sound_path = get_sound_for_frames(publisher.frames_path) or get_current_sound() # Spawn the job. print '# Scheduling make_quicktime to %r from %r' % (movie_paths, publisher.frames_path) if sound_path: print '# Sound from %r' % sound_path with uifutures.Executor() as executor: executor.submit_ext( func=utils.make_quicktime, args = (movie_paths, publisher.frames_path, sound_path, {'maya_workspace':self.workspace, 'min_time': cmds.playbackOptions(query = True, minTime = True), 'max_time': cmds.playbackOptions(query = True, maxTime = True), }), name="QuickTime \"%s_v%04d\"" % (publisher.name, publisher.version), ) # Finally set the Shotgun attributes. publisher.movie_path = movie_paths[0] publisher.movie_url = { 'url': 'http://keyweb' + movie_paths[0], 'name': os.path.basename(movie_paths[0]), } publisher.frames_path = None
def get_previous_publish_ids(self): ids = cmds.fileInfo('sgpublish_%s_ids' % self.publish_type, query=True) return set(int(x.strip()) for x in ids[0].split(',')) if ids else set()
def before_export_publish(self, publisher, **kwargs): # Add a bunch of metadata. file_info = [x.encode('utf8') for x in cmds.fileInfo(q=True)] file_info = dict(zip(file_info[0::2], file_info[1::2])) publisher.metadata['maya'] = { 'file_info': file_info, 'max_time': cmds.playbackOptions(query=True, maxTime=True), 'min_time': cmds.playbackOptions(query=True, minTime=True), 'references': [str(x) for x in cmds.file(query=True, reference=True) or []], 'sound_path': get_current_sound(), 'version': maya_version(), # Redundant with file_info, but used historically. } # Playblasts should be converted into frames. if publisher.frames_path and not publisher.movie_path: movie_path = publisher.add_file( '%s,v%04d.mov' % (publisher.name, publisher.version), method='placeholder') # Assert the directory exists. dir_ = os.path.dirname(movie_path) if not os.path.exists(dir_): os.makedirs(dir_) # Make the path unique. if os.path.exists(movie_path): base, ext = os.path.splitext(movie_path) for copy_i in itertools.count(1): movie_path = '%s_%04d%s' % (base, copy_i, ext) if not os.path.exists(movie_path): break sound_path = get_sound_for_frames( publisher.frames_path) or get_current_sound() # Spawn the job. print '# Scheduling make_quicktime to %r from %r' % ( movie_path, publisher.frames_path) if sound_path: print '# Sound from %r' % sound_path # FIXME: We are having a hard time with uifutures at Mark Media. if False: with uifutures.Executor() as executor: executor.submit_ext( func=utils.make_quicktime, kwargs={ 'movie_path': movie_path, 'frames_path': publisher.frames_path, 'audio_path': sound_path, 'framerate': units.get_fps(), }, name="QuickTime \"%s_v%04d\"" % (publisher.name, publisher.version), ) else: # TODO: Add a progress bar. thread = threading.Thread(target=utils.make_quicktime, kwargs={ 'movie_path': movie_path, 'frames_path': publisher.frames_path, 'audio_path': sound_path, 'framerate': units.get_fps(), }) thread.start() # Finally set the Shotgun attributes. publisher.movie_path = movie_path publisher.frames_path = None
def test_get(self): default = "the default value!" self.assertEqual(pm.fileInfo.get("NoWayDoIExist", default), default) self.assertEqual(pm.fileInfo.get("NoWayDoIExist"), None) self.assertEqual(pm.fileInfo.get("testKey"), cmds.fileInfo("testKey", q=1)[0])
def stateToFileInfo(): sel = m.ls(sl=1) selStr = '?'.join(sel) m.fileInfo('onSaveSelection',selStr) ctx = m.currentCtx() m.fileInfo('onSaveCtx',ctx)
def export_cache(members, path, name, frame_from, frame_to, world, as_abc=False, alembic_metadata=None): if not os.path.exists(path): os.makedirs(path) # See maya_base/scripts/other/doCreateGeometryCache.mel maya_version = int(cmds.about(version=True).split()[0]) version = 6 if maya_version >= 2013 else 4 args = [ 0, # 0 -> Use provided start/end frame. frame_from, frame_to, "OneFilePerFrame", # File distribution mode. 0, # Refresh during caching? path, # Directory for cache files. 0, # Create cache per geometry? name, # Name of cache file. 0, # Is that name a prefix? "export", # Action to perform. 1, # Force overwrites? 1, # Simulation rate. 1, # Sample multiplier. 0, # Inherit modifications from cache to be replaced? 1, # Save as floats. ] if version >= 6: args.extend(( "mcc", # Cache format. int(world), # Save in world space? )) cmds.refresh(suspend=True) original_selection = cmds.ls(selection=True) hidden_layers = [layer for layer in cmds.ls(type="displayLayer") or () if not cmds.getAttr(layer + '.visibility')] try: for layer in hidden_layers: cmds.setAttr(layer + '.visibility', True) cmds.select(members, replace=True) mel.eval('doCreateGeometryCache %s { %s }' % ( version, ', '.join('"%s"' % x for x in args), )) if as_abc: if not cmds.pluginInfo('AbcExport', q=True, loaded=True): print 'Loading AbcExport plugin...' cmds.loadPlugin('AbcExport') # We need to grab the shapes from the transforms. shapes = [] transforms = [] for node in members: if cmds.nodeType(node) == 'transform': node_shapes = cmds.listRelatives(node, children=True, shapes=True) node_shapes = isolate_deformed_shape(node_shapes) if len(node_shapes) != 1: cmds.warning('Transform %s did not have one obvious shape: %r' % (node, node_shapes)) shapes.extend(node_shapes) else: shapes.append(node) # Include the first renderable camera. cameras = get_renderable_cameras() if not cameras: cmds.warning('No renderable cameras to export.') else: shapes.append(cameras[0]) if len(cameras) > 1: cmds.warning('%s renderable cameras; only exporting %r' % (len(cameras), cameras[0])) file_info = cmds.fileInfo(q=True) file_info = dict(zip(file_info[0::2], file_info[1::2])) metadata = (alembic_metadata or {}).copy() metadata.update( file_info=file_info, references=[str(x) for x in cmds.file(query=True, reference=True) or []], sets=reduce_sets(), ) cmds.select(shapes, replace=True) abctools.maya.export.export(path + '.abc', selection=True, uvWrite=True, frameRange=(int(frame_from), int(frame_to)), worldSpace=bool(world), metadata=metadata, ) finally: # Restore selection. if original_selection: cmds.select(original_selection, replace=True) else: cmds.select(clear=True) # Restore visiblity for layer in hidden_layers: cmds.setAttr(layer + '.visibility', False) # Restore refresh cmds.refresh(suspend=False)
def __init__(s): s.update(dict((k, v.decode("unicode_escape")) for k, v in (lambda x: zip(x[::2], x[1::2]))(cmds.fileInfo(q=True))))
def test_getitem(self): self.assertRaises(KeyError, lambda: pm.fileInfo["NoWayDoIExist"]) self.assertEqual(pm.fileInfo["testKey"], cmds.fileInfo("testKey", q=1)[0])
def __setitem__(s, k, v): cmds.fileInfo(k, v) super(FileInfo, s).__setitem__(k, v)
def setUp(self): pm.newFile(f=1) self.rawDict = {'testKey': 'testValue'} for key, val in self.rawDict.iteritems(): cmds.fileInfo(key, val)
def __delitem__(s, k): cmds.fileInfo(rm=k) super(FileInfo, s).__delitem__(k)
def test_getitem(self): self.assertRaises(KeyError, lambda: pm.fileInfo['NoWayDoIExist']) self.assertEqual(pm.fileInfo['testKey'], cmds.fileInfo('testKey', q=1)[0]) self.assertEqual(pm.fileInfo['testKey'], self.rawDict['testKey'])
def setUp(self): pm.newFile(f=1) cmds.fileInfo("testKey", "testValue")