#version 300 es
precision highp float;

uniform sampler2D uMainTex;
uniform vec2 uResolution;
uniform float uDotSize;     // 点的大小
uniform float uDotSpace;    // 点的间距
uniform vec3 uDotBgColor;   // 点阵背景色
uniform float uSaturation;  // 饱和度控制
uniform float uDotShadowStrength; // 添加阴影强度控制

in vec2 v_originTexCoord;
out vec4 fragColor;

// 移除固定的宏定义
// #define DOT_SIZE 20.5
// #define DOT_SPACE 20.0

vec4 safeTexture(sampler2D tex, vec2 uv) {
    if (uv.x < 0.001 || uv.x > 0.999 || uv.y < 0.001 || uv.y > 0.999) {
        return texture(tex, v_originTexCoord);
    }
    return texture(tex, uv);
}

// 添加饱和度调整函数
vec3 adjustSaturation(vec3 color, float saturation) {
    float grey = dot(color, vec3(0.2126, 0.7152, 0.0722));
    return mix(vec3(grey), color, saturation);
}

void main() {
    float size = uDotSize;
    
    if (size <= 0.0) {
        fragColor = texture(uMainTex, v_originTexCoord);
        return;
    }
    
    vec2 coord = v_originTexCoord * uResolution;
    vec2 center = floor(coord/uDotSpace) * uDotSpace + uDotSpace/2.0;

    vec4 centerColor = safeTexture(uMainTex, center/uResolution);
    vec3 saturatedColor = adjustSaturation(centerColor.rgb, uSaturation);

    float dist = length(coord - center);
    float smoothWidth = 2.0;

    // 添加阴影效果
    float shadowSize = size * 1.5;
    float shadowMask = 1.0 - smoothstep(size/2.0, shadowSize/2.0, dist);
    
    // 点的mask
    float dotMask = 1.0 - smoothstep(size/2.0 - smoothWidth, size/2.0, dist);

    // 合并点和阴影
    vec3 withShadowColor = mix(uDotBgColor * (1.0 - uDotShadowStrength * shadowMask),
        mix(uDotBgColor, saturatedColor.rgb, dotMask),
        dotMask);

    fragColor = vec4(withShadowColor, 1.0);
}