Search code examples
openglvboopengl-3

Using VBOs to render a square


I'm having a bit of trouble understanding how VBOs are used. I've been trying to get an image equivalent to:

glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective (70, 4.0f / 3, 1, 1000);

glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();

gluLookAt (0, 0, -5,
           0, 0,  0,
           0, 1,  0);

glBegin (GL_TRIANGLES);
glVertex3f (-1, -1, -1);
glVertex3f (1, -1, -1);
glVertex3f (1, 1, -1);
glVertex3f (-1, -1, -1);
glVertex3f (1, 1, -1);
glVertex3f (-1, 1, -1);
glEnd ();

which results in a white square. Using VBOs, from what I could gather from an assortment of tutorials, should change the code to:

float vertexes[][3] = {
    { 1,  1, -1},
    { 1, -1, -1},
    {-1,  1, -1},
    {-1, -1, -1},
};

unsigned int indexes[] = {
    3, 1, 0,
    3, 0, 2,
};

GLuint vbo, ibo;

glGenBuffers (1, &vbo);
glBindBuffer (GL_ARRAY_BUFFER, vbo);
glEnableClientState (GL_VERTEX_ARRAY);
glVertexPointer (3, GL_FLOAT, 0, 0);

glGenBuffers (1, &ibo);
glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, ibo);

glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective (70, 4.0f / 3, 1, 1000);

glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();

gluLookAt (0, 0, -5,
       0, 0,  0,
       0, 1,  0);

glBufferData (GL_ARRAY_BUFFER, sizeof vertexes, vertexes, GL_STATIC_DRAW);
glBufferData (GL_ELEMENT_ARRAY_BUFFER, sizeof indexes, indexes, GL_STATIC_DRAW);

glDrawElements (GL_TRIANGLES, 2, GL_UNSIGNED_INT, 0);

However, this does not render anything.


Solution

  • Found out what my error was. This call:

    glDrawElements (GL_TRIANGLES, 2, GL_UNSIGNED_INT, 0);
    

    asks OpenGL to draw a triangle with two vertexes, and not two triangles with three vertexes each as I thought. The correct call is:

    glDrawElements (GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);