def __init__( self ): self.ButtonIsStart = False self.ObjectPicked = None self.RotatePosition = MTVector( 0.0, 0.0, 0.0 ) self.RotateAroundSelected = -1 self.SelectedObjects = None self.ObjectsToRotate = None self.IgnoreSelectionChangeEvent = False self.CloseButtonPressed = False self.DummyNode = None self.CurrentContext = None self.BuildUI() self.OnRotateAroundCenterBBoxSelected( None ) self.OnSelectionChange() self.SelectionJob = cmds.scriptJob( event = ( "SelectionChanged", self.OnSelectionChange ), parent = self.Window ) self.DeleteJob = cmds.scriptJob( uiDeleted = ( self.Window, self.OnWindowClosed ) ) # se crea un nodo invisible que servira para obtener las rotaciones de mundo self.DummyNode = cmds.createNode( "transform", skipSelect = True ) # nuevo rotator para saber cuando se termina de girar self.CurrentContext = cmds.currentCtx() self.ManipRotate = cmds.manipRotateContext( mode = 1, postDragCommand = ( self.OnObjectRotated, "transform" ) )
def win(*args): '''Window used to update the mesh ''' #if any windows are open that deal with updating the mesh, close them winList=['atom_meshUpdateWin', 'keyMeshdirDialogWin'] for win in winList: if cmds.window(win, ex=True): cmds.deleteUI(win) #create the window cmds.window('atom_meshUpdateWin', title = 'Atom Mesh Update') cmds.columnLayout(co=['both',5],adj=True, rs=5) path = os.path.join(cmds.workspace(query=True, o=True), 'scenes/anim/template_rig/CharactersWork/SantaPup/RIG/mesh_update_info') button_state = True #Test if the mesh_update_folder is the current path, this will usually be false if os.path.exists(path) != True: print path path = cmds.workspace(query=True, o=True) button_state=False print 'mesh_update_info folder not found. Browse to folder to continue.' cmds.textFieldButtonGrp('atom_meshUpdatePath_tfbg', label='Path:', tx=path, buttonLabel='Set Path', ct3=['left','both','left'], co3=[0,0,5],cl3=['left', 'center', 'center'], ad3=2, cw3=[35,100,80], bc='from atom import atom_updateMesh_lib\natom_updateMesh_lib.dirDialog()') cmds.button('atom_meshUpdate_button',l='Update Mesh', c ='from atom import atom_updateMesh_lib\natom_updateMesh_lib.updateMeshCMD()', en=button_state ) cmds.scriptJob(runOnce=True,uid=['atom_meshUpdateWin', 'from atom import atom_updateMesh_lib\natom_updateMesh_lib.deleteDirDialog()']) cmds.showWindow('atom_meshUpdateWin')
def __cancelCallback(*pArgs): if cmds.window(axisParallelPlane.windowID, exists = True): cmds.deleteUI(axisParallelPlane.windowID) if (cmds.scriptJob(ex = axisParallelPlane.job)): cmds.scriptJob(kill = axisParallelPlane.job, force = 1) axisParallelPlane.job = -1
def flatten(averaged=True): """ Flattens selection by averaged normal. """ def flatten(component, script_job=False): if script_job: cmds.select(selected.cmdslist()) else: cmds.select(component.cmdslist()) center = list(component.bbox.center)[:3] origin = get_average_vert_normal(component.normals, component.indices) # Perform scale cmds.manipScaleContext('Scale', e=True, mode=6, alignAlong=origin) radians = cmds.manipScaleContext('Scale', q=True, orientAxes=True) t = [math.degrees(r) for r in radians] cmds.scale(0, 1, 1, r=True, oa=t, p=center) def script_job(): """ Get normal from script job selection and pass it to flatten. """ flatten(next(iter(mampy.complist())).to_vert(), True) selected = mampy.complist() if averaged: for comp in selected: flatten(comp.to_vert()) cmds.select(selected.cmdslist(), r=True) else: # Scale selection to given selection. cmds.scriptJob(event=['SelectionChanged', script_job], runOnce=True)
def newItemJob(self): # Reset the object creation handling job if(cmds.scriptJob(exists=self.newObjectJob)): cmds.scriptJob(kill=self.newObjectJob) self.newObjectJob = cmds.scriptJob(event=('DagObjectCreated', self.onNewObject)) # Store the current tool so we can change back to it when the user has finished painting self.currentContext = cmds.currentCtx()
def createWindow(self): self.log.debug("creating window "+self.windowName) if self.windowExists(self.windowName): raise Exception("window %s already opened" % self.windowName) if not self.useUserPrefSize: try: cmds.windowPref(self.windowName,remove=True) cmds.windowPref(self.windowName,width=self.defaultWidth,height=self.defaultHeight) except: pass cmds.window(self.windowName, title=self.windowTitle, maximizeButton=False, minimizeButton=False, width=self.defaultWidth, height=self.defaultHeight, sizeable=self.sizeable, menuBar=self.menuBar) cmds.scriptJob(uiDeleted=[self.windowName,self.onWindowDeleted]) HeadlessDataHost.HANDLE.addReference(self)
def buildGUI(self): if cmds.window(self.name, q=True, exists=True): cmds.deleteUI(self.name) cmds.window(self.name, title=self.title, sizeable=False, mxb=False, mnb=False, toolbox=False, w=100, h=30) cmds.columnLayout("mainLayout", adj=True, parent=self.name, co=("left", 5)) # Add onClose Event cmds.scriptJob(uiDeleted=(self.name, self.onClose)) # Help Menu cmds.menuBarLayout("menuBar") cmds.menu(label="Show Help", helpMenu =True, pmc=self.showHelp) # Import paths cmds.textFieldButtonGrp("tfbDBPath", label="Links: ", bl="Set Link Path", cw=(1,50), parent="mainLayout", bc=self.setDBPath) cmds.textFieldButtonGrp("tfbShaderPath", label="Shaders: ", bl="Set Shader Path", cw=(1,50), parent="mainLayout", bc=self.setShaderPath) cmds.checkBox("cbSelection", label="Use Selection", parent="mainLayout") cmds.checkBox("cbSubstring", label="Substring prefix", parent="mainLayout", value=True) cmds.textField("tfSubstring", parent="mainLayout", text="s100_char") cmds.separator(h=10, style="none", parent="mainLayout") # Buttons cmds.rowColumnLayout("buttonsLayout", numberOfColumns=2, parent="mainLayout") cmds.button("bExportLinks", label = "Export Links", w=200, h=30, parent="buttonsLayout", c=self.exportLinks) cmds.button("bImportShader", label="Link Shaders", w=200, h=30, parent="buttonsLayout", c=self.linkShaders) cmds.showWindow(self.name)
def __init__(self, parent = uiH.getMayaWindow(), *args ): if uiH.USEPYQT: super(base, self).__init__(parent) else: super(LighterHelperUI, self).__init__(parent) self.setupUi(self) #load arnold if it is not loaded self.loadArnold() self.setObjectName( 'ligther_Helper_WIN' ) self._makeConnections() #self._addAllAovs() #create an scriptjob thats update the UI on renderlayer change mc.scriptJob( e = ["renderLayerManagerChange", partial( self.updateLighterUI )], p = 'ligther_Helper_WIN' ) self.updateLighterUI() #set icons for toolbar self.actionSpot.setIcon(QtGui.QIcon(":/spotlight.png")) self.actionDirectional.setIcon(QtGui.QIcon(":/directionallight.png")) self.actionPoint.setIcon(QtGui.QIcon(":/pointlight.png")) self.actionAmbient.setIcon(QtGui.QIcon(":/ambientlight.png")) self.actionArea.setIcon(QtGui.QIcon(":/arealight.png")) self.actionVolume.setIcon(QtGui.QIcon(":/volumelight.png")) self.actionRenderGlobals.setIcon(QtGui.QIcon(":/renderGlobals.png")) self.actionRenderView.setIcon(QtGui.QIcon(":/render.png")) self.actionLookThrough.setIcon(QtGui.QIcon(":/fileTextureView.png")) #internal variables self.isolatedLights = [] #lights that are beign turn off when we want to isolate others! self.isolatedObjects = [] #objects that are beign turn off when we one to isolate others! uiH.loadSkin( self, 'QTDarkGreen' )
def setMode(self, onOff): utilMod.killScriptJobs("G.microTransformScriptJobs") if onOff: self.rotationOrientMode = cmds.manipRotateContext('Rotate', query=True, mode=True) cmds.manipRotateContext('Rotate', edit=True, mode=2)#gimbal #update values on turning on self.addMicroTransform() G.microTransformScriptJobs = [] # get the current selected object values G.microTransformScriptJobs.append(cmds.scriptJob(runOnce = False, killWithScene = False, event =('SelectionChanged', self.addMicroTransform ))) G.microTransformScriptJobs.append(cmds.scriptJob(runOnce = False, killWithScene = False, event =('timeChanged', self.updateValues ))) G.microTransformScriptJobs.append(cmds.scriptJob(runOnce = False, killWithScene = False, event =('Undo', self.updateValues ))) G.microTransformScriptJobs.append(cmds.scriptJob(runOnce = False, killWithScene = False, event =('Redo', self.updateValues ))) G.microTransformScriptJobs.append(cmds.scriptJob(runOnce = False, killWithScene = False, event =('DragRelease', self.release ))) #print "microTransform is ON." else: cmds.manipRotateContext('Rotate', edit=True, mode=self.rotationOrientMode) self.removeMicroTransform()
def _FILE_Save(s, todo, archive): path = s._FILE_Running() if path: if todo: def fileArchive(): # Begin the archive process realpath = os.path.realpath(path) if archive: archive(realpath) process = cmds.scriptJob(e=['SceneSaved', fileArchive], ro=True) try: message = """ <div>- This Scene was last saved on <em>%(time)s</em>.</div> <div>- Completing the task: <code>%(todo)s</code></div> <div>- The file <strong>has not been modified since.</strong></div><br> """ % {"time": time.ctime(), "todo": todo.label} with Popup(message): cmds.file(save=True) # Save the scene return True except RuntimeError as e: # If scene save was canceled or failed. Reset everything print "Warning: %s" % e if cmds.scriptJob(ex=process): cmds.scriptJob(kill=process) else: try: cmds.file(save=True) return True except RuntimeError as e: print "Warning: %s" % e else: # Nothing in the scene to save return True
def __init__(s): s.registerHooks() # Load our hooks if cmds.dockControl("TODO_WINDOW", ex=True): cmds.deleteUI("TODO_WINDOW") s.fireHook("app.end") print "Window exists. Closing and opening a new window." s.page = "" # Page we are on. s._refresh() # Initialize saved data s.fireHook("app.start") s.regex = {} # Compiled regexes title = "Todo" try: with open(os.path.join(os.path.dirname(__file__), "quotes.json"), "r") as f: # Motivation! title = random.choice(json.load(f)) except (IOError, ValueError): print "No inspirational quotes loaded." window = cmds.window(title=title, rtf=True) s.container = cmds.columnLayout(adj=True) s.wrapper = "" allowed_areas = ['right', 'left'] s.dock = cmds.dockControl("TODO_WINDOW", a='left', content=window, aa=allowed_areas, fl=True, l=title, fcc=s.moveDock, vcc=s.closeDock) s._buildTodo() if s.location == 'float': cmds.dockControl(s.dock, e=True, fl=True) elif s.location in allowed_areas: cmds.dockControl(s.dock, e=True, a=s.location, fl=False) cmds.scriptJob(e=["PostSceneRead", s._refresh], p=s.dock) cmds.scriptJob(e=["NewSceneOpened", s._refresh], p=s.dock)
def rigUpdate(self): #disable refresh until the rig update is complete cmds.refresh(su=True) rigNodeFound = False try: rigGuiNode = self.scene.sceneNodes["Rig"] rigNodeFound = True except KeyError: rigNodeFound = False if rigNodeFound: #kill all script jobs created by controllers to avoid #an update loop which the rig is updated for jobNum in self.scriptJobNumbers: if jobNum != globals.currentScriptJobNum: cmds.scriptJob(k=jobNum) self.scriptJobNumbers = [] rigGuiNode.updateVersion += 0.1 rootElem = self.recursiveGetXML(rigGuiNode) self.indent(rootElem) tree = xml.ElementTree(rootElem) file = open(self.updateXmlPath, 'w') tree.write(file) file.close() self.recursiveZeroOutControllers(rigGuiNode) if rigGuiNode.metaNodeName is not None and rigGuiNode.metaNodeName != "": self.rootNodeName = mel.eval("updateMetaDataManager -n \""+rigGuiNode.metaNodeName+"\";") else: self.rootNodeName = mel.eval("loadRig -p \""+self.updateXmlPath+"\";") cmds.select(cl=True) self.recursiveUpdateMetaNodes(rigGuiNode,self.rootNodeName) self.recursiveSetupScriptJobs(rigGuiNode) cmds.refresh(su=False)
def renderLayersSetup(self, layers) : """renderLayersSetup :param layers: :return: """ # add script job for renaming render layer #print '* renderLayersSetup' selector = self.winMain + '|f0|c0|r0|layer_selector' firstRun = True for layer in layers: if layer != 'defaultRenderLayer': # cmds.scriptJob( # nodeNameChanged=[layer, partial(self.renderLayerRenamed)], # parent=top, # replacePrevious=firstRun # ) cmds.scriptJob( nodeNameChanged=[ layer, 'import maya.OpenMaya; ' 'maya.cmds.evalDeferred(' ' "meArnoldRender.renderLayerRenamed()",' ' lowestPriority=True' ')' ], parent=selector, replacePrevious=firstRun ) firstRun = False
def __init__(s): with report.Report(): tracker = JointTracker() winName = "Orient_Joints" if cmds.window(winName, ex=True): cmds.deleteUI(winName) s.win = cmds.window(rtf=True, w=300, t="Orient Joints") cmds.columnLayout(adj=True) cmds.button( l="Attach Marker", h=50, c=Callback(tracker.addMarker), ann=""" Attach a Marker to the selected Joint. Rotate the marker into the desired joint rotation. """ ) cmds.button( l="Update Joints", h=50, c=Callback(tracker.orientJoints), ann=""" Rotate all joints that have markers to their respective rotations. """ ) cmds.showWindow(s.win) cmds.scriptJob(uid=[s.win, tracker.removeMarkers])
def main(): def create_filter(fn): regex = re.compile(fn, re.I) test = lambda p: regex.search(p) items.update_filter(test) with gui.Window() as w: with forms.NavForm() as nav: with forms.VerticalForm() as navbar: one = gui.Button() two = gui.Button() three = gui.Button() with forms.HeaderForm() as main: filter_field = QTextField() main_list = lists.VerticalList() items > bind() > main_list.collection items.bind.viewCount > bind() > three.bind.label items.bind.count > bind() > two.bind.label w.update_bindings() w.buffer = InputBuffer(w, create_filter) filter_field.textChanged += w.buffer.handle cmds.scriptJob(lj=True) return w
def register_event(self, event): """ Create the scriptJob for AttributeNotifier <event> """ attrib = "{0}.{1}".format(self, event.attribute) event_data = dict((k, v) for k, v in event.items() if not k.startswith("_")) handler = partial(AttributeChangeHandler.handle, uuid=self.uuid, attribute=event.attribute, handler=event.handler, data=event_data) ac_job = cmds.scriptJob(kws=1, ac=(attrib, handler)) delete_handler = partial(AttributeChangeHandler.reassign, attrib=event.attribute, uuid=self.uuid, job=ac_job) rn_job = cmds.scriptJob(kws=1, runOnce=True, nnc=(self, delete_handler)) _logger.info('listening on %s' % attrib) return ac_job, rn_job
def enableRitalin(enable = True): global RitalinEnabled global resetTumbleToolToCOI if enable == True: if RitalinEnabled == False: if (cmds.tumbleCtx ("tumbleContext", query = True, localTumble = true)) == 1: cmds.tumbleCtx ("tumbleContext", edit = True, localTumble = 0) resetTumbleToolToCOI = True else: resetTumbleToolToCOI = False cleanRitalinScriptJobs() #The dragRelease event is king, it always gets fired when the user presses the mouse button or moves the mouse with the button pressed - exactly what we need Job1 = cmds.scriptJob(runOnce = False, killWithScene = False, event =('DragRelease', "cmds.undoInfo (swf = False); setCamRotatePivots(); cmds.undoInfo (swf = True)")) RitalinScriptJobs.append(Job1) #Due to a bug in Maya we need to run the following event at least once to ensure that the DragRelease event gets triggered above. Otherwise it never kicks in :-( #Also, to prevent the undo/redo queue from getting overwritten we only do store selected components when there are no commands to redo, #which is only the case if the selction change was due to user-action rather than undo/redo... Job2 = cmds.scriptJob(runOnce = False, killWithScene = False, event =('SelectionChanged', "cmds.undoInfo (swf = False); setCamRotatePivots(); cmds.undoInfo (swf = True)")) #if cmds.undoInfo(q = true, redoName = True) == '': RitalinScriptJobs.append(Job2) Job3 = cmds.scriptJob(runOnce = False, killWithScene = False, event =('Undo', "cmds.undoInfo (swf = False); setCamRotatePivots(); cmds.undoInfo (swf = True)")) #if cmds.undoInfo(q = true, redoName = True) == '': RitalinScriptJobs.append(Job3) Job4 = cmds.scriptJob(runOnce = False, killWithScene = False, event =('Redo', "cmds.undoInfo (swf = False); setCamRotatePivots(); cmds.undoInfo (swf = True)")) #if cmds.undoInfo(q = true, redoName = True) == '': RitalinScriptJobs.append(Job4) setCamRotatePivots() if enable == False: #print ("Attempting to disable Ritalin - Deleting script Jobs") if resetTumbleToolToCOI == True: cmds.tumbleCtx ("tumbleContext", edit = True, localTumble = 1) cleanRitalinScriptJobs()
def deregisterScriptJobs(self): for i in self.scriptJobs: try: cmds.scriptJob(kill=i) except: pass self.scriptJobs = []
def __init__(self): self.win = cmds.window() # MyWin.windows = MyWin.windows + 1 MyWin.windows.append(self.win) # cmds.scriptJob( uiDeleted=[self.win, self.updateAttr ]) cmds.scriptJob( uiDeleted=[self.win, Callback( self.updateAttr2, self.win ) ])
def setupScriptJobs(self): if self.metaNodeName is not None and self.metaNodeName != "": self.controllerJobNums = [] controllerName = mel.eval('getMetaNodeConnection -n "'+self.metaNodeName+'" -c "controller";') self.controllerJobNums.append( cmds.scriptJob( ro=True, ac=[controllerName+'.translate', self.controllerTranslateUpdate] ) ) self.controllerJobNums.append( cmds.scriptJob( ro=True, ac=[controllerName+'.rotate', self.controllerRotateUpdate] ) ) self.controllerJobNums.append( cmds.scriptJob( ro=True, ac=[controllerName+'.scale', self.controllerScaleUpdate] ) ) return self.controllerJobNums
def updateSelectionChangedScriptJob(self): if self.ui.cb_selected.isChecked(): if self.selectionChangedScriptJob is None: self.selectionChangedScriptJob = cmds.scriptJob(e=["SelectionChanged", self.fillList]) else: if not self.selectionChangedScriptJob is None: cmds.scriptJob(kill=self.selectionChangedScriptJob) self.selectionChangedScriptJob = None
def closeDock(self, *loop): visible = cmds.dockControl(self.GUI['dock'], q=True, vis=True) if not visible and loop: cmds.scriptJob(ie=self.closeDock, p=self.GUI['dock'], ro=True) elif not visible: self.cleanUp() cmds.deleteUI(self.GUI['dock'], control=True) print "Window closed."
def main(): uvwin = MiUV() uvwin.createUI() cmds.scriptJob( event=["SelectionChanged", uvwin.selectUVshellBorder], parent=uvwin.windowName) mel.eval("""textureWindow -edit -displaySolidMap 1 polyTexturePlacementPanel1; txtWndUpdateEditor("polyTexturePlacementPanel1", "textureWindow", "null", 101);""")
def dpaf_postSceneReadJob(self): self.dpaf_separateLayerAdj() self.dpaf_setRendererName('current') self.dpaf_init_Resolution() # scenes switching engine cmds.scriptJob(e= ['PostSceneRead', self.dpaf_postSceneReadJob], ro= 1, p= 'cgru_afanasy_wnd')
def cleanRCSScriptJobs(): global RCSScriptJobs for job in RCSScriptJobs: try: cmds.scriptJob (kill = job) except: Warning ("Job " + str(job) + " could not be killed!") RCSScriptJobs = []
def toggleframePlaybackRange(onOff): utilMod.killScriptJobs("G.framePlaybackRangeScriptJobs") if onOff: G.framePlaybackRangeScriptJobs.append(cmds.scriptJob(runOnce = False, killWithScene = False, event =('ToolChanged', framePlaybackRangeFn)) ) G.framePlaybackRangeScriptJobs.append(cmds.scriptJob(runOnce = False, killWithScene = False, event =('SelectionChanged', framePlaybackRangeFn)) ) framePlaybackRangeFn()
def event(self): def allFunctionsDoIt( *args ): for function in uiData.updateFunctionList: function() cmds.scriptJob( e=['Undo', allFunctionsDoIt], p= self._winName ) cmds.scriptJob( e=['Redo', allFunctionsDoIt], p= self._winName )
def __init__(s, i18n, char, requestCharEdit, requestClipEdit, sendRunClip): s.i18n = i18n s.char = char s.requestClipEdit = requestClipEdit # We're asking to edit the clip s.sendRunClip = sendRunClip # User wants to place the clip s.clips = [] # Init clips! name = s.char.metadata.get("name", "CLips").title() if not char.data: # Does the character contain nothing? with warn: requestCharEdit(char, s.refresh) s.winName = "%sWin" % name if cmds.window(s.winName, ex=True): cmds.deleteUI(s.winName) s.window = cmds.window(s.winName, rtf=True, s=False, t="%s %s" % (name, i18n["clips.title"])) cmds.columnLayout(adj=True) cmds.rowLayout(nc=2, adj=2) # Open Row cmds.iconTextButton( ann=i18n["clips.editChar"], style="iconOnly", font="boldLabelFont", image="goToBindPose.png", h=50, w=50, bgc=[0.3,0.3,0.3], c=lambda: requestCharEdit(s.char, s.refresh) ) cmds.text( l="<h1>%s</h1>" % name, hl=True, h=50 ) cmds.setParent("..") # Close row cmds.columnLayout(adj=True) # Open Col cmds.button( l=i18n["clips.newClip"], h=50, c=lambda x: warn.run(requestClipEdit, s.char, s.refresh) ) cmds.setParent("..") # Close row cmds.floatSlider( min=50, max=200, v=100, dc=s.sizeClips, h=20 ) cmds.separator() cmds.frameLayout(l=i18n["clips.moreInfo"], font="tinyBoldLabelFont") cmds.scrollLayout(cr=True, bgc=[0.2,0.2,0.2], h=400) s.wrapper = cmds.gridLayout(w=400, cwh=[100, 120], cr=True, aec=False) cmds.setParent("..") # Close grid cmds.setParent("..") # Close Scroll cmds.separator() cmds.showWindow(s.window) cmds.scriptJob(uid=[s.window, s.cleanup], ro=True) s.refresh()
def loop(): while True: msg = recv() if not msg: # All done! log('No more messages!') return type_ = msg['type'] log('Dispatching %s to main event loop.', type_) cmds.scriptJob(idleEvent=lambda: safe_call(dispatch, msg), runOnce=True)
def activateValueJob(*args): if plug(): varInitiate() # cmds.scriptJob(ac=[plug(), "import webrImport as web\ncss = web.mod('curveSoftSelect')\ncss.jobValue()"]) cmds.scriptJob(ac=[plug(), "import %s as css\ncss.jobValue()" % (tempModName())]) message('Value script ON', maya=True) else: # message('nothing selected ____coudn\'t activate') pass
def initialize(self): ## Set Columns Width to match content: for column in range(self.treeWidget.columnCount()): self.treeWidget.setColumnWidth(column, 100) # self.treeWidget.resizeColumnToContents( column ) self.sliderRange = 25 self.treeWidget.setSelectionMode( QtWidgets.QAbstractItemView.ExtendedSelection) # monitor selection self.scriptJobID = cmds.scriptJob( event=["SelectionChanged", self.selectInScene], killWithScene=1) # update current selection self.selectInScene()
def create_script_job(self): ''' The script job is being stored into a variable so that it can be killed later when the user decided to close the UI. The script job is being killed so that the scene stays clean. ''' print "Creating Script Job" self.job_num = cmds.scriptJob( event=["SelectionChanged", self.modify_selected], parent=self.ui_elements["main_window"] )
def sceneCamSwitch(self): i = self.getCameras('scene') # check cached offset to see if it's beyond the limit if Cache.camSceneOffset > len(i) - 1: Cache.camSceneOffset = 0 # create window & script job JR_camera_shuffle.createWindow(i) # if Cache.cameraJob == 2000: ### this is the default number setup in Cache, not the most ideal way to work :S Cache.cameraJob = cmds.scriptJob(event=[ "SelectionChanged", "JR_camera_shuffle.currentCamera()" ]) #, protected=True) print Cache.cameraJob, ' this is the camera job #' # add to the offset Cache.camSceneOffset += 1
def load(self, name): """ Loads the specified attribute set Args: name (str): Name of the attribute set to import """ attrs = self[name]['attributes'] # check if substrate is available substrateAttr = "{0}.substrateTexture".format(mnpr_info.configNode) p = lib.Path(lib.getLibDir()).parent().child("textures") textures = os.listdir(p.path) if attrs[substrateAttr] not in textures: # check if substrates have been installed if len(textures) <= 2: result = cmds.confirmDialog(t="Substrates (papers/canvas) not found", m="The required substrate is not available.\nWould you like to download the MNPR substrates?", b=['Yes', 'Load anyway', 'Close'], icn="warning") if result == "Close": return elif result == "Yes": mnpr_runner.downloadSubstrates() return else: cmds.warning("Substrate texture not found, reverting to default substrate (style might not display correctly)") attrs[substrateAttr] = "rough_default_2k.jpg" else: cmds.warning("Substrate texture not found, reverting to default substrate (style might not display correctly)") attrs[substrateAttr] = "rough_default_2k.jpg" # check change of style first styleAttr = "{0}.style".format(mnpr_info.configNode) if styleAttr in attrs: style = attrs[styleAttr] if style != cmds.mnpr(style=True): lib.setAttr(mnpr_info.configNode, "style", style) func = functools.partial(self.loadStyle, attrs) return cmds.scriptJob(runOnce=True, event=["SelectionChanged", func]) else: # set attributes for attr in attrs: splitter = attr.split('.') lib.setAttr(splitter[0], splitter[1], attrs[attr]) else: # for legacy presets (we do not worry about styles here) for attr in attrs: splitter = attr.split('.') if "NPRConfig" in splitter[0]: splitter[0] = "mnprConfig" lib.setAttr(splitter[0], splitter[1], attrs[attr]) lib.printInfo("Attributes set successfully")
def createManipCtxDeferred(): deleteManipCtx() def prPanelCtxManipScriptJob(): if manipCtxNodeTypeChange(): global MANIP_NODE_TYPE setManipCommands( nodeType=MANIP_NODE_TYPE, preFunc=lambda: preCommand(**preCommandKwargs), postFunc=postCommand) prPanelCtxManipScriptJob() global MANIP_CTX_ID MANIP_CTX_ID = mc.scriptJob( event=["SelectionChanged", prPanelCtxManipScriptJob])
def addCBs(self, event=None): """Add the callbacks""" try: self.renderLayer.currentIndexChanged.connect(self.layerChanged) self.NodeNameMsgId = MNodeMessage.addNameChangedCallback( MObject(), self.nameChangedCB) self.newNodeCBMsgId = MDGMessage.addNodeAddedCallback( self.newNodeCB) self.delNodeCBMsgId = MDGMessage.addNodeRemovedCallback( self.delNodeCB) self.layerChangedJob = cmds.scriptJob( event=["renderLayerManagerChange", self.setCurrentLayer]) except: pass
def switch(self, onOff): utilMod.killScriptJobs("G.selectionCounterScriptJobs") cmds.iconTextButton("selectionCounterButton", edit=True, visible=False) if onOff: cmds.iconTextButton("selectionCounterButton", edit=True, visible=True) G.selectionCounterScriptJobs.append( cmds.scriptJob(runOnce=False, killWithScene=False, event=('SelectionChanged', self.update))) self.update()
def __init__(self, parent=maya_main_window()): super(TestDialog, self).__init__(parent) # Set the UI name so that it can be used as a parent for script jobs. # Script jobs are then deleted automatically when the UI is deleted. self.setObjectName("MyUniqueObjectName") self.setFixedSize(300, 160) self.create_widgets() self.create_layout() self.create_connections() # Use parent flag to parent the scriptJob to the UI job_number = cmds.scriptJob(event=["DagObjectCreated", "on_dag_object_created()"], parent="MyUniqueObjectName") print("Added job: {0}".format(job_number))
def setup_camera_callback(self): if not self.camera_cb.isChecked( ) and self.__sj_time_changed and self.__sj_selection_changed: mc.scriptJob(k=self.__sj_time_changed, f=True) mc.scriptJob(k=self.__sj_selection_changed, f=True) elif self.camera_cb.isChecked(): self.__sj_time_changed = mc.scriptJob( cu=True, kws=False, event=['timeChanged', self.refresh]) self.__sj_selection_changed = mc.scriptJob( cu=True, kws=False, event=['SelectionChanged', self.refresh])
def apply_viewport_updates(): """Create a script job that runs on timeline update. This will update all cache paths on yeti nodes to match the current frame every time the timeline is updated. The purpose of this is to allow yeti nodes that have been created on the fly to update in the viewport. """ disable_viewport_updates() # Create new script job _cmd = time.strftime('\n'.join([ '# PSYHIVE_YETI', 'import {} as yeti'.format(__name__), 'yeti.update_yeti_caches_to_cur_frame()', ])) _id = cmds.scriptJob(event=('timeChanged', _cmd), killWithScene=True) print 'CREATED SCRIPT JOB', _id
def __init__(self,parent=maya_main_window()): if omui.MQtUtil.findWindow(u'J_2dPaintTool'): cmds.deleteUI(u'J_2dPaintTool') #pram self.layerCount=0 self.scriptJobNumber0=0 self.scriptJobNumber1=0 self.eraseState=0 #pram super(J_mainWin, self).__init__(parent) self.setWindowFlags(QtCore.Qt.Window) self.J_mainWindow=J_2dPaintTool_UI() self.J_mainWindow.J_create2dPaintTool_UI(self) self.J_createSlots()#关联按钮 self.J_mainWindow.comboBox_cam.addItems(cmds.ls(type='camera'))#给列表添加摄像机 self.scriptJobNumber0=cmds.scriptJob( e=['SelectionChanged','J_2DTransferIns.J_changeState()'],parent='J_2dPaintTool') self.J_initListView()
def _codeAttrChanged(self): #print('AttrChanged: %s %r' % (self._node, self._ignoreCodeChange)) if self._ignoreCodeChange: self._ignoreCodeChange = False return self._refresh(self._node) # Copy Tab したアトリビュートエディタは、フレームの閉じるボタンで閉じれば消滅するが、 # ウィンドウ内の Close ボタンで閉じると vis=False 状態で残ってしまう。(maya 2017 win64 調べ) # New Scene したら削除されるようだが、それまでの間も不要な scriptJob が残り続けるのを避けるため、 # ジョブが呼ばれた際に vis をチェックして kill する。 # オブジェクト自体はウィンドウが削除されるまで残ってしまうが、まあ良いとする。 jid = self._jid_codeAttrChange if jid and not _isUIVisible(self.root): self._jid_codeAttrChange = None #print('KILL %d, %s' % (jid, self.root)) cmds.evalDeferred(lambda: cmds.scriptJob(k=jid, f=True))
def setNode(self, node): mnode = api2_mnode(node) if not self._mnode or self._mnode != mnode: if self._cid_attrChanged: #print('KILL APICB', self.root) _1_MNodeMessage.removeCallback(self._cid_attrChanged) self._mnode = mnode #print('NEW APICB', self.root) self._cid_attrChanged = _1_MNodeMessage.addAttributeChangedCallback( api1_mnode(node), self._apiAttrChanged) self._jid_nodeDeleted = cmds.scriptJob( p=self.path, rp=True, nd=(node, self._killApiattrChanged)) self._inputChangeProcNode = node self._inputChangedProc() return True return False
def __init__( self, selection='' ): #print ">> meCheckTexturePaths: Class created" self.selection = selection self.winMain = '' self.winReplace = '' self.listTextures = '' self.rootDir = cmds.workspace( q=True, rootDirectory=True ) self.strToFind = self.getDefaultStrValue( 'strToFind', '' ) self.strToReplace = self.getDefaultStrValue( 'strToReplace', '' ) self.fileTextures = [] self.mr_fileTextures = [] self.imagePlanes = [] self.ui=self.setupUI() self.jobOnDelete=cmds.scriptJob( uiDeleted=[ self.winMain , self.onDeleteMainWin ] )
def transfertSelectionToTarget_window(): """ Creates the 'Transfert Selection To Target' main window. """ cmds.windowPref(enableAll=False) if (cmds.window("transfertSelectionToTarget_window", exists=True)): cmds.deleteUI("transfertSelectionToTarget_window") cmds.window("transfertSelectionToTarget_window", title="Transfert Selection To Target", width=320) spacing = 5 cmds.columnLayout(adjustableColumn=True, rowSpacing=spacing) cmds.rowLayout(numberOfColumns=3, columnWidth3=(125, 150, 130), adjustableColumn=2, columnAlign=(2, "left"), columnAttach=[(1, "both", spacing), (2, "both", spacing), (3, "both", spacing)]) cmds.text(label="Target:") sources_textField = cmds.textField("target_textField") cmds.button("pickTarget_button", label="Pick Target!", command=pickTarget_button_OnClicked) cmds.setParent(topLevel=True) cmds.separator(style="single") cmds.button("transfertSelection_button", label="Transfert Selection!", command=transfertSelection_button_OnClicked) setUnsetContextHotkeys() scriptJob = cmds.scriptJob(uiDeleted=("transfertSelectionToTarget_window", setUnsetContextHotkeys), runOnce=True) cmds.showWindow("transfertSelectionToTarget_window") cmds.windowPref(enableAll=True)
def start(s): """ Get running! """ activity.Monitor.start(s) cmds.scriptJob(e=("SelectionChanged", s.checkin)) cmds.scriptJob(e=("timeChanged", s.checkin)) cmds.scriptJob(e=("ToolChanged", s.checkin)) s.idle_job = functools.partial( cmds.scriptJob, e=("idle", s.idle_callback), ro=True) # Lower priority than "idleEvent" s.sem = threading.BoundedSemaphore(1) s.idle = False threading.Thread(target=s.idle_loop).start() threading.Thread(target=s.busy_loop).start()
def detect_overrides(self): self.layer_overrides_dic = {} for layer in self.render_layers_in_order: #print ' ' #print 'layer = ',layer cmds.editRenderLayerGlobals(currentRenderLayer=layer) for attr in self.scriptJob_attrs: if attr in self.xforms: light_parent = cmds.listRelatives( self.current_chosen_light, parent=True) light_parent = light_parent[0] light_name_attr = light_parent + '.' + attr else: light_name_attr = self.current_chosen_light + '.' + attr value = cmds.getAttr(light_name_attr) for default_attr in self.default_layer_values_dic: if default_attr == attr: #print 'default_attr = ',default_attr #print cmds.editRenderLayerGlobals( query = True, currentRenderLayer = True) #print 'attr = ',attr attr_value = cmds.getAttr(light_name_attr) default_attr = self.default_layer_values_dic[attr] #print 'attr_value = ',attr_value #print 'default_attr = ',default_attr if attr_value != default_attr: #print 'attr_value = ',attr_value #print 'default_attr = ',default_attr self.layer_overrides_dic[attr] = layer print 'self.layer_overrides_dic = ', self.layer_overrides_dic cmds.editRenderLayerGlobals( currentRenderLayer=self.current_render_layer) for light in self.light_names: for attr in self.scriptJob_attrs: light_name_attr = light + '.' + attr if attr in self.xforms: light_parent = cmds.listRelatives(light, parent=True) light_parent = light_parent[0] light_name_attr = light_parent + '.' + attr else: light_name_attr = light + '.' + attr #print 'light_name_attr = ',light_name_attr self.myScriptJobID = cmds.scriptJob( p=window_name, attributeChange=[light_name_attr, self.populate_gui])
def editPivotHandle(self): qt_maya_window.installEventFilter(self.keypressFilter) #create transform self.pivotHandle = mc.group(em=True, name='Adjust_Pivot') mc.setAttr(self.pivotHandle + '.rotate', lock=True) mc.setAttr(self.pivotHandle + '.rx', keyable=False) mc.setAttr(self.pivotHandle + '.ry', keyable=False) mc.setAttr(self.pivotHandle + '.rz', keyable=False) mc.setAttr(self.pivotHandle + '.scale', lock=True) mc.setAttr(self.pivotHandle + '.sx', keyable=False) mc.setAttr(self.pivotHandle + '.sy', keyable=False) mc.setAttr(self.pivotHandle + '.sz', keyable=False) mc.setAttr(self.pivotHandle + '.visibility', lock=True, keyable=False) mc.setAttr(self.pivotHandle + '.displayHandle', True) self.pivotHandle = mc.parent(self.pivotHandle, self.node)[0] mc.addAttr(self.pivotHandle, ln='ml_pivot_handle', at='bool', keyable=False) #set initial position mc.setAttr(self.pivotHandle + '.translate', *mc.getAttr(self.node + '.rotatePivot')[0]) #lock it so you don't delete it or something. mc.lockNode(self.pivotHandle, lock=True) self.scriptJob = mc.scriptJob(event=['SelectionChanged', self.cleanup], runOnce=True) mc.setToolTo('Move') mc.inViewMessage( amg= 'After moving the pivot, press <hl>Return</hl> to bake or <hl>Esc</hl> to cancel.', pos='midCenterTop', fade=True, fadeStayTime=4000, dragKill=True)
def init(*args): """ Initilizes the mampref package. Init takes one or several paths """ global config # init config set_cwd_and_cfg_paths() config = Config() # add custom path for setting. if args: for i in args: cfg_paths.append(i) initialize_settings() job = cmds.scriptJob(e=['NewSceneOpened', initialize_settings]) config['CURRENT_MAYA_SESSION_SCRIPTJOB_NUMBER'] = job
def IK_FK_Switch(prefix, switchCtrl, pvCtrl, ikCtrl, skinJoints, fkCtrlList): """ IK_FK seamless switch by scriptJob and scriptNode :param prefix: str, prefix of the scriptNode :param switchCtrl: str, switchCtrl Name, usually IK_FK_Blend_Ctrl.C :param pvCtrl: str, pole vector Ctrl name. :param ikCtrl: str, IK Ctrl name :param skinJoints: list(str), list of the skin joints[shoulder, elbow, wrist] :param fkCtrlList: list(str), list of the FK Ctrl[FK_shoulder, FK_elbow, FK_wrist] :return: None """ codeStr = ''' import maya.cmds as cmds def switch(): switchCtrl = '{0}' pvCtrl = '{1}' ikCtrl = '{2}' skinJoints = {3} fkCtrlList = {4} objAttr = switchCtrl + '.Mode' objTy = switchCtrl + '.ty' # FK 2 IK if cmds.getAttr(objAttr) == 0: cmds.matchTransform(pvCtrl, skinJoints[1], pos=1, rot=0) cmds.matchTransform(ikCtrl, skinJoints[-1], pos=1, rot=1) cmds.setAttr(objTy, 1) # IK 2 FK elif cmds.getAttr(objAttr) == 1: for i in xrange(len(skinJoints)): cmds.matchTransform(fkCtrlList[i], skinJoints[i], pos=1, rot=1) cmds.setAttr(objTy, 0) cmds.scriptJob(attributeChange=['{5}' + '.Mode', switch]) '''.format(switchCtrl, pvCtrl, ikCtrl, skinJoints, fkCtrlList, switchCtrl) nodeName = cmds.scriptNode(st=2, bs=codeStr.replace("'''", "''"), n=prefix + 'Arm_IKFK_Switch_Node_#', stp='python') cmds.scriptNode(nodeName, executeBefore=1)
def switch(self, onOff): self.removeMessages() utilMod.killScriptJobs("G.animationCrashRecoveryScriptJobs") if onOff: #self.saveAllAnimationData(update=True) self.addAnimSceneMessages() self.addNodeMessages() self.addMdgMessages() G.animationCrashRecoveryScriptJobs.append(cmds.scriptJob(runOnce = False, killWithScene = False, event =('SelectionChanged', self.addNodeMessages ))) self.recommendSaving(True) #self.recommendSaving(False)#TMP else: G.deferredManager.removeFromQueue("ACR") self.setLed("off")
def closeCurrentInstance(cls): if cls._currentInstance is not None: if cls._currentInstance._mayaSelectionChangedJob is not None: cmds.scriptJob(kill=cls._currentInstance._mayaSelectionChangedJob) cls._currentInstance._mayaSelectionChangedJob = None if cls._currentInstance._mayaUndoJob is not None: cmds.scriptJob(kill=cls._currentInstance._mayaUndoJob) cls._currentInstance._mayaUndoJob = None if cls._currentInstance._mayaRedoJob is not None: cmds.scriptJob(kill=cls._currentInstance._mayaRedoJob) cls._currentInstance._mayaRedoJob = None cls._currentInstance.close() cls._currentInstance = None
def match_transform(mode=''): from . import sisidebar_sub pre_sel = cmds.ls(sl=True, l=True) selection = cmds.ls(sl=True, l=True, type='transform') if not selection: return sisidebar_sub.set_maching(nodes=selection, mode=mode ,pre_sel=pre_sel) msg = lang.Lang(en=u"<hl>Select Matching Object</hl>", ja=u"<hl>一致対象オブジェクトを選択してください</hl>") cmds.inViewMessage( amg=msg.output(), pos='midCenterTop', fade=True ) #cmds.select(cl=True) maching_tool = cmds.scriptCtx( title='Much Transform', totalSelectionSets=3, cumulativeLists=True, expandSelectionList=True, tct="edit", setNoSelectionPrompt='Select the object you want to matching transform.' ) cmds.setToolTo(maching_tool) jobNum = cmds.scriptJob(ro=True, e=('SelectionChanged', qt.Callback(sisidebar_sub.trs_matching)), protected=True) sisidebar_sub.get_matrix()
def checkUnits(self): #load custom units from cfg file cfgl.configLoader()[9] custom_sys_units = cfgl.configLoader()[9] cur_work_units = cmds.currentUnit(query=True) #check units change Job UnitsCheckerJob = cmds.scriptJob( runOnce=False, event=['linearUnitChanged', self.UnitChanger]) if custom_sys_units != cur_work_units: cmds.currentUnit(linear=custom_sys_units) if custom_sys_units == 'm': self.cboxSysUnits.setCurrentIndex(0) if custom_sys_units == 'cm': self.cboxSysUnits.setCurrentIndex(1) if custom_sys_units == 'mm': self.cboxSysUnits.setCurrentIndex(2) print "PolygonTools: Units changed to ", custom_sys_units self.lblInfo_01.setText("Units changed to " + custom_sys_units) else: if custom_sys_units == 'm': self.cboxSysUnits.setCurrentIndex(0) if custom_sys_units == 'cm': self.cboxSysUnits.setCurrentIndex(1) if custom_sys_units == 'mm': self.cboxSysUnits.setCurrentIndex(2) print "PolygonTools: Units is ", custom_sys_units self.lblInfo_01.setText("Units is " + custom_sys_units)
def __init__(self, parent=getMayaMainWindow()): #ensure not more than one at the same time try: pm.deleteUI('PickerUI') logger.debug("delete UI") except: logger.debug("no prev UI") deleteControl("PickerUIWorkspaceControl") super(pickerBaseUI, self).__init__(parent) self.setWindowTitle("Picker UI") #set title self.setMinimumWidth(400) #set width self.setObjectName("PickerUI") self.setAttribute(QtCore.Qt.WA_DeleteOnClose) #get rid of help button on window self.setWindowFlags(self.windowFlags() ^ QtCore.Qt.WindowContextHelpButtonHint) self.objects = { } #dictionary of objects in scene and what buttons they are connected to. They are separated by each tab. key- object name, value- array of buttons self.buttons = [] #array of references to buttons according to tab self.previousSelection = cmds.ls( sl=True) #array of last selection of objects in scene self.edit = True #start with showing edit tools self.IK_FK_Controller = IK_FKMatchingController.MatchingController( False, self) self.buildUI() #add to UI elements to window #update which buttons are selected/outlined each time the selection in scene is changed sj = cmds.scriptJob( event=["SelectionChanged", lambda: self.updateBtnSelect()], parent="PickerUI") self.show(dockable=True)
def connect_widgets(self): """ Connect widgets to functions """ # Grabbing all QWidgets self.horizontalSlider = self.findChild(QSlider, "horizontalSlider") self.checkbox = self.findChild(QCheckBox, "checkBox") self.pushbutton_add = self.findChild(QPushButton, "pushButton_add") self.pushbutton_snap = self.findChild(QPushButton, "pushButton_snap") self.pushbutton_delete = self.findChild(QPushButton, "pushButton_delete") self.listWidget = self.findChild(QListWidget, "listWidget") self.listWidget.clear() self.selectJob = cmds.scriptJob( e=["SelectionChanged", self.maya_item_changed], protected=True) self.horizontalSlider.valueChanged.connect(self.update_size) self.checkbox.released.connect(self.vis_locators) self.pushbutton_add.clicked.connect(self.add_locator) self.pushbutton_snap.clicked.connect(self.snap_values) self.pushbutton_delete.clicked.connect(self.delete_locators) self.listWidget.itemSelectionChanged.connect(self.list_item_changed) self.listWidget.itemClicked.connect(self.list_item_changed)
def IK_FK_Switch(prefix, switchCtrl, pvCtrl, ikCtrl, skinJoints, fkCtrlList): codeStr = ''' import maya.cmds as cmds def switch(): switchCtrl = '{0}' pvCtrl = '{1}' ikCtrl = '{2}' skinJoints = {3} fkCtrlList = {4} objAttr = switchCtrl + '.Mode' objTy = switchCtrl + '.ty' # FK 2 IK if cmds.getAttr(objAttr) == 0: cmds.matchTransform(pvCtrl, skinJoints[1], pos=1, rot=0) cmds.matchTransform(ikCtrl, skinJoints[-1], pos=1, rot=1) cmds.setAttr(objTy, 1) # IK 2 FK elif cmds.getAttr(objAttr) == 1: for i in xrange(len(skinJoints)): cmds.matchTransform(fkCtrlList[i], skinJoints[i], pos=1, rot=1) cmds.setAttr(objTy, 0) cmds.scriptJob(attributeChange=['{5}' + '.Mode', switch]) '''.format(switchCtrl, pvCtrl, ikCtrl, skinJoints, fkCtrlList, switchCtrl) cmds.scriptNode(st=2, bs=codeStr.replace("'''", "''"), n=prefix + 'Arm_IKFK_SwitchMode', stp='python')
def finishLayout(self): """This must be called to prepare the UI after all of the display rows and panels have been inserted. """ # Setup resize event filter. self.resizeEventFilter.install(self.parent, self.gui) # Setup focus event filter. self.focusEventFilter.install(self.panels) # Setup animation curve callback and time changed callback. callbackId = anim.MAnimMessage.addAnimKeyframeEditedCallback( self.animKeyframeCallback) self.callbacks.append(callbackId) jobId = cmds.scriptJob(event=("timeChanged", self.timeChangedCallback)) self.jobs.append(jobId) # Setup the rest of the UI and show it. self.searchField.textChanged.connect(self.search) self.gui.layout().setAlignment(Qt.AlignTop) self.relayout() self.gui.show()
def initScriptJobs(self): self.scriptJobIds.append( mc.scriptJob(event=("SelectModeChanged", catchJobException(self.actuTypeSelection)))) self.scriptJobIds.append( mc.scriptJob(event=("SelectTypeChanged", catchJobException(self.actuTypeSelection)))) self.scriptJobIds.append( mc.scriptJob(event=("SelectionChanged", catchJobException(self.actuSelection)))) self.scriptJobIds.append( mc.scriptJob(event=("ToolChanged", catchJobException(self.actuToolSettings)))) self.scriptJobIds.append( mc.scriptJob(event=("ModelPanelSetFocus", catchJobException(self.testJob)))) self.scriptJobIds.append( mc.scriptJob(event=("modelEditorChanged", catchJobException(self.initDisplay))))
def CreateScriptJob(): return cmds.scriptJob(e=("animLayerRefresh", UpdateSelectedAnimLayer), killWithScene=True, compressUndo=True)