vkmEngine 1.0.15
A C++ game engine · vkmengine.com
Loading...
Searching...
No Matches
bounds.h
1#pragma once
2
3#include <optional>
4
5#include <glm/glm.hpp>
6#include <glm/gtc/constants.hpp>
7
8namespace Vkm::Engine::Math {
9
10// Minimum squared extent for a valid AABB (1e-4 squared). glm::epsilon is too
11// small for world coordinates in [-1000, 1000].
12inline constexpr float BOUNDS_EPSILON_SQ = 1e-8f;
13
17struct AABB {
18 glm::vec3 min{0.0f};
19 glm::vec3 max{0.0f};
20
26 bool valid() const noexcept {
27 const glm::vec3 extent = max - min;
28 return glm::dot(extent, extent) > BOUNDS_EPSILON_SQ;
29 }
30
31 glm::vec3 center() const noexcept { return (min + max) * 0.5f; }
32
33 glm::vec3 halfExtent() const noexcept { return (max - min) * 0.5f; }
34};
35
43inline AABB transform(const glm::mat4& matrix, const AABB& local) {
44 AABB world;
45 world.min = glm::vec3(matrix[3]);
46 world.max = glm::vec3(matrix[3]);
47
48 for (int j = 0; j < 3; ++j) {
49 const glm::vec3 col(matrix[j]);
50 const glm::vec3 a = col * local.min[j];
51 const glm::vec3 b = col * local.max[j];
52 world.min += glm::min(a, b);
53 world.max += glm::max(a, b);
54 }
55 return world;
56}
57
61struct Ray {
62 glm::vec3 origin{0.0f};
63 glm::vec3 direction{0.0f, 0.0f, -1.0f};
64};
65
76inline Ray rayThroughNdc(const glm::mat4& invViewProj, const glm::vec2& ndc) {
77 glm::vec4 nearPoint = invViewProj * glm::vec4(ndc, -1.0f, 1.0f);
78 glm::vec4 farPoint = invViewProj * glm::vec4(ndc, 1.0f, 1.0f);
79 nearPoint /= nearPoint.w;
80 farPoint /= farPoint.w;
81 return Ray{glm::vec3(nearPoint), glm::normalize(glm::vec3(farPoint - nearPoint))};
82}
83
94inline bool rayIntersectsAABB(
95 const glm::vec3& origin,
96 const glm::vec3& invDir,
97 const AABB& box,
98 float& tHit
99) noexcept {
100 const glm::vec3 t0 = (box.min - origin) * invDir;
101 const glm::vec3 t1 = (box.max - origin) * invDir;
102
103 const glm::vec3 tMinV = glm::min(t0, t1);
104 const glm::vec3 tMaxV = glm::max(t0, t1);
105
106 float tMin = glm::max(glm::max(tMinV.x, tMinV.y), tMinV.z);
107 float tMax = glm::min(glm::min(tMaxV.x, tMaxV.y), tMaxV.z);
108
109 // Inside the box tMin is behind, so the hit is the exit; a negative tMin would
110 // let a box enclosing the camera undercut every genuine hit in a ranking.
111 tHit = tMin > 0.0f ? tMin : tMax;
112 return tMax >= tMin && tMax >= 0.0f;
113}
114
123inline std::optional<glm::vec3> rayHitsLevel(const Ray& ray, float y) noexcept {
124 if (glm::abs(ray.direction.y) < glm::epsilon<float>()) return std::nullopt;
125 const float t = (y - ray.origin.y) / ray.direction.y;
126 if (t <= 0.0f) return std::nullopt;
127 return ray.origin + ray.direction * t;
128}
129
130} // namespace Vkm::Engine::Math
An axis-aligned box.
Definition bounds.h:17
bool valid() const noexcept
True when the box has non-degenerate extent.
Definition bounds.h:26
A half-line in world space.
Definition bounds.h:61
glm::vec3 direction
Unit length.
Definition bounds.h:63