vector=require("vector")

local gui={}

local gui_vertex_shader=[[
#version 450
layout (location=0) in vec2 pos;
layout (location=1) in vec2 texcoord;
uniform vec2 rpos;
uniform vec2 rsize;
out vec2 otexcoord;
void main()
{
	gl_Position=vec4(vec2(pos.x*rsize.x,pos.y*rsize.y)+rpos,0.0,1.0);
	otexcoord=rpos+texcoord*rsize;
}]]

local gui_fragment_shader=[[
#version 450
uniform vec4 color;
uniform vec2 rsize;
uniform vec2 rpos;
in vec2 otexcoord;
out vec4 ocolor;
float dist_Rect(vec2 pixel, vec2 rect_center, vec2 rect_size) {  
  vec2 d = abs(rect_center - pixel) - rect_size*0.5;
  return length(max(d,0.0));
}
float dist_RoundRect(vec2 pixel, vec2 rect_center, vec2 rect_size, float rect_round) {
    return dist_Rect(pixel, rect_center, rect_size - vec2(rect_round*2.0)) - rect_round;
}
void main()
{
    float d = dist_RoundRect(otexcoord, rpos+rsize*0.5, rsize,0.05);
    if(d<0)
		ocolor=vec4(color.rgb,color.a);
	else
		ocolor=vec4(0.0,0.0,0.0,0.0);
}]]

gui.init=function(w)
	local shader=w:shader(w:vertexshader(gui_vertex_shader),w:fragmentshader(gui_fragment_shader))
	local vd=shader:vertex("pos")
	vd:add(0.0,0.0)
	vd:add(1.0,0.0)
	vd:add(1.0,1.0)
	vd:add(1.0,1.0)
	vd:add(0.0,1.0)
	vd:add(0.0,0.0)
	local texcoord=shader:vertex("texcoord")
	texcoord:add(0.0,0.0)
	texcoord:add(1.0,0.0)
	texcoord:add(1.0,1.0)
	texcoord:add(1.0,1.0)
	texcoord:add(0.0,1.0)
	texcoord:add(0.0,0.0)
	local vbo=vd:vbo()
	local vbo2=texcoord:vbo()
	local vao=w:vao("triangles",vbo,vbo2)
	return setmetatable({win=w,vao=vao},{__index=gui})
end

gui.draw=function(self,x,y,w,h,color)
	local width,height=self.win:getsize()
	local oh=h/height*2
	self.vao:draw({color=vector:new(table.unpack(color)),rpos=vector:new((x+2)/width*2-1,-((y-2)/height*2-1)-oh),
	rsize=vector:new((w-4)/width*2,(h-4)/height*2)})
end

return gui