Usage of Vertex Color

A triangle was drew in the previous post. We used just positions as attributes. But, we can give different attributes these vertices. I'm going to give three different colors (red, green, blue) to three vertices. 

Firstly, I changed a little bit vertex shader source code like in the below:
#version 330 core

in vec3 aPos;
in vec3 aColor;

out vec3 outColor;

void main()
{
    gl_Position = vec4(aPos, 1.0);
    outColor = aColor;
}
The fragment shader source code was changed according to the vertex shader:
#version 330 core

in vec3 outColor;

out vec4 FragColor;

void main()
{
    FragColor = vec4(outColor, 1.0f);
}
When we gave different color for each vertex, OpenGL interpolated these colors as default. It gives gradient effect from the color to another color visually. 

Let's change our float array called vertices as follows:
            float[] vertices = 
            {
                // x, y, z, r, g, b
                -0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,  
                 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 
                 0.0f,  0.5f, 0.0f, 0.0f, 0.0f, 1.0f
            };
We will add new attribute pointer for color. The important thing is to know how to use stride and offset parameters of VertexAttribPointer.
            GL.GenVertexArrays(1, out vao);
            GL.BindVertexArray(vao);
            // create vbo to store the data in opengl and copy data to vbo
            GL.GenBuffers(1, out vbo);
            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
            GL.BufferData(BufferTarget.ArrayBuffer, sizeof(float) * vertices.Length, vertices, BufferUsageHint.StaticDraw);
            // tell opengl how to use the data via attributes
            // position attribute
            int attrPosition_Position = GL.GetAttribLocation(shader.ShaderProgram, "aPos");
            GL.EnableVertexAttribArray(attrPosition_Position);
            GL.VertexAttribPointer(attrPosition_Position, 3, VertexAttribPointerType.Float, false, sizeof(float) * 6, 0);
            // color attribute
            int attrPosition_Color = GL.GetAttribLocation(shader.ShaderProgram, "aColor");
            GL.EnableVertexAttribArray(attrPosition_Color);
            GL.VertexAttribPointer(attrPosition_Color, 3, VertexAttribPointerType.Float, false, sizeof(float) * 6, sizeof(float) * 3);
            
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            GL.BindVertexArray(0);
I tried to explain how we can detect stride and offset for attributes as follows:
Stride and Offset

 Let's see the output:
interpolation triangle

No comments:

Post a Comment