I've started a game engine for learning purposes. I have successfully gotten an opengl renderer working and I can draw textures of varying sizes to the screen. The way I have done this is by creating a hard coded array of vertices that are just a box.
float Renderer2D::vertices[30] = {
0.f, 1.f, 0.0f, 0.0f, 0.0f, // Top-left
0.f, 0.f, 0.0f, 0.0f, 1.0f, // Bottom-left
1.f, 1.f, 0.0f, 1.0f, 0.0f, // Top-right
1.f, 1.f, 0.0f, 1.0f, 0.0f, // Top-right
0.f, 0.f, 0.0f, 0.0f, 1.0f, // Bottom-left
1.f, 0.f, 0.0f, 1.0f, 1.0f // Bottom-right
};
(The first three are xyz - The fourth and fifth floats are texture coords)
I send this to the GPU at the beginning of my program. For every sprite I draw, I create a transformation matrix like this:
void Renderer2D::draw(int x, int y, int w, int h)
{
float posX = 2.0f * x / m_screenWidth - 1.0f;
float posY = 1.0f - 2.0f * y / m_screenHeight - 2.0f*h/m_screenHeight;
glm::mat4 translation, scale;
translation = glm::translate(glm::mat4(1.0f), glm::vec3(posX, posY, 0));
scale = glm::scale(glm::mat4(1.0f), glm::vec3(2.0f * w / m_screenWidth,2.0f*h/m_screenHeight, 1.f));
transformation = translation * scale;
glUniformMatrix4fv(m_shaderProgram.getMVPLocation(), 1, GL_FALSE, &transformation[0][0]);
glUniform1i(m_shaderProgram.getSamplerLocation(), 0);
m_shaderProgram.enableVertexAttribArray();
glActiveTexture(GL_TEXTURE0);
glDrawArrays(GL_TRIANGLES, 0, 6);
m_shaderProgram.disableVertexAttribArray();
}
I started looking up other questions on here about sprite batches, so I could optimize my draw calls. But in all of these questions it was suggested that a vertex array should be built up, with vertex's for every sprite.
In my code, I send vertices to the gpu once, and call glDrawArrays for every sprite. If I built the vertex array every frame, I'd send the vertices every frame (not every sprite) and call glDrawArrays once per frame. I would still have to calculate the matrices for every sprite.
Is glDrawArrays much more computationally expensive than sending a vertex buffer? Does this definitely need fixing?
If I build a vertex buffer dynamically, how could I allocate the space if I don't know how many sprites are going to be drawn? Do you just put a hard limit on it?