// -*-C++-*-
#version 120

// Vertex stage for the ALS-compatible glTF PBR effect.
// This is not a full implementation of the ALS lighting pipeline.
// It derives the simplified ambient haze and day/night shading inputs
// needed by the PBR fragment shader from the existing skydome ALS model.

uniform float hazeLayerAltitude;
uniform float terminator;
uniform float avisibility;
uniform float visibility;
uniform float terrain_alt;
uniform float air_pollution;

uniform bool flip_vertically;

varying vec3 normal;
varying vec3 view_position;
varying vec2 texCoord;

varying vec3 hazeColor;
varying float earthShade;

// Approximate the ALS atmospheric light response for one color channel.
// The parameters control the shape of the transition through the
// day/night terminator. This function is adapted from the existing
// skydome ALS lighting calculation.

float light_func(
    in float x,
    in float a,
    in float b,
    in float c,
    in float d,
    in float e)
{
    x = x - 0.5;

    if (x > 30.0)
        return e;

    if (x < -15.0)
        return 0.0;

    return e / pow(1.0 + a * exp(-b * (x - c)), 1.0 / d);
}

void main()
{
    normal = normalize(gl_NormalMatrix * gl_Normal);
    view_position = (gl_ModelViewMatrix * gl_Vertex).xyz;
    texCoord = (gl_TextureMatrix[0] * gl_MultiTexCoord0).xy;

    if (flip_vertically)
        texCoord.y = 1.0 - texCoord.y;

    vec3 viewDir = normalize(view_position);

    vec3 lightDirection = normalize(gl_LightSource[0].position.xyz);
    vec3 lightHorizon = normalize(vec3(lightDirection.x, lightDirection.y, 0.0));

    // Approximate the skydome ALS terminator at the current viewing
    // direction. avisibility provides the effective distance used by the
    // skydome haze model rather than a physical model-space position.
    float yprime = -dot(viewDir, lightHorizon) * avisibility;
    yprime -= sqrt(2.0 * 5800000.0 * hazeLayerAltitude);

    float terminator_width = 200000.0;

    earthShade =
        0.9 *
        (1.0 - smoothstep(
            -terminator_width + terminator,
             terminator_width + terminator,
             yprime
        )) +
        0.1;

    float lightArg = (terminator - yprime) / 100000.0;

    hazeColor.r = light_func(lightArg, 8.305e-06, 0.161,
                             4.827 - 3.0 * air_pollution,
                             3.04e-05, 1.0);

    hazeColor.g = light_func(lightArg, 3.931e-06, 0.264, 3.827, 7.93e-06, 1.0);

    hazeColor.b = light_func(lightArg, 1.330e-05, 0.264,
                             1.527 + 2.0 * air_pollution,
                             1.08e-05, 1.0);

    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
