Skip to main content

hayro_syntax/
transform.rs

1// Copyright 2018 the Kurbo Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! 2D affine transformations.
5
6use core::ops::Mul;
7
8/// A 2D affine transform.
9#[derive(Clone, Copy, Debug, PartialEq)]
10pub struct Transform([f64; 6]);
11
12impl Transform {
13    /// The identity transform.
14    pub const IDENTITY: Self = Self::scale(1.0);
15
16    #[inline(always)]
17    pub(crate) const fn new(c: [f64; 6]) -> Self {
18        Self(c)
19    }
20
21    #[inline(always)]
22    pub(crate) const fn scale(s: f64) -> Self {
23        Self([s, 0.0, 0.0, s, 0.0, 0.0])
24    }
25
26    pub(crate) const ROTATE_CW_90: Self = Self::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0]);
27
28    pub(crate) const ROTATE_CCW_90: Self = Self::new([0.0, -1.0, 1.0, 0.0, 0.0, 0.0]);
29
30    #[inline(always)]
31    pub(crate) const fn translate(p: (f64, f64)) -> Self {
32        Self([1.0, 0.0, 0.0, 1.0, p.0, p.1])
33    }
34
35    /// Get the coefficients of the transform.
36    #[inline(always)]
37    pub const fn as_coeffs(self) -> [f64; 6] {
38        self.0
39    }
40}
41
42impl Mul for Transform {
43    type Output = Self;
44
45    #[inline]
46    fn mul(self, other: Self) -> Self {
47        Self([
48            self.0[0] * other.0[0] + self.0[2] * other.0[1],
49            self.0[1] * other.0[0] + self.0[3] * other.0[1],
50            self.0[0] * other.0[2] + self.0[2] * other.0[3],
51            self.0[1] * other.0[2] + self.0[3] * other.0[3],
52            self.0[0] * other.0[4] + self.0[2] * other.0[5] + self.0[4],
53            self.0[1] * other.0[4] + self.0[3] * other.0[5] + self.0[5],
54        ])
55    }
56}