precision highp float;

uniform sampler2D	uColorSampler;
uniform sampler2D	uIdSampler;
uniform vec3		uSelectedId;
uniform vec3		uHoveredId;
uniform vec2		uNormalizedPixelSize;
uniform float		uPulseFactor;

varying vec2 vTCoord;

void main(void) 
{
	vec3 lEdgeColor = vec3(1.);
	
	vec3 lColor = texture2D(uColorSampler, vTCoord).rgb;
	vec3 lId = texture2D(uIdSampler, vTCoord).rgb;
	vec3 lIdLeft = vec3(0.);
	vec3 lIdRight = vec3(0.);
	vec3 lIdTop = vec3(0.);
	vec3 lIdBottom = vec3(0.);
	bool lIsEdge = false;
	
	if(uSelectedId != vec3(0.) || uHoveredId != vec3(0.))
	{
		lIdLeft = texture2D(uIdSampler, vTCoord + uNormalizedPixelSize * vec2(-1.,0.)).rgb;
		lIdRight = texture2D(uIdSampler, vTCoord + uNormalizedPixelSize * vec2(1.,0.)).rgb;
		lIdTop = texture2D(uIdSampler, vTCoord + uNormalizedPixelSize * vec2(0.,1.)).rgb;
		lIdBottom = texture2D(uIdSampler, vTCoord + uNormalizedPixelSize * vec2(0.,-1.)).rgb;
		lIsEdge = lIdLeft != lId || lIdRight != lId || lIdTop != lId || lIdBottom != lId;
	}
	
	if(uSelectedId != vec3(0.))
	{
		bool lIsNearSelectedId = lId == uSelectedId || lIdLeft == uSelectedId || lIdRight == uSelectedId || lIdTop == uSelectedId || lIdBottom == uSelectedId;
		
		if(lIsNearSelectedId)
		{
			lColor = mix(lColor,vec3(0.8),abs(uPulseFactor)*0.4);
			if(lIsEdge)
				lColor = mix(lColor,vec3(0.),0.7);
		}
	}
	
	if(uHoveredId != vec3(0.))
	{
		bool lIsNearHoveredId = lId == uHoveredId || lIdLeft == uHoveredId || lIdRight == uHoveredId || lIdTop == uHoveredId || lIdBottom == uHoveredId;
		if(lIsNearHoveredId)
		{
			if(lIsEdge)
				lColor = mix(lColor,vec3(1.,1.,1.),0.7);
		}
		else
		{
			float lGrayScale = dot(lColor,vec3(0.299,0.587,0.114));
			lColor = mix(lColor,vec3(lGrayScale),0.8)*0.8;
		}
		
	}
	
	gl_FragColor = vec4(lColor,1.);
}