#version 450

/*
   
   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; either version 2
   of the License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/

layout(push_constant) uniform Push
{
	vec4 SourceSize;
	vec4 OriginalSize;
	vec4 OutputSize;
	uint FrameCount;
	float gammaout,warpX,warpY,vignette,vign,corners,beam1,beam2,
    scanline1,scanline2,interlace,progress,boost1,boost2,sat,flick;
    } params;

layout(std140, set = 0, binding = 0) uniform UBO
{
    mat4 MVP;
    float DOTMASK_STRENGTH,maskDark,maskLight,shadowMask,bgr,maskl,maskh,gl,
    ntsc,TEMP,size;
} global;

#pragma parameter bogus_geom "[ GEOMETRY ]" 0.0 0.0 0.0 0.0

#pragma parameter warpX "Curvature X" 0.03 0.00 0.20 0.01 
#pragma parameter warpY "Curvature Y" 0.05 0.00 0.20 0.01
#pragma parameter corners "Corners cut On/Off" 1.0 0.0 1.0 1.0
#pragma parameter vignette "Vignette On/Off" 1.0 0.0 1.0 1.0
#pragma parameter vign "Vignette Strength" 0.10 0.0 0.50 0.01

#pragma parameter bogus_masks "[ MASK SETTINGS ]" 0.0 0.0 0.0 0.0

#pragma parameter shadowMask "Mask Style 0:cgwg,1-4:Lottes,5:Sin,Slot2" 1.0 -1.0 6.0 1.0
#pragma parameter size "Mask Size" 1.0 1.0 2.0 1.0
#pragma parameter maskl "Mask Low" 0.9 0.0 1.0 0.05
#pragma parameter maskh "Mask High" 0.6 0.0 1.0 0.05
#pragma parameter bgr "RGB/BGR subpixels" 1.0 0.0 1.0 1.0
#pragma parameter DOTMASK_STRENGTH "CGWG Dot Mask Strength" 0.7 0.0 1.0 0.05
#pragma parameter maskDark "Lottes maskDark" 0.5 0.0 2.0 0.1
#pragma parameter maskLight "Lottes maskLight" 1.5 0.0 2.0 0.1

#pragma parameter bogus_scan "[ SCANLINE SETTINGS ]" 0.0 0.0 0.0 0.0

#pragma parameter interlace "Interlace On/Off" 1.0 0.0 1.0 1.0
#pragma parameter progress "Force 240p" 0.0 0.0 1.0 1.0  
#pragma parameter beam1 "Scanline Beam Low" 6.0 1.0 15.0 0.5
#pragma parameter beam2 "Scanline Beam High" 8.0 1.0 15.0 0.5
#pragma parameter scanline1 "Scanline Low" 1.35 0.5 3.0 0.05
#pragma parameter scanline2 "Scanline High" 1.05 0.5 3.0 0.05

#pragma parameter bogus_col "[ COLOR SETTINGS ]" 0.0 0.0 0.0 0.0

#pragma parameter ntsc "NTSC Colors" 1.0 0.0 1.0 1.0
#pragma parameter TEMP "Color Temperature in Kelvins"  6500.0 1031.0 12047.0 72.0
#pragma parameter gammaout "Gamma Out" 2.2 1.0 4.0 0.05
#pragma parameter sat "Saturation" 1.0 0.0 2.0 0.01
#pragma parameter boost1 "Boost Dark Colors" 1.45 1.0 2.0 0.05
#pragma parameter boost2 "Boost Bright Colors" 1.25 1.0 2.0 0.05
#pragma parameter gl "Glow Strength" 0.15 0.0 1.0 0.01
#pragma parameter flick "Flicker Strength" 2.0 0.0 10.0 0.1

#define scanline1 params.scanline1
#define beam2 params.beam2
#define beam1 params.beam1
#define flick params.flick
#define progress params.progress
#define interlace params.interlace
#define maskLight global.maskLight
#define maskDark global.maskDark
#define DOTMASK_STRENGTH global.DOTMASK_STRENGTH
#define bgr global.bgr
#define maskh global.maskh
#define maskl global.maskl
#define size global.size
#define shadowMask global.shadowMask
#define vign params.vign
#define vignette params.vignette
#define corners params.corners
#define warpY params.warpY
#define warpX params.warpX
#define scanline2 params.scanline2
#define ntsc global.ntsc
#define TEMP global.TEMP
#define gammaout params.gammaout
#define sat params.sat
#define boost1 params.boost1
#define boost2 params.boost2
#define gl global.gl

#define pi 3.141592
#define SourceSize params.SourceSize
#define OutputSize params.OutputSize
#define FrameCount params.FrameCount
#define OriginalSize params.OriginalSize
#define timer float(FrameCount*2.0)
#define flicker sin(timer)*flick/1000.0
#define mod_factor vTexCoord.x * SourceSize.x * OutputSize.x/size / SourceSize.x

#pragma stage vertex
layout(location = 0) in vec4 Position;
layout(location = 1) in vec2 TexCoord;
layout(location = 0) out vec2 vTexCoord;

void main()
{
   gl_Position = global.MVP * Position;
   vTexCoord = TexCoord*1.0001;
}

#pragma stage fragment
layout(location = 0) in vec2 vTexCoord;
layout(location = 0) out vec4 FragColor;
layout(set = 0, binding = 2) uniform sampler2D Source;



vec3 Mask(vec2 pos){
  vec3 mask=vec3(maskDark,maskDark,maskDark);
 if (shadowMask == 0.0)
{
   float mask = 1.0 - DOTMASK_STRENGTH;
   //Output pixels are alternately tinted green and magenta
   vec3 dotMaskWeights = mix(vec3(1.0, mask, 1.0),
                          vec3(mask, 1.0, mask),
                          floor(mod(mod_factor, 2.0)));
   return dotMaskWeights;
}

// Very compressed TV style shadow mask.
    else if (shadowMask == 1.0) {
    float line=maskLight;
    float odd=0.0;
    if(fract(pos.x/6.0)<0.5)odd=1.0;
    if(fract((pos.y+odd)/2.0)<0.5)line=maskDark;  
    pos.x=fract(pos.x/3.0);
   
    if(pos.x<0.333)     bgr == 1.0? mask.b=maskLight : mask.r=maskLight;
    else if(pos.x<0.666)mask.g=maskLight;
    else                bgr == 1.0? mask.r=maskLight : mask.b=maskLight;
    mask*=line;  
  } 

// Aperture-grille.
  else if (shadowMask == 2.0) {
    pos.x=fract(pos.x/3.0);

    if(pos.x<0.333)     bgr == 1.0? mask.b=maskLight : mask.r=maskLight;
    else if(pos.x<0.666)mask.g=maskLight;
    else                bgr == 1.0? mask.r=maskLight : mask.b=maskLight;
  } 

// Stretched VGA style shadow mask (same as prior shaders).
  else if (shadowMask == 3.0) {
    pos.x+=pos.y*3.0;
    pos.x=fract(pos.x/6.0);

    if(pos.x<0.333)     bgr == 1.0? mask.b=maskLight : mask.r=maskLight;
    else if(pos.x<0.666)mask.g=maskLight;
    else                bgr == 1.0? mask.r=maskLight : mask.b=maskLight;
  }

// VGA style shadow mask.
  else if (shadowMask == 4.0) {
    pos.xy=floor(pos.xy*vec2(1.0,0.5));
    pos.x+=pos.y*3.0;
    pos.x=fract(pos.x/6.0);

    if(pos.x<0.333)     bgr == 1.0? mask.b=maskLight : mask.r=maskLight;
    else if(pos.x<0.666)mask.g=maskLight;
    else                bgr == 1.0? mask.r=maskLight : mask.b=maskLight;
  }

  else if (shadowMask == 5.0)
  {
    float MaskR = sin(OutputSize.x*vTexCoord.x*pi*1.0+pi*0.00000+vTexCoord.y*OutputSize.y*pi*0.5)*0.5+0.5;
    float MaskG = sin(OutputSize.x*vTexCoord.x*pi*1.0+pi*1.33333+vTexCoord.y*OutputSize.y*pi*0.5)*0.5+0.5;
    float MaskB = sin(OutputSize.x*vTexCoord.x*pi*1.0+pi*0.66667+vTexCoord.y*OutputSize.y*pi*0.5)*0.5+0.5;
    
    vec3 Mask; bgr == 1.0? Mask = vec3(MaskB,MaskG,MaskR) : Mask = vec3(MaskR,MaskG,MaskB) ;
    
    Mask = min(Mask*2.0,1.0);
    
    return vec3(Mask);
}

   else if (shadowMask == 6.0) {
    float line=maskLight;
    float odd=0.0;
    if(fract(pos.x/4.0)<0.5)odd=1.0;
    if(fract((pos.y+odd)/2.0)<0.5)line=maskDark;  
    pos.x=fract(pos.x/2.0);
   
    if(pos.x<0.5)     mask.rb=vec2(maskLight) ;
    else              mask.g=maskLight;
    mask*=line;  
  } 
else if (shadowMask == -1.0) {
mask = vec3(1.0);
}

  return mask;
}

// Lanczos filter
float sinc(float x)
{
    return sin(x * pi) / (x * pi); 
}

float lanczosWeight(float n, float N)
{
    return ((n == 0.0)   ? (1.0) : 
            (abs(n) < N) ? sinc(n) * sinc(n / N) : 
            0.0);
}

vec3 Lanczos(vec2 uv, vec2 InvResolution)
{
    vec2 center = (floor(uv * SourceSize.xy) + 0.5) * InvResolution;
    vec2 offset = fract(uv * SourceSize.xy) - 0.5;

    vec3 col = vec3(0.0);
    float weight = 0.0;

    // Anti-ringing: track local min/max neighborhood
    vec3 localMin = vec3( 10e6 );
    vec3 localMax = vec3(-10e6 );

    for (float x = -2.0; x < 3.0; x += 1.0)
    {
        for (float y = -1.0; y < 2.0; y += 1.0)
        {
            vec3 smpl = texture(Source, center + vec2(x, y) * InvResolution).rgb;

            // Track min/max neighborhood bounds
            localMin = min(localMin, smpl);
            localMax = max(localMax, smpl);

            float wx = lanczosWeight(x - offset.x, 2.0);
            float wy = lanczosWeight(y - offset.y, 1.0);
            float w = wx * wy;

            col += smpl * w;
            weight += w;
        }
    }

    col /= weight;

    // Anti-ringing clamp
    col = clamp(col, localMin, localMax);

    return col;
}

// Distortion of scanlines
vec2 Warp(vec2 pos)
{
    pos  = pos*2.0-1.0;    
    pos *= vec2(1.0 + (pos.y*pos.y)*warpX, 1.0 + (pos.x*pos.x)*warpY);
    return pos*0.5 + 0.5;
}

//Vignette
mat3 vignet()
{
    vec2 vpos = vTexCoord;

    vpos *= 1.0 - vpos.xy;
    float vig = vpos.x * vpos.y * 50.0;
    vig = min(pow(vig, vign), 1.0); 
    if (vignette == 0.0) vig=1.0;
   
    return mat3(vig, 0, 0,
                 0,   vig, 0,
                 0,    0, vig);
}

float sw(float y, float l)
{
    float scan = mix(beam1, beam2, y);
    float tmp = mix(scanline1, scanline2, l);
    float ex = y*tmp;
    return exp2(-scan*ex*ex);
}


vec3 glow(vec2 pos)
{
    vec3 col = vec3(0.0);
    float x = SourceSize.z;
    float y = SourceSize.w;
    float sum = 0.0;
for (float x=-2; x<3; x +=1.0)
{
    for (float y=-2; y<3; y +=1.0)
    {
    float wy = exp(-0.4*y*y);    
    float wx = exp(-0.15*x*x);    
    float w = wx + wy;    
    col += w*texture(Source,pos + vec2(x,y)*SourceSize.zw).rgb;
    sum += w;
    }
}
    col /= sum;
    return col*col*gl;
}

vec3 DecodeGamma(vec3 color, float gamma)
{
    color = clamp(color, 0.0, 1.0);
    color.r = (color.r <= 0.00313066844250063) ?
    color.r * 12.92 : 1.055 * pow(color.r, 1.0 / gamma) - 0.055;
    color.g = (color.g <= 0.00313066844250063) ?
    color.g * 12.92 : 1.055 * pow(color.g, 1.0 / gamma) - 0.055;
    color.b = (color.b <= 0.00313066844250063) ?
    color.b * 12.92 : 1.055 * pow(color.b, 1.0 / gamma) - 0.055;

    return color;
}

mat3 sRGB_to_NTSC = mat3(
  1.0143, -0.0165, 0.0307,
0.0723,  0.9125,  0.0173,
0.0175,  -0.0419, 1.1101

);


float saturate(float v) 
    { 
        return clamp(v, 0.0, 1.0);       
    }

vec3 ColorTemp(float temperatureInKelvins)
{
    vec3 retColor;
    temperatureInKelvins = clamp(temperatureInKelvins, 1000.0, 40000.0) / 100.0;
    
    if (temperatureInKelvins <= 66.0)
    {
        retColor.r = 1.0;
        retColor.g = saturate(0.39008157876901960784 * log(temperatureInKelvins) - 0.63184144378862745098);
    }
    else
    {
        float t = temperatureInKelvins - 60.0;
        retColor.r = saturate(1.29293618606274509804 * pow(t, -0.1332047592));
        retColor.g = saturate(1.12989086089529411765 * pow(t, -0.0755148492));
    }
    
    if (temperatureInKelvins >= 66.0)
        retColor.b = 1.0;
    else if(temperatureInKelvins <= 19.0)
        retColor.b = 0.0;
    else
        retColor.b = saturate(0.54320678911019607843 * log(temperatureInKelvins - 10.0) - 1.19625408914);

    return retColor;
}



void main()
{
    vec2 pos = Warp(vTexCoord);
    vec2 uv = pos * vec2(0.5, 2.0);
    vec2 InvResolution = SourceSize.zw;

    float f = fract(0.5+pos.y*SourceSize.y);
    float f2 = fract(pos.y*SourceSize.y);

//handle interlacing
if (OriginalSize.y > 400.0 && interlace == 1.0) 
    {
    f = fract(0.5+pos.y*SourceSize.y/2.0);
    f2 = fract((pos.y-0.5)*SourceSize.y/2.0);
    sin(timer) > 0.0 ? f=f : f=f2;
    }
if (OriginalSize.y > 400.0 && interlace == 0.0 && progress == 1.0)
    {
    f = fract(0.5+pos.y*SourceSize.y/2.0);
    }

    vec3 res = Lanczos(pos, InvResolution);
    float lumsat  = dot(vec3(0.3,0.6,0.1),res);
    res = mix(vec3(lumsat),res,sat);

    if (ntsc == 1.0) {
        res = sRGB_to_NTSC*res;
    }
	res = clamp(res,vec3(0.0),vec3(1.0));
    res += glow(pos);
    res *= ColorTemp(TEMP);
    float lumscan = max(max(res.r,res.g),res.b);

    res = res*sw(f,lumscan) + res*sw(abs(1.0-f),lumscan);
    float msk = mix(maskl,maskh,lumscan);
    res *= mix(vec3(1.0),Mask(floor(vTexCoord.xy * OutputSize.xy/size + vec2(0.5))),msk);

    res *= mix(boost1,boost2,lumsat);
    res = pow(res,vec3(1.0/gammaout));
    res *= vignet();
    res += flicker;

    vec2 corn = min(pos,vec2(1.0)-pos); // This is used to mask corners
    corn.x = 0.0001/corn.x;             
    if (corners == 1.0 && corn.y <= corn.x || corn.x < 0.0001 ) res = vec3(0.0);

    FragColor = vec4(res,1.0);
}
