#version 410

#pragma include "filter_common.glsl"
#pragma include "spect.glsl"

//#define SPECT

uniform float u_Time;
uniform sampler2D u_RegisTex;
uniform sampler2D u_DamageTex;
uniform sampler2D u_EndTex;
uniform sampler2D u_BackTex;
uniform float u_Regis;
uniform float u_Damage;
uniform bool u_End;
uniform bool u_Back;
uniform float u_Scroll;

// Author Attribution:
// This tone mapping function is inspired by the Uncharted 2 video game's tone mapping curve.
// The Uncharted 2 tone mapping formula is well-known for its ability to produce realistic high dynamic range (HDR) lighting effects
// while preserving image details, even in very bright scenes.
// This function is based on the work of John Hable, who developed this approach for Naughty Dog’s Uncharted 2.
// - Reference: John Hable's blog "Filmic Tonemapping" (http://filmicworlds.com/blog/filmic-tonemapping-operators/)
vec3 applyToneMapUncharted2(vec3 color) {
    // Constants derived from John Hable's tone mapping curve
    const float A = 0.15;
    const float B = 0.50;
    const float C = 0.10;
    const float D = 0.20;
    const float E = 0.02;
    const float F = 0.30;
    const float W = 11.2;

    // Apply the Uncharted 2 tone mapping formula
    vec3 mapped_color = ((color * (A * color + C * B) + D * E) / (color * (A * color + B) + D * F)) - E / F;

    // Normalize by white point
    vec3 white_scale = vec3(1.0) / ((W * (A * W + C * B) + D * E) / (W * (A * W + B) + D * F) - E / F);

    return mapped_color * white_scale;
}


void main() {
//    p3d_FragColor = texture(p3d_Texture0, uv);
    p3d_FragColor = vec4(texture(p3d_Texture0, uv).rgb, 1.0);
    // Tone mapping
    p3d_FragColor.rgb = applyToneMapUncharted2(p3d_FragColor.rgb);



    if (u_Damage > 0.0) {
        p3d_FragColor.rgb  = mix(p3d_FragColor.rgb, texture(u_DamageTex, uv).rgb, u_Damage);
    } else if (u_Regis == -1.0) {
        p3d_FragColor.rgb  = texture(u_RegisTex, uv).rgb;
    } else if (u_Regis > -0.5) {
//        vec4 regisColor = texture(u_RegisTex, uv + vec2(0.0, 0.041));
        vec4 regisColor = texture(u_RegisTex, uv + vec2(0.0, 0.025));
        p3d_FragColor.rgb = mix(p3d_FragColor.rgb * 0.75, regisColor.rgb, regisColor.a);
        if (uv.y <= 0.125 || uv.y >= 0.875) {
            p3d_FragColor.rgb = vec3(0.0, 0.0, 0.0);
        }
        p3d_FragColor.rgb = mix(p3d_FragColor.rgb, vec3(1.0), u_Regis);
    }


    p3d_FragColor.rgb *= u_MasterFade;

}
