varying vec2 v_texCoord;
uniform sampler2D u_texture;
uniform float GRADIENT_LENGHT;
uniform vec2 GRADIENT_ORIGO;

uniform int poly_size;
uniform float poly_x[50];
uniform float poly_y[50];
uniform float gradient_lenght_outline;

vec2 projectPoint(vec2 line1, vec2 line2, vec2 toProject)
{
	float m = (line2.y - line1.y) / (line2.x - line1.x);
	float b = line1.y - (m * line1.x);

	float x = (m * toProject.y + toProject.x - m * b) / (m * m + 1.0);
	float y = (m * m * toProject.y + m * toProject.x + b) / (m * m + 1.0);

	return vec2(x, y);
}

void main() {

	vec4 color = texture2D(u_texture, v_texCoord);

	if(poly_size > 0)
	{
		//Calculate this pixels min dist from shape outline
		float min_dist = 50000.0;
		for(int i = 1; i < poly_size; i++)
		{
			float X0 = poly_x[i];
			float Y0 = poly_y[i];

			float X1 = poly_x[i-1];
			float Y1 = poly_y[i-1];

			vec2 PROJECTED_P = projectPoint(vec2(X0,Y0), vec2(X1,Y1), v_texCoord);

			float dist = distance(PROJECTED_P, v_texCoord);
			if(dist < min_dist)
			{
				min_dist = dist;
			}
		}
		//Last line
		float X0 = poly_x[0];
		float Y0 = poly_y[0];

		float X1 = poly_x[poly_size-1];
		float Y1 = poly_y[poly_size-1];

		vec2 PROJECTED_P = projectPoint(vec2(X0,Y0), vec2(X1,Y1), v_texCoord);

		float dist = distance(PROJECTED_P, v_texCoord);
		if(dist < min_dist)
		{
			min_dist = dist;
		}


		float ratio = min_dist/gradient_lenght_outline;
		if(ratio > 1.0) ratio = 1.0;
		if(ratio < 0) ratio = 0;

		float a = color.a;
		color *= 0.5 + 0.5 * ratio;
		color.a = a;

		gl_FragColor = color;
	}
	else
	{

		if(color.r > 0)
		{
			vec4 color_half = color * 0.5;

			bool REVERSE_GRADIENT = false;
			float LENGTH = GRADIENT_LENGHT;
			if(GRADIENT_LENGHT < 0)
			{
				REVERSE_GRADIENT = true;
				LENGTH *= -1.0;
			}

			float dist = distance(GRADIENT_ORIGO,v_texCoord);
			float ratio = dist / (LENGTH);//1.0;
			if(ratio > 1.0) ratio = 1.0;

			if(REVERSE_GRADIENT) ratio = 1.0 - ratio;

			color = color_half + color_half * ratio;
			color.a = 1.0;
			gl_FragColor = color;
		}
		else
		{
			gl_FragColor = vec4(0);
		}
	}


}