def fillColor(color, colorName):
    validateChannels()
    channel = getCurrentColorSetNames()[0]
    colorName = COLOR_SET_NAMES[channel] if colorName == None else colorName
    warnMessage = "Fill %s channel's color to %s?" % (channel, colorName)
    resetAll = channel == MAIN_COLOR_SET
    if resetAll:
        warnMessage = "Fill all channels color to %s?" % (colorName)

    result = cmds.confirmDialog(title='Warning',
                                message=warnMessage,
                                button=['OK', 'Cancel'],
                                defaultButton='OK',
                                cancelButton='Cancel',
                                dismissString='Cancel')

    if result != "OK":
        return

    for mesh in getMeshIter():
        colors = mesh.getVertexColors(MAIN_COLOR_SET)
        numColors = len(colors)
        if resetAll:
            for colorSet in RESERVED_SETS:
                defaultColor = COLOR_SET_COLORS[colorSet]
                newColor = [a * b for a, b in zip(color, defaultColor)]
                newColors = om.MColorArray(numColors, om.MColor(newColor))
                mesh.setCurrentColorSetName(colorSet)
                mesh.setVertexColors(newColors, getIncrementIter(numColors))
        else:
            defaultColor = COLOR_SET_COLORS[channel]
            newColor = [a * b for a, b in zip(color, defaultColor)]
            newColors = om.MColorArray(numColors, om.MColor(newColor))
            mesh.setVertexColors(newColors, getIncrementIter(numColors))
Esempio n. 2
0
def create_vertex_color_set(mesh_fn, color_set_name, vertex_colors, mdg):
    """
    Create color set
    """
    mesh_name = mesh_fn.fullPathName()
    vert_ids = xrange(len(vertex_colors))
    colarray = OpenMaya.MColorArray(map(OpenMaya.MColor, vertex_colors))

    current_color_sets = mesh_fn.getColorSetNames()

    if color_set_name in current_color_sets:
        cmds.polyColorSet(mesh_name, delete=True, colorSet=color_set_name)

    clr_vertex_name = "{}.colorPerVertex".format(mesh_name)
    if cmds.objExists(clr_vertex_name):
        cmds.setAttr(clr_vertex_name, lock=False, keyable=True)

    vertex_name = "{}.vertexColor".format(mesh_name)
    if cmds.objExists(vertex_name):
        cmds.setAttr(vertex_name, lock=False, keyable=True)

    mesh_fn.createColorSet(color_set_name,
                           False,
                           rep=OpenMaya.MFnMesh.kRGB,
                           modifier=mdg)

    mesh_fn.setCurrentColorSetName(color_set_name, modifier=mdg)
    mesh_fn.setVertexColors(colarray, vert_ids, modifier=mdg)
Esempio n. 3
0
def vtxColor_2_finalData(inMesh, inColors, div=1.0, defaultAlpha=1):
    meshFn = getMFnMesh(inMesh)
    vfs = cmd.filterExpand('%s.vtxFace[*]' % inMesh, sm=70)
    #vfs_2_v_f_dict = {}
    v_2_vfs_dict = {}
    vis = []
    fis = []
    for vf in vfs:
        vi = int(vf.split('[')[1].split(']')[0])
        fi = int(vf.split('[')[2].split(']')[0])
        vis.append(vi)
        fis.append(fi)
        if vi not in v_2_vfs_dict.keys():
            v_2_vfs_dict[vi] = []
        v_2_vfs_dict[vi].append(vf)
    #print v_2_vfs_dict
    vf_2_color_dict = {}
    for i, color in enumerate(inColors):
        for vf in v_2_vfs_dict[i]:
            vf_2_color_dict[vf] = list(color)
    outColors = []
    for vf in vfs:
        color = vf_2_color_dict[vf]
        color = [x / div for x in color]
        color.append(defaultAlpha)
        outColors.append(color)
    outColors = om2.MColorArray(outColors)
    return outColors, fis, vis
    def combineChannels(self, switchToMain, *args):
        currentChannel = None
        for mesh in getMeshIter():
            currentChannel = mesh.currentColorSetName()

        validateChannels()

        iter = getMeshIter()
        # combine SUB_COLOR_SETS' into MAIN_COLOR_SET
        for mesh in iter:
            rColors = mesh.getVertexColors(R_CHANNEL)
            gColors = mesh.getVertexColors(G_CHANNEL)
            bColors = mesh.getVertexColors(B_CHANNEL)
            aColors = mesh.getVertexColors(A_CHANNEL)

            colors = om.MColorArray(mesh.numVertices, om.MColor((1, 1, 1, 1)))
            for i in xrange(mesh.numVertices):
                colors[i] = om.MColor(
                    (rColors[i].r, gColors[i].g, bColors[i].b, aColors[i].r))

            mesh.setCurrentColorSetName(MAIN_COLOR_SET)
            mesh.setVertexColors(colors, getIncrementIter(mesh.numVertices))
            mesh.syncObject()

        if switchToMain:
            currentChannel = MAIN_COLOR_SET

        if currentChannel != None:
            for mesh in getMeshIter():
                mesh.setCurrentColorSetName(currentChannel)
            self.updateUi()
Esempio n. 5
0
def static_compare(mesh, target, clamp=10, world=True):
    """
    Compares two meshes on a given static frame.
    Sets a vertex color value to show the distance values.
    
    :param mesh: The name or path to the mesh to visualize on.
    :param target: The name or path of the mesh we are comparing against.
    :param clamp: The value to clamp against. All values be scaled accordingly.
    :param world: Whether to compare in world space or object space.
    """
    # Get the Dag Paths to the mesh shapes
    mesh = get_shape(mesh)
    target = get_shape(target)

    # Turn on visualization of the vertex colors on the shape
    mesh_path = mesh.fullPathName()
    mc.polyOptions(mesh_path, colorShadedDisplay=True)

    # Get Mesh objects from the shapes.
    mesh_mesh = om.MFnMesh(mesh)
    target_mesh = om.MFnMesh(target)

    # For each mesh, get their points
    space = om.MSpace.kWorld if world else om.MSpace.kObject
    mesh_points = mesh_mesh.getPoints(space)
    target_points = target_mesh.getPoints(space)
    print("mesh points = ", len(mesh_points))
    print("target points = ", len(target_points))

    colors = om.MColorArray()
    ids = []

    # Loop through to calculate the colors
    for i, mpoint in enumerate(mesh_points):
        tpoint = target_points[i]

        # Get the distance between the vertices.
        distance = math.sqrt(((mpoint.x - tpoint.x)**2) +
                             ((mpoint.y - tpoint.y)**2) +
                             ((mpoint.z - tpoint.z)**2))

        # If our distance is not zero, then process it
        if distance:
            # First scale according to the clamp value
            scaled = distance / clamp
            # Then clamp it off at 1
            clamped = min(scaled, 1)
            # Finally we only want half its value since our base color is 50% grey
            distance = clamped / 2.0

        # Start from 50% grey and bias to the red channel as distance grows
        color = om.MColor((0.5 + distance, 0.5 - distance, 0.5 - distance))

        colors.append(color)
        ids.append(i)

    # Apply the colors
    mesh_mesh.setVertexColors(colors, ids)
Esempio n. 6
0
def smooth_vertex_with_falloff():

    #dist = Om2.MVector()
    for vtx_a in xrange(vtx):
        near_colors = Om2.MColorArray()
        near_distances = []
        for vtx_b in xrange(vtx):
            dist = mesh_vector_array[vtx_a] - mesh_vector_array[vtx_b]
            if dist.length() < max_dist:
                near_distances.append(dist.length())
                near_colors.append(color_array[vtx_b])

        final_color_array[vtx_a] = distance_falloff.get_falloff(
            near_distances, near_colors)

    return final_color_array
Esempio n. 7
0
    def verifyLayerState(self, layer):
        if layer == 'composite':
            return
        else:
            obj = sxglobals.settings.shapeArray[
                len(sxglobals.settings.shapeArray) - 1]
            selectionList = OM.MSelectionList()
            selectionList.add(obj)
            nodeDagPath = OM.MDagPath()
            nodeDagPath = selectionList.getDagPath(0)
            MFnMesh = OM.MFnMesh(nodeDagPath)

            layerColors = OM.MColorArray()
            layerColors = MFnMesh.getFaceVertexColors(colorSet=layer)

            # States: visibility, mask, adjustment
            state = [False, False, False]
            state[0] = (bool(
                maya.cmds.getAttr(str(obj) + '.' + str(layer) + 'Visibility')))

            for k in range(len(layerColors)):
                if ((layerColors[k].a > 0)
                        and (layerColors[k].a <
                             sxglobals.settings.project['AlphaTolerance'])):
                    state[2] = True
                elif ((layerColors[k].a >=
                       sxglobals.settings.project['AlphaTolerance'])
                      and (layerColors[k].a <= 1)):
                    state[1] = True

            if not state[0]:
                hidden = 'H'
            else:
                hidden = ' '
            if state[1]:
                mask = 'M'
            else:
                mask = ' '
            if state[2]:
                adj = 'A'
            else:
                adj = ' '

            layerName = sxglobals.settings.project['LayerData'][layer][6]
            itemString = hidden + mask + adj + '  ' + layerName
            return itemString
Esempio n. 8
0
    def compute(self, plug, data):

        if plug == self.aOutShape:

            thisObj = self.thisMObject()
            origHandle = data.inputValue(self.aOrigShape)
            deformedHandle = data.inputValue(self.aDeformedShape)
            outHandle = data.outputValue(self.aOutShape)
            colorRamp = om2.MRampAttribute(thisObj, self.aColorRamp)

            if self.isOrigDirty:
                self.isOrigDirty = False
                self.origEdgeLenArray = self.getEdgeLen(origHandle)

            if self.isDeformedDirty:
                self.isDeformedDirty = False
                self.deformedEdgeLenArray = self.getEdgeLen(deformedHandle)

            origEdges = self.origEdgeLenArray
            defmEdges = self.deformedEdgeLenArray

            if len(origEdges) == len(defmEdges):

                outHandle.copy(deformedHandle)
                outHandle.setMObject(deformedHandle.asMesh())

                outMesh = outHandle.asMesh()
                meshFn = om2.MFnMesh(outMesh)
                numVerts = meshFn.numVertices
                vertColors = om2.MColorArray()
                vertColors.setLength(numVerts)

                for i in xrange(numVerts):
                    delta = 0.5
                    delta += ((origEdges[i] - defmEdges[i]) / origEdges[i])

                    vertColor = colorRamp.getValueAtPosition(delta)
                    vertColors[i] = vertColor

                if not self.setAndAssignColors(meshFn, vertColors):
                    self.setVertexColors(meshFn, vertColors)

            else:
                print("Edge count doesn't match.")

        data.setClean(plug)
Esempio n. 9
0
def glDrawTriangles(drawManager, camMatrix, coords, ssOffsets, color, colors):
    colorsArray = ompy.MColorArray()
    for i in range(0, coords.length()):
        if (colors.length() == 0):
            colorsArray.append(
                ompy.MColor([color[0], color[1], color[2], color[3]]))
        else:
            colorsArray.append(
                ompy.MColor(
                    [colors[i][0], colors[i][1], colors[i][2], colors[i][3]]))

    for i in range(0, coords.length()):
        coords[i] += utils_screenTo3dOffset(
            camMatrix, coords[i], ssOffsets[min(i,
                                                ssOffsets.length() - 1)])

    drawManager.mesh(ompyr.MUIDrawManager.kTriangles, coords, None,
                     colorsArray)
def loadTexture(fileName, fileType):
    if (fileName == None or len(fileName) == 0):
        return
    maya.mel.eval("PaintVertexColorTool;")
    context = cmds.currentCtx()
    cmds.artAttrPaintVertexCtx(context,
                               whichTool="colorPerVertex",
                               e=True,
                               ifm="rgba",
                               ifl=fileName)

    mesh = getMesh()

    if isMainColorSet():
        subColorSets = SUB_COLOR_SETS
        colors = mesh.getVertexColors(MAIN_COLOR_SET)
    else:
        subColorSets = [mesh.currentColorSetName()]
        colors = mesh.getVertexColors(subColorSets[0])

    # filter unused channel
    for subColorSet in subColorSets:
        mesh.setCurrentColorSetName(subColorSet)
        useR = int(subColorSet == R_CHANNEL or subColorSet == MAIN_COLOR_SET)
        useG = int(subColorSet == G_CHANNEL or subColorSet == MAIN_COLOR_SET)
        useB = int(subColorSet == B_CHANNEL or subColorSet == MAIN_COLOR_SET)
        useA = int(subColorSet == A_CHANNEL)

        numColors = len(colors)
        subColors = om.MColorArray(numColors, om.MColor((1.0, 1.0, 1.0, 1.0)))
        for i in xrange(numColors):
            color = colors[i]
            subColors[i] = om.MColor((color.r * useR + color.a * useA,
                                      color.g * useG + color.a * useA,
                                      color.b * useB + color.a * useA, 1))
        mesh.setVertexColors(subColors, getIncrementIter(numColors))
Esempio n. 11
0
def static_compare(mesh, target, clamp=1, world=False, saturation=0.8):
    """
    Compares two meshes on a given static frame.
    Sets a vertex color value to show the distance values.
    Colors will go from green at the least to red at the point of clamping.
    
    :param mesh: The name or path to the mesh to visualize on.
    :param target: The name or path of the mesh we are comparing against.
    :param clamp: The value to clamp against. All values be scaled accordingly.
                  i.e if you clamp at 10, absolute red will be 10 units
    :param world: Whether to compare in world space or object space.
    :param saturation: The maximum saturation value to use
    """
    # Get the Dag Paths to the mesh shapes
    mesh = get_shape(mesh)
    target = get_shape(target)

    # Turn on visualization of the vertex colors on the shape
    mesh_path = mesh.fullPathName()
    mc.polyOptions(mesh_path, colorShadedDisplay=True)

    # Get Mesh objects from the shapes.
    mesh_mesh = om.MFnMesh(mesh)
    target_mesh = om.MFnMesh(target)

    # For each mesh, get their points
    space = om.MSpace.kWorld if world else om.MSpace.kObject
    mesh_points = mesh_mesh.getPoints(space)
    target_points = target_mesh.getPoints(space)

    if len(mesh_points) != len(target_points):
        raise RuntimeError("Meshes do not have the same vertex count")

    colors = om.MColorArray()
    ids = []

    # Loop through to calculate the colors
    for i, mpoint in enumerate(mesh_points):
        tpoint = target_points[i]

        # Get the distance between the vertices.
        distance = math.sqrt(((mpoint.x - tpoint.x)**2) +
                             ((mpoint.y - tpoint.y)**2) +
                             ((mpoint.z - tpoint.z)**2))

        hue = 0
        sat = 0
        val = 0.5
        # If our distance is not zero, then process it
        if distance:
            sat = saturation
            val = 1
            # First scale according to the clamp value
            scaled = distance / clamp
            # Then clamp it off at 1
            clamped = min(scaled, 1)
            hue = 180 - ((360 * clamped) / 2)

        # Start from 50% grey and bias to the red channel as distance grows
        color = om.MColor((hue, sat, val), om.MColor.kHSV)

        colors.append(color)
        ids.append(i)

    # Apply the colors
    mesh_mesh.setVertexColors(colors, ids)
Esempio n. 12
0
    def _importCtm(self, fileName, importOptions):
        verbose = importOptions.get('verbose', False)
        context = openctm.ctmNewContext(openctm.CTM_IMPORT)

        # Extract file
        openctm.ctmLoad(context, fileName)
        e = openctm.ctmGetError(context)
        if e != 0:
            s = openctm.ctmErrorString(e)
            print(s)
            openctm.ctmFreeContext(context)
            raise Exception(s)

        # Extract indices
        triCount = openctm.ctmGetInteger(context, openctm.CTM_TRIANGLE_COUNT)
        ctmIndices = openctm.ctmGetIntegerArray(context, openctm.CTM_INDICES)
        polyCount = [3] * triCount

        # Extract vertices
        vertCount = openctm.ctmGetInteger(context, openctm.CTM_VERTEX_COUNT)
        ctmVertices = openctm.ctmGetFloatArray(context, openctm.CTM_VERTICES)
        vertices = OpenMaya.MFloatPointArray()
        vertices.setLength(vertCount)

        # Extract Normals
        ctmVertNormals = None
        vertNormals = OpenMaya.MFloatPointArray()
        hasNormals = openctm.ctmGetInteger(
            context, openctm.CTM_HAS_NORMALS) == openctm.CTM_TRUE
        if hasNormals:
            ctmVertNormals = openctm.ctmGetFloatArray(context,
                                                      openctm.CTM_NORMALS)
            vertNormals.setLength(vertCount)

        # Extract UVs
        hasUVs = openctm.ctmGetInteger(context, openctm.CTM_UV_MAP_COUNT) > 0
        ctmTexCoords = None
        uCoords = OpenMaya.MFloatArray()
        vCoords = OpenMaya.MFloatArray()

        if hasUVs:
            ctmTexCoords = openctm.ctmGetFloatArray(context,
                                                    openctm.CTM_UV_MAP_1)
            uCoords.setLength(vertCount)
            vCoords.setLength(vertCount)
            textureFilename = openctm.ctmGetUVMapString(
                context, openctm.CTM_UV_MAP_1, openctm.CTM_FILE_NAME)
            # TODO: Load texture file
            if textureFilename:
                pass

        # Extract colors
        colorAttrib = openctm.ctmGetNamedAttribMap(context, "Color")
        hasVertexColors = colorAttrib != openctm.CTM_NONE
        ctmColors = None
        vertexColors = OpenMaya.MColorArray()
        if hasVertexColors:
            ctmColors = openctm.ctmGetFloatArray(context, colorAttrib)
            vertexColors.setLength(vertCount)

        pointToIndex = {}
        ctmVertIndexToUniqueIndex = {}
        nrSkippedVertices = 0
        for i in range(vertCount):
            ctmVertIndex = i * 3
            p = (float(ctmVertices[ctmVertIndex]),
                 float(ctmVertices[ctmVertIndex + 1]),
                 float(ctmVertices[ctmVertIndex + 2]))
            if p not in pointToIndex:
                index = i - nrSkippedVertices
                pointToIndex[p] = index
                ctmVertIndexToUniqueIndex[i] = index
                vertices[index].x = p[0]
                vertices[index].y = p[1]
                vertices[index].z = p[2]

                if hasNormals:
                    vertNormals[index].x = float(ctmVertNormals[ctmVertIndex])
                    vertNormals[index].y = float(ctmVertNormals[ctmVertIndex +
                                                                1])
                    vertNormals[index].z = float(ctmVertNormals[ctmVertIndex +
                                                                2])

                if hasUVs:
                    ctmUVIndex = i * 2
                    uCoords[index] = float(ctmTexCoords[ctmUVIndex])
                    vCoords[index] = float(ctmTexCoords[ctmUVIndex + 1])

                if hasVertexColors:
                    ctmColIndex = i * 4
                    vertexColors[index].r = float(ctmColors[ctmColIndex])
                    vertexColors[index].g = float(ctmColors[ctmColIndex + 1])
                    vertexColors[index].b = float(ctmColors[ctmColIndex + 2])
                    vertexColors[index].a = float(ctmColors[ctmColIndex + 3])
            else:
                ctmVertIndexToUniqueIndex[i] = pointToIndex[p]
                nrSkippedVertices += 1

        uniqVertCount = len(pointToIndex)
        vertices.setLength(uniqVertCount)
        vertNormals.setLength(uniqVertCount)

        indices = [
            ctmVertIndexToUniqueIndex[ctmIndices[i]]
            for i in range(3 * triCount)
        ]

        if hasUVs:
            uCoords.setLength(uniqVertCount)
            vCoords.setLength(uniqVertCount)

        if hasVertexColors:
            vertexColors.setLength(uniqVertCount)

        if verbose:
            method = openctm.ctmGetInteger(context,
                                           openctm.CTM_COMPRESSION_METHOD)
            if method == openctm.CTM_METHOD_RAW:
                methodStr = "RAW"
            elif method == openctm.CTM_METHOD_MG1:
                methodStr = "MG1"
            elif method == openctm.CTM_METHOD_MG2:
                methodStr = "MG2"
            else:
                methodStr = "Unknown"
            print("File: %s" % fileName)
            print("Comment: %s" %
                  str(openctm.ctmGetString(context, openctm.CTM_FILE_COMMENT)))
            print("Compression Method: %s" % methodStr)
            print("Vertices Count : %d" % vertCount)
            print("Unique Vertices Count : %d" % uniqVertCount)
            print("Triangles Count: %d" % triCount)
            print("Has normals: %r" % hasNormals)
            print("Has UVs: %r" % hasUVs)
            print("Has Vertex Colors: %r" % hasVertexColors)

        fnMesh = OpenMaya.MFnMesh()
        newMesh = fnMesh.create(vertices, polyCount, indices, uCoords, vCoords)

        if hasNormals:
            fnMesh.setVertexNormals(vertNormals, range(len(vertices)))

        if hasVertexColors:
            fnMesh.setVertexColors(vertexColors, range(len(vertices)))

        fnMesh.updateSurface()

        # Assign initial shading group
        slist = OpenMaya.MGlobal.getSelectionListByName("initialShadingGroup")
        initialSG = slist.getDependNode(0)

        fnSG = OpenMaya.MFnSet(initialSG)
        if fnSG.restriction() == OpenMaya.MFnSet.kRenderableOnly:
            fnSG.addMember(newMesh)
def validateChannels():
    # create MAIN_COLOR_SET if not exist: rename existing color set or create a new one if no color sets defined

    for mesh in getMeshIter():
        currentColorSet = mesh.currentColorSetName()
        colorSets = mesh.getColorSetNames()
        if colorSets == None or not MAIN_COLOR_SET in colorSets:
            mainColors = om.MColorArray(mesh.numVertices,
                                        om.MColor((1.0, 1.0, 1.0, 1.0)))
            mesh.createColorSet(MAIN_COLOR_SET, True)
            mesh.setColors(mainColors, MAIN_COLOR_SET)
            mesh.setCurrentColorSetName(MAIN_COLOR_SET)
            mesh.setVertexColors(mainColors,
                                 getIncrementIter(mesh.numVertices))
            mesh.syncObject()

        mainColors = None

        for subColorSet in SUB_COLOR_SETS:
            if colorSets == None or not subColorSet in colorSets:
                if mainColors == None:
                    mainColors = mesh.getVertexColors(MAIN_COLOR_SET)
                numColors = len(mainColors)
                mesh.createColorSet(subColorSet, True)
                useR = int(subColorSet == R_CHANNEL
                           or subColorSet == A_CHANNEL)
                useG = int(subColorSet == G_CHANNEL
                           or subColorSet == A_CHANNEL)
                useB = int(subColorSet == B_CHANNEL
                           or subColorSet == A_CHANNEL)

                subColors = om.MColorArray(numColors,
                                           om.MColor((1.0, 1.0, 1.0, 1.0)))
                for i in xrange(numColors):
                    color = mainColors[i]
                    subColors[i] = om.MColor(
                        (color.r * useR, color.g * useG, color.b * useB, 1))

                mesh.setCurrentColorSetName(subColorSet)
                mesh.setVertexColors(subColors, getIncrementIter(numColors))

        # make sure color_sets[0] is MAIN_COLOR_SET
        colorSets = mesh.getColorSetNames()
        if colorSets[0] != MAIN_COLOR_SET:
            otherSet = colorSets[0]
            aBuff = mesh.getVertexColors(otherSet)
            bBuff = mesh.getVertexColors(MAIN_COLOR_SET)
            mesh.setCurrentColorSetName(otherSet)
            mesh.setVertexColors(bBuff, getIncrementIter(len(bBuff)))
            mesh.setCurrentColorSetName(MAIN_COLOR_SET)
            mesh.setVertexColors(aBuff, getIncrementIter(len(aBuff)))
            mesh.syncObject()
            cmds.polyColorSet(rename=True,
                              colorSet=otherSet,
                              newColorSet="__TEMP")
            cmds.polyColorSet(rename=True,
                              colorSet=MAIN_COLOR_SET,
                              newColorSet=otherSet)
            cmds.polyColorSet(rename=True,
                              colorSet="__TEMP",
                              newColorSet=MAIN_COLOR_SET)

        if (currentColorSet == None or len(currentColorSet) == 0):
            mesh.setCurrentColorSetName(R_CHANNEL)
        else:
            mesh.setCurrentColorSetName(currentColorSet)
Esempio n. 14
0
    def getLayerPaletteAndOpacity(self, obj, layer):
        selectionList = OM.MSelectionList()
        selectionList.add(obj)
        nodeDagPath = OM.MDagPath()
        nodeDagPath = selectionList.getDagPath(0)
        MFnMesh = OM.MFnMesh(nodeDagPath)

        layerColorArray = OM.MColorArray()
        layerColorArray = MFnMesh.getFaceVertexColors(colorSet=layer)
        black = OM.MColor()
        black = (0, 0, 0, 1)

        layerPaletteArray = OM.MColorArray()
        layerPaletteArray.setLength(8)
        for k in range(0, 8):
            layerPaletteArray[k] = black

        n = 0
        alphaMax = 0
        for k in range(len(layerColorArray)):
            match = False
            for p in range(0, 8):
                if ((layerColorArray[k].r == layerPaletteArray[p].r)
                        and (layerColorArray[k].g == layerPaletteArray[p].g)
                        and (layerColorArray[k].b == layerPaletteArray[p].b)):
                    match = True

            if (not match) and (n < 8):
                layerPaletteArray[n] = layerColorArray[k]
                n += 1

            if layerColorArray[k].a > alphaMax:
                alphaMax = layerColorArray[k].a

        if maya.cmds.floatSlider('layerOpacitySlider', exists=True):
            maya.cmds.floatSlider('layerOpacitySlider',
                                  edit=True,
                                  value=alphaMax)
            sxglobals.settings.layerAlphaMax = alphaMax

        for k in range(0, 8):
            maya.cmds.palettePort('layerPalette',
                                  edit=True,
                                  rgb=(k, layerPaletteArray[k].r,
                                       layerPaletteArray[k].g,
                                       layerPaletteArray[k].b))
            maya.cmds.palettePort('layerPalette', edit=True, redraw=True)

        if 'layer' not in layer:
            if maya.cmds.optionMenu('layerBlendModes', exists=True):
                maya.cmds.optionMenu('layerBlendModes',
                                     edit=True,
                                     enable=False)
            if maya.cmds.text('layerOpacityLabel', exists=True):
                maya.cmds.text('layerOpacityLabel', edit=True, enable=False)
            if maya.cmds.floatSlider('layerOpacitySlider', exists=True):
                maya.cmds.floatSlider('layerOpacitySlider',
                                      edit=True,
                                      enable=False)
            return
        # Blend modes are only valid for color layers,
        # not material channels
        else:
            if maya.cmds.text('layerOpacityLabel', exists=True):
                maya.cmds.text('layerOpacityLabel', edit=True, enable=True)
            if maya.cmds.floatSlider('layerOpacitySlider', exists=True):
                maya.cmds.floatSlider('layerOpacitySlider',
                                      edit=True,
                                      enable=True)

            attr = ('.' + sxglobals.settings.project['RefNames'][
                sxglobals.settings.tools['selectedLayerIndex'] - 1] +
                    'BlendMode')
            mode = maya.cmds.getAttr(str(obj) + attr) + 1
            maya.cmds.optionMenu('layerBlendModes',
                                 edit=True,
                                 select=mode,
                                 enable=True)
Esempio n. 15
0
    def compositeLayers(self):
        # startTimeOcc = maya.cmds.timerX()
        if sxglobals.settings.tools['compositeEnabled']:
            numLayers = sxglobals.settings.project['LayerCount']

            maya.cmds.polyColorSet(sxglobals.settings.shapeArray,
                                   currentColorSet=True,
                                   colorSet='composite')

            for selected in sxglobals.settings.shapeArray:
                selectionList = OM.MSelectionList()
                selectionList.add(selected)
                nodeDagPath = OM.MDagPath()
                nodeDagPath = selectionList.getDagPath(0)
                MFnMesh = OM.MFnMesh(nodeDagPath)

                sourceColorArray = OM.MColorArray()
                targetColorArray = OM.MColorArray()
                targetColorArray = MFnMesh.getFaceVertexColors(
                    colorSet='layer1')

                faceIds = OM.MIntArray()
                vtxIds = OM.MIntArray()

                lenSel = len(targetColorArray)

                faceIds.setLength(lenSel)
                vtxIds.setLength(lenSel)

                # generate faceID and vertexID arrays
                fvIt = OM.MItMeshFaceVertex(nodeDagPath)
                k = 0
                while not fvIt.isDone():
                    faceIds[k] = fvIt.faceId()
                    vtxIds[k] = fvIt.vertexId()
                    k += 1
                    fvIt.next()

                sel = str(selected)
                shading = int(maya.cmds.getAttr(sel + '.shadingMode'))

                # Set layer1 to black if hidden
                visAttr = '.layer1Visibility'
                vis = bool(maya.cmds.getAttr(sel + visAttr))

                if not vis:
                    fvIt = OM.MItMeshFaceVertex(nodeDagPath)
                    k = 0
                    while not fvIt.isDone():
                        targetColorArray[k].r = 0.0
                        targetColorArray[k].g = 0.0
                        targetColorArray[k].b = 0.0
                        targetColorArray[k].a = 1.0
                        k += 1
                        fvIt.next()

                # accumulate targetColorArray through the remaining layers
                if shading == 0:
                    if numLayers > 1:
                        for i in range(2, numLayers + 1):
                            sourceLayer = 'layer' + str(i)

                            modeAttr = '.' + sourceLayer + 'BlendMode'
                            mode = int(maya.cmds.getAttr(sel + modeAttr))

                            visAttr = '.' + sourceLayer + 'Visibility'
                            vis = bool(maya.cmds.getAttr(sel + visAttr))
                            sourceColorArray = MFnMesh.getFaceVertexColors(
                                colorSet=sourceLayer)

                            fvIt = OM.MItMeshFaceVertex(nodeDagPath)

                            if not vis:
                                continue

                            elif mode == 0:
                                k = 0
                                while not fvIt.isDone():
                                    targetColorArray[k].r = (
                                        sourceColorArray[k].r *
                                        sourceColorArray[k].a +
                                        targetColorArray[k].r *
                                        (1 - sourceColorArray[k].a))
                                    targetColorArray[k].g = (
                                        sourceColorArray[k].g *
                                        sourceColorArray[k].a +
                                        targetColorArray[k].g *
                                        (1 - sourceColorArray[k].a))
                                    targetColorArray[k].b = (
                                        sourceColorArray[k].b *
                                        sourceColorArray[k].a +
                                        targetColorArray[k].b *
                                        (1 - sourceColorArray[k].a))
                                    #targetColorArray[k].a = 1.0
                                    k += 1
                                    fvIt.next()

                            elif mode == 1:
                                k = 0
                                while not fvIt.isDone():
                                    targetColorArray[k].r += sourceColorArray[
                                        k].r * sourceColorArray[k].a
                                    targetColorArray[k].g += sourceColorArray[
                                        k].g * sourceColorArray[k].a
                                    targetColorArray[k].b += sourceColorArray[
                                        k].b * sourceColorArray[k].a
                                    #targetColorArray[k].a = 1.0
                                    k += 1
                                    fvIt.next()

                            elif mode == 2:
                                # layer2 lerp with white using (1-alpha), multiply with layer1
                                k = 0
                                while not fvIt.isDone():
                                    sourceColorArray[k].r = (
                                        (sourceColorArray[k].r *
                                         sourceColorArray[k].a) +
                                        (1.0 * (1 - sourceColorArray[k].a)))
                                    sourceColorArray[k].g = (
                                        (sourceColorArray[k].g *
                                         sourceColorArray[k].a) +
                                        (1.0 * (1 - sourceColorArray[k].a)))
                                    sourceColorArray[k].b = (
                                        (sourceColorArray[k].b *
                                         sourceColorArray[k].a) +
                                        (1.0 * (1 - sourceColorArray[k].a)))

                                    targetColorArray[k].r = sourceColorArray[
                                        k].r * targetColorArray[k].r
                                    targetColorArray[k].g = sourceColorArray[
                                        k].g * targetColorArray[k].g
                                    targetColorArray[k].b = sourceColorArray[
                                        k].b * targetColorArray[k].b
                                    k += 1
                                    fvIt.next()
                            else:
                                print('SX Tools Error: Invalid blend mode')
                                return

                elif shading == 1:
                    targetColorArray = MFnMesh.getFaceVertexColors(
                        colorSet=sxglobals.settings.tools['selectedLayer'])
                    fvIt = OM.MItMeshFaceVertex(nodeDagPath)
                    k = 0
                    while not fvIt.isDone():
                        if targetColorArray[k].a == 0.0:
                            targetColorArray[k].r = 0.0
                            targetColorArray[k].g = 0.0
                            targetColorArray[k].b = 0.0
                        k += 1
                        fvIt.next()

                elif shading == 2:
                    targetColorArray = MFnMesh.getFaceVertexColors(
                        colorSet=sxglobals.settings.tools['selectedLayer'])
                    fvIt = OM.MItMeshFaceVertex(nodeDagPath)
                    k = 0
                    while not fvIt.isDone():
                        targetColorArray[k].r = targetColorArray[k].a
                        targetColorArray[k].g = targetColorArray[k].a
                        targetColorArray[k].b = targetColorArray[k].a
                        targetColorArray[k].a = 1.0
                        k += 1
                        fvIt.next()

                MFnMesh.setFaceVertexColors(targetColorArray, faceIds, vtxIds)
Esempio n. 16
0
    def mergeLayers(self, objects, sourceLayer, targetLayer, up):
        # startTimeOcc = maya.cmds.timerX()

        attrA = '.' + str(sourceLayer) + 'BlendMode'
        attrB = '.' + str(targetLayer) + 'BlendMode'
        color = sxglobals.settings.project['LayerData'][sourceLayer][1]

        fillColor = OM.MColor()
        fillColor.r = color[0]
        fillColor.g = color[1]
        fillColor.b = color[2]
        fillColor.a = color[3]

        for obj in objects:
            mode = int(maya.cmds.getAttr(obj + attrA))

            selectionList = OM.MSelectionList()
            selectionList.add(obj)
            nodeDagPath = OM.MDagPath()
            nodeDagPath = selectionList.getDagPath(0)
            MFnMesh = OM.MFnMesh(nodeDagPath)

            sourceColorArray = OM.MColorArray()
            targetColorArray = OM.MColorArray()
            fillColorArray = OM.MColorArray()
            sourceColorArray = MFnMesh.getFaceVertexColors(
                colorSet=sourceLayer)
            targetColorArray = MFnMesh.getFaceVertexColors(
                colorSet=targetLayer)
            fillColorArray = MFnMesh.getFaceVertexColors(colorSet=sourceLayer)
            faceIds = OM.MIntArray()
            vtxIds = OM.MIntArray()

            lenSel = len(sourceColorArray)

            faceIds.setLength(lenSel)
            vtxIds.setLength(lenSel)

            fvIt = OM.MItMeshFaceVertex(nodeDagPath)
            k = 0
            while not fvIt.isDone():
                faceIds[k] = fvIt.faceId()
                vtxIds[k] = fvIt.vertexId()
                fillColorArray[k] = fillColor
                k += 1
                fvIt.next()

            fvIt = OM.MItMeshFaceVertex(nodeDagPath)

            # alpha blend
            if mode == 0:
                k = 0
                while not fvIt.isDone():
                    targetColorArray[k].r = (
                        sourceColorArray[k].r * sourceColorArray[k].a +
                        targetColorArray[k].r * (1 - sourceColorArray[k].a))
                    targetColorArray[k].g = (
                        sourceColorArray[k].g * sourceColorArray[k].a +
                        targetColorArray[k].g * (1 - sourceColorArray[k].a))
                    targetColorArray[k].b = (
                        sourceColorArray[k].b * sourceColorArray[k].a +
                        targetColorArray[k].b * (1 - sourceColorArray[k].a))
                    targetColorArray[k].a += sourceColorArray[k].a
                    if targetColorArray[k].a > 1.0:
                        targetColorArray[k].a = 1.0
                    k += 1
                    fvIt.next()

            # additive
            elif mode == 1:
                k = 0
                while not fvIt.isDone():
                    faceIds[k] = fvIt.faceId()
                    vtxIds[k] = fvIt.vertexId()

                    targetColorArray[
                        k].r += sourceColorArray[k].r * sourceColorArray[k].a
                    targetColorArray[
                        k].g += sourceColorArray[k].g * sourceColorArray[k].a
                    targetColorArray[
                        k].b += sourceColorArray[k].b * sourceColorArray[k].a
                    targetColorArray[k].a += sourceColorArray[k].a
                    if targetColorArray[k].a > 1.0:
                        targetColorArray[k].a = 1.0
                    k += 1
                    fvIt.next()

            # multiply
            elif mode == 2:
                # layer2 lerp with white using (1-alpha), multiply with layer1
                k = 0
                while not fvIt.isDone():
                    faceIds[k] = fvIt.faceId()
                    vtxIds[k] = fvIt.vertexId()

                    sourceColorArray[k].r = (
                        (sourceColorArray[k].r * sourceColorArray[k].a) +
                        (1.0 * (1 - sourceColorArray[k].a)))
                    sourceColorArray[k].g = (
                        (sourceColorArray[k].g * sourceColorArray[k].a) +
                        (1.0 * (1 - sourceColorArray[k].a)))
                    sourceColorArray[k].b = (
                        (sourceColorArray[k].b * sourceColorArray[k].a) +
                        (1.0 * (1 - sourceColorArray[k].a)))

                    targetColorArray[
                        k].r = sourceColorArray[k].r * targetColorArray[k].r
                    targetColorArray[
                        k].g = sourceColorArray[k].g * targetColorArray[k].g
                    targetColorArray[
                        k].b = sourceColorArray[k].b * targetColorArray[k].b
                    k += 1
                    fvIt.next()
            else:
                print('SX Tools Error: Invalid blend mode')
                return

            if up:
                maya.cmds.polyColorSet(obj,
                                       currentColorSet=True,
                                       colorSet=targetLayer)
                MFnMesh.setFaceVertexColors(targetColorArray, faceIds, vtxIds)
                maya.cmds.polyColorSet(obj,
                                       currentColorSet=True,
                                       colorSet=sourceLayer)
                MFnMesh.setFaceVertexColors(fillColorArray, faceIds, vtxIds)
            else:
                maya.cmds.polyColorSet(obj,
                                       currentColorSet=True,
                                       colorSet=sourceLayer)
                MFnMesh.setFaceVertexColors(targetColorArray, faceIds, vtxIds)
                maya.cmds.polyColorSet(obj,
                                       currentColorSet=True,
                                       colorSet=targetLayer)
                MFnMesh.setFaceVertexColors(fillColorArray, faceIds, vtxIds)

            maya.cmds.setAttr(str(obj) + attrA, 0)
            maya.cmds.setAttr(str(obj) + attrB, 0)