#include "inc/uniforms.glsl"
#include "inc/utils.glsl"
#include "inc/buffers.glsl"

#ifdef VERTEX
layout(location=0) in vec4 in_Position;
layout(location=1) in vec4 in_Color;
// normal
layout(location=3) in vec2 in_UV;
out vec4 ex_Color;
out vec2 ex_UV;
out vec3 dir, pos;
mat4 clipToModel = inverse(modelViewProject);
mat4 cameraToModel = inverse(modelView);

void main()
{
	//dir = vec4(clipToModel*vec4(in_Position.xyz+vec3(.0, .0, .1),.0)).xyz;
	dir = vec4(cameraToModel*vec4(in_Position.xyz+vec3(.0, .0, -2.0), .0)).xyz;
	pos = vec3(.0, .0, -200.0*p_beat)+vec4(cameraToModel*vec4(.0, .0, .0,1.0)).xyz;
	ex_Color = in_Color;
	ex_UV = in_UV;
	gl_Position = in_Position;
}
#endif

// https://www.youtube.com/watch?v=nd8pNiGKN0E
#ifdef FRAGMENT
#include "inc/geometry_io.fs"
in vec3 dir, pos;
uniform vec4 base_color, fractal_color;
void main()
{
	vec3 c = vec3(sin(ex_UV.x*2.0 + p_beat), sin(ex_UV.x*4.0 + p_beat) * sin(ex_UV.y*5.0), sin(ex_UV.y*10.0));
	vec4 col = vec4(c, 1.0);
	vec3 ray = normalize(dir);
	float hit_depth = abs((pos.y+sign(ray.y)*50.0)/ray.y);
	vec2 hit_uv = .001*(pos.xz+ray.xz*hit_depth)*sign(ray.y);
	
	vec4 sky = vec4(base_color.rgb, 1.0);
	//sky.rgb *= 1.0 - sign(ray.y)*4.0;
	vec4 cloud = vec4(fractal_color.rgb, 1.0);
	cloud.b *= 1.0 - sign(ray.y)*0.3; // ground bluer
	vec2 local = vec2(2.0, .0)+vec2(1.0)-vec2(5.0*atan(hit_uv.x), 20.0*cos(.2*hit_uv.y))/3.141592;
	local *= .1;
	for (float i = .0; i < 60.0; i += 1.0)
		local = vec2(local.x*local.x-local.y*local.y, 2*local.x*local.y)+vec2(-0.8, 0.156);
	float thick = atan(-.01*length(local))/3.141592+.5;
	float cloud_transparency = abs(thick);
	out_Color = mix((.9 + .2*sign(ray.y))*mix(sky, cloud, clamp(cloud_transparency, .0, 1.0)), vec4(1.0), clamp(hit_depth*.00001, .0, 1.0));
} 
#endif