package alive;

/**
 * <ALIVE Project>
 * Experiment 0 Particles Physics test
 * Collision detection test
 */

import javax.vecmath.*;
import javax.media.j3d.*;

public class xp0_Particle extends Agent {
  xp0_Environment env = null;
  double size = 1;
  Vector3d dis = new Vector3d();

  public xp0_Particle(xp0_Environment env) { // Constructor
    this.configureToEnvironment(env);
    this.env = env;
    speed = generateRandomVector(); speed.scale(rnd(0,env.MAX_SPEED));
    message("o"); // Agent Created code
    super.makeAlive();
  }
  public void behavior() { //  ***
    acceleration.set(0,0,0);
    //direction.set(0,0,1);
    test();
  }
  public Actor createActor() {
    this.actor = new Actor_Sphere();
    //actor.setTexture(env.config.codeBase + "textures/red.gif");
    color.set((float)rnd(0,.5),(float)rnd(0,.5),(float)rnd(0,.5));
    return actor;
  }
  public void updateActor() {
    actor.set(position,direction,size);
  }

  // Implementation exclusive
  public void test() {
    for (int i = 0; i < env.agents.size() ; i++) {
      Agent ag = env.getAgent(i);
      if (ag != null) {
        if (ag.id != this.id) {
          dis.set(ag.position.x, ag.position.y, ag.position.z);
          dis.sub(this.position);
          double distance = dis.length();
          dis.normalize();
          if (distance < 2*size) { // in range
            dis.normalize();
            ag.acceleration.set(dis.x, dis.y, dis.z);
            ag.acceleration.scale(speed.length());
            acceleration.set(-dis.x, -dis.y, -dis.z);
            acceleration.scale(ag.speed.length());
            /**
             * The physics of collisions performed here are approximations to
             * momentum conservation equations for particles of equal mass,
             * and not implemented to be perfect, but computationally cheap.
             */
          }
        }
      }
    }
  }
}