/*
   RetroFX palette reduction from MariENB
   (C)2012-2023 Marisa the Magician
*/
vec3 rgb2hsv( vec3 c )
{
	vec4 K = vec4(0.,-1./3.,2./3.,-1.);
	vec4 p = (c.g<c.b)?vec4(c.bg,K.wz):vec4(c.gb,K.xy);
	vec4 q = (c.r<p.x)?vec4(p.xyw,c.r):vec4(c.r,p.yzx);
	float d = q.x-min(q.w,q.y);
	float e = 1.e-10;
	return vec3(abs(q.z+(q.w-q.y)/(6.*d+e)),d/(q.x+e),q.x);
}
vec3 hsv2rgb( vec3 c )
{
	vec4 K = vec4(1.,2./3.,1./3.,3.);
	vec3 p = abs(fract(c.xxx+K.xyz)*6.-K.www);
	return c.z*mix(K.xxx,clamp(p-K.xxx,0.,1.),c.y);
}

void main()
{
	vec2 coord = TexCoord;
	vec4 res = texture(InputTexture,coord);
	vec3 hsv = rgb2hsv(res.rgb);
	hsv.y = clamp(hsv.y*palsat,0.,1.);
	hsv.z = pow(max(hsv.z,0.),palpow);
	res.rgb = hsv2rgb(hsv);
	ivec2 dcoord = ivec2(int(coord.x*sfact.x)%dsize,int(coord.y*sfact.y)%dsize+doffset);
	res.rgb += (texelFetch(DitherTexture,dcoord,0).x-.5)*paldither;
	vec3 lc = clamp(floor(res.rgb*63.),0.,63.);
	ivec2 lcoord = ivec2(int(lc.r),int(lc.g)+int(lc.b)*64);
	lcoord.x += 64*palnum;
	res.rgb = texelFetch(PalLUTTexture,lcoord,0).rgb;
	FragColor = res;
}
