varying vec2 v_TexCoord;
varying vec2 v_Position;
uniform float u_Time;
uniform sampler2D u_Tex0;
uniform sampler2D u_Tex1;
uniform vec2 u_Resolution;
const float PI = 3.1415926535897932;

// CONFIG
float speed = 3.0;
float height = 10.7;
float angle = 22.0; // degrees
float intensity = 0.9;
// CONFIG END

vec2 rotate(vec2 v, float a) {
    float s = sin(a);
    float c = cos(a);
    mat2 m = mat2(c, -s, s, c);
    return m * v;
}

// speed
const float crystals_speed = 0.16;
const float crystals_speed_x = 0.13;
const float crystals_speed_y = 0.12;

// geometry
const float noise_intensity = 100.;
const int steps = 9;
const float frequency = 70.0;
const int noise_angle = 13; // better when a prime

// reflection and emboss
const float delta = 500.;
const float intence = 70.3;
const float emboss = 3.7;

//---------- crystals effect
float col(vec2 coord)
{
    float delta_theta = 2.0 * PI / float(noise_angle);
    float col = 0.0;
    float theta = 0.0;

    for(int i = 0; i < steps; i++) {
        vec2 adjc = coord;
        theta = delta_theta*float(i);
        adjc.x += cos(theta)*u_Time*crystals_speed + u_Time * crystals_speed_x;
        adjc.y -= sin(theta)*u_Time*crystals_speed - u_Time * crystals_speed_y;
        col = col + cos( (adjc.x*cos(theta) - adjc.y*sin(theta))*frequency) * noise_intensity;
    }
    return cos(col);
}

void main()
{

    vec2 p = v_TexCoord, c1 = p, c2 = p;
    float cc1 = col(c1);

    c2.x += u_Resolution.x/delta;
    float dx = emboss*(cc1-col(c2))/delta;

    c2.x = p.x;
    c2.y += u_Resolution.y/delta;
    float dy = emboss*(cc1-col(c2))/delta;

    c1.x += dx;
    c1.y += dy;

    float alpha = 1.+dot(dx,dy)*intence;

    gl_FragColor = texture2D(u_Tex0, c1);
    vec4 texcolor = texture2D(u_Tex0, c1);
    vec4 effectColor = texture2D(u_Tex1, v_TexCoord);

    vec2 rotated = rotate(v_Position, (angle / 180.0) * PI);
    float frame = mod(rotated.y, height);
    float timeFrame = mod(u_Time * speed, height);
    float dist = min(abs(frame - timeFrame), min(abs(frame - timeFrame - height), abs(frame - timeFrame + height)));

    if(texcolor.a > 0.9) {
        vec3 tempColor = gl_FragColor.xyz;
        gl_FragColor.xyz *= max(1.0, 1.0 / max(intensity / sqrt(max(1.0, dist)), 0.1));
    }

    if(gl_FragColor.a < 0.01) discard;
}