precision mediump float;
uniform vec2 iResolution;
uniform float iTime;

// 圆角矩形SDF
float roundedBoxSDF(vec2 centerPos, vec2 size, float radius) {
    return length(max(abs(centerPos) - size + radius, 0.0)) - radius;
}

// 计算边缘高光
vec3 calculateHighlight(float sdf, vec2 uv, vec3 baseColor) {
    // 计算边缘宽度和强度
    float edgeWidth = 0.15;
    float edge = 1.0 - smoothstep(0.0, edgeWidth, abs(sdf));
    
    // 计算表面法线方向
    vec2 gradientDir = normalize(vec2(
        dFdx(sdf),
        dFdy(sdf)
    ));
    
    // 定义光源方向
    vec2 lightDir1 = normalize(vec2(-0.7, 0.7));
    vec2 lightDir2 = normalize(vec2(0.7, 0.7));
    
    // 计算基础光照（用于暗部）
    float diffuse1 = max(0.0, dot(gradientDir, lightDir1));
    float diffuse2 = max(0.0, dot(gradientDir, lightDir2));
    float diffuse = (diffuse1 + diffuse2) * 0.5;
    
    // 计算高光强度（更强的高光）
    float specular1 = pow(max(0.0, dot(gradientDir, lightDir1)), 16.0);
    float specular2 = pow(max(0.0, dot(gradientDir, lightDir2)), 16.0);
    float specular = (specular1 + specular2) * 1.2; // 增强高光强度
    
    // 计算边缘光晕（基于法线）
    vec2 viewDir = normalize(vec2(0.0, 1.0)); // 假设从上方观察
    float rimFactor = 1.0 - max(0.0, dot(gradientDir, viewDir));
    float rimLight = pow(rimFactor * edge, 3.0) * 0.5;
    
    // 暗部处理
    float shadowFactor = mix(0.6, 1.0, diffuse); // 增强暗部对比度
    
    // 计算最终颜色
    vec3 highlightColor = vec3(1.0, 0.95, 0.8);
    vec3 rimColor = vec3(1.0, 0.9, 0.7);
    
    // 使用更合理的光照混合方式
    vec3 diffuseColor = baseColor * shadowFactor;
    vec3 specularColor = highlightColor * (specular * edge);
    vec3 rimLightColor = rimColor * rimLight;
    
    // 使用基于能量守恒的混合
    float metallic = 0.7; // 金属度
    float roughness = 0.3; // 粗糙度
    
    // 计算菲涅尔效应
    float fresnel = pow(1.0 - max(0.0, dot(gradientDir, viewDir)), 5.0);
    float F0 = mix(0.04, 0.9, metallic); // 基础反射率
    float F = F0 + (1.0 - F0) * fresnel;
    
    // 最终颜色混合
    vec3 finalColor = mix(diffuseColor, specularColor, F);
    finalColor += rimLightColor * (1.0 - roughness);
    
    return finalColor;
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    // 将坐标归一化到[-1, 1]范围
    vec2 uv = (2.0 * fragCoord - iResolution.xy) / min(iResolution.x, iResolution.y);
    
    // 定义圆角矩形的参数
    vec2 size = vec2(0.6, 0.4);  // 矩形大小
    float radius = 0.15;         // 圆角半径
    
    // 计算SDF
    float d = roundedBoxSDF(uv, size, radius);
    
    // 基础颜色
    vec3 baseColor = vec3(0.8, 0.6, 0.1);
    
    // 计算带高光的最终颜色
    vec3 finalColor = calculateHighlight(d, uv, baseColor);
    
    // 应用SDF，绘制形状
    float shape = 1.0 - smoothstep(-0.01, 0.01, d);
    
    // 输出最终颜色
    fragColor = vec4(finalColor * shape, shape);
}

void main() {
    mainImage(gl_FragColor, gl_FragCoord.xy);
} 