opengl_learn

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

ogl_lookat.c (1927B)


      1 /*
      2 2018 David DiPaola
      3 licensed under CC0 (public domain, see https://creativecommons.org/publicdomain/zero/1.0/)
      4 */
      5 
      6 #include <GL/glew.h>
      7 
      8 #include "ogl.h"
      9 
     10 void
     11 ogl_lookat(
     12 	struct ogl_vec3f eye, struct ogl_vec3f center, struct ogl_vec3f up,
     13 	struct ogl_mat4f * out_matrix
     14 ) {
     15 	/* equivelant to gluLookAt() followed by glTranslatef(). see: https://www.opengl.org/discussion_boards/showthread.php/130409-using-gluLookAt-properly */
     16 	/* see OpenGL 2.1 gluLookAt(): https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluLookAt.xml */
     17 	/* see OpenGL 2.1 glTranslate(): https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glTranslate.xml */
     18 	/* note: gluLookAt() and glTranslate() were deprecated, then removed from later OpenGL versions. don't use them */
     19 
     20 	struct ogl_vec3f f = {
     21 		.x = center.x - eye.x,
     22 		.y = center.y - eye.y,
     23 		.z = center.z - eye.z,
     24 	};
     25 	struct ogl_vec3f f_norm;
     26 	ogl_vec3f_normal(f, &f_norm);
     27 
     28 	struct ogl_vec3f up_norm;
     29 	ogl_vec3f_normal(up, &up_norm);
     30 
     31 	struct ogl_vec3f s;
     32 	ogl_vec3f_cross(f_norm, up_norm, &s);
     33 
     34 	struct ogl_vec3f s_norm;
     35 	ogl_vec3f_normal(s, &s_norm);
     36 
     37 	struct ogl_vec3f u;
     38 	ogl_vec3f_cross(s_norm, f_norm, &u);
     39 
     40 	GLfloat eye_translate_x;
     41 	ogl_vec3f_dot(s_norm, eye, &eye_translate_x);
     42 	eye_translate_x *= -1.0f;
     43 
     44 	GLfloat eye_translate_y;
     45 	ogl_vec3f_dot(u, eye, &eye_translate_y);
     46 	eye_translate_y *= -1.0f;
     47 
     48 	GLfloat eye_translate_z;
     49 	ogl_vec3f_dot(f_norm, eye, &eye_translate_z);
     50 
     51 	GLfloat * values = (*out_matrix).values;
     52 	values[ 0] = s.x;          values[ 1] = s.y;          values[ 2] = s.z;          values[ 3] = eye_translate_x;
     53 	values[ 4] = u.x;          values[ 5] = u.y;          values[ 6] = u.z;          values[ 7] = eye_translate_y;
     54 	values[ 8] = -f_norm.x;    values[ 9] = -f_norm.y;    values[10] = -f_norm.z;    values[11] = eye_translate_z;
     55 	values[12] = 0.0f;         values[13] = 0.0f;         values[14] = 0.0f;         values[15] = 1.0f;
     56 }
     57