Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@hamsham
Last active February 3, 2016 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamsham/81c578bdcbf9d04d1907 to your computer and use it in GitHub Desktop.
Save hamsham/81c578bdcbf9d04d1907 to your computer and use it in GitHub Desktop.
FOV-based camera clipping in 3D
bool is_point_in_fov(const ls::draw::Camera& cam, math::vec3 point, const float fovReduction = 1.f) {
// Get the local camera's absolute position and direction in world-space
const math::vec3&& eyePos = cam.get_abs_position();
const math::vec3&& eyeDir = math::normalize(cam.get_eye_direction());
// translate the input point using a model-view matrix (no projection
// matrix should be used).
const math::mat4&& mvMat = modelMatrix * cam.get_view_matrix();
const math::vec4&& temp = math::vec4{-point[0], -point[1],-point[2], 0.f} * mvMat;
// Move the translated point into the camera's local space
point = {temp[0], temp[1], temp[2]};
point = math::normalize(eyePos - point);
// Get the cosine of the angle at which the point is oriented from the
// camera's view direction
const float angleToPoint = math::dot(point, eyeDir) * cam.get_fov();
const float angleOfView = std::cos(cam.get_fov()) / fovReduction;
/* FOV is in radians, pointAngle is from -1 to 1. FOV defines the angle of
* a cone by which objects can be clipped within. Through extensive
* testing, it appears the difference in units between these two values
* doesn't matter :D
*
* A variable, fovReduction, has been provided to help grow or shrink the
* FOV to account for the camera's viewport dimensions not fitting
* perfectly within the clipping cone.
* ______
* /clipping\
* /__________\
* || viewport ||
* ||__________||
* \ cone /
* \ ______ /
*/
return angleToPoint >= angleOfView;
}
@hamsham
Copy link
Author

hamsham commented Feb 3, 2016

Updated with a more accurate way to clip points out of a camera's FOV while taking into account multiple resolutions/aspect ratios.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment