user3124361
user3124361

Reputation: 489

How are attributes passed to vertex shader in GLSL?

I want to pass a single float or unsigned int type variable to vertex shader but you can only pass vec or struct as an attribute variable. So, I used a vec2 type attribute variable and later used it to access the content.

glBindAttribLocation(program, 0, "Bid");    
glEnableVertexAttribArray(0);    
glVertexAttribIPointer(0, 1, GL_UNSIGNED_INT, sizeof(strideStructure), (const GLvoid*)0);    

The vertex shader contains this code:

attribute ivec2 Bid;    
void main()    
{    
int x = Bid.x;    
int y = Bid.y;    
}    

So, when I pass value each time, doesn't the value get stored in x-component of vec2 Bid? In the second run of the loop, will the passed data be stored in x- component of different vector attribute? Also, if I change the size parameter to 2 for example, what would be the order in which data are stored in the vector attribute?

Upvotes: 1

Views: 2009

Answers (1)

Reto Koradi
Reto Koradi

Reputation: 54572

You can use scalar types for attributes. From the GLSL 1.50 spec (which corresponds to OpenGL 3.2):

Vertex shader inputs can only be float, floating-point vectors, matrices, signed and unsigned integers and integer vectors. Vertex shader inputs can also form arrays of these types, but not structures.

No matter if you use vector or scalar values, the types have to match. In your example, you're specifying GL_UNSIGNED_INT as the attribute type, but the type in the shader is ivec2, which is a signed value. It should be uvec2 to match the specified attribute type.

Yes, if you declare the type in the shader as uvec2 Bid, but pass only one value, that value will be in Bid.x. Bid.y will be 0. If you pass two values per vertex, the first one will be in Bid.x, and the second one in Bid.y.

You sound a little unclear about how vertex shaders are invoked, particularly when you talk about "run of the loop". There is no looping here. The vertex shader is invoked once for each vertex, and the corresponding attribute values for this specific vertex will be passed in the attribute variables. They will be in the same attribute variables, and in the same place within these variables, for each vertex.

I guess you can picture a "loop" in the sense of the vertex shader being invoked for each vertex. In reality, a lot of processing on the GPU will happen in parallel. This means that the vertex shader for a bunch of vertices will be invoked at the same time. Each one has its own variable instances, so they will not get in each others way, and the attributes for each one will be passed in exactly the same way.

An additional note on your code. You need to be careful with this call:

glBindAttribLocation(program, 0, "Bid");

glBindAttribLocation() needs to be called before linking the shader program. Otherwise it will have no effect.

Upvotes: 3

Related Questions