简体   繁体   中英

OpenglES 2.0 Vertex Shader Attributes

I've read in tutorials that the bare minimum a vertex shader needs is define below:

attribute vec3 v3_variable;
attribute vec3 v3Pos;

void main()
{
    gl_Position = v3Pos;
}

OpenglES passes to the shader vertex data to v3Pos but the name of this variable can actually be anything, other tutorials name it a_Position , a_Pos , whatever~.

So my question is, how does OpenglES know that when I call glVertexAttribPointer() it knows that it should put that data into v3Pos instead of v3_variable ?

Okay, so on the app side you will have a call that looks like either

glBindAttribLocation(MyShader, 0, "v3Pos"); 

(before you link the shader) or

vertexLoc = glGetAttribLocation(MyShader, "v3Pos");

After you link the program.

Then the first element of the glVertexAttribPointer call will either be 0 or vertexLoc.

glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, sizeof(MyVertex), BUFFER_OFFSET(0));

In short, the gl linker is going to either assign v3Pos it's own location in memory, or go off of what you tell it. Either way you are going to have to perform some interaction with the shader in order to interact with the attribute.

Hope that helps

There are two methods of identifying which attributes in your shaders get 'paired' with the data you provide to glVertexAttribPointer . The only identifier you get with glVertexAttribPointer is the index (the first parameter), so it must be done by index somehow.

In the first method, you obtain the index of the attribute from your shader after it is compiled and linked using glGetAttribLocation , and use that as the first parameter, eg.

GLint program = ...;
GLint v3PosAttributeIndex = glGetAttribLocation(program, "v3Pos");
GLint v3varAttributeIndex = glGetAttribLocation(program, "v3_variable");
glVertexAttribPointer(v3PosAttributeIndex, ...);
glVertexAttribPointer(v3varAttributeIndex, ...);

You can also explicitly set the layout of the attributes when authoring the shader (as @jp's comment suggests), so you would modify your shader like so:

layout(location = 1) in vec3 v3_variable;
layout(location = 0) in vec3 v3Pos;

And then in code you would set them explicitly:

glVertexAttribPointer(0, ...); // v3Pos data
glVertexAttribPointer(1, ...); // v3_variable data

This second method only works in GLES 3.0+ (and OpenGL 3.0+), so it may not be applicable to your case if you are only using GLES 2.0. Also, note that you can use both of these methods together. Eg. even if you explicitly define the layouts, it doesn't restrict you from querying them later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM