#ifdef EXTERNAL
#extension GL_OES_EGL_image_external : require
#endif

precision mediump float;

varying vec2 v_texcoord;
varying vec2 v_geo;

#ifdef EXTERNAL
uniform samplerExternalOES tex;
#else
uniform sampler2D tex;
#endif
#ifdef ALPHA_MULTIPLIER
uniform float alpha;
#endif
uniform vec2 size;
uniform vec4 corner_radius;
uniform float scale;

float rounding_alpha(vec2 coords, vec2 half_size, vec4 radii) {
	float radius;
	vec2 center;

	if (coords.x < half_size.x && coords.y < half_size.y) {
		radius = radii.x; // top-left
		center = vec2(radius, radius);
	} else if (coords.x >= half_size.x && coords.y < half_size.y) {
		radius = radii.y; // top-right
		center = vec2(size.x - radius, radius);
	} else if (coords.x >= half_size.x && coords.y >= half_size.y) {
		radius = radii.z; // bottom-right
		center = vec2(size.x - radius, size.y - radius);
	} else {
		radius = radii.w; // bottom-left
		center = vec2(radius, size.y - radius);
	}

	if (radius == 0.0)
		return 1.0;

	float dist = distance(coords, center);
	float half_px = 0.5 / scale;
	return 1.0 - smoothstep(radius - half_px, radius + half_px, dist);
}

void main() {
	vec2 half_size = size / 2.0;
	float ra = rounding_alpha(v_geo, half_size, corner_radius);

#ifdef ALPHA

#ifdef ALPHA_MULTIPLIER
	gl_FragColor = texture2D(tex, v_texcoord) * alpha * ra;
#else // !ALPHA_MULTIPLIER
	gl_FragColor = texture2D(tex, v_texcoord) * ra;
#endif // ALPHA_MULTIPLIER

#else // !ALPHA

#ifdef ALPHA_MULTIPLIER
	vec4 tc = texture2D(tex, v_texcoord);
	gl_FragColor = vec4(tc.rgb * alpha * ra, alpha * ra);
#else // !ALPHA_MULTIPLIER
	vec4 tc = texture2D(tex, v_texcoord);
	gl_FragColor = vec4(tc.rgb * ra, ra);
#endif // ALPHA_MULTIPLIER

#endif // ALPHA
}
