# GluPerspective code

From OpenGL.org

Revision as of 20:49, 24 December 2009 by Dark Photon (talk | contribs)

Warning: This article describes legacy OpenGL APIs that have been removed from core OpenGL 3.1 and above (they are only deprecated in OpenGL 3.0). It is recommended that you not use this functionality in your programs. |

GLU - the OpenGL Utility library is an additional library that contains a handful of functions for additional tasks.

It is traditional and can be found in a lot of tutorials and examples.

gluPerspective's source code is very simple and can be replaced easily.

The code here comes from glh library (OpenGL Helper Library), which is for Windows, LGPL license
http://www.geocities.com/vmelkon/glhlibrary.html

It has glhPerspectivef2 and glhPerspectived2 (a float and double version).

Here is the float version of the code, slightly simplified :

//matrix will receive the calculated perspective matrix. //You would have to upload to your shader or use glLoadMatrixf if you aren't using shaders. void glhPerspectivef2(float *matrix, float fovyInDegrees, float aspectRatio, float znear, float zfar) { float ymax, xmax; float temp, temp2, temp3, temp4; ymax = znear * tanf(fovyInDegrees * M_PI / 360.0); // NOTE: Bug! fovyInDegrees should be divided by 2 //ymin = -ymax; //xmin = -ymax * aspectRatio; xmax = ymax * aspectRatio; glhFrustumf2(matrix, -xmax, xmax, -ymax, ymax, znear, zfar); }

void glhFrustumf2(float *matrix, float left, float right, float bottom, float top, float znear, float zfar) { float temp, temp2, temp3, temp4; temp = 2.0 * znear; temp2 = right - left; temp3 = top - bottom; temp4 = zfar - znear; matrix[0] = temp / temp2; matrix[1] = 0.0; matrix[2] = 0.0; matrix[3] = 0.0; matrix[4] = 0.0; matrix[5] = temp / temp3; matrix[6] = 0.0; matrix[7] = 0.0; matrix[8] = (right + left) / temp2; matrix[9] = (top + bottom) / temp3; matrix[10] = (-zfar - znear) / temp4; matrix[11] = -1.0; matrix[12] = 0.0; matrix[13] = 0.0; matrix[14] = (-temp * zfar) / temp4; matrix[15] = 0.0; }