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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
/*----------------------------------------------------------------------------------------------------------
 *  Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/piot/fixed32-math-rs
 *  Licensed under the MIT License. See LICENSE in the project root for license information.
 *--------------------------------------------------------------------------------------------------------*/

/*!
# Vector and Rect Library

This Rust crate that provides efficient 2D vector and rectangle operations using fixed-point arithmetic.
Designed for applications where fixed precision is preferred, this crate is ideal for scenarios such as graphics programming,
game development, and embedded systems where deterministic results are crucial.
*/

use core::fmt;
use core::ops::{Add, AddAssign, Div, Mul, Neg, Sub};

use fixed32::Fp;

mod test;

/// Represents a vector in a 2D space.
///
#[derive(Default, PartialEq, Clone, Copy)]
pub struct Vector {
    pub x: Fp,
    pub y: Fp,
}

impl Vector {
    /// Creates a new `Vector` with the specified `x` and `y` components.
    ///
    /// # Parameters
    /// - `x`: The x-coordinate of the vector.
    /// - `y`: The y-coordinate of the vector.
    ///
    /// # Returns
    /// A `Vector` instance with the given `x` and `y` components.
    ///
    /// # Examples
    ///
    /// ```
    /// use fixed32::Fp;
    /// use fixed32_math::Vector;
    ///
    /// let v = Vector::new(Fp::from(2), Fp::from(3));
    /// assert_eq!(v.x, Fp::from(2));
    /// assert_eq!(v.y, Fp::from(3));
    /// ```
    pub fn new(x: Fp, y: Fp) -> Self {
        Self { x, y }
    }

    /// Returns a `Vector` pointing to the left (negative x-axis direction).
    ///
    /// This is a convenience method to create a vector that represents a direction
    /// to the left in 2D space.
    ///
    /// # Returns
    /// A `Vector` instance with `x` set to `-1` and `y` set to `0`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fixed32::Fp;
    /// use fixed32_math::Vector;
    ///
    /// let left = Vector::left();
    /// assert_eq!(left.x, Fp::neg_one());
    /// assert_eq!(left.y, Fp::zero());
    /// ```
    #[inline]
    pub fn left() -> Self {
        Self {
            x: Fp::neg_one(),
            y: Fp::zero(),
        }
    }

    /// Returns a `Vector` pointing to the right (positive x-axis direction).
    ///
    /// This is a convenience method to create a vector that represents a direction
    /// to the right in 2D space.
    ///
    /// # Returns
    /// A `Vector` instance with `x` set to `1` and `y` set to `0`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fixed32::Fp;
    /// use fixed32_math::Vector;
    ///
    /// let right = Vector::right();
    /// assert_eq!(right.x, Fp::one());
    /// assert_eq!(right.y, Fp::zero());
    /// ```
    #[inline]
    pub fn right() -> Self {
        Self {
            x: Fp::one(),
            y: Fp::zero(),
        }
    }

    /// Returns a `Vector` pointing upwards (positive y-axis direction).
    ///
    /// This is a convenience method to create a vector that represents a direction
    /// upwards in 2D space.
    ///
    /// # Returns
    /// A `Vector` instance with `x` set to `0` and `y` set to `1`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fixed32::Fp;
    /// use fixed32_math::Vector;
    ///
    /// let up = Vector::up();
    /// assert_eq!(up.x, Fp::zero());
    /// assert_eq!(up.y, Fp::one());
    /// ```
    #[inline]
    pub fn up() -> Self {
        Self {
            x: Fp::zero(),
            y: Fp::one(),
        }
    }

    /// Returns a `Vector` pointing downwards (negative y-axis direction).
    ///
    /// This is a convenience method to create a vector that represents a direction
    /// downwards in 2D space.
    ///
    /// # Returns
    /// A `Vector` instance with `x` set to `0` and `y` set to `-1`.
    ///
    /// # Examples
    ///
    /// ```
    /// use fixed32::Fp;
    /// use fixed32_math::Vector;
    ///
    /// let down = Vector::down();
    /// assert_eq!(down.x, Fp::zero());
    /// assert_eq!(down.y, Fp::neg_one());
    /// ```
    #[inline]
    pub fn down() -> Self {
        Self {
            x: Fp::zero(),
            y: Fp::neg_one(),
        }
    }

    /// Computes the squared length (magnitude) of the vector.
    ///
    /// This method calculates the squared length of the vector, which is the sum of the
    /// squares of its `x` and `y` components. It is often used for performance reasons when
    /// the actual length is not needed, as computing the square root can be costly.
    ///
    /// # Returns
    /// The squared length of the vector as an [`Fp`] value.
    ///
    /// # Examples
    ///
    /// ```
    /// use fixed32::Fp;
    /// use fixed32_math::Vector;
    ///
    /// let v = Vector::new(Fp::from(3), Fp::from(4));
    /// let sqr_len = v.sqr_len();
    /// assert_eq!(sqr_len, Fp::from(25));
    /// ```
    pub fn sqr_len(&self) -> Fp {
        self.x * self.x + self.y * self.y
    }

    /// Returns the length of the vector.
    pub fn len(&self) -> Fp {
        self.sqr_len().sqrt()
    }

    /// Returns a normalized vector with length 1. Returns `None` if the vector is zero-length.
    pub fn normalize(&self) -> Option<Self> {
        let length = self.len();
        if length.is_zero() {
            None
        } else {
            Some(Self {
                x: self.x / length,
                y: self.y / length,
            })
        }
    }

    /// Computes the dot product of this vector with another.
    pub fn dot(&self, other: &Self) -> Fp {
        self.x * other.x + self.y * other.y
    }

    /// Computes the magnitude of the cross product in 2D (which is a scalar value).
    pub fn cross(&self, other: &Self) -> Fp {
        self.x * other.y - self.y * other.x
    }

    /// Scales the vector by another vector component-wise.
    pub fn scale(&self, factor: &Self) -> Self {
        Self {
            x: self.x * factor.x,
            y: self.y * factor.y,
        }
    }

    /// Rotates the vector by the given angle in radians.
    pub fn rotate(&self, angle: Fp) -> Self {
        let cos_angle = angle.cos();
        let sin_angle = angle.sin();
        Self {
            x: self.x * cos_angle - self.y * sin_angle,
            y: self.x * sin_angle + self.y * cos_angle,
        }
    }

    /// Returns the absolute value of each component of the vector.
    pub fn abs(&self) -> Self {
        Self {
            x: self.x.abs(),
            y: self.y.abs(),
        }
    }
}

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

impl fmt::Display for Vector {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "vec:{},{}", self.x, self.y)
    }
}

impl From<(i16, i16)> for Vector {
    fn from(values: (i16, i16)) -> Self {
        Self {
            x: Fp::from(values.0),
            y: Fp::from(values.1),
        }
    }
}

impl From<(f32, f32)> for Vector {
    fn from(values: (f32, f32)) -> Self {
        Self {
            x: Fp::from(values.0),
            y: Fp::from(values.1),
        }
    }
}

impl Sub for Vector {
    type Output = Vector;

    fn sub(self, rhs: Self) -> Self::Output {
        Self {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
        }
    }
}

impl Add for Vector {
    type Output = Vector;

    fn add(self, rhs: Self) -> Self::Output {
        Self {
            x: self.x + rhs.x,
            y: self.y + rhs.y,
        }
    }
}

impl AddAssign for Vector {
    fn add_assign(&mut self, rhs: Self) {
        self.x += rhs.x;
        self.y += rhs.y;
    }
}

impl Mul<Vector> for Vector {
    type Output = Vector;

    fn mul(self, rhs: Vector) -> Self::Output {
        Vector {
            x: self.x * rhs.x,
            y: self.y * rhs.y,
        }
    }
}

impl Mul<Vector> for Fp {
    type Output = Vector;

    fn mul(self, rhs: Vector) -> Self::Output {
        Vector {
            x: self * rhs.x,
            y: self * rhs.y,
        }
    }
}

impl Mul<Fp> for Vector {
    type Output = Vector;

    fn mul(self, rhs: Fp) -> Self::Output {
        Vector {
            x: self.x * rhs,
            y: self.y * rhs,
        }
    }
}

impl Div<Vector> for Vector {
    type Output = Vector;

    fn div(self, rhs: Vector) -> Self::Output {
        Vector {
            x: self.x / rhs.x,
            y: self.y / rhs.y,
        }
    }
}

impl Div<Vector> for i16 {
    type Output = Vector;

    fn div(self, rhs: Vector) -> Self::Output {
        Vector {
            x: (self / rhs.x),
            y: (self / rhs.y),
        }
    }
}

impl Div<Fp> for Vector {
    type Output = Vector;

    fn div(self, rhs: Fp) -> Self::Output {
        Vector {
            x: self.x / rhs,
            y: self.y / rhs,
        }
    }
}

impl Div<i16> for Vector {
    type Output = Vector;

    fn div(self, rhs: i16) -> Self::Output {
        Vector {
            x: self.x / Fp::from(rhs),
            y: self.y / Fp::from(rhs),
        }
    }
}

impl Mul<Vector> for i16 {
    type Output = Vector;

    fn mul(self, rhs: Vector) -> Self::Output {
        Vector {
            x: self * rhs.x,
            y: self * rhs.y,
        }
    }
}

impl Mul<i16> for Vector {
    type Output = Vector;

    fn mul(self, rhs: i16) -> Self::Output {
        Vector {
            x: self.x * Fp::from(rhs),
            y: self.y * Fp::from(rhs),
        }
    }
}

impl Neg for Vector {
    type Output = Vector;

    fn neg(self) -> Self {
        Self {
            x: -self.x,
            y: -self.y,
        }
    }
}

/// Represents a rectangle in a 2D space.
///
/// The `Rect` struct is defined by its position (`pos`) and size (`size`), both of which are
/// represented as [`Vector`] instances. The position indicates the coordinates of the rectangle's
/// bottom-left corner, and the size indicates the width and height of the rectangle.
///
/// # Examples
///
/// Creating a new rectangle:
/// ```
/// use fixed32::Fp;
/// use fixed32_math::{Vector, Rect};
///
/// let pos = Vector::new(Fp::from(1), Fp::from(2));
/// let size = Vector::new(Fp::from(3), Fp::from(4));
/// let rect = Rect::new(pos, size);
/// ```
///
/// Accessing the position and size:
/// ```
/// use fixed32::Fp;
/// use fixed32_math::{Vector, Rect};
///
/// let pos = Vector::new(Fp::from(1), Fp::from(2));
/// let size = Vector::new(Fp::from(3), Fp::from(4));
/// let rect = Rect::new(pos, size);
/// assert_eq!(rect.pos.x, Fp::from(1));
/// assert_eq!(rect.size.y, Fp::from(4));
/// ```
#[derive(Debug, Default, PartialEq, Clone, Copy)]
pub struct Rect {
    pub pos: Vector,
    pub size: Vector,
}

impl Rect {
    /// Creates a new `Rect` with the specified position and size.
    ///
    /// # Parameters
    /// - `pos`: The position of the rectangle's top-left corner as a [`Vector`].
    /// - `size`: The size of the rectangle, including its width and height, as a [`Vector`].
    ///
    /// # Returns
    /// A `Rect` instance with the given position and size.
    ///
    /// # Examples
    ///
    /// ```
    /// use fixed32::Fp;
    /// use fixed32_math::{Vector, Rect};
    ///
    /// let pos = Vector::new(Fp::from(1), Fp::from(2));
    /// let size = Vector::new(Fp::from(3), Fp::from(4));
    /// let rect = Rect::new(pos, size);
    /// assert_eq!(rect.pos, pos);
    /// assert_eq!(rect.size, size);
    /// ```
    pub fn new(pos: Vector, size: Vector) -> Self {
        Self { pos, size }
    }

    /// Returns a new `Rect` with its position translated by the given vector.
    ///
    /// This method is useful for moving the rectangle while keeping its size unchanged.
    ///
    /// # Parameters
    /// - `offset`: A vector indicating how much to translate the rectangle's position.
    ///
    /// # Returns
    /// A new `Rect` with the position translated by the given vector. The size remains unchanged.
    ///
    /// # Examples
    ///
    /// ```
    /// use fixed32::Fp;
    /// use fixed32_math::{Rect, Vector};
    ///
    /// let pos = Vector::new(Fp::from(1), Fp::from(2));
    /// let size = Vector::new(Fp::from(3), Fp::from(4));
    /// let rect = Rect::new(pos, size);
    /// let offset = Vector::new(Fp::from(1), Fp::from(-1));
    /// let translated_rect = rect.move_by(offset);
    /// assert_eq!(translated_rect.pos.x, Fp::from(2));
    /// assert_eq!(translated_rect.pos.y, Fp::from(1));
    /// assert_eq!(translated_rect.size, size);
    /// ```
    pub fn move_by(self, offset: Vector) -> Self {
        Self {
            pos: self.pos + offset,
            size: self.size,
        }
    }

    /// Calculates the area of the rectangle.
    pub fn area(&self) -> Fp {
        self.size.x * self.size.y
    }

    /// Calculates the perimeter of the rectangle.
    pub fn perimeter(&self) -> Fp {
        2 * (self.size.x + self.size.y)
    }

    /// Calculates the intersection of two rectangles.
    pub fn intersection(&self, other: &Self) -> Option<Self> {
        let x_overlap = Fp::max(self.pos.x, other.pos.x)
            ..Fp::min(self.pos.x + self.size.x, other.pos.x + other.size.x);
        let y_overlap = Fp::max(self.pos.y, other.pos.y)
            ..Fp::min(self.pos.y + self.size.y, other.pos.y + other.size.y);

        if x_overlap.is_empty() || y_overlap.is_empty() {
            None
        } else {
            Some(Self {
                pos: Vector {
                    x: x_overlap.start,
                    y: y_overlap.start,
                },
                size: Vector {
                    x: x_overlap.end - x_overlap.start,
                    y: y_overlap.end - y_overlap.start,
                },
            })
        }
    }

    /// Calculates the union of two rectangles.
    pub fn union(&self, other: &Self) -> Self {
        let x_min = Fp::min(self.pos.x, other.pos.x);
        let y_min = Fp::min(self.pos.y, other.pos.y);
        let x_max = Fp::max(self.pos.x + self.size.x, other.pos.x + other.size.x);
        let y_max = Fp::max(self.pos.y + self.size.y, other.pos.y + other.size.y);

        Self {
            pos: Vector { x: x_min, y: y_min },
            size: Vector {
                x: x_max - x_min,
                y: y_max - y_min,
            },
        }
    }

    /// Checks if a point is inside the rectangle.
    pub fn contains_point(&self, point: &Vector) -> bool {
        point.x >= self.pos.x
            && point.x < self.pos.x + self.size.x
            && point.y >= self.pos.y
            && point.y < self.pos.y + self.size.y
    }

    /// Checks if another rectangle is completely inside this rectangle.
    pub fn contains_rect(&self, other: &Self) -> bool {
        self.contains_point(&other.pos) && self.contains_point(&(other.pos + other.size))
    }

    /// Expands the rectangle by a given offset.
    pub fn expanded(&self, offset: Vector) -> Self {
        Self {
            pos: self.pos - offset,
            size: self.size + offset * Fp::from(2.0),
        }
    }

    /// Contracts the rectangle by a given offset.
    pub fn contracted(&self, offset: Vector) -> Self {
        Self {
            pos: self.pos + offset,
            size: self.size - offset * Fp::from(2.0),
        }
    }

    /// Calculates the aspect ratio of the rectangle.
    pub fn aspect_ratio(&self) -> Fp {
        self.size.x / self.size.y
    }
}

impl From<(i16, i16, i16, i16)> for Rect {
    fn from(values: (i16, i16, i16, i16)) -> Self {
        Self {
            pos: Vector::from((values.0, values.1)),
            size: Vector::from((values.2, values.3)),
        }
    }
}

impl From<(f32, f32, f32, f32)> for Rect {
    fn from(values: (f32, f32, f32, f32)) -> Self {
        Self {
            pos: Vector::from((values.0, values.1)),
            size: Vector::from((values.2, values.3)),
        }
    }
}