#version 300 es

precision mediump float;

in vec2 v_originTexCoord;

uniform vec3 bgColor;
uniform vec3 fgColor;

uniform vec4 wave;

out vec4 fragColor;

float culDist(vec2 pp, out bool milk, float t)
{
    pp.y += (
    .4 * sin(wave[0]*pp.x+pp.y) +
    .2 * sin(wave[1]*pp.x+pp.y) +
    0.1*sin(wave[2]*pp.x)+
    0.06*cos(wave[3]*pp.x));
    pp += vec2(0., t);
    float thresh = 0.6;
    milk = pp.y > thresh;
    float d = abs(pp.y - thresh);
    return d;
}

vec3 render(in vec2 pp)
{
    bool milk;
    float d = culDist(pp, milk, 2.);

    if (!milk){
        // 阴影
        float s = smoothstep(.0, .055, d);
        vec3 res = mix(vec3(0.348,0.346,0.336), bgColor, s);
        return res;
    } else {
        float height = smoothstep(.0, .95, d)*2.0;
        height = 50.*pow(height, .2);
        // 有瑕疵的计算法线
        vec3 mormal = vec3(-dFdx(height), 1., -dFdy(height));
        mormal = normalize(mormal);
        vec3 light = normalize(vec3(.5, .7, -1.5));
        vec3 res = pow(dot(mormal, light), 10.)*vec3(1.);
        res += fgColor;
        return res;
    }
}

void main()
{
    vec2 uv = v_originTexCoord;
    uv.y=-uv.y;
    fragColor = vec4(render(uv*4.), 1.0);
}