/*
====================================================================================================

    Copyright (C) 2020 RRe36

    All Rights Reserved unless otherwise explicitly stated.


    By downloading this you have agreed to the license and terms of use.
    These can be found inside the included license-file
    or here: https://rre36.com/copyright-license

    Violating these terms may be penalized with actions according to the Digital Millennium
    Copyright Act (DMCA), the Information Society Directive and/or similar laws
    depending on your country.

====================================================================================================
*/

/*DRAWBUFFERS:3*/
layout(location = 0) out vec3 bloomData;

#include "/lib/head.glsl"

//bloom downsampling method based on chocapic13's shaders

uniform vec2 bloomResolution;
uniform vec2 pixelSize;
uniform vec2 viewSize;

in vec2 coord;

#if pass == 0
    uniform sampler2D colortex0;
#elif pass == 1
    uniform sampler2D colortex3;
#endif


void main() {
    if (clamp(coord, -0.003, 1.003) != coord) discard;

    #if pass == 0
        vec2 rscale    = max(viewSize, bloomResolution)/bloomResolution;
        vec2 qrescoord = (gl_FragCoord.xy*2.0*pixelSize-vec2(0.0, 0.5))*rscale;
    #elif pass == 1
        vec2 qrescoord = gl_FragCoord.xy*2.0*pixelSize+vec2(0.0, 0.25);
    #endif

    #if pass == 0
        #define coltex colortex0
    #elif pass == 1
        #define coltex colortex3
    #endif

    //0.5
    vec4 blur       = texture(coltex, qrescoord-1.0*vec2(pixelSize.x, pixelSize.y))/4.0*0.5;
        blur       += texture(coltex, qrescoord+1.0*vec2(pixelSize.x, pixelSize.y))/4.0*0.5;
        blur       += texture(coltex, qrescoord+1.0*vec2(-pixelSize.x, pixelSize.y))/4.0*0.5;
        blur       += texture(coltex, qrescoord+1.0*vec2(pixelSize.x, -pixelSize.y))/4.0*0.5;

    //0.25
        blur       += texture(coltex, qrescoord-2.0*vec2(pixelSize.x, 0.0))/2.0*0.125;
        blur       += texture(coltex, qrescoord+2.0*vec2(0.0, pixelSize.y))/2.0*0.125;
        blur       += texture(coltex, qrescoord+2.0*vec2(-pixelSize.x, 0.0))/2.0*0.125;
        blur       += texture(coltex, qrescoord+2.0*vec2(0.0, -pixelSize.y))/2.0*0.125;

    //0.125
        blur       += texture(coltex, qrescoord-2.0*vec2(pixelSize.x, pixelSize.y))/4.0*0.125;
        blur       += texture(coltex, qrescoord+2.0*vec2(pixelSize.x, pixelSize.y))/4.0*0.125;
        blur       += texture(coltex, qrescoord+2.0*vec2(-pixelSize.x, pixelSize.y))/4.0*0.125;
        blur       += texture(coltex, qrescoord+2.0*vec2(pixelSize.x, -pixelSize.y))/4.0*0.125;

        blur       += texture(coltex, qrescoord)*0.125;

    #if pass == 0
        if (qrescoord.x>1.0-3.5*pixelSize.x || qrescoord.y>1.0-3.5*pixelSize.y || qrescoord.x<3.5*pixelSize.x || qrescoord.y<3.5*pixelSize.y) blur = vec4(0.0);
    #endif

        blur.a  = 1.0;

    bloomData = clamp16F(blur.rgb);
}