CanvasLib
Loading...
Searching...
No Matches
Vec2.hpp
1#pragma once
2#include <cmath>
3#include <cstdint>
4#include <iostream>
5#include <sstream>
6
7namespace canv
8{
9
14template <typename T>
15class Vec2
16{
17public:
22 : X(0),
23 Y(0)
24 {
25 }
26
27 Vec2(T x, T y) // NOLINT
28 : X(x),
29 Y(y)
30 {
31 }
32
36 template <typename U>
37 auto DistToSquared(const Vec2<U>& other)
38 {
39 return (X - other.X) * (X - other.X) + (Y - other.Y) * (Y - other.Y);
40 }
41
45 template <typename U>
46 auto DistTo(const Vec2<U>& other)
47 {
48 return std::sqrt(DistToSquared(other));
49 }
50
51 auto AsTuple() const -> std::tuple<T, T>
52 {
53 return std::make_tuple(X, Y);
54 }
55
56 template <typename U>
57 auto operator+=(const Vec2<U>& other) -> Vec2<T>&
58 {
59 X += other.X;
60 Y += other.Y;
61 return *this;
62 }
63 template <typename U>
64 auto operator-=(const Vec2<U>& other) -> Vec2<T>&
65 {
66 X -= other.X;
67 Y -= other.Y;
68 return *this;
69 }
70 explicit operator std::string()
71 {
72 std::stringstream ss;
73 ss << *this;
74 return ss.str();
75 }
76
77 template <typename U>
78 friend auto operator<<(std::ostream&, const Vec2<U>&) -> std::ostream&;
79 template <typename R, typename U>
80 friend auto operator*(const Vec2<R>& vec, const U& value) -> Vec2<R>;
81 template <typename R, typename U>
82 friend auto operator*(const U& value, const Vec2<R>& vec) -> Vec2<R>;
83
84 T X;
85 T Y;
86};
87
88using Vec2f = Vec2<float>;
89using Vec2d = Vec2<double>;
90using Vec2i = Vec2<int32_t>;
91using Vec2ui = Vec2<uint32_t>;
92
93template <typename T, typename U>
94auto operator*(const Vec2<T>& vec, const U& value) -> Vec2<T>
95{
96 return { vec.X * static_cast<T>(value), vec.Y * static_cast<T>(value) };
97}
98template <typename T, typename U>
99auto operator*(const U& value, const Vec2<T>& vec) -> Vec2<T>
100{
101 return { vec.X * static_cast<T>(value), vec.Y * static_cast<T>(value) };
102}
103
104template <typename U>
105auto operator<<(std::ostream& out, const Vec2<U>& v) -> std::ostream&
106{
107 return out << "Vec2<" << typeid(U).name() << ">(" << v.X << "," << v.Y
108 << ")";
109}
110
111} // namespace canv
Utility Vec2 class with x, y coordinates.
Definition Vec2.hpp:16
auto DistToSquared(const Vec2< U > &other)
returns distance^2 to other point
Definition Vec2.hpp:37
auto DistTo(const Vec2< U > &other)
returns distance to other point
Definition Vec2.hpp:46
Vec2()
creates Vec2 with 0, 0 coordinates
Definition Vec2.hpp:21
Definition CanvasLib.hpp:44