1
$\begingroup$

I got a model in -1 to 1 space and I want to encode each vertex position into the the vertex color for future use. There seems to be nothing by default to do that so I will have to use a custom script for that. I have never used scripting in Blender so I am a bit lost on how to access its data etc. and could use some help.

The pseudo code would be something like this:

foreach vertex in mesh.vertices
    vertex.color = (vertex.pos * 0.5) + 1
$\endgroup$
  • 1
    $\begingroup$ Depending on your purpose, you could just use Cycles UV coordinates fed directly into a shader $\endgroup$ – Duarte Farrajota Ramos Mar 28 '18 at 0:34
  • $\begingroup$ @DuarteFarrajotaRamos i need it for exporting so i have to bake it into the vertex colors. i also tried to bake a blender render material into vertex colors but while it looks fine in material mode it is wrong after baking $\endgroup$ – HellGate Mar 28 '18 at 13:00
1
$\begingroup$

After quickly scraping together some knowledge about Python and Blender I managed to create a very basic script to do what I want (looks horrible but does its job).

import bpy
from mathutils import Color, Vector

my_object = bpy.context.active_object.data
vert_list = my_object.vertices
color_map = my_object.vertex_colors.new()

i = 0
for poly in my_object.polygons:
    for idx in poly.loop_indices:
        loop = my_object.loops[idx]
        v = loop.vertex_index
        x = (vert_list[v].co.x + 1) / 2
        y = (vert_list[v].co.y + 1) / 2
        z = (vert_list[v].co.z + 1) / 2

        color_map.data[i].color = Color((x, y, z))
        i += 1
| improve this answer | |
$\endgroup$
1
$\begingroup$

I updated the script to work in 2.8.


import bpy
from mathutils import Color, Vector

my_object = bpy.context.active_object.data
vert_list = my_object.vertices
color_map_collection = my_object.vertex_colors

if len(color_map_collection) == 0:
    color_map_collection.new()

color_map = color_map_collection['Col']


i = 0
for poly in my_object.polygons:
    for idx in poly.loop_indices:
        loop = my_object.loops[idx]
        v = loop.vertex_index
        x = (vert_list[v].co.x + 1) / 2
        y = (vert_list[v].co.y + 1) / 2
        z = (vert_list[v].co.z + 1) / 2
        t = 0
        final = (x,y,z,t)
        color_map.data[i].color = final
        i += 1


# set to vertex paint mode to see the result
bpy.ops.object.mode_set(mode='VERTEX_PAINT')

part of the solution was from https://blenderscripting.blogspot.com/2013/03/vertex-color-map.html

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.