Skip to main content

bhoo/
projective.rs

1//! Homogeneous transforms for mapping a planar surface through perspective.
2//!
3//! This is geometry only: rendering a textured surface also requires
4//! perspective-correct interpolation in the renderer.
5
6/// A row-major 3×3 homography acting on points `[x, y, 1]`.
7#[derive(Clone, Copy, Debug, PartialEq)]
8pub struct ProjectiveTransform {
9    matrix: [[f64; 3]; 3],
10}
11
12impl ProjectiveTransform {
13    pub const IDENTITY: Self = Self { matrix: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] };
14
15    /// Create a transform from finite homogeneous coefficients.
16    pub fn new(matrix: [[f64; 3]; 3]) -> Option<Self> {
17        matrix.iter().flatten().all(|value| value.is_finite()).then_some(Self { matrix })
18    }
19
20    pub fn coefficients(self) -> [[f64; 3]; 3] { self.matrix }
21
22    /// Project a view's planar rotation using Skia's camera-axis convention.
23    /// Angles are in degrees and `camera_distance` is in the same units as
24    /// the view coordinates. The caller supplies the platform camera distance.
25    pub fn camera_view(pivot: [f64; 2], translation: [f64; 2], scale: [f64; 2],
26        rotation: [f64; 3], camera_distance: f64) -> Option<Self> {
27        if !camera_distance.is_finite() || camera_distance <= 0.0
28            || !pivot.into_iter().chain(translation).chain(scale).chain(rotation).all(f64::is_finite) {
29            return None;
30        }
31        let [x, y, z] = rotation.map(f64::to_radians);
32        let (sx, cx) = x.sin_cos();
33        let (sy, cy) = y.sin_cos();
34        let (sz, cz) = z.sin_cos();
35        // Sk3DView concatenates rotations around X, negative Y and negative Z,
36        // then projects its X and negative-Y patch vectors through the camera.
37        let u = [cy * cz, -cx * sz - sx * sy * cz, -sx * sz + cx * sy * cz];
38        let v = [-cy * sz, -cx * cz + sx * sy * sz, -sx * cz - cx * sy * sz];
39        let projection = Self::new([[u[0], v[0], 0.0], [-u[1], -v[1], 0.0],
40            [u[2] / camera_distance, v[2] / camera_distance, 1.0]])?;
41        let local = Self::new([[scale[0], 0.0, -scale[0] * pivot[0]],
42            [0.0, scale[1], -scale[1] * pivot[1]], [0.0, 0.0, 1.0]])?;
43        let offset = Self::new([[1.0, 0.0, pivot[0] + translation[0]],
44            [0.0, 1.0, pivot[1] + translation[1]], [0.0, 0.0, 1.0]])?;
45        offset.then(projection)?.then(local)
46    }
47
48    /// Compose transforms so `local` is applied before `self`.
49    pub fn then(self, local: Self) -> Option<Self> {
50        let matrix = std::array::from_fn(|row| std::array::from_fn(|column|
51            (0..3).map(|k| self.matrix[row][k] * local.matrix[k][column]).sum()));
52        Self::new(matrix)
53    }
54
55    /// Map a point, returning `None` at the horizon or for non-finite results.
56    pub fn map(self, point: [f64; 2]) -> Option<[f64; 2]> {
57        if !point.iter().all(|value| value.is_finite()) { return None; }
58        let [x, y] = point;
59        let m = self.matrix;
60        let w = m[2][0] * x + m[2][1] * y + m[2][2];
61        if w == 0.0 || !w.is_finite() { return None; }
62        let result = [(m[0][0] * x + m[0][1] * y + m[0][2]) / w,
63                      (m[1][0] * x + m[1][1] * y + m[1][2]) / w];
64        result.iter().all(|value| value.is_finite()).then_some(result)
65    }
66
67    /// Bounds of a rectangle after projection, provided it does not cross the
68    /// projective horizon. Crossing rectangles have no finite bounding box.
69    pub fn map_rect(self, rect: [f64; 4]) -> Option<[f64; 4]> {
70        let [x, y, width, height] = rect;
71        if !rect.iter().all(|v| v.is_finite()) || width < 0.0 || height < 0.0 { return None; }
72        let mut low = [f64::INFINITY; 2];
73        let mut high = [f64::NEG_INFINITY; 2];
74        let mut sign = 0.0;
75        for px in [x, x + width] {
76            for py in [y, y + height] {
77                let w = self.matrix[2][0] * px + self.matrix[2][1] * py + self.matrix[2][2];
78                if !w.is_finite() || w == 0.0 || (sign != 0.0 && sign != w.signum()) { return None; }
79                sign = w.signum();
80                let point = self.map([px, py])?;
81                for axis in 0..2 { low[axis] = low[axis].min(point[axis]); high[axis] = high[axis].max(point[axis]); }
82            }
83        }
84        Some([low[0], low[1], high[0] - low[0], high[1] - low[1]])
85    }
86
87    /// Invert a non-singular transform for mapping pointer input to the surface.
88    pub fn inverse(self) -> Option<Self> {
89        let [[a, b, c], [d, e, f], [g, h, i]] = self.matrix;
90        let adjugate = [[e*i-f*h, c*h-b*i, b*f-c*e],
91                        [f*g-d*i, a*i-c*g, c*d-a*f],
92                        [d*h-e*g, b*g-a*h, a*e-b*d]];
93        let determinant = a*adjugate[0][0] + b*adjugate[1][0] + c*adjugate[2][0];
94        if determinant == 0.0 || !determinant.is_finite() { return None; }
95        Self::new(adjugate.map(|row| row.map(|value| value / determinant)))
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::ProjectiveTransform;
102
103    #[test]
104    fn perspective_points_round_trip_and_compose() {
105        let perspective = ProjectiveTransform::new([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.01, 0.0, 1.0]]).unwrap();
106        let translate = ProjectiveTransform::new([[1.0, 0.0, 5.0], [0.0, 1.0, -3.0], [0.0, 0.0, 1.0]]).unwrap();
107        let combined = translate.then(perspective).unwrap();
108        assert_eq!(combined.map([100.0, 20.0]), Some([55.0, 7.0]));
109        let original = combined.inverse().unwrap().map([55.0, 7.0]).unwrap();
110        assert!((original[0] - 100.0).abs() < 1e-10 && (original[1] - 20.0).abs() < 1e-10);
111        assert_eq!(perspective.map([-100.0, 0.0]), None);
112    }
113
114    #[test]
115    fn rejects_singular_and_non_finite_transforms() {
116        assert!(ProjectiveTransform::new([[1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]).unwrap().inverse().is_none());
117        assert!(ProjectiveTransform::new([[f64::NAN; 3]; 3]).is_none());
118    }
119
120    #[test]
121    fn projected_bounds_reject_horizon_crossings() {
122        let p = ProjectiveTransform::new([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.01, 0.0, 1.0]]).unwrap();
123        assert_eq!(p.map_rect([0.0, 0.0, 100.0, 20.0]), Some([0.0, 0.0, 50.0, 20.0]));
124        assert_eq!(p.map_rect([-150.0, 0.0, 100.0, 20.0]), None);
125        assert_eq!(p.map_rect([0.0, 0.0, -1.0, 20.0]), None);
126    }
127
128    #[test]
129    fn camera_axes_preserve_pivot_and_project_in_opposite_depths() {
130        let x = ProjectiveTransform::camera_view([50.0, 50.0], [3.0, -2.0], [1.0, 1.0], [60.0, 0.0, 0.0], 576.0).unwrap();
131        assert_eq!(x.map([50.0, 50.0]), Some([53.0, 48.0]));
132        let upper = x.map([50.0, 0.0]).unwrap();
133        let lower = x.map([50.0, 100.0]).unwrap();
134        assert!(upper[1] > 23.0 && lower[1] > 73.0);
135        let y = ProjectiveTransform::camera_view([0.0, 0.0], [0.0, 0.0], [1.0, 1.0], [0.0, 60.0, 0.0], 576.0).unwrap();
136        assert!((y.map([100.0, 0.0]).unwrap()[0] - 43.464).abs() < 0.01);
137        assert!(ProjectiveTransform::camera_view([0.0; 2], [0.0; 2], [1.0; 2], [0.0; 3], 0.0).is_none());
138    }
139
140    #[test]
141    fn combined_camera_rotation_matches_skia_probe() {
142        // Sk3DView: rotateX(31), rotateY(23), rotateZ(-19), default camera.
143        // Reference probe: tools/bhoo-skia-camera-probe.cpp, Skia scalar floats.
144        let actual = ProjectiveTransform::camera_view([0.0; 2], [0.0; 2], [1.0; 2],
145            [31.0, 23.0, 19.0], 576.0).unwrap().coefficients();
146        let skia = [[0.870354414, -0.299687088, 0.0],
147                    [0.469343930, 0.744949818, 0.0],
148                    [0.000258671702, -0.00103475351, 1.0]];
149        for (row, reference) in actual.iter().zip(skia) {
150            for (value, expected) in row.iter().zip(reference) {
151                assert!((value - expected).abs() < 1e-6, "{value} != {expected}");
152            }
153        }
154    }
155
156    #[test]
157    fn camera_pivot_scale_translation_match_android_composition_probe() {
158        // The second matrix emitted by tools/bhoo-skia-camera-probe.cpp follows
159        // Android RenderProperties' preScale / camera / pivot composition.
160        let actual = ProjectiveTransform::camera_view([37.0, 61.0], [8.0, -5.0], [1.3, 0.7],
161            [31.0, 23.0, 19.0], 576.0).unwrap().coefficients();
162        let reference = [[1.14659297, -0.242375702, 17.3609695],
163                         [0.628978431, 0.480902523, 3.39274406],
164                         [0.000336273195, -0.000724327459, 1.03174186]];
165        for (row, expected_row) in actual.iter().zip(reference) {
166            for (value, expected) in row.iter().zip(expected_row) {
167                assert!((value - expected).abs() < 1e-5, "{value} != {expected}");
168            }
169        }
170    }
171}