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
use crate::{
    eval::{BulkEvaluator, Interval, Shape, Tape, TracingEvaluator},
    Error,
};
use nalgebra::{Matrix4, Point3, Vector3};

/// A generic [`Shape`] that has been transformed by a 4x4 transform matrix
#[derive(Clone)]
pub struct TransformedShape<S> {
    shape: S,
    mat: Matrix4<f32>,
}

impl<S> TransformedShape<S> {
    /// Builds a new [`TransformedShape`] with the identity transform
    pub fn new(shape: S, mat: Matrix4<f32>) -> Self {
        Self { shape, mat }
    }

    /// Appends a translation to the transformation matrix
    pub fn translate(&mut self, offset: Vector3<f32>) {
        self.mat.append_translation_mut(&offset);
    }

    /// Appends a uniform scale to the transformation matrix
    pub fn scale(&mut self, scale: f32) {
        self.mat.append_scaling_mut(scale);
    }

    /// Resets to the identity transform matrix
    pub fn reset(&mut self) {
        self.mat = Matrix4::identity();
    }

    /// Sets the transform matrix
    pub fn set_transform(&mut self, mat: Matrix4<f32>) {
        self.mat = mat;
    }
}

/// A generic [`Tape`] with an associated 4x4 transform matrix
pub struct TransformedTape<T> {
    tape: T,
    mat: Matrix4<f32>,
}

impl<T: Tape> Tape for TransformedTape<T> {
    type Storage = <T as Tape>::Storage;
    fn recycle(self) -> Self::Storage {
        self.tape.recycle()
    }
}

/// A generic [`TracingEvaluator`] which applies a transform matrix
#[derive(Default)]
pub struct TransformedTracingEval<E> {
    eval: E,
}

trait Transformable {
    fn transform(
        x: Self,
        y: Self,
        z: Self,
        mat: Matrix4<f32>,
    ) -> (Self, Self, Self)
    where
        Self: Sized;
}

impl Transformable for f32 {
    fn transform(x: f32, y: f32, z: f32, mat: Matrix4<f32>) -> (f32, f32, f32) {
        let out = mat.transform_point(&Point3::new(x, y, z));
        (out.x, out.y, out.z)
    }
}

impl Transformable for Interval {
    fn transform(
        x: Interval,
        y: Interval,
        z: Interval,
        mat: Matrix4<f32>,
    ) -> (Interval, Interval, Interval) {
        let out = [0, 1, 2, 3].map(|i| {
            let row = mat.row(i);
            x * row[0] + y * row[1] + z * row[2] + Interval::from(row[3])
        });

        (out[0] / out[3], out[1] / out[3], out[2] / out[3])
    }
}

impl<T: TracingEvaluator> TracingEvaluator for TransformedTracingEval<T>
where
    <T as TracingEvaluator>::Data: Transformable,
{
    type Data = <T as TracingEvaluator>::Data;
    type Tape = TransformedTape<<T as TracingEvaluator>::Tape>;
    type TapeStorage = <T as TracingEvaluator>::TapeStorage;
    type Trace = <T as TracingEvaluator>::Trace;
    fn eval<F: Into<Self::Data>>(
        &mut self,
        tape: &Self::Tape,
        x: F,
        y: F,
        z: F,
        vars: &[f32],
    ) -> Result<(Self::Data, Option<&Self::Trace>), Error> {
        let x = x.into();
        let y = y.into();
        let z = z.into();
        let (x, y, z) = Transformable::transform(x, y, z, tape.mat);
        self.eval.eval(&tape.tape, x, y, z, vars)
    }
}

/// A generic [`BulkEvaluator`] which applies a transform matrix
#[derive(Default)]
pub struct TransformedBulkEval<E> {
    eval: E,
    xs: Vec<f32>,
    ys: Vec<f32>,
    zs: Vec<f32>,
}

impl<T: BulkEvaluator> BulkEvaluator for TransformedBulkEval<T> {
    type Data = <T as BulkEvaluator>::Data;
    type Tape = TransformedTape<<T as BulkEvaluator>::Tape>;
    type TapeStorage = <T as BulkEvaluator>::TapeStorage;
    fn eval(
        &mut self,
        tape: &Self::Tape,
        x: &[f32],
        y: &[f32],
        z: &[f32],
        vars: &[f32],
    ) -> Result<&[Self::Data], Error> {
        if x.len() != y.len() || x.len() != z.len() {
            return Err(Error::MismatchedSlices);
        }
        let n = x.len();
        self.xs.resize(n, 0.0);
        self.ys.resize(n, 0.0);
        self.zs.resize(n, 0.0);
        for i in 0..x.len() {
            let p = tape.mat.transform_point(&Point3::new(x[i], y[i], z[i]));
            self.xs[i] = p.x;
            self.ys[i] = p.y;
            self.zs[i] = p.z;
        }
        self.eval
            .eval(&tape.tape, &self.xs, &self.ys, &self.zs, vars)
    }
}

impl<S: Shape> Shape for TransformedShape<S> {
    type Trace = <S as Shape>::Trace;
    type Storage = <S as Shape>::Storage;
    type Workspace = <S as Shape>::Workspace;
    type TapeStorage = <S as Shape>::TapeStorage;
    type PointEval = TransformedTracingEval<<S as Shape>::PointEval>;
    type IntervalEval = TransformedTracingEval<<S as Shape>::IntervalEval>;
    type FloatSliceEval = TransformedBulkEval<<S as Shape>::FloatSliceEval>;
    type GradSliceEval = TransformedBulkEval<<S as Shape>::GradSliceEval>;
    fn tile_sizes_2d() -> &'static [usize] {
        S::tile_sizes_2d()
    }
    fn tile_sizes_3d() -> &'static [usize] {
        S::tile_sizes_3d()
    }
    fn size(&self) -> usize {
        self.shape.size()
    }
    fn recycle(self) -> Option<Self::Storage> {
        self.shape.recycle()
    }
    fn point_tape(
        &self,
        storage: Self::TapeStorage,
    ) -> TransformedTape<<<S as Shape>::PointEval as TracingEvaluator>::Tape>
    {
        TransformedTape {
            tape: self.shape.point_tape(storage),
            mat: self.mat,
        }
    }
    fn interval_tape(
        &self,
        storage: Self::TapeStorage,
    ) -> TransformedTape<<<S as Shape>::IntervalEval as TracingEvaluator>::Tape>
    {
        TransformedTape {
            tape: self.shape.interval_tape(storage),
            mat: self.mat,
        }
    }
    fn float_slice_tape(
        &self,
        storage: Self::TapeStorage,
    ) -> TransformedTape<<<S as Shape>::FloatSliceEval as BulkEvaluator>::Tape>
    {
        TransformedTape {
            tape: self.shape.float_slice_tape(storage),
            mat: self.mat,
        }
    }
    fn grad_slice_tape(
        &self,
        storage: Self::TapeStorage,
    ) -> TransformedTape<<<S as Shape>::GradSliceEval as BulkEvaluator>::Tape>
    {
        TransformedTape {
            tape: self.shape.grad_slice_tape(storage),
            mat: self.mat,
        }
    }
    fn simplify(
        &self,
        trace: &Self::Trace,
        storage: Self::Storage,
        workspace: &mut Self::Workspace,
    ) -> Result<Self, Error> {
        let shape = self.shape.simplify(trace, storage, workspace)?;
        Ok(Self {
            shape,
            mat: self.mat,
        })
    }

    type TransformedShape = Self;
    fn apply_transform(mut self, mat: Matrix4<f32>) -> Self::TransformedShape {
        self.mat *= mat;
        self
    }
}