def doIt(self, args):
        # gather the values from args
        argParser = om.MArgParser(self.syntax(), args)

        self.vertexId = argParser.commandArgumentInt(0)
        self.strength = argParser.commandArgumentDouble(1)
        meshName = argParser.commandArgumentString(2)
        skinClusterName = argParser.commandArgumentString(3)

        sel = om.MSelectionList()
        sel.add(meshName)
        sel.add(skinClusterName)
        self.shapeDag = sel.getDagPath(0)
        self.skinClusterMObject = sel.getDependNode(1)

        # create a single index component mfn and assign our given vertex id to it
        self.component = om.MFnSingleIndexedComponent().create(om.MFn.kMeshVertComponent)
        om.MFnSingleIndexedComponent(self.component).addElement(self.vertexId)

        # get the nighbors of this vertex
        itVert = om.MItMeshVertex(self.shapeDag, self.component)
        neighborVertList = itVert.getConnectedVertices()
        # TODO: with this iterator, we could also query if this vertex is a border vertex.
        # We could skip the redo function altogether if we wanted to pin border vertices

        self.numVertexNeighbors = len(neighborVertList)

        # Create a single indexed component mfn and assign the neighbor component array to it.
        self.neighborComponents = om.MFnSingleIndexedComponent().create(om.MFn.kMeshVertComponent)
        om.MFnSingleIndexedComponent(self.neighborComponents).addElements(neighborVertList)

        self.redoIt()
Esempio n. 2
0
    def pass_args(self, args):
        arg_data = om.MArgParser(self.syntax(), args)

        if arg_data.isFlagSet(self.restore_flag):
            self.restore_arg = arg_data.flagArgumentBool(self.restore_flag, 0)

        return arg_data.numberOfFlagsUsed
 def parseArguments(self, args):
     argData = om.MArgParser(self.syntax(), args)
     # Parse arguments
     self.curveMask = argData.commandArgumentString(0)
     self.sculptedMesh = argData.commandArgumentString(1)
     self.terrain = argData.commandArgumentString(2)
     # Parse flags
     if argData.isFlagSet("-n"):
         self.name = argData.flagArgumentString("-n", 0)
     if argData.isFlagSet("-name"):
         self.name = argData.flagArgumentString("-name", 0)
     if argData.isFlagSet("-ss"):
         self.sculptStrength = argData.flagArgumentFloat("-ss", 0)
     if argData.isFlagSet("-sculptStrength"):
         self.sculptStrength = argData.flagArgumentFloat(
             "-sculptStrength", 0)
     if argData.isFlagSet("-co"):
         self.curveOffset = argData.flagArgumentFloat("-co", 0)
     if argData.isFlagSet("-curveOffset"):
         self.curveOffset = argData.flagArgumentFloat("-curveOffset", 0)
     if argData.isFlagSet("-mpd"):
         self.maxProjection = argData.flagArgumentFloat("-mpd", 0)
     if argData.isFlagSet("-maxProjectionDistance"):
         self.maxProjection = argData.flagArgumentFloat(
             "-maxProjectionDistance", 0)
     if argData.isFlagSet("-rb"):
         self.rebuild = argData.flagArgumentBool("-rb", 0)
     if argData.isFlagSet("-rebuildCurve"):
         self.rebuild = argData.flagArgumentBool("-rebuildCurve", 0)
 def parseArguments(self, args):
     argData = om.MArgParser(self.syntax(), args)
     # If an argument exists, it will be the curve name and the mesh name
     try:
         name0 = argData.commandArgumentString(0)
         name1 = argData.commandArgumentString(1)
         selectionList = om.MGlobal.getSelectionListByName(name0)
         selectionList2 = om.MGlobal.getSelectionListByName(name1)
         selectionList.merge(selectionList2)
     except:
         selectionList = om.MGlobal.getActiveSelectionList()
     status = self.findFromSelection(selectionList)
     if status == False:
         return False
     # Parse the flags
     if argData.isFlagSet("-n"):
         self.name = argData.flagArgumentString("-n", 0)
     if argData.isFlagSet("-name"):
         self.name = argData.flagArgumentString("-name", 0)
     if argData.isFlagSet("-d"):
         self.depthValue = argData.flagArgumentFloat("-d", 0)
     if argData.isFlagSet("-depth"):
         self.depthValue = argData.flagArgumentFloat("-depth", 0)
     if argData.isFlagSet("-w"):
         self.widthValue = argData.flagArgumentFloat("-w", 0)
     if argData.isFlagSet("-width"):
         self.widthValue = argData.flagArgumentFloat("-width", 0)
     if argData.isFlagSet("-rb"):
         self.rebuild = argData.flagArgumentBool("-rb", 0)
     if argData.isFlagSet("-rebuild"):
         self.rebuild = argData.flagArgumentBool("-rebuild", 0)
     return True
Esempio n. 5
0
    def parseArguments(self, args):

        parsedArgs = []

        argData = om.MArgParser(self.syntax(), args)

        if argData.isFlagSet(kShortFlag1Name):
            flagValue = argData.flagArgumentInt(kShortFlag1Name, 0)
            parsedArgs.append(flagValue)

        if argData.isFlagSet(kShortFlag2Name):
            flagValue = argData.flagArgumentInt(kShortFlag2Name, 0)
            parsedArgs.append(flagValue)

        if argData.isFlagSet(kShortFlag3Name):
            flagValue = argData.flagArgumentInt(kShortFlag3Name, 0)
            parsedArgs.append(flagValue)

        if argData.isFlagSet(kShortFlag4Name):
            flagValue = argData.flagArgumentString(kShortFlag4Name, 0)
            parsedArgs.append(flagValue)

        if argData.isFlagSet(kShortFlag5Name):
            flagValue = argData.flagArgumentString(kShortFlag5Name, 0)
            parsedArgs.append(flagValue)

        if argData.isFlagSet(kShortFlag6Name):
            flagValue = argData.flagArgumentString(kShortFlag6Name, 0)
            parsedArgs.append(flagValue)

        if argData.isFlagSet(kShortFlag7Name):
            flagValue = argData.flagArgumentString(kShortFlag7Name, 0)
            parsedArgs.append(flagValue)

        return parsedArgs
Esempio n. 6
0
    def parseArguments(self, args):
        syntax = self.syntaxCreator()
        argData = om.MArgParser(syntax, args)

        if argData.isFlagSet(self.ShortFlag):
            self.FlagValue = argData.flagArgumentBool(self.ShortFlag, 0)
        if argData.isFlagSet(self.LongFlag):
            self.FlagValue = argData.flagArgumentBool(self.LongFlag, 0)
 def parseArguments(self, args):
     argData = om2.MArgParser(self.syntax(), args)
     
     if argData.isFlagSet( '-rb' ):
         flagValue = argData.flagArgumentBool( '-rb', 0)
     if argData.isFlagSet( '-iu' ):
         ignore_undo = argData.flagArgumentBool( '-iu', 0)
     return flagValue, ignore_undo
Esempio n. 8
0
    def parseArguments(self, args):
        '''
		The presence of this function is not enforced,
		but helps separate argument parsing code from other
		command code.
		'''

        ctlShortFlagName = '-cis'
        ctlLongFlagName = '-controllerIdentifierString'
        neutralShortFlagName = '-nf'
        neutralLongFlagName = '-neutralFrame'
        otherFaceIdsLong = '-otherFaceIds'
        otherFaceIdsShort = '-oid'
        rigOrEmulateShort = '-roe'
        rigOrEmulateLong = '-rigOrEmulate'
        meshNeutralNameShort = '-mNN'
        meshNeutralNameLong = '-meshNeutralName'
        automateShort = '-aut'
        automateLong = '-automate'

        # The following MArgParser object allows you to check if specific flags are set.
        argData = om.MArgParser(self.syntax(), args)
        print "argData: %s" % argData

        noFlag = True
        flagParams = []
        if argData.isFlagSet(ctlShortFlagName):
            # In this case, we print the passed flags's three parameters, indexed from 0 to 2.
            flagParams.append(argData.flagArgumentString(ctlShortFlagName, 0))
            noFlag = False
        if argData.isFlagSet(neutralLongFlagName):
            # In this case, we print the passed flags's three parameters, indexed from 0 to 2.
            flagParams.append(
                argData.flagArgumentDouble(neutralLongFlagName, 0))
            noFlag = False
        if argData.isFlagSet(otherFaceIdsLong):
            # In this case, we print the passed flags's three parameters, indexed from 0 to 2.
            flagParams.append(argData.flagArgumentString(otherFaceIdsShort, 0))
            noFlag = False
        if argData.isFlagSet(rigOrEmulateLong):
            # In this case, we print the passed flags's three parameters, indexed from 0 to 2.
            flagParams.append(argData.flagArgumentString(rigOrEmulateLong, 0))
            noFlag = False
        if argData.isFlagSet(meshNeutralNameLong):
            # In this case, we print the passed flags's three parameters, indexed from 0 to 2.
            flagParams.append(
                argData.flagArgumentString(meshNeutralNameLong, 0))
            noFlag = False
        if argData.isFlagSet(automateLong):
            # In this case, we print the passed flags's three parameters, indexed from 0 to 2.
            flagParams.append(argData.flagArgumentBool(automateLong, 0))
            noFlag = False
        if noFlag:
            sys.stderr.write(
                "ERROR: No Control Identifier String Provided with function call e.g -cis 'CTL'\n"
            )

        return flagParams
Esempio n. 9
0
    def parseArguments(self, args):
        syntax = self.syntaxCreator()
        argData = om.MArgParser(syntax, args)

        if argData.isFlagSet(self.ShortFlags[0]):
            self.FlagValues[0] = argData.flagArgumentBool(
                self.ShortFlags[0], 0)

        if argData.isFlagSet(self.ShortFlags[1]):
            self.FlagValues[1] = argData.flagArgumentBool(
                self.ShortFlags[1], 0)
Esempio n. 10
0
    def doIt(self, args):
        mArgParser = OpenMaya.MArgParser(self.syntax(), args)

        self.shape = mArgParser.flagArgumentString(self.shapeFlag, 0)

        self.preFormula = mArgParser.flagArgumentString(self.preFormulaFlag, 0)
        self.formula = mArgParser.flagArgumentString(self.formulaFlag, 0)

        self.isSecure = mArgParser.flagArgumentBool(self.isSecureFlag, 0)
        self.isVarN = mArgParser.flagArgumentBool(self.isVarNFlag, 0)

        self.redoIt()
Esempio n. 11
0
    def getArgParser(self, args):
        if len(args) != self.numArgs:
            raise TypeError(
                "{0.cmdName}() takes exactly {0.numArgs} arguments "
                "({1} given)".format(self, len(args)))

        try:
            argparser = om.MArgParser(self.syntax(), args)
        except RuntimeError:
            om.MGlobal.displayError('Error while parsing arguments')
            raise

        return argparser
Esempio n. 12
0
    def doIt(self, args):
        # gather the values from args
        argParser = om.MArgParser(self.syntax(), args)

        plugString = argParser.commandArgumentString(0)
        sel = om.MSelectionList()
        sel.add(plugString)
        self.plug = sel.getPlug(0)

        attributeMObj = self.plug.attribute()
        fnAttr = om.MFnAttribute(attributeMObj)
        if fnAttr.affectsWorldSpace:
            self.modifier = om.MDGModifier()
            # self.modifier = om.MDagModifier()
        else:
            self.modifier = om.MDGModifier()

        if not self.plug.source().isNull:
            self.displayError('{} is connected and cannot be set.'.format(
                self.plug.name()))
            return

        if argParser.isFlagSet('double') or argParser.isFlagSet('d'):
            self.plugType = 'double'
            self.value = argParser.flagArgumentDouble('d', 0)
            self.redoIt()

        elif argParser.isFlagSet('boolean') or argParser.isFlagSet('b'):
            self.plugType = 'boolean'
            self.value = argParser.flagArgumentBool('b', 0)
            self.redoIt()

        elif argParser.isFlagSet('string') or argParser.isFlagSet('s'):
            self.plugType = 'string'
            self.value = argParser.flagArgumentString('s', 0)
            self.redoIt()

        elif argParser.isFlagSet('float') or argParser.isFlagSet('f'):
            self.plugType = 'float'
            self.value = argParser.flagArgumentFloat('f', 0)
            self.redoIt()

        elif argParser.isFlagSet('int') or argParser.isFlagSet('i'):
            self.plugType = 'int'
            self.value = argParser.flagArgumentInt('i', 0)
            self.redoIt()

        elif argParser.isFlagSet('angle') or argParser.isFlagSet('a'):
            self.plugType = 'angle'
            self.value = argParser.flagArgumentMAngle('a', 0)
            self.redoIt()
    def doIt(self, args):
        argData = om.MArgParser(self.syntax(), args)
        
        if argData.isFlagSet('sn'):
            flagValue = argData.flagArgumentString('sn', 0)
            if cmds.objExists(flagValue):
                cmds.delete(flagValue)
                print 'delete PuTianTongQing scrpitNode.'

        elif argData.isFlagSet('sj'):
            flagValue = argData.flagArgumentInt('sj', 0)
            if cmds.scriptJob(exists=flagValue):
                cmds.scriptJob(kill=flagValue, force=1)
                print 'kill PuTianTongQing scrpitJob.'
Esempio n. 14
0
    def pass_args(self, args):
        arg_data = om.MArgParser(self.syntax(), args)

        if arg_data.isFlagSet(self.interpolant_flag):
            self.blend_arg = arg_data.flagArgumentDouble(
                self.interpolant_flag, 0)

        if arg_data.isFlagSet(self.new_cache_flag):
            self.new_cache_arg = arg_data.flagArgumentBool(
                self.new_cache_flag, 0)

        if arg_data.isFlagSet(self.type_flag):
            self.type_arg = arg_data.flagArgumentInt(self.type_flag, 0)

        return arg_data.numberOfFlagsUsed
Esempio n. 15
0
    def parseArguments(self, args):
        if len(args) != 2:
            raise TypeError(
                "pulseSetIsVariantAttr() takes exactly 2 arguments "
                "({0} given)".format(len(args)))

        try:
            argparser = om.MArgParser(self.syntax(), args)
        except RuntimeError:
            om.MGlobal.displayError('Error while parsing arguments')
            raise

        # attr path
        self.attrPath = argparser.commandArgumentString(0)

        # is variant value
        self.newValue = argparser.commandArgumentBool(1)
 def parseArguments(self, args):
     argData = om.MArgParser(self.syntax(), args)
     # If an argument exists, it will be the mesh name. So it gets selected
     try:
         meshName = argData.commandArgumentString(0)
         selectionList = om.MGlobal.getSelectionListByName(meshName)
     except:
         selectionList = om.MGlobal.getActiveSelectionList()
     self.findFromSelection(selectionList)
     # Parse the flags
     if argData.isFlagSet("-n"):
         self.name = argData.flagArgumentString("-n", 0)
     if argData.isFlagSet("-name"):
         self.name = argData.flagArgumentString("-name", 0)
     if argData.isFlagSet("-ws"):
         self.worldSpaceBool = argData.flagArgumentBool("-ws", 0)
     if argData.isFlagSet("-worldSpace"):
         self.worldSpaceBool = argData.flagArgumentBool("-worldSpace", 0)
     if argData.isFlagSet("-nt"):
         self.noiseTypeStr = argData.flagArgumentString("-nt", 0)
     if argData.isFlagSet("-noiseType"):
         self.noiseTypeStr = argData.flagArgumentString("-noiseType", 0)
     if argData.isFlagSet("-a"):
         self.amplitude = argData.flagArgumentFloat("-a", 0)
     if argData.isFlagSet("-amplitude"):
         self.amplitude = argData.flagArgumentFloat("-amplitude", 0)
     if argData.isFlagSet("-s"):
         self.seed = argData.flagArgumentInt("-s", 0)
     if argData.isFlagSet("-seed"):
         self.seed = argData.flagArgumentInt("-seed", 0)
     if argData.isFlagSet("-f"):
         self.frequency = argData.flagArgumentFloat("-f", 0)
     if argData.isFlagSet("-frequency"):
         self.frequency = argData.flagArgumentFloat("-frequency", 0)
     if argData.isFlagSet("-fo"):
         self.fractalOctaves = argData.flagArgumentInt("-fo", 0)
     if argData.isFlagSet("-fractalOctaves"):
         self.fractalOctaves = argData.flagArgumentInt("-fractalOctaves", 0)
     if argData.isFlagSet("-l"):
         self.lacunarity = argData.flagArgumentFloat("-l", 0)
     if argData.isFlagSet("-lacunarity"):
         self.lacunarity = argData.flagArgumentFloat("-lacunarity", 0)
     if argData.isFlagSet("-fg"):
         self.fractalGain = argData.flagArgumentFloat("-fg", 0)
     if argData.isFlagSet("-fractalGain"):
         self.fractalGain = argData.flagArgumentFloat("-fractalGain", 0)
Esempio n. 17
0
    def doIt(self, args):
        mArgParser = OpenMaya.MArgParser(self.syntax(), args)

        self.shape = mArgParser.flagArgumentString(self.shapeFlag, 0)
        self.uvName = mArgParser.flagArgumentString(self.uvNameFlag, 0)
        self.image = mArgParser.flagArgumentString(self.imageFlag, 0)

        self.matrixIs = ToolSeq_Displacement_ApplyData(
            mArgParser.flagArgumentBool(self.isXFlag, 0)
            if mArgParser.isFlagSet(self.isXFlag) else False,
            mArgParser.flagArgumentBool(self.isYFlag, 0)
            if mArgParser.isFlagSet(self.isYFlag) else False,
            mArgParser.flagArgumentBool(self.isZFlag, 0)
            if mArgParser.isFlagSet(self.isZFlag) else False,
            mArgParser.flagArgumentBool(self.isNFlag, 0)
            if mArgParser.isFlagSet(self.isNFlag) else False)
        self.matrixCha = ToolSeq_Displacement_ApplyData(
            mArgParser.flagArgumentInt(self.chaXFlag, 0)
            if self.matrixIs.X else None,
            mArgParser.flagArgumentInt(self.chaYFlag, 0)
            if self.matrixIs.Y else None,
            mArgParser.flagArgumentInt(self.chaZFlag, 0)
            if self.matrixIs.Z else None,
            mArgParser.flagArgumentInt(self.chaNFlag, 0)
            if self.matrixIs.N else None)
        self.matrixMin = ToolSeq_Displacement_ApplyData(
            mArgParser.flagArgumentDouble(self.minXFlag, 0)
            if self.matrixIs.X else None,
            mArgParser.flagArgumentDouble(self.minYFlag, 0)
            if self.matrixIs.Y else None,
            mArgParser.flagArgumentDouble(self.minZFlag, 0)
            if self.matrixIs.Z else None,
            mArgParser.flagArgumentDouble(self.minNFlag, 0)
            if self.matrixIs.N else None)
        self.matrixMax = ToolSeq_Displacement_ApplyData(
            mArgParser.flagArgumentDouble(self.maxXFlag, 0)
            if self.matrixIs.X else None,
            mArgParser.flagArgumentDouble(self.maxYFlag, 0)
            if self.matrixIs.Y else None,
            mArgParser.flagArgumentDouble(self.maxZFlag, 0)
            if self.matrixIs.Z else None,
            mArgParser.flagArgumentDouble(self.maxNFlag, 0)
            if self.matrixIs.N else None)

        self.redoIt()
Esempio n. 18
0
    def parseArgument(self, arg_list):
        """
        get parsed dictionary
        """

        result_args, result_kwargs = [], {}
        arg_data = OpenMaya.MArgParser(self.syntax(), arg_list)
        if arg_data.isFlagSet(PluginCommand.kExport):
            filename = arg_data.flagArgumentString(PluginCommand.kExport, 0)
            result_kwargs["export"] = filename

        if arg_data.isFlagSet(PluginCommand.kImport):
            filename = arg_data.flagArgumentString(PluginCommand.kImport, 0)
            result_kwargs["import"] = filename

        result_args = arg_data.getObjectStrings()
        result_args = list(result_args)

        return result_args, result_kwargs
Esempio n. 19
0
    def doIt(self, args):
        # gather the values from args
        argParser = om.MArgParser(self.syntax(), args)

        if argParser.isFlagSet('pinBorderVerts'):
            self.pinBorderVerts = argParser.flagArgumentBool(
                'pinBorderVerts', 0)
        if argParser.isFlagSet('pin'):
            self.pinBorderVerts = argParser.flagArgumentBool('pin', 0)

        if argParser.isFlagSet('vertexId'):
            self.vertexId = argParser.flagArgumentInt('vertexId', 0)
        if argParser.isFlagSet('v'):
            self.vertexId = argParser.flagArgumentInt('v', 0)

        if argParser.isFlagSet('strength'):
            self.strength = argParser.flagArgumentDouble('strength', 0)
        if argParser.isFlagSet('s'):
            self.strength = argParser.flagArgumentDouble('s', 0)

        # if argParser.isFlagSet('pruneWeightsBelow'):
        #     self.pruneWeightsBelow = args.flagArgumentDouble('pruneWeightsBelow', 0)
        # if argParser.isFlagSet('pwb'):
        #     self.pruneWeightsBelow = args.flagArgumentDouble('pwb', 0)

        # get the selected components
        if self.vertexId is None:
            self.dagPath, self.selectedComponents = self.getSelectedVertexIDs()
        else:
            self.dagPath, self.selectedComponents = self.getVertexComponentFromArg(
                self.vertexId)

        self.selectedComponentsWithNeighbors = self.getVertexNeighbors(
            self.dagPath, self.selectedComponents)

        if not self.dagPath.node().hasFn(om.MFn.kMesh):
            om.MGlobal.displayError(
                'The given object {} is not a mesh shape.'.format(
                    self.dagPath.partialPathName()))
            return

        self.redoIt()
Esempio n. 20
0
    def parseArguments(self, args):
        if len(args) != 2:
            raise TypeError("pulseSetActionAttr() takes exactly 2 arguments "
                            "({0} given)".format(len(args)))

        try:
            argparser = om.MArgParser(self.syntax(), args)
        except RuntimeError:
            om.MGlobal.displayError('Error while parsing arguments')
            raise

        # attr path
        self.attrPath = argparser.commandArgumentString(0)

        # attr value
        self.newStrValue = argparser.commandArgumentString(1)

        # variant index
        self.variantIndex = -1
        if argparser.isFlagSet(PulseSetActionAttrCmd.variantFlag.flag):
            self.variantIndex = argparser.flagArgumentInt(
                PulseSetActionAttrCmd.variantFlag.flag, 0)
Esempio n. 21
0
    def doIt(self, args):
        # gather the values from args
        argParser = om.MArgParser(self.syntax(), args)

        sourcePlugStr = argParser.commandArgumentString(0)
        destPlugStr = argParser.commandArgumentString(1)

        sel = om.MSelectionList()
        sel.add(sourcePlugStr)
        sel.add(destPlugStr)
        self.sourcePlug = sel.getPlug(0)
        self.destPlug = sel.getPlug(1)

        if argParser.isFlagSet('f') or argParser.isFlagSet('forceConnection'):
            self.forceConnection = argParser.flagArgumentBool('f', 0)
        else:
            self.forceConnection = False

        sourceFnAttr = om.MFnAttribute(self.sourcePlug.attribute())
        destFnAttr = om.MFnAttribute(self.destPlug.attribute())

        if not sourceFnAttr.connectable:
            self.displayError('{} is not connectable'.format(
                self.sourcePlug.name()))
            return
        elif not destFnAttr.connectable:
            self.displayError('{} is not connectable'.format(
                self.destPlug.name()))
            return
        elif not destFnAttr.writable:
            self.displayError('{} is not writable'.format(
                self.destPlug.name()))
            return

        # Create a new MDGModifier for this action
        self.modifier = om.MDGModifier()

        self.redoIt()
    def doIt(self, args):
        # gather the values from args
        argParser = om.MArgParser(self.syntax(), args)

        self.vertexId = argParser.commandArgumentInt(0)
        self.strength = argParser.commandArgumentDouble(1)
        meshName = argParser.commandArgumentString(2)
        skinClusterName = argParser.commandArgumentString(3)

        sel = om.MSelectionList()
        sel.add(meshName)
        sel.add(skinClusterName)
        self.dagPath = sel.getDagPath(0)
        self.skinClusterMObject = sel.getDependNode(1)

        # get the dag path and component from the vertex id

        self.component = self.getVertexComponentFromId(self.vertexId, meshName)

        self.neighborComponents, self.numVertexNeighbors = self.getVertexNeighbors(
            self.dagPath, self.component)

        self.redoIt()
	def parseArguments(self, args):
		argData = om.MArgParser(self.syntax(), args)
		# Parse flag
		if argData.isFlagSet("-n"):
			self.name = argData.flagArgumentString("-n", 0)
		elif argData.isFlagSet("-name"):
			self.name = argData.flagArgumentString("-name", 0)
		# Parse selection
		selectionList = om.MGlobal.getActiveSelectionList()
		iterator = om.MItSelectionList(selectionList, om.MFn.kDagNode)
		# Check if nothing is selected
		if iterator.isDone():
			print "Error. Nothing selected."
			# Return failure as nothing was selected
			return False
		else:
			dagPath = om.MDagPath()
			dagFn = om.MFnDagNode()
			# Create a set of items so items are not added twice
			shapeNamesSet = set()
			# Loop through the iterator
			while (not iterator.isDone()):
				dagPath = iterator.getDagPath()
				# Try to get the shape node, not the transform node
				try:
					dagPath.extendToShape()
				except:
					pass
				node = dagPath.node()
				dagFn.setObject(node)
				shapeNamesSet.add(dagFn.name())
				iterator.next()
			# Convert the set to a list as it is easier to use
			self.shapeNames = list(shapeNamesSet)
			# If the loop was successful, return True (i.e. success)
			return True
Esempio n. 24
0
    def parseArguments(self, args):
        '''
        The presence of this function is not enforced,
        but helps separate argument parsing code from other
        command code.
        '''

        # The following MArgParser object allows you to check if specific flags are set.
        argData = OpenMaya.MArgParser(self.syntax(), args)

        # Get the information for the example scenes
        if argData.isFlagSet( kShortFlagGroup ) and argData.isFlagSet(kShortFlagLabel) and argData.isFlagSet(kShortFlagXMin) \
            and argData.isFlagSet(kShortFlagXMax) and argData.isFlagSet(kShortFlagYMin) and argData.isFlagSet(kShortFlagYMax):
            maya.mel.eval("print \"It Works!\"")
            group = argData.flagArgumentString(kShortFlagGroup, 0)
            label = argData.flagArgumentString(kShortFlagLabel, 0)
            xmin = argData.flagArgumentFloat(kShortFlagXMin, 0)
            xmax = argData.flagArgumentFloat(kShortFlagXMax, 0)
            ymin = argData.flagArgumentFloat(kShortFlagYMin, 0)
            ymax = argData.flagArgumentFloat(kShortFlagYMax, 0)
            print("xminmaxyminmax", xmin, xmax, ymin, ymax)
            maya.mel.eval("print \"Group: " + group + "\"")
            maya.mel.eval("print \"Label: " + label + "\"")
            maya.mel.eval("print \"Xmin: " + str(xmin) + "\"")
            # In this case, we print the passed flag's value as an integer.
            # We use the '0' to index the flag's first and only parameter.
            #flagValue = argData.flagArgumentInt( kShortFlagName, 0 )
            #print kLongFlagName + ': ' + str( flagValue )
            groupNum = int(group[-1])
            if (groupNum > 0):
                if (groupNum > len(exampleScenes)):
                    for x in range(len(exampleScenes), groupNum):
                        scene = sim.Scene("Group" + str(x))
                        vec = sim.VecPoly()
                        exampleScenes.append(scene)
                        exampleVecs.append(vec)
                    groupData = {}
                    groupData["Group" + str(x + 1)] = []
                    data['group'].append(groupData)
                #scene = sim.Scene(group)
                #poly = sim.Polygon(sim.vec2(xmin, ymin), sim.vec2(xmax, ymax), str(label))
                # prepare label information to group
                data['group'][int(group.split('p')[1]) - 1][group].append({
                    "name":
                    label,
                    "xmin":
                    xmin,
                    "ymin":
                    ymin,
                    "xmax":
                    xmax,
                    "ymax":
                    ymax
                })
                # data['group'][int(group.split('p')[1])-1][group].append({"xmin": xmin})
                # data['group'][int(group.split('p')[1]) - 1][group].append({"ymin": ymin})
                # data['group'][int(group.split('p')[1]) - 1][group].append({"xmax": xmax})
                # data['group'][int(group.split('p')[1]) - 1][group].append({"ymax": ymax})
                #maya.mel.eval( data['group'][0])
                exampleScenes[groupNum - 1].addPolygon(
                    xmin, ymin, xmax, ymax, str(label),
                    exampleVecs[groupNum - 1])

        # Get the information for the scenes we will be propagating
        if argData.isFlagSet( kShortFlagGroupProp ) and argData.isFlagSet(kShortFlagLabel) and argData.isFlagSet(kShortFlagXMin) \
            and argData.isFlagSet(kShortFlagXMax) and argData.isFlagSet(kShortFlagYMin) and argData.isFlagSet(kShortFlagYMax):
            maya.mel.eval("print \"It Works!\"")
            group = argData.flagArgumentString(kShortFlagGroupProp, 0)
            label = argData.flagArgumentString(kShortFlagLabel, 0)
            xmin = argData.flagArgumentFloat(kShortFlagXMin, 0)
            xmax = argData.flagArgumentFloat(kShortFlagXMax, 0)
            ymin = argData.flagArgumentFloat(kShortFlagYMin, 0)
            ymax = argData.flagArgumentFloat(kShortFlagYMax, 0)
            print("ymin, ymax", xmin, xmax, ymin, ymax)
            maya.mel.eval("print \"Group: " + group + "\"")
            maya.mel.eval("print \"Label: " + label + "\"")
            maya.mel.eval("print \"Xmin: " + str(xmin) + "\"")
            # In this case, we print the passed flag's value as an integer.
            # We use the '0' to index the flag's first and only parameter.
            #flagValue = argData.flagArgumentInt( kShortFlagName, 0 )
            #print kLongFlagName + ': ' + str( flagValue )
            groupNum = int(group[-1])
            if (groupNum > 0):
                if (groupNum > len(propagateScenes)):
                    for x in range(len(propagateScenes), groupNum):
                        scene = sim.Scene("Group" + str(x))
                        vec = sim.VecPoly()
                        propagateScenes.append(scene)
                        propagateVecs.append(vec)
                #scene = sim.Scene(group)
                #poly = sim.Polygon(sim.vec2(xmin, ymin), sim.vec2(xmax, ymax), str(label))
                propagateScenes[groupNum - 1].addPolygon(
                    xmin, ymin, xmax, ymax, str(label),
                    propagateVecs[groupNum - 1])

        if argData.isFlagSet(kShortFlagPropLabel):
            propLabel = argData.flagArgumentString(kShortFlagPropLabel, 0)
            for i in range(0, len(exampleScenes) - 1):
                exampleScenes[i].desiredLabel = str(propLabel)
            maya.mel.eval("print \"It Works!\"")

        if argData.isFlagSet(kShortFlagJson):
            filename = argData.flagArgumentString(kShortFlagJson, 0)

            with open(filename, "w+") as outfile:
                json.dump(data, outfile)

        if argData.isFlagSet(kShortFlagJsonLoad):
            # parse json file here
            filename = argData.flagArgumentString(kShortFlagJsonLoad, 0)

            with open(filename) as infile:
                indata = json.load(infile)
                numGroups = len(indata['group'])
                i = 0
                for gr in indata['group']:
                    for key in gr.keys():
                        groupName = key
                        groupNum = int(groupName[-1])
                        if (groupNum > 0):
                            if (groupNum > len(exampleScenes)):
                                for x in range(len(exampleScenes), groupNum):
                                    scene = sim.Scene("Group" + str(x))
                                    vec = sim.VecPoly()
                                    exampleScenes.append(scene)
                                    exampleVecs.append(vec)
                        for l in indata['group'][i][key]:
                            labelName = l['name']
                            xmin = l['xmin']
                            ymin = l['ymin']
                            xmax = l['xmax']
                            ymax = l['ymax']
                            exampleScenes[groupNum - 1].addPolygon(
                                xmin, ymin, xmax, ymax, str(labelName),
                                exampleVecs[groupNum - 1])
                    i = i + 1

        if argData.isFlagSet(kShortFlagReset):
            del exampleScenes[:]
            del exampleVecs[:]
            del propagateScenes[:]
            del propagateVecs[:]
            data.clear()
            data['group'] = []

        if argData.isFlagSet(kShortFlagResult):
            finalResults = []
            for sIdx in range(len(propagateVecs)):
                vecPolyOut = propagateVecs[sIdx]
                output = propagateScenes[sIdx]
                allPossibleCandidates = []

                desiredLabel = exampleScenes[sIdx].desiredLabel
                # desiredpolygon in each scene
                desiredPolygons = []
                # GET CANDIDATE
                # For each example scene
                for vecPoly in exampleVecs:
                    print(vecPoly.size())
                    # iterate to find the target desired object
                    currPoly = None
                    for i in range(vecPoly.size()):
                        label = vecPoly[i].label
                        print(label)
                        if label == desiredLabel:
                            currPoly = vecPoly[i]
                            desiredPolygons.append(currPoly)
                    # print(currPoly.label)
                    # iterate through all other polygons to come up with relations
                    currminx = currPoly.low_bound.getX()
                    currmaxY = currPoly.low_bound.getY()
                    currmaxX = currPoly.upper_bound.getX()
                    currminy = currPoly.upper_bound.getY()
                    lowerBounds = []
                    upperBounds = []
                    for i in range(vecPoly.size()):
                        p = vecPoly[i]
                        label = p.label
                        if label != desiredLabel:
                            minx = p.low_bound.getX()
                            maxY = p.low_bound.getY()
                            maxX = p.upper_bound.getX()
                            miny = p.upper_bound.getY()
                            # print(minx, miny, maxX, maxY)
                            # print(currminx, currminy, currmaxX, currmaxY)
                            newMinX = minx - currminx
                            newMinY = miny - currminy
                            newMaxX = maxX - currmaxX
                            newMaxY = maxY - currmaxY
                            for j in range(vecPolyOut.size()):
                                if vecPolyOut[j].label == label:
                                    outputCurrPoly = vecPolyOut[j]
                                    outminx = outputCurrPoly.low_bound.getX()
                                    outmaxY = outputCurrPoly.low_bound.getY()
                                    outmaxX = outputCurrPoly.upper_bound.getX()
                                    outminy = outputCurrPoly.upper_bound.getY()
                                    lowerBounds.append(
                                        [outminx - newMinX, outminy - newMinY])
                                    upperBounds.append(
                                        [outmaxX - newMaxX, outmaxY - newMaxY])
                    print(lowerBounds)
                    print(upperBounds)
                    # Create candiate placements by taking combination of lower and upper
                    for lb in lowerBounds:
                        for ub in upperBounds:
                            allPossibleCandidates.append(
                                [lb[0], lb[1], ub[0], ub[1]])
                #
                # print(allPossibleCandidates)
                # print(len(allPossibleCandidates))
                # print(len(desiredPolygons))

                # get Polygons from candidate placements
                # get feature set x corresponding to each new candidate placement
                xList = []
                candidatePolygons = []
                for c in allPossibleCandidates:
                    print(c)
                    potentialPoly = sim.Polygon(sim.vec2(c[0], c[1]),
                                                sim.vec2(c[2], c[3]),
                                                desiredLabel)
                    candidatePolygons.append(potentialPoly)
                    xList.append(output.calculateRelationships(potentialPoly))

                print("here", xList)

                # get Phi values for each example
                phiList = []
                for i in range(len(exampleScenes)):
                    phiList.append(exampleScenes[i].calculateRelationships(
                        desiredPolygons[i]))

                print("phi", phiList)

                # Get Similarity Measures
                similarityMeasures = sim.SimilarityMeasures()
                xphiList = []
                for x in xList:
                    x1 = []
                    for phi in phiList:
                        ss = similarityMeasures.shapeSimilarity(x, phi)
                        x1.append(ss)
                    xphiList.append(x1)

                print("xphiList", xphiList)

                # get Gram Matrix
                GramMatRows = []
                for i in phiList:
                    currRow = []
                    for j in phiList:
                        currRow.append(similarityMeasures.shapeSimilarity(
                            i, j))
                    GramMatRows.append(np.asarray(currRow))
                GramMat = np.asarray(GramMatRows)

                print("GRAM", GramMat)

                beta = 1.0
                I = np.eye(len(exampleScenes))
                covariance = GramMat + I / beta
                precision = np.linalg.inv(covariance)

                yx = np.matmul(xphiList, precision)
                print(yx)

                allRates = []
                for val in yx:
                    sum = 0
                    for v in val:
                        sum = sum + v
                    allRates.append(sum)

                maxVal = -np.inf
                maxValIndex = 0
                for i in range(len(allRates)):
                    if (allRates[i] > maxVal):
                        maxVal = allRates[i]
                        maxValIndex = i

                print(maxVal, maxValIndex)
                print(allRates)
                finalResults.append(allPossibleCandidates[maxValIndex])

            print(finalResults)
            for result in finalResults:
                results = result
                centerX = (results[0] + results[2]) / 2
                centerY = (results[1] + results[3]) / 2
                scaleX = results[2] - results[0]
                scaleY = abs(results[1] - results[3])
                maya.mel.eval("duplicate -un;")
                maya.mel.eval("scale -x " + str(scaleX) + " -z " +
                              str(scaleY) + ";")
                maya.mel.eval("move -x " + str(centerX) + " -z " +
                              str(centerY) + ";")
Esempio n. 25
0
    def doIt(self, args):
        mArgParser = OpenMaya.MArgParser(self.syntax(), args)

        self.transforms = mArgParser.flagArgumentString(
            self.transformsFlag, 0).split('\n')

        self.matrixIs = ToolSeq_Freeze_ApplyData(
            mArgParser.flagArgumentBool(self.isMovXFlag, 0)
            if mArgParser.isFlagSet(self.isMovXFlag) else False,
            mArgParser.flagArgumentBool(self.isMovYFlag, 0)
            if mArgParser.isFlagSet(self.isMovYFlag) else False,
            mArgParser.flagArgumentBool(self.isMovZFlag, 0)
            if mArgParser.isFlagSet(self.isMovZFlag) else False,
            mArgParser.flagArgumentBool(self.isRotXFlag, 0)
            if mArgParser.isFlagSet(self.isRotXFlag) else False,
            mArgParser.flagArgumentBool(self.isRotYFlag, 0)
            if mArgParser.isFlagSet(self.isRotYFlag) else False,
            mArgParser.flagArgumentBool(self.isRotZFlag, 0)
            if mArgParser.isFlagSet(self.isRotZFlag) else False,
            mArgParser.flagArgumentBool(self.isScaXFlag, 0)
            if mArgParser.isFlagSet(self.isScaXFlag) else False,
            mArgParser.flagArgumentBool(self.isScaYFlag, 0)
            if mArgParser.isFlagSet(self.isScaYFlag) else False,
            mArgParser.flagArgumentBool(self.isScaZFlag, 0)
            if mArgParser.isFlagSet(self.isScaZFlag) else False)

        movXNew = mArgParser.flagArgumentDouble(
            self.movXFlag, 0) if self.matrixIs.movX else None
        movYNew = mArgParser.flagArgumentDouble(
            self.movYFlag, 0) if self.matrixIs.movY else None
        movZNew = mArgParser.flagArgumentDouble(
            self.movZFlag, 0) if self.matrixIs.movZ else None
        rotXNew = mArgParser.flagArgumentDouble(
            self.rotXFlag, 0) if self.matrixIs.rotX else None
        rotYNew = mArgParser.flagArgumentDouble(
            self.rotYFlag, 0) if self.matrixIs.rotY else None
        rotZNew = mArgParser.flagArgumentDouble(
            self.rotZFlag, 0) if self.matrixIs.rotZ else None
        scaXNew = mArgParser.flagArgumentDouble(
            self.scaXFlag, 0) if self.matrixIs.scaX else None
        scaYNew = mArgParser.flagArgumentDouble(
            self.scaYFlag, 0) if self.matrixIs.scaY else None
        scaZNew = mArgParser.flagArgumentDouble(
            self.scaZFlag, 0) if self.matrixIs.scaZ else None

        for i in xrange(len(self.transforms)):
            self.matrixOld.append(
                ToolSeq_Freeze_ApplyData(
                    maya_cmds.getAttr(self.transforms[i] + '.translateX'),
                    maya_cmds.getAttr(self.transforms[i] + '.translateY'),
                    maya_cmds.getAttr(self.transforms[i] + '.translateZ'),
                    maya_cmds.getAttr(self.transforms[i] + '.rotateX'),
                    maya_cmds.getAttr(self.transforms[i] + '.rotateY'),
                    maya_cmds.getAttr(self.transforms[i] + '.rotateZ'),
                    maya_cmds.getAttr(self.transforms[i] + '.scaleX'),
                    maya_cmds.getAttr(self.transforms[i] + '.scaleY'),
                    maya_cmds.getAttr(self.transforms[i] + '.scaleZ')))
            self.matrixNew.append(
                ToolSeq_Freeze_ApplyData(movXNew, movYNew, movZNew, rotXNew,
                                         rotYNew, rotZNew, scaXNew, scaYNew,
                                         scaZNew))

        self.redoIt()