#version 300 es
precision highp float;

uniform sampler2D uPassTex;
uniform sampler2D uBlurTex;
uniform float uTime;
uniform float uRate;
uniform float distortIntensity;
uniform float bump;
uniform int shapeMode; // 0.0为圆形, 1.0为椭圆形

in vec2 vUVRev;
in vec2 vUV;
out vec4 fragColor;

// 坐标变换：笛卡尔坐标到极坐标
vec2 cartesianToPolar(vec2 cartesian) {
    float r = length(cartesian);
    float theta = atan(cartesian.y, cartesian.x);
    return vec2(r, theta);
}

// 坐标变换：极坐标到笛卡尔坐标
vec2 polarToCartesian(float r, float theta) {
    return vec2(r * cos(theta), r * sin(theta));
}

// 安全的纹理采样
vec4 sampleTextureSafe(sampler2D tex, vec2 uv, vec2 fallbackUV) {
    bool isOutOfBounds = any(lessThan(uv, vec2(0.001))) || 
                        any(greaterThan(uv, vec2(0.999)));
    return isOutOfBounds ? texture(tex, fallbackUV) : texture(tex, uv);
}

// 统一的扭曲效果处理
vec2 distortionEffect(vec2 uv, vec2 center, float intensity, int shapeMode) {
    // 转换到相对坐标
    vec2 relativePos = 2.0 * uv - 1.0;
    relativePos -= center;
    
    if (shapeMode == 1) {
        // 椭圆变形
        relativePos.y *= 1.5;
    }
    
    // 转换到极坐标
    vec2 polar = cartesianToPolar(relativePos);
    
    // 根据模式应用不同的扭曲
    if (shapeMode == 1) {
        polar.x *= 1.0;
        polar.y += intensity * polar.x;
    } else {
        polar = vec2(1.0, intensity) * polar;
    }
    
    // 转回笛卡尔坐标
    vec2 distorted = polarToCartesian(polar.x, polar.y);
    
    if (shapeMode == 1) {
        distorted.y /= 1.5;
    }
    
    // 转回UV空间
    distorted += center;
    return 0.5 * distorted + 0.5;
}

void main() {
    // 计算动态中心点
    vec2 center = 0.7 * vec2(cos(uTime), sin(uTime));
    
    // 根据shapeMode选择扭曲效果
    vec2 distortedUV = distortionEffect(vUVRev, center, distortIntensity, shapeMode);
    
    // 计算混合因子
    float blendFactor = smoothstep(0.0, 1.0, 
        bump * distance(distortedUV, 0.5 * center + 0.5));
    
    // 混合原始UV和扭曲UV
    vec2 finalUV = mix(vUVRev, distortedUV, blendFactor * uRate);
    
    // 采样并混合原始图像和模糊图像
    vec3 originalColor = texture(uPassTex, finalUV).rgb;
    vec3 blurColor = sampleTextureSafe(uBlurTex, 
        vec2(finalUV.x, 1.0 - finalUV.y), vUV).rgb;
    
    // 输出最终颜色
    fragColor = vec4(mix(originalColor, blurColor, uRate), 1.0);
}