0
votes

I was trying out a shader example to draw a triangle with the RGB interpolated across the vertices, and assumed that using

layout (location = 0)in vec4 vertex;
layout (location = 1) in vec4 VertexColor;

in the vertex shader would work, since the 4 float colors immediately follow 4 float vertices in the array. However, it always drew a solid red triangle. So I tried location = 4 only to get a black screen. Experimenting further gave a blue triangle for location = 2, and finally got the interpolated result with location = 3.

My question is, how was I expected to know to enter 3 as the location? The vertex array looks like this:

GLfloat vertices[] = {  -1.5,-1.5, 0.0, 1.0,    //first 3D vertex
                         1.0, 0.0, 0.0, 1.0,    //first color
                         0.0, 1.5, 0.0, 1.0,    //second vertex
                         0.0, 1.0, 0.0, 1.0,    //second color
                         1.5,-1.5, 0.0, 1.0,    //third vertex
                         0.0, 0.0, 1.0, 1.0,};  //third color

note: edited the original layout=1 from layout = 3 in first code block

1

1 Answers

4
votes

each location can hold 4 floats (a single vec4), So a valid option would also be:

layout (location = 0)in vec4 vertex;
layout (location = 1) in vec4 VertexColor;

What dictates where what attribute comes from is the set of glVertexAttribPointer calls.

these are the ones I would expect for the glsl declaration above (assuming you use a VBO)

glVertexAttribPointer(0, 4, GL_FLOAT, false, sizeof(float)*4*2, 0);
glVertexAttribPointer(1, 4, GL_FLOAT, false, sizeof(float)*4*2, sizeof(float)*4);