Created
June 13, 2019 03:37
-
-
Save lqt0223/68d1ff8cd793a3e36e8f4f52193fd9d5 to your computer and use it in GitHub Desktop.
37 perspective, view matrix derivation in vertex shader program
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
uniform mat4 u_modelMatrix; | |
uniform vec2 u_resolution; | |
uniform vec3 u_camera; | |
attribute vec4 a_position; | |
varying vec4 v_position; | |
attribute vec4 a_color; | |
varying vec4 v_color; | |
attribute vec3 a_normal; | |
varying vec3 v_normal; | |
attribute vec2 a_texcoord; | |
varying vec2 v_texcoord; | |
const float f = 0.1; | |
const float n = 100.; | |
const float fov = 0.707; | |
mat4 perspective() { | |
float fovv = fov; | |
float c = 1./tan(fovv/2.); | |
float ar = u_resolution.x/u_resolution.y; | |
float a = (f+n)/(f-n); | |
float b = 2.*f*n/(f-n); | |
return mat4( | |
c/ar,0.,0.,0., | |
0.,c,0.,0., | |
0.,0.,a,-1., | |
0.,0.,b,0. | |
); | |
} | |
mat4 view() { | |
vec3 v = normalize(u_camera); | |
vec3 up = vec3(0.,1.,0.); | |
vec3 r = normalize(cross(up,v)); | |
vec3 u = normalize(cross(v,r)); | |
mat4 basis = mat4( | |
r.x,u.x,v.x,0., | |
r.y,u.y,v.y,0., | |
r.z,u.z,v.z,0., | |
0.,0.,0.,1. | |
); | |
mat4 translate = mat4( | |
1.,0.,0.,0., | |
0.,1.,0.,0., | |
0.,0.,1.,0., | |
-u_camera.x,-u_camera.y,-u_camera.z,1. | |
); | |
return basis * translate; | |
} | |
void main(void) { | |
v_position = a_position; | |
v_color = a_color; | |
v_normal = a_normal; | |
v_texcoord = a_texcoord; | |
gl_Position = perspective() * view() * u_modelMatrix * v_position; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Some conventions about orders in GLSL:
For example, the matrix in mathematical notation:
should be initialized like this
For example, the code
can be interpreted as concatenate matrix operations such that model matrix operation is applied first, then view matrix operation, at last perspective matrix operation. Then the concatenated matrix is applied to the vector to be transformed.