Question

Is it possible to set the color of a single vertex using a GLSL vertex shader program, in the same way that gl_Position changes the position of a vertex ?

Was it helpful?

Solution

For versions of GLSL prior version 1.30, you want to write to the gl_FrontColor or gl_BackColor built-ins, which are varyings accessible in the vertex shader. Read about varyings in the GLSL 1.10 specification (http://www.opengl.org/registry/doc/GLSLangSpec.Full.1.10.59.pdf) to learn more about them, or the GL_ARB_vertex_shader extension specification.

gl_FrontColor and gl_BackColor are 4D RGBA vectors which take normalized floating point scalars.

But this will set all the vertices to red, not just one vertex. This is because the same vertex shader is run for all the vertices. If you want to set individual colours, use glColorPointer together with glDrawArrays, glDrawElements, glDrawRangeElements or glMultiDrawElements. The vertex color set by glColorPointer can be read as gl_Color in the vertex shader. gl_Color in the vertex shader is a per-vertex attribute.

To read the color you wrote in the vertex shader, in the fragment shader, read the built-in varying gl_Color. Finished fragments should be written to gl_FragColor.

Vertex shader example:

void main()
{
    gl_FrontColor = gl_Color;
    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}

Fragment shader example:

void main()
{
    gl_FragColor = gl_Color;
}

Also, to make the vertex shader set the varyings just like the OpenGL fixed-function pipeline, call the function ftransform().

void main()
{
    ftransform();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top