/* 
Mihut Ionescu       Francis Li
SID#:  12398942     SID#:  13086460
CS 184
LAB5
Developed on PC (Win95).
*/

import vrml.*;
import vrml.node.*;
import vrml.field.*;
import java.util.*;

public class FishBehavior extends Script {
  private float MAX_DEPTH = 30.0f;
  private float MAX_RADIUS = 20.0f;
  private float MIN_RADIUS = 10.0f;
  
  private SFVec3f currentTranslation;
  private SFRotation currentRotation;
  private SFVec3f set_translation;
  private SFRotation set_rotation;
  
  private Random randomGenerator;
  private float depth;
  private float radius;
  private float initialAngle;
  private float previousFraction;
  private float[] previousTranslation;
  
  public void initialize() {
    float[] rotation = new float[4];
    
    currentTranslation = (SFVec3f) getField("currentTranslation");
    currentRotation = (SFRotation) getField("currentRotation");
    set_translation = (SFVec3f) getEventOut("set_translation");
    set_rotation = (SFRotation) getEventOut("set_rotation");
    
    randomGenerator = new Random();
    depth = randomGenerator.nextFloat() * MAX_DEPTH - currentTranslation.getY();
    radius = randomGenerator.nextFloat() * MAX_RADIUS + MIN_RADIUS - currentTranslation.getZ();
    currentRotation.getValue(rotation);
    initialAngle = rotation[3];
    previousFraction = 0.0f;
    previousTranslation = new float[3];
    previousTranslation[0] = currentTranslation.getX();
    previousTranslation[1] = currentTranslation.getY();
    previousTranslation[2] = currentTranslation.getZ();
    }
  
  public void processEvent(Event e) {
    String eventName = e.getName();
    
    if (eventName.equals("set_fraction"))
      set_fraction(((ConstSFFloat) e.getValue()).getValue());
    }
  
  private void set_fraction(float fraction) {
    float x = currentTranslation.getX();
    float y = currentTranslation.getY();
    float z = currentTranslation.getZ();
    
    if (fraction < previousFraction) {
      depth = randomGenerator.nextFloat() * MAX_DEPTH - y;
      radius = randomGenerator.nextFloat() * MAX_RADIUS + MIN_RADIUS - z;
      previousTranslation[1] = y;
      previousTranslation[2] = z;
      }   
    y = previousTranslation[1] + fraction * depth;
    z = previousTranslation[2] + fraction * radius;
    currentTranslation.setValue(x, y, z);
    set_translation.setValue(currentTranslation);
    set_rotation.setValue(0.0f, 1.0f, 0.0f, initialAngle+fraction*(6.28f));
    previousFraction = fraction;
    }
  }