// AntiAliased Nearest Neighbor
// by jimbo1qaz and wareya

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

#define NOT(fl) (1-fl)
#define YES(fl) fl

float4 vpow(float4 n, float e)
{
    return float4(pow(n.x, e), pow(n.y, e), pow(n.z, e), pow(n.w, e));
}

float4 getLQV(float3 mine) {
    return float4
    ( mine.r
    , mine.g
    , mine.b
    ,(mine.r + mine.g + mine.b)/3);
}

float3 fromLQV(float4 mine) {
    float f = mine.w/(mine.r + mine.g + mine.b)*3;
    return float3(mine.rgb)*f;
}

float3 percent(float ssize, float tsize, float coord) {
    float minfull = (coord*tsize - 0.5) /tsize*ssize;
    float maxfull = (coord*tsize + 0.5) /tsize*ssize;

    float realfull = floor(maxfull);

    if (minfull > realfull) {
        return float3(1, (realfull+0.5)/ssize, (realfull+0.5)/ssize);
    }

    return float3(
            (maxfull - realfull) / (maxfull - minfull),
            (realfull-0.5) / ssize,
            (realfull+0.5) / ssize
        );
}

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

   float4 color : COLOR,
   out float4 oColor : COLOR,

   float2 texCoord : TEXCOORD,
   out float2 oTexCoord : TEXCOORD,

   uniform input IN
)
{
   oPosition = mul(modelViewProj, position);
   oColor = color;
   oTexCoord = texCoord;
}

float4 main_fragment (in float2 texCoord : TEXCOORD, in sampler2D s0 : TEXUNIT0, uniform input IN) : COLOR
{
    float cheapsrgb = 2.1;
    float gamma = 3.0;
    vec3 xstuff = percent(IN.texture_size.x, IN.output_size.x, texCoord.x);
    vec3 ystuff = percent(IN.texture_size.y, IN.output_size.y, texCoord.y);

    float xkeep = xstuff[0];
    float ykeep = ystuff[0];
    
    // get points to interpolate across, in linear rgb
    float4 a = getLQV(vpow(tex2D(s0,float2(xstuff[1],ystuff[1])), cheapsrgb).rgb);
    float4 b = getLQV(vpow(tex2D(s0,float2(xstuff[2],ystuff[1])), cheapsrgb).rgb);
    float4 c = getLQV(vpow(tex2D(s0,float2(xstuff[1],ystuff[2])), cheapsrgb).rgb);
    float4 d = getLQV(vpow(tex2D(s0,float2(xstuff[2],ystuff[2])), cheapsrgb).rgb);
    
    // use perceptual gamma for luminance component
    a.w = pow(a.w, 1/gamma);
    b.w = pow(b.w, 1/gamma);
    c.w = pow(c.w, 1/gamma);
    d.w = pow(d.w, 1/gamma);
    
    // interpolate
    float4 gammaLQVresult =
        NOT(xkeep)*NOT(ykeep)*a +
        YES(xkeep)*NOT(ykeep)*b +
        NOT(xkeep)*YES(ykeep)*c +
        YES(xkeep)*YES(ykeep)*d;
    
    // change luminance gamma back to linear
    float4 LQVresult = gammaLQVresult;
    LQVresult.w = pow(gammaLQVresult.w, gamma);
    
    // convert back to srgb; lqv -> lrgb -> srgb
    float4 c1 = vpow(float4(fromLQV(LQVresult), 1), 1/cheapsrgb);
      return c1;
}
