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

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

项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def shape_from_element(element):
    """Return shape of given 'element'

    Supports components, meshes, and surfaces

    """

    try:
        # Get either shape or transform, based on element-type
        node = cmds.ls(element, objectsOnly=True)[0]
    except Exception:
        cmds.warning("Could not find node in %s" % element)
        return None

    if cmds.nodeType(node) == 'transform':
        try:
            return cmds.listRelatives(node, shapes=True)[0]
        except Exception:
            cmds.warning("Could not find shape in %s" % element)
            return None

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

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

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

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

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

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

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

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

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

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

    """

    clones = list()

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

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

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

    if not clones:
        return

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

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

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

    Supports components, meshes, and surfaces

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

    Returns:
        str of path if found, None otherwise

    """

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

    if cmds.nodeType(node) == "transform":
        try:
            return cmds.listRelatives(node, shapes=True, fullPath=True)[0]
        except IndexError:
            return cmds.warning("Could not find shape in %s" % element)
    else:
        return node
项目: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 get_skin_clusters(nodes):
    """Get the skinClusters attached to the specified node and all nodes in descendents.

    :param nodes: List of dag nodes.
    @return A list of the skinClusters in the hierarchy of the specified root node.
    """
    if isinstance(nodes, basestring):
        nodes = [nodes, ]
    all_skins = []
    for node in nodes:
        relatives = cmds.listRelatives(node, ad=True, path=True) or []
        relatives.insert(0, node)
        relatives = [shortcuts.get_shape(node) for node in relatives]
        for relative in relatives:
            history = cmds.listHistory(relative, pruneDagObjects=True, il=2) or []
            skins = [x for x in history if cmds.nodeType(x) == 'skinCluster']
            if skins:
                all_skins.append(skins[0])
    return list(set(all_skins))
项目:surume    作者:tm8r    | 项目源码 | 文件源码
def get_unused_shading_engines():
    u"""????ShadingEngine???????

    :return: ????ShadingEngine????
    :rtype: list of unicode
    """
    shading_engines = cmds.ls(type="shadingEngine")

    unused_shading_engines = []
    for s in shading_engines:
        if s in _DEFAULT_SHADING_ENGINES:
            continue
        unused = True
        for c in cmds.listConnections(s):
            node_type = cmds.nodeType(c)
            if "shader" in cmds.getClassification(node_type)[0]:
                unused = False
                break
        if unused:
            unused_shading_engines.append(s)
    return unused_shading_engines
项目:mayakit    作者:danbradham    | 项目源码 | 文件源码
def to_curve_fn(curve):

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

    sel = om.MSelectionList()
    sel.add(shape)
    dep = sel.getDagPath(0)
    fn = om.MFnNurbsCurve(dep)
    return fn
项目:OBB    作者:chrisdevito    | 项目源码 | 文件源码
def getShape(self,  node):
        """
        Gets the shape node from the input node.

        :param node (str): string name of input node

        Raises:
            `RuntimeError` if no shape node.
        Returns:
            (str) shape node name
        """
        if cmds.nodeType(node) == 'transform':
            shapes = cmds.listRelatives(node, shapes=True)

            if not shapes:
                raise RuntimeError('%s has no shape' % node)

            return shapes[0]

        elif cmds.nodeType(node) == "mesh":
            return node
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def get_deformers(obj, *args):
    """
    gets a list of deformers on the passed obj
    :param obj: string - the transform to get deformers on
    :param args:
    :return:
    """
    history = cmds.listHistory(obj)
    deformerList = []
    if history:
        for node in history:
            types = cmds.nodeType(node, inherited=True)
            if "geometryFilter" in types:
                deformerList.append(types[1])

    return(deformerList)
项目:core    作者:getavalon    | 项目源码 | 文件源码
def shape_from_element(element):
    """Return shape of given 'element'

    Supports components, meshes, and surfaces

    """

    try:
        # Get either shape or transform, based on element-type
        node = cmds.ls(element, objectsOnly=True)[0]
    except:
        cmds.warning("Could not find node in %s" % element)
        return None

    if cmds.nodeType(node) == 'transform':
        try:
            return cmds.listRelatives(node, shapes=True)[0]
        except:
            cmds.warning("Could not find shape in %s" % element)
            return None

    else:
        return node
项目:maya2katana    作者:ababak    | 项目源码 | 文件源码
def getNodeAttributes(node):
    '''
    Get Maya node attributes
    '''
    attributes = cmds.listAttr(node)
    attr = {}
    attr['nodeName'] = node
    attr['nodeType'] = cmds.nodeType(node)
    for attribute in attributes:
        if '.' in attribute:
            continue
        try:
            val = cmds.getAttr(node + '.' + attribute)
        except RuntimeError:
            continue
        attr[attribute] = val
    return attr
项目:maya2katana    作者:ababak    | 项目源码 | 文件源码
def processNode(node):
    '''
    Start individual node processing
    '''
    if 'name' not in node:
        return None
    nodeName = node['name']
    nodeType = node['type']
    if nodeType not in mappings:
        return None

    xmlPath = os.path.join(basedir, 'nodes', nodeType + '.xml')
    if not os.path.isfile(xmlPath) or mappings.get(nodeType) is None:
        return None

    tree = ET.parse(xmlPath)
    root = tree.getroot()

    root.attrib['name'] = nodeName
    xmlNode = root.find("./group_parameter/string_parameter[@name='name']")
    if xmlNode is not None:
        xmlNode.attrib['value'] = nodeName

    iterateMappingRecursive(mappings[nodeType], root, node)
    return root
项目:pw_mGeoExporter    作者:paulwinex    | 项目源码 | 文件源码
def getParent(self,name, filter=None):
        if cmds.objExists(name):
            if cmds.nodeType(name) == 'mesh':
                name = cmds.listRelatives(name, p=True, f=True)
            par = cmds.listRelatives(name, p=True, f=True)
            if par:
                parent = par[0].split('|')[-1]
                if filter:
                    tok = self.tokenPrefix(filter)
                    for t in tok:
                        if t in parent:
                            return parent
                    return self.getParent(par[0], filter)
                else:
                    return parent
            else:
                return 'NoParent'
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def getSkinCluster(mesh):
    '''
    Return the first skinCluster affecting this mesh.
    '''

    if mc.nodeType(mesh) in ('mesh','nurbsSurface','nurbsCurve'):
        shapes = [mesh]
    else:
        shapes = mc.listRelatives(mesh, shapes=True, path=True)

    for shape in shapes:
        history = mc.listHistory(shape, groupLevels=True, pruneDagObjects=True)
        if not history:
            continue
        skins = mc.ls(history, type='skinCluster')
        if skins:
            return skins[0]
    return None
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def pivot_driver_attr(node):
    '''
    Start with supporting pivots driven by remap value nodes, more support in the future as requested.
    '''
    #rpSrc = mc.listConnections(node+'.rotatePivot', source=True, destination=False, plugs=True)
    #if rpSrc and rpSrc[0].endswith('.translate') and mc.getAttr(rpSrc[0], keyable=True):
        #return rpSrc[0]

    for each in ('rotatePivotX', 'rotatePivotY', 'rotatePivotZ'):
        src = mc.listConnections(node+'.'+each, source=True, destination=False)
        if not src:
            continue
        srcType = mc.nodeType(src[0])
        if srcType == 'remapValue':
            src = mc.listConnections(src[0]+'.inputValue', source=True, destination=False, plugs=True)
            if src and mc.getAttr(src[0], keyable=True) and not mc.getAttr(src[0], lock=True):
                return src[0]
    return None
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def parent_group(source, transferTransform=True):
    """Create and transfer transforms to parent group"""
    assert cmds.objExists(source), "%s does not exist" % source
    assert cmds.nodeType(source) == "transform", (
        "%s must be transform" % source)

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

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

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

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

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

    return group
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def create_ncloth(input_mesh):
    """Replace Create nCloth menu item

    This performs the identical option of nCloth -> Create nCloth
    with the following changes.

    1. Input mesh not made intermediate
    2. Current mesh and shape named "currentMesh"

    Arguments:
        input_mesh (str): Path to shape

    """

    assert cmds.nodeType(input_mesh) == "mesh", (
        "%s was not of type mesh" % input_mesh)

    nucleus = cmds.createNode("nucleus", name="nucleus1")
    ncloth = cmds.createNode("nCloth", name="nClothShape1")
    current_mesh = cmds.createNode("mesh", name="currentMesh")

    cmds.connectAttr(input_mesh + ".worldMesh[0]", ncloth + ".inputMesh")
    cmds.connectAttr(ncloth + ".outputMesh", current_mesh + ".inMesh")
    cmds.connectAttr("time1.outTime", nucleus + ".currentTime")
    cmds.connectAttr("time1.outTime", ncloth + ".currentTime")
    cmds.connectAttr(ncloth + ".currentState", nucleus + ".inputActive[0]")
    cmds.connectAttr(ncloth + ".startState", nucleus + ".inputActiveStart[0]")
    cmds.connectAttr(nucleus + ".outputObjects[0]", ncloth + ".nextState")
    cmds.connectAttr(nucleus + ".startFrame", ncloth + ".startFrame")

    # Assign default shader
    cmds.sets(current_mesh, addElement="initialShadingGroup")

    return current_mesh
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def process(self, instance):
        from maya import cmds

        has_multiple_shapes = list()

        # Consider entire hierarchy of nodes included in an Instance
        hierarchy = cmds.listRelatives(instance, allDescendents=True)

        # Consider only nodes of type="mesh"
        meshes = cmds.ls(hierarchy, type="mesh", long=True)
        transforms = cmds.listRelatives(meshes, parent=True)

        for transform in set(transforms):
            shapes = cmds.listRelatives(transform, shapes=True) or list()

            # Ensure the one child is a shape
            has_single_shape = len(shapes) == 1
            self.log.info("has single shape: %s" % has_single_shape)

            # Ensure the one shape is of type "mesh"
            has_single_mesh = (
                has_single_shape and
                cmds.nodeType(shapes[0]) == "mesh"
            )
            self.log.info("has single mesh: %s" % has_single_mesh)

            if not all([has_single_shape, has_single_mesh]):
                has_multiple_shapes.append(transform)

        assert not has_multiple_shapes, (
            "\"%s\" has transforms with multiple shapes: %s" % (
                instance, ", ".join(
                    "\"" + member + "\"" for member in has_multiple_shapes))
        )
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def process(self, instance):
        import os
        from maya import cmds

        # Resources are optional
        if "resources_SEL" not in instance:
            return

        resources = dict()
        for resource in cmds.sets("resources_SEL", query=True):
            if cmds.nodeType(resource) == "reference":
                path = cmds.referenceQuery(resource,
                                           filename=True,
                                           unresolvedName=True)

            elif cmds.nodeType(resource) == "AlembicNode":
                path = cmds.getAttr(resource + ".abc_File")

            else:
                # Unsupported
                path = None

            resources[resource] = path

        # All resources were resolved
        assert all(resources.values()), (
            "Unsupported resource(s): " +
            ", ".join("'%s': '%s'" % (resource, path)
                      for resource, path in resources.items()
                      if path is not None)
        )

        # No resource contains an absolute path
        assert not any(os.path.isabs(fname) for fname in resources), (
            "Some resources are absolute: " +
            ", ".join(resources)
        )
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def get_shape(node, intermediate=False):
    """Get the shape node of a tranform

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

    :param node:  node The name of the node.
    :param intermediate:  intermediate True to get the intermediate shape
    :return: The name of the shape node.
    """
    if cmds.nodeType(node) == 'transform':
        shapes = cmds.listRelatives(node, shapes=True, path=True)
        if not shapes:
            shapes = []
        for shape in shapes:
            is_intermediate = cmds.getAttr('%s.intermediateObject' % shape)
            if intermediate and is_intermediate and cmds.listConnections(shape, source=False):
                return shape
            elif not intermediate and not is_intermediate:
                return shape
        if shapes:
            return shapes[0]
    elif cmds.nodeType(node) in ['mesh', 'nurbsCurve', 'nurbsSurface']:
        is_intermediate = cmds.getAttr('%s.intermediateObject' % node)
        if is_intermediate and not intermediate:
            node = cmds.listRelatives(node, parent=True, path=True)[0]
            return get_shape(node)
        else:
            return node
    return None
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def get_data(root):
    """Get the data dictionary that makes up a joint/transform hierarchy.  Non-transform
    branches will be skipped.
    :param root: The root node of the hierarchy to export.
    :return: A dictionary containing all data required to rebuild the hierarchy in Maya.
    """
    node_type = cmds.nodeType(root)
    shapes = cmds.listRelatives(root, children=True, shapes=True)
    if node_type not in ['joint', 'transform'] or (shapes and node_type == 'transform'):
        # Skip nodes that are not joints or transforms or if there are shapes below.
        return None
    # Store everything we need to recreate the node
    data = {
        'nodeType': node_type,
        'name': root,
        'translate': [truncate(x) for x in cmds.getAttr('{0}.t'.format(root))[0]],
        'rotate': [truncate(x) for x in cmds.getAttr('{0}.r'.format(root))[0]],
        'scale': [truncate(x) for x in cmds.getAttr('{0}.s'.format(root))[0]],
        'rotateOrder': cmds.getAttr('{0}.rotateOrder'.format(root)),
        'rotateAxis': [truncate(x) for x in cmds.getAttr('{0}.ra'.format(root))[0]],
        'children': [],
    }
    if node_type == 'joint':
        data['jointOrient'] = [truncate(x) for x in cmds.getAttr('{0}.jo'.format(root))[0]]
        data['radius'] = cmds.getAttr('{0}.radius'.format(root))
        data['side'] = cmds.getAttr('{0}.side'.format(root))
        data['type'] = cmds.getAttr('{0}.type'.format(root))
        data['otherType'] = cmds.getAttr('{0}.otherType'.format(root))
        data['jointTypeX'] = cmds.getAttr('{0}.jointTypeX'.format(root))
        data['jointTypeY'] = cmds.getAttr('{0}.jointTypeX'.format(root))
        data['jointTypeZ'] = cmds.getAttr('{0}.jointTypeX'.format(root))

    # Recurse down to all the children
    children = cmds.listRelatives(root, children=True, path=True) or []
    for child in children:
        child_data = get_data(child)
        if child_data:
            data['children'].append(child_data)
    return data
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def dump(curves=None, stack=False):
    """Get a data dictionary representing all the given curves.

    :param curves: Optional list of curves.
    :return: A json serializable list of dictionaries containing the data required to recreate the curves.
    """
    if curves is None:
        curves = cmds.ls(sl=True) or []
    data = []
    for node in curves:
        shape = shortcuts.get_shape(node)
        if cmds.nodeType(shape) == 'nurbsCurve':
            control = {
                'name': node,
                'cvs': cmds.getAttr('{0}.cv[*]'.format(node)),
                'degree': cmds.getAttr('{0}.degree'.format(node)),
                'form': cmds.getAttr('{0}.form'.format(node)),
                'xform': cmds.xform(node, q=True, ws=True, matrix=True),
                'knots': get_knots(node),
                'pivot': cmds.xform(node, q=True, rp=True),
                'overrideEnabled': cmds.getAttr('{0}.overrideEnabled'.format(node)),
                'overrideRGBColors': cmds.getAttr('{0}.overrideRGBColors'.format(node)),
                'overrideColorRGB': cmds.getAttr('{0}.overrideColorRGB'.format(node))[0],
                'overrideColor': cmds.getAttr('{0}.overrideColor'.format(node)),
            }
            if stack:
                control['stack'] = get_stack_count(node)
                control['parent'] = get_stack_parent(node)
            data.append(control)
    if curves:
        cmds.select(curves)
    return data
项目:pipeline    作者:liorbenhorin    | 项目源码 | 文件源码
def list_referenced_files():
    results = []
    links = cmds.filePathEditor(query=True, listDirectories="")
    for link in links:
        pairs =  cmds.filePathEditor(query=True, listFiles=link, withAttribute=True, status=True)
        '''
        paris: list of strings ["file_name node status ...", "file_name node status ...",...]
        we need to make this large list of ugly strings (good inforamtion seperated by white space) into a dictionry we can use
        '''        
        l = len(pairs)
        items = l/3
        order = {}
        index = 0

        '''
        order: dict of {node: [file_name, status],...}
        '''

        for i in range(0,items):
            order[pairs[index+1]] = [os.path.join(link,pairs[index]),pairs[index+1],pairs[index+2]]
            index = index + 3  

        for key in order:            
            # for each item in the dict, if the status is 0, repath it
            if order[key][2] == "1": 
                results.append([order[key][0],cmds.nodeType(order[key][1])])

    return results
项目:sfx    作者:theodox    | 项目源码 | 文件源码
def test_sfx_create(self):
        new_network = SFXNetwork.create('example')
        assert cmds.ls('example') == ['example']
        assert cmds.nodeType('example') == 'ShaderfxShader'
        assert new_network.shader == 'example'
项目:mayakit    作者:danbradham    | 项目源码 | 文件源码
def get_history(node, node_type=None):

    history = cmds.listHistory(node)
    if not node_type:
        return history

    return [n for n in history if cmds.nodeType(n) == node_type]
项目:mayakit    作者:danbradham    | 项目源码 | 文件源码
def add_curves_to_hair_system():

    sel = cmds.ls(sl=True, dag=True, leaf=True, long=True)
    if len(sel) < 2:
        cmds.warning('Select a bunch of curves and a hairSystem node.')
        return

    curves = sel[:-1]
    hair_system = sel[-1].split('|')[-1]
    if cmds.nodeType(hair_system) != 'hairSystem':
        cmds.warning(hair_system + ' is not a hairSystem.')
        return

    for curve in curves:
        add_curve_to_system(curve, hair_system)
项目:pyblish-starter    作者:pyblish    | 项目源码 | 文件源码
def process(self, instance):
        import os
        from maya import cmds

        # Resources are optional
        if "resources_SEL" not in instance:
            return

        resources = dict()
        for resource in cmds.sets("resources_SEL", query=True):
            if cmds.nodeType(resource) == "reference":
                path = cmds.referenceQuery(resource,
                                           filename=True,
                                           unresolvedName=True)

            elif cmds.nodeType(resource) == "AlembicNode":
                path = cmds.getAttr(resource + ".abc_File")

            else:
                # Unsupported
                path = None

            resources[resource] = path

        # All resources were resolved
        assert all(resources.values()), (
            "Unsupported resource(s): " +
            ", ".join("'%s': '%s'" % (resource, path)
                      for resource, path in resources.items()
                      if path is not None)
        )

        # No resource contains an absolute path
        assert not any(os.path.isabs(fname) for fname in resources), (
            "Some resources are absolute: " +
            ", ".join(resources)
        )
项目: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
项目:pw_mGeoExporter    作者:paulwinex    | 项目源码 | 文件源码
def getStereoRigShapeNode(self, name):
        sh = cmds.listRelatives(name, s=1)
        for s in sh:
            if cmds.nodeType(s) == 'stereoRigCamera':
                return s
            else:
                return name
项目:pw_mGeoExporter    作者:paulwinex    | 项目源码 | 文件源码
def getNodeType(self, iter):
        obj = om.MObject()
        iter.getDependNode(obj)
        dep = om.MFnDependencyNode(obj)
        return cmds.nodeType(dep.name())
项目:pw_mGeoExporter    作者:paulwinex    | 项目源码 | 文件源码
def readCustomAttrib(self, iter):
        # attribs = self.tokenPrefix(self.op['exppivattrib'][1])
        # attribs = self.tokenAttributes(attribs)
        attribs = self.reorderAttrs(self.op['exppivattrib'][1])
        dagPath = om.MDagPath()
        nodes = []
        while not iter.isDone():
            iter.getDagPath( dagPath )
            nd = cmds.nodeType(dagPath.fullPathName())
            if nd in self.spetialObjectsList:
                proc = self.spetialObjectsList[nd]
                objName = proc(dagPath.fullPathName())
            else:
                try:
                    dagPath.extendToShape()
                except:
                    pass
                    print 'No shape for', dagPath.fullPathName()
                objName = dagPath.fullPathName()
            nodes.append(objName)
            iter.next()
        iter.reset()
        checked, pp = self.checkAttribtypes(nodes, attribs)
        for i, node in enumerate(nodes):
            for attr in checked:
                renamed = self.checkLegalChar(checked[attr][2]) or self.checkLegalChar(attr)
                if not renamed in self.pointAttribArray:
                    self.pointAttribArray[renamed] = []
                default = checked[attr][0]
                value = self.getAttribFromNode(node, attr, checked[attr][1], default)
                if value is None:
                    value = default
                self.defaultValues[renamed] = default
                self.pointAttribArray[renamed] += ([value])


###################################
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def getChannelFromAnimCurve(curve, plugs=True):
    '''
    Finding the channel associated with a curve has gotten really complicated since animation layers.
    This is a recursive function which walks connections from a curve until an animated channel is found.
    '''


    #we need to save the attribute for later.
    attr = ''
    if '.' in curve:
        curve, attr = curve.split('.')

    nodeType = mc.nodeType(curve)
    if nodeType.startswith('animCurveT') or nodeType.startswith('animBlendNode'):
        source = mc.listConnections(curve+'.output', source=False, plugs=plugs)
        if not source and nodeType=='animBlendNodeAdditiveRotation':
            #if we haven't found a connection from .output, then it may be a node that uses outputX, outputY, etc.
            #get the proper attribute by using the last letter of the input attribute, which should be X, Y, etc.
            #if we're not returning plugs, then we wont have an attr suffix to use, so just use X.
            attrSuffix = 'X'
            if plugs:
                attrSuffix = attr[-1]

            source = mc.listConnections(curve+'.output'+attrSuffix, source=False, plugs=plugs)
        if source:
            nodeType = mc.nodeType(source[0])
            if nodeType.startswith('animCurveT') or nodeType.startswith('animBlendNode'):
                return getChannelFromAnimCurve(source[0], plugs=plugs)
            return source[0]
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def getCurrentCamera():
    '''
    Returns the camera that you're currently looking through.
    If the current highlighted panel isn't a modelPanel, 
    '''

    panel = mc.getPanel(withFocus=True)

    if mc.getPanel(typeOf=panel) != 'modelPanel':
        #just get the first visible model panel we find, hopefully the correct one.
        for p in mc.getPanel(visiblePanels=True):
            if mc.getPanel(typeOf=p) == 'modelPanel':
                panel = p
                mc.setFocus(panel)
                break

    if mc.getPanel(typeOf=panel) != 'modelPanel':
        OpenMaya.MGlobal.displayWarning('Please highlight a camera viewport.')
        return False

    camShape = mc.modelEditor(panel, query=True, camera=True)
    if not camShape:
        return False

    camNodeType = mc.nodeType(camShape)
    if mc.nodeType(camShape) == 'transform':
        return camShape
    elif mc.nodeType(camShape) in ['camera','stereoRigCamera']:
        return mc.listRelatives(camShape, parent=True, path=True)[0]
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def clone(shape, worldspace=False):
    """Clone `shape`

    Arguments:
        shape (str): Absolute path to shape
        worldspace (bool, optional): Whether or not to consider worldspace

    Returns:
        node (str): Newly created clone

    """

    type = cmds.nodeType(shape)
    assert type in ("mesh", "nurbsSurface", "nurbsCurve"), (
        "clone() works on polygonal and nurbs surfaces")

    src, dst = {
        "mesh": (".outMesh", ".inMesh"),
        "nurbsSurface": (".local", ".create"),
        "nurbsCurve": (".local", ".create"),
    }[type]

    nodetype = cmds.nodeType(shape)

    name = lib.unique(name=shape.rsplit("|")[-1])
    clone = cmds.createNode(nodetype, name=name)

    cmds.connectAttr(shape + src, clone + dst, force=True)

    if worldspace:
        transform = cmds.createNode("transformGeometry",
                                    name=name + "_transformGeometry")

        cmds.connectAttr(shape + src,
                         transform + ".inputGeometry", force=True)
        cmds.connectAttr(shape + ".worldMatrix[0]",
                         transform + ".transform", force=True)
        cmds.connectAttr(transform + ".outputGeometry",
                         clone + dst, force=True)

    # Assign default shader
    cmds.sets(clone, addElement="initialShadingGroup")

    return clone
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def follicle(*args):
    supported = ["mesh", "nurbsSurface"]
    selection = cmds.ls(sl=1)

    new_follicles = []
    for sel in selection:
        uv = lib.uv_from_element(sel)

        geometry_shape = lib.shape_from_element(sel)
        geometry_transform = cmds.listRelatives(geometry_shape, parent=True)[0]

        # Figure out output connection
        inputs = [".inputMesh", ".inputSurface"]
        outputs = [".outMesh", ".local"]

        failed = False
        type = cmds.nodeType(geometry_shape)
        if type not in supported:
            failed = True
            shapes = cmds.listRelatives(geometry_shape, shapes=True)

            if shapes:
                geometry_shape = shapes[0]
                type = cmds.nodeType(geometry_shape)
                if type in supported:
                    failed = False

        if failed:
            cmds.error("Skipping '%s': Type not accepted" % type)
            return

        input = inputs[supported.index(type)]
        output = outputs[supported.index(type)]

        # Make follicle
        follicle = cmds.createNode("follicle",
                                   name=geometry_transform + "_follicleShape1")
        follicle_transform = cmds.listRelatives(follicle, parent=True)[0]
        follicle_transform = cmds.rename(follicle_transform,
                                         geometry_transform + "_follicle1")

        # Set U and V value
        cmds.setAttr(follicle + ".parameterU", uv[0])
        cmds.setAttr(follicle + ".parameterV", uv[1])

        # Make the connections
        cmds.connectAttr(follicle + ".outTranslate",
                         follicle_transform + ".translate")
        cmds.connectAttr(follicle + ".outRotate",
                         follicle_transform + ".rotate")
        cmds.connectAttr(geometry_shape + output,
                         follicle + input)

        # Select last
        new_follicles.append(follicle_transform)

    # Select newly created follicles
    if new_follicles:
        cmds.select(new_follicles, r=1)

    return new_follicles
项目:maya-capture-gui    作者:Colorbleed    | 项目源码 | 文件源码
def get_current_camera():
    """Returns the currently active camera.

    Searched in the order of:
        1. Active Panel
        2. Selected Camera Shape
        3. Selected Camera Transform

    Returns:
        str: name of active camera transform

    """

    # Get camera from active modelPanel  (if any)
    panel = cmds.getPanel(withFocus=True)
    if cmds.getPanel(typeOf=panel) == "modelPanel":
        cam = cmds.modelEditor(panel, query=True, camera=True)
        # In some cases above returns the shape, but most often it returns the
        # transform. Still we need to make sure we return the transform.
        if cam:
            if cmds.nodeType(cam) == "transform":
                return cam
            # camera shape is a shape type
            elif cmds.objectType(cam, isAType="shape"):
                parent = cmds.listRelatives(cam, parent=True, fullPath=True)
                if parent:
                    return parent[0]

    # Check if a camShape is selected (if so use that)
    cam_shapes = cmds.ls(selection=True, type="camera")
    if cam_shapes:
        return cmds.listRelatives(cam_shapes,
                                  parent=True,
                                  fullPath=True)[0]

    # Check if a transform of a camShape is selected
    # (return cam transform if any)
    transforms = cmds.ls(selection=True, type="transform")
    if transforms:
        cam_shapes = cmds.listRelatives(transforms, shapes=True, type="camera")
        if cam_shapes:
            return cmds.listRelatives(cam_shapes,
                                      parent=True,
                                      fullPath=True)[0]
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def follicle(surface="none", folName="none", u=0.5, v=0.5, *args):
    """
    creates a follicle on a surface based on the uv input.
    Args are: surface, folName, u, v
    """
#------------do a bit more checking here to make sure the shapes, numbers etc work out
    if surface=="none":
        #decide if surface is polymesh or nurbsSurface
        surfaceXform = cmds.ls(sl=True, dag=True, type="transform")[0]
        surfaceShape = cmds.listRelatives(surfaceXform, shapes=True)[0]
    else:
        surfaceXform = surface
        surfaceShape = cmds.listRelatives(surfaceXform, shapes=True)[0]

    if folName == "none":
        folShapeName = "myFollicleShape"
        folXformName = "myFollicle"
    else:
        folShapeName = "%sShape"%folName
        folXformName = folName

#------------test if follicle exists
    #create the follicle
    folShape = cmds.createNode("follicle", n=folShapeName)
    folXform = cmds.listRelatives(folShape, p=True, type="transform")[0]
    cmds.rename(folXform, folXformName)

    #connect up the follicle!
    #connect the matrix of the surface to the matrix of the follicle
    cmds.connectAttr("%s.worldMatrix[0]"%surfaceShape, "%s.inputWorldMatrix"%folShape)

    #check for surface type, poly or nurbs and connect the matrix into the follicle
    if (cmds.nodeType(surfaceShape)=="nurbsSurface"):
        cmds.connectAttr("%s.local"%surfaceShape, "%s.inputSurface"%folShape)
    elif (cmds.nodeType(surfaceShape)=="mesh"):
        cmds.connectAttr("%s.outMesh"%surfaceShape, "%s.inputMesh"%folShape)
    else:
        cmds.warning("not the right kind of selection. Need a poly or nurbs surface")

    #connect the transl, rots from shape to transform of follicle
    cmds.connectAttr("%s.outTranslate"%folShape, "%s.translate"%folXform)
    cmds.connectAttr("%s.outRotate"%folShape, "%s.rotate"%folXform)

    cmds.setAttr("%s.parameterU"%folShape, u)
    cmds.setAttr("%s.parameterV"%folShape, v)

    cmds.setAttr("%s.translate"%folXform, l=True)
    cmds.setAttr("%s.rotate"%folXform, l=True)

    return(folXform, folShape)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def zbw_follicle(surface="none", folName="none", u=0.5, v=0.5, *args):

#------------do a bit more checking here to make sure the shapes, numbers etc work out
    if surface=="none":
        #decide if surface is polymesh or nurbsSurface
        surfaceXform = cmds.ls(sl=True, dag=True, type="transform")[0]
        surfaceShape = cmds.listRelatives(surfaceXform, shapes=True)[0]
    else:
        surfaceXform = surface
        surfaceShape = cmds.listRelatives(surfaceXform, shapes=True)[0]

    if folName == "none":
        folShapeName = "myFollicleShape"
        folXformName = "myFollicle"
    else:
        folShapeName = "%sShape"%folName
        folXformName = folName

    #create the follicle
    folShape = cmds.createNode("follicle", n=folShapeName)
    folXform = cmds.listRelatives(folShape, p=True, type="transform")[0]
    cmds.rename(folXform, folXformName)

    #connect up the follicle!
    #connect the matrix of the surface to the matrix of the follicle
    cmds.connectAttr("%s.worldMatrix[0]"%surfaceShape, "%s.inputWorldMatrix"%folShape)

    #check for surface type, poly or nurbs and connect the matrix into the follicle
    if (cmds.nodeType(surfaceShape)=="nurbsSurface"):
        cmds.connectAttr("%s.local"%surfaceShape, "%s.inputSurface"%folShape)
    elif (cmds.nodeType(surfaceShape)=="mesh"):
        cmds.connectAttr("%s.outMesh"%surfaceShape, "%s.inputMesh"%folShape)
    else:
        cmds.warning("not the right kind of selection. Need a poly or nurbs surface")

    #connect the transl, rots from shape to transform of follicle
    cmds.connectAttr("%s.outTranslate"%folShape, "%s.translate"%folXform)
    cmds.connectAttr("%s.outRotate"%folShape, "%s.rotate"%folXform)

    cmds.setAttr("%s.parameterU"%folShape, u)
    cmds.setAttr("%s.parameterV"%folShape, v)

    cmds.setAttr("%s.translate"%folXform, l=True)
    cmds.setAttr("%s.rotate"%folXform, l=True)

    return(folXform, folShape)
项目:maya2katana    作者:ababak    | 项目源码 | 文件源码
def preprocessNode(nodeName):
    '''
    Preprocessing a node.
    This is needed as some nodes (like ramp or bump) can be
    replaced by several other nodes for Katana.
    We return either one original node or several
    nodes if something was replaced during preprocessing
    '''
    nodeType = cmds.nodeType(nodeName)
    if nodeType not in premap:
        return None
    nodes = {}
    attributes = getNodeAttributes(nodeName)
    connections = {}
    nodeConnections = cmds.listConnections(nodeName, source=True, destination=False, connections=True, plugs=True)
    if nodeConnections:
        for i in range(len(nodeConnections) / 2):
            connTo = nodeConnections[i * 2]
            connTo = connTo[connTo.find('.') + 1:]
            connFrom = nodeConnections[i * 2 + 1]
            connections[connTo] = {
                'node': connFrom[:connFrom.find('.')],
                'originalPort': connFrom[connFrom.find('.') + 1:]
            }

    node = {
        'name': nodeName,
        'type': nodeType,
        'attributes': attributes,
        'connections': connections,
        'renamings': {}
    }
    premapSettings = premap[nodeType]
    for attr in ['type', 'postprocess']:
        if premapSettings.get(attr):
            node[attr] = premapSettings.get(attr)
    if premapSettings.get('preprocess'):
        preprocessFunc = premapSettings.get('preprocess')
        if preprocessFunc:
            preprocessResult = preprocessFunc(node)
            if preprocessResult:
                nodes.update(preprocessResult)
    else:
        nodes[node['name']] = node
    return nodes
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def parentShape(child=None, parent=None, maintainOffset=True):
    '''
    Parent a child shape node to a parent transform. The child node can be a shape,
    or a transform which has any number of shapes.
    '''

    if not child or not parent:
        sel = mc.ls(sl=True)
        if sel and len(sel) > 1:
            child = sel[:-1]
            parent = sel[-1]
        else:
            OpenMaya.MGlobal.displayWarning('Please make a selection.')
            return

    parentNodeType = mc.nodeType(parent)
    if not parentNodeType in ('transform', 'joint', 'ikHandle'):
        OpenMaya.MGlobal.displayWarning('Parent must be a transform node.')
        return

    if not isinstance(child, (list, tuple)):
        child = [child]

    newChild = unparentShape(child)

    shapes = list()
    for each in newChild:
        thisChild = mc.parent(each, parent)[0]
        mc.makeIdentity(thisChild, apply=True)

        for s in mc.listRelatives(thisChild, shapes=True, noIntermediate=True, path=True):
            shape = mc.parent(s, parent, shape=True, relative=True)[0]
            #move to bottom
            mc.reorder(shape, back=True)

            #rename
            parentName = mc.ls(parent, shortNames=True)[0]
            shapes.append(mc.rename(shape, parentName+'Shape#'))

    mc.delete(newChild)

    for each in child:
        if not mc.listRelatives(each):
            #if it doesn't have any kids, delete it
            mc.delete(each)

    return shapes
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def unparentShape(objs=None):

    if not objs:
        objs = mc.ls(sl=True)
        if not objs:
            OpenMaya.MGlobal.displayWarning('Please select one or more nodes with shapes to unparent.')
            return
    elif not isinstance(objs, (list,tuple)):
        objs = [objs]

    #are these shapes or transforms
    transforms = list()
    shapes = list()
    for obj in objs:
        nodeType = mc.nodeType(obj)
        if nodeType in ('mesh','nurbsCurve','nurbsSurface','locator','annotationShape'):
            shapes.append(obj)
        elif nodeType in ('transform', 'joint', 'ikHandle'):
            if not mc.listRelatives(obj, shapes=True, path=True, noIntermediate=True):
                OpenMaya.MGlobal.displayWarning(obj+' has no shapes, skipping.')
                return
            transforms.append(obj)
        else:
            OpenMaya.MGlobal.displayWarning(obj+' must be a shape, or a transform with shapes. Skipping')
            return

    for each in transforms:
        childShapes = mc.listRelatives(each, shapes=True, path=True, noIntermediate=True)
        shapes.extend([x for x in childShapes if x not in shapes])

    #shapes that share a common parent get unparented together
    newTransforms = dict()
    for each in shapes:
        shapeParent = mc.listRelatives(each, parent=True, fullPath=True)[0]
        if not shapeParent in newTransforms:
            newTransforms[shapeParent] = mc.createNode('transform', name='unparentedShape#')
            newTransforms[shapeParent] = mc.parent(newTransforms[shapeParent], shapeParent)[0]
            mc.setAttr(newTransforms[shapeParent]+'.translate', 0,0,0)
            mc.setAttr(newTransforms[shapeParent]+'.rotate', 0,0,0)
            mc.setAttr(newTransforms[shapeParent]+'.scale', 1,1,1)
            newTransforms[shapeParent] = mc.parent(newTransforms[shapeParent], world=True)[0]

        shape = mc.parent(each, newTransforms[shapeParent], shape=True, relative=True)[0]
    return newTransforms.values()