Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- enum AXIS {
- X_AXIS = 0,
- Y_AXIS = 1,
- Z_AXIS = 2
- };
- class AABB {
- public:
- glm::vec3 Min{};
- glm::vec3 Max{};
- AABB() = default;
- AABB(glm::vec3 min, glm::vec3 max);
- void Expand(const AABB& aabb);
- void Expand(const glm::vec3& point);
- AXIS GetLongestAxis() const;
- float IntersectsRay(const Ray& ray) const;
- float IntersectsAABB(const AABB& aabb) const;
- };
- AABB::AABB(glm::vec3 min, glm::vec3 max)
- : Min(min)
- , Max(max)
- {
- }
- void AABB::Expand(const AABB& aabb)
- {
- Min = glm::min(Min, aabb.Min);
- Max = glm::max(Max, aabb.Max);
- }
- void AABB::Expand(const glm::vec3& point)
- {
- Min = glm::min(Min, point);
- Max = glm::max(Max, point);
- }
- AXIS AABB::GetLongestAxis() const
- {
- glm::vec3 diag = Max - Min;
- if (diag.x > diag.y && diag.x > diag.z)
- return X_AXIS;
- else if (diag.y > diag.z)
- return Y_AXIS;
- else
- return Z_AXIS;
- }
- float AABB::IntersectsRay(const Ray& ray) const
- {
- // Ray vs AABB using 'Slab method'.
- // Source: https://tavianator.com/fast-branchless-raybounding-box-intersections/
- const float rxinv = 1.0f / ray.Dir().x;
- const float ryinv = 1.0f / ray.Dir().y;
- const float rzinv = 1.0f / ray.Dir().z;
- const float tx1 = (Min.x - ray.Origin().x) * rxinv;
- const float tx2 = (Max.x - ray.Origin().x) * rxinv;
- float tmin = std::min(tx1, tx2);
- float tmax = std::max(tx1, tx2);
- float ty1 = (Min.y - ray.Origin().y) * ryinv;
- float ty2 = (Max.y - ray.Origin().y) * ryinv;
- tmin = std::max(tmin, std::min(ty1, ty2));
- tmax = std::min(tmax, std::max(ty1, ty2));
- float tz1 = (Min.z - ray.Origin().z) * rzinv;
- float tz2 = (Max.z - ray.Origin().z) * rzinv;
- tmin = std::max(tmin, std::min(tz1, tz2));
- tmax = std::min(tmax, std::max(tz1, tz2));
- // No intersection
- if (tmax < tmin)
- return -1.0f;
- // Ray origin is inside the AABB
- if (tmin < Utils::Constants::ALMOST_ZERO)
- return tmax;
- return tmin;
- }
- float AABB::IntersectsAABB(const AABB& aabb) const
- {
- assert(false); // Not implemented yet.
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement