luastd/std/AABB.lua

81 lines
1.7 KiB
Lua

---@class AABB
local Vector3 = require("Vector3")
local AABB = {}
AABB.__index = AABB
function AABB.new(min, max)
return setmetatable({
min = min:copy(),
max = max:copy()
}, AABB)
end
function AABB:copy()
return AABB.new(self.min, self.max)
end
function AABB:__tostring()
return string.format("AABB(%s, %s)", tostring(self.min), tostring(self.max))
end
function AABB:expandTo(point)
return AABB.new(
Vector3.new(
math.min(self.min.x, point.x),
math.min(self.min.y, point.y),
math.min(self.min.z, point.z)
),
Vector3.new(
math.max(self.max.x, point.x),
math.max(self.max.y, point.y),
math.max(self.max.z, point.z)
)
)
end
function AABB:contains(point)
return point.x >= self.min.x and point.x <= self.max.x and
point.y >= self.min.y and point.y <= self.max.y and
point.z >= self.min.z and point.z <= self.max.z
end
function AABB:intersects(other)
return self.max.x >= other.min.x and self.min.x <= other.max.x and
self.max.y >= other.min.y and self.min.y <= other.max.y and
self.max.z >= other.min.z and self.min.z <= other.max.z
end
function AABB:union(other)
return AABB.new(
Vector3.new(
math.min(self.min.x, other.min.x),
math.min(self.min.y, other.min.y),
math.min(self.min.z, other.min.z)
),
Vector3.new(
math.max(self.max.x, other.max.x),
math.max(self.max.y, other.max.y),
math.max(self.max.z, other.max.z)
)
)
end
function AABB:center()
return self.min:add(self.max):div(2)
end
function AABB:size()
return self.max:sub(self.min)
end
function AABB:translated(v)
return AABB.new(
self.min:add(v),
self.max:add(v)
)
end
return AABB