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

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

项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def add_top_level_ctrl(origCtrl, type, geo, *args):
    """
    creates a new ctrl, orients it to the geo and parent constrains the orig ctrl rig under itself
    :param origCtrl: the control we're working from
    :param type: the ctrl type of shape see zbw_rig.createControl for options
    :param geo: the geo to orient to
    :param args:
    :return: topCtrl (the new ctrl), grp (the top ctrl grp freeze grp)
    """
    # THIS IS THE XTRA CTRL LAYER, THIS ORIENTS CTRL AND CONNECTS ORIG CTRL TO THE NEW CTRL
    origCtrlPos = cmds.xform(origCtrl, q=True, ws=True, rp=True)
    topCtrl = rig.createControl(name="{0}_moveCtrl".format(origCtrl.rpartition("_")[0]), type=type, axis="z",
                              color="yellow")
    grp = rig.groupFreeze(topCtrl)
    cmds.xform(grp, ws=True, t=origCtrlPos)
    nc = cmds.normalConstraint(geo, grp, worldUpType="vector", upVector=(0, 1, 0))
    cmds.delete(nc)
    pc = cmds.parentConstraint(topCtrl, origCtrl, mo=True)
    sc = cmds.scaleConstraint(topCtrl, origCtrl, mo=True)
    return(topCtrl, grp)
项目: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
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def make_planar(joints):
    for joint in joints:
        parent = cmds.listRelatives(joint, parent=True, path=True)
        if not parent:
            log.warning('Cannot make %s planar because it does not have a parent.', joint)
            continue
        children = _unparent_children(joint)
        if not children:
            log.warning('Cannot make %s planar because it does not have any children.', joint)
            continue
        cmds.delete(cmds.aimConstraint(children[0], joint, aim=(1, 0, 0), u=(0, 1, 0), worldUpType='object', worldUpObject=parent[0]))
        cmds.makeIdentity(joint, apply=True)
        _reparent_children(joint, children)

    if joints:
        cmds.select(joints)
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def align_with_child(joints):
    """Aligns the up axis of the given joints with their respective child joint.

    @param joints: List of joints to orient.
    """
    for joint in joints:
        children = _unparent_children(joint)
        if children:
            cmds.delete(cmds.aimConstraint(children[0], joint, aim=(1, 0, 0), upVector=(0, 1, 0),
                                           worldUpType="objectrotation", worldUpVector=(0, 1, 0),
                                           worldUpObject=children[0]))
            cmds.makeIdentity(joint, apply=True)
        _reparent_children(joint, children)

    if joints:
        cmds.select(joints)
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def create_curve(control):
    """Create a curve.

    :param control: A data dictionary generated from the dump function.
    :return: The created curve.
    """
    periodic = control['form'] == 2
    degree = control['degree']
    points = control['cvs']
    points = points + points[:degree] if periodic else points
    curve = cmds.curve(degree=degree, p=points, n=control['name'], per=periodic, k=control['knots'])
    cmds.xform(curve, ws=True, matrix=control['xform'])
    cmds.xform(curve, piv=control['pivot'])
    cmds.delete(curve, constructionHistory=True)
    cmds.setAttr('{0}.overrideEnabled'.format(curve), control['overrideEnabled'])
    cmds.setAttr('{0}.overrideRGBColors'.format(curve), control['overrideRGBColors'])
    cmds.setAttr('{0}.overrideColorRGB'.format(curve), *control['overrideColorRGB'])
    cmds.setAttr('{0}.overrideColor'.format(curve), control['overrideColor'])
    return curve
项目: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 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 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 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
项目:maya_rotationDriver    作者:ryusas    | 项目源码 | 文件源码
def doit(radius=5., num=36):
    cmds.loadPlugin('rotationDriver', qt=True)
    node = cmds.createNode('composeRotate')
    node_or = node + '.outRotate'
    node_h = node + '.bendH'
    node_v = node + '.bendV'

    shiftX = radius * 1.25

    top0 = _plotBendHV(node_or, node_h, node_v, 'plotStereoProj', radius, num)
    cmds.setAttr(top0 + '.tx', -shiftX)

    cmds.setAttr(node + '.method', 1)
    top1 = _plotBendHV(node_or, node_h, node_v, 'plotExpmap', radius, num)
    cmds.setAttr(top1 + '.tx', shiftX)

    cmds.delete(node)

    cmds.select([top0, top1])
项目:SETools    作者:dtzxporter    | 项目源码 | 文件源码
def ResetSceneAnim():
    # Loop through them all
    SceneJoints = cmds.ls(type="joint")
    # Loop
    for name in SceneJoints:
        # Disconnect if required
        ResetBoneKeyframes(DagPathFromJoint(name, False).transform())
        # Check for undo
        if (cmds.objExists(name + ".seanimUndoT")):
            # Reset to it
            ResetTranslation = cmds.getAttr(name + ".seanimUndoT")[0]
            ResetScale = cmds.getAttr(name + ".seanimUndoS")[0]
            ResetRotation = cmds.getAttr(name + ".seanimUndoR")[0]
            # Apply
            cmds.setAttr(name + ".t", ResetTranslation[0], ResetTranslation[1], ResetTranslation[2])
            cmds.setAttr(name + ".scale", ResetScale[0], ResetScale[1], ResetScale[2])
            cmds.setAttr(name + ".r", 0, 0, 0)
            cmds.setAttr(name + ".jo", ResetRotation[0], ResetRotation[1], ResetRotation[2])
    # Remove notetracks
    if cmds.objExists("SENotes"):
        # Delete
        cmds.delete("SENotes")

# Processes a joint, creating it's rest position, and returning a dag path
项目: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 groupOrient(target='none',orig='none', group="GRP"):
    """
    groups the second object and snaps the group to the second (point and orient). The group arg is to name the suffix you want the group to have (default is '_GRP')
    Arguments: target (to be constrained to), orig (obj to move), group (suffix for group)
    """
    if (target == "none"):
        sel = getTwoSelection()
        target = sel[0]
        orig = sel[1]

    cmds.select(orig)
    grpName = "%s_%s"%(orig,group)
    cmds.group(name=grpName)
    pc = cmds.pointConstraint(target, grpName)
    oc = cmds.orientConstraint(target, grpName)
    cmds.delete(pc)
    cmds.delete(oc)
    cmds.select(clear=True)

    return(grpName)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def positionsAlongCurve(crv="", numPts = 3, *args):
    """
    returns list of numPts evenly distributed world positions along given nurbs crv
    """
    if not crv:
        return

    if isType(crv, "nurbsCurve"):
        posList = []
        shp = cmds.listRelatives(crv, s=True)[0]
        poc = cmds.shadingNode("pointOnCurveInfo", asUtility=True, name="tmpPOCInfo")
        cmds.connectAttr("{}.local".format(shp), "{}.inputCurve".format(poc))
        cmds.setAttr("{}.turnOnPercentage".format(poc), 1)
        lineLen = cmds.arclen(crv, ch=False)
        dist = float(numPts)/lineLen

        for x in range(0, numPts+1):
            perc = 1.0/numPts
            cmds.setAttr("{}.parameter".format(poc),x*perc)
            print x*perc
            pos = cmds.getAttr("{}.position".format(poc))[0]
            posList.append(pos)

        cmds.delete(poc)
        return(posList)
项目:gozbruh    作者:LumaPictures    | 项目源码 | 文件源码
def create(obj):
    """Tell ZBrush to treat `obj` as a new object.

    Under the hood this changes a gozbruhBrush ID to match object name.
    """
    # does not change selection:
    cmds.delete(obj, constructionHistory=True)
    shape = cmds.ls(obj, type='mesh', dag=True)[0]
    xform = cmds.listRelatives(shape, parent=True, fullPath=True)[0]
    goz_check_xform = cmds.attributeQuery(
        'gozbruhBrushID', node=xform, exists=True)
    goz_check_shape = cmds.attributeQuery(
        'gozbruhBrushID', node=shape, exists=True)

    if goz_check_shape:
        cmds.setAttr(shape + '.gozbruhBrushID', obj, type='string')
    if goz_check_xform:
        cmds.setAttr(xform + '.gozbruhBrushID', obj, type='string')
    return xform
项目:gozbruh    作者:LumaPictures    | 项目源码 | 文件源码
def _cleanup(name):
    """Removes un-used nodes on import of obj
    """

    # Don't delete the old mesh if gozbruh_delete option var exists and is set to
    #     false, simply rename it
    if cmds.optionVar(ex='gozbruh_delete') and not cmds.optionVar(q='gozbruh_delete'):
        if cmds.objExists(name):
            cmds.rename(name, name + '_old')
    else:
        if cmds.objExists(name):
            cmds.delete(name)

    for node in GARBAGE_NODES:
        node = name + '_' + node
        if cmds.objExists(node):
            cmds.delete(node)

#------------------------------------------------------------------------------
# Helpers
#------------------------------------------------------------------------------
项目:maya_greenCageDeformer    作者:ryusas    | 项目源码 | 文件源码
def doit(cage_tgt=None):
    if not cage_tgt:
        cage_tgt = cmds.ls(sl=True, o=True)
    cage = cage_tgt[0]
    tgt = cage_tgt[1:]

    cmds.loadPlugin('greenCageDeformer.py', qt=True)
    deformer = cmds.deformer(tgt, type='greenCageDeformer')[0]

    freezer = cmds.createNode('transformGeometry')
    cmds.connectAttr(cage + '.o', freezer + '.ig')
    cmds.connectAttr(cage + '.wm', freezer + '.txf')
    cmds.connectAttr(freezer + '.og', deformer + '.bc')
    cmds.disconnectAttr(freezer + '.og', deformer + '.bc')
    cmds.delete(freezer)

    cmds.connectAttr(cage + '.w', deformer + '.ic')
    cmds.dgeval(cmds.listConnections(deformer + '.og', s=False, d=True, sh=True, p=True))


#doit([cmds.polyCube(w=2.5, d=2.5, h=2.5)[0], cmds.polySphere()[0]])
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def ui():
    '''
    User interface for arc tracer
    '''

    globalScale = 1
    if mc.optionVar(exists='ml_arcTracer_brushGlobalScale'):
        globalScale = mc.optionVar(query='ml_arcTracer_brushGlobalScale')       

    with utl.MlUi('ml_arcTracer', 'Arc Tracer', width=400, height=180, info='''Select objects to trace.
Choose camera space or worldspace arc.
Press clear to delete the arcs, or retrace to redo the last arc.''') as win:

        win.buttonWithPopup(label='Trace Camera', command=traceCamera, annotation='Trace an arc as an overlay over the current camera.', 
                            shelfLabel='cam', shelfIcon='flowPathObj')#motionTrail
        win.buttonWithPopup(label='Trace World', command=traceWorld, annotation='Trace an arc in world space.', 
                            shelfLabel='world', shelfIcon='flowPathObj')
        win.buttonWithPopup(label='Retrace Previous', command=retraceArc, annotation='Retrace the previously traced arc.', 
                            shelfLabel='retrace', shelfIcon='flowPathObj')
        win.buttonWithPopup(label='Clear Arcs', command=clearArcs, annotation='Clear all arcs.', 
                            shelfLabel='clear', shelfIcon='flowPathObj')
        fsg = mc.floatSliderGrp( label='Line Width', minValue=0.1, maxValue=5, value=globalScale)
        mc.floatSliderGrp(fsg, edit=True, dragCommand=partial(setLineWidthCallback, fsg))
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def snap(node, snapTo):

    #duplicate the node we want snap
    dup = mc.duplicate(node, parentOnly=True)[0]
    #unlock translates and rotates
    for a in ('.t','.r'):
        for b in 'xyz':
            mc.setAttr(dup+a+b, lock=False)

    mc.parentConstraint(snapTo, dup)

    for a in ('.t','.r'):
        for b in ('x','y','z'):
            try:
                mc.setAttr(node+a+b, mc.getAttr(dup+a+b))
            except StandardError:
                pass

    mc.delete(dup)
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def copySkinComponents(source, destinationVerts):

    if not mc.listRelatives(source, shapes=True):
        raise RuntimeError('Source object must be geometry.')

    sourceSkin = getSkinCluster(source)

    if not sourceSkin:
        raise RuntimeError("Source mesh doesn't have a skinCluster to copy from.")

    destMesh = mc.ls(destinationVerts[0], o=True)[0]
    destMesh = mc.listRelatives(destMesh, parent=True)[0]
    destSkin = copySkinInfluences(source, destMesh)

    tempSet = mc.sets(destinationVerts)

    mc.select(source, tempSet)

    mc.copySkinWeights(noMirror=True,
                       surfaceAssociation='closestPoint', 
                       influenceAssociation='closestJoint', 
                       normalize=True)    

    mc.delete(tempSet)
    mc.select(destinationVerts)
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def minimizeRotationCurves(obj):
    '''
    Sets rotation animation to the value closest to zero.
    '''

    rotateCurves = mc.keyframe(obj, attribute=('rotateX','rotateY', 'rotateZ'), query=True, name=True)

    if not rotateCurves or len(rotateCurves) < 3:
        return

    keyTimes = mc.keyframe(rotateCurves, query=True, timeChange=True)
    tempFrame = sorted(keyTimes)[0] - 1

    #set a temp frame
    mc.setKeyframe(rotateCurves, time=(tempFrame,), value=0)

    #euler filter
    mc.filterCurve(rotateCurves)

    #delete temp key
    mc.cutKey(rotateCurves, time=(tempFrame,))
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def cutKey(self, includeSubFrames=False, **kwargs):
        '''
        Wrapper for the cutKey command. Curve and time arguments will be provided based on 
        how this object was intitialized, otherwise usage is the same as maya's cutKey command.
        Option to delete sub-frames.
        '''

        if not 'includeUpperBound' in kwargs:
            kwargs['includeUpperBound'] = False

        if self.selected:
            mc.cutKey(sl=True, **kwargs)
            return

        if not 'time' in kwargs:
            if includeSubFrames:
                kwargs['time'] = (round(self.time[0])-0.5, round(self.time[-1])+0.5)
            else:
                kwargs['time'] = self.time
        mc.cutKey(self.curves, **kwargs)
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def cleanup(self):
        '''
        Clean up the mess we made.
        '''
        try:
            mc.lockNode(self.pivotHandle, lock=False)
            mc.delete(self.pivotHandle)
        except: pass

        try:
            if mc.scriptJob(exists=self.scriptJob):
                mc.scriptJob(kill=self.scriptJob, force=True)
        except: pass

        pivotHandles = mc.ls('*.ml_pivot_handle', o=True)
        if pivotHandles:
            for each in pivotHandles:
                mc.lockNode(each, lock=False)
                mc.delete(each)
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def match_transform(src, dst):
    """Transform `src` to `dst`, taking worldspace into account

    Arguments:
        src (str): Absolute path to source transform
        dst (str): Absolute path to destination transform

    """

    try:
        parent = cmds.listRelatives(src, parent=True)[0]
    except Exception:
        parent = None

    node_decompose = cmds.createNode("decomposeMatrix")
    node_multmatrix = cmds.createNode("multMatrix")

    connections = {
        dst + ".worldMatrix": node_multmatrix + ".matrixIn[0]",
        node_multmatrix + ".matrixSum": node_decompose + ".inputMatrix",
        node_decompose + ".outputTranslate": src + ".translate",
        node_decompose + ".outputRotate": src + ".rotate",
        node_decompose + ".outputScale": src + ".scale",
    }

    if parent:
        connections.update({
            parent + ".worldInverseMatrix": node_multmatrix + ".matrixIn[1]"
        })

    for s, d in connections.iteritems():
        cmds.connectAttr(s, d, force=True)

    cmds.refresh()

    cmds.delete([node_decompose, node_multmatrix])
项目: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
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def get_knots(curve):
    """Gets the list of knots of a curve so it can be recreated.

    :param curve: Curve to query.
    :return: A list of knot values that can be passed into the curve creation command.
    """
    curve = shortcuts.get_shape(curve)
    info = cmds.createNode('curveInfo')
    cmds.connectAttr('{0}.worldSpace'.format(curve), '{0}.inputCurve'.format(info))
    knots = cmds.getAttr('{0}.knots[*]'.format(info))
    cmds.delete(info)
    return knots
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def create_transform_stack(node, count=2):
    """Creates a transform stack above the given node.

    Any previous transform stack will be deleted.

    :param node: Node to parent into a transform stack.
    :param count: Number of transforms to add in the stack.
    :return: A list of the transform nodes created starting from top to bottom.
    """
    previous_parent = cmds.listRelatives(node, parent=True, path=True)
    if previous_parent:
        previous_parent = previous_parent[0]
        while previous_parent and STACK_ATTRIBUTE in (cmds.listAttr(previous_parent, ud=True) or []):
            parent = cmds.listRelatives(previous_parent, parent=True, path=True)
            if parent:
                cmds.parent(node, parent)
                parent = parent[0]
            else:
                cmds.parent(node, world=True)
            cmds.delete(previous_parent)
            previous_parent = parent

    nulls = []
    for i in reversed(range(count)):
        name = '_'.join(node.split('_')[:-1])
        name = '{0}_{1}nul'.format(name, i+1)
        null = cmds.createNode('transform', name=name)
        nulls.append(null)
        cmds.addAttr(null, ln=STACK_ATTRIBUTE, at='message')
        cmds.connectAttr('{0}.message'.format(node), '{0}.{1}'.format(null, STACK_ATTRIBUTE))
        cmds.delete(cmds.parentConstraint(node, null))
        if previous_parent:
            cmds.parent(null, previous_parent)
        previous_parent = null
    cmds.parent(node, previous_parent)
    return nulls
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def setUp(self):
        self.joint1 = cmds.joint(p=(-0.5, -0.5, 0))
        self.joint2 = cmds.joint(p=(0, 0.0, 0))
        self.joint3 = cmds.joint(p=(0.5, 0.5, 0))
        self.shape = cmds.polyCube()[0]
        cmds.delete(self.shape, ch=True)
        self.skin = cmds.skinCluster(self.joint1, self.joint2, self.joint3, self.shape)[0]
        self.expected = {
            'bindMethod': 1,
            'blendWeights': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
            'dropoffRate': 4.0,
            'heatmapFalloff': 0.0,
            'maintainMaxInfluences': False,
            'maxInfluences': 2,
            'name': u'skinCluster1',
            'normalizeWeights': 1,
            'shape': u'pCube1',
            'skinningMethod': 0,
            'useComponents': False,
            'weightDistribution': 0,
            'weights': {
                u'joint1': [0.9, 0.5, 0.5, 0.0, 0.5, 0.0, 0.9, 0.5],
                u'joint2': [0.10000000000000002,
                            0.5,
                            0.5,
                            0.5,
                            0.5,
                            0.5,
                            0.10000000000000002,
                            0.5],
                u'joint3': [0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0]}
        }
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def test_import_skin(self):
        file_path = self.get_temp_filename('temp.skin')
        skinio.export_skin(file_path, self.shape)
        cmds.delete(self.skin)
        skinio.import_skin(file_path)
        self.assertTrue(cmds.objExists(self.skin))
项目:OpenTimelineIO    作者:PixarAnimationStudios    | 项目源码 | 文件源码
def build_sequence(timeline, clean=False):
    existing_shots = cmds.ls(type='shot') or []
    if clean:
        cmds.delete(existing_shots)
        existing_shots = []

    tracks = [
        track for track in timeline.tracks
        if track.kind == otio.schema.TrackKind.Video
    ]

    for track_no, track in enumerate(reversed(tracks)):
        _build_track(track, track_no, existing_shots=existing_shots)
项目:SETools    作者:dtzxporter    | 项目源码 | 文件源码
def DeleteMenu():
    # Check for existing control, remove it if we can
    if cmds.control(MENU_DATA['menu'][0], exists=True):
        # Found it, delete it
        cmds.deleteUI(MENU_DATA['menu'][0], menu=True)

# Create the menu
项目:SETools    作者:dtzxporter    | 项目源码 | 文件源码
def CreateMenu():
    # Set the diplay's parent
    cmds.setParent(mel.eval("$temp1=$gMainWindow"))

    # Purge old one
    DeleteMenu()

    # Make new menu
    menu = cmds.menu(MENU_DATA['menu'][0], label=MENU_DATA["menu"][1], tearOff=True)    # Recreate the base
    # Add children
    cmds.menuItem(label="Import <- SEAnim", command=lambda x:ImportSEAnim(), annotation="Imports a SEAnim, resetting the scene first")
    cmds.menuItem(label="Import and Blend <- SEAnim", command=lambda x:ImportMergeSEAnim(), annotation="Imports a SEAnim without resetting the scene (Blending the animations together)")
    cmds.menuItem(divider=True)
    cmds.menuItem(label="Export -> SEAnim", command=lambda x:ExportEntireSceneAnim(), annotation="Exports all joints, or all selected joints to a SEAnim file")
    cmds.menuItem(divider=True)
    cmds.menuItem(label="Clean Namespaces", command=lambda x:NamespaceClean(), annotation="Removes all namespaces from the scene")
    cmds.menuItem(label="Place Notetrack", command=lambda x:PlaceNote(), annotation="Places a notetrack at the current scene time")
    cmds.menuItem(label="Select All Joints", command=lambda x:SelectAllJoints(), annotation="Selects all joints")
    cmds.menuItem(label="Select Keyed Joints", command=lambda x:SelectKeyframes(), annotation="Selects keyed joints, this feature does not work with conversion rigs")
    cmds.menuItem(divider=True)
    cmds.menuItem(label="Reset Scene", command=lambda x:ResetSceneAnim(), annotation="Manually reset the scene to bind position")
    cmds.menuItem(label="Clear Curves", command=lambda x:PurgeAllKeyframes(), annotation="Manually delete all cached keyframe curves in the scene")
    cmds.menuItem(divider=True)
    game_menu = cmds.menuItem(label="Game Specific Tools", subMenu=True)    # Make game specific submenu
    cmds.menuItem(label="Call of Duty", subMenu=True)
    cmds.menuItem(label="Attach Weapon to Rig", command=lambda x:WeaponBinder(), annotation="Attatches the weapon to the viewhands, does not work properly with conversion rigs")
    cmds.setParent(game_menu, menu=True)    # Close out menu (Call of Duty)
    cmds.setParent(menu, menu=True)         # Close out menu (Game tools)
    cmds.menuItem(divider=True)
    cmds.menuItem(label="Reload Plugin", command=lambda x:ReloadMayaPlugin(), annotation="Attempts to reload the plugin")
    cmds.menuItem(label="About", command=lambda x:AboutWindow())

# Reloads a maya plugin
项目:SETools    作者:dtzxporter    | 项目源码 | 文件源码
def PurgeAllKeyframes():
    # Grab existing curves
    ExistingFrames = cmds.ls(type="animCurveTA") + cmds.ls(type="animCurveTL")
    # Iterate and remove
    for KeyCurve in ExistingFrames:
        # Delete it
        cmds.delete(KeyCurve)

# Resets a bones keyframes
项目:mayakit    作者:danbradham    | 项目源码 | 文件源码
def conform_curve(source, destination):

    point_on_curve = cmds.createNode('nearestPointOnCurve')
    cmds.connectAttr(destination + '.worldSpace', point_on_curve + '.inputCurve')

    for i, point in enumerate(cmds.getAttr(source + '.cv[*]')):
        cmds.setAttr(point_on_curve + '.inPosition', point[0], point[1], point[2])
        result_point = cmds.getAttr(point_on_curve + '.result.position')[0]
        cmds.setAttr('{}.cv[{}]'.format(source, i), result_point[0], result_point[1], result_point[2])
    cmds.delete(point_on_curve)
项目:dm2skin    作者:duncanskertchly    | 项目源码 | 文件源码
def deleteMush(self):
        mesh = self.sourceField.text()
        if not mesh:
            return
        if not cmds.objExists(mesh + '_Mush'):
            return
        cmds.delete(mesh + '_Mush')
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def zbw_swapRotateOrder():

    #find frame range from slider
    startF = cmds.playbackOptions (query=True, minTime=True)
    endF = cmds.playbackOptions (query=True, maxTime=True)

    objs = cmds.ls (selection=True)
    #dummy check for two objects!    
    objA = objs[0]
    objB = objs[1]

    #get list of keys to use
    keysAtFull = cmds.keyframe (objA, query=True, time=(startF,endF), attribute=('tx','ty','tz','rx','ry','rz'))
    keysSet = set(keysAtFull)    
    keyList=[]
    for key in keysSet:
        keyList.append(key)
    keyList.sort()
    #print keyList

    for thisKey in keyList: #populate the dictionary with the key values
        cmds.currentTime(thisKey) #set currentTime to the value
        cmds.pointConstraint(objA, objB, name="pointConst")#pointConstriain B to A
        cmds.orientConstraint(objA, objB, name="orientConst")#orientConstan B to A
        getRot() #getData() for B and puts it in keyBuffer
        getTrans() #gets tranlslation data for same
        cmds.delete('pointConst','orientConst') # delete the constaints on B

    #since I can't add the keys while I"m constraining, do it now from dictionary   
    for newKey in keyList:
        objRot = rotBuffer[newKey]
        objTrans = transBuffer[newKey]
        cmds.setKeyframe( objB, t=newKey,at='tx', v=objTrans[0]) #set keys for B on all the frames in keyBuffer to values in keyBuffer
        cmds.setKeyframe( objB,t=newKey,at='ty', v=objTrans[1])
        cmds.setKeyframe( objB,t=newKey,at='tz', v=objTrans[2])
        cmds.setKeyframe( objB,t=newKey,at='rx', v=objRot[0])
        cmds.setKeyframe( objB,t=newKey,at='ry', v=objRot[1])
        cmds.setKeyframe( objB,t=newKey,at='rz', v=objRot[2])

    cmds.filterCurve((objB+'_rotateX'), (objB+'_rotateY'), (objB+'_rotateZ' ))  #run Euler filter on curves for rotation?
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def deleteRig(*args):
    # check for ctrl
    sel = cmds.ls(sl=True, type="transform")
    if sel:
        for ctrl in sel:
            # try
            rpt = cmds.connectionInfo("{0}.rptMult".format(ctrl), sfd=True).partition(".")[0]
            dens = cmds.connectionInfo("{0}.densMult".format(ctrl), sfd=True).partition(".")[0]
            curve = cmds.connectionInfo("{0}.origCrv".format(ctrl), sfd=True).partition(".")[0]
            para = cmds.connectionInfo("{0}.paraMult".format(ctrl), sfd=True).partition(".")[0]

            if rig.parentCheck(curve):
                cmds.parent(curve, world=True)
            cmds.setAttr("{0}.v".format(curve), 1)

            # check for file node, grab it, then find p2d from that and delete it
            fTextFull = cmds.connectionInfo("{0}.fileTexture".format(ctrl), sfd=True)
            print
            "fTextFull:", fTextFull
            if fTextFull:
                fText = fTextFull.partition(".")[0]
                print
                fText
                p2dFull = cmds.connectionInfo("{0}.uvCoord".format(fText), sfd=True)
                print
                p2dFull
                if p2dFull:
                    p2d = p2dFull.partition(".")[0]
                    cmds.delete(p2d)
                print
                "ready to delete"
                cmds.delete(fText)

            cmds.delete([ctrl, rpt, dens, para])
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def alignToUV(targetObj="none", sourceObj="none", sourceU=0.0, sourceV=0.0, mainAxis="+z", secAxis="+x", UorV="v"):
    """
    inputs should be 1. targetObj 2. sourceObj 3. sourceU 4. sourceV 5. mainAxis(lowerCase, + or -, i.e."-x" 8. secAxis (lowcase, + or -) 7, UorV ("u" or "v" for the direction along surface for the sec axis)
"""

    axisDict = {"+x":(1,0,0), "+y":(0,1,0), "+z":(0,0,1), "-x":(-1,0,0), "-y":(0,-1,0), "-z":(0,0,-1)}

    #Does this create a new node? no To create a node, use the flag "ch=True". That creates a pointOnSurface node
    pos = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, position=True)
    posVec = om.MVector(pos[0], pos[1], pos[2])
    cmds.xform(targetObj, ws=True, t=pos)

    #get normal, tanU and tanV at selected UV position on source surface
    tanV = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, tv=True)
    tanU = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, tu=True)
    norm = cmds.pointOnSurface(sourceObj, u=sourceU, v=sourceV, nn=True)

    #decide where up axis is on normal constraint, u or v tangent
    if UorV == "v":
        wup = tanV
    elif UorV == "u":
        wup = tanU

    #create normal constraint
    nc = cmds.normalConstraint(sourceObj, targetObj, aimVector=axisDict[mainAxis], upVector=axisDict[secAxis], worldUpVector=(wup))
    cmds.delete(nc) #delete constraint
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def swapDupe(obj, target, delete = True, name="", *args):
    """
    replaces an target with a duplicate of the obj
    select the object you want to duplicate, then the target(s), delete bool, name optional
    [obj] is the object to duplicate
    [target] is the target to match and delete(?)
    [delete] is bool to tell whether to delete the target or not
    [name] is string to rename to
    """

    if not name:
        name = obj

    # get pos, rot, scale of target
    pos = cmds.xform(target, q=True, ws=True, rp=True)
    rot = cmds.xform(target, q=True, ws=True, ro=True)
    scl = cmds.getAttr("{0}.scale".format(target))

    # duplicate the object and rename to name, if no name just use unique names
    dupe = cmds.duplicate(obj, name=name, returnRootsOnly=True, renameChildren=True)
    cmds.xform(dupe, ws=True, t=pos)
    cmds.xform(dupe, ws=True, ro=rot)
    cmds.xform(dupe, ws=True, s=scl[0])

    parent = cmds.listRelatives(target, parent=True)
    if parent:
        cmds.parent(dupe, parent[0])

    if delete:
        cmds.delete(target)

    return(dupe[0])
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def closest_pt_on_mesh_rotation(point, mesh, *args):
# TODO - generalize for various orientations, and various rotation orders
    """
    takes a point (can be name of transform or iterable(3) of rotations and a poly mesh and gives the rotation [rot
    order xyz] (for
    aim along y) align to surface of
    the xform at that point
    """
    if isinstance(point, basestring):
        if isType(point, "transform"):
            cmds.select(point, r=True)
            ptPos = cmds.xform(point, ws=True, q=True, rp=True)
            name = point
        else:
            cmds.warning("zbw_rig.closest_pt_on_mesh_position: the string you gave me isn't a transform")
            return ()
    elif isinstance(point, (list, tuple)):
        if len(point) == 3:
            ptPos = point
            name = mesh
        else:
            cmds.warning("zbw_rig.closest_pt_on_mesh_position: there are not the right number of entries in the "
                         "list you gave me")

    # get the rotations to align to normal at this point
    loc = cmds.spaceLocator()
    CPOMesh = closest_pt_on_mesh_position(point, mesh)
    cmds.xform(loc, ws=True, t=CPOMesh)
    aimVec = (0, 1, 0)
    upVec = (0, 1, 0)
    nc = cmds.normalConstraint(mesh, loc, aim=aimVec, upVector=upVec)
    rot = cmds.xform(loc, ws=True, q=True, ro=True)
    cmds.delete(nc, loc)
    return (rot)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def deleteAll(*args):
    """deletes all audio in the scene"""

    nodes = cmds.textScrollList(widgets["audioTSL"], q=True, ai=True)
    for node in nodes:
        cmds.delete(node)
    cmds.textScrollList(widgets["audioTSL"], e=True, ra=True)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def dupeIt(*args):
    """uses the first selection and duplicates it to the transforms of the rest of the selected objects, with or without connections"""

    sel=cmds.ls(sl=True, type="transform", l=True)
    inputs = cmds.radioButtonGrp("inputsRBG", q=True, sl=True)
    if sel:
        base=sel[0]
        if len(sel)>1:
            objs=sel[1:]
            transforms = {}
            x=0

            for obj in objs:
                #get pos, rot, scale
                pos = cmds.xform(obj, ws=True, q=True, t=True)
                rot = cmds.xform(obj, ws=True, q=True, ro=True)
                scal = cmds.getAttr("%s.scale"%obj)[0]
                transforms[x] = [pos, rot, scal]

                #delete the obj
                cmds.delete(obj)
                x=x+1

            for key in transforms.keys():
                if inputs == 1:
                    dupe = cmds.duplicate(base)[0]
                elif inputs == 3:
                    dupe = cmds.duplicate(base, un=True, rr=True)[0]
                elif inputs == 2:
                    dupe = cmds.duplicate(base, ic=True)[0]
                print dupe
                cmds.xform(dupe, ws=True, t=transforms[key][0])
                cmds.xform(dupe, ws=True, ro=transforms[key][1])
                cmds.setAttr("%s.scale"%dupe, transforms[key][2][0], transforms[key][2][1], transforms[key][2][2])

#TODO - checkbox to copy inputs on orig objects to corresponding inputs on top level of duplicates

        else:
            cmds.warning("You need to select more than one object in order to swap!")
    else:
        cmds.warning("Please select some transform nodes to dupe!")
项目:core    作者:getavalon    | 项目源码 | 文件源码
def unlock():
    """Permanently unlock a locked scene

    Doesn't throw an error if scene is already unlocked.

    """

    try:
        cmds.delete("lock")
    except ValueError:
        pass
项目:core    作者:getavalon    | 项目源码 | 文件源码
def remove(container):
    """Remove an existing `container` from Maya scene

    Deprecated; this functionality is replaced by `api.remove()`

    Arguments:
        container (avalon-core:container-1.0): Which container
            to remove from scene.

    """

    node = container["objectName"]

    # Assume asset has been referenced
    reference_node = next((node for node in cmds.sets(node, query=True)
                          if cmds.nodeType(node) == "reference"), None)

    assert reference_node, ("Imported container not supported; "
                            "container must be referenced.")

    log.info("Removing '%s' from Maya.." % container["name"])

    namespace = cmds.referenceQuery(reference_node, namespace=True)
    fname = cmds.referenceQuery(reference_node, filename=True)
    cmds.file(fname, removeReference=True)

    try:
        cmds.delete(node)
    except ValueError:
        # Already implicitly deleted by Maya upon removing reference
        pass

    try:
        # If container is not automatically cleaned up by May (issue #118)
        cmds.namespace(removeNamespace=namespace, deleteNamespaceContent=True)
    except RuntimeError:
        pass
项目:gozbruh    作者:LumaPictures    | 项目源码 | 文件源码
def relink(obj, goz_id):
    """Relink object name with existing gozbruhBrushID.
    """
    # manages re linking gozbruhBrush IDs, checks for attribute on shape/xform

    # in the case of a object being duplicated this removes the duplicate
    # to prevent deletion, the 'create' option is prefered
    # is only happens when an object was duplicated and merged (original
    # still exists)
    if cmds.objExists(goz_id):
        cmds.delete(goz_id)

    cmds.rename(obj, goz_id)
    return create(goz_id)
项目:ModularChannelBox    作者:Vaei    | 项目源码 | 文件源码
def channelbox_command_break(box, menuItem, key, *args):
    with sysCmd.Undo():
        for plug in channelBox_SelectedPlugs(box):
            if cmds.connectionInfo(plug, isDestination=1):
                destination = cmds.connectionInfo(plug, getExactDestination=1)

                # when delete source conn from character, must remove from character set or set becomes inconsistent
                src_conn = cmds.listConnections(destination, s=1, d=0, type="character")
                if src_conn:
                    warn_msg = "Removed \'^1s\' from character \'^2s\'."
                    cmds.warning(cmds.format(warn_msg, s=(destination, src_conn[0])))
                    cmds.character(destination, e=1, rm=src_conn[0])

                # is tracking edits?
                import maya.api.OpenMaya as om
                obj = om.MSelectionList().add(destination).getDependNode(0)
                depend_fn = om.MFnDependencyNode(obj)
                tracking_edits = depend_fn.isTrackingEdits()
                del obj
                del depend_fn

                if tracking_edits:
                    src = cmds.connectionInfo(destination, sourceFromDestination=1)
                    cmds.disconnectAttr(src, destination)
                else:
                    cmds.delete(destination, icn=1)
项目:ModularChannelBox    作者:Vaei    | 项目源码 | 文件源码
def channelbox_command_deleteNode(box, menuItem, key, *args):
    cmds.delete(cmds.channelBox(box.channelbox, q=1, historyObjectList=1),
                cmds.channelBox(box.channelbox, q=1, outputObjectList=1))
项目:3D_Software_and_Python    作者:p4vv37    | 项目源码 | 文件源码
def create_and_animate_trees():
    """
    Function uses the create_palm() support function to create and animate some palm trees.
    It was created to show how to create basic geometry objects, use instances and use modificators.
    """

    palm1 = create_palm(diameter=1.3, segs_num=20, leafs_num=9, bending=34, id_num=1, anim_start=11, anim_end=26)
    palm2 = create_palm(diameter=1.6, segs_num=20, leafs_num=9, bending=34, id_num=2, anim_start=40, anim_end=45)
    palm3 = create_palm(diameter=1.1, segs_num=18, leafs_num=9, bending=24, id_num=3, anim_start=20, anim_end=35)
    palm4 = create_palm(diameter=1.1, segs_num=24, leafs_num=9, bending=24, id_num=4, anim_start=25, anim_end=40)

    cmds.currentTime(55) # The removal of history had strange effect when it was applied before tree animation
    # Next line is intended to avoid a bug. If the history has to be deleted with a cmds.delete function. If it
    # would not be modified then the bend modifictor would have to be moved wit an object or it would affect an object
    # in different ways then desired during a changes in its position. The problem is, that during that an evaluation
    # of commands may take some time and the removing of history resulted in not deformed mesh or a partialy
    # deformed mesh. This is why cmds.refresh() ommand was used.
    cmds.refresh(f=True)

    cmds.delete(palm1, ch=True)
    cmds.rotate(0.197, 105, 0.558, palm1, absolute=True)  # Rotate the palm
    cmds.move(-8.5, -4.538, 18.1, palm1, absolute=True)  # Position the palm
    cmds.parent(palm1, 'land', relative=True) # Rename it

    cmds.delete(palm2, ch=True)
    cmds.rotate(-16.935, 74.246, -23.907, palm2)
    cmds.move(29.393, -3.990, 4.526, palm2)
    cmds.parent(palm2, 'land', relative=True)

    cmds.delete(palm3, ch=True)
    cmds.move(24.498, -3.322, 36.057, palm3)
    cmds.rotate(0.023, 0.248, -1.950, palm3)
    cmds.parent(palm3, 'land', relative=True)

    cmds.delete(palm4, ch=True)
    cmds.move(4.353, -1.083, 22.68, palm4)
    cmds.rotate(-150, -102.569, 872.616, palm4)
    cmds.parent(palm4, 'land', relative=True)