1use crate::array_tools::Point;
7
8const EPSILON: f64 = 1e-15;
9const ONE_EPSILON: f64 = 1.0 - EPSILON;
10const MINUS_ONE_EPSILON: f64 = -1.0 + EPSILON;
11
12fn norm_sin_cos(v: f64) -> f64 {
14 if v.abs() < EPSILON {
15 0.0
16 } else if v > ONE_EPSILON {
17 1.0
18 } else if v < MINUS_ONE_EPSILON {
19 -1.0
20 } else {
21 v
22 }
23}
24
25#[derive(Debug, Clone, Copy, PartialEq)]
28pub struct Transform {
29 #[allow(missing_docs)]
30 pub xx: f64,
31 #[allow(missing_docs)]
32 pub xy: f64,
33 #[allow(missing_docs)]
34 pub yx: f64,
35 #[allow(missing_docs)]
36 pub yy: f64,
37 #[allow(missing_docs)]
38 pub dx: f64,
39 #[allow(missing_docs)]
40 pub dy: f64,
41}
42
43pub const IDENTITY: Transform = Transform::new(1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
45
46impl Default for Transform {
47 fn default() -> Self {
48 IDENTITY
49 }
50}
51
52impl From<[f64; 6]> for Transform {
53 fn from([xx, xy, yx, yy, dx, dy]: [f64; 6]) -> Self {
54 Transform::new(xx, xy, yx, yy, dx, dy)
55 }
56}
57
58impl Transform {
59 pub const fn new(xx: f64, xy: f64, yx: f64, yy: f64, dx: f64, dy: f64) -> Self {
61 Transform {
62 xx,
63 xy,
64 yx,
65 yy,
66 dx,
67 dy,
68 }
69 }
70
71 pub const fn offset(x: f64, y: f64) -> Self {
73 Transform::new(1.0, 0.0, 0.0, 1.0, x, y)
74 }
75
76 pub fn to_array(self) -> [f64; 6] {
78 [self.xx, self.xy, self.yx, self.yy, self.dx, self.dy]
79 }
80
81 pub fn is_identity(&self) -> bool {
83 *self == IDENTITY
84 }
85
86 pub fn transform_point(&self, (x, y): Point) -> Point {
88 (
89 self.xx * x + self.yx * y + self.dx,
90 self.xy * x + self.yy * y + self.dy,
91 )
92 }
93
94 pub fn transform_points(&self, points: &[Point]) -> Vec<Point> {
96 points.iter().map(|&p| self.transform_point(p)).collect()
97 }
98
99 pub fn scaling(x: f64, y: Option<f64>) -> Self {
101 Transform::new(x, 0.0, 0.0, y.unwrap_or(x), 0.0, 0.0)
102 }
103
104 pub fn transform_vector(&self, (dx, dy): Point) -> Point {
106 (self.xx * dx + self.yx * dy, self.xy * dx + self.yy * dy)
107 }
108
109 pub fn transform_vectors(&self, vectors: &[Point]) -> Vec<Point> {
111 vectors.iter().map(|&v| self.transform_vector(v)).collect()
112 }
113
114 pub fn to_ps(&self) -> String {
116 let v: Vec<String> = self.to_array().iter().map(|&x| py_num(x)).collect();
117 format!("[{}]", v.join(" "))
118 }
119
120 pub fn translate(&self, x: f64, y: f64) -> Self {
122 self.transform(&Transform::new(1.0, 0.0, 0.0, 1.0, x, y))
123 }
124
125 pub fn scale(&self, x: f64, y: Option<f64>) -> Self {
127 let y = y.unwrap_or(x);
128 self.transform(&Transform::new(x, 0.0, 0.0, y, 0.0, 0.0))
129 }
130
131 pub fn rotate(&self, angle: f64) -> Self {
133 let c = norm_sin_cos(angle.cos());
134 let s = norm_sin_cos(angle.sin());
135 self.transform(&Transform::new(c, s, -s, c, 0.0, 0.0))
136 }
137
138 pub fn skew(&self, x: f64, y: f64) -> Self {
140 self.transform(&Transform::new(1.0, y.tan(), x.tan(), 1.0, 0.0, 0.0))
141 }
142
143 pub fn transform(&self, other: &Transform) -> Self {
145 let (xx1, xy1, yx1, yy1, dx1, dy1) =
146 (other.xx, other.xy, other.yx, other.yy, other.dx, other.dy);
147 let (xx2, xy2, yx2, yy2, dx2, dy2) = (self.xx, self.xy, self.yx, self.yy, self.dx, self.dy);
148 Transform::new(
149 xx1 * xx2 + xy1 * yx2,
150 xx1 * xy2 + xy1 * yy2,
151 yx1 * xx2 + yy1 * yx2,
152 yx1 * xy2 + yy1 * yy2,
153 xx2 * dx1 + yx2 * dy1 + dx2,
154 xy2 * dx1 + yy2 * dy1 + dy2,
155 )
156 }
157
158 pub fn reverse_transform(&self, other: &Transform) -> Self {
160 other.transform(self)
161 }
162
163 pub fn inverse(&self) -> Self {
165 if self.is_identity() {
166 return *self;
167 }
168 let (xx, xy, yx, yy, dx, dy) = (self.xx, self.xy, self.yx, self.yy, self.dx, self.dy);
169 let det = xx * yy - yx * xy;
170 let (xx, xy, yx, yy) = (yy / det, -xy / det, -yx / det, xx / det);
171 let (dx, dy) = (-xx * dx - yx * dy, -xy * dx - yy * dy);
172 Transform::new(xx, xy, yx, yy, dx, dy)
173 }
174
175 pub fn to_decomposed(&self) -> DecomposedTransform {
177 DecomposedTransform::from_transform(self)
178 }
179}
180
181fn py_num(x: f64) -> String {
183 if x.fract() == 0.0 && x.abs() < 1e16 {
184 format!("{}", x as i64)
185 } else {
186 crate::py::float_repr(x)
187 }
188}
189
190impl std::fmt::Display for Transform {
192 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193 let v: Vec<String> = self
194 .to_array()
195 .iter()
196 .map(|&x| crate::py::format_g_lower(x, 6))
197 .collect();
198 write!(f, "<Transform [{}]>", v.join(" "))
199 }
200}
201
202#[derive(Debug, Clone, Copy, PartialEq)]
205pub struct DecomposedTransform {
206 #[allow(missing_docs)]
207 pub translate_x: f64,
208 #[allow(missing_docs)]
209 pub translate_y: f64,
210 pub rotation: f64,
212 #[allow(missing_docs)]
213 pub scale_x: f64,
214 #[allow(missing_docs)]
215 pub scale_y: f64,
216 pub skew_x: f64,
218 pub skew_y: f64,
220 #[allow(missing_docs)]
221 pub t_center_x: f64,
222 #[allow(missing_docs)]
223 pub t_center_y: f64,
224}
225
226impl Default for DecomposedTransform {
227 fn default() -> Self {
228 DecomposedTransform {
229 translate_x: 0.0,
230 translate_y: 0.0,
231 rotation: 0.0,
232 scale_x: 1.0,
233 scale_y: 1.0,
234 skew_x: 0.0,
235 skew_y: 0.0,
236 t_center_x: 0.0,
237 t_center_y: 0.0,
238 }
239 }
240}
241
242impl DecomposedTransform {
243 pub fn is_identity(&self) -> bool {
245 *self == DecomposedTransform::default()
246 }
247
248 pub fn from_transform(transform: &Transform) -> Self {
250 let (mut a, mut b, c, d, x, y) = (
251 transform.xx,
252 transform.xy,
253 transform.yx,
254 transform.yy,
255 transform.dx,
256 transform.dy,
257 );
258 let sx = 1f64.copysign(a);
259 if sx < 0.0 {
260 a *= sx;
261 b *= sx;
262 }
263 let delta = a * d - b * c;
264 let mut rotation = 0.0;
265 let (mut scale_x, mut scale_y) = (0.0, 0.0);
266 let mut skew_x = 0.0;
267 if a != 0.0 || b != 0.0 {
268 let r = (a * a + b * b).sqrt();
269 rotation = if b >= 0.0 {
270 (a / r).acos()
271 } else {
272 -(a / r).acos()
273 };
274 (scale_x, scale_y) = (r, delta / r);
275 skew_x = ((a * c + b * d) / (r * r)).atan();
276 } else if c != 0.0 || d != 0.0 {
277 let s = (c * c + d * d).sqrt();
278 rotation = (-c).atan2(d);
279 if rotation == -std::f64::consts::PI {
280 rotation = std::f64::consts::PI;
281 }
282 (scale_x, scale_y) = (delta / s, s);
283 }
284 DecomposedTransform {
285 translate_x: x,
286 translate_y: y,
287 rotation: rotation.to_degrees(),
288 scale_x: scale_x * sx,
289 scale_y,
290 skew_x: skew_x.to_degrees() * sx,
291 skew_y: 0.0,
292 t_center_x: 0.0,
293 t_center_y: 0.0,
294 }
295 }
296
297 pub fn to_transform(&self) -> Transform {
299 IDENTITY
300 .translate(
301 self.translate_x + self.t_center_x,
302 self.translate_y + self.t_center_y,
303 )
304 .rotate(self.rotation.to_radians())
305 .scale(self.scale_x, Some(self.scale_y))
306 .skew(self.skew_x.to_radians(), self.skew_y.to_radians())
307 .translate(-self.t_center_x, -self.t_center_y)
308 }
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314
315 #[test]
317 fn doctests() {
318 let t = IDENTITY.scale(2.0, Some(3.0)).translate(4.0, 5.0);
319 assert_eq!(t.transform_point((0.0, 0.0)), (8.0, 15.0));
320 let t = Transform::new(2.0, 0.0, 0.0, 3.0, 0.0, 0.0);
321 assert_eq!(t.transform_point((100.0, 100.0)), (200.0, 300.0));
322 assert_eq!(
323 t.transform(&Transform::new(4.0, 3.0, 2.0, 1.0, 5.0, 6.0)),
324 Transform::new(8.0, 9.0, 4.0, 3.0, 10.0, 18.0)
325 );
326 assert_eq!(
327 IDENTITY.rotate(std::f64::consts::PI / 2.0),
328 Transform::new(0.0, 1.0, -1.0, 0.0, 0.0, 0.0)
329 );
330 assert_eq!(
331 IDENTITY.skew(std::f64::consts::PI / 4.0, 0.0),
332 Transform::new(1.0, 0.0, 0.9999999999999999, 1.0, 0.0, 0.0)
333 );
334 let t = Transform::new(2.0, 0.0, 0.0, 3.0, 8.0, 15.0);
335 let it = t.inverse();
336 assert_eq!(t.transform_point((10.0, 20.0)), (28.0, 75.0));
337 assert_eq!(it.transform_point((28.0, 75.0)), (10.0, 20.0));
338 }
339
340 #[test]
341 fn decomposed() {
342 let d = DecomposedTransform {
343 scale_x: 2.0,
344 scale_y: 2.0,
345 ..Default::default()
346 };
347 assert_eq!(
348 d.to_transform(),
349 Transform::new(2.0, 0.0, 0.0, 2.0, 0.0, 0.0)
350 );
351 let d = DecomposedTransform::from_transform(&IDENTITY.scale(3.0, Some(2.0)));
352 assert_eq!((d.rotation, d.scale_x, d.scale_y), (0.0, 3.0, 2.0));
353 let d = DecomposedTransform::from_transform(&Transform::new(0.0, 0.0, 0.0, 1.0, 0.0, 0.0));
354 assert_eq!((d.scale_x, d.scale_y), (0.0, 1.0));
355 let d = DecomposedTransform::from_transform(&Transform::new(0.0, 0.0, 1.0, 1.0, 0.0, 0.0));
356 assert_eq!(
357 (d.rotation, d.scale_x, d.scale_y),
358 (-45.0, 0.0, std::f64::consts::SQRT_2)
359 );
360 }
361}