libcruft-util/geom/frustum.hpp

69 lines
1.9 KiB
C++

/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2018 Danny Robson <danny@nerdcruft.net>
*/
#ifndef CRUFT_UTIL_GEOM_FRUSTUM_HPP
#define CRUFT_UTIL_GEOM_FRUSTUM_HPP
#include "../matrix.hpp"
#include "plane.hpp"
#include "aabb.hpp"
#include <array>
#include <cstddef>
namespace util::geom {
/// a viewing frustrum comprised of 4 axis planes, a near plane, and a far
/// plane. it may describe something other than a perspective projection
/// (eg, an orthographic projection)
template <typename ValueT>
struct frustum {
explicit frustum (const matrix<4,4,ValueT>&);
std::array<plane<3,ValueT>, 6> planes;
};
using frustum3f = frustum<float>;
/// tests whether a frustum and an aabb overlap
///
/// XXX: there may be occasional false positives.
template <size_t S, typename T>
bool
intersects (const frustum<T> &f, const aabb<S,T> &b)
{
for (const auto &p: f.planes) {
const auto n = normal (p);
const auto positive = n > 0;
const auto lo = select (positive, b.lo, b.hi);
const auto hi = select (positive, b.hi, b.lo);
if (dot (n, lo) + p.coefficients[S] > 0)
return false; // OUTSIDE
if (dot (n, hi) + p.coefficients[S] >= 0)
return true; //INTERSECT
}
// INSIDE
return true;
}
};
#endif