Python maya.cmds.select() Examples

The following are 30 code examples of maya.cmds.select(). 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.cmds , or try the search function .
Example #1
Source File: dpSelectAllControls.py    From dpAutoRigSystem with GNU General Public License v2.0 8 votes vote down vote up
def dpSelectAllCtrls(self, allGrpNode, *args):
        """ Select all controls using All_Grp.
        """
        ctrlsToSelectList = []
        if cmds.objExists(allGrpNode+"."+self.ctrlsAttr):
            ctrlsAttr = cmds.getAttr(allGrpNode+"."+self.ctrlsAttr)
            if ctrlsAttr:
                currentNamespace = ""
                if ":" in allGrpNode:
                    currentNamespace = allGrpNode[:allGrpNode.find(":")]
                ctrlsList = ctrlsAttr.split(";")
                if ctrlsList:
                    for ctrlName in ctrlsList:
                        if ctrlName:
                            if currentNamespace:
                                ctrlsToSelectList.append(currentNamespace+":"+ctrlName)
                            else:
                                ctrlsToSelectList.append(ctrlName)
                    cmds.select(ctrlsToSelectList)
                    print self.langDic[self.langName]["m169_selectedCtrls"]+str(ctrlsToSelectList)
            else:
                mel.eval("warning \""+self.langDic[self.langName]["e019_notFoundAllGrp"]+"\";") 
Example #2
Source File: dpControls.py    From dpAutoRigSystem with GNU General Public License v2.0 7 votes vote down vote up
def renameShape(self, transformList, *args):
        """Find shapes, rename them to Shapes and return the results.
        """
        resultList = []
        for transform in transformList:
            # list all children shapes:
            childShapeList = cmds.listRelatives(transform, shapes=True, children=True, fullPath=True)
            if childShapeList:
                # verify if there is only one shape and return it renamed:
                if len(childShapeList) == 1:
                    shape = cmds.rename(childShapeList[0], transform+"Shape")
                    cmds.select(clear=True)
                    resultList.append(shape)
                # else rename and return one list of renamed shapes:
                elif len(childShapeList) > 1:
                    for i, child in enumerate(childShapeList):
                        shape = cmds.rename(child, transform+str(i)+"Shape")
                        resultList.append(shape)
                    cmds.select(clear=True)
            else:
                print "There are not children shape to rename inside of:", transform
        return resultList 
Example #3
Source File: dpCopySkin.py    From dpAutoRigSystem with GNU General Public License v2.0 7 votes vote down vote up
def dpCopySkin(self, sourceItem, destinationList, skinInfList, *args):
        """ Do the copy skin from sourceItem to destinationList using the skinInfList.
        """
        for item in destinationList:
            # get correct naming
            skinClusterName = utils.extractSuffix(item)
            if "|" in skinClusterName:
                skinClusterName = skinClusterName[skinClusterName.rfind("|")+1:]
            # create skinCluster node
            cmds.skinCluster(skinInfList, item, name=skinClusterName+"_SC", toSelectedBones=True, maximumInfluences=3, skinMethod=0)
            cmds.select(sourceItem)
            cmds.select(item, toggle=True)
            # copy skin weights from sourceItem to item node
            cmds.copySkinWeights(noMirror=True, surfaceAssociation="closestPoint", influenceAssociation=["label", "oneToOne", "closestJoint"])
            # log result
            print self.langDic[self.langName]['i083_copiedSkin'], sourceItem, item 
Example #4
Source File: manager.py    From spore with MIT License 6 votes vote down vote up
def item_clicked(self, widget, event):

        item_name = widget.long_name
        item_state = widget.is_selected
        if cmds.objExists(item_name):

            is_modified = event.modifiers() == Qt.ControlModifier
            if not is_modified:
                cmds.select(clear=True)

            for geo_item, spore_items in self.wdg_tree.iteritems():
                for spore_item in spore_items:
                    if is_modified \
                    and spore_item.is_selected:
                        cmds.select(spore_item.long_name, add=True)
                    else:
                        spore_item.deselect()
                        cmds.select(spore_item.long_name, deselect=True)

            widget.set_select(item_state)
            if not is_modified:
                cmds.select(item_name)

        else:
            self.refresh_spore() 
Example #5
Source File: miscFunc.py    From DeformationLearningSolver with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def applyDeltaMush(smooth=1.0, iterations=20, useBuildIn=False):
    """
    Args:
      smooth (float)
      iterations (int)
    """
    sel = cmds.ls(sl=1, ap=1)

    if not sel:
        om.MGlobal.displayError("Please select a few meshes.")
        return

    if useBuildIn:
        cmds.deltaMush(sel, si=iterations, ss=smooth, pbv=0)
    else:
        cmds.wbDeltaMush(sel, si=iterations, ss=smooth, pbv=0)

#---------------------------------------------------------------------- 
Example #6
Source File: transform.py    From SISideBar with MIT License 6 votes vote down vote up
def move_center_each_object():
    object_mode = cmds.selectMode( q=True, o=True )
    cmds.selectMode(o=True)
    selection = cmds.ls(sl=True, l=True)
    meshes = common.search_polygon_mesh(selection, fullPath=True, nurbs=True)
    if not meshes:
        return
    dummy = common.TemporaryReparent().main(mode='create')
    for m in meshes:
        cmds.selectMode(o=True)
        common.TemporaryReparent().main(m, dummyParent=dummy, mode='cut')
        cmds.select(m, r=True)
        if not object_mode:
            cmds.selectMode(co=True)
        move_center2selection()
        common.TemporaryReparent().main(m, dummyParent=dummy, mode='parent')
    common.TemporaryReparent().main(dummyParent=dummy, mode='delete')
    freeze.main(mesh=selection)
    cmds.select(selection, r=True) 
Example #7
Source File: miscFunc.py    From DeformationLearningSolver with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def selectInfluenceJoints():
    try:
        sel = cmds.ls(sl=1, ap=1)[0]
        try:
            skinNode = utils.findRelatedSkinCluster(sel)
            infs = cmds.skinCluster(skinNode, q=1, inf=1)
        except:
            om.MGlobal.displayError("No skinCluster found in history of %s." % sel)
            return             
        cmds.select(infs)
    except:
        om.MGlobal.displayError("Please select something.")
        return 
Example #8
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 #9
Source File: manager.py    From spore with MIT License 6 votes vote down vote up
def context_request(self, widget, action):

        if action.text() == 'Delete':
            selection = cmds.ls(sl=1, typ='sporeNode')
            for geo_wdg, spore_wdgs in self.wdg_tree.iteritems():
                for spore_wdg in spore_wdgs:

                    spore_node = spore_wdg.name
                    print spore_node
                    if spore_wdg.is_selected and cmds.objExists(spore_node):
                        instancer = node_utils.get_instancer(spore_node)
                        transform = cmds.listRelatives(spore_node, p=True, f=True)

                        if len(cmds.listRelatives(transform, c=1)) == 1:
                            cmds.delete((spore_node, transform[0], instancer))
                        else:
                            cmds.delete((spore_node, instancer))

                        selection.remove(spore_node)
                        cmds.select(selection)

            self.refresh_spore() 
Example #10
Source File: ui.py    From maya-skinning-tools with GNU General Public License v3.0 6 votes vote down vote up
def contextMenuEvent(self, event):    
        menu = Qt.QMenu(self)
        influence = menu.addAction(
            "Select: Influence", 
            partial(
                cmds.select, 
                self.influence
            )
        )
        influence.setIcon(Qt.QIcon(SELECT_ICON))
        influence.setEnabled(True if self.influence else False)

        soft = menu.addAction(
            "Select: Soft Selection",
            self.selectSoftSelection
        )
        soft.setIcon(Qt.QIcon(SELECT_ICON))
        soft.setEnabled(True if self.ssData else False)
        
        menu.exec_(self.mapToGlobal(event.pos())) 
Example #11
Source File: dpIsolate.py    From dpAutoRigSystem with GNU General Public License v2.0 6 votes vote down vote up
def dpIsolate(self, attrName, nodeList, *args):
        """ Function to run isolate setup.
        """
        # get father zero out transform node
        zeroGrp = cmds.listRelatives(nodeList[2], allParents=True, type="transform")[0]
        # create parent constraint
        pConst = cmds.parentConstraint(nodeList[0], nodeList[1], zeroGrp, maintainOffset=True, skipTranslate=["x", "y", "z"])[0]
        # add isolate attribute to selected control
        cmds.addAttr(nodeList[2], longName=attrName, defaultValue=1.0, minValue=0, maxValue=1, keyable=True) 
        # create reverse node
        reverseNode = cmds.createNode('reverse', name=nodeList[2]+"_"+attrName.capitalize()+"_Rev")
        # do isolate connections
        cmds.connectAttr(nodeList[2]+"."+attrName, pConst+"."+nodeList[0]+"W0", force=True)
        cmds.connectAttr(nodeList[2]+"."+attrName, reverseNode+".inputX", force=True)
        cmds.connectAttr(reverseNode+".outputX", pConst+"."+nodeList[1]+"W1", force=True)
        cmds.select(nodeList[2]) 
Example #12
Source File: curve.py    From maya-spline-ik with GNU General Public License v3.0 6 votes vote down vote up
def convertToBezierCurve(curve):
    """
    Check if the parsed curve is a bezier curve, if this is not the case
    convert the curve to a bezier curve.
    
    :param str curve: Name of curve
    """
    # get shape
    curveShape = cmds.listRelatives(curve, s=True)[0]

    # convert to bezier curve
    if cmds.nodeType(curveShape) == "bezierCurve":
        return
        
    cmds.select(curve)
    cmds.nurbsCurveToBezier()


# ---------------------------------------------------------------------------- 
Example #13
Source File: normal.py    From SISideBar with MIT License 6 votes vote down vote up
def convert_edge_lock():
    sel = cmds.ls(sl=True, l=True)
    meshes = common.search_polygon_mesh(sel, serchChildeNode=False)
    if not meshes:
        return
    for mesh in meshes:
        d_mesh = cmds.duplicate(mesh, rr=True)[0]
        modeling.setSoftEdge(mesh, angle=120)
        cmds.transferAttributes(d_mesh, mesh,
                                flipUVs=0, 
                                transferPositions=0, 
                                transferUVs=0, 
                                sourceUvSpace="map1", 
                                searchMethod=3, 
                                transferNormals=1, 
                                transferColors=0, 
                                targetUvSpace="map1", 
                                colorBorders=1, 
                                sampleSpace=5)
        freeze.main(mesh)
        cmds.polyNormalPerVertex(mesh, ufn=True)
        cmds.delete(d_mesh)
    cmds.select(meshes) 
Example #14
Source File: test_instance_data.py    From spore with MIT License 6 votes vote down vote up
def setUp(self):

        # create new scene & load plugin
        cmds.file(new=True, f=True)
        plugin = 'spore'
        self.load_plugin('spore')

        # setup a simple scene
        plane = cmds.polyPlane()
        cone = cmds.polyCone()
        cmds.select(plane[0], cone[0])
        spore = cmds.spore()

        # get new instance data object and connect it to the current node
        self.node = node_utils.get_mobject_from_name(spore[0])
        self.instance_data = instance_data.InstanceData(self.node)
        self.instance_data.initialize_data() 
Example #15
Source File: test_geo_cache.py    From spore with MIT License 6 votes vote down vote up
def setUp(self):

        # create new scene & load plugin
        cmds.file(new=True, f=True)
        plugin = 'spore'
        self.load_plugin('spore')

        # setup a simple scene
        plane = cmds.polyPlane(sx=10, sy=10, w=10, h=10)
        #  cone = cmds.polyCone()
        #  cmds.select(plane[0], cone[0])
        #  spore = cmds.spore()

        # get new instance data object and connect it to the current node
        #  self.node = node_utils.get_mobject_from_name(spore[0])
        self.plane = node_utils.get_dagpath_from_name(plane[0])
        self.geo_cache = geo_cache.GeoCache() 
Example #16
Source File: learning.py    From tutorials with MIT License 6 votes vote down vote up
def gainLights(lightsList, gain):
	"""
	gainLights(list lightsList, float gain)
	
	Multiplies the value of gain, into the 
	intensity of every light in the scene.
	"""

	for light in lightsList:
		cmds.select(light, r=True)
		
		intens = cmds.getAttr(".intensity")
		newItensity = intens * gain
		
		cmds.setAttr(".intensity", newItensity)
		
		print "Light: %s, Old: %s, New: %s" % (light, intens, newItensity) 
Example #17
Source File: lib.py    From core with MIT License 6 votes vote down vote up
def maintained_selection():
    """Maintain selection during context

    Example:
        >>> scene = cmds.file(new=True, force=True)
        >>> node = cmds.createNode("transform", name="Test")
        >>> cmds.select("persp")
        >>> with maintained_selection():
        ...     cmds.select("Test", replace=True)
        >>> "Test" in cmds.ls(selection=True)
        False

    """

    previous_selection = cmds.ls(selection=True)
    try:
        yield
    finally:
        if previous_selection:
            cmds.select(previous_selection,
                        replace=True,
                        noExpand=True)
        else:
            cmds.select(clear=True) 
Example #18
Source File: dpBaseControlClass.py    From dpAutoRigSystem with GNU General Public License v2.0 6 votes vote down vote up
def getControlUIValues(self, cvName='', *args):
        """ Check and get all UI values to define variables.
            Return them in a list:
            [cvName, cvSize, cvDegree, cvDirection, cvAction]
        """
        # here we will use all info from UI elements in order to call the correct action to do:
        customName = cmds.textFieldGrp(self.dpUIinst.allUIs["controlNameTFG"], query=True, text=True)
        self.cvName = cvName
        if customName:
            self.cvName = customName
        # action
        self.cvAction = cmds.radioButtonGrp(self.dpUIinst.allUIs["controlActionRBG"], query=True, select=True)
        # degree
        degreeRBGValue = cmds.radioButtonGrp(self.dpUIinst.allUIs["degreeRBG"], query=True, select=True)
        self.cvDegree = 1 #linear
        if degreeRBGValue == 2:
            self.cvDegree = 3 #cubic
        # size
        self.cvSize = cmds.floatSliderGrp(self.dpUIinst.allUIs["controlSizeFSG"], query=True, value=True)
        # direction
        self.cvDirection = cmds.optionMenuGrp(self.dpUIinst.allUIs["directionOMG"], query=True, value=True)
        return [self.cvName, self.cvSize, self.cvDegree, self.cvDirection, self.cvAction] 
Example #19
Source File: uExport.py    From uExport with zlib License 5 votes vote down vote up
def itemClicked(self, *args):
        #select nodes if there is selection metadata
        if self.mousePress is 'left':
            if hasattr(args[0], 'selectMe'):
                cmds.select(args[0].selectMe)


## P4 CRAP
########################################################################
    #check that P4 exists 
Example #20
Source File: anim_utils.py    From mgear_core with MIT License 5 votes vote down vote up
def selGroup(model, groupSuffix):
    """Select the members of a given set

    Args:
        model (PyNode): Rig top node
        groupSuffix (str): Set suffix name
    """
    controlers = getControlers(model, groupSuffix)
    pm.select(controlers) 
Example #21
Source File: anim_utils.py    From mgear_core with MIT License 5 votes vote down vote up
def quickSel(model, channel, mouse_button):
    """Select the object stored on the quick selection attributes

    Args:
        model (PyNode): The rig top node
        channel (str): The quick selection channel name
        mouse_button (QtSignal): Clicked mouse button

    Returns:
        None
    """
    qs_attr = model.attr("quicksel%s" % channel)

    if mouse_button == QtCore.Qt.LeftButton:  # Call Selection
        names = qs_attr.get().split(",")
        if not names:
            return
        pm.select(clear=True)
        for name in names:
            ctl = dag.findChild(model, name)
            if ctl:
                ctl.select(add=True)
    elif mouse_button == QtCore.Qt.MidButton:  # Save Selection
        names = [sel.name().split("|")[-1]
                 for sel in pm.ls(selection=True)
                 if sel.name().endswith("_ctl")]

        qs_attr.set(",".join(names))

    elif mouse_button == QtCore.Qt.RightButton:  # Key Selection
        names = qs_attr.get().split(",")
        if not names:
            return
        else:
            keyObj(model, names)


##################################################
# KEY
##################################################
# ================================================ 
Example #22
Source File: append_polygon.py    From SISideBar with MIT License 5 votes vote down vote up
def create_job(self):
        cmds.selectMode(co=True)
        #cmds.select(cl=True)
        self.reset_var()
        self.script_job = cmds.scriptJob(cu=True, e=("SelectionChanged", qt.Callback(self.append_polygon)))
        self.undo_flag = False
        print 'create append job :', self.script_job 
Example #23
Source File: anim_utils.py    From mgear_core with MIT License 5 votes vote down vote up
def selAll(model):
    """Select all controlers

    Args:
        model (PyNode): Rig top node
    """
    controlers = getControlers(model)
    pm.select(controlers) 
Example #24
Source File: anim_utils.py    From mgear_core with MIT License 5 votes vote down vote up
def getRootNode():
    """Returns the root node from a selected node

    Returns:
        PyNode: The root top node
    """

    root = None

    current = pm.ls(sl=True)
    if not current:
        raise RuntimeError("You need to select at least one rig node")

    if pm.objExists("{}.is_rig".format(current[0])):
        root = current[0]
    else:
        holder = current[0]
        while pm.listRelatives(holder, parent=True) and not root:
            if pm.objExists("{}.is_rig".format(holder)):
                root = holder
            else:
                holder = pm.listRelatives(holder, parent=True)[0]

    if not root:
        raise RuntimeError("Couldn't find root node from your selection")

    return root 
Example #25
Source File: dagmenu.py    From mgear_core with MIT License 5 votes vote down vote up
def __select_nodes_callback(*args):
    """ Wrapper function to call Maya select command

    Args:
        list: callback from menuItem
    """

    cmds.select(args[0], add=True) 
Example #26
Source File: dagmenu.py    From mgear_core with MIT License 5 votes vote down vote up
def __select_host_callback(*args):
    """ Wrapper function to call mGears select host

    Args:
        list: callback from menuItem
    """

    cmds.select(get_host_from_node(args[0])) 
Example #27
Source File: modeling.py    From SISideBar with MIT License 5 votes vote down vote up
def paste(self, mesh):
        if not self.cluster_list:
            return
        for cls in self.cluster_list:
            weights = self.cls_weight_dict[cls]
            print 'paste cls :',cls
            cmds.select(cl=True)            
            points = self.point_dict[cls]
            newcls = cmds.cluster(points, n=cls)
            for i, v in enumerate(points):
                cmds.percent(newcls[0], v, v=(weights[i])) 
        return newcls
        
#ポリゴンメッシュをウェイト付きで複製する関数 
Example #28
Source File: modeling.py    From SISideBar with MIT License 5 votes vote down vote up
def copy(self, mesh):
        self.cluster_list = []
        self.point_dict = {}
        self.cls_weight_dict = {}
            
        dummy = common.TemporaryReparent().main(mode='create')
        common.TemporaryReparent().main(mesh, dummyParent=dummy, mode='cut')
        
        cluster = cmds.ls(cmds.listHistory(mesh), type='cluster', l=True)
        for cls in cluster:
            set_node = cmds.ls(cmds.listHistory(cls, f=True), type='objectSet', l=True)[0]
            cmds.select(set_node)
            vertices = cmds.ls(sl=True)
            vertices = cmds.filterExpand(vertices, sm=31)
            cmds.select(vertices, r=True)
            try:
                weights = cmds.percent(cls, q=True, v=True)
                print weights
            #値が取れないときアンドゥするとなぜか直ることがある
            except Exception as e:
                print e.message
                cmds.delete(cls)
                cmds.undo()
                set_node = cmds.ls(cmds.listHistory(cls, f=True), type='objectSet', l=True)[0]
                vertices = cmds.ls(sl=True)
                vertices = cmds.filterExpand(vertices, sm=31)
                cmds.select(vertices, r=True)
                weights = cmds.percent(cls, q=True, v=True)
            self.cluster_list.append(cls)
            self.cls_weight_dict[cls] = weights
            self.point_dict[cls] = vertices
        common.TemporaryReparent().main(mesh, dummyParent=dummy, mode='parent')#コピーのおわったメッシュの子供を元に戻す
        common.TemporaryReparent().main(dummyParent=dummy, mode='delete')#ダミー親削除
        return self.point_dict, self.cls_weight_dict 
Example #29
Source File: append_polygon.py    From SISideBar with MIT License 5 votes vote down vote up
def check_normal_uv(self):
        self.check_normal_flag = True
        pre_sel = cmds.ls(sl=True)
        cmds.selectMode(o=True)
        nmv = common.conv_comp(cmds.polyInfo(nmv=True), mode='vtx')
        last_face = common.conv_comp(self.mesh, mode='face')[-1]
        last_vtx = common.conv_comp(last_face, mode='vtx')[-3:]
        #print 'nmv :',nmv
        if nmv:
            #print 'last vtx :', last_vtx
            #フェースの頂点がすべて非多様頂点だった場合は反転する
            if len(list(set(nmv) & set(last_vtx))) == 3:
                #print 'get rev face :', last_face
                if maya_ver <= 2015:#2016以降、コマンドのふるまいが変わっていたので使い分け
                    cmds.polyNormal(last_face, ch=1, normalMode=4)
                else:
                    cmds.polyNormal(last_face, ch=1, normalMode=0)
                    
        self.move_uv(last_face)#UV座標の移動
        cmds.selectMode(co=True)
        cmds.select(pre_sel)
        self.check_normal_flag = False
        
        cmds.polySoftEdge(last_face, a=self.soft_angle.value())
        
    #UV座標の移動 
Example #30
Source File: assetImporter3.py    From tutorials with MIT License 5 votes vote down vote up
def load(self, obj):
        """
        load(string/Asset obj) 
        
            Imports an Asset by a given name or Asset into Maya
        """

        if isinstance(obj, Asset):
            assets = [obj]
        else:
            assets = self.list(name)

        self._print("Loading %d assets..." % len(assets))

        cmds.select(clear=True)

        for asset in assets:

            before = set(cmds.ls(assemblies=True, r=True))
            cmds.file(asset.scene, namespace=asset.name, r=True, gl=True, loadReferenceDepth="all")
            after = set(cmds.ls(assemblies=True, r=True))

            newStuff = after.difference(before)

            for item in newStuff:

                cmds.addAttr(item, longName=self.ATTR_ASSET_NAME, dataType="string")
                cmds.addAttr(item, longName=self.ATTR_ASSET_SHOW, dataType="string")

                cmds.setAttr("%s.%s" % (item, self.ATTR_ASSET_NAME), asset.name, type="string")
                cmds.setAttr("%s.%s" % (item, self.ATTR_ASSET_SHOW), asset.show, type="string")
            
            self._print("=> Loaded: %s" % asset)

            cmds.select(list(newStuff), add=True)