def doIt(self, args_list): args_data = OpenMaya.MArgDatabase(self.syntax(), args_list) if args_data.isFlagSet(LoadControlShapesCommand.FILEPATH_FLAG): self.filepath = args_data.flagArgumentString( LoadControlShapesCommand.FILEPATH_FLAG, 0) else: self.displayError("Must specify a filepath.") return selection = args_data.getObjectList() for i in xrange(selection.length()): try: dag_path = selection.getDagPath(i) except RuntimeError: continue if not (dag_path.hasFn(OpenMaya.MFn.kTransform) or dag_path.hasFn(OpenMaya.MFn.kNurbsCurve)): continue if not dag_path.node().hasFn(OpenMaya.MFn.kTransform): dag_path.pop() self.selection.append(dag_path.node()) self.redoIt()
def doIt(self, *args): # NOTE(fuzes): Here we only gather the data for the command and then call the reDoIt() method to do the rest of the job argDB = om2.MArgDatabase(self.syntax(), args[0]) if argDB.isFlagSet("-pn"): self._plugName = argDB.flagArgumentString("-pn", 0) if not self._plugName in _PER_VERTEX_ATTRIBUTE_NAMES: m_cmds.error("Invalid Plug Name") return else: m_cmds.error("plugName flag must be set") selList = argDB.getObjectList() mob = selList.getDependNode(0) self._nObjectMobHandle = om2.MObjectHandle(mob) if argDB.isFlagSet("-vw"): self._current_weights = om2.MDoubleArray() for i in xrange(argDB.numberOfFlagUses("-vw")): argList = argDB.getFlagArgumentList("-vw", i) self._current_weights.append(argList.asDouble(0)) else: m_cmds.error("vertexWeight flag must be set") self.redoIt()
def doIt(self, args_list): args_data = OpenMaya.MArgDatabase(self.syntax(), args_list) selection = args_data.getObjectList() for i in xrange(selection.length()): try: dag_path = selection.getDagPath(i) except RuntimeError: continue if not (dag_path.hasFn(OpenMaya.MFn.kTransform) or dag_path.hasFn(OpenMaya.MFn.kNurbsCurve)): continue if not dag_path.node().hasFn(OpenMaya.MFn.kTransform): dag_path.pop() self.selection.append(dag_path.node()) if len(self.selection) < 2: self.displayError("Must select at least two controls.") return self.redoIt()
def doIt(self, arg_list): try: arg_db = om.MArgDatabase(self.syntax(), arg_list) except: self.displayError("Error parsing arguments") raise selection_list = arg_db.getObjectList() self.selected_obj = selection_list.getDependNode(0) if self.selected_obj.apiType() != om.MFn.kTransform: raise RuntimeError("This command requires a transform node") self.edit = arg_db.isEdit self.query = arg_db.isQuery self.translate = arg_db.isFlagSet(SimpleCmd.TRANSLATE_FLAG[0]) if self.translate: transform_fn = om.MFnTransform(self.selected_obj) self.orig_translation = transform_fn.translation( om.MSpace.kTransform) if self.edit: self.new_translation = [ arg_db.flagArgumentDouble(SimpleCmd.TRANSLATE_FLAG[0], 0), arg_db.flagArgumentDouble(SimpleCmd.TRANSLATE_FLAG[0], 1), arg_db.flagArgumentDouble(SimpleCmd.TRANSLATE_FLAG[0], 2) ] self.undoable = True self.version = arg_db.isFlagSet(SimpleCmd.VERSION_FLAG[0]) self.redoIt()
def doIt(self, args): try: argdb = om2.MArgDatabase(self.syntax(), args) except RuntimeError: om2.MGlobal.displayError( 'Error while parsing arguments:\n#\t# If passing in list of nodes, also check that node names exist in scene.' ) return False if argdb.isFlagSet("scale"): self.matchScale = argdb.flagArgumentBool("scale", 0) if argdb.isFlagSet("rotation"): self.matchRotation = argdb.flagArgumentBool("rotation", 0) if argdb.isFlagSet("translation"): self.matchTranslation = argdb.flagArgumentBool("translation", 0) print self.matchTranslation self.selList.copy(argdb.getObjectList()) if self.selList.length() < 2: om2.MGlobal.displayWarning( 'etMatchXfo: You must select target objects, then a source object.' ) return False self.redoIt()
def doIt(self, args): # Parse the arguments. argData = OpenMaya.MArgDatabase(self.syntax(), args) try: self.cmdArg = argData.commandArgumentString(0) except RuntimeError: pass if argData.isFlagSet(kVerboseFlag): self.verbose = argData.flagArgumentBool(kVerboseFlag, 0) if argData.isFlagSet(kMenuFlag): self.menu = argData.flagArgumentBool(kMenuFlag, 0) logger = setupLogger(self.verbose) self.mw = Gui(logger, CMD_DICT, self.menu, getMayaWindow()) self.mw.show() pos = Qt.QtGui.QCursor.pos() self.mw.move( pos.x() - (self.mw.width() / 2), pos.y() - (self.mw.height() / 2)) self.mw.raise_() self.mw.activateWindow()
def _parse_args(self, args): args_data = OpenMaya.MArgDatabase(self.syntax(), args) if args_data.isFlagSet('sc'): self._skin_cluster_arg = args_data.flagArgumentString('sc', 0) if args_data.isFlagSet('i'): self._index_arg = args_data.flagArgumentString('i', 0) if args_data.isFlagSet('w'): self._weight_arg = args_data.flagArgumentString('w', 0)
def doIt(self, args): # Use an MArgDatabase to parse the command invocation. # try: argDb = OpenMaya.MArgDatabase(self.syntax(), args) except RuntimeError as ex: raise RunTimeError(kParsingError % str(ex)) # add and deselect are non-query mode flags add = argDb.isFlagSet(RenderSetupSelectCmd.kAddFlag) deselect = argDb.isFlagSet(RenderSetupSelectCmd.kDeselectFlag) if argDb.isQuery and (add or deselect): raise RuntimeError(kAddAndDeselectEditOnly) # renderLayers, collections, and overrides are query mode flags renderLayers = argDb.isFlagSet(RenderSetupSelectCmd.kRenderLayersFlag) collections = argDb.isFlagSet(RenderSetupSelectCmd.kCollectionsFlag) overrides = argDb.isFlagSet(RenderSetupSelectCmd.kOverridesFlag) if not argDb.isQuery and (renderLayers or collections or overrides): raise RuntimeError(kNotEditableFlags) if argDb.isQuery: results = getSelection(renderLayers, collections, overrides) self.setResult(results) else: selectionModel = getSelectionModel() if selectionModel is None: if argDb.numberOfFlagsUsed: raise RuntimeError(kSelectionEditFailed) # Can't have both add and deselect at the same time if add and deselect: raise RuntimeError(kAddAndDeselectNoTogether) # Find the items that we are selecting and add them to our item selection from PySide2.QtCore import QItemSelection, QItemSelectionModel import maya.app.renderSetup.views.proxy.renderSetup as renderSetupProxy itemsToSelect = argDb.getObjectStrings() selection = QItemSelection() models = itertools.ifilter(None, (utils.nameToUserNode(item) for item in itemsToSelect)) proxies = [renderSetupProxy.getProxy(model) for model in models] for proxy in proxies: selection.select(proxy.index(), proxy.index()) if not deselect: treeview = getRenderSetupView() for proxy in proxies: parent = proxy.parent() while parent: treeview.setExpanded(parent.index(), True) parent = parent.parent() # Use the appropriate selection method selectMode = QItemSelectionModel.Select if add else QItemSelectionModel.Deselect if deselect else QItemSelectionModel.ClearAndSelect selectionModel.select(selection, selectMode)
def doIt(self, args): sel = om2.MGlobal.getActiveSelectionList() self.iter_components = om2.MItSelectionList(sel) argDb = om2.MArgDatabase(self.syntax(), args) if argDb.isFlagSet(vertMatch.mirrorFlag): self.mirror = argDb.flagArgumentBool(vertMatch.mirrorFlag, 0) self.redoIt()
def doIt(self, args): arg_data = om.MArgDatabase(syntaxCreator(), args) if arg_data.isFlagSet(self.doIt_label_long) and arg_data.isFlagSet(self.undoIt_label_long): doIt_id = long(arg_data.flagArgumentString(self.doIt_label_long, 0)) undoIt_id = long(arg_data.flagArgumentString(self.undoIt_label_long, 0)) self.doIt_def = ctypes.cast(doIt_id, ctypes.py_object).value self.undoIt_def = ctypes.cast(undoIt_id, ctypes.py_object).value self.redoIt() else: om.MGlobal.displayError('No doItComm and undoItComm') return
def doIt(self, args): argData = om.MArgDatabase(self.syntax(), args) # check if a arg is provided if argData.isFlagSet(HelloWorldCmd.kNameFlag): name = argData.flagArgumentString(HelloWorldCmd.kNameFlag, 0) else: name = 'world' om.MGlobal.displayInfo("Hello, %s!" % name)
def parseArguments(self, args): if len(args) != 2: raise TypeError("pulseMoveStep() takes exactly 2 arguments " "({0} given)".format(len(args))) try: argdb = om.MArgDatabase(self.syntax(), args) except RuntimeError: om.MGlobal.displayError('Error while parsing arguments') raise self.sourcePath = argdb.commandArgumentString(0) self.targetPath = argdb.commandArgumentString(1)
def doIt(self, args_list): args_data = OpenMaya.MArgDatabase(self.syntax(), args_list) if args_data.isFlagSet(CopyControlShapesCommand.MIRROR_ACROSS_FLAG): self.mirror_across = args_data.flagArgumentString( CopyControlShapesCommand.MIRROR_ACROSS_FLAG, 0).upper() if not self.mirror_across in ['XY', 'YZ', 'XZ']: err_msg = ( "The {}/{} flag expects a value of 'XY', 'YZ', or 'XZ'." ).format(CopyControlShapesCommand.MIRROR_ACROSS_FLAG, CopyControlShapesCommand.MIRROR_ACROSS_LONG) self.displayError(err_msg) return if self.mirror_across == 'XY': self.mirrorMatrix = OpenMaya.MMatrix( [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1]) elif self.mirror_across == 'YZ': self.mirrorMatrix = OpenMaya.MMatrix( [-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]) elif self.mirror_across == 'XZ': self.mirrorMatrix = OpenMaya.MMatrix( [1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]) self.world_space = args_data.isFlagSet( CopyControlShapesCommand.WORLD_FLAG) selection = args_data.getObjectList() for i in xrange(selection.length()): try: dag_path = selection.getDagPath(i) except RuntimeError: continue if not (dag_path.hasFn(OpenMaya.MFn.kTransform) or dag_path.hasFn(OpenMaya.MFn.kNurbsCurve)): continue if not dag_path.node().hasFn(OpenMaya.MFn.kTransform): dag_path.pop() self.selection.append(dag_path.node()) if len(self.selection) < 2: self.displayError("Must select at least two controls.") return self.redoIt()
def doIt(self, argList): try: argData = om.MArgDatabase(self.syntax(), argList) except RuntimeError: om.MGlobal.displayError('Error while parsing arguments:\n#\t#') raise self.selection = argData.getObjectList().getSelectionStrings() if argData.isFlagSet(self.kFlagCopy): self.copy = argData.flagArgumentDouble(self.kFlagCopy, 0) else: self.copy = 1 if argData.isFlagSet(self.kFlagMode): self.mode = argData.flagArgumentString(self.kFlagMode, 0) if not self.mode in ["insert", "merge"]: om.MGlobal.displayError( 'Error while parsing arguments: -mode accepts only "insert" or "merge"' ) return else: self.mode = "insert" if argData.isFlagSet(self.kFlagFile): self.file = argData.flagArgumentString(self.kFlagFile, 0) if not type(self.file) is types.UnicodeType: om.MGlobal.displayError( 'Error while parsing arguments: -file accepts only string value' ) return else: om.MGlobal.displayError( 'Error while parsing arguments: -f or -file required') return if argData.isFlagSet(self.kFlagTime): try: self.time = argData.flagArgumentDouble(self.kFlagTime, 0) except: om.MGlobal.displayError( 'Error while parsing arguments: -time accepts only numeric value' ) return else: om.MGlobal.displayError( 'Error while parsing arguments: -t or -time required') return print self.selection, self.copy, self.file, self.time, self.mode self.option = "targetTime=3;pictures=0;connect=0;option=%s;" % self.mode self.option += "time=%d;copies=%d;" % (self.time, self.copy) self.namespace = self.file.split("\\")[-1].split(".")[0] self.redoIt()
def doIt(self, args): # Use an MArgDatabase to parse the command invocation. # argDb = OpenMaya.MArgDatabase(self.syntax(), args) # Will raise an exception and output its own message if parameters are invalid self.clearResult() rsm = renderSetupModel.instance() slist=argDb.getObjectList() for i in range( slist.length() ): dependNode = OpenMaya.MFnDependencyNode( slist.getDependNode(i) ) layer = rsm.getRenderLayer( dependNode.name() ) # Will raise an exception with an appropriate message if dependNode is not a valid renderSetupLayer self.appendToResult( layer._getLegacyNodeName() )
def doIt(self, args): # To parse the arguments, we pass them to the MArgDatabase and use the MPxCommands built in syntax method to resolve it argData = om.MArgDatabase(self.syntax(), args) # First we need to check if a flag has been provided if argData.isFlagSet(HelloWorldCmd.kNameFlag): # Then we get its value. # THe 0 tells us which index to get in the event that multiples of the flag have been provided. # Since we only have one, just bother with the first one name = argData.flagArgumentString(HelloWorldCmd.kNameFlag, 0) else: # If nothing is provided default to world name = 'World' om.MGlobal.displayInfo("Hello, %s!" % name)
def doIt(self, args): # Parse the arguments. argData = OpenMaya.MArgDatabase(self.syntax(), args) if argData.isFlagSet(kVerboseFlag): self.verbose = argData.flagArgumentBool(kVerboseFlag, 0) self.mw = Gui(getMayaWindow()) self.mw.show() pos = QtGui.QCursor.pos() self.mw.move(pos.x() - (self.mw.width() / 2), pos.y() - (self.mw.height() / 2)) self.mw.raise_() self.mw.activateWindow()
def doIt(self, args): try: arguments = om.MArgDatabase(self.syntax(), args) except RuntimeError: om.MGlobal.displayError(( 'Error while parsing arguments:' ' If passing in list of nodes, also check that node names exist in scene.' )) raise selection = arguments.getObjectList() if arguments.isFlagSet(FgAverageComponents_cmd.axisFlag): axis = arguments.flagArgumentString( FgAverageComponents_cmd.axisFlag, 0) else: axis = 'x' mdl.move_components_to_axis(selection.getSelectionStrings(), axis=axis)
def doIt(self, args): # Use an MArgDatabase to parse the command invocation. # try: argDb = OpenMaya.MArgDatabase(self.syntax(), args) except RuntimeError as e: errorMsg = maya.stringTable['y_modelCmds.kRenderSetupCmdParsingError' ] errorMsg += e.message OpenMaya.MGlobal.displayError(errorMsg) raise RuntimeError(errorMsg) # For now we only support -query -renderLayers if not argDb.isQuery or not argDb.isFlagSet(RenderSetupCmd.kRenderLayersFlag): errorMsg = maya.stringTable['y_modelCmds.kRenderSetupCmdInvalidUsage' ] OpenMaya.MGlobal.displayError(errorMsg) raise RuntimeError(errorMsg) rsm = renderSetupModel.instance() self.setResult([rl.name() for rl in rsm.getRenderLayers()])
def doIt(self, args_list): args_data = OpenMaya.MArgDatabase(self.syntax(), args_list) if args_data.isFlagSet(SaveControlShapesCommand.FILEPATH_FLAG): self.filepath = args_data.flagArgumentString( SaveControlShapesCommand.FILEPATH_FLAG, 0) else: self.displayError("Must specify a filepath.") return if args_data.isFlagSet(SaveControlShapesCommand.PRETTY_FLAG): self.indent = 4 else: self.indent = None selection = args_data.getObjectList() for i in xrange(selection.length()): try: dag_path = selection.getDagPath(i) except RuntimeError: continue if dag_path.hasFn(OpenMaya.MFn.kTransform): for shape in iter_shapes(dag_path.node()): if shape.hasFn(OpenMaya.MFn.kNurbsCurve): break else: continue elif not dag_path.hasFn(OpenMaya.MFn.kNurbsCurve): continue if not dag_path.node().hasFn(OpenMaya.MFn.kTransform): dag_path.pop() self.selection.append(dag_path.node()) if not self.selection: self.displayError("Must select at least one control.") return self.redoIt()
def parse_args(self, arg_list): """ Extract the argument data and pass it as 2 Strings. Args: arg_list ([MArgList]): Maya Object containing all the data given to the command. Returns: [String]: Return 2 Strings, the Source and Destination Node. """ try: arg_parse = api2.MArgDatabase(self.syntax(), arg_list) except RuntimeError as re: re.message = "Wrong arguments given to %s.\nSignature: %s(Str(srcNode), Str(dstNode))" % ( self.COMMAND_NAME, self.COMMAND_NAME) self.runtimeErr(re) return None # -raises unexpected Failure when raising the error srcNode_str = arg_parse.commandArgumentString(0) dstNode_str = arg_parse.commandArgumentString(1) return srcNode_str, dstNode_str
def doIt(self, *args): # NOTE(fuzes): Here we only gather the data for the command argDB = om2.MArgDatabase(self.syntax(), args[0]) if argDB.isFlagSet("-pn"): plugName = argDB.flagArgumentString("-pn", 0) if not plugName in _PER_VERTEX_ATTRIBUTE_NAMES: m_cmds.error("Invalid Plug Name") return else: m_cmds.error("plugName flag must be set") selList = argDB.getObjectList() mob = selList.getDependNode(0) nMob = getNObjectMobFromMob(mob) if nMob.isNull(): m_cmds.error("Selection has no relationship with nObjects") return mfn_dep_nCloth = om2.MFnDependencyNode(nMob) plug = mfn_dep_nCloth.findPlug(plugName, False) dataHandle = plug.asMDataHandle() data = dataHandle.data() isDataNull = data.isNull() result = om2.MDoubleArray() if isDataNull: self.clearResult() self.setResult(result) else: doubleArrayData = om2.MFnDoubleArrayData(data) result = doubleArrayData.array() self.clearResult() self.setResult(result)
def doIt(self, argList): try: argData = om.MArgDatabase(self.syntax(), argList) except RuntimeError: om.MGlobal.displayError('Error while parsing arguments:\n#\t#') raise if argData.isFlagSet(self.kFlagFile): self.file = argData.flagArgumentString(self.kFlagFile, 0) if not type(self.file) is types.UnicodeType: om.MGlobal.displayError( 'Error while parsing arguments: -file accepts only string value' ) return else: om.MGlobal.displayError( 'Error while parsing arguments: -f or -file required') return if argData.isFlagSet(self.kFlagStartTime): try: self.startTime = argData.flagArgumentDouble( self.kFlagStartTime, 0) except: om.MGlobal.displayError( 'Error while parsing arguments: -startTime accepts only numeric value' ) return else: om.MGlobal.displayError( 'Error while parsing arguments: -st or -startTime required') return if argData.isFlagSet(self.kFlagEndTime): try: self.endTime = argData.flagArgumentDouble(self.kFlagEndTime, 0) except: om.MGlobal.displayError( 'Error while parsing arguments: -endTime accepts only numeric value' ) return else: om.MGlobal.displayError( 'Error while parsing arguments: -et or -endTime required') return print self.startTime, self.endTime, self.file opt = "precision=8;intValue=17;nodeNames=1;verboseUnits=0;whichRange=2;" opt += "range=%d:%d;" % (self.startTime, self.endTime) opt += "options=curve;hierarchy=below;controlPoints=0;shapes=0;helpPictures=0;useChannelBox=0;" opt += "copyKeyCmd=-animation objects " opt += "-time >%d:%d> -float >%d:%d> " % (self.startTime, self.endTime, self.startTime, self.endTime) opt += "-option curve -hierarchy below -controlPoints 0 -shape 0 " cmds.file(self.file, type="animExport", options=opt, force=True, es=True, pr=True)
def parseArguments(self, args): argData=om.MArgDatabase(self.syntax(),args) if argData.isFlagSet('-mu'): self.u_parameter = argData.flagArgumentDouble( '-mu', 0 ) if argData.isFlagSet('-mmn'): self.mesh_name = argData.flagArgumentString( '-mmn', 0 ) if argData.isFlagSet('-mbn'): self.joint_name = argData.flagArgumentString( '-mbn', 0 ) if argData.isFlagSet('-md'): self.division = argData.flagArgumentInt( '-md', 0 ) # WHEN NO MESH IS SPECIFIED IN THE COMMAND, GET THE FIRST SELECTED MESH FROM THE SELECTION LIST: if (self.mesh_name == "") or (self.joint_name == ""): sList = om.MGlobal.getActiveSelectionList() iter=om.MItSelectionList (sList, om.MFn.kMesh) i=0 while( not iter.isDone()): # RETRIEVE THE MESH self.mesh_dagPath = iter.getDagPath() meshFn=om.MFnMesh(self.mesh_dagPath) name=meshFn.fullPathName().split('|') self.mesh_name=name[-1] i+=1 iter.next() if i==0: raise ValueError("No mesh or mesh transform specified!") elif i>1: raise ValueError("Multiple meshes or mesh transforms specified!") iter.reset() iter=om.MItSelectionList (sList, om.MFn.kJoint) i=0 while not iter.isDone(): #RETRIEVE THE JOINT self.Joint_dagPath = iter.getDagPath() jointFn=om.MFnDagNode(self.Joint_dagPath) name=jointFn.name() i+=1 iter.next() if i==0: raise ValueError("No Joint or Joint transform specified!") elif i>1: raise ValueError("Multiple Joints or Joint transforms specified!") # get dagpath from mesh's and joint's names else: try: selectionList = om.MGlobal.getSelectionListByName(self.mesh_name) except: raise else: self.mesh_dagPath = selectionList.getDagPath( 0 ) try: selectionList = om.MGlobal.getSelectionListByName(self.joint_name) except: raise else: self.Joint_dagPath = selectionList.getDagPath( 0 )
def doIt(self, args): # Use an MArgDatabase to Parse our command # try: argdb = om.MArgDatabase(self.syntax(), args) except RuntimeError: om.MGlobal.displayError( 'Error while parsing arguments:\n#\t# If passing in list of nodes, also check that node names exist in scene.' ) raise # SELECTION or LIST of Node Names # selList = argdb.getObjectList() # FORCE # force = argdb.isFlagSet(PyMetaDataCmd.forceFlag) # NAME # if argdb.isFlagSet(PyMetaDataCmd.nameFlag): name = argdb.flagArgumentString(PyMetaDataCmd.nameFlag, 0) else: name = 'ownerName' # VALUE # if argdb.isFlagSet(PyMetaDataCmd.valueFlag): value = argdb.flagArgumentString(PyMetaDataCmd.valueFlag, 0) else: if os.environ.has_key('USERNAME'): value = os.environ['USERNAME'] elif os.environ.has_key('USER'): value = os.environ['USER'] else: value = 'USERNAME' # Use an MDGModifier so we can undo this work # self.dgmod = om.MDGModifier() # Define a function to do most of the work # def addMetaData(dependNode, fnDN): # Check to see if the attribute already exists on the node # if fnDN.hasAttribute(name): if force: plug = om.MPlug(dependNode, fnDN.attribute(name)) self.dgmod.newPlugValueString(plug, value) self.dgmod.doIt() else: print('passing over "' + fnDN.name() + '": force flag not set to True') else: # Create a new attribute # fnAttr = om.MFnTypedAttribute() newAttr = fnAttr.create(name, name, om.MFnData.kString) # Now add the new attribute to the current dependency node, # using dgmod to facilitate undo # self.dgmod.addAttribute(dependNode, newAttr) self.dgmod.doIt() # Create a plug to set and retrieve value off the node. # plug = om.MPlug(dependNode, newAttr) # Set the value for the plug, using dgmod to facilitate undo # self.dgmod.newPlugValueString(plug, value) self.dgmod.doIt() # Iterate over all dependency nodes in list # add the meta-data attribute if it is not already there # for i in range(selList.length()): # Get the dependency node and create # a function set for it # try: dependNode = selList.getDependNode(i) fnDN = om.MFnDependencyNode(dependNode) except RuntimeError: om.MGlobal.displayWarning('item %d is not a depend node' % i) continue addMetaData(dependNode, fnDN)