Skip to content

Instantly share code, notes, and snippets.

@tamask
Created January 29, 2019 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamask/0169d7ef0d5ac820c2a548912e61fc7f to your computer and use it in GitHub Desktop.
Save tamask/0169d7ef0d5ac820c2a548912e61fc7f to your computer and use it in GitHub Desktop.
Simple tool for packing colors into UV maps
'''
Simple tool for packing colors into UV maps
'''
import bpy
import math
import mathutils
def v2_to_float(v2, precision=4096):
'''Pack two 0-1 float values into a single float'''
p = precision - 1
x, y = v2
x = math.floor(x * p)
y = math.floor(y * p)
f = (x * precision) + y
return f
def float_to_v2(f, precision=4096):
'''Unpack two 0-1 float values from a single float'''
p = precision - 1
x = math.floor(f / precision) / p
y = (f % precision) / p
return x, y
def pack_rgba(obj, uvmap_name, color_name, alpha_name=None, precision=4096):
uvmap = obj.data.uv_layers[uvmap_name].data
color = obj.data.vertex_colors[color_name].data
if alpha_name is None:
for loop_index, uv_loop in enumerate(uvmap):
r, g, b, a = color[loop_index].color
uv_loop.uv.x = v2_to_float((r, g), precision=precision)
uv_loop.uv.y = v2_to_float((b, a), precision=precision)
else:
alpha = obj.data.vertex_colors[alpha_name].data
for loop_index, uv_loop in enumerate(uvmap):
r, g, b, a = color[loop_index].color
a = mathutils.Color((alpha[loop_index].color[:3])).v
print(a)
uv_loop.uv.x = v2_to_float((r, g), precision=precision)
uv_loop.uv.y = v2_to_float((b, a), precision=precision)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment