#version 130

uniform float iTime;
float voroniTiles = 32.;
uniform float minVoroniDist = 1;
uniform sampler2D currentTexture;

vec2 random( vec2 p ) {
    return fract(sin(vec2(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3))))*43758.5453);
}

float voroniFunc(vec2 uv)
{
    //uv = fragCoord/vec2(1920., 1080.);
    uv.x *= 1920. / 1080.;
    
    uv *= voroniTiles;
    
    vec2 tile = floor(uv);
    vec2 tileCoord = fract(uv);
    
    float minDist = 10000.;
    
    for(int y = -1; y <= 1; y++)
    {
        for(int x = -1; x <= 1; x++)
        {
            vec2 n = vec2(x,y);
            vec2 p = random(tile + n);
            
            p = sin((iTime) * p) / 2. + 0.5;
            
            float dist = length(p + n - tileCoord);
            
            minDist = min(minDist, dist);
        }
    }


    minDist = max(minDist, minVoroniDist);
    
    return length(minDist);
}

void main()
{
    // Normalized pixel coordinates (from 0 to 1)
    vec2 uv = gl_TexCoord[0].xy; // fragCoord/iResolution.xy;
    
    vec3 col = vec3(0.);
    
    float voroni = voroniFunc(uv);
    vec3 tex = texture(currentTexture, uv * voroni).xyz;
    vec3 tex1 = texture(currentTexture, uv).xyz;
    
    if (voroni <= minVoroniDist) col = tex1;
    else col = tex;
    
    // Output to screen
    gl_FragColor = vec4(col,1.0);
}