rive_rs/math/
vec.rs

1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
6
7use crate::math::Mat;
8
9#[derive(Clone, Copy, Debug, Default, PartialEq)]
10pub struct Vec {
11    pub x: f32,
12    pub y: f32,
13}
14
15impl Vec {
16    pub const fn new(x: f32, y: f32) -> Self {
17        Self { x, y }
18    }
19
20    pub fn transform_dir(self, mat: &Mat) -> Self {
21        Self {
22            x: self.x * mat.scale_x + self.y * mat.shear_y,
23            y: self.x * mat.shear_x + self.y * mat.scale_y,
24        }
25    }
26
27    pub fn length(self) -> f32 {
28        (self.x * self.x + self.y * self.y).sqrt()
29    }
30
31    pub fn distance(self, other: Self) -> f32 {
32        (self - other).length()
33    }
34
35    pub fn normalize(self) -> Self {
36        let length = self.length();
37
38        if length > 0.0 {
39            self * length.recip()
40        } else {
41            self
42        }
43    }
44
45    pub fn dot(self, other: Self) -> f32 {
46        self.x * other.x + self.y * other.y
47    }
48
49    pub fn lerp(self, other: Self, ratio: f32) -> Self {
50        self + (other - self) * ratio
51    }
52}
53
54impl Eq for Vec {}
55
56impl Add for Vec {
57    type Output = Self;
58
59    fn add(self, rhs: Self) -> Self::Output {
60        Vec::new(self.x + rhs.x, self.y + rhs.y)
61    }
62}
63
64impl AddAssign for Vec {
65    fn add_assign(&mut self, rhs: Self) {
66        *self = *self + rhs;
67    }
68}
69
70impl Sub for Vec {
71    type Output = Self;
72
73    fn sub(self, rhs: Self) -> Self::Output {
74        Vec::new(self.x - rhs.x, self.y - rhs.y)
75    }
76}
77
78impl SubAssign for Vec {
79    fn sub_assign(&mut self, rhs: Self) {
80        *self = *self - rhs;
81    }
82}
83
84impl Mul for Vec {
85    type Output = Self;
86
87    fn mul(self, rhs: Self) -> Self::Output {
88        Self::new(self.x * rhs.x, self.y * rhs.y)
89    }
90}
91
92impl Mul<f32> for Vec {
93    type Output = Self;
94
95    fn mul(self, rhs: f32) -> Self::Output {
96        Self::new(self.x * rhs, self.y * rhs)
97    }
98}
99
100impl Div for Vec {
101    type Output = Self;
102
103    fn div(self, rhs: Self) -> Self::Output {
104        Self::new(self.x / rhs.x, self.y / rhs.y)
105    }
106}
107
108impl Neg for Vec {
109    type Output = Self;
110
111    fn neg(self) -> Self::Output {
112        Self::new(-self.x, -self.y)
113    }
114}