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

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

项目:PythonForMayaSamples    作者:dgovil    | 项目源码 | 文件源码
def saveScreenshot(self, name, directory=DIRECTORY):
        path = os.path.join(directory, '%s.jpg' % name)

        # We'll fit the view to the objects in our scene or our selection
        cmds.viewFit()

        # We'll change our render format to jpg
        cmds.setAttr("defaultRenderGlobals.imageFormat", 8) # This is the value for jpeg

        # Finally we'll save out our image using the playblast module
        # There are a lot of arguments here so it's good to use the documentation to know what's going on
        cmds.playblast(completeFilename=path, forceOverwrite=True, format='image', width=200, height=200,
                       showOrnaments=False, startTime=1, endTime=1, viewer=False)

        # Return the path of the file we saved
        return path


# This will be our first Qt UI!
# We'll be creating a dialog, so lets start by inheriting from Qt's QDialog
项目:PythonForMayaSamples    作者:dgovil    | 项目源码 | 文件源码
def modifyExtrude(self, teeth=10, length=0.3):
        faces = self.getTeethFaces(teeth)

        # The extrude node has an attribute called inputComponents
        # To change it we can use a simple setAttr call instead of recreating the extrude which can be expensive
        # The arguments to changing a list of components is slightly different than a simple setAttr
        # it is:
        #   cmds.setAttr('extrudeNode.inputComponents', numberOfItems, item1, item2, item3, type='componentList')
        cmds.setAttr('%s.inputComponents' % self.extrude, len(faces), *faces, type='componentList')

        # The *faces will be new to you.
        # It basically means to expand a list in place for arguments
        # so if the list has ['f[1]', 'f[2]'] etc, it will be expanded in the arguments to be like this
        # cmds.setAttr('extrudeNode.inputComponents', 2, 'f[1]', 'f[2]', type='componentList'

        # Finally we modify the length
        self.changeLength(length)
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def follicle(shape, u=0, v=0, name=""):
    """Attach follicle to "shape" at specified "u" and "v" values"""

    type = cmds.nodeType(shape)
    assert type in ("mesh", "nurbsSurface"), (
        "follicle() works on polygonal meshes and nurbs")

    src, dst = {
        "mesh": (".outMesh", ".inputMesh"),
        "nurbsSurface": (".local", ".inputSurface")
    }[type]

    follicle = cmds.createNode("follicle", name=name + "Shape")
    transform = cmds.listRelatives(follicle, parent=True)[0]

    cmds.setAttr(follicle + ".parameterU", u)
    cmds.setAttr(follicle + ".parameterV", v)

    cmds.connectAttr(follicle + ".outTranslate", transform + ".translate")
    cmds.connectAttr(follicle + ".outRotate", transform + ".rotate")
    cmds.connectAttr(shape + ".worldMatrix[0]", follicle + ".inputWorldMatrix")
    cmds.connectAttr(shape + src, follicle + dst, force=True)

    return transform
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def set_defaults(*args):
    """Set currently selected values from channel box to their default value

    If no channel is selected, default all keyable attributes.

    """

    for node in cmds.ls(selection=True):
        selected_channels = read_selected_channels()
        for channel in (selected_channels or
                        cmds.listAttr(node, keyable=True)):
            try:
                default = cmds.attributeQuery(channel,
                                              node=node,
                                              listDefault=True)[0]
            except Exception:
                continue

            else:
                cmds.setAttr(node + "." + channel, default)
项目: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")
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def offset_orient(joints, amount, axis):
    """Offsets the orient by the given amount

    @param joints: Joints to orient.
    @param amount: Amount to offset by.
    @param axis: Which axis X, Y or Z
    """
    for joint in joints:
        children = _unparent_children(joint)
        attribute = '{0}.jointOrient{1}'.format(joint, axis)
        orient = cmds.getAttr(attribute)
        orient += amount
        cmds.setAttr(attribute, orient)
        _reparent_children(joint, children)

    if joints:
        cmds.select(joints)
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def create_shaders():
    """
    Creates the red/green/blue shaders.
    @return: (Red, green, blue material nodes)
    """
    red = cmds.shadingNode('lambert', asShader=True)
    cmds.setAttr('{0}.color'.format(red), 1, 0, 0, type='double3')
    cmds.setAttr('{0}.ambientColor'.format(red), 1, 0, 0, type='double3')
    green = cmds.shadingNode('lambert', asShader=True)
    cmds.setAttr('{0}.color'.format(green), 0, 1, 0, type='double3')
    cmds.setAttr('{0}.ambientColor'.format(green), 0, 1, 0, type='double3')
    blue = cmds.shadingNode('lambert', asShader=True)
    cmds.setAttr('{0}.color'.format(blue), 0, 0, 1, type='double3')
    cmds.setAttr('{0}.ambientColor'.format(blue), 0, 0, 1, type='double3')

    t = 0.9
    for node in [red, green, blue]:
        cmds.setAttr('{0}.transparency'.format(node), t, t, t, type='double3')

    return red, green, blue
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def create_node(node_dictionary, parent=None):
    """Create the Maya node described by the given data dictionary.
    :param node_dictionary: The data dictionary generated by one of the load/get functions.
    :param parent: The node to parent the created node to.
    """
    node = cmds.createNode(node_dictionary['nodeType'], name=node_dictionary['name'])
    if parent:
        cmds.parent(node, parent)
    cmds.setAttr('{0}.t'.format(node), *node_dictionary['translate'])
    cmds.setAttr('{0}.r'.format(node), *node_dictionary['rotate'])
    cmds.setAttr('{0}.s'.format(node), *node_dictionary['scale'])
    cmds.setAttr('{0}.rotateOrder'.format(node), node_dictionary['rotateOrder'])
    cmds.setAttr('{0}.rotateAxis'.format(node), *node_dictionary['rotateAxis'])
    if node_dictionary['nodeType'] == 'joint':
        cmds.setAttr('{0}.jointOrient'.format(node), *node_dictionary['jointOrient'])
        cmds.setAttr('{0}.radius'.format(node), node_dictionary['radius'])
        cmds.setAttr('{0}.side'.format(node), node_dictionary['side'])
        cmds.setAttr('{0}.type'.format(node), node_dictionary['type'])
        cmds.setAttr('{0}.otherType'.format(node), node_dictionary['otherType'], type='string')
        cmds.setAttr('{0}.jointTypeX'.format(node), node_dictionary['jointTypeX'])
        cmds.setAttr('{0}.jointTypeY'.format(node), node_dictionary['jointTypeY'])
        cmds.setAttr('{0}.jointTypeZ'.format(node), node_dictionary['jointTypeZ'])

    for child in node_dictionary.get('children', []):
        create_node(child, node)
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def mirror(joint, search_for, replace_with):
    joints = [joint, ] + (cmds.listRelatives(joint, ad=True, path=True) or [])
    for joint in joints:
        mirrored_joint = joint.replace(search_for, replace_with)
        if cmds.objExists(mirrored_joint):
            translate = list(cmds.getAttr('{0}.t'.format(joint))[0])
            parent = cmds.listRelatives(joint, parent=True, path=True)
            if parent and search_for not in parent[0]:
                translate[2] *= -1.0
            else:
                translate = [x * -1.0 for x in translate]
            cmds.setAttr('{0}.t'.format(mirrored_joint), *translate)

            rotate = cmds.getAttr('{0}.r'.format(joint))[0]
            cmds.setAttr('{0}.r'.format(mirrored_joint), *rotate)

            scale = cmds.getAttr('{0}.s'.format(joint))[0]
            cmds.setAttr('{0}.s'.format(mirrored_joint), *scale)
项目: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
项目:pipeline    作者:liorbenhorin    | 项目源码 | 文件源码
def playblast_snapshot(path = None,format = None, compression = None, hud = None, offscreen = None, range=None, scale = None):
    current_image_format = cmds.getAttr("defaultRenderGlobals.imageFormat")
    cmds.setAttr("defaultRenderGlobals.imageFormat", 32) # *.png

    if range is None:

        range = playback_selection_range()
        print range
        if range is None:

            start = cmds.playbackOptions( q=True,min=True )
            end  = cmds.playbackOptions( q=True,max=True )
            range = [start, end]

    cmds.playblast(frame =int((range[0] + range[1])/2), cf = path, fmt="image",  orn=hud, os=offscreen, wh = scene_resolution(), p=scale, v=False) 

    cmds.setAttr("defaultRenderGlobals.imageFormat", current_image_format)
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def BT_Double3ValuesToNode(values = None, node = None, attr = None):
    if not values or len(values) != 3:
        return False

    cmds.setAttr(node +'.' +attr, values[0], values[1], values[2], type = 'double3')
项目: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 WeaponBinder():
    # Call of Duty specific
    for x in xrange(0, len(GUN_BASE_TAGS)):
        try:
            # Select both tags and parent them
            cmds.select(GUN_BASE_TAGS[x], replace = True)
            cmds.select(VIEW_HAND_TAGS[x], toggle = True)
            # Connect
            cmds.connectJoint(connectMode = True)
            # Parent
            mel.eval("parent " + GUN_BASE_TAGS[x] + " " + VIEW_HAND_TAGS[x])
            # Reset the positions of both bones
            cmds.setAttr(GUN_BASE_TAGS[x] + ".t", 0, 0, 0)
            cmds.setAttr(GUN_BASE_TAGS[x] + ".jo", 0, 0, 0)
            cmds.setAttr(GUN_BASE_TAGS[x] + ".rotate", 0, 0, 0)
            # Reset the rotation of the parent tag
            cmds.setAttr(VIEW_HAND_TAGS[x] + ".jo", 0, 0, 0)
            cmds.setAttr(VIEW_HAND_TAGS[x] + ".rotate", 0, 0, 0)
            # Remove
            cmds.select(clear = True)
        except:
            pass


# Place a notetrack
项目: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
项目:mayakit    作者:danbradham    | 项目源码 | 文件源码
def combine_curves(curve_shapes):

    pnt_attr_nodes = []
    for node in curve_shapes:
        pa = cmds.createNode('pointAttributeToArray')
        cmds.connectAttr(node + '.worldSpace', pa + '.inGeometry')
        cmds.setAttr(pa + '.pointPosition', 1)
        cmds.setAttr(pa + '.pointTangent', 1)
        pnt_attr_nodes.append(pa)


    positions = cmds.createNode('combineArrays')
    tangents = cmds.createNode('combineArrays')

    for i, pa in enumerate(pnt_attr_nodes):
        cmds.connectAttr(pa + '.outPositionPP', (positions + '.inArrays[{}]').format(i))
        cmds.connectAttr(pa + '.outTangentPP', (tangents + '.inArrays[{}]').format(i))

    return positions, tangents
项目:mayakit    作者:danbradham    | 项目源码 | 文件源码
def create_hair_system(nucleus=None):
    '''Create a hair system, add it to the specified nucleus or active nucleus'''

    if not nucleus:
        nucleus = get_nucleus()

    hair_system = cmds.createNode('hairSystem')
    cmds.connectAttr('time1.outTime', hair_system + '.currentTime')
    index = cmds.getAttr(nucleus + '.inputActive', size=True)
    input_active = '{}.inputActive[{}]'.format(nucleus, index)
    input_start = '{}.inputActiveStart[{}]'.format(nucleus, index)
    output_object = '{}.outputObjects[{}]'.format(nucleus, index)
    cmds.setAttr(hair_system + '.active', 1)
    cmds.connectAttr(hair_system + '.currentState', input_active)
    cmds.connectAttr(hair_system + '.startState', input_start)
    cmds.connectAttr(output_object, hair_system + '.nextState')
    cmds.connectAttr(nucleus + '.startFrame', hair_system + '.startFrame')
    return hair_system
项目:Modular_Rigging_Thesis    作者:LoganKelly    | 项目源码 | 文件源码
def recursiveZeroOutControllers(self,node):
        if node is not None:
            if node.nodeType == 'globalComponent' or node.nodeType == 'hipComponent':
                if node.metaNodeName is not None:
                    controllerName = mel.eval('getMetaNodeConnection -n "'+node.metaNodeName+'" -c "controller";')
                    cmds.setAttr(controllerName+'.tx',0)
                    cmds.setAttr(controllerName+'.ty',0)
                    cmds.setAttr(controllerName+'.tz',0)
                    cmds.setAttr(controllerName+'.rx',0)
                    cmds.setAttr(controllerName+'.ry',0)
                    cmds.setAttr(controllerName+'.rz',0)
                    cmds.setAttr(controllerName+'.sx',1)
                    cmds.setAttr(controllerName+'.sy',1)
                    cmds.setAttr(controllerName+'.sz',1)
            for childNode in node.childNodes:
                self.recursiveZeroOutControllers(childNode)
项目: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 softWave(sftmod, arrow, ctrl,  *args):
    # add values to positions in graph
    positions = [0.0, 0.3, 0.6, 0.9, 0.95]
    values = [1.0, -0.3, 0.1, -0.05, 0.01]
    for i in range(len(positions)):
        cmds.setAttr("{0}.falloffCurve[{1}].falloffCurve_Position".format(sftmod, i), positions[i])
        cmds.setAttr("{0}.falloffCurve[{1}].falloffCurve_FloatValue".format(sftmod, i), values[i])
        cmds.setAttr("{0}.falloffCurve[{1}].falloffCurve_Interp".format(sftmod, i), 2)

    cmds.addAttr(arrow, ln="WaveAttrs", at="enum", k=True)
    cmds.setAttr("{0}.WaveAttrs".format(arrow), l=True)

    # expose these on the control
    for j in range(5):
        cmds.addAttr(arrow, ln="position{0}".format(j), at="float", min=0.0, max=1.0, dv=positions[j], k=True)
        cmds.connectAttr("{0}.position{1}".format(arrow, j),
                         "{0}.falloffCurve[{1}].falloffCurve_Position".format(sftmod, j))

    for j in range(5):
        cmds.addAttr(arrow, ln="value{0}".format(j), at="float", min=-1.0, max=1.0, dv=values[j], k=True)
        cmds.connectAttr("{0}.value{1}".format(arrow, j),
                         "{0}.falloffCurve[{1}].falloffCurve_FloatValue".format(sftmod, j))
        cmds.setAttr("{0}.position{1}".format(arrow, j), l=True)
        cmds.setAttr("{0}.value{1}".format(arrow, j), l=True)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def stripToTranslate(first="none", *args):
    """strips for all selected or entered as args, sets all attrs but translate to locked and hidden"""
    attrs = ["rx", "ry", "rz", "sx", "sy", "sz", "visibility"]
    objs = []
    if first=="none":
        objs = getSelection()
    else:
        objs.append(first)
        if args:
            for each in args:
                objs.append(each)
##    print(objs)
    for me in objs:
        for attr in attrs:
            objAttr = me + "." + attr
            cmds.setAttr(objAttr, lock=True, k=False)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def stripTransforms(first="none", *args):
    """locks and hides all transforms from channel box. can call multiple objs as arguments or use selection of objects"""
    attrs = ["rx", "ry", "rz", "tx", "ty", "tz", "sx", "sy", "sz", "visibility"]
    objs = []
    if first=="none":
        objs = getSelection()
    else:
        objs.append(first)
        if args:
            for each in args:
                objs.append(each)
    print(objs)
    for me in objs:
        for attr in attrs:
            objAttr = me + "." + attr
            cmds.setAttr(objAttr, lock=True, k=False)
项目: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)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def setValues(*args):
    """sets the values from window on all selected objs for appropriate channels"""

    sel = cmds.ls(sl=True)

    attrs = cmds.checkBoxGrp(widgets["transCBG"], q=True, va3=True)
    trans = attrs[0]
    rots = attrs[1]
    scls = attrs[2]

    for obj in sel:
        if cmds.objectType(obj)=="transform":
            if trans:
                t = cmds.floatFieldGrp(widgets["trnFFG"], q=True, v=True)
                cmds.setAttr("{}.translate".format(obj), t[0], t[1], t[2])
            if rots:
                r = cmds.floatFieldGrp(widgets["rotFFG"], q=True, v=True)
                cmds.setAttr("{}.rotate".format(obj), r[0],r[1], r[2])
            if scls:
                s = cmds.floatFieldGrp(widgets["sclFFG"], q=True, v=True)
                cmds.setAttr("{}.scale".format(obj), s[0], s[1], s[2])
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def changeValue(attr, slider, *args):

    value = cmds.floatSliderGrp(slider, q=True, v=True)
    cmds.setAttr(attr, value)

# def focusToCamera():

    #get camera from focus window
    # panel = cmds.getPanel(wf=True)
    # cam = cmds.modelEditor(panel, q=True, camera=True)

#----------get camera from focus . . .
#----------have camera list to select from . . .

# (coverageX)
# (coverageY)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def createJointsAlongCurve(crv="", numJnts=3, *args):
    jnts = []
    crvShp = cmds.listRelatives(crv, s=True)[0]
    poc = cmds.shadingNode("pointOnCurveInfo", asUtility=True, name="tmpPOCInfo")
    cmds.connectAttr("{}.local".format(crvShp), "{}.inputCurve".format(poc))
    cmds.setAttr("{}.turnOnPercentage".format(poc), 1)
    lineLen = cmds.arclen(crv)
    dist = float(numJnts)/lineLen

    for x in range(0, numJnts+1):
        perc = 1.0/numJnts
        cmds.setAttr("{}.parameter".format(poc),x*perc)
        print x*perc
        pos = cmds.getAttr("{}.position".format(poc))[0]
        jnt = cmds.joint(p=pos)
        jnts.append(jnt)
        # add one joint at the end to orient    
    return(jnts)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def hideArnoldAttrs(*args):
    """
    will hide the arnold attributes from the channelbox
    """
    crvAttrs = [".ai_curve_shaderb", ".ai_curve_shaderg", ".ai_curve_shaderr", ".srate", ".cwdth", ".rcurve"]
    meshAttrs = [".emitSpecular", ".emitDiffuse", ".intensity", ".scb", ".scg", ".scr", ".ai_color_temperature", ".ai_use_color_temperature", ".ai_volume", ".ai_indirect", ".ai_sss", ".ai_specular", ".ai_diffuse", ".ai_exposure", ".ai_shadow_density"]

    octaneAttrs = [".octGeoType", ".octGenVis", ".octCamVis", ".octShVis", ".octLayerId", ".octBakGrId", ".octRandomSeed", ".octRPassColorR", ".octRPassColorG", ".octRPassColorB", ".octConstTopology", ".octMergeUnweldedVert", ".octSubdLevel", ".octSubdSharpness", ".octSubdBoundInterp", ".octSubdSceme"]

    meshes = cmds.ls(type="mesh")
    if meshes:
        for m in meshes:
            for attr in meshAttrs:
                cmds.setAttr("{0}.{1}".format(m, attr), keyable=False, channelBox=False)

    crvs = cmds.ls(type="nurbsCurve")
    if crvs:
        for c in crvs:
            for attr in crvAttrs:
                cmds.setAttr("{0}.{1}".format(c, attr), keyable=False, channelBox=False)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def toggle_sel_shape_vis(*args):
    """toggles the selected transforms' shape visibility"""
    sel = cmds.ls(sl=True, type="transform")
    if sel:
        for obj in sel:
            shp = cmds.listRelatives(obj, s=True)
            if not shp:
                return ()
            for s in shp:
                currVal = cmds.getAttr("{0}.visibility".format(s))
                newVal = 0
                if currVal == 0:
                    newVal = 1
                elif currVal == 1:
                    newVal = 0
                cmds.setAttr("{0}.visibility".format(s), newVal)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def JntSegScl(*args):
    """turns on/off selected jnts seg scale compensate attr"""

    jnts = cmds.ls(sl=True, type="joint")
    if not jnts:
        cmds.warning("No joints selected!")
        return ()

    for jnt in jnts:
        currVal = cmds.getAttr("{0}.segmentScaleCompensate".format(jnt))
        if currVal == 0:
            newVal = 1
        elif currVal == 1:
            newVal = 0

        cmds.setAttr("{0}.segmentScaleCompensate".format(jnt), newVal)
项目:core    作者:getavalon    | 项目源码 | 文件源码
def lock():
    """Lock scene

    Add an invisible node to your Maya scene with the name of the
    current file, indicating that this file is "locked" and cannot
    be modified any further.

    """

    if not cmds.objExists("lock"):
        with lib.maintained_selection():
            cmds.createNode("objectSet", name="lock")
            cmds.addAttr("lock", ln="basename", dataType="string")

            # Permanently hide from outliner
            cmds.setAttr("lock.verticesOnlySet", True)

    fname = cmds.file(query=True, sceneName=True)
    basename = os.path.basename(fname)
    cmds.setAttr("lock.basename", basename, type="string")
项目: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
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def applyBrush(curve, parent):
    '''
    Simply applies the paint effects brush to the curve with the settings we want.
    '''

    mc.AttachBrushToCurves(curve)
    stroke = mc.ls(sl=True)[0]
    stroke = mc.parent(stroke,parent)[0]

    mc.setAttr(stroke+'.displayPercent',92)
    mc.setAttr(stroke+'.sampleDensity',0.5)
    mc.setAttr(stroke+'.inheritsTransform',0)
    mc.setAttr(stroke+'.translate',0,0,0)
    mc.setAttr(stroke+'.rotate',0,0,0)

    return stroke
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def attributeMenuItem(node, attr):

    plug = node+'.'+attr
    niceName = mc.attributeName(plug, nice=True)

    #get attribute type
    attrType = mc.getAttr(plug, type=True)

    if attrType == 'enum':
        listEnum = mc.attributeQuery(attr, node=node, listEnum=True)[0]
        if not ':' in listEnum:
            return
        listEnum = listEnum.split(':')
        mc.menuItem(label=niceName, subMenu=True)
        for value, label in enumerate(listEnum):
            mc.menuItem(label=label, command=partial(mc.setAttr, plug, value))
        mc.setParent('..', menu=True)
    elif attrType == 'bool':
        value = mc.getAttr(plug)
        label = 'Toggle '+ niceName
        mc.menuItem(label=label, command=partial(mc.setAttr, plug, not value))
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def setAnimValue(plug, value, tangentType=None):
    '''
    Sets key if the channel is keyed, otherwise setAttr
    '''

    if mc.keyframe(plug, query=True, name=True):
        mc.setKeyframe(plug, value=value)
        if tangentType:
            time = mc.currentTime(query=True)
            itt = tangentType
            ott = tangentType
            if tangentType == 'step':
                itt = 'linear'
            mc.keyTangent(plug, time=(time,), edit=True, itt=itt, ott=ott)                                            

    mc.setAttr(plug, value)
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def colorShape(obj, rgb=None, hsv=None):

    if not rgb:
        if hsv and len(hsv) == 3:
            rgb = colorsys.hsv_to_rgb(*hsv)
        else:
            raise RuntimeError('colorShape requires an rgb or hsv input.')

    mc.setAttr('{}.overrideEnabled'.format(obj), 1)
    mc.setAttr('{}.overrideRGBColors'.format(obj), 1)
    mc.setAttr('{}.overrideColorRGB'.format(obj), *rgb)

    shapes = mc.listRelatives(obj, shapes=True, pa=True)
    for shape in shapes:
        #if mc.getAttr('{}.overrideEnabled'.format(shape)): 
        mc.setAttr('{}.overrideEnabled'.format(shape), 1)           
        mc.setAttr('{}.overrideRGBColors'.format(shape), 1)
        mc.setAttr('{}.overrideColorRGB'.format(shape), *rgb)
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def main():

    sel = mc.ls(sl=True)

    if not sel:
        return

    for each in sel:
        plug = each+'.v'
        try:
            locked = mc.getAttr(plug, lock=True)
            if locked:
                mc.setAttr(plug, lock=False)

            if mc.getAttr(plug):
                mc.setAttr(plug, 0)
            else:
                mc.setAttr(plug, 1)

            if locked:
                mc.setAttr(plug, lock=True)
        except:
            pass
项目:TACTIC-Handler    作者:listyque    | 项目源码 | 文件源码
def set_info_to_scene(search_key, context):
    # add info about particular scene
    skey_link = 'skey://{0}&context={1}'.format(search_key, context)
    if not cmds.attributeQuery('tacticHandler_skey', node='defaultObjectSet', exists=True):
        cmds.addAttr('defaultObjectSet', longName='tacticHandler_skey', dataType='string')
    cmds.setAttr('defaultObjectSet.tacticHandler_skey', skey_link, type='string')
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def on_pool_changed(self, index):
        pool = self.pools.itemText(index)
        cmds.setAttr(self.render_globals + ".pool", pool, type="string")
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def on_group_changed(self, index):
        group = self.groups.itemText(index)
        cmds.setAttr(self.render_globals + ".group", group, type="string")
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def _set_uuid(node):
    """Add mbID to `node`

    Unless one already exists.

    """

    attr = "{0}.mbID".format(node)

    if not cmds.objExists(attr):
        cmds.addAttr(node, longName="mbID", dataType="string")
        _, uid = str(uuid.uuid4()).rsplit("-", 1)
        cmds.setAttr(attr, uid, type="string")
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def zero_orient(joints):
    for joint in joints:
        children = _unparent_children(joint)
        cmds.setAttr('{0}.jointOrient'.format(joint), 0, 0, 0)
        _reparent_children(joint, children)

    if joints:
        cmds.select(joints)
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def template_joints(joints=None, reorient_children=True, reset_orientation=True):
    if joints is None:
        joints = cmds.ls(sl=True, type='joint')
    if not joints:
        raise RuntimeError('No joint selected to orient.')

    if reorient_children:
        children = cmds.listRelatives(fullPath=True, allDescendents=True, type='joint')
        joints.extend(children)

    red, green, blue = create_shaders()

    orient_group = cmds.createNode('transform', name=ORIENT_GROUP)
    manips = []
    for joint in joints:
        if reset_orientation:
            cmds.makeIdentity(joint, apply=True)
            cmds.joint(joint, edit=True, orientJoint='xyz', secondaryAxisOrient='yup', children=False, zeroScaleOrient=True)
        if not cmds.listRelatives(joint, children=True):
            zero_orient([joint])
            continue
        group, manip = create_orient_manipulator(joint, blue)
        manips.append(manip)
        cmds.parent(group, orient_group)
        cmds.parentConstraint(joint, group)
        cmds.setAttr(joint + '.template', 1)
    cmds.select(manips)
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def create_orient_manipulator(joint, material):
    joint_scale = cmds.jointDisplayScale(query=True)
    joint_radius = cmds.getAttr('{0}.radius'.format(joint))
    radius = joint_scale * joint_radius
    children = cmds.listRelatives(joint, children=True, path=True)
    if children:
        p1 = cmds.xform(joint, q=True, ws=True, t=True)
        p1 = OpenMaya.MPoint(*p1)
        p2 = cmds.xform(children[0], q=True, ws=True, t=True)
        p2 = OpenMaya.MPoint(*p2)
        radius = p1.distanceTo(p2)
    arrow_cvs = [[-1, 0, 0], [-1, 2, 0], [-2, 2, 0], [0, 4, 0], [2, 2, 0], [1, 2, 0], [1, 0, 0], [-1, 0, 0]]
    arrow_cvs = [[x[0]*radius, x[1]*radius, x[2]*radius] for x in arrow_cvs]
    shape = cmds.curve(name='{0}_zForward'.format(joint), degree=1, point=arrow_cvs)
    # shape = cmds.sphere(n='{0}_zForward'.format(joint), p=(0, 0, 0), ax=(0, 0, -1), ssw=0, esw=180, r=radius, d=3, ut=0, tol=0.01, s=8, nsp=4, ch=0)[0]
    # cmds.setAttr('{0}.sz'.format(shape), 0)
    # cmds.select(shape)
    # cmds.hyperShade(assign=material)
    group = cmds.createNode('transform', name='{0}_grp'.format(shape))
    cmds.parent(shape, group)
    cmds.makeIdentity(shape, apply=True)
    cmds.addAttr(shape, longName=MESSAGE_ATTRIBUTE, attributeType='message')
    cmds.connectAttr('{0}.message'.format(joint), '{0}.{1}'.format(shape, MESSAGE_ATTRIBUTE))
    for attr in ['tx', 'ty', 'tz', 'ry', 'rz', 'v']:
        cmds.setAttr('{0}.{1}'.format(shape, attr), lock=True, keyable=False)
    return group, shape
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def set_color(self):
        """Open a dialog to set the override RGB color of the selected nodes."""
        nodes = cmds.ls(sl=True) or []
        if nodes:
            color = cmds.getAttr('{0}.overrideColorRGB'.format(nodes[0]))[0]
            color = QtGui.QColor(color[0]*255, color[1]*255, color[2]*255)
            color = QtWidgets.QColorDialog.getColor(color, self, 'Set Curve Color')
            if color.isValid():
                color = [color.redF(), color.greenF(), color.blueF()]
                for node in nodes:
                    cmds.setAttr('{0}.overrideEnabled'.format(node), True)
                    cmds.setAttr('{0}.overrideRGBColors'.format(node), True)
                    cmds.setAttr('{0}.overrideColorRGB'.format(node), *color)
项目:pipeline    作者:liorbenhorin    | 项目源码 | 文件源码
def snapshot(path = None, width = 96, height = 96):
    current_image_format = cmds.getAttr("defaultRenderGlobals.imageFormat")
    cmds.setAttr("defaultRenderGlobals.imageFormat", 32) # *.png
    #path = "/Users/liorbenhorin/Library/Preferences/Autodesk/maya/2015-x64/scripts/pipeline/thumb.png"
    cmds.playblast(cf = path, fmt="image", frame = cmds.currentTime( query=True ), orn=False, wh = [width,height], p=100, v=False)
    cmds.setAttr("defaultRenderGlobals.imageFormat", current_image_format)

    if os.path.isfile(path):
        return path
    else:
        return False
项目:surume    作者:tm8r    | 项目源码 | 文件源码
def _apply(self, *args):
        selected = cmds.textScrollList(self.text_scroll, q=True, si=True)
        fov = cmds.textFieldGrp(self.text_field, q=True, tx=True)
        if not selected or not fov:
            return
        camera = selected[0]
        vfa = cmds.getAttr(camera + ".verticalFilmAperture")

        focal_length = 0.5 * vfa / math.tan(float(fov) / 2.0 / 57.29578) / 0.03937

        cmds.setAttr(camera + ".focalLength", focal_length)
        cmds.textFieldGrp(self.result_field, e=True, tx=round(focal_length, 3))
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def BT_Setup(set = None):

    if not set:
        return False

    transforms = cmds.listConnections(set +'.dagSetMembers')
    if not transforms:
        return False

    if not cmds.attributeQuery('Blend_Node', n = set, ex = True):
        cmds.addAttr(set, ln = 'Blend_Node', k = False, h = True, dt = 'string')
    else:
        return False

    btNode = cmds.createNode("BlendTransforms")
    cmds.setAttr(set +'.Blend_Node', btNode, type = "string")

    for i in range(0, len(transforms)):
        baseMatrix = cmds.xform(transforms[i], q = True, m = True)
        baseScale = cmds.getAttr(transforms[i] +'.scale')[0]
        baseRotOffset = [0.0, 0.0, 0.0]

        if cmds.objectType(transforms[i], isType = 'joint'):
            baseRotOffset = cmds.getAttr(transforms[i] +'.jointOrient')[0]

        btAttr = 'transforms[' +str(i) +'].baseMatrix'
        btScaleAttr = 'transforms[' +str(i) +'].baseScale'
        btRotOffsetAttr = 'transforms[' +str(i) +'].baseRotOffset'

        BT_MatrixValuesToNode(values = baseMatrix, node = btNode, attr = btAttr)
        BT_Double3ValuesToNode(values = baseScale, node = btNode, attr = btScaleAttr)
        BT_Double3ValuesToNode(values = baseRotOffset, node = btNode, attr = btRotOffsetAttr)
        BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i])

    return True
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def BT_Double3ValuesToNode(values = None, node = None, attr = None):
    if not values or len(values) != 3:
        return False

    cmds.setAttr(node +'.' +attr, values[0], values[1], values[2], type = 'double3')
项目:BlendTransforms    作者:duncanskertchly    | 项目源码 | 文件源码
def BT_Setup(set = None):

    if not set:
        return False

    transforms = cmds.listConnections(set +'.dagSetMembers')
    if not transforms:
        return False

    if not cmds.attributeQuery('Blend_Node', n = set, ex = True):
        cmds.addAttr(set, ln = 'Blend_Node', k = False, h = True, dt = 'string')
    else:
        return False

    btNode = cmds.createNode("BlendTransforms")
    cmds.setAttr(set +'.Blend_Node', btNode, type = "string")

    for i in range(0, len(transforms)):
        baseMatrix = cmds.xform(transforms[i], q = True, m = True)
        baseScale = cmds.getAttr(transforms[i] +'.scale')[0]
        baseRotOffset = [0.0, 0.0, 0.0]

        if cmds.objectType(transforms[i], isType = 'joint'):
            baseRotOffset = cmds.getAttr(transforms[i] +'.jointOrient')[0]

        btAttr = 'transforms[' +str(i) +'].baseMatrix'
        btScaleAttr = 'transforms[' +str(i) +'].baseScale'
        btRotOffsetAttr = 'transforms[' +str(i) +'].baseRotOffset'

        BT_MatrixValuesToNode(values = baseMatrix, node = btNode, attr = btAttr)
        BT_Double3ValuesToNode(values = baseScale, node = btNode, attr = btScaleAttr)
        BT_Double3ValuesToNode(values = baseRotOffset, node = btNode, attr = btRotOffsetAttr)
        BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i])

    return True