Skip to main content

viewport_lib_input/controllers/
orbit.rs

1//! Orbit/pan/zoom camera controller.
2//!
3//! [`OrbitCameraController`] wraps [`crate::input::viewport_input::ViewportInput`] and
4//! applies resolved orbit / pan / zoom actions directly to a [`crate::Camera`].
5
6use crate::{Camera, LookAngles};
7use viewport_lib_types::camera::{CameraTarget, Pose};
8
9use crate::input::action::Action;
10use crate::input::action_frame::ActionFrame;
11use crate::input::context::ViewportContext;
12use crate::input::event::ViewportEvent;
13use crate::input::mode::NavigationMode;
14use crate::input::preset::{BindingPreset, preset_bindings};
15use crate::input::viewport_binding::ViewportBinding;
16use crate::input::viewport_input::ViewportInput;
17
18use super::movement::wish_from_actions;
19
20/// High-level orbit / pan / zoom camera controller.
21///
22/// Wraps the lower-level [`ViewportInput`] resolver and applies semantic
23/// camera actions to a [`Camera`] in a single `apply_to_camera` call.
24///
25/// The controller keeps the orbit centre and distance as its own state and
26/// writes the camera's pose, with the focus distance set to the orbit
27/// distance. When something else moves the camera (a fly-to, a preset, a
28/// host writing the pose), the next call reads the pivot back from the
29/// camera's focus point, so the orbit continues from the new view.
30///
31/// # Integration pattern (winit / single window)
32///
33/// ```text
34/// // --- AppState construction ---
35/// controller.begin_frame(ViewportContext::new(InputOwnership::full_window(), viewport_size));
36///
37/// // --- window_event ---
38/// controller.push_event(translated_event);
39///
40/// // --- RedrawRequested ---
41/// controller.apply_to_camera(&mut state.camera);
42/// controller.begin_frame(ViewportContext::new(InputOwnership::full_window(), viewport_size));
43/// // ... render ...
44/// ```
45///
46/// # Integration pattern (eframe / egui)
47///
48/// ```text
49/// // --- update() ---
50/// use viewport_lib_input::input::adapters::{AdapterCtx, egui};
51/// let ownership = egui::ownership(&response, ui.ctx(), rect, session_active);
52/// controller.begin_frame(ViewportContext::new(ownership, [rect.width(), rect.height()]));
53/// let actx = AdapterCtx::new(1.0, glam::Vec2::new(rect.left(), rect.top()));
54/// let mut events = Vec::new();
55/// ui.input(|i| {
56///     egui::begin_frame(i, &actx, &mut events);
57///     for ev in &i.events {
58///         egui::translate(ev, &actx, &mut events);
59///     }
60/// });
61/// for ev in events {
62///     controller.push_event(ev);
63/// }
64/// controller.apply_to_camera(&mut self.camera);
65/// ```
66pub struct OrbitCameraController {
67    input: ViewportInput,
68    /// How drag input is interpreted by [`apply_to_camera`](Self::apply_to_camera).
69    ///
70    /// Defaults to [`NavigationMode::Arcball`].
71    pub navigation_mode: NavigationMode,
72    /// Movement speed for [`NavigationMode::Fly`], in world units per second.
73    /// Moving diagonally is as fast as moving straight.
74    ///
75    /// Defaults to `6.0`. Scale this to match your scene : `6.0` suits a scene
76    /// with objects a few units across.
77    pub fly_speed: f32,
78    /// Multiplier on [`fly_speed`](Self::fly_speed) while
79    /// [`Action::FlySpeedBoost`](crate::input::Action::FlySpeedBoost) is held
80    /// (Shift in the default bindings). Defaults to `3.0`.
81    pub fly_boost: f32,
82    /// Sensitivity for drag-based orbit (radians per pixel).
83    pub orbit_sensitivity: f32,
84    /// Sensitivity for scroll-based zoom (scale factor per pixel).
85    pub zoom_sensitivity: f32,
86    /// Sensitivity applied to two-finger trackpad rotation gesture (radians per radian).
87    /// Default: `1.0` (gesture angle applied directly to camera yaw).
88    /// Set to `0.0` to suppress the gesture entirely.
89    pub gesture_sensitivity: f32,
90    /// Current viewport size (cached from the last `begin_frame`).
91    viewport_size: [f32; 2],
92    /// The orbit centre, distance and orientation the controller turns about.
93    pivot: Option<CameraTarget>,
94    /// The camera pose and focus distance last written, to tell when something
95    /// else has moved the camera and the pivot must be read from it again.
96    written: Option<(Pose, f32)>,
97}
98
99impl OrbitCameraController {
100    /// Default drag orbit sensitivity: 0.005 radians per pixel.
101    pub const DEFAULT_ORBIT_SENSITIVITY: f32 = 0.005;
102    /// Default scroll zoom sensitivity: 0.001 scale per pixel.
103    pub const DEFAULT_ZOOM_SENSITIVITY: f32 = 0.001;
104    /// Default gesture sensitivity: 1.0 (gesture radians applied 1:1 to camera yaw).
105    pub const DEFAULT_GESTURE_SENSITIVITY: f32 = 1.0;
106    /// Default fly speed: 6 world units per second.
107    pub const DEFAULT_FLY_SPEED: f32 = 6.0;
108    /// Default fly speed multiplier while boosting.
109    pub const DEFAULT_FLY_BOOST: f32 = 3.0;
110
111    /// Create a controller that holds no bindings of its own.
112    ///
113    /// This is the one to use. The host (or a `ViewportInstance`) owns the
114    /// [`ViewportInput`] that holds the bindings and resolves the frame; the
115    /// controller just applies the resulting [`ActionFrame`] to a camera through
116    /// [`apply`](Self::apply). Sensitivities stay on the controller.
117    pub fn new_stateless() -> Self {
118        Self::from_bindings(Vec::new())
119    }
120
121    /// Create a controller from the given binding preset.
122    ///
123    /// The preset seeds an internal resolver used only by the deprecated
124    /// event-driven methods ([`push_event`](Self::push_event) and
125    /// [`apply_to_camera`](Self::apply_to_camera)). **A session ignores it**:
126    /// `ViewportInstance` resolves with its own bindings and calls
127    /// [`apply`](Self::apply), so the preset chosen here has no effect there. Set the
128    /// scheme on the session instead, with `ViewportInstance::with_bindings`.
129    pub fn new(preset: BindingPreset) -> Self {
130        Self::from_bindings(preset_bindings(preset))
131    }
132
133    fn from_bindings(bindings: Vec<ViewportBinding>) -> Self {
134        Self {
135            input: ViewportInput::new(bindings),
136            navigation_mode: NavigationMode::Arcball,
137            fly_speed: Self::DEFAULT_FLY_SPEED,
138            fly_boost: Self::DEFAULT_FLY_BOOST,
139            orbit_sensitivity: Self::DEFAULT_ORBIT_SENSITIVITY,
140            zoom_sensitivity: Self::DEFAULT_ZOOM_SENSITIVITY,
141            gesture_sensitivity: Self::DEFAULT_GESTURE_SENSITIVITY,
142            viewport_size: [1.0, 1.0],
143            pivot: None,
144            written: None,
145        }
146    }
147
148    /// Create a controller seeded with the [`BindingPreset::Viewer`] scheme.
149    ///
150    /// The scheme has changed: left drag still orbits, but right drag no longer pans.
151    /// See [`new`](Self::new) for why a session ignores this.
152    pub fn viewer() -> Self {
153        Self::new(BindingPreset::Viewer)
154    }
155
156    /// Former name for [`viewer`](Self::viewer).
157    #[deprecated(
158        note = "renamed: use OrbitCameraController::viewer, or new_stateless if the host owns the resolver"
159    )]
160    pub fn viewport_primitives() -> Self {
161        Self::new(BindingPreset::Viewer)
162    }
163
164    /// Former name for `new(BindingPreset::Default)`, from when that preset was
165    /// called `ViewportAll`.
166    #[deprecated(
167        note = "renamed: use OrbitCameraController::new_stateless if a session or host owns the resolver, or new(BindingPreset::Default) for the standalone path"
168    )]
169    pub fn viewport_all() -> Self {
170        Self::new(BindingPreset::Default)
171    }
172
173    /// Begin a new frame.
174    ///
175    /// Resets per-frame accumulators and records viewport context (hover/focus
176    /// state and size). Call this at the **end** of each rendered frame : after
177    /// `apply_to_camera` : so the accumulator is ready for the next batch of
178    /// events.
179    ///
180    /// Also call once immediately after construction to prime the accumulator.
181    pub fn begin_frame(&mut self, ctx: ViewportContext) {
182        self.viewport_size = ctx.viewport_size;
183        self.input.begin_frame(ctx);
184    }
185
186    /// Record the viewport size used for pan when applying a frame through
187    /// [`apply`](Self::apply) without going through
188    /// [`begin_frame`](Self::begin_frame).
189    pub fn set_viewport_size(&mut self, viewport_size: [f32; 2]) {
190        self.viewport_size = viewport_size;
191    }
192
193    /// Push a single viewport-scoped event into the controller's own accumulator.
194    ///
195    /// Superseded: own a [`ViewportInput`] (or a `ViewportInstance`), push events
196    /// into that, and drive the camera with [`apply`](Self::apply). Bindings belong
197    /// to the resolver, and a controller holding a second one is how a session and a
198    /// controller end up disagreeing about the control scheme.
199    #[deprecated(
200        note = "own a ViewportInput and use OrbitCameraController::apply(&mut camera, &frame, dt)"
201    )]
202    pub fn push_event(&mut self, event: ViewportEvent) {
203        self.input.push_event(event);
204    }
205
206    /// Resolve accumulated events into an [`ActionFrame`] without applying any
207    /// camera navigation.
208    ///
209    /// Use this when the caller needs to inspect actions but camera movement
210    /// should be suppressed : for example during gizmo manipulation or fly mode
211    /// where the camera is driven by other logic.
212    pub fn resolve(&self) -> ActionFrame {
213        self.input.resolve()
214    }
215
216    /// Resolve accumulated events, apply camera navigation, and return the
217    /// [`ActionFrame`] for this frame.
218    ///
219    /// Call this in the render / update step, **before** `begin_frame` for the
220    /// next frame.
221    ///
222    /// The behavior of orbit drag depends on [`Self::navigation_mode`]:
223    /// - [`NavigationMode::Arcball`]: unconstrained arcball (default).
224    /// - [`NavigationMode::Turntable`]: yaw around world Z, pitch clamped to +/-89 deg.
225    /// - [`NavigationMode::Planar`]: pan only, orbit input is ignored.
226    /// - [`NavigationMode::Fly`]: mouselook + WASD translation. Requires
227    ///   the `Default` binding preset so that movement keys are resolved.
228    ///
229    /// Takes no frame time, so fly movement assumes 60 frames per second.
230    #[deprecated(
231        note = "own a ViewportInput and use OrbitCameraController::apply(&mut camera, &frame, dt)"
232    )]
233    pub fn apply_to_camera(&mut self, camera: &mut Camera) -> ActionFrame {
234        let frame = self.input.resolve();
235        self.apply(camera, &frame, 1.0 / 60.0);
236        frame
237    }
238
239    /// Orbit `camera` by a pointer delta in pixels, as a drag in the viewport
240    /// would: scaled by [`orbit_sensitivity`](Self::orbit_sensitivity) and
241    /// applied in [`navigation_mode`](Self::navigation_mode). Planar mode
242    /// ignores it.
243    ///
244    /// Use this for a drag the viewport did not see itself, such as a drag on
245    /// an orientation widget, so it moves the camera the same way a drag in the
246    /// scene does.
247    pub fn orbit_by(&mut self, camera: &mut Camera, delta: glam::Vec2) {
248        if delta == glam::Vec2::ZERO {
249            return;
250        }
251        let mut target = self.pivot(camera);
252        self.orbit_target_by(&mut target, delta);
253        self.write(camera, target);
254    }
255
256    /// The orbit centre, distance and orientation the controller last wrote,
257    /// or `None` before it has moved a camera.
258    pub fn target(&self) -> Option<CameraTarget> {
259        self.pivot
260    }
261
262    /// Read the pivot from `camera`'s focus point now rather than on the next
263    /// call that sees the camera has moved.
264    pub fn sync_from_camera(&mut self, camera: &Camera) {
265        self.pivot = Some(camera.orbit_target());
266        self.written = Some((camera.pose, camera.focus_distance()));
267    }
268
269    /// The pivot to work from: the controller's own, unless the camera has
270    /// moved since the controller last wrote it.
271    fn pivot(&mut self, camera: &Camera) -> CameraTarget {
272        let current = (camera.pose, camera.focus_distance());
273        match self.pivot {
274            Some(pivot) if self.written == Some(current) => pivot,
275            _ => {
276                self.sync_from_camera(camera);
277                camera.orbit_target()
278            }
279        }
280    }
281
282    fn write(&mut self, camera: &mut Camera, target: CameraTarget) {
283        camera.set_orbit_target(target);
284        self.pivot = Some(target);
285        self.written = Some((camera.pose, camera.focus_distance()));
286    }
287
288    fn orbit_target_by(&self, target: &mut CameraTarget, delta: glam::Vec2) {
289        if delta == glam::Vec2::ZERO {
290            return;
291        }
292        let yaw = delta.x * self.orbit_sensitivity;
293        let pitch = delta.y * self.orbit_sensitivity;
294        orbit_in_mode(target, self.navigation_mode, yaw, pitch);
295    }
296
297    /// Apply an already-resolved [`ActionFrame`] to the camera without draining
298    /// the event queue.
299    ///
300    /// Use this when the host owns a single [`ViewportInput`] resolver shared
301    /// across several controllers (orbit, first-person, third-person) and feeds
302    /// the same frame to whichever one is active.
303    /// [`apply_to_camera`](Self::apply_to_camera) is the convenience wrapper
304    /// that resolves and applies in one call.
305    ///
306    /// Pan needs the viewport height, read from the size recorded by the last
307    /// [`begin_frame`](Self::begin_frame) or
308    /// [`set_viewport_size`](Self::set_viewport_size).
309    ///
310    /// `dt` is the frame time in seconds. Only held input reads it: fly movement
311    /// in [`NavigationMode::Fly`]. Drags, the wheel and touch arrive as deltas
312    /// and move the camera the same at any frame rate.
313    pub fn apply(&mut self, camera: &mut Camera, frame: &ActionFrame, dt: f32) {
314        let nav = &frame.navigation;
315        let h = self.viewport_size[1];
316        let start = self.pivot(camera);
317        let mut t = start;
318        let gesture = nav.twist * self.gesture_sensitivity;
319        let pan = |t: &mut CameraTarget| {
320            if nav.pan != glam::Vec2::ZERO {
321                let scale = camera.view_height_at(t.distance) / h.max(1.0);
322                t.pan_world(nav.pan.x * scale, nav.pan.y * scale);
323            }
324        };
325        let zoom = |t: &mut CameraTarget| {
326            if nav.zoom != 0.0 {
327                t.zoom_by_factor(1.0 - nav.zoom * self.zoom_sensitivity);
328            }
329        };
330
331        match self.navigation_mode {
332            NavigationMode::Arcball => {
333                self.orbit_target_by(&mut t, nav.orbit);
334                if gesture != 0.0 {
335                    t.orbit(gesture, 0.0);
336                }
337                pan(&mut t);
338                zoom(&mut t);
339            }
340
341            NavigationMode::Turntable => {
342                self.orbit_target_by(&mut t, nav.orbit);
343                if gesture != 0.0 {
344                    // Gesture twist is yaw-only in turntable mode.
345                    apply_turntable(&mut t, gesture, 0.0);
346                }
347                pan(&mut t);
348                zoom(&mut t);
349            }
350
351            NavigationMode::Planar => {
352                // Orbit input is silently ignored; pan and zoom still work.
353                pan(&mut t);
354                zoom(&mut t);
355            }
356
357            NavigationMode::Fly => {
358                // Mouselook: drag rotates the view while the eye stays fixed.
359                self.orbit_target_by(&mut t, nav.orbit);
360                if gesture != 0.0 {
361                    apply_fly_look(&mut t, gesture, 0.0);
362                }
363
364                // WASD / QE translation in the view's own basis.
365                let q = t.orientation;
366                let forward = -(q * glam::Vec3::Z);
367                let wish = wish_from_actions(frame, forward, q * glam::Vec3::X, q * glam::Vec3::Y);
368                let speed = if frame.is_active(Action::FlySpeedBoost) {
369                    self.fly_speed * self.fly_boost
370                } else {
371                    self.fly_speed
372                };
373                // Translate the centre (and so the eye) without turning or zooming.
374                t.centre += (wish * speed * dt).as_dvec3();
375            }
376
377            // NavigationMode is non_exhaustive; no-op for modes not handled here.
378            _ => {}
379        }
380
381        if t != start {
382            self.write(camera, t);
383        }
384    }
385}
386
387// ---------------------------------------------------------------------------
388// Navigation mode helpers
389// ---------------------------------------------------------------------------
390
391/// Highest eye elevation, above or below the horizon, that turntable and fly
392/// look reach: just short of the poles, where yaw stops meaning anything.
393const POLE_LIMIT: f32 = 89.0 * std::f32::consts::PI / 180.0;
394
395/// Rotate an orbit view by `yaw` and `pitch` radians the way `mode` interprets
396/// an orbit drag. Planar ignores it.
397///
398/// The one rotation path for the orbit controller and for a
399/// [`CameraAnimator`](crate::controllers::CameraAnimator) coasting in a mode, so
400/// a coast after a drag turns the camera the way the drag did.
401pub(crate) fn orbit_in_mode(target: &mut CameraTarget, mode: NavigationMode, yaw: f32, pitch: f32) {
402    match mode {
403        NavigationMode::Arcball => target.orbit(yaw, pitch),
404        NavigationMode::Turntable => apply_turntable(target, yaw, pitch),
405        NavigationMode::Fly => apply_fly_look(target, yaw, pitch),
406        // Planar ignores orbit; NavigationMode is non_exhaustive.
407        _ => {}
408    }
409}
410
411/// Apply a turntable yaw + clamped pitch to an orbit view.
412///
413/// Yaw rotates around world Z. Pitch changes elevation in camera-local space,
414/// stopping at [`POLE_LIMIT`] above or below the XY plane. A step that would
415/// cross the limit takes the part of it that reaches the limit, so a fast drag
416/// ends at the limit rather than short of it, and a step that starts past the
417/// limit can still come back toward the horizon.
418fn apply_turntable(view: &mut CameraTarget, yaw: f32, pitch: f32) {
419    // Yaw: pre-multiply by a world-Z rotation (same as the yaw component of Camera::orbit).
420    if yaw != 0.0 {
421        view.orientation = (glam::Quat::from_rotation_z(-yaw) * view.orientation).normalize();
422    }
423
424    if pitch != 0.0 {
425        // Elevation of the eye above the XY plane: the eye direction is
426        // `orientation * Z`, and its z-component is the sine of the elevation.
427        let elevation = |q: glam::Quat| (q * glam::Vec3::Z).z.clamp(-1.0, 1.0).asin();
428        let pitched =
429            |amount: f32| (view.orientation * glam::Quat::from_rotation_x(-amount)).normalize();
430
431        // How fast elevation moves per radian of pitch, from a small probe step:
432        // +/-1 when the camera carries no roll, less when it does. Working from the
433        // rate rather than the end orientation keeps a step large enough to pass
434        // over the pole from looking like a small one.
435        const PROBE: f32 = 1e-3;
436        let current = elevation(view.orientation);
437        let rate = (elevation(pitched(PROBE)) - current) / PROBE;
438        if rate.abs() < 1e-3 {
439            // Rolled on its side: pitch does not move the elevation.
440            view.orientation = pitched(pitch);
441            return;
442        }
443
444        let target = current + rate * pitch;
445        if target.abs() <= POLE_LIMIT {
446            view.orientation = pitched(pitch);
447        } else if target.abs() > current.abs() && current.abs() >= POLE_LIMIT {
448            // Already at or past the limit and heading further out.
449        } else {
450            view.orientation = pitched((POLE_LIMIT.copysign(target) - current) / rate);
451        }
452    }
453}
454
455/// Apply mouselook (yaw + pitch) while keeping the camera eye position fixed.
456///
457/// Yaw turns around world Z and pitch tilts the view, held to [`POLE_LIMIT`]
458/// so the view cannot go over the top and roll. Roll the camera carried in from
459/// another mode is levelled out. The orbit centre moves so the eye stays put.
460fn apply_fly_look(view: &mut CameraTarget, yaw: f32, pitch: f32) {
461    let eye = view.eye();
462    // A positive pitch delta is a downward drag, which looks down.
463    let look = LookAngles::from_orientation(view.orientation)
464        .turned(yaw, -pitch)
465        .with_pitch_clamped(-POLE_LIMIT, POLE_LIMIT);
466    view.orientation = look.orientation();
467    view.centre = eye + (look.direction() * view.distance).as_dvec3();
468}
469
470#[cfg(test)]
471mod tests {
472    use super::*;
473    use crate::input::binding::KeyCode;
474    use glam::DVec3;
475
476    fn camera_facing(orientation: glam::Quat) -> Camera {
477        Camera::orbit(DVec3::ZERO, 5.0, orientation)
478    }
479
480    fn default_target() -> CameraTarget {
481        Camera::default().orbit_target()
482    }
483    use crate::input::event::{ButtonState, ScrollUnits, ViewportEvent};
484
485    fn make_ctx() -> ViewportContext {
486        ViewportContext::new(crate::input::InputOwnership::full_window(), [800.0, 600.0])
487    }
488
489    #[test]
490    fn new_defaults() {
491        let ctrl = OrbitCameraController::viewport_primitives();
492        assert_eq!(ctrl.navigation_mode, NavigationMode::Arcball);
493        assert!((ctrl.fly_speed - OrbitCameraController::DEFAULT_FLY_SPEED).abs() < 1e-6);
494        assert!(
495            (ctrl.orbit_sensitivity - OrbitCameraController::DEFAULT_ORBIT_SENSITIVITY).abs()
496                < 1e-6
497        );
498    }
499
500    #[test]
501    fn resolve_no_events_zero_nav() {
502        let mut ctrl = OrbitCameraController::new(BindingPreset::Default);
503        ctrl.begin_frame(make_ctx());
504        let frame = ctrl.resolve();
505        assert_eq!(frame.navigation.orbit, glam::Vec2::ZERO);
506        assert_eq!(frame.navigation.pan, glam::Vec2::ZERO);
507        assert_eq!(frame.navigation.zoom, 0.0);
508    }
509
510    #[test]
511    fn apply_zoom_changes_distance() {
512        let mut ctrl = OrbitCameraController::viewport_primitives();
513        ctrl.begin_frame(make_ctx());
514        let mut cam = Camera::default();
515        let d0 = cam.focus_distance();
516        ctrl.push_event(ViewportEvent::Wheel {
517            delta: glam::Vec2::new(0.0, 100.0),
518            units: ScrollUnits::Pixels,
519        });
520        ctrl.apply_to_camera(&mut cam);
521        assert!(
522            (cam.focus_distance() - d0).abs() > 1e-4,
523            "zoom should change camera distance"
524        );
525    }
526
527    #[test]
528    fn orbit_by_matches_a_drag_in_every_mode() {
529        let delta = glam::Vec2::new(37.0, -21.0);
530        let mut frame = ActionFrame::default();
531        frame.navigation.orbit = delta;
532        let start =
533            || camera_facing(glam::Quat::from_rotation_z(0.7) * glam::Quat::from_rotation_x(0.9));
534        for mode in [
535            NavigationMode::Arcball,
536            NavigationMode::Turntable,
537            NavigationMode::Fly,
538            NavigationMode::Planar,
539        ] {
540            let mut ctrl = OrbitCameraController::viewer();
541            ctrl.navigation_mode = mode;
542            let mut by_drag = start();
543            ctrl.apply(&mut by_drag, &frame, 1.0 / 60.0);
544            let mut by_call = start();
545            ctrl.orbit_by(&mut by_call, delta);
546            assert!(
547                by_drag.orientation().angle_between(by_call.orientation()) < 1e-5,
548                "{mode:?}: orientation differs"
549            );
550            assert!(
551                (by_drag.target() - by_call.target()).length() < 1e-4,
552                "{mode:?}: centre differs"
553            );
554            match mode {
555                NavigationMode::Planar => assert_eq!(by_call.orientation(), start().orientation()),
556                // Mouselook keeps the eye still, so the centre moves: proof the
557                // mode's own rotation ran rather than the arcball one.
558                NavigationMode::Fly => {
559                    assert!((by_call.target() - start().target()).length() > 1e-3)
560                }
561                _ => assert!(by_call.orientation().angle_between(start().orientation()) > 1e-3),
562            }
563        }
564    }
565
566    #[test]
567    fn planar_mode_ignores_orbit() {
568        let mut ctrl = OrbitCameraController::viewport_primitives();
569        ctrl.navigation_mode = NavigationMode::Planar;
570        ctrl.begin_frame(make_ctx());
571        let mut cam = Camera::default();
572        let orient_before = cam.orientation();
573        // Simulate a left-drag (orbit gesture in primitives preset)
574        ctrl.push_event(ViewportEvent::PointerMoved {
575            position: glam::Vec2::new(100.0, 100.0),
576        });
577        ctrl.push_event(ViewportEvent::MouseButton {
578            button: crate::input::binding::MouseButton::Left,
579            state: ButtonState::Pressed,
580        });
581        ctrl.push_event(ViewportEvent::PointerMoved {
582            position: glam::Vec2::new(200.0, 200.0),
583        });
584        ctrl.apply_to_camera(&mut cam);
585        let after = cam.orientation();
586        assert!(
587            (after.x - orient_before.x).abs() < 1e-6
588                && (after.y - orient_before.y).abs() < 1e-6
589                && (after.z - orient_before.z).abs() < 1e-6
590                && (after.w - orient_before.w).abs() < 1e-6,
591            "planar mode should not change orientation"
592        );
593    }
594
595    #[test]
596    fn turntable_pitch_clamped() {
597        let mut cam = default_target();
598        // Try to apply extreme pitch
599        for _ in 0..1000 {
600            apply_turntable(&mut cam, 0.0, 0.1);
601        }
602        // Check eye direction Z component stays within sin(89 deg)
603        let eye_z = (cam.orientation * glam::Vec3::Z).z;
604        let max_sin = 89.0_f32.to_radians().sin();
605        assert!(
606            eye_z.abs() <= max_sin + 1e-4,
607            "turntable pitch should be clamped: eye_z={eye_z}"
608        );
609    }
610
611    #[test]
612    fn fly_look_preserves_eye() {
613        let mut cam = default_target();
614        let eye_before = cam.eye();
615        apply_fly_look(&mut cam, 0.3, 0.2);
616        let eye_after = cam.eye();
617        let diff = (eye_after - eye_before).length();
618        assert!(
619            diff < 1e-3,
620            "firstperson look should preserve eye position, diff={diff}"
621        );
622    }
623
624    #[test]
625    fn fly_moves_camera() {
626        let mut ctrl = OrbitCameraController::new(BindingPreset::Default);
627        ctrl.navigation_mode = NavigationMode::Fly;
628        // The deprecated path assumes 60 Hz: 60 units per second is 1 per frame.
629        ctrl.fly_speed = 60.0;
630        ctrl.begin_frame(make_ctx());
631        let mut cam = camera_facing(glam::Quat::IDENTITY);
632        let centre_before = cam.target();
633        ctrl.push_event(ViewportEvent::Key {
634            key: KeyCode::W,
635            state: ButtonState::Pressed,
636            repeat: false,
637            logical: None,
638        });
639        ctrl.apply_to_camera(&mut cam);
640        assert!(
641            (cam.target() - centre_before).length() > 0.5,
642            "FlyForward should move camera centre"
643        );
644    }
645
646    #[test]
647    fn apply_consumes_external_frame() {
648        // The frame-consumer path applies an already-resolved ActionFrame
649        // without draining events, the basis for sharing one resolver across
650        // the controller family.
651        let mut ctrl = OrbitCameraController::viewport_primitives();
652        let mut cam = Camera::default();
653        let before = cam.orientation();
654        let mut frame = ActionFrame::default();
655        frame.navigation.orbit = glam::Vec2::new(20.0, 0.0);
656        ctrl.apply(&mut cam, &frame, 1.0 / 60.0);
657        assert_ne!(
658            cam.orientation(),
659            before,
660            "apply(&frame) should orbit from the frame's nav delta"
661        );
662    }
663
664    #[test]
665    fn pivot_follows_a_camera_moved_elsewhere() {
666        let mut ctrl = OrbitCameraController::new_stateless();
667        let mut cam = Camera::default();
668        let mut frame = ActionFrame::default();
669        frame.navigation.orbit = glam::Vec2::new(10.0, 0.0);
670        ctrl.apply(&mut cam, &frame, 1.0 / 60.0);
671        assert_eq!(ctrl.target().unwrap().centre, DVec3::ZERO);
672
673        // A preset or fly-to moves the camera; the next drag orbits about the
674        // new focus point at the new distance.
675        let centre = DVec3::new(10.0, -3.0, 2.0);
676        cam = Camera::orbit(centre, 4.0, cam.orientation());
677        ctrl.apply(&mut cam, &frame, 1.0 / 60.0);
678        assert!((cam.target() - centre).length() < 1e-4);
679        assert_eq!(cam.focus_distance(), 4.0);
680        assert_eq!(ctrl.target().unwrap().centre, centre);
681    }
682
683    #[test]
684    fn no_input_leaves_the_camera_alone() {
685        let mut ctrl = OrbitCameraController::new_stateless();
686        let mut cam = Camera::default();
687        cam.set_orthographic(true);
688        let before = cam.clone();
689        ctrl.apply(&mut cam, &ActionFrame::default(), 1.0 / 60.0);
690        assert_eq!(cam, before);
691    }
692
693    #[test]
694    fn zoom_scales_an_orthographic_view() {
695        let mut ctrl = OrbitCameraController::new_stateless();
696        let mut cam = Camera::default();
697        cam.set_orthographic(true);
698        let height = cam.view_height_at(1.0);
699        let mut frame = ActionFrame::default();
700        frame.navigation.zoom = 500.0;
701        ctrl.apply(&mut cam, &frame, 1.0 / 60.0);
702        let ratio = cam.focus_distance() / 5.0;
703        assert!(ratio < 1.0);
704        assert!((cam.view_height_at(1.0) - height * ratio).abs() < 1e-4);
705    }
706
707    fn fly_frame(actions: &[Action]) -> ActionFrame {
708        let mut frame = ActionFrame::default();
709        for &a in actions {
710            frame
711                .actions
712                .insert(a, crate::input::action_frame::ResolvedActionState::Held);
713        }
714        frame
715    }
716
717    fn fly_controller() -> OrbitCameraController {
718        let mut ctrl = OrbitCameraController::new_stateless();
719        ctrl.navigation_mode = NavigationMode::Fly;
720        ctrl.fly_speed = 1.0;
721        ctrl
722    }
723
724    #[test]
725    fn fly_diagonal_moves_as_far_as_straight() {
726        let mut ctrl = fly_controller();
727        let level = LookAngles::FORWARD.orientation();
728        let mut moved = |actions: &[Action]| {
729            let mut cam = camera_facing(level);
730            let before = cam.target();
731            ctrl.apply(&mut cam, &fly_frame(actions), 1.0);
732            (cam.target() - before).length()
733        };
734        let straight = moved(&[Action::FlyForward]);
735        let diagonal = moved(&[Action::FlyForward, Action::FlyRight]);
736        let three = moved(&[Action::FlyForward, Action::FlyRight, Action::FlyUp]);
737        assert!((straight - 1.0).abs() < 1e-5);
738        assert!((diagonal - straight).abs() < 1e-5, "diagonal={diagonal}");
739        assert!((three - straight).abs() < 1e-5, "three axes={three}");
740    }
741
742    #[test]
743    fn fly_look_stops_short_of_vertical() {
744        let mut cam = default_target();
745        cam.orientation = LookAngles::FORWARD.orientation();
746        // Drag up a long way: negative pitch delta looks up.
747        for _ in 0..200 {
748            apply_fly_look(&mut cam, 0.0, -0.1);
749        }
750        let look = LookAngles::from_orientation(cam.orientation);
751        assert!(
752            (look.pitch - POLE_LIMIT).abs() < 1e-3,
753            "pitch={}",
754            look.pitch
755        );
756        // No roll: the camera's right vector stays level.
757        assert!((cam.orientation * glam::Vec3::X).z.abs() < 1e-4);
758    }
759
760    #[test]
761    fn fly_look_matches_the_old_turn_directions() {
762        let mut cam = default_target();
763        cam.orientation = LookAngles::FORWARD.orientation();
764        apply_fly_look(&mut cam, 0.2, 0.1);
765        let look = LookAngles::from_orientation(cam.orientation);
766        // Positive yaw turns right, a positive (downward) pitch delta looks down.
767        assert!(look.yaw > 0.0 && look.pitch < 0.0, "{look:?}");
768    }
769
770    #[test]
771    fn turntable_fast_step_reaches_the_limit() {
772        let mut cam = default_target();
773        cam.orientation = LookAngles::FORWARD.orientation();
774        // One step far past the limit lands on it instead of being dropped.
775        apply_turntable(&mut cam, 0.0, 2.0);
776        let eye_elevation = (cam.orientation * glam::Vec3::Z).z.asin();
777        assert!(
778            (eye_elevation.abs() - POLE_LIMIT).abs() < 1e-3,
779            "elevation={eye_elevation}"
780        );
781    }
782
783    #[test]
784    fn turntable_can_back_away_from_past_the_limit() {
785        let mut cam = default_target();
786        // Arcball left the eye past the limit, looking almost straight down.
787        cam.orientation = LookAngles::new(0.0, -1.565).orientation();
788        let before = (cam.orientation * glam::Vec3::Z).z;
789        // A drag further over the top does nothing.
790        apply_turntable(&mut cam, 0.0, 0.01);
791        assert!(((cam.orientation * glam::Vec3::Z).z - before).abs() < 1e-6);
792        // A drag back toward the horizon applies.
793        apply_turntable(&mut cam, 0.0, -0.01);
794        let after = (cam.orientation * glam::Vec3::Z).z;
795        assert!(after < before, "before={before} after={after}");
796    }
797
798    #[test]
799    fn fly_speed_is_per_second() {
800        let mut ctrl = fly_controller();
801        let mut moved = |dt: f32, frames: usize| {
802            let mut cam = camera_facing(LookAngles::FORWARD.orientation());
803            let before = cam.target();
804            for _ in 0..frames {
805                ctrl.apply(&mut cam, &fly_frame(&[Action::FlyForward]), dt);
806            }
807            (cam.target() - before).length()
808        };
809        // One second at 30, 60 and 144 Hz covers the same ground.
810        for (dt, frames) in [(1.0 / 30.0, 30), (1.0 / 60.0, 60), (1.0 / 144.0, 144)] {
811            assert!((moved(dt, frames) - 1.0).abs() < 1e-3, "dt={dt}");
812        }
813    }
814
815    #[test]
816    fn fly_boost_multiplies_speed() {
817        let mut ctrl = fly_controller();
818        let mut cam = camera_facing(LookAngles::FORWARD.orientation());
819        let before = cam.target();
820        ctrl.apply(
821            &mut cam,
822            &fly_frame(&[Action::FlyForward, Action::FlySpeedBoost]),
823            1.0,
824        );
825        let moved = (cam.target() - before).length();
826        assert!(
827            (moved - f64::from(ctrl.fly_boost)).abs() < 1e-5,
828            "moved={moved}"
829        );
830    }
831
832    #[test]
833    fn shift_resolves_to_fly_speed_boost() {
834        use crate::input::binding::Modifiers;
835        let mut input = ViewportInput::new(crate::input::viewport_default_bindings());
836        input.begin_frame(make_ctx());
837        input.push_event(ViewportEvent::ModifiersChanged(Modifiers::SHIFT));
838        assert!(input.resolve().is_active(Action::FlySpeedBoost));
839        input.push_event(ViewportEvent::ModifiersChanged(Modifiers::NONE));
840        assert!(!input.resolve().is_active(Action::FlySpeedBoost));
841    }
842}