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
use alga::general::Real;
use alga::linear::Transformation;
use na;
use num_traits::Float;
use {BoundingBox, Object, PrimitiveParameters};

#[derive(Clone, Debug)]
/// AffineTransformer is a primitive that takes an object as input and allows to modify it using
/// affine transforms.
/// Usually it is used indirectly through ```Object::scale()```, ```Object::translate()``` or ```Object::rotate()```.
pub struct AffineTransformer<S: Real> {
    object: Box<Object<S>>,
    transform: na::Matrix4<S>,
    scale_min: S,
    bbox: BoundingBox<S>,
}

impl<S: Real + Float + From<f32>> Object<S> for AffineTransformer<S> {
    fn approx_value(&self, p: &na::Point3<S>, slack: S) -> S {
        let approx = self.bbox.distance(p);
        if approx <= slack {
            self.object
                .approx_value(&self.transform.transform_point(&p), slack / self.scale_min)
                * self.scale_min
        } else {
            approx
        }
    }
    fn bbox(&self) -> &BoundingBox<S> {
        &self.bbox
    }
    fn set_parameters(&mut self, p: &PrimitiveParameters<S>) {
        self.object.set_parameters(p);
    }
    fn normal(&self, p: &na::Point3<S>) -> na::Vector3<S> {
        self.transform
            .transform_vector(&self.object.normal(&self.transform.transform_point(&p)))
            .normalize()
    }
    fn translate(&self, v: &na::Vector3<S>) -> Box<Object<S>> {
        let new_trans = self.transform.append_translation(&-v);
        AffineTransformer::new_with_scaler(self.object.clone(), new_trans, self.scale_min)
    }
    fn rotate(&self, r: &na::Vector3<S>) -> Box<Object<S>> {
        let euler = ::na::Rotation::from_euler_angles(r.x, r.y, r.z).to_homogeneous();
        let new_trans = self.transform * euler;
        AffineTransformer::new_with_scaler(self.object.clone(), new_trans, self.scale_min)
    }
    fn scale(&self, s: &na::Vector3<S>) -> Box<Object<S>> {
        let one: S = From::from(1f32);
        let new_trans = self.transform.append_nonuniform_scaling(&na::Vector3::new(
            one / s.x,
            one / s.y,
            one / s.z,
        ));
        AffineTransformer::new_with_scaler(
            self.object.clone(),
            new_trans,
            self.scale_min * Float::min(s.x, Float::min(s.y, s.z)),
        )
    }
}

impl<S: Real + Float + From<f32>> AffineTransformer<S> {
    fn identity(o: Box<Object<S>>) -> Box<Object<S>> {
        AffineTransformer::new(o, na::Matrix4::identity())
    }
    fn new(o: Box<Object<S>>, t: na::Matrix4<S>) -> Box<AffineTransformer<S>> {
        let one: S = From::from(1f32);
        AffineTransformer::new_with_scaler(o, t, one)
    }
    fn new_with_scaler(
        o: Box<Object<S>>,
        t: na::Matrix4<S>,
        scale_min: S,
    ) -> Box<AffineTransformer<S>> {
        // TODO: Calculate scale_min from t.
        // This should be something similar to
        // 1./Vector::new(t.x.x, t.y.x, t.z.x).magnitude().min(
        // 1./Vector::new(t.x.y, t.y.y, t.z.y).magnitude().min(
        // 1./Vector::new(t.x.z, t.y.z, t.z.z).magnitude()))

        match t.try_inverse() {
            None => panic!("Failed to invert {:?}", t),
            Some(t_inv) => {
                let bbox = o.bbox().transform(&t_inv);
                Box::new(AffineTransformer {
                    object: o,
                    transform: t,
                    scale_min,
                    bbox,
                })
            }
        }
    }
    /// Create a new translated version of the input.
    pub fn new_translate(o: Box<Object<S>>, v: &na::Vector3<S>) -> Box<Object<S>> {
        AffineTransformer::identity(o).translate(v)
    }
    /// Create a new rotated version of the input.
    pub fn new_rotate(o: Box<Object<S>>, r: &na::Vector3<S>) -> Box<Object<S>> {
        AffineTransformer::identity(o).rotate(r)
    }
    /// Create a new scaled version of the input.
    pub fn new_scale(o: Box<Object<S>>, s: &na::Vector3<S>) -> Box<Object<S>> {
        AffineTransformer::identity(o).scale(s)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[derive(Clone, Debug, PartialEq)]
    pub struct MockObject<S: Real> {
        value: S,
        normal: na::Vector3<S>,
        bbox: BoundingBox<S>,
    }

    impl<S: ::std::fmt::Debug + Float + Real> MockObject<S> {
        pub fn new(value: S, normal: na::Vector3<S>) -> Box<MockObject<S>> {
            Box::new(MockObject {
                value,
                normal,
                bbox: BoundingBox::infinity(),
            })
        }
    }

    impl<S: ::std::fmt::Debug + Real + Float + From<f32>> Object<S> for MockObject<S> {
        fn approx_value(&self, _: &na::Point3<S>, _: S) -> S {
            self.value
        }
        fn normal(&self, _: &na::Point3<S>) -> na::Vector3<S> {
            self.normal
        }
        fn bbox(&self) -> &BoundingBox<S> {
            &self.bbox
        }
    }

    #[test]
    fn translate() {
        let mock_object = MockObject::new(1.0, na::Vector3::new(1.0, 0.0, 0.0));
        let translated = mock_object.translate(&na::Vector3::new(0.0001, 0.0, 0.0));
        let p = na::Point3::new(1.0, 0.0, 0.0);
        assert_eq!(mock_object.normal(&p), translated.normal(&p));
    }
}