Last active
June 17, 2020 20:32
-
-
Save pingpoli/458a1cfe046da9979a71134cd772c2d0 to your computer and use it in GitHub Desktop.
calculate the perspective projection view frustum in opengl
This file contains hidden or 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
void ViewFrustum::calculate( const float fov , const float aspectratio , const float n , const float f ) | |
{ | |
float nearPlane = -n; | |
float farPlane = -f; | |
float y1 = nearPlane * tanf(torad(fov)/2.0f); | |
float y2 = farPlane * tanf(torad(fov)/2.0f); | |
// calculate the horizontal fov from the vertical one | |
float fov_horizontal = 2.0f * atanf( tanf(torad(fov)/2.0f) * aspectratio ); | |
float x1 = nearPlane * tanf(fov_horizontal/2.0f); | |
float x2 = farPlane * tanf(fov_horizontal/2.0f); | |
// near vertices | |
this->vertices[0] = vec3( x1 , -y1 , n ); | |
this->vertices[1] = vec3( x1 , y1 , n ); | |
this->vertices[2] = vec3( -x1 , y1 , n ); | |
this->vertices[3] = vec3( -x1 , -y1 , n ); | |
// far vertices | |
this->vertices[4] = vec3( x2 , -y2 , f ); | |
this->vertices[5] = vec3( x2 , y2 , f ); | |
this->vertices[6] = vec3( -x2 , y2 , f ); | |
this->vertices[7] = vec3( -x2 , -y2 , f ); | |
} | |
void ViewFrustum::convertToWorldSpace( const mat4& M_view_inv ) | |
{ | |
for ( uint i = 0 ; i < 8 ; ++i ) | |
{ | |
vec4 v = M_view_inv * vec4( this->vertices[i] , 1.0f ); | |
this->vertices[i] = vec3( v.x , v.y , v.z ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment