/*
   Paint filter from MariENB (third pass FXAA)
   (C)2012-2022 Marisa the Magician
*/

void main()
{
	vec2 coord = TexCoord;
	vec4 res = vec4(1.);
	vec2 bresl = textureSize(InputTexture,0);
	vec2 bof = 1./bresl;
	float fxaareducemul = 1./16.;
	float fxaareducemin = 1./128.;
	float fxaaspanmax = 4.;
	vec3 rgbNW = texture(InputTexture,coord+vec2(-1,-1)*bof).rgb;
	vec3 rgbNE = texture(InputTexture,coord+vec2(1,-1)*bof).rgb;
	vec3 rgbSW = texture(InputTexture,coord+vec2(-1,1)*bof).rgb;
	vec3 rgbSE = texture(InputTexture,coord+vec2(1,1)*bof).rgb;
	vec3 rgbM = texture(InputTexture,coord).rgb;
	vec3 luma = vec3(.299,.587,.114);
	float lumaNW = dot(rgbNW,luma);
	float lumaNE = dot(rgbNE,luma);
	float lumaSW = dot(rgbSW,luma);
	float lumaSE = dot(rgbSE,luma);
	float lumaM = dot(rgbM,luma);
	float lumaMin = min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));
	float lumaMax = max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));
	vec2 dir = vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));
	float dirReduce = max((lumaNW+lumaNE+lumaSW+lumaSE)*(.25*fxaareducemul),fxaareducemin);
	float rcpDirMin = 1./(min(abs(dir.x),abs(dir.y))+dirReduce);
	dir = min(vec2(fxaaspanmax,fxaaspanmax),max(vec2(-fxaaspanmax,-fxaaspanmax),dir*rcpDirMin))/bresl;
	vec3 rgbA = (1./2.)*(texture(InputTexture,coord+dir*(1./3.-.5)).rgb+texture(InputTexture,coord+dir*(2./3.-.5)).rgb);
	vec3 rgbB = rgbA*(1./2.)+(1./4.)*(texture(InputTexture,coord+dir*(0./3.-.5)).rgb+texture(InputTexture,coord+dir*(3./3.-.5)).rgb);
	float lumaB = dot(rgbB,luma);
	if ( (lumaB < lumaMin) || (lumaB > lumaMax) ) res.rgb = rgbA;
	else res.rgb = rgbB;
	FragColor = res;
}
