]> git.localhorst.tv Git - space.git/blobdiff - src/graphics/Vector.h
force based movement
[space.git] / src / graphics / Vector.h
index b5c6d7d11dd9f9452c0a65b781a511b8fa9603ad..992ba1eef6a8bbdc323b8f612eef14eb2471f7d7 100644 (file)
@@ -2,7 +2,9 @@
 #define SPACE_VECTOR_H_
 
 #include <algorithm>
+#include <cmath>
 #include <ostream>
+#include <SDL.h>
 
 
 namespace space {
@@ -17,6 +19,12 @@ public:
        template<class Other>
        constexpr Vector(Vector<Other> other) : x(other.x), y(other.y) { }
 
+       static Vector<Scalar> FromPolar(Scalar rad, Scalar az) {
+               return Vector<Scalar>(rad * std::cos(az), rad * std::sin(az));
+       }
+
+       static constexpr Vector<Scalar> unit45 = Vector<Scalar>(-0.7071, 0.7071);
+
 public:
        Vector<Scalar> &operator +=(Vector<Scalar> other) {
                x += other.x;
@@ -29,12 +37,53 @@ public:
                return *this;
        }
 
+       SDL_Point ToPoint() const {
+               SDL_Point p;
+               p.x = x;
+               p.y = y;
+               return p;
+       }
+
 public:
        Scalar x;
        Scalar y;
 
 };
 
+template<class T>
+constexpr Vector<T> Vector<T>::unit45;
+
+/// specialization with same layout as SDL_Point
+template<>
+class Vector<int>
+: public SDL_Point {
+
+public:
+       constexpr Vector() : SDL_Point({0, 0}) { }
+       constexpr Vector(int x, int y) : SDL_Point({x, y}) { }
+
+       template<class Other>
+       constexpr Vector(Vector<Other> other)
+       : SDL_Point({int(other.x), int(other.y)}) { }
+
+public:
+       Vector<int> &operator +=(Vector<int> other) {
+               x += other.x;
+               y += other.y;
+               return *this;
+       }
+       Vector<int> &operator -=(Vector<int> other) {
+               x -= other.x;
+               y -= other.y;
+               return *this;
+       }
+
+       SDL_Point ToPoint() const {
+               return *this;
+       }
+
+};
+
 
 template<class Scalar>
 constexpr Vector<Scalar> operator -(Vector<Scalar> v) {
@@ -93,6 +142,29 @@ constexpr bool operator !=(Vector<Scalar> lhs, Vector<Scalar> rhs) {
 }
 
 
+template<class Scalar>
+constexpr Scalar Dot(Vector<Scalar> lhs, Vector<Scalar> rhs) {
+       return (lhs.x * rhs.x) + (lhs.y * rhs.y);
+}
+template<class Scalar>
+constexpr Scalar Length(Vector<Scalar> v) {
+       return std::sqrt(Dot(v, v));
+}
+
+template<class Scalar>
+constexpr Vector<Scalar> Rotate90(Vector<Scalar> v) {
+       return Vector<Scalar>(-v.y, v.x);
+}
+template<class Scalar>
+constexpr Vector<Scalar> Rotate180(Vector<Scalar> v) {
+       return -v;
+}
+template<class Scalar>
+constexpr Vector<Scalar> Rotate270(Vector<Scalar> v) {
+       return Vector<Scalar>(v.y, -v.x);
+}
+
+
 template<class Scalar>
 inline std::ostream &operator <<(std::ostream &out, Vector<Scalar> v) {
        return out << '<' << v.x << ',' << v.y << '>';