def onPress(self): mods = cmds.getModifiers() if (mods & 4) > 0: return if (cmds.draggerContext(self.ctxName, q=True, bu=True) > 1): self.reset() self.updateStatusLine() return p = self.getClickedParams() if (not p): return if (len(self.clickedPoints) > 1 and self.curve): mods = cmds.getModifiers() if (mods & 1) > 0: self.clickedPoints[0] = p else: self.clickedPoints[1] = p self.modifyCurve() elif (len(self.clickedPoints) == 1): self.clickedPoints.append(p) self.createCurve() else: self.clickedPoints.append(p) self.updateStatusLine()
def selCtrl(self, ctrl): print ctrl ov = cmds.optionMenu('oMenu', q=1, value=1) if ov == 'root': ov = ':' mods = cmds.getModifiers() if mods == 4: cmds.select(ov + ':' + ctrl, add=1) else: cmds.select(ov + ':' + ctrl, replace=1)
def isPressed(self, modifier): ''' returns True if the modifier is currently pressed ''' bitmask = mc.getModifiers() & self.modifierMask[modifier] if bitmask > 0 : return True else: return False;
def selectList(self): """ select objects in list of connected objects :return: None """ logger.debug("select!") add = False if (cmds.getModifiers() == 1): #add to selection if shift is pressed logger.debug("shift") add = True if (self.selected == False): #select objects in connections list self.setChecked(True) #set white outline self.selected = True if (add == False): #deselect everything first try: cmds.select(self.connection[0]) except: logger.error(self.connection[0] + " doesn't exist in scene") for obj in self.connection: #select objects in list try: cmds.select(obj, add=True) except: logger.error(obj + " doesn't exist in scene") else: #deselect objects in connections list self.setChecked(False) #set black outline self.selected = False for obj in self.connection: #deselects objects try: cmds.select(obj, deselect=True) except: logger.error( "Nothing deselected. Objects don't exist in scene")
def _rename_(self, mode=''): selection = pymel.ls(selection=True) nameList = [] for each in selection: nameList.append(each.nodeName()) if mode == 'searchAndReplace': renameList = self.figureOut_searchAndReplace(nameList) if mode == 'prefixSuffix': renameList = self.figureOut_prefixSuffix(nameList) if mode == 'nameAndNumber': renameList = self.figureOut_nameAndNumber(nameList) # renameList = self.figureOut_rename(selection) for i, each in enumerate(selection): pymel.rename( selection[i], renameList[i] ) self.update() mods = cmds.getModifiers() if (mods & 4) > 0: #Ctrl self.close()
def onDrag(self): mods = cmds.getModifiers() if (mods & 4) > 0: pressPosition = cmds.draggerContext(self.ctxName, query=True, anchorPoint=True) dragPosition = cmds.draggerContext(self.ctxName, query=True, dragPoint=True) self.magCoeff += (float(dragPosition[0]) - float(pressPosition[0])) * 0.001 if (len(self.clickedPoints) > 1 and self.curve): self.modifyCurve() """ elif( len( self.clickedPoints ) > 1 and self.curve ): p = self.getClickedParams() if( mods & 1 ) > 0: self.clickedPoints[0] = p else: self.clickedPoints[1] = p self.modifyCurve() """ cmds.refresh(cv=True)
def _buttonSelect(self, controller, ikFk): """ Button selection method :param controller: :param extraCode: :return: """ # if ikFk attribute is true object = '%s_%s' % (self.chName, controller) ikfkNodeName = '_'.join(object.split('_')[0:3]) + '_attrShape' if ikFk: if cmds.getAttr('%s.ikFk' % ikfkNodeName): object = object.replace('fk', 'ik') # select command # info about the keys modifier = cmds.getModifiers() noKey = modifier == 0 shift = modifier == 1 control = modifier == 4 # combined keys controlShift = modifier == 5 logger.debug('Modifier value: %s' % modifier) logger.debug('shift: %s' % shift) logger.debug('control: %s' % control) logger.debug('controlShift: %s' % controlShift) # select command cmds.select(object, r=noKey, tgl=shift, add=controlShift, d=control) print 'Select %s' % object
def selectControls(self, controls, buttonInfo, *args): # buttonInfo = [[buttonName, buttonBGC]] # if yo have shift held down mods = cmds.getModifiers() if (mods & 1) > 0: for i in range(len(controls)): cmds.select(controls[i], tgl=True) buttonName = buttonInfo[i][0] buttonBGC = buttonInfo[i][1] cmds.button(buttonName, edit=True, bgc=[1.0, 1.0, 1.0]) ++i # call our scriptJob self.createSelectionScriptJob(controls[i], buttonName, buttonBGC) # if you have no modifier: else: cmds.select(clear=True) for i in range(len(controls)): cmds.select(controls[i], add=True) buttonName = buttonInfo[i][0] buttonBGC = buttonInfo[i][1] cmds.button(buttonName, edit=True, bgc=[1.0, 1.0, 1.0]) ++i # call our scriptJob self.createSelectionScriptJob(controls[i], buttonName, buttonBGC)
def RemoveUnusedInfluence(*args, **kwargs): # Get shift key mods = cmds.getModifiers() shift = (mods & 1) > 0 boleanCheck = False # if shift: boleanCheck = True # def unused_influence(object=''): # mainSkin = [ item for item in cmds.listHistory(object) if cmds.objectType(item, isType='skinCluster') ] if len(mainSkin) == 0: return jntList = set( [itm for itm in cmds.skinCluster(mainSkin[0], q=1, inf=1)]) weigthedList = set( [itm for itm in cmds.skinCluster(mainSkin[0], q=1, wi=1)]) non_weigthed = list(jntList.difference(weigthedList)) cmds.skinCluster(mainSkin[0], edit=True, ri=non_weigthed) print('Removed from Skin: {} :: {} '.format(mainSkin[0], non_weigthed)) if boleanCheck: [unused_influence(obj) for obj in cmds.ls(type='mesh')] else: [unused_influence(obj) for obj in cmds.ls(sl=True)]
def ldmt_turboSmooth(): mods = cmds.getModifiers() mel.eval('resetPolySelectConstraint;') sel = cmds.ls(sl=1,o=1) sel = sel[0] cmds.select(sel+'.e[*]',r=1) cmds.polySelectConstraint(m=3,t=0x8000,sm=1) cmds.sets(n="ldmt_turboSmoothQS") currentSel = cmds.ls(sl=1) if currentSel != []: try: cmds.polyCrease(value=1) except: pass cmds.select(sel,r=1) cmds.polySmooth(sel,mth=0,sdt=2,ovb=2,ofb=3,ofc=1,ost=1,ocr=1,dv=1,bnr=1,c=0,kb=0,ksb=1,khe=1,kt=0,kmb=0,suv=1,peh=1,sl=1,dpe=1,ps=0.1,ro=1,ch=1) cmds.select("ldmt_turboSmoothQS",r=1) currentSel = cmds.ls(sl=1) if currentSel != []: try: cmds.polySoftEdge(a=0,ch=1) cmds.polyCrease(value=0) except: pass if mods == 4: try: cmds.polyCrease(value=1) except: pass cmds.polySelectConstraint(m=0,dis=1) cmds.select(sel,r=1) cmds.delete("ldmt_turboSmoothQS")
def is_shift_down(*args): mods = cmds.getModifiers() #bitwise 1 to get if shift down if (mods & 1) > 0: return True else: return False
def getFrame(val=0, attr='r_ojo', ctr='L_EYE_PUPILA_CNT', *args): # Con esta funcion pregunto si existe el control que le estoy pasando por # argumento if cmds.objExists(ctr + '.' + attr): currentVal = cmds.getAttr(ctr + '.' + attr) # Devuelve el evento que preciono mods = cmds.getModifiers() setKeyNow(ctr, attr) # pregunto si se preciono y es shift y agrego a la seleccion if (mods & 1) > 0:#Shift if 'l_' in attr: attr = 'r_' + attr.split('l_')[1] cmds.setAttr(ctr + '.' + attr, val) setKeyNow(ctr, attr) elif 'r_' in attr: attr = 'l_' + attr.split('r_')[1] cmds.setAttr(ctr + '.' + attr, val) setKeyNow(ctr, attr) else: cmds.warning( 'No contiene el otro lado de la misma imagen nombrada L_ o R_') # de lo contrario solo selecciono else: cmds.setAttr(ctr + '.' + attr, val) setKeyNow(ctr, attr) else: cmds.warning('No existe el atributo o variable ' + attr + ', en el control ' + ctr + ' o necesita de un namespace.')
def is_control_down(*args): mods = cmds.getModifiers() #bitwise 4 to get if control down if (mods & 4) > 0: return True else: return False
def changeCommand(scrubWidget, values): modifiers = cmds.getModifiers() if (modifiers & 4) > 0: ctrlDown = True else: ctrlDown = False ka_weightBlender.change(blendValue=values[0], bothNeighbors=ctrlDown)
def select(self, target): shift, ctrl = 1, 4 mod = int(cmds.getModifiers()) flags = {"replace": mod == 0, "toggle": mod == shift, "deselect": mod == ctrl, "add": mod == ctrl + shift} cmds.select(target, **flags)
def MessageBox(Message): '''Displaying Entered Message as Popup ''' oWindow = cmds.window(title = 'Message Box', s = False) if cmds.windowPref(oWindow, exists = True): cmds.windowPref(oWindow, remove = True) cmds.columnLayout(adjustableColumn = True) cmds.text('\n\t%s\t\n' % Message, bgc = (.25,.25,.25),enableBackground = False) cmds.button(label = 'Close', command = ('cmds.deleteUI(\"'+oWindow+'\",window = True)'), bgc = (.2,.2,.2),enableBackground = False) cmds.setParent('..') cmds.showWindow(oWindow) # Print Methods import maya.mel as mel dir(mel) # To Get the creation time of a file from datetime import datetime import os tCreateTime = os.path.getmtime('/job/nysm2/film/bt163/bt163_0485/work/dyabu/maya/scenes/bt163_0485_DY.v001.01.Ohoh.0002.mb') print datetime.fromtimestamp(tCreateTime).strftime('%Y-%m-%d %H:%M:%S') ### Modifiers K = cmds.getModifiers() sMenu = ''' ----- ALT [8] ----- CTL [4] ----- SFT [1] ----- CTL + SFT [5] ----- ALT + SFT [9] ----- CTL + ALT [12] ----- CTL + ALT + SFT [13]''' ### fill with 0 in a string. ex "003" '1'.zfill(3) ### Prompt Dialog Box o = cmds.confirmDialog( title='Confirm', message='Are you sure?', button=['Yes','No','Maybe','Not Sure'], defaultButton='Yes', cancelButton='No', dismissString='No' , bgc = [1.2,1.2,1.2]) ### Prompt Enter Box def EnterBox(): oResult = cmds.promptDialog( title='Rename Object', message='Enter Name:', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if oResult == 'OK': sText = cmds.promptDialog(query=True, text=True) return sText else:
def UIButton_Capture(self, sView, *args): # Display Logic K = cmds.getModifiers() sGrayOut = 'darkgray' dToolInfo = StudioSettings.SceneInfoStorage(self.sTool) sLabel = dToolInfo[sView] iStartCapture = 0 if K: if sLabel == '-': sLabel = sView else: sLabel = '-' dToolInfo[sView] = sLabel StudioSettings.SceneInfoStorage(self.sTool, dToolInfo) else: if not sLabel == '-': iStartCapture = 1 #self.UIDisplayChecker() # PlayBlast time! if iStartCapture: sCapturePath = self.dShotInfo['sPlayBlastSeqPath']+'/'+sView+'/PlayBlast_%s'%sView #sCapturePath = self.aShotInfo[7]+'/'+sView+'/PlayBlast_%s'%sView sIn = dToolInfo['currentStartFrame'] sOut = dToolInfo['currentEndFrame'] cmds.playblast(format = 'image', filename = sCapturePath, st = int(sIn), et = int(sOut), sequenceTime = 0, clearCache = 1, viewer = 0, showOrnaments = 1, offScreen = True, fp = 4, percent = 100, compression = "jpg", quality = 70, fo = True, wh = [self.iPBwidth, self.iPBheight]) cmds.warning('Capture Process All Finished') #self.UIDisplayChecker() cmds.button('oUICapture%sButton'%sView, e = True, bgc = self.UIBGColour('tone1')) #self.dDict['LastCapture'] = sView dToolInfo['LastCapture'] = sView self.PrintOnScreen(['a7a8af', 'Playblast done [%s]'%sView, 0x6b6c75]) StudioSettings.SceneInfoStorage(self.sTool, dToolInfo) self.UIConvertTool_DisplayChecker() self.UIDisplayChecker()
def mousePressEvent(self, event): mods = cmds.getModifiers() if (mods & 1) > 0: for obj in self.objects: cmds.select(obj, add=True) if (mods & 1) == 0: cmds.select(clear=True) for obj in self.objects: cmds.select(obj, tgl=True)
def getModifier(): ''' return the modifier key pressed ''' mods = cmds.getModifiers() if (mods & 1) > 0: return 'Shift' if (mods & 2) > 0: return 'CapsLock' if (mods & 4) > 0: return 'Ctrl' if (mods & 8) > 0: return 'Alt' else: return False
def fixCurvatureDirection(): mods = cmds.getModifiers() if (mods == 8): sel = cmds.ls(sl=1, o=1) kWorld = om2.MSpace.kWorld for each in sel: eachList = om2.MSelectionList() eachList.add(each) eachPath = eachList.getDagPath(0) eachMesh = om2.MFnMesh(eachPath) point0 = eachMesh.getPoint(0, space=kWorld) point1 = eachMesh.getPoint(1, space=kWorld) point0_MVec = om2.MVector(point0[0], point0[1], point0[2]) point1_MVec = om2.MVector(point1[0], point1[1], point1[2]) normal0 = eachMesh.getClosestNormal(point0, space=kWorld) normal1 = eachMesh.getClosestNormal(point1, space=kWorld) point0N = point0_MVec + normal0[0] point1N = point1_MVec + normal1[0] vec0_1 = point1_MVec - point0_MVec vec0_1_length = vec0_1.length() point0N_MVec = om2.MVector(point0N[0], point0N[1], point0N[2]) point1N_MVec = om2.MVector(point1N[0], point1N[1], point1N[2]) vec0N_1N = point1N_MVec - point0N_MVec ifSameDirection = vec0_1 * vec0N_1N attrCurvature = each + '.curvature' if ifSameDirection > 0 or vec0N_1N.length() > vec0_1.length(): curvatureValue = cmds.getAttr(attrCurvature) cmds.setAttr(attrCurvature, curvatureValue * (-1)) else: sel = cmds.ls(sl=1, o=1) kWorld = om2.MSpace.kWorld for each in sel: eachList = om2.MSelectionList() eachList.add(each) eachPath = eachList.getDagPath(0) eachMesh = om2.MFnMesh(eachPath) point0 = eachMesh.getPoint(0, space=kWorld) point1 = eachMesh.getPoint(1, space=kWorld) point0_MVec = om2.MVector(point0[0], point0[1], point0[2]) point1_MVec = om2.MVector(point1[0], point1[1], point1[2]) normal0 = eachMesh.getClosestNormal(point0, space=kWorld) normal1 = eachMesh.getClosestNormal(point1, space=kWorld) point0N = point0_MVec + normal0[0] point1N = point1_MVec + normal1[0] vec0_1 = point1_MVec - point0_MVec vec0_1_length = vec0_1.length() point0N_MVec = om2.MVector(point0N[0], point0N[1], point0N[2]) point1N_MVec = om2.MVector(point1N[0], point1N[1], point1N[2]) vec0N_1N = point1N_MVec - point0N_MVec ifSameDirection = vec0_1 * vec0N_1N attrCurvature = each + '.curvature' if ifSameDirection < 0 or vec0N_1N.length() < vec0_1.length(): curvatureValue = cmds.getAttr(attrCurvature) cmds.setAttr(attrCurvature, curvatureValue * (-1))
def modifier_pressed(self): ''' return the string associated with the currently held modifier key ''' mods = cmds.getModifiers() return_list = [] if (mods & 1) > 0: return_list.append('SHIFT') if (mods & 2) > 0: return_list.append('CAPSLOCK') if (mods & 4) > 0: return_list.append('CONTROL') if (mods & 8) > 0: return_list.append('ALT') return return_list
def keysPressed(): m_mods = cmds.getModifiers() m_keys = '' if (m_mods & 1) > 0: m_keys = 'Shift' if (m_mods & 2) > 0: m_keys = 'CapsLock' if (m_mods & 4) > 0: m_keys = 'Ctrl' if (m_mods & 8) > 0: m_keys = 'Alt' return m_keys
def to( self, null, shelf, pos, *args ): # delete from MM when CTRL is pressed if m.getModifiers() == 4 and pos: m.optionVar( rm=mmName + pos ) return # remember recenctly pressed from non radial list if not shelf in self.inRadial: if shelf in self.recent: self.recent.remove(shelf) self.recent.append(shelf) m.optionVar( sv=[mmName + 'Recent', ','.join(self.recent)] ) m.shelfTabLayout( mayaShelf, edit=1, selectTab=shelf )
def seleccion(ctr='',*args): #Con esta funcion pregunto si existe el control que le estoy pasando por argumento if cmds.objExists(ctr): #Devuelve el evento que preciono mods = cmds.getModifiers() #pregunto si se preciono y es shift y agrego a la seleccion if (mods & 1) > 0: cmds.select(ctr,add=True) #de lo contrario solo selecciono else: cmds.select(ctr) else: cmds.warning('No existe el control %s o existen dos iguales o necesita un namespace.'%(ctr))
def selectControls(controls, *args): #Shift command mods = cmds.getModifiers() if (mods & 1) > 0: cmds.select(controls, add=True) else: cmds.select(clear=True) cmds.select(controls, tgl=True)
def button_callback(button, *args): mods = cmds.getModifiers() if (mods & 1) > 0: # If shift is pressed if not button.is_selected(): # If the button is currently not selected, but it must be : ctrlManager.add_controller_to_selection(button.controller) else: # If the buttonn is currently selected, but is must not be : ctrlManager.remove_controller_from_selection(button.controller) else: # If shift is not pressed if ctrlManager.is_button_unique(button): # If the button is currently not selected, but it must be : ctrlManager.clear_selection() else: ctrlManager.change_selected_controller(button.controller) cmds.select( ctrlManager.get_selection_list() )
def UIButton_Open(self, sOpen, *args): # 'PB' for quad view, 'Anno' for opening Annotation.rv K = cmds.getModifiers() if sOpen == 'PB': if not os.path.exists(self.sRvPath): K = 100 if K: # If with any Modifiers, Create a fresh Active.rv. (deletes all markings etc.) dInfo = StudioSettings.SceneInfoStorage( self.sTool) # Check function for more info. sIn = dInfo['prodStartFrame'] if sIn == None: sIn = dInfo['currentStartFrame'] sOut = dInfo['prodEndFrame'] if sOut == None: sOut = dInfo['currentEndFrame'] aPath = [ None, None, None, None, ] for i in range(0, len(aPath)): #aPath[i] = self.aShotInfo[7] + '/%s/PlayBlast_%s.%s-%s@@@@.jpg'%(str(i+1), str(i+1), sIn, sOut) aPath[i] = self.dShotInfo[ 'sPlayBlastSeqPath'] + '/%s/PlayBlast_%s.%s-%s@@@@.jpg' % ( str(i + 1), str(i + 1), sIn, sOut) sContent = self.CreateLatestQuadRvFile(aPath) if sContent: oRvFile = open(self.sRvPath, 'w') oRvFile.write(sContent) oRvFile.close() aPrint = ['a7a8af', 'Creating a New .rv', 0x6b6c75] else: aPrint = ['a7a8af', 'Opening Existing .rv', 0x6b6c75] try: cmd = 'rv %s &' % (self.sRvPath) os.system(cmd) except Exception as e: print e self.PrintOnScreen(aPrint) self.UIDisplayChecker()
def Button_OpenFolder(self, *args): StudioSettings.ShotInfo(0,1) # (1,1) = (Folder Creation, Print paths.) aPath = self.GetScenePathFromCurrentEnvironment().split('/') #aPath = self.sScenePath sPath = '/'.join(aPath) if not cmds.getModifiers() == 0: StudioSettings.OSFileBrowserCommand(sPath) aPrint = ['a7a8af', 'Opening Folder.', 0x6b6c75] else: StudioSettings.CopyToClipBoard(sPath) aPrint = ['a7a8af', 'Copied to Clipboard.', 0x6b6c75] cmds.inViewMessage(amg = '<text style="color:#%s";>%s</text>'%(aPrint[0], aPrint[1]), pos = 'botCenter', fade = True, fts = 7, ft = 'arial',bkc = aPrint[2] )
def selectControls(controls, buttons, *args): # If you have shift held down (shift is a modifier): mods = cmds.getModifiers() if (mods & 1) > 0: for control in controls: cmds.select(control, tgl = True) # If you have no modifiers: else: cmds.select(clear = True) # Clear the selection. for i in range(len(controls)): cmds.select(controls[i], add = True)
def getModKeyPressed(): mods = cmds.getModifiers() if mods == 1: return "shift" if mods == 4: return "ctrl" if mods == 8: return "alt" if mods == 5: return "ctrlShift" if mods == 9: return "altShift" if mods == 12: return "altCtrl" if mods == 13: return "altCtrlShift"
def selectControl(self, controls, args): mods = cmds.getModifiers() if (mods & 1) > 0: for i in range(len(controls)): cmds.select(controls[i], tgl = True) ++i elif (mods & 8) > 0: cmds.select(clear = True) else: cmds.select(clear = True) for i in range(len(controls)): cmds.select(controls[i], add = True) ++i
def group_button_callback(group_button, *args): mods = cmds.getModifiers() if (mods & 1) > 0: # If shift is pressed if not group_button.is_selected(): # If the button is currently not selected, but it must be : for button in group_button.get_associated_buttons(): ctrlManager.add_controller_to_selection(button.controller) else: # If the buttonn is currently selected, but is must not be : for button in group_button.get_associated_buttons(): ctrlManager.remove_controller_from_selection(button.controller) else: # If shift is not pressed if ctrlManager.is_buttongroup_unique(group_button): # If only this group is selected ctrlManager.clear_selection() else: ctrlManager.clear_selection() for button in group_button.get_associated_buttons(): ctrlManager.add_controller_to_selection(button.controller) cmds.select( ctrlManager.get_selection_list() )
def mousePressEvent(self, event): mods = cmds.getModifiers() if (mods & 1) > 0: cmds.select(self.object, tgl=True) if (mods & 1) == 0: cmds.select(self.object) if self.object in cmds.ls(sl=True): self.brush.setColor(QtCore.Qt.white) else: self.brush.setColor(self.brushColor) self.update() QtWidgets.QGraphicsPolygonItem.mousePressEvent(self, event)
def UIButton_OpenFolder(self, sFolder, *args): K = cmds.getModifiers() if sFolder == 'rv': #sPath = self.aShotInfo[6] sPath = self.dShotInfo['sPlayBlastToolPath'] elif sFolder == 'seq': ##sPath = self.aShotInfo[7] sPath = self.dShotInfo['sPlayBlastSeqPath'] if K: StudioSettings.OSFileBrowserCommand(sPath) aPrint = ['a7a8f', 'Opening a FileBrowser.', 0x6b6c75] else: StudioSettings.CopyToClipBoard(sPath) aPrint = ['a7a8af', 'Copied Path to Clipboard.', 0x6b6c75] self.PrintOnScreen(aPrint)
def onShadingNodeLabelPressed(shadingNode): mod = cmds.getModifiers() if mod == 1: # shift mel.eval('hyperShade -assign "' + shadingNode + '";') elif mod == 8: # alt # TODO: need to check, if the hyperShadePanel1 exists either in a viewport or in a window result = '' try: mel.eval('setFocus "hyperShadePanel1";') mel.eval('hyperShadePanelMenuCommand("hyperShadePanel1", "showBottomTabsOnly");') mel.eval('hyperShade -shaderNetwork "' + shadingNode + '";') mel.eval('hyperShadePanelGraphCommand("hyperShadePanel1", "rearrangeGraph");') except: mel.eval('print "Please open the Hypershader first and try again.";') result = cmds.confirmDialog(message = 'Please open the Hypershader first and try again.\nSorry, that might be a Maya bug... or maybe not...\nWe will see :)', button = 'Open Hypershader') if result == 'Open Hypershader': mel.eval('HypershadeWindow;') elif mod == 4: # ctrl mel.eval('hyperShade -objects "' + shadingNode + '";')
def render(mod=None): """ calls this function to run the script. If ctrl is pressed render is done with Ambient Occlusion """ if mod == None: mod = cmds.getModifiers() if mod == 4: FLAG = True else: FLAG = False if not cmds.ls(sl=True): loaded = True bI = BaseInitializer() bI.mrCheck() inst = GUI(FLAG, True) else: ## something was selected render first then show GUI instCSC = CreateShaderConnect(FLAG, "surfaceShader", False) CreateShaderConnect.isRenderable(instCSC)
def getState(self): ''' return 3 booleans for ctrl / shift / alt state keypress event ''' ctrl = shift = alt = False modifiers = mc.getModifiers() # SHIFT EVENT if (modifiers & 1) > 0 : if (self.shiftReleased): # shift was released in the previous iteration, this is a keypress self.shiftReleased = False shift = True else: # shift is not currently pressed, reseting the tracking self variable to released state self.shiftReleased = True # CTRL EVENT if (modifiers & 4) > 0 : if (self.ctrlReleased): # ctrl was released in the previous iteration, this is a keypress self.ctrlReleased = False ctrl = True else: # ctrl is not currently pressed, reseting the tracking self variable to released state self.ctrlReleased = True # ALT EVENT if (modifiers & 8) > 0 : if (self.altReleased): # alt was released in the previous iteration, this is a keypress self.altReleased = False alt = True else: # alt is not currently pressed, reseting the tracking self variable to released state self.altReleased = True return ctrl, shift, alt
def openTextureLocation(fileNode): import os.path from os import startfile filePath = cmds.getAttr(fileNode + '.fileTextureName') if filePath != '': mods = cmds.getModifiers() if mods == 0: startfile(os.path.dirname(filePath)) if mods == 1: # alt r = Tk() r.withdraw() r.clipboard_clear() r.clipboard_append(filePath) r.destroy() if mods == 8: # shift r = Tk() r.withdraw() r.clipboard_clear() r.clipboard_append(os.path.dirname(filePath)) r.destroy()
def run(mod=None): """ open outlier and select the node in outliner that is selected in veiwport. if Control Key is pressed on keyboard then open hypershade and graphs the material of selected object. Kwargs: :param mod: key modifer pressed :type mod: int """ mod = cmds.getModifiers() if mod == 4: print "Ctrl pressed", mod # show hypershade if _isobjectInList(cmds.getPanel(vis=1), 'hyperShade'): _graphMatSelObj() else: print "Hypershade is not open" cmds.HypershadeWindow() _graphMatSelObj() else: # show Outliner _openOutliner()
def onDrag(self): # modifier self.mod = cmds.getModifiers() # positions currentPos = cmds.draggerContext(self.dragCtx, query=True, dragPoint=True) # camera far clip currentView = omui.M3dView().active3dView() camDP = om.MDagPath() currentView.getCamera(camDP) camFn = om.MFnCamera(camDP) farclip = camFn.farClippingPlane() # screen to world conversion worldPos, worldDir = utils().viewToWorld(currentPos[0],currentPos[1]) closestHit = None closestObj = None for obj in self.targetObj: state, hit, fnMesh, facePtr, triPtr = utils().intersect(obj, worldPos, worldDir, farclip) if state is True: dif = [hit.x - worldPos[0],hit.y - worldPos[1],hit.z - worldPos[2]] distToCam = math.sqrt(math.pow(float(dif[0]),2) + math.pow(float(dif[1]),2) + math.pow(float(dif[2]),2)) if closestHit == None: closestHit = distToCam closestObj = [state, hit, fnMesh, facePtr, triPtr] elif distToCam < closestHit: closestHit = distToCam closestObj = [state, hit, fnMesh, facePtr, triPtr] if closestObj is not None: state, hit, fnMesh, facePtr, triPtr = closestObj mHit = om.MPoint(hit) # get smooth normal normal = om.MVector() fnMesh.getClosestNormal(mHit, normal, om.MSpace.kWorld, None) tangent = utils().crossProduct(normal,self.worldUp) upAxis = utils().crossProduct(normal,tangent) # define transformation matrix matrix = [tangent.x,tangent.y,tangent.z,0,upAxis.x,upAxis.y,upAxis.z,0,normal.x,normal.y,normal.z,0,hit.x,hit.y,hit.z,0] # apply matrix dist = om.MVector( (hit.x - self.prevHit.x),(hit.y - self.prevHit.y),(hit.z - self.prevHit.z) ) if utils().magnitude(dist) > self.step: if self.mod == 0: cmds.curve(self.loc,append=True,p=(hit.x,hit.y,hit.z)) else: hit = self.prevHit if self.mesh is True: v1 = cmds.pointPosition(self.loc + '.cv[0]',w=True) v2 = cmds.pointPosition(self.loc + '.cv[1]',w=True) v = om.MVector(v2[0] - v1[0],v2[1] - v1[1],v2[2] - v1[2]) v.normalize() cmds.setAttr(self.circle[1] + '.normalX',v.x) cmds.setAttr(self.circle[1] + '.normalY',v.y) cmds.setAttr(self.circle[1] + '.normalZ',v.z) if self.mod == 1: mag = utils().magnitude(dist) * self.bMult if dist.y < 0: mag = -mag currentValue = cmds.getAttr(self.circle[1] + '.radius') compVal = sorted((0.0001,currentValue + mag))[1] self.bRad = compVal cmds.setAttr(self.circle[1] + '.radius',compVal) if self.mod == 4: mag = utils().magnitude(dist) * self.bMult if dist.y < 0: mag = -mag currentValue = cmds.getAttr(self.extrude[1] + '.scale') compVal = sorted((0.0001,currentValue + mag))[1] self.taper = compVal cmds.setAttr(self.extrude[1] + '.scale',compVal) self.prevHit = hit # print cmds.timerX(st=self.timer) # refresh viewport currentView.refresh(False,True,False)
def onPress(self): """ execute on press """ # modifier self.mod = cmds.getModifiers() # button self.btn = cmds.draggerContext(self.dragCtx, query=True, button=True) # timer self.timer = cmds.timerX() initPos = cmds.draggerContext(self.dragCtx, query=True, anchorPoint=True) # camera far clip currentView = omui.M3dView().active3dView() camDP = om.MDagPath() currentView.getCamera(camDP) camFn = om.MFnCamera(camDP) farclip = camFn.farClippingPlane() # screen to world conversion worldPos, worldDir = utils().viewToWorld(initPos[0],initPos[1]) if self.btn is not 2: closestHit = None closestObj = None for obj in self.targetObj: if cmds.objExists(obj): state, hit, fnMesh, facePtr, triPtr = utils().intersect(obj, worldPos, worldDir, farclip) if state is True: dif = [hit.x - worldPos[0],hit.y - worldPos[1],hit.z - worldPos[2]] distToCam = math.sqrt(math.pow(float(dif[0]),2) + math.pow(float(dif[1]),2) + math.pow(float(dif[2]),2)) if closestHit == None: closestHit = distToCam closestObj = [state, hit, fnMesh, facePtr, triPtr] elif distToCam < closestHit: closestHit = distToCam closestObj = [state, hit, fnMesh, facePtr, triPtr] else: self.targetObj.remove(obj) if closestObj is not None: state, hit, fnMesh, facePtr, triPtr = closestObj mHit = om.MPoint(hit) # get smooth normal normal = om.MVector() fnMesh.getClosestNormal(mHit, normal, om.MSpace.kWorld, None) # get smooth normal normal = om.MVector() fnMesh.getClosestNormal(mHit, normal, om.MSpace.kWorld, None) tangent = utils().crossProduct(normal,self.worldUp) upAxis = utils().crossProduct(normal,tangent) # define transformation matrix matrix = [tangent.x,tangent.y,tangent.z,0,upAxis.x,upAxis.y,upAxis.z,0,normal.x,normal.y,normal.z,0,hit.x,hit.y,hit.z,0] # create object if self.mod == 0: self.loc = cmds.curve(p = (hit.x,hit.y,hit.z)) # cmds.toggle(self.loc, localAxis=True) # store values self.prevHit = hit print self.prevHit self.screenPoint = initPos self.angle = 0 # draw Mesh if self.mesh is True and self.mod == 0: self.circle = cmds.circle(center = (hit.x,hit.y,hit.z),radius = self.bRad,d=3) self.extrude = cmds.extrude(self.circle[0],self.loc,po=1, ch=True,rn=False,et=2,ucp=0,fpt=0,upn=0,rotation=0,scale=1,rsp=1) self.nbTes = cmds.listConnections(self.extrude[1] + '.outputSurface')[0] cmds.setAttr(self.nbTes + '.polygonType',1) cmds.setAttr(self.nbTes + '.format',2) cmds.setAttr(self.nbTes + '.polygonCount',200) cmds.setAttr(self.nbTes + '.uType',3) cmds.setAttr(self.nbTes + '.uNumber',1) cmds.setAttr(self.nbTes + '.vType',3) cmds.setAttr(self.nbTes + '.vNumber',1) cmds.setAttr(self.extrude[1] + '.scale',self.taper) if self.autoAdd is True and self.extrude[0] not in self.targetObj: self.targetObj.append(self.extrude[0]) # refresh viewport cmds.refresh(cv=True)
def autoRenderViewMinimize(state=None, renderView="renderViewWindow"): """ Overrides the renderView's restore command so that it directly minimizes again. This is especially useful when rendering with V-ray Framebuffer enabled, because on rendering it 'pops up' the default maya render view (which is extremely annoying). Enabling this autoRenderViewMinimize will directly minimize the render view window when the render starts. Default value for state is None. This means the value will depend on user input during the execution of the script. If the user holds any of the following keys the autoRenderViewMinimize will be disabled: Shift, Alt, Control. This makes it an easy to use shelf button script. :) Note: You should leave the render view window open, but minimized. Because Maya's render view code has been hard coded this to re-open and resize this is really the only viable way to hide it without breaking stuff. Until chaosgroup overrides the functionality - eg. hiding the render view when their renderer (or framebufffer) kicks in - this is a neat solution. Note: Another way might be to dock the renderView window to your interface and hide it. This way it will not pop up. But because Maya (auto-)resizes the top window if the view is too small when pressing the render button in the UI it will resize Maya's main window (because that is then the top window.) A reference to this method can be found here: http://polygonspixelsandpaint.tumblr.com/post/68136553566 :param state: The state to set the autoRenderViewMinimize to. A True value will open and minimize the render view and override the minimize/restore state functionality. A False value will make sure the functionality is removed. If None it will default to True, unless during the run of the script the user pressed (hold it to be sure) any of the following keys: - Shift - Alt - Control. :type state: bool or None :param renderView: The name of the renderView window object to act upon. The maya default renderView window object is called: "renderViewWindow". This is the default value. :type renderView: str :rtype: bool :return: The resulting state """ if state is None: # If state is None we allow the user to set the state by whether they have pressed a modifier button during execution. # If any modifier key is pressed when the script is running then the RenderView minimize override is disabled. (force removed) # So to disable the functionality run this script while holding: Shift, Alt and/or Control. Else it will enable # the functionality. state = not (mc.getModifiers()) print "Setting the override render view minimize to: {0}".format(state) if state: if not mc.window(renderView, q=1, exists=True): mc.RenderViewWindow() # RuntimeCommand (to force create the renderView) renderViewMinimize = lambda: mc.window(renderView, e=True, i=True) renderViewMinimize() # Minimize the renderView mc.window(renderView, e=True, restoreCommand=renderViewMinimize) # Override the renderView restore command else: if mc.window(renderView, q=1, exists=True): mc.deleteUI(renderView) mc.RenderViewWindow() return state