Skip to content

Instantly share code, notes, and snippets.

@pingpoli
Last active June 17, 2020 20:32
Show Gist options
  • Save pingpoli/458a1cfe046da9979a71134cd772c2d0 to your computer and use it in GitHub Desktop.
Save pingpoli/458a1cfe046da9979a71134cd772c2d0 to your computer and use it in GitHub Desktop.
calculate the perspective projection view frustum in opengl
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