Python maya.cmds.ls() Examples

The following are 30 code examples for showing how to use maya.cmds.ls(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module maya.cmds , or try the search function .

Example 1
Project: core   Author: getavalon   File: util.py    License: MIT License 6 votes vote down vote up
def shape_from_element(element):
    """Return shape of given 'element'

    Supports components, meshes, and surfaces

    """

    try:
        # Get either shape or transform, based on element-type
        node = cmds.ls(element, objectsOnly=True)[0]
    except:
        cmds.warning("Could not find node in %s" % element)
        return None

    if cmds.nodeType(node) == 'transform':
        try:
            return cmds.listRelatives(node, shapes=True)[0]
        except:
            cmds.warning("Could not find shape in %s" % element)
            return None

    else:
        return node 
Example 2
Project: core   Author: getavalon   File: lib.py    License: 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 3
Project: core   Author: getavalon   File: lib.py    License: MIT License 6 votes vote down vote up
def lsattr(attr, value=None):
    """Return nodes matching `key` and `value`

    Arguments:
        attr (str): Name of Maya attribute
        value (object, optional): Value of attribute. If none
            is provided, return all nodes with this attribute.

    Example:
        >> lsattr("id", "myId")
        ["myNode"]
        >> lsattr("id")
        ["myNode", "myOtherNode"]

    """

    if value is None:
        return cmds.ls("*.%s" % attr,
                       recursive=True,
                       objectsOnly=True,
                       long=True)
    return lsattrs({attr: value}) 
Example 4
Project: dpAutoRigSystem   Author: nilouco   File: dpFacialControl.py    License: GNU General Public License v2.0 6 votes vote down vote up
def dpLoadBSNode(self, *args):
        """ Load selected object as blendShapeNode
        """
        selectedList = cmds.ls(selection=True)
        if selectedList:
            if cmds.objectType(selectedList[0]) == "blendShape":
                cmds.textField(self.bsNodeTextField, edit=True, text=selectedList[0])
                self.dpLoadBSTgtList(selectedList[0])
                self.bsNode = selectedList[0]
            elif cmds.objectType(selectedList[0]) == "transform":
                meshList = cmds.listRelatives(selectedList[0], children=True, shapes=True, noIntermediate=True, type="mesh")
                if meshList:
                    bsNodeList = cmds.listConnections(meshList[0], type="blendShape")
                    if bsNodeList:
                        self.dpLoadBSTgtList(bsNodeList[0])
                        self.bsNode = bsNodeList[0]
                    else:
                        mel.eval("warning \""+self.langDic[self.langName]["e018_selectBlendShape"]+"\";")
                else:
                    mel.eval("warning \""+self.langDic[self.langName]["e018_selectBlendShape"]+"\";")
            else:
                mel.eval("warning \""+self.langDic[self.langName]["e018_selectBlendShape"]+"\";")
        else:
            mel.eval("warning \""+self.langDic[self.langName]["e018_selectBlendShape"]+"\";") 
Example 5
Project: dpAutoRigSystem   Author: nilouco   File: dpRivet.py    License: GNU General Public License v2.0 6 votes vote down vote up
def dpLoadGeoToAttach(self, geoName=None, geoFromUI=None, *args):
        """ Load selected object a geometry to attach rivet.
        """
        if geoName:
            selectedList = [geoName]
        elif geoFromUI:
            selectedList = [cmds.textField(self.geoToAttachTF, query=True, text=True)]
        else:
            selectedList = cmds.ls(selection=True)
        if selectedList:
            if self.dpCheckGeometry(selectedList[0]):
                self.geoToAttach = selectedList[0]
                cmds.textField(self.geoToAttachTF, edit=True, text=self.geoToAttach)
                self.dpLoadUVSet(self.geoToAttach)
        else:
            mel.eval("warning \"Select a geometry in order use it to attach rivets, please.\";") 
Example 6
Project: dpAutoRigSystem   Author: nilouco   File: dpControls.py    License: GNU General Public License v2.0 6 votes vote down vote up
def pasteAttr(self, destinationList=False, verbose=False, *args):
        """ Get to destination list and set the dictionary values on them.
        """
        # getting destinationList:
        if not destinationList:
            destinationList = cmds.ls(selection=True, long=True)
        if destinationList and self.attrValueDic:
            # set dic values to destinationList:
            for destItem in destinationList:
                for attr in self.attrValueDic:
                    try:
                        cmds.setAttr(destItem+'.'+attr, self.attrValueDic[attr])
                    except:
                        try:
                            cmds.setAttr(destItem+'.'+attr, self.attrValueDic[attr], type='string')
                        except:
                            pass
                            if verbose:
                                print self.dpUIinst.langDic[self.dpUIinst.langName]["e016_notPastedAttr"], attr
            if verbose:
                print self.dpUIinst.langDic[self.dpUIinst.langName]["i126_pastedAttr"] 
Example 7
Project: dpAutoRigSystem   Author: nilouco   File: dpUtils.py    License: GNU General Public License v2.0 6 votes vote down vote up
def findModuleLastNumber(className, typeName):
    """ Find the last used number of this type of module.
        Return its highest number.
    """
    # work with rigged modules in the scene:
    numberList = []
    guideTypeCount = 0
    # list all transforms and find the existing value in them names:
    transformList = cmds.ls(selection=False, transforms=True)
    for transform in transformList:
        if cmds.objExists(transform+"."+typeName):
            if cmds.getAttr(transform+"."+typeName) == className:
                numberList.append(className)
        # try check if there is a masterGrp and get its counter:
        if cmds.objExists(transform+".masterGrp") and cmds.getAttr(transform+".masterGrp") == 1:
            guideTypeCount = cmds.getAttr(transform+'.dp'+className+'Count')
    if(guideTypeCount > len(numberList)):
        return guideTypeCount
    else:
        return len(numberList) 
Example 8
Project: dpAutoRigSystem   Author: nilouco   File: dpUtils.py    License: GNU General Public License v2.0 6 votes vote down vote up
def getOriginedFromDic():
    """ List all transforms in the scene, verify if there is an originedFrom string attribute and store it value in a dictionary.
        Return a dictionary with originedFrom string as keys and transform nodes as values of these keys.
    """
    originedFromDic = {}
    allTransformList = cmds.ls(selection=False, type="transform")
    if allTransformList:
        for transform in allTransformList:
            if cmds.objExists(transform+".originedFrom"):
                tempOriginedFrom = cmds.getAttr(transform+".originedFrom")
                if tempOriginedFrom:
                    if not ";" in tempOriginedFrom:
                        originedFromDic[tempOriginedFrom] = transform
                    else:
                        tempOriginedFromList = tempOriginedFrom.split(";")
                        for orignedFromString in tempOriginedFromList:
                            originedFromDic[orignedFromString] = transform
    return originedFromDic 
Example 9
Project: spore   Author: wiremas   File: AEsporeNodeTemplate.py    License: MIT License 6 votes vote down vote up
def add_instance(self):
        """ add a source to the instancer and the sporeNode """

        selection = cmds.ls(sl=True, l=True)
        spore_node = selection.pop(-1)

        num_items = cmds.textScrollList('instanceList', numberOfItems=True, q=True)
        items = cmds.textScrollList('instanceList', q=True, ai=True)
        instances = node_utils.get_instanced_geo(self._node)

        for i, obj in enumerate(selection):
            # TODO - check if object type is valid
            if obj not in instances:
                obj_name = '[{}]: {}'.format(i + num_items, obj)
                cmds.textScrollList('instanceList', e=1, append=obj_name)
                node_utils.connect_to_instancer(obj, self._node) 
Example 10
Project: spore   Author: wiremas   File: manager.py    License: 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 11
Project: SISideBar   Author: ShikouYamaue   File: transform.py    License: 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 12
Project: SISideBar   Author: ShikouYamaue   File: transform.py    License: MIT License 6 votes vote down vote up
def reset_actor():
    from . import sisidebar_sub
    sel = cmds.ls(sl=True, l=True)
    joints = cmds.ls(sl=True, l=True, type='joint')
    if not joints:
        joints = []
    for s in sel:
        if cmds.nodeType(s) == 'KTG_ModelRoot':
            child_joints = cmds.ls(cmds.listRelatives(s, ad=True, f=True), l=True, type='joint')
            if child_joints:
                joints += child_joints
    if not sel:
        joints = cmds.ls(l=True, type='joint')
    for j in joints:
        con_info = cmds.connectionInfo(j+'.bindPose', dfs=True)
        if not con_info:
            continue
        con_info = con_info[0]
        bind_info = con_info.replace('world', 'xform')
        pose = cmds.getAttr(bind_info)
        cmds.xform(j, m=pose)
    sisidebar_sub.get_matrix() 
Example 13
Project: SISideBar   Author: ShikouYamaue   File: uv.py    License: MIT License 6 votes vote down vote up
def ajustSelection(self):
        #選択したものからメッシュノードがあるものを取り出し。
        #何も選択されていなかったらシーン内のメッシュ全取得
        selection = cmds.ls(sl=True)
        #print len(selection)
        #print selection
        if self.popUpMsg:
            if len(selection) == 0:
                allMeshSel = cmds.confirmDialog(m=self.msg01, t='', b= [self.msg02, self.msg03], db=self.msg02, cb=self.msg03, icn='question',ds=self.msg03)
                #print allMeshSel
                if allMeshSel == self.msg02:
                    selection = cmds.ls(type='transform')
        else:
            if len(selection) == 0:
                #print 'process all of mesh'
                selection = cmds.ls(type='transform')
        #メッシュノードが存在したらリストに加える
        return [sel for sel in selection if common.search_polygon_mesh(sel)] 
Example 14
Project: SISideBar   Author: ShikouYamaue   File: go.py    License: MIT License 6 votes vote down vote up
def maya_import():
    temp = __name__.split('.')#nameは自分自身のモジュール名。splitでピリオドごとに3分割。
    folderPath = os.path.join(os.getenv('MAYA_APP_DIR'),'Scripting_Files','go')
    if not os.path.exists(folderPath):
        os.makedirs(os.path.dirname(folderPath+'\\'))  # 末尾\\が必要なので注意
    #print folderPath
    files = os.listdir(folderPath)
    if files is not None:
        for file in files:
            print file
            nameSpace = file.replace('.ma', '')
            cmds.file(folderPath+'\\'+file, i=True, typ="mayaAscii", iv=True, mnc=False, options="v=0;", pr=True)
            #重複マテリアルにファイル名が頭に付与されてしまうのを修正
            allMat = cmds.ls(mat=True)
            fileName = file.split('.')[0]
            for mat in allMat:
                if mat.startswith(fileName+'_'):
                    cmds.rename(mat, mat.replace(fileName+'_', ''))
        cmds.inViewMessage( amg='<hl>Go Maya</hl> : Imoprt objects', pos='midCenterTop', fade=True, ta=0.75, a=0.5)
    else:
        cmds.inViewMessage( amg='<hl>Go Maya</hl> : There is no exported object', pos='midCenterTop', fade=True, ta=0.75, a=0.5) 
Example 15
Project: SISideBar   Author: ShikouYamaue   File: freeze.py    License: MIT License 6 votes vote down vote up
def freeze():
    cmds.selectMode(o=True)
    selection = cmds.ls(sl=True, type = 'transform')
    dummy = common.TemporaryReparent().main(mode='create')#モジュールでダミーの親作成
    clusterCopy = modeling.ClusterCopy()
    for sel in selection:
        allChildren = [sel] + cmds.listRelatives(sel, ad=True)#子供を取得して1つのリストにする
        polyMesh = common.search_polygon_mesh(allChildren)
        if polyMesh:
            for mesh in polyMesh:
                common.TemporaryReparent().main(mesh, dummyParent=dummy, mode='cut')
                defCls = clusterCopy.copy(mesh)
                cmds.bakePartialHistory(mesh,pc=True)
                if defCls:
                    clusterCopy.paste(mesh)
                common.TemporaryReparent().main(mesh, dummyParent=dummy, mode='parent')#コピーのおわったメッシュの子供を元に戻す
    common.TemporaryReparent().main(dummyParent=dummy, mode='delete')#ダミー親削除
    cmds.select(selection, r=True) 
Example 16
Project: SISideBar   Author: ShikouYamaue   File: sisidebar_sub.py    License: MIT License 6 votes vote down vote up
def pre_pro_reference(sel=None):
    global pre_ref_mode, pre_sel, ctx_mode, pre_obj_list
    if cmds.selectMode(q=True, o=True):
        pre_ref_mode = 'object'
    else:
        prej_ref_mode = 'component'
        if cmds.selectType(q=True, pv=True):
            pre_ref_mode = 'vertex'
        if cmds.selectType(q=True, pe=True):
            pre_ref_mode = 'edge'
        if cmds.selectType(q=True, pf=True):
            pre_ref_mode = 'face'
    pre_sel = sel
    if cmds.selectMode(q=True, co=True):
        cmds.selectMode(o=True)
        pre_obj_list = cmds.ls(sl=True, l=True)
        cmds.selectMode(co=True)
    return pre_ref_mode 
Example 17
Project: SISideBar   Author: ShikouYamaue   File: sets.py    License: MIT License 6 votes vote down vote up
def add_to_set_members():
    selection = cmds.ls(sl=True)
    
    if selection:
        setCount = 0
        for node in selection:
            if cmds.nodeType(node) != 'objectSet':
                continue
            for sel in selection:
                if sel == node:
                    continue
                try:
                    cmds.sets(sel, add=node)
                except Exception as e:
                    print e.message
            setCount += 1
        if setCount == 0:
            cmds.confirmDialog( title='Error',message='Please select set_node')

#選択セットのノード、コンポーネントを削除 
Example 18
Project: core   Author: getavalon   File: pipeline.py    License: MIT License 5 votes vote down vote up
def _ls():
    """Yields Avalon container node names.

    Used by `ls()` to retrieve the nodes and then query the full container's
    data.

    Yields:
        str: Avalon container node name (objectSet)

    """

    def _maya_iterate(iterator):
        """Helper to iterate a maya iterator"""
        while not iterator.isDone():
            yield iterator.thisNode()
            iterator.next()

    ids = {AVALON_CONTAINER_ID,
           # Backwards compatibility
           "pyblish.mindbender.container"}

    # Iterate over all 'set' nodes in the scene to detect whether
    # they have the avalon container ".id" attribute.
    fn_dep = om.MFnDependencyNode()
    iterator = om.MItDependencyNodes(om.MFn.kSet)
    for mobject in _maya_iterate(iterator):
        if mobject.apiTypeStr != "kSet":
            # Only match by exact type
            continue

        fn_dep.setObject(mobject)
        if not fn_dep.hasAttribute("id"):
            continue

        plug = fn_dep.findPlug("id", True)
        value = plug.asString()
        if value in ids:
            yield fn_dep.name() 
Example 19
Project: core   Author: getavalon   File: pipeline.py    License: MIT License 5 votes vote down vote up
def ls():
    """Yields containers from active Maya scene

    This is the host-equivalent of api.ls(), but instead of listing
    assets on disk, it lists assets already loaded in Maya; once loaded
    they are called 'containers'

    Yields:
        dict: container

    """
    container_names = _ls()

    has_metadata_collector = False
    config_host = find_submodule(api.registered_config(), "maya")
    if hasattr(config_host, "collect_container_metadata"):
        has_metadata_collector = True

    for container in sorted(container_names):
        data = parse_container(container)

        # Collect custom data if attribute is present
        if has_metadata_collector:
            metadata = config_host.collect_container_metadata(container)
            data.update(metadata)

        yield data 
Example 20
Project: core   Author: getavalon   File: pipeline.py    License: MIT License 5 votes vote down vote up
def update_hierarchy(containers):
    """Hierarchical container support

    This is the function to support Scene Inventory to draw hierarchical
    view for containers.

    We need both parent and children to visualize the graph.

    """
    container_names = set(_ls())  # lookup set

    for container in containers:
        # Find parent
        parent = cmds.listSets(object=container["objectName"]) or []
        for node in parent:
            if node in container_names:
                container["parent"] = node
                break

        # List children
        children = cmds.ls(cmds.sets(container["objectName"], query=True),
                           type="objectSet")
        container["children"] = [child for child in children
                                 if child in container_names]

        yield container 
Example 21
Project: core   Author: getavalon   File: pipeline.py    License: MIT License 5 votes vote down vote up
def process(self):
        nodes = list()

        with lib.undo_chunk():
            if (self.options or {}).get("useSelection"):
                nodes = cmds.ls(selection=True)

            instance = cmds.sets(nodes, name=self.name)
            lib.imprint(instance, self.data)

        return instance 
Example 22
Project: core   Author: getavalon   File: lib.py    License: MIT License 5 votes vote down vote up
def apply_shaders(relationships, namespace=None):
    """Given a dictionary of `relationships`, apply shaders to meshes

    Arguments:
        relationships (avalon-core:shaders-1.0): A dictionary of
            shaders and how they relate to meshes.

    """

    if namespace is not None:
        # Append namespace to shader group identifier.
        # E.g. `blinn1SG` -> `Bruce_:blinn1SG`
        relationships = {
            "%s:%s" % (namespace, shader): relationships[shader]
            for shader in relationships
        }

    for shader, ids in relationships.items():
        print("Looking for '%s'.." % shader)
        shader = next(iter(cmds.ls(shader)), None)
        assert shader, "Associated shader not part of asset, this is a bug"

        for id_ in ids:
            mesh, faces = (id_.rsplit(".", 1) + [""])[:2]

            # Find all meshes matching this particular ID
            # Convert IDs to mesh + id, e.g. "nameOfNode.f[1:100]"
            meshes = list(".".join([mesh, faces])
                          for mesh in lsattr("mbID", value=mesh))

            if not meshes:
                continue

            print("Assigning '%s' to '%s'" % (shader, ", ".join(meshes)))
            cmds.sets(meshes, forceElement=shader) 
Example 23
Project: dpAutoRigSystem   Author: nilouco   File: dpBaseControlClass.py    License: GNU General Public License v2.0 5 votes vote down vote up
def cvCreate(self, useUI, cvID, cvName='Control_Ctrl', cvSize=1.0, cvDegree=1, cvDirection='+Y', cvRot=(0, 0, 0), cvAction=1, dpGuide=False, combine=False, *args):
        """ Check if we need to get parameters from UI.
            Create a respective curve shape.
            Return the transform curve or a list of selected destination items.
        """
        # getting current selection:
        destinationList = cmds.ls(selection=True, type="transform")
        # check if the given name is good or add a sequencial number on it:
        self.cvName = utils.validateName(cvName, self.suffix)
        self.cvID = cvID
        self.cvSize = cvSize
        self.cvDegree = cvDegree
        self.cvDirection = cvDirection
        self.cvRot = cvRot
        self.cvAction = cvAction
        # getting UI info:
        if useUI:
            self.getControlUIValues(self.cvName)
        
        # combine or create curve using the parameters:
        if combine:
            self.cvCurve = self.generateCombineCurves(useUI, self.cvID, self.cvName, self.cvSize, self.cvDegree, self.cvDirection)
        else:
            # getting curve info to be created based on choose degree:
            if self.cvDegree == 1: #linear
                self.getLinearPoints()
            else: #cubic
                self.getCubicPoints()
            self.cvCurve = self.createCurve(self.cvName, self.cvDegree, self.cvPointList, self.cvKnotList, self.cvPeriodic, dpGuide)
        # set control direction for the control curve:
        self.setControlDirection(self.cvCurve, self.cvDirection)
        
        # working about action to do, like new control, add shape or replace shapes:
        self.doControlAction(destinationList)
        # select the result node and return it
        if self.cvAction == 1: #new control
            cmds.select(self.cvCurve)
            return self.cvCurve
        elif destinationList:
            cmds.select(destinationList)
            return destinationList 
Example 24
Project: dpAutoRigSystem   Author: nilouco   File: dpAutoRig.py    License: GNU General Public License v2.0 5 votes vote down vote up
def populateJoints(self, *args):
        """ This function is responsable to list all joints or only dpAR joints in the interface in order to use in skinning.
        """
        # get current jointType (all or just dpAutoRig joints):
        jntSelectedRadioButton = cmds.radioCollection(self.allUIs["jntCollection"], query=True, select=True)
        chooseJnt = cmds.radioButton(jntSelectedRadioButton, query=True, annotation=True)
        
        # list joints to be populated:
        jointList, sortedJointList = [], []
        allJointList = cmds.ls(selection=False, type="joint")
        if chooseJnt == "allJoints":
            jointList = allJointList
            cmds.checkBox(self.allUIs["_JntCB"], edit=True, enable=False)
            cmds.checkBox(self.allUIs["_JisCB"], edit=True, enable=False)
        elif chooseJnt == "dpARJoints":
            cmds.checkBox(self.allUIs["_JntCB"], edit=True, enable=True)
            cmds.checkBox(self.allUIs["_JisCB"], edit=True, enable=True)
            displayJnt = cmds.checkBox(self.allUIs["_JntCB"], query=True, value=True)
            displayJis = cmds.checkBox(self.allUIs["_JisCB"], query=True, value=True)
            for jointNode in allJointList:
                if cmds.objExists(jointNode+'.'+BASE_NAME+'joint'):
                    if displayJnt:
                        if "_Jnt" in jointNode:
                            jointList.append(jointNode)
                    if displayJis:
                        if "_Jis" in jointNode:
                            jointList.append(jointNode)
        
        # sort joints by name filter:
        jointName = cmds.textField(self.allUIs["jointNameTF"], query=True, text=True)
        if jointList:
            if jointName:
                sortedJointList = utils.filterName(jointName, jointList, " ")
            else:
                sortedJointList = jointList
        
        # populate the list:
        cmds.textScrollList( self.allUIs["jntTextScrollLayout"], edit=True, removeAll=True)
        cmds.textScrollList( self.allUIs["jntTextScrollLayout"], edit=True, append=sortedJointList)
        # atualize of footerB text:
        self.atualizeSkinFooter() 
Example 25
Project: dpAutoRigSystem   Author: nilouco   File: dpTargetMirror.py    License: GNU General Public License v2.0 5 votes vote down vote up
def dpLoadOriginalModel(self, *args):
        """ Load selected object as original model
        """
        selectedList = cmds.ls(selection=True)
        if selectedList:
            if self.dpCheckGeometry(selectedList[0]):
                cmds.textField(self.originalModelTextField, edit=True, text=selectedList[0])
        else:
            print "Original Model > None" 
Example 26
Project: dpAutoRigSystem   Author: nilouco   File: dpTargetMirror.py    License: GNU General Public License v2.0 5 votes vote down vote up
def dpAddSelect(self, *args):
        """ Add selected items to target textscroll list
        """
        # declare variables
        selMeshList = []
        # get selection
        selList = cmds.ls(selection=True)
        # check if there is any selected object in order to continue
        if selList:
            # find meshes transforms
            for item in selList:
                if not item in selMeshList:
                    if self.dpCheckGeometry(item):
                        selMeshList.append(item)
                    else:
                        return
            if selMeshList:
                # get current list
                currentList = cmds.textScrollList(self.targetScrollList, query=True, allItems=True)
                if currentList:
                    # clear current list
                    cmds.textScrollList(self.targetScrollList, edit=True, removeAll=True)
                    # avoid repeated items
                    for item in selMeshList:
                        if not item in currentList:
                            currentList.append(item)
                    # refresh textScrollList
                    cmds.textScrollList(self.targetScrollList, edit=True, append=currentList)
                else:
                    # add selected items in the empyt target scroll list
                    cmds.textScrollList(self.targetScrollList, edit=True, append=selMeshList)
            else:
                mel.eval("warning \""+self.langDic[self.langName]["i055_tgtSelect"]+"\";")
        else:
            mel.eval("warning \""+self.langDic[self.langName]["i055_tgtSelect"]+"\";") 
Example 27
Project: dpAutoRigSystem   Author: nilouco   File: dpSelectAllControls.py    License: GNU General Public License v2.0 5 votes vote down vote up
def dpFindAllGrpBySelection(self, *args):
        """ Try to find All_Grp by selected hierarchy.
        """
        selList = cmds.ls(selection=True)
        if selList:
            for item in selList:
                if self.dpCheckAllGrp(item):
                    return item
            for item in selList:
                relativeList = cmds.listRelatives(item, allParents=True, type="transform")
                while relativeList:
                    if self.dpCheckAllGrp(relativeList[0]):
                        return relativeList[0]
                    relativeList = cmds.listRelatives(relativeList[0], allParents=True, type="transform")
        return False 
Example 28
Project: dpAutoRigSystem   Author: nilouco   File: dpSelectAllControls.py    License: GNU General Public License v2.0 5 votes vote down vote up
def dpFindAllGrp(self, *args):
        """ Try to find All_Grp without selection searching for all nodes in the scene.
            Returns the first one found.
        """
        allNodeList = cmds.ls(selection=False)
        if allNodeList:
            for item in allNodeList:
                if self.dpCheckAllGrp(item):
                    return item
        return False 
Example 29
Project: dpAutoRigSystem   Author: nilouco   File: dpPrintSelection.py    License: GNU General Public License v2.0 5 votes vote down vote up
def dpMain(self, *args):
        """ Main function.
            Get selection and call the print function.
        """
        # get selection list
        self.selList = cmds.ls(selection=True)
        if self.selList:
            self.resultDic = self.dpDefineDic(self.selList)
            if self.resultDic:
                self.dpPrintResults(self.resultDic)
        else:
            mel.eval("warning \""+self.langDic[self.langName]['i042_notSelection']+"\";") 
Example 30
Project: dpAutoRigSystem   Author: nilouco   File: dpUpdateRigInfo.py    License: GNU General Public License v2.0 5 votes vote down vote up
def updateRigInfoLists(*args):
        """
        """
        masterGrp = None
        masterGrpAttr = "masterGrp"
        allList = cmds.ls(selection=False)
        for nodeItem in allList:
            if cmds.objExists(nodeItem+"."+masterGrpAttr) and \
                (cmds.getAttr(nodeItem+"."+masterGrpAttr, type=True) == "bool" or \
                cmds.getAttr(nodeItem+"."+masterGrpAttr, type=True) == "long") and \
                cmds.getAttr(nodeItem+"."+masterGrpAttr) == 1:
                masterGrp = nodeItem
        if masterGrp:
            ctrlList = cmds.ls("*_Ctrl")
            ctrlString = ""
            if ctrlList:
                for i, item in enumerate(ctrlList):
                    if (loadedSqBindPose):
                        nCurNode = pymel.PyNode(item)
                        if sqBindPose.is_pose_outdated(nCurNode):
                            sqBindPose.store_pose(pymel.PyNode(item))
                    ctrlString = ctrlString + str(item)
                    if i < len(ctrlList):
                        ctrlString = ctrlString + ";"
                cmds.setAttr(masterGrp+".controlList", ctrlString, type="string")
            
            meshList = cmds.ls("*_Mesh")
            meshString = ""
            if meshList:
                for i, item in enumerate(meshList):
                    meshString = meshString + str(item)
                    if i < len(meshList):
                        meshString = meshString + ";"
                cmds.setAttr(masterGrp+".geometryList", meshString, type="string")
            print "Control List = ", ctrlString
            print "Mesh List    = ", meshString
            print "Updated Rig Info: "+masterGrp,