Python maya.cmds.listConnections() Examples

The following are 30 code examples of maya.cmds.listConnections(). 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: dpFacialControl.py    From dpAutoRigSystem with GNU General Public License v2.0 7 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 #2
Source File: BlendTransforms.py    From BlendTransforms with The Unlicense 6 votes vote down vote up
def BT_ConnectSetup(set = None):

    if not set or not cmds.objExists(set):
        return False

    if BT_IsSetupConnected(set = set):
        cmds.warning('Setup already connected!')
        return False
    
    btNode = cmds.getAttr(set +'.Blend_Node')
    if not btNode or not cmds.objExists(btNode):
        return False

    transforms = cmds.listConnections(set +'.dagSetMembers')
    for i in range(0, len(transforms)):
        try:
            BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i])
        except:
            pass

    mults = cmds.listConnections(btNode, d = True, type = 'multiplyDivide')
    if mults:
        cmds.delete(mults)

    return True 
Example #3
Source File: spore_sampler.py    From spore with MIT License 6 votes vote down vote up
def initialize_filtering(self):
        # texture filter
        if self.use_tex:
            try:
                texture = cmds.listConnections('{}.emitTexture'.format(self.node_name))[0]
            except RuntimeError:
                texture = None

            if texture:
                self.evaluate_uvs()
                self.texture_filter(texture, 0) # TODO - Filter size

        # altitude filter
        if self.min_altitude != 0 or self.max_altitude != 1:
            self.altitude_filter(self.min_altitude, self.max_altitude, self.min_altitude_fuzz, self.max_altitude_fuzz)

        # slope filter
        if self.min_slope != 0 or self.max_slope != 180:
            self.slope_filter(self.min_slope, self.max_slope, self.slope_fuzz) 
Example #4
Source File: anim_utils.py    From mgear_core with MIT License 6 votes vote down vote up
def select_all_child_controls(control, *args):  # @unusedVariable
    """ Selects all child controls from the given control

    This function uses Maya's controller nodes and commands to find relevant
    dependencies between controls

    Args:
        control (str): parent animation control (transform node)
        *args: State of the menu item (if existing) send by mgear's dagmenu
    """

    # gets controller node from the given control. Returns if none is found
    tag = cmds.ls(cmds.listConnections(control), type="controller")
    if not tag:
        return

    # query child controls
    children = get_all_tag_children(tag)

    # adds to current selection the children elements
    cmds.select(children, add=True) 
Example #5
Source File: pickWalk.py    From mgear_core with MIT License 6 votes vote down vote up
def get_all_tag_children(node):
    """Gets all child tag controls from the given tag node

    Args:
        node (dagNode): Controller object with tag

    Returns:
        list: List of child controls (Maya transform nodes)
    """

    # store child nodes
    children = []

    # gets first child control
    child = cmds.controller(node, query=True, children=True)

    # loop on child controller nodes to get all children
    while child is not None:
        children.extend(child)
        tag = cmds.ls(cmds.listConnections(child[0], type="controller"))
        if cmds.listConnections("{}.parent".format(tag[0])) == node:
            return children
        child = cmds.controller(tag, query=True, children=True)

    return children 
Example #6
Source File: BlendTransforms.py    From BlendTransforms with The Unlicense 6 votes vote down vote up
def BT_ConnectSetup(set = None):

    if not set or not cmds.objExists(set):
        return False

    if BT_IsSetupConnected(set = set):
        cmds.warning('Setup already connected!')
        return False
    
    btNode = cmds.getAttr(set +'.Blend_Node')
    if not btNode or not cmds.objExists(btNode):
        return False

    transforms = cmds.listConnections(set +'.dagSetMembers')
    for i in range(0, len(transforms)):
        try:
            BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i])
        except:
            pass

    mults = cmds.listConnections(btNode, d = True, type = 'multiplyDivide')
    if mults:
        cmds.delete(mults)

    return True 
Example #7
Source File: BlendTransforms.py    From BlendTransforms with The Unlicense 6 votes vote down vote up
def BT_ConnectSetup(set = None):

    if not set or not cmds.objExists(set):
        return False

    if BT_IsSetupConnected(set = set):
        cmds.warning('Setup already connected!')
        return False
    
    btNode = cmds.getAttr(set +'.Blend_Node')
    if not btNode or not cmds.objExists(btNode):
        return False

    transforms = cmds.listConnections(set +'.dagSetMembers')
    for i in range(0, len(transforms)):
        try:
            BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i])
        except:
            pass

    mults = cmds.listConnections(btNode, d = True, type = 'multiplyDivide')
    if mults:
        cmds.delete(mults)

    return True 
Example #8
Source File: BlendTransforms.py    From BlendTransforms with The Unlicense 6 votes vote down vote up
def BT_ConnectSetup(set = None):

    if not set or not cmds.objExists(set):
        return False

    if BT_IsSetupConnected(set = set):
        cmds.warning('Setup already connected!')
        return False
    
    btNode = cmds.getAttr(set +'.Blend_Node')
    if not btNode or not cmds.objExists(btNode):
        return False

    transforms = cmds.listConnections(set +'.dagSetMembers')
    for i in range(0, len(transforms)):
        try:
            BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i])
        except:
            pass

    mults = cmds.listConnections(btNode, d = True, type = 'multiplyDivide')
    if mults:
        cmds.delete(mults)

    return True 
Example #9
Source File: mayascenematerial.py    From cross3d with MIT License 6 votes vote down vote up
def __iter__(self):
		mapSets = dict()
		cons = cmds.listConnections(
			self.name() + '.surfaceShader',
		) or []
		for con in cons:
			maps = cmds.listConnections(
				con,
				plugs=True,
				type='file',
			) or []
			for mapSpec in maps:
				(name, plug) = re.split(r'[.]', mapSpec)
				mapPath = os.path.normpath(cmds.getAttr(name + '.fileTextureName'))
				if mapPath and MaterialPropertyMap.hasKey(plug):
					mapSets[MaterialPropertyMap.valueByLabel(plug)] = mapPath
				else:
					mapSets[plug] = mapPath
		yield ('name', self.name())
		yield ('maps', mapSets)
		yield ('objects', [o.name() for o in self.objects()]) 
Example #10
Source File: uExport.py    From uExport with zlib License 6 votes vote down vote up
def connectRenderMeshes(self, renderMeshes, LOD=0):
        try:
            cmds.undoInfo(openChunk=True)
            lodAttr = None
            if LOD >=0 or LOD <=4:
                lodAttr = self.node + '.rendermeshes_LOD' + str(LOD)
                conns = cmds.listConnections(lodAttr, plugs=1, destination=1)
                if conns:
                    for conn in cmds.listConnections(lodAttr, plugs=1, destination=1):
                        cmds.disconnectAttr(lodAttr, conn)
            if lodAttr:
                for mesh in renderMeshes:
                    msgConnect(lodAttr, mesh + '.uExport')
            else:
                cmds.error('connectRenderMeshes>>> please specify a LOD integer (0-4) for your meshes')

        except Exception as e:
            print e
        finally:
            cmds.undoInfo(closeChunk=True) 
Example #11
Source File: leg.py    From cmt with MIT License 6 votes vote down vote up
def __create_fk(self):
        ik_switch = cmds.listConnections(
            "{}.ikBlend".format(self.two_bone_ik.ik_handle), d=False, plugs=True
        )[0]
        for ikh in [self.ik_handle_ball, self.ik_handle_toe]:
            cmds.connectAttr(ik_switch, "{}.ikBlend".format(ikh))
        self.ball_fk_ctrl = cmds.createNode(
            "transform", name="{}_fk_ctrl".format(self.ball_joint)
        )
        common.snap_to(self.ball_fk_ctrl, self.ball_joint)
        common.lock_and_hide(self.ball_fk_ctrl, "sv")
        cmds.parent(self.ball_fk_ctrl, self.two_bone_ik.end_fk_control)
        common.freeze_to_parent_offset(self.ball_fk_ctrl)
        ori = cmds.orientConstraint(self.ball_fk_ctrl, self.ball_joint)[0]
        cmds.connectAttr(
            "{}.ikFk".format(self.two_bone_ik.config_control),
            "{}.{}W0".format(ori, self.ball_fk_ctrl),
        ) 
Example #12
Source File: ml_utilities.py    From ml_tools with MIT License 6 votes vote down vote up
def listAnimCurves(objOrAttrs):
    '''
    This lists connections to all types of animNodes
    '''

    animNodes = list()

    tl = mc.listConnections(objOrAttr, s=True, d=False, type='animCurveTL')
    ta = mc.listConnections(objOrAttr, s=True, d=False, type='animCurveTA')
    tu = mc.listConnections(objOrAttr, s=True, d=False, type='animCurveTU')

    if tl:
        animNodes.extend(tl)
    if ta:
        animNodes.extend(ta)
    if tu:
        animNodes.extend(tu)

    return animNodes 
Example #13
Source File: ml_centerOfMass.py    From ml_tools with MIT License 6 votes vote down vote up
def getRootAndCOM(node):
    '''
    Given either the root or COM, return root and COM based on connections.
    '''

    com = None
    root = None

    if mc.attributeQuery(COM_ATTR, node=node, exists=True):
        com = node
        messageCon = mc.listConnections(com+'.'+COM_ATTR, source=True, destination=False)
        if not messageCon:
            raise RuntimeError('Could not determine root from COM, please select root and run again.')
        root = messageCon[0]
    else:
        messageCon = mc.listConnections(node+'.message', source=False, destination=True, plugs=True)
        if messageCon:
            for each in messageCon:
                eachNode, attr = each.rsplit('.',1)
                if attr == COM_ATTR:
                    com = eachNode
                    root = node
                    break

    return root, com 
Example #14
Source File: ml_graphEditorMask.py    From ml_tools with MIT License 6 votes vote down vote up
def selected(*args):

    curves = mc.keyframe(query=True, selected=True, name=True)
    if not curves:
        return

    try:
        mc.delete(ATTR_FILTER_NAME)
    except:pass
    try:
        mc.delete(OBJ_FILTER_NAME)
    except:pass

    filters = list()
    for c in curves:
        plug = mc.listConnections(c, plugs=True, source=False, destination=True)[0]
        print plug
        filters.append(mc.itemFilter(byName=plug, classification='user'))

    print filters
    selectedFilter = mc.itemFilter(union=filters)
    #mc.delete(filters)
    print selectedFilter
    mc.outlinerEditor('graphEditor1OutlineEd', edit=True, attrFilter=selectedFilter) 
Example #15
Source File: ml_pivot.py    From ml_tools with MIT License 6 votes vote down vote up
def pivot_driver_attr(node):
    '''
    Start with supporting pivots driven by remap value nodes, more support in the future as requested.
    '''
    #rpSrc = mc.listConnections(node+'.rotatePivot', source=True, destination=False, plugs=True)
    #if rpSrc and rpSrc[0].endswith('.translate') and mc.getAttr(rpSrc[0], keyable=True):
        #return rpSrc[0]

    for each in ('rotatePivotX', 'rotatePivotY', 'rotatePivotZ'):
        src = mc.listConnections(node+'.'+each, source=True, destination=False)
        if not src:
            continue
        srcType = mc.nodeType(src[0])
        if srcType == 'remapValue':
            src = mc.listConnections(src[0]+'.inputValue', source=True, destination=False, plugs=True)
            if src and mc.getAttr(src[0], keyable=True) and not mc.getAttr(src[0], lock=True):
                return src[0]
    return None 
Example #16
Source File: blendshape.py    From cmt with MIT License 6 votes vote down vote up
def zero_weights(blendshape):
    """Disconnects all connections to blendshape target weights and zero's
     out the weights.

    :param blendshape: Blendshape node name
    :return: Dictionary of connections dict[target] = connection
    """
    connections = {}
    targets = get_target_list(blendshape)
    for t in targets:
        plug = "{}.{}".format(blendshape, t)
        connection = cmds.listConnections(plug, plugs=True, d=False)
        if connection:
            connections[t] = connection[0]
            cmds.disconnectAttr(connection[0], plug)
        cmds.setAttr(plug, 0)
    return connections 
Example #17
Source File: rbf.py    From cmt with MIT License 6 votes vote down vote up
def input_transform(self, i):
        """Get the input transform at index

        :param i: Index
        :return: The transform driving the input at index i
        """
        input_count = cmds.getAttr("{}.inputQuatCount".format(self.name))
        if i >= input_count:
            raise RuntimeError("Invalid input index")
        # Traverse connections to the transform
        # inputQuat <- decomposeMatrix <- transform
        connection = cmds.listConnections(
            "{}.inputQuat[{}]".format(self.name, i), d=False
        )

        if not connection or cmds.nodeType(connection[0]) != "decomposeMatrix":
            return None
        connection = cmds.listConnections(
            "{}.inputMatrix".format(connection[0]), d=False
        )
        return connection[0] if connection else None 
Example #18
Source File: control.py    From cmt with MIT License 6 votes vote down vote up
def _set_from_curve(self, transform):
        """Store the parameters from an existing curve in the CurveShape object.

        :param transform: Transform
        """
        shape = shortcuts.get_shape(transform)
        if shape and cmds.nodeType(shape) == "nurbsCurve":
            create_attr = "{}.create".format(shape)
            connection = cmds.listConnections(create_attr, plugs=True, d=False)
            if connection:
                cmds.disconnectAttr(connection[0], create_attr)
            self.transform = transform
            self.cvs = cmds.getAttr("{}.cv[*]".format(shape))
            self.degree = cmds.getAttr("{}.degree".format(shape))
            self.form = cmds.getAttr("{}.form".format(shape))
            self.knots = get_knots(shape)
            if cmds.getAttr("{}.overrideEnabled".format(shape)):
                if cmds.getAttr("{}.overrideRGBColors".format(shape)):
                    self.color = cmds.getAttr("{}.overrideColorRGB".format(shape))[0]
                else:
                    self.color = cmds.getAttr("{}.overrideColor".format(shape))
            else:
                self.color = None
            if connection:
                cmds.connectAttr(connection[0], create_attr) 
Example #19
Source File: uExport.py    From uExport with zlib License 6 votes vote down vote up
def connectRoot(self, uNode, root, rewire=1):
        try:
            cmds.undoInfo(openChunk=True)
            if rewire:
                conns = cmds.listConnections(uNode + '.export_root', plugs=1, source=1)
                if conns:
                    for conn in conns:
                        cmds.disconnectAttr(conn, uNode + '.export_root')

            if not attrExists(root+'.export'):
                cmds.addAttr(root, longName='export', attributeType='message')
            cmds.connectAttr(root + '.export', uNode + '.export_root' )
        except Exception as e:
            print e
        finally:
            cmds.undoInfo(closeChunk=True) 
Example #20
Source File: dge.py    From cmt with MIT License 5 votes vote down vote up
def eval(self, expression_string, container=None, **kwargs):

        long_kwargs = {}
        for var, value in kwargs.items():
            if isinstance(value, string_types):
                tokens = value.split(".")
                if len(tokens) == 1:
                    # Assume a single node name is the world matrix
                    value = "{}.worldMatrix[0]".format(tokens[0])
                else:
                    # Turn all attribute names into long names for consistency with
                    # results in listConnections
                    value = tokens[0]
                    for t in tokens[1:]:
                        attr = "{}.{}".format(value, t)
                        value += ".{}".format(cmds.attributeName(attr, long=True))
            long_kwargs[var] = value

        self.kwargs = long_kwargs
        # Reverse variable look up to write cleaner notes
        self._reverse_kwargs = {}
        for k, v in self.kwargs.items():
            self._reverse_kwargs[v] = k
        self.expression_string = expression_string
        self.expr_stack = []
        self.assignment_stack = []
        self.results = self.bnf.parseString(expression_string, True)
        self.container = (
            cmds.container(name=container, current=True) if container else None
        )
        self.created_nodes = {}
        stack = self.expr_stack[:] + self.assignment_stack[:]
        result = self.evaluate_stack(stack)

        if self.container:
            self.publish_container_attributes()
        return result 
Example #21
Source File: swingtwist.py    From cmt with MIT License 5 votes vote down vote up
def _twist_network_exists(driver):
    """Test whether the twist decomposition network already exists on driver.

    :param driver: Driver transform
    :return: True or False
    """
    has_twist_attribute = cmds.objExists("{}.{}".format(driver, TWIST_OUTPUT))
    if not has_twist_attribute:
        return False
    twist_node = cmds.listConnections("{}.{}".format(driver, TWIST_OUTPUT), d=False)
    return True if twist_node else False 
Example #22
Source File: shortcuts.py    From cmt with MIT License 5 votes vote down vote up
def get_shape(node, intermediate=False):
    """Get the shape node of a tranform

    This is useful if you don't want to have to check if a node is a shape node
    or transform.  You can pass in a shape node or transform and the function
    will return the shape node.

    :param node:  node The name of the node.
    :param intermediate:  intermediate True to get the intermediate shape
    :return: The name of the shape node.
    """
    if cmds.objectType(node, isAType="transform"):
        shapes = cmds.listRelatives(node, shapes=True, path=True)
        if not shapes:
            shapes = []
        for shape in shapes:
            is_intermediate = cmds.getAttr("{}.intermediateObject".format(shape))
            if (
                intermediate
                and is_intermediate
                and cmds.listConnections(shape, source=False)
            ):
                return shape
            elif not intermediate and not is_intermediate:
                return shape
        if shapes:
            return shapes[0]
    elif cmds.nodeType(node) in ["mesh", "nurbsCurve", "nurbsSurface"]:
        is_intermediate = cmds.getAttr("{}.intermediateObject".format(node))
        if is_intermediate and not intermediate:
            node = cmds.listRelatives(node, parent=True, path=True)[0]
            return get_shape(node)
        else:
            return node
    return None 
Example #23
Source File: anim.py    From video2mocap with MIT License 5 votes vote down vote up
def applyEulerFilter(transforms):
    """
    Apply an euler filter to fix euler issues on curves connected to the
    transforms rotation attributes.

    :param list transforms: Path to transforms
    """
    # get anim curves connected to the rotate attributes
    rotationCurves = []

    # loop transforms
    for transform in transforms:
        # loop channels
        for channel in ["X", "Y", "Z"]:
            # variables
            node = "{0}.rotate{1}".format(transform, channel)

            # get connected animation curve
            rotationCurves.extend(
                cmds.listConnections(
                    node,
                    type="animCurve",
                    destination=False
                ) or []
            )

    # apply euler filter
    if rotationCurves:
        cmds.filterCurve(*rotationCurves, filter="euler") 
Example #24
Source File: gears2.py    From PythonForMayaSamples with GNU General Public License v3.0 5 votes vote down vote up
def createPipe(self, spans):
        # We set the transform and shape to the class variables
        self.transform, self.shape = cmds.polyPipe(subdivisionsAxis=spans)

        # I didn't like having to find the constructor from the extrude node
        # Lets just find it now and save it to the class because it won't change
        for node in cmds.listConnections('%s.inMesh' % self.transform):
            if cmds.objectType(node) == 'polyPipe':
                self.constructor = node
                break 
Example #25
Source File: texture.py    From SISideBar with MIT License 5 votes vote down vote up
def searchPlace2d(self, parentNode):
        #ノード接続のソース側のみ取得、dフラグで目的側は取得除外
        self.__nodeName.append(parentNode)#無限ループ回避リスト
        if cmds.nodeType(parentNode) == 'place2dTexture':#ノードタイプがplace2dなら
            self.place2dItems.append(parentNode)
            return
        connectNodes = cmds.listConnections(parentNode, s=True, d=False)
        if connectNodes is not None:
            for nextNode in connectNodes:
                recicleFlag = False#無限サイクル回避フラグ
                for nN in self.__nodeName:#既に処理済みのノードなら
                    if nN == nextNode:
                        recicleFlag = True#サイクルフラグをTrueに
                if recicleFlag is False:#処理済みでないノードであれば再帰的呼び出しする
                    self.searchPlace2d(nextNode) 
Example #26
Source File: uExport.py    From uExport with zlib License 5 votes vote down vote up
def rendermeshes_LOD0(self):
        conns = cmds.listConnections(self.node + '.rendermeshes_LOD0')
        if conns:
            return conns
        else: return [] 
Example #27
Source File: uExport.py    From uExport with zlib License 5 votes vote down vote up
def getAssocShaders(self, mesh):
        shapes = cmds.listRelatives(mesh, shapes=1, f=True)
        shadingGrps = cmds.listConnections(shapes,type='shadingEngine')
        shaders = cmds.ls(cmds.listConnections(shadingGrps),materials=1)
        return shaders 
Example #28
Source File: weight.py    From SISideBar with MIT License 5 votes vote down vote up
def symmetry_weight(srcNode=None, dstNode=None, symWeight=True):
    '''
    ウェイトシンメトリする関数
    srcNode→反転元
    dstNode→反転先
    symWeight→ウェイトミラーするかどうか
    '''
    # スキンクラスタを取得
    if srcNode is None:
        return
    srcShapes = cmds.listRelatives(srcNode, s=True, pa=True, type='mesh')
    if srcShapes:
        srcSkinCluster = cmds.ls(cmds.listHistory(srcNode), type='skinCluster')
        # スキンクラスタがあったらジョイントラベルを設定してウェイトミラー
        if srcSkinCluster:
            # バインド状態を転送する関数呼び出し
            skinJointAll = cmds.skinCluster(srcSkinCluster, q=True, inf=True) #ジョイントを取得
            for skinJoint in skinJointAll:
                # ジョイントラベル設定関数呼び出し
                joint_label(skinJoint, visibility=False)
            if symWeight is False or dstNode is None:
                return
            transfer_weight(srcNode, dstNode, transferWeight=False, returnInfluences=True)
            dstShapes = cmds.listRelatives(dstNode, s=True, pa=True, type='mesh')
            dstSkinCluster = cmds.listConnections(dstShapes[0] + '.inMesh', s=True, d=False)
            cmds.copySkinWeights(ss=srcSkinCluster[0], ds=dstSkinCluster[0],
                                 mirrorMode='YZ', surfaceAssociation='closestComponent',
                                 influenceAssociation='label', normalize=True) 
Example #29
Source File: uExport.py    From uExport with zlib License 5 votes vote down vote up
def rendermeshes_LOD4(self):
        conns = cmds.listConnections(self.node + '.rendermeshes_LOD4')
        if conns:
            return conns
        else: return [] 
Example #30
Source File: uExport.py    From uExport with zlib License 5 votes vote down vote up
def rendermeshes_LOD1(self):
        conns = cmds.listConnections(self.node + '.rendermeshes_LOD1')
        if conns:
            return conns
        else: return []