#version 300 es
precision highp float;

uniform sampler2D uMainTex;
uniform vec2 uOffset;
uniform float uDepth;

in vec2 vUV;
out vec4 fragColor;

float luminance(vec3 c) {
    return dot(c, vec3(0.2126, 0.7152, 0.0722));
}

vec3 texSample(float x, float y) {
    return texture(uMainTex, vUV + vec2(x, y)).rgb;
}

void main() {
    float R = abs(luminance(texSample(uOffset[0], 0.0)));
    float L = abs(luminance(texSample(-uOffset[0], 0.0)));
    float D = abs(luminance(texSample(0.0, uOffset[1])));
    float U = abs(luminance(texSample(0.0, -uOffset[1])));

    float X = (L - R) * 0.5;
    float Y = (U - D) * 0.5;

    vec3 normal = normalize(vec3(X, Y, 1.0 / uDepth));
    
    // 将法线从 [-1,1] 转换到 [0,1] 范围
    normal = normal * 0.5 + 0.5;
    
    fragColor = vec4(normal, 1.0);
}