Marcus Mathiassen
Marcus Mathiassen

Reputation: 53

OpenGL instanced rendering slower than glBegin/glEnd

I'm porting an older program using glBegin()/glEnd() (top picture) to glDrawArraysInstanced() (bottom picture). I expected some performance improvements, but I got the opposite. Now this is the first time I've tried using glDrawArraysInstanced() so I think I must have screwed up somewhere.

The two are basically identical and the only difference is how they draw the circles.

What have I done wrong? And if not, what makes it slower?

enter image description here enter image description here

// This runs once at startup
std::vector<glm::mat4> transforms;
glGenBuffers(NUM_BUFFERS, VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO[TRANSFORM]);
for (int i = 0; i < 4; ++i) {
  glEnableVertexAttribArray(1 + i);
  glVertexAttribPointer(1 + i, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4),
                      (GLvoid *)(i * sizeof(glm::vec4)));
  glVertexAttribDivisor(1 + i, 1);
} // ---------


// This runs every frame
if (num_circles > transforms.size()) transforms.resize(num_circles);
int i = 0;
for (const auto &circle : circle_vec) {
  transforms[i++] = circle.transform.getModel();
}

glBindBuffer(GL_ARRAY_BUFFER, VBO[TRANSFORM]);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::mat4) * num_circles,    &transforms[0], GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

glBindVertexArray(VAO);
glDrawArraysInstanced(GL_LINE_LOOP, 0, CIRCLE_NUM_VERTICES, num_circles);
glBindVertexArray(0);
// ---------


// And this is the vertex shader
#version 410

in vec3 position;
in mat4 transform;

void main()
{
   gl_Position = transform * vec4(position, 1.0);
}

Upvotes: 3

Views: 517

Answers (1)

Onur A.
Onur A.

Reputation: 3027

What I saw at my first glimpse is that you are creating a new vector on every frame. Consider caching it.

// This runs every frame
std::vector<glm::mat4> transforms;

Upvotes: 4

Related Questions