attribute vec2 uv;
attribute vec3 position;
// Add instanced attributes just like any attribute
attribute vec3 offset;
attribute vec3 random;
attribute vec3 normal;

uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
uniform mat4 normalMatrix;

uniform float uTime;
uniform float uRot;
varying vec2 vUv;
varying vec3 vNormal;
varying float fog;

void rotate2d(inout vec2 v, float a){
    mat2 m = mat2(cos(a), -sin(a), sin(a),  cos(a));
    v = m * v;
}
void main() {
    vUv = uv;

    vNormal = normal;

    /* vNormal = normalize(normalMatrix * normal); */
    
    // copy position so that we can modify the instances
    vec3 pos = position;
    
    // scale first
    fog = (offset.z+1.0)/2.0;
    pos *= 0.4 + (1.0-fog) * 0.6;
    
    // rotate around y axis
    rotate2d(pos.xz, random.x * 6.28 + 1.0 * uTime * (random.y - 0.5));
    
    rotate2d(pos.xy, random.y * 6.28 + 1.0 * uTime * (random.y - 0.5));
    // rotate around x axis just to add some extra variation
    rotate2d(pos.zy, random.z * 0.5 * sin(uTime * random.x + random.z * 3.14));
    
    pos.y += sin(uRot/500.0+random.y*50.0)/5.0+(1.0-fog)*uRot;

    pos += offset;

    
    gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
}
