import java.awt.*;
import java.lang.Math;

public class week5 extends BufferedApplet {
	int wid_, hei_;
	long T0 = -1;
	double tlast_ = 0.;
	int depth_=2;
	Vector3D mouse_ = new Vector3D();
	boolean pushing_;
	Matrix3D view_ = new Matrix3D(),
		screen_ = new Matrix3D();
	Color backg_ = Color.white;
	Spinny spinny_ = new Spinny(0);
	public void init() {
		super.init();
		wid_ = getBounds().width;
		hei_ = getBounds().height;
		animating=true;
		view_.identity();
		int smdim = Math.min(hei_,wid_);
		screen_.identity();
		screen_.scale(smdim/2.,-smdim/2.,0);
		screen_.translate(wid_/2.,hei_/2.,0);
		spinny_.setScale(0.5,0.5,0.5);
		spinny_.expand(depth_);
	}
	public void render(Graphics g) {
		long T = System.currentTimeMillis();
		if(T0<0) {
			T0 = T;
			return; // in case zero time is bad
		}
		double t = (T-T0) / 1000.0,
			dt = t - tlast_;
		Graphics2D g2 = (Graphics2D)g;
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
	    g.setColor(backg_);
     	g.fillRect(0,0,wid_,hei_);
     	
     	if(pushing_)
     		spinny_.presh(mouse_);
     	spinny_.render(screen_,t,dt);
     	spinny_.draw(g);
     	
     	//screen_.yRotation(Math.sin(t/10.)/2.);
     	

		tlast_ = t;
	}
	public boolean mouseMove(Event e, int wx, int wy) {
		mouse_.set(0,wx);
		mouse_.set(1,wy);
		return true;
	}
	public boolean mouseDown(Event e, int wx, int wy) {
		pushing_ = true;
		return true;
	}
	public boolean mouseUp(Event e, int wx, int wy) {
		pushing_ = false;
		return true;
	}
	public boolean keyDown(Event e, int key) {
		switch(key) {
		case Event.UP:
			depth_ += 2;
			spinny_.expand(depth_);
			break;
		case Event.DOWN:
			depth_ = Math.max(0,depth_-2);
			spinny_.contract(depth_);
			break;
		case 'z':
			spinny_.zounds();
			break;
		case Event.RIGHT:
			Spinny.DRAG -= 0.01;
			break;
		case Event.LEFT:
			Spinny.DRAG = Math.min(Spinny.DRAG+0.01,1.);
			break;
		}			
		return true;
	}	
}
