Manipulate vertex color of fluid mesh with python

I’m pretty new to Python programming and to the Blender API so this might be a stupid question.

I want to set the vertex color of the vertices of a fluid simulated mesh in Blender 2.90. The goal is to have the vertex color set to the velocity of the nearest fluid particle. I already managed to get the velocity of the nearest particle at any point in space. The problem is, I can’t get access to the fluid mesh vertex colors.

With the following code:

domain = bpy.data.objects["Domain"]
mesh = domain.data
color = (0.0, 1.0, 1.0, 0.0)
for poly in mesh.polygons:
    for idx in poly.loop_indices:
        mesh.vertex_colors[0].data[idx].color = color

I can set the vertex color of the original domain object (visible in edit mode).
I tried various combinations with .evaluated_get() and .to_mesh() but couldn’t get it to manipulate the modified mesh.

For example:

domain = bpy.data.objects["Domain"]
depg = bpy.context.evaluated_depsgraph_get()
mesh = domain.evaluated_get(depg).data
color = (0.0, 1.0, 1.0, 0.0)
for poly in mesh.polygons:
    for idx in poly.loop_indices:
        mesh.vertex_colors[0].data[idx].color = color

with this code, there exists no vertex_colors (‘bpy_prop_collection[key]: key 0 not found’)

But I couldn’t get it to manipulate the vertex color after the FluidSim modifier (therefore the domain has the set color in edit mode but the fluid mesh stays black)

Can anyone help me with this?

I found the solution:

Apaprently “applying” the fluid sim modifier (either in the UI or by .evaluated_get()) the vertex colors get removed. This makes kind of sense, because the original vertices get completely replaced. So the solution is to create new vertex_colors after the .evaluated_get():

domain = bpy.data.objects["Domain"]
depg = bpy.context.evaluated_depsgraph_get()
mesh = domain.evaluated_get(depg).data
vert_colors = mesh.vertex_colors.new(name="start_pos")
for poly in mesh.polygons:
    for idx in poly.loop_indices:
        vert_colors.data[idx].color = (1.0, 0.5, 0.0, 1.0)
2 Likes