Python源码示例:pymel.core.PyNode()

示例1
def getBaseCtrl(self, sCtrlType, sAttrName, sCtrlName, fRadius, iDegree = 1, iSection = 8):
        nCtrl = None
        self.ctrlCreated = False
        try:
            nCtrl= self.masterGrp.getAttr(sAttrName)
        except pymel.MayaAttributeError:
            try:
                nCtrl = pymel.PyNode(self.prefix + sCtrlName)
            except pymel.MayaNodeError:
                if (sCtrlName != (self.prefix + "Option_Ctrl")):
                    nCtrl = pymel.PyNode(self.ctrls.cvControl(sCtrlType, sCtrlName, r=fRadius, d=iDegree, dir="+X"))
                else:
                    nCtrl = pymel.PyNode(self.ctrls.cvCharacter(sCtrlType, sCtrlName, r=(fRadius*0.2)))
                self.ctrlCreated = True
            finally:
                #Since there is no connection between the master and the node found, create the connection
                self.masterGrp.addAttr(sAttrName, attributeType='message')
                nCtrl.message.connect(self.masterGrp.attr(sAttrName))

        return nCtrl 
示例2
def test_emptyClass(self):

        data_inn = EmptyClass()
        self._monkeypatch_various_types(data_inn)

        # Serializae
        network = export_network(data_inn)
        self.assertTrue(isinstance(network, pymel.PyNode))

        # Deserialize
        data_out = import_network(network)

        # Compare output
        for att in dir(data_out):
            if att[0] != '_':
                val_inn = getattr(data_inn, att)
                val_out = getattr(data_out, att)
                if isinstance(val_inn, (float, long)):
                    pass # can't correctly raise assert (almostEqual don't work...)
                else:
                    self.assertEquals(val_inn, val_out) 
示例3
def __mirror_flip_pose_callback(*args):
    """Wrapper function to call mGears mirroPose function

    Args:
        list: callback from menuItem
    """

    # cast controls into pymel object nodes
    controls = [pm.PyNode(x) for x in args[0]]

    # triggers mirror
    # we handle the mirror/flip each control individually even if the function
    # accepts several controls. Flipping on proxy attributes like blend
    # attributes cause an issue to rather than trying the complete list we do
    # one control to avoid the mirror to stop
    for ctl in controls:
        mirrorPose(flip=args[1], nodes=[ctl]) 
示例4
def __reset_attributes_callback(*args):
    """ Wrapper function to call mGears resetTransform function

    Args:
        list: callback from menuItem
    """

    attribute = args[1]

    for node in args[0]:
        control = pm.PyNode(node)

        if attribute == "translate":
            resetTransform(control, t=True, r=False, s=False)
        if attribute == "rotate":
            resetTransform(control, t=False, r=True, s=False)
        if attribute == "scale":
            resetTransform(control, t=False, r=False, s=True) 
示例5
def getMirror(node):
    """Get the mirrored node usin _L and _R replacement

    Arguments:
        node (dagNode or list of dagNodes): The dagNode to look for a
            mirror

    Returns:
        dagNode or list of dagNodes: The dagNode contrapart on the other
            side _L or _R

    """
    if not isinstance(node, list):
        node = [node]
    mirrorNodes = []
    for n in node:
        try:
            mirrorNodes.append(pm.PyNode(string.convertRLName(n.name())))
        except Exception:
            pm.displayInfo("The object: %s doesn't have mirror _L or _R "
                           "contrapart. Skipped!" % n.name())
            mirrorNodes.append(n)

    return mirrorNodes 
示例6
def connectSet(source, target, testInstance):
    """Connect or set attributes

    Connects or set attributes depending if is instance of a instance check

    Args:
        source (str or Attr): Striname of the attribute or PyNode attribute
        target (str or Attr): Striname of the attribute or PyNode attribute
        testInstance (tuple): Tuple of types to check
    """
    if not isinstance(testInstance, tuple):
        testInstance = tuple(testInstance)

    if isinstance(source, testInstance):
        pm.connectAttr(source, target)
    else:
        pm.setAttr(target, source) 
示例7
def as_pynode(obj):
    """Check and convert a given string to Pynode

    If the object is not str or unicode or PyNode will raise type error

    Args:
        obj (str, unicode, PyNode): Object to check and/or convert to PyNode

    Returns:
        PyNode: the pynode object
    """
    if isinstance(obj, str) or isinstance(obj, unicode):
        obj = pm.PyNode(obj)

    if not isinstance(obj, pm.PyNode):
        raise TypeError("{} is type {} not str, unicode or PyNode".format(
            str(obj), type(obj)))

    return obj 
示例8
def recordNodesMatrices(nodes, desiredTime):
    """get the matrices of the nodes provided and return a dict of
    node:matrix

    Args:
        nodes (list): of nodes

    Returns:
        dict: node:node matrix
    """
    nodeToMat_dict = {}
    for fk in nodes:
        fk = pm.PyNode(fk)
        nodeToMat_dict[fk.name()] = fk.getAttr("worldMatrix", time=desiredTime)

    return nodeToMat_dict 
示例9
def getControlers(model, gSuffix=CTRL_GRP_SUFFIX):
    """Get thr controlers from the set

    Args:
        model (PyNode): Rig root
        gSuffix (str, optional): set suffix

    Returns:
        list: The members of the group
    """
    try:
        ctl_set = pm.PyNode(model.name() + gSuffix)
        members = ctl_set.members()

        return members
    except TypeError:
        return None 
示例10
def toggleAttr(model, object_name, attr_name):
    """Toggle a boolean attribute

    Args:
        model (PyNode): Rig top node
        object_name (str): The name of the control containing the attribute to
            toggle
        attr_name (str): The attribute to toggle
    """
    nameSpace = getNamespace(model)
    if nameSpace:
        node = dag.findChild(nameSpace + ":" + object_name)
    else:
        node = dag.findChild(model, object_name)

    oAttr = node.attr(attr_name)
    if oAttr.type() in ["float", "bool"]:
        oVal = oAttr.get()
        if oVal == 1:
            oAttr.set(0)
        else:
            oAttr.set(1)

# ================================================ 
示例11
def getComboKeys(model, object_name, combo_attr):
    """Get the keys from a combo attribute

    Args:
        model (PyNode): Rig top node
        object_name (str): Control name
        combo_attr (str): Combo attribute name

    Returns:
        list: Keys names from the combo attribute.
    """
    nameSpace = getNamespace(model)

    return getComboKeys_with_namespace(nameSpace, object_name, combo_attr)

##################################################
# IK FK switch match
##################################################
# ================================================ 
示例12
def spine_IKToFK(fkControls, ikControls, matchMatrix_dict=None):
    """position the IK controls to match, as best they can, the fk controls.
    Supports component: spine_S_shape_01, spine_ik_02

    Args:
        fkControls (list): list of fk controls, IN THE ORDER OF HIERARCHY,
        ["spine_C0_fk0_ctl", ..., ..., "spine_C0_fk6_ctl"]
        ikControls (list): all ik controls
    """
    if matchMatrix_dict is None:
        currentTime = pm.currentTime(q=True)
        matchMatrix_dict = recordNodesMatrices(fkControls,
                                               desiredTime=currentTime)

    attribute.reset_SRT(ikControls)

    for fk in fkControls:
        fk = pm.PyNode(fk)
        fk.setMatrix(matchMatrix_dict[fk.name()], worldSpace=True) 
示例13
def gatherMirrorData(nameSpace, node, flip):
    """Get the data to mirror

    Args:
        nameSpace (str): Namespace
        node (PyNode): No
        flip (TYPE): flip option

    Returns:
        [dict[str]: The mirror data
    """
    if isSideElement(node.name()):

        nameParts = stripNamespace(node.name()).split("|")[-1]
        nameParts = swapSideLabel(nameParts)
        nameTarget = ":".join([nameSpace, nameParts])

        oTarget = getNode(nameTarget)

        return calculateMirrorData(node, oTarget, flip=flip)

    else:
        return calculateMirrorData(node, node, flip=False) 
示例14
def setCtrls(self, fks, ik, upv, ikRot):
        # type: (list[str], str, str) -> None
        """gather core PyNode represented each controllers"""

        self.fkCtrls = [self._getNode(x) for x in fks]
        self.fkTargets = [self._getMth(x) for x in fks]

        self.ikCtrl = self._getNode(ik)
        self.ikTarget = self._getMth(ik)

        self.upvCtrl = self._getNode(upv)
        self.upvTarget = self._getMth(upv)

        if ikRot:
            self.ikRotCtl = self._getNode(ikRot)
            self.ikRotTarget = self._getMth(ikRot)
            self.hasIkRot = True
        else:
            self.hasIkRot = False 
示例15
def addTransform(parent, name, m=datatypes.Matrix()):
    """Create a transform dagNode.

    Arguments:
        parent (dagNode): The parent for the node.
        name (str): The Node name.
        m (matrix): The matrix for the node transformation (optional).

    Returns:
        dagNode: The newly created node.

    """
    node = pm.PyNode(pm.createNode("transform", n=name))
    node.setTransformation(m)

    if parent is not None:
        parent.addChild(node)

    return node 
示例16
def addTransformFromPos(parent, name, pos=datatypes.Vector(0, 0, 0)):
    """Create a transform dagNode.

    Arguments:
        parent (dagNode): The parent for the node.
        name (str): The Node name.
        pos (vector): The vector for the node position (optional).

    Returns:
        dagNode: The newly created node.

    """
    node = pm.PyNode(pm.createNode("transform", n=name))
    node.setTranslation(pos, space="world")

    if parent is not None:
        parent.addChild(node)

    return node

# ===========================================
# LOCATOR 
示例17
def addLocator(parent, name, m=datatypes.Matrix(), size=1):
    """Create a space locator dagNode.

    Arguments:
        parent (dagNode): The parent for the node.
        name (str): The Node name.
        m (matrix): The matrix for the node transformation (optional).
        size (float): The space locator shape size (optional).

    Returns:
        dagNode: The newly created node.

    """
    node = pm.PyNode(pm.createNode("locator")).getParent()
    node.rename(name)
    node.setTransformation(m)
    node.setAttr("localScale", size, size, size)

    if parent is not None:
        parent.addChild(node)

    return node 
示例18
def addJoint(parent, name, m=datatypes.Matrix(), vis=True):
    """Create a joint dagNode.

    Note:
        I'm not using the joint() comand because this is parenting
        the newly created joint to current selection which might not be desired

    Arguments:
        parent (dagNode): The parent for the node.
        name (str): The node name.
        m (matrix): The matrix for the node transformation (optional).
        vis (bool): Set the visibility of the new joint.

    Returns:
        dagNode: The newly created node.

    """
    node = pm.PyNode(pm.createNode("joint", n=name))
    node.setTransformation(m)
    node.setAttr("visibility", vis)

    if parent is not None:
        parent.addChild(node)

    return node 
示例19
def addJointFromPos(parent, name, pos=datatypes.Vector(0, 0, 0)):
    """Create a joint dagNode.

    Note:
        I'm not using the joint() comand because this is parenting
        the newly created joint to current selection which might not be desired

    Arguments:
        parent (dagNode): The parent for the node.
        name (str): The node name.
        pos (vector): The vector for the node position (optional).
        vis (bool): Set the visibility of the new joint.

    Returns:
        dagNode: The newly created node.

    """
    node = pm.PyNode(pm.createNode("joint", n=name))
    node.setTranslation(pos, space="world")

    if parent is not None:
        parent.addChild(node)

    return node 
示例20
def __findChild(node, name):
    """This find children function will stop search after firs child found.child

    This is a faster version of __findchildren

    Arguments:
        node (dagNode): The input node to search
        name (str): The name to search

    Returns:
        dagNode: Children node
    """
    try:
        for item in cmds.listRelatives(node.name(),
                                       allDescendents=True,
                                       type="transform"):
            if item.split("|")[-1] == name:
                return pm.PyNode(item)
    except pm.MayaNodeError:
        for item in node.listRelatives(allDescendents=True,
                                       type="transform"):
            if item.split("|")[-1] == name:
                return item

    return False 
示例21
def getGeometryComponents(skinCls):
    """Get the geometry components from skincluster

    Arguments:
        skinCls (PyNode): The skincluster node

    Returns:
        dagPath: The dagpath for the components
        componets: The skincluster componets
    """
    fnSet = OpenMaya.MFnSet(skinCls.__apimfn__().deformerSet())
    members = OpenMaya.MSelectionList()
    fnSet.getMembers(members, False)
    dagPath = OpenMaya.MDagPath()
    components = OpenMaya.MObject()
    members.getDagPath(0, dagPath, components)
    return dagPath, components 
示例22
def getCurrentWeights(skinCls, dagPath, components):
    """Get the skincluster weights

    Arguments:
        skinCls (PyNode): The skincluster node
        dagPath (MDagPath): The skincluster dagpath
        components (MObject): The skincluster components

    Returns:
        MDoubleArray: The skincluster weights

    """
    weights = OpenMaya.MDoubleArray()
    util = OpenMaya.MScriptUtil()
    util.createFromInt(0)
    pUInt = util.asUintPtr()
    skinCls.__apimfn__().getWeights(dagPath, components, weights, pUInt)
    return weights

######################################
# Skin Collectors
###################################### 
示例23
def collectInfluenceWeights(skinCls, dagPath, components, dataDic):
    weights = getCurrentWeights(skinCls, dagPath, components)

    influencePaths = OpenMaya.MDagPathArray()
    numInfluences = skinCls.__apimfn__().influenceObjects(influencePaths)
    numComponentsPerInfluence = weights.length() / numInfluences
    for ii in range(influencePaths.length()):
        influenceName = influencePaths[ii].partialPathName()
        influenceWithoutNamespace = pm.PyNode(influenceName).stripNamespace()
        # build a dictionary of {vtx: weight}. Skip 0.0 weights.
        inf_w = {
                jj: weights[jj * numInfluences + ii]
                for jj in range(numComponentsPerInfluence)
                if weights[jj * numInfluences + ii] != 0.0
                }
        # cast to float to avoid rounding errors when dividing integers?
        dataDic['vertexCount'] = int(weights.length() / float(numInfluences))
        # cast influenceWithoutNamespace as string otherwise it can end up
        # as DependNodeName(u'jointName') in the data.
        dataDic['weights'][str(influenceWithoutNamespace)] = inf_w 
示例24
def controller_tag_connect(ctt, tagParent):
    """Summary

    Args:
        ctt (TYPE): Teh control tag
        tagParent (TYPE): The object with the parent control tag
    """
    if pm.controller(tagParent, q=True):
        tpTagNode = pm.PyNode(pm.controller(tagParent, q=True)[0])
        tpTagNode.cycleWalkSibling.set(True)
        pm.connectAttr(tpTagNode.prepopulate, ctt.prepopulate, f=True)

        ni = attribute.get_next_available_index(tpTagNode.children)
        pm.disconnectAttr(ctt.parent)
        pm.connectAttr(ctt.parent, tpTagNode.attr(
                       "children[%s]" % str(ni))) 
示例25
def set_arnold_texture_search_path(cls):
        """sets environment defaults
        """
        start = time.time()
        from stalker import Repository

        all_repos = Repository.query.all()

        try:
            # add all repo paths to Arnold Texture search path
            texture_search_path = []
            for repo in all_repos:
                texture_search_path.append(repo.windows_path)
                texture_search_path.append(repo.linux_path)

            texture_search_path = ';'.join(texture_search_path)

            dARO = pm.PyNode('defaultArnoldRenderOptions')
            dARO.setAttr('texture_searchpath', texture_search_path)
        except (pm.MayaNodeError, ValueError, pm.MayaAttributeError):
            pass

        end = time.time()
        logger.debug('set_arnold_texture_search_path() took '
                     '%f seconds' % (end - start)) 
示例26
def redshift_ic_ipc_bake(cls):
        """Sets the render settings for IC + IPC bake
        """
        # set motion blur
        start_frame = int(pm.playbackOptions(q=True, ast=True))
        end_frame = int(pm.playbackOptions(q=True, aet=True))

        cls.rso_options['bake']['motionBlurFrameDuration'] = end_frame - start_frame + 1

        rso = pm.PyNode('redshiftOptions')

        # store and set attributes
        for attr in cls.rso_options['bake']:
            cls.rso_options['orig'][attr] = rso.attr(attr).get()
            rso.attr(attr).set(cls.rso_options['bake'][attr])

        # go to the first frame
        current_frame = pm.currentTime(q=1)
        cls.rso_options['current_frame'] = current_frame
        pm.currentTime(start_frame)

        # do a render
        pm.mel.eval('rsRender -render -rv -cam "<renderview>";') 
示例27
def redshift_ic_ipc_bake_restore(cls):
        """restores the previous render settings
        """
        rso = pm.PyNode('redshiftOptions')

        # revert settings back
        for attr in cls.rso_options['orig']:
            rso.attr(attr).set(cls.rso_options['orig'][attr])

        # set the GI engines
        rso.primaryGIEngine.set(cls.rso_options['bake']['primaryGIEngine'])
        rso.secondaryGIEngine.set(cls.rso_options['bake']['secondaryGIEngine'])

        # set the irradiance method to load
        rso.irradiancePointCloudMode.set(1)  # Load
        rso.irradianceCacheMode.set(1)  # Load

        # set the cache paths
        rso.irradiancePointCloudFilename.set(cls.rso_options['bake']['irradiancePointCloudFilename'])
        rso.irradianceCacheFilename.set(cls.rso_options['bake']['irradianceCacheFilename'])

        # go to current frame
        current_frame = cls.rso_options['current_frame']
        pm.currentTime(current_frame) 
示例28
def export_shader_attributes(cls):
        """exports the selected shader attributes to a JSON file
        """
        # get data
        data = []
        nodes = pm.ls(sl=1)
        for node in nodes:
            node_attr_data = {}
            attrs = node.listAttr()
            for attr in attrs:
                try:
                    value = attr.get()
                    if not isinstance(value, pm.PyNode):
                        node_attr_data[attr.shortName()] = value
                except TypeError:
                    continue
            data.append(node_attr_data)

        # write data
        import json
        with open(cls.node_attr_info_temp_file_path, 'w') as f:
            json.dump(data, f) 
示例29
def generate_reflection_curve(self):
        """Generates a curve which helps creating specular at the desired point
        """
        from maya.OpenMaya import MVector
        from anima.env.mayaEnv import auxiliary

        vtx = pm.ls(sl=1)[0]
        normal = vtx.getNormal(space='world')
        panel = auxiliary.Playblaster.get_active_panel()
        camera = pm.PyNode(pm.modelPanel(panel, q=1, cam=1))
        camera_axis = MVector(0, 0, -1) * camera.worldMatrix.get()

        refl = camera_axis - 2 * normal.dot(camera_axis) * normal

        # create a new curve
        p1 = vtx.getPosition(space='world')
        p2 = p1 + refl

        curve = pm.curve(d=1, p=[p1, p2])

        # move pivot to the first point
        pm.xform(curve, rp=p1, sp=p1) 
示例30
def test_slice_will_set_the_data_attributes_on_camera(self):
        """testing if calling the slice() method will set the data
        attributes properly on camera
        """
        # check the scene render resolution first
        dres = pm.PyNode('defaultResolution')
        dres.width.set(960)
        dres.height.set(540)

        rs = RenderSlicer(camera=self.camera)
        rs.slice(10, 20)

        self.assertEqual(rs.camera.isSliced.get(), True)
        self.assertEqual(rs.camera.nonSlicedResolutionX.get(), 960)
        self.assertEqual(rs.camera.nonSlicedResolutionY.get(), 540)
        self.assertEqual(rs.camera.slicesInX.get(), 10)
        self.assertEqual(rs.camera.slicesInY.get(), 20)