Search code examples
c++openglvbovao

OpenGL : multiple VAOs for one VBO


I'm a newbie to OpenGL and I'm trying draw two triangles using two VAOs and only one VBO. Even if after some research, I came to have a better understanding of VAO, VBO and how the needed glew functions work, I have no clue why my program displays only one triangle instead of two. Can somebody help?

...

GLfloat points[] = {
    0.5f, 0.5f, 0.0f, //First Triangle
    -0.5f, 0.5f, 0.0f,
    0.5f, -0.5f, 0.0f,

    0.0f, 0.0f, 0.0f, //Second Triangle
    -1.0f, 0.0f, 0.0f,
    0.0f, -1.0f, 0.0f
};

GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

GLuint vao1;
glGenVertexArrays(1, &vao1);
glBindVertexArray(vao1);        
    glBindBuffer(GL_ARRAY_BUFFER, vbo);         
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);   
        glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

GLuint vao2;
glGenVertexArrays(1, &vao2);
glBindVertexArray(vao2);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);         
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (char*)NULL + 9);    
        glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

...

while (!glfwWindowShouldClose(window))
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(shader_program);

        glBindVertexArray(vao1);
            glDrawArrays(GL_TRIANGLES, 0, 3);
        glBindVertexArray(0);           

        glBindVertexArray(vao2);
            glDrawArrays(GL_TRIANGLES, 0, 3);
        glBindVertexArray(0);

    glUseProgram(0);

    glfwPollEvents();
    glfwSwapBuffers(window);
}

...

Solution

  • The last parameter for this function call is incorrect:

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (char*)NULL + 9); 
    

    You're telling it to add 9 bytes, but your points are floats

    Try this:

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (char*)NULL + 9 * sizeof(float));