// // [return] //
//exballs.java
/**********************************************************
 Script for the behavioral animation
 Written By Alberto B. Raposo and Leo Pini Magalhaes
 Computer Graphics Lab - CS Univ. of Waterloo
 Last Modified 11-Oct.-96
***********************************************************/

// This program is the script that implements the "behavior" of 
// the sphere in the VRML 2.0 animation ex-script-balls.wrl

import vrml.*;
import vrml.field.*;
import vrml.node.*;

public class exballs extends Script {
	private SFNode inside;
	private SFNode outside;
	private SFVec3f newPosition;
	private SFNode PosInterp1;
	private SFNode PosInterp2;
	private Node aux;
	private float ff = (float) 1.;
	private boolean outsid = true;

	// Function called once, when the VRML file is loaded
	public void initialize()	{
		// mapping variables into VRML-script fields/events
		inside = (SFNode) getField("inside");
		outside = (SFNode) getField("outside");
		newPosition = (SFVec3f) getEventOut("newPosition");
		PosInterp1 = (SFNode) getField("PosInterp1");
		PosInterp2 = (SFNode) getField("PosInterp2");
		aux = (Node) PosInterp2.getValue();
	}

	// Function called everytime an event of the script is generated
	// (in this case, at each clock tick).
	public void processEvent (Event e) {
		ConstSFBool sensor1;
		ConstSFBool sensor2;

		// Getting sensor events
		Node aux1 = (Node)(inside.getValue());
		sensor1 = (ConstSFBool) aux1.getEventOut("isOver");
		aux1 = (Node)(outside.getValue());
		sensor2 = (ConstSFBool) aux1.getEventOut("isOver");

		// The boolean outsid stores the last sensor touch
		if(sensor2.getValue()) outsid = true;
		else  if(sensor1.getValue()) outsid = false;
		

		// Choosing which trajectory to follow, according to the
		// boolean outsid. This occurs only at the beggining of a
		// clock cycle (ff > f.getValue())			       
		ConstSFFloat f = (ConstSFFloat) e.getValue();
		
		if( outsid && ff > f.getValue() )
		   aux = (Node) PosInterp2.getValue();
		   		  
		else if ( !outsid && ff > f.getValue() )
		   aux = (Node) PosInterp1.getValue();

		ff = f.getValue();

		// Mapping the new position into a VRML-script EventOut
		ConstSFVec3f tmp = 
			(ConstSFVec3f) aux.getEventOut("value_changed");
		newPosition.setValue(tmp);
		
		} 

}