Python maya.OpenMaya.MSelectionList() Examples

The following are 30 code examples of maya.OpenMaya.MSelectionList(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module maya.OpenMaya , or try the search function .
Example #1
Source File: skin.py    From mgear_core with MIT License 7 votes vote down vote up
def getGeometryComponents(skinCls):
    """Get the geometry components from skincluster

    Arguments:
        skinCls (PyNode): The skincluster node

    Returns:
        dagPath: The dagpath for the components
        componets: The skincluster componets
    """
    fnSet = OpenMaya.MFnSet(skinCls.__apimfn__().deformerSet())
    members = OpenMaya.MSelectionList()
    fnSet.getMembers(members, False)
    dagPath = OpenMaya.MDagPath()
    components = OpenMaya.MObject()
    members.getDagPath(0, dagPath, components)
    return dagPath, components 
Example #2
Source File: glTFExport.py    From maya-glTF with MIT License 6 votes vote down vote up
def _get_rotation_quaternion(self):
        obj=OpenMaya.MObject()
        #make a object of type MSelectionList
        sel_list=OpenMaya.MSelectionList()
        #add something to it
        #you could retrieve this from function or the user selection
        sel_list.add(self.maya_node)
        #fill in the MObject
        sel_list.getDependNode(0,obj)
        #check if its a transform
        if (obj.hasFn(OpenMaya.MFn.kTransform)):
            quat = OpenMaya.MQuaternion()
            #then we can add it to transfrom Fn
            #Fn is basically the collection of functions for given objects
            xform=OpenMaya.MFnTransform(obj)
            xform.getRotation(quat)
            # glTF requires normalize quat
            quat.normalizeIt()
        
        py_quat = [quat[x] for x in range(4)]
        return py_quat 
Example #3
Source File: capi.py    From fossil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def asMObjectOld( otherMobject ):
    '''
    tries to cast the given obj to an mobject - it can be string
    Taken from zoo.
    '''
    if isinstance( otherMobject, basestring ):
        sel = maya.OpenMaya.MSelectionList()
        sel.add( otherMobject )
        
        if '.' in otherMobject:
            plug = maya.OpenMaya.MPlug()
            sel.getPlug( 0, plug )
            tmp = plug.asMObject()
            tmp.__MPlug__ = plug
        else:
            tmp = maya.OpenMaya.MObject()
            sel.getDependNode( 0, tmp )

        return tmp

    if isinstance( otherMobject, (maya.OpenMaya.MObject, maya.OpenMaya.MObjectHandle) ):
        return otherMobject 
Example #4
Source File: mayaGauge2.py    From tutorials with MIT License 6 votes vote down vote up
def updateGauge(self, *args, **kwargs):
        """
        updateGauge()

        Checks the current scene selection, and update 
        both the text label, and the gauge progress. 
        """
        sel = om.MSelectionList()
        om.MGlobal.getActiveSelectionList(sel)
        num_selected = sel.length()

        self.text.setText("Selected %d out of %d objects" % (num_selected, self.maxValue))

        progress = float(num_selected) / self.maxValue
        currentVal = self.gauge.value()

        # animate from our current value, to our new value
        anim = self._value_animator
        anim.setStartValue(currentVal)
        anim.setEndValue(progress)
        anim.start() 
Example #5
Source File: cmdx.py    From cmdx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _encodedagpath1(path):
    """Convert `path` to Maya API 1.0 MObject

    Arguments:
        path (str): Absolute or relative path to DAG or DG node

    Raises:
        ExistError on `path` not existing

    """

    selectionList = om1.MSelectionList()

    try:
        selectionList.add(path)
    except RuntimeError:
        raise ExistError("'%s' does not exist" % path)

    dagpath = om1.MDagPath()
    selectionList.getDagPath(0, dagpath)
    return dagpath 
Example #6
Source File: cmdx.py    From cmdx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _encode1(path):
    """Convert `path` to Maya API 1.0 MObject

    Arguments:
        path (str): Absolute or relative path to DAG or DG node

    Raises:
        ExistError on `path` not existing

    """

    selectionList = om1.MSelectionList()

    try:
        selectionList.add(path)
    except RuntimeError:
        raise ExistError("'%s' does not exist" % path)

    mobject = om1.MObject()
    selectionList.getDependNode(0, mobject)
    return mobject 
Example #7
Source File: cmdx.py    From cmdx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def encode(path):
    """Convert relative or absolute `path` to cmdx Node

    Fastest conversion from absolute path to Node

    Arguments:
        path (str): Absolute or relative path to DAG or DG node

    """

    assert isinstance(path, string_types), "%s was not string" % path

    selectionList = om.MSelectionList()

    try:
        selectionList.add(path)
    except RuntimeError:
        raise ExistError("'%s' does not exist" % path)

    mobj = selectionList.getDependNode(0)
    return Node(mobj) 
Example #8
Source File: mayascene.py    From cross3d with MIT License 6 votes vote down vote up
def _setNativeSelection(self, selection):
		""" Select the inputed native objects in the scene
			:param selection: <list> [ <PySoftimage.xsi.Object> nativeObject, .. ] || MSelectionList || str || unicode
			:return: <bool> success
		"""
		if isinstance(selection, basestring):
			try:
				om.MGlobal.selectByName(selection)
			except RuntimeError, e:
				if e.message.find('kNotFound') != -1:
					# No objects were selected
					return False
				else:
					# Something is broken. Investigate as needed
					raise
			finally: 
Example #9
Source File: mayascene.py    From cross3d with MIT License 6 votes vote down vote up
def _selectionIter(cls):
		""" A Maya Helper that returns a iterator of maya objects currently
		selected.
		"""
		# Create object named selection and type - SelectionList
		selection = om.MSelectionList()
		# Fill variable "selection" with list of selected objects
		om.MGlobal.getActiveSelectionList(selection)
		# Create iterator through list of selected object
		selection_iter = om.MItSelectionList(selection)
		# Loop though iterator objects
		while not selection_iter.isDone():
			obj = om.MObject()
			selection_iter.getDependNode(obj)
			yield obj
			selection_iter.next() 
Example #10
Source File: utils.py    From DeformationLearningSolver with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def getDagPathComponents(compList):
    """
    Args:
      compList (list)

    Returns:
      MObject
    """

    currSel = cmds.ls(sl=1, l=1)
    cmds.select(compList, r=1)
    selList = om.MSelectionList()
    om.MGlobal.getActiveSelectionList(selList)
    dagPath = om.MDagPath()
    components = om.MObject()
    selList.getDagPath(0, dagPath, components)
    cmds.select(cl=1)
    try:
        cmds.select(currSel, r=1)
    except:
        pass
    return dagPath, components

#---------------------------------------------------------------------- 
Example #11
Source File: utils.py    From DeformationLearningSolver with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def getComponent(name):
    """
    Args:
      name (str)

    Returns:
      MOBject
    """
    selList = om.MSelectionList()
    selList.add (name)
    dagPath = om.MDagPath()
    component = om.MObject()
    selList.getDagPath(0, dagPath, component)
    return component

#---------------------------------------------------------------------- 
Example #12
Source File: node_utils.py    From spore with MIT License 6 votes vote down vote up
def get_mobject_from_name(name):
    """ get mObject from a given dag-path
    :param name : the name or dag-path to a shapenode to return a mObject to """
    sl = om.MSelectionList()
    if not cmds.objExists(name):
        raise RuntimeError('Object does not exist: {}'.format(name))
    om.MGlobal.getSelectionListByName(name, sl)
    node = om.MObject()
    sl.getDependNode(0, node)
    return node 
Example #13
Source File: mesh_utils.py    From spore with MIT License 6 votes vote down vote up
def get_mesh_fn(target):
    """ get mesh function set for the given target
    :param target: dag path of the mesh
    :return MFnMesh """

    if isinstance(target, str) or isinstance(target, unicode):
        slls = om.MSelectionList()
        slls.add(target)
        ground_path = om.MDagPath()
        slls.getDagPath(0, ground_path)
        ground_path.extendToShapeDirectlyBelow(0)
        ground_node = ground_path.node()
    elif isinstance(target, om.MObject):
        ground_node = target
        ground_path = target
    elif isinstance(target, om.MDagPath):
        ground_node = target.node()
        ground_path = target
    else:
        raise TypeError('Must be of type str, MObject or MDagPath, is type: {}'.format(type(target)))

    if ground_node.hasFn(om.MFn.kMesh):
        return om.MFnMesh(ground_path)
    else:
        raise TypeError('Target must be of type kMesh') 
Example #14
Source File: shortcuts.py    From cmt with MIT License 5 votes vote down vote up
def get_dag_path2(node):
    """Get the MDagPath of the given node.

    :param node: Node name
    :return: Node MDagPath
    """
    selection_list = OpenMaya2.MSelectionList()
    selection_list.add(node)
    return selection_list.getDagPath(0) 
Example #15
Source File: spore_command.py    From spore with MIT License 5 votes vote down vote up
def parse_args(self, args):
        """ parse args """


        arg_data = om.MArgDatabase(self.syntax(), args)

        if arg_data.isFlagSet(k_name_flag):
            self.name = arg_data.getFlagArgument(k_name_flag, 0)

        selection = om.MSelectionList()
        arg_data.getObjects(selection)

        #  # check if we got at least on item
        if selection.length() == 0:
            self.logger.error('Spore Command failed: Nothing Selected')
            return False

        for i in xrange(selection.length()):
            dag_path = om.MDagPath()
            selection.getDagPath(i, dag_path)

            # get target
            if i == 0:

                try:
                    dag_path.extendToShape()
                except RuntimeError:
                    self.logger.error('Spore Command failed: Object has more than one shape')
                    return False

                if dag_path.hasFn(om.MFn.kMesh):
                    self.target = dag_path.node()
                else:
                    self.logger.error('Spore Command failed: Object is not of type kMesh')
                    return False

            # get source
            else:
                self.source.append(dag_path.node())

        return True 
Example #16
Source File: benchmark.py    From tutorials with MIT License 5 votes vote down vote up
def testPyApi():

    start   = time.time()

    # creating the helix via the cmds module, for consistency
    # in the helix object and number of vertices
    helix   = cmds.polyHelix(**HELIX_OPTS)
    pHelix  = helix[0]

    sel     = OpenMaya.MSelectionList()
    node    = OpenMaya.MObject()

    sel.add(pHelix)
    sel.getDependNode( 0, node ) 

    vector = OpenMaya.MVector()

    iter = OpenMaya.MItMeshVertex(node)

    while not iter.isDone():

        vector.x = RAND.uniform(LOW, HIGH)
        iter.translateBy(vector)

        iter.next()
    
    OpenMaya.MGlobal.deleteNode(node)

    end = time.time()
    return end-start 
Example #17
Source File: sticker.py    From NodeSticker with MIT License 5 votes vote down vote up
def reveal():
    """Reveal custom icon from previous saved scene

    Can use with scene open callback for auto display custom icon saved
    from previous session.

    """
    sel_list = oldOm.MSelectionList()
    ns_list = [""] + oldOm.MNamespace.getNamespaces(":", True)
    for ns in ns_list:
        if ns in (":UI", ":shared"):
            continue
        try:
            sel_list.add(ns + ":*." + ICON_ATTRIBUTE)
        except RuntimeError:
            pass

    for i in range(sel_list.length()):
        mobj = oldOm.MObject()
        sel_list.getDependNode(i, mobj)
        node = oldOm.MFnDependencyNode(mobj)
        plug = node.findPlug(ICON_ATTRIBUTE)
        icon_path = plug.asString()

        try:
            node.setIcon(os.path.expandvars(icon_path))
        except RuntimeError:
            pass 
Example #18
Source File: sticker.py    From NodeSticker with MIT License 5 votes vote down vote up
def _parse_nodes(target):
    """Internal function for getting MFnDependencyNode"""
    mfn_nodes = list()
    sel_list = oldOm.MSelectionList()

    for path in target:
        sel_list.add(path)

    for i in range(len(target)):
        mobj = oldOm.MObject()
        sel_list.getDependNode(i, mobj)
        mfn_nodes.append(oldOm.MFnDependencyNode(mobj))

    return mfn_nodes 
Example #19
Source File: instanceAlongCurve.py    From instanceAlongCurve with MIT License 5 votes vote down vote up
def createChildren(self):

        # List of tuples
        self.manipCount = 0
        self.manipHandleList = []
        self.manipIndexCallbacks = {}

        selectedObjects = OpenMaya.MSelectionList()
        OpenMaya.MGlobal.getActiveSelectionList(selectedObjects)

        # Because we need to know the selected object to manipulate, we cannot manipulate various nodes at once...
        if selectedObjects.length() != 1:
            return None

        dagPath = OpenMaya.MDagPath()
        selectedObjects.getDagPath(0, dagPath)
        dagPath.extendToShape()

        nodeFn = OpenMaya.MFnDependencyNode(dagPath.node())
        enableManipulators = nodeFn.findPlug(instanceAlongCurveLocator.enableManipulatorsAttr).asBool()

        # If the node is not using the custom rotation, prevent the user from breaking it ;)
        if not enableManipulators:
            return None

        self.manipCount = nodeFn.findPlug(instanceAlongCurveLocator.curveAxisHandleCountAttr).asInt()

        for i in xrange(self.manipCount):
            pointOnCurveManip = self.addPointOnCurveManip("pointCurveManip" + str(i), "pointCurve" + str(i))
            discManip = self.addDiscManip("discManip" + str(i), "disc" + str(i))
            self.manipHandleList.append((pointOnCurveManip, discManip)) 
Example #20
Source File: shortcuts.py    From cmt with MIT License 5 votes vote down vote up
def get_mobject(node):
    """Get the MObject of the given node.

    :param node: Node name
    :return: Node MObject
    """
    selection_list = OpenMaya.MSelectionList()
    selection_list.add(node)
    mobject = OpenMaya.MObject()
    selection_list.getDependNode(0, mobject)
    return mobject 
Example #21
Source File: shortcuts.py    From cmt with MIT License 5 votes vote down vote up
def get_dag_path(node):
    """Get the MDagPath of the given node.

    :param node: Node name
    :return: Node MDagPath
    """
    selection_list = OpenMaya.MSelectionList()
    selection_list.add(node)
    path = OpenMaya.MDagPath()
    selection_list.getDagPath(0, path)
    return path 
Example #22
Source File: utils.py    From DeformationLearningSolver with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getDependNode(name):
    """
    Args:
      name (str)

    Returns:
      MOBject
    """
    selList = om.MSelectionList()
    selList.add (name)
    node = om.MObject()
    selList.getDependNode(0, node)
    return node

#---------------------------------------------------------------------- 
Example #23
Source File: skinio.py    From cmt with MIT License 5 votes vote down vote up
def __get_geometry_components(self):
        """Get the MDagPath and component MObject of the deformed geometry.

        :return: (MDagPath, MObject)
        """
        # Get dagPath and member components of skinned shape
        fnset = OpenMaya.MFnSet(self.fn.deformerSet())
        members = OpenMaya.MSelectionList()
        fnset.getMembers(members, False)
        dag_path = OpenMaya.MDagPath()
        components = OpenMaya.MObject()
        members.getDagPath(0, dag_path, components)
        return dag_path, components 
Example #24
Source File: ml_softWeights.py    From ml_tools with MIT License 5 votes vote down vote up
def getSoftSelectionWeights():

    #get selection
    sel = om.MSelectionList()
    softSelection = om.MRichSelection()
    om.MGlobal.getRichSelection(softSelection)
    softSelection.getSelection(sel)

    dagPath = om.MDagPath()
    component = om.MObject()

    iter = om.MItSelectionList(sel, om.MFn.kMeshVertComponent)
    weights = {}

    while not iter.isDone():

        iter.getDagPath( dagPath, component )
        dagPath.pop() #Grab the parent of the shape node
        node = dagPath.fullPathName()
        fnComp = om.MFnSingleIndexedComponent(component)

        for i in range(fnComp.elementCount()):
            weight = 1.0
            if fnComp.hasWeights():
                weight = fnComp.weight(i).influence()

            weights['{}.vtx[{}]'.format(node, fnComp.element(i))] = weight

        iter.next()

    return weights 
Example #25
Source File: ml_centerOfMass.py    From ml_tools with MIT License 5 votes vote down vote up
def getFacesArea(faces):
    '''
    Get the area of a list of mesh faces.
    '''

    total=0
    for f in faces:
        om.MGlobal.clearSelectionList()
        om.MGlobal.selectByName(f)
        sList = om.MSelectionList()
        om.MGlobal.getActiveSelectionList(sList)

        sIter = om.MItSelectionList(sList, om.MFn.kMeshPolygonComponent) #change1

        dagPath = om.MDagPath()
        component = om.MObject()

        sIter.getDagPath(dagPath, component) #change2
        polyIter = om.MItMeshPolygon(dagPath, component)

        util = om.MScriptUtil()
        util.createFromDouble(0.0)
        ptr = util.asDoublePtr()
        polyIter.getArea(ptr, om.MSpace.kWorld)
        area = om.MScriptUtil(ptr).asDouble()
        total+=area

    return total 
Example #26
Source File: ml_arcTracer.py    From ml_tools with MIT License 5 votes vote down vote up
def getWorldValueAtFrame(attr, frame):
    mSelectionList = OpenMaya.MSelectionList()
    mSelectionList.add(attr)
    plug = OpenMaya.MPlug()
    mSelectionList.getPlug(0, plug)
    context = OpenMaya.MDGContext(OpenMaya.MTime(frame))
    return plug.asDouble(context) 
Example #27
Source File: bake_skin_weight.py    From SIWeightEditor with MIT License 5 votes vote down vote up
def redoIt(self, flash=True):
        for node, vtxIndices in self.bake_node_id_dict.items():
            weights = self.bake_node_weight_dict[node]
            infIndices = self.bake_node_inf_dict[node]
            skinFn = self.node_skinFn_dict[node]
            
            if MAYA_VER >= 2016:
                sList = om2.MSelectionList()
                sList.add(node)
                meshDag, component = sList.getComponent(0)
                # 指定の頂点をコンポーネントとして取得する
                singleIdComp = om2.MFnSingleIndexedComponent()
                vertexComp = singleIdComp.create(om2.MFn.kMeshVertComponent )
                singleIdComp.addElements(vtxIndices)
            else:
                sList = om.MSelectionList()
                sList.add(node)
                meshDag = om.MDagPath()
                component = om.MObject()
                sList.getDagPath(0, meshDag, component)
                singleIdComp = om.MFnSingleIndexedComponent()
                vertexComp = singleIdComp.create(om.MFn.kMeshVertComponent )
                singleIdComp.addElements(vtxIndices)
                            
            ##引数(dag_path, MIntArray, MIntArray, MDoubleArray, Normalize, old_weight_undo)
            #print meshDag, vertexComp , infIndices , weights
            #print type(infIndices)
            #print type(vertexComp)
            skinFn.setWeights(meshDag, vertexComp , infIndices , weights, False)
        #アンドゥ用ウェイトデータをアップデートする
        siweighteditor.update_dict(self.redo_node_weight_dict, self.bake_node_id_dict)
        if flash:
            if self.ignore_undo:#スライダー制御中のアンドゥ履歴は全無視する
                return
            siweighteditor.refresh_window() 
Example #28
Source File: bake_skin_weight.py    From SIWeightEditor with MIT License 5 votes vote down vote up
def undoIt(self):
        siweighteditor.reverse_dict(self.undo_node_weight_dict, self.bake_node_id_dict)
        if self.ignore_undo:#スライダー制御中のアンドゥ履歴は全無視する
            return
        for node, vtxIndices in self.bake_node_id_dict.items():
            weights = self.org_node_weight_dict[node]
            infIndices = self.bake_node_inf_dict[node]
            skinFn = self.node_skinFn_dict[node]
            
            if MAYA_VER >= 2016:
                sList = om2.MSelectionList()
                sList.add(node)
                meshDag, component = sList.getComponent(0)
                singleIdComp = om2.MFnSingleIndexedComponent()
                vertexComp = singleIdComp.create(om2.MFn.kMeshVertComponent )
                singleIdComp.addElements(vtxIndices)
            else:
                sList = om.MSelectionList()
                sList.add(node)
                meshDag = om.MDagPath()
                component = om.MObject()
                sList.getDagPath(0, meshDag, component)
                singleIdComp = om.MFnSingleIndexedComponent()
                vertexComp = singleIdComp.create(om.MFn.kMeshVertComponent )
                singleIdComp.addElements(vtxIndices)
                        
            ##引数(dag_path, MIntArray, MIntArray, MDoubleArray, Normalize, old_weight_undo)
            skinFn.setWeights(meshDag, vertexComp , infIndices , weights, False)
        #アンドゥの度に読み込むと重いからどうしよう。
        siweighteditor.refresh_window() 
Example #29
Source File: store_skin_weight_om2.py    From SIWeightEditor with MIT License 5 votes vote down vote up
def om_get_shape(self, name):
        sllist = om.MSelectionList()
        om.MGlobal.getSelectionListByName( name , sllist )
        dpg = om.MDagPath()
        sllist.getDagPath( 0 , dpg )
        return dpg 
Example #30
Source File: store_skin_weight.py    From SIWeightEditor with MIT License 5 votes vote down vote up
def om_get_shape(self, name):
        sllist = om.MSelectionList()
        om.MGlobal.getSelectionListByName( name , sllist )
        dpg = om.MDagPath()
        sllist.getDagPath( 0 , dpg )
        return dpg