Custom vertex data to shader

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Ducku

I’m using ArrayMesh to generate a mesh, but now I would like to pass some custom data only available while generating the mesh into a custom shader. ArrayMesh only provides the default position, color, uv, etc. But i would like to pass something other than these values into the shader (namely a single int). From my OpenGL experience, I recall you could basically dump whatever data you need into an AttribArray and send it to the shader pipeline. Is anything like this possible within godot?

1 Like
:bust_in_silhouette: Reply From: Helgrind

Uniforms are what you’re looking for.
You can then access your parameters through code with set_shader_param().

Sadly uniforms are an identical value per material instance. What I need is a way to pass custom vertex specific data to the shader, like the position, normal or UV.

Ducku | 2020-11-08 17:57

One kludgey option is to encode one or more small integers into the lower bits of one or more vertex colors. Alpha is usually the best choice because it typically doesn’t need fine granularity at all. Red and blue are the second best because the human eye notices subtle shifts in green more than any the other two primary colors.

For example, to encode a 4-bit integer i (0-15) into the alpha channel of a color (effectively making alpha 4-bit instead of 8-bit):

color.a8 = (color.a8 & 0xF0) | i

And to decode it in the shader:

void vertex() {
  int i = int(COLOR.a * 255.0) & 0x0F;  // extract 'i'
  COLOR.a /= (240.0/255.0);  // normalize 'a' to be 0..1 (effectively 'a = (a/0xF0)*0xFF')
}