| 1 | // LAF Base Library |
| 2 | // Copyright (c) 2001-2016 David Capello |
| 3 | // |
| 4 | // This file is released under the terms of the MIT license. |
| 5 | // Read LICENSE.txt for more information. |
| 6 | |
| 7 | #ifndef BASE_VECTOR2D_H_INCLUDED |
| 8 | #define BASE_VECTOR2D_H_INCLUDED |
| 9 | #pragma once |
| 10 | |
| 11 | #include <cmath> |
| 12 | |
| 13 | namespace base { |
| 14 | |
| 15 | template<typename T> |
| 16 | class Vector2d { |
| 17 | public: |
| 18 | T x, y; |
| 19 | |
| 20 | Vector2d() { |
| 21 | x = y = 0.0; |
| 22 | } |
| 23 | |
| 24 | Vector2d(const T& u, const T& v) { |
| 25 | x = u; y = v; |
| 26 | } |
| 27 | |
| 28 | Vector2d(const Vector2d& v) { |
| 29 | x = v.x; y = v.y; |
| 30 | } |
| 31 | |
| 32 | Vector2d operator-() const { return Vector2d(-x, -y); } |
| 33 | |
| 34 | Vector2d operator+(const Vector2d& v) const { return Vector2d(x+v.x, y+v.y); } |
| 35 | Vector2d operator-(const Vector2d& v) const { return Vector2d(x-v.x, y-v.y); } |
| 36 | T operator*(const Vector2d& v) const { return dotProduct(v); } |
| 37 | Vector2d operator*(const T& f) const { return Vector2d(x*f, y*f); } |
| 38 | Vector2d operator/(const T& f) const { return Vector2d(x/f, y/f); } |
| 39 | |
| 40 | Vector2d& operator= (const Vector2d& v) { x=v.x; y=v.y; return *this; } |
| 41 | Vector2d& operator+=(const Vector2d& v) { x+=v.x; y+=v.y; return *this; } |
| 42 | Vector2d& operator-=(const Vector2d& v) { x-=v.x; y-=v.y; return *this; } |
| 43 | Vector2d& operator*=(const T& f) { x*=f; y*=f; return *this; } |
| 44 | Vector2d& operator/=(const T& f) { x/=f; y/=f; return *this; } |
| 45 | |
| 46 | T magnitude() const { |
| 47 | return std::sqrt(x*x + y*y); |
| 48 | } |
| 49 | |
| 50 | T dotProduct(const Vector2d& v) const { |
| 51 | return x*v.x + y*v.y; |
| 52 | } |
| 53 | |
| 54 | Vector2d projectOn(const Vector2d& v) const { |
| 55 | return v * (this->dotProduct(v) / std::pow(v.magnitude(), 2)); |
| 56 | } |
| 57 | |
| 58 | T angle() const { |
| 59 | return std::atan2(y, x); |
| 60 | } |
| 61 | |
| 62 | Vector2d normalize() const { |
| 63 | return Vector2d(*this) / magnitude(); |
| 64 | } |
| 65 | |
| 66 | Vector2d getNormal() const { |
| 67 | return Vector2d(y, -x); |
| 68 | } |
| 69 | |
| 70 | }; |
| 71 | |
| 72 | } // namespace base |
| 73 | |
| 74 | template<typename T> |
| 75 | base::Vector2d<T> operator*(const T& f, const base::Vector2d<T>& v) { |
| 76 | return base::Vector2d<T>(v.x*f, v.y*f); |
| 77 | } |
| 78 | |
| 79 | #endif // BASE_VECTOR2D_H_INCLUDED |
| 80 | |