When i only have a VBO and a VAO all works fine but when adding an IBO i'm getting a black screen. Here is the code:
initialisation:
GLuint vbo = 0;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW);
GLuint ibo;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
GLuint vao = 0;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float), NULL);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBindVertexArray(0);
inside loop:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(shader_programme);
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, 14, GL_UNSIGNED_INT, NULL);
glBindVertexArray(0);
vertices and indicies:
float points[] = {
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
-1.0, 1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, -1.0, -1.0,
1.0, -1.0, -1.0,
-1.0, 1.0, -1.0,
1.0, 1.0, -1.0,
};
float indices[] = {
0, 1, 2, 3, 7, 1, 5, 4, 7, 6, 2, 4, 0, 1
};
The 5th parameter of glVertexAttribPointer
is the byte offset between consecutive generic vertex attributes. If it is 0 then the vertex attributes are understood to be tightly packed.
Your vertices consists of three components of type float
, so the stride is 3*sizeof(float)
:
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), NULL);
Since the vertices are tightly packed, you can also pass 0 to the paramter:
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
The type of the indices is GL_UNSIGNED_INT
. The type of the index array has to be an integral data type which corresponds to GL_UNSIGNED_INT
. In your case it has to be unsigned int
.
unsigned int indices[] = { .... };
Further, the primitive type GL_TRIANGLES
consists of a list of indices where each 3 form a triangle. Indices 0, 1, 2 for ma triangle, indices 4, 5, 6 form the next triangle and so on. So the number of indices has to be dividable by 3.
If you want to draw a cube, then the list of indices may look like this:
unsigned int indices[] = {
0,1,2, 0,2,3,
1,5,6, 1,6,2,
5,4,7, 5,7,6,
4,0,3, 4,3,7,
3,2,6, 3,6,7,
1,0,4, 1,4,5
};
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, NULL);