def vertexColorFloodMaya(colorSet, value, channels=[False, False, False, False], replace=True): """ Assigns vertex colors to a specific colorSet of all selected objects Args: colorSet (str): Which color set to flood value (float): What value to flood the color with channels (bool lst): RGBA list of color channels to flood replace (bool): If the value needs to be replaced """ logger.debug("-> Flooding {0} at channels {1} with value {2}".format(colorSet, channels, value)) channelChars = ['r', 'g', 'b', 'a'] # find selected shapes selected = cmds.ls(sl=True) shapes = lib.getShapes(selected) enableVtxCtrl(shapes) # set the current color set try: cmds.polyColorSet(shapes, currentColorSet=True, cs=colorSet) # sets the current color set of all shapes except RuntimeError: cmds.error("One or more of the objects has not been prepped") # find channel to flood for channel in channels: if channel: channelChar = channelChars[channels.index(channel)] if replace: logger.debug("Resetting control parameters in: {0} with {1}".format(shapes, value)) eval("cmds.polyColorPerVertex({0}={1})".format(channelChar, value)) else: logger.debug("Flooding control parameters in: {0} with {1}".format(shapes, value)) eval("cmds.polyColorPerVertex({0}={1}, rel=True)".format(channelChar, value))
def switch_to_color_set(obj): """ Switches supplied object's color set to display skin weights. Needs to do this otherwise we risk overwriting another color set. Args: obj(string) """ color_set_name = "weightsEditorColorSet" obj_shapes = cmds.listRelatives(obj, f=True, shapes=True) or [] old_color_sets = set( cmds.ls(cmds.listHistory(obj_shapes), type="createColorSet")) obj_color_sets = cmds.polyColorSet(obj, q=True, allColorSets=True) or [] if color_set_name not in obj_color_sets: cmds.polyColorSet(obj, create=True, clamped=False, representation="RGB", colorSet=color_set_name) cmds.polyColorSet(obj, currentColorSet=True, colorSet=color_set_name) new_color_sets = set( cmds.ls(cmds.listHistory(obj_shapes), type="createColorSet")) dif_color_sets = list(new_color_sets.difference(old_color_sets)) if dif_color_sets: cmds.addAttr(dif_color_sets[0], ln="weightsEditorCreateColorSet", dt="string") cmds.rename(dif_color_sets[0], "weightsEditorCreateColorSet")
def delete_color_sets(shapes, color_sets): """ Deletes vertex color sets and their history from shapes Args: shapes (list): Shapes to delete vertex color sets from color_sets (list, unicode): Vertex color sets to delete """ shapes = clib.u_enlist(shapes) # put in list color_sets = clib.u_enlist(color_sets) # put in list nodes2delete = [] for shape in shapes: shape_color_sets = cmds.polyColorSet( shape, query=True, allColorSets=True) or [] for color_set in color_sets: if color_set in shape_color_sets: cmds.polyColorSet(shape, colorSet=color_set, delete=True) history = cmds.listHistory(shape) for node in history: # check if attribute exists if not cmds.attributeQuery('colorSetName', n=node, ex=True): continue # attribute exists, check name of color set name color_set_name = cmds.getAttr( "{0}.colorSetName".format(node)) if color_set_name == color_set: nodes2delete.append(node) if nodes2delete: cmds.delete(nodes2delete) LOG.debug("Vertex color sets {} deleted for: {}".format( color_sets, shapes))
def addSetCB(self, args) : result = cmds.promptDialog(title='Add Color Set', message='Enter Set Name:', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if result == 'OK' : sname = cmds.promptDialog(q=True, text=True) cmds.select(self.objectSet) cmds.polyColorSet(cr=True, cs=sname) self.refreshColorSets()
def refreshColorSets(self) : cmds.select(self.objectSet) mesh = cmds.ls(sl=True) cmds.textScrollList(self.window+'SetList', e=True, removeAll=True) if len(mesh) == 0 : return csets = cmds.polyColorSet(q=True, allColorSets=True) if not csets : return csets = set(csets) csetstr =' '.join(csets) import mtoa ver = mtoa.Version from distutils.version import StrictVersion for m in mesh : cmds.setAttr(m+'.aiExportColors', 1) if StrictVersion(ver) > StrictVersion('1.22.4') : cmds.setAttr(m+'.aiExportColorsAsVectors', csetstr, type='string') cursets = cmds.polyColorSet(m, q=True, allColorSets=True) for c in csets : if c not in cursets : cmds.polyColorSet(m, c=True, clamped=True, colorSet=c) cmds.textScrollList(self.window+'SetList', e=True, removeAll=True) csetlist = list(csets) csetlist.sort() cmds.textScrollList(self.window+'SetList', e=True, append=csetlist)
def create_color_set(shapes, color_sets, delete_history=True): """ Create a color set on shapes (with cmds) with (0, 0, 0, 0) as default color Note: SLOW, use create_color_set_api instead Args: shapes (unicode, list): shapes to create color set in color_sets (unicode, list): color sets to create in shapes delete_history (bool): If createColorSet history should be deleted """ shapes = clib.u_enlist(shapes) color_sets = clib.u_enlist(color_sets) selection = cmds.ls(sl=True) for shape in shapes: cmds.select(shape, r=True) shape_color_sets = cmds.polyColorSet( shape, query=True, allColorSets=True) or [] for color_set in color_sets: if color_set not in shape_color_sets: cmds.polyColorSet(shape, cs=color_set, representation="RGBA", create=True) cmds.polyColorPerVertex(rgb=(0.0, 0.0, 0.0), a=0.0) # needs the object selected cmds.select(selection, r=True) if delete_history: delete_color_set_history(shapes)
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)
def _CopyColorSetToMeshAsDisplayColor(self, srcMesh, colorSetName, dstMesh): """ Copies a color set named colorSetName from the MFnMesh srcMesh to the MFnMesh dstMesh. All existing color sets on dstMesh will be removed. """ testUsdExportColorSets._ClearColorSets(dstMesh) colorSetData = OpenMaya.MColorArray() unsetColor = OpenMaya.MColor(-999, -999, -999, -999) srcMesh.getFaceVertexColors(colorSetData, colorSetName, unsetColor) colorRep = srcMesh.getColorRepresentation(colorSetName) colorRepString = 'RGBA' if colorRep == OpenMaya.MFnMesh.kAlpha: colorRepString = 'A' elif colorRep == OpenMaya.MFnMesh.kRGB: colorRepString = 'RGB' isClamped = srcMesh.isColorClamped(colorSetName) cmds.polyColorSet(dstMesh.name(), create=True, colorSet='displayColor', representation=colorRepString, clamped=isClamped) dstMesh.setCurrentColorSetName('displayColor') # XXX: The Maya setFaceVertexColor() API seems to somehow still author # faceVertex colors we don't want it to, so after setting the ones we # intend, we also remove the ones we don't. removeFaces = OpenMaya.MIntArray() removeVertices = OpenMaya.MIntArray() itMeshFV = OpenMaya.MItMeshFaceVertex(srcMesh.object()) itMeshFV.reset() while not itMeshFV.isDone(): faceId = itMeshFV.faceId() vertId = itMeshFV.vertId() faceVertId = itMeshFV.faceVertId() next(itMeshFV) colorIndexPtr = OpenMaya.intPtr() srcMesh.getFaceVertexColorIndex(faceId, faceVertId, colorIndexPtr, colorSetName) colorSetValue = colorSetData[colorIndexPtr.value()] if colorSetValue == unsetColor: removeFaces.append(faceId) removeVertices.append(vertId) continue dstMesh.setFaceVertexColor(colorSetValue, faceId, vertId, None, colorRep) if removeFaces.length() > 0 and removeVertices.length() > 0: dstMesh.removeFaceVertexColors(removeFaces, removeVertices)
def delete_colorsets(self, nodes=None): if nodes: for node in nodes: colorsets = cmds.polyColorSet(node, query=True, acs=True) if colorsets: for cset in colorsets: cmds.polyColorSet(node, d=True, cs=cset) else: cmds.polyColorSet(d=True, acs=True)
def color_set(): '''顶点着色 ''' _color_set = [] _dags = cmds.ls(dag=1) if _dags: for _dag in _dags: if cmds.polyColorSet(_dag, q=1, acs=1): cmds.polyColorSet(_dag, e=1, d=1)
def removeSetCB(self, args) : self.saveSelection() selected = cmds.textScrollList(self.window+'SetList', q=True, selectItem=True) if not selected : return cmds.select(self.objectSet) cmds.polyColorSet(e=True, delete=True, cs=selected[0]) self.refreshColorSets() self.revertSelection()
def _CopyColorSetToMeshAsDisplayColor(self, srcMesh, colorSetName, dstMesh): """ Copies a color set named colorSetName from the MFnMesh srcMesh to the MFnMesh dstMesh. All existing color sets on dstMesh will be removed. """ testUsdExportColorSets._ClearColorSets(dstMesh) colorSetData = OpenMaya.MColorArray() unsetColor = OpenMaya.MColor(-999, -999, -999, -999) srcMesh.getFaceVertexColors(colorSetData, colorSetName, unsetColor) colorRep = srcMesh.getColorRepresentation(colorSetName) colorRepString = 'RGBA' if colorRep == OpenMaya.MFnMesh.kAlpha: colorRepString = 'A' elif colorRep == OpenMaya.MFnMesh.kRGB: colorRepString = 'RGB' isClamped = srcMesh.isColorClamped(colorSetName) cmds.polyColorSet(dstMesh.name(), create=True, colorSet='displayColor', representation=colorRepString, clamped=isClamped) dstMesh.setCurrentColorSetName('displayColor') # XXX: The Maya setFaceVertexColor() API seems to somehow still author # faceVertex colors we don't want it to, so after setting the ones we # intend, we also remove the ones we don't. removeFaces = OpenMaya.MIntArray() removeVertices = OpenMaya.MIntArray() itMeshFV = OpenMaya.MItMeshFaceVertex(srcMesh.object()) itMeshFV.reset() while not itMeshFV.isDone(): faceId = itMeshFV.faceId() vertId = itMeshFV.vertId() faceVertId = itMeshFV.faceVertId() itMeshFV.next() colorIndexPtr = OpenMaya.intPtr() srcMesh.getFaceVertexColorIndex(faceId, faceVertId, colorIndexPtr, colorSetName) colorSetValue = colorSetData[colorIndexPtr.value()] if colorSetValue == unsetColor: removeFaces.append(faceId) removeVertices.append(vertId) continue dstMesh.setFaceVertexColor(colorSetValue, faceId, vertId, None, colorRep) if removeFaces.length() > 0 and removeVertices.length() > 0: dstMesh.removeFaceVertexColors(removeFaces, removeVertices)
def removeRandomColor(*args): ''' Apply Random definition ''' for shape in cmds.ls(typ='mesh', l=True): if cmds.polyColorSet(shape, allColorSets=True, q=True): cmds.polyColorSet(shape,delete=True) else: pass
def paintKeyClicked(widget, key=True): """ Inserts or removes a keyframe on the vertex colors of a shape Args: widget (PaintWidget): PaintWidget object calling the function key (bool): Key or remove key """ # get vertices to key mel.eval("ConvertSelectionToVertices;") selectedVertices = cmds.ls(sl=True, et="float3") if selectedVertices: c = ["ColorR", "ColorG", "ColorB", "Alpha"] # get shape, channels and colorset shapes = lib.getShapes(selectedVertices) channels = widget.fx.channels colorSet = widget.fx.controlSet cmds.polyColorSet(shapes, currentColorSet=True, cs=colorSet) # sets the current color set of shapes # get suffix of attribute to key channelIdx = math.trunc(paintIndex(widget) / 2.0) suffix = "" for idx in xrange(len(channels[channelIdx])): if channels[channelIdx][idx]: suffix = c[idx] break # vertex colors in maya are stored per adjacent face, to minimize the amount # of animation curves, we can find exactly which vtx face and attribute to key # in the specified vertex color set, and its respective polyColorPerVertex node vtxFaces = [vtx.replace("vtx", "vtxFace") for vtx in selectedVertices] vtxFaceAttrs = cmds.listAttr( vtxFaces, s=True) # list attributes of adjacent faces attributes = [ attr for attr in vtxFaceAttrs if "vertexFace{0}".format(suffix) in attr ] pColorVertexNodes = polyColorPerVertexNodes(shapes, colorSet) if pColorVertexNodes: for attr in attributes: if key: # key vertex color attribute cmds.setKeyframe("{0}.{1}".format(pColorVertexNodes[0], attr)) else: # remove the vertex color key currentTime = cmds.currentTime(query=True) cmds.cutKey("{0}.{1}".format(pColorVertexNodes[0], attr), time=(currentTime, currentTime)) else: cmds.error( "History has been deleted from the mesh object, keying of vertex colors is impossible" ) showKeyedTimeline(widget)
def checkerRoutineFunctions(self, SelectedShapes): self.checkCheckerTextureRepeat() cmds.select(SelectedShapes) self.btnRemCheck.setEnabled(True) self.gboxCheckRes.setEnabled(True) #delete colorsets for i in range(len(SelectedShapes)): CurrentColorSet = cmds.polyColorSet(SelectedShapes[i], q=True, currentColorSet=True) if CurrentColorSet != None: cmds.polyColorSet (SelectedShapes[i], delete=True )
def checkColorSet(self): allColorSetList = self.targetObjMesh.getColorSetNames() # tmpColorSetがすでに存在するかチェックしてなければ生成 if self.baseColorSerRep == "RGB" or self.baseColorSerRep == "RGBA": if not "tmpColorSet_R" in allColorSetList: mc.polyColorSet(create=True, colorSet="tmpColorSet_R", clamped=True, representation="RGB") if not "tmpColorSet_G" in allColorSetList: mc.polyColorSet(create=True, colorSet="tmpColorSet_G", clamped=True, representation="RGB") if not "tmpColorSet_B" in allColorSetList: mc.polyColorSet(create=True, colorSet="tmpColorSet_B", clamped=True, representation="RGB") if self.baseColorSerRep == "RGBA" or self.baseColorSerRep == "A": if not "tmpColorSet_A" in allColorSetList: mc.polyColorSet(create=True, colorSet="tmpColorSet_A", clamped=True, representation="RGB")
def importVertexColors(path): """ Import vertex colors from a json file at path Args: path: path of json file with vertex color information """ # initialize variables namespace = "" namespacePrompt = False # load json file with open(path, 'r') as f: shapeDict = json.load(f) # assign vertex color parameters on each shape for shape in shapeDict: print("Importing parameters to {0}".format(shape)) shapeName = "{0}".format(shape) if namespace: shapeName = "{0}:{1}".format(namespace, shapeName) # check for namespaces if not cmds.objExists(shape) and not namespacePrompt: result = cmds.promptDialog(title='Possible namespace issues', message='Some shapes where not found in the scene. Could they be under a different namespace?', button=['Change namespace', 'No'], defaultButton='Change namespace', cancelButton='No', dismissString='No') if result == 'Change namespace': namespace = cmds.promptDialog(query=True, text=True) shapeName = "{0}:{1}".format(namespace, shapeName) namespacePrompt = True if cmds.objExists(shapeName): oShape = getMObject(shapeName) # grabs the MObject of the shape fnMesh = om.MFnMesh(oShape) # access mesh data (oShape can also be replaced by MDagPath) colorSets = cmds.polyColorSet(shapeName, query=True, allColorSets=True) for colorSet in shapeDict[shape]: if colorSet not in colorSets: cmds.polyColorSet(shapeName, newColorSet=colorSet) oVertexColorArray = fnMesh.getVertexColors(colorSet) # MColorArray vertexListLength = len(oVertexColorArray) vertexIndexArray = list(xrange(vertexListLength)) vertexIndex = 0 for vertexColor in shapeDict[shape][colorSet]: oVertexColorArray[vertexIndex] = vertexColor vertexIndex += 1 fnMesh.setCurrentColorSetName(colorSet) fnMesh.setVertexColors(oVertexColorArray, vertexIndexArray) else: logger.debug("No {0} shape exists in the scene".format(shapeName)) printInfo("Vertex colors successfully exported from {0}".format(os.path.basename(path)))
def import_abcgeom(self): # import alembic alembic_node = cmds.AbcImport(self.asset_path, mode="import", recreateAllColorSets=True) trans_node = cmds.listConnections(alembic_node, type="mesh")[0] mesh_node = cmds.listRelatives(trans_node, type="mesh")[0] # need test if all color sets can be imported from aiUserDataColor cmds.setAttr('{}.allColorSets'.format(alembic_node), 1) current_color = cmds.polyColorSet(trans_node, query=True, currentColorSet=True)[0] # need to test: allColorSet=True # create shader surface_name = '{}_geom'.format(trans_node) # create surface shader surface_name = core.createArnoldNode('aiStandardSurface', name=surface_name) cmds.sets(trans_node, edit=True, forceElement='{}SG'.format(surface_name)) # import color if self.import_color: cmds.setAttr('{trans}|{mesh}.aiExportColors'.format(trans=trans_node, mesh=mesh_node), 1) color_name = '{0}_{1}'.format(surface_name, current_color) # import particle color color_name = core.createArnoldNode('aiUserDataColor', name=color_name) cmds.setAttr('{}.colorAttrName'.format(color_name), current_color, type='string') if self.color_channel == 'baseColor': cmds.connectAttr('{}.outColor'.format(color_name), '{}.baseColor'.format(surface_name)) elif self.color_channel == 'emitColor': cmds.connectAttr('{}.outColor'.format(color_name), '{}.emissionColor'.format(surface_name)) cmds.setAttr('{}.emission'.format(surface_name), 1) # set opacity if self.import_opacity: cmds.setAttr('{trans}|{mesh}.aiOpaque'.format(trans=trans_node, mesh=mesh_node), 0)
def create_colour_set(mesh, name, colours): """ :param str mesh: :param str name: :param list colours: """ dag = api.conversion.get_dag(mesh) dag.extendToShape() mesh_fn = OpenMaya.MFnMesh(dag) vertices = range(mesh_fn.numVertices) cmds.polyColorSet(mesh, create=True, colorSet=name, clamped=True, representation="RGB") mesh_fn.setVertexColors(colours, vertices)
def main(self, *args): ''' This method will be the main function of the tool letting the user generate random values for the color set 2. ''' selected_obj = cmds.ls(selection=True) #Warning message for no selection if not selected_obj: cmds.confirmDialog( title="Error Message", message="No objects selected. Must select one object!", button="Accept" ) return False color_sets = cmds.polyColorSet(query=True, allColorSets=True) #Warning message for no current color sets if not color_sets: cmds.confirmDialog( title="Error Message", message="Must create color set two!", button="Accept" ) return False #If statement generates random values based on the users input for Minimum and Maximum sliders if "colorSet2" in color_sets: for index in xrange(cmds.polyEvaluate(selected_obj[0], vertex=True)): #slider values min_value = cmds.intSliderGrp("minimum", query=True, value=True) max_value = cmds.intSliderGrp("maximum", query=True, value=True) generate_value = rand.randint(min_value, max_value) color_value = generate_value/100.00 color_set = cmds.polyColorPerVertex( "{object}.vtx[{number}]".format(object=selected_obj[0], number=index), rgb=( color_value, color_value, color_value) ) #Error Message if colorSet2 does not exist else: cmds.confirmDialog( title="Error Message", message="Must create color set two!", button="Accept" ) return False
def removeFromSelection(value, *args): sel = cmds.ls(sl=True, l=True) if len(sel) < 1: cmds.warning('Nothing is selected.') else: for s in sel: if value == 'diffuse_color': if cmds.attributeQuery("rmanCdiffuse_color", n=s, exists=True) == 1: cmds.deleteAttr(s, at='rmanCdiffuse_color') if cmds.polyColorSet(s, allColorSets=True, q=True): cmds.polyColorSet(s, delete=True) else: if cmds.attributeQuery("rmanF" + value, n=s, exists=True) == 1: cmds.deleteAttr(s, at="rmanF" + value)
def btnCleanCheckClicked(self): SelectionData = gen_func.checkSelection() #shapes array selectedShapes = SelectionData[0] current_languge = cfgl.configLoader()[14] if len(selectedShapes) > 0: try: for i in range(len(selectedShapes)): CurrentColorSet = cmds.polyColorSet(selectedShapes[i], q=True, currentColorSet=True) if CurrentColorSet != None: cmds.polyColorSet (selectedShapes[i], delete=True ) print gen_func.shortNamer(selectedShapes[i]), "was cleaned." self.showInfo("info", "Check Texel Density results have been cleared!") self.lblInRangeInfo.setText("Previous check results have been cleared!") self.btnSelectTinyUVShell.setText("Not checked yet") self.btnSelectTinyFace.setText("Not checked yet") self.btnSelectTinyFace.setDisabled(True) self.btnSelectTinyUVShell.setDisabled(True) self.tiny_uv_arr=[] self.tiny_geo_arr=[] self.pbChekProgress.setValue(0) cmds.select( selectedShapes ) conclusion_text = conclusion.CleanCheckClicked(current_languge, True) self.txtbrowTexConclusion.setHtml(conclusion_text) except: self.showInfo("warn", "There is nothing to clean! Try to clean after checking.") conclusion_text = conclusion.CleanCheckClicked(current_languge, False) self.txtbrowTexConclusion.setHtml(conclusion_text) else: self.showInfo("warn", "Can't clean check texel density results. Please select already checked mesh object in Object Mode.") conclusion_text = conclusion.noSelection(current_languge, "clean_check") self.txtbrowTexConclusion.setHtml(conclusion_text)
def paint(RGBA, paintType, cClamp=["both", 0, 1], aClamp=["none", 0, 1], colorSet="controlSetA"): """ Set artisan context with painting and brush parameters for artAttrPaintVertexCtx Args: RGBA (list): Channels to paint e.g. [ 0, 1, 0, 0 ] paintType (str): "additive" or "subtract" cClamp (list): Clamping settings for color [clamp, clamplower, clampupper] aClamp (list): Clamping settings for alpha [clamp, clamplower, clampupper] colorSet (str): Color set to paint into """ # SET UP ARTISAN CONTEXT # set channels to RGBA and enable paint tool attributes cmds.radioButtonGrp('artAttrColorChannelChoices', sl=2, e=True) # set to RGBA in artisan UI cmds.artAttrPaintVertexCtx('artAttrColorPerVertexContext', paintRGBA=True, e=True) # set to RGBA cmds.floatSliderGrp('colorPerVertexAlpha', en=True, e=True) # enable alpha painting cmds.floatFieldGrp('colorPerVertexMinMaxAlphaValue', en=True, e=True) # enable alpha min max cmds.checkBoxGrp('artAttrAlphaClampChkBox', en=True, e=True) # enable alpha clamp checkbox # before stroke command cmds.artAttrPaintVertexCtx('artAttrColorPerVertexContext', bsc="artAttrPaintVertexCtx -edit -showactive 0 artAttrColorPerVertexContext", e=True) # after stroke command cmds.artAttrPaintVertexCtx('artAttrColorPerVertexContext', asc="artAttrPaintVertexCtx -edit -showactive 1 artAttrColorPerVertexContext", e=True) # PREPARE MESHES selected = cmds.ls(sl=True) shapes = lib.getShapes(selected) enableVtxCtrl(shapes) # SET UP PAINTING PARAMETERS cmds.polyColorSet(shapes, currentColorSet=True, cs=colorSet) # sets the current color set of all shapes cmds.artAttrPaintVertexCtx('artAttrColorPerVertexContext', selectedattroper=paintType, e=True) # add or substract color cmds.artAttrPaintVertexCtx('artAttrColorPerVertexContext', cl4=RGBA, e=True) # define channels to paint cmds.floatSliderGrp('colorPerVertexAlpha', value=RGBA[3], e=True) # set alpha painting value cmds.artAttrPaintVertexCtx('artAttrColorPerVertexContext', opacity=0.2, e=True) # set opacity to 0.2 cmds.artAttrPaintVertexCtx('artAttrColorPerVertexContext', accopacity=True, e=True) # oppacity accumulates cmds.artAttrPaintVertexCtx('artAttrColorPerVertexContext', clamp=cClamp[0], e=True) # color clamp cmds.artAttrPaintVertexCtx('artAttrColorPerVertexContext', clamplower=cClamp[1], e=True) # lower clamp cmds.artAttrPaintVertexCtx('artAttrColorPerVertexContext', clampupper=cClamp[2], e=True) # upper clamp cmds.artAttrPaintVertexCtx('artAttrColorPerVertexContext', alphaclamp=aClamp[0], e=True) # alpha clamp cmds.artAttrPaintVertexCtx('artAttrColorPerVertexContext', alphaclamplower=aClamp[1], e=True) # alpha lower clamp cmds.artAttrPaintVertexCtx('artAttrColorPerVertexContext', alphaclampupper=aClamp[2], e=True) #alpha upper clamp
def tagMesh(meshDagPath): """Tag the points on the supplied mesh with vertex colors to store Maya's point order""" # clear any extant vertex colors try: cmds.polyColorSet(meshDagPath.partialPathName(), e=True, delete=True, acs=True) except: pass # encode each point index in the red and green channels of each point's color value meshFn = om.MFnMesh(meshDagPath) vertexCount = om.MIntArray() vertexList = om.MIntArray() meshFn.getVertices(vertexCount, vertexList) vertexColors = om.MColorArray(meshFn.numVertices(), om.MColor(0.0,0.0,1.0,1.0)) for i in xrange(meshFn.numVertices()): col = om.MColor(tagIndexToColor(i)) vertexColors[i].r = col.r vertexColors[i].g = col.g meshFn.createColorSetWithName('blendShapeIndexMap') meshFn.setColors(vertexColors, 'blendShapeIndexMap') meshFn.assignColors(vertexList)
def exportVertexColors(objs, path): """ Exports vertex colors of objs to a json file at path Args: objs: objects to export from path: path to save json file to """ # initialize variables namespace = False namespacePrompt = False # get shapes, its control sets and colors shapeDict = {} shapes = getShapes(objs) for shape in shapes: print("Extracting vertex colors from {0}".format(shape)) shapeName = "{0}".format(shape) # check for namespaces namespacePos = shape.rfind(":") namespaceQuery = namespacePos > 0 if not namespacePrompt and namespaceQuery: # ask if shapes should be exported with namespaces result = cmds.confirmDialog(title="Wait a second...", icon = "question", message = "Would you like to export vertex colors with namespace?", button=['Yes', 'No'], defaultButton='No', cancelButton='No', dismissString='No', ma='center') if result == "Yes": namespace = True namespacePrompt = True # change shape name accordingly if not namespace: if namespaceQuery: shapeName = shape[namespacePos+1:] # get data colorSetDict = {} oShape = getMObject(shape) # grabs the MObject of the shape fnMesh = om.MFnMesh(oShape) # access mesh data (oShape can also be replaced by MDagPath) colorSets = cmds.polyColorSet(shape, query=True, allColorSets=True) if colorSets: for colorSet in colorSets: oVertexColorArray = fnMesh.getVertexColors(colorSet) # MColorArray colorSetDict[colorSet] = [vtxColor.getColor() for vtxColor in oVertexColorArray] shapeDict[shapeName] = colorSetDict # write and save json info with open(path, 'w') as f: json.dump(shapeDict, f, separators=(',', ':'), indent=2) printInfo("Vertex colors successfully exported")
def setColorset(): """Make sure the mesh has the right colorset enabled""" # Try to switch to the crease colorset. If we can't, make one. try: cmds.polyColorSet(currentColorSet=True, colorSet=CREASE_COLORSET) except RuntimeError: cmds.polyColorSet(create=True, colorSet=CREASE_COLORSET) cmds.polyColorSet(currentColorSet=True, colorSet=CREASE_COLORSET) """TODO: Also apply the colorset to the shader if not already. E.g.:
def color_set(): '''顶点着色 ''' _color_set = [] _dags = cmds.ls(dag=1) if not _dags: return True, None for _dag in _dags: _set = cmds.polyColorSet(_dag, q=1, acs=1) if _set: _color_set.extend(_set) if _color_set: info = "场景存在顶点着色\n{}".format("\n".join(_color_set)) return False, info else: return True, None
def test_execute_from_mesh(self): """ Execute the transfer from a provided mesh and validate the name and colour sets on the created target mesh. """ t = transfer.Transfer("source_MESH", "target_MESH") t.set_create_colour_sets(True) self.assertTrue(t.is_valid()) mesh = t.execute_from_mesh("jawOpen_MESH", name="jawOpen") mesh_colour_sets = cmds.polyColorSet( mesh, query=True, allColorSets=True) or [] self.assertEqual(mesh, "jawOpen") self.assertIn("deformed", mesh_colour_sets) self.assertIn("weights", mesh_colour_sets)
def closeEvent(self, event): # 他のオブジェクトを選択している可能性もあるのでそのリストを取得しておき、 # 選択をターゲットに置き換えておく selList = mc.ls(sl=True) mc.select(self.targetObj.fullPathName(), replace=True) # ウィンドウのインスタンスをdeleteすることで登録したscriptJobもまとめて解除しておく self.deleteInstances() # ノード名変更のコールバックを削除 if self.callbackID_nameChanged: om2.MNodeMessage.removeCallback(self.callbackID_nameChanged) self.callbackID_nameChanged = None # ターゲットオブジェクトの全colorSetリストを取得 allColorSetList = self.targetObjMesh.getColorSetNames() # tmpColorSetを削除する if "tmpColorSet_R" in allColorSetList: mc.polyColorSet(delete=True, colorSet="tmpColorSet_R") if "tmpColorSet_G" in allColorSetList: mc.polyColorSet(delete=True, colorSet="tmpColorSet_G") if "tmpColorSet_B" in allColorSetList: mc.polyColorSet(delete=True, colorSet="tmpColorSet_B") if "tmpColorSet_A" in allColorSetList: mc.polyColorSet(delete=True, colorSet="tmpColorSet_A") # displayColorsを元に戻しておく mc.setAttr("%s.displayColors" % self.targetObjMesh.fullPathName(), self.attrDispColor) # colorMaterialChannelとmaterialBlendを元に戻しておく mc.polyOptions(colorMaterialChannel=self.pOption_matChl, gl=False) mc.polyOptions(materialBlend=self.pOption_matBld, gl=False) # 最後にヒストリもきれいにしておく historyDelete(self.targetObj.fullPathName(), False) # 選択を戻す mc.select(selList, replace=True)
def updateColorSets(self): # Delete the current set of color sets try: menuItems = cmds.optionMenu(self.colorSetListCtrl, q=True, itemListLong=True) if menuItems != None and menuItems != []: cmds.deleteUI(menuItems) except: pass colorSets = cmds.polyColorSet( query=True, allColorSets=True) if colorSets : for c in colorSets: cmds.menuItem(parent=self.colorSetListCtrl, label=c) if cmds.checkBox(self.userWeightCheckBoxCtrl, query = True, value=True): cmds.optionMenu(self.colorSetListCtrl, edit=True, en=True) cmds.intSlider(self.wmSliderCtrl, edit=True, en=True) else: cmds.optionMenu(self.colorSetListCtrl, edit=True, en=False) cmds.intSlider(self.wmSliderCtrl, edit=True, en=False)
def checkIt(self, objs, settings=None): # type: (list) -> (list) # Reset result self.errors = [] for obj in objs: try: allColorSets = cmds.polyColorSet(obj, q=True, allColorSets=True) if allColorSets is None: continue else: err = Error(obj) self.errors.append(err) except RuntimeError: pass return self.errors
def create_color_set(self, *args): ''' This method will create the initial Color Sets that are needed. It will also check to see if color sets currently exist in the scene and if not it will create a default color set then create color set 2. ''' print "Creating Color Set" selected_obj = cmds.ls(selection=True) #Error message if the use has not selected anything if not selected_obj: cmds.confirmDialog( title="Error Message", message="No objects selected. Must select one object!", button="Accept" ) return False color_sets = cmds.polyColorSet(query=True, allColorSets=True) # Create colorSet1 if it does not exist if not color_sets: print "Creating ColorSet1" cmds.polyColorSet(create=True, rpt="RBGA", colorSet="colorSet1") # Create colorSet2 print "Creating ColorSet2" cmds.polyColorSet(create=True, rpt="RBGA", colorSet="colorSet2") cmds.polyColorSet(currentColorSet=True, colorSet= 'colorSet2' ) self.main()
def initMesh(name, stepAccuracy = 0.1): global accuracy accuracy = stepAccuracy cmds.polyColorSet(name, colorSet="meshDensitySet_#", clamped=1, rpt='RGB') cmds.polyColorPerVertex(name, r = 0.0, g = 0.0, b = 0.0)
def deform (self, dataBlock,geoIterator, matrix, geometryIndex): input = OpenMayaMPx.cvar.MPxDeformerNode_input # attach a handle to input Array Attribute # prevent recomputation dataHandleInputArray = dataBlock.outputArrayValue(input) #jump to particular element dataHandleInputArray.jumpToElement (geometryIndex) #attach a handle to specific data block dataHandleInputElement = dataHandleInputArray.outputValue() #reach to the child inputGeom = OpenMayaMPx.cvar.MPxDeformerNode_inputGeom dataHandleInputGeom = dataHandleInputElement.child (inputGeom) inMesh = dataHandleInputGeom.asMesh() #envelope envolope = OpenMayaMPx.cvar.MPxDeformerNode_envelope dataHandleEnvelope = dataBlock.inputValue(envolope) envolopeValue = dataHandleEnvelope.asFloat() #amplitude dataHandleAmplitude = dataBlock.inputValue (rippleDeformer.amplitude) amplitudeValue = dataHandleAmplitude.asFloat() #displace dataHandleDisplace = dataBlock.inputValue (rippleDeformer.displacement) displaceValue = dataHandleDisplace.asFloat() #matrix dataHandleMatrix = dataBlock.inputValue (rippleDeformer.matrix) MatrixValue = dataHandleMatrix.asMatrix() #read translation from Matrix mTransMatrix = OpenMaya.MTransformationMatrix(MatrixValue) translationValue = mTransMatrix.getTranslation(OpenMaya.MSpace.kObject) #mEulerRot = OpenMaya.MVector() #mEulerRot = mTransMatrix.eulerRotation().asVector() mFloatVectorArray_Normal = OpenMaya.MFloatVectorArray() inMeshMfn = OpenMaya.MFnMesh (inMesh) inMeshMfn.getVertexNormals(False,mFloatVectorArray_Normal,OpenMaya.MSpace.kObject) #create colorSet inMeshMfn.createColorSetDataMesh('vertexColorSet') inMeshMfn.setIsColorClamped('vertexColorSet',True) mPointArray_meshVert = OpenMaya.MPointArray() mColorArray_meshVert = OpenMaya.MColorArray() mVertexArray_meshVert = OpenMaya.MIntArray() while (not geoIterator.isDone()): pointPosition = geoIterator.position() weight=self.weightValue(dataBlock,geometryIndex,geoIterator.index()) #inMeshMfn.setVertexColor(pointColor, geoIterator.index(),None,OpenMaya.MFnMesh.kRGBA) pointPosition.x= pointPosition.x + math.sin (geoIterator.index() + displaceValue + translationValue[0] ) * amplitudeValue * envolopeValue * mFloatVectorArray_Normal[geoIterator.index()].x*weight pointPosition.y= pointPosition.y + math.sin (geoIterator.index() + displaceValue + translationValue[0] ) * amplitudeValue * envolopeValue * mFloatVectorArray_Normal[geoIterator.index()].y*weight pointPosition.z= pointPosition.z + math.sin (geoIterator.index() + displaceValue + translationValue[0] ) * amplitudeValue * envolopeValue * mFloatVectorArray_Normal[geoIterator.index()].z*weight mPointArray_meshVert.append(pointPosition) #paint vertex color Color_R = math.sin (geoIterator.index() + displaceValue) * amplitudeValue Color_G = math.cos (geoIterator.index()+ displaceValue) * amplitudeValue Color_B = math.sin (geoIterator.index()- displaceValue) * amplitudeValue pointColor=OpenMaya.MColor (Color_R, Color_G, Color_B, 1.0) mColorArray_meshVert.append(pointColor) mVertexArray_meshVert.append (geoIterator.index()) geoIterator.next() #optimize performance geoIterator.setAllPositions(mPointArray_meshVert) inMeshMfn.setVertexColors(mColorArray_meshVert,mVertexArray_meshVert,None,OpenMaya.MFnMesh.kRGBA) #set current colorset #inMeshMfn.setCurrentColorSetDataMesh('vertexColorSet') if (not cmds.polyColorSet(ccs=True, q=True)=='vertexColorSet'): cmds.polyColorSet (ccs=True, cs='vertexColorSet')
def writeAscii(fileHandle, itDag): try: dom = minidom.Document() meshElement = dom.createElement("Mesh") dom.appendChild(meshElement) ### DEFAULT_COLOR= (1.0, 1.0, 1.0, 1.0) DEFAULT_UV= (0,0) vertexDict= {} # {[idPoint, idNormal, idColor, idUV0, idUV1,], } pointsDict= {} # {(float, float, float, float): id} normalsDict= {} # {(float, float, float): id} tangentsDict= {} # {(float, float, float): id} binormalsDict= {} # {(float, float, float): id} colorsDict= {DEFAULT_COLOR: 0} # {(r, g, b, a): id} uvCoordsDict= {DEFAULT_UV: 0} # {(r, g, b, a): id} faceList = [] objectFaces = [] # [ [faceID1, faceID2], [], ] colorSetNames = cmds.polyColorSet( query=True, allColorSets=True ) #export objects numExportedObjects = 0 while not itDag.isDone(): dagPath = getDagPath(itDag) dagFn = OpenMaya.MFnDagNode(dagPath) mesh = OpenMaya.MFnMesh(dagPath) print ">> writing: %s ..." % dagPath.fullPathName() ### collect face defintions ### itPolygon = OpenMaya.MItMeshPolygon(dagPath) points = OpenMaya.MPointArray() normals = OpenMaya.MVectorArray() tangents = OpenMaya.MVectorArray() binormals = OpenMaya.MVectorArray() colors = OpenMaya.MColorArray() uList = OpenMaya.MFloatArray() vList = OpenMaya.MFloatArray() uvSetNames = [] itPolygon.getUVSetNames( uvSetNames ) facesInObject = [] while not itPolygon.isDone(): itPolygon.getPoints(points, OpenMaya.MSpace.kObject) itPolygon.getNormals(normals, OpenMaya.MSpace.kObject) if colorSetNames: itPolygon.getColors(colors, colorSetNames[0]) #print "got colors %s" % colors else: colors= None for uvSet in uvSetNames: try: itPolygon.getUVs(uList, vList, uvSet) except Exception, msg: print "failed to query uvSet '%s'" % uvSet uList = OpenMaya.MFloatArray() vList = OpenMaya.MFloatArray() #print "tangent=%s" % ([tangent.x,tangent.y,tangent.z]) # Flip z for left-handed coordinate system #tangents.append( [tangent.x, tangent.y, -(tangent.z)] ) #binormals.append( [binormal.x, binormal.y, -(binormal.z)] ) itFaceVertex.next() ### iterate over face vertices ### faceVerticeIndexes = [] i=0 #for i in range( points.length() ): itFaceVertex = OpenMaya.MItMeshFaceVertex( dagPath, itPolygon.polygon() ) while not itFaceVertex.isDone(): ### get tangents and binormals #uvSets = [] #itPolygon.getUVSetNames( uvSets ) ### get position p = points[i] tPoint= (p.x, p.y, p.z, 1.0) if pointsDict.has_key( tPoint ): pointIndex = pointsDict[tPoint] else: pointIndex = len(pointsDict) pointsDict[tPoint]= pointIndex ### get tangent t = itFaceVertex.getTangent( OpenMaya.MSpace.kObject, uvSetNames[0] ) tangent= (t.x, t.y, t.z) if tangentsDict.has_key( tangent ): tangentIndex = tangentsDict[tangent] else: tangentIndex = len(tangentsDict) tangentsDict[tangent]= tangentIndex ### get binormal b = itFaceVertex.getBinormal( OpenMaya.MSpace.kObject, uvSetNames[0] ) binormal= (b.x, b.y, b.z) if binormalsDict.has_key( binormal ): binormalIndex = binormalsDict[binormal] else: binormalIndex = len(binormalsDict) binormalsDict[binormal]= binormalIndex ### get normal n = normals[i] tNormal= (n.x, n.y, n.z) if normalsDict.has_key( tNormal ): normalIndex = normalsDict[tNormal] else: normalIndex = len(normalsDict) normalsDict[tNormal]= normalIndex ### get uvs if len(uList) > i and len(vList) > i: tUV = (float(uList[i]), float(vList[i])) if uvCoordsDict.has_key( tUV ): uvCoordIndex = uvCoordsDict[tUV] else: uvCoordIndex = len(uvCoordsDict) uvCoordsDict[tUV]= uvCoordIndex else: uvCoordIndex = 0 ### export Colors ### if not colors: tColor= DEFAULT_COLOR else: c = colors[i] #tColor= ( clamp(int(c.r * 255), 0, 255), # clamp(int(c.g * 255), 0, 255), # clamp(int(c.b * 255), 0, 255), # clamp(int(c.a * 255), 0, 255)) # Fix default colors if c.r == -1 and c.g == -1 and c.b == -1 and c.a == -1: c.r = c.g = c.b = c.a = 1.0 tColor= ( c.r, c.g, c.b, c.a) if colorsDict.has_key( tColor ): colorIndex = colorsDict[tColor] else: colorIndex = len(colorsDict) colorsDict[tColor]= colorIndex ### write vertex definition vertexDef= (pointIndex, normalIndex, colorIndex, uvCoordIndex, tangentIndex, binormalIndex) if vertexDict.has_key( vertexDef ): vertexIndex = vertexDict[vertexDef] else: vertexIndex = len(vertexDict) vertexDict[vertexDef]= vertexIndex faceVerticeIndexes.append("%s" % vertexIndex ) ### next vertex i+=1 itFaceVertex.next() facesInObject.append( len( faceList ) ) faceList.append( " ".join(faceVerticeIndexes) ) itPolygon.next() objectFaces.append( facesInObject ) numExportedObjects += 1 itDag.next() ### write vertex def list ### attributesElement= dom.createElement("Attributes") meshElement.appendChild(attributesElement) for id,listName, vtype in [ ("POSITION", "Positions", "R32G32B32A32_Float"), ("NORMAL", "Normals", "R32G32B32_Float"), ("COLOR", "Colors", "R32G32B32A32_Float"), ("TEXCOORD", "UVCoords", "R32G32_Float"), ("TANGENT", "Tangents", "R32G32B32_Float"), ("BINORMAL", "Binormals", "R32G32B32_Float"), ]: attributeElement= dom.createElement("Attribute") attributeElement.setAttribute("id", id ) attributeElement.setAttribute("type", vtype ) attributeElement.setAttribute("list", listName ) attributesElement.appendChild(attributeElement) ### write vertices ### verticesElement = dom.createElement("Vertices") meshElement.appendChild(verticesElement) t= dom.createTextNode( getDictAsList( vertexDict ) ) verticesElement.appendChild(t) ### write positions ### positionsElement = dom.createElement("Positions") meshElement.appendChild(positionsElement) t= dom.createTextNode( getDictAsList( pointsDict ) ) positionsElement.appendChild(t) ### write normals ### normalsElement = dom.createElement("Normals") meshElement.appendChild(normalsElement) t= dom.createTextNode( getDictAsList( normalsDict ) ) normalsElement.appendChild(t) ### write tangents ### tangentsElement = dom.createElement("Tangents") meshElement.appendChild(tangentsElement) t= dom.createTextNode( getDictAsList( tangentsDict ) ) tangentsElement.appendChild(t) ### write binormals ### binormalElement = dom.createElement("Binormals") meshElement.appendChild(binormalElement) t= dom.createTextNode( getDictAsList( binormalsDict ) ) binormalElement.appendChild(t) ### write colors ### colorsElement = dom.createElement("Colors") meshElement.appendChild(colorsElement) t= dom.createTextNode( getDictAsList( colorsDict ) ) colorsElement.appendChild(t) ### write UVCoords ### uvCoordsElement = dom.createElement("UVCoords") meshElement.appendChild(uvCoordsElement) t= dom.createTextNode( getDictAsList( uvCoordsDict ) ) uvCoordsElement.appendChild(t) ### write faces ### facesElement = dom.createElement("Faces") meshElement.appendChild(facesElement) t= dom.createTextNode(", \n".join( faceList )) facesElement.appendChild(t) ### write objects ### objectsElement = dom.createElement("Objects") meshElement.appendChild(objectsElement) tlist= [] for of in objectFaces: tlist.append( listToString( of ) ) t= dom.createTextNode( " ,\n".join( tlist) ) objectsElement.appendChild(t) #fileHandle.write( "<!DOCTYPE StillMesh>\n") fileHandle.write( dom.toprettyxml(indent=" ") ) return True