Exemple #1
0
def set_index_position(mesh_obj, vertex_index=0, position=()):
    """
    sets the position of the vertex index.
    :param mesh_obj:
    :param vertex_index: <int> set the position for this vertex index.
    :param position: <tuple> the position vector to set the index at.
    :return: <bool> True for success.
    """
    mesh_obj = object_utils.get_m_obj(mesh_obj)

    # if nurbsSurface shape
    if object_utils.is_shape_nurbs_surface(mesh_obj):
        s_iter = OpenMaya.MItSurfaceCV(mesh_obj)
        while not s_iter.isDone():
            index_num = s_iter.index()
            if vertex_index == index_num:
                s_iter.setPosition(OpenMaya.MPoint(
                    OpenMaya.MVector(*position)))
                break
            s_iter.next()

    # if mesh shape
    if object_utils.is_shape_mesh(mesh_obj):
        msh_iter = OpenMaya.MItMeshVertex(mesh_obj)
        while not msh_iter.isDone():
            index_num = msh_iter.index()
            if vertex_index == index_num:
                msh_iter.setPosition(
                    OpenMaya.MPoint(OpenMaya.MVector(*position)))
                break
            msh_iter.next()
    return True
def get_mfn_anim_node(object_node):
    """
    returns an OpenMaya.MFnAnimCurve object from the object specified.
    :param object_node: <str> object node.
    :return: <OpenMaya.MFnAnimCurve> maya object.
    """
    return OpenMayaAnim.MFnAnimCurve(object_utils.get_m_obj(object_node))
    def __init__(self,
                 maya_node="",
                 all_attrs=False,
                 keyable=False,
                 custom=False,
                 connected=False):
        self.MAYA_M_OBJECT = object_utils.get_m_obj(maya_node)
        self.MAYA_MFN_OBJECT = object_utils.get_mfn_obj(maya_node)
        self.OBJECT_NODE_TYPE = self.MAYA_MFN_OBJECT.typeName()
        self.MAYA_STR_OBJECT = self.MAYA_MFN_OBJECT.name()
        # self.MAYA_STR_OBJECT = maya_node
        self.attr_data = {}
        self._hash = None

        self.DEFAULT_ATTRS = self.get_attribute_list()
        self.get_attributes(all_attrs=all_attrs,
                            keyable=keyable,
                            custom=custom,
                            connected=connected)

        # get only the keyable custom attributes
        if keyable and custom and self.attr_data:
            new_data = {}
            for a_name in list(set(self.attr_data) - set(self.DEFAULT_ATTRS)):
                if self.is_attr_keyable(a_name):
                    new_data[a_name] = self.attr_data[a_name]
            self.attr_data = new_data
Exemple #4
0
def attach_follicle(mesh_name, follicle_object="", follicle_name=""):
    """
    attaches a follicle to the specified mesh object.
    :param follicle_object: <str> the follicle object to use.
    :param follicle_name: <str> the follicle name to use when creating new follicle nodes.
    :param mesh_name: <str> the shape object name. Could be a nurbsSurface to a mesh object.
    :return: <bool> True for success. <bool> False for failure.
    """
    # get the first mesh shape, we don't want a Shape Orig
    shape_m_obj_array = object_utils.get_shape_obj(mesh_name)[0],
    shape_name_array = object_utils.get_shape_name(mesh_name)[0],

    follicles = ()
    for shape_m_obj, shape_name in zip(shape_m_obj_array, shape_name_array):
        if follicle_name:
            follicle_shape_name = create_follicle_node(name=follicle_name)
            follicle_name = object_utils.get_parent_name(follicle_shape_name)[0]
        elif not follicle_name and follicle_object:
            if object_utils.has_fn(follicle_object, 'transform'):
                follicle_shape_name = object_utils.get_shape_name(follicle_object)[0]
                follicle_name = follicle_object
            elif object_utils.has_fn(follicle_object, 'follicle'):
                follicle_name = object_utils.get_parent_name(follicle_object)[0]
                follicle_shape_name = follicle_object
            elif object_utils.has_fn(follicle_object, 'component'):
                follicle_shape_name = object_utils.get_shape_name(follicle_object)[0]
                follicle_name = object_utils.get_parent_name(follicle_object)[0]
            else:
                m_obj = object_utils.get_m_obj(follicle_object)
                print(m_obj.apiTypeStr())
                raise NotImplementedError("[AttachFollicle] :: Could not get follicle node name.")

        follicles += follicle_name,

        if object_utils.check_shape_type_name(shape_m_obj, 'nurbsSurface'):
            attr_connect(attr_name(shape_name, 'matrix'), attr_name(follicle_shape_name, 'inputWorldMatrix'))
            attr_connect(attr_name(shape_name, 'worldSpace[0]'), attr_name(follicle_shape_name, 'inputSurface'))

        elif object_utils.check_shape_type_name(shape_m_obj, 'mesh'):
            attr_connect(attr_name(shape_name, 'worldMatrix[0]'), attr_name(follicle_shape_name, 'inputWorldMatrix'))
            attr_connect(attr_name(shape_name, 'outMesh'), attr_name(follicle_shape_name, 'inputMesh'))

        elif object_utils.check_shape_type_name(shape_m_obj, 'nurbsCurve'):
            attr_connect(attr_name(shape_name, 'worldMatrix[0]'), attr_name(follicle_shape_name, 'inputWorldMatrix'))
            attr_connect(attr_name(shape_name, 'worldSpace[0]'), attr_name(follicle_shape_name, 'inputCurve'))

        attr_connect(attr_name(follicle_shape_name, 'outRotate'), attr_name(follicle_name, 'rotate'))
        attr_connect(attr_name(follicle_shape_name, 'outTranslate'), attr_name(follicle_name, 'translate'))
    return follicles
Exemple #5
0
def get_mirror_index(mesh_obj,
                     vertex_index=0,
                     world_space=False,
                     object_space=False,
                     deviation_delta=0.00):
    """
    gets the mirror mesh vertex index.
    :param mesh_obj: <str> the mesh object to get mesh data from.
    :param vertex_index: <int> get the position data from this vertex point.
    :param world_space: <bool> if True, get the data from worldSpace position coordinates.
    :param object_space: <bool> if True, get the data from objectSpace position coordinates.
    :param deviation_delta: <float> the deviation delta to get vertex position comparison from.
    :return: <bool>, <bool> False, False for failure. <int>, <tuple> for success.
    """
    mesh_obj = object_utils.get_m_obj(mesh_obj)

    # if nurbsSurface shape
    if object_utils.is_shape_nurbs_surface(mesh_obj):
        msh_iter = OpenMaya.MItSurfaceCV(mesh_obj)

    # if mesh shape
    if object_utils.is_shape_mesh(mesh_obj):
        msh_iter = OpenMaya.MItMeshVertex(mesh_obj)

    # grab the position the index is at
    while not msh_iter.isDone():
        index_num = msh_iter.index()
        if vertex_index == index_num:
            m_point = msh_iter.position(get_space(world_space, object_space))
            break
        msh_iter.next()

    # now find the mirror vertex index by comparing the mirror position
    while not msh_iter.isDone():
        find_point = msh_iter.position(get_space(world_space, object_space))
        index_num = msh_iter.index()
        vector1 = find_point.x, find_point.y, find_point.z
        vector2 = m_point.x * -1, m_point.y, m_point.z
        # compare the second vector with a deviation relative to the first vector
        if compare_positions(vector1,
                             vector2,
                             deviation_delta=deviation_delta,
                             interval_comparison=True):
            return index_num, vector1
        msh_iter.next()
    return False, False
def get_anim_connections(object_name=""):
    """
    get plug connections
    :param object_name:
    :return: <dict> found animation connection plugs.
    """
    found_nodes = {}

    for cur_node in connections_gen(object_utils.get_m_obj(object_name)):
        if cur_node.hasFn(OpenMaya.MFn.kBlendWeighted):
            plugs = object_utils.get_plugs(
                cur_node, source=False, ignore_nodes=['kBlendWeighted', 'kUnitConversion', 'kNodeGraphEditorInfo'])

            if "targets" not in found_nodes:
                found_nodes["targets"] = []

            # get plug nodes
            found_nodes["targets"].extend(plugs)

        # find what the curve nodes are attached to.
        if cur_node.hasFn(OpenMaya.MFn.kAnimCurve):
            if "source" not in found_nodes:
                found_nodes["source"] = []
            plugs = object_utils.get_plugs(cur_node, source=True)
            for p_node in plugs:
                if p_node not in found_nodes["source"]:
                    found_nodes["source"].append(p_node)

            # collect anim nodes.
            if "animNodes" not in found_nodes:
                found_nodes["animNodes"] = {}
            anim_fn = OpenMayaAnim.MFnAnimCurve(cur_node)
            if anim_fn.numKeys():
                anim_node = OpenMaya.MFnDependencyNode(cur_node).name()
                found_nodes["animNodes"].update(get_animation_data_from_node(anim_node))
    # change the lists into tuples
    if "source" in found_nodes:
        if found_nodes["source"]:
            found_nodes["source"] = tuple(found_nodes["source"])
    if "targets" in found_nodes:
        if found_nodes["targets"]:
            found_nodes["targets"] = tuple(found_nodes["targets"])
    return found_nodes
def connections_gen(object_name="", attribute="", direction='kDownstream', level='kPlugLevel', ftype=''):
    """
    get plug connections
    :param object_name: <str> object to check connections frOpenMaya.
    :param direction: <str> specify which direction to traverse.
    :param attribute: <str> find nodes connected to this attribute.
    :param ftype: <str> specify which type to filter.
    :param level: <str> specify which level to traverse.
    """
    # define function variables
    node = object_utils.get_m_obj(object_name)
    direction = eval('OpenMaya.MItDependencyGraph.{}'.format(direction))
    level = eval('OpenMaya.MItDependencyGraph.{}'.format(level))
    if ftype:
        ftype = eval('OpenMaya.MFn.{}'.format(ftype))

        # initiate the iterator object
        dag_iter = OpenMaya.MItDependencyGraph(
            node,
            ftype,
            direction
        )
    else:
        # initiate the iterator object
        dag_iter = OpenMaya.MItDependencyGraph(
            node,
            direction,
            level
        )
    dag_iter.reset()

    # iterate the dependency graph to find what we want.
    while not dag_iter.isDone():
        if not attribute:
            yield object_utils.Item(dag_iter.currentItem())
        elif attribute:
            attribute_name = '{}.{}'.format(object_name, attribute)
            item = object_utils.Item(dag_iter.currentItem())
            plugs = item.source_plugs()
            if filter(lambda x: attribute_name in x, plugs):
                yield item
        dag_iter.next()
def get_animation_data_from_node(object_node=""):
    """
    get the animation data from the node specified.
    :param object_node: <str> the object to check the data frOpenMaya.
    :return: <dict> key data.
    """
    if not object_node:
        return False

    o_anim = None
    if isinstance(object_node, (str, unicode)):
        m_object = object_utils.get_m_obj(object_node)
        o_anim = OpenMayaAnim.MFnAnimCurve(m_object)

    if isinstance(object_node, OpenMayaAnim.MFnAnimCurve):
        o_anim = object_node
        object_node = o_anim.name()

    if isinstance(object_node, OpenMaya.MObject):
        o_anim = OpenMayaAnim.MFnAnimCurve(object_node)
        object_node = o_anim.name()

    # get connections
    source_attr = object_utils.get_plugs(
        object_node, source=True)
    destination_attr = object_utils.get_plugs(
        object_node, source=False,
        ignore_nodes=['kUnitConversion', 'kBlendWeighted', 'kNodeGraphEditorInfo'])

    # get the time from the keys supplied
    number_of_keys = o_anim.numKeys()
    anim_data = {}
    if number_of_keys > 1:
        anim_data[object_node] = {'data': {},
                                  'tangents': {},
                                  'sourceAttr': source_attr,
                                  'targetAttr': destination_attr
                                  }
        for i_key in xrange(number_of_keys):
            # this is a lie
            # i_x = _float_ptr.get_float_ptr()
            # i_y = _float_ptr.get_float_ptr()
            #
            # o_x = _float_ptr.get_float_ptr()
            # o_y = _float_ptr.get_float_ptr()
            #
            # o_anim.getTangent(i_key, i_x, i_y, True)
            # o_anim.getTangent(i_key, o_x, o_y, True)
            # this is a lie
            # v_float = o_anim.value(i_key)

            # this will get me the values that I want.
            # anim_data[object_node]['tangents'][i_key] = (ScriptUtil(i_x).asFloat(), ScriptUtil(i_y).asFloat(),
            #                                              ScriptUtil(o_x).asFloat(), ScriptUtil(o_y).asFloat())
            # anim_data[object_node]['tangents'][i_key] = (ScriptUtil(o_x).asFloat(), ScriptUtil(o_y).asFloat())

            # get the information the standard way
            v_float = cmds.keyframe(object_node, q=1, valueChange=1)[i_key]
            try:
                t_float = cmds.keyframe(object_node, floatChange=1, q=1)[i_key]
            except TypeError:
                t_float = i_key
            o_x = cmds.getAttr('{}.keyTanOutX[{}]'.format(object_node, i_key))
            o_y = cmds.getAttr('{}.keyTanOutY[{}]'.format(object_node, i_key))
            i_x = cmds.getAttr('{}.keyTanInX[{}]'.format(object_node, i_key))
            i_y = cmds.getAttr('{}.keyTanInY[{}]'.format(object_node, i_key))

            # save the information
            anim_data[object_node]['tangents'][t_float] = {'out': (o_x, o_y),
                                                           'in': (i_x, i_y),
                                                           'keyNum': i_key}
            anim_data[object_node]['data'][t_float] = v_float
    return anim_data