import java.util.Enumeration;
import java.awt.*;
import javax.media.j3d.*;
import javax.vecmath.*;
import javax.swing.*;

public class TwistBehavior extends Behavior {

    Alpha alpha;
	TransformGroup tg;
	Transform3D t1;
	Matrix3d mat1,rotx,roty,rotz;
	double direction_scale = 1.0;
	double dphi = Math.PI/300;
	double lastTime = 0;
	int nsteps = 0;

    WakeupOnElapsedFrames w = new WakeupOnElapsedFrames(0);

    public void initialize() {
		alpha.setStartTime(System.currentTimeMillis());

		wakeupOn(w);
    }

    public void processStimulus(Enumeration criteria) {

		nsteps++;
		if(nsteps % 10 == 0) {
			double thisTime = System.currentTimeMillis();
			float fps = 0.0f;
			if(thisTime > lastTime) fps =  10000.0f/(float)(thisTime-lastTime) ;
			lastTime = thisTime;
		}

		if(nsteps == 70) {
			if(Math.random() < 0.5) {
				rotx.rotX(-dphi);
			} else {
				rotx.rotX(dphi);
			}
			if(Math.random() < 0.5) {
				roty.rotY(-dphi);
			} else {
				roty.rotY(dphi);
			}
			if(Math.random() < 0.5) {
				rotz.rotZ(-dphi);
			} else {
				rotz.rotZ(dphi);
			}
			direction_scale = -direction_scale;
			nsteps = 0;

		}
		tg.getTransform(t1);
		double scale = t1.getScale();
		scale += direction_scale*0.007;
		t1.setScale(scale);

		t1.getRotationScale(mat1);
		mat1.mul(rotx);
		mat1.mul(roty);
        mat1.mul(rotz);
		t1.setRotationScale(mat1);

		tg.setTransform(t1);
		
	// Set wakeup criteria for next time
		wakeupOn(w);
    }

    public TwistBehavior(Alpha A, TransformGroup T) {
		tg = T;
		alpha = A;
		t1 = new Transform3D();
		mat1 = new Matrix3d();
		rotx = new Matrix3d();
		rotx.rotX(dphi);
		roty = new Matrix3d();
		roty.rotY(-dphi);
        rotz = new Matrix3d();
        rotz.rotZ(-dphi);
		nsteps = 0;
    }
}
