/*
   Author: Themaister
   License: Public domain
*/

struct tex_coord
{
   float2 c00, c02, c20, c22;
};

struct input
{
   float2 video_size;
   float2 texture_size;
   float2 output_size;
};

void main_vertex
(
   float4 position : POSITION,
   out float4 oPosition : POSITION,
   uniform float4x4 modelViewProj,

   float4 color : COLOR,
   out float4 oColor : COLOR,

   float2 tex : TEXCOORD,
   out float2 oTex : TEXCOORD,

   uniform input IN,
   out tex_coord coords
)
{
   oPosition = mul(modelViewProj, position);
   oColor = color;
   oTex = tex;

   float2 texsize = IN.texture_size;
   float2 delta = 0.5 / texsize;
   float dx = delta.x;
   float dy = delta.y;

   coords = tex_coord (
      tex + float2(-dx, -dy),
      tex + float2(-dy, dy),
      tex + float2(dx, -dy),
      tex + float2(dx, dy)
   );
}

float3 grayscale(float3 color)
{
   return dot(color, float3(0.3, 0.59, 0.11));
}

float4 main_fragment (in tex_coord co, uniform input IN, float2 tex : TEXCOORD, uniform sampler2D s0 : TEXUNIT0) : COLOR
{
   float3 c00 = tex2D(s0, co.c00).xyz;
   float3 c02 = tex2D(s0, co.c02).xyz;
   float3 c11 = tex2D(s0, tex).xyz;
   float3 c20 = tex2D(s0, co.c20).xyz;
   float3 c22 = tex2D(s0, co.c22).xyz;

   float2 texsize = IN.texture_size;

   float3 first = mix(c00, c20, frac(tex.x * texsize.x + 0.5));
   float3 second = mix(c02, c22, frac(tex.x * texsize.x + 0.5));

   float3 res = mix(first, second, frac(tex.y * texsize.y + 0.5));
   float3 final = 5.0 * grayscale(abs(res - c11));
   return float4(saturate(final), 1.0);
}

