Search code examples
c++openglglfwvbovao

Drawing multiple triangles with different VAOs and VBOs


I'm trying to draw two triangles using separate VAOs and VBOs but while execution I see only one triangle being rendered. Below is my code snippet. I'm not sure where I'm messing up.

I'm using glfw and glew.

.....
//initialization and creating shader program
.....
GLfloat vertices[] = {
    -0.9f, -0.5f, 0.0f,  // Left 
    -0.0f, -0.5f, 0.0f,  // Right
    -0.45f, 0.5f, 0.0f,  // Top 
};

GLfloat vertices2[] = {
    0.0f, -0.5f, 0.0f,  // Left
    0.9f, -0.5f, 0.0f,  // Right
    0.45f, 0.5f, 0.0f   // Top 
};


GLuint VBO1, VAO1, EBO;
glGenVertexArrays(1, &VAO1);
glGenBuffers(1, &VBO1);
glGenBuffers(1, &EBO);

GLuint VBO2, VAO2;
glGenBuffers(1, &VAO2);
glGenBuffers(1, &VBO2);

glBindVertexArray(VAO1);
glBindBuffer(GL_ARRAY_BUFFER, VBO1);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
//glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)nullptr);
glEnableVertexAttribArray(0);

//glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);



glBindVertexArray(VAO1);
glBindBuffer(GL_ARRAY_BUFFER, VBO2);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices2), vertices2, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)nullptr);
glEnableVertexAttribArray(0);

//glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

while (!glfwWindowShouldClose(window))
{
    glfwPollEvents();


    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);

    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgram(ShaderProgramID);

    glBindVertexArray(VAO1);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    //glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    //glBindVertexArray(0);

    glBindVertexArray(VAO2);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    //glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    //glBindVertexArray(0);

    glfwSwapBuffers(window);
}
glDeleteVertexArrays(1, &VAO1);
glDeleteVertexArrays(1, &VAO2);

glDeleteBuffers(1, &VBO1);
glDeleteBuffers(1, &VBO2);

glfwTerminate();
...

Although if I create VAOs and VBOs as array like below and change the code above code accordingly I see both the triangles. I'm unable to understand why is it so?

GLuint VAO[2], VBO[2];

Solution

  • GLuint VBO2, VAO2;
    glGenBuffers(1, &VAO2);
    
    ...
    
    glBindVertexArray(VAO2);
    

    You've initialized VAO2 as a buffer, not a VAO.