Python maya.cmds 模块,warning() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用maya.cmds.warning()

项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def _output_node(source, type, suffix):
    newname = lib.unique(name=source.rsplit("_", 1)[0] + suffix)

    node = cmds.createNode(type)
    node = [cmds.listRelatives(node, parent=True) or node][0]
    node = cmds.rename(node, newname)

    try:
        cmds.parent(node, source)
        match_transform(node, source)

    except Exception:
        cmds.warning("Could not create %s" % node)
        cmds.delete(node)

    return node
项目:PythonForMayaSamples    作者:dgovil    | 项目源码 | 文件源码
def save(self):
        # We start off by getting the name in the text field
        name = self.saveNameField.text()

        # If the name is not given, then we will not continue and we'll warn the user
        # The strip method will remove empty characters from the string, so that if the user entered spaces, it won't be valid
        if not name.strip():
            cmds.warning("You must give a name!")
            return

        # We use our library to save with the given name
        self.library.save(name)
        # Then we repopulate our UI with the new data
        self.populate()
        # And finally, lets remove the text in the name field so that they don't accidentally overwrite the file
        self.saveNameField.setText('')
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
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 Exception:
        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 Exception:
            cmds.warning("Could not find shape in %s" % element)
            return None

    else:
        return node
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def clone_special(*args):
    """Clone in localspace, and preserve user-defined attributes"""

    for transform in cmds.ls(selection=True, long=True):
        if cmds.nodeType(transform) != "transform":
            cmds.warning("Skipping '%s', not a `transform`" % transform)
            continue

        shape = _find_shape(transform)
        type = cmds.nodeType(shape)

        if type not in ("mesh", "nurbsSurface", "nurbsCurve"):
            cmds.warning("Skipping '{transform}': cannot clone nodes "
                         "of type '{type}'".format(**locals()))
            continue

        cloned = commands.clone(shape, worldspace=False)
        new_transform = cmds.listRelatives(cloned,
                                           parent=True,
                                           fullPath=True)[0]

        new_transform = cmds.rename(new_transform,
                                    new_transform.rsplit(":", 1)[-1])

        for attr in cmds.listAttr(transform,
                                  userDefined=True) or list():
            try:
                cmds.addAttr(new_transform, longName=attr, dataType="string")
            except Exception:
                continue

            value = cmds.getAttr(transform + "." + attr)
            cmds.setAttr(new_transform + "." + attr, value, type="string")

        # Connect visibility
        cmds.connectAttr(transform + ".visibility",
                         new_transform + ".visibility")
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def _clone(worldspace=False):
    """Clone selected objects in viewport

    Arguments:
        worldspace (bool): Whether or not to append a transformGeometry to
            resulting clone.

    """

    clones = list()

    for node in cmds.ls(selection=True, long=True):
        shape = _find_shape(node)
        type = cmds.nodeType(shape)

        if type not in ("mesh", "nurbsSurface", "nurbsCurve"):
            cmds.warning("Skipping '{node}': cannot clone nodes "
                         "of type '{type}'".format(**locals()))
            continue

        cloned = commands.clone(shape, worldspace=worldspace)
        clones.append(cloned)

    if not clones:
        return

    # Select newly created transform nodes in the viewport
    transforms = list()

    for clone in clones:
        transform = cmds.listRelatives(clone, parent=True, fullPath=True)[0]
        transforms.append(transform)

    cmds.select(transforms, replace=True)
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def _find_shape(element):
    """Return shape of given 'element'

    Supports components, meshes, and surfaces

    Arguments:
        element (str): Path to component, mesh or surface

    Returns:
        str of path if found, None otherwise

    """

    # Get either shape or transform, based on element-type
    node = cmds.ls(element, objectsOnly=True, long=True)[0]

    if cmds.nodeType(node) == "transform":
        try:
            return cmds.listRelatives(node, shapes=True, fullPath=True)[0]
        except IndexError:
            return cmds.warning("Could not find shape in %s" % element)
    else:
        return node
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def __init__( self, parent = BT_GetMayaWindow() ):
        super(BT_UIForm, self).__init__(parent)

        uicPath = BT_FindUIFile()

        if not uicPath:
            return None

        self.ui = None
        if BT_MayaVersionNumber < 2014:
            self.ui = uic.loadUi(uicPath, self)
        else:
            loader = QtUiTools.QUiLoader()
            self.ui = loader.load(uicPath, self)

        self.ui.loadSelectedButton.clicked.connect(self.loadSelectedSet)
        self.ui.connectButton.clicked.connect(self.connectSetup)
        self.ui.disconnectButton.clicked.connect(self.disconnectSetup)
        self.ui.setToBaseButton.clicked.connect(self.setToBasePose)
        self.ui.setToSelectedButton.clicked.connect(self.setToPose)
        self.ui.addPoseButton.clicked.connect(self.addPose)
        self.ui.deletePoseButton.clicked.connect(self.deletePose)
        self.ui.updateSelectedButton.clicked.connect(self.updatePose)

        unitResult = BT_SetUnits()
        if unitResult:
            QtGui.QMessageBox.warning(self, "Blend Transforms", "Units set to centimetres.", "Okay")

        self.ui.show()
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def updatePose(self):
        uiSet = str(self.ui.setEdit.text())
        ind = self.ui.poseList.currentRow()
        currentItem = self.ui.poseList.currentItem().text()

        if BT_IsSetupConnected(uiSet):
            cmds.warning('Disconnect setup first!')
            return False

        result =    QtGui.QMessageBox.question(self, 'Update Pose', 'Really Update ' +str(currentItem) +' ?',
                    QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)

        if result != QtGui.QMessageBox.Yes:
            return False

        if not uiSet:
            return False
        if ind < 0:
            return False
        BT_AddPose(set = uiSet, index = ind)
        return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def deletePose(self):
        uiSet = str(self.ui.setEdit.text())
        currentItem = self.ui.poseList.currentItem().text()
        if not uiSet:
            return False

        if BT_IsSetupConnected(uiSet):
            cmds.warning('Disconnect setup first!')
            return False

        result =    QtGui.QMessageBox.question(self, 'Delete Pose', 'Really Delete ' +str(currentItem) +' ?',
                    QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)

        if result != QtGui.QMessageBox.Yes:
            return False

        poseIndex = self.ui.poseList.currentRow()
        BT_DeletePose(set = uiSet, poseIndex = poseIndex)
        poses = BT_GetPosesFromSet(uiSet)
        self.ui.poseList.clear()
        self.ui.poseList.addItems(poses)
        return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def loadSelectedSet(self):
        selection = BT_GetSelectedSet()
        if not selection:
            return False

        if not cmds.attributeQuery('Blend_Node', ex = True, n = selection):
            cmds.warning('Blend_Node attribute not found! This set might not be connected to a BlendTransforms node yet.')
            return False

        self.ui.poseList.clear()
        self.ui.setEdit.setText(selection)

        poses = BT_GetPosesFromSet(selection)
        if not poses:
            return False

        self.ui.poseList.addItems(poses)
        return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
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
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def deletePose(self):
        uiSet = str(self.ui.setEdit.text())
        currentItem = self.ui.poseList.currentItem().text()
        if not uiSet:
            return False

        if BT_IsSetupConnected(uiSet):
            cmds.warning('Disconnect setup first!')
            return False

        result =    QtGui.QMessageBox.question(self, 'Delete Pose', 'Really Delete ' +str(currentItem) +' ?',
                    QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)

        if result != QtGui.QMessageBox.Yes:
            return False

        poseIndex = self.ui.poseList.currentRow()
        BT_DeletePose(set = uiSet, poseIndex = poseIndex)
        poses = BT_GetPosesFromSet(uiSet)
        self.ui.poseList.clear()
        self.ui.poseList.addItems(poses)
        return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def loadSelectedSet(self):
        selection = BT_GetSelectedSet()
        if not selection:
            return False

        if not cmds.attributeQuery('Blend_Node', ex = True, n = selection):
            cmds.warning('Blend_Node attribute not found! This set might not be connected to a BlendTransforms node yet.')
            return False

        self.ui.poseList.clear()
        self.ui.setEdit.setText(selection)

        poses = BT_GetPosesFromSet(selection)
        if not poses:
            return False

        self.ui.poseList.addItems(poses)
        return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def BT_DoSetup():
    sets =  cmds.ls(sl = True, type = 'objectSet')

    if len(sets) <= 0:
        cmds.warning("Select a set.")
        return False

    set = sets[0]

    unitResult = BT_SetUnits()
    if unitResult:
        QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Units set to centimetres.", "Okay")

    result = BT_Setup(set = set)
    if not result:
        QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Problem with setup. May already be connected.", "Okay")
        return False

    print('Success!')
    return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
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
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def updatePose(self):
        uiSet = str(self.ui.setEdit.text())
        ind = self.ui.poseList.currentRow()
        currentItem = self.ui.poseList.currentItem().text()

        if BT_IsSetupConnected(uiSet):
            cmds.warning('Disconnect setup first!')
            return False

        result =    QtGui.QMessageBox.question(self, 'Update Pose', 'Really Update ' +str(currentItem) +' ?',
                    QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)

        if result != QtGui.QMessageBox.Yes:
            return False

        if not uiSet:
            return False
        if ind < 0:
            return False
        BT_AddPose(set = uiSet, index = ind)
        return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def deletePose(self):
        uiSet = str(self.ui.setEdit.text())
        currentItem = self.ui.poseList.currentItem().text()
        if not uiSet:
            return False

        if BT_IsSetupConnected(uiSet):
            cmds.warning('Disconnect setup first!')
            return False

        result =    QtGui.QMessageBox.question(self, 'Delete Pose', 'Really Delete ' +str(currentItem) +' ?',
                    QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)

        if result != QtGui.QMessageBox.Yes:
            return False

        poseIndex = self.ui.poseList.currentRow()
        BT_DeletePose(set = uiSet, poseIndex = poseIndex)
        poses = BT_GetPosesFromSet(uiSet)
        self.ui.poseList.clear()
        self.ui.poseList.addItems(poses)
        return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def BT_DoSetup():
    sets =  cmds.ls(sl = True, type = 'objectSet')

    if len(sets) <= 0:
        cmds.warning("Select a set.")
        return False

    set = sets[0]

    unitResult = BT_SetUnits()
    if unitResult:
        QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Units set to centimetres.", "Okay")

    result = BT_Setup(set = set)
    if not result:
        QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Problem with setup. May already be connected.", "Okay")
        return False

    print('Success!')
    return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def updatePose(self):
        uiSet = str(self.ui.setEdit.text())
        ind = self.ui.poseList.currentRow()
        currentItem = self.ui.poseList.currentItem().text()

        if BT_IsSetupConnected(uiSet):
            cmds.warning('Disconnect setup first!')
            return False

        result =    QtGui.QMessageBox.question(self, 'Update Pose', 'Really Update ' +str(currentItem) +' ?',
                    QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)

        if result != QtGui.QMessageBox.Yes:
            return False

        if not uiSet:
            return False
        if ind < 0:
            return False
        BT_AddPose(set = uiSet, index = ind)
        return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def deletePose(self):
        uiSet = str(self.ui.setEdit.text())
        currentItem = self.ui.poseList.currentItem().text()
        if not uiSet:
            return False

        if BT_IsSetupConnected(uiSet):
            cmds.warning('Disconnect setup first!')
            return False

        result =    QtGui.QMessageBox.question(self, 'Delete Pose', 'Really Delete ' +str(currentItem) +' ?',
                    QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)

        if result != QtGui.QMessageBox.Yes:
            return False

        poseIndex = self.ui.poseList.currentRow()
        BT_DeletePose(set = uiSet, poseIndex = poseIndex)
        poses = BT_GetPosesFromSet(uiSet)
        self.ui.poseList.clear()
        self.ui.poseList.addItems(poses)
        return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def loadSelectedSet(self):
        selection = BT_GetSelectedSet()
        if not selection:
            return False

        if not cmds.attributeQuery('Blend_Node', ex = True, n = selection):
            cmds.warning('Blend_Node attribute not found! This set might not be connected to a BlendTransforms node yet.')
            return False

        self.ui.poseList.clear()
        self.ui.setEdit.setText(selection)

        poses = BT_GetPosesFromSet(selection)
        if not poses:
            return False

        self.ui.poseList.addItems(poses)
        return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
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
项目:mayakit    作者:danbradham    | 项目源码 | 文件源码
def to_curve_fn(curve):

    shape = None
    if cmds.nodeType(curve, 'nurbsCurve'):
        shape = curve
    else:
        child = cmds.listRelatives(curve, shapes=True, noIntermediate=True)
        if child:
            shape = child[0]
        else:
            cmds.warning('Not a proper nurbsCurve: {}'.format(curve))
            raise Exception('Not a proper nurbsCurve: {}'.format(curve))

    sel = om.MSelectionList()
    sel.add(shape)
    dep = sel.getDagPath(0)
    fn = om.MFnNurbsCurve(dep)
    return fn
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def populateCrvField(tfgKey="", *args):
    if tfgKey not in ["cntrPivTFBG", "cntrPiv2TFBG", "upLoc2TFBG", "upLocTFBG"]:
        sel = cmds.ls(sl=True)
        if sel and len(sel)!=1:
            cmds.warning("only select the curve you want to rig up!")
        else:
            if rig.isType(sel[0], "nurbsCurve"):
                cmds.textFieldButtonGrp(widgets[tfgKey], e=True, tx=sel[0])
            else:
                cmds.warning("That's not a curve!")
    else:
        sel = cmds.ls(sl=True)
        if sel and len(sel)!=1:
            cmds.warning("only select the object you want to rig up!")
        else:
            cmds.textFieldButtonGrp(widgets[tfgKey], e=True, tx=sel[0])
            if tfgKey == "upLocTFBG":
                cmds.textFieldButtonGrp(widgets["upLoc2TFBG"], e=True, tx=sel[0])
            if tfgKey == "cntrPivTFBG":
                cmds.textFieldButtonGrp(widgets["cntrPiv2TFBG"], e=True, tx=sel[0])
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def getObj(*args):
    #get selection and put it in the widgets["objTFG"]
    clearList()
    sel = cmds.ls(sl=True, type="transform")
    if (sel and (len(sel)==1)):
        cmds.textFieldGrp(widgets["objTFG"], e=True, tx=sel[0])
    else:
        cmds.warning("you must select one object with the \"follow\" attribute")

    #------------maybe add attr onto end of obj text, then you don't have to get it later if you needed to ???

    #now create a button for each value in the "follow" attr
    #channels = cmds.channelBox ('mainChannelBox', query=True, selectedMainAttributes=True)
    enumValueStr = cmds.attributeQuery("follow", node=sel[0], listEnum=True)[0]
    values = enumValueStr.split(":")

    for i in range(0,len(values)):
        #pick a random color?
        r = random.uniform(0.5,1)
        g = random.uniform(0.5,1)
        b = random.uniform(0.5,1)
        color = (r, g, b)

        #here create the button
        cmds.button(l=values[i], w=125, p=widgets["bottomRCLO"], bgc=color, h=50, c=partial(switchMatchSpace, i))
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def move_pivot(end, *args):
    """

    Args:
        end (int): parameter value (0 or 1 from buttons) the point on curve will return, start or end
        *args:
    """

    check = False   
    sel = cmds.ls(sl=True, exactType = "transform")

    if sel:
        for x in sel:
            check = rig.isType(x, "nurbsCurve")
            if check:
                # get curve info
                pos = cmds.pointOnCurve(x, parameter = end, position = True)
                cmds.xform(x, ws=True, piv=pos)
            else:
                cmds.warning("{0} is not a nurbsCurve object. Skipping!".format(x))
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def reparameter(*args):
    """
    reparameterizes curves to be from 0-1
    Args:
    Returns:
    """
    sel = cmds.ls(sl=True, exactType = "transform")

    check = False
    newCrvs = []

    if sel:
        for x in sel:
            check = rig.isType(x, "nurbsCurve")
            if check:
                crv = x
                newCrv = cmds.rebuildCurve(crv, constructionHistory=False, rebuildType = 0, keepControlPoints=True,  keepRange = 0, replaceOriginal=True, name = "{0}_RB".format(crv))[0]

            # reconnect parents and children of orig curve

            else:
                cmds.warning("{0} is not a nurbsCurve object. Skipping!".format(x))

    cmds.select(sel, r=True)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def align_along_curve(*args):
    """
    aligns and objet along a curve at given param
    Args:
        *args:
    Returns:
        void
    """
    sel = cmds.ls(sl=True, type="transform")
    if len(sel) != 2:
        cmds.warning("You need to select curve then object to align!")
        return()
    crv = sel[0]
    obj = sel[1]
    if not rig.isType(crv, "nurbsCurve"):
        cmds.warning("select curve first, THEN object")
        return()

    param = cmds.floatFieldGrp(widgets["alExFFG"], q=True, v1=True)

    rig.align_to_curve(crv, obj, param)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def fileLoad(*args):
    sel = cmds.ls(sl=True)
    origTexture = sel[0]
    ctrls = sel[1:]

    # get path
    path = cmds.getAttr("{0}.fileTextureName".format(origTexture))
    if not path:
        cmds.warning("No file present in {0}. Cancelling!".format(origTexture))
        return

    for ctrl in ctrls:
        ctrlFile = cmds.connectionInfo("{0}.fileTexture".format(ctrl), sfd=True).partition(".")[0]

        # add path to ctrl file
        cmds.setAttr("{0}.fileTextureName".format(ctrlFile), path, type="string")
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def capReplace(*args):
    sel = cmds.ls(sl=True, type="transform")

    if sel < 2:
        cmds.warning("You don't have two things selected (cap and one ctrl minimum)!")
        return

    newCap = sel[0]
    ctrls = sel[1:]
    for ctrl in ctrls:
        oldCap = cmds.connectionInfo("{0}.capRig".format(ctrl), sfd=True).partition(".")[0]
        dupe = rig.swapDupe(newCap, oldCap, delete=True, name=oldCap)
        cmds.connectAttr("{0}.rotateCap".format(ctrl), "{0}.rotateY".format(dupe))
        cmds.connectAttr("{0}.message".format(dupe), "{0}.capRig".format(ctrl))
        cmds.setAttr("{0}.v".format(dupe), 1)

    # if not already, parent cap replace obj in folder and hide
    par = cmds.listRelatives(newCap, p=True)
    if not par or par[0] != "pastaRigSetupComponents_Grp":
        cmds.parent(newCap, "pastaRigSetupComponents_Grp")

    cmds.setAttr("{0}.v".format(newCap), 0)
    cmds.select(ctrls, r=True)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def addBaseCap(*args):
    sel = cmds.ls(sl=True, type="transform")

    if sel < 2:
        cmds.warning("You don't have two things selected (cap and one ctrl minimum)!")
        return

    newCap = sel[0]
    ctrls = sel[1:]

    for ctrl in ctrls:
        tempCap = cmds.connectionInfo("{0}.tempBaseCap".format(ctrl), sfd=True).partition(".")[0]

        dupe = rig.swapDupe(newCap, tempCap, delete=True, name="{0}_baseCap".format(ctrl))
        cmds.setAttr("{0}.v".format(dupe), 1)
        cmds.connectAttr("{0}.rotateBaseCap".format(ctrl), "{0}.rotateY".format(dupe))
        cmds.connectAttr("{0}.message".format(dupe), "{0}.tempBaseCap".format(ctrl))

    # if not already, parent cap replace obj in folder and hide
    par = cmds.listRelatives(newCap, p=True)
    if not par or par[0] != "pastaRigSetupComponents_Grp":
        cmds.parent(newCap, "pastaRigSetupComponents_Grp")

    cmds.setAttr("{0}.v".format(newCap), 0)
    cmds.select(ctrls, r=True)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def getValues(*args):
    try: 
        obj = cmds.ls(sl=True, transforms = True)[0]

        #currentFrame = cmds.currentTime(q = True)

        step = cmds.intFieldGrp(widgets['stepIFG'], q = True, v1 = True)
        frmVal = cmds.radioButtonGrp(widgets["frmRBG"], q=True, sl=True)
        suffix = cmds.textFieldGrp(widgets["sufTFG"], q = True, tx = True)
        name = "%s_%s"%(obj, suffix)

        if frmVal == 1:
            frameStart = int(cmds.playbackOptions(query=True, min=True))
            frameEnd = int(cmds.playbackOptions(query=True, max=True))

        else: 
            frameStart = cmds.intFieldGrp(widgets["frmRngIFG"], q = True, v1 = True)
            frameEnd = cmds.intFieldGrp(widgets["frmRngIFG"], q = True, v2 = True)

        makeSequence(obj, name, frameStart, frameEnd, step) 

    except:
        cmds.warning("Select one object with a transform")
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def getObjectList(*args):
    """gets the list of object of type txt"""

    objs = []
    objText = getTypeText()

    if objText in typeList:
        objs = cmds.ls(type=objText)
    else:
        cmds.warning("This instance of Maya doesn't recognize that type of object: {0}!".format(objText))
        return()

    if objs:
#---------------- check if we're promoting shapes       
#---------------- if yes, send out list to see which elements are shapes and promote them, return a new list into obj ie. objs = promoteList(objs), this will return either the same list or an ammended list
        addObjectsToScrollList(objs)
    else:
        cmds.warning("No objects found of type: {0}".format(objText))
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def getAttr(*args):
    """grabs the selected channel from the selected obj and puts the enum values into the list"""
    #--------here could require a channel of a specific name, then you could do it automagically (check for "follow", "spaces", "space", "ss", etc)
    obj = cmds.textFieldGrp(widgets["objTFG"], q=True, tx=True)
    cmds.select(obj, r=True)
    channels = cmds.channelBox ('mainChannelBox', query=True, selectedMainAttributes=True)
    print channels
    if (channels and (len(channels)==1)):
        if (cmds.attributeQuery(channels[0], node=obj, enum=True)):
            enumValue = cmds.attributeQuery(channels[0], node=obj, listEnum=True)
            values = enumValue[0].split(":")
            for value in values:
                cmds.textScrollList(widgets["spacesTSL"], e=True, append=value)
                #----------create a button for each one???
                #----------or have them be double clicked???
    else:
        cmds.warning("select only the enum space switch channel")
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def populateList(*args):
    xform = None
    tsl = widgets["defTSL"]
    cmds.textScrollList(tsl, e=True, removeAll=True)
    cmpnts = cmds.filterExpand(ex=False, sm=[28, 31])
    if cmpnts:
        xform = cmpnts[0].partition(".")[0]
    if not cmpnts:
        sel = cmds.ls(sl=True, type="transform")
        if sel:
            xform = sel[0]
    if not xform:
        cmds.warning("You must select a piece of geo or some components on a piece of geo!")
        return()
    cmds.textFieldGrp(widgets["objTFG"], e=True, tx=xform)
    defs = getDeformers(xform)
    for d in defs:
        cmds.textScrollList(tsl, e=True, a=d)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def connect_param(src, tgt, attrType, prm, force=False, *args):
    """
    connects the indiv chnls based on the checkbox sorting in connect_attrs
    args:
        src (string): source object
        tgt (string): target object
        attrType (string): attr short name (t, r, s)
        prm (string): specific channel name (x, y, z)
        force (bool): value for force flag. Defaults to False
    return:
        None
    """
    try:
        cmds.connectAttr("{0}.{1}{2}".format(src, attrType, prm), "{0}.{1}{2}".format(tgt, attrType, prm), force=force)
    except:
        cmds.warning(
            "there was an issue connecting to {0}{1} of {2}. Make sure the channels are free!".format(attrType, prm,
                                                                                                      tgt))
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def locked_attr(*args):
    """
    creates a locked attr (I use as a separator). Uses the long name as the nice name (literal name in channel box)
    """
    attrName = cmds.textFieldButtonGrp(widgets["lockAttrTFBG"], q=True, tx=True)

    if attrName:
        sel = cmds.ls(sl=True)

        if sel:
            for obj in sel:
                try:
                    cmds.addAttr(obj, ln=attrName, nn=attrName, at="enum", en="-----", k=True)
                    cmds.setAttr("%s.%s" % (obj, attrName), l=True)
                except:
                    cmds.warning("Failed to add %s to %s, skipping!" % (attrName, obj))
        else:
            cmds.warning("Please select some objects to add attr to!")
    else:
        cmds.warning("Please enter a name for the attr!")
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def add_zero_one_attribute(attrType, *args):
    """
    adds an attribute with range of 0 to 1 to each selected obj
    :param attrType: either "short" or "float"
    :param args:
    :return:
    """
    sel = cmds.ls(sl=True)
    if not sel:
        cmds.warning("You need to select an object add attrs to!")
        return()
    attrName = cmds.textFieldGrp(widgets["newAttrTFG"], q=True, tx=True)
    if not attrName:
        cmds.warning("Please enter a name for the attribute in the field!")
        return()
    for obj in sel:
        try:
            cmds.addAttr(obj, ln=attrName, at=attrType, min=0, max=1, dv=0, k=True)
        except:
            cmds.warning("Couldn't add attr: {0} to object: {1}. Skipping.".format(attrName, obj))
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def connectShapeVis(*args):
    """Connects the attr from the assoc. text field to the shape Visibility of selected objects"""

    sel = cmds.ls(sl=True, type="transform")
    driver = cmds.textFieldButtonGrp(widgets["toShapeVis"], q=True, tx=True)

    if sel:
        if driver:
            for obj in sel:
                shapes = cmds.listRelatives(obj, s=True)
                for shape in shapes:
                    try:
                        cmds.connectAttr(driver, "%s.v" % shape, f=True)
                        cmds.warning("Connected %s to %s" % (driver, shape))
                    except:
                        cmds.warning("Couldn't connect %s to %s. Sorry! Check the Script Editor." % (driver, shape))
    else:
        cmds.warning("You need to select an object to connect the shape.vis!")
项目:core    作者:getavalon    | 项目源码 | 文件源码
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
项目:ModularChannelBox    作者:Vaei    | 项目源码 | 文件源码
def channelbox_command_cboxReset(box, menuItem, key, *args):
    with sysCmd.Undo(0):
        confirm = cmds.confirmDialog(t="Reset to Default",
                                     m="Delete all saved data and modified settings associated with this Channel Box?",
                                     icon="critical", button=["Reset", "Cancel"])

        if confirm == "Reset":

            default_states = box.menu_default_states

            for k, v in default_states.iteritems():
                # compare keys containing a default state with items that exist in the edit menu or others
                # specified and restore them
                box.saved_states[k] = v

            sysCmd.channelbox_pickle_delete_state(box)
            # box.re_init(box)  # re-initialize to update our changes in the display
            cmds.warning("Please close the ChannelBox UI and re-open it for changes to take effect")
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def combine(nodes):
    """Produce a new mesh with the contents of `nodes`

    Arguments:
        nodes (list): Path to shapes

    """

    unite = cmds.createNode("polyUnite", n=nodes[0] + "_polyUnite")

    count = 0
    for node in nodes:
        # Are we dealing with transforms, or shapes directly?
        shapes = cmds.listRelatives(node, shapes=True) or [node]

        for shape in shapes:
            try:
                cmds.connectAttr(shape + ".outMesh",
                                 unite + ".inputPoly[%s]" % count, force=True)
                cmds.connectAttr(shape + ".worldMatrix",
                                 unite + ".inputMat[%s]" % count, force=True)
                count += 1

            except Exception:
                cmds.warning("'%s' is not a polygonal mesh" % shape)

    if count:
        output = cmds.createNode("mesh", n=nodes[0] + "_combinedShape")
        cmds.connectAttr(unite + ".output", output + ".inMesh", force=True)
        return output

    else:
        cmds.delete(unite)
        return None
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def parent_group(source, transferTransform=True):
    """Create and transfer transforms to parent group"""
    assert cmds.objExists(source), "%s does not exist" % source
    assert cmds.nodeType(source) == "transform", (
        "%s must be transform" % source)

    parent = cmds.listRelatives(source, parent=True)

    if transferTransform:
        group = cmds.createNode("transform", n="%s_parent" % source)
        match_transform(group, source)

        try:
            cmds.parent(source, group)
        except Exception:
            cmds.warning("Failed to parent child under new parent")
            cmds.delete(group)

        if parent:
            cmds.parent(group, parent[0])

    else:
        cmds.select(source)
        group = cmds.group(n="%s_parent" % source)

    return group
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def connect_matching_attributes(source, target):
    """Connect matching attributes from source to target

    Arguments:
        source (str): Absolute path to node from which to connect
        target (str): Target node

    Example:
        >>> # Select two matching nodes
        >>> source = cmds.createNode("transform", name="source")
        >>> target = cmds.createNode("transform", name="target")
        >>> cmds.select([source, target], replace=True)
        >>> source, target = cmds.ls(selection=True)
        >>> connect_matching_attributes(source, target)

    """

    dsts = cmds.listAttr(target, keyable=True)
    for src in cmds.listAttr(source, keyable=True):
        if src not in dsts:
            continue

        try:
            src = "." + src
            cmds.connectAttr(source + src,
                             target + src,
                             force=True)
        except RuntimeError as e:
            cmds.warning("Could not connect %s: %s" % (src, e))
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def transfer_outgoing_connections(*args):
    """Connect outgoing connections from first to second selected node"""

    try:
        src, dst = cmds.ls(selection=True)
    except ValueError:
        return cmds.warning("Select source and destination nodes")

    commands.transfer_outgoing_connections(src, dst)
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def auto_connect(*args):
    """Connect `src` to `dst` via the most likely input and output"""
    try:
        commands.auto_connect(*cmds.ls(selection=True))
    except TypeError:
        cmds.warning("Select only source and destination nodes.")
项目:maya-pulse    作者:bohdon    | 项目源码 | 文件源码
def setPresetColor(widget, preset):
        """
        Apply a preset color to the given widget using style sheets

        Args:
            widget: A QWidget to apply styling to
            preset: A string name of the preset color
        """
        if preset in DesignViewPanel.PRESET_COLORS:
            widget.setStyleSheet('background-color: {0};'.format(DesignViewPanel.PRESET_COLORS[preset]))
        else:
            cmds.warning('preset color not found: `{0}`'.format(preset))
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def BT_DisconnectSetup(set = None):

    if not set:
        return False

    if not BT_IsSetupConnected(set = set):
        cmds.warning('Setup already disconnected!')
        return False

    btNode = cmds.getAttr(set +'.Blend_Node')
    if not btNode or not cmds.objExists(btNode):
        return False

    numOutputs = cmds.getAttr(btNode +'.output', size = True)
    print numOutputs
    tempMult = None
    for i in range(0, numOutputs):

        conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputT', s = False, d = True)
        if conns:
            tempMult = cmds.createNode('multiplyDivide')
            cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputT', conns[0] +'.translate')
            cmds.connectAttr(btNode +'.output[' +str(i) +'].outputT', tempMult +'.input1')

        conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputR', s = False, d = True)
        if conns:
            tempMult = cmds.createNode('multiplyDivide')
            cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputR', conns[0] +'.rotate')
            cmds.connectAttr(btNode +'.output[' +str(i) +'].outputR', tempMult +'.input1')

        conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputS', s = False, d = True)
        if conns:
            tempMult = cmds.createNode('multiplyDivide')
            cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputS', conns[0] +'.scale')
            cmds.connectAttr(btNode +'.output[' +str(i) +'].outputS', tempMult +'.input1')

    cmds.select(cl = True)

    return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def __init__( self, parent = BT_GetMayaWindow() ):
        super(BT_UIForm, self).__init__(parent)

        uicPath = BT_FindUIFile()

        if not uicPath:
            return None

        self.ui = None
        if BT_MayaVersionNumber < 2014:
            self.ui = uic.loadUi(uicPath, self)
        else:
            loader = QtUiTools.QUiLoader()
            self.ui = loader.load(uicPath, self)

        self.ui.loadSelectedButton.clicked.connect(self.loadSelectedSet)
        self.ui.connectButton.clicked.connect(self.connectSetup)
        self.ui.disconnectButton.clicked.connect(self.disconnectSetup)
        self.ui.setToBaseButton.clicked.connect(self.setToBasePose)
        self.ui.setToSelectedButton.clicked.connect(self.setToPose)
        self.ui.addPoseButton.clicked.connect(self.addPose)
        self.ui.deletePoseButton.clicked.connect(self.deletePose)
        self.ui.updateSelectedButton.clicked.connect(self.updatePose)

        unitResult = BT_SetUnits()
        if unitResult:
            QtGui.QMessageBox.warning(self, "Blend Transforms", "Units set to centimetres.", "Okay")

        self.ui.show()
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def BT_DisconnectSetup(set = None):

    if not set:
        return False

    if not BT_IsSetupConnected(set = set):
        cmds.warning('Setup already disconnected!')
        return False

    btNode = cmds.getAttr(set +'.Blend_Node')
    if not btNode or not cmds.objExists(btNode):
        return False

    numOutputs = cmds.getAttr(btNode +'.output', size = True)
    print numOutputs
    tempMult = None
    for i in range(0, numOutputs):

        conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputT', s = False, d = True)
        if conns:
            tempMult = cmds.createNode('multiplyDivide')
            cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputT', conns[0] +'.translate')
            cmds.connectAttr(btNode +'.output[' +str(i) +'].outputT', tempMult +'.input1')

        conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputR', s = False, d = True)
        if conns:
            tempMult = cmds.createNode('multiplyDivide')
            cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputR', conns[0] +'.rotate')
            cmds.connectAttr(btNode +'.output[' +str(i) +'].outputR', tempMult +'.input1')

        conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputS', s = False, d = True)
        if conns:
            tempMult = cmds.createNode('multiplyDivide')
            cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputS', conns[0] +'.scale')
            cmds.connectAttr(btNode +'.output[' +str(i) +'].outputS', tempMult +'.input1')

    cmds.select(cl = True)

    return True