import SGBackground.*;
import Tuple.*;
import SGCamera.*;
import SGQuickVar.*;
import SGPhysics.*;
 
 
Gradient back;
SGCamera cam;
 
int res = 15;
 
float time = 0;
 
PFont font;
 
SGVariable barrel,len,jello,wonky;
 
PhysicsEngine PE;
 
 
void setup(){
 
size(550,550,P3D);
frameRate(30);
 
 
font = loadFont("writing.vlw");
textFont(font);
barrel = new SGVariable(this,font,"Length Segments",'a','z',3,1,1,10);
len = new SGVariable(this,font,"Barrel Segments",'s','x',4,1,1,10);
jello = new SGVariable(this,font,"Jelly",'d','c',.5,.03,.01,.3);
wonky = new SGVariable(this,font,"Wonky",'f','v',0,1,0,20);
 
cam = new SGCamera(this,20,-10,150,0,0,0);
cam.setMouseMode(LEFT,SGCamera.ORBIT);
cam.setMouseMode(RIGHT,SGCamera.DOLLY);
 
textureMode(NORMALIZED);
 
back = new Gradient(this,10);
back.addLight(new Tuple3f(width/2,0,300),color(170),1.f,1);
back.addLight(new Tuple3f(0,0,400),color(30,0,0),1.f,1);
 
PE = new PhysicsEngine(this);
PE.addForce(new LinearForce(new Tuple3f(0,.08,0)));
sphereDetail(4);
buildThing();
}
 
 
 
void buildThing(){
PE.clearObjects();
float sc = 10;
DynamicBody de;
float vs;
for (int i =0; i < barrel.val; i++){
for (float j =0; j < 2*PI; j+= 2*PI/len.val){
de = new DynamicBody(new Tuple3f(sc*cos(j) + random(-wonky.val,wonky.val),-100 + sqrt(2)*sc*i, sc*sin(j)+ random(-wonky.val,wonky.val) ));
de.mass = random(1,10);
PE.addBody(de);
}
}
SGBody a,b;
for (int i=0; i < PE.bodies.size(); i++){
a = (SGBody)PE.bodies.elementAt(i);
for (int j = i+1; j < PE.bodies.size(); j++){
b = (SGBody)PE.bodies.elementAt(j);
PE.addConstraint(new Constraint(a,b,jello.val));
}
}
 
 
 
}
 
void draw(){
 
time += .1f;
back.draw();
lights();
cam.feed();
 
fill(128);
DynamicBody temp;
for (int i = 0; i < PE.bodies.size(); i++){
temp = (DynamicBody)PE.bodies.elementAt(i);
pushMatrix();
translate(temp.pos.x,temp.pos.y,temp.pos.z);
sphere(1);
popMatrix();
if (temp.pos.y > 0 ) {
Tuple3f up = temp.getDX();
up.x = -up.x;
up.z = -up.z;
up.y = -up.y;
temp.impulse(up);
temp.pos.y = 0;
}
}
 
stroke(0);
Constraint c;
for (int i=0; i < PE.constraints.size(); i++){
c = (Constraint)PE.constraints.elementAt(i);
c.render(this);
}
fill(100,80,80);
noStroke();
beginShape();
vertex(-100,0,-100);
vertex(100,0,-100);
vertex(100,0,100);
vertex(-100,0,100);
endShape();
 
}
 
 
 
void keyPressed(){
if (key == ' '){
buildThing();
}
}