/* COMPATIBILITY
   - Cg   compilers
*/

/*
   Sharpness shader - by Hyllian - 2013

   Public Domain  

   use it at 1x scale.
*/


const static float sharpness = 0.08;  /**** Useful Range: 0.0 to 1.0  ****/

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


struct out_vertex {
    float4 position : POSITION;
    float4 color    : COLOR;
    float2 texCoord : TEXCOORD0;
    float4 t1       : TEXCOORD1;
    float4 t2       : TEXCOORD2;
    float4 t3       : TEXCOORD3;
};



/*    VERTEX_SHADER    */
out_vertex main_vertex
(
    float4 position : POSITION,
    float4 color    : COLOR,
    float2 texCoord : TEXCOORD0,

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

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

    float2 ps = float2(1.0/IN.texture_size.x, 1.0/IN.texture_size.y);
    float dx = ps.x;
    float dy = ps.y;

    //    A1 B1 C1
    // A0  A  B  C C4
    // D0  D  E  F F4
    // G0  G  H  I I4
    //    G5 H5 I5

    OUT.texCoord = texCoord;
    OUT.t1 = texCoord.xxxy + float4( -dx, 0, dx,    -dy); //  A  B  C
    OUT.t2 = texCoord.xxxy + float4( -dx, 0, dx,      0); //  D  E  F
    OUT.t3 = texCoord.xxxy + float4( -dx, 0, dx,     dy); //  G  H  I

    return OUT;
}


/*    FRAGMENT SHADER    */
float4 main_fragment(in out_vertex VAR, uniform sampler2D decal : TEXUNIT0, uniform input IN) : COLOR
{
    float3 E  = tex2D(decal, VAR.texCoord).rgb;

    float3 color = 8*E;
    float3 B = tex2D(decal, VAR.t1.yw).rgb;
    float3 D = tex2D(decal, VAR.t2.xw).rgb;
    float3 F = tex2D(decal, VAR.t2.zw).rgb;
    float3 H = tex2D(decal, VAR.t3.yw).rgb;
    color -= tex2D(decal, VAR.t1.xw).rgb;
    color -= B;
    color -= tex2D(decal, VAR.t1.zw).rgb;
    color -= D;
    color -= F;
    color -= tex2D(decal, VAR.t3.xw).rgb;
    color -= H;
    color -= tex2D(decal, VAR.t3.zw).rgb;

    color = ((E!=F && E!=D) || (E!=B && E!=H)) ? saturate(E + color*sharpness) : E; 

    return float4(color, 1.0);
}

