shader_type spatial;

// Aggiunto 'ambient_light_disabled' per proteggere i colori piatti
// Mantenuto 'diffuse_toon' per ottimizzare i calcoli della luce interna di Godot
render_mode diffuse_toon, specular_disabled, ambient_light_disabled;

group_uniforms Albedo_Settings;
uniform vec4 albedo_color : source_color = vec4(1.0);
uniform sampler2D albedo_texture : source_color, filter_nearest;
uniform bool use_texture = true;
uniform vec2 uv_scale = vec2(1.0, 1.0);
// NUOVO PARAMETRO: Slider per scorrere la palette in verticale
uniform float palette_shift_y : hint_range(0.0, 1.0) = 0.0;

group_uniforms Toon_Lighting;
uniform float light_steps : hint_range(1.0, 10.0, 1.0) = 3.0;
uniform float step_softness : hint_range(0.01, 1.0) = 0.1;
uniform vec4 shadow_color : source_color = vec4(0.4, 0.4, 0.6, 1.0);
uniform float shadow_offset : hint_range(-1.0, 1.0) = 0.0;

// NUOVO PARAMETRO IMPORTATO: Intensità delle ombre proiettate su questo materiale
uniform float cast_shadow_strength : hint_range(0.0, 1.0) = 0.6;

group_uniforms Emission_Settings;
uniform vec4 emission_color : source_color = vec4(0.0, 0.0, 0.0, 1.0);
uniform float emission_energy : hint_range(0.0, 16.0) = 0.0;

void fragment() {
	// 1. Albedo (Colore base dell'oggetto)
	// APPLICATO LO SHIFT SULL'ASSE Y SULLE UV
	vec2 final_uv = (UV * uv_scale) + vec2(0.0, palette_shift_y);
	vec4 tex = texture(albedo_texture, final_uv);
	
	vec3 base_color = albedo_color.rgb;
	if (use_texture) base_color *= tex.rgb;
	
	// Passiamo il colore crudo a Godot. 
	// Godot si occuperà di moltiplicarlo per la luce alla fine.
	ALBEDO = base_color;
	
	// 2. Emission
	EMISSION = emission_color.rgb * emission_energy;
}

// --- NUOVA LOGICA LUCE INTEGRATA ---
void light() {
	float shadow_factor = mix(1.0 - cast_shadow_strength, 1.0, ATTENUATION);
	float n_dot_l = dot(NORMAL, LIGHT);
	
	float intensity = clamp((n_dot_l * shadow_factor) + shadow_offset, 0.0, 1.0);
	
	float raw_step = intensity * light_steps;
	float lower_step = floor(raw_step);
	float fract_step = fract(raw_step);
	float lerp_step = smoothstep(0.5 - step_softness, 0.5 + step_softness, fract_step);
	float stepped_intensity = (lower_step + lerp_step) / light_steps;
	
	vec3 light_part = vec3(1.2);
	vec3 shaded_part = shadow_color.rgb;
	
	vec3 final_toon_light = mix(shaded_part, light_part, clamp(stepped_intensity, 0.0, 1.0));
	
	// Porchiddio Michele
	float cutoff_mask = smoothstep(0.0, 0.05, ATTENUATION);
	
	DIFFUSE_LIGHT += (final_toon_light * LIGHT_COLOR) * cutoff_mask;
}