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
use crate::{LinearTransformation, Point, Transform, Transformation, Vector};

#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(C)]
pub struct AffineTransformation {
    pub xy: LinearTransformation,
    pub z: Vector,
}

impl AffineTransformation {
    pub fn new(xy: LinearTransformation, z: Vector) -> AffineTransformation {
        AffineTransformation { xy, z }
    }

    pub fn identity() -> AffineTransformation {
        AffineTransformation::new(LinearTransformation::identity(), Vector::zero())
    }

    pub fn scaling(v: Vector) -> AffineTransformation {
        AffineTransformation::new(LinearTransformation::scaling(v), Vector::zero())
    }

    pub fn uniform_scaling(k: f32) -> AffineTransformation {
        AffineTransformation::new(LinearTransformation::uniform_scaling(k), Vector::zero())
    }

    pub fn translation(v: Vector) -> AffineTransformation {
        AffineTransformation::new(LinearTransformation::identity(), v)
    }

    pub fn scale(self, v: Vector) -> AffineTransformation {
        AffineTransformation::new(self.xy.scale(v), self.z.scale(v))
    }

    pub fn uniform_scale(self, k: f32) -> AffineTransformation {
        AffineTransformation::new(self.xy.uniform_scale(k), self.z * k)
    }

    pub fn translate(self, v: Vector) -> AffineTransformation {
        AffineTransformation::new(self.xy, self.z + v)
    }
}

impl Transformation for AffineTransformation {
    fn transform_point(&self, p: Point) -> Point {
        p.transform(&self.xy) + self.z
    }

    fn transform_vector(&self, v: Vector) -> Vector {
        v.transform(&self.xy)
    }
}