00001 # ifndef VECTOR3D_H
00002 # define VECTOR3D_H
00003
00004 #include <math.h>
00005
00006 #define vector3d_ZERO 1.0E-9
00007
00009 class vector3d
00010 {
00011 public:
00013 union
00014 {
00015 struct { double x, y, z; };
00016 double c[3];
00017 };
00018
00020 vector3d() : x(0.0), y(0.0), z(0.0) {}
00021
00023 vector3d(double X, double Y, double Z) : x(X), y(Y), z(Z) {}
00024
00026 double operator[](int i) const {
00027 return c[i];
00028 }
00029
00031 double& operator[](int i) {
00032 return c[i];
00033 }
00034
00038 operator const double*() const {
00039 return c;
00040 }
00041
00043 vector3d& operator=(const vector3d& v)
00044 {
00045 x = v.x; y = v.y; z = v.z;
00046 return *this;
00047 }
00048
00050 friend vector3d operator-(const vector3d &a, const vector3d &b)
00051 {
00052 return vector3d(a.x-b.x, a.y-b.y, a.z-b.z);
00053 }
00054
00056 friend double operator*(const vector3d &a, const vector3d &b)
00057 {
00058 return a.x*b.x + a.y*b.y + a.z*b.z;
00059 }
00060
00062 friend vector3d operator*(const vector3d &a, float k)
00063 {
00064 return vector3d(a.x*k, a.y*k, a.z*k);
00065 }
00066
00068 friend vector3d operator*(float k, const vector3d &a)
00069 {
00070 return a*k;
00071 }
00072
00074 friend vector3d operator+(const vector3d &a, const vector3d &b)
00075 {
00076 return vector3d(a.x+b.x, a.y+b.y, a.z+b.z);
00077 }
00078
00086
00091 friend vector3d operator/(const vector3d &a, double k)
00092 {
00093 return vector3d(a.x/k, a.y/k, a.z/k);
00094 }
00095
00105
00108 vector3d& operator/=(double k)
00109 {
00110 x /=k;
00111 y /=k;
00112 z /=k;
00113 return *this;
00114 }
00115
00120 friend bool operator==(const vector3d &a, const vector3d &b)
00121 {
00122
00123 return(a-b).norm() < vector3d_ZERO;
00124
00125 }
00126
00130 friend vector3d cross(const vector3d &a, const vector3d &b)
00131 {
00132 return vector3d(a.y*b.z - a.z*b.y,
00133 a.z*b.x - a.x*b.z,
00134 a.x*b.y - a.y*b.x);
00135 }
00136
00139 double squaredNorm() const { return (x*x + y*y + z*z); }
00140
00143 double norm() const { return sqrt(x*x + y*y + z*z); }
00144
00149 vector3d project(const vector3d &a)
00150 {
00151 double k=(*this * a)/squaredNorm();
00152 return vector3d(a.x*k,a.y*k,a.z*k);
00153
00154
00155 }
00156
00161 double normalize()
00162 {
00163 double b=norm();
00164 if (b < vector3d_ZERO)
00165 {
00166 return(-1);
00167 }
00168 *this /=b;
00169 return(b);
00170 }
00171
00172
00176 static double vecAngle(const vector3d &a, const vector3d &b)
00177 {
00178 double sprodukt;
00179 double n1,q,an,ang;
00180
00181 sprodukt=a*b;
00182 n1=a.norm()*b.norm();
00183 q=sprodukt/n1;
00184 an=acos(q);
00185 ang=an*360/(2*3.1415);
00186 return(ang);
00187 }
00188
00192 static double vecRadAngle(const vector3d &a, const vector3d &b)
00193 {
00194 double sprodukt;
00195 double n1,q,an,ang;
00196
00197 sprodukt=a*b;
00198 n1=a.norm()*b.norm();
00199 q=sprodukt/n1;
00200 an=acos(q);
00201 return(ang);
00202 }
00203
00204 };
00205
00206 #endif