/** * Basic core vector class, dot products, cross products * and basic vector operations. * * @author Daniel Staudigel */ public class Vector { /** * * We are using public fields here for performance */ public double x,y,z; /** * * Vector(): Basic stuff * * */ public Vector() { x = 0; y = 0; z = 0; } /** * * Creates a 3D double vector with given (x,y,z) * * @param px Input X value * * @param py Input Y value * * @param pz Input Z value */ public Vector(double px,double py,double pz) { x = px; y = py; z = pz; } /** * * Copies X,Y,Z, information from another Vector * * @param copy vector to copy */ public Vector(Vector copy) { x = copy.x; y = copy.y; z = copy.z; } /** * * Returns a copy of the current vector * * @return copy of the current vector */ public Vector copy() { return new Vector(this); } /** * * Performs a dot product * * @param vec vector to dot with * * @return the dot product */ public double dot(Vector vec) { return x*vec.x + y*vec.y + z*vec.z; } /** * * Performs the cross product * * @param vec Vector to perform with * * @return the Vector cross product */ public Vector cross(Vector vec) { return new Vector(y*vec.z - z*vec.y, z*vec.x - x*vec.z, x*vec.y - y*vec.x); } /** * * Returns the square of the length of the vector * * @return square of the length */ public double lengthSquared() { return x*x+y*y+z*z; } /** * * Returns the length of the vector * * @return length of the vector */ public double length() { return Math.sqrt(x*x+y*y+z*z); } /** * * Normalizes the vector and returns the length * * @return Length of vector */ public double normalize() { double length,square = x*x+y*y+z*z; if(square > 0) { length = Math.sqrt(square); x /= length; y /= length; z /= length; } else { length = 0; } return length; } /** * * Adds two vectors * * @param v other vector * * @return vector sum of target and argument */ public Vector add(Vector v) { return new Vector(x+v.x,y+v.y,z+v.z); } /** * * Subtracts two vectors * * @param v another vector * * @return vector subtraction of target and argument */ public Vector sub(Vector v) { return new Vector(x-v.x,y-v.y,z-v.z); } /** * * Sets the vector's contents to v * * @param v */ public void set(Vector v) { x = v.x; y = v.y; z = v.z; } /** * * Scales the vector by f (scalar multiplication) * * @param f scale factor */ public void scale(double f) { x *= f; y *= f; z *= f; } /** * * Scalar multiplication * * @param f scale factor * * @return result vector */ public Vector mul(double f) { return new Vector(x*f,y*f,z*f); } public Vector component_mul(Vector v) { return new Vector(x*v.x,y*v.y,z*v.z); } }