Implementing Projection Matrix

  • gluPerspective
    void gluPerspective(float fovy, float aspect, float zNear, float zFar)
    {
        MGfloat left, right, bottom, top;
        top = fnear * (MGfloat)tan(fovy * 3.1415962f / 360.0f);
        bottom = -top;
        left = left * aspect;
        right = right * aspect;
    
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glFrustumf(left, right, bottom, top, zNear, zFar);
        glMatrixMode(GL_MODELVIEW);
    }
    
  • glFrustum
    void glFrustumf(float l, float r, float b, float t, float n, float f)
    {
    /*
        2n/r-l      0       r+l/r-l     0
        0         2n/t-b    t+b/t-b     0
        0           0      -(f+n)/f-n   -2fn/f-n
        0           0         -1        0
    */
        // OpenGL matrix is column major.
        float m[16] = {
           2n/r-l,        0,          0,  0,
           0,        2n/t-b,          0,  0,
           r+l/r-l, t+b/t-b, -(f+n)/f-n, -1,
           0,             0,   -2fn/f-n,  0 
        };