I have a model with for which all matdexs (read matrix index) are either 0, 1, and 2 roughly evenly distributed. bonebends[matdex[whichvertex]] tells us which matrix should be used on this vertex.
initializing, c++:
std::vector< GLint > matdex; //initialized to 0, 1, or 2 for each vertex loaded, not shown for brevity
std::vector<glm::mat4> bonebends;
int frames=0;
bonebends.push_back(glm::mat4(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)); //identity matrices initially
bonebends.push_back(glm::mat4(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1));
bonebends.push_back(glm::mat4(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)); // thats 3 bones
ver_ind = glGetAttribLocation(shaderID, "VER_IND");
boneID = glGetUniformLocation(shaderID, "BONE_MATRIX[0]");
glGenBuffers(1, &ind_buff);
glBindBuffer(GL_ARRAY_BUFFER, ind_buff);
glBufferData(GL_ARRAY_BUFFER, matdex.size() * sizeof(GLint), &matdex[0], GL_STATIC_DRAW);
periodically in main loop, c++:
glEnableVertexAttribArray(3); //IND
glBindBuffer(GL_ARRAY_BUFFER, ind_buff);
glVertexAttribPointer( ver_ind, 1, GL_INT, GL_FALSE, 0, (void*)0 );
//ALSO LOOK HERE
glUniformMatrix4fv(boneID, 3 , GL_FALSE, &bonebends[0][0][0]);
frames+=1;
float cs=cos(3.14*2.0*(frames/100.0));
float sn=sin(3.14*2.0*(frames/100.0));
// LOOK HERE
bonebends[0]=glm::mat4(
cs , 0,-sn,0 ,
0 , 1, 0,0 ,
sn, 0, cs,0 ,
0 , 0, 0,1 );
in the shader, glsl:
layout(location = 3) in int VER_IND;
uniform mat4 BONE_MATRIX[3];
in the main function of shader, glsl:
gl_Position = BONE_MATRIX[VER_IND] * vec4(VER_POS,1); //VER_POS is the vertex's coordinates
I hoped this would make all the vertices with a coinciding matdex of 0 to rotate, and the rest remain stationary. Instead this displays the model (which is otherwise rendered correctly) spinning, as if all matdexs values are equal to 0. Which a little couting tells me they are not. I don't know how to debug VER_IND in the shader. I tried
using uint instead of int for all incarnations of matdex, which didn't make a difference.
Changing BONE_MATRIX[VER_IND] to BONE_MATRIX[0] in shader, which made it crash(???)
Changing the second and fourth argument of glUniformMatrix4fv(boneID, 3 , GL_FALSE, &bonebends[0][0][0]); in various ways, didn't help.
changed matdexs values such that none of them were 0, and it still rotates as if the shader is only using BONE_MATRIX[0].
Changing the line below // LOOK HERE to bonebends[1]=glm::mat4( results in the model not spinning at all.
From this I concluded that its only ever using the first of BONE_MATRIX[3], probably because the shader isn't receiving it correctly. I can post the whole thing but its a bit lengthy. I would like to know what I am doing wrong and how to get information back from the shader.
There are a lot of problems.
First, matdex is empty. So you're not getting any actual information.
Second,
layout(location = 3) in int VER_IND;
glVertexAttribPointer( ver_ind, 1, GL_INT, GL_FALSE, 0, (void*)0 );
These two things cannot work together. glVertexAttribPointer can only feed floating-point inputs. If you use integer formats like GL_INT, they will be converted to floats. If you want to feed integer inputs, you must use glVertexAttribIPointer (note the I).
Or just make VER_IND a float. And pass GLubytes instead of GLints. Really, there's no point in taking up all of that memory.
Third:
glEnableVertexAttribArray(3); //IND
glVertexAttribPointer( ver_ind, 1, GL_INT, GL_FALSE, 0, (void*)0 );
The first parameter of both of these functions should be the same, if you're trying to enable ver_ind.
Fourth:
//ALSO LOOK HERE
glUniformMatrix4fv(boneID, 3 , GL_FALSE, &bonebends[0][0][0]);
I don't see where you use glUseProgram to set the program you wanted to change the uniform data on.
Fifth:
// LOOK HERE
bonebends[0]=glm::mat4(
Changing a value after you have uploaded it does not magically cause the uploaded value to change.
There may be (and likely are) more problems, but the code you posted is incomplete and I don't intend to be your personal debugger. At the very least, start with code that you know works, then make the smallest change leading towards what you want. Get that working, then make another change. And so on. You did a bunch of stuff all at once, and it didn't work out.
Related
I am just starting to learn OpenGL today from this tutorial: http://openglbook.com/the-book/
I got to chapter 2, where I draw a triangle, and I understand everything except VAOs (is this acronym OK?). The tutorial has this code:
glGenVertexArrays(1, &VaoId);
glBindVertexArray(VaoId);
While I understand that the code is necessary, I have no clue what it does. Although I never use VaoId past this point (except to destroy it), the code does not function without it. I am assuming this is because it is required to be bound, but I don't know why. Does this exact code just need to be part of every OpenGL program? The tutorial explains VAOs as:
A Vertex Array Object (or VAO) is an object that describes how the vertex attributes are stored in a Vertex Buffer Object (or VBO). This means that the VAO is not the actual object storing the vertex data, but the descriptor of the vertex data. Vertex attributes can be described by the glVertexAttribPointer function and its two sister functions glVertexAttribIPointer and glVertexAttribLPointer, the first of which we’ll explore below.
I don't understand how the VAO describes the vertex attributes. I have not described them in any way. Does it get the information from the glVertexAttribPointer? I guess this must be it. Is the VAO simply a destination for the information from glVertexAttribPointer?
On a side note, is the tutorial I am following acceptable? Is there anything I should watch out for or a better tutorial to follow?
"Vertex Array Object" is brought to you by the OpenGL ARB Subcommittee for Silly Names.
Think of it as a geometry object. (As an old time SGI Performer programmer, I call them geosets.) The instance variables/members of the object are your vertex pointer, normal pointer, color pointer, attrib N pointer, ...
When a VAO is first bound, you assign these members by calling
glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer...;
glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer...;
and so on. Which attributes are enabled and the pointers you supply are stored in the VAO.
After that when you bind the VAO again, all the those attributes and pointers also become current. So one glBindVertexArray call is equivalent to all the code previously needed to set up all the attributes. It's handy for passing geometry around between functions or methods without having to create your own structs or objects.
(One time setup, multiple use is the easiest way to use VAOs, but you can also change attributes just by binding it and doing more enable/pointer calls. VAOs are not constants.)
More info in response to Patrick's questions:
The default for a newly created VAO is that it's empty (AFAIK). No geometry at all, not even vertexes, so if you try to draw it, you'll get an OpenGL error. This is reasonably sane, as in "initialize everything to False/NULL/zero".
You only need to glEnableClientState when you set things up. The VAO remembers the enable/disable state for each pointer.
Yes the VAO will store glEnableVertexAttribArray and glVertexAttrib. The old vertex, normal, color, ... arrays are the same as attribute arrays, vertex == #0 and so on.
I always think about VAO as an array of data buffers used by OpenGL. Using modern OpenGL you will create a VAO and Vertex Buffer Objects.
//vaoB is a buffer
glGenVertexArrays(1, vaoB); //creates one VAO
glBindVertexArray(vao.get(0));
glGenBuffers(vbo.length, vbo, 0); //vbo is a buffer
glBindVertexArray(vao.get(1));
glGenBuffers(vbo1.length, vbo1, 0); //vbo1 is a buffer
glBindVertexArray(vao.get(2));
glGenBuffers(vbo2.length, vbo2, 0); //vbo2 is a buffer
The next step is to bind data to a buffer:
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glBufferData(GL_ARRAY_BUFFER,vertBuf.limit()*4, vertBuf, GL_STATIC_DRAW); //vertf buf is a floatbuffer of vertices
At this point OpenGL Sees:
Now we can use glVertexAttribPointer to tell OpenGL what the data in the buffer represents:
glBindBuffer(GL_ARRAY_BUFFER, 0); //bind VBO at 0
glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); //each vertex has 3 components of size GL_FLOAT with 0 stride (space) between them and the first component starts at 0 (start of data)
OpenGL now has the data in the buffer and knows how the data is organized into vertices. The same process can be applied to texture coordinates etc but for texture coordinates there would be two values.
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glBufferData(GL_ARRAY_BUFFER,coordBuf.limit()*4, coordBuf, GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, false, 0, 0);
Next you can bind texture and draw arrays, you will want to create a Vert and Frag shader, compile and attach it to a program (not included here).
glActiveTexture(textureID); //bind our texture
glBindTexture(GL_TEXTURE_2D, textureID);
glDrawArrays(GL_TRIANGLES,0,6); //in this case 6 indices are used for two triangles forming a square
Vertex Array Objects are like macros in word processing programs and the like. A good description is found here.
Macros just remember the actions you did, such as activate this attribute, bind that buffer, etc. When you call glBindVertexArray( yourVAOId ), it simply replays those attribute pointer bindings and buffer bindings.
So your next call to draw uses whatever was bound by the VAO.
VAO's don't store vertex data. No. The vertex data is stored in a vertex buffer or in an array of client memory.
VAO is an object that represents the vertex fetch stage of the OpenGL pipeline and is used to supply input to the vertex shader.
You can create vertex array object like this
GLuint vao;
glCreateVertexArrays(1, &vao);
glBindVertexArray(vao);
First let' do a simple example. Consider such an input parameter in a shader code
layout (location = 0) in vec4 offset; // input vertex attribute
To fill in this attribute we can use
glVertexAttrib4fv(0, attrib); // updates the value of input attribute 0
Although the vertex array object stores these static attribute values for
you, it can do a lot more.
After creating vertex array object we can start filling in its state. We will ask OpenGL to fill it automatically using the data stored in a buffer object that we supply. Each vertex attribute gets to fetch data from a buffer bound to one of several vertex buffer bindings. For this end we use glVertexArrayAttribBinding(GLuint vao, GLuint attribindex, GLuint bindingindex). Also we use the glVertexArrayVertexBuffer() function to bind a buffer to one of the vertex buffer bindings. We use the glVertexArrayAttribFormat() function to describe the layout and format of the data, and finally we enable automatic filling of the attribute by calling glEnableVertexAttribArray().
When a vertex attribute is enabled, OpenGL will feed data to the vertex shader based on the format and location information you’ve provided with
glVertexArrayVertexBuffer() and glVertexArrayAttribFormat(). When
the attribute is disabled, the vertex shader will be provided with the static information you provide with a call to glVertexAttrib*().
// First, bind a vertex buffer to the VAO
glVertexArrayVertexBuffer(vao, 0, buffer, 0, sizeof(vmath::vec4));
// Now, describe the data to OpenGL, tell it where it is, and turn on automatic
// vertex fetching for the specified attribute
glVertexArrayAttribFormat(vao, 0, 4, GL_FLOAT, GL_FALSE, 0);
glEnableVertexArrayAttrib(vao, 0);
And code in a shader
layout (location = 0) in vec4 position;
After all you need to call to glDeleteVertexArrays(1, &vao).
You can read OpenGL SuperBible to understand it better.
I was trying to understand this as well and now that I think I do, it would be prudent to post a code example aimed at
people less familiar with OpenGL architecture, as I found the previous examples not very illuminating and most tutorials
just tell you to copy paste the code without explaining it.
(This is in C++ but the code can be easily translated to C)
In this example, we'll be rendering a rectangle, which has 4 vertices. Each vertex has a position (vec3, xyz), texture coordinate (vec2, uv) and color attribute (vec4, rgba).
I think it's cleanest to separate each attribute into their own array:
float positions[] = {
+0.5, +0.5, 0,
+0.5, -0.5, 0,
-0.5, -0.5, 0,
-0.5, +0.5, 0
};
float colors[] = {
1, 1, 1, 1,
1, 1, 1, 1,
1, 1, 1, 1,
1, 1, 1, 1
};
float tex_coords[] = {
0, 0,
0, 1,
1, 1,
1, 0
};
Our vertex array object will describe the four vertices with these properties.
First, we need to create the vertex array:
GLuint vertex_array;
glGenVertexArrays(1, &vertex_array);
Each vertex array has a number of buffers, these can be thought of as properties of the array. Each vertex array has an
arbitrary number of "slots" for the buffers. Along with which buffer is in which slot, it saves the CPU-side pointer to
the data for the buffer, and the CPU-side datas format. We need to make OpenGL aware of both which slot to use, where the
data is, and how it is formatted.
The buffers slots are indexed, so the first buffer is index 0, the second is 1, etc.
These locations correspond to the layout defined in the vertex shader:
// vertex shader
std::string _noop_vertex_shader_source = R"(
#version 420
layout (location = 0) in vec3 _position_3d; // slot 0: xyz
layout (location = 1) in vec4 _color_rgba; // slot 1: rgba
layout (location = 2) in vec2 _tex_coord; // slot 2: uv
out vec2 _vertex_tex_coord;
out vec4 _vertex_color_rgba;
void main()
{
gl_Position = vec4(_position_3d.xy, 1, 1); // forward position to fragment shader
_vertex_color_rgba = _color_rgba; // forward color to fragment shader
_vertex_tex_coord = _tex_coord; // forward tex coord to fragment shader
}
)";
We see that the position property is at location 0, the color property at 1 and the tex coords at 2. We'll store these
for clarity:
// property locations from our shader
const auto vertex_pos_location = 0;
const auto vertex_color_location = 1;
const auto vertex_tex_coord_location = 2;
We now need to tell OpenGL the information about each buffer outlined above:
// bind the array, this makes OpenGL aware that we are modifying it with future calls
glBindVertexArray(vertex_array);
// create the position buffer
glGenBuffers(1, &position_buffer);
// bind the buffer so opengl knows we are currently operating on it
glBindBuffer(GL_ARRAY_BUFFER, position_buffer);
// tell opengl where the data pointer is
glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions, GL_STATIC_DRAW);
// tell opengl how the data is formatted
glVertexAttribPointer(vertex_pos_location, 3, GL_FLOAT, GL_FALSE, 0, (void*) 0);
// tell opengl that this slot should be used
glEnableVertexAttribArray(vertex_pos_location);
Here, we generate a buffer that will hold our position data. For glVertexAttribPointer, we choose the
correct location, 3 elements (as the positions are xyz coordinates), and no offset or stride.
Because we have a separate array for all our properties, we can leave both as 0.
Similar to the position, we generate and fill the buffers for the color and tex coord property:
// color
glGenBuffers(1, &color_buffer); // generate
glBindBuffer(GL_ARRAY_BUFFER, color_buffer); // bind
glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW); // set pointer
glVertexAttribPointer(vertex_color_location, 4, GL_FLOAT, GL_FALSE, 0, (void*) 0); // set data format
glEnableVertexAttribArray(vertex_color_location); // enable slot
// tex coords
glGenBuffers(1, &tex_coord_buffer);
glBindBuffer(GL_ARRAY_BUFFER, tex_coord_buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(tex_coords), tex_coords, GL_STATIC_DRAW);
glVertexAttribPointer(vertex_tex_coord_location, 2, GL_FLOAT, GL_FALSE, 0, (void*) 0);
glEnableVertexAttribArray(vertex_tex_coord_location);
Where we chose 4 elements for the colors because they are in RGBA format and 2 for the tex coords for obvious reasons.
The last thing we need to render a vertex array is an element buffer. These can be thought of as a list of
indices that define which order the vertices will be rendered in. For us, we want to render the
rectangle as two tris in a triangle fan, so we choose the following element buffer:
// vertex order
static uint32_t indices[] = {
0, 1, 2, 1, 2, 3
};
glGenBuffers(1, &element_buffer); // generate
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element_buffer); // bind
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW) // set pointer
We do not need to enable the element buffers slot, it is separate from the vertex array. We don't have to specify the format of the elements buffer here, that will be done during glDrawElements in the render step.
So why all this? All these functions tell OpenGL where to look for the data for the vertices. Specifying the pointers to
the correct buffer data and their layout, if we now bind the vertex array during a render step:
glUseProgram(shader.get_program_id()); // shader program with our vertex shader
glBindVertexArray(vertex_array);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element_buffer);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
Where 6 is the number of elements in the element buffer.
This is all that's needed to correctly update the in values in the vertex shader. OpenGL will move the data from
our CPU-side positions, colors and tex_coords into the correct locations 0, 1 and 2 of the vertex shader respectively.
We don't need to bind anything else, the vertex array remembers what we gave it and does it for us, which is why it's convenient and should be preferred in modern OpenGL.
In summary:
Each vertex array has n buffers for arbitrary properties and 1 element buffer. For each property / buffer, we need to
a) generate it (glGenBuffers)
b) bind it (glBindBuffer(GL_ARRAY_BUFFER)
c) tell OpenGL where the data is located in RAM (glBufferData)
d) tell OpenGL how the data is formatted (glVertexAttribPointer)
e) tell OpenGL to use that slot (glEnableVertexAttribArray)
for the element buffer, we only need to generate it, bind it to GL_ELEMENT_ARRAY_BUFFER, then tell opengl
where the data is.
Hopefully that helped shed some light on things. I'm almost positive there will be factual errors in this post as
I'm also mostly new to OpenGL but this was the way I conceptualized it to get my code working.
Currently I have following setup which is working fine for far.
struct Vertex {
glm::vec3 position;
glm::vec3 normal;
glm::vec2 texCoord;
}
std::vector<Vertex> vertices;
The Vertex-Attributes:
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*) offsetof(Vertex, Vertex::position));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*) offsetof(Vertex, Vertex::normal));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*) offsetof(Vertex, Vertex::texCoord));
Now I want to increase my performance by changing the vertex attributes to from float to short.
I tried to start with the vertex positions.
OpenGL's Vertex Specification Best Practices tells me this:
Positions [...]
To do this, you rearrange your model space data so that all positions are packed in a [-1, 1] box around the origin. You do that by finding the min/max values in XYZ among all positions. Then you subtract the center point of the min/max box from all vertex positions; followed by scaling all of the positions by half the width/height/depth of the min/max box. You need to keep the center point and scaling factors around.
When you build your model-to-view matrix (or model-to-whatever matrix), you need to apply the center point offset and scale at the top of the transform stack (so at the end, right before you draw).
I also read this Thread.
That's why I added this preprocessing step mapping all vertices to [-1,1]
for (auto& v : vertices) {
v.position = (v.position - center) * halfAxisLengths;
}
and recale it in the vertex-shader
vec4 rescaledPos = vec4(in_pos, 1.0) * vec4(halfAxisLengths, 1.0) + vec4(center, 0.0);
gl_Position = P * V * M * rescaledPos;
My vertex attribute using GL_SHORT instead of GL_FLOAT, and normalize set to GL_TRUE:
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_SHORT, GL_TRUE, sizeof(Vertex), (void*) offsetof(Vertex, Vertex::position));
As result I just get a chaos of triangles, but not my model with increased fps.
Is this the correct way to set vertex attributes to short?
Or do I have to change my complete Vertex structure?
If yes, what's the best way to do this (glm vectors with shorts?).
An working example would be great, I couldn't find any.
I adjusted the data structure for the vertex buffer:
struct newVertex {
GLshort position[4]; // for GL_SHORT
GLint normal; // for GL_INT_2_10_10_10_REV
GLshort texCoord[2]; // for GL_SHORT
};
As a result I get ~20% increased performance.
Or do I have to change my complete Vertex structure?
Yes, OpenGL will not magically do the conversion for you. But then if performance is your goal…
Now I want to increase my performance by changing the vertex attributes to from float to short.
This would actually hurt performance. GPUs are optimized for processing vectors as floating point values. This in turn influences the memory interface, which is designed to give best performance for 32 bit aligned accesses. Bysubmitting as 16 bit short integer you're forcing the current line of GPUs to perform suboptimal memory access and an intermediary conversion step.
If performance is your goal stick to single precision float. If you don't believe me: Benchmark it.
Does anyone know why this error is being thrown?
I thought I am binding to VBO when I use glEnableVertexAttribArray?
com.jogamp.opengl.GLException: array vertex_buffer_object must be bound to call this method
at jogamp.opengl.gl4.GL4bcImpl.checkBufferObject(GL4bcImpl.java:39146)
at jogamp.opengl.gl4.GL4bcImpl.checkArrayVBOBound(GL4bcImpl.java:39178)
at jogamp.opengl.gl4.GL4bcImpl.glVertexAttribPointer(GL4bcImpl.java:37371)
This is my code to draw ..
public void draw(final GL2ES2 gl, Matrix4f projectionMatrix, Matrix4f viewMatrix, int shaderProgram, final Vec3 position, final float angle) {
// enable glsl
gl.glUseProgram(shaderProgram);
// enable alpha
gl.glEnable(GL2ES2.GL_BLEND);
gl.glBlendFunc(GL2ES2.GL_SRC_ALPHA, GL2ES2.GL_ONE_MINUS_SRC_ALPHA);
// get handle to glsl variables
mPositionHandle = gl.glGetAttribLocation(shaderProgram, "vPosition");
setmColorHandle(gl.glGetUniformLocation(shaderProgram, "vColor"));
mProj = gl.glGetUniformLocation(shaderProgram, "mProj");
mView = gl.glGetUniformLocation(shaderProgram, "mView");
mModel = gl.glGetUniformLocation(shaderProgram, "mModel");
// perform translations
getModelMatrix().loadIdentity();
getModelMatrix().translate(new Vec3(position.x * 60.0f, position.y * 60.0f, position.z * 60.0f));
getModelMatrix().rotate(angle, 0, 0, 1);
// set glsl variables
gl.glUniform4fv(getmColorHandle(), 1, getColorArray(), 0);
gl.glUniformMatrix4fv(mProj, 1, true, projectionMatrix.getValues(), 0);
gl.glUniformMatrix4fv(mView, 1, true, viewMatrix.getValues(), 0);
gl.glUniformMatrix4fv(mModel, 1, true, getModelMatrix().getValues(), 0);
// Enable a handle to the triangle vertices
gl.glEnableVertexAttribArray(mPositionHandle);
// Prepare the triangle coordinate data
gl.glVertexAttribPointer(
getmPositionHandle(),
COORDS_PER_VERTEX,
GL2ES2.GL_FLOAT,
false,
vertexStride, 0L); // This is the line that throws error
// Draw the square
gl.glDrawElements(
GL2ES2.GL_TRIANGLES,
drawOrder.length,
GL2ES2.GL_UNSIGNED_SHORT,
0L);
// Disable vertex array
gl.glDisableVertexAttribArray(mPositionHandle);
gl.glDisable(GL2ES2.GL_BLEND);
gl.glUseProgram(0);
}
(I've never used OpenGL with Java, so I'll use C/C++ code, but I hope it will come across well)
You do not create or bind a Vertex Buffer Object.
First, use glGenBuffers to create a buffer, as so:
GLuint bufferID;
glGenBuffers(1, &bufferID);
This allocates a handle and stores it in bufferID.
Then, bind the buffer:
glBindBuffers(GL_ARRAY_BUFFER, bufferID);
This makes it the "current" buffer to use.
Next, fill the buffer with data. Assuming vertices is an array that stores your vertex coordinates, in flat format, with three floats per vertex:
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW);
This actually puts the data in GPU memory.
Then enable the attribute array and set the pointer:
glEnableVertexAttribArray(mPositionHandle);
glVertexAttribPointer(mPositionHandle, 3, GL_FLOAT, 0, 0, 0);
This will make the data in vertices available for shader programs under the vertex attribute location of mPositionHandle.
The second-to-last parameter of glVertexAttribPointer is stride. In this example, it is 0, because the buffer contains only vertex position data. If you want to pack both vertex position data and color data in the same buffer, as so:
v1.positionX v1.positionY v1.positionZ v1.colorR v1.colorG v1.colorB
v2.positionX ...
you will need to use a non-zero stride. stride specifies the offset between one attribute and the next of the same type; with stride of 0, they are assumed to be tightly packed. In this case, you'll want to set a stride of sizeof(GLfloat) * 6, so that after reading one vertex's position, it will skip the color data to arrive at the next vertex, and similarily for colors.
// (create, bind and fill vertex buffer here)
glEnableVertexAttribArray(location_handle_of_position_data);
glVertexAttribPointer(location_handle_of_position_data, 3, GL_FLOAT, 0, sizeof(GLfloat) * 6, 0);
glEnableVertexAttribArray(location_handle_of_color_data);
glVertexAttribPointer(location_handle_of_color_data, 3, GL_FLOAT, 0, sizeof(GLfloat) * 6, sizeof(GLfloat) * 3);
The last parameter is the offset to the first attribute - the first color attribute starts after the third float.
Other considerations:
You should look into using Vertex Array Objects. It might or might not work without them, but by standard they are required, and they simplify the code in any case.
For the sake of simplicity, this example code stores color data in floats, but for real use bytes are preferable.
glVertexAttribPointer() specifies that data for the attribute should be pulled from the currently bound vertex buffer, using the parameters specified. So you need to call:
gl.glBindBuffer(GL_VERTEX_ARRAY, ...);
before you call glVertexAttribPointer().
glEnableVertexAttribArray() specifies that an array should be used for the vertex attribute. Otherwise, a constant value, specified with calls like glVertexAttrib4f() is used. But it does not specify that the array is in a buffer. And even more importantly, there's no way glVertexAttribPointer() would know which buffer to use for the attribute unless you bind a specific buffer.
I am trying to do a simple map rendered in OpenGL 2.1 and Qt5. But I'm failing on very basic issues. The one I'm presenting here is surface normals.
I have 4 object made of a single triangle geometry. A geoetry to make simple, is a dynamically allocated array of Vertex, where a Vertex is a couple of two QVector3D, a 3D position class predefined in Qt.
struct Vertex
{
QVector3D position;
QVector3D normal;
};
I'm computing the normal at a vertex by using the cross product of the two vectors from that vertex to the next or previous vertex. Normal computation for the structure seems fine, by debugging or printing results to the console.
QVector3D(-2, -2, -2) has normal QVector3D(0, 0, 1)
QVector3D(2, -2, -2) has normal QVector3D(0, 0, 1)
QVector3D(-2, 2, -2) has normal QVector3D(0, 0, 1)
...
But when I feed the data to the shaders, the result are absurd! Here is a picture of the polygons colored with the normal value at each position:
As in normal maps, red=x, green=y and blue=z. The top left corner of the black square is the origin of the world. As you can see the normal at some point seems to simply be the position at that point, without the z-value. Can you hint me what might be wrong, knowing the painting code is :
glUseProgram(program.programId());
glEnableClientState(GL_NORMAL_ARRAY);
program.setUniformValue("modelViewProjectionMatrix", viewCamera);
program.setUniformValue("entityBaseColor", QColor(0,120,233));
program.setUniformValue("sunColor", QColor("white"));
program.setUniformValue("sunBrightness", 1.0f);
static QVector3D tmpSunDir = QVector3D(0.2,-0.2,1.0).normalized();
program.setUniformValue("sunDir",tmpSunDir);
for( size_t i = 0; i < m_numberOfBoundaries; ++i)
{
glBindBuffer(GL_ARRAY_BUFFER, m_bufferObjects[i]);
int vertexLocation = program.attributeLocation("vertexPosition");
program.setAttributeArray( vertexLocation, GL_FLOAT, &(m_boundaries[i].data->position), sizeof(Vertex) );
program.enableAttributeArray(vertexLocation);
glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0 );
int vertexNormal = program.attributeLocation("vertexNormal");
program.setAttributeArray( vertexNormal, GL_FLOAT, &(m_boundaries[i].data->normal), sizeof(Vertex) );
program.enableAttributeArray(vertexNormal);
glVertexAttribPointer( vertexNormal, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0 );
glDrawArrays( GL_POLYGON, 0, m_boundaries[i].sizeOfData );
}
glDisableClientState(GL_NORMAL_ARRAY);
where a boundary is a geometrically connected component of the polygon. program is a QOpenGLShaderProgram, an Qt abstraction for shader programs. Each boundary is bound to a buffer object. The buffer object numbers are stored in the array m_bufferObjects. Polygon “boundaries” are stored as struct in the array m_boundaries. They have two fields : data, a pointer to the start of the array of vertices for the loop, and sizeOfData, the number of points for the polygon.
Until I get to the real problem of yours, here's something, probably unrelated but just as wrong:
glEnableClientState(GL_NORMAL_ARRAY);
/*...*/
glDisableClientState(GL_NORMAL_ARRAY);
You're using self defined vertex attributes, so it makes absolutely no sense to use those old fixed function pipeline client state locations. Use glEnableVertexAttribArray(location_index) instead,
Update
So I finally came around to take a closer look at your code and your problem is the mix of Qt's abstraction layer and use of raw OpenGL commands. Essentially your problem boils down to that you have a VBO bound when making calls to QOpenGLShaderProgram::setAttribArray followed by a call of glVertexAttribPointer.
One problem is, that setAttribArray internally makes the call of glVertexAttribPointer for you, so your own call to it is redundant and overwrites whatever Qt's stuff did. The more severe problem is, that you do have a VBO bound by glBindBuffer, so calls to glVertexAttribPointer actually take an byte offset into the VBO data instead of a pointer (in fact with a VBO bound passing a 0, which in pointer terms was a null pointer will yield a perfectly valid data offset). See this answer by me, why this is all a bit misleading and actually violates the C specification: https://stackoverflow.com/a/8284829/524368
Recent OpenGL versions actually have a new API for specifying attrib array offsets that conform to the C language specification.
The correct Qt method to use would be QOpenGLShaderProgramm::setAttribBuffer. Unfortunately your code shows not the exact definition of m_boundaries and your call to glBufferData or glBufferSubData; if I had that I could give you instructions on how to alter your code.
I am just starting to learn OpenGL today from this tutorial: http://openglbook.com/the-book/
I got to chapter 2, where I draw a triangle, and I understand everything except VAOs (is this acronym OK?). The tutorial has this code:
glGenVertexArrays(1, &VaoId);
glBindVertexArray(VaoId);
While I understand that the code is necessary, I have no clue what it does. Although I never use VaoId past this point (except to destroy it), the code does not function without it. I am assuming this is because it is required to be bound, but I don't know why. Does this exact code just need to be part of every OpenGL program? The tutorial explains VAOs as:
A Vertex Array Object (or VAO) is an object that describes how the vertex attributes are stored in a Vertex Buffer Object (or VBO). This means that the VAO is not the actual object storing the vertex data, but the descriptor of the vertex data. Vertex attributes can be described by the glVertexAttribPointer function and its two sister functions glVertexAttribIPointer and glVertexAttribLPointer, the first of which we’ll explore below.
I don't understand how the VAO describes the vertex attributes. I have not described them in any way. Does it get the information from the glVertexAttribPointer? I guess this must be it. Is the VAO simply a destination for the information from glVertexAttribPointer?
On a side note, is the tutorial I am following acceptable? Is there anything I should watch out for or a better tutorial to follow?
"Vertex Array Object" is brought to you by the OpenGL ARB Subcommittee for Silly Names.
Think of it as a geometry object. (As an old time SGI Performer programmer, I call them geosets.) The instance variables/members of the object are your vertex pointer, normal pointer, color pointer, attrib N pointer, ...
When a VAO is first bound, you assign these members by calling
glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer...;
glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer...;
and so on. Which attributes are enabled and the pointers you supply are stored in the VAO.
After that when you bind the VAO again, all the those attributes and pointers also become current. So one glBindVertexArray call is equivalent to all the code previously needed to set up all the attributes. It's handy for passing geometry around between functions or methods without having to create your own structs or objects.
(One time setup, multiple use is the easiest way to use VAOs, but you can also change attributes just by binding it and doing more enable/pointer calls. VAOs are not constants.)
More info in response to Patrick's questions:
The default for a newly created VAO is that it's empty (AFAIK). No geometry at all, not even vertexes, so if you try to draw it, you'll get an OpenGL error. This is reasonably sane, as in "initialize everything to False/NULL/zero".
You only need to glEnableClientState when you set things up. The VAO remembers the enable/disable state for each pointer.
Yes the VAO will store glEnableVertexAttribArray and glVertexAttrib. The old vertex, normal, color, ... arrays are the same as attribute arrays, vertex == #0 and so on.
I always think about VAO as an array of data buffers used by OpenGL. Using modern OpenGL you will create a VAO and Vertex Buffer Objects.
//vaoB is a buffer
glGenVertexArrays(1, vaoB); //creates one VAO
glBindVertexArray(vao.get(0));
glGenBuffers(vbo.length, vbo, 0); //vbo is a buffer
glBindVertexArray(vao.get(1));
glGenBuffers(vbo1.length, vbo1, 0); //vbo1 is a buffer
glBindVertexArray(vao.get(2));
glGenBuffers(vbo2.length, vbo2, 0); //vbo2 is a buffer
The next step is to bind data to a buffer:
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glBufferData(GL_ARRAY_BUFFER,vertBuf.limit()*4, vertBuf, GL_STATIC_DRAW); //vertf buf is a floatbuffer of vertices
At this point OpenGL Sees:
Now we can use glVertexAttribPointer to tell OpenGL what the data in the buffer represents:
glBindBuffer(GL_ARRAY_BUFFER, 0); //bind VBO at 0
glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); //each vertex has 3 components of size GL_FLOAT with 0 stride (space) between them and the first component starts at 0 (start of data)
OpenGL now has the data in the buffer and knows how the data is organized into vertices. The same process can be applied to texture coordinates etc but for texture coordinates there would be two values.
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glBufferData(GL_ARRAY_BUFFER,coordBuf.limit()*4, coordBuf, GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, false, 0, 0);
Next you can bind texture and draw arrays, you will want to create a Vert and Frag shader, compile and attach it to a program (not included here).
glActiveTexture(textureID); //bind our texture
glBindTexture(GL_TEXTURE_2D, textureID);
glDrawArrays(GL_TRIANGLES,0,6); //in this case 6 indices are used for two triangles forming a square
Vertex Array Objects are like macros in word processing programs and the like. A good description is found here.
Macros just remember the actions you did, such as activate this attribute, bind that buffer, etc. When you call glBindVertexArray( yourVAOId ), it simply replays those attribute pointer bindings and buffer bindings.
So your next call to draw uses whatever was bound by the VAO.
VAO's don't store vertex data. No. The vertex data is stored in a vertex buffer or in an array of client memory.
VAO is an object that represents the vertex fetch stage of the OpenGL pipeline and is used to supply input to the vertex shader.
You can create vertex array object like this
GLuint vao;
glCreateVertexArrays(1, &vao);
glBindVertexArray(vao);
First let' do a simple example. Consider such an input parameter in a shader code
layout (location = 0) in vec4 offset; // input vertex attribute
To fill in this attribute we can use
glVertexAttrib4fv(0, attrib); // updates the value of input attribute 0
Although the vertex array object stores these static attribute values for
you, it can do a lot more.
After creating vertex array object we can start filling in its state. We will ask OpenGL to fill it automatically using the data stored in a buffer object that we supply. Each vertex attribute gets to fetch data from a buffer bound to one of several vertex buffer bindings. For this end we use glVertexArrayAttribBinding(GLuint vao, GLuint attribindex, GLuint bindingindex). Also we use the glVertexArrayVertexBuffer() function to bind a buffer to one of the vertex buffer bindings. We use the glVertexArrayAttribFormat() function to describe the layout and format of the data, and finally we enable automatic filling of the attribute by calling glEnableVertexAttribArray().
When a vertex attribute is enabled, OpenGL will feed data to the vertex shader based on the format and location information you’ve provided with
glVertexArrayVertexBuffer() and glVertexArrayAttribFormat(). When
the attribute is disabled, the vertex shader will be provided with the static information you provide with a call to glVertexAttrib*().
// First, bind a vertex buffer to the VAO
glVertexArrayVertexBuffer(vao, 0, buffer, 0, sizeof(vmath::vec4));
// Now, describe the data to OpenGL, tell it where it is, and turn on automatic
// vertex fetching for the specified attribute
glVertexArrayAttribFormat(vao, 0, 4, GL_FLOAT, GL_FALSE, 0);
glEnableVertexArrayAttrib(vao, 0);
And code in a shader
layout (location = 0) in vec4 position;
After all you need to call to glDeleteVertexArrays(1, &vao).
You can read OpenGL SuperBible to understand it better.
I was trying to understand this as well and now that I think I do, it would be prudent to post a code example aimed at
people less familiar with OpenGL architecture, as I found the previous examples not very illuminating and most tutorials
just tell you to copy paste the code without explaining it.
(This is in C++ but the code can be easily translated to C)
In this example, we'll be rendering a rectangle, which has 4 vertices. Each vertex has a position (vec3, xyz), texture coordinate (vec2, uv) and color attribute (vec4, rgba).
I think it's cleanest to separate each attribute into their own array:
float positions[] = {
+0.5, +0.5, 0,
+0.5, -0.5, 0,
-0.5, -0.5, 0,
-0.5, +0.5, 0
};
float colors[] = {
1, 1, 1, 1,
1, 1, 1, 1,
1, 1, 1, 1,
1, 1, 1, 1
};
float tex_coords[] = {
0, 0,
0, 1,
1, 1,
1, 0
};
Our vertex array object will describe the four vertices with these properties.
First, we need to create the vertex array:
GLuint vertex_array;
glGenVertexArrays(1, &vertex_array);
Each vertex array has a number of buffers, these can be thought of as properties of the array. Each vertex array has an
arbitrary number of "slots" for the buffers. Along with which buffer is in which slot, it saves the CPU-side pointer to
the data for the buffer, and the CPU-side datas format. We need to make OpenGL aware of both which slot to use, where the
data is, and how it is formatted.
The buffers slots are indexed, so the first buffer is index 0, the second is 1, etc.
These locations correspond to the layout defined in the vertex shader:
// vertex shader
std::string _noop_vertex_shader_source = R"(
#version 420
layout (location = 0) in vec3 _position_3d; // slot 0: xyz
layout (location = 1) in vec4 _color_rgba; // slot 1: rgba
layout (location = 2) in vec2 _tex_coord; // slot 2: uv
out vec2 _vertex_tex_coord;
out vec4 _vertex_color_rgba;
void main()
{
gl_Position = vec4(_position_3d.xy, 1, 1); // forward position to fragment shader
_vertex_color_rgba = _color_rgba; // forward color to fragment shader
_vertex_tex_coord = _tex_coord; // forward tex coord to fragment shader
}
)";
We see that the position property is at location 0, the color property at 1 and the tex coords at 2. We'll store these
for clarity:
// property locations from our shader
const auto vertex_pos_location = 0;
const auto vertex_color_location = 1;
const auto vertex_tex_coord_location = 2;
We now need to tell OpenGL the information about each buffer outlined above:
// bind the array, this makes OpenGL aware that we are modifying it with future calls
glBindVertexArray(vertex_array);
// create the position buffer
glGenBuffers(1, &position_buffer);
// bind the buffer so opengl knows we are currently operating on it
glBindBuffer(GL_ARRAY_BUFFER, position_buffer);
// tell opengl where the data pointer is
glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions, GL_STATIC_DRAW);
// tell opengl how the data is formatted
glVertexAttribPointer(vertex_pos_location, 3, GL_FLOAT, GL_FALSE, 0, (void*) 0);
// tell opengl that this slot should be used
glEnableVertexAttribArray(vertex_pos_location);
Here, we generate a buffer that will hold our position data. For glVertexAttribPointer, we choose the
correct location, 3 elements (as the positions are xyz coordinates), and no offset or stride.
Because we have a separate array for all our properties, we can leave both as 0.
Similar to the position, we generate and fill the buffers for the color and tex coord property:
// color
glGenBuffers(1, &color_buffer); // generate
glBindBuffer(GL_ARRAY_BUFFER, color_buffer); // bind
glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW); // set pointer
glVertexAttribPointer(vertex_color_location, 4, GL_FLOAT, GL_FALSE, 0, (void*) 0); // set data format
glEnableVertexAttribArray(vertex_color_location); // enable slot
// tex coords
glGenBuffers(1, &tex_coord_buffer);
glBindBuffer(GL_ARRAY_BUFFER, tex_coord_buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(tex_coords), tex_coords, GL_STATIC_DRAW);
glVertexAttribPointer(vertex_tex_coord_location, 2, GL_FLOAT, GL_FALSE, 0, (void*) 0);
glEnableVertexAttribArray(vertex_tex_coord_location);
Where we chose 4 elements for the colors because they are in RGBA format and 2 for the tex coords for obvious reasons.
The last thing we need to render a vertex array is an element buffer. These can be thought of as a list of
indices that define which order the vertices will be rendered in. For us, we want to render the
rectangle as two tris in a triangle fan, so we choose the following element buffer:
// vertex order
static uint32_t indices[] = {
0, 1, 2, 1, 2, 3
};
glGenBuffers(1, &element_buffer); // generate
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element_buffer); // bind
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW) // set pointer
We do not need to enable the element buffers slot, it is separate from the vertex array. We don't have to specify the format of the elements buffer here, that will be done during glDrawElements in the render step.
So why all this? All these functions tell OpenGL where to look for the data for the vertices. Specifying the pointers to
the correct buffer data and their layout, if we now bind the vertex array during a render step:
glUseProgram(shader.get_program_id()); // shader program with our vertex shader
glBindVertexArray(vertex_array);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element_buffer);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
Where 6 is the number of elements in the element buffer.
This is all that's needed to correctly update the in values in the vertex shader. OpenGL will move the data from
our CPU-side positions, colors and tex_coords into the correct locations 0, 1 and 2 of the vertex shader respectively.
We don't need to bind anything else, the vertex array remembers what we gave it and does it for us, which is why it's convenient and should be preferred in modern OpenGL.
In summary:
Each vertex array has n buffers for arbitrary properties and 1 element buffer. For each property / buffer, we need to
a) generate it (glGenBuffers)
b) bind it (glBindBuffer(GL_ARRAY_BUFFER)
c) tell OpenGL where the data is located in RAM (glBufferData)
d) tell OpenGL how the data is formatted (glVertexAttribPointer)
e) tell OpenGL to use that slot (glEnableVertexAttribArray)
for the element buffer, we only need to generate it, bind it to GL_ELEMENT_ARRAY_BUFFER, then tell opengl
where the data is.
Hopefully that helped shed some light on things. I'm almost positive there will be factual errors in this post as
I'm also mostly new to OpenGL but this was the way I conceptualized it to get my code working.