uniform sampler2D firstPass; 
uniform float poly[50];
uniform int poly_size;

varying vec2 v_texCoord;
varying vec4 v_fragmentColor;

bool isLeft(vec2 a, vec2 b, vec2 c){
     return ((b.x - a.x)*(c.y - a.y) - (b.y - a.y)*(c.x - a.x)) > 0;
}

//Calculate points distance to line
float sqrDistToLine(vec2 p, vec2 s, vec2 e){

	float px = e.x - s.x;
	float py = e.y - s.y;

	float squared = px*px + py*py;

	float u = ((p.x - s.x) * px + (p.y - s.y) * py)/ squared;

	if (u > 1) {
		u = 1;
	}else if( u < 0){
		u = 0;
	}

	float x = s.x + u * px;
	float y = s.y + u * py;

	float dx = x - p.x;
	float dy = y - p.y;

	return dx*dx + dy*dy;
}

float length_squared(vec2 v, vec2 w){
	float px = v.x - w.x;
	float py = v.y - w.y;

	return px*px + py*py;
}

float minimum_distance(vec2 v, vec2 w, vec2 p) {
  // Return minimum distance between line segment vw and point p
  float l2 = length_squared(v, w);  // i.e. |w-v|^2 -  avoid a sqrt
  if (l2 == 0.0) return distance(p, v);   // v == w case
  // Consider the line extending the segment, parameterized as v + t (w - v).
  // We find projection of point p onto the line. 
  // It falls where t = [(p-v) . (w-v)] / |w-v|^2
  float t = dot(p - v, w - v) / l2;
  if (t < 0.0) return distance(p, v);       // Beyond the 'v' end of the segment
  else if (t > 1.0) return distance(p, w);  // Beyond the 'w' end of the segment
  vec2 projection = v + t * (w - v);  // Projection falls on the segment
  return distance(p, projection);
}


//Remove pixels that are outside of the polygon
 void main(){	

	vec4 color = vec4(0,0,0,0);
	
	//Find the closest face of the polygon
	int closest = 0;
	float closest_sqr = 100000;
	for(int i = 0; i < poly_size; i+=2){
	 
	 	float x0 = 0;
		float y0 = 0;
		float x1 = 0;
		float y1 = 0;
		
		if(i == (poly_size-4)){
		
			x0 = poly[i];
			 y0 = poly[i+1];
			 x1 = poly[i+2];
			 y1 = poly[i+3];
		
			 float dist_to_face = minimum_distance(vec2(x0,y0),vec2(x1,y1),v_texCoord);
			
			 if(dist_to_face < closest_sqr){
				 closest_sqr = dist_to_face;
				 closest = i;
			 }
			 
			x0 = poly[i+2];
			y0 = poly[i+3];
			x1 = poly[0];
			y1 = poly[1];
			
			
		}else{
			x0 = poly[i];
			y0 = poly[i+1];
			x1 = poly[i+2];
			y1 = poly[i+3];
		}
	 
		float dist_to_face = minimum_distance(vec2(x0,y0),vec2(x1,y1),v_texCoord);
		if(dist_to_face < closest_sqr){
			closest_sqr = dist_to_face;
			closest = i;
		}
	
	 }
	 
	float x0 = poly[closest];
	float y0 = poly[closest+1];
	float x1 = poly[closest+2];
	float y1 = poly[closest+3];
	 
	bool is_left = isLeft(vec2(x0,y0),vec2(x1,y1),v_texCoord);
	
	if(is_left){
		color = vec4(1,1,1,1);
	}
	
	gl_FragColor = color;
}
