#pragma parameter percent "Interlacing Scanline Bright %" 0.0 0.0 1.0 0.05
#pragma parameter force_240p "Force 240p Mode" 0.0 0.0 1.0 1.0
#pragma parameter top_field_first "Top Field First Enable" 0.0 0.0 1.0 1.0
#ifdef PARAMETER_UNIFORM
uniform float percent;
uniform float force_240p;
uniform float top_field_first;
#else
#define percent 0.0
#define force_240p 0.0
#define top_field_first 0.0
#endif

/*
   Interlacing
   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.
   This shader will un-weave the image, resulting in a standard, alternating-field interlacing.
*/

/* 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;
}

float4 interlacing(float2 texture_size, float2 video_size, float frame_count, float2 texCoord, COMPAT_Texture2D(decal))
{
   float4 res = COMPAT_Sample(decal, texCoord);
   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 * !force_240p) + top_field_first;
   else
      y = 2.000001 * texture_size.y * texCoord.y + top_field_first;

   if (fmod(y, 2.0) > 0.99999) return res;
   else
      return float4(percent,percent,percent,percent) * res;
}

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