#version 120
//Vignetting, applies bloom, applies exposure and tonemaps the final image
#extension GL_EXT_gpu_shader4 : enable

#define EXPOSURE_MULTIPLIER 1.0 //[0.25 0.4 0.5 0.6 0.7 0.75 0.8 0.85 0.9 0.95 1.0 1.1 1.2 1.3 1.4 1.5 2.0 3.0 4.0]

uniform float viewHeight;
uniform float viewWidth;
float pw = 1.0/viewWidth;
float ph = 1.0/viewHeight;
varying vec2 texcoord;
uniform vec2 texelSize;
uniform sampler2D colortex5;
uniform sampler2D colortex3;
uniform sampler2D noisetex;
uniform int isEyeInWater;
uniform float frameTimeCounter;
#include "lib/color_transforms.glsl"
#include "lib/color_dither.glsl"

float w0(float a)
{
    return (1.0/6.0)*(a*(a*(-a + 3.0) - 3.0) + 1.0);
}

float w1(float a)
{
    return (1.0/6.0)*(a*a*(3.0*a - 6.0) + 4.0);
}

float w2(float a)
{
    return (1.0/6.0)*(a*(a*(-3.0*a + 3.0) + 3.0) + 1.0);
}

float w3(float a)
{
    return (1.0/6.0)*(a*a*a);
}

float g0(float a)
{
    return w0(a) + w1(a);
}

float g1(float a)
{
    return w2(a) + w3(a);
}

float h0(float a)
{
    return -1.0 + w1(a) / (w0(a) + w1(a));
}

float h1(float a)
{
    return 1.0 + w3(a) / (w2(a) + w3(a));
}

vec4 texture2D_bicubic(sampler2D tex, vec2 uv)
{
	vec4 texelSize = vec4(1.0/vec2(viewWidth,viewHeight),viewWidth,viewHeight);

	uv = uv*texelSize.zw;
	vec2 iuv = floor( uv );
	vec2 fuv = fract( uv );

    float g0x = g0(fuv.x);
    float g1x = g1(fuv.x);
    float h0x = h0(fuv.x);
    float h1x = h1(fuv.x);
    float h0y = h0(fuv.y);
    float h1y = h1(fuv.y);

	vec2 p0 = (vec2(iuv.x + h0x, iuv.y + h0y) - 0.5) * texelSize.xy;
	vec2 p1 = (vec2(iuv.x + h1x, iuv.y + h0y) - 0.5) * texelSize.xy;
	vec2 p2 = (vec2(iuv.x + h0x, iuv.y + h1y) - 0.5) * texelSize.xy;
	vec2 p3 = (vec2(iuv.x + h1x, iuv.y + h1y) - 0.5) * texelSize.xy;

    return g0(fuv.y) * (g0x * texture2D(tex, p0)  +
                        g1x * texture2D(tex, p1)) +
           g1(fuv.y) * (g0x * texture2D(tex, p2)  +
                        g1x * texture2D(tex, p3));
}

//////////////////////////////VOID MAIN//////////////////////////////
//////////////////////////////VOID MAIN//////////////////////////////
//////////////////////////////VOID MAIN//////////////////////////////
//////////////////////////////VOID MAIN//////////////////////////////
//////////////////////////////VOID MAIN//////////////////////////////

void main() {
	vec3 col = texture2D(colortex5,texcoord).rgb*(1.5-dot(texcoord-0.5,texcoord-0.5)*2.);

	vec3 bloom = texture2D(colortex3,texcoord/2.).rgb;

	//col = texture2D(colortex3,texcoord).rgb;
	float exposure=pow(texelFetch2D(colortex5,ivec2(0),0).r,1.0/3.0);
  col = mix(col,bloom*100./6.,0.1*exp(1.85*sqrt(exposure)-1)+0.5*isEyeInWater);
	gl_FragColor.rgb = int8Dither(ACESFilm(col*EXPOSURE_MULTIPLIER*0.75*vec3(1.0,0.87,0.78)*exposure*0.17),texcoord);

	gl_FragColor.a = 1.0;
}
