#version 120
#include "commonSettings.glsl"

#if DRAWING_STYLE == 1
    // Pencil on Paper Style
    #define STYLE_PIXEL_BLOOM 1
#elif DRAWING_STYLE == 2
    // Colorful Sketch Style
    #define STYLE_PIXEL_BLOOM 1
#elif DRAWING_STYLE == 3
    // Blue Pen Style
    #define STYLE_PIXEL_BLOOM 1
#elif DRAWING_STYLE == 4
    // Painterly (Oil Paint) Style - uses Kuwahara filter
    // colortex2 is pre-downsampled by composite1, so no per-tap box filter needed
    #define STYLE_PIXEL_BLOOM 0
#elif DRAWING_STYLE == 5
    // Outline Pencil on Paper Style
    #define STYLE_PIXEL_BLOOM 1
#else
    // Fallback to Pencil style
    #define STYLE_PIXEL_BLOOM 1
#endif

// Bloom settings
#define BLOOM_ENABLED 1 // Enable bloom effect [0 1]
#define BLOOM_RADIUS 10.0 // Bloom blur radius [2.5 5.0 10.0 15.0 20.0]
#define PIXEL_BLOOM STYLE_PIXEL_BLOOM // Pixelated bloom [0 1]

uniform sampler2D colortex2; // Bright areas from composite1
uniform float viewWidth;
uniform float viewHeight;

/* RENDERTARGETS:3 */

varying vec2 texcoord;

// Horizontal gaussian blur
vec3 gaussianBlurHorizontal(sampler2D tex, vec2 texcoord) {
    #if BLOOM_ENABLED == 0
    return vec3(0.0);
    #endif

    vec2 pixelSize = vec2(1.0 / viewWidth, 1.0 / viewHeight);
    vec3 result = vec3(0.0);
    float totalWeight = 0.0;

    // Gaussian weights
    float weights[5] = float[](0.227027, 0.1945946, 0.1216216, 0.054054, 0.016216);

    #if PIXEL_BLOOM == 1
        // Pixel-crisp bloom: tap the raw bright-areas buffer at integer pixel
        // offsets so block edges stay sharp (styles 1-3).
        result += texture2D(tex, texcoord).rgb * weights[0];
        totalWeight += weights[0];

        for (int i = 1; i < 5; i++) {
            vec2 offset = vec2(1.0, 0.0) * pixelSize * float(i) * BLOOM_RADIUS;
            result += texture2D(tex, texcoord + offset).rgb * weights[i];
            result += texture2D(tex, texcoord - offset).rgb * weights[i];
            totalWeight += weights[i] * 2.0;
        }
    #else
        // Soft bloom
        result += texture2D(tex, texcoord).rgb * weights[0];
        totalWeight += weights[0];

        for (int i = 1; i < 5; i++) {
            vec2 offset = vec2(1.0, 0.0) * pixelSize * float(i) * BLOOM_RADIUS;
            result += texture2D(tex, texcoord + offset).rgb * weights[i];
            result += texture2D(tex, texcoord - offset).rgb * weights[i];
            totalWeight += weights[i] * 2.0;
        }
    #endif

    return result / totalWeight;
}

void main() {
    // Horizontal blur with improved connectivity
    vec3 bloomBlur = gaussianBlurHorizontal(colortex2, texcoord);
    
    // Store horizontally blurred bloom in colortex3
    gl_FragData[0] = vec4(bloomBlur, 1.0);
}