# neglect / neglect / cpplib / include / neglect / quaternion.hpp

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136``` ```/* platform independence utilities */ #ifndef _INC_NEGLECT_QUATERNION_HPP_ #define _INC_NEGLECT_QUATERNION_HPP_ #include #include #include #include namespace neglect { /* implements quaternions. we represent quaternions as a scalar w plus a three dimensional vector x, y, z. */ template class quaternion { public: T w; vector vec; quaternion() { } quaternion(T w, T x, T y, T z) : w(w), vec(x, y, z) { } quaternion(T w, const vector &vec) : w(w), vec(vec) { } static quaternion zero() { quaternion rv; rv.set_zero(); return rv; } // pointer access T *ptr() { return &w; } const T *ptr() const { return &w; } // element access T &operator[](size_t idx) { return *(&w + i); } T operator[](size_t idx) const { return *(&w + i); } void set_zero() { w = vec.x = vec.y = vec.z = T(); } quaternion operator-() const { return quaternion(-w, -vec); } }; /* multiply two quaternions */ template quaternion operator*(const quaternion &lhs, const quaternion &rhs) { return quaternion(lhs.w * rhs.w - dot(lhs.vec, rhs.vec), (lhs.w * rhs.vec) + (rhs.w * lhs.vec) + cross(lhs.vec, rhs.vec)); } template quaternion &operator*=(quaternion &lhs, const quaternion &rhs) { lhs = lhs * rhs; return lhs; } /* compare two quaternions */ template bool operator==(const quaternion &q1, const quaternion &q2) { return q1.w == q2.w && q1.vec == q2.vec; } template bool operator!=(const quaternion &q1, const quaternion &q2) { return !(q1 == q2); } template bool almost_equal(const quaternion &q1, const quaternion &q2) { return almost_equal(q1.w, q2.w) && almost_equal(q1.vec, q2.vec); } /* calculate the inverse of a quaternion */ template quaternion inverse(const quaternion &q) { return quaternion(q.w, -q.vec); } /* calculate the dot product */ template T dot(const quaternion &lhs, const quaternion &rhs) { return lhs.w * rhs.w + dot(lhs.vec, rhs.vec); } typedef quaternion quat; typedef quaternion quati; } #endif ```