

#include "/lib/taa/res_params.glsl"

varying vec3 np3;
varying vec4 color;

uniform sampler2D texture;
uniform float nightblend5;
uniform float nightblend5Inv;

flat varying float emissive;
uniform float frameTimeCounter;
#include "/lib/projections.glsl"
#include "/lib/uniforms.glsl"

// faster and actually more precise than pow 2.2
vec3 toLinear(vec3 sRGB)
{
    return sRGB * (sRGB * (sRGB * 0.305306011 + 0.682171111) + 0.012522878);
}

uniform sampler2D gaux3;
float NoisyStarField(in vec2 vSamplePos, float fThreshold)
{
    float StarVal =
        fract(dot(fract(vec3(vSamplePos.xyx) * 0.1031) +
                      dot(fract(vec3(vSamplePos.xyx) * 0.1031), fract(vec3(vSamplePos.xyx) * 0.1031).yzx + 19.19),
                  vec3(1.0)));

    StarVal = max(0.0, pow((abs(StarVal) - fThreshold) / (1.0 - fThreshold), 6.0));
    return clamp(StarVal, 0, 1);
}

float StableStarField(in vec2 vSamplePos, float fThreshold)
{
    float fractX = fract(vSamplePos.x);
    float fractY = fract(vSamplePos.y);
    vec2 floorSample = floor(vSamplePos);

    float v1 = NoisyStarField(floorSample, fThreshold);
    float v2 = NoisyStarField(floorSample + vec2(0.0, 1.0), fThreshold);
    float v3 = NoisyStarField(floorSample + vec2(1.0, 0.0), fThreshold);
    float v4 = NoisyStarField(floorSample + vec2(1.0, 1.0), fThreshold);

    float StarVal = mix(mix(v1, v2, fractY), mix(v3, v4, fractY), fractX);
    return StarVal;
}

float stars(vec3 fragpos)
{
    float elevation = clamp(fragpos.y, 0, 1);
    vec2 uv = fragpos.xz / (1 + elevation);

    return nightblend5Inv * 4 * StableStarField(uv * 700, 0.999) * (0.3 - 0.3 * rainStrength);
}
/* RENDERTARGETS: 8 */
vec3 Dither_Vlachos(vec3 rgba, float levels)
{
    // Vlachos 2016, "Advanced VR Rendering"
    vec3 noise = vec3(dot(vec2(171.0, 231.0), gl_FragCoord.xy));
    noise = fract(noise / vec3(103.0, 71.0, 97.0));
    noise = noise - 0.5;
    return vec3(rgba.rgb + (noise / (levels - 1.0)));
}
void main()
{

    vec3 normp3 = normalize(np3);
    // float stars = stars(normp3) * 0.1;
    // Vanilla Star Dedection by Builderb0y

    float vanillaStars = float(color.r == color.g && color.g == color.b && color.r > 0.0 && color.r < 0.51) * nightblend5;

    vec3 outcolor = skyFromTex2(normp3, gaux3).rgb;
    outcolor.rgb = Dither_Vlachos(outcolor, 2048);
    gl_FragData[0].rgb = outcolor;       // Albedo
    gl_FragData[0].a = 1 - vanillaStars; // Albedo
}
