//Magnus Pfleghar
import processing.sound.*;
int bands =32;
FFT fft;
AudioIn audio;
float[][]points;
int gain=50;
int scl=20;
void setup() {
  frameRate(60);
  size(800, 800, P3D);
  audio = new AudioIn(this, 0);
  audio.start();
  int index=0;
  points=new float[bands][bands];
  println("Init Done");
  fft = new FFT(this, points.length);
  fft.input(audio);
}
void draw() {
  background(0);
  for (int a=0; a<bands-1; a++) {
    points[0][a]=constrain(map(fft.spectrum[a]*gain,0,10, 0,200),0,200);
    }
  translate(width/2, height/2);
  rotateX(PI/4);
  translate(-width/2+width/8, -height/2);
  
  //translate(-width/2+width/8, -height/2+width/8);
  if (frameCount%2==0) {
    fft.analyze();
    shift();
  }
 
  stroke(255);
  strokeWeight(1);
  //noFill();
  for (int y=0; y<bands-1; y++) {
    beginShape(TRIANGLE_STRIP);
    for (int x=0; x<bands-1; x++) {
      //fill(map(this.points[x][y],0,10,0,255),map(this.points[x][y],0,10,255,0),0);
      colorMode(HSB, 255);
      stroke(map(points[x][y],0,10,0,255),map(points[x][y],0,10,0,255),map(points[x][y],0,10,255,0));
      fill(map(points[x][y],0,10,0,255),255,255);
      vertex(x*scl, y*scl, points[x][y]);
      vertex(x*scl, (y+1)*scl, points[x][y+1]);
    }
    endShape();
  }
}
void shift() {
  //println("Shifting");
  for (int i=bands-1; i>0; i--) {
    //println("Row:"+i);
    for (int a=0; a<bands-1; a++) {
      points[i][a]=points[i-1][a];
      //println("Point:"+(i-1)+"|"+a+"filled with:"+i+"|"+a);
    }
    //println("Row done");
  }
}