libcruft-util/geom/frustum.hpp

66 lines
1.8 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) {
// find the distance to the point, if it's positive it's inside
// the frustum.
const auto d = max (
p.coefficients * b.lo.template redim<S+1> (1),
p.coefficients * b.hi.template redim<S+1> (1)
);
if (sum (d) < 0)
return false;
}
return true;
}
};
#endif