Skip to main content

crcbl_render/
orbit.rs

1//! The orbit camera: turning drags into a [`Camera`], and nothing else.
2//!
3//! ```text
4//! orbit(dyaw, dpitch) ─┐
5//! pan(right, up) ──────┼─▶ OrbitCamera { pivot, distance, yaw, pitch } ─▶ Camera
6//! zoom(delta) ─────────┤
7//! frame(bounds, aspect)┘
8//! ```
9//!
10//! The viewer's orbit controls and the stage-8 editor's
11//! viewport are the same controller, which is why it is here beside [`Camera`]
12//! rather than in an app: it is arithmetic, it needs no device, and every one of
13//! its claims is a unit test.
14//!
15//! # It takes deltas, never keys
16//!
17//! Nothing in this module names a key, a mouse button or a modifier. Which
18//! gesture produces a yaw delta is the *app's* decision and the DCC tools
19//! disagree about it — orbit-follows-mouse and object-follows-mouse are opposite
20//! signs for the same drag, and an editor whose users came from a different tool
21//! will want the other one. A controller that read the mouse itself could not be
22//! reused by an app whose input model is not the sample's.
23//!
24//! So this module fixes the *geometry* and leaves the *gesture* alone. The
25//! conventions it does fix are:
26//!
27//! * **A positive yaw delta swings the eye toward the camera's own right**, and
28//!   the view therefore turns left. That is the same rotation sense as
29//!   [`crate::fly::Flyer`] — a rising yaw is a rotation about `+Y` that carries
30//!   `+Z` toward `+X` — so the two cameras in this engine agree about which way
31//!   an angle goes, and an app that wants the object to follow the pointer
32//!   negates the delta on its way in.
33//! * **A positive pitch delta lifts the eye**, so the camera looks *down* on the
34//!   pivot. `pitch` here is the eye's elevation above the pivot's horizontal
35//!   plane, not the view's inclination; they are the same angle with opposite
36//!   signs, and this one is the one a turntable is usually written in.
37//! * **Pan is measured in fractions of the viewport height**, not in metres or
38//!   pixels. A drag of half the window's height moves the pivot by half of what
39//!   the window shows at the pivot's depth, so the scene keeps up with the
40//!   pointer at any zoom and on any window size. Doing that conversion needs the
41//!   field of view and the distance, which is exactly the arithmetic that would
42//!   otherwise be copied into every app.
43//!
44//! # Perspective only, and the type says so
45//!
46//! [`OrbitCamera::new`] takes a [`Projection`] and refuses an orthographic one,
47//! keeping the field of view and near plane rather than the enum. Zoom under an
48//! orthographic projection is a change of `half_height` and not of distance, so
49//! a controller that accepted one would have a zoom that moved the eye and
50//! changed nothing on screen — "not supported here" arriving as "worked".
51//! `docs/backlog.md` carries the orthographic mode as the thing that would
52//! change this.
53
54use core::f32::consts::FRAC_PI_2;
55
56use glam::{DVec3, Vec3};
57
58use crate::camera::{Camera, Projection};
59use crate::cull::Aabb;
60
61/// How far the eye may rise or fall from the pivot's horizontal plane, in
62/// radians.
63///
64/// Just short of straight up and straight down, and [`crate::fly::Flyer`]'s own
65/// pitch limit is the precedent. At *exactly* vertical the direction from pivot
66/// to eye is parallel to `Vec3::Y` and [`Camera::view`] panics rather than hand
67/// back a matrix of `NaN`s — so an unclamped turntable does not wobble, it takes
68/// the process down.
69pub const PITCH_LIMIT: f32 = FRAC_PI_2 - 0.05;
70
71/// The closest the eye may come to the pivot, in metres.
72///
73/// A geometric guard, **not** the near plane: zooming until the pivot is inside
74/// the near plane is ordinary DCC behaviour and this does not prevent it. What
75/// it prevents is distance reaching zero, where `eye == target` and
76/// [`Camera::view`] panics, and negative distance, where the camera passes
77/// through the pivot and comes out looking at it backwards.
78pub const MIN_DISTANCE: f32 = 0.01;
79
80/// The furthest the eye may retreat, in metres — a thousand kilometres.
81///
82/// [`OrbitCamera::zoom`] is multiplicative, so without an upper bound a user
83/// leaning on the wheel reaches `inf` in a few hundred notches and every
84/// subsequent frame is `NaN`.
85pub const MAX_DISTANCE: f32 = 1.0e6;
86
87/// How much larger than the framed bounds the view is, as a ratio.
88///
89/// [`OrbitCamera::frame`] fits the bounding sphere and then backs off by this,
90/// so a framed object has a little air around it instead of touching all four
91/// edges.
92pub const FRAME_MARGIN: f32 = 1.1;
93
94/// A camera that turns about a pivot: orbit, pan, zoom, frame.
95///
96/// Holds a pivot, a distance and two angles rather than a [`Camera`], for the
97/// same reason [`crate::fly::Flyer`] holds angles: an eye and a target
98/// integrated directly drift apart, and "orbit" would depend on how far away the
99/// target happened to be.
100///
101/// ```
102/// use crcbl_render::{Camera, OrbitCamera, Projection};
103/// use glam::Vec3;
104///
105/// let mut orbit = OrbitCamera::new(Vec3::ZERO, 4.0, Projection::default());
106/// // Zero yaw stands where the engine's default camera stands: back along +Z.
107/// assert_eq!(orbit.camera().eye, Vec3::new(0.0, 0.0, 4.0));
108///
109/// // A quarter turn to the eye's right puts it on +X, still looking at the pivot.
110/// orbit.orbit(core::f32::consts::FRAC_PI_2, 0.0);
111/// let camera = orbit.camera();
112/// assert!((camera.eye - Vec3::new(4.0, 0.0, 0.0)).length() < 1e-5);
113/// assert_eq!(camera.target, Vec3::ZERO);
114/// ```
115#[derive(Clone, Copy, Debug, PartialEq)]
116pub struct OrbitCamera {
117    /// What the camera looks at and turns around.
118    pivot: Vec3,
119    /// How far the eye is from the pivot, in metres.
120    distance: f32,
121    /// Azimuth about `+Y`, measured so that `0` puts the eye on `+Z`.
122    yaw: f32,
123    /// Elevation above the pivot's horizontal plane, positive up.
124    pitch: f32,
125    /// Vertical field of view, in radians. Kept rather than the [`Projection`]
126    /// because this controller is perspective-only and both [`Self::pan`] and
127    /// [`Self::frame`] need the angle itself.
128    fov_y: f32,
129    /// Near plane distance, carried so [`Self::camera`] can rebuild the
130    /// projection it was given.
131    near: f32,
132}
133
134impl OrbitCamera {
135    /// A camera `distance` metres from `pivot`, looking at it from `+Z`.
136    ///
137    /// Zero yaw and zero pitch put the eye where [`Camera::default`] puts it —
138    /// back along `+Z`, looking down `-Z` — so an orbit camera nobody has
139    /// dragged yet frames the world the same way the rest of the engine does.
140    ///
141    /// # Panics
142    ///
143    /// If `projection` is [`Projection::Orthographic`], which this controller
144    /// does not support (see the [module docs](self)), if `distance` is not
145    /// finite, or on the same field of view and near plane
146    /// [`Projection::matrix`] refuses — each of which otherwise turns into a
147    /// `NaN` matrix and a blank screen with no error anywhere.
148    #[must_use]
149    pub fn new(pivot: Vec3, distance: f32, projection: Projection) -> Self {
150        let Projection::Perspective { fov_y, near } = projection else {
151            panic!("an orbit camera is perspective-only, got {projection:?}");
152        };
153        assert!(
154            distance.is_finite(),
155            "the orbit distance must be finite, got {distance}"
156        );
157        assert!(near > 0.0, "the near plane must be positive, got {near}");
158        assert!(
159            fov_y > 0.0 && fov_y < core::f32::consts::PI,
160            "the field of view must be in (0, π), got {fov_y}"
161        );
162        Self {
163            pivot,
164            distance: distance.clamp(MIN_DISTANCE, MAX_DISTANCE),
165            yaw: 0.0,
166            pitch: 0.0,
167            fov_y,
168            near,
169        }
170    }
171
172    /// What the camera turns around and looks at.
173    #[must_use]
174    pub const fn pivot(&self) -> Vec3 {
175        self.pivot
176    }
177
178    /// How far the eye is from the pivot, in metres.
179    #[must_use]
180    pub const fn distance(&self) -> f32 {
181        self.distance
182    }
183
184    /// Turns the eye about the pivot by `yaw` and `pitch` radians.
185    ///
186    /// The pivot does not move and the distance does not change; this is the
187    /// operation that makes it a turntable rather than a look-around. Positive
188    /// `yaw` swings the eye toward the camera's own right, positive `pitch`
189    /// lifts it — see the [module docs](self) — and the pitch is clamped to
190    /// [`PITCH_LIMIT`] short of vertical, where the view matrix is degenerate.
191    ///
192    /// # Panics
193    ///
194    /// If either delta is not finite. An angle that goes `NaN` here stays `NaN`
195    /// for the rest of the session, and the panic it eventually causes is in
196    /// [`Camera::view`], several frames from the input that caused it.
197    pub fn orbit(&mut self, yaw: f32, pitch: f32) {
198        assert!(
199            yaw.is_finite() && pitch.is_finite(),
200            "orbit deltas must be finite, got yaw {yaw} and pitch {pitch}"
201        );
202        self.yaw += yaw;
203        self.pitch = (self.pitch + pitch).clamp(-PITCH_LIMIT, PITCH_LIMIT);
204    }
205
206    /// Slides the pivot across the view plane, in fractions of the viewport
207    /// height.
208    ///
209    /// Positive `right` moves the pivot toward the camera's own right and
210    /// positive `up` toward its own up, so the scene appears to move the *other*
211    /// way — an app implementing grab-and-drag negates both. The eye follows
212    /// rigidly: panning changes what the camera looks at, never how far away it
213    /// is or which way it faces.
214    ///
215    /// One unit is the whole viewport height **at the pivot's depth**, which is
216    /// what makes a drag track the pointer: the point under the cursor when the
217    /// drag began is still under it when the drag ends, as long as that point
218    /// was near the pivot's plane. Points nearer or further than the pivot move
219    /// by more or less, which is parallax and is correct.
220    ///
221    /// # Panics
222    ///
223    /// If either delta is not finite, for the reason [`Self::orbit`] gives.
224    pub fn pan(&mut self, right: f32, up: f32) {
225        assert!(
226            right.is_finite() && up.is_finite(),
227            "pan deltas must be finite, got right {right} and up {up}"
228        );
229        let (right_axis, up_axis) = self.basis();
230        self.pivot += (right_axis * right + up_axis * up) * self.viewport_height();
231    }
232
233    /// Moves the eye along its own view ray. Positive `delta` moves closer.
234    ///
235    /// **Multiplicative, and the field of view never changes.** Each unit of
236    /// `delta` divides the distance by `e`, so a wheel notch covers the same
237    /// fraction of the way in whether the camera is a metre out or a kilometre —
238    /// which is the only behaviour that is usable across the range a model
239    /// viewer sees. Changing the field of view instead would be a dolly zoom:
240    /// the framing would match and the perspective would not.
241    ///
242    /// The result is clamped to [`MIN_DISTANCE`]`..=`[`MAX_DISTANCE`], so no
243    /// amount of zooming reaches the pivot, passes through it, or runs off to
244    /// infinity.
245    ///
246    /// # Panics
247    ///
248    /// If `delta` is not finite, for the reason [`Self::orbit`] gives.
249    pub fn zoom(&mut self, delta: f32) {
250        assert!(
251            delta.is_finite(),
252            "the zoom delta must be finite, got {delta}"
253        );
254        self.distance = (self.distance * (-delta).exp()).clamp(MIN_DISTANCE, MAX_DISTANCE);
255    }
256
257    /// Centres `bounds` and backs off far enough to see all of it, keeping the
258    /// direction the camera is already looking from.
259    ///
260    /// **The fit is on the bounding sphere and on both axes.** A sphere because
261    /// a box's silhouette changes as the camera orbits, so a box fit would frame
262    /// the object at one angle and clip it at the next; the sphere's does not
263    /// change at all, at the cost of a little air around a flat object. Both
264    /// axes because the horizontal half-angle is
265    /// `atan(tan(fov_y / 2) · aspect)`, which in a window narrower than it is
266    /// tall is *smaller* than the vertical one — so framing a wide object by
267    /// height alone leaves it hanging off both sides of a narrow window. The
268    /// limiting half-angle `θ` is whichever is smaller, and a sphere of radius
269    /// `r` fits inside it at `r / sin θ`, times [`FRAME_MARGIN`].
270    ///
271    /// The distance is then held to at least `near + r`, so the whole sphere is
272    /// in front of the near plane rather than half of it behind — which matters
273    /// for a small object, where the fit distance alone can be shorter than the
274    /// near plane.
275    ///
276    /// # Panics
277    ///
278    /// If `aspect` is not finite and positive, as [`Projection::matrix`], or if
279    /// `bounds` is not finite.
280    pub fn frame(&mut self, bounds: Aabb, aspect: f32) {
281        assert!(
282            aspect.is_finite() && aspect > 0.0,
283            "aspect ratio must be finite and positive, got {aspect}"
284        );
285        assert!(
286            bounds.min.is_finite() && bounds.max.is_finite(),
287            "the framed bounds must be finite, got {bounds:?}"
288        );
289        let radius = bounds.half_extent().length();
290        let half_fov_y = 0.5 * self.fov_y;
291        let half_fov_x = (half_fov_y.tan() * aspect).atan();
292        let half_fov = half_fov_y.min(half_fov_x);
293        self.pivot = bounds.center();
294        self.distance = (radius * FRAME_MARGIN / half_fov.sin())
295            .max(self.near + radius)
296            .clamp(MIN_DISTANCE, MAX_DISTANCE);
297    }
298
299    /// The camera this controller is.
300    ///
301    /// `up` is the world's `+Y` rather than the view's own up vector: the pitch
302    /// clamp is what keeps the two from becoming parallel, and a turntable whose
303    /// up drifted with the view would roll.
304    #[must_use]
305    pub fn camera(&self) -> Camera {
306        Camera {
307            eye: self.pivot + self.direction() * self.distance,
308            target: self.pivot,
309            up: Vec3::Y,
310            projection: Projection::Perspective {
311                fov_y: self.fov_y,
312                near: self.near,
313            },
314        }
315    }
316
317    /// The world-space direction a stick means, at the yaw the view is at.
318    ///
319    /// `ahead` is positive away from the camera and `strafe` positive to the
320    /// camera's right; both are expected in `-1..=1`. The result is a **unit**
321    /// direction, or zero where nothing was asked for — the caller multiplies
322    /// by a speed and a timestep to get the displacement a character controller
323    /// takes.
324    ///
325    /// An associated function rather than a method because a follow camera
326    /// rebuilds its [`OrbitCamera`] every frame from a pivot that has moved,
327    /// and holds only the two angles between frames: it has a yaw before it has
328    /// a rig. What makes this the rig's arithmetic and not the caller's is the
329    /// **measure** — the yaw is the one this module turns, so `ahead` is the
330    /// direction [`camera`](Self::camera) looks with the vertical taken out and
331    /// `right` is the cross product this camera's own basis is built from.
332    ///
333    /// It is `f64` where the rest of this module is `f32` because a character
334    /// controller integrates a position in metres over a whole session, which
335    /// is where single precision runs out first.
336    ///
337    /// Normalised rather than passed through, so holding two keys does not walk
338    /// `√2` times faster than holding one — which is the oldest bug in this
339    /// conversion.
340    #[must_use]
341    pub fn walk_direction(yaw: f64, ahead: f64, strafe: f64) -> DVec3 {
342        let (sin, cos) = yaw.sin_cos();
343        let along = DVec3::new(-sin, 0.0, -cos);
344        let right = DVec3::new(cos, 0.0, -sin);
345        (along * ahead + right * strafe).normalize_or_zero()
346    }
347
348    /// The unit vector from the pivot towards the eye.
349    fn direction(&self) -> Vec3 {
350        let (sin_yaw, cos_yaw) = self.yaw.sin_cos();
351        let (sin_pitch, cos_pitch) = self.pitch.sin_cos();
352        Vec3::new(sin_yaw * cos_pitch, sin_pitch, cos_yaw * cos_pitch)
353    }
354
355    /// The camera's own right and up axes, both unit length.
356    ///
357    /// Built from the view direction the same way [`Camera::view`] builds its
358    /// basis, so "the camera's right" means one thing in this module and in the
359    /// matrix it produces. The cross with `Vec3::Y` is never degenerate because
360    /// [`PITCH_LIMIT`] stops the direction short of vertical.
361    fn basis(&self) -> (Vec3, Vec3) {
362        let forward = -self.direction();
363        let right = forward.cross(Vec3::Y).normalize();
364        (right, right.cross(forward))
365    }
366
367    /// How much world the viewport shows vertically at the pivot's depth.
368    fn viewport_height(&self) -> f32 {
369        2.0 * self.distance * (0.5 * self.fov_y).tan()
370    }
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376    use core::f32::consts::FRAC_PI_2;
377
378    const ASPECT: f32 = 16.0 / 9.0;
379
380    fn orbit_camera() -> OrbitCamera {
381        OrbitCamera::new(Vec3::new(1.0, 2.0, -3.0), 5.0, Projection::default())
382    }
383
384    /// The camera's own right vector, from the [`Camera`] itself rather than
385    /// from the controller's internals — so a test using it is asserting about
386    /// the basis the view matrix will be built from.
387    fn right_of(camera: &Camera) -> Vec3 {
388        (camera.target - camera.eye)
389            .normalize()
390            .cross(Vec3::Y)
391            .normalize()
392    }
393
394    /// Zero yaw and zero pitch stand where the rest of the engine's cameras
395    /// stand, which is what makes the first frame of a viewer the frame every
396    /// other tool would draw.
397    #[test]
398    fn an_untouched_orbit_camera_matches_the_engine_default_pose() {
399        let orbit = OrbitCamera::new(Vec3::ZERO, 2.0, Projection::default());
400        assert_eq!(orbit.camera(), Camera::default());
401    }
402
403    /// **A positive yaw delta swings the eye toward the camera's own right.**
404    ///
405    /// The claim is made against the camera's *own* starting basis, never
406    /// against a world axis, so it holds at every orientation — which is why the
407    /// loop runs it again from an already-orbited pose. `apps/lantern` shipped a
408    /// camera that turned the wrong way because its only yaw test compared a
409    /// stored angle, and a stored angle is right on a controller that builds its
410    /// basis backwards too.
411    #[test]
412    fn a_positive_yaw_delta_swings_the_eye_toward_the_cameras_own_right() {
413        for (turn, sign) in [(0.1f32, 1.0f32), (-0.1, -1.0)] {
414            for (start_yaw, start_pitch) in [(0.0f32, 0.0f32), (2.3, 0.6), (-1.1, -0.4)] {
415                let mut orbit = orbit_camera();
416                orbit.orbit(start_yaw, start_pitch);
417
418                let before = orbit.camera();
419                let right = right_of(&before);
420                orbit.orbit(turn, 0.0);
421                let after = orbit.camera();
422
423                let moved = (after.eye - before.eye).normalize();
424                let leaned = moved.dot(right);
425                assert!(
426                    leaned * sign > 0.9,
427                    "a yaw of {turn} from ({start_yaw}, {start_pitch}) moved the eye {leaned} of \
428                     the way along the camera's own right {right:?}, and the sign says it went \
429                     the other way"
430                );
431                // Small enough that the eye has not swung past the perpendicular
432                // and made a wrong sign read as a right one.
433                assert!(
434                    (after.eye - before.eye).length() < 0.2 * orbit.distance(),
435                    "a yaw of {turn} moved the eye too far for the sign above to mean what it says"
436                );
437                // And it is an *orbit*: the pivot stays put and the distance
438                // does not change, which is what separates it from a look-around.
439                assert_eq!(after.target, before.target, "the pivot moved");
440                assert!(
441                    ((after.eye - after.target).length() - (before.eye - before.target).length())
442                        .abs()
443                        < 1e-4,
444                    "the distance changed"
445                );
446            }
447        }
448    }
449
450    /// **A positive pitch delta lifts the eye**, so the view looks down on the
451    /// pivot. The two halves of that sentence are asserted separately: a
452    /// controller that raised the eye and then looked the other way would pass
453    /// the first alone.
454    #[test]
455    fn a_positive_pitch_delta_lifts_the_eye_and_aims_the_view_downward() {
456        for (tilt, sign) in [(0.5f32, 1.0f32), (-0.5, -1.0)] {
457            let mut orbit = orbit_camera();
458            let before = orbit.camera();
459            orbit.orbit(0.0, tilt);
460            let after = orbit.camera();
461
462            assert!(
463                (after.eye.y - before.eye.y) * sign > 0.0,
464                "a pitch of {tilt} moved the eye from {:?} to {:?}, which is the wrong way",
465                before.eye,
466                after.eye
467            );
468            let forward = (after.target - after.eye).normalize();
469            assert!(
470                forward.y * sign < 0.0,
471                "a pitch of {tilt} left the view looking {forward:?}, which is not back down at \
472                 the pivot"
473            );
474            assert_eq!(after.target, before.target, "the pivot moved");
475        }
476    }
477
478    /// The pitch stops short of vertical, where the direction is parallel to
479    /// `up` and [`Camera::view`] panics rather than return a matrix of `NaN`s.
480    ///
481    /// The view matrix is *built* here, not just inspected: the panic this
482    /// guards against is inside it, so a clamp that left the basis degenerate
483    /// while keeping the angle plausible would still take this test down.
484    ///
485    /// **The claim is monotonicity across the sweep, not the pose at the end**,
486    /// because an unclamped turntable sails over the top and comes back down the
487    /// far side into a pose that looks entirely legal — this test first passed
488    /// against a controller with the clamp deleted, for exactly that reason.
489    #[test]
490    fn the_pitch_clamp_stops_short_of_vertical_and_the_view_still_builds() {
491        for sign in [1.0f32, -1.0] {
492            let mut orbit = orbit_camera();
493            let mut highest = f32::NEG_INFINITY;
494            // Far more tilt than the limit is away, in steps that straddle
495            // vertical rather than landing on it.
496            for step in 0..40 {
497                orbit.orbit(0.0, sign * 0.5);
498                let camera = orbit.camera();
499                let direction = (camera.eye - camera.target).normalize();
500                let elevation = direction.y * sign;
501                assert!(
502                    elevation >= highest - 1e-6,
503                    "at step {step} the eye's elevation fell from {highest} to {elevation}: it \
504                     went over the top instead of stopping"
505                );
506                assert!(
507                    elevation <= PITCH_LIMIT.sin() + 1e-6,
508                    "at step {step} the eye reached an elevation of {elevation}, past the limit"
509                );
510                assert!(
511                    camera.view().is_finite(),
512                    "at step {step} the pose produced a NaN view matrix"
513                );
514                highest = elevation;
515            }
516
517            // And one enormous delta, which is what a fast drag or a wheel
518            // gesture arrives as: it lands *on* the limit rather than wherever
519            // the raw angle happens to wrap to.
520            let mut orbit = orbit_camera();
521            orbit.orbit(0.0, sign * 10.0);
522            let camera = orbit.camera();
523            let direction = (camera.eye - camera.target).normalize();
524            assert!(
525                (direction.y * sign - PITCH_LIMIT.sin()).abs() < 1e-5,
526                "a ten-radian tilt left the eye at {direction:?} rather than on the limit"
527            );
528            let level = Vec3::new(direction.x, 0.0, direction.z).length();
529            assert!(level > 0.01, "no horizontal component left at all");
530            assert!(
531                camera.view().is_finite(),
532                "the clamped pose still produced a NaN view matrix"
533            );
534        }
535    }
536
537    /// **Pan moves the pivot in the view plane**, so the same delta goes a
538    /// different way once the camera has orbited.
539    ///
540    /// Two poses, and the second is a quarter turn from the first: a controller
541    /// that panned along world axes would move the pivot the same way in both
542    /// and fail the perpendicularity check, while still passing a pan test
543    /// written at one orientation only.
544    #[test]
545    fn panning_follows_the_view_plane_rather_than_the_world_axes() {
546        let displace = |yaw: f32, pitch: f32| {
547            let mut orbit = orbit_camera();
548            orbit.orbit(yaw, pitch);
549            let before = orbit.camera();
550            orbit.pan(1.0, 0.0);
551            let after = orbit.camera();
552            // The whole camera slides: panning changes what it looks at, not
553            // where it looks from relative to that.
554            assert!(
555                (after.eye - before.eye - (after.target - before.target)).length() < 1e-4,
556                "pan moved the eye and the pivot by different amounts"
557            );
558            (after.target - before.target, right_of(&before))
559        };
560
561        for pitch in [0.0f32, 0.7, -0.7] {
562            let (level, right) = displace(0.0, pitch);
563            assert!(
564                level.normalize().dot(right) > 0.999,
565                "a rightward pan moved the pivot {level:?}, not along the camera's right {right:?}"
566            );
567            // Pitched or not, a rightward pan is level: the camera's right is
568            // always horizontal, because `up` is the world's.
569            assert!(
570                level.y.abs() < 1e-5,
571                "a rightward pan at pitch {pitch} changed the height by {}",
572                level.y
573            );
574        }
575
576        let (facing_z, _) = displace(0.0, 0.0);
577        let (facing_x, right) = displace(FRAC_PI_2, 0.0);
578        assert!(
579            facing_x.normalize().dot(right) > 0.999,
580            "after a quarter turn a rightward pan moved the pivot {facing_x:?}, not along the \
581             camera's new right {right:?}"
582        );
583        assert!(
584            facing_z.normalize().dot(facing_x.normalize()).abs() < 1e-5,
585            "a quarter turn left the pan direction unchanged at {facing_z:?} and {facing_x:?}, \
586             which is what panning in world axes looks like"
587        );
588
589        // And up is up: with the eye above the pivot, panning "up" the screen
590        // pushes the pivot away and higher, not straight up the world's +Y.
591        let mut orbit = orbit_camera();
592        orbit.orbit(0.0, 0.7);
593        let before = orbit.camera();
594        orbit.pan(0.0, 1.0);
595        let moved = orbit.camera().target - before.target;
596        let (_, up_axis) = orbit.basis();
597        assert!(
598            moved.normalize().dot(up_axis) > 0.999,
599            "an upward pan moved the pivot {moved:?}, not along the camera's up {up_axis:?}"
600        );
601        assert!(
602            moved.y > 0.0 && moved.dot(Vec3::Y).abs() < moved.length(),
603            "an upward pan from a raised eye must rise *and* travel, got {moved:?}"
604        );
605    }
606
607    /// **A drag tracks the pointer**, which is the whole reason pan is measured
608    /// in fractions of the viewport height rather than in metres.
609    ///
610    /// The observable is where the *old* pivot lands on screen: pan up by half
611    /// the viewport and it must sit exactly on the bottom edge of the frame,
612    /// `y = -1` in NDC. A pan in world units would land it somewhere that
613    /// depended on the zoom, and a pan that forgot the factor of two would land
614    /// it in the middle of the lower half.
615    #[test]
616    fn a_half_height_pan_moves_the_scene_exactly_half_a_screen() {
617        for distance in [0.5f32, 5.0, 500.0] {
618            let mut orbit = OrbitCamera::new(Vec3::ZERO, distance, Projection::default());
619            orbit.orbit(0.9, 0.4);
620            let was = orbit.pivot();
621            orbit.pan(0.0, 0.5);
622
623            let clip = orbit.camera().view_projection(ASPECT) * was.extend(1.0);
624            let ndc_y = clip.y / clip.w;
625            assert!(
626                (ndc_y + 1.0).abs() < 1e-4,
627                "at {distance} m a half-height pan put the old pivot at y = {ndc_y} in NDC, not on \
628                 the bottom edge at -1"
629            );
630            assert!(
631                (clip.x / clip.w).abs() < 1e-4,
632                "a vertical pan moved the scene sideways"
633            );
634        }
635    }
636
637    /// Zoom changes the distance and nothing else: same direction, same pivot,
638    /// same field of view. A dolly zoom would keep the framing and change the
639    /// perspective, which is a shot, not a control.
640    #[test]
641    fn zoom_moves_the_eye_along_its_ray_and_leaves_the_lens_alone() {
642        let mut orbit = orbit_camera();
643        orbit.orbit(0.8, 0.3);
644        let before = orbit.camera();
645
646        orbit.zoom(1.0);
647        let after = orbit.camera();
648        assert!(
649            after.eye.distance(after.target) < before.eye.distance(before.target),
650            "a positive zoom delta moved the eye away from the pivot"
651        );
652        assert_eq!(after.target, before.target, "the pivot moved");
653        assert_eq!(after.projection, before.projection, "the lens changed");
654        assert!(
655            (after.eye - after.target)
656                .normalize()
657                .dot((before.eye - before.target).normalize())
658                > 0.9999,
659            "the eye left its own view ray"
660        );
661
662        // Multiplicative: the same delta covers the same *fraction* of the way
663        // in, wherever it starts from. An additive zoom would take a fixed
664        // number of metres and be unusable at one end of the range or the other.
665        let ratio = |start: f32| {
666            let mut orbit = OrbitCamera::new(Vec3::ZERO, start, Projection::default());
667            orbit.zoom(0.25);
668            orbit.distance() / start
669        };
670        assert!(
671            (ratio(2.0) - ratio(2000.0)).abs() < 1e-5,
672            "zoom is not scale-free"
673        );
674    }
675
676    /// **Zoom never reaches the pivot and never passes through it.** At distance
677    /// zero `eye == target` and [`Camera::view`] panics; past it the camera is
678    /// on the far side looking back, which reads as the model turning inside out.
679    #[test]
680    fn zoom_stops_short_of_the_pivot_and_short_of_infinity() {
681        let mut orbit = orbit_camera();
682        orbit.orbit(0.4, 0.2);
683        let approach = (orbit.camera().eye - orbit.pivot()).normalize();
684
685        for _ in 0..200 {
686            orbit.zoom(5.0);
687        }
688        assert_eq!(
689            orbit.distance(),
690            MIN_DISTANCE,
691            "the near clamp did not hold"
692        );
693        let camera = orbit.camera();
694        let offset = camera.eye - camera.target;
695        assert!(
696            offset.dot(approach) > 0.0,
697            "zooming in passed through the pivot: the eye is at {offset:?} against an approach \
698             along {approach:?}"
699        );
700        assert!(
701            offset.length() > 0.0 && camera.view().is_finite(),
702            "the fully zoomed camera has no view matrix"
703        );
704
705        for _ in 0..200 {
706            orbit.zoom(-5.0);
707        }
708        assert_eq!(orbit.distance(), MAX_DISTANCE, "the far clamp did not hold");
709        assert!(orbit.camera().eye.is_finite());
710    }
711
712    /// **Framing fits both axes**, which is the case a height-only fit gets
713    /// wrong: a wide object in a window narrower than it is tall hangs off both
714    /// sides.
715    ///
716    /// The test projects the box's own corners through the real
717    /// [`Camera::view_projection`] and demands every one inside the frame, then
718    /// re-projects them at the distance a height-only fit would have chosen and
719    /// demands that one *fails* — because a fit test that both formulas pass is
720    /// not testing the thing that distinguishes them.
721    #[test]
722    fn framing_fits_a_wide_object_in_a_narrow_window_where_height_alone_would_not() {
723        let bounds = Aabb {
724            min: Vec3::new(-5.0, -0.5, -0.5),
725            max: Vec3::new(5.0, 0.5, 0.5),
726        };
727        let corners = |bounds: Aabb| {
728            let (lo, hi) = (bounds.min, bounds.max);
729            [
730                Vec3::new(lo.x, lo.y, lo.z),
731                Vec3::new(hi.x, lo.y, lo.z),
732                Vec3::new(lo.x, hi.y, lo.z),
733                Vec3::new(hi.x, hi.y, lo.z),
734                Vec3::new(lo.x, lo.y, hi.z),
735                Vec3::new(hi.x, lo.y, hi.z),
736                Vec3::new(lo.x, hi.y, hi.z),
737                Vec3::new(hi.x, hi.y, hi.z),
738            ]
739        };
740        // The widest a point sits in the frame, over both screen axes: 1.0 is
741        // the edge.
742        let extent = |camera: &Camera, aspect: f32, points: &[Vec3]| {
743            let view_projection = camera.view_projection(aspect);
744            points.iter().fold(0.0f32, |worst, &point| {
745                let clip = view_projection * point.extend(1.0);
746                assert!(clip.w > 0.0, "{point:?} is behind the eye");
747                worst
748                    .max((clip.x / clip.w).abs())
749                    .max((clip.y / clip.w).abs())
750            })
751        };
752
753        let mut narrow = 0.0;
754        for aspect in [2.0f32, 1.0, 0.5] {
755            let mut orbit = OrbitCamera::new(Vec3::ZERO, 1.0, Projection::default());
756            orbit.frame(bounds, aspect);
757            assert_eq!(orbit.pivot(), bounds.center(), "framing did not recentre");
758
759            let camera = orbit.camera();
760            let worst = extent(&camera, aspect, &corners(bounds));
761            assert!(
762                worst <= 1.0,
763                "at aspect {aspect} a corner projected to {worst}, outside the frame"
764            );
765            // And it is *framed*, not merely somewhere in front: the bounding
766            // sphere's silhouette reaches the edge, less the margin.
767            let radius = bounds.half_extent().length();
768            let (right, up) = orbit.basis();
769            let silhouette = [
770                camera.target + right * radius,
771                camera.target - right * radius,
772                camera.target + up * radius,
773                camera.target - up * radius,
774            ];
775            let reach = extent(&camera, aspect, &silhouette);
776            assert!(
777                (0.8..=1.0).contains(&reach),
778                "at aspect {aspect} the framed sphere only reached {reach} of the frame"
779            );
780
781            if aspect == 0.5 {
782                narrow = orbit.distance();
783            } else if aspect == 2.0 {
784                assert!(
785                    orbit.distance() < narrow || narrow == 0.0,
786                    "a narrow window must back further off than a wide one"
787                );
788            }
789        }
790
791        // The control. Height alone gives `r / sin(fov_y / 2)`, which is what
792        // this returns at every aspect — and at 0.5 it is not enough.
793        let Projection::Perspective { fov_y, .. } = Projection::default() else {
794            unreachable!("the default projection is perspective")
795        };
796        let radius = bounds.half_extent().length();
797        let height_only = Camera {
798            eye: Vec3::Z * (radius * FRAME_MARGIN / (0.5 * fov_y).sin()),
799            ..Camera::default()
800        };
801        let missed = extent(&height_only, 0.5, &corners(bounds));
802        assert!(
803            missed > 1.0,
804            "the control is only meaningful if a height-only fit genuinely fails here; it kept \
805             every corner inside the frame at {missed}"
806        );
807    }
808
809    /// Framing keeps the direction the camera is already looking from — the
810    /// behaviour that makes it a "frame selection" rather than a "reset view".
811    #[test]
812    fn framing_moves_the_camera_without_turning_it() {
813        let mut orbit = orbit_camera();
814        orbit.orbit(1.4, -0.6);
815        let before = orbit.camera();
816        let facing = (before.eye - before.target).normalize();
817
818        orbit.frame(
819            Aabb {
820                min: Vec3::new(8.0, 8.0, 8.0),
821                max: Vec3::new(12.0, 10.0, 12.0),
822            },
823            ASPECT,
824        );
825        let after = orbit.camera();
826        assert!(
827            (after.eye - after.target).normalize().dot(facing) > 0.9999,
828            "framing turned the camera from {facing:?} to {:?}",
829            (after.eye - after.target).normalize()
830        );
831        assert_eq!(after.target, Vec3::new(10.0, 9.0, 10.0));
832    }
833
834    /// A zero-size bound is a real input — one imported node, one selected
835    /// vertex — and the fit distance for it is zero, which is a camera that
836    /// panics. The near-plane floor is what catches it.
837    ///
838    /// **The observable is the framed point's depth**, not merely that it has
839    /// one: [`Camera::depth_of`] answers `Some` for anything in front of the
840    /// *eye*, so a camera parked a centimetre from the point — inside its own
841    /// near plane, where nothing is drawn — passes an `is_some` check happily.
842    /// It did, until this test read the depth instead.
843    #[test]
844    fn framing_a_single_point_leaves_a_usable_camera() {
845        let point = Vec3::new(3.0, -1.0, 2.0);
846        let mut orbit = orbit_camera();
847        orbit.frame(
848            Aabb {
849                min: point,
850                max: point,
851            },
852            ASPECT,
853        );
854        assert!(
855            orbit.distance() >= MIN_DISTANCE,
856            "framing a point put the eye {} m from it",
857            orbit.distance()
858        );
859        let camera = orbit.camera();
860        assert!(camera.view().is_finite());
861        let Projection::Perspective { near, .. } = camera.projection else {
862            unreachable!("an orbit camera is perspective-only")
863        };
864        assert!(
865            orbit.distance() >= near,
866            "framing a point put the eye {} m from it, inside its own {near} m near plane",
867            orbit.distance()
868        );
869        let depth = camera
870            .depth_of(point, ASPECT)
871            .expect("the framed point is in front of the eye");
872        assert!(
873            depth > 0.0 && depth <= crcbl_hal::depth::NEAR + 1e-5,
874            "the framed point projected to depth {depth}, and anything above {} is nearer than \
875             the near plane and never drawn",
876            crcbl_hal::depth::NEAR
877        );
878    }
879
880    /// An orthographic projection has no field of view to fit against and a zoom
881    /// that would move the eye and change nothing on screen, so it is refused at
882    /// the boundary rather than silently mis-served.
883    #[test]
884    #[should_panic(expected = "perspective-only")]
885    fn an_orthographic_projection_is_refused() {
886        let _ = OrbitCamera::new(
887            Vec3::ZERO,
888            4.0,
889            Projection::Orthographic {
890                half_height: 1.0,
891                near: 0.1,
892                far: 100.0,
893            },
894        );
895    }
896
897    /// A `NaN` delta stays in the angle forever and takes the view matrix down
898    /// several frames later, so it stops here instead.
899    #[test]
900    #[should_panic(expected = "orbit deltas must be finite")]
901    fn a_non_finite_orbit_delta_is_refused() {
902        orbit_camera().orbit(f32::NAN, 0.0);
903    }
904
905    #[test]
906    #[should_panic(expected = "pan deltas must be finite")]
907    fn a_non_finite_pan_delta_is_refused() {
908        orbit_camera().pan(0.0, f32::INFINITY);
909    }
910
911    #[test]
912    #[should_panic(expected = "zoom delta must be finite")]
913    fn a_non_finite_zoom_delta_is_refused() {
914        orbit_camera().zoom(f32::NAN);
915    }
916}