uniform sampler2D tex;
uniform sampler2D dirtex;
uniform sampler2D randomtex;
uniform float voima;
uniform float freq;
uniform float time;

#define NUMBALLS 32.0

float saha(float x) {
  float xx=mod(abs(x), 2.0);
  if (xx>1.0) return 2.0-xx;
  else return xx;
}

float ypos(vec2 pos) {
  return sin(pos.x*0.003872+sin(pos.y*0.004775)*2.0)*64.0+sin(pos.x*0.002242-pos.y*0.001411)*128.0+(pos.x*pos.x+pos.y*pos.y)*0.0002;
}


void main(void) {
	vec2 texc = gl_TexCoord[0].xy;
	vec4 pier = texture2D(tex, texc);
	vec3 dir = texture2D(dirtex, texc).rgb, dir2;
	vec3 pos = pier.rgb; 
	vec3 pos2;
	float life=pier.a;

  pos2 = pos+dir*voima;  
  dir2.x = dir.x+sin(pos.y*0.623*freq+time*4.831+sin(pos.z*3.542*freq-time*2.812)*0.5)*0.025;
  dir2.y = dir.y+sin(pos.z*0.742*freq-time*4.827+sin(pos.x*2.272*freq+time*4.172)*0.5)*0.025;
  dir2.z = dir.z+sin(pos.x*0.587*freq+time*5.712+sin(pos.y*4.662*freq-time*3.278)*0.5)*0.025;
  life=life+voima*0.02;
  
  if (life>(1.0+sin(pos.x*2.7777)*0.1)) {
    if (texc.y<0.5) {
      float xx, yy;
      //xx=(texc.x-0.5)*2.0;
      //yy=(texc.y-0.25)*4.0;
      //vec2 xzpos=vec2(xx*xx*xx*2048.0*4.0, yy*yy*yy*4096.0*4.0);
      vec2 xzpos=texture2D(randomtex, texc).xz*8.0;
      float y=ypos(xzpos);
      pos2=vec3(xzpos.x, y, xzpos.y);
      dir2=vec3(0.0, 1.0, 0.0);
    } else {
      float balls=float(int(texc.x*NUMBALLS)+5);
      vec2 bp=vec2(sin(balls*1.4)*32.0*balls, cos(balls*1.4)*32.0*balls);
      float ballsize=sin(balls*1.782)*32.0+64.0;
      vec3 ballpos=vec3(bp.x, ypos(bp)+ballsize, bp.y);
      vec3 ppos=vec3(sin(pos.x*0.412+time*3.124), sin(pos.y*0.823+time*5.82143), sin(pos.z*0.421+time*2.8324));
      ppos=normalize(ppos);
      dir2=ppos;
      ppos*=ballsize;
      pos2=ppos+ballpos;
    }
    life=0.0;
  }
  
  gl_FragData[0] = vec4(pos2, life);
  gl_FragData[1] = vec4(normalize(dir2), 1.0);
}
