uniform sampler2D depthtex1;
uniform sampler2D gaux4;
uniform float rainStrength;

#define BRIGHTNESS  1.0
#define CONTRAST    1.0
#define EXPOSURE    1.0
#define SATURATION  0.923
#define WHITESCALE  2.0

vec3 waterTonemapping(vec3 color) {
    color = 0.7 * color;
    color = color / pow(pow(color, vec3(2.3)) + 1.0, vec3(0.4347826086956522));

    return pow(color, vec3(1.1));
}

vec3 tonemappingFW(vec3 color) {
    float a = 0.05;
    float b = 0.30 * BRIGHTNESS;
    float c = 0.022 * CONTRAST;
    float d = 0.60;
    float e = 0.15 * 0.7;
    float f = 0.30;
    float w = 4.0 * WHITESCALE;

    color = mix(color, vec3(dot(color, vec3(0.3333))), -SATURATION * 0.8 + 1.0);
    color = pow(color, vec3(2.0));

    color *= 1.8;
    color = ((color * (e * color + b * a) + d * c) /
             (color * (e * color + a) + d * f)) - c / f;

    float whiteScale = 1.0 / (((w * (e * w + b * a) + d * c) /
                               (w * (e * w + a) + d * f)) - c / f);
    color *= whiteScale;

    color *= vec3(0.95, 1.05, 1.1);

    float boost = 1.2;
    color = mix(vec3(dot(color, vec3(0.3333))), color, boost);

    color = pow(color, vec3(0.5));

    return color;
}

vec3 tonemapping(vec3 color) {
	vec4 waterId = vec4(texture2D(gaux4, texcoord).rgb, 1.0);
    float depth = texture2D(depthtex1, texcoord).z;
    float water = texture2D(gaux4, texcoord).g;
    
    bool isSky = depth == 1.0;
    bool isWater = water > 2.5;
    
	float a = 0.2;
    float b = 0.10 * BRIGHTNESS;
    float c = 0.022 * CONTRAST;
    float d = 0.60;
    float e = 0.15  * EXPOSURE;
    float f = 0.30;
    float w = 9.8  * WHITESCALE;
	
	vec3 colSky = color * 0.8;
    vec3 toneSkyColor = mix(colSky, vec3(dot(colSky, vec3(0.3333))), -1.0 * 1.15 + 1.0);
    toneSkyColor = pow(toneSkyColor, vec3(2.2));
    toneSkyColor = 1.0 - exp(-toneSkyColor);
    toneSkyColor = pow(toneSkyColor, vec3(0.3636));
	
	color = mix(color, vec3(dot(color, vec3(0.3333))), -SATURATION * 1.1 + 1.0);
	color = pow(color, vec3(2.0));

	color *= 4.6;
    color = ((color * (e * color + b * a) + d * c) /
             (color * (e * color + a) + d * f)) - c / f;

    float whiteScale = 1.0 / (((w * (e * w + b * a) + d * c) /
                               (w * (e * w + a) + d * f)) - c / f);
                               
    color *= whiteScale;

    color = pow(color, vec3(0.5));
	
	color = isWater ? tonemappingFW(colSky * 1.4) : color;
    return isSky ? toneSkyColor : mix(color, toneSkyColor, rainStrength);
}

vec3 custom_sigmoid(vec3 color) {
    return tonemapping(color);
}

vec3 custom_sigmoid_alt(vec3 color) {
    return tonemapping(color);
}