user1203803
user1203803

Reputation:

How to use GLKMatrixStack?

I'm writing an iOS game that draws many cubes on screen, but I have a problem with positioning the cubes.

I have a function draw_voxel that draws a cube:

void draw_voxel(Point location, Color color, GLKMatrixStackRef stack) {
  GLKMatrixStackPush(stack);
  GLKMatrixStackTranslate(stack, location.x, location.y, location.z);

  std::array<Color, 36> triangle_colors;
  triangle_colors.fill(color);

  glEnableVertexAttribArray(GLKVertexAttribPosition);
  glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 0, static_cast<const GLvoid*>(triangle_vertices.data()));
  glEnableVertexAttribArray(GLKVertexAttribColor);
  glVertexAttribPointer(GLKVertexAttribColor, 4, GL_FLOAT, GL_FALSE, 0, static_cast<const GLvoid*>(triangle_colors.data()));
  glDrawArrays(GL_TRIANGLES, 0, 36);
  glDisableVertexAttribArray(GLKVertexAttribPosition);
  glDisableVertexAttribArray(GLKVertexAttribColor);

  GLKMatrixStackPop(stack);
}

I pass it a GLKMatrixStackRef, push the current matrix on top and use GLKMatrixStackTranslate to translate the top matrix. However, all cubes are still drawn at (0, 0, 0).

I call draw_voxel like this:

[self.effect prepareToDraw];

GLKMatrixStackRef stack = GLKMatrixStackCreate(nullptr);
draw_voxel(Point(-1.0f, 0.0f, 0.0f), Color(1.0f, 0.0f, 0.0f, 1.0f), stack);
draw_voxel(Point(+0.0f, 0.0f, 0.0f), Color(0.0f, 1.0f, 0.0f, 1.0f), stack);
draw_voxel(Point(+1.0f, 0.0f, 0.0f), Color(0.0f, 0.0f, 1.0f, 1.0f), stack);
CFRelease(stack);

I couldn't find any useful information on the internet about GLKit matrix stacks, and I'm really stuck. How do I "apply" the top matrix so that the cubes are translated?

Upvotes: 1

Views: 633

Answers (1)

Germano
Germano

Reputation: 2482

While I still haven't fully grasp how to use GLKMatrixStack, looking at your code I think the problem is that you are not passing the top matrix of the stack to the shader, or, in GLKit words, you are not properly configuring the effect. Probably, at some point you should be doing something like:

self.effect.transform.modelviewMatrix = GLKMatrixStackGetMatrix4(stack);

Hope this help, I'm stuck on that stack too :)

Upvotes: 1

Related Questions