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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};

/// A vector has a direction and length.
/// A [`Vec2`] is often used to represent a size.
///
/// emath represents positions using [`crate::Pos2`].
///
/// Normally the units are points (logical pixels).
#[repr(C)]
#[derive(Clone, Copy, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]
pub struct Vec2 {
    /// Rightwards. Width.
    pub x: f32,

    /// Downwards. Height.
    pub y: f32,
}

/// `vec2(x, y) == Vec2::new(x, y)`
#[inline(always)]
pub const fn vec2(x: f32, y: f32) -> Vec2 {
    Vec2 { x, y }
}

// ----------------------------------------------------------------------------
// Compatibility and convenience conversions to and from [f32; 2]:

impl From<[f32; 2]> for Vec2 {
    #[inline(always)]
    fn from(v: [f32; 2]) -> Self {
        Self { x: v[0], y: v[1] }
    }
}

impl From<&[f32; 2]> for Vec2 {
    #[inline(always)]
    fn from(v: &[f32; 2]) -> Self {
        Self { x: v[0], y: v[1] }
    }
}

impl From<Vec2> for [f32; 2] {
    #[inline(always)]
    fn from(v: Vec2) -> Self {
        [v.x, v.y]
    }
}

impl From<&Vec2> for [f32; 2] {
    #[inline(always)]
    fn from(v: &Vec2) -> Self {
        [v.x, v.y]
    }
}

// ----------------------------------------------------------------------------
// Compatibility and convenience conversions to and from (f32, f32):

impl From<(f32, f32)> for Vec2 {
    #[inline(always)]
    fn from(v: (f32, f32)) -> Self {
        Self { x: v.0, y: v.1 }
    }
}

impl From<&(f32, f32)> for Vec2 {
    #[inline(always)]
    fn from(v: &(f32, f32)) -> Self {
        Self { x: v.0, y: v.1 }
    }
}

impl From<Vec2> for (f32, f32) {
    #[inline(always)]
    fn from(v: Vec2) -> Self {
        (v.x, v.y)
    }
}

impl From<&Vec2> for (f32, f32) {
    #[inline(always)]
    fn from(v: &Vec2) -> Self {
        (v.x, v.y)
    }
}

// ----------------------------------------------------------------------------
// Mint compatibility and convenience conversions

#[cfg(feature = "mint")]
impl From<mint::Vector2<f32>> for Vec2 {
    #[inline]
    fn from(v: mint::Vector2<f32>) -> Self {
        Self::new(v.x, v.y)
    }
}

#[cfg(feature = "mint")]
impl From<Vec2> for mint::Vector2<f32> {
    #[inline]
    fn from(v: Vec2) -> Self {
        Self { x: v.x, y: v.y }
    }
}

// ----------------------------------------------------------------------------

impl Vec2 {
    pub const X: Self = Self { x: 1.0, y: 0.0 };
    pub const Y: Self = Self { x: 0.0, y: 1.0 };

    pub const RIGHT: Self = Self { x: 1.0, y: 0.0 };
    pub const LEFT: Self = Self { x: -1.0, y: 0.0 };
    pub const UP: Self = Self { x: 0.0, y: -1.0 };
    pub const DOWN: Self = Self { x: 0.0, y: 1.0 };

    pub const ZERO: Self = Self { x: 0.0, y: 0.0 };
    pub const INFINITY: Self = Self::splat(f32::INFINITY);

    #[inline(always)]
    pub const fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }

    /// Set both `x` and `y` to the same value.
    #[inline(always)]
    pub const fn splat(v: f32) -> Self {
        Self { x: v, y: v }
    }

    /// Treat this vector as a position.
    /// `v.to_pos2()` is equivalent to `Pos2::default() + v`.
    #[inline(always)]
    pub fn to_pos2(self) -> crate::Pos2 {
        crate::Pos2 {
            x: self.x,
            y: self.y,
        }
    }

    /// Safe normalize: returns zero if input is zero.
    #[must_use]
    #[inline(always)]
    pub fn normalized(self) -> Self {
        let len = self.length();
        if len <= 0.0 {
            self
        } else {
            self / len
        }
    }

    /// Rotates the vector by 90°, i.e positive X to positive Y
    /// (clockwise in egui coordinates).
    #[inline(always)]
    pub fn rot90(self) -> Self {
        vec2(self.y, -self.x)
    }

    #[inline(always)]
    pub fn length(self) -> f32 {
        self.x.hypot(self.y)
    }

    #[inline(always)]
    pub fn length_sq(self) -> f32 {
        self.x * self.x + self.y * self.y
    }

    /// Measures the angle of the vector.
    ///
    /// ```
    /// # use emath::Vec2;
    /// use std::f32::consts::TAU;
    ///
    /// assert_eq!(Vec2::ZERO.angle(), 0.0);
    /// assert_eq!(Vec2::angled(0.0).angle(), 0.0);
    /// assert_eq!(Vec2::angled(1.0).angle(), 1.0);
    /// assert_eq!(Vec2::X.angle(), 0.0);
    /// assert_eq!(Vec2::Y.angle(), 0.25 * TAU);
    ///
    /// assert_eq!(Vec2::RIGHT.angle(), 0.0);
    /// assert_eq!(Vec2::DOWN.angle(), 0.25 * TAU);
    /// assert_eq!(Vec2::UP.angle(), -0.25 * TAU);
    /// ```
    #[inline(always)]
    pub fn angle(self) -> f32 {
        self.y.atan2(self.x)
    }

    /// Create a unit vector with the given CW angle (in radians).
    /// * An angle of zero gives the unit X axis.
    /// * An angle of 𝞃/4 = 90° gives the unit Y axis.
    ///
    /// ```
    /// # use emath::Vec2;
    /// use std::f32::consts::TAU;
    ///
    /// assert_eq!(Vec2::angled(0.0), Vec2::X);
    /// assert!((Vec2::angled(0.25 * TAU) - Vec2::Y).length() < 1e-5);
    /// ```
    #[inline(always)]
    pub fn angled(angle: f32) -> Self {
        let (sin, cos) = angle.sin_cos();
        vec2(cos, sin)
    }

    #[must_use]
    #[inline(always)]
    pub fn floor(self) -> Self {
        vec2(self.x.floor(), self.y.floor())
    }

    #[must_use]
    #[inline(always)]
    pub fn round(self) -> Self {
        vec2(self.x.round(), self.y.round())
    }

    #[must_use]
    #[inline(always)]
    pub fn ceil(self) -> Self {
        vec2(self.x.ceil(), self.y.ceil())
    }

    #[must_use]
    #[inline]
    pub fn abs(self) -> Self {
        vec2(self.x.abs(), self.y.abs())
    }

    /// True if all members are also finite.
    #[inline(always)]
    pub fn is_finite(self) -> bool {
        self.x.is_finite() && self.y.is_finite()
    }

    /// True if any member is NaN.
    #[inline(always)]
    pub fn any_nan(self) -> bool {
        self.x.is_nan() || self.y.is_nan()
    }

    #[must_use]
    #[inline]
    pub fn min(self, other: Self) -> Self {
        vec2(self.x.min(other.x), self.y.min(other.y))
    }

    #[must_use]
    #[inline]
    pub fn max(self, other: Self) -> Self {
        vec2(self.x.max(other.x), self.y.max(other.y))
    }

    /// The dot-product of two vectors.
    #[inline]
    pub fn dot(self, other: Self) -> f32 {
        self.x * other.x + self.y * other.y
    }

    /// Returns the minimum of `self.x` and `self.y`.
    #[must_use]
    #[inline(always)]
    pub fn min_elem(self) -> f32 {
        self.x.min(self.y)
    }

    /// Returns the maximum of `self.x` and `self.y`.
    #[inline(always)]
    #[must_use]
    pub fn max_elem(self) -> f32 {
        self.x.max(self.y)
    }

    /// Swizzle the axes.
    #[inline]
    #[must_use]
    pub fn yx(self) -> Self {
        Self {
            x: self.y,
            y: self.x,
        }
    }

    #[must_use]
    #[inline]
    pub fn clamp(self, min: Self, max: Self) -> Self {
        Self {
            x: self.x.clamp(min.x, max.x),
            y: self.y.clamp(min.y, max.y),
        }
    }
}

impl std::ops::Index<usize> for Vec2 {
    type Output = f32;

    #[inline(always)]
    fn index(&self, index: usize) -> &f32 {
        match index {
            0 => &self.x,
            1 => &self.y,
            _ => panic!("Vec2 index out of bounds: {index}"),
        }
    }
}

impl std::ops::IndexMut<usize> for Vec2 {
    #[inline(always)]
    fn index_mut(&mut self, index: usize) -> &mut f32 {
        match index {
            0 => &mut self.x,
            1 => &mut self.y,
            _ => panic!("Vec2 index out of bounds: {index}"),
        }
    }
}

impl Eq for Vec2 {}

impl Neg for Vec2 {
    type Output = Self;

    #[inline(always)]
    fn neg(self) -> Self {
        vec2(-self.x, -self.y)
    }
}

impl AddAssign for Vec2 {
    #[inline(always)]
    fn add_assign(&mut self, rhs: Self) {
        *self = Self {
            x: self.x + rhs.x,
            y: self.y + rhs.y,
        };
    }
}

impl SubAssign for Vec2 {
    #[inline(always)]
    fn sub_assign(&mut self, rhs: Self) {
        *self = Self {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
        };
    }
}

impl Add for Vec2 {
    type Output = Self;

    #[inline(always)]
    fn add(self, rhs: Self) -> Self {
        Self {
            x: self.x + rhs.x,
            y: self.y + rhs.y,
        }
    }
}

impl Sub for Vec2 {
    type Output = Self;

    #[inline(always)]
    fn sub(self, rhs: Self) -> Self {
        Self {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
        }
    }
}

/// Element-wise multiplication
impl Mul<Self> for Vec2 {
    type Output = Self;

    #[inline(always)]
    fn mul(self, vec: Self) -> Self {
        Self {
            x: self.x * vec.x,
            y: self.y * vec.y,
        }
    }
}

/// Element-wise division
impl Div<Self> for Vec2 {
    type Output = Self;

    #[inline(always)]
    fn div(self, rhs: Self) -> Self {
        Self {
            x: self.x / rhs.x,
            y: self.y / rhs.y,
        }
    }
}

impl MulAssign<f32> for Vec2 {
    #[inline(always)]
    fn mul_assign(&mut self, rhs: f32) {
        self.x *= rhs;
        self.y *= rhs;
    }
}

impl DivAssign<f32> for Vec2 {
    #[inline(always)]
    fn div_assign(&mut self, rhs: f32) {
        self.x /= rhs;
        self.y /= rhs;
    }
}

impl Mul<f32> for Vec2 {
    type Output = Self;

    #[inline(always)]
    fn mul(self, factor: f32) -> Self {
        Self {
            x: self.x * factor,
            y: self.y * factor,
        }
    }
}

impl Mul<Vec2> for f32 {
    type Output = Vec2;

    #[inline(always)]
    fn mul(self, vec: Vec2) -> Vec2 {
        Vec2 {
            x: self * vec.x,
            y: self * vec.y,
        }
    }
}

impl Div<f32> for Vec2 {
    type Output = Self;

    #[inline(always)]
    fn div(self, factor: f32) -> Self {
        Self {
            x: self.x / factor,
            y: self.y / factor,
        }
    }
}

impl std::fmt::Debug for Vec2 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{:.1} {:.1}]", self.x, self.y)
    }
}

#[test]
fn test_vec2() {
    macro_rules! almost_eq {
        ($left: expr, $right: expr) => {
            let left = $left;
            let right = $right;
            assert!((left - right).abs() < 1e-6, "{} != {}", left, right);
        };
    }
    use std::f32::consts::TAU;

    assert_eq!(Vec2::ZERO.angle(), 0.0);
    assert_eq!(Vec2::angled(0.0).angle(), 0.0);
    assert_eq!(Vec2::angled(1.0).angle(), 1.0);
    assert_eq!(Vec2::X.angle(), 0.0);
    assert_eq!(Vec2::Y.angle(), 0.25 * TAU);

    assert_eq!(Vec2::RIGHT.angle(), 0.0);
    assert_eq!(Vec2::DOWN.angle(), 0.25 * TAU);
    almost_eq!(Vec2::LEFT.angle(), 0.50 * TAU);
    assert_eq!(Vec2::UP.angle(), -0.25 * TAU);

    let mut assignment = vec2(1.0, 2.0);
    assignment += vec2(3.0, 4.0);
    assert_eq!(assignment, vec2(4.0, 6.0));

    let mut assignment = vec2(4.0, 6.0);
    assignment -= vec2(1.0, 2.0);
    assert_eq!(assignment, vec2(3.0, 4.0));

    let mut assignment = vec2(1.0, 2.0);
    assignment *= 2.0;
    assert_eq!(assignment, vec2(2.0, 4.0));

    let mut assignment = vec2(2.0, 4.0);
    assignment /= 2.0;
    assert_eq!(assignment, vec2(1.0, 2.0));
}