Search code examples
c++openglmatrixglrotate

OpenGL glTranslate and glRotate


I need a function that applies a translation like glTranslate() to a point. Does someone know of a function like glTranslate() and glRotate() to modify and retrieve a matrix to multiply?


Solution

  • There are thousands of free matrix classes out there. Have a hunt round google and then you can set up a translation and rotation without using the gl* functions at all ...

    edit: If you really just want to create the matrix without using a more than handy matrix class then you can define glRotatef( angle, x, y, z ) as follows:

    const float cosA = cosf( angle );
    const float sinA = sinf( angle );
    float m[16] = { cosA + ((x * x) * (1 - cosA)), ((x * y) * (1 - cosA)) - (z * sinA), ((x * z) * (1 - cosA)) + (y * sinA), 0.0f,
                    ((y * x) * (1 - cosA)) + (z * sinA), cosA + ((y * y) * (1 - cosA)), ((y * z) * (1 - cosA)) - (x * sinA), 0.0f,
                    ((z * x) * (1 - cosA)) - (y * sinA), ((z * y) * (1 - cosA)) + (x * sinA), cosA + ((z * z) * (1 - cosA)), 0.0f,
                    0.0f, 0.0f, 0.0f, 1.0f
                   };
    

    As taken from wikipedia.

    A translation matrix is really easy to create: glTranslatef( x, y, z) is define as follows:

    float m[16] = { 1.0f, 0.0f, 0.0f, 0.0f,
                    0.0f, 1.0f, 0.0f, 0.0f,
                    0.0f, 0.0f, 1.0f, 0.0f,
                       x,    y,    z, 1.0f
                   };
    

    You can look up matrix multiplication and matrix-vector multiplication pretty easily.

    To make your life simple, though, you could just download a matrix class which does all this for you ...