// // vector3d.cc // // A vector in 3d space // // Copyright (C) J. Belson 1998.11.30 // #include #include "vector3d.h" using namespace std; /** * Constructor */ vector3d::vector3d(float ii, float jj, float kk, bool norm) { i = ii; j = jj; k = kk; if (norm) { normalise(); } } /** * Calculate A.B * Divide result by |A| and |B| to get cos(angle) */ float vector3d::dot_product(const vector3d &v) const { return i*v.i + j*v.j + k*v.k; } /** * Calculate A+B */ vector3d vector3d::vector_product(const vector3d &v) const { vector3d tmp( j*v.k - k*v.j, k*v.i - i*v.k, i*v.j - j*v.i); return tmp; } /** * Get angle between two vectors */ float vector3d::angle(const vector3d& v) const { const float dp = dot_product(v); if (dp > 1.0) { return 0; } if (dp < -1.0) { return M_PI; } return acos(dp); } /** * Calculate magnitude of this vector */ float vector3d::magnitude(void) const { return sqrt(i*i + j*j + k*k); } /** * Normalise by dividing each component * by vector magnitude */ void vector3d::normalise(void) { float mag = magnitude(); if (mag) { i /= mag; j /= mag; k /= mag; } } /** * Add another vector to this one */ vector3d vector3d::operator+(vector3d v) const { vector3d temp(v.i + i, v.j + j, v.k + k); return temp; } /** * Subtract another vector from this one */ vector3d vector3d::operator-(vector3d v) const { vector3d temp(i - v.i, j - v.j, k - v.k); return temp; } /** * Scale this vector by a constant */ vector3d vector3d::operator*(float f) const { vector3d temp(i*f, j*f, k*f); return temp; } /** * Negate this vector */ vector3d vector3d::operator-() const { vector3d temp(-i, -j, -k); return temp; } /** * Write vector attributes to a stream * @param str Stream to write to * @param v Vector to operate on */ ostream& operator<<(ostream& str, const vector3d& v) { str << "[" << v.i << ", " << v.j << ", " << v.k << "]"; return str; }