/// Author:		Nathaniel Meyer
///
/// Copyright:	Nutty Software
///				http://www.nutty.ca


#ifdef GL_ES
	precision highp float;
#endif


/// <summary>
/// Uniform variables.
/// <summary>
uniform vec2 ImageSize;
uniform vec2 TexelSize;
uniform vec4 Colour;
uniform sampler2D Sample0;


/// <summary>
/// Varying variables.
/// <summary>
varying vec2 vUv;


/// <summary>
/// Sobel kernels. Cannot initialize arrays in ES 2.0 :(
/// <summary>
//const float kernel1[9] = float[] (-1.0, 0.0, 1.0, -2.0, 0.0, 2.0, -1.0, 0.0, 1.0);
//const float kernel2[9] = float[] (-1.0, -2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 2.0, 1.0);


/// <summary>
/// Fragment shader entry.
/// <summary>
void main ()
{
	float kernel2[3];
	kernel2[0] = 1.0; kernel2[1] = 2.0; kernel2[2] = 1.0;

	// Apply Sobel kernels
	vec4 sobel1 = vec4(0.0, 0.0, 0.0, 0.0);
	vec4 sobel2 = vec4(0.0, 0.0, 0.0, 0.0);
	for (float y = -1.0; y <= 1.0; ++y)
	{
		for (float x = -1.0; x <= 1.0; ++x)
		{
			sobel1 += texture2D(Sample0, vUv + vec2(TexelSize.x * x, TexelSize.y * y)) * ((y == 0.0) ? (x * 2.0) : x);
			if ( y == -1.0 )
				sobel2 += texture2D(Sample0, vUv + vec2(TexelSize.x * x, TexelSize.y * y)) * -kernel2[int(x) + 1];
			else if ( y == 1.0 )
				sobel2 += texture2D(Sample0, vUv + vec2(TexelSize.x * x, TexelSize.y * y)) * kernel2[int(x) + 1];
		}
	}
	vec4 sobel = abs(sobel1) + abs(sobel2);
	sobel = clamp(sobel, 0.0, 1.0);
	sobel.w = (sobel.x + sobel.y + sobel.z) / 3.0;
	
	gl_FragColor = Colour * sobel;
}