#version 450

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

layout(set = 0, binding = 0) uniform sampler2D tex;
layout(location = 0) in vec2 tex_pos;
layout(location = 1) 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);
	vec4 c = textureLod(tex, tex_pos, 0);
	if (has_alpha_multiplier) {
		if (src_has_alpha) {
			c *= data.mul;
		} else {
			c = vec4(c.rgb * data.mul, data.mul);
		}
	}
	float ra = rounding_alpha(geo_pos, size, corner_radius);
	c *= ra;
	out_color = c;
}
