
// ------- UNIFORMS (SHADER CONSTS) -------
uniform sampler2D	hu_sSceneTexture0;
uniform sampler2D	hu_sSceneTexture1;
uniform sampler2D	hu_sDepthTexture0;
uniform vec4		hu_vCameraNearFar;

uniform vec4		u_vAlphaDistanceFunction;
uniform vec4		u_vAlphaDistanceFunctionOutline;
uniform vec4		u_vOutlineColor;
//uniform vec4		u_vColorModifier;

// ------- INTERPOLATORS (SHADER INPUTS) -------
varying vec2		v_vTex0UV;
varying vec2		v_vUV0;
varying vec2		v_vUV1;
varying vec2		v_vUV2;
varying vec2		v_vUV3;

// ------- FUNCTIONS ------- 

float GetLinearDepth(float fDepth)
{
	return (2.0*hu_vCameraNearFar.x)/(hu_vCameraNearFar.w - fDepth*hu_vCameraNearFar.z);
}

float GetDist(sampler2D sDepth, vec2 vCoords)
{
	float fDepth = texture2D(sDepth, vCoords).x;
	return GetLinearDepth(fDepth)*hu_vCameraNearFar.z;
}

void main(void)
{
	vec4 f = vec4(0.0);

	vec4 f1 = texture2D(hu_sSceneTexture1, v_vTex0UV);
	if (f1.b < 0.99)
	{
		vec4 f2 = texture2D(hu_sSceneTexture0, v_vTex0UV);
		if (f2.r < 0.99)
 		{
			float fDist = GetDist(hu_sDepthTexture0, v_vTex0UV);

  			bool b1 = f1.a == texture2D(hu_sSceneTexture1, v_vUV0).a && f1.a == texture2D(hu_sSceneTexture1, v_vUV1).a && 
  				f1.a == texture2D(hu_sSceneTexture1, v_vUV2).a && f1.a == texture2D(hu_sSceneTexture1, v_vUV3).a;
				
			bool b2 = f2.a <= texture2D(hu_sSceneTexture0, v_vUV0).a && f2.a <= texture2D(hu_sSceneTexture0, v_vUV1).a && 
				f2.a <= texture2D(hu_sSceneTexture0, v_vUV2).a && f2.a <= texture2D(hu_sSceneTexture0, v_vUV3).a;

			if (b2 || !b1)
			{	// inside
				float a = GetGrowingValue(u_vAlphaDistanceFunction, fDist);
				f = vec4(f2.rgb, a);
				//f = vec4(f2.rgb*0.001 + vec3(a), 1.0);
			}
			else
			{	// outline
				float a = GetGrowingValue(u_vAlphaDistanceFunctionOutline, fDist);			
				f = vec4(u_vOutlineColor.rgb, a*u_vOutlineColor.a);
			}
 		}
	}

	gl_FragColor = f;
}
