viewport-lib-input 0.4.0

Input handling for viewport-lib: the event resolver, the camera controllers, and the optional winit/egui adapters. A replaceable layer on viewport-lib-types - resolve events into an ActionFrame, then apply it to a Camera however you like.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
//! A flat orthographic camera for 2D views, and the controller that drives it.
//!
//! [`Camera2d`] describes a view in 2D terms (a centre on a world plane, a zoom
//! as world units per pixel, a turn about the view axis) and writes the
//! orthographic [`Camera`](crate::Camera) the renderer draws with. It looks straight at its
//! plane and never orbits.
//!
//! [`Camera2dController`] applies drag-to-pan and zoom-about-the-cursor from an
//! [`ActionFrame`](crate::input::ActionFrame) to a `Camera2d`. Pair it with
//! [`BindingPreset::Planar`](crate::input::BindingPreset::Planar).
//! [`Camera2dControl`] wraps the two as a [`CameraController`], for a runner
//! that drives a `Camera` through that trait.
//!
//! [`snap_camera_to_pixels`] snaps any orthographic camera to whole device
//! pixels, for a host that moves the camera after `Camera2d` has written it.
//!
//! Screen positions are viewport-local logical pixels with the origin at the
//! top left and y down, the same space as
//! [`PointerFrame::cursor`](crate::input::PointerFrame::cursor). Plane
//! positions are `Vec2`s in world units along the plane's two axes; see
//! [`Plane2d`].
//!
//! The viewport size is the size the scene draws at. For a viewport presented
//! at a fixed reference size (`Presentation::Reference` on the renderer's
//! viewport frame) that is the reference size, with one pixel per point, and
//! screen positions are reference pixels: map the cursor with the renderer's
//! `window_to_reference` first.

use glam::{DMat3, DQuat, DVec3, Vec2, Vec3};
use viewport_lib_types::camera::{Pose, Projection};

use crate::CameraController;

use crate::Camera;
use crate::input::action_frame::ActionFrame;
use crate::input::context::ViewportContext;
use crate::input::event::ViewportEvent;
use crate::input::preset::planar_bindings;
use crate::input::viewport_binding::ViewportBinding;
use crate::input::viewport_input::ViewportInput;

/// The world plane a [`Camera2d`] looks at.
///
/// Both choices put plane x on world +X (screen right at rotation 0) and plane
/// y on the world axis that should read as up. They match
/// `viewport_lib::WorldPlane` (the plane of a world overlay layer) and the
/// tilemap's `TilemapPlane`, axis for axis, and convert to `WorldPlane` with
/// `From`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum Plane2d {
    /// The world XY plane seen from above, looking along -Z. Plane y is world
    /// +Y. The plane for a top-down view or a document.
    #[default]
    Xy,
    /// The world XZ plane seen from the front, looking along +Y. Plane y is
    /// world +Z, so up on screen is up in the Z-up world: the plane for a side
    /// view.
    Xz,
}

impl From<Plane2d> for viewport_lib_types::overlay::WorldPlane {
    fn from(plane: Plane2d) -> Self {
        match plane {
            Plane2d::Xy => Self::Xy,
            Plane2d::Xz => Self::Xz,
        }
    }
}

impl Plane2d {
    /// World direction of plane +x.
    pub fn x_axis(self) -> Vec3 {
        Vec3::X
    }

    /// World direction of plane +y.
    pub fn y_axis(self) -> Vec3 {
        match self {
            Plane2d::Xy => Vec3::Y,
            Plane2d::Xz => Vec3::Z,
        }
    }

    /// The direction the camera looks: into the plane.
    pub fn view_direction(self) -> Vec3 {
        match self {
            Plane2d::Xy => Vec3::NEG_Z,
            Plane2d::Xz => Vec3::Y,
        }
    }

    /// The world point at plane position `p`, on the plane through the origin.
    pub fn to_world(self, p: Vec2) -> DVec3 {
        (self.x_axis() * p.x + self.y_axis() * p.y).as_dvec3()
    }

    /// The plane position of a world point, dropping its depth along the view
    /// direction.
    pub fn from_world(self, p: DVec3) -> Vec2 {
        match self {
            Plane2d::Xy => Vec2::new(p.x as f32, p.y as f32),
            Plane2d::Xz => Vec2::new(p.x as f32, p.z as f32),
        }
    }
}

/// An axis-aligned rectangle, in plane units or in pixels depending on use.
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub struct Rect2d {
    /// The corner with the smaller coordinates.
    pub min: Vec2,
    /// The corner with the larger coordinates.
    pub max: Vec2,
}

impl Rect2d {
    /// The rectangle spanning two corners, in either order.
    pub fn new(a: Vec2, b: Vec2) -> Self {
        Self {
            min: a.min(b),
            max: a.max(b),
        }
    }

    /// The rectangle `size` across, centred on `centre`.
    pub fn from_centre_size(centre: Vec2, size: Vec2) -> Self {
        let half = size.abs() * 0.5;
        Self {
            min: centre - half,
            max: centre + half,
        }
    }

    /// The middle of the rectangle.
    pub fn centre(&self) -> Vec2 {
        (self.min + self.max) * 0.5
    }

    /// Width and height.
    pub fn size(&self) -> Vec2 {
        self.max - self.min
    }

    /// Whether `p` lies inside or on the edge.
    pub fn contains(&self, p: Vec2) -> bool {
        p.cmpge(self.min).all() && p.cmple(self.max).all()
    }
}

/// A decaying screen shake in progress.
#[derive(Clone, Copy, Debug, Default)]
struct Shake {
    amplitude: f32,
    duration: f32,
    elapsed: f32,
    /// The current offset in pixels, x right and y down.
    offset: Vec2,
}

impl Shake {
    fn remaining_amplitude(&self) -> f32 {
        if self.duration <= 0.0 || self.elapsed >= self.duration {
            0.0
        } else {
            let left = 1.0 - self.elapsed / self.duration;
            self.amplitude * left * left
        }
    }
}

/// A flat orthographic camera described in 2D terms.
///
/// The view is a `centre` on a [`Plane2d`], a zoom as `units_per_pixel` (world
/// units across one logical pixel), and a `rotation` about the view axis.
/// [`apply_to`](Self::apply_to) writes the orthographic pose and projection
/// into a [`Camera`] the host owns, and [`camera`](Self::camera) builds a new
/// one; give the renderer that each frame.
///
/// On top of the view sit a follow target with damping and a dead zone,
/// optional world bounds the visible area is kept inside, a decaying screen
/// shake, and pixel snapping for pixel art. [`update`](Self::update) advances
/// the follow and the shake once per frame.
///
/// The stored zoom is never snapped. With
/// [`snap_zoom_to_texel`](Self::snap_zoom_to_texel) set, the camera written
/// out uses the nearest zoom that shows a whole number of device pixels per
/// texel ([`drawn_units_per_pixel`](Self::drawn_units_per_pixel)), so small
/// wheel steps still add up to the next scale.
///
/// [`screen_to_world`](Self::screen_to_world),
/// [`world_to_screen`](Self::world_to_screen) and
/// [`visible_rect`](Self::visible_rect) describe the view at the drawn zoom,
/// without the shake offset or the position snapping that
/// [`apply_to`](Self::apply_to) adds.
#[derive(Clone, Debug)]
pub struct Camera2d {
    /// The plane the camera looks at.
    pub plane: Plane2d,
    /// How far the eye sits in front of the plane, in world units. Content
    /// between the eye and the far plane draws, so keep it larger than the
    /// highest layer above the plane. Defaults to `100.0`.
    pub distance: f32,
    /// Physical pixels per logical pixel, for pixel snapping and
    /// [`snap_zoom_to_integer_scale`](Self::snap_zoom_to_integer_scale).
    /// Defaults to `1.0`. Keep it at `1.0` for a viewport presented at a
    /// reference size, whose scene target has one pixel per point.
    pub pixels_per_point: f32,
    /// Round the written camera position so the plane origin lands on a whole
    /// device pixel, which keeps pixel art from shimmering as the camera moves.
    /// Off by default. A host that moves the camera after
    /// [`apply_to`](Self::apply_to) (a blend or its own shake) leaves this off
    /// and calls [`snap_camera_to_pixels`] last instead.
    pub snap_to_pixels: bool,
    /// World units per texel of the art, to keep the drawn zoom at a whole
    /// number of device pixels per texel: the written camera uses the nearest
    /// such zoom, at least one device pixel per texel, while
    /// [`units_per_pixel`](Self::units_per_pixel) keeps the unsnapped value.
    /// `None` (the default) draws at the stored zoom.
    pub snap_zoom_to_texel: Option<f32>,
    /// Near and far plane distances along the view direction, measured from
    /// the eye, for the written projection. `None` (the default) keeps the
    /// projection's automatic planes, which reach about `max(1000, 3 *
    /// distance)` from the eye. The far plane is never nearer than three
    /// times [`distance`](Self::distance), which keeps the plane itself in
    /// view.
    pub depth_range: Option<[f32; 2]>,
    /// The smallest units per pixel zooming reaches (the closest zoom).
    pub min_units_per_pixel: f32,
    /// The largest units per pixel zooming reaches (the furthest zoom).
    pub max_units_per_pixel: f32,
    /// How quickly the camera catches up with its follow target: the time in
    /// seconds for the distance left outside the dead zone to fall to about
    /// 37%. Zero or less snaps straight to it. Defaults to `0.25`.
    pub follow_time_constant: f32,
    /// The area around the screen centre the follow target can move in without
    /// the camera moving, in pixel offsets from the centre with x right and y
    /// down. Defaults to an empty rectangle at the centre, so the camera keeps
    /// the target centred.
    pub dead_zone: Rect2d,
    centre: Vec2,
    units_per_pixel: f32,
    rotation: f32,
    viewport_size: Vec2,
    bounds: Option<Rect2d>,
    follow_target: Option<Vec2>,
    shake: Shake,
    rng: u32,
}

impl Default for Camera2d {
    fn default() -> Self {
        Self::new(Plane2d::default())
    }
}

impl Camera2d {
    /// Default distance from the eye to the plane.
    pub const DEFAULT_DISTANCE: f32 = 100.0;
    /// Default zoom: 100 logical pixels per world unit.
    pub const DEFAULT_UNITS_PER_PIXEL: f32 = 0.01;
    /// Default follow time constant, in seconds.
    pub const DEFAULT_FOLLOW_TIME_CONSTANT: f32 = 0.25;

    /// A camera on `plane`, centred on the origin at the default zoom, for a
    /// 1 by 1 pixel viewport: call [`set_viewport_size`](Self::set_viewport_size)
    /// before producing a camera.
    pub fn new(plane: Plane2d) -> Self {
        Self {
            plane,
            distance: Self::DEFAULT_DISTANCE,
            pixels_per_point: 1.0,
            snap_to_pixels: false,
            snap_zoom_to_texel: None,
            depth_range: None,
            min_units_per_pixel: 1.0e-6,
            max_units_per_pixel: 1.0e6,
            follow_time_constant: Self::DEFAULT_FOLLOW_TIME_CONSTANT,
            dead_zone: Rect2d::default(),
            centre: Vec2::ZERO,
            units_per_pixel: Self::DEFAULT_UNITS_PER_PIXEL,
            rotation: 0.0,
            viewport_size: Vec2::ONE,
            bounds: None,
            follow_target: None,
            shake: Shake::default(),
            rng: 0x9E37_79B9,
        }
    }

    /// Builder: set the centre; see [`set_centre`](Self::set_centre).
    pub fn with_centre(mut self, centre: Vec2) -> Self {
        self.set_centre(centre);
        self
    }

    /// Builder: set the zoom; see [`set_units_per_pixel`](Self::set_units_per_pixel).
    pub fn with_units_per_pixel(mut self, units_per_pixel: f32) -> Self {
        self.set_units_per_pixel(units_per_pixel);
        self
    }

    /// Builder: set the viewport size in logical pixels.
    pub fn with_viewport_size(mut self, size: Vec2) -> Self {
        self.set_viewport_size(size);
        self
    }

    /// Builder: set the rotation; see [`set_rotation`](Self::set_rotation).
    pub fn with_rotation(mut self, rotation: f32) -> Self {
        self.set_rotation(rotation);
        self
    }

    /// Builder: keep the visible area inside `bounds`; see
    /// [`set_bounds`](Self::set_bounds).
    pub fn with_bounds(mut self, bounds: Rect2d) -> Self {
        self.set_bounds(Some(bounds));
        self
    }

    // -----------------------------------------------------------------------
    // View state
    // -----------------------------------------------------------------------

    /// The plane position at the middle of the screen.
    pub fn centre(&self) -> Vec2 {
        self.centre
    }

    /// Move the middle of the screen to `centre`, then apply the bounds.
    pub fn set_centre(&mut self, centre: Vec2) {
        self.centre = centre;
        self.clamp_to_bounds();
    }

    /// World units across one logical pixel. Smaller is closer. This is the
    /// stored zoom, never snapped; see
    /// [`drawn_units_per_pixel`](Self::drawn_units_per_pixel).
    pub fn units_per_pixel(&self) -> f32 {
        self.units_per_pixel
    }

    /// The zoom the written camera draws at: [`units_per_pixel`](Self::units_per_pixel),
    /// or with [`snap_zoom_to_texel`](Self::snap_zoom_to_texel) set the
    /// nearest zoom that shows a whole number of device pixels per texel.
    pub fn drawn_units_per_pixel(&self) -> f32 {
        match self.snap_zoom_to_texel {
            Some(units_per_texel) if units_per_texel > 0.0 => {
                integer_scale_zoom(units_per_texel, self.pixels_per_point, self.units_per_pixel).0
            }
            _ => self.units_per_pixel,
        }
    }

    /// Set the zoom about the screen centre, clamped to
    /// `[min_units_per_pixel, max_units_per_pixel]`, then apply the bounds.
    pub fn set_units_per_pixel(&mut self, units_per_pixel: f32) {
        self.units_per_pixel = self.clamp_zoom(units_per_pixel);
        self.clamp_to_bounds();
    }

    /// The turn of the view about the view axis, in radians. Positive turns
    /// the camera counter-clockwise on the plane, so the content appears to
    /// turn clockwise.
    pub fn rotation(&self) -> f32 {
        self.rotation
    }

    /// Set the turn about the view axis, then apply the bounds.
    pub fn set_rotation(&mut self, rotation: f32) {
        self.rotation = rotation;
        self.clamp_to_bounds();
    }

    /// The viewport size in logical pixels.
    pub fn viewport_size(&self) -> Vec2 {
        self.viewport_size
    }

    /// Set the viewport size in logical pixels, keeping the centre and zoom,
    /// then apply the bounds. Call it whenever the viewport resizes.
    ///
    /// This is the size the scene draws at, which sets the written camera's
    /// aspect and height: for a viewport presented at a reference size, pass
    /// the reference size (and keep [`pixels_per_point`](Self::pixels_per_point)
    /// at `1.0`), not the window's.
    pub fn set_viewport_size(&mut self, size: Vec2) {
        self.viewport_size = size.max(Vec2::ZERO);
        self.clamp_to_bounds();
    }

    /// The area the visible rectangle is kept inside, if any.
    pub fn bounds(&self) -> Option<Rect2d> {
        self.bounds
    }

    /// Keep the visible area inside `bounds` (in plane units), or remove the
    /// limit with `None`. Along an axis where the view is wider than the
    /// bounds, the view centres on them instead. The shake offset is not
    /// limited.
    pub fn set_bounds(&mut self, bounds: Option<Rect2d>) {
        self.bounds = bounds;
        self.clamp_to_bounds();
    }

    /// The screen's right and up directions on the plane.
    fn screen_axes(&self) -> (Vec2, Vec2) {
        let (s, c) = self.rotation.sin_cos();
        (Vec2::new(c, s), Vec2::new(-s, c))
    }

    /// A screen offset in pixels (x right, y down) as a plane vector.
    fn offset_to_plane(&self, offset: Vec2) -> Vec2 {
        let (right, up) = self.screen_axes();
        (right * offset.x - up * offset.y) * self.drawn_units_per_pixel()
    }

    /// A plane vector as a screen offset in pixels (x right, y down).
    fn plane_to_offset(&self, v: Vec2) -> Vec2 {
        let (right, up) = self.screen_axes();
        Vec2::new(v.dot(right), -v.dot(up)) / self.drawn_units_per_pixel()
    }

    /// The plane position under a screen position.
    pub fn screen_to_world(&self, screen: Vec2) -> Vec2 {
        self.centre + self.offset_to_plane(screen - self.viewport_size * 0.5)
    }

    /// The screen position of a plane position.
    pub fn world_to_screen(&self, world: Vec2) -> Vec2 {
        self.viewport_size * 0.5 + self.plane_to_offset(world - self.centre)
    }

    /// The plane area the viewport shows: exact at rotation 0, and the
    /// bounding rectangle of the turned view otherwise.
    pub fn visible_rect(&self) -> Rect2d {
        Rect2d {
            min: self.centre - self.visible_half_extent(),
            max: self.centre + self.visible_half_extent(),
        }
    }

    fn visible_half_extent(&self) -> Vec2 {
        let (right, up) = self.screen_axes();
        let half = self.viewport_size * 0.5 * self.drawn_units_per_pixel();
        right.abs() * half.x + up.abs() * half.y
    }

    fn clamp_zoom(&self, units_per_pixel: f32) -> f32 {
        let lo = self.min_units_per_pixel.max(f32::MIN_POSITIVE);
        let hi = self.max_units_per_pixel.max(lo);
        if units_per_pixel.is_finite() {
            units_per_pixel.clamp(lo, hi)
        } else {
            self.units_per_pixel
        }
    }

    fn clamp_to_bounds(&mut self) {
        let Some(bounds) = self.bounds else {
            return;
        };
        let half = self.visible_half_extent();
        let size = bounds.size();
        for axis in 0..2 {
            self.centre[axis] = if 2.0 * half[axis] >= size[axis] {
                bounds.centre()[axis]
            } else {
                self.centre[axis]
                    .clamp(bounds.min[axis] + half[axis], bounds.max[axis] - half[axis])
            };
        }
    }

    // -----------------------------------------------------------------------
    // Navigation
    // -----------------------------------------------------------------------

    /// Move the view as if the content were dragged by `delta_pixels` (x right,
    /// y down): the centre moves the other way by the delta times
    /// [`units_per_pixel`](Self::units_per_pixel).
    pub fn pan(&mut self, delta_pixels: Vec2) {
        if delta_pixels != Vec2::ZERO {
            self.centre -= self.offset_to_plane(delta_pixels);
            self.clamp_to_bounds();
        }
    }

    /// Zoom by `factor` about a screen position: above 1 zooms in, below 1
    /// zooms out, and the plane point under `cursor_pixels` stays under it
    /// (unless the zoom limits or the bounds move it). The factor applies to
    /// the stored zoom, so with [`snap_zoom_to_texel`](Self::snap_zoom_to_texel)
    /// set, small steps add up until the drawn scale changes.
    pub fn zoom_at(&mut self, cursor_pixels: Vec2, factor: f32) {
        if !(factor > 0.0) || factor == 1.0 {
            return;
        }
        let anchor = self.screen_to_world(cursor_pixels);
        self.units_per_pixel = self.clamp_zoom(self.units_per_pixel / factor);
        self.centre = anchor - self.offset_to_plane(cursor_pixels - self.viewport_size * 0.5);
        self.clamp_to_bounds();
    }

    /// Set the stored zoom so that one texel of art drawn at
    /// `units_per_texel` world units covers a whole number of device pixels,
    /// the nearest to the current zoom and at least one. Returns that number.
    /// The centre stays.
    ///
    /// This rewrites the zoom, so calling it every frame rounds small wheel
    /// steps back to the same scale. To keep every frame on a whole scale
    /// while zooming, set [`snap_zoom_to_texel`](Self::snap_zoom_to_texel)
    /// instead.
    pub fn snap_zoom_to_integer_scale(&mut self, units_per_texel: f32) -> u32 {
        let (units_per_pixel, scale) =
            integer_scale_zoom(units_per_texel, self.pixels_per_point, self.units_per_pixel);
        self.set_units_per_pixel(units_per_pixel);
        scale
    }

    // -----------------------------------------------------------------------
    // Follow and shake
    // -----------------------------------------------------------------------

    /// Follow `target`, a plane position. Call it each frame the target
    /// moves; [`update`](Self::update) moves the camera toward it once it
    /// leaves the [`dead_zone`](Self::dead_zone).
    pub fn follow(&mut self, target: Vec2) {
        self.follow_target = Some(target);
    }

    /// Stop following. The camera stays where it is.
    pub fn stop_following(&mut self) {
        self.follow_target = None;
    }

    /// The position being followed, if any.
    pub fn follow_target(&self) -> Option<Vec2> {
        self.follow_target
    }

    /// Start a shake: a random offset of up to `amplitude_pixels` that decays
    /// to nothing over `duration` seconds. It moves only the written camera,
    /// never the centre. A weaker shake does not cut short a stronger one
    /// still running.
    pub fn shake(&mut self, amplitude_pixels: f32, duration: f32) {
        if amplitude_pixels <= 0.0 || duration <= 0.0 {
            return;
        }
        if self.shake.remaining_amplitude() > amplitude_pixels {
            return;
        }
        self.shake = Shake {
            amplitude: amplitude_pixels,
            duration,
            elapsed: 0.0,
            offset: Vec2::ZERO,
        };
        self.shake.offset = self.random_offset() * amplitude_pixels;
    }

    /// The current shake offset in pixels, x right and y down.
    pub fn shake_offset(&self) -> Vec2 {
        self.shake.offset
    }

    /// Advance the follow and the shake by `dt` seconds.
    pub fn update(&mut self, dt: f32) {
        let dt = dt.max(0.0);
        if let Some(target) = self.follow_target {
            let offset = self.plane_to_offset(target - self.centre);
            let zone = Rect2d::new(self.dead_zone.min, self.dead_zone.max);
            let excess = offset - offset.clamp(zone.min, zone.max);
            if excess != Vec2::ZERO {
                let k = if self.follow_time_constant > 0.0 {
                    1.0 - (-dt / self.follow_time_constant).exp()
                } else {
                    1.0
                };
                self.centre += self.offset_to_plane(excess) * k;
                self.clamp_to_bounds();
            }
        }
        if self.shake.duration > 0.0 {
            self.shake.elapsed += dt;
            let amplitude = self.shake.remaining_amplitude();
            if amplitude > 0.0 {
                self.shake.offset = self.random_offset() * amplitude;
            } else {
                self.shake = Shake::default();
            }
        }
    }

    /// A point in the unit square about the origin, from a small xorshift
    /// generator so a shake is the same on every run.
    fn random_offset(&mut self) -> Vec2 {
        let mut next = || {
            let mut x = self.rng;
            x ^= x << 13;
            x ^= x >> 17;
            x ^= x << 5;
            self.rng = x;
            (x >> 8) as f32 / (1u32 << 24) as f32 * 2.0 - 1.0
        };
        Vec2::new(next(), next())
    }

    // -----------------------------------------------------------------------
    // The produced camera
    // -----------------------------------------------------------------------

    /// Write this view into `camera`: an orthographic projection as tall as
    /// the viewport height times [`drawn_units_per_pixel`](Self::drawn_units_per_pixel),
    /// with [`depth_range`](Self::depth_range) as its planes when set, and a
    /// pose looking along the plane's view direction from
    /// [`distance`](Self::distance) in front of it, moved by the shake offset
    /// and, with [`snap_to_pixels`](Self::snap_to_pixels), snapped to whole
    /// device pixels. The aspect comes from the viewport size and the focus
    /// distance is set to `distance`; the exposure is otherwise left alone.
    ///
    /// The viewport size is the size the scene draws at: the reference size
    /// for a viewport presented at one (see
    /// [`set_viewport_size`](Self::set_viewport_size)).
    ///
    /// The camera is the host's to change afterwards: blend it, shake it,
    /// then call [`snap_camera_to_pixels`] last if it should stay on the
    /// pixel grid.
    pub fn apply_to(&self, camera: &mut Camera) {
        let (right, up) = self.screen_axes();
        let centre = self.centre + self.offset_to_plane(self.shake.offset);

        let plane = self.plane;
        let world_right = plane.x_axis() * right.x + plane.y_axis() * right.y;
        let world_up = plane.x_axis() * up.x + plane.y_axis() * up.y;
        let back = -plane.view_direction();
        let basis = DMat3::from_cols(world_right.as_dvec3(), world_up.as_dvec3(), back.as_dvec3());
        let orientation = DQuat::from_mat3(&basis).normalize();
        let distance = self.distance.max(1e-3);
        let eye = plane.to_world(centre) + back.as_dvec3() * f64::from(distance);

        let height = self.viewport_size.y * self.drawn_units_per_pixel();
        let (near, far) = match self.depth_range {
            Some([near, far]) => (Some(near), Some(far)),
            None => (None, None),
        };
        camera.set_pose(Pose::new(eye, orientation));
        camera.projection = Projection::Orthographic { height, near, far };
        camera.set_aspect_ratio(self.viewport_size.x, self.viewport_size.y);
        camera.set_focus_distance(distance);
        if self.snap_to_pixels {
            snap_camera_to_pixels(camera, self.viewport_size, self.pixels_per_point);
        }
    }

    /// A new camera with this view written into it; see
    /// [`apply_to`](Self::apply_to).
    pub fn camera(&self) -> Camera {
        let mut camera = Camera::new(Pose::IDENTITY);
        self.apply_to(&mut camera);
        camera
    }
}

/// The zoom nearest `units_per_pixel` at which one texel of `units_per_texel`
/// world units covers a whole number of device pixels (at least one), and that
/// number.
fn integer_scale_zoom(
    units_per_texel: f32,
    pixels_per_point: f32,
    units_per_pixel: f32,
) -> (f32, u32) {
    let ppp = pixels_per_point.max(1e-3);
    let device_per_texel = units_per_texel * ppp / units_per_pixel;
    let scale = device_per_texel.round().max(1.0);
    (units_per_texel * ppp / scale, scale as u32)
}

/// Move an orthographic camera across its view so the world origin lands on a
/// whole device pixel, which keeps pixel art from shimmering as the camera
/// moves. The camera's own right and up axes set the pixel grid, so it works
/// at any turn about the view axis; the depth along the view is untouched.
///
/// `viewport_size` (in logical pixels) and `pixels_per_point` describe the
/// target the scene draws into: for a viewport presented at a reference size,
/// pass the reference size and `1.0`. Call it last, after any blend or shake
/// the host applies. A perspective or matrix projection is left alone.
pub fn snap_camera_to_pixels(camera: &mut Camera, viewport_size: Vec2, pixels_per_point: f32) {
    let Projection::Orthographic { height, .. } = camera.projection else {
        return;
    };
    let ppp = pixels_per_point.max(1e-3);
    let device = viewport_size.as_dvec2() * f64::from(ppp);
    if !(height > 0.0) || !(device.y > 0.0) {
        return;
    }
    let per_device = f64::from(height) / device.y;
    let right = camera.pose.orientation * DVec3::X;
    let up = camera.pose.orientation * DVec3::Y;
    let eye = camera.pose.position;
    // The origin lands on a whole device pixel when the left and top edges
    // sit a whole number of device pixels from it.
    let r = eye.dot(right) / per_device;
    let u = eye.dot(up) / per_device;
    let snapped_r = (r - device.x * 0.5).round() + device.x * 0.5;
    let snapped_u = (u + device.y * 0.5).round() - device.y * 0.5;
    camera.pose.position =
        eye + right * ((snapped_r - r) * per_device) + up * ((snapped_u - u) * per_device);
}

/// A [`Camera2d`] and a [`Camera2dController`] as one [`CameraController`]:
/// each frame it applies pan and zoom from the resolved input, advances the
/// follow and the shake, and writes the view into the camera with
/// [`Camera2d::apply_to`].
///
/// Hand it to a runner that drives a camera through [`CameraController`]
/// (`ViewportApp`'s `CameraControl::Controller`), and reach the 2D camera
/// through [`camera`](Self::camera) to follow, shake or set bounds. The runner
/// passes the size the scene draws at through
/// [`CameraController::set_viewport`] before each apply.
pub struct Camera2dControl {
    /// The 2D view.
    pub camera: Camera2d,
    /// The pan and zoom policy, with no resolver of its own.
    pub controller: Camera2dController,
}

impl Camera2dControl {
    /// Drive `camera` with a stateless [`Camera2dController`].
    pub fn new(camera: Camera2d) -> Self {
        Self {
            camera,
            controller: Camera2dController::new_stateless(),
        }
    }
}

impl CameraController for Camera2dControl {
    fn apply(&mut self, camera: &mut Camera, frame: &ActionFrame, dt: f32) {
        self.controller.apply(&mut self.camera, frame, dt);
        self.camera.apply_to(camera);
    }

    fn set_viewport(&mut self, viewport_size: [f32; 2], pixels_per_point: f32) {
        let size = Vec2::from(viewport_size);
        if size != self.camera.viewport_size() {
            self.camera.set_viewport_size(size);
        }
        self.camera.pixels_per_point = pixels_per_point;
    }

    fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
        Some(self)
    }
}

/// Drag-to-pan and zoom-about-the-cursor for a [`Camera2d`].
///
/// Two ways to drive it, as with the other controllers:
///
/// - The host owns a [`ViewportInput`] (or a `ViewportInstance`) with
///   [`planar_bindings`] and hands each resolved frame to
///   [`apply`](Self::apply). Create the controller with
///   [`new_stateless`](Self::new_stateless).
/// - The controller owns the resolver: create it with [`new`](Self::new), call
///   [`begin_frame`](Self::begin_frame) with the frame's
///   [`ViewportContext`], push every translated event with
///   [`push_event`](Self::push_event), and call
///   [`apply_to_camera`](Self::apply_to_camera) once per frame. Events are
///   routed by the context's input ownership, so a drag that starts over the
///   application's UI does not pan.
///
/// ```text
/// controller.begin_frame(ViewportContext::new(ownership, viewport_size));
/// for event in events { controller.push_event(event); }
/// controller.apply_to_camera(&mut camera2d, dt);
/// frame_camera = camera2d.camera();
/// ```
///
/// Both paths also advance the camera's follow and shake, so do not call
/// [`Camera2d::update`] as well.
pub struct Camera2dController {
    input: ViewportInput,
    /// Multiplier on pan deltas. Defaults to `1.0`, which keeps the content
    /// under the pointer while dragging.
    pub pan_sensitivity: f32,
    /// Zoom per pixel of wheel or pinch input: each frame zooms by
    /// `exp(zoom * zoom_sensitivity)`. Defaults to
    /// [`DEFAULT_ZOOM_SENSITIVITY`](Self::DEFAULT_ZOOM_SENSITIVITY).
    pub zoom_sensitivity: f32,
    viewport_size: Vec2,
}

impl Default for Camera2dController {
    fn default() -> Self {
        Self::new()
    }
}

impl Camera2dController {
    /// Default zoom sensitivity: a wheel notch zooms by about 6%.
    pub const DEFAULT_ZOOM_SENSITIVITY: f32 = 0.002;

    /// A controller with its own resolver holding [`planar_bindings`].
    pub fn new() -> Self {
        Self::from_bindings(planar_bindings())
    }

    /// A controller with its own resolver holding `bindings`.
    pub fn from_bindings(bindings: Vec<ViewportBinding>) -> Self {
        Self {
            input: ViewportInput::new(bindings),
            pan_sensitivity: 1.0,
            zoom_sensitivity: Self::DEFAULT_ZOOM_SENSITIVITY,
            viewport_size: Vec2::ZERO,
        }
    }

    /// A controller with no bindings, for a host that resolves its own frames
    /// and calls [`apply`](Self::apply).
    pub fn new_stateless() -> Self {
        Self::from_bindings(Vec::new())
    }

    /// The controller's own resolver, for touch settings or cancelling a
    /// gesture.
    pub fn input_mut(&mut self) -> &mut ViewportInput {
        &mut self.input
    }

    /// Begin a frame: clear the per-frame input and record the context (input
    /// ownership and viewport size). Call it before pushing the frame's events.
    pub fn begin_frame(&mut self, ctx: ViewportContext) {
        self.viewport_size = Vec2::from(ctx.viewport_size);
        self.input.begin_frame(ctx);
    }

    /// [`begin_frame`](Self::begin_frame) with the host's clock, which double
    /// tap and long press need.
    pub fn begin_frame_at(&mut self, ctx: ViewportContext, time_seconds: f32) {
        self.viewport_size = Vec2::from(ctx.viewport_size);
        self.input.begin_frame_at(ctx, time_seconds);
    }

    /// Push one translated event. Routing follows the ownership given to the
    /// last [`begin_frame`](Self::begin_frame).
    pub fn push_event(&mut self, event: ViewportEvent) {
        self.input.push_event(event);
    }

    /// Resolve the events pushed this frame without moving any camera.
    pub fn resolve(&self) -> ActionFrame {
        self.input.resolve()
    }

    /// Resolve this frame's events, set the camera's viewport size from the
    /// last [`begin_frame`](Self::begin_frame), apply the input and advance
    /// follow and shake by `dt`. Returns the resolved frame.
    pub fn apply_to_camera(&mut self, camera: &mut Camera2d, dt: f32) -> ActionFrame {
        let frame = self.input.resolve();
        if self.viewport_size != Vec2::ZERO && self.viewport_size != camera.viewport_size() {
            camera.set_viewport_size(self.viewport_size);
        }
        self.apply(camera, &frame, dt);
        frame
    }

    /// Apply a resolved frame: pan by `navigation.pan`, zoom by
    /// `navigation.zoom` about the cursor (the touch point during a pinch, the
    /// screen centre with neither), then advance follow and shake by `dt`.
    /// Orbit and twist are ignored. The camera's viewport size must already
    /// be current.
    pub fn apply(&mut self, camera: &mut Camera2d, frame: &ActionFrame, dt: f32) {
        let nav = &frame.navigation;
        if nav.pan != Vec2::ZERO {
            camera.pan(nav.pan * self.pan_sensitivity);
        }
        if nav.zoom != 0.0 {
            let pointer = &frame.pointer;
            let anchor = if pointer.contacts >= 2 {
                pointer.touch_position.or(pointer.cursor)
            } else {
                pointer.cursor
            }
            .unwrap_or(camera.viewport_size() * 0.5);
            camera.zoom_at(anchor, (nav.zoom * self.zoom_sensitivity).exp());
        }
        camera.update(dt);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::input::binding::MouseButton;
    use crate::input::context::InputOwnership;
    use crate::input::event::{ButtonState, ScrollUnits};

    const PLANES: [Plane2d; 2] = [Plane2d::Xy, Plane2d::Xz];

    fn close(a: Vec2, b: Vec2, eps: f32) -> bool {
        (a - b).abs().max_element() <= eps
    }

    fn cam(plane: Plane2d) -> Camera2d {
        Camera2d::new(plane)
            .with_viewport_size(Vec2::new(800.0, 600.0))
            .with_units_per_pixel(0.05)
            .with_centre(Vec2::new(3.0, -2.0))
    }

    /// Where a plane point lands on screen through the produced camera, in
    /// device pixels.
    fn project(c: &Camera2d, world: Vec2) -> Vec2 {
        let camera = c.camera();
        let ndc = camera
            .view_proj_matrix()
            .project_point3(c.plane.to_world(world).as_vec3());
        let device = c.viewport_size() * c.pixels_per_point;
        Vec2::new(
            (ndc.x + 1.0) * 0.5 * device.x,
            (1.0 - ndc.y) * 0.5 * device.y,
        )
    }

    #[test]
    fn zoom_at_cursor_keeps_the_point_under_it() {
        for plane in PLANES {
            for rotation in [0.0, 0.4] {
                let mut c = cam(plane).with_rotation(rotation);
                let cursor = Vec2::new(620.0, 140.0);
                let before = c.screen_to_world(cursor);
                c.zoom_at(cursor, 1.7);
                assert!((c.units_per_pixel() - 0.05 / 1.7).abs() < 1e-7);
                assert!(close(c.screen_to_world(cursor), before, 1e-4));
                assert!(close(project(&c, before), cursor, 0.05), "{plane:?}");
                c.zoom_at(cursor, 0.3);
                assert!(close(c.screen_to_world(cursor), before, 1e-4));
            }
        }
    }

    #[test]
    fn pan_moves_by_pixels_times_units_per_pixel() {
        let mut c = cam(Plane2d::Xy);
        let p = Vec2::new(1.0, 1.5);
        let on_screen = c.world_to_screen(p);
        c.pan(Vec2::new(10.0, -4.0));
        // Dragging right moves the centre left; dragging up (y down) moves it down.
        assert!(close(c.centre(), Vec2::new(3.0 - 0.5, -2.0 - 0.2), 1e-5));
        assert!(close(
            c.world_to_screen(p),
            on_screen + Vec2::new(10.0, -4.0),
            1e-3
        ));
        // Turned a quarter, the same drag moves along the turned axes.
        let mut r = cam(Plane2d::Xz).with_rotation(std::f32::consts::FRAC_PI_2);
        r.pan(Vec2::new(10.0, 0.0));
        assert!(close(r.centre(), Vec2::new(3.0, -2.0 - 0.5), 1e-5));
    }

    #[test]
    fn follow_waits_for_the_dead_zone_then_converges() {
        let mut c = Camera2d::new(Plane2d::Xy)
            .with_viewport_size(Vec2::new(400.0, 300.0))
            .with_units_per_pixel(0.1);
        c.dead_zone = Rect2d::from_centre_size(Vec2::ZERO, Vec2::new(100.0, 100.0));
        c.follow_time_constant = 0.5;

        // 30 px right and 40 px up: inside the 50 px half-size.
        c.follow(Vec2::new(3.0, 4.0));
        for _ in 0..30 {
            c.update(1.0 / 60.0);
        }
        assert_eq!(c.centre(), Vec2::ZERO);

        // 100 px right: 50 px (5 units) outside the zone.
        c.follow(Vec2::new(10.0, 0.0));
        for _ in 0..10 {
            c.update(0.05);
        }
        let left = 10.0 - 5.0 - c.centre().x;
        let expected = 5.0 * (-1.0f32).exp();
        assert!((left - expected).abs() < 1e-4, "{left} vs {expected}");
        assert_eq!(c.centre().y, 0.0);

        for _ in 0..200 {
            c.update(0.05);
        }
        // Settles with the target on the zone's edge, not the centre.
        assert!(close(c.centre(), Vec2::new(5.0, 0.0), 1e-4));
    }

    #[test]
    fn bounds_clamp_and_centre_on_small_bounds() {
        // 200 x 100 px at 0.1 shows 20 x 10 units.
        let mut c = Camera2d::new(Plane2d::Xy)
            .with_viewport_size(Vec2::new(200.0, 100.0))
            .with_units_per_pixel(0.1)
            .with_bounds(Rect2d::new(Vec2::ZERO, Vec2::new(100.0, 50.0)));
        c.set_centre(Vec2::new(-50.0, 70.0));
        assert!(close(c.centre(), Vec2::new(10.0, 45.0), 1e-5));
        let v = c.visible_rect();
        assert!(v.min.x >= -1e-5 && v.max.y <= 50.0 + 1e-5);
        c.pan(Vec2::new(-1.0e5, 0.0));
        assert!(close(c.centre(), Vec2::new(90.0, 45.0), 1e-4));

        // Bounds narrower than the view along x only: centred on x, clamped on y.
        c.set_bounds(Some(Rect2d::new(Vec2::ZERO, Vec2::new(10.0, 50.0))));
        assert!(close(c.centre(), Vec2::new(5.0, 45.0), 1e-5));

        // Smaller than the view on both axes: centred on them.
        c.set_bounds(Some(Rect2d::new(Vec2::ZERO, Vec2::new(10.0, 5.0))));
        assert!(close(c.centre(), Vec2::new(5.0, 2.5), 1e-5));
        c.zoom_at(Vec2::new(10.0, 10.0), 0.5);
        assert!(close(c.centre(), Vec2::new(5.0, 2.5), 1e-5));
    }

    #[test]
    fn shake_decays_to_zero_and_leaves_the_centre() {
        let mut c = cam(Plane2d::Xz);
        let centre = c.centre();
        let rest = c.camera().target();
        c.shake(12.0, 0.5);
        assert!(c.shake_offset() != Vec2::ZERO);
        assert!(c.camera().target() != rest);
        let mut t = 0.0f32;
        let mut moved = false;
        while t < 0.6 {
            c.update(1.0 / 60.0);
            t += 1.0 / 60.0;
            let limit = if t < 0.5 {
                12.0 * (1.0 - t / 0.5).powi(2) + 1e-4
            } else {
                0.0
            };
            assert!(c.shake_offset().abs().max_element() <= limit);
            moved |= c.shake_offset() != Vec2::ZERO;
            assert_eq!(c.centre(), centre);
        }
        assert!(moved);
        assert_eq!(c.shake_offset(), Vec2::ZERO);
        assert_eq!(c.camera().target(), rest);
    }

    #[test]
    fn pixel_snapping_lands_on_whole_device_pixels() {
        for (size, ppp) in [
            (Vec2::new(201.0, 101.0), 1.0),
            (Vec2::new(320.0, 180.0), 2.0),
        ] {
            for plane in PLANES {
                let mut c = Camera2d::new(plane)
                    .with_viewport_size(size)
                    .with_units_per_pixel(0.013)
                    .with_centre(Vec2::new(0.3337, -1.2345));
                c.pixels_per_point = ppp;
                let frac = |p: Vec2| (p - p.round()).abs().max_element();
                assert!(
                    frac(project(&c, Vec2::ZERO)) > 0.01,
                    "unsnapped is off-grid"
                );
                c.snap_to_pixels = true;
                let per_device = 0.013 / ppp;
                for k in [0.0, 3.0, -7.0] {
                    let p = project(&c, Vec2::splat(k * per_device));
                    assert!(frac(p) < 2e-3, "{plane:?} {size} {ppp}: {p}");
                }
            }
        }
    }

    #[test]
    fn integer_zoom_snaps_to_a_whole_scale() {
        let mut c = cam(Plane2d::Xy);
        c.pixels_per_point = 2.0;
        // One texel is 1/16 unit; at 0.05 units per pixel that is 2.5 device px.
        let scale = c.snap_zoom_to_integer_scale(1.0 / 16.0);
        assert!(scale == 2 || scale == 3);
        let device_per_texel = (1.0 / 16.0) * 2.0 / c.units_per_pixel();
        assert!((device_per_texel - scale as f32).abs() < 1e-4);
        assert!(close(c.centre(), Vec2::new(3.0, -2.0), 1e-6));
    }

    #[test]
    fn screen_and_world_round_trip() {
        for plane in PLANES {
            let c = cam(plane).with_rotation(-1.1);
            for p in [Vec2::ZERO, Vec2::new(12.5, -3.25), Vec2::new(-40.0, 17.0)] {
                assert!(close(c.screen_to_world(c.world_to_screen(p)), p, 1e-4));
            }
        }
    }

    #[test]
    fn projection_extent_matches_the_visible_rect() {
        for plane in PLANES {
            let c = cam(plane);
            let camera = c.camera();
            assert!(camera.is_orthographic());
            let rect = c.visible_rect();
            assert!(close(rect.size(), Vec2::new(40.0, 30.0), 1e-4));

            // Rays through the NDC corners cross the plane at the rect corners.
            let corner = |ndc: Vec2| {
                let (origin, dir) = camera.screen_ray(ndc);
                assert!((dir - plane.view_direction()).length() < 1e-5);
                plane.from_world(origin.as_dvec3())
            };
            assert!(
                close(corner(Vec2::new(-1.0, -1.0)), rect.min, 1e-3),
                "{plane:?}"
            );
            assert!(
                close(corner(Vec2::new(1.0, 1.0)), rect.max, 1e-3),
                "{plane:?}"
            );

            // And the view-projection maps the rect corners to the NDC corners.
            let vp = camera.view_proj_matrix();
            let ndc = |p: Vec2| {
                let v = vp.project_point3(plane.to_world(p).as_vec3());
                assert!(v.z > 0.0 && v.z < 1.0);
                Vec2::new(v.x, v.y)
            };
            assert!(close(ndc(rect.min), Vec2::new(-1.0, -1.0), 1e-5));
            assert!(close(ndc(rect.max), Vec2::new(1.0, 1.0), 1e-5));
            // Screen up is plane +y on both planes.
            assert!((camera.up() - plane.y_axis()).length() < 1e-6);
            assert!((camera.right() - Vec3::X).length() < 1e-6);
        }
    }

    #[test]
    fn controller_drags_to_pan_and_wheels_about_the_cursor() {
        let mut ctrl = Camera2dController::new();
        let mut c = Camera2d::new(Plane2d::Xy).with_units_per_pixel(0.1);
        let ctx = ViewportContext::new(InputOwnership::full_window(), [800.0, 600.0]);

        ctrl.begin_frame(ctx);
        ctrl.push_event(ViewportEvent::PointerMoved {
            position: Vec2::new(100.0, 100.0),
        });
        ctrl.push_event(ViewportEvent::MouseButton {
            button: MouseButton::Left,
            state: ButtonState::Pressed,
        });
        ctrl.push_event(ViewportEvent::PointerMoved {
            position: Vec2::new(130.0, 80.0),
        });
        let frame = ctrl.apply_to_camera(&mut c, 0.0);
        assert_eq!(frame.navigation.orbit, Vec2::ZERO);
        assert_eq!(c.viewport_size(), Vec2::new(800.0, 600.0));
        assert!(close(c.centre(), Vec2::new(-3.0, -2.0), 1e-4));

        ctrl.begin_frame(ctx);
        ctrl.push_event(ViewportEvent::MouseButton {
            button: MouseButton::Left,
            state: ButtonState::Released,
        });
        let under = c.screen_to_world(Vec2::new(130.0, 80.0));
        ctrl.push_event(ViewportEvent::Wheel {
            delta: Vec2::new(0.0, 3.0),
            units: ScrollUnits::Lines,
        });
        ctrl.apply_to_camera(&mut c, 0.0);
        assert!(c.units_per_pixel() < 0.1);
        assert!(close(
            c.screen_to_world(Vec2::new(130.0, 80.0)),
            under,
            1e-4
        ));
    }

    /// Where a plane point lands through `camera`, in device pixels.
    fn project_camera(camera: &Camera, plane: Plane2d, world: Vec2, device: Vec2) -> Vec2 {
        let ndc = camera
            .view_proj_matrix()
            .project_point3(plane.to_world(world).as_vec3());
        Vec2::new(
            (ndc.x + 1.0) * 0.5 * device.x,
            (1.0 - ndc.y) * 0.5 * device.y,
        )
    }

    #[test]
    fn apply_to_writes_the_view_into_a_host_camera() {
        for plane in PLANES {
            let c = cam(plane).with_rotation(0.3);
            let mut host = Camera::default();
            host.exposure.aperture = 2.8;
            c.apply_to(&mut host);
            let built = c.camera();
            assert_eq!(host.pose, built.pose);
            assert_eq!(host.projection, built.projection);
            assert_eq!(host.aspect, built.aspect);
            assert_eq!(host.focus_distance(), built.focus_distance());
            // The rest of the host's camera is its own.
            assert_eq!(host.exposure.aperture, 2.8);
        }
    }

    #[test]
    fn a_camera_applied_shaken_blended_and_snapped_lands_on_a_device_pixel() {
        let size = Vec2::new(320.0, 180.0);
        for (plane, ppp) in [(Plane2d::Xy, 1.0), (Plane2d::Xz, 2.0)] {
            let mut c = Camera2d::new(plane)
                .with_viewport_size(size)
                .with_units_per_pixel(0.013)
                .with_centre(Vec2::new(0.3337, -1.2345));
            c.pixels_per_point = ppp;
            let mut host = Camera::default();
            c.apply_to(&mut host);

            // The host shakes by a fraction of a pixel along the screen axes,
            // then blends toward another view of the same zoom.
            let shake = host.right().as_dvec3() * 0.0041 + host.up().as_dvec3() * -0.0077;
            host.pose.position += shake;
            let other = c.clone().with_centre(Vec2::new(2.71, 0.577)).camera();
            let mut blended = Camera::lerp(&host, &other, 0.37);

            let device = size * ppp;
            let frac = |p: Vec2| (p - p.round()).abs().max_element();
            let origin = project_camera(&blended, plane, Vec2::ZERO, device);
            assert!(frac(origin) > 0.01, "the blend is off the grid");

            snap_camera_to_pixels(&mut blended, size, ppp);
            let per_device = 0.013 / ppp;
            for k in [0.0, 5.0, -11.0] {
                let p = project_camera(&blended, plane, Vec2::splat(k * per_device), device);
                assert!(frac(p) < 2e-3, "{plane:?} {ppp}: {p}");
            }
        }
    }

    #[test]
    fn snapping_the_written_camera_matches_snapping_it_afterwards() {
        for plane in PLANES {
            let mut c = cam(plane).with_rotation(0.7);
            c.pixels_per_point = 2.0;
            c.snap_to_pixels = true;
            let snapped = c.camera();
            c.snap_to_pixels = false;
            let mut after = c.camera();
            snap_camera_to_pixels(&mut after, c.viewport_size(), c.pixels_per_point);
            assert!((snapped.eye() - after.eye()).length() < 1e-9);
        }
    }

    #[test]
    fn a_snapped_zoom_keeps_small_wheel_steps() {
        let mut c = cam(Plane2d::Xy);
        c.pixels_per_point = 2.0;
        c.snap_zoom_to_texel = Some(1.0 / 16.0);
        // 2.5 device pixels per texel draws at a whole scale.
        let drawn = c.drawn_units_per_pixel();
        let scale = (1.0 / 16.0) * 2.0 / drawn;
        assert!((scale - scale.round()).abs() < 1e-4);
        assert_eq!(c.units_per_pixel(), 0.05);
        let height = c.camera().view_height_at(1.0);
        assert!((height - 600.0 * drawn).abs() < 1e-3);

        // Each small step moves the stored zoom; together they reach the
        // next drawn scale.
        let centre = c.viewport_size() * 0.5;
        let start = scale.round();
        let mut steps = 0;
        while ((1.0 / 16.0) * 2.0 / c.drawn_units_per_pixel()).round() == start {
            let before = c.units_per_pixel();
            c.zoom_at(centre, 1.02);
            assert!(c.units_per_pixel() < before);
            steps += 1;
            assert!(steps < 100, "the wheel never reached the next scale");
        }
        assert!(steps > 1);
    }

    #[test]
    fn depth_range_sets_the_written_planes() {
        let mut c = cam(Plane2d::Xy);
        c.distance = 2000.0;
        let auto = c.camera().depth_range();
        assert_eq!(auto, (0.6, 6000.0));
        c.depth_range = Some([100.0, 7000.0]);
        let camera = c.camera();
        assert_eq!(camera.depth_range(), (100.0, 7000.0));
        // A layer 1500 behind the plane sits inside the depth range.
        let v = camera
            .view_proj_matrix()
            .project_point3(glam::Vec3::new(3.0, -2.0, -1500.0));
        assert!(v.z > 0.0 && v.z < 1.0, "{v}");
    }

    #[test]
    fn the_control_adapter_drives_a_host_camera() {
        let mut control =
            Camera2dControl::new(Camera2d::new(Plane2d::Xy).with_units_per_pixel(0.1));
        CameraController::set_viewport(&mut control, [400.0, 300.0], 2.0);
        assert_eq!(control.camera.viewport_size(), Vec2::new(400.0, 300.0));
        assert_eq!(control.camera.pixels_per_point, 2.0);

        let mut frame = ActionFrame::default();
        frame.navigation.pan = Vec2::new(10.0, 0.0);
        let mut host = Camera::default();
        CameraController::apply(&mut control, &mut host, &frame, 0.0);
        assert!(close(control.camera.centre(), Vec2::new(-1.0, 0.0), 1e-5));
        assert_eq!(host.pose, control.camera.camera().pose);
        assert!(control.as_any_mut().is_some());
    }

    #[test]
    fn controller_ignores_a_drag_the_viewport_does_not_own() {
        let mut ctrl = Camera2dController::new();
        let mut c = Camera2d::new(Plane2d::Xy);
        let ctx = ViewportContext::new(InputOwnership::default(), [800.0, 600.0]);
        ctrl.begin_frame(ctx);
        ctrl.push_event(ViewportEvent::PointerMoved {
            position: Vec2::new(100.0, 100.0),
        });
        ctrl.push_event(ViewportEvent::MouseButton {
            button: MouseButton::Left,
            state: ButtonState::Pressed,
        });
        ctrl.push_event(ViewportEvent::PointerMoved {
            position: Vec2::new(160.0, 100.0),
        });
        ctrl.apply_to_camera(&mut c, 0.0);
        assert_eq!(c.centre(), Vec2::ZERO);
    }
}