#if !defined SCATTERING_LIB
#define SCATTERING_LIB
	vec3 atmosphereScattering(vec3 p, vec3 d, vec3 l) {
		float R = length(p);
		float Mu = dot(p / R, d);
		float MuS = dot(p / R, l);
		float V = dot(d, l);

		ivec2 res = textureSize(depthtex1, 0);

		vec3 rayleigh = vec3(0.0);
		{
			vec4 coord = atmosphereScatteringLookupUv(R, Mu, MuS, V);
			vec2 lookup0 = atmosphere4DLookupUv(coord + vec4(0.0, 0.0, 0.0      , 0.0     )) / vec2(res);
			vec2 lookup1 = atmosphere4DLookupUv(coord + vec4(0.0, 0.0, 1.0/resMu, 0.0     )) / vec2(res);
			vec2 lookup2 = atmosphere4DLookupUv(coord + vec4(0.0, 0.0, 0.0      , 1.0/resR)) / vec2(res);
			vec2 lookup3 = atmosphere4DLookupUv(coord + vec4(0.0, 0.0, 1.0/resMu, 1.0/resR)) / vec2(res);
			vec2 f = fract(coord.zw * vec2(128, 32));
			vec3 s0 = texture(depthtex1, lookup0).rgb;
			vec3 s1 = texture(depthtex1, lookup1).rgb;
			vec3 s2 = texture(depthtex1, lookup2).rgb;
			vec3 s3 = texture(depthtex1, lookup3).rgb;
			vec3 blended = mix(mix(s0, s1, f.x), mix(s2, s3, f.x), f.y);
			rayleigh = phaseFunctions(V).x * blended;
		}

		vec3 mie = vec3(0.0);
		{
			vec4 coord = atmosphereScatteringLookupUv(R, Mu, MuS, V) + vec4(0, 0, 1, 0);
			vec2 lookup0 = atmosphere4DLookupUv(coord + vec4(0.0, 0.0, 0.0      , 0.0     )) / vec2(res);
			vec2 lookup1 = atmosphere4DLookupUv(coord + vec4(0.0, 0.0, 1.0/resMu, 0.0     )) / vec2(res);
			vec2 lookup2 = atmosphere4DLookupUv(coord + vec4(0.0, 0.0, 0.0      , 1.0/resR)) / vec2(res);
			vec2 lookup3 = atmosphere4DLookupUv(coord + vec4(0.0, 0.0, 1.0/resMu, 1.0/resR)) / vec2(res);
			vec2 f = fract(coord.zw * vec2(128, 32));
			vec3 s0 = texture(depthtex1, lookup0).rgb;
			vec3 s1 = texture(depthtex1, lookup1).rgb;
			vec3 s2 = texture(depthtex1, lookup2).rgb;
			vec3 s3 = texture(depthtex1, lookup3).rgb;
			vec3 blended = mix(mix(s0, s1, f.x), mix(s2, s3, f.x), f.y);
			mie = phaseFunctions(V).y * blended;
		}

		return rayleigh + mie;
	}

	vec3 atmosphericScattering(in vec3 position, in vec3 direction) {
		vec3 sunScatter  = atmosphereScattering(position, direction,  sunVector) *  sunIlluminance;
		vec3 moonScatter = atmosphereScattering(position, direction, moonVector) * moonIlluminance;
		return sunScatter + moonScatter;
	}
#endif