/* COMPATIBILITY 
   - HLSL compilers
   - Cg   compilers
   - FX11 compilers
*/

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

struct out_vertex
{
	float4 position : COMPAT_POS;
	float2 texCoord : TEXCOORD0;
#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;
	
	return OUT;
}

#define TEX2D(c) COMPAT_Sample(decal,(c))
#define PI 3.141592653589
#define phase 0.0
#define gamma 2.5
#define distortion 0.00

float2 barrelDistortion(float2 coord) 
{
  float2 cc = coord - 0.5;
  float dist = dot(cc, cc);
  return coord + cc * (dist + distortion * dist * dist) * distortion;
}

float4 tv_highcontrast_hd(float2 output_size, float2 texCoord, COMPAT_Texture2D(decal))
{
	float2 rubyInputSize = float2(0.999/512.0, 0.999/448.0);
	float2 rubyOutputSize = output_size;
	float2 rubyTextureSize = float2(0.999/768.0, 0.999/480.0);
   	
	float2 xy = barrelDistortion(texCoord.xy);
	float2 one = 1.0/rubyTextureSize;
	xy = xy + float2(0.0 , -0.5 * (phase + (1-phase) * rubyInputSize.y/rubyOutputSize.y) * one.y);
	float4 texels[8];
   texels[0] = TEX2D(xy + float2(-one.x,0.0));
   texels[1] = TEX2D(xy);
   texels[2] = TEX2D(xy + float2(one.x, 0.0));
   texels[3] = TEX2D(xy + float2(2 * one.x, 0.0));
   texels[4] = TEX2D(xy + float2(-one.x,one.y));
   texels[5] = TEX2D(xy + float2(0.0, one.y));
   texels[6] = TEX2D(xy + one);
   texels[7] = TEX2D(xy + float2(2 * one.x, one.y));


	float2 uv_ratio = frac(xy*rubyTextureSize);
	
	float4 col, col2;
	
	float4 coeffs = float4(1.0 + uv_ratio.x, uv_ratio.x, 1.0 - uv_ratio.x, 2.0 - uv_ratio.x);
	coeffs = (sin(PI * coeffs) * sin(PI * coeffs / 2.0)) / (coeffs * coeffs);
	coeffs = coeffs / (coeffs.x+coeffs.y+coeffs.z+coeffs.w);
	
	col  = clamp(coeffs.x * texels[0] + coeffs.y * texels[1] + coeffs.z * texels[2] + coeffs.w * texels[3], 0.0, 1.0);
	col2 = clamp(coeffs.x * texels[4] + coeffs.y * texels[5] + coeffs.z * texels[6] + coeffs.w * texels[7], 0.0, 1.0);
	col = pow(col, gamma);
	col2 = pow(col2, gamma);
	
	float4 wid = 2 + 2 * pow(col, 4.0);
	float4 weights = uv_ratio.y/0.3;
	weights = 0.51*exp(-pow(weights*sqrt(2/wid),wid))/0.3/(0.6+0.2*wid);
	wid = 2 + 4 * pow(col2,4.0);
	float4 weights2 = (1.0-uv_ratio.y)/0.3;
	weights2 = 0.51*exp(-pow(weights2*sqrt(2/wid),wid))/0.3/(0.6+0.2*wid);
	
	float4 mcol = 1.0;
	if ( fmod(xy.x*rubyOutputSize.x,2.0) < 1.0)
		mcol.g = 0.7;
	else
		mcol.rb = 0.7;
	
	float4 final = pow(mcol*(col * weights + col2 * weights2), 1.0/2.2);
	
	return final;   	
}

float4 main_fragment(COMPAT_IN_FRAGMENT) : COMPAT_Output
{
	return tv_highcontrast_hd(COMPAT_output_size, VOUT.texCoord, decal);
}
COMPAT_END