// Smart TV resize shader
// Copyright (C) 2007 guest(r) - guest.r@gmail.com
// Can be distributed with the guest(r) pete_ogl2_guest_shaders_2.2(tm) shaderpack.

uniform vec4 OGL2InvSize;
uniform vec4 OGL2Size;
uniform sampler2D OGL2Texture;
uniform sampler2D OGL2TMU1;


float native_x = 1024.0*OGL2Size.z;
float native_y =  512.0*OGL2Size.w;
const float TV_x     = 720.0;
const float TV_y     = 576.0;

void main()
{
	
	// Calculating coordinates

	vec2 OGL2Pos = gl_TexCoord[0].xy*OGL2Size.xy;
	vec2 fp  = fract(OGL2Pos);
	vec2 d11 = floor(OGL2Pos)/OGL2Size.xy;
	vec2 d1  = vec2( OGL2InvSize.x, OGL2InvSize.y);
	vec2 dx  = vec2( OGL2InvSize.x, 0.0);
	vec2 dy  = vec2( 0.0, OGL2InvSize.y);


	// Reading the texels

	vec3 c00 = texture2D(OGL2Texture,d11).xyz;
	vec3 c20 = texture2D(OGL2Texture,d11+dx).xyz;
	vec3 c22 = texture2D(OGL2Texture,d11+d1).xyz;
	vec3 c02 = texture2D(OGL2Texture,d11+dy).xyz;
	vec3 dtm = texture2D(OGL2TMU1,gl_TexCoord[1].xy*vec2(TV_x/2048.0,TV_y/2048.0)).xyz;

	// calculating interpolation type

	float px = clamp(TV_x/native_x,1.0,2.0); 
	float py = clamp(TV_y/native_y,1.0,2.0); 

	vec2 x=vec2(pow(1.0-fp.x,px),pow(fp.x,px));
	vec2 y=vec2(pow(1.0-fp.y,py),pow(fp.y,py));


	// calculating final product	

	c00 = ((c00*x.x+c20*x.y)*y.x+(c02*x.x+c22*x.y)*y.y)/((x.x+x.y)*(y.x+y.y));

	float th = 0.3 - 0.25*length(dtm);

	gl_FragColor.xyz = mix(c00,dtm,th);
}
