cgmath/
transform.rs

1// Copyright 2014 The CGMath Developers. For a full listing of the authors,
2// refer to the Cargo.toml file at the top-level directory of this distribution.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use structure::*;
17
18use approx;
19use matrix::{Matrix2, Matrix3, Matrix4};
20use num::{BaseFloat, BaseNum};
21use point::{Point2, Point3};
22use rotation::*;
23use vector::{Vector2, Vector3};
24
25use std::ops::Mul;
26
27/// A trait representing an [affine
28/// transformation](https://en.wikipedia.org/wiki/Affine_transformation) that
29/// can be applied to points or vectors. An affine transformation is one which
30pub trait Transform<P: EuclideanSpace>: Sized + One {
31    /// Create a transformation that rotates a vector to look at `center` from
32    /// `eye`, using `up` for orientation.
33    #[deprecated = "Use look_at_rh or look_at_lh"]
34    fn look_at(eye: P, center: P, up: P::Diff) -> Self;
35
36    /// Create a transformation that rotates a vector to look at `center` from
37    /// `eye`, using `up` for orientation.
38    fn look_at_rh(eye: P, center: P, up: P::Diff) -> Self;
39
40    /// Create a transformation that rotates a vector to look at `center` from
41    /// `eye`, using `up` for orientation.
42    fn look_at_lh(eye: P, center: P, up: P::Diff) -> Self;
43
44    /// Transform a vector using this transform.
45    fn transform_vector(&self, vec: P::Diff) -> P::Diff;
46
47    /// Inverse transform a vector using this transform
48    fn inverse_transform_vector(&self, vec: P::Diff) -> Option<P::Diff> {
49        self.inverse_transform()
50            .and_then(|inverse| Some(inverse.transform_vector(vec)))
51    }
52
53    /// Transform a point using this transform.
54    fn transform_point(&self, point: P) -> P;
55
56    /// Combine this transform with another, yielding a new transformation
57    /// which has the effects of both.
58    fn concat(&self, other: &Self) -> Self;
59
60    /// Create a transform that "un-does" this one.
61    fn inverse_transform(&self) -> Option<Self>;
62
63    /// Combine this transform with another, in-place.
64    #[inline]
65    fn concat_self(&mut self, other: &Self) {
66        *self = Self::concat(self, other);
67    }
68}
69
70/// A generic transformation consisting of a rotation,
71/// displacement vector and scale amount.
72#[derive(Copy, Clone, Debug, PartialEq)]
73pub struct Decomposed<V: VectorSpace, R> {
74    pub scale: V::Scalar,
75    pub rot: R,
76    pub disp: V,
77}
78
79impl<P: EuclideanSpace, R: Rotation<Space = P>> One for Decomposed<P::Diff, R>
80where
81    P::Scalar: BaseFloat,
82{
83    fn one() -> Self {
84        Decomposed {
85            scale: P::Scalar::one(),
86            rot: R::one(),
87            disp: P::Diff::zero(),
88        }
89    }
90}
91
92impl<P: EuclideanSpace, R: Rotation<Space = P>> Mul for Decomposed<P::Diff, R>
93where
94    P::Scalar: BaseFloat,
95    P::Diff: VectorSpace,
96{
97    type Output = Self;
98
99    /// Multiplies the two transforms together.
100    /// The result should be as if the two transforms were converted
101    /// to matrices, then multiplied, then converted back with
102    /// a (currently nonexistent) function that tries to convert
103    /// a matrix into a `Decomposed`.
104    fn mul(self, rhs: Decomposed<P::Diff, R>) -> Self::Output {
105        self.concat(&rhs)
106    }
107}
108
109impl<P: EuclideanSpace, R: Rotation<Space = P>> Transform<P> for Decomposed<P::Diff, R>
110where
111    P::Scalar: BaseFloat,
112    P::Diff: VectorSpace,
113{
114    #[inline]
115    fn look_at(eye: P, center: P, up: P::Diff) -> Decomposed<P::Diff, R> {
116        let rot = R::look_at(center - eye, up);
117        let disp = rot.rotate_vector(P::origin() - eye);
118        Decomposed {
119            scale: P::Scalar::one(),
120            rot: rot,
121            disp: disp,
122        }
123    }
124
125    #[inline]
126    fn look_at_lh(eye: P, center: P, up: P::Diff) -> Decomposed<P::Diff, R> {
127        let rot = R::look_at(center - eye, up);
128        let disp = rot.rotate_vector(P::origin() - eye);
129        Decomposed {
130            scale: P::Scalar::one(),
131            rot: rot,
132            disp: disp,
133        }
134    }
135
136    #[inline]
137    fn look_at_rh(eye: P, center: P, up: P::Diff) -> Decomposed<P::Diff, R> {
138        let rot = R::look_at(eye - center, up);
139        let disp = rot.rotate_vector(P::origin() - eye);
140        Decomposed {
141            scale: P::Scalar::one(),
142            rot: rot,
143            disp: disp,
144        }
145    }
146
147    #[inline]
148    fn transform_vector(&self, vec: P::Diff) -> P::Diff {
149        self.rot.rotate_vector(vec * self.scale)
150    }
151
152    #[inline]
153    fn inverse_transform_vector(&self, vec: P::Diff) -> Option<P::Diff> {
154        if ulps_eq!(self.scale, &P::Scalar::zero()) {
155            None
156        } else {
157            Some(self.rot.invert().rotate_vector(vec / self.scale))
158        }
159    }
160
161    #[inline]
162    fn transform_point(&self, point: P) -> P {
163        self.rot.rotate_point(point * self.scale) + self.disp
164    }
165
166    fn concat(&self, other: &Decomposed<P::Diff, R>) -> Decomposed<P::Diff, R> {
167        Decomposed {
168            scale: self.scale * other.scale,
169            rot: self.rot * other.rot,
170            disp: self.rot.rotate_vector(other.disp * self.scale) + self.disp,
171        }
172    }
173
174    fn inverse_transform(&self) -> Option<Decomposed<P::Diff, R>> {
175        if ulps_eq!(self.scale, &P::Scalar::zero()) {
176            None
177        } else {
178            let s = P::Scalar::one() / self.scale;
179            let r = self.rot.invert();
180            let d = r.rotate_vector(self.disp.clone()) * -s;
181            Some(Decomposed {
182                scale: s,
183                rot: r,
184                disp: d,
185            })
186        }
187    }
188}
189
190pub trait Transform2:
191    Transform<Point2<<Self as Transform2>::Scalar>> + Into<Matrix3<<Self as Transform2>::Scalar>>
192{
193    type Scalar: BaseNum;
194}
195pub trait Transform3:
196    Transform<Point3<<Self as Transform3>::Scalar>> + Into<Matrix4<<Self as Transform3>::Scalar>>
197{
198    type Scalar: BaseNum;
199}
200
201impl<S: BaseFloat, R: Rotation2<Scalar = S>> From<Decomposed<Vector2<S>, R>> for Matrix3<S> {
202    fn from(dec: Decomposed<Vector2<S>, R>) -> Matrix3<S> {
203        let m: Matrix2<_> = dec.rot.into();
204        let mut m: Matrix3<_> = (&m * dec.scale).into();
205        m.z = dec.disp.extend(S::one());
206        m
207    }
208}
209
210impl<S: BaseFloat, R: Rotation3<Scalar = S>> From<Decomposed<Vector3<S>, R>> for Matrix4<S> {
211    fn from(dec: Decomposed<Vector3<S>, R>) -> Matrix4<S> {
212        let m: Matrix3<_> = dec.rot.into();
213        let mut m: Matrix4<_> = (&m * dec.scale).into();
214        m.w = dec.disp.extend(S::one());
215        m
216    }
217}
218
219impl<S: BaseFloat, R: Rotation2<Scalar = S>> Transform2 for Decomposed<Vector2<S>, R> {
220    type Scalar = S;
221}
222
223impl<S: BaseFloat, R: Rotation3<Scalar = S>> Transform3 for Decomposed<Vector3<S>, R> {
224    type Scalar = S;
225}
226
227impl<S: VectorSpace, R, E: BaseFloat> approx::AbsDiffEq for Decomposed<S, R>
228where
229    S: approx::AbsDiffEq<Epsilon = E>,
230    S::Scalar: approx::AbsDiffEq<Epsilon = E>,
231    R: approx::AbsDiffEq<Epsilon = E>,
232{
233    type Epsilon = E;
234
235    #[inline]
236    fn default_epsilon() -> E {
237        E::default_epsilon()
238    }
239
240    #[inline]
241    fn abs_diff_eq(&self, other: &Self, epsilon: E) -> bool {
242        S::Scalar::abs_diff_eq(&self.scale, &other.scale, epsilon)
243            && R::abs_diff_eq(&self.rot, &other.rot, epsilon)
244            && S::abs_diff_eq(&self.disp, &other.disp, epsilon)
245    }
246}
247
248impl<S: VectorSpace, R, E: BaseFloat> approx::RelativeEq for Decomposed<S, R>
249where
250    S: approx::RelativeEq<Epsilon = E>,
251    S::Scalar: approx::RelativeEq<Epsilon = E>,
252    R: approx::RelativeEq<Epsilon = E>,
253{
254    #[inline]
255    fn default_max_relative() -> E {
256        E::default_max_relative()
257    }
258
259    #[inline]
260    fn relative_eq(&self, other: &Self, epsilon: E, max_relative: E) -> bool {
261        S::Scalar::relative_eq(&self.scale, &other.scale, epsilon, max_relative)
262            && R::relative_eq(&self.rot, &other.rot, epsilon, max_relative)
263            && S::relative_eq(&self.disp, &other.disp, epsilon, max_relative)
264    }
265}
266
267impl<S: VectorSpace, R, E: BaseFloat> approx::UlpsEq for Decomposed<S, R>
268where
269    S: approx::UlpsEq<Epsilon = E>,
270    S::Scalar: approx::UlpsEq<Epsilon = E>,
271    R: approx::UlpsEq<Epsilon = E>,
272{
273    #[inline]
274    fn default_max_ulps() -> u32 {
275        E::default_max_ulps()
276    }
277
278    #[inline]
279    fn ulps_eq(&self, other: &Self, epsilon: E, max_ulps: u32) -> bool {
280        S::Scalar::ulps_eq(&self.scale, &other.scale, epsilon, max_ulps)
281            && R::ulps_eq(&self.rot, &other.rot, epsilon, max_ulps)
282            && S::ulps_eq(&self.disp, &other.disp, epsilon, max_ulps)
283    }
284}
285
286#[cfg(feature = "serde")]
287#[doc(hidden)]
288mod serde_ser {
289    use super::Decomposed;
290    use serde::ser::SerializeStruct;
291    use serde::{self, Serialize};
292    use structure::VectorSpace;
293
294    impl<V, R> Serialize for Decomposed<V, R>
295    where
296        V: Serialize + VectorSpace,
297        V::Scalar: Serialize,
298        R: Serialize,
299    {
300        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
301        where
302            S: serde::Serializer,
303        {
304            let mut struc = serializer.serialize_struct("Decomposed", 3)?;
305            struc.serialize_field("scale", &self.scale)?;
306            struc.serialize_field("rot", &self.rot)?;
307            struc.serialize_field("disp", &self.disp)?;
308            struc.end()
309        }
310    }
311}
312
313#[cfg(feature = "serde")]
314#[doc(hidden)]
315mod serde_de {
316    use super::Decomposed;
317    use serde::{self, Deserialize};
318    use std::fmt;
319    use std::marker::PhantomData;
320    use structure::VectorSpace;
321
322    enum DecomposedField {
323        Scale,
324        Rot,
325        Disp,
326    }
327
328    impl<'a> Deserialize<'a> for DecomposedField {
329        fn deserialize<D>(deserializer: D) -> Result<DecomposedField, D::Error>
330        where
331            D: serde::Deserializer<'a>,
332        {
333            struct DecomposedFieldVisitor;
334
335            impl<'b> serde::de::Visitor<'b> for DecomposedFieldVisitor {
336                type Value = DecomposedField;
337
338                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
339                    formatter.write_str("`scale`, `rot` or `disp`")
340                }
341
342                fn visit_str<E>(self, value: &str) -> Result<DecomposedField, E>
343                where
344                    E: serde::de::Error,
345                {
346                    match value {
347                        "scale" => Ok(DecomposedField::Scale),
348                        "rot" => Ok(DecomposedField::Rot),
349                        "disp" => Ok(DecomposedField::Disp),
350                        _ => Err(serde::de::Error::custom("expected scale, rot or disp")),
351                    }
352                }
353            }
354
355            deserializer.deserialize_str(DecomposedFieldVisitor)
356        }
357    }
358
359    impl<'a, S: VectorSpace, R> Deserialize<'a> for Decomposed<S, R>
360    where
361        S: Deserialize<'a>,
362        S::Scalar: Deserialize<'a>,
363        R: Deserialize<'a>,
364    {
365        fn deserialize<D>(deserializer: D) -> Result<Decomposed<S, R>, D::Error>
366        where
367            D: serde::de::Deserializer<'a>,
368        {
369            const FIELDS: &'static [&'static str] = &["scale", "rot", "disp"];
370            deserializer.deserialize_struct("Decomposed", FIELDS, DecomposedVisitor(PhantomData))
371        }
372    }
373
374    struct DecomposedVisitor<S: VectorSpace, R>(PhantomData<(S, R)>);
375
376    impl<'a, S: VectorSpace, R> serde::de::Visitor<'a> for DecomposedVisitor<S, R>
377    where
378        S: Deserialize<'a>,
379        S::Scalar: Deserialize<'a>,
380        R: Deserialize<'a>,
381    {
382        type Value = Decomposed<S, R>;
383
384        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
385            formatter.write_str("`scale`, `rot` and `disp` fields")
386        }
387
388        fn visit_map<V>(self, mut visitor: V) -> Result<Decomposed<S, R>, V::Error>
389        where
390            V: serde::de::MapAccess<'a>,
391        {
392            let mut scale = None;
393            let mut rot = None;
394            let mut disp = None;
395
396            while let Some(key) = visitor.next_key()? {
397                match key {
398                    DecomposedField::Scale => {
399                        scale = Some(visitor.next_value()?);
400                    }
401                    DecomposedField::Rot => {
402                        rot = Some(visitor.next_value()?);
403                    }
404                    DecomposedField::Disp => {
405                        disp = Some(visitor.next_value()?);
406                    }
407                }
408            }
409
410            let scale = match scale {
411                Some(scale) => scale,
412                None => return Err(serde::de::Error::missing_field("scale")),
413            };
414
415            let rot = match rot {
416                Some(rot) => rot,
417                None => return Err(serde::de::Error::missing_field("rot")),
418            };
419
420            let disp = match disp {
421                Some(disp) => disp,
422                None => return Err(serde::de::Error::missing_field("disp")),
423            };
424
425            Ok(Decomposed {
426                scale: scale,
427                rot: rot,
428                disp: disp,
429            })
430        }
431    }
432}