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

/*
   Bob-and-ghost Deinterlacing
   Author: hunterk
   License: Public domain
   
   Note: This shader is designed to work with the typical interlaced output from an emulator, which displays both even and odd fields twice.
   As such, it is inappropriate for general video use unless the video has already been similarly woven beforehand.
*/

#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 one_pixel float2(1.0 / texture_size)
   
float4 bob_and_ghost(float2 texture_size, float2 video_size, float frame_count, float2 texCoord, COMPAT_Texture2D(decal))
{
	float4 res = float4(pow(COMPAT_Sample(decal, texCoord), 2.2));
	float4 color = float4(0,0,0,0);
	float y = 0.0;

	// assume anything with a vertical resolution greater than 400 lines is interlaced
	if (video_size.y > 400.0) 
	{
		y = texture_size.y * texCoord.y + frame_count;
		res = pow(float4(COMPAT_Sample(decal, texCoord + float2(0.0, one_pixel.y))), 2.2);
		color = pow((float4(COMPAT_Sample(decal, texCoord - float2(0.0, 0.5 * one_pixel.y))) + float4(COMPAT_Sample(decal, texCoord + float2(0.0, 0.5 * one_pixel.y)))) / 2.0, 2.2);
	}
	else
	{
		y = 2.000001 * texture_size.y * texCoord.y;
		color = res;
	}

	if (fmod(y, 2.0) > 0.99999) res = res;
	else res = float4(pow(COMPAT_Sample(decal, texCoord), 2.2));
	return float4(pow((res + color) / float4(2,2,2,2), float4(1.0 / 2.2, 1.0 / 2.2, 1.0 / 2.2, 1.0 / 2.2)));
}

float4 main_fragment(COMPAT_IN_FRAGMENT) : COMPAT_Output
{
	return bob_and_ghost(COMPAT_texture_size, COMPAT_video_size, COMPAT_frame_count, VOUT.texCoord, decal);
}
COMPAT_END
