shader_type spatial;
render_mode specular_disabled, cull_disabled;

// CC0 (Quaternius) foliage: alpha-cut leaf / flower / fern cards of the nature kit, drawn with the
// same wind and cel lighting as the procedural trees (env_prop.gdshader). Only the leaf surfaces use
// this material; bark keeps the toon material, so trunks stay still. Sway grows with the vertex's
// height above the plant's origin (world metres, so any MultiMesh scale works), plus a small leaf
// flutter. Painted lime tips on up-facing leaves (style guide: sun-hit leaf #bce363).
#include "res://shaders/env_common.gdshaderinc"

uniform vec4 albedo : source_color = vec4(1.0);
uniform sampler2D tex : source_color, hint_default_white, filter_linear_mipmap_anisotropic, repeat_enable;
uniform float alpha_cut = 0.2;
// optional repaint (rgb target, a = amount): e.g. the kit's red twisted-tree leaves on the common bush
// -> green, olive CC0 canopies -> the brighter style-guide greens. Luminance / recolor_ref keeps detail.
uniform vec4 recolor : source_color = vec4(0.0);
uniform float recolor_ref = 0.2;
uniform float wind = 0.016;        // metres of sway per metre of height
uniform float flutter = 0.035;     // leaf jitter (m), grows with height too
uniform float soft = 0.3;
uniform float shade_amount = 0.9;
uniform float rim_amount = 0.1;
uniform vec3 shade_color = vec3(0.50, 0.40, 0.56);
uniform vec4 tip_color : source_color = vec4(0.74, 0.89, 0.39, 1.0);
uniform float tip_amount = 0.25;

varying vec3 wnrm;
varying vec3 wpos;

void vertex() {
	vec3 origin = MODEL_MATRIX[3].xyz;
	vec3 w = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
	float h = max(w.y - origin.y, 0.0);
	vec3 sway = env_wind(origin, h, wind);
	// flutter: per-vertex phase, fades in above ~1 m so bush bases / fern roots stay planted
	float ph = dot(w, vec3(1.7, 2.3, 1.3));
	sway += vec3(sin(TIME * 3.1 + ph), sin(TIME * 2.3 + ph * 1.3) * 0.5, cos(TIME * 2.7 + ph)) * flutter * min(h, 3.0) / 3.0;
	VERTEX += inverse(mat3(MODEL_MATRIX)) * sway;
	wpos = w;
	wnrm = normalize((MODEL_MATRIX * vec4(NORMAL, 0.0)).xyz);
}

void fragment() {
	vec4 t = texture(tex, UV);
	vec3 tc = t.rgb;
	if (recolor.a > 0.0) {
		float l = dot(tc, vec3(0.299, 0.587, 0.114));
		tc = mix(tc, recolor.rgb * (l / recolor_ref), recolor.a);
	}
	vec3 c = albedo.rgb * tc;
	if (tip_amount > 0.0) {
		float up = smoothstep(0.35, 0.95, wnrm.y + (vnoise(wpos.xz * 2.5 + wpos.y) - 0.5) * 0.35);
		// keep the painted leaf detail: lime scaled by the texel brightness
		c = mix(c, tip_color.rgb * mix(1.0, dot(tc, vec3(0.333)) * 2.2, 0.5), up * tip_amount);
	}
	ALBEDO = c;
	ALPHA = t.a * albedo.a;
	ALPHA_SCISSOR_THRESHOLD = alpha_cut;
	ROUGHNESS = 1.0;
}

void light() {
	if (LIGHT_IS_DIRECTIONAL) {
		vec3 band = env_toon(NORMAL, LIGHT, VIEW, ATTENUATION, soft, shade_amount, shade_color, rim_amount);
		DIFFUSE_LIGHT += band * LIGHT_COLOR / PI;
	} else {
		DIFFUSE_LIGHT += env_local_light(NORMAL, LIGHT, ATTENUATION, LIGHT_COLOR) / PI;
	}
}
