shader_type spatial;
render_mode blend_mix, cull_back;

uniform sampler2D albedo_tex : source_color, filter_nearest;
uniform float emission_strength : hint_range(0.0, 20.0) = 6.0;
uniform float flicker_speed : hint_range(0.0, 10.0) = 3.0;
uniform float flicker_amount : hint_range(0.0, 1.0) = 0.4;
// Hue thresholds for detecting "flame" pixels
uniform float flame_min_r : hint_range(0.0, 1.0) = 0.6;
uniform float flame_max_g : hint_range(0.0, 1.0) = 0.6;
uniform float flame_max_b : hint_range(0.0, 1.0) = 0.3;

void fragment() {
	vec4 tex = texture(albedo_tex, UV);
	ALBEDO = tex.rgb;
	ALPHA = tex.a;
	ALPHA_SCISSOR_THRESHOLD = 0.01;

	// Detect orange-ish flame pixels: high red, medium green, low blue
	bool is_flame = tex.r > flame_min_r && tex.g < flame_max_g && tex.b < flame_max_b && tex.a > 0.5;

	if (is_flame) {
		// Animated flicker using layered sine waves
		float t = TIME * flicker_speed;
		float flicker = sin(t) * 0.5 + sin(t * 2.3 + 1.7) * 0.3 + sin(t * 5.1 + 3.2) * 0.2;
		float intensity = emission_strength * (1.0 + flicker * flicker_amount);

		// Warm up the emission color slightly
		vec3 flame_color = tex.rgb * vec3(1.2, 0.9, 0.5);
		EMISSION = flame_color * intensity;
	}
}
