Major cleanup of Utils class.
[trakem2.git] / ini / trakem2 / utils / Vector3D.java
blob84deb84d73c63e77ce83781dbdd1d8c4cead1cd9
1 /** Adapted by Albert Cardona from the ArcBall C code in the Graphics Gems IV, 1993. */
2 package ini.trakem2.utils;
4 public class Vector3D {
6 public double x, y, z;
8 public Vector3D(double x, double y, double z) {
9 this.x = x;
10 this.y = y;
11 this.z = z;
14 public Vector3D() { this(0,0,0); }
16 public Vector3D(Vector3D v) { this(v.x, v.y, v.z); }
18 public Object clone() { return new Vector3D(x, y, z); }
20 public String toString() { return "Vector3D(" + x + ", " + y + ", " + z + ")"; }
22 public double length() { return Math.sqrt(x*x + y*y + z*z); }
24 /** Does nothing if the length is zero. */
25 public void normalize() {
26 double vlen = length();
27 if (vlen != 0.0) {
28 x /= vlen;
29 y /= vlen;
30 z /= vlen;
34 public void scale(double s) {
35 x *= s;
36 y *= s;
37 z *= s;
40 /** Substracts the given vector to this one. */
41 public void substract(Vector3D v) {
42 x -= v.x;
43 y -= v.y;
44 z -= v.z;
47 public void add(Vector3D v) {
48 x += v.x;
49 y += v.y;
50 z += v.z;
53 public void negate() {
54 x = -x;
55 y = -y;
56 z = -z;
59 public double dotProduct(Vector3D v) {
60 return x*v.x + y*v.y + z*v.z;
63 public Vector3D crossProduct(Vector3D v) {
64 return new Vector3D(y*v.z - z*v.y, z*v.x - x*v.z, x*v.y - y*v.x);
67 /** @return half arc between vector and v */
68 public Vector3D bisect(Vector3D v) {
69 Vector3D r = new Vector3D(x + v.x, y + v.y, z + v.z);
70 double length = r.length();
71 if (length < 1.0e-7) {
72 r.set(0, 0, 1);
73 } else {
74 r.scale(1/length);
76 return r;
79 public void set(double x, double y, double z) {
80 this.x = x;
81 this.y = y;
82 this.z = z;
85 public Vector3D rotateAroundAxis(Vector3D axis, double sin, double cos) {
86 // obtain a normalized axis first
87 Vector3D r = new Vector3D(axis);
88 r.normalize();
89 return new Vector3D((cos + (1-cos) * r.x * r.x) * x + ((1-cos) * r.x * r.y - r.z * sin) * y + ((1-cos) * r.x * r.z + r.y * sin) * z,
90 ((1-cos) * r.x * r.y + r.z * sin) * x + (cos + (1-cos) * r.y * r.y) * y + ((1-cos) * r.y * r.z - r.x * sin) * z,
91 ((1-cos) * r.y * r.z - r.y * sin) * x + ((1-cos) * r.y * r.z + r.x * sin) * y + (cos + (1-cos) * r.z * r.z) * z);