def do_retime(self): pm.waitCursor(state=True) self.set_playback_range() for line in self.nodes: frame, linked_frame = line linked_frame, decimal = divmod(float(linked_frame), 1) self.set_curve_keyframe(frame, linked_frame, decimal) self.cut_key() pm.waitCursor(state=False)
def __create__(self): # if type equal 1 we use the main Progress Bar if self._type == 1: self.gMainProgressBar = pmc.melGlobals['$gMainProgressBar'] pmc.progressBar( self.gMainProgressBar, edit=True, beginProgress=True, isInterruptable=False, status=self.title, maxValue=self._maxAmount ) # if type equal 2 we use a window elif self._type == 2: pmc.waitCursor( state=True ) self._maxAmount += 1 self.__createUI__() self.progress(1)
def restDynamics( restTime=100 ): """Positions particles at their goal objects.""" pm.waitCursor( state=True ) currentFrame = pm.currentTime() for i in range( restTime ): pm.currentTime( currentFrame+.1 ) pm.currentTime( currentFrame ) pm.waitCursor( state=False ) print '// Result: Particle states rested.'
def terminate(self): """Terminate the progress bar""" # if main progress bar if self._type == 1: pmc.progressBar(self.gMainProgressBar, edit=True, endProgress=True) # if window progress bar elif self._type == 2: pmc.waitCursor( state=False ) if (pmc.window(self.ui['win'], exists=True)): self.ui['pgb'].step(self._maxAmount) pmc.deleteUI(self.ui['win'])
def delAllShaders(geos): # 删除所有材质球 # # 参数geos: 模型对象 try: defaultShader = pm.PyNode("lambert1") defaultSG = pm.PyNode("initialShadingGroup") except: defaultShader, defaultSG = pm.createSurfaceShader("lambert", name="lambert1") pm.waitCursor(state=1) pm.sets(defaultSG, forceElement=geos) pm.mel.MLdeleteUnused() pm.waitCursor(state=0)
def wrapper(*args, **kwargs): is_batch = pm.about(batch=True) if not is_batch: pm.waitCursor(state=True) try: return func(*args, **kwargs) except Exception as e: print(traceback.format_exc()) error(str(e)) finally: if not is_batch: pm.waitCursor(state=False)
def assignShader(obj, shader, sg): #给物体赋予材质球 # #参数obj: 模型对象 # #参数shader: 材质球对象 # #参数sg: shadingEngine对象 # #创建节点 pm.waitCursor(state=1) pm.sets(sg, forceElement = obj) pm.waitCursor(state=0) return shader
def delAllShaders(geos): #删除所有材质球 # #参数geos: 模型对象 try: defaultShader = pm.PyNode("lambert1") defaultSG = pm.PyNode("initialShadingGroup") except: defaultShader, defaultSG = pm.createSurfaceShader('lambert', name='lambert1') pm.waitCursor(state=1) pm.sets(defaultSG, forceElement=geos) pm.mel.MLdeleteUnused() pm.waitCursor(state=0)
def run(self): pm.setParent(pm.mel.eval('getOptionBox()')) pm.setUITemplate('DefaultTemplate', pushTemplate=True) pm.waitCursor(state=1) pm.tabLayout(tabsVisible=False, scrollable=True) self.options_box_setup() self.option_box_load() pm.waitCursor(state=0) pm.setUITemplate(popTemplate=True) # We need to set both apply and apply and close explicitly. Maya breaks apply and close # if apply is set to a Python function. def apply(unused): self.option_box_save() self.option_box_apply() def apply_and_close(unused): self.option_box_save() self.option_box_apply() pm.mel.eval('hideOptionBox()') pm.button(pm.mel.eval('getOptionBoxApplyBtn()'), edit=True, command=apply) pm.button(pm.mel.eval('getOptionBoxApplyAndCloseBtn()'), edit=True, command=apply_and_close) # XXX: Is there a way for us to add a help link? pm.mel.eval('setOptionBoxCommandName("%s")' % self.title) # pm.mel.eval('setOptionBoxHelpTag "%s"' % self.title) pm.mel.eval('setOptionBoxTitle("%s");' % self.title) pm.mel.eval('showOptionBox()') # These need to be set directly to the menu item after showing the option box to # work around a Maya bug that breaks these when they're connected to Python functions. pm.menuItem(pm.mel.globals['gOptionBoxEditMenuSaveItem'], edit=True, command=lambda unused: self.option_box_save()) pm.menuItem(pm.mel.globals['gOptionBoxEditMenuResetItem'], edit=True, command=lambda unused: self.option_box_reset())
def run_import(): progress = mh.ProgressWindowMaya() try: pm.waitCursor(state=True) _create_materials(progress) except util.CancelledException as e: pass except BaseException as e: # Log the exception, then swallow it, since throwing an exception up to Maya will just # log it again. log.exception(e) finally: progress.hide() pm.waitCursor(state=False)
def loopDynamics( loops=3 ): """Sets initial state of particles to values of end frame.""" pm.waitCursor( state=True ) startFrame = pm.playbackOptions( query=True, min=True ) endFrame = pm.playbackOptions( query=True, max=True ) for i in range( loops ): for j in range( startFrame, endFrame+1 ): pm.currentTime( j ) pm.saveInitialState( all=True ) pm.currentTime( startFrame ) pm.waitCursor( state=False ) print '// Result: Particle states set.'
def redst_blend_shapes(src_node, dst_node, src_blend_shape_node, dst_blend_shape_node, blend_shape_indices, connect_weights, use_cvwrap): try: pm.waitCursor(state=True) # Remember the selection, so we can restore it. old_selection = pm.ls(sl=True) # Delete any nodes created while doing this when we're done. with maya_helpers.temporary_namespace(): with maya_helpers.restores() as restores: prep_for_retargetting(src_blend_shape_node, restores) src_to_dst_weights = redst_blend_shapes_inner( src_node, dst_node, src_blend_shape_node, dst_blend_shape_node, blend_shape_indices, use_cvwrap=use_cvwrap) # Copy or connect weights. Do this after we finish the above, since we need to let maya_helpers.restores() # restore the original weights before we copy them, or they'll all be set to 0. for src_weight, dst_weight in src_to_dst_weights.items(): if connect_weights: # Connect the source blend shape's weight to the target. src_weight.connect(dst_weight) else: # Copy the source weight. dst_weight.set(src_weight.get()) return src_to_dst_weights finally: pm.waitCursor(state=False) pm.select(old_selection)
def importGrooming(self, palName, descName= None, version= None): """ """ self.clearPreview() if descName: descs = [descName] else: descs = xg.descriptions(palName) # copy groom dir from versionRepo if @version has given if version: # check exists groomDesc = {} hasMissing = False for desc in descs: if xg.getAttr('groom', palName, desc): groomSource = '/'.join([self.paletteVerDir(palName, version), desc, 'groom']) if os.path.exists(groomSource): groomDesc[desc] = groomSource else: hasMissing = True msg = '[XGen Hub] : palette [%s] description [%s] version [%s] NOT exists. -> %s' pm.warning(msg % (palName, desc, version, groomSource)) # copy file if no missing if not hasMissing: for desc in groomDesc: src = groomDesc[desc] dst = '/'.join([self.paletteWipDir(palName), desc, 'groom']) if os.path.isdir(dst): try: dir_util.remove_tree(dst) except: pm.warning('[XGen Hub] : Dir may not remove. -> ' + dst) dir_util._path_created = {} dir_util.copy_tree(src, dst) else: pm.error('[XGen Hub] : Some data missing, Check ScriptEditor. grooming import stopped.') return None self.refresh() # IMPORT GROOMING # clear out autoExport path for preventing grooming auto export xg.setOptionVarString('igAutoExportFolder', '') for desc in descs: if xg.getAttr('groom', palName, desc): importPath = xg.expandFilepath('${DESC}/groom', desc) igDescr = xg.igDescription(desc) # import Attribute Map try: pm.waitCursor(state= True) pm.mel.iGroom(im= importPath, d= igDescr) finally: pm.waitCursor(state= False) # import Mask try: pm.waitCursor(state= True) pm.mel.iGroom(ik= importPath, d= igDescr) finally: pm.waitCursor(state= False) # import Region try: pm.waitCursor(state= True) pm.mel.iGroom(ir= importPath, d= igDescr) finally: pm.waitCursor(state= False) # restore default autoExport path xg.setOptionVarString('igAutoExportFolder', '${DESC}/groom') # IMPORT GROOM SETTINGS """ Currently only grab [density] setting, ['length', 'width'] will messed up imported grooming's map attribute """ for desc in descs: igdesc = xg.getAttr('groom', palName, desc) jsonPath = xg.expandFilepath('${DESC}/groom', desc) + 'groomSettings.json' if igdesc and os.path.isfile(jsonPath): groomSettings = {} with open(jsonPath) as jsonFile: groomSettings = json.load(jsonFile) for key in groomSettings: # grab [density] setting only if key == 'density': pm.setAttr(igdesc + '.' + key, groomSettings[key]) self.notifyMsg('Grooming Import Complete !', 0) return True
def toggle_wait_cursor(): logger.debug("Toggle wait cursor") current_state = pmc.waitCursor(query=True, state=True) pmc.waitCursor(state=not current_state) return True
def exportFullPackage(self, palName, version, bake= False, anim= False): """ Export Palettes, Descriptions, Grooming, Guides, all together, even bake modifiers befoer export if needed. """ self.clearPreview() # bake modifiers generator = {} if bake: for desc in xg.descriptions(palName): # bake Noise modifiers # fxModules evals from bottom to top clumpModLast = '' for fxm in xg.fxModules(palName, desc): if xg.fxModuleType(palName, desc, fxm) == 'ClumpingFXModule': # set the top clumpingMod cvAttr to True, for anim modifiers which needs clump if clumpModLast: xg.setAttr('cvAttr', 'false', palName, desc, clumpModLast) xg.setAttr('cvAttr', 'true', palName, desc, fxm) clumpModLast = fxm if xg.fxModuleType(palName, desc, fxm) == 'NoiseFXModule': # temporarily turn off lod so we dont bake it in lod = xg.getAttr('lodFlag', palName, desc) xg.setAttr('lodFlag', 'false', palName, desc) # change mode for bake xg.setAttr('mode', '2', palName, desc, fxm) # bake the noise pm.mel.xgmNullRender(pb= desc) # restore xg.setAttr('lodFlag', lod, palName, desc) # change mode to baked xg.setAttr('mode', '1', palName, desc, fxm) # bake groom modifiers fxm = xg.addFXModule(palName, desc, 'BakedGroomManagerFXModule') xg.setAttr('active', 'true', palName, desc, fxm) xg.bakedGroomManagerBake(palName, desc) # set Generator to XPD generator[desc] = xg.getActive(palName, desc, 'Generator') xg.setActive(palName, desc, 'FileGenerator') # change to export version path and keep current workPath = xg.getAttr('xgDataPath', palName) workProj = xg.getAttr('xgProjectPath', palName) xg.setAttr('xgDataPath', self.paletteVerDir(palName, version, raw= True), palName) xg.setAttr('xgProjectPath', self.projPath, palName) # get resolved repo path dataPath = self.paletteVerDir(palName, version) # set [xgDogTag] attr for ANIM record branchName if anim: xg.setAttr('xgDogTag', version, palName) # export descriptions for desc in xg.descriptions(palName): dstDescDir = xg.expandFilepath('${DESC}', desc, True, True) expPath = dstDescDir + desc + '.xdsc' xg.exportDescription(palName, desc, expPath) # copy map files srcDescVar = workPath.replace('${PROJECT}', workProj) + '/${DESC}' srcDescDir = xg.expandFilepath(srcDescVar, desc) for mapDir in os.listdir(srcDescDir): srcMap = os.path.join(srcDescDir, mapDir) dstMap = os.path.join(dstDescDir, mapDir) if os.path.isdir(srcMap): dir_util._path_created = {} dir_util.copy_tree(srcMap, dstMap) # export palettes expPath = dataPath + '/' + palName + '.xgen' xg.exportPalette(palName, expPath) # export grooming for desc in xg.descriptions(palName): igdesc = xg.getAttr('groom', palName, desc) if igdesc: expPath = xg.expandFilepath('${DESC}/groom', desc, True, True) tpu = 5 sampling = 1 igDescr = xg.igDescription(desc) # export Attribute Map try: pm.waitCursor(state= True) # may have .ptx file handle lock issue pm.mel.iGroom(exportMaps= expPath, texelsPerUnit= tpu, instanceMethod= sampling, description= igDescr) finally: pm.waitCursor(state= False) # export Mask try: pm.waitCursor(state= True) # may have .ptx file handle lock issue pm.mel.iGroom(exportMask= expPath, texelsPerUnit= tpu, description= igDescr) finally: pm.waitCursor(state= False) # export Region try: pm.waitCursor(state= True) # may have .ptx file handle lock issue pm.mel.iGroom(exportRegion= expPath, texelsPerUnit= tpu, description= igDescr) finally: pm.waitCursor(state= False) # export Settings jsonPath = expPath + 'groomSettings.json' groomSettings = {}.fromkeys(['density', 'length', 'width']) for key in groomSettings: groomSettings[key] = pm.getAttr(igdesc + '.' + key) with open(jsonPath, 'w') as jsonFile: json.dump(groomSettings, jsonFile, indent=4) # export guides with undoable('exportGuides'): for desc in xg.descriptions(palName): # listGuides guides = xg.descriptionGuides(desc) if not guides: continue expPath = xg.expandFilepath('${DESC}', desc) pm.select(guides, r= 1) # guides to curves curves = pm.mel.xgmCreateCurvesFromGuides(0, True) # export as alembic if not pm.pluginInfo('AbcExport', q= 1, l= 1): pm.loadPlugin('AbcExport') abcCmds = '-frameRange 1 1 -uvWrite -worldSpace -dataFormat ogawa ' abcRoot = '-root ' + ' -root '.join([cur.longName() for cur in pm.ls(curves)]) abcPath = expPath + 'curves.abc' pm.mel.AbcExport(j= abcCmds + abcRoot + ' -file ' + abcPath) if anim: # save out hairSystem preset presetMel = [] for nodeType in ['nucleus', 'hairSystem', 'nRigid']: presetDict = self.ioAttrPreset(nodeType, True) presetMel.extend(presetDict.values()) # move preset file to version repo presetRepo = self.nDynPresetPath(palName, version) if not os.path.exists(presetRepo): os.makedirs(presetRepo) for prs in presetMel: dstPath = '/'.join([presetRepo, os.path.basename(prs)]) shutil.move(prs, dstPath) # create empty _shot_ folder shotDir = self.paletteDeltaDir(palName, version, '') if not os.path.exists(shotDir): os.makedirs(shotDir) # export snapshot for i in range(5): tmpPath = self.snapshotTmp % (i+1) if os.path.isfile(tmpPath): imgPath = self.snapshotImgPath(palName, version, str(i+1)) if not os.path.exists(os.path.dirname(imgPath)): os.makedirs(os.path.dirname(imgPath)) shutil.move(tmpPath, imgPath) # restore dataPath xg.setAttr('xgDataPath', workPath, palName) xg.setAttr('xgProjectPath', workProj, palName) # restore modifiers if bake: for desc in xg.descriptions(palName): # bake Noise modifiers for fxm in xg.fxModules(palName, desc): if xg.fxModuleType(palName, desc, fxm) == 'NoiseFXModule': # restore to live mode xg.setAttr('mode', '0', palName, desc, fxm) # remove bake groom modifiers for fxm in xg.fxModules(palName, desc): if xg.fxModuleType(palName, desc, fxm) == 'BakedGroomManagerFXModule': xg.removeFXModule(palName, desc, fxm) # restore Generator xg.setActive(palName, desc, generator[desc]) self.refresh('Full') self.notifyMsg('Collection Export Complete !', 0) return True
def mirrorAnimation( defaultAxis='XZ' ): tempGroups = [] st2 = pm.timerX() pm.waitCursor( state=True ) autoKeyState = pm.autoKeyframe( query=True, state=True ) pm.autoKeyframe( state=False ) pm.select( pm.ls( selection=True ), replace=True ) objects = pm.ls( selection=True, type='transform' ) if len( objects ) == 0: mel.warning( 'No Transform objects selected for mirroring.' ) else: for obj in objects: if obj.mirrorAxis.exists(): axis = ( 'XY', 'YZ', 'XZ' )[ obj.mirrorAxis.get() ] else: axis = defaultAxis split = obj.split( ':' ) if len( split ) > 1: a = split[1] else: a = obj if a.startswith( prefix[0] ) or a.startswith( prefix[1] ): if a.startswith( prefix[1] ): prefix.reverse() opposite = pm.PyNode( obj.replace( prefix[0], prefix[1] ) ) else: opposite = None if opposite is not None and opposite.exists(): # -- make holder group -- g = pm.group( name='%s_holder' % obj, empty=True ) tempGroups.append( g ) ud_attrs = map( pm.Attribute, obj.listAttr( keyable=True ) ) for attr in ud_attrs: newAttr = pm.Attribute( '%s.%s' % ( g, attr.longName() ) ) if not newAttr.exists(): newAttr.add( attributeType=attr.type(), keyable=True ) if attr.longName() in mirrAttrs[axis] or attr.longName() in extrasList: newAttr.set( -attr.get() ) else: newAttr.set( attr.get() ) copy_result = pm.copyKey( obj, hierarchy='none', controlPoints=0, shape=1 ) if copy_result > 0: pm.pasteKey( g, option='replaceCompletely', copies=1, connect=1, timeOffset=0, floatOffset=0, valueOffset=0 ) # -- get opposite's values/keys -- og = '%s_holder' % opposite print 'tempGroups:', tempGroups print 'og:', og print len( tempGroups ) if og in tempGroups: obj2 = og else: obj2 = opposite copy_result = pm.copyKey( obj2, hierarchy=None, controlPoints=0, shape=1 ) if copy_result > 0: pm.pasteKey( obj, option='replaceCompletely', copies=1, connect=1, timeOffset=0, floatOffset=0, valueOffset=0 ) for attr in ud_attrs: srcAttr = pm.Attribute( '%s.%s' % ( obj2, attr.longName() ) ) if srcAttr.exists(): if attr.longName() in mirrAttrs[axis] or attr.longName() in extrasList: attr.set( -srcAttr.get() ) mirrorCurve( curves=attr.listConnections() ) else: attr.set( srcAttr.get() ) else: for attr in map( pm.Attribute, obj.listAttr( keyable=True ) ): if attr.longName() in mirrAttrs[axis] or attr.longName() in extrasList: attr.set( -attr.get() ) mirrorCurve( curves=attr.listConnections() ) # -- Finalize -- try: pm.delete( tempGroups ) except: pass pm.select( objects, replace=True ) pm.autoKeyframe( state=autoKeyState ) print '// Results: Mirrored animation for %i objects in %f seconds' % ( len( objects ), pm.timerX( st=st2 ) ) pm.waitCursor( state=False )
def render( camera='persp', width=128, height=128, bgc=[0,0,0], name=pm.sceneName().namebase, lights=0 ): sel_list = pm.ls(sl=1) pm.waitCursor(state=1) scene_name = pm.sceneName().namebase current_ws = pm.workspace.getName() current_frame = pm.currentTime() pm.workspace.open('default') image_dir = pm.workspace.getcwd() # --- --- hwr_globals = pm.PyNode('defaultHardwareRenderGlobals') hwr_globals.filename.set( scene_name ) hwr_globals.extension.set( 1 ) hwr_globals.imageFormat.set( TGA ) #8: JPG, 19: TGA hwr_globals.startFrame.set( current_frame ) hwr_globals.endFrame.set( current_frame ) hwr_globals.byFrame.set( 1 ) hwr_globals.resolution.set( "name %s %s %s" % ( width, height, float(width)/height ) ) hwr_globals.alphaSource.set( 0 ) hwr_globals.writeZDepth.set( 0 ) hwr_globals.lightingMode.set( lights ) hwr_globals.drawStyle.set( 3 ) hwr_globals.texturing.set( 1 ) hwr_globals.lineSmoothing.set( 0 ) hwr_globals.fullImageResolution.set( 0 ) hwr_globals.geometryMask.set( 0 ) hwr_globals.displayShadows.set( 0 ) hwr_globals.multiPassRendering.set( 0 ) hwr_globals.antiAliasPolygons.set( 1 ) hwr_globals.edgeSmoothing.set( 1 ) hwr_globals.motionBlur.set( 0 ) hwr_globals.grid.set( 0 ) hwr_globals.emitterIcons.set( 0 ) hwr_globals.lightIcons.set( 0 ) hwr_globals.fieldIcons.set( 0 ) hwr_globals.transformIcons.set( 0 ) hwr_globals.backgroundColor.set( bgc ) ''' // --- --- string $renderCamera; if($camera == "new") { $tempCamera = `camera -centerOfInterest 5 -focalLength 35 -lensSqueezeRatio 1 -cameraScale 1 -horizontalFilmAperture 1.41732 -horizontalFilmOffset 0 -verticalFilmAperture 0.94488 -verticalFilmOffset 0 -filmFit Fill -overscan 1 -motionBlur 0 -shutterAngle 144 -nearClipPlane 0.01 -farClipPlane 1000 -orthographic 0 -orthographicWidth 30 -name "tempCamera"`; xform -ws -t 4 2.7 6.7 -ro -12 32 0 $tempCamera[0]; viewSet -fit -ff 1 $tempCamera[0]; lookThroughModelPanelClipped $tempCamera[0] modelPanel4 0.001 10000; $renderCamera = $tempCamera[1]; } else $renderCamera = ($camera + "Shape"); // --- --- glRenderWin(); // print("//RENDER: " + $renderCamera + " //\n"); glRenderEditor -e -lookThru $renderCamera hardwareRenderView; ''' mel.glRenderWin() pm.glRender( e=1, flipbookCallback='kx_renderCleanup' ) mel.glRender( '-renderSequence', 'hardwareRenderView' ) pm.select( sel_list ) pm.workspace.open( current_ws ) pm.waitCursor( state=False )