Python maya.OpenMaya.MIntArray() Examples

The following are 30 code examples of maya.OpenMaya.MIntArray(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module maya.OpenMaya , or try the search function .
Example #1
Source File: conversion.py    From maya-skinning-tools with GNU General Public License v3.0 6 votes vote down vote up
def asMIntArray(index):
    """
    index -> OpenMaya.MIntArray

    :param int/list of ints/OpenMaya.MIntArray index: indices
    :return: Array of indices
    :rtype: OpenMaya.MIntArray
    """
    if type(index) != OpenMaya.MIntArray:
        array = OpenMaya.MIntArray()
        if type(index) == list:
            for i in index:
                array.append(i)
        else:
            array.append(index)

        return array

    return index 
Example #2
Source File: utils.py    From maya-retarget-blendshape with GNU General Public License v3.0 6 votes vote down vote up
def asComponent(index, t=OpenMaya.MFn.kMeshVertComponent):
    """
    index -> OpenMaya.MFn.kComponent
    Based on the input type it will create a component type for this tool
    the following components are being used.
    
    * OpenMaya.MFn.kMeshVertComponent
    * OpenMaya.MFn.kMeshEdgeComponent
    
    :param int/OpenMaya.MIntArray index: indices to create component for
    :param OpenMaya.MFn.kComponent t: can be all of OpenMaya component types.
    :return: Initialized components
    :rtype: OpenMaya.MFnSingleIndexedComponent
    """
    # convert input to an MIntArray if it not already is one
    array = asMIntArray(index)

    # initialize component
    component = OpenMaya.MFnSingleIndexedComponent().create(t)
    OpenMaya.MFnSingleIndexedComponent(component).addElements(array)
    return component


# ---------------------------------------------------------------------------- 
Example #3
Source File: fnData.py    From DeformationLearningSolver with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def getWeightData(self, elements):
        """
        Args:
          elements (list)

        Returns:
          SkinWeightData
        """
        dagPath, components = utils.getDagPathComponents(elements)

        # Get all influences
        infs = self.listInfluences(asDagPath=False)
        influenceIndices = om.MIntArray()
        [influenceIndices.append(self.getPhysicalInfluenceIndex(inf)) for inf in infs]

        # Get all weights
        weights = om.MDoubleArray()
        self.fn.getWeights(dagPath, components, influenceIndices, weights)
        weights = [w for w in weights]

        return SkinWeightData(elements, infs, weights)

    #---------------------------------------------------------------------- 
Example #4
Source File: fnData.py    From DeformationLearningSolver with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setWeightData(self, data, normalize=True):
        """
        Args:
          data (SkinWeightData)
          normalize (bool, Optional): Defaults to True
        """
        # Construct dagPath and components
        compList = data.getComponents()
        dagPath, components = utils.getDagPathComponents(compList)

        # Construct influence indices
        influenceIndices = om.MIntArray()
        [influenceIndices.append(self.getPhysicalInfluenceIndex(inf)) for inf in data.getInfluences()]

        # Construct weights
        weights = om.MDoubleArray()
        [weights.append(w) for w in data.getWeights()]
        oldValues = om.MDoubleArray()
        self.fn.getWeights(dagPath, components, influenceIndices, oldValues)

        self.fn.setWeights(dagPath, components, influenceIndices, weights, normalize, oldValues)

    #---------------------------------------------------------------------- 
Example #5
Source File: geo_cache.py    From spore with MIT License 6 votes vote down vote up
def cache(self, triangle):
        """ cache setter
        append one triangle to the end of the current cache
        :param triangle:    argument must be of type tuple or list
        it must consist of the following items in the exact same order:
        id  content           data type
        0 - p0              - MPointArray
        1 - p2              - MPointArray
        2 - p1              - MPointArray
        3 - face normal     - MVectorArray
        4 - polygon id      - MIntArray
        5 - vector AB       - MVectorArray
        6 - vector AC       - MvectorArray
        note: no error or type checking is done!
        """

        self.p0.append(triangle[0])
        self.p1.append(triangle[1])
        self.p2.append(triangle[2])
        self.normals.append(triangle[3])
        self.poly_id.append(int(triangle[4]))
        self.AB.append(triangle[5])
        self.AC.append(triangle[6]) 
Example #6
Source File: geo_cache.py    From spore with MIT License 6 votes vote down vote up
def cache(self):
        """ cache getter
        :return:    tuple of entire geo cache:
        id  content           data type
        0 - p0              - MPointArray
        1 - p2              - MPointArray
        2 - p1              - MPointArray
        3 - face normal     - MVectorArray
        4 - polygon id      - MIntArray
        5 - vector AB       - MVectorArray
        6 - vector AC       - MvectorArray
        """

        return self.p0,\
                self.p1,\
                self.p2,\
                self.normals,\
                self.poly_id,\
                self.AB,\
                self.AC 
Example #7
Source File: conversion.py    From maya-skinning-tools with GNU General Public License v3.0 6 votes vote down vote up
def asComponent(index):
    """
    index -> OpenMaya.MFn.kMeshVertComponent

    :param int/OpenMaya.MIntArray index: indices to create component for
    :return: Initialized component(s)
    :rtype: OpenMaya.MFn.kMeshVertComponent
    """
    # convert input to an MIntArray if it not already is one
    indices = asMIntArray(index)

    # initialize component(s)
    t = OpenMaya.MFn.kMeshVertComponent
    component = OpenMaya.MFnSingleIndexedComponent().create(t)
    OpenMaya.MFnSingleIndexedComponent(component).addElements(indices)

    return component 
Example #8
Source File: mesh.py    From maya-skinning-tools with GNU General Public License v3.0 6 votes vote down vote up
def getConnectedVertices(dag, component):
    """
    index -> OpenMaya.MFn.kMeshVertComponent

    :param OpenMaya.MDagPath dag:
    :param OpenMaya.MFn.kMeshVertComponent component:
    :return: Initialized component(s), number of connected vertices
    :rtype: tuple(OpenMaya.MFn.kMeshVertComponent, int)
    """
    connected = OpenMaya.MIntArray()

    # get connected vertices
    iter = OpenMaya.MItMeshVertex(dag, component)
    iter.getConnectedVertices(connected)

    # get component of connected vertices
    component = asComponent(connected)
    return component, len(connected) 
Example #9
Source File: mesh.py    From maya-skinning-tools with GNU General Public License v3.0 6 votes vote down vote up
def getConnectedVerticesMapper(dag):
    """
    Create a dictionary where the keys are the indices of the vertices and the
    values a list of indices of the connected vertices.

    :param OpenMaya.MDagPath dag:
    :return: Connected vertices mapper
    :rtype: dict
    """
    # variable
    data = {}

    # get connected vertices
    connected = OpenMaya.MIntArray()
    iter = OpenMaya.MItMeshVertex(dag)

    while not iter.isDone():
        # get connected data
        iter.getConnectedVertices(connected)
        data[iter.index()] = [c for c in connected]

        # go next
        iter.next()

    return data 
Example #10
Source File: spore_context.py    From spore with MIT License 6 votes vote down vote up
def undo_int_action(self, attr, undo_command):
        """ undo the last action that modified an integer value on the
        instance data object
        :param attr:  the name of the attribute to undo
        :type attr: str
        :param undo_command: the commond built from the undo journal
        :type undo_command: list
        :return: """

        if not hasattr(self.instance_data, attr):
            self.logger.error('Instance data has not attribute: {}'.format(attr))
            return

        ids = []
        values = om.MIntArray()
        for i in range(len(undo_command) / 2):
            ids.append(int(undo_command[i * 2]))
            values.append(int(undo_command[i * 2 + 1]))

        self.instance_data.set_points(ids, **{attr: values})
        self.instance_data.set_state() 
Example #11
Source File: weight_transfer_multiple.py    From SIWeightEditor with MIT License 5 votes vote down vote up
def init_bake_data(self):
        if MAYA_VER >= 2016:
            self.bake_node_id_dict = defaultdict(lambda : om2.MIntArray())
            self.bake_node_weight_dict = defaultdict(lambda : om2.MDoubleArray())
            self.bake_node_inf_dict = defaultdict(lambda : om2.MIntArray())
            self.org_node_weight_dict = defaultdict(lambda : om2.MDoubleArray())
        else:
            self.bake_node_id_dict = defaultdict(lambda : om.MIntArray())
            self.bake_node_weight_dict = defaultdict(lambda : om.MDoubleArray())
            self.bake_node_inf_dict = defaultdict(lambda : om.MIntArray())
            self.org_node_weight_dict = defaultdict(lambda : om.MDoubleArray())
        self.undo_node_weight_dict = defaultdict(lambda : [])
        self.redo_node_weight_dict = defaultdict(lambda : [])
        
    #部分転送 
Example #12
Source File: paintRemoveInfluenceCtxCommands.py    From maya-skinning-tools with GNU General Public License v3.0 5 votes vote down vote up
def undoIt(self):
        manager.beforeSelection = OpenMaya.MIntArray() 
Example #13
Source File: paintRemoveInfluenceCtxCommands.py    From maya-skinning-tools with GNU General Public License v3.0 5 votes vote down vote up
def getSelection(self):
        # variable
        indices = OpenMaya.MIntArray()
        allIndices = OpenMaya.MIntArray()
        
        # get active selection
        selection = OpenMaya.MSelectionList()  
        OpenMaya.MGlobal.getActiveSelectionList(selection)

        # loop selection
        iter = OpenMaya.MItSelectionList(selection)
        while not iter.isDone():
            # variables
            component = OpenMaya.MObject()
            dag = OpenMaya.MDagPath()

            iter.getDagPath(dag, component)
            
            if not component.isNull(): 
                objIndices = OpenMaya.MIntArray()

                components = OpenMaya.MFnSingleIndexedComponent(component) 
                components.getElements(indices)
                
                for i in range(indices.length()):
                    allIndices.append(indices[i])
                
            iter.next()
            
        return allIndices 
Example #14
Source File: instanceAlongCurve.py    From instanceAlongCurve with MIT License 5 votes vote down vote up
def getAvailableLogicalIndices(self, plug, numIndices):
        
        # Allocate and initialize
        outIndices = OpenMaya.MIntArray(numIndices)
        indices = OpenMaya.MIntArray(plug.numElements())
        plug.getExistingArrayAttributeIndices(indices)

        currentAvailableIndex = 0
        indicesFound = 0

        # Assuming indices are SORTED :)
        for i in indices:

            connectedPlug = plug.elementByLogicalIndex(i).isConnected()

            # Iteratively find available indices in the sparse array
            while i > currentAvailableIndex:
                outIndices[indicesFound] = currentAvailableIndex
                indicesFound += 1
                currentAvailableIndex += 1

            # Check against this index, add it if it is not connected
            if i == currentAvailableIndex and not connectedPlug:
                outIndices[indicesFound] = currentAvailableIndex
                indicesFound += 1

            currentAvailableIndex += 1

            if indicesFound == numIndices:
                return outIndices

        # Fill remaining expected indices
        for i in xrange(indicesFound, numIndices):
            outIndices[i] = currentAvailableIndex
            currentAvailableIndex += 1

        return outIndices 
Example #15
Source File: paintRemoveInfluenceCtxCommands.py    From maya-skinning-tools with GNU General Public License v3.0 5 votes vote down vote up
def reset(self):
        self._obj = None
        self._dag = None
        self._index = None
        self._influence = None
        self._influences = OpenMaya.MDagPathArray()
        self._influencesLocked = []
        
        self._skinCluster = None
        self._normalizeMode = None
        
        self.beforeSelection = OpenMaya.MIntArray()
        self.afterSelection = OpenMaya.MIntArray() 
Example #16
Source File: skinio.py    From cmt with MIT License 5 votes vote down vote up
def set_influence_weights(self, dag_path, components):
        """Sets all the influence weights.

        :param dag_path: MDagPath of the deformed geometry.
        :param components: Component MObject of the deformed components.
        """
        influence_paths = OpenMaya.MDagPathArray()
        influence_count = self.fn.influenceObjects(influence_paths)

        elements = OpenMaya.MIntArray()
        fncomp = OpenMaya.MFnSingleIndexedComponent(components)
        fncomp.getElements(elements)
        weights = OpenMaya.MDoubleArray(elements.length() * influence_count)

        components_per_influence = elements.length()

        for imported_influence, imported_weights in self.data["weights"].items():
            imported_influence = imported_influence.split("|")[-1]
            for ii in range(influence_paths.length()):
                influence_name = influence_paths[ii].partialPathName()
                influence_without_namespace = shortcuts.remove_namespace_from_name(
                    influence_name
                )
                if influence_without_namespace == imported_influence:
                    # Store the imported weights into the MDoubleArray
                    for jj in range(components_per_influence):
                        weights.set(imported_weights[elements[jj]], jj * influence_count + ii)
                    break

        influence_indices = OpenMaya.MIntArray(influence_count)
        for ii in range(influence_count):
            influence_indices.set(ii, ii)
        self.fn.setWeights(dag_path, components, influence_indices, weights, False) 
Example #17
Source File: skinio.py    From cmt with MIT License 5 votes vote down vote up
def set_blend_weights(self, dag_path, components):
        """Set the blendWeights.

        :param dag_path: MDagPath of the deformed geometry.
        :param components: Component MObject of the deformed components.
        """
        elements = OpenMaya.MIntArray()
        fncomp = OpenMaya.MFnSingleIndexedComponent(components)
        fncomp.getElements(elements)
        blend_weights = OpenMaya.MDoubleArray(elements.length())
        for i in range(elements.length()):
            blend_weights.set(self.data["blendWeights"][elements[i]], i)
        self.fn.setBlendWeights(dag_path, components, blend_weights) 
Example #18
Source File: skin.py    From mgear_core with MIT License 5 votes vote down vote up
def setInfluenceWeights(skinCls, dagPath, components, dataDic, compressed):
    unusedImports = []
    weights = getCurrentWeights(skinCls, dagPath, components)
    influencePaths = OpenMaya.MDagPathArray()
    numInfluences = skinCls.__apimfn__().influenceObjects(influencePaths)
    numComponentsPerInfluence = weights.length() / numInfluences

    for importedInfluence, wtValues in dataDic['weights'].items():
        for ii in range(influencePaths.length()):
            influenceName = influencePaths[ii].partialPathName()
            nnspace = pm.PyNode(influenceName).stripNamespace()
            influenceWithoutNamespace = nnspace
            if influenceWithoutNamespace == importedInfluence:
                if compressed:
                    for jj in range(numComponentsPerInfluence):
                        # json keys can't be integers. The vtx number key
                        # is unicode. example: vtx[35] would be: u"35": 0.6974,
                        # But the binary format is still an int, so check both.
                        # if the key doesn't exist, set it to 0.0
                        wt = wtValues.get(jj) or wtValues.get(str(jj)) or 0.0
                        weights.set(wt, jj * numInfluences + ii)
                else:
                    for jj in range(numComponentsPerInfluence):
                        wt = wtValues[jj]
                        weights.set(wt, jj * numInfluences + ii)
                    break
        else:
            unusedImports.append(importedInfluence)

    influenceIndices = OpenMaya.MIntArray(numInfluences)
    for ii in range(numInfluences):
        influenceIndices.set(ii, ii)
    skinCls.__apimfn__().setWeights(dagPath,
                                    components,
                                    influenceIndices,
                                    weights,
                                    False) 
Example #19
Source File: spore_sampler.py    From spore with MIT License 5 votes vote down vote up
def __init__(self):

        self.position = om.MPointArray()
        self.normal = om.MVectorArray()
        self.poly_id = om.MIntArray()
        self.u_coord = [] # om.MDoubleArray()
        self.v_coord = [] # om.MDoubleArray() 
Example #20
Source File: instance_data.py    From spore with MIT License 5 votes vote down vote up
def append_points(self, position, scale, rotation, instance_id, visibility, normal, tangent, u_coord, v_coord, poly_id, color):
        """ append the given array to the instance data object
        :param position:
        :param scale:
        :param rotation:
        :param instance_id:
        :param visibility:
        :param normal:
        :param tangent:
        :param u_coord:
        :param v_coord:
        :param poly_id:
        :param color:
        :return: """

        appended_ids = om.MIntArray()
        for i in xrange(position.length()):
            self.position.append(position[i])
            self.scale.append(scale[i])
            self.rotation.append(rotation[i])
            self.instance_id.append(instance_id[i])
            self.visibility.append(visibility[i])
            self.normal.append(normal[i])
            self.tangent.append(tangent[i])
            self.u_coord.append(u_coord[i])
            self.v_coord.append(v_coord[i])
            self.poly_id.append(poly_id[i])
            self.color.append(color[i])

            # append position to numpy array
            np_position = [[position[i].x, position[i].y, position[i].z]]
            self.np_position = np.append(self.np_position, np_position, axis=0)

            self.unique_id.append(self.position.length() - 1)
            appended_ids.append(self.position.length() - 1)

        return appended_ids 
Example #21
Source File: spore_sampler.py    From spore with MIT License 5 votes vote down vote up
def undoIt(self):
        visibility = om.MIntArray()
        for i in range(*self.undo_range):
            self.instance_data.visibility.set(0, i)
            #  visibility.append(0)

        self.instance_data.clean_up()
        self.instance_data.set_state() 
Example #22
Source File: spore_context.py    From spore with MIT License 5 votes vote down vote up
def __init__(self):
        ompx.MPxToolCommand.__init__(self)
        self.setCommandString(K_TOOL_CMD_NAME)
        K_TRACKING_DICTIONARY[ompx.asHashable(self)] = self

        log_lvl = sys._global_spore_dispatcher.spore_globals['LOG_LEVEL']
        self.logger = logging_util.SporeLogger(__name__, log_lvl)

        self.brush_state = None
        self.instance_data = None
        self.last_brush_position = None

        self.last_undo_journal = ''
        self.last_count = 0
        self.last_state = {}
        self.next_redo_journal = ''

        self.position = om.MVectorArray()
        self.scale = om.MVectorArray()
        self.rotation = om.MVectorArray()
        self.instance_id = om.MIntArray()
        self.visibility = om.MIntArray()
        self.normal = om.MVectorArray()
        self.tangent = om.MVectorArray()
        self.u_coord = om.MDoubleArray()
        self.v_coord = om.MDoubleArray()
        self.poly_id = om.MIntArray()
        self.color = om.MVectorArray()
        self.point_id = om.MIntArray()

        self.initial_rotation = om.MVectorArray()
        self.initial_scale = om.MVectorArray()
        self.initial_offset = om.MDoubleArray()
        self.initial_id = om.MIntArray()
        self.spray_coords = [] 
Example #23
Source File: spore_context.py    From spore with MIT License 5 votes vote down vote up
def undo_place_action(self, start, end):
        """ undo the last place action
        :param start: start index
        :param end: end index
        :return: """

        visibility = om.MIntArray()
        ids = range(start, end + 1)
        [visibility.append(0) for i in ids]
        self.instance_data.set_points(ids, visibility=visibility)
        self.instance_data.clean_up()
        self.instance_data.set_state() 
Example #24
Source File: test_instance_data.py    From spore with MIT License 5 votes vote down vote up
def create_test_data(length):
    """ helper function to create an instance data set of the given length """

    position = om.MVectorArray()
    scale = om.MVectorArray()
    rotation = om.MVectorArray()
    instance_id = om.MIntArray()
    visibility = om.MIntArray()
    normal = om.MVectorArray()
    tangent = om.MVectorArray()
    u_coord =  om.MIntArray()
    v_coord = om.MIntArray()
    poly_id = om.MIntArray()
    color = om.MVectorArray()
    for i in xrange(length):
        position.append(om.MVector(i, i, i))
        scale.append(om.MVector(i, i, i))
        rotation.append(om.MVector(i, i, i))
        instance_id.append(i)
        visibility.append(1)
        normal.append(om.MVector(i, i, i))
        tangent.append(om.MVector(i, i, i))
        u_coord.append(i)
        v_coord.append(i)
        poly_id.append(i)
        color.append(om.MVector(i, i, i))
    return position, scale, rotation, instance_id, visibility, normal, tangent, u_coord, v_coord, poly_id, color 
Example #25
Source File: instance_data.py    From spore with MIT License 5 votes vote down vote up
def __init__(self, node):

        log_lvl = sys._global_spore_dispatcher.spore_globals['LOG_LEVEL']
        self.logger = logging_util.SporeLogger(__name__, log_lvl)


        dg_fn = om.MFnDependencyNode(node)
        self.node_name = dg_fn.name()
        self.node = node # TODO - hold on to selection list instead of mobj
        #  self.bounding_box = None
        self.state = None
        self.data_plug = om.MPlug()
        self.data_object = om.MObject()

        # instance data attributes
        self.position = om.MVectorArray()
        self.scale = om.MVectorArray()
        self.rotation = om.MVectorArray()
        self.instance_id = om.MIntArray()
        self.visibility = om.MIntArray()
        self.normal = om.MVectorArray()
        self.tangent = om.MVectorArray()
        self.u_coord = om.MDoubleArray()
        self.v_coord = om.MDoubleArray()
        self.poly_id = om.MIntArray()
        self.color = om.MVectorArray()
        self.unique_id = om.MIntArray()

        self.exclusive_paint = []

        # collect points for kd tree
        self.np_position = np.empty((0,3), float)
        self.tree = None

        self.logger.info('Instanciate new InstanceData object for: {}'.format(self.node_name)) 
Example #26
Source File: utils.py    From maya-retarget-blendshape with GNU General Public License v3.0 5 votes vote down vote up
def asMIntArray(index):
    """
    index -> OpenMaya.MIntArray
    
    :param int/OpenMaya.MIntArray index: indices
    :return: Array of indices
    :rtype: OpenMaya.MIntArray
    """
    if type(index) != OpenMaya.MIntArray:
        array = OpenMaya.MIntArray()
        array.append(index)
        return array

    return index 
Example #27
Source File: ptc_cache.py    From spore with MIT License 5 votes vote down vote up
def __init__(self):

        self._locked = False

        # sampled data from the ptc
        self.points = om.MPointArray()
        self.normals = om.MVectorArray()
        self.poly_ids = om.MIntArray()
        self.u_coords = om.MDoubleArray()
        self.v_coords = om.MDoubleArray()
        self.user = []
        self.bb = None 
Example #28
Source File: ptc_cache.py    From spore with MIT License 5 votes vote down vote up
def get_points(self):
        """
        return all points from the cache
        :return:        MPointArray   - list of all point positions
                        MVectorArray  - list of all normals
                        MIntArray     - list of all polygon ids
                        MDoubleArray  - list of all u_coordinates
                        MDoubleArray  - list of all v coordinates
        """

        return self.points, self.normals, self.poly_ids, self.u_coords, self.v_coords, self.user 
Example #29
Source File: geo_cache.py    From spore with MIT License 5 votes vote down vote up
def create_uv_lookup(self):
        """ create a dict with an entry for every vertex and a list of
        neighbouring faces as well as a kd tree tro look up close face ids """

        self.logger.debug('Create UV lookup for the current GeoCache')

        util = om.MScriptUtil()
        connected_faces = om.MIntArray()

        mesh_fn = om.MFnMesh(self.mesh)
        num_verts = mesh_fn.numVertices()
        points = np.zeros(shape=(num_verts, 2))

        vert_iter = om.MItMeshVertex(self.mesh)
        while not vert_iter.isDone():

            index = vert_iter.index()
            vert_iter.getConnectedFaces(connected_faces)
            self.neighbor_lookup[index] = [connected_faces[i] for i in xrange(connected_faces.length())]

            util.createFromDouble(0.0, 0.0)
            uv_ptr = util.asFloat2Ptr()
            vert_iter.getUV(uv_ptr)
            u_coord = util.getFloat2ArrayItem(uv_ptr, 0, 0)
            v_coord = util.getFloat2ArrayItem(uv_ptr, 0, 1)
            points[index] = (u_coord, v_coord)

            vert_iter.next()

        self.uv_kd_tree = kd_tree(points) 
Example #30
Source File: geo_cache.py    From spore with MIT License 5 votes vote down vote up
def flush_cache(self):

        self.logger.debug('Flush GeoCache')
        self.p0 = om.MPointArray()
        self.p1 = om.MPointArray()
        self.p2 = om.MPointArray()
        self.normals = om.MVectorArray()
        self.poly_id = om.MIntArray()
        self.AB = om.MVectorArray()
        self.AC = om.MVectorArray()
        self.cached = False