/* COMPATIBILITY 
   - HLSL compilers
   - Cg   compilers
*/

/*
   Scale2xPlus shader 

           - Copyright (C) 2007 guest(r) - guest.r@gmail.com

           - License: GNU-GPL  


   The Scale2x algorithm:

           - Scale2x Homepage: http://scale2x.sourceforge.net/

           - Copyright (C) 2001, 2002, 2003, 2004 Andrea Mazzoleni 
		
           - License: GNU-GPL  

*/

/*
	VERTEX_SHADER
*/
void main_vertex
(
	float4 position	: POSITION,
	float2 texCoord : TEXCOORD0,

	uniform float4x4 modelViewProj,

	out float4 oPosition	: POSITION,
	out float2 otexCoord	: TEXCOORD
)
{
	oPosition = mul(modelViewProj, position);
	otexCoord = texCoord;
}

/*
	FRAGMENT SHADER
*/

struct output
{
	float4 color	: COLOR;
};

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

output main_fragment(float2 texCoord: TEXCOORD0, uniform sampler2D decal : TEXUNIT0)
{

   float2 ps = float2(0.999/512.0, 0.999/448.0);
	half2 dx = half2(ps.x, 0.0);
	half2 dy = half2(0.0, ps.y);

	float2 pixcoord = texCoord/ps;
	float2 fp	= frac(pixcoord);
	float2 d11	= texCoord-fp*ps;

	// Reading the texels

	half3 B = tex2D(decal,d11-dy).xyz;
	half3 D = tex2D(decal,d11-dx).xyz;
	half3 E = tex2D(decal,d11   ).xyz;
	half3 F = tex2D(decal,d11+dx).xyz;
	half3 H = tex2D(decal,d11+dy).xyz;
	
	half3 E0 = D == B && B != H && D != F ? D : E;
	half3 E1 = B == F && B != H && D != F ? F : E;
	half3 E2 = D == H && B != H && D != F ? D : E;
	half3 E3 = H == F && B != H && D != F ? F : E;


	// Product interpolation
	output OUT;
	OUT.color = float4((E3*fp.x+E2*(1-fp.x))*fp.y+(E1*fp.x+E0*(1-fp.x))*(1-fp.y),1); 
	return OUT;
}
