def extract_transform_primitive(self,
                                 mfn_type,
                                 shape=True,
                                 parent_mobject=None):
     dag_path_array = OpenMaya.MDagPathArray()
     seen = []
     mit_dependency_nodes = OpenMaya.MItDependencyNodes(mfn_type)
     while not mit_dependency_nodes.isDone():
         mobject = mit_dependency_nodes.item()
         mfn_dag_node = OpenMaya.MFnDagNode(mobject)
         if parent_mobject:
             current_root = mfn_dag_node.fullPathName().split('|')[1]
             current_root_mobject = self.get_mobject(current_root)
             if current_root_mobject != parent_mobject:
                 mit_dependency_nodes.next()
                 continue
         if not shape:
             p_mobject = mfn_dag_node.parent(0)
             mfn_dag_node = OpenMaya.MFnDagNode(p_mobject)
         p_dag_path = OpenMaya.MDagPath()
         mfn_dag_node.getPath(p_dag_path)
         if p_dag_path in seen:
             mit_dependency_nodes.next()
             continue
         seen.append(p_dag_path)
         dag_path_array.append(p_dag_path)
         mit_dependency_nodes.next()
     dag_path_array = OpenMaya.MDagPathArray(dag_path_array)
     return dag_path_array
Exemple #2
0
 def __init__(self):
     OMMPx.MPxCommand.__init__(self)
     self.__selection = OM.MSelectionList()
     self.__prefix = ''
     self.__suffix = '_xForm'
     self.__scale = OM.MVector(1.0, 1.0, 1.0)
     self.__pickedObjects = OM.MDagPathArray()  # all valid transform nodes in the selection
     self.__newLocators = OM.MDagPathArray()  # any new locators created by the command
     self.__dagModify = OM.MDagModifier()  # modifier to create and modify the new nodes
Exemple #3
0
    def redoIt(self):
        # clear out the modifier and arrays so they don't store old object names
        self.__oldTransformationMatrices = []
        self.__newLocators = OM.MDagPathArray()
        self.__pickedObjects = OM.MDagPathArray()
        self.__dagModify = OM.MDagModifier()

        # iterate through the list of selected transform nodes and create a locator for each one
        iter = OM.MItSelectionList(self.__selection, OM.MFn.kTransform)
        # containers for use inside the iterator
        currentObject = OM.MObject()
        currentObjectFn = OM.MFnDagNode()
        currentDagPath = OM.MDagPath()
        currentPlug = OM.MPlug()
        currentParent = OM.MObject()
        currentObjectFn = OM.MFnTransform()
        newLocator = OM.MObject()
        newLocFn = OM.MFnTransform()
        newLocatorPath = OM.MDagPath()
        while not iter.isDone():
            # append the current object to the array of picked objects
            iter.getDagPath(currentDagPath)
            self.__pickedObjects.append(currentDagPath)
            # create the new locator
            newLocator = self.__dagModify.createNode('locator')
            # insert the locator sibling to the object
            currentObjectFn.setObject(currentDagPath)
            currentParent = currentObjectFn.parent(0)
            self.__dagModify.reparentNode(newLocator, currentParent)
            # move the new locator to the same location as its corresponding object, parent, and name appropriately
            newLocFn.setObject(newLocator)
            newLocFn.set(currentObjectFn.transformation())  # align the new locator to the object
            self.__dagModify.reparentNode(currentDagPath.node(),
                                          newLocator)  # the object is now a child of the new locator
            currentObjectFn.set(OM.MTransformationMatrix())  # set the object's local matrix to identity
            self.__dagModify.renameNode(newLocator, self.__prefix + currentObjectFn.partialPathName() + self.__suffix)
            # append the new locator to the array
            newLocFn.getPath(newLocatorPath)
            self.__newLocators.append(newLocatorPath)
            iter.next()
        # WARNING: must tell the MDagModifier to doIt() now in order to let Maya's auto-rename kick in and ensure the names are unique
        # otherwise attempts to use setAttr below may end up using some other object
        self.__dagModify.doIt()

        # now set the attributes and reparent the selected objects
        selectionString = ''  # the selection list needs to be formatted for MEL
        for i in range(0, self.__newLocators.length()):
            newLocFn.setObject(self.__newLocators[i])
            selectionString += ' %s' % newLocFn.fullPathName()
            # resize the new locator
            self.__dagModify.commandToExecute('setAttr %s.localScaleX %f' % (newLocFn.fullPathName(), self.__scale.x))
            self.__dagModify.commandToExecute('setAttr %s.localScaleY %f' % (newLocFn.fullPathName(), self.__scale.y))
            self.__dagModify.commandToExecute('setAttr %s.localScaleZ %f' % (newLocFn.fullPathName(), self.__scale.z))

        # select the new locators
        self.__dagModify.commandToExecute('select%s' % selectionString)
        self.__dagModify.doIt()
 def getSkinclusterJoints(self, node):
     result = OpenMaya.MDagPathArray()
     if not node:
         return result
     if not isinstance(node, OpenMaya.MObject):
         node = self.getMObject(node)
     mfn_skincluster = OpenMayaAnim.MFnSkinCluster(node)
     dag_path_array = OpenMaya.MDagPathArray()
     mfn_skincluster.influenceObjects(dag_path_array)
     for index in range(dag_path_array.length()):
         result.append(dag_path_array[index])
     return result
Exemple #5
0
    def __init__(self):
        OpenMayaMPx.MPx3dModelView.__init__(self)

        self.fOldCamera = OpenMaya.MDagPath()
        self.fCameraList = OpenMaya.MDagPathArray()
        self.fCurrentPass = 0
        self.fDrawManips = True
        self.fOldDisplayStyle = OpenMayaUI.M3dView.kWireFrame
        self.fLightTest = False
        self.fListList = OpenMaya.MDagPathArray()
        self.tol = 10.0

        self.setMultipleDrawEnable(True)
def get_influence_ids(skin_cluster):
    """
    Collects all influences and its ids from a skinCluster.
    
    Args:
        skin_cluster(string): A skinCluster's name.
    
    Returns:
        A dictionary: {id(int):inf_name(string)}
    """
    has_infs = cmds.skinCluster(skin_cluster, q=True, influence=True) or []
    if not has_infs:
        return []

    skin_cluster_node = to_m_object(skin_cluster)
    skin_cluster_fn = OpenMayaAnim.MFnSkinCluster(skin_cluster_node)

    # Collect influences
    inf_array = OpenMaya.MDagPathArray()
    skin_cluster_fn.influenceObjects(inf_array)

    # {inf_name(string):id(int)}
    inf_ids = {}

    for x in range(inf_array.length()):
        inf_path = inf_array[x].partialPathName()
        inf_id = int(skin_cluster_fn.indexForInfluenceObject(inf_array[x]))
        inf_ids[inf_id] = inf_path

    return inf_ids
Exemple #7
0
    def gatherInfluenceWeights(self, dagPath, components):
        """
        get and store the weights of each influence object for same ordered components(vertex) in data['weights'] dictionary
        :param dagPath:
        :param components: mesh components(vertex)
        :return: None
        """
        # Gathers all the influence weights
        weights = self.__getCurrentWeights(dagPath, components)

        influencePaths = openmaya.MDagPathArray()
        # influencePaths is the fullPath of the object(joint)
        numInfluences = self.fn.influenceObjects(influencePaths)
        # weight size = number of components(vertex) * number of influenceObjects(joints)
        numComponentsPerInfluence = weights.length() / numInfluences

        for ii in range(influencePaths.length()):
            influenceName = influencePaths[ii].partialPathName()
            # we want to store the weights by influence without the namespace so it is easier
            # to import if the namespace is different
            influenceNameWithoutNamespace = SkinCluster.removeNamespaceFromString(
                influenceName)
            # store the weight of each influence object(joint) for same ordered components(vertex)
            self.data['weights'][influenceNameWithoutNamespace] = [
                weights[jj * numInfluences + ii]
                for jj in range(numComponentsPerInfluence)
            ]
Exemple #8
0
     def gatherInfluenceData(self, dagPath, components):
         """
         Get the influence data
         """
         weights = self.__getCurrentWeights(dagPath, components)
 
         influencePaths = OM.MDagPathArray()
         numInfluences = self.fn.influenceObjects(influencePaths)
         numComponentsPerInfluence = weights.length() / numInfluences
         
         self.progressBar_start(stepMaxValue=influencePaths.length(), 
                                statusMessage='Calculating....', 
                                interruptableState=False)
         _d_influenceData = {}            
         for i in range(influencePaths.length()):
             _k = str(i)
             influenceName = influencePaths[i].partialPathName()
             influenceWithoutNamespace = names.getBaseName(influenceName)
             
             _d_influenceData[_k] = {'name': influenceWithoutNamespace,
                                     'position':distance.returnWorldSpacePosition(influenceName)}
             
             # store weights by influence & not by namespace so it can be imported with different namespaces.
             self.progressBar_iter(status = 'Getting {0}...data'.format(influenceName))                                
             self._d_data['weights'][_k] = \
                 [weights[jj*numInfluences+i] for jj in range(numComponentsPerInfluence)]
             
         self._d_data['influences']['data'] = _d_influenceData  
         self.progressBar_end()
 def getInfDags(self, skinFn):
     """
     Get influence dag objects to be passed around methods
     """
     infDags = om.MDagPathArray()
     skinFn.influenceObjects(infDags)
     return infDags
Exemple #10
0
def hierarchyA():
    worldDag = getWorld()
    worldDagNode = om.MFnDagNode(worldDag)
    assemblyList = []
    worldAssembly = assembly(worldDag, worldDagNode, "root")
    assemblyList.append(worldAssembly)
    #tMatrix = om.MMatrix()
    parseChildren(worldDagNode, worldAssembly, assemblyList)
    #printAss(0, worldAssembly)

    #    for ass in assemblyList:
    #        parentAss = ass.parentAss
    #        if parentAss:
    #            print "Assembly List: ", ass.name, "parent", ass.parentAss.name
    #        else:
    #            print "Assembly List: ", ass.name, "parent", "world"
    #        for ai in ass.assembly_instances:
    #            print ass.name, "Instance:", ai.name
    #        for ai in ass.geometry:
    #            print "->Geo:", ai

    for i in instList:
        print "Instance", i.fullPathName()
        dpa = om.MDagPathArray()
        dn = om.MFnDagNode(i)
        dn.getAllPaths(dpa)
        print "NumPaths", dpa.length()
        for dp in range(dpa.length()):
            print dpa[dp].fullPathName()
Exemple #11
0
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)
Exemple #12
0
    def set_weights(self, dag_path, components):
        weights = self._get_current_weights(dag_path, components)

        infl_paths = om.MDagPathArray()
        n_infl = self.fn.influenceObjects(infl_paths)

        infl_per_vtx = weights.length() / n_infl

        for imported_infl, imported_weights in self.data['weights'].items():
            for ii in xrange(infl_paths.length()):
                infl = infl_paths[ii].partialPathName()
                infl = SkinCluster.remove_namespace_from(infl)

                if infl == imported_infl:
                    for jj in xrange(infl_per_vtx):
                        weights.set(imported_weights[jj], jj * n_infl + ii)

                    break

        infl_indices = om.MIntArray(n_infl)

        for ii in xrange(n_infl):
            infl_indices.set(ii, ii)

        self.fn.setWeights(dag_path, components, infl_indices, weights, False)
    def initialize(self, obj):
        # if no obj reset variables
        if not obj:
            self.reset()
            return

        # get object data
        self._obj = utils.asMObject(obj)
        self._dag = utils.asMDagPath(self.obj)

        # get skin cluster
        self._skinCluster = utils.asMFnSkinCluster(self.obj)

        # get skin cluster data
        maxPlug = self.skinCluster.findPlug("maxInfluences")
        normalPlug = self.skinCluster.findPlug("normalizeWeights")
        maintainPlug = self.skinCluster.findPlug("maintainMaxInfluences")

        self._maxInfluences = maxPlug.asInt()
        self._normalizeMode = normalPlug.asInt()
        self._maintainMaxInfluences = maintainPlug.asBool()

        # get influences
        self._influences = OpenMaya.MDagPathArray()
        self.skinCluster.influenceObjects(self._influences)

        # get locked influences
        self._influencesLocked = []
        for i in range(self.influences.length()):
            path = self.influences[i].fullPathName()
            locked = cmds.getAttr("{0}.liw".format(path))

            self._influencesLocked.append(locked)
Exemple #14
0
    def doIt(self, *args):
        om.MGlobal.getActiveSelectionList(self.__selection)

        if not (self.__selection.length() == 2):
            om.MGlobal.displayWarning("Select only 2 objects to scatter geometry. Skipping.")
            return

        self.__selection.getDagPath(1, self.__dagPath)
        it = om.MItMeshVertex(self.__dagPath)

        self.__selection.getDagPath(0, self.__dagPath)
        self.__dagNodeFn.setObject(self.__dagPath)

        while not it.isDone():
            point = it.position(om.MSpace.kWorld)
            pos = om.MVector(point)

            copy = self.__dagNodeFn.duplicate()
            arr = om.MDagPathArray()
            om.MDagPath.getAllPathsTo(copy, arr)
            path = om.MDagPath(arr[0])

            cmds.sets(path.partialPathName(), add="initialShadingGroup")

            self.__transformFn.setObject(arr[0])
            self.__transformFn.setTranslation(pos, om.MSpace.kWorld)

            it.next()
Exemple #15
0
def getInfluencePhysicalIndex(skinCluster, influence):
    '''
	Return the physical (non-sparce) index of an influence for a specified skinCluster
	@param skinCluster: SkinCluster to query influence index from
	@type skinCluster: str
	@param influence: Influence to query index of
	@type influence: str
	'''
    # Verify skinCluster
    if not isSkinCluster(skinCluster):
        raise Exception('Invalid skinCluster "' + skinCluster + '" specified!')

    # Check influence
    if not mc.objExists(influence):
        raise Exception('Influence object "' + influence + '" does not exist!')

    # Get skinCluster node
    skinClusterFn = getSkinClusterFn(skinCluster)

    # Get influence path list
    infPathArray = OpenMaya.MDagPathArray()
    skinClusterFn.influenceObjects(infPathArray)
    infNameArray = [
        infPathArray[i].partialPathName() for i in range(infPathArray.length())
    ]

    # Check influence
    if not infNameArray.count(influence):
        raise Exception('Unable to determine influence index for "' +
                        influence + '"!')
    infIndex = infNameArray.index(influence)

    # Retrun result
    return infIndex
Exemple #16
0
    def getInfluencesAffectingPoints(self, vertList, geo):
        '''
        returns influences that affect components
        input MObject (components)
        input DagPath (mesh) 
        returns MSelectionList
        '''

        influenceArray = om.MDagPathArray()
        self.skinclusterFn.influenceObjects(influenceArray)

        outputSelectionList = om.MSelectionList()

        for influence in range(influenceArray.length()):

            weightList = om.MDoubleArray()
            index = self.skinclusterFn.indexForInfluenceObject(
                influenceArray[influence])

            self.skinclusterFn.getWeights(geo, vertList, index, weightList)

            for weightValue in range(weightList.length()):

                if weightList[weightValue] > 0:

                    outputSelectionList.add(influenceArray[influence])

        return outputSelectionList
def getInfluences(skinCluster):
    """
    Get all of the influence data connected to the skinCluster. This is a 
    OpenMaya.MDagPathArray, OpenMaya.MIntArray() and a regular list of partial
    names.
    
    :param OpenMaya.MFnSkinCluster skinCluster:
    :return: Dag paths, integer and partial names
    :rtype: tuple(
        OpenMaya.MDagPathArray
        OpenMaya.MIntArray
        list of strings
    )
    """
    # variables
    influencesDag = OpenMaya.MDagPathArray()
    influencesI = OpenMaya.MIntArray()
    influencesN = []
    
    # get influences
    skinCluster.influenceObjects(influencesDag)
    
    # get influences data
    for i in range(influencesDag.length()):
        influencesI.append(i)
        influencesN.append(influencesDag[i].partialPathName())

    return influencesDag, influencesI, influencesN
Exemple #18
0
    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)
Exemple #19
0
 def set_mirror_flip(self, tag, type, radiobuttons):
     selections = self.my_maya.getSelectedDagPaths()
     # to check your selection
     selection_array = OpenMaya.MDagPathArray()
     for index in range(selections.length()):
         if tag == 'cluster':
             if not self.my_maya.hasCluster(selections[index]):
                 continue
             selection_array.append(selections[index])
         if tag == 'skincluster':
             if not self.my_maya.hasJoint(selections[index]):
                 continue
             selection_array.append(selections[index])
     if not selection_array.length():
         OpenMaya.MGlobal.displayWarning('Your select not contain %s!...' %
                                         tag)
         return
     axis = [1, 1, 1]
     if radiobuttons[0].isChecked():
         axis = [-1, 1, 1]
     if radiobuttons[1].isChecked():
         axis = [1, -1, 1]
     if radiobuttons[2].isChecked():
         axis = [1, 1, -1]
     if tag == 'cluster':
         self.cluster.create_mirror_flip(selection_array, axis, type)
     if tag == 'skincluster':
         self.skincluster.create_mirror_flip(selection_array, axis, type)
     OpenMaya.MGlobal.displayInfo('%s %s Done!...' % (tag, type))
 def getInfDags(self, skinFn):
     """
     Helper function to get influence dag objects
     """
     infDags = om.MDagPathArray()
     skinFn.influenceObjects(infDags)
     return infDags
Exemple #21
0
def get_influence_ids(skin_cluster):
    """
    Collects all influences and its ids from a skinCluster.

    Returns:
        A dictionary: {id(int):inf_name(string)}
    """
    has_infs = get_influences(skin_cluster)
    if not has_infs:
        return {}

    skin_cluster_mobj = to_mobject(skin_cluster)
    mfn_skin_cluster = OpenMayaAnim.MFnSkinCluster(skin_cluster_mobj)

    inf_mdag_paths = OpenMaya.MDagPathArray()
    mfn_skin_cluster.influenceObjects(inf_mdag_paths)

    inf_ids = {}

    for i in range(inf_mdag_paths.length()):
        inf_id = int(
            mfn_skin_cluster.indexForInfluenceObject(inf_mdag_paths[i]))
        inf_ids[inf_id] = inf_mdag_paths[i].partialPathName()

    return inf_ids
Exemple #22
0
    def __set_influence_weights(self, dagpath, components):
        """ Set the influence weights for the specified skincluster """
        weights = self.__get_current_weights(dagpath, components)

        dagPathArray = OpenMaya.MDagPathArray()
        numInfluences = self.fnSkinCluster.influenceObjects(dagPathArray)
        influencePerComponent = weights.length() / numInfluences

        unusedImport = list()
        noMatch = [
            dagPathArray[ii].partialPathName()
            for ii in range(dagPathArray.length())
        ]

        for joint, weight in self.data['weights'].items():
            for i in range(dagPathArray.length()):
                influenceName = dagPathArray[i].partialPathName()
                if influenceName == joint:
                    for j in range(influencePerComponent):
                        weights.set(weight[j], j * numInfluences + i)
                    noMatch.remove(influenceName)
                    break
                else:
                    unusedImport.append(joint)

        influencedIndices = OpenMaya.MIntArray(numInfluences)
        for i in range(numInfluences):
            influencedIndices.set(i, i)
        self.fnSkinCluster.setWeights(dagpath, components, influencedIndices,
                                      weights, False)
Exemple #23
0
    def to_specific_deformer(self, tag):
        if not self.target_deformers:
            self.target_deformers = []
            for x in range(len(self.source_deformers)):
                self.target_deformers.append(None)
        loop = min([len(self.target_deformers), len(self.source_deformers)])
        source_deformer_dag_path = OpenMaya.MDagPathArray()
        for index in range(loop):
            source_dag_path = self.getDagPath(self.source_deformers[index])
            source_deformer_dag_path.append(source_dag_path)

        for index in range(source_deformer_dag_path.length()):
            source_dag_path = source_deformer_dag_path[index]
            if source_dag_path.hasFn(OpenMaya.MFn.kCurve):  # to check to curve
                curve_weights = self.getWeightsFromCurve(
                    source_dag_path, self.source_geometry)
                for k, v in curve_weights.items():
                    name = '%s_%s_%s_cluster' % (self.source_deformers[index],
                                                 k, tag)
                    cluster, clusterhandel = self.create(name, clear=True)
                    self.setClusterPosition(clusterhandel, v['position'])
                    self.setClusterWeights(self.target_geometrys[0], cluster,
                                           v['weights'])
            elif source_dag_path.hasFn(
                    OpenMaya.MFn.kTransform) or source_dag_path.hasFn(
                        OpenMaya.MFn.kJoint):
                _targt_deformer = self.target_deformers[index]
                if source_dag_path.hasFn(OpenMaya.MFn.kJoint):
                    children = self.getChildren(source_dag_path)
                else:
                    children = self.getChildren(
                        source_dag_path, mfn_shape=OpenMaya.MFn.kCluster)
                for cindex in range(children.length()):
                    self.unParent(children[cindex])
                if not self.target_deformers[index]:
                    name = '%s_%s_cluster' % (self.source_deformers[index],
                                              tag)
                    cluster, clusterhandle = self.create(name, clear=True)
                    if source_dag_path.hasFn(OpenMaya.MFn.kJoint):
                        x, y, z = self.getJointPosition(
                            self.source_deformers[index])
                    else:
                        x, y, z = self.getClusterPosition(
                            self.source_deformers[index])
                    self.setClusterPosition(clusterhandle, [x, y, z])
                    _targt_deformer = clusterhandle
                attribute = '{}.translateX'.format(
                    self.source_deformers[index])
                cluster_mobject = self.getDependences(
                    _targt_deformer, OpenMaya.MFn.kClusterFilter)
                weights = self.getWeightsFromEnvelope(self.source_geometry,
                                                      self.source_geometry,
                                                      attribute)
                self.setClusterWeights(self.target_geometrys[0],
                                       cluster_mobject[0], weights)
                for rindex in range(children.length()):
                    self.parentTo(children[rindex], source_dag_path)
            else:
                OpenMaya.MGlobal.displayWarning('Your select is wrong!...')
def influenceObjects(skinCluster):
    mfnSkin = apiAnim.MFnSkinCluster(toMObject(skinCluster))
    dagPaths = api.MDagPathArray()
    mfnSkin.influenceObjects(dagPaths)
    influences = []
    for i in xrange(dagPaths.length()):
        influences.append(dagPaths[i].fullPathName())
    return influences
Exemple #25
0
    def listInfluences(self):
        dagPaths = om.MDagPathArray()

        self.fn.influenceObjects(dagPaths)
        result = []
        for i in range(dagPaths.length()):
            result.append(dagPaths[i].fullPathName())

        return result
Exemple #26
0
def getSkinWeights(skinCluster):
    # dataSkin[shape][joint][0] ---> indexes
    # dataSkin[shape][joint][1] ---> weights
    dataSkin = {}
    #convert the vertex component names into vertex indices

    shape = mc.skinCluster(skinCluster, q=True, g=True)[0]
    obj = mc.listRelatives(shape, p=True)[0]
    vtxNbr = mc.polyEvaluate(obj, v=True)
    joints = mc.skinCluster(skinCluster, q=True, weightedInfluence=True)

    idxJointWeight = []
    for i in range(0, vtxNbr):
        idxJointWeight.append((i, []))

    #get an MObject for the skin cluster node
    skinFn = API_skinClusterClass(skinCluster)

    #construct a dict mapping joint names to joint indices
    jApiIndices = {}
    _tmp = om.MDagPathArray()
    skinFn.influenceObjects(_tmp)

    for n in range(_tmp.length()):
        jApiIndices[str(
            _tmp[n].partialPathName())] = skinFn.indexForInfluenceObject(
                _tmp[n])

    weightListP = skinFn.findPlug("weightList")
    weightListObj = weightListP.attribute()
    weightsP = skinFn.findPlug("weights")

    tmpIntArray = om.MIntArray()
    baseFmtStr = str(
        skinCluster
    ) + '.weightList[%d]'  #pre build this string: fewer string ops == faster-ness!

    dataSkin[obj] = {}
    for i in range(0, vtxNbr):
        #we need to use the api to query the physical indices used
        weightsP.selectAncestorLogicalIndex(i, weightListObj)
        weightsP.getExistingArrayAttributeIndices(tmpIntArray)

        weightFmtStr = baseFmtStr % i + '.weights[%d]'

        #at this point using the api or mel to set the data is a moot point...  we have the strings already so just use mel
        for j in range(0, len(joints)):
            infIdx = jApiIndices[joints[j]]
            weight = mc.getAttr(weightFmtStr % infIdx)
            if (0 < weight):
                if not (joints[j] in dataSkin[obj].keys()):
                    dataSkin[obj][joints[j]] = [[i], [weight]]
                else:
                    dataSkin[obj][joints[j]][0].append(i)
                    dataSkin[obj][joints[j]][1].append(weight)

    return dataSkin
 def listInfluences(self, asDagPath=True):
     """
     Returns:
       list
     """
     dagPaths = om.MDagPathArray()
     self.fn.influenceObjects(dagPaths)
     if asDagPath: return dagPaths
     else: return [dagPaths[i].partialPathName() for i in xrange(dagPaths.length())]
Exemple #28
0
    def getInfluencesFromSkincluster(self):
        '''
        get influences from skincluster
        output MDagPathArray (influences)   
        '''

        dagArray = om.MDagPathArray()
        self.skinclusterFn.influenceObjects(dagArray)
        return dagArray
Exemple #29
0
    def setInfluenceWeights(self, dagPath, components):
        """

        :param dagPath:
        :param components:
        :return:
        """
        # get the existing weights and fill in the new weights
        weights = self.__getCurrentWeights(dagPath, components)
        influencePaths = openmaya.MDagPathArray()
        numInfluences = self.fn.influenceObjects(influencePaths)
        numComponentsPerInfluence = weights.length() / numInfluences

        # Keep track of which imported influences aren't used
        unusedImports = []
        # Keep track of which existing influences don't get anything imported
        noMatch = [
            influencePaths[ii].partialPathName()
            for ii in xrange(influencePaths.length())
        ]

        for importedInfluence, importedWeights in self.data['weights'].items():
            for inf_count in xrange(influencePaths.length()):
                # partialPathName used to return exclusive partial path name of the object
                influenceName = influencePaths[inf_count].partialPathName()
                influenceWithoutNamespace = SkinCluster.removeNamespaceFromString(
                    influenceName)

                if influenceWithoutNamespace == importedInfluence:
                    # Store the imported weights into the MDoubeArray
                    for jj in xrange(numComponentsPerInfluence):
                        weights.set(importedWeights[jj],
                                    jj * numInfluences + inf_count)

                    noMatch.remove(influenceName)
                    break
            else:
                unusedImports.append(importedInfluence)

        if unusedImports and noMatch:
            mappingDialog = WeightRemapDialog(getMayaWindow())
            mappingDialog.setInfluences(unusedImports, noMatch)
            mappingDialog.exec_()
            for src, dst in mappingDialog.mapping.items():
                for ii in range(influencePaths.length()):
                    if influencePaths[ii].partialPathName() == dst:
                        for jj in range(numComponentsPerInfluence):
                            weights.set(self.data['weights'][src][jj],
                                        jj * numInfluences + ii)
                        break

        influenceIndics = openmaya.MIntArray(numInfluences)
        for ii in range(numInfluences):
            influenceIndics.set(ii, ii)
        self.fn.setWeights(dagPath, components, influenceIndics, weights,
                           False)
Exemple #30
0
    def _TestPrototypes(self, instancerName):
        """
        Tests that all of the instancer prototypes made it to USD.
        """
        self.assertTrue(self.stage)
        instancer = OMFX.MFnInstancer(self._GetDagPath(instancerName))

        # Move to the last frame so that we can ensure all of the prototypes
        # are in use.
        cmds.currentTime(self.END_TIMECODE, edit=True)
        paths = OM.MDagPathArray()
        matrices = OM.MMatrixArray()
        particlePathStartIndices = OM.MIntArray()
        pathIndices = OM.MIntArray()
        instancer.allInstances(paths, matrices, particlePathStartIndices,
                               pathIndices)

        # Check that the Maya instanced objects are what we think they are.
        pathStrings = [paths[i].fullPathName() for i in range(paths.length())]
        self.assertEqual(
            pathStrings,
            [
                # 0 (logical 0) - Cube
                "|dummyGroup|pCube1|pCubeShape1",
                "|dummyGroup|pCube1|pSphere1|pSphereShape1",
                # 1 (logical 2) - Sphere
                "|InstancerTest|%s|prototypeUnderInstancer|prototypeUnderInstancerShape"
                % instancerName,
                # 2 (logical 3) - Reference
                "|referencePrototype|NS_referencePrototype:Geom|NS_referencePrototype:Cone|NS_referencePrototype:ConeShape"
            ])

        # Check that the USD prims have correct type name, references, kinds,
        # kinds, instancerTranslate xformOps.
        instancerPrim = self.stage.GetPrimAtPath("/InstancerTest/%s" %
                                                 instancerName)
        self.assertEqual(
            Usd.ModelAPI(instancerPrim).GetKind(), Kind.Tokens.subcomponent)

        prototypesPrim = instancerPrim.GetChild("Prototypes")
        self.assertEqual(len(prototypesPrim.GetChildren()), 3)
        self.assertEqual(
            Usd.ModelAPI(prototypesPrim).GetKind(), Kind.Tokens.subcomponent)

        # Note that pCube1_0 is a special case where instancerTranslate
        # isn't the opposite of translate, so both have to be left in.
        prototype0 = prototypesPrim.GetChild("pCube1_0")
        self._AssertPrototype(prototype0, "Xform", 2, True)

        prototype1 = prototypesPrim.GetChild("prototypeUnderInstancer_1")
        self._AssertPrototype(prototype1, "Mesh", 0, False)

        prototype2 = prototypesPrim.GetChild("referencePrototype_2")
        self._AssertPrototype(prototype2, "Xform", 1, False)
        self.assertEqual(
            Usd.ModelAPI(prototype2).GetAssetName(), "ConeAssetName")