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

void main()
{
	vec2 coord = TexCoord;
	vec4 res = texture(InputTexture,coord);
	vec2 bresl = textureSize(InputTexture,0);
	vec2 bof = 1./bresl;
	float n = 16.;
	vec3 m[4] = vec3[](vec3(0.),vec3(0.),vec3(0.),vec3(0.)),
		s[4] = vec3[](vec3(0.),vec3(0.),vec3(0.),vec3(0.)),
		c;
	int i, j;
	for ( i=-3; i<=0; i++ ) for ( j=-3; j<=0; j++ )
	{
		c = texture(InputTexture,coord+vec2(i,j)*bof).rgb;
		m[0] += c;
		s[0] += c*c;
	}
	for ( i=-3; i<=0; i++ ) for ( j=0; j<=3; j++ )
	{
		c = texture(InputTexture,coord+vec2(i,j)*bof).rgb;
		m[1] += c;
		s[1] += c*c;
	}
	for ( i=0; i<=3; i++ ) for ( j=-3; j<=0; j++ )
	{
		c = texture(InputTexture,coord+vec2(i,j)*bof).rgb;
		m[2] += c;
		s[2] += c*c;
	}
	for ( i=0; i<=3; i++ ) for ( j=0; j<=3; j++ )
	{
		c = texture(InputTexture,coord+vec2(i,j)*bof).rgb;
		m[3] += c;
		s[3] += c*c;
	}
	float min_sigma2 = 1e+2, sigma2;
	for ( i=0; i<4; i++ )
	{
		m[i] /= n;
		s[i] = abs(s[i]/n-m[i]*m[i]);
		sigma2 = s[i].r+s[i].g+s[i].b;
		if ( sigma2 >= min_sigma2 ) continue;
		min_sigma2 = sigma2;
		res.rgb = m[i];
	}
	FragColor = res;
}
