]> git.lizzy.rs Git - nothing.git/blob - src/math/vec.h
point.h -> vec.h
[nothing.git] / src / math / vec.h
1 #ifndef POINT_H_
2 #define POINT_H_
3
4 #include "math/pi.h"
5
6 typedef struct Point {
7     float x, y;
8 } Point;
9
10 typedef Point Vec;
11
12 static inline
13 Vec vec(float x, float y)
14 {
15     Vec result = {
16         .x = x,
17         .y = y
18     };
19     return result;
20 }
21
22 static inline
23 Vec vec_scala_mult(Vec v, float scalar)
24 {
25     Vec result = {
26         .x = v.x * scalar,
27         .y = v.y * scalar
28     };
29     return result;
30 }
31
32 static inline
33 Vec vec_from_polar(float arg, float mag)
34 {
35     return vec_scala_mult(
36         vec(cosf(arg), sinf(arg)),
37         mag);
38 }
39
40 static inline
41 Vec vec_from_ps(Point p1, Point p2)
42 {
43     Vec result = {
44         .x = p2.x - p1.x,
45         .y = p2.y - p1.y
46     };
47     return result;
48 }
49
50 static inline
51 float vec_arg(Vec v)
52 {
53     return atan2f(v.y, v.x);
54 }
55
56 static inline
57 float vec_mag(Vec v)
58 {
59     return sqrtf(v.x * v.x + v.y * v.y);
60 }
61
62 static inline
63 Vec vec_sum(Vec v1, Vec v2)
64 {
65     Vec result = {
66         .x = v1.x + v2.x,
67         .y = v1.y + v2.y
68     };
69     return result;
70 }
71
72 static inline
73 Vec vec_sub(Vec v1, Vec v2)
74 {
75     Vec result = {
76         .x = v1.x - v2.x,
77         .y = v1.y - v2.y
78     };
79     return result;
80 }
81
82 static inline
83 Vec vec_neg(Vec v)
84 {
85     Vec result = {
86         .x = -v.x,
87         .y = -v.y
88     };
89
90     return result;
91 }
92
93 static inline
94 float vec_length(Vec v)
95 {
96     return sqrtf(v.x * v.x + v.y * v.y);
97 }
98
99 static inline
100 void vec_add(Vec *v1, Vec v2)
101 {
102     v1->x += v2.x;
103     v1->y += v2.y;
104 }
105
106 static inline
107 Vec vec_entry_mult(Vec v1, Vec v2)
108 {
109     Vec result = {
110         .x = v1.x * v2.x,
111         .y = v1.y * v2.y
112     };
113
114     return result;
115 }
116
117 static inline
118 Vec vec_entry_div(Vec v1, Vec v2)
119 {
120     Vec result = {
121         .x = v1.x / v2.x,
122         .y = v1.y / v2.y
123     };
124
125     return result;
126 }
127
128 static inline
129 float rad_to_deg(float a)
130 {
131     return 180 / PI * a;
132 }
133
134 static inline
135 Vec vec_norm(Vec v)
136 {
137     // TODO(#657): math/point/vec_norm: using vec_length is too expensive
138     //   It involves multiplication and sqrt. We can just check if its components are close to 0.0f.
139
140     const float l = vec_length(v);
141
142     if (l < 1e-6) {
143         return vec(0.0f, 0.0f);
144     }
145
146     return vec(v.x / l, v.y / l);
147 }
148
149 static inline
150 float vec_sqr_norm(Vec v)
151 {
152     return v.x * v.x + v.y * v.y;
153 }
154
155 #define vec_scale vec_scala_mult
156
157 #endif  // POINT_H_