1 --[[ builtin/vector.lua ]]--
3 local function wrap(op, body_wrapper, ...)
4 return loadstring("return function(a, b) " .. body_wrapper(op, ...) .. "end")()
7 local function arith_mt(...)
9 __add = wrap("+", ...),
10 __sub = wrap("-", ...),
11 __mul = wrap("*", ...),
12 __div = wrap("/", ...),
13 __mod = wrap("%", ...),
19 local mt_vec2 = arith_mt(function(op)
21 if type(b) == "number" then
22 return vec2(a.x ]] .. op.. [[ b, a.y ]] .. op .. [[ b)
24 return vec2(a.x ]] .. op.. [[ b.x, a.y ]] .. op.. [[ b.y)
29 function mt_vec2:__neg()
30 return vec2(-self.x, -self.y)
33 function mt_vec2:__tostring()
34 return "(" .. self.x .. ", " .. self.y .. ")"
38 validate = function(self)
39 assert(type(self.x) == "number")
40 assert(type(self.y) == "number")
48 if type(a) == "number" then
56 setmetatable(o, mt_vec2)
62 local mt_vec3 = arith_mt(function(op)
64 if type(b) == "number" then
65 return vec3(a.x ]] .. op.. [[ b, a.y ]] .. op .. [[ b, a.z ]] .. op .. [[ b)
67 return vec3(a.x ]] .. op.. [[ b.x, a.y ]] .. op.. [[ b.y, a.z ]] .. op.. [[ b.z)
72 function mt_vec3:__neg()
73 return vec3(-self.x, -self.y, -self.z)
76 function mt_vec3:__tostring()
77 return "(" .. self.x .. ", " .. self.y .. ", " .. self.z .. ")"
81 validate = function(self)
82 assert(type(self.x) == "number")
83 assert(type(self.y) == "number")
84 assert(type(self.z) == "number")
89 function vec3(a, b, c)
92 if type(a) == "number" then
102 setmetatable(o, mt_vec3)
108 local mt_box = arith_mt(function(op)
109 return "return box(a.min " .. op .. " b, a.max " .. op .. " b)"
112 function mt_box:__neg()
113 return box(-self.min, -self.max)
116 function mt_box:__tostring()
117 return "[" .. self.min .. "; " .. self.max .. "]"
121 contains = function(a, b)
122 if type(b) == "number" or b.x then
123 return a.min <= b and a.max >= b
125 return a.min <= b.min and a.max >= b.max
128 validate = function(self)
129 if type(self.min) == "number" then
130 assert(type(self.max) == "number")
132 assert(not self.min.z == not self.max.z)
142 if type(a) == "number" or a.x then
150 setmetatable(o, mt_box)