
export const fragmentShader = `
uniform float u_intensity;
uniform float u_time;
uniform int width;
uniform int height;

varying vec2 vUv;
varying float vDisplacement;

//from Hash Functions for GPU Rendering (Jarzynski et al.)
//http://www.jcgt.org/published/0009/03/02/
vec3 pcg3d(uvec3 v)
{
    v = v * 1664525u + 1013904223u;
    v.x += v.y*v.z; v.y += v.z*v.x; v.z += v.x*v.y;
    v ^= v >> 16u;
    v.x += v.y*v.z; v.y += v.z*v.x; v.z += v.x*v.y;
    return vec3(v) * (1.0/float(0xffffffffu));
}

// convert texture coordinates to pixel
float t2p(float t, int noOfPixels){
    return t * float(noOfPixels) - 0.5;
}

#define M_PI 3.1415926535897932384626433832795
vec2 randomGradient(uvec3 p){
    vec3 _uv = pcg3d(p);
    float r = sqrt(_uv[0]);
    float phi = 2.0 * M_PI * _uv[1];
    return vec2(r* cos(phi), r * sin(phi));
}


vec3 gradientNoise(vec2 pos, float gridSize){
    vec2 gridPos = pos * gridSize;
    uvec2 i = uvec2(gridPos);
    vec2 f = fract(gridPos);

    vec2 g11 = randomGradient(uvec3(i.x,i.y,1));
    vec2 g12 = randomGradient(uvec3(i.x + 1u,i.y,1));
    vec2 g21 = randomGradient(uvec3(i.x,i.y + 1u,1));
    vec2 g22 = randomGradient(uvec3(i.x + 1u,i.y +1u,1));

    float d11 = dot(g11, f);
    float d12 = dot(g12, f - vec2(1.0, 0.0));
    float d21 = dot(g21, f - vec2(0.0, 1.0));
    float d22 = dot(g22, f - vec2(1.0, 1.0));
    
    vec3 f11 = pcg3d(uvec3(i.x,i.y,0)) * (d11 + 1.0);
    vec3 f12 = pcg3d(uvec3(i.x + 1u,i.y,0))* (d12 + 1.0);
    vec3 f21 = pcg3d(uvec3(i.x,i.y + 1u,0))* (d21 + 1.0);
    vec3 f22 = pcg3d(uvec3(i.x + 1u,i.y +1u,0))* (d22 + 1.0);
    
    f = smoothstep(0.0, 1.0, f);

    vec3 q1 = mix(f11, f12, vec3(f.x));
    vec3 q2 = mix(f21, f22, vec3(f.x));
    vec3 p = mix(q1, q2, vec3(f.y));    
    
    return p;
}


void main() {
    float distort = 2.0 * vDisplacement + u_intensity;
    vec2 pos = vec2(u_time) /5.0 + vUv;
    vec3 texColor = gradientNoise(pos, 4.0);
    texColor.y = 0.0;
    gl_FragColor = vec4(texColor, 1.0);
}

`

