Using OpenGL to calculate transformations

For my final art project, I’m working on programmatically generating scenes to be rendered in Sunflow. Lot of the work is placing objects where I want them. The following is just a way to use OpenGL to do your matrix multiplications and transformations.

glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();

// transformations go here

GLfloat modelMatrix[16];
glGetFloatv (GL_MODELVIEW_MATRIX, modelMatrix);
glPopMatrix();

Transformation functions: glTranslate, glRotate, glScale, glMultMatrix

The returned array is a column-major representation of a 4×4 matrix. This section of the OpenGL guide is a good reference for remembering in which order to apply transformations.

For example, if I want to translate an object by (3,4,5) and then rotate it 45 degrees around the z-axis, I would use the following code to retrieve the transformation matrix. Notice the order of the transformation functions.

glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();

glRotatef(45, 0, 0, 1);
glTranslatef(3, 4, 5);

GLfloat modelMatrix[16];
glGetFloatv (GL_MODELVIEW_MATRIX, modelMatrix);
glPopMatrix();

for (int i = 0; i < 4; i++) {
  for (int j = 0; j < 4; j++) {
    printf("%f ", modelMatrix[j * 4 + i]);
  }
  printf("\n");
}

The code to the right outputs the following:

0.707107 -0.707107 0.000000 -0.707107
0.707107  0.707107 0.000000  4.949748
0.000000  0.000000 1.000000  5.000000
0.000000  0.000000 0.000000  1.000000
評論
  • Oscar Josue Alvarez Marquez

    I fucking Love You! that was very helpfuly for my final project!