summaryrefslogtreecommitdiff
path: root/gfx/frustum.cpp
blob: 865dcde8bc99174215352f60d31fa3894a1555da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include "frustum.h"
#include <algorithm>
#include <collections.h>
#include <glm/ext/matrix_transform.hpp>

static constexpr auto PLANES = std::array {0, 1, 2} * std::array {1.F, -1.F};

Frustum::Frustum(const GlobalPosition3D & pos, const glm::mat4 & view, const glm::mat4 & projection) :
	position {pos}, view {view}, projection {projection}, viewProjection {}, inverseViewProjection {}, planes {}
{
	updateCache();
}

void
Frustum::updateView(const glm::mat4 & newView)
{
	view = newView;
	updateCache();
}

bool
Frustum::contains(const BoundingBox & aabb) const
{
	static constexpr auto EXTENT_CORNER_IDXS = [] {
		using Extent = GlobalPosition3D BoundingBox::*;
		constexpr auto EXTENTS = std::array {&BoundingBox::min, &BoundingBox::max};
		std::array<glm::vec<3, Extent>, 2ZU * 2ZU * 2ZU> out {};
		std::ranges::copy(std::views::cartesian_product(EXTENTS, EXTENTS, EXTENTS)
						| std::views::transform(
								std::make_from_tuple<glm::vec<3, Extent>, std::tuple<Extent, Extent, Extent>>),
				out.begin());
		return out;
	}();

	const std::array<RelativePosition4D, 8> corners
			= EXTENT_CORNER_IDXS * [relativeAabb = aabb - position](auto idxs) -> glm::vec4 {
		return {(relativeAabb.*(idxs.x)).x, (relativeAabb.*(idxs.y)).y, (relativeAabb.*(idxs.z)).z, 1.F};
	};
	return std::ranges::none_of(planes, [&corners](const auto & frustumPlane) {
		return (std::ranges::all_of(corners, [&frustumPlane](const auto & corner) {
			return glm::dot(frustumPlane, corner) < 0.F;
		}));
	});
}

void
Frustum::updateCache()
{
	viewProjection = projection * view;
	inverseViewProjection = glm::inverse(viewProjection);
	std::ranges::transform(PLANES, planes.begin(), [vpt = glm::transpose(viewProjection)](const auto & idxs) {
		const auto [idx, sgn] = idxs;
		return vpt[3] + (vpt[idx] * sgn);
	});
}