shader_type sky;

uniform float star_size: hint_range(50.0, 500.0) = 120.0;

uniform sampler2D star_colors: hint_default_white;
uniform sampler2D sky_gradient: hint_default_black, repeat_disable;
uniform sampler2D nebula_gradient: hint_default_black, repeat_disable;
uniform float nebula_offset;
uniform sampler2D universe_background: hint_default_black;

// https://github.com/Norrox/GodotShaders/blob/master/Shaders/Voronoi-Worley/Voronoi.shader
vec3 RNGV3(vec3 p) {
	vec3 a = fract(vec3(p.x, p.y, p.z) * vec3(111.11,333.33,444.44));
	a += dot(a, a+33.51);
	return fract(vec3(a.x*a.y, a.y*a.z, a.z*a.x)); //outputs a random vec2 between 0 and 1
}

vec4 voronoy(vec3 loc, float scale){
    loc = loc*scale;
    vec4 output = vec4(0., 0., 0., 10.);
    for(float y=-1.; y<=1.; y++){
		for(float x=-1.; x<=1.; x++){
            for(float z=-1.; z<=1.; z++){
                vec3 offs = vec3(x,y,z);
                vec3 n = RNGV3(floor(loc)+offs)*2.0-1.0;
                vec3 p = offs+sin(n) * .5;
                float  d = length((fract(loc)-0.5)-p);
                if(d<output.q){
                    vec3 rng = RNGV3(floor(loc)+offs);
                    output = vec4(rng.x, rng.y, rng.z, d);
                }
            }
		}
	}
    return output;
}

void sky() {
    vec4 star_noise = voronoy(EYEDIR, star_size);
    vec3 stars = pow(max((0.25-star_noise.q)*4.0, 0), 0.3) * texture(star_colors, vec2(star_noise.x)).xyz * pow(star_noise.z, 2.2);
    stars *= float(star_noise.y*4.0 < pow(texture(universe_background, SKY_COORDS).z, 2.0));
    stars *= (0.7 + sin(TIME*(star_noise.z*1.5+0.2)) * 0.5);
    vec2 moving_noise = (texture(universe_background, SKY_COORDS + TIME * vec2(0.001, .0)).xy - 0.5) * 0.1;
    COLOR = pow(texture(sky_gradient, pow(moving_noise + EYEDIR.yy, vec2(0.8))).xyz, vec3(2.2));
    vec4 nebula = texture(nebula_gradient, //selecting the correct color
                             pow(vec2(texture(universe_background, SKY_COORDS).z), vec2(0.8+nebula_offset)) * nebula_offset //setting the base gradient
                             * 1.5 * texture(universe_background, -SKY_COORDS  + TIME * vec2(0.001, 0) + moving_noise).xy // adding distortion
                            );
                            
    //COLOR += pow(texture(nebula_gradient, vec2(texture(universe_background, SKY_COORDS).z + nebula_offset * texture(universe_background, -SKY_COORDS  + TIME * vec2(0.0005, 0) + moving_noise).z + 0.1)).xyz, vec3(2.0));
    COLOR = (COLOR * (1.0-nebula.q) + nebula.xyz + stars * SKY_COORDS.y)*float(SKY_COORDS.y<0.5);
    //COLOR = texture(universe_background, SKY_COORDS).zzz;
}
