Implement gravity and velocity vector.
[gravitysimulator.git] / src / edu / mit / ezyang / gravity / j3d / behaviors / PhysicsBehavior.java
blob49090f4a8eae697e707ab120ddcbd1994f04cf55
1 package edu.mit.ezyang.gravity.j3d.behaviors;
3 import edu.mit.ezyang.gravity.GravitySimulatorView;
4 import edu.mit.ezyang.gravity.actors.Body;
5 import edu.mit.ezyang.gravity.j3d.EditableGroup;
6 import java.util.Enumeration;
7 import javax.media.j3d.Behavior;
8 import javax.media.j3d.Node;
9 import javax.media.j3d.Transform3D;
10 import javax.media.j3d.TransformGroup;
11 import javax.media.j3d.WakeupOnElapsedTime;
12 import javax.vecmath.Vector3f;
14 /**
16 * @author Edward Z. Yang <ezyang@mit.edu>
18 public class PhysicsBehavior extends Behavior {
19 protected TransformGroup targetTG;
20 protected GravitySimulatorView view;
21 protected int interval = 10;
22 static public float G = .01f;
23 public PhysicsBehavior(TransformGroup tg, GravitySimulatorView view) {
24 this.targetTG = tg;
25 // Yeah, I know this is very hacky. We need to separate out the
26 // rendering components from the GUI view class
27 this.view = view;
29 public void initialize() {
30 this.wakeupOn(new WakeupOnElapsedTime(interval));
32 public void processStimulus(Enumeration criteria) {
33 if (targetTG.getChild(0) instanceof Body) {
34 Body body = (Body) targetTG.getChild(0);
35 Transform3D transform = new Transform3D();
36 targetTG.getTransform(transform);
37 Vector3f trans = new Vector3f();
38 transform.get(trans);
39 // velocity modifications from force
40 if (body.mass != 0f) {
41 Enumeration<Node> children = view.universeRoot.getAllChildren();
42 while (children.hasMoreElements()) {
43 Node node = children.nextElement();
44 if (node instanceof EditableGroup) {
45 TransformGroup group = ((EditableGroup) node).getTransformGroup();
46 Node subnode = group.getChild(0);
47 if (subnode instanceof Body) {
48 // ok, this can affect our dude
49 Body otherBody = (Body) subnode;
50 if (otherBody == body) continue;
51 // disregard massless objects
52 if (otherBody.mass == 0) continue;
53 Transform3D otherTransform = new Transform3D();
54 group.getTransform(otherTransform);
55 Vector3f otherVector = new Vector3f();
56 otherTransform.get(otherVector);
57 otherVector.sub(trans);
58 float distance = Math.abs(otherVector.length());
59 if (distance == 0f) continue;
60 float force = G * otherBody.mass * body.mass / (distance * distance);
61 float accel = force / body.mass;
62 otherVector.normalize();
63 otherVector.scale(accel);
64 body.velocity.add(otherVector);
65 if (body == view.selectedPrimitive) {
66 view.notifyPick(body);
73 // now redraw the object
74 if (body.velocity.length() != 0f) {
75 trans.x += body.velocity.x / 1000 * interval;
76 trans.y += body.velocity.y / 1000 * interval;
77 trans.z += body.velocity.z / 1000 * interval;
78 transform.set(trans, 1.0f);
79 targetTG.setTransform(transform);
80 postId(1);
83 this.wakeupOn(new WakeupOnElapsedTime(interval));