Category Archives: Python

Setting poly vertex colors quickly with the Maya Python API

Here's a little snippet I think I should save, and it might be useful for someone else out there too.
This is a way to set vertex colors on a mesh all at once, really quickly, using Python in Maya and the OpenMaya API

I hope the code styling shows up after it goes through my content publishing system!

import maya.OpenMaya as OpenMaya
import pymel.core as pm

sel = pm.selected()[0]
shape = sel.getShape()

mobj = shape.__apimobject__()
meshFn = OpenMaya.MFnMesh(mobj)

vertexColorList = OpenMaya.MColorArray()
normalsList = OpenMaya.MFloatVectorArray()

meshFn.getVertexColors(vertexColorList)
meshFn.getNormals(normalsList)

lenVertexList = vertexColorList.length()

fnComponent = OpenMaya.MFnSingleIndexedComponent()
fullComponent = fnComponent.create( OpenMaya.MFn.kMeshVertComponent )

fnComponent.setCompleteData( lenVertexList );

vertexIndexList = OpenMaya.MIntArray()
fnComponent.getElements(vertexIndexList)

for k in range(lenVertexList):
    vertexColorList[k].r = normalsList[k].x
    vertexColorList[k].g = normalsList[k].y
    vertexColorList[k].b = normalsList[k].z

meshFn.setVertexColors(vertexColorList,vertexIndexList, None)
Tagged