#include "../../compat_includes.inc"
uniform COMPAT_Texture2D(decal) : TEXUNIT0;
uniform float4x4 modelViewProj;

struct out_vertex
{
	float4 position : COMPAT_POS;
	float2 texCoord : TEXCOORD0;
	float2 pix_no   : TEXCOORD1;
	float2 one      : TEXCOORD2;
#ifndef HLSL_4
	float4 Color    : COLOR;
#endif
};

out_vertex main_vertex(COMPAT_IN_VERTEX)
{
	out_vertex OUT;
#ifdef HLSL_4
	float4 position = VIN.position;
	float2 texCoord = VIN.texCoord;
#else
	OUT.Color = color;
#endif
	OUT.position = mul(modelViewProj, position);
	OUT.texCoord = texCoord;
	OUT.pix_no = texCoord * COMPAT_texture_size;
	OUT.one = 1.0 / COMPAT_texture_size;
	
	return OUT;
}

#pragma parameter NTSC_CRT_GAMMA "NTSC CRT Gamma" 2.5 0.0 10.0 0.1
#pragma parameter NTSC_DISPLAY_GAMMA "NTSC Display Gamma" 2.1 0.0 10.0 0.1

#ifdef PARAMETER_UNIFORM
uniform float NTSC_CRT_GAMMA;
uniform float NTSC_DISPLAY_GAMMA;
#else
#define NTSC_CRT_GAMMA 2.5
#define NTSC_DISPLAY_GAMMA 2.1
#endif

float4 ntsc_gauss_pass(float2 tex, COMPAT_Texture2D(s0), float2 one, float2 pix_no)
{
#define TEX(off) pow(COMPAT_Sample(s0, tex + float2(0.0, (off) * one.y)).rgb, float3(NTSC_CRT_GAMMA, NTSC_CRT_GAMMA, NTSC_CRT_GAMMA))

   float3 frame0 = TEX(-2.0);
   float3 frame1 = TEX(-1.0);
   float3 frame2 = TEX(0.0);
   float3 frame3 = TEX(1.0);
   float3 frame4 = TEX(2.0);

   float offset_dist = frac(pix_no.y) - 0.5;
   float dist0 =  2.0 + offset_dist;
   float dist1 =  1.0 + offset_dist;
   float dist2 =  0.0 + offset_dist;
   float dist3 = -1.0 + offset_dist;
   float dist4 = -2.0 + offset_dist;

   float3 scanline = frame0 * exp(-5.0 * dist0 * dist0);
   scanline += frame1 * exp(-5.0 * dist1 * dist1);
   scanline += frame2 * exp(-5.0 * dist2 * dist2);
   scanline += frame3 * exp(-5.0 * dist3 * dist3);
   scanline += frame4 * exp(-5.0 * dist4 * dist4);
   
   float3 gamma_mod = float3(1.0 / NTSC_DISPLAY_GAMMA, 1.0 / NTSC_DISPLAY_GAMMA, 1.0 / NTSC_DISPLAY_GAMMA);

   return float4(pow(float3(1.15, 1.15, 1.15) * scanline, gamma_mod), 1.0);
}

float4 main_fragment(COMPAT_IN_FRAGMENT) : COMPAT_Output
{
	return ntsc_gauss_pass(VOUT.texCoord, decal, VOUT.one, VOUT.pix_no);
}
COMPAT_END