uniform vec4 grad_color;
uniform vec2 grad_pos;
uniform vec2 tex_size;

uniform float gradient_r;

uniform int poly_size;

uniform float poly_x[80];
uniform float poly_y[80];

uniform sampler2D u_texture;
varying vec2 v_texCoord;
varying vec4 v_fragmentColor;

float distSqr(vec2 p0, vec2 p1)
{
	return (p1.x - p0.x)*(p1.x - p0.x) + (p1.y - p0.y)*(p1.y - p0.y);
}

float distToLine(vec2 p0, vec2 p1, vec2 p)
{
	float l2 = distSqr(p0,p1); 

	if (l2 == 0.0) return distance(p0, p); 

	float t = dot(p - p0, (p1 - p0)) / l2;

	if (t < 0.0) return distance(p, p0);  

	else if (t > 1.0) return distance(p, p1); 

	vec2 projection = p0 + (p1 - p0)*t;

	//return projection;
	return distance(p, projection);
}

void main()
{
	vec4 color = texture2D(u_texture, v_texCoord);

	if(color.a > 0)
	{
		float min_dist = 100000;
		float max_r = gradient_r/tex_size.x; //TEMPPI

		for(int i = 0; i < poly_size; i++)
		{
			float x0 = poly_x[i];
			float y0 = poly_y[i];

			float dist = distance(vec2(x0,y0), v_texCoord);

			if(dist < min_dist)
			{
				min_dist = dist;
			}
		}

		if(min_dist > max_r) min_dist = max_r;
		min_dist /= max_r;

		float ratio = min_dist;
	
		color = grad_color *1.0  + grad_color * 0.4*ratio;

		color.a = 0.9;

		if(grad_color.a > 0.6)
		{
			color.a = 1.0;
		}

		//vec4 final_color = vec4(color.r, color.g, color.b, color.a);

		vec3 color_m = vec3(color.r, color.g, color.b) * 1.0; //1.2

		vec4 final_color = vec4(color_m.r, color_m.g, color_m.b, color.a);

		gl_FragColor = final_color;
		return;
	}

	gl_FragColor = vec4(0);

}
