#ifndef AURORA_GLSL
#define AURORA_GLSL

// Aurora implementation extracted from clouds.glsl
#if AURORA_COLOR == 6
#include "/lib/color/auroraColor.glsl"
#endif

float AuroraSample(vec2 coord, vec2 wind) {
    float noise = texture2D(noisetex, coord * 0.04 + wind * 0.25).b * 3.0;
    noise += texture2D(noisetex, coord * 0.02 + wind * 0.15).b * 3.0;
    noise = max(1.0 - 2.0 * abs(noise - 3.0), 0.0);
    return noise;
}

vec3 DrawAurora(vec3 viewPos, float dither, int samples) {
    #ifdef TAA
        #if TAA_MODE == 0
            dither = fract(dither + frameCounter * 0.618);
        #else
            dither = fract(dither + frameCounter * 0.5);
        #endif
    #endif

    float sampleStep = 1.0 / samples;
    float currentStep = dither * sampleStep;
    float VoU = dot(normalize(viewPos), upVec);
    float visibility = moonVisibility * (1.0 - rainStrength) * (1.0 - rainStrength);

    #ifdef WEATHER_PERBIOME
        visibility *= isCold * isCold;
    #endif

    vec2 wind = vec2(
        frametime * CLOUD_SPEED * 0.000125,
        sin(frametime * CLOUD_SPEED * 0.05) * 0.00025
    );

    vec3 aurora = vec3(0.0);

    if (VoU > 0.0 && visibility > 0.0) {
        vec3 worldPos = normalize((gbufferModelViewInverse * vec4(viewPos, 1.0)).xyz);
        for(int i = 0; i < samples; i++) {
            vec3 planeCoord = worldPos * ((6.0 + currentStep * 16.0) / worldPos.y) * 0.003;
            vec2 coord = cameraPosition.xz * 0.00004 + planeCoord.xz;
            coord += vec2(coord.y, -coord.x) * 0.6;
            float noise = AuroraSample(coord, wind);
            if (noise > 0.0) {
                noise *= texture2D(noisetex, coord * 0.125 + wind * 0.25).b;
                noise *= texture2D(noisetex, coord + wind * 16.0).b * 0.5 + 0.75;
                noise = noise * noise * 3.0 * sampleStep;
                noise *= max(sqrt(1.0 - length(planeCoord.xz) * 3.0), 0.0);
                vec3 auroraColor = mix(auroraLowCol, auroraHighCol, pow(currentStep, 0.4));
                aurora += noise * auroraColor * exp2(-8.0 * i * sampleStep);
            }
            currentStep += sampleStep;
        }
    }

    #if MC_VERSION >= 11800
        visibility *= clamp((cameraPosition.y + 70.0) / 8.0, 0.0, 1.0);
    #else
        visibility *= clamp((cameraPosition.y + 6.0) / 8.0, 0.0, 1.0);
    #endif

    #ifdef UNDERGROUND_SKY
        visibility *= mix(clamp((cameraPosition.y - 48.0) / 16.0, 0.0, 1.0), 1.0, eBS);
    #endif

    return aurora * visibility;
}

#endif // AURORA_GLSL

