Skip to main content

graphics_core/camera/
mod.rs

1//! Camera abstractions for 2D viewports and external host matrix injection.
2
3use glam::{DMat4, Mat2, Mat4, Vec2, Vec3};
4
5use crate::math::{ViewportRect, viewport_to_world_2d, world_to_viewport_2d};
6
7const MIN_CAMERA_ZOOM: f32 = 1e-4;
8
9/// 2D pan/zoom viewport camera with rotation support.
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct Camera2D {
12    pub pan: Vec2,
13    pub zoom: f32,
14    pub rotation: f32,
15}
16
17impl Default for Camera2D {
18    fn default() -> Self {
19        Self {
20            pan: Vec2::ZERO,
21            zoom: 1.0,
22            rotation: 0.0,
23        }
24    }
25}
26
27impl Camera2D {
28    pub fn new(pan: Vec2, zoom: f32) -> Self {
29        Self {
30            pan,
31            zoom,
32            rotation: 0.0,
33        }
34    }
35
36    /// Computes the 2D view matrix (pan, rotation, and uniform zoom).
37    pub fn view_matrix(&self) -> Mat4 {
38        Mat4::from_scale_rotation_translation(
39            Vec3::new(self.zoom, self.zoom, 1.0),
40            glam::Quat::from_rotation_z(self.rotation),
41            Vec3::new(self.pan.x, self.pan.y, 0.0),
42        )
43    }
44
45    /// Computes the orthographic projection matrix for a given viewport size (center-origin, Y-up).
46    pub fn proj_matrix(&self, width: f32, height: f32) -> Mat4 {
47        let w = width.max(1.0);
48        let h = height.max(1.0);
49        Mat4::orthographic_rh(-w * 0.5, w * 0.5, -h * 0.5, h * 0.5, -1000.0, 1000.0)
50    }
51
52    /// Combined view-projection matrix.
53    pub fn view_proj_matrix(&self, width: f32, height: f32) -> Mat4 {
54        self.proj_matrix(width, height) * self.view_matrix()
55    }
56
57    /// Converts a screen pixel coordinate within `viewport` to Y-up 2D world coordinates.
58    pub fn screen_to_world(&self, screen_pt: Vec2, viewport: ViewportRect) -> Vec2 {
59        if self.zoom.abs() < 1e-6 {
60            return Vec2::ZERO;
61        }
62        let inv = self
63            .view_proj_matrix(viewport.width, viewport.height)
64            .inverse();
65        viewport_to_world_2d(screen_pt, viewport, inv)
66    }
67
68    /// Converts a Y-up 2D world point to screen pixel coordinates within `viewport`.
69    pub fn world_to_screen(&self, world_pt: Vec2, viewport: ViewportRect) -> Vec2 {
70        world_to_viewport_2d(
71            world_pt,
72            viewport,
73            self.view_proj_matrix(viewport.width, viewport.height),
74        )
75    }
76
77    /// Updates zoom to `new_zoom` while keeping the world point under `screen_pt` stationary.
78    pub fn zoom_at(&mut self, screen_pt: Vec2, viewport: ViewportRect, new_zoom: f32) {
79        let clamped_zoom = if new_zoom.is_finite() {
80            new_zoom.max(MIN_CAMERA_ZOOM)
81        } else {
82            self.zoom.max(MIN_CAMERA_ZOOM)
83        };
84        let old_zoom = self.zoom;
85        let world_before = self.screen_to_world(screen_pt, viewport);
86        self.zoom = clamped_zoom;
87        self.pan += (old_zoom - clamped_zoom) * (Mat2::from_angle(self.rotation) * world_before);
88    }
89
90    /// Multiplies zoom by `factor` while keeping the world point under `screen_pt` stationary.
91    pub fn zoom_by_at(&mut self, screen_pt: Vec2, viewport: ViewportRect, factor: f32) {
92        if !factor.is_finite() || factor <= 0.0 {
93            return;
94        }
95        self.zoom_at(screen_pt, viewport, self.zoom * factor);
96    }
97
98    /// Returns the axis-aligned world-space bounding rectangle visible inside `viewport`.
99    pub fn visible_world_rect(&self, viewport: ViewportRect) -> ViewportRect {
100        let corners = [
101            Vec2::new(viewport.x, viewport.y),
102            Vec2::new(viewport.x + viewport.width, viewport.y),
103            Vec2::new(viewport.x, viewport.y + viewport.height),
104            Vec2::new(viewport.x + viewport.width, viewport.y + viewport.height),
105        ];
106        let mut min = Vec2::splat(f32::INFINITY);
107        let mut max = Vec2::splat(f32::NEG_INFINITY);
108        for corner in corners {
109            let world = self.screen_to_world(corner, viewport);
110            min = min.min(world);
111            max = max.max(world);
112        }
113        ViewportRect::new(min.x, min.y, max.x - min.x, max.y - min.y)
114    }
115
116    /// Returns a 2D affine `[a, b, c, d, e, f]` (column-major 2x3, matching `kurbo::Affine::new`)
117    /// mapping Y-up world coordinates to top-left Y-down canvas pixels of size `(width, height)`.
118    pub fn to_vello_affine_ortho(&self, width: f32, height: f32) -> [f64; 6] {
119        let (s, c) = (self.rotation as f64).sin_cos();
120        let z = self.zoom as f64;
121        [
122            z * c,
123            -z * s,
124            -z * s,
125            -z * c,
126            width as f64 * 0.5 + self.pan.x as f64,
127            height as f64 * 0.5 - self.pan.y as f64,
128        ]
129    }
130
131    /// Returns a 2D affine `[a, b, c, d, e, f]` (matching `kurbo::Affine::new`)
132    /// for Y-down world space (`p_screen = pan + zoom * R(rotation) * p_world`).
133    pub fn to_vello_affine_y_down(&self) -> [f64; 6] {
134        let (s, c) = (self.rotation as f64).sin_cos();
135        let z = self.zoom as f64;
136        [
137            z * c,
138            z * s,
139            -z * s,
140            z * c,
141            self.pan.x as f64,
142            self.pan.y as f64,
143        ]
144    }
145
146    /// Converts a screen pixel coordinate within `viewport` to Y-down 2D world coordinates.
147    pub fn screen_to_world_y_down(&self, screen_pt: Vec2, viewport: ViewportRect) -> Vec2 {
148        if self.zoom.abs() < 1e-6 {
149            return Vec2::ZERO;
150        }
151        let local = screen_pt - Vec2::new(viewport.x, viewport.y);
152        Mat2::from_angle(-self.rotation) * ((local - self.pan) / self.zoom)
153    }
154
155    /// Converts a Y-down 2D world point to screen pixel coordinates within `viewport`.
156    pub fn world_to_screen_y_down(&self, world_pt: Vec2, viewport: ViewportRect) -> Vec2 {
157        Vec2::new(viewport.x, viewport.y)
158            + self.pan
159            + self.zoom * (Mat2::from_angle(self.rotation) * world_pt)
160    }
161
162    /// Multiplies zoom by `factor` while keeping `screen_pt` stationary in Y-down canvas space.
163    pub fn zoom_at_y_down(&mut self, screen_pt: Vec2, factor: f32) {
164        if !factor.is_finite() || factor <= 0.0 || self.zoom.abs() < 1e-6 {
165            return;
166        }
167        let old_zoom = self.zoom;
168        let new_zoom = (old_zoom * factor).max(MIN_CAMERA_ZOOM);
169        let ratio = new_zoom / old_zoom;
170        self.pan = screen_pt - (screen_pt - self.pan) * ratio;
171        self.zoom = new_zoom;
172    }
173}
174
175/// Raw camera definition for injecting pre-computed matrices from external hosts (e.g. CAD or C/C++ viewports).
176#[derive(Clone, Copy, Debug, PartialEq)]
177pub struct RawCamera {
178    pub view: Mat4,
179    pub proj: Mat4,
180}
181
182fn gl_row_major_to_dmat4s(
183    view_row_major: &[f64; 16],
184    proj_row_major: &[f64; 16],
185) -> (DMat4, DMat4) {
186    let mut remapped_proj = *proj_row_major;
187    // OpenGL NDC Z in [-1, 1] -> WGPU NDC Z in [0, 1]: Z_wgpu = 0.5 * Z_gl + 0.5 * W_gl.
188    for col in 0..4 {
189        remapped_proj[8 + col] = 0.5 * remapped_proj[8 + col] + 0.5 * remapped_proj[12 + col];
190    }
191    let view = DMat4::from_cols_array(view_row_major).transpose();
192    let proj = DMat4::from_cols_array(&remapped_proj).transpose();
193    (view, proj)
194}
195
196impl RawCamera {
197    pub fn new(view: Mat4, proj: Mat4) -> Self {
198        Self { view, proj }
199    }
200
201    /// Converts OpenGL row-major `f64` view and projection matrices (NDC Z in `[-1, 1]`)
202    /// into a column-major WGPU [`RawCamera`] (NDC Z in `[0, 1]`).
203    pub fn from_gl_row_major_f64(view_row_major: &[f64; 16], proj_row_major: &[f64; 16]) -> Self {
204        let (view, proj) = gl_row_major_to_dmat4s(view_row_major, proj_row_major);
205        Self {
206            view: view.as_mat4(),
207            proj: proj.as_mat4(),
208        }
209    }
210
211    /// Multiplies `proj * view` in `f64` precision before narrowing to `f32` [`Mat4`],
212    /// preserving accuracy for large world coordinates far from origin.
213    pub fn view_proj_gl_row_major_f64(
214        view_row_major: &[f64; 16],
215        proj_row_major: &[f64; 16],
216    ) -> Mat4 {
217        let (view, proj) = gl_row_major_to_dmat4s(view_row_major, proj_row_major);
218        (proj * view).as_mat4()
219    }
220
221    pub fn view_proj_matrix(&self) -> Mat4 {
222        self.proj * self.view
223    }
224
225    pub fn inv_view_proj_matrix(&self) -> Mat4 {
226        self.view_proj_matrix().inverse()
227    }
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233    use glam::Vec4;
234
235    #[test]
236    fn camera2d_screen_world_roundtrip_with_pan_zoom_rotation_and_offset() {
237        let cam = Camera2D {
238            pan: Vec2::new(42.5, -18.25),
239            zoom: 2.5,
240            rotation: 0.65,
241        };
242        let vp = ViewportRect::new(15.0, 25.0, 800.0, 600.0);
243        let screen = Vec2::new(317.0, 412.0);
244        let world = cam.screen_to_world(screen, vp);
245        let back = cam.world_to_screen(world, vp);
246        assert!(
247            (back - screen).length() < 1e-3,
248            "back={back:?} screen={screen:?}"
249        );
250    }
251
252    #[test]
253    fn camera2d_zoom_at_preserves_cursor_world_point() {
254        let vp = ViewportRect::new(10.0, 20.0, 1024.0, 768.0);
255        let cursor = Vec2::new(712.0, 245.0);
256        for rotation in [0.0_f32, 0.78] {
257            let mut cam = Camera2D {
258                pan: Vec2::new(-35.0, 60.0),
259                zoom: 1.5,
260                rotation,
261            };
262            let world_before = cam.screen_to_world(cursor, vp);
263            cam.zoom_by_at(cursor, vp, 2.25);
264            let screen_after = cam.world_to_screen(world_before, vp);
265            assert!(
266                (screen_after - cursor).length() < 1e-3,
267                "rotation={rotation} screen_after={screen_after:?} cursor={cursor:?}"
268            );
269        }
270    }
271
272    #[test]
273    fn camera2d_visible_world_rect_bounds_rotated_zoomed() {
274        let cam = Camera2D {
275            pan: Vec2::new(40.0, -20.0),
276            zoom: 2.0,
277            rotation: std::f32::consts::FRAC_PI_4,
278        };
279        let vp = ViewportRect::new(0.0, 0.0, 400.0, 200.0);
280        let rect = cam.visible_world_rect(vp);
281        // Rotated 400x200 box at zoom=2 has world half-dims (100, 50); rotated 45 deg -> span = (100+50)*sqrt(2)
282        let expected_span = 150.0 * std::f32::consts::SQRT_2;
283        assert!((rect.width - expected_span).abs() < 1e-2);
284        assert!((rect.height - expected_span).abs() < 1e-2);
285    }
286
287    #[test]
288    fn camera2d_to_vello_affine_ortho_matches_world_to_screen() {
289        let cam = Camera2D {
290            pan: Vec2::new(33.0, -47.0),
291            zoom: 1.75,
292            rotation: -0.42,
293        };
294        let w = 640.0_f32;
295        let h = 480.0_f32;
296        let vp = ViewportRect::new(0.0, 0.0, w, h);
297        let affine = cam.to_vello_affine_ortho(w, h);
298        let world_pt = Vec2::new(125.0, -80.0);
299
300        let affine_x =
301            (affine[0] * world_pt.x as f64 + affine[2] * world_pt.y as f64 + affine[4]) as f32;
302        let affine_y =
303            (affine[1] * world_pt.x as f64 + affine[3] * world_pt.y as f64 + affine[5]) as f32;
304        let screen_pt = cam.world_to_screen(world_pt, vp);
305
306        assert!((affine_x - screen_pt.x).abs() < 1e-3);
307        assert!((affine_y - screen_pt.y).abs() < 1e-3);
308    }
309
310    #[test]
311    fn camera2d_y_down_roundtrip_affine_and_zoom_at() {
312        let mut cam = Camera2D {
313            pan: Vec2::new(100.0, 50.0),
314            zoom: 2.0,
315            rotation: 0.3,
316        };
317        let vp = ViewportRect::new(12.0, 8.0, 800.0, 600.0);
318        let world = Vec2::new(45.0, -22.0);
319        let screen = cam.world_to_screen_y_down(world, vp);
320        let back = cam.screen_to_world_y_down(screen, vp);
321        assert!((back - world).length() < 1e-4);
322
323        let origin_vp = ViewportRect::new(0.0, 0.0, 800.0, 600.0);
324        let affine = cam.to_vello_affine_y_down();
325        let ax = (affine[0] * world.x as f64 + affine[2] * world.y as f64 + affine[4]) as f32;
326        let ay = (affine[1] * world.x as f64 + affine[3] * world.y as f64 + affine[5]) as f32;
327        let s0 = cam.world_to_screen_y_down(world, origin_vp);
328        assert!((ax - s0.x).abs() < 1e-4);
329        assert!((ay - s0.y).abs() < 1e-4);
330
331        let cursor = Vec2::new(250.0, 175.0);
332        let before = cam.screen_to_world_y_down(cursor, origin_vp);
333        cam.zoom_at_y_down(cursor, 1.8);
334        let after = cam.world_to_screen_y_down(before, origin_vp);
335        assert!((after - cursor).length() < 1e-3);
336    }
337
338    #[test]
339    fn raw_camera_gl_row_major_f64_remaps_z_and_transposes() {
340        // OpenGL perspective projection (near=1.0, far=10.0, fov=90 deg, aspect=1.0) in row-major f64:
341        // f = 1 / tan(45 deg) = 1.0
342        // row2 = [0, 0, -(f+n)/(f-n), -2*f*n/(f-n)] = [0, 0, -11/9, -20/9]
343        // row3 = [0, 0, -1, 0]
344        let view_rm: [f64; 16] = [
345            1.0, 0.0, 0.0, 2.0, 0.0, 1.0, 0.0, -3.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
346        ];
347        let proj_rm: [f64; 16] = [
348            1.0,
349            0.0,
350            0.0,
351            0.0,
352            0.0,
353            1.0,
354            0.0,
355            0.0,
356            0.0,
357            0.0,
358            -11.0 / 9.0,
359            -20.0 / 9.0,
360            0.0,
361            0.0,
362            -1.0,
363            0.0,
364        ];
365
366        let raw = RawCamera::from_gl_row_major_f64(&view_rm, &proj_rm);
367        let vp = raw.view_proj_matrix();
368
369        // Point at eye z = -1.0 (near plane): world = (-2, 3, -1, 1) -> eye = (0, 0, -1, 1) -> z_wgpu = 0.0
370        let c_near = vp * Vec4::new(-2.0, 3.0, -1.0, 1.0);
371        assert!((c_near.z / c_near.w - 0.0).abs() < 1e-5);
372
373        // Point at eye z = -10.0 (far plane): world = (-2, 3, -10, 1) -> eye = (0, 0, -10, 1) -> z_wgpu = 1.0
374        let c_far = vp * Vec4::new(-2.0, 3.0, -10.0, 1.0);
375        assert!((c_far.z / c_far.w - 1.0).abs() < 1e-5);
376
377        // Point where GL NDC z == 0 (eye z = -20/11): z_wgpu = 0.5
378        let z_mid = -20.0_f32 / 11.0;
379        let c_mid = vp * Vec4::new(-2.0, 3.0, z_mid, 1.0);
380        assert!((c_mid.z / c_mid.w - 0.5).abs() < 1e-5);
381
382        // Verify transpose of translation: world (0,0,0,1) -> eye (2, -3, 0, 1)
383        let eye0 = raw.view * Vec4::new(0.0, 0.0, 0.0, 1.0);
384        assert!((eye0.x - 2.0).abs() < 1e-5);
385        assert!((eye0.y - (-3.0)).abs() < 1e-5);
386    }
387
388    #[test]
389    fn raw_camera_view_proj_gl_row_major_f64_preserves_large_offset_precision() {
390        // World origin shifted by 1e7 with non-power-of-two scale (1/3):
391        // f64 multiplication before narrowing avoids f32 intermediate cancellation/drift.
392        let offset = 10_000_000.0_f64;
393        let view_rm: [f64; 16] = [
394            1.0, 0.0, 0.0, -offset, 0.0, 1.0, 0.0, -offset, 0.0, 0.0, 1.0, -5.0, 0.0, 0.0, 0.0, 1.0,
395        ];
396        let proj_rm: [f64; 16] = [
397            1.0 / 3.0,
398            0.0,
399            0.0,
400            0.0,
401            0.0,
402            1.0 / 3.0,
403            0.0,
404            0.0,
405            0.0,
406            0.0,
407            -2.0 / 99.0,
408            -101.0 / 99.0,
409            0.0,
410            0.0,
411            0.0,
412            1.0,
413        ];
414
415        let vp = RawCamera::view_proj_gl_row_major_f64(&view_rm, &proj_rm);
416        let expected_tx = (-offset / 3.0) as f32;
417        assert!(
418            (vp.w_axis.x - expected_tx).abs() <= 0.5,
419            "vp.w_axis.x={} expected={}",
420            vp.w_axis.x,
421            expected_tx
422        );
423
424        // Verify exact transform on power-of-two ortho scale with large offset.
425        let ortho_view_rm: [f64; 16] = [
426            1.0,
427            0.0,
428            0.0,
429            -1_000_000.0,
430            0.0,
431            1.0,
432            0.0,
433            -1_000_000.0,
434            0.0,
435            0.0,
436            1.0,
437            -5.0,
438            0.0,
439            0.0,
440            0.0,
441            1.0,
442        ];
443        let ortho_proj_rm: [f64; 16] = [
444            0.125,
445            0.0,
446            0.0,
447            0.0,
448            0.0,
449            0.125,
450            0.0,
451            0.0,
452            0.0,
453            0.0,
454            -2.0 / 99.0,
455            -101.0 / 99.0,
456            0.0,
457            0.0,
458            0.0,
459            1.0,
460        ];
461        let vp_ortho = RawCamera::view_proj_gl_row_major_f64(&ortho_view_rm, &ortho_proj_rm);
462        let clip = vp_ortho * Vec4::new(1_000_002.0, 999_997.0, 0.0, 1.0);
463        assert!((clip.x - 0.25).abs() < 1e-4, "clip.x={}", clip.x);
464        assert!((clip.y - (-0.375)).abs() < 1e-4, "clip.y={}", clip.y);
465    }
466}