#version 300 es
precision highp float;

uniform sampler2D uMainTex;
uniform vec2 uTexelSize;  // 纹理像素大小 (1/width, 1/height)
uniform int uBlurRadius;  // 模糊半径
uniform bool uHorizontal; // 是否为水平方向模糊

in vec2 v_originTexCoord;
out vec4 fragColor;

float gaussian(float x, float sigma) {
    return exp(-(x * x) / (2.0 * sigma * sigma)) / (sqrt(2.0 * 3.14159) * sigma);
}

// 添加安全的纹理采样
vec4 safeTexture(sampler2D tex, vec2 uv) {
    // 镜像采样：将超出范围的坐标镜像回来
    vec2 safeUV = vec2(
        uv.x < 0.0 ? -uv.x : (uv.x > 1.0 ? 2.0 - uv.x : uv.x),
        uv.y < 0.0 ? -uv.y : (uv.y > 1.0 ? 2.0 - uv.y : uv.y)
    );
    return texture(tex, safeUV);
}

void main() {
    if (uBlurRadius <= 0) {
        fragColor = texture(uMainTex, v_originTexCoord);
        return;
    }

    vec4 color = vec4(0.0);
    float totalWeight = 0.0;
    float sigma = float(uBlurRadius) / 2.0;

    for (int i = -uBlurRadius; i <= uBlurRadius; i++) {
        float weight = gaussian(float(i), sigma);
        vec2 offset = (uHorizontal ? vec2(float(i), 0.0) : vec2(0.0, float(i))) * uTexelSize;
        // 使用安全的纹理采样
        color += safeTexture(uMainTex, v_originTexCoord + offset) * weight;
        totalWeight += weight;
    }

    fragColor = color / totalWeight;
}