#ifdef GL_ES
precision mediump float;
#endif

varying vec2 vTexCoord;

uniform sampler2D texture;
uniform float noise;
uniform int shader_type;
uniform float time;
uniform float startMillis;


vec3 glitch(vec2 uv) {
  vec3 col;
  vec2 offset = vec2(noise * 0.05, 0.0);

  col.r = texture2D(texture, uv + offset).r;
  col.g = texture2D(texture, uv).g;
  col.b = texture2D(texture, uv - offset).b;

  return col;
}

vec3 earthquake(vec2 uv) {
  vec3 col;

  vec2 offset = vec2(0.0, noise * 0.07);

  col.r = texture2D(texture, uv - offset).r;
  col.g = texture2D(texture, uv - offset).g;
  col.b = texture2D(texture, uv - offset).b;

  return col;
}

vec3 colorLoop(vec2 uv) {
  vec3 col;

  float avg = (texture2D(texture, uv).r + texture2D(texture, uv).g + texture2D(texture, uv).b)/3.0;

  col.r = avg + sin(time/100.0) * 0.3;
  col.g = avg + cos(time/100.0) * 0.3;
  col.b = avg;

  return col;
}

vec3 offSet(vec2 uv, float time, float startMillis) {
  vec3 col;

  float currentTime = time - startMillis;

  float offsetAngle = 3.1415926 * currentTime/1500.0;
  float offsetDist  = sin(3.1415926 * currentTime/130000.0) * 0.010;

  vec2 offset = vec2(sin(offsetAngle), -cos(offsetAngle))*offsetDist;

  col.r = texture2D(texture, uv).r;
  col.g = texture2D(texture, uv - offset).g;
  col.b = texture2D(texture, uv + offset).b;

  return col;
}

vec3 colorLoop2(vec2 uv, float time, float startMillis) {
  vec3 col;

  float currentTime = (time - startMillis)/1000.0;  

  col.r = (texture2D(texture, uv).r - texture2D(texture, uv).g) * sin ( currentTime * 3.14159) + texture2D(texture, uv).r;
  col.g = (texture2D(texture, uv).r - texture2D(texture, uv).g) * sin ( (currentTime + 0.5) * 3.14159) + texture2D(texture, uv).g;
  col.b = texture2D(texture, uv).b;

  return col;
}



void main() {
  vec2 uv = vTexCoord;
  uv.y = 1.0 - uv.y;

  vec3 col;
  
  if (shader_type == 0) {
    col = glitch(uv);
  } else if (shader_type == 1) {
    col = earthquake(uv);
  } else if (shader_type == 2) {
    col = colorLoop(uv);
  } else if (shader_type == 3) {
    col = offSet(uv, time, startMillis);
  } else if (shader_type == 4) {
    col = colorLoop2(uv, time, startMillis);
  } else {
    col.r = texture2D(texture, uv).r;
    col.g = texture2D(texture, uv).g;
    col.b = texture2D(texture, uv).b;
  }
  
  gl_FragColor = vec4(col, 1.0);
}
