Home > Net >  OpenGL how to set attribute in draw arrays
OpenGL how to set attribute in draw arrays

Time:10-04

I have a GLfloat array containing my data that looks like this:

GLfloat arr[] = {
     //position    //color
     300, 380, 0,  0, 1, 0,
     300, 300, 0,  1, 1, 0,
     380, 300, 0,  0, 1, 1,
     380, 380, 0,  1, 0, 1
};

I'm trying to draw 4 points each with their respective color, currently I'm doing this:

glPointSize(10);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, arr);
glDrawArrays(GL_POINTS, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY);

But my attempts at modifying this to accept the color values failed.

vertex and frag shaders:

#version 330 core
out vec4 FragColor;
in vec3 ourColor;

void main()
{
    FragColor = vec4(ourColor, 1.0);
} 

#version 330 core
layout (location = 0) in vec4 position;
layout (location = 1) in vec3 color;

out vec3 ourColor;

uniform mat4 projection;

void main()
{
    gl_Position = projection * vec4(position.xy, 0.0, 1.0);
    ourColor = color;
}

CodePudding user response:

You are using a shader program. The vertex attribute has the attribute index 0 and the color has the index 1. Use glVertexAttribPointer to define the 2 arrays of generic vertex attribute data:

glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, arr);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(flaot)*6, arr);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(flaot)*6, arr 3);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);

The vertex array of attribute consist of a tuple with 6 components (x, y, z, r, g, b). Therefore the byte offset between consecutive generic vertex attributes (stride) is sizeof(flaot)*6 bytes.
The address of the first vertex is arr and the address of the first color is arr 3 (respectively (unsigned char*)arr sizeof(float)*3).

  • Related