/* COMPATIBILITY 
   - HLSL compilers
   - Cg   compilers
*/

struct input
{
  float2 video_size;
  float2 texture_size;
  float2 output_size;
  float frame_count;
  float frame_direction;
  float frame_rotation;
};


struct VERTEX_OUTPUT {
  float4 position : POSITION;
  float2 texCoord : TEXCOORD0;
};


VERTEX_OUTPUT main_vertex
(
	float4 position	: POSITION,
	float2 texCoord : TEXCOORD0,

   	uniform float4x4 modelViewProj,
	uniform input IN
)
{
	VERTEX_OUTPUT OUT;

	OUT.position = mul(modelViewProj, position);
	OUT.texCoord = texCoord;

	return OUT;
}

float4 ToonConfig;
float threshold = 0.001;

struct output 
{
  float4 color    : COLOR;
};

struct VERTEX_INPUT
{
	float4 position : POSITION;
	float2 CT : TEXCOORD0;
};

#define NUM 9

output main_fragment(in VERTEX_INPUT VAR, uniform sampler2D decal : TEXUNIT0, uniform input IN) 
{
	output OUT;

	ToonConfig.xyz = 4; //RGB colours
	float4 Color = tex2D( decal, VAR.CT.xy );

	Color.r = round(Color.r*ToonConfig.r)/ToonConfig.r;
	Color.g = round(Color.g*ToonConfig.g)/ToonConfig.g;
	Color.b = round(Color.b*ToonConfig.b)/ToonConfig.b;
	const float2 c[NUM] =
	{
		float2(-0.0078125, 0.0078125), 
		float2( 0.00 ,     0.0078125),
		float2( 0.0078125, 0.0078125),
		float2(-0.0078125, 0.00 ),
		float2( 0.0,       0.0),
		float2( 0.0078125, 0.007 ),
		float2(-0.0078125,-0.0078125),
		float2( 0.00 ,    -0.0078125),
		float2( 0.0078125,-0.0078125),
	};

	int i;
	float3 col[NUM];
	for (i=0; i < NUM; i++)
	{
		col[i] = tex2D(decal, VAR.CT.xy + 0.2*c[i]);
	}

	float3 rgb2lum = float3(0.30, 0.59, 0.11);
	float lum[NUM];
	for (i = 0; i < NUM; i++)
	{
		lum[i] = dot(col[i].xyz, rgb2lum);
	}
	float x = lum[2]+  lum[8]+2*lum[5]-lum[0]-2*lum[3]-lum[6];
	float y = lum[6]+2*lum[7]+  lum[8]-lum[0]-2*lum[1]-lum[2];
	float edge =(x*x + y*y < threshold)? 1.0:0.0;
	Color.rgb *= edge;

	OUT.color = Color;
	return OUT;
}
