#version 450

#include "../frag_spec_const.glsl"
#include "rounded_fill.common.glsl"

layout(location = 0) in vec2 geo_pos;
layout(location = 0) out vec4 out_color;

float rounding_alpha(vec2 coords, vec2 size, vec4 corner_radius) {
	if (coords.x < 0.0 || coords.y < 0.0 || coords.x > size.x || coords.y > size.y) {
		return 0.0;
	}
	vec2 center;
	float radius;
	if (coords.x < corner_radius.x && coords.y < corner_radius.x) {
		radius = corner_radius.x;
		center = vec2(radius, radius);
	} else if (coords.x > size.x - corner_radius.y && coords.y < corner_radius.y) {
		radius = corner_radius.y;
		center = vec2(size.x - radius, radius);
	} else if (coords.x > size.x - corner_radius.z && coords.y > size.y - corner_radius.z) {
		radius = corner_radius.z;
		center = vec2(size.x - radius, size.y - radius);
	} else if (coords.x < corner_radius.w && coords.y > size.y - corner_radius.w) {
		radius = corner_radius.w;
		center = vec2(radius, size.y - radius);
	} else {
		return 1.0;
	}
	float half_px = 0.5 / data.scale;
	float dist = distance(coords, center);
	return 1.0 - smoothstep(radius - half_px, radius + half_px, dist);
}

void main() {
	vec2 size = vec2(data.size_x, data.size_y);
	vec4 corner_radius = vec4(data.corner_radius_tl, data.corner_radius_tr, data.corner_radius_br, data.corner_radius_bl);
	float outer_alpha = rounding_alpha(geo_pos, size, corner_radius);
	float alpha = outer_alpha;
	if (data.border_width > 0.0) {
		vec2 inner_coords = geo_pos - vec2(data.border_width);
		vec2 inner_size = size - vec2(2.0 * data.border_width);
		vec4 inner_radius = max(corner_radius - vec4(data.border_width), vec4(0.0));
		float inner_alpha = rounding_alpha(inner_coords, inner_size, inner_radius);
		alpha = outer_alpha * (1.0 - inner_alpha);
	}
	out_color = data.color * alpha;
}
