// 3D Plasma Sphere
// by Rick Companje
// 22-5-2006

float i=2;
float step = .1;
float h = step/2;
float xmag, ymag = 5;
float newXmag, newYmag = 0;
float maxc=0,minc=0;
float d;

void setup() {
  size(400,300,P3D);
  colorMode(HSB,1);
}

void draw() {
  float cx,cy,c;
  background(0);
  translate(width/2, height/2);
  scale(100); //=radius
  noStroke();
  lights();
  
  newXmag = mouseX/float(width) * TWO_PI;
  newYmag = mouseY/float(height) * TWO_PI;
  
  float diff = xmag-newXmag;
  if (abs(diff) > 0.01) { xmag -= diff/4.0; }  
  diff = ymag-newYmag;
  if (abs(diff) > 0.01) { ymag -= diff/4.0; }
  
  i+=.01;
  
  for (float p=0; p<PI; p+=step) {
       
    cx = 3*sin(p * 1 + i);

    for (float t=0; t<PI; t+=step) {
     
      cy = 3*sin(t + i);
 
      c=cx+cy;

      //if (c>maxc) {maxc=c; println("max: " + c);}
      //if (c<minc) {minc=c; println("min: " + c);}
      
      c+=6;
      c/=12;
      
      fill(c,1,1);
      
      pushMatrix();
      
      rotateX(-ymag);
      rotateY(-xmag);
      
      beginShape(QUADS);
      vertex(sincos(p-h,t-h), sinsin(p-h,t-h), cos(p-h));
      vertex(sincos(p+h,t-h), sinsin(p+h,t-h), cos(p+h));
      vertex(sincos(p+h,t+h), sinsin(p+h,t+h), cos(p+h));
      vertex(sincos(p-h,t+h), sinsin(p-h,t+h), cos(p-h));
      endShape();
     
      beginShape(QUADS);
      vertex(-sincos(PI-p-h,PI-t-h), -sinsin(PI-p-h,PI-t-h), -cos(PI-p-h));
      vertex(-sincos(PI-p+h,PI-t-h), -sinsin(PI-p+h,PI-t-h), -cos(PI-p+h));
      vertex(-sincos(PI-p+h,PI-t+h), -sinsin(PI-p+h,PI-t+h), -cos(PI-p+h));
      vertex(-sincos(PI-p-h,PI-t+h), -sinsin(PI-p-h,PI-t+h), -cos(PI-p-h));
      endShape();
      popMatrix();
      
    }
  }
}

float sincos(float a,float b) { return sin(a)*cos(b); }
float sinsin(float a,float b) { return sin(a)*sin(b); }