shader_type spatial;
render_mode depth_prepass_alpha;

group_uniforms gunk_material;
uniform vec3 color_1: source_color = vec3(0.0, 0.03, 0.1);
uniform vec3 color_2: source_color = vec3(0.0, 0.1, 0.3);
uniform vec3 emission_color: source_color = vec3(0.25, 0.88, 1.0);

uniform float pixellation = 128.0;
uniform float time_pixellation = 30.0;

uniform float roughness: hint_range(0.0, 1.0) = 0.15;
uniform float specular_contribution = 0.8;
uniform float emission_strength = 0.05;

// Used ONLY by the gunk, does not affect the gunk mask.
uniform vec2 uv_scale = vec2(1.0);

uniform float time_scale = 1.0;

uniform float edge_bleed = 0.25;

uniform sampler2D gunk_mask;

uniform highp sampler3D gunk_noise;
uniform highp sampler3D gunk_normal_map;

group_uniforms jitter;
uniform mediump float jitter_magnitude = 0.0;
uniform lowp float jitter_time_scale = 0.1;

uniform highp sampler3D jitter_noise;

group_uniforms inflation;
uniform highp float vertex_inflation = 0.0;
uniform highp float inflation_pixellation = 10.0;

void vertex() {
	float mixer = VERTEX.x + 0.553 * VERTEX.z + 1.618 * VERTEX.y;
	float local_time = floor(TIME * jitter_time_scale * time_pixellation) / time_pixellation;
	float sample = texture(jitter_noise, vec3(cos(mixer), sin(mixer), local_time)).r;
	float inflation = floor(vertex_inflation * inflation_pixellation) / inflation_pixellation;
	float jitter = jitter_magnitude * (sample - 0.5 + inflation);
	VERTEX *= 1.0 + jitter;
}

float hardstep(float value) {
	float x = clamp(value, 0.0, 1.0);
	return 0.5 * tanh( (20.0 * x - 10.0) * inversesqrt(x - x * x) ) + 0.5;
}

void fragment() {
	vec2 local_uv = floor(UV * uv_scale * pixellation) / pixellation;
	float local_time = floor(TIME * time_scale * time_pixellation) / time_pixellation;

	// swirl
	vec3 uvt = vec3(local_uv.x, local_uv.y, local_time);
	uvt.x += sin(uvt.y * 1.54 * PI + uvt.z) * cos(uvt.y * 1.31 * PI + uvt.z) * 0.2;
	uvt.y += cos(uvt.x * 1.74 * PI + uvt.z) * -sin(uvt.y * 1.64 * PI + uvt.z) * 0.3;


	float value = texture(gunk_noise, uvt).r;
	vec3 color = mix(color_1, color_2, value);

	ALBEDO = color.rgb;
	ROUGHNESS = value * roughness;
	EMISSION = (1.0 - value) * emission_color * emission_strength;
	SPECULAR = 0.5 * inversesqrt(specular_contribution);
	NORMAL_MAP = texture(gunk_normal_map, uvt).xyz;

	float mask = texture(gunk_mask, UV).r;

	// soften edges
	NORMAL_MAP *= smoothstep(1.0, 0.0, mask);

	/*
	// Hard edge
	if(mask + edge_bleed < 0.5) {
		ALPHA = 1.0;
	} else {
		ALPHA = 0.0;
	}
	*/

	// Hardish edge
	ALPHA = hardstep(1.0 - mask + edge_bleed);
}