opengl_learn

Step-by-step introduction to OpenGL
git clone https://0xdd.org/code/opengl_learn.git
Log | Files | Refs | README | LICENSE

ogl_perspective.c (1663B)


      1 /*
      2 2018 David DiPaola
      3 licensed under CC0 (public domain, see https://creativecommons.org/publicdomain/zero/1.0/)
      4 */
      5 
      6 #include <stdio.h>
      7 
      8 #include <stdlib.h>
      9 
     10 #include <GL/glew.h>
     11 
     12 #include <math.h>
     13 
     14 #include "ogl.h"
     15 #include "_ogl.h"
     16 
     17 void
     18 ogl_perspective(
     19 	GLfloat fovy, GLfloat zNear, GLfloat zFar,
     20 	struct ogl_mat4f * out_matrix
     21 ) {
     22 	/* from https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluPerspective.xml */
     23 
     24 	GLfloat aspect = (GLfloat)_ogl_window_width / (GLfloat)_ogl_window_height;
     25 
     26 	if (fovy < 0.0f) {
     27 		fprintf(stderr, "ogl:perspective() ERROR: fovy < 0.0f (is %g)" "\n", fovy);
     28 		exit(-1);
     29 	}
     30 	if (aspect < 0.0f) {
     31 		fprintf(stderr, "ogl:perspective() ERROR: aspect < 0.0f (is %g)" "\n", aspect);
     32 		exit(-1);
     33 	}
     34 	if (zNear < 0.0f) {
     35 		fprintf(stderr, "ogl:perspective() ERROR: zNear < 0.0f (is %g)" "\n", zNear);
     36 		exit(-1);
     37 	}
     38 	if (zFar < 0.0f) {
     39 		fprintf(stderr, "ogl:perspective() ERROR: zFar < 0.0f (is %g)" "\n", zFar);
     40 		exit(-1);
     41 	}
     42 	if (zNear > zFar) {
     43 		fprintf(stderr, "ogl:perspective() ERROR: zNear > zFar (%g > %g)" "\n", zNear, zFar);
     44 		exit(-1);
     45 	}
     46 
     47 	GLfloat f = 1.0f / tanf(fovy / 2.0f);
     48 	
     49 	GLfloat * values = (*out_matrix).values;
     50 	values[ 0] = f / aspect;    values[ 1] = 0.0f;    values[ 2] =  0.0f;                          values[ 3] = 0.0f;
     51 	values[ 4] = 0.0f;          values[ 5] = f;       values[ 6] =  0.0f;                          values[ 7] = 0.0f;
     52 	values[ 8] = 0.0f;          values[ 9] = 0.0f;    values[10] = (zFar+zNear) / (zNear-zFar);    values[11] = (2*zFar*zNear) / (zNear-zFar);
     53 	values[12] = 0.0f;          values[13] = 0.0f;    values[14] = -1.0f;                          values[15] = 0.0f;
     54 }
     55