Skip to main content

viewport_lib_input/controllers/
camera2d.rs

1//! A flat orthographic camera for 2D views, and the controller that drives it.
2//!
3//! [`Camera2d`] describes a view in 2D terms (a centre on a world plane, a zoom
4//! as world units per pixel, a turn about the view axis) and writes the
5//! orthographic [`Camera`](crate::Camera) the renderer draws with. It looks straight at its
6//! plane and never orbits.
7//!
8//! [`Camera2dController`] applies drag-to-pan and zoom-about-the-cursor from an
9//! [`ActionFrame`](crate::input::ActionFrame) to a `Camera2d`. Pair it with
10//! [`BindingPreset::Planar`](crate::input::BindingPreset::Planar).
11//! [`Camera2dControl`] wraps the two as a [`CameraController`], for a runner
12//! that drives a `Camera` through that trait.
13//!
14//! [`snap_camera_to_pixels`] snaps any orthographic camera to whole device
15//! pixels, for a host that moves the camera after `Camera2d` has written it.
16//!
17//! Screen positions are viewport-local logical pixels with the origin at the
18//! top left and y down, the same space as
19//! [`PointerFrame::cursor`](crate::input::PointerFrame::cursor). Plane
20//! positions are `Vec2`s in world units along the plane's two axes; see
21//! [`Plane2d`].
22//!
23//! The viewport size is the size the scene draws at. For a viewport presented
24//! at a fixed reference size (`Presentation::Reference` on the renderer's
25//! viewport frame) that is the reference size, with one pixel per point, and
26//! screen positions are reference pixels: map the cursor with the renderer's
27//! `window_to_reference` first.
28
29use glam::{DMat3, DQuat, DVec3, Vec2, Vec3};
30use viewport_lib_types::camera::{Pose, Projection};
31
32use crate::CameraController;
33
34use crate::Camera;
35use crate::input::action_frame::ActionFrame;
36use crate::input::context::ViewportContext;
37use crate::input::event::ViewportEvent;
38use crate::input::preset::planar_bindings;
39use crate::input::viewport_binding::ViewportBinding;
40use crate::input::viewport_input::ViewportInput;
41
42/// The world plane a [`Camera2d`] looks at.
43///
44/// Both choices put plane x on world +X (screen right at rotation 0) and plane
45/// y on the world axis that should read as up. They match
46/// `viewport_lib::WorldPlane` (the plane of a world overlay layer) and the
47/// tilemap's `TilemapPlane`, axis for axis, and convert to `WorldPlane` with
48/// `From`.
49#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
50#[non_exhaustive]
51pub enum Plane2d {
52    /// The world XY plane seen from above, looking along -Z. Plane y is world
53    /// +Y. The plane for a top-down view or a document.
54    #[default]
55    Xy,
56    /// The world XZ plane seen from the front, looking along +Y. Plane y is
57    /// world +Z, so up on screen is up in the Z-up world: the plane for a side
58    /// view.
59    Xz,
60}
61
62impl From<Plane2d> for viewport_lib_types::overlay::WorldPlane {
63    fn from(plane: Plane2d) -> Self {
64        match plane {
65            Plane2d::Xy => Self::Xy,
66            Plane2d::Xz => Self::Xz,
67        }
68    }
69}
70
71impl Plane2d {
72    /// World direction of plane +x.
73    pub fn x_axis(self) -> Vec3 {
74        Vec3::X
75    }
76
77    /// World direction of plane +y.
78    pub fn y_axis(self) -> Vec3 {
79        match self {
80            Plane2d::Xy => Vec3::Y,
81            Plane2d::Xz => Vec3::Z,
82        }
83    }
84
85    /// The direction the camera looks: into the plane.
86    pub fn view_direction(self) -> Vec3 {
87        match self {
88            Plane2d::Xy => Vec3::NEG_Z,
89            Plane2d::Xz => Vec3::Y,
90        }
91    }
92
93    /// The world point at plane position `p`, on the plane through the origin.
94    pub fn to_world(self, p: Vec2) -> DVec3 {
95        (self.x_axis() * p.x + self.y_axis() * p.y).as_dvec3()
96    }
97
98    /// The plane position of a world point, dropping its depth along the view
99    /// direction.
100    pub fn from_world(self, p: DVec3) -> Vec2 {
101        match self {
102            Plane2d::Xy => Vec2::new(p.x as f32, p.y as f32),
103            Plane2d::Xz => Vec2::new(p.x as f32, p.z as f32),
104        }
105    }
106}
107
108/// An axis-aligned rectangle, in plane units or in pixels depending on use.
109#[derive(Clone, Copy, Debug, PartialEq, Default)]
110pub struct Rect2d {
111    /// The corner with the smaller coordinates.
112    pub min: Vec2,
113    /// The corner with the larger coordinates.
114    pub max: Vec2,
115}
116
117impl Rect2d {
118    /// The rectangle spanning two corners, in either order.
119    pub fn new(a: Vec2, b: Vec2) -> Self {
120        Self {
121            min: a.min(b),
122            max: a.max(b),
123        }
124    }
125
126    /// The rectangle `size` across, centred on `centre`.
127    pub fn from_centre_size(centre: Vec2, size: Vec2) -> Self {
128        let half = size.abs() * 0.5;
129        Self {
130            min: centre - half,
131            max: centre + half,
132        }
133    }
134
135    /// The middle of the rectangle.
136    pub fn centre(&self) -> Vec2 {
137        (self.min + self.max) * 0.5
138    }
139
140    /// Width and height.
141    pub fn size(&self) -> Vec2 {
142        self.max - self.min
143    }
144
145    /// Whether `p` lies inside or on the edge.
146    pub fn contains(&self, p: Vec2) -> bool {
147        p.cmpge(self.min).all() && p.cmple(self.max).all()
148    }
149}
150
151/// A decaying screen shake in progress.
152#[derive(Clone, Copy, Debug, Default)]
153struct Shake {
154    amplitude: f32,
155    duration: f32,
156    elapsed: f32,
157    /// The current offset in pixels, x right and y down.
158    offset: Vec2,
159}
160
161impl Shake {
162    fn remaining_amplitude(&self) -> f32 {
163        if self.duration <= 0.0 || self.elapsed >= self.duration {
164            0.0
165        } else {
166            let left = 1.0 - self.elapsed / self.duration;
167            self.amplitude * left * left
168        }
169    }
170}
171
172/// A flat orthographic camera described in 2D terms.
173///
174/// The view is a `centre` on a [`Plane2d`], a zoom as `units_per_pixel` (world
175/// units across one logical pixel), and a `rotation` about the view axis.
176/// [`apply_to`](Self::apply_to) writes the orthographic pose and projection
177/// into a [`Camera`] the host owns, and [`camera`](Self::camera) builds a new
178/// one; give the renderer that each frame.
179///
180/// On top of the view sit a follow target with damping and a dead zone,
181/// optional world bounds the visible area is kept inside, a decaying screen
182/// shake, and pixel snapping for pixel art. [`update`](Self::update) advances
183/// the follow and the shake once per frame.
184///
185/// The stored zoom is never snapped. With
186/// [`snap_zoom_to_texel`](Self::snap_zoom_to_texel) set, the camera written
187/// out uses the nearest zoom that shows a whole number of device pixels per
188/// texel ([`drawn_units_per_pixel`](Self::drawn_units_per_pixel)), so small
189/// wheel steps still add up to the next scale.
190///
191/// [`screen_to_world`](Self::screen_to_world),
192/// [`world_to_screen`](Self::world_to_screen) and
193/// [`visible_rect`](Self::visible_rect) describe the view at the drawn zoom,
194/// without the shake offset or the position snapping that
195/// [`apply_to`](Self::apply_to) adds.
196#[derive(Clone, Debug)]
197pub struct Camera2d {
198    /// The plane the camera looks at.
199    pub plane: Plane2d,
200    /// How far the eye sits in front of the plane, in world units. Content
201    /// between the eye and the far plane draws, so keep it larger than the
202    /// highest layer above the plane. Defaults to `100.0`.
203    pub distance: f32,
204    /// Physical pixels per logical pixel, for pixel snapping and
205    /// [`snap_zoom_to_integer_scale`](Self::snap_zoom_to_integer_scale).
206    /// Defaults to `1.0`. Keep it at `1.0` for a viewport presented at a
207    /// reference size, whose scene target has one pixel per point.
208    pub pixels_per_point: f32,
209    /// Round the written camera position so the plane origin lands on a whole
210    /// device pixel, which keeps pixel art from shimmering as the camera moves.
211    /// Off by default. A host that moves the camera after
212    /// [`apply_to`](Self::apply_to) (a blend or its own shake) leaves this off
213    /// and calls [`snap_camera_to_pixels`] last instead.
214    pub snap_to_pixels: bool,
215    /// World units per texel of the art, to keep the drawn zoom at a whole
216    /// number of device pixels per texel: the written camera uses the nearest
217    /// such zoom, at least one device pixel per texel, while
218    /// [`units_per_pixel`](Self::units_per_pixel) keeps the unsnapped value.
219    /// `None` (the default) draws at the stored zoom.
220    pub snap_zoom_to_texel: Option<f32>,
221    /// Near and far plane distances along the view direction, measured from
222    /// the eye, for the written projection. `None` (the default) keeps the
223    /// projection's automatic planes, which reach about `max(1000, 3 *
224    /// distance)` from the eye. The far plane is never nearer than three
225    /// times [`distance`](Self::distance), which keeps the plane itself in
226    /// view.
227    pub depth_range: Option<[f32; 2]>,
228    /// The smallest units per pixel zooming reaches (the closest zoom).
229    pub min_units_per_pixel: f32,
230    /// The largest units per pixel zooming reaches (the furthest zoom).
231    pub max_units_per_pixel: f32,
232    /// How quickly the camera catches up with its follow target: the time in
233    /// seconds for the distance left outside the dead zone to fall to about
234    /// 37%. Zero or less snaps straight to it. Defaults to `0.25`.
235    pub follow_time_constant: f32,
236    /// The area around the screen centre the follow target can move in without
237    /// the camera moving, in pixel offsets from the centre with x right and y
238    /// down. Defaults to an empty rectangle at the centre, so the camera keeps
239    /// the target centred.
240    pub dead_zone: Rect2d,
241    centre: Vec2,
242    units_per_pixel: f32,
243    rotation: f32,
244    viewport_size: Vec2,
245    bounds: Option<Rect2d>,
246    follow_target: Option<Vec2>,
247    shake: Shake,
248    rng: u32,
249}
250
251impl Default for Camera2d {
252    fn default() -> Self {
253        Self::new(Plane2d::default())
254    }
255}
256
257impl Camera2d {
258    /// Default distance from the eye to the plane.
259    pub const DEFAULT_DISTANCE: f32 = 100.0;
260    /// Default zoom: 100 logical pixels per world unit.
261    pub const DEFAULT_UNITS_PER_PIXEL: f32 = 0.01;
262    /// Default follow time constant, in seconds.
263    pub const DEFAULT_FOLLOW_TIME_CONSTANT: f32 = 0.25;
264
265    /// A camera on `plane`, centred on the origin at the default zoom, for a
266    /// 1 by 1 pixel viewport: call [`set_viewport_size`](Self::set_viewport_size)
267    /// before producing a camera.
268    pub fn new(plane: Plane2d) -> Self {
269        Self {
270            plane,
271            distance: Self::DEFAULT_DISTANCE,
272            pixels_per_point: 1.0,
273            snap_to_pixels: false,
274            snap_zoom_to_texel: None,
275            depth_range: None,
276            min_units_per_pixel: 1.0e-6,
277            max_units_per_pixel: 1.0e6,
278            follow_time_constant: Self::DEFAULT_FOLLOW_TIME_CONSTANT,
279            dead_zone: Rect2d::default(),
280            centre: Vec2::ZERO,
281            units_per_pixel: Self::DEFAULT_UNITS_PER_PIXEL,
282            rotation: 0.0,
283            viewport_size: Vec2::ONE,
284            bounds: None,
285            follow_target: None,
286            shake: Shake::default(),
287            rng: 0x9E37_79B9,
288        }
289    }
290
291    /// Builder: set the centre; see [`set_centre`](Self::set_centre).
292    pub fn with_centre(mut self, centre: Vec2) -> Self {
293        self.set_centre(centre);
294        self
295    }
296
297    /// Builder: set the zoom; see [`set_units_per_pixel`](Self::set_units_per_pixel).
298    pub fn with_units_per_pixel(mut self, units_per_pixel: f32) -> Self {
299        self.set_units_per_pixel(units_per_pixel);
300        self
301    }
302
303    /// Builder: set the viewport size in logical pixels.
304    pub fn with_viewport_size(mut self, size: Vec2) -> Self {
305        self.set_viewport_size(size);
306        self
307    }
308
309    /// Builder: set the rotation; see [`set_rotation`](Self::set_rotation).
310    pub fn with_rotation(mut self, rotation: f32) -> Self {
311        self.set_rotation(rotation);
312        self
313    }
314
315    /// Builder: keep the visible area inside `bounds`; see
316    /// [`set_bounds`](Self::set_bounds).
317    pub fn with_bounds(mut self, bounds: Rect2d) -> Self {
318        self.set_bounds(Some(bounds));
319        self
320    }
321
322    // -----------------------------------------------------------------------
323    // View state
324    // -----------------------------------------------------------------------
325
326    /// The plane position at the middle of the screen.
327    pub fn centre(&self) -> Vec2 {
328        self.centre
329    }
330
331    /// Move the middle of the screen to `centre`, then apply the bounds.
332    pub fn set_centre(&mut self, centre: Vec2) {
333        self.centre = centre;
334        self.clamp_to_bounds();
335    }
336
337    /// World units across one logical pixel. Smaller is closer. This is the
338    /// stored zoom, never snapped; see
339    /// [`drawn_units_per_pixel`](Self::drawn_units_per_pixel).
340    pub fn units_per_pixel(&self) -> f32 {
341        self.units_per_pixel
342    }
343
344    /// The zoom the written camera draws at: [`units_per_pixel`](Self::units_per_pixel),
345    /// or with [`snap_zoom_to_texel`](Self::snap_zoom_to_texel) set the
346    /// nearest zoom that shows a whole number of device pixels per texel.
347    pub fn drawn_units_per_pixel(&self) -> f32 {
348        match self.snap_zoom_to_texel {
349            Some(units_per_texel) if units_per_texel > 0.0 => {
350                integer_scale_zoom(units_per_texel, self.pixels_per_point, self.units_per_pixel).0
351            }
352            _ => self.units_per_pixel,
353        }
354    }
355
356    /// Set the zoom about the screen centre, clamped to
357    /// `[min_units_per_pixel, max_units_per_pixel]`, then apply the bounds.
358    pub fn set_units_per_pixel(&mut self, units_per_pixel: f32) {
359        self.units_per_pixel = self.clamp_zoom(units_per_pixel);
360        self.clamp_to_bounds();
361    }
362
363    /// The turn of the view about the view axis, in radians. Positive turns
364    /// the camera counter-clockwise on the plane, so the content appears to
365    /// turn clockwise.
366    pub fn rotation(&self) -> f32 {
367        self.rotation
368    }
369
370    /// Set the turn about the view axis, then apply the bounds.
371    pub fn set_rotation(&mut self, rotation: f32) {
372        self.rotation = rotation;
373        self.clamp_to_bounds();
374    }
375
376    /// The viewport size in logical pixels.
377    pub fn viewport_size(&self) -> Vec2 {
378        self.viewport_size
379    }
380
381    /// Set the viewport size in logical pixels, keeping the centre and zoom,
382    /// then apply the bounds. Call it whenever the viewport resizes.
383    ///
384    /// This is the size the scene draws at, which sets the written camera's
385    /// aspect and height: for a viewport presented at a reference size, pass
386    /// the reference size (and keep [`pixels_per_point`](Self::pixels_per_point)
387    /// at `1.0`), not the window's.
388    pub fn set_viewport_size(&mut self, size: Vec2) {
389        self.viewport_size = size.max(Vec2::ZERO);
390        self.clamp_to_bounds();
391    }
392
393    /// The area the visible rectangle is kept inside, if any.
394    pub fn bounds(&self) -> Option<Rect2d> {
395        self.bounds
396    }
397
398    /// Keep the visible area inside `bounds` (in plane units), or remove the
399    /// limit with `None`. Along an axis where the view is wider than the
400    /// bounds, the view centres on them instead. The shake offset is not
401    /// limited.
402    pub fn set_bounds(&mut self, bounds: Option<Rect2d>) {
403        self.bounds = bounds;
404        self.clamp_to_bounds();
405    }
406
407    /// The screen's right and up directions on the plane.
408    fn screen_axes(&self) -> (Vec2, Vec2) {
409        let (s, c) = self.rotation.sin_cos();
410        (Vec2::new(c, s), Vec2::new(-s, c))
411    }
412
413    /// A screen offset in pixels (x right, y down) as a plane vector.
414    fn offset_to_plane(&self, offset: Vec2) -> Vec2 {
415        let (right, up) = self.screen_axes();
416        (right * offset.x - up * offset.y) * self.drawn_units_per_pixel()
417    }
418
419    /// A plane vector as a screen offset in pixels (x right, y down).
420    fn plane_to_offset(&self, v: Vec2) -> Vec2 {
421        let (right, up) = self.screen_axes();
422        Vec2::new(v.dot(right), -v.dot(up)) / self.drawn_units_per_pixel()
423    }
424
425    /// The plane position under a screen position.
426    pub fn screen_to_world(&self, screen: Vec2) -> Vec2 {
427        self.centre + self.offset_to_plane(screen - self.viewport_size * 0.5)
428    }
429
430    /// The screen position of a plane position.
431    pub fn world_to_screen(&self, world: Vec2) -> Vec2 {
432        self.viewport_size * 0.5 + self.plane_to_offset(world - self.centre)
433    }
434
435    /// The plane area the viewport shows: exact at rotation 0, and the
436    /// bounding rectangle of the turned view otherwise.
437    pub fn visible_rect(&self) -> Rect2d {
438        Rect2d {
439            min: self.centre - self.visible_half_extent(),
440            max: self.centre + self.visible_half_extent(),
441        }
442    }
443
444    fn visible_half_extent(&self) -> Vec2 {
445        let (right, up) = self.screen_axes();
446        let half = self.viewport_size * 0.5 * self.drawn_units_per_pixel();
447        right.abs() * half.x + up.abs() * half.y
448    }
449
450    fn clamp_zoom(&self, units_per_pixel: f32) -> f32 {
451        let lo = self.min_units_per_pixel.max(f32::MIN_POSITIVE);
452        let hi = self.max_units_per_pixel.max(lo);
453        if units_per_pixel.is_finite() {
454            units_per_pixel.clamp(lo, hi)
455        } else {
456            self.units_per_pixel
457        }
458    }
459
460    fn clamp_to_bounds(&mut self) {
461        let Some(bounds) = self.bounds else {
462            return;
463        };
464        let half = self.visible_half_extent();
465        let size = bounds.size();
466        for axis in 0..2 {
467            self.centre[axis] = if 2.0 * half[axis] >= size[axis] {
468                bounds.centre()[axis]
469            } else {
470                self.centre[axis]
471                    .clamp(bounds.min[axis] + half[axis], bounds.max[axis] - half[axis])
472            };
473        }
474    }
475
476    // -----------------------------------------------------------------------
477    // Navigation
478    // -----------------------------------------------------------------------
479
480    /// Move the view as if the content were dragged by `delta_pixels` (x right,
481    /// y down): the centre moves the other way by the delta times
482    /// [`units_per_pixel`](Self::units_per_pixel).
483    pub fn pan(&mut self, delta_pixels: Vec2) {
484        if delta_pixels != Vec2::ZERO {
485            self.centre -= self.offset_to_plane(delta_pixels);
486            self.clamp_to_bounds();
487        }
488    }
489
490    /// Zoom by `factor` about a screen position: above 1 zooms in, below 1
491    /// zooms out, and the plane point under `cursor_pixels` stays under it
492    /// (unless the zoom limits or the bounds move it). The factor applies to
493    /// the stored zoom, so with [`snap_zoom_to_texel`](Self::snap_zoom_to_texel)
494    /// set, small steps add up until the drawn scale changes.
495    pub fn zoom_at(&mut self, cursor_pixels: Vec2, factor: f32) {
496        if !(factor > 0.0) || factor == 1.0 {
497            return;
498        }
499        let anchor = self.screen_to_world(cursor_pixels);
500        self.units_per_pixel = self.clamp_zoom(self.units_per_pixel / factor);
501        self.centre = anchor - self.offset_to_plane(cursor_pixels - self.viewport_size * 0.5);
502        self.clamp_to_bounds();
503    }
504
505    /// Set the stored zoom so that one texel of art drawn at
506    /// `units_per_texel` world units covers a whole number of device pixels,
507    /// the nearest to the current zoom and at least one. Returns that number.
508    /// The centre stays.
509    ///
510    /// This rewrites the zoom, so calling it every frame rounds small wheel
511    /// steps back to the same scale. To keep every frame on a whole scale
512    /// while zooming, set [`snap_zoom_to_texel`](Self::snap_zoom_to_texel)
513    /// instead.
514    pub fn snap_zoom_to_integer_scale(&mut self, units_per_texel: f32) -> u32 {
515        let (units_per_pixel, scale) =
516            integer_scale_zoom(units_per_texel, self.pixels_per_point, self.units_per_pixel);
517        self.set_units_per_pixel(units_per_pixel);
518        scale
519    }
520
521    // -----------------------------------------------------------------------
522    // Follow and shake
523    // -----------------------------------------------------------------------
524
525    /// Follow `target`, a plane position. Call it each frame the target
526    /// moves; [`update`](Self::update) moves the camera toward it once it
527    /// leaves the [`dead_zone`](Self::dead_zone).
528    pub fn follow(&mut self, target: Vec2) {
529        self.follow_target = Some(target);
530    }
531
532    /// Stop following. The camera stays where it is.
533    pub fn stop_following(&mut self) {
534        self.follow_target = None;
535    }
536
537    /// The position being followed, if any.
538    pub fn follow_target(&self) -> Option<Vec2> {
539        self.follow_target
540    }
541
542    /// Start a shake: a random offset of up to `amplitude_pixels` that decays
543    /// to nothing over `duration` seconds. It moves only the written camera,
544    /// never the centre. A weaker shake does not cut short a stronger one
545    /// still running.
546    pub fn shake(&mut self, amplitude_pixels: f32, duration: f32) {
547        if amplitude_pixels <= 0.0 || duration <= 0.0 {
548            return;
549        }
550        if self.shake.remaining_amplitude() > amplitude_pixels {
551            return;
552        }
553        self.shake = Shake {
554            amplitude: amplitude_pixels,
555            duration,
556            elapsed: 0.0,
557            offset: Vec2::ZERO,
558        };
559        self.shake.offset = self.random_offset() * amplitude_pixels;
560    }
561
562    /// The current shake offset in pixels, x right and y down.
563    pub fn shake_offset(&self) -> Vec2 {
564        self.shake.offset
565    }
566
567    /// Advance the follow and the shake by `dt` seconds.
568    pub fn update(&mut self, dt: f32) {
569        let dt = dt.max(0.0);
570        if let Some(target) = self.follow_target {
571            let offset = self.plane_to_offset(target - self.centre);
572            let zone = Rect2d::new(self.dead_zone.min, self.dead_zone.max);
573            let excess = offset - offset.clamp(zone.min, zone.max);
574            if excess != Vec2::ZERO {
575                let k = if self.follow_time_constant > 0.0 {
576                    1.0 - (-dt / self.follow_time_constant).exp()
577                } else {
578                    1.0
579                };
580                self.centre += self.offset_to_plane(excess) * k;
581                self.clamp_to_bounds();
582            }
583        }
584        if self.shake.duration > 0.0 {
585            self.shake.elapsed += dt;
586            let amplitude = self.shake.remaining_amplitude();
587            if amplitude > 0.0 {
588                self.shake.offset = self.random_offset() * amplitude;
589            } else {
590                self.shake = Shake::default();
591            }
592        }
593    }
594
595    /// A point in the unit square about the origin, from a small xorshift
596    /// generator so a shake is the same on every run.
597    fn random_offset(&mut self) -> Vec2 {
598        let mut next = || {
599            let mut x = self.rng;
600            x ^= x << 13;
601            x ^= x >> 17;
602            x ^= x << 5;
603            self.rng = x;
604            (x >> 8) as f32 / (1u32 << 24) as f32 * 2.0 - 1.0
605        };
606        Vec2::new(next(), next())
607    }
608
609    // -----------------------------------------------------------------------
610    // The produced camera
611    // -----------------------------------------------------------------------
612
613    /// Write this view into `camera`: an orthographic projection as tall as
614    /// the viewport height times [`drawn_units_per_pixel`](Self::drawn_units_per_pixel),
615    /// with [`depth_range`](Self::depth_range) as its planes when set, and a
616    /// pose looking along the plane's view direction from
617    /// [`distance`](Self::distance) in front of it, moved by the shake offset
618    /// and, with [`snap_to_pixels`](Self::snap_to_pixels), snapped to whole
619    /// device pixels. The aspect comes from the viewport size and the focus
620    /// distance is set to `distance`; the exposure is otherwise left alone.
621    ///
622    /// The viewport size is the size the scene draws at: the reference size
623    /// for a viewport presented at one (see
624    /// [`set_viewport_size`](Self::set_viewport_size)).
625    ///
626    /// The camera is the host's to change afterwards: blend it, shake it,
627    /// then call [`snap_camera_to_pixels`] last if it should stay on the
628    /// pixel grid.
629    pub fn apply_to(&self, camera: &mut Camera) {
630        let (right, up) = self.screen_axes();
631        let centre = self.centre + self.offset_to_plane(self.shake.offset);
632
633        let plane = self.plane;
634        let world_right = plane.x_axis() * right.x + plane.y_axis() * right.y;
635        let world_up = plane.x_axis() * up.x + plane.y_axis() * up.y;
636        let back = -plane.view_direction();
637        let basis = DMat3::from_cols(world_right.as_dvec3(), world_up.as_dvec3(), back.as_dvec3());
638        let orientation = DQuat::from_mat3(&basis).normalize();
639        let distance = self.distance.max(1e-3);
640        let eye = plane.to_world(centre) + back.as_dvec3() * f64::from(distance);
641
642        let height = self.viewport_size.y * self.drawn_units_per_pixel();
643        let (near, far) = match self.depth_range {
644            Some([near, far]) => (Some(near), Some(far)),
645            None => (None, None),
646        };
647        camera.set_pose(Pose::new(eye, orientation));
648        camera.projection = Projection::Orthographic { height, near, far };
649        camera.set_aspect_ratio(self.viewport_size.x, self.viewport_size.y);
650        camera.set_focus_distance(distance);
651        if self.snap_to_pixels {
652            snap_camera_to_pixels(camera, self.viewport_size, self.pixels_per_point);
653        }
654    }
655
656    /// A new camera with this view written into it; see
657    /// [`apply_to`](Self::apply_to).
658    pub fn camera(&self) -> Camera {
659        let mut camera = Camera::new(Pose::IDENTITY);
660        self.apply_to(&mut camera);
661        camera
662    }
663}
664
665/// The zoom nearest `units_per_pixel` at which one texel of `units_per_texel`
666/// world units covers a whole number of device pixels (at least one), and that
667/// number.
668fn integer_scale_zoom(
669    units_per_texel: f32,
670    pixels_per_point: f32,
671    units_per_pixel: f32,
672) -> (f32, u32) {
673    let ppp = pixels_per_point.max(1e-3);
674    let device_per_texel = units_per_texel * ppp / units_per_pixel;
675    let scale = device_per_texel.round().max(1.0);
676    (units_per_texel * ppp / scale, scale as u32)
677}
678
679/// Move an orthographic camera across its view so the world origin lands on a
680/// whole device pixel, which keeps pixel art from shimmering as the camera
681/// moves. The camera's own right and up axes set the pixel grid, so it works
682/// at any turn about the view axis; the depth along the view is untouched.
683///
684/// `viewport_size` (in logical pixels) and `pixels_per_point` describe the
685/// target the scene draws into: for a viewport presented at a reference size,
686/// pass the reference size and `1.0`. Call it last, after any blend or shake
687/// the host applies. A perspective or matrix projection is left alone.
688pub fn snap_camera_to_pixels(camera: &mut Camera, viewport_size: Vec2, pixels_per_point: f32) {
689    let Projection::Orthographic { height, .. } = camera.projection else {
690        return;
691    };
692    let ppp = pixels_per_point.max(1e-3);
693    let device = viewport_size.as_dvec2() * f64::from(ppp);
694    if !(height > 0.0) || !(device.y > 0.0) {
695        return;
696    }
697    let per_device = f64::from(height) / device.y;
698    let right = camera.pose.orientation * DVec3::X;
699    let up = camera.pose.orientation * DVec3::Y;
700    let eye = camera.pose.position;
701    // The origin lands on a whole device pixel when the left and top edges
702    // sit a whole number of device pixels from it.
703    let r = eye.dot(right) / per_device;
704    let u = eye.dot(up) / per_device;
705    let snapped_r = (r - device.x * 0.5).round() + device.x * 0.5;
706    let snapped_u = (u + device.y * 0.5).round() - device.y * 0.5;
707    camera.pose.position =
708        eye + right * ((snapped_r - r) * per_device) + up * ((snapped_u - u) * per_device);
709}
710
711/// A [`Camera2d`] and a [`Camera2dController`] as one [`CameraController`]:
712/// each frame it applies pan and zoom from the resolved input, advances the
713/// follow and the shake, and writes the view into the camera with
714/// [`Camera2d::apply_to`].
715///
716/// Hand it to a runner that drives a camera through [`CameraController`]
717/// (`ViewportApp`'s `CameraControl::Controller`), and reach the 2D camera
718/// through [`camera`](Self::camera) to follow, shake or set bounds. The runner
719/// passes the size the scene draws at through
720/// [`CameraController::set_viewport`] before each apply.
721pub struct Camera2dControl {
722    /// The 2D view.
723    pub camera: Camera2d,
724    /// The pan and zoom policy, with no resolver of its own.
725    pub controller: Camera2dController,
726}
727
728impl Camera2dControl {
729    /// Drive `camera` with a stateless [`Camera2dController`].
730    pub fn new(camera: Camera2d) -> Self {
731        Self {
732            camera,
733            controller: Camera2dController::new_stateless(),
734        }
735    }
736}
737
738impl CameraController for Camera2dControl {
739    fn apply(&mut self, camera: &mut Camera, frame: &ActionFrame, dt: f32) {
740        self.controller.apply(&mut self.camera, frame, dt);
741        self.camera.apply_to(camera);
742    }
743
744    fn set_viewport(&mut self, viewport_size: [f32; 2], pixels_per_point: f32) {
745        let size = Vec2::from(viewport_size);
746        if size != self.camera.viewport_size() {
747            self.camera.set_viewport_size(size);
748        }
749        self.camera.pixels_per_point = pixels_per_point;
750    }
751
752    fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
753        Some(self)
754    }
755}
756
757/// Drag-to-pan and zoom-about-the-cursor for a [`Camera2d`].
758///
759/// Two ways to drive it, as with the other controllers:
760///
761/// - The host owns a [`ViewportInput`] (or a `ViewportInstance`) with
762///   [`planar_bindings`] and hands each resolved frame to
763///   [`apply`](Self::apply). Create the controller with
764///   [`new_stateless`](Self::new_stateless).
765/// - The controller owns the resolver: create it with [`new`](Self::new), call
766///   [`begin_frame`](Self::begin_frame) with the frame's
767///   [`ViewportContext`], push every translated event with
768///   [`push_event`](Self::push_event), and call
769///   [`apply_to_camera`](Self::apply_to_camera) once per frame. Events are
770///   routed by the context's input ownership, so a drag that starts over the
771///   application's UI does not pan.
772///
773/// ```text
774/// controller.begin_frame(ViewportContext::new(ownership, viewport_size));
775/// for event in events { controller.push_event(event); }
776/// controller.apply_to_camera(&mut camera2d, dt);
777/// frame_camera = camera2d.camera();
778/// ```
779///
780/// Both paths also advance the camera's follow and shake, so do not call
781/// [`Camera2d::update`] as well.
782pub struct Camera2dController {
783    input: ViewportInput,
784    /// Multiplier on pan deltas. Defaults to `1.0`, which keeps the content
785    /// under the pointer while dragging.
786    pub pan_sensitivity: f32,
787    /// Zoom per pixel of wheel or pinch input: each frame zooms by
788    /// `exp(zoom * zoom_sensitivity)`. Defaults to
789    /// [`DEFAULT_ZOOM_SENSITIVITY`](Self::DEFAULT_ZOOM_SENSITIVITY).
790    pub zoom_sensitivity: f32,
791    viewport_size: Vec2,
792}
793
794impl Default for Camera2dController {
795    fn default() -> Self {
796        Self::new()
797    }
798}
799
800impl Camera2dController {
801    /// Default zoom sensitivity: a wheel notch zooms by about 6%.
802    pub const DEFAULT_ZOOM_SENSITIVITY: f32 = 0.002;
803
804    /// A controller with its own resolver holding [`planar_bindings`].
805    pub fn new() -> Self {
806        Self::from_bindings(planar_bindings())
807    }
808
809    /// A controller with its own resolver holding `bindings`.
810    pub fn from_bindings(bindings: Vec<ViewportBinding>) -> Self {
811        Self {
812            input: ViewportInput::new(bindings),
813            pan_sensitivity: 1.0,
814            zoom_sensitivity: Self::DEFAULT_ZOOM_SENSITIVITY,
815            viewport_size: Vec2::ZERO,
816        }
817    }
818
819    /// A controller with no bindings, for a host that resolves its own frames
820    /// and calls [`apply`](Self::apply).
821    pub fn new_stateless() -> Self {
822        Self::from_bindings(Vec::new())
823    }
824
825    /// The controller's own resolver, for touch settings or cancelling a
826    /// gesture.
827    pub fn input_mut(&mut self) -> &mut ViewportInput {
828        &mut self.input
829    }
830
831    /// Begin a frame: clear the per-frame input and record the context (input
832    /// ownership and viewport size). Call it before pushing the frame's events.
833    pub fn begin_frame(&mut self, ctx: ViewportContext) {
834        self.viewport_size = Vec2::from(ctx.viewport_size);
835        self.input.begin_frame(ctx);
836    }
837
838    /// [`begin_frame`](Self::begin_frame) with the host's clock, which double
839    /// tap and long press need.
840    pub fn begin_frame_at(&mut self, ctx: ViewportContext, time_seconds: f32) {
841        self.viewport_size = Vec2::from(ctx.viewport_size);
842        self.input.begin_frame_at(ctx, time_seconds);
843    }
844
845    /// Push one translated event. Routing follows the ownership given to the
846    /// last [`begin_frame`](Self::begin_frame).
847    pub fn push_event(&mut self, event: ViewportEvent) {
848        self.input.push_event(event);
849    }
850
851    /// Resolve the events pushed this frame without moving any camera.
852    pub fn resolve(&self) -> ActionFrame {
853        self.input.resolve()
854    }
855
856    /// Resolve this frame's events, set the camera's viewport size from the
857    /// last [`begin_frame`](Self::begin_frame), apply the input and advance
858    /// follow and shake by `dt`. Returns the resolved frame.
859    pub fn apply_to_camera(&mut self, camera: &mut Camera2d, dt: f32) -> ActionFrame {
860        let frame = self.input.resolve();
861        if self.viewport_size != Vec2::ZERO && self.viewport_size != camera.viewport_size() {
862            camera.set_viewport_size(self.viewport_size);
863        }
864        self.apply(camera, &frame, dt);
865        frame
866    }
867
868    /// Apply a resolved frame: pan by `navigation.pan`, zoom by
869    /// `navigation.zoom` about the cursor (the touch point during a pinch, the
870    /// screen centre with neither), then advance follow and shake by `dt`.
871    /// Orbit and twist are ignored. The camera's viewport size must already
872    /// be current.
873    pub fn apply(&mut self, camera: &mut Camera2d, frame: &ActionFrame, dt: f32) {
874        let nav = &frame.navigation;
875        if nav.pan != Vec2::ZERO {
876            camera.pan(nav.pan * self.pan_sensitivity);
877        }
878        if nav.zoom != 0.0 {
879            let pointer = &frame.pointer;
880            let anchor = if pointer.contacts >= 2 {
881                pointer.touch_position.or(pointer.cursor)
882            } else {
883                pointer.cursor
884            }
885            .unwrap_or(camera.viewport_size() * 0.5);
886            camera.zoom_at(anchor, (nav.zoom * self.zoom_sensitivity).exp());
887        }
888        camera.update(dt);
889    }
890}
891
892#[cfg(test)]
893mod tests {
894    use super::*;
895    use crate::input::binding::MouseButton;
896    use crate::input::context::InputOwnership;
897    use crate::input::event::{ButtonState, ScrollUnits};
898
899    const PLANES: [Plane2d; 2] = [Plane2d::Xy, Plane2d::Xz];
900
901    fn close(a: Vec2, b: Vec2, eps: f32) -> bool {
902        (a - b).abs().max_element() <= eps
903    }
904
905    fn cam(plane: Plane2d) -> Camera2d {
906        Camera2d::new(plane)
907            .with_viewport_size(Vec2::new(800.0, 600.0))
908            .with_units_per_pixel(0.05)
909            .with_centre(Vec2::new(3.0, -2.0))
910    }
911
912    /// Where a plane point lands on screen through the produced camera, in
913    /// device pixels.
914    fn project(c: &Camera2d, world: Vec2) -> Vec2 {
915        let camera = c.camera();
916        let ndc = camera
917            .view_proj_matrix()
918            .project_point3(c.plane.to_world(world).as_vec3());
919        let device = c.viewport_size() * c.pixels_per_point;
920        Vec2::new(
921            (ndc.x + 1.0) * 0.5 * device.x,
922            (1.0 - ndc.y) * 0.5 * device.y,
923        )
924    }
925
926    #[test]
927    fn zoom_at_cursor_keeps_the_point_under_it() {
928        for plane in PLANES {
929            for rotation in [0.0, 0.4] {
930                let mut c = cam(plane).with_rotation(rotation);
931                let cursor = Vec2::new(620.0, 140.0);
932                let before = c.screen_to_world(cursor);
933                c.zoom_at(cursor, 1.7);
934                assert!((c.units_per_pixel() - 0.05 / 1.7).abs() < 1e-7);
935                assert!(close(c.screen_to_world(cursor), before, 1e-4));
936                assert!(close(project(&c, before), cursor, 0.05), "{plane:?}");
937                c.zoom_at(cursor, 0.3);
938                assert!(close(c.screen_to_world(cursor), before, 1e-4));
939            }
940        }
941    }
942
943    #[test]
944    fn pan_moves_by_pixels_times_units_per_pixel() {
945        let mut c = cam(Plane2d::Xy);
946        let p = Vec2::new(1.0, 1.5);
947        let on_screen = c.world_to_screen(p);
948        c.pan(Vec2::new(10.0, -4.0));
949        // Dragging right moves the centre left; dragging up (y down) moves it down.
950        assert!(close(c.centre(), Vec2::new(3.0 - 0.5, -2.0 - 0.2), 1e-5));
951        assert!(close(
952            c.world_to_screen(p),
953            on_screen + Vec2::new(10.0, -4.0),
954            1e-3
955        ));
956        // Turned a quarter, the same drag moves along the turned axes.
957        let mut r = cam(Plane2d::Xz).with_rotation(std::f32::consts::FRAC_PI_2);
958        r.pan(Vec2::new(10.0, 0.0));
959        assert!(close(r.centre(), Vec2::new(3.0, -2.0 - 0.5), 1e-5));
960    }
961
962    #[test]
963    fn follow_waits_for_the_dead_zone_then_converges() {
964        let mut c = Camera2d::new(Plane2d::Xy)
965            .with_viewport_size(Vec2::new(400.0, 300.0))
966            .with_units_per_pixel(0.1);
967        c.dead_zone = Rect2d::from_centre_size(Vec2::ZERO, Vec2::new(100.0, 100.0));
968        c.follow_time_constant = 0.5;
969
970        // 30 px right and 40 px up: inside the 50 px half-size.
971        c.follow(Vec2::new(3.0, 4.0));
972        for _ in 0..30 {
973            c.update(1.0 / 60.0);
974        }
975        assert_eq!(c.centre(), Vec2::ZERO);
976
977        // 100 px right: 50 px (5 units) outside the zone.
978        c.follow(Vec2::new(10.0, 0.0));
979        for _ in 0..10 {
980            c.update(0.05);
981        }
982        let left = 10.0 - 5.0 - c.centre().x;
983        let expected = 5.0 * (-1.0f32).exp();
984        assert!((left - expected).abs() < 1e-4, "{left} vs {expected}");
985        assert_eq!(c.centre().y, 0.0);
986
987        for _ in 0..200 {
988            c.update(0.05);
989        }
990        // Settles with the target on the zone's edge, not the centre.
991        assert!(close(c.centre(), Vec2::new(5.0, 0.0), 1e-4));
992    }
993
994    #[test]
995    fn bounds_clamp_and_centre_on_small_bounds() {
996        // 200 x 100 px at 0.1 shows 20 x 10 units.
997        let mut c = Camera2d::new(Plane2d::Xy)
998            .with_viewport_size(Vec2::new(200.0, 100.0))
999            .with_units_per_pixel(0.1)
1000            .with_bounds(Rect2d::new(Vec2::ZERO, Vec2::new(100.0, 50.0)));
1001        c.set_centre(Vec2::new(-50.0, 70.0));
1002        assert!(close(c.centre(), Vec2::new(10.0, 45.0), 1e-5));
1003        let v = c.visible_rect();
1004        assert!(v.min.x >= -1e-5 && v.max.y <= 50.0 + 1e-5);
1005        c.pan(Vec2::new(-1.0e5, 0.0));
1006        assert!(close(c.centre(), Vec2::new(90.0, 45.0), 1e-4));
1007
1008        // Bounds narrower than the view along x only: centred on x, clamped on y.
1009        c.set_bounds(Some(Rect2d::new(Vec2::ZERO, Vec2::new(10.0, 50.0))));
1010        assert!(close(c.centre(), Vec2::new(5.0, 45.0), 1e-5));
1011
1012        // Smaller than the view on both axes: centred on them.
1013        c.set_bounds(Some(Rect2d::new(Vec2::ZERO, Vec2::new(10.0, 5.0))));
1014        assert!(close(c.centre(), Vec2::new(5.0, 2.5), 1e-5));
1015        c.zoom_at(Vec2::new(10.0, 10.0), 0.5);
1016        assert!(close(c.centre(), Vec2::new(5.0, 2.5), 1e-5));
1017    }
1018
1019    #[test]
1020    fn shake_decays_to_zero_and_leaves_the_centre() {
1021        let mut c = cam(Plane2d::Xz);
1022        let centre = c.centre();
1023        let rest = c.camera().target();
1024        c.shake(12.0, 0.5);
1025        assert!(c.shake_offset() != Vec2::ZERO);
1026        assert!(c.camera().target() != rest);
1027        let mut t = 0.0f32;
1028        let mut moved = false;
1029        while t < 0.6 {
1030            c.update(1.0 / 60.0);
1031            t += 1.0 / 60.0;
1032            let limit = if t < 0.5 {
1033                12.0 * (1.0 - t / 0.5).powi(2) + 1e-4
1034            } else {
1035                0.0
1036            };
1037            assert!(c.shake_offset().abs().max_element() <= limit);
1038            moved |= c.shake_offset() != Vec2::ZERO;
1039            assert_eq!(c.centre(), centre);
1040        }
1041        assert!(moved);
1042        assert_eq!(c.shake_offset(), Vec2::ZERO);
1043        assert_eq!(c.camera().target(), rest);
1044    }
1045
1046    #[test]
1047    fn pixel_snapping_lands_on_whole_device_pixels() {
1048        for (size, ppp) in [
1049            (Vec2::new(201.0, 101.0), 1.0),
1050            (Vec2::new(320.0, 180.0), 2.0),
1051        ] {
1052            for plane in PLANES {
1053                let mut c = Camera2d::new(plane)
1054                    .with_viewport_size(size)
1055                    .with_units_per_pixel(0.013)
1056                    .with_centre(Vec2::new(0.3337, -1.2345));
1057                c.pixels_per_point = ppp;
1058                let frac = |p: Vec2| (p - p.round()).abs().max_element();
1059                assert!(
1060                    frac(project(&c, Vec2::ZERO)) > 0.01,
1061                    "unsnapped is off-grid"
1062                );
1063                c.snap_to_pixels = true;
1064                let per_device = 0.013 / ppp;
1065                for k in [0.0, 3.0, -7.0] {
1066                    let p = project(&c, Vec2::splat(k * per_device));
1067                    assert!(frac(p) < 2e-3, "{plane:?} {size} {ppp}: {p}");
1068                }
1069            }
1070        }
1071    }
1072
1073    #[test]
1074    fn integer_zoom_snaps_to_a_whole_scale() {
1075        let mut c = cam(Plane2d::Xy);
1076        c.pixels_per_point = 2.0;
1077        // One texel is 1/16 unit; at 0.05 units per pixel that is 2.5 device px.
1078        let scale = c.snap_zoom_to_integer_scale(1.0 / 16.0);
1079        assert!(scale == 2 || scale == 3);
1080        let device_per_texel = (1.0 / 16.0) * 2.0 / c.units_per_pixel();
1081        assert!((device_per_texel - scale as f32).abs() < 1e-4);
1082        assert!(close(c.centre(), Vec2::new(3.0, -2.0), 1e-6));
1083    }
1084
1085    #[test]
1086    fn screen_and_world_round_trip() {
1087        for plane in PLANES {
1088            let c = cam(plane).with_rotation(-1.1);
1089            for p in [Vec2::ZERO, Vec2::new(12.5, -3.25), Vec2::new(-40.0, 17.0)] {
1090                assert!(close(c.screen_to_world(c.world_to_screen(p)), p, 1e-4));
1091            }
1092        }
1093    }
1094
1095    #[test]
1096    fn projection_extent_matches_the_visible_rect() {
1097        for plane in PLANES {
1098            let c = cam(plane);
1099            let camera = c.camera();
1100            assert!(camera.is_orthographic());
1101            let rect = c.visible_rect();
1102            assert!(close(rect.size(), Vec2::new(40.0, 30.0), 1e-4));
1103
1104            // Rays through the NDC corners cross the plane at the rect corners.
1105            let corner = |ndc: Vec2| {
1106                let (origin, dir) = camera.screen_ray(ndc);
1107                assert!((dir - plane.view_direction()).length() < 1e-5);
1108                plane.from_world(origin.as_dvec3())
1109            };
1110            assert!(
1111                close(corner(Vec2::new(-1.0, -1.0)), rect.min, 1e-3),
1112                "{plane:?}"
1113            );
1114            assert!(
1115                close(corner(Vec2::new(1.0, 1.0)), rect.max, 1e-3),
1116                "{plane:?}"
1117            );
1118
1119            // And the view-projection maps the rect corners to the NDC corners.
1120            let vp = camera.view_proj_matrix();
1121            let ndc = |p: Vec2| {
1122                let v = vp.project_point3(plane.to_world(p).as_vec3());
1123                assert!(v.z > 0.0 && v.z < 1.0);
1124                Vec2::new(v.x, v.y)
1125            };
1126            assert!(close(ndc(rect.min), Vec2::new(-1.0, -1.0), 1e-5));
1127            assert!(close(ndc(rect.max), Vec2::new(1.0, 1.0), 1e-5));
1128            // Screen up is plane +y on both planes.
1129            assert!((camera.up() - plane.y_axis()).length() < 1e-6);
1130            assert!((camera.right() - Vec3::X).length() < 1e-6);
1131        }
1132    }
1133
1134    #[test]
1135    fn controller_drags_to_pan_and_wheels_about_the_cursor() {
1136        let mut ctrl = Camera2dController::new();
1137        let mut c = Camera2d::new(Plane2d::Xy).with_units_per_pixel(0.1);
1138        let ctx = ViewportContext::new(InputOwnership::full_window(), [800.0, 600.0]);
1139
1140        ctrl.begin_frame(ctx);
1141        ctrl.push_event(ViewportEvent::PointerMoved {
1142            position: Vec2::new(100.0, 100.0),
1143        });
1144        ctrl.push_event(ViewportEvent::MouseButton {
1145            button: MouseButton::Left,
1146            state: ButtonState::Pressed,
1147        });
1148        ctrl.push_event(ViewportEvent::PointerMoved {
1149            position: Vec2::new(130.0, 80.0),
1150        });
1151        let frame = ctrl.apply_to_camera(&mut c, 0.0);
1152        assert_eq!(frame.navigation.orbit, Vec2::ZERO);
1153        assert_eq!(c.viewport_size(), Vec2::new(800.0, 600.0));
1154        assert!(close(c.centre(), Vec2::new(-3.0, -2.0), 1e-4));
1155
1156        ctrl.begin_frame(ctx);
1157        ctrl.push_event(ViewportEvent::MouseButton {
1158            button: MouseButton::Left,
1159            state: ButtonState::Released,
1160        });
1161        let under = c.screen_to_world(Vec2::new(130.0, 80.0));
1162        ctrl.push_event(ViewportEvent::Wheel {
1163            delta: Vec2::new(0.0, 3.0),
1164            units: ScrollUnits::Lines,
1165        });
1166        ctrl.apply_to_camera(&mut c, 0.0);
1167        assert!(c.units_per_pixel() < 0.1);
1168        assert!(close(
1169            c.screen_to_world(Vec2::new(130.0, 80.0)),
1170            under,
1171            1e-4
1172        ));
1173    }
1174
1175    /// Where a plane point lands through `camera`, in device pixels.
1176    fn project_camera(camera: &Camera, plane: Plane2d, world: Vec2, device: Vec2) -> Vec2 {
1177        let ndc = camera
1178            .view_proj_matrix()
1179            .project_point3(plane.to_world(world).as_vec3());
1180        Vec2::new(
1181            (ndc.x + 1.0) * 0.5 * device.x,
1182            (1.0 - ndc.y) * 0.5 * device.y,
1183        )
1184    }
1185
1186    #[test]
1187    fn apply_to_writes_the_view_into_a_host_camera() {
1188        for plane in PLANES {
1189            let c = cam(plane).with_rotation(0.3);
1190            let mut host = Camera::default();
1191            host.exposure.aperture = 2.8;
1192            c.apply_to(&mut host);
1193            let built = c.camera();
1194            assert_eq!(host.pose, built.pose);
1195            assert_eq!(host.projection, built.projection);
1196            assert_eq!(host.aspect, built.aspect);
1197            assert_eq!(host.focus_distance(), built.focus_distance());
1198            // The rest of the host's camera is its own.
1199            assert_eq!(host.exposure.aperture, 2.8);
1200        }
1201    }
1202
1203    #[test]
1204    fn a_camera_applied_shaken_blended_and_snapped_lands_on_a_device_pixel() {
1205        let size = Vec2::new(320.0, 180.0);
1206        for (plane, ppp) in [(Plane2d::Xy, 1.0), (Plane2d::Xz, 2.0)] {
1207            let mut c = Camera2d::new(plane)
1208                .with_viewport_size(size)
1209                .with_units_per_pixel(0.013)
1210                .with_centre(Vec2::new(0.3337, -1.2345));
1211            c.pixels_per_point = ppp;
1212            let mut host = Camera::default();
1213            c.apply_to(&mut host);
1214
1215            // The host shakes by a fraction of a pixel along the screen axes,
1216            // then blends toward another view of the same zoom.
1217            let shake = host.right().as_dvec3() * 0.0041 + host.up().as_dvec3() * -0.0077;
1218            host.pose.position += shake;
1219            let other = c.clone().with_centre(Vec2::new(2.71, 0.577)).camera();
1220            let mut blended = Camera::lerp(&host, &other, 0.37);
1221
1222            let device = size * ppp;
1223            let frac = |p: Vec2| (p - p.round()).abs().max_element();
1224            let origin = project_camera(&blended, plane, Vec2::ZERO, device);
1225            assert!(frac(origin) > 0.01, "the blend is off the grid");
1226
1227            snap_camera_to_pixels(&mut blended, size, ppp);
1228            let per_device = 0.013 / ppp;
1229            for k in [0.0, 5.0, -11.0] {
1230                let p = project_camera(&blended, plane, Vec2::splat(k * per_device), device);
1231                assert!(frac(p) < 2e-3, "{plane:?} {ppp}: {p}");
1232            }
1233        }
1234    }
1235
1236    #[test]
1237    fn snapping_the_written_camera_matches_snapping_it_afterwards() {
1238        for plane in PLANES {
1239            let mut c = cam(plane).with_rotation(0.7);
1240            c.pixels_per_point = 2.0;
1241            c.snap_to_pixels = true;
1242            let snapped = c.camera();
1243            c.snap_to_pixels = false;
1244            let mut after = c.camera();
1245            snap_camera_to_pixels(&mut after, c.viewport_size(), c.pixels_per_point);
1246            assert!((snapped.eye() - after.eye()).length() < 1e-9);
1247        }
1248    }
1249
1250    #[test]
1251    fn a_snapped_zoom_keeps_small_wheel_steps() {
1252        let mut c = cam(Plane2d::Xy);
1253        c.pixels_per_point = 2.0;
1254        c.snap_zoom_to_texel = Some(1.0 / 16.0);
1255        // 2.5 device pixels per texel draws at a whole scale.
1256        let drawn = c.drawn_units_per_pixel();
1257        let scale = (1.0 / 16.0) * 2.0 / drawn;
1258        assert!((scale - scale.round()).abs() < 1e-4);
1259        assert_eq!(c.units_per_pixel(), 0.05);
1260        let height = c.camera().view_height_at(1.0);
1261        assert!((height - 600.0 * drawn).abs() < 1e-3);
1262
1263        // Each small step moves the stored zoom; together they reach the
1264        // next drawn scale.
1265        let centre = c.viewport_size() * 0.5;
1266        let start = scale.round();
1267        let mut steps = 0;
1268        while ((1.0 / 16.0) * 2.0 / c.drawn_units_per_pixel()).round() == start {
1269            let before = c.units_per_pixel();
1270            c.zoom_at(centre, 1.02);
1271            assert!(c.units_per_pixel() < before);
1272            steps += 1;
1273            assert!(steps < 100, "the wheel never reached the next scale");
1274        }
1275        assert!(steps > 1);
1276    }
1277
1278    #[test]
1279    fn depth_range_sets_the_written_planes() {
1280        let mut c = cam(Plane2d::Xy);
1281        c.distance = 2000.0;
1282        let auto = c.camera().depth_range();
1283        assert_eq!(auto, (0.6, 6000.0));
1284        c.depth_range = Some([100.0, 7000.0]);
1285        let camera = c.camera();
1286        assert_eq!(camera.depth_range(), (100.0, 7000.0));
1287        // A layer 1500 behind the plane sits inside the depth range.
1288        let v = camera
1289            .view_proj_matrix()
1290            .project_point3(glam::Vec3::new(3.0, -2.0, -1500.0));
1291        assert!(v.z > 0.0 && v.z < 1.0, "{v}");
1292    }
1293
1294    #[test]
1295    fn the_control_adapter_drives_a_host_camera() {
1296        let mut control =
1297            Camera2dControl::new(Camera2d::new(Plane2d::Xy).with_units_per_pixel(0.1));
1298        CameraController::set_viewport(&mut control, [400.0, 300.0], 2.0);
1299        assert_eq!(control.camera.viewport_size(), Vec2::new(400.0, 300.0));
1300        assert_eq!(control.camera.pixels_per_point, 2.0);
1301
1302        let mut frame = ActionFrame::default();
1303        frame.navigation.pan = Vec2::new(10.0, 0.0);
1304        let mut host = Camera::default();
1305        CameraController::apply(&mut control, &mut host, &frame, 0.0);
1306        assert!(close(control.camera.centre(), Vec2::new(-1.0, 0.0), 1e-5));
1307        assert_eq!(host.pose, control.camera.camera().pose);
1308        assert!(control.as_any_mut().is_some());
1309    }
1310
1311    #[test]
1312    fn controller_ignores_a_drag_the_viewport_does_not_own() {
1313        let mut ctrl = Camera2dController::new();
1314        let mut c = Camera2d::new(Plane2d::Xy);
1315        let ctx = ViewportContext::new(InputOwnership::default(), [800.0, 600.0]);
1316        ctrl.begin_frame(ctx);
1317        ctrl.push_event(ViewportEvent::PointerMoved {
1318            position: Vec2::new(100.0, 100.0),
1319        });
1320        ctrl.push_event(ViewportEvent::MouseButton {
1321            button: MouseButton::Left,
1322            state: ButtonState::Pressed,
1323        });
1324        ctrl.push_event(ViewportEvent::PointerMoved {
1325            position: Vec2::new(160.0, 100.0),
1326        });
1327        ctrl.apply_to_camera(&mut c, 0.0);
1328        assert_eq!(c.centre(), Vec2::ZERO);
1329    }
1330}