#version 300 es
precision highp float;

uniform sampler2D uMainTex;
uniform vec2 uResolution;    // Screen resolution
uniform float uRainDensity;  // Rain density control (0.0 - 1.0)
uniform float uDropSize;     // Raindrop size control

in vec2 v_originTexCoord;
out vec4 fragColor;

// 噪声函数
vec3 N13(float p) {
    vec3 p3 = fract(vec3(p) * vec3(.1031, .11369, .13787));
    p3 += dot(p3, p3.yzx + 19.19);
    return fract(vec3((p3.x + p3.y)*p3.z, (p3.x+p3.z)*p3.y, (p3.y+p3.z)*p3.x));
}

// 雨滴
float drops(vec2 uv) {
    uv *= (40. * uDropSize);  // 使用 uDropSize 控制雨滴大小
    vec2 id = floor(uv);
    uv = fract(uv)-.5;
    vec3 n = N13(id.x*106.55+id.y*3553.551);
    
    // 添加扭曲效果
    float distort = cos(uv.y*3.14159)*0.2;
    vec2 p = (n.xy-.5)*.7;
    p.x += distort * (n.z-.1) / 8.0;
    float d = length(uv-p);
    
    float c = smoothstep(.3, 0., d)*fract(n.z*10.);
    return c;
}

void main() {
    vec2 uv = (v_originTexCoord - 0.5) * vec2(uResolution.x/uResolution.y, 1.0);
    vec2 UV = v_originTexCoord;

    float staticDrops = smoothstep(-.5, 1., uRainDensity)*2.;
    float c = smoothstep(.3, 1., drops(uv)*staticDrops);
    
    // 多点采样计算法线
    vec2 e = vec2(.001, 0.);
    float cx1 = smoothstep(.3, 1., drops(uv+e)*staticDrops);
    float cx2 = smoothstep(.3, 1., drops(uv-e)*staticDrops);
    float cy1 = smoothstep(.3, 1., drops(uv+e.yx)*staticDrops);
    float cy2 = smoothstep(.3, 1., drops(uv-e.yx)*staticDrops);
    
    // 计算x和y方向的梯度
    float gradX = (cx1 - cx2) * 0.5;
    float gradY = (cy1 - cy2) * 0.5;
    vec2 n = vec2(gradX, gradY);
    
    fragColor = texture(uMainTex, UV + n);
}