#version 330 core

// Interpolated values from the vertex shaders
in vec2 UV;
uniform sampler2D prev;
uniform float dt;

// output
layout(location = 0) out vec4 state;

const float regenthr = -1.0;

float rand(vec2 co){
    return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}

vec4 spawn(vec4 state) {
  return vec4(rand(state.xy + UV.xy),
              rand(state.yx + UV.yx),
              state.z + 0.8 + 0.4 * rand(state.xy) - regenthr,
              state.a);
}

void main() {
  vec4 prevstate = texture(prev, UV);
  state = prevstate + 0.3*dt*vec4(0.0,0.0,-1.0,0.0);

  if (state.z < regenthr) {
    state = spawn(state);
    state.a = 1.0;
  }
}