def doAddAOVAttr(*args): if( ( isSelEmpty() and isObjType() ) == False ): return 0 aovName = pm.textFieldButtonGrp( 'txtBtnAddAttr', query=True, text=True ) if( len(aovName) == 0 ): pm.confirmDialog( t='warning', message='AOV name field is empty!', icon='warning' ) return 0 for obj in sel: if( not( obj.hasAttr(prefixAOV+'Id') ) ): addUserAttr( obj, 'string' ) # add AOV name as Attribute pm.PyNode( obj + '.' + prefixAOV + 'Id' ).set( 'id_'+aovName ) # skip loop if the input textfield is empty if( len(aovName) == 0 ): continue # add AOV render pass # check if AOV already existing if( len( pm.ls('aiAOV_id_'+aovName) ) == 0 ): addAOV( aovName ) return 1
def replaceString(*args): fileNodes = pc.ls(exactType='file') # Get the search string searchString = pc.textField(uiWidgets['searchField'], q=1, text=1) # Get the replace string replaceString = pc.textField(uiWidgets['replaceField'], q=1, text=1) if len(searchString) == 0 or len(replaceString) == 0: pc.confirmDialog(t="Error", message="Either the search or the replace string is empty. Try again.", icon='critical') exit(1) fileModified = 0 for node in fileNodes: filePath = str(node.fileTextureName.get()) print "Found a file node: %s" % node print "Current path is: %s" % filePath if str(searchString) in filePath: print "Found an occurence of the search string." print type(filePath) newFilePath = filePath.replace(searchString,replaceString) print "Setting new path to: %s" % newFilePath node.fileTextureName.set(newFilePath) fileModified += 1 pc.confirmDialog(t="Success", message=str(fileModified)+" file(s) has been modified.")
def doSaveAOVData(*args): color_tag = [ ['obj_R',(1, 0, 0)], ['obj_G', (0, 1, 0)], ['obj_B', (0, 0, 1)], ['obj_W', (1, 1, 1)] ] sceneAOVs = aovs.AOVInterface().getAOVNodes(names=True) #// collect custom id AOVs id_aov_sets = [ ( name, node ) for name, node in sceneAOVs if( name.find('id_') == 0 and node.hasAttr('isID') ) ] aov_info = str() for aov_name, aov_node in id_aov_sets: aov_info += '\n' for cl_attr, cl_val in color_tag: # print '%s: %s, %s' % (aov_name, cl_attr, cl_val) list_obj = pm.PyNode( aov_node + "." + cl_attr ).get().split(';')[:-1] #// convert to a list to save out as a file aov_info += ( aov_name + '.' + cl_attr + '--' + ';'.join(list_obj) + '\n' ) #// write to file if( outputAOVLists(aov_info) == 0 ): pm.confirmDialog( t='Cancel!', message='Svaing is cancel!', b=['OK'], icon='information' ) return 0 pm.confirmDialog( t='Save Complete!', message='Save AOVs Info is done!', b=['OK'], icon='information' ) return 1
def setButtonPress(self, *args): """Sets the plane we'll be snapping to from the three selected vertices Called by "set plane" button """ sel = pm.ls(selection=1, flatten=1) if len(sel) ==3: self.cleanUp() pos1 = sel[0].getPosition() pos2 = sel[1].getPosition() pos3 = sel[2].getPosition() vct1 = pos2-pos1 vct2 = pos3-pos1 # ^ is owerwritten to perform a cross product self.normal = vct1 ^ vct2 self.normal.normalize() self.position = pos1 pm.select(sel) layerObj = pm.createDisplayLayer(name=self.layername, empty=1) for i, vtx in enumerate(sel): annotation = pm.annotate(vtx, tx="V%d" % (i+1), p=vtx.getPosition(space="world") ) annotation.setAttr("overrideEnabled", 1) annotation.setAttr("overrideColor", 17) annTrans = annotation.getParent() annTrans.rename("annotateVts%d" % (i+1)) layerObj.addMembers(annTrans) layerObj.addMembers(annotation) layerObj.setAttr("displayType", 1) else: pm.confirmDialog(message="Please select exactly 3 vertices", title="Error", button="OK", defaultButton="OK", dismissString="OK", cancelButton="OK")
def initGeometry(self): selection = m.ls(sl=True) meshes = m.ls( selection=True, long=True, dagObjects=True, allPaths=True, type='mesh', noIntermediate=True ) if meshes: for mesh in meshes: transform = com.getParent(mesh) if transform: self.backupers.append(backuper.Backuper(mesh, transform)) m.polyNormalPerVertex(mesh, ufn=True) m.polySoftEdge(transform, a=180, ch=False) geomProcessor = geom_processor.GeomProcessor(mesh) geomProcessor.params = Parameters self.processors.append(geomProcessor) else: pm.confirmDialog( title='Error', message='Invalid selection. Select at least one mesh.', button=['OK'], defaultButton='OK', icon='critical' ) return m.select(selection, r=True)
def setColor(color, *args): # Get current AOV name aov = pc.radioButtonGrp(uiWidgets['aovs'], q=1, select=1) if aov == 1: aovName = 'mtoa_constant_rgbMask' elif aov == 2: aovName = 'mtoa_constant_rgbMask1' elif aov == 3: aovName = 'mtoa_constant_rgbMask2' elif aov == 4: aovName = 'mtoa_constant_rgbMask3' if aovName is None: raise Exception('Error while determining which AOV to focus on.') print "AOV Name: %s" % aovName listSel = pc.ls(sl=1) if len(listSel) == 0: pc.confirmDialog(t="Error", message="Nothing selected.", icon='critical') else: for sel in listSel: recursiveAssign(aovName, sel, color)
def error_gui(message): """Simple gui for displaying errors """ pm.confirmDialog( title=str('gozbruh Error:'), message='\n' + str(message), button=['Ok'])
def populateList(): # Get shader type shaderSel = pc.radioButtonGrp(uiWidgets['shaderType'], q=1, select=1) if shaderSel == 1: shaderType = 'lambert' elif shaderSel == 2: shaderType = 'blinn' elif shaderSel == 3: shaderType = 'phong' # Get shader prefix shaderPrefix = pc.textField(uiWidgets['shadersPrefix'], q=1, text=1) if len(shaderPrefix) == 0: listShaders = pc.ls(exactType=shaderType) else: listShaders = pc.ls(shaderPrefix+'*', exactType=shaderType) if len(listShaders) == 0: pc.confirmDialog(t="Error", message="No shaders fitting the given paramaters has been found.", icon='critical') exit(1) elif len(listShaders) > 0: pc.confirmDialog(t="Shaders found", message=str(len(listShaders))+" shader(s) found. Click confirm to continue.") else: exit("Unknown error.") # for info in infos.keys(): # print "#######################" # print "### Shader: '%s'" % info # print " - Found %s shape(s)" % len(infos[info]) # print "Shapes list: %s " % infos[info] return listShaders
def _prep(self,args): basename=self.inputName.getText() nparticle=pm.ls(sl=True)[0] if not pm.objExists(self.inputBar.getText()): pm.error ('GEO plane doesn\'t exist') geo = pm.PyNode(self.inputBar.getText()) if not isinstance(nparticle.getShape(), pm.nt.NParticle): pm.error('Your selection is not an nParticle object') #create an instancer tempCube=pm.polyCube(n='temp_iinst_GEO',w=.01,h=.01,d=.01,ch=0) self.instancer=pm.PyNode(pm.particleInstancer(nparticle,name=(nparticle.name().replace('_NPARTICLE','_INSTANCER')),addObject=True,object=tempCube[0],cycleStep=1,cycleStepUnits='Frames',levelOfDetail='Geometry',rotationUnits='Degrees',rotationOrder='XYZ',position='worldPosition',rotation='rotPP',scale='scalePP',objectIndex='indexPP')) pm.delete(tempCube) #group the nparticle + instancer group=pm.group(n=(nparticle.name().replace('_NPATICLE','_lodA_GRP'))) nparticle.setParent(group) self.instancer.setParent(group) #nCache itR if not pm.objExists( nparticle.name().replace('_NPARTICLE','_NUCLEUS') ): pm.error('Nucleus doesn\'t exist!') nucleus = nparticle.name().replace('_NPARTICLE','_NUCLEUS') #delete everything unnecessary that might cause issues print geo, nucleus print 'issue?' pm.delete(geo, nucleus) print 'issue?' pm.select(nparticle) mm.eval('performCreateNclothCache 1 \"add\";') pm.confirmDialog(m='WARNING, DO NOT SAVE AFTER THIS STEP',t='DONT SAVE!')
def __init__(self): self.name = "MusterSubmitClass" self.widgets = {} self.pools = [] self.userPass = {} self.renderers = [] self.cameras = pm.ls(ca = True) self.scene = pm.sceneName() self.priority = self.__class__.defaults['priority'] self.childrenTabs = [] self.startFrame = pm.SCENE.defaultRenderGlobals.startFrame.get() self.endFrame = pm.SCENE.defaultRenderGlobals.endFrame.get() self.mustertool = None self._saveUser = None self._saveRenderer = None self._savePool = None self.fileInfo = PT.PRAFileInfo(self.scene) try: self.output = os.path.join(self.__class__.renderDrive, self.fileInfo.getProject(), self.fileInfo.getEpShotName()).replace("\\","/") except TypeError: #file info returned None self.output = '' try: self._getData() #this bit is slow. use threadding maybe? except: pm.confirmDialog(title = "Confirm", Message = "Error connecting to muster database / executable. Speak to your IT helpdesk. \nContinuing using Demo mode", buttonm = ['OK'] )
def delGroupId(): model = MODELIntercept() model.modelHistory() for name in model.historyResult: shape = pm.PyNode(name) historyLst = shape.listHistory() if len(historyLst) == 1 and historyLst[0] == shape: pass else : sg = [h for h in historyLst if h.type() == "shadingEngine"] if len(sg) == 1: shaderLst = sg[0].surfaceShader.inputs() if shaderLst: try: outAttrLst = shape.outputs(type = "shadingEngine", c = 1, p = 1) osattr = outAttrLst[0][0] odattr = outAttrLst[0][1] newattr = pm.PyNode(".".join(osattr.name().split(".")[:-1])) newattr >> odattr except: pass inAttrLst = shape.inputs(type = "shadingEngine", c = 1, p = 1) isattr = inAttrLst[0][1] idattr = inAttrLst[0][0] isattr // idattr groupID = [g for g in historyLst if g.type() == "groupId"] pm.delete(groupID) pm.confirmDialog( title=u'提示', message=u'groupId清理完成', button=['OK'], defaultButton='OK')
def simpleWarning(message, icon='information'): pm.confirmDialog( icon=icon, title=SCRIPT_NAME, message=message, button=['Ok'] )
def check_overlapping(anim_curves, choice, current_time, offset_val): for anim_curve in anim_curves: key_cnt = anim_curve.numKeys() message = 'Some Keys are overlapping within Offset Value\n' message += 'Do you want continue on Moving other Keys ?\n' for i in range(0, key_cnt): key_time = anim_curve.getTime(i) if choice == 'forward': if key_time <= current_time + offset_val: range_dialog = pm.confirmDialog(title='Error', message=message, button=['Yes', 'No'], cancelButton='No', dismissString='No') if range_dialog == 'Yes': return 1 else: raise RuntimeError('Move Keys process interrupted by User.') if choice == 'back': if key_time >= current_time + offset_val: range_dialog = pm.confirmDialog(title='Error', message=message, button=['Yes', 'No'], cancelButton='No', dismissString='No') if range_dialog == 'Yes': return 1 else: raise RuntimeError('Move Keys process interrupted by User.')
def check_shot_attributes(self): """check some of mandatory attributes """ shots_with_bad_attrs = [] attrs = { 'scale': 1.0, 'preHold': 0.0, 'postHold': 0.0 } shots = self.shot_list for shot in shots: for item in attrs.iteritems(): value = shot.getAttr(item[0]) if value != item[1]: shots_with_bad_attrs.append([shot, item[0], value, item[1]]) if shots_with_bad_attrs: message = 'Shots below have restricted values for shot attrs:\r\n' message += '\r' for info in shots_with_bad_attrs: message += '[ %s ] - %s | su an %s -> %s olmali\n' % (info[0], info[1], info[2], info[3]) pm.confirmDialog(title='Error', message=message, button='OK') raise RuntimeError('There Are restricted values in Shot Nodes.')
def doIDShdNetwork(*args): ## check if the shading network is existing shdName = 'idSetup' if( len( pm.ls(shdName + "_SHD") ) ) != 0: pm.confirmDialog(t="Warning", message="The shader has been existed!", icon='warning') return 0 # aiUserDataColor dataColor = pm.shadingNode('aiUserDataColor', asUtility=True, name=shdName+'DataColor') dataColor.colorAttrName.set('idcolor') # aiUserDataString dataString = pm.shadingNode('aiUserDataString', asUtility=True, name=shdName+'DataString') dataString.stringAttrName.set('Id') # aiWriteColor writeColor = pm.shadingNode('aiWriteColor', asUtility=True, name=shdName+'WriteColor') # aiUtility aiIDShd = pm.shadingNode('aiUtility', asShader=True, name=shdName+'_SHD') aiIDShd.shadeMode.set(2) # connections dataColor.outColor >> writeColor.input dataString.outValue >> writeColor.aovName writeColor.outColor >> aiIDShd.color
def replaceL2H(fr, to): #把参考文件的低模, 替换成高模 # #把字段f替换成t # #列出所有参考文件,存到以namespace为key的字典中 refs = pm.system.getReferences() noH = [] for key, value in refs.items(): name_space = key fileRef = value #列出参考文件的路径和文件名 file_path = fileRef.path file_name = file_path.name #将带'_l_'标示的低模, 替换成带'_h_'标示的高模 if fr in file_name: hf = file_name.replace(fr, to) hd = file_path.replace(fr, to) dir = pm.Path(file_path).dirname() #如果服务器上有高模文件就进行替换, 没有就加入到一个列表里以便弹窗报错 if hf in [f.name for f in dir.files()]: fileRef.replaceWith(hd) else : noH.append(file_path) if noH : pm.confirmDialog( title=u'提示', message='\n'.join(noH) + u'\n 没有"_h_"文件', button=[u'确认']) else: pm.confirmDialog( title=u'提示', message=u'完成', button=[u'确认'])
def checkAndLoadPlugin(pluginName): """ Checks and loads plugin with GUI dialogs """ if pm.pluginInfo(pluginName, query=True, loaded=True) == False: ans = pm.confirmDialog( title="Warning!!!", message="%s not loaded,,, \n Do you wish to load it now?" % pluginName, button=["YES", "NO"], defaultButton="YES", dismissString="NO", ) if ans == "YES": try: pm.loadPlugin(pluginName) return True except RuntimeError: pm.warning("%s plugin not found in path!" % pluginName) pm.confirmDialog( title="Warning!!!", message="%s plugin not found!" % pluginName, button=["OK"], defaultButton="OK", dismissString="OK", ) return False # TODO : Raise Plugin Not Found Error! if ans == "NO": return False
def ui_badSelectionWarning(self): pm.confirmDialog( title='Error', message='Invalid selection.\nSelect at least one polygon and press "' + UI_APPLY_BUTTON_STRING + '".', button=['OK'], defaultButton='OK', icon='critical' )
def createRig(self): pm.currentTime(0, e=True) global sel_objects sel_objects = pm.ls(sl=True, tr=True) if sel_objects == []: print '\n# Error: Please select an object first' pm.confirmDialog(title = 'Error: Nothing Selected', m = 'Please select an object to create the light rig around.', button = 'Ok', db = 'Ok') self.close() gui(dock=False) else: global light_name light_name = 'light1' name_request = pm.promptDialog( t='Light Name', m='Enter Your New Light\'s Name', ma='left', tx='Ex: key_light', st='text', b=['Ok', 'Cancel'], db='Ok', cb='Cancel', ds='Cancel') if name_request == 'Ok': light_name = pm.promptDialog(query=True, text=True) global sel_center sel_center = command.averageCoords(sel_objects) global rigOrbit, rigInterv, rigLight rigOrbit = pm.group(n='olp_orbitsGrp1', em=True) rigInterv = pm.group(n='olp_intervalsGrp1', em=True) rigLight = self.createLight(sel_center) self.setExpression() pm.createRenderLayer([sel_objects, rigOrbit, rigInterv, rigLight], noRecurse=True, name='{0}_layer'.format(light_name)) self.createVis() pm.xform(rigOrbit, a=True, t=sel_center) pm.xform(rigInterv, a=True, t=sel_center) pm.parent(rigLight, rigInterv) pm.parent(rigInterv, rigOrbit) pm.select(sel_objects, r=True) # GUI Components enable/disable self.enableDisable_component(self.createRig_btn, enabled=False) self.enableDisable_component(self.deleteRig_btn, enabled=True) self.enableDisable_component(self.distance_label, enabled=True) self.enableDisable_component(self.distance_float, enabled=True) self.enableDisable_component(self.orbit_label, enabled=True) self.enableDisable_component(self.orbit_int, enabled=True) self.enableDisable_component(self.interv_label, enabled=True) self.enableDisable_component(self.interv_int, enabled=True) self.enableDisable_component(self.showVis_ckbx, enabled=True)
def move_all_keys(choice): offset_val = offset_intfield.getValue() if offset_val < 1: raise RuntimeError('Enter an Offset Value greater than 0.') if choice == 'back': offset_val = offset_intfield.getValue() * -1 unlock_val = unlock_state.getValue1() current_time = pm.currentTime() anim_curves = pm.ls(type='animCurve') non_moved_curves = [] if choice == 'back': check_overlapping(anim_curves, choice, current_time, offset_val) for anim_curve in anim_curves: try: if unlock_val is True and anim_curve.isLocked(): anim_curve.setLocked(0) key_cnt = anim_curve.numKeys() for i in range(1, key_cnt + 1): if choice == 'forward': ind = key_cnt - i if choice == 'back': ind = i - 1 if anim_curve.getTime(ind) >= current_time: pm.keyframe(anim_curve, index=ind, iub=False, animation='objects', relative=True, option='move', tc=offset_val ) except: if anim_curve not in non_moved_curves: non_moved_curves.append(anim_curve) continue if not non_moved_curves: pm.confirmDialog(title='Info', message='Keys Moved Successfully.', button='OK') else: message = 'Anim Curves can NOT be moved:\r\n' message += '\r' for i in range(0, len(non_moved_curves)): message += '%s\n' % non_moved_curves[i] if i > 30: message += '+ More...\n' break print non_moved_curves pm.confirmDialog(title='Error', message=message, button='OK')
def setOverrides(function, *args): listSel = pc.ls(sl=1) if len(listSel) == 0: pc.confirmDialog(t="Error", message="Nothing selected.", icon='critical') else: for sel in listSel: recursiveAssign(sel, function)
def disperse(self, *args): """Called when the disperse button is pressed""" if self.sourceObj == None or self.targetObjs == None: pm.confirmDialog(t='Error', b=['OK'], m='Please make sure source and targets are selected.') return # get copy number copyNum = self.copyNum.getValue() copyNum = min(copyNum, len(self.vertIndexList)) # get rotation rotationMode = self.rotationModeRC.getSelect() rotationMode = pm.control(rotationMode, q=True, fpn=True) if rotationMode == self.rotBtnRand: origRot = pm.xform(self.sourceObj, ro=True, q=True) rotRange = self.rotationRange.getValue() # get scale scaleMode = self.scaleModeRC.getSelect() scaleMode = pm.control(scaleMode, q=True, fpn=True) if scaleMode == self.scaleBtnRand: scaleRange = self.scaleRange.getValue() # make copies randVertIndexList = random.sample(self.vertIndexList, copyNum) for i in randVertIndexList: newObj = pm.duplicate(self.sourceObj, n='%s_copy'%self.sourceObj) # decide which target the random vert index falls on vertSum = 0 targetIndex = 0 targetVertIndex = 0 for j, k in enumerate(self.targetVertNumList): vertSum += k if i + 1 <= vertSum: targetIndex = j targetVertIndex = i - (vertSum - k) break # apply scale if scaleMode == self.scaleBtnRand: randScale = random.uniform(scaleRange[0], scaleRange[1]) pm.xform(newObj, s=(randScale,randScale,randScale)) # apply rotation if rotationMode == self.rotBtnAlign: # normal constraint pm.normalConstraint(self.targetObjs[targetIndex], newObj, aim=(0,0,1), u=(0,1,0)) elif rotationMode == self.rotBtnRand: newRotX = random.uniform(origRot[0]-rotRange[0]/2,origRot[0]+rotRange[0]/2) newRotY = random.uniform(origRot[1]-rotRange[1]/2,origRot[1]+rotRange[1]/2) newRotZ = random.uniform(origRot[2]-rotRange[2]/2,origRot[2]+rotRange[2]/2) pm.xform(newObj, ro=(newRotX,newRotY,newRotZ)) rotatePivot = pm.xform(newObj, rp=True, q=True) newPos = pm.pointPosition('%s.vtx[%d]'%(self.targetObjs[targetIndex],targetVertIndex)) posOffset = [newPos[0]-rotatePivot[0], newPos[1]-rotatePivot[1], newPos[2]-rotatePivot[2]] pm.xform(newObj, t=posOffset) # remove constraint after translation if rotationMode == self.rotBtnAlign: pm.delete(newObj, cn=True)
def SelectGeometry_callBack(self): selection = pm.ls(selection = True) self.geometry = self.FindGeometry(selection) if self.geometry == None: pm.confirmDialog(title = "Attach Geometry to Blueprint", message = "Geometry selection invalid. \nTerminating tool.", button = ["Accept"], defaultButton = "Accept") else: self.AttachGeometryToBlueprint_attachment()
def importSelected(self, camFilePath): dialog = QtGui.QFileDialog() filename, fileType = dialog.getOpenFileName(self, "Select File", os.path.dirname(camFilePath), options=QtGui.QFileDialog.DontUseNativeDialog) if filename: cmds.AbcImport(filename) pm.confirmDialog(t= 'Camera Import', m='%s imported successfully' % os.path.split(filename)[1], b='OK')
def isSelEmpty(*args): ## access the global "sel" global sel sel = pm.ls( sl=True, dag=True, type='mesh' ) if( sel == [] ): pm.confirmDialog(t="Error", message="No Object is selected", icon='critical') return 0 return 1
def run(): if len(g_selectedMeshList) == 0: pm.confirmDialog(title='Error', button=['OK'], defaultButton='OK', m="Please select the original model!") return if len(g_selectedMeshList) > 2: pm.confirmDialog(title='Error', button=['OK'], defaultButton='OK', m="more than 2 objects are selected: "+str(g_selectedMeshList)) return myUI = UI()
def run(): # Get selected camera sel = pc.ls(sl=True, ca=True, dag=True) if len(sel) < 1: pc.confirmDialog(t='Select a camera', m='Please, select a camera to apply the noise on.', b='OK') return else: cam = pc.listRelatives(sel[0], p=True)[0] cn = CamNoiseTool(cam) cn.showUI()
def runDelIDs(): # RUN procedure of DELETE SHADER IDS AND aiWriteColor NODES nodesWC = pm.ls( sl = True ) if nodesWC: # delete selected shader IDs confirm = pm.confirmDialog ( title='WARNING', message='DELETE SELECTED IDS?', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' ) if confirm == 'Yes': deleteIDS(nodesWC) else: # delete ALL shader IDS confirm = pm.confirmDialog ( title='WARNING', message='DELETE ALL SHADER IDS?', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' ) if confirm == 'Yes': nodesWC = pm.ls('WRC_*', type = 'aiWriteColor') # select all aiWriteColors for IDs nodeAOV = pm.ls('aiAOV_IDS_*', type = 'aiAOV') # select all AOVs for shader IDs deleteIDS(nodesWC)
def _newAssetInfoConfirmed(self, args): sceneName = _pmCore.textFieldGrp(self._sceneName, query=True, text=True) directory = _pmCore.textFieldGrp(self._filePath, query=True, text=True) description = _pmCore.scrollField(self._description, query=True, text=True) category = _pmCore.optionMenuGrp(self._category, value=True, query=True) if not sceneName or not directory or not description: _pmCore.confirmDialog(title='Invalid Asset Info', message='Asset info for "Scene Name", "Directory" and "Description" can not be empty.', button='OK') return self._newAssetInfoClose() fileID = _MayaFunctions.saveScene(sceneName, directory, description, category) if self._addedCallback: self._addedCallback(fileID, category)
def isObjType(*args): tmpList = [ o.getParent() for o in sel if not(pm.nodeType(o) == 'mesh' or pm.nodeType(o) == 'nurbsSurface') ] tmpStr = '' for s in tmpList: tmpStr = tmpStr + s + ',' if( len(tmpList) > 0 ): pm.confirmDialog(t="Error", message= tmpStr + " are not mesh or nurbsSurface", icon='critical') return 0 return 1
def okCallback(self, *args): self.putProjectSettings() projName = self.projDict['projectName'] if self.new: if not projName: pm.confirmDialog( title='error', ma='center', message='Please choose a name for the project!!', button=['OK'], defaultButton='OK', dismissString='OK') return existName = database.getProjectDict(projName) if existName: pm.confirmDialog( title='error', ma='center', message='This Name exists. Please choose another name', button=['OK'], defaultButton='OK', dismissString='OK') return database.addProject(**self.projDict) pm.deleteUI(self.parentWidget.projPopUp) self.parentWidget.makePopup() self.parentWidget.changeProjectCallBack(projName) else: database.putProjectDict(self.projDict, projName) pm.deleteUI(self.win)
def check_stalker_tasks(self): """check if all shots have proper stalker tasks """ shot_tasks = self.scene_shot_tasks shots = self.shot_list shots_without_task = [] for shot in shots: check = 0 for t in shot_tasks: if shot.getShotName() == t.nice_name.split('_')[-1]: check = 1 else: pass if check == 0: shots_without_task.append(shot) if shots_without_task: message = 'Shots do not have a Task to save:\r\n' message += '\r' for shot in shots_without_task: message += 'shot [ %s ]\n' % (shot.getShotName()) pm.confirmDialog(title='Error', message=message, button='OK') raise RuntimeError('Some Shots do not have Stalker Tasks.')
def checkCam(listCam): if len(listCam) > 1: confirm = pm.confirmDialog( title='Warning', message= 'There are extra camera in the scene. \r\nDelete or rename extra cameras!', button=['OK', 'HELP'], cancelButton='OK') if confirm == 'HELP': pm.warning( 'This scene should contain only one camera named E###_S###. You should delete or rename all extra cameras!' ) return [] else: return listCam
def switchToStandIn(renderGeometry): rndGeoName = (pm.ls(sl=1)[0]).split('_Geo') rndAssName = str(rndGeoName[0]) + '_Ass' assList = [] for geo in list: #export ass from selected group assName = geo + assVer assExport = os.path.join(sPath, assDir, assName).replace('\\', '/') mayaSmoothOff(geo) pm.select(geo) pm.hyperShade(assign='lambert1') pm.exportSelected(assExport, force=1) pm.importFile(assExport) #import ass and rename standIn = pm.PyNode('ArnoldStandIn') standIn.rename('ASS_' + geo) standIn.mode.set(0) #set standIn display mode copyMTOAAttr( geo, standIn) # copy mtoa attributes from render geo to standIn assList.append(standIn) standIn.translate.lock() # lock TRANSFORM for STANDIN standIn.rotate.lock() standInGRP = pm.group(assList, n=rndAssName) standInGRP.translate.lock() standInGRP.rotate.lock() pm.parent(standInGRP, asset) pm.parent(rndGeo, w=1) #Unparent Render geo pm.select(asset) if os.path.exists(SI(asset, siVer)): confirm = pm.confirmDialog(title='File exists!', message=str(SI(asset, siVer)).split('/')[-1], button=['OVERWRITE', 'CANCEL'], defaultButton='OVERWRITE', cancelButton='CANCEL', dismissString='CANCEL') if confirm == 'OVERWRITE': siExport = pm.exportSelected(SI(asset, siVer), force=1) #export SI file print 'ASSET OVERWRITEN TO: ' + str(siExport) else: print 'CANCELED!' sys.exit() else: siExport = pm.exportSelected(SI(asset, siVer), force=1) #export SI file print 'ASSET CONVERTED TO: ' + str(siExport)
def importConfig(self): """Import channel wrangler configuration""" # TODO: if import dict ask to add to the current # configuration or replace. startDir = pm.workspace(q=True, rootDirectory=True) filePath = pm.fileDialog2( fileMode=1, startingDirectory=startDir, fileFilter='Channel Wrangler Configuration .cwc (*%s)' % ".cwc") if not filePath: return if not isinstance(filePath, basestring): filePath = filePath[0] configDict = json.load(open(filePath)) # also ask for proxy and move policy if is not the same when we add to # the current list if self.table.rowCount(): option = pm.confirmDialog( title='Channel Wrangler Configuration Import Style', message='Do you want to repace current configuration or' ' add it?\n if add the move policy and proxy policy' ' will not change', button=['Replace', 'Add', 'Cancel'], defaultButton='Reaplace', cancelButton='Cancel', dismissString='Cancel') else: option = "Replace" if option == "Replace": self.clearAllRows() # set move policy indexList = ["merge", "index", "fullName"] self.cwUIInst.movePolicy_comboBox.setCurrentIndex( indexList.index(configDict["movePolicy"])) # set proxy policy indexList = ["index", "fullName"] self.cwUIInst.proxyPolicy_comboBox.setCurrentIndex( indexList.index(configDict["proxyPolicy"])) for rule in configDict["map"]: row_pos = self._addNewRow(channel=rule[0], source=rule[1], target=rule[2]) oCombo = self.table.cellWidget(row_pos, 4) oCombo.setCurrentIndex(rule[3])
def __init__(self, **kwargs): script_name = pm.sceneName() _, ext = os.path.splitext(script_name) if ext == '.mb': pm.confirmDialog( message= "There is no option to export on render farm the *.mb file. Please, save file as Maya ASCII and try again.", button=["ok"]) raise Exception("File must be MAYA ASCII") self._assembly = kwargs.get('assembly', False) if self._assembly == True: if pm.renderer('redshift', exists=True) == 0: pm.confirmDialog( message= "Render shaded option uses Redshift renderer. Please, turn on redshift renderer and try again.", button=["ok"]) raise Exception("Turn on REDSHIFT") if int(pm.playbackOptions(q=True, min=True)) < 0: pm.confirmDialog( message="Negative frames are not supported. Sorry...", button=["ok"]) raise Exception("Negative frames are not supported") self._errors = {} self._exportables = kwargs.get('export_extensions', []) self._json_rig = None self._usd_step_frame = kwargs.get('usd_step_frame', 20) self._nodes = [] self._graph = HaGraph(graph_items_args=[]) self._graph.set_render(kwargs.get('render', SlurmRender.SlurmRender)) self._jobname_hash = random_hash_string() script_name = pm.sceneName() _, name = os.path.split(script_name) self.scene_name = name self._export_sets = {} self.basename, ext = os.path.splitext(name) self.tempdir = tempfile.mkdtemp(prefix="_".join( [os.getlogin(), self.scene_name, self._jobname_hash + "_"]), dir=SCRATCH) os.chmod(self.tempdir, 0o0777) self.assembly_json = AssemblyJson() self.global_params = dict( queue='3d', group='allhosts', start_frame=int(pm.playbackOptions(q=True, min=True)), end_frame=int(pm.playbackOptions(q=True, max=True)), job_on_hold=kwargs.get('job_on_hold', False), priority=-500, jobname=self.scene_name, exclude_list=[], usd_step_frame=self._usd_step_frame, assembly_json_file=self.tempdir + os.sep + "assembly.json")
def write_config(self, *args): """Takes the new user input and sets up everything necessary for the writing process """ # Update data for all of the new field entries self.update_network() # Set env vars self.set_env_vars() # Write the CONFIG_PATH dirs/files on the current machine. utils.install_goz() choice = pm.confirmDialog(title="ZBrush Success", message='Config Write Complete!', button=['Ok'])
def assertCurrentSceneReadWithoutDataLoss(prompt=True): if mc.file(q=True, errorStatus=True) > 0: sConfirm = 'Abort' sMsg = "ERRORS have occurred while reading this scene \n\nthat may result in DATA LOSS !" if prompt: sConfirm = pm.confirmDialog(title='WARNING !', message=sMsg, button=['Continue', 'Abort'], defaultButton='Abort', cancelButton='Abort', dismissString='Abort', icon="warning") if sConfirm == 'Abort': raise AssertionError(sMsg.replace('\n', ''))
def copy(src, trgs=None): """Copies main skinCluster data from source geo to target # Usage: Select src and target(s) If target dosen't have one, user will be prompted to create new # Return: list(), cretaed skinClster nodes """ ls_src_scl = pm.PyNode(src).listHistory(type="skinCluster") if not ls_src_scl: print " skinCluster not found on source" return src_scl = ls_src_scl[0] src_infs = pm.skinCluster(src_scl, q=1, inf=1) trgs = pm.ls(trgs) items = [] for sel in trgs: scl = None ls_trg_scl = sel.listHistory(type="skinCluster") if not ls_trg_scl: print " on target: {}".format(sel) user_inp = pm.confirmDialog(m="skinCluster not found\nCreate?", t=sel.nodeName(), b=["Create", "Skip", "Cancel"], cb="Cancel") if user_inp == "Cancel": return if user_inp == "Skip": continue scl = mk_skin_cluster(sel, src_infs) else: scl = ls_trg_scl[0] # recreate influence order cp_infs(src_scl, scl) # copy cp_values(src_scl, scl) # copy bind prematrix cp_bind_pm(src_scl, scl) if scl: items.append(scl) return items
def makeUserColorAttrs(sel=None): mattes = ['A', 'B', 'C', 'D', 'E', 'F', 'X'] if sel is None: ## Select all geo in the scene if no selection is specified chk = pm.confirmDialog( title='Really?', message= '''Heads up - pressing this with nothing selected will\nadd custom attributes to all the geo in your scene.\nThis won't hurt anything, but it isn't really undoable\nand it might take a while. Continue?''', button=['Ok', 'Cancel'], defaultButton='Ok', cancelButton='Cancel', dismissString='Cancel') if chk == 'Ok': ## Dialog confirms the big operation sel = [mesh for mesh in pm.ls(type='mesh')] if sel is None: ## Break the operation if the user cancels. return False sel = convertSel(sel, sh=True) for id in mattes: for obj in sel: try: pm.addAttr(obj, longName=('vrayUserColor_matte' + id), nn=('matte' + id), usedAsColor=True, at='float3') pm.addAttr(obj, longName=('matte' + id + '_R'), attributeType='float', parent='vrayUserColor_matte' + id) pm.addAttr(obj, longName=('matte' + id + '_G'), attributeType='float', parent='vrayUserColor_matte' + id) pm.addAttr(obj, longName=('matte' + id + '_B'), attributeType='float', parent='vrayUserColor_matte' + id) except: ## Checking for the attributes already existing. Throws a warning for generic failure. try: test = obj.attr('VRayUserColor_matte' + id).get() continue except: pass #pm.warning('Could not add some attributes')
def mongoConnect(): global db try: client = pymongo.MongoClient('localhost', 27017, serverSelectionTimeoutMS=5000, socketTimeoutMS=5000) db = client.lcPipeline except: resp = pm.confirmDialog(title='Error', message='No Database Connection Found!', button=['OK'], defaultButton='Ok', dismissString='Ok') if resp == 'Ok': sys.exit()
def publishFile(self, *args): # get database info on item item = Item(task=self.task, code=self.code, itemType=self.type) item.proxyMode = self.proxyMode item.publishAs() version.takeSnapShot(item.getDataDict()) self.closeWin() print 'publish ver %s, at %s' % (item.publishVer, item.getPublishPath()) resp = pm.confirmDialog(title='Warning', ma='center', message='PUBLISH: %s %s \n Reopen working task?' % (item.name, item.task), button=['Ok', 'No'], defaultButton='Ok', dismissString='No') if resp == 'Ok': version.open(type=item.type, task=item.task, code=item.code, force=True) else: pm.newFile(f=True, new=True)
def editCollection(coll, *args, **kwargs): print(args, kwargs) kw = dict( t='Edit Collection: {0}'.format(coll.name), m='{0} set(s)'.format(len(coll.sets)), db='Cancel', cb='Cancel', ds='dismiss', b=['Delete', 'Clear', 'Rename', 'Cancel'], ) action = pm.confirmDialog(**kw) if action == 'Clear': coll.clearSets() elif action == 'Delete': coll.delete() elif action == 'Rename': QuickSelectCollectionsMenu.renameCollectionPrompt(coll)
def restore(lssl=None): """select transform(s)""" lssl = pm.ls(lssl) if not lssl: lssl = pm.selected() for sel in lssl: ls_cns = find(sel) if ls_cns: user_inp = pm.confirmDialog( m="Delete existing constraints on {}?".format(sel), b=["Delete", "Cancel"], cb="Cancel", db="Cancel") if user_inp == "Cancel": continue pm.delete(ls_cns) doRestore(sel)
def clean(ctrl): #missingTargets = [] for i, spaceTarget in enumerate(getTargetInfo(ctrl)): if not spaceTarget.target: #missingTargets.append(spaceTarget) res = confirmDialog(m='There is nothing connected to %s' % spaceTarget.name, b=['Delete', 'Ignore']) if res == 'Delete': conditions = ctrl.attr( common.ENUM_ATTR).listConnections(type='condition') for condition in conditions: if int( condition.secondTerm.get() ) == i and not condition.outColorR.listConnections(p=True): delete(condition) break
def editSet(self, quickSet, quickSetIndex): kw = dict( t='Edit Quick Select Set:', m=quickSet.getTitle(), db='Cancel', cb='Cancel', ds='dismiss', b=['Add', 'Replace', 'Rename', 'Delete', 'Cancel'], ) action = pm.confirmDialog(**kw) if action == 'Add': self.addSelection(quickSet) elif action == 'Replace': self.replaceWithSelection(quickSet) elif action == 'Rename': self.renamePrompt(quickSet) elif action == 'Delete': self.deleteSet(quickSetIndex)
def open(): ''' ensures the scene is saved prior to opening UI can be bypassed by creating instance of MusterSubmit class then running ui function ''' if pm.sceneName() == '': check = pm.confirmDialog( title='Save', message=' Scene not saved.\nDo you wish to save it now?', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' ) if check == 'Yes': pm.runtime.SaveSceneAs() open() #re-run to make sure the user didn't cancel the save dialog else: win = MusterSubmit() win.ui() return win
def save_incr(self, comment=None): ''' Increment Scene. ''' curr_path = pmc.sceneName() curr_name, curr_ext = curr_path.name.splitext() re_incr = re.compile(r"_\d+") matches = re_incr.findall(curr_name) if len(matches) == 0: logger.warning( "Please check filename format: 'your_asset_name_XX_optional_comment.ma'!" ) return False else: match = matches[-1] curr_asset = curr_name.split(match)[0] curr_incr_str = match.replace("_", "") new_incr_int = int(curr_incr_str) + 1 # "_{num:0{width}d}" creates the increment suffix with leading zeroes new_incr_str = "_{num:0{width}d}".format(num=new_incr_int, width=self.incr_padding) incr_file = pmc.Path(curr_path.parent + "/" + curr_asset + new_incr_str + curr_ext) if os.path.exists(incr_file): logger.error("FILE ALREADY EXITS!") confirmation = pmc.confirmDialog(title='Confirm', message="Force Save?", button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No') if confirmation == 'Yes': self.save_as(incr_file, comment) else: return False else: return self.save_as(incr_file, comment)
def checkWeighting(*args): percent = totalGrades.queryAnti().getValue2() + totalGrades.queryComp( ).getValue2() + totalGrades.queryPro().getValue2() print percent if percent != 100: dialogCheck = pm.confirmDialog(title='Confirm Output', message='percentage not equal 100', button=['override', 'change'], defaultButton='change', cancelButton='change', dismissString='override') if dialogCheck == 'change': print("Output Cancelled") else: print("override") output() else: output()
def exportFileLV( fileNameFull): # Save LAST VERSION of INPUT file. Inputs(fileNameFull) print 'dna.exportFileLV [ INPUT FILE ]: {0}'.format(fileNameFull) # Analize FILE PATH fileParts = fileNameFull.split('/') fileName = fileParts.pop(-1) fileExt = fileName.split('.')[-1] fileVer = fileName.split('.')[0].split('_')[-1] fileNameNoVer = fileName.split('{0}.{1}'.format(fileVer, fileExt))[0] filePath = '' # Rebuild full path to a FILE for i in fileParts: filePath += i + '/' # print filePath, fileNameNoVer, fileVer, fileExt if os.path.exists(fileNameFull): # IF FILE EXISTS listExisted = glob.glob('{0}{1}*.{2}'.format(filePath, fileNameNoVer, fileExt)) listVersions = [] for i in listExisted: version = i.split('\\')[-1].split( '.{}'.format(fileExt))[0].split('_')[-1] listVersions.append(version) versionCurrent = int( max(listVersions)) # create number for latest version confirm = pm.confirmDialog(title='File exists!', message='{0}{1:03d}.{2}'.format( fileNameNoVer, versionCurrent, fileExt), button=['SAVE NEXT VERSION', 'CANCEL'], cancelButton='CANCEL', dismissString='CANCEL') if confirm == 'SAVE NEXT VERSION': fileNameFullNextVer = '{0}{1}{2:03d}.{3}'.format( filePath, fileNameNoVer, versionCurrent + 1, fileExt) export(fileNameFullNextVer, fileExt) print 'CREATED NEXT VERSION: {}'.format(fileNameFullNextVer) else: sys.exit('CANCELED!') else: # IF FILE NOT EXISTS if not os.path.exists(filePath): os.makedirs(filePath) else: export(fileNameFull, fileExt) print 'FILE CREATED: {}'.format(fileNameFull)
def show(): #check modifyed if not sceneName(): PopupError('Save scene before continue') return if cmds.file(q=True, modified=True) and not objExists(submitter_variables.root_group_name): if confirmDialog( title='Continue ?', message='Scene have unsaved changes\n\nContinue without saving?', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' ) == 'No': return def showUI(): from . import submitter_window reload(submitter_window) w = submitter_window.SubmitterWindowClass() w.show() load_ai() QTimer.singleShot(1000, showUI)
def tagMain(self): obj = selected()[0] main = ls('*.' + core.find.FOSSIL_MAIN_CONTROL) if main: # Already tagged as main if main[0].node() == obj: return if confirmDialog( m='{} is already tagged, are you sure want to make {} the main?'.format(main[0].node(), obj), b=['Yes', 'No'] ) == 'Yes': main[0].node().deleteAttr(core.find.FOSSIL_MAIN_CONTROL) else: return core.find.tagAsMain(obj) self.update()
def displayMessage(self, title, message, details=None, buttons=('Ok',), defaultButton=None, cancelButton=None, checkBox=None): """This is basically Maya's copy of a QMessageBox.""" if checkBox is None: return pm.confirmDialog( title=title, message=message, button=buttons, defaultButton=defaultButton, cancelButton=cancelButton, dismissString=cancelButton, ) return super(MayaWindow, self).displayMessage( title=title, message=message, buttons=buttons, defaultButton=defaultButton, cancelButton=cancelButton, checkBox=checkBox, )
def clone_attrs(attrs=None, targObj=None, connect=None): """Given a list of pymel attribute objects, re-create them on the targObj. Optional "connect" flag accepts string args: "forward", which connects the original attrs to the cloned ones; "reverse", which connects the cloned ones to the original ones; or "move", which bypasses the old object completely and reconnects the new attributes to any previous downstream plugs.""" if not targObj: targObj = pmc.selected()[0] if not attrs: attrs = get_selected_cb_attrs() if not connect: connect = pmc.confirmDialog( title="Attribute Cloner", message="What kind of connections should be made?", button=("New > Old", "Old > New", "Replace", "None")) for a in attrs: kwargs = { "k": True, "at": a.type(), "ln": a.longName(), "sn": a.shortName() } args = (("max", a.getMax()), ("min", a.getMin()), ("smx", a.getSoftMax()), ("smn", a.getSoftMin())) for name, val in args: if val is not None: kwargs[name] = val pmc.addAttr(targObj, **kwargs) targAttr = targObj.attr(a.attrName()) targAttr.set(a.get()) if connect == "New > Old": targAttr >> a elif connect == "Old > New": a >> targAttr elif connect == "Replace": for out_plug in a.outputs(plugs=True): targAttr >> out_plug # kill old attribute a.delete()
def removeAdjustment(self): rowIndices = [modelIndex.row() for modelIndex in self.ui.aligns.selectedIndexes()] toDelete = [] for i in rowIndices: toDelete.append( self.commands[i].card.name() + ' ' + self.commands[i].data['call'] ) if confirmDialog(m='Delete these %i adjusters?\n' % len(rowIndices ) + '\n'.join(toDelete), b=['Delete', 'Cancel'] ) == 'Delete': for rowIndex in rowIndices: with self.commands[rowIndex].card.rigData as rigData: print('Rig Data', rigData) for i, data in enumerate(rigData['tpose']): print('COMP', data['order'], self.commands[rowIndex].order) if data['order'] == self.commands[rowIndex].order: print('Found and deleting') del rigData['tpose'][i] break self.listAdjustments()
def updateSun(self, node=None): thisLight = pm.PyNode(node) if thisLight.mtco_useAsSun.get(): otherLights = [] for light in pm.ls(type="directionalLight"): if light.mtco_useAsSun.get() and (light != thisLight): otherLights.append(light) if len(otherLights) > 0: result = pm.confirmDialog( title="Sun Problem", message= "Another Light already has sun activated, what should be done?", button=["Use This light", "Use Other Light"]) if result == "Use This light": for light in otherLights: light.mtco_useAsSun.set(False) else: thisLight.mtco_useAsSun.set(False)
def on_delete_btn(self, *args): # Delete image plane handler confirm = pm.confirmDialog(title='Delete', message='Deleting image plane %s ?' % (self.currentImgPlane), button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No') if confirm == 'Yes': print('ipm: deleting %s' % self.currentImgPlane) if pm.objExists('%s_mover' % self.currentImgPlane[0]): pm.delete('%s_mover' % self.currentImgPlane[0]) pm.delete('%s_moveroffset' % self.currentImgPlane[0]) pm.delete(pm.listRelatives(self.currentImgPlane, p=1)) self.imp_option_list() self.create()
def createShdrID(*agrs): checkArnold() # check if any Shading Group selected or not shdrs = pm.ls(sl = 1, type='shadingEngine') if shdrs: print 'Shading groups selected manualy' else: confirm = pm.confirmDialog ( title='WARNING', message='No shading group selected, create IDs for all shades in scene?', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' ) if confirm == 'Yes': shdrs = pm.ls(type='shadingEngine') shdrs.remove('initialParticleSE') shdrs.remove('initialShadingGroup') else: sys.exit() index = checkShdrID() for i in iterBy(shdrs,3): addShdrAOV('%02d' %index) #create AOV #create and plug R createShaderR('%02d' %index) shader = 'id_R_%02d' %index SHD = pm.PyNode(shader) SHD.outColor >> i[0].aiCustomAOVs[index].aovInput; #create and plug G if i[1]: createShaderG('%02d' %index) shader = 'id_G_%02d' %index SHD = pm.PyNode(shader) SHD.outColor >> i[1].aiCustomAOVs[index].aovInput; #create and plug B if i[2]: createShaderB('%02d' %index) shader = 'id_B_%02d' %index SHD = pm.PyNode(shader) SHD.outColor >> i[2].aiCustomAOVs[index].aovInput; index +=1
def generateShaderReport(squelch_valid=False, *a): sel = pm.ls(sl=True) sel = selection.convert(sel, xf=True) diag = pm.confirmDialog( title='Check shaders >>', message= 'Do you want to select any meshes the script finds problems with?\nNOTE: Instanced meshes always fail, not sure why just yet.', button=['Yes', 'No'], defaultButton='Yes') problem_objects = [] for obj in sel: sobj = str(obj).ljust(50) if not obj.getShape().nodeType() == 'mesh': continue valid, obj, shading_groups = validateShaderAssignment(obj) if valid and not squelch_valid: mat = getShader(obj, select_result=False) pm.warning("Object: " + sobj + " : properly shaded : " + str(mat)) elif valid == False: #mat = [] #for sg in shading_groups: # for m in MATERIALS: # mat += sg.listConnections(s=True, d=False, t=m, et=True) problem_objects.append(obj) pm.warning("Object: " + sobj + " : multiple materials") # : " + str(mat)) elif valid == None: problem_objects.append(obj) pm.warning("Object: " + sobj + " : no materials") pm.warning("::::::: REPORT COMPLETE :::::::") if diag == 'Yes': pm.select(problem_objects) else: pass return problem_objects
def exportSelected(self, *args): '''Export selected rig''' # Get information fName = pm.textFieldGrp(self.fNameFld, q=1, text=1) animFile = pm.cmds.file(q=1, sn=1) exportFile = os.path.dirname(animFile) + os.path.sep + fName + '.fbx' if os.path.exists(exportFile): answer = pm.confirmDialog(title='FBX File exists', message='Overwrite?', button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No') if answer == 'No': print 'Export canceled.' return try: root = pm.ls(sl=1)[0] except: raise Exception(self.noSelError) pm.select(root.replace('MAINCtrl', 'MAINSHJnt'), r=1) root = pm.ls(sl=1)[0] # Import reference self._importRef(sel=root) # Bake animation on SH self._bakeAnim(root=root.name()) # Delete constraint self._delConstraints(jnt=root) # Move out of rig heirarchy pm.parent(root, w=1) # Export selected heirarchy self._fbxExport(selection=root, fileName=exportFile) print "Export complete.\n\n"