// class BounceOff by Alexander Barth, Gerd Trautner, yuri(RR) 1998
// alexander.barth@fhs-hagenberg.ac.at
// gerd@mond.at
// http://yuri.weirdoz.org

import java.util.Enumeration;
import javax.media.j3d.*;
import javax.vecmath.*;
import com.sun.j3d.utils.geometry.*;

public class BallBehavior extends Behavior{
    
	public Vector3d position;

// physical properties
	private double maxVelocity = 0.3;
	private double deltaY;
	private final static double gravity = 0.003; // is used for adding  (< maxVelocity)
	private final static double attenuation = 0.5; // attenuation factor (< 1.0)    	
    	    	
    	private Sphere sphere;
    	private TransformGroup sphereTrans;
	private Transform3D sphereTranslate;
	
    	private WakeupOnCollisionEntry wEnter;
    	private WakeupOnElapsedTime wTime;
    	private WakeupOr TimeOrColl;
    	
    	
	
    public BallBehavior(Sphere s, TransformGroup sphereTrans, Vector3d position) {
    	
		this.sphere = s;
		this.sphereTrans = sphereTrans;
		this.position = position;
		sphereTranslate = new Transform3D();
    }

    public void initialize() {
    		// create Enter - CollisionDetector on sphere
			wEnter = new WakeupOnCollisionEntry(sphere);
		// create Timer			
			wTime = new WakeupOnElapsedTime(400);
		// wakeup criterials are collision and every 400ms
			WakeupCriterion[] wc = {wEnter, wTime};		
		// OR the wakeup criterials
			TimeOrColl = new WakeupOr(wc);
		// Console Init output, to proof the startposition
			System.out.println("Init Sphere CollisionBounds: " + sphere.getCollisionBounds());
		// Wait for wakeup
			wakeupOn(TimeOrColl);
    }

    public void processStimulus(Enumeration criteria) {
		
		if (wEnter.hasTriggered()) {
		// Console otput
			System.out.println ("Collision ocurred: "+position.y);
		// Invert Sphere Direction
			deltaY = deltaY*(-1)*attenuation;
		// Wait for next wakeup
			wakeupOn(TimeOrColl);
		}

		if (wTime.hasTriggered()){
		// Console output
			System.out.println("Sphere ColBounds:" + sphere.getCollisionBounds());
			System.out.println("Calc. y-position:       " + position);
			System.out.println();
		// set position
			position.y -= deltaY;
		// move TransformGroup
			sphereTranslate.setTranslation(position);
		    	sphereTrans.setTransform(sphereTranslate);
		// accelerate
			if( deltaY < maxVelocity) deltaY += gravity;
		// Wait for next wakeup
			wakeupOn(TimeOrColl);
		}
    }
    
}
