shader_type canvas_item;
render_mode unshaded;

// Graphics v2 post pass (GfxLook.post_layer): drawn over the finished 3D view, behind the HUD.
//  1. light contrast-adaptive sharpen (crisper textures / edges after MSAA + FSR)
//  2. vibrance: lifts dull colours more than already-saturated ones (no neon skin)
//  3. soft S-curve contrast around the mid grey (kills the milky, low-contrast look)
//  4. split tone: cool violet shadows, warm sunny highlights (STYLE_GUIDE §2-3)
//  5. soft vignette (old post_vignette look, a bit lighter)
uniform sampler2D screen : hint_screen_texture, filter_linear, repeat_disable;
uniform float sharpen : hint_range(0.0, 1.0) = 0.22;
uniform float vibrance : hint_range(0.0, 1.0) = 0.28;
uniform float contrast : hint_range(0.0, 0.5) = 0.24;
// highlight shoulder: channels above 0.72 are compressed (bright plazas / sand keep their texture)
uniform float rolloff : hint_range(0.0, 1.0) = 0.45;
uniform vec3 shadow_tint = vec3(0.975, 0.97, 1.04);
uniform vec3 highlight_tint = vec3(1.03, 1.01, 0.97);
uniform float vig_strength : hint_range(0.0, 1.0) = 0.1;
uniform float vig_radius : hint_range(0.2, 1.5) = 0.9;
uniform vec4 vig_tint : source_color = vec4(0.25, 0.2, 0.4, 1.0);

float luma(vec3 c) {
	return dot(c, vec3(0.299, 0.587, 0.114));
}

void fragment() {
	vec2 uv = SCREEN_UV;
	vec3 c = texture(screen, uv).rgb;
	if (sharpen > 0.0) {
		vec2 px = SCREEN_PIXEL_SIZE;
		vec3 n = texture(screen, uv + vec2(0.0, -px.y)).rgb;
		vec3 s = texture(screen, uv + vec2(0.0, px.y)).rgb;
		vec3 e = texture(screen, uv + vec2(px.x, 0.0)).rgb;
		vec3 w = texture(screen, uv + vec2(-px.x, 0.0)).rgb;
		vec3 mn = min(c, min(min(n, s), min(e, w)));
		vec3 mx = max(c, max(max(n, s), max(e, w)));
		// CAS-style: sharpen less where local contrast is already high (no halos on outlines / text)
		vec3 amp = clamp(min(mn, 1.0 - mx) / max(mx, vec3(0.001)), 0.0, 1.0);
		amp = sqrt(amp) * sharpen;
		vec3 d = c * 4.0 - (n + s + e + w);
		c = clamp(c + d * amp * 0.25, mn, mx);
	}
	float l = luma(c);
	float sat = max(c.r, max(c.g, c.b)) - min(c.r, min(c.g, c.b));
	c = mix(vec3(l), c, 1.0 + vibrance * (1.0 - clamp(sat * 1.6, 0.0, 1.0)));
	c = clamp(c, 0.0, 1.0);
	// S-curve (smoothstep) blended in: deeper darks, brighter highlights, mid grey kept
	c = mix(c, c * c * (3.0 - 2.0 * c), contrast);
	c = mix(c, 0.72 + (c - 0.72) * 0.55, rolloff * step(0.72, c));
	float l2 = luma(c);
	c *= mix(shadow_tint, highlight_tint, smoothstep(0.15, 0.85, l2));
	vec2 p = (SCREEN_UV - 0.5) * vec2(SCREEN_PIXEL_SIZE.y / SCREEN_PIXEL_SIZE.x, 1.0) * 1.1;
	float v = smoothstep(vig_radius * 0.45, vig_radius, length(p)) * vig_strength;
	c = mix(c, vig_tint.rgb, v);
	COLOR = vec4(c, 1.0);
}
