diff options
author | ubq323 <ubq323@ubq323.website> | 2025-02-18 21:15:17 +0000 |
---|---|---|
committer | ubq323 <ubq323@ubq323.website> | 2025-02-18 21:15:17 +0000 |
commit | bcc60fda65fd583a331a0a21c4d47092c95329eb (patch) | |
tree | 397789cf3e5925cb520ea075a3caac6182fbd9d6 /rect.lua | |
parent | f1492b52414b6f2ad6cfff45375c08677feab18c (diff) |
rect
Diffstat (limited to 'rect.lua')
-rw-r--r-- | rect.lua | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/rect.lua b/rect.lua new file mode 100644 index 0000000..ca87e49 --- /dev/null +++ b/rect.lua @@ -0,0 +1,65 @@ +local class = require'r.class' +local Pos = require'r.pos' +local Rect = class() +function Rect.from_coords(cls, x0, y0, x1, y1) + assert(x0<x1,"x coords interchanged") + assert(y0<y1,"y coords interchanged") + return setmetatable({ + tl=Pos:make(x0,y0), + br=Pos:make(x1,y1), + x0=x0, y0=y0, x1=x1, y1=y1, + w=x1-x0, h=y1-y0, + }, cls) +end +function Rect.from_pos(cls, tl, br) + assert(tl.x<br.x,"x coords interchanged") + assert(tl.y<br.y,"y coords interchanged") + return setmetatable({ + tl=tl, br=br, + x0=tl.x, y0=tl.y, x1=br.x, y1=br.y, + w=br.x-tl.x, h=br.y-tl.y, + }, cls) +end +function Rect.from_xywh(cls, x0,y0, width,hight) + assert(0<width, "nonpositive width") + assert(0<hight, "nonpositive hight") + return setmetatable({ + tl=Pos:make(x0,y0), + br=Pos:make(x0+width,y0+hight), + x0=x0, y0=y0, + x1=x0+width, + y1=y0+hight, + w=width, h=hight, + }, cls) +end +function Rect.from_centre_dims(cls, centre, width, hight) + assert(0<width, "nonpositive width") + assert(0<hight, "nonpositive hight") + local x0,x1 = centre.x-width/2, centre.x+width/2 + local y0,y1 = centre.y-hight/2, centre.y+hight/2 + return setmetatable({ + tl=Pos:make(x0,y0), + br=Pos:make(x1,y1), + x0=x0,y0=y0,x1=x1,y1=y1, + w=width, h=hight, + }, cls) +end + +function Rect.has(self, point) + return self.x0 <= point.x and point.x <= self.x1 + and self.y0 <= point.y and point.y <= self.y1 +end + +function Rect.vals(self) + return self.x0, self.y0, self.w, self.h +end + +function Rect.draw(self, mode) + love.graphics.rectangle(mode or 'line', self:vals()) +end + +function Rect.__tostring(self) + return tostring(self.tl).."\u{25af}"..tostring(self.br) +end + +return Rect |