/* COMPATIBILITY 
   - HLSL compilers
   - Cg   compilers
*/

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


struct VERTEX_OUTPUT {
  float4 position : POSITION;
  float4 vpos : TEXCOORD1;
  float2 texCoord : TEXCOORD0;
};

VERTEX_OUTPUT main_vertex
(
	float4 position	: POSITION,
	float2 texCoord : TEXCOORD0,
	float4 vpos : TEXCOORD1,
    uniform input IN,
   	uniform float4x4 modelViewProj
)
{
	VERTEX_OUTPUT OUT;
	OUT.position = mul(modelViewProj, position);
    OUT.vpos = OUT.position;
	OUT.texCoord = texCoord;
	return OUT;
}

struct output 
{
  float4 color : COLOR;
};

float4 rgbdistort(float2 tc, sampler2D tex)
{
   float chroma = 4;
   float shift = chroma / 256;
   float red = tex2D(tex, tc+shift).r;
   float green = tex2D(tex,tc).g;
   float blue = tex2D(tex,tc-shift).b;
   return float4(red,green ,blue , 1.0);
}


float seed_random (float2 coords, float frame_cnt)
{
   frame_cnt = cos(frame_cnt);
   float2 constant1 = frame_cnt * float2(142.0/11.0, 1017.0/13.0);
   float constant2 = frame_cnt * 481344.0 / 11.0;
   return clamp(frac(sin(dot(coords, constant1)) * constant2) + 0.2, 0.0 ,1.0);
}

output main_fragment(in VERTEX_OUTPUT VAR, uniform sampler2D decal : TEXUNIT0, uniform input IN) 
{
    //yes Cg is THIS retarded, passing position as texturecoord
	output OUT;
	VAR.vpos /= VAR.vpos.w;
    float2 p = VAR.texCoord;
    float frameLimit = 0.16;
    float frameShape = 0.44;
    float frameSharpness = 4.80;
    float interference = 0.43;
    const float base_brightness = 0.95;
	
	float f = (1.0 - VAR.vpos.x *VAR.vpos.x) * (1.0 - VAR.vpos.y * VAR.vpos.y);
	float frame = clamp(frameSharpness * (pow(f, frameShape) - frameLimit), 0.0, 1.0);
    float4 image = tex2D(decal, p);
    image = (image - 16.0/255.0) * (255.0/219.0);
	float rand = seed_random(p, IN.frame_count);
    float luminance = dot(image.rgb, float3(0.299, 0.587, 0.114));
    image.rgb = float3(luminance,luminance,luminance);
    float4 distortion = rgbdistort(p,decal);

    OUT.color = frame * (interference *distortion*rand+ image);
	return OUT;
}
