I just started opengl and cpp for two weeks now, and I have run into a very mysterious problem with my Renderer.
The pattern of my render engine is the render class sets the shaders, uniforms, and calls draw()
on Mesh’s to render. The Mesh class does all the vertexBuffer and element managing and call the glDraw...()
in drawMesh()
.
I have many different Mesh classes (not all necessarily subclasses), and this glitch I am encountering is that only the first instantiated Mesh of its class will draw properly.
void Renderer_initFrames()
{
box1 = new FrameMesh(1.0f, 1.0f); // box1 instantiated first.
box2 = new FrameMesh(1.0f, 1.0f);
}
...
void Renderer_renderFrames()
{
g_worldShader->use();
g_worldShader->setMat4("u_projMatrix", g_prospMatrix);
g_worldShader->setMat4("u_viewMatrix", g_camMatrix);
g_worldShader->setMat4("u_modelMatrix", box1->m_modelMatrix);// box->m_modelMatrix);
box1->drawMesh();
}
Running the above code, a box frame is rendered, but if I switch the order to
box2 = new FrameMesh(1.0f, 1.0f); // box2 instantiated first.
box1 = new FrameMesh(1.0f, 1.0f);
No box frame is rendered at all. What makes it even more puzzling is that if I instantiated a couple more FrameMesh
's, renderings the latter FrameMesh
's seems to be corrupted to be triangles instead of rectangles. This makes me think that there is a memory bug somewhere, but I am not sure. Any help would be appreciated.
The following is my FrameMesh.cpp
FrameMesh::FrameMesh(float width, float height)
{
int indices[] = {
0, 1, 2,
2, 3, 0,
};
float vertices[] = {
0.0f, 0.0f, 0.0f,
width, 0.0f, 0.0f,
width, height, 0.0f,
0.0f, height, 0.0f,
};
glGenVertexArrays(1, &m_VAO);
glGenBuffers(1, &m_VBO);
glGenBuffers(1, &m_EBO);
glBindVertexArray(m_VAO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
m_modelMatrix = translate(mat4(1), vec3(0, 0, -1.0f));
}
void FrameMesh::setPosition(float x, float y)
{
m_modelMatrix = translate(mat4(1), vec3(x, y, -1.0f));
}
void FrameMesh::drawMesh()
{
glBindVertexArray(m_VAO);
glDrawElements(m_EBO, 6, GL_UNSIGNED_INT, 0);
}