Skip to main content

voxel_framework/player/
camera_response.rs

1//! Camera response to player movement: a speed-based field-of-view boost and
2//! a lean (roll) toward sideways movement.
3//!
4//! Both effects are configured by [`CameraResponseConfig`] and are neutral by
5//! default: with the default resource the player's [`Transform`] and
6//! [`Projection`] are never written by this module.
7//!
8//! # How it composes with the player systems
9//!
10//! The camera entity is the player, so its rotation is also the player's
11//! orientation (movement axes, collision capsule, snap roll). The lean is
12//! therefore applied only between frames:
13//!
14//! ```text
15//! camera_response_restore → player_look → player_move → player_resolve_collision
16//!     → … → camera_response_apply
17//! ```
18//!
19//! [`camera_response_restore`] removes last frame's lean before any player
20//! system reads the rotation, and [`camera_response_apply`] adds the new lean
21//! after they ran. The lean is a rotation around the camera's local Z axis, so
22//! the view direction (`Transform::forward`) is never changed by it; only
23//! `up` and `right` are tilted for systems that read the transform outside
24//! this window.
25//!
26//! The field of view is composed with whatever value the [`Projection`]
27//! holds: the value found there is taken as the base, and a value written by
28//! anything else later (a settings menu, for example) becomes the new base.
29//! [`CameraResponse::base_fov_radians`] returns the base without the boost.
30//!
31//! While [`PauseMenuState`] is registered and not `Playing`, and while
32//! [`CameraResponseConfig::enabled`] is `false`, the camera is put back to
33//! its base field of view and unleaned orientation.
34
35use bevy::prelude::*;
36
37use super::Player;
38use crate::ui::PauseMenuState;
39
40/// Smallest field of view, in radians, that a boost may produce (1°).
41const MIN_BOOSTED_FOV: f32 = std::f32::consts::PI / 180.0;
42
43/// Largest field of view, in radians, that a boost may produce (179°).
44const MAX_BOOSTED_FOV: f32 = std::f32::consts::PI * 179.0 / 180.0;
45
46/// Largest lean, in degrees, in either direction.
47const MAX_LEAN_DEGREES: f32 = 89.0;
48
49/// Difference below which a smoothed value lands exactly on its target.
50const SMOOTHING_EPSILON: f32 = 1.0e-5;
51
52/// How the player camera responds to movement.
53///
54/// [`PlayerPlugin`](super::PlayerPlugin) initializes this resource with the
55/// defaults, which are neutral: no field-of-view change and no lean. Insert
56/// your own value to turn the effects on, and flip
57/// [`enabled`](Self::enabled) at runtime (for example from an accessibility
58/// setting) to turn them off without losing the tuned values:
59///
60/// ```rust,no_run
61/// use bevy::prelude::*;
62/// use voxel_framework::prelude::*;
63///
64/// App::new()
65///     .add_plugins(PlayerPlugin::<DefaultVoxel>::new())
66///     .insert_resource(CameraResponseConfig {
67///         fov_boost_degrees: 6.0,
68///         lean_degrees: 2.0,
69///         smoothing_seconds: 0.15,
70///         ..default()
71///     });
72/// ```
73///
74/// The values are read every frame.
75#[derive(Resource, Debug, Clone, Copy, PartialEq)]
76pub struct CameraResponseConfig {
77    /// Master switch. When `false` the camera returns to its base field of
78    /// view and unleaned orientation on the next frame, without smoothing.
79    /// Default `true` (the amounts below default to zero, so the default
80    /// configuration still does nothing).
81    pub enabled: bool,
82    /// Degrees added to the vertical field of view when the player moves at
83    /// the reference speed or faster; scaled linearly below it. Negative
84    /// values narrow the view. The resulting field of view is kept between 1°
85    /// and 179°. A non-finite value counts as `0.0`. Default `0.0`.
86    pub fov_boost_degrees: f32,
87    /// Degrees the camera rolls toward sideways movement when the player
88    /// strafes at the reference speed or faster; scaled linearly below it.
89    /// Negative values lean away from the movement. Limited to ±89°. A
90    /// non-finite value counts as `0.0`. Default `0.0`.
91    pub lean_degrees: f32,
92    /// Time constant, in seconds, with which both effects follow their
93    /// target: after this long about 63% of a change has been applied. `0.0`
94    /// (the default), a negative or a non-finite value follows the target
95    /// instantly, which still is as smooth as the player's own acceleration.
96    pub smoothing_seconds: f32,
97    /// Speed, in world units per second, at which the effects reach their
98    /// full amount. `None` (the default), or a value that is not positive and
99    /// finite, uses [`Player::speed`]. Set it above the base speed when a
100    /// faster state (such as grounded sprinting) should be told apart.
101    pub reference_speed: Option<f32>,
102}
103
104impl Default for CameraResponseConfig {
105    fn default() -> Self {
106        Self {
107            enabled: true,
108            fov_boost_degrees: 0.0,
109            lean_degrees: 0.0,
110            smoothing_seconds: 0.0,
111            reference_speed: None,
112        }
113    }
114}
115
116impl CameraResponseConfig {
117    /// Field-of-view boost at full speed, in radians (`0.0` when not finite).
118    fn fov_boost_radians(&self) -> f32 {
119        if self.fov_boost_degrees.is_finite() {
120            self.fov_boost_degrees.to_radians()
121        } else {
122            0.0
123        }
124    }
125
126    /// Lean at full sideways speed, in radians (`0.0` when not finite).
127    fn lean_radians(&self) -> f32 {
128        if self.lean_degrees.is_finite() {
129            self.lean_degrees
130                .clamp(-MAX_LEAN_DEGREES, MAX_LEAN_DEGREES)
131                .to_radians()
132        } else {
133            0.0
134        }
135    }
136
137    /// Whether this configuration can change the camera at all.
138    fn has_effect(&self) -> bool {
139        self.enabled && (self.fov_boost_radians() != 0.0 || self.lean_radians() != 0.0)
140    }
141
142    /// The configured reference speed, or `player_speed` when unset or invalid.
143    fn reference_speed_or(&self, player_speed: f32) -> f32 {
144        self.reference_speed
145            .filter(|speed| speed.is_finite() && *speed > 0.0)
146            .unwrap_or(player_speed)
147    }
148}
149
150/// A lean currently baked into the player's rotation.
151#[derive(Debug, Clone, Copy, PartialEq)]
152struct AppliedLean {
153    /// Rotation around local Z that was applied, in radians.
154    angle: f32,
155    /// Rotation before the lean was applied.
156    base_rotation: Quat,
157    /// Rotation after the lean was applied.
158    leaned_rotation: Quat,
159}
160
161/// Runtime state of the camera response, stored on the player entity.
162///
163/// [`camera_response_apply`] inserts it the first time a non-neutral
164/// [`CameraResponseConfig`] is active. A game only needs it to read the
165/// current values, for example to show the base field of view in its own
166/// settings screen.
167#[derive(Component, Debug, Clone, Default, PartialEq)]
168pub struct CameraResponse {
169    fov_boost: f32,
170    lean: f32,
171    applied_lean: Option<AppliedLean>,
172    base_fov: Option<f32>,
173    written_fov: Option<f32>,
174}
175
176impl CameraResponse {
177    /// Field-of-view boost currently requested, in radians (after smoothing,
178    /// before the 1°–179° limit on the resulting field of view).
179    pub fn fov_boost_radians(&self) -> f32 {
180        self.fov_boost
181    }
182
183    /// Lean currently applied, in radians, in the
184    /// [`Transform::rotate_local_z`] convention: negative leans to the right.
185    pub fn lean_radians(&self) -> f32 {
186        self.lean
187    }
188
189    /// The field of view without the boost, in radians, as last seen on the
190    /// player's perspective [`Projection`]. `None` until the response first
191    /// ran on a perspective camera.
192    pub fn base_fov_radians(&self) -> Option<f32> {
193        self.base_fov
194    }
195
196    /// Whether nothing of the response is currently applied to the camera.
197    fn is_neutral(&self) -> bool {
198        self.fov_boost == 0.0
199            && self.lean == 0.0
200            && self.applied_lean.is_none()
201            && self.written_fov == self.base_fov
202    }
203}
204
205// ─── Pure math ───────────────────────────────────────────────────────────────
206
207/// Fraction of the reference speed the player is moving at, in `[0, 1]`.
208///
209/// Returns `0.0` when `reference_speed` is not positive and finite or the
210/// velocity is not finite.
211pub(crate) fn speed_fraction(velocity: Vec3, reference_speed: f32) -> f32 {
212    if !(reference_speed.is_finite() && reference_speed > 0.0) || !velocity.is_finite() {
213        return 0.0;
214    }
215    (velocity.length() / reference_speed).clamp(0.0, 1.0)
216}
217
218/// Signed fraction of the reference speed the player is moving sideways at,
219/// in `[-1, 1]`; positive is toward `right`.
220///
221/// Returns `0.0` when `reference_speed` is not positive and finite or an
222/// input is not finite.
223pub(crate) fn lateral_fraction(velocity: Vec3, right: Vec3, reference_speed: f32) -> f32 {
224    if !(reference_speed.is_finite() && reference_speed > 0.0)
225        || !velocity.is_finite()
226        || !right.is_finite()
227    {
228        return 0.0;
229    }
230    (velocity.dot(right) / reference_speed).clamp(-1.0, 1.0)
231}
232
233/// Field-of-view boost, in radians, for a speed fraction in `[0, 1]`.
234pub(crate) fn fov_boost_target(config: &CameraResponseConfig, speed_fraction: f32) -> f32 {
235    config.fov_boost_radians() * speed_fraction.clamp(0.0, 1.0)
236}
237
238/// Lean, in radians, for a lateral fraction in `[-1, 1]`.
239///
240/// The result follows the [`Transform::rotate_local_z`] convention, in which
241/// a positive angle rolls to the left, so moving right with a positive
242/// [`CameraResponseConfig::lean_degrees`] gives a negative angle.
243pub(crate) fn lean_target(config: &CameraResponseConfig, lateral_fraction: f32) -> f32 {
244    -config.lean_radians() * lateral_fraction.clamp(-1.0, 1.0)
245}
246
247/// Moves `current` toward `target` with an exponential time constant.
248///
249/// A `smoothing_seconds` that is not positive and finite returns `target`.
250/// Otherwise the remaining difference shrinks by `exp(-dt / smoothing_seconds)`,
251/// which is independent of the frame rate, and lands exactly on `target` once
252/// closer than a small epsilon.
253pub(crate) fn smooth_toward(current: f32, target: f32, smoothing_seconds: f32, dt: f32) -> f32 {
254    if !(smoothing_seconds.is_finite() && smoothing_seconds > 0.0) || !current.is_finite() {
255        return target;
256    }
257    if !(dt.is_finite() && dt > 0.0) {
258        return current;
259    }
260    let next = target + (current - target) * (-dt / smoothing_seconds).exp();
261    if (next - target).abs() < SMOOTHING_EPSILON {
262        target
263    } else {
264        next
265    }
266}
267
268/// The base field of view given the value currently on the projection.
269///
270/// If the projection still holds what the response wrote last
271/// (`written == Some(current)`), the remembered `base` stands. Any other
272/// value was written by something else and becomes the new base.
273pub(crate) fn resolve_base_fov(current: f32, written: Option<f32>, base: Option<f32>) -> f32 {
274    match (written, base) {
275        (Some(written), Some(base)) if written == current => base,
276        _ => current,
277    }
278}
279
280/// The field of view to write for a base value and a boost, both in radians.
281///
282/// A zero boost returns `base` untouched; otherwise the sum is kept between
283/// 1° and 179°.
284pub(crate) fn boosted_fov(base: f32, boost: f32) -> f32 {
285    if boost == 0.0 {
286        base
287    } else {
288        (base + boost).clamp(MIN_BOOSTED_FOV, MAX_BOOSTED_FOV)
289    }
290}
291
292/// The rotation with an applied lean removed.
293///
294/// When `current` is exactly the rotation the response wrote, the stored
295/// base rotation is returned, so applying and removing the lean every frame
296/// accumulates no error. When something else rotated the camera in between,
297/// the lean angle is rotated back out around the current local Z axis.
298fn unleaned_rotation(current: Quat, applied: AppliedLean) -> Quat {
299    if current == applied.leaned_rotation {
300        applied.base_rotation
301    } else {
302        (current * Quat::from_rotation_z(-applied.angle)).normalize()
303    }
304}
305
306// ─── Systems ─────────────────────────────────────────────────────────────────
307
308/// Removes the lean that [`camera_response_apply`] added on the previous
309/// frame, so the other player systems see the player's own orientation.
310///
311/// Must run before [`player_look`](super::player_look).
312/// [`PlayerPlugin`](super::PlayerPlugin) schedules it there. It does nothing
313/// when no lean is applied.
314pub fn camera_response_restore(
315    mut query: Query<(&mut Transform, &mut CameraResponse), With<Player>>,
316) {
317    let Ok((mut transform, mut state)) = query.single_mut() else {
318        return;
319    };
320    if state.applied_lean.is_none() {
321        return;
322    }
323    if let Some(applied) = state.applied_lean.take() {
324        let rotation = unleaned_rotation(transform.rotation, applied);
325        transform.rotation = rotation;
326    }
327}
328
329/// Applies the speed-based field-of-view boost and the lean configured by
330/// [`CameraResponseConfig`] to the player camera.
331///
332/// Must run after the player's look, movement and collision systems.
333/// [`PlayerPlugin`](super::PlayerPlugin) schedules it after them and, unlike
334/// those, keeps it running while the pause menu is open, where it puts the
335/// camera back to its base field of view and orientation. Without the
336/// resource, or with its default value, the system changes nothing.
337///
338/// The speed is the length of [`Player::velocity`]; in
339/// [`PlayerMode::Grounded`](super::PlayerMode::Grounded) that is the
340/// horizontal velocity, so falling does not widen the view.
341pub fn camera_response_apply(
342    mut commands: Commands,
343    mut query: Query<(
344        Entity,
345        &Player,
346        &mut Transform,
347        Option<&mut Projection>,
348        Option<&mut CameraResponse>,
349    )>,
350    config: Option<Res<CameraResponseConfig>>,
351    time: Res<Time>,
352    pause: Option<Res<State<PauseMenuState>>>,
353) {
354    let Ok((entity, player, mut transform, projection, state)) = query.single_mut() else {
355        return;
356    };
357    let config = config.as_deref().copied().unwrap_or_default();
358    let playing = pause.map_or(true, |s| matches!(s.get(), PauseMenuState::Playing));
359    let active = config.enabled && playing;
360    let wants_effect = active && config.has_effect();
361
362    let Some(mut state) = state else {
363        if wants_effect {
364            commands.entity(entity).insert(CameraResponse::default());
365        }
366        return;
367    };
368    if !wants_effect && state.is_neutral() {
369        return;
370    }
371
372    // Take out the previous lean first: the new one is measured against the
373    // player's own orientation.
374    if let Some(applied) = state.applied_lean.take() {
375        let rotation = unleaned_rotation(transform.rotation, applied);
376        transform.rotation = rotation;
377    }
378
379    let (fov_boost, lean) = if active {
380        let reference = config.reference_speed_or(player.speed);
381        let right = transform.rotation * Vec3::X;
382        let fov_target = fov_boost_target(&config, speed_fraction(player.velocity, reference));
383        let lean_goal = lean_target(&config, lateral_fraction(player.velocity, right, reference));
384        let dt = time.delta_secs();
385        (
386            smooth_toward(state.fov_boost, fov_target, config.smoothing_seconds, dt),
387            smooth_toward(state.lean, lean_goal, config.smoothing_seconds, dt),
388        )
389    } else {
390        (0.0, 0.0)
391    };
392    state.fov_boost = fov_boost;
393    state.lean = lean;
394
395    if lean != 0.0 {
396        let base_rotation = transform.rotation;
397        let leaned_rotation = (base_rotation * Quat::from_rotation_z(lean)).normalize();
398        transform.rotation = leaned_rotation;
399        state.applied_lean = Some(AppliedLean {
400            angle: lean,
401            base_rotation,
402            leaned_rotation,
403        });
404    }
405
406    if let Some(mut projection) = projection {
407        let current = match &*projection {
408            Projection::Perspective(perspective) => Some(perspective.fov),
409            _ => None,
410        };
411        if let Some(current) = current {
412            let base = resolve_base_fov(current, state.written_fov, state.base_fov);
413            let fov = boosted_fov(base, fov_boost);
414            state.base_fov = Some(base);
415            state.written_fov = Some(fov);
416            if fov != current {
417                if let Projection::Perspective(perspective) = &mut *projection {
418                    perspective.fov = fov;
419                }
420            }
421        }
422    }
423}
424
425// ─── Tests ───────────────────────────────────────────────────────────────────
426
427#[cfg(test)]
428mod tests {
429    use super::*;
430    use bevy::ecs::system::RunSystemOnce;
431
432    fn config(fov: f32, lean: f32) -> CameraResponseConfig {
433        CameraResponseConfig {
434            fov_boost_degrees: fov,
435            lean_degrees: lean,
436            ..default()
437        }
438    }
439
440    fn approx(a: f32, b: f32) -> bool {
441        (a - b).abs() < 1.0e-4
442    }
443
444    #[test]
445    fn default_config_is_neutral() {
446        let c = CameraResponseConfig::default();
447        assert!(c.enabled);
448        assert_eq!(c.fov_boost_degrees, 0.0);
449        assert_eq!(c.lean_degrees, 0.0);
450        assert_eq!(c.smoothing_seconds, 0.0);
451        assert_eq!(c.reference_speed, None);
452        assert!(!c.has_effect());
453    }
454
455    #[test]
456    fn disabled_or_non_finite_config_has_no_effect() {
457        let mut c = config(6.0, 2.0);
458        assert!(c.has_effect());
459        c.enabled = false;
460        assert!(!c.has_effect());
461        assert!(!config(f32::NAN, f32::INFINITY).has_effect());
462    }
463
464    #[test]
465    fn speed_fraction_scales_and_clamps() {
466        assert_eq!(speed_fraction(Vec3::ZERO, 4.0), 0.0);
467        assert!(approx(speed_fraction(Vec3::new(0.0, 0.0, -2.0), 4.0), 0.5));
468        assert_eq!(speed_fraction(Vec3::new(10.0, 0.0, 0.0), 4.0), 1.0);
469    }
470
471    #[test]
472    fn speed_fraction_rejects_bad_inputs() {
473        assert_eq!(speed_fraction(Vec3::X, 0.0), 0.0);
474        assert_eq!(speed_fraction(Vec3::X, -1.0), 0.0);
475        assert_eq!(speed_fraction(Vec3::X, f32::NAN), 0.0);
476        assert_eq!(speed_fraction(Vec3::splat(f32::NAN), 4.0), 0.0);
477    }
478
479    #[test]
480    fn lateral_fraction_is_signed_and_ignores_forward_motion() {
481        assert!(approx(
482            lateral_fraction(Vec3::new(2.0, 0.0, 0.0), Vec3::X, 4.0),
483            0.5
484        ));
485        assert!(approx(
486            lateral_fraction(Vec3::new(-2.0, 0.0, 0.0), Vec3::X, 4.0),
487            -0.5
488        ));
489        assert_eq!(
490            lateral_fraction(Vec3::new(0.0, 3.0, -4.0), Vec3::X, 4.0),
491            0.0
492        );
493        assert_eq!(
494            lateral_fraction(Vec3::new(40.0, 0.0, 0.0), Vec3::X, 4.0),
495            1.0
496        );
497        assert_eq!(
498            lateral_fraction(Vec3::new(-40.0, 0.0, 0.0), Vec3::X, 4.0),
499            -1.0
500        );
501        assert_eq!(lateral_fraction(Vec3::X, Vec3::X, 0.0), 0.0);
502    }
503
504    #[test]
505    fn fov_boost_target_scales_with_speed() {
506        let c = config(10.0, 0.0);
507        assert_eq!(fov_boost_target(&c, 0.0), 0.0);
508        assert!(approx(fov_boost_target(&c, 0.5), 5_f32.to_radians()));
509        assert!(approx(fov_boost_target(&c, 1.0), 10_f32.to_radians()));
510        assert!(approx(fov_boost_target(&c, 3.0), 10_f32.to_radians()));
511        assert_eq!(fov_boost_target(&config(f32::NAN, 0.0), 1.0), 0.0);
512    }
513
514    #[test]
515    fn lean_target_rolls_toward_the_movement() {
516        let c = config(0.0, 4.0);
517        // Moving right leans right, which is a negative local-Z rotation.
518        assert!(approx(lean_target(&c, 1.0), -4_f32.to_radians()));
519        assert!(approx(lean_target(&c, -0.5), 2_f32.to_radians()));
520        assert_eq!(lean_target(&c, 0.0), 0.0);
521    }
522
523    #[test]
524    fn lean_is_limited() {
525        let c = config(0.0, 500.0);
526        assert!(approx(lean_target(&c, -1.0), 89_f32.to_radians()));
527    }
528
529    #[test]
530    fn smoothing_zero_or_invalid_follows_instantly() {
531        assert_eq!(smooth_toward(0.0, 1.0, 0.0, 0.016), 1.0);
532        assert_eq!(smooth_toward(0.0, 1.0, -1.0, 0.016), 1.0);
533        assert_eq!(smooth_toward(0.0, 1.0, f32::NAN, 0.016), 1.0);
534        assert_eq!(smooth_toward(0.0, 1.0, f32::INFINITY, 0.016), 1.0);
535    }
536
537    #[test]
538    fn smoothing_applies_the_time_constant() {
539        // After one time constant, 1 - 1/e of the change is applied.
540        let v = smooth_toward(0.0, 1.0, 0.5, 0.5);
541        assert!(approx(v, 1.0 - (-1.0_f32).exp()));
542        // No time passed: nothing moves.
543        assert_eq!(smooth_toward(0.25, 1.0, 0.5, 0.0), 0.25);
544    }
545
546    #[test]
547    fn smoothing_is_frame_rate_independent() {
548        let one_step = smooth_toward(0.0, 1.0, 0.2, 0.1);
549        let mut two_steps = 0.0;
550        for _ in 0..2 {
551            two_steps = smooth_toward(two_steps, 1.0, 0.2, 0.05);
552        }
553        assert!(approx(one_step, two_steps));
554    }
555
556    #[test]
557    fn smoothing_lands_exactly_on_the_target() {
558        let mut v = 0.1;
559        for _ in 0..2000 {
560            v = smooth_toward(v, 0.0, 0.1, 0.016);
561        }
562        assert_eq!(v, 0.0);
563    }
564
565    #[test]
566    fn base_fov_survives_own_writes_and_follows_external_ones() {
567        // First run: whatever is on the projection is the base.
568        assert_eq!(resolve_base_fov(1.5, None, None), 1.5);
569        // Projection still holds our write: the base stands.
570        assert_eq!(resolve_base_fov(1.6, Some(1.6), Some(1.5)), 1.5);
571        // Something else wrote a new value: it becomes the base.
572        assert_eq!(resolve_base_fov(1.2, Some(1.6), Some(1.5)), 1.2);
573    }
574
575    #[test]
576    fn boosted_fov_adds_and_clamps() {
577        assert_eq!(boosted_fov(1.5, 0.0), 1.5);
578        assert!(approx(boosted_fov(1.5, 0.1), 1.6));
579        assert_eq!(boosted_fov(3.0, 1.0), MAX_BOOSTED_FOV);
580        assert_eq!(boosted_fov(0.1, -1.0), MIN_BOOSTED_FOV);
581        // A zero boost never touches an out-of-range base.
582        assert_eq!(boosted_fov(3.5, 0.0), 3.5);
583    }
584
585    #[test]
586    fn unleaning_an_untouched_rotation_is_exact() {
587        let base_rotation = Quat::from_euler(EulerRot::YXZ, 0.7, -0.3, 0.2);
588        let angle = 0.05;
589        let leaned_rotation = (base_rotation * Quat::from_rotation_z(angle)).normalize();
590        let applied = AppliedLean {
591            angle,
592            base_rotation,
593            leaned_rotation,
594        };
595        assert_eq!(unleaned_rotation(leaned_rotation, applied), base_rotation);
596    }
597
598    #[test]
599    fn unleaning_a_rotation_changed_elsewhere_rotates_the_lean_back_out() {
600        let base_rotation = Quat::IDENTITY;
601        let angle = 0.1;
602        let leaned_rotation = base_rotation * Quat::from_rotation_z(angle);
603        let applied = AppliedLean {
604            angle,
605            base_rotation,
606            leaned_rotation,
607        };
608        // Something yawed the leaned camera around its own up axis.
609        let yaw = Quat::from_rotation_y(0.4);
610        let changed = leaned_rotation * yaw;
611        let restored = unleaned_rotation(changed, applied);
612        let expected = changed * Quat::from_rotation_z(-angle);
613        assert!(restored.angle_between(expected) < 1.0e-4);
614        assert_ne!(restored, base_rotation);
615    }
616
617    // ---- System tests (headless) ------------------------------------------
618
619    const BASE_FOV: f32 = 1.5;
620
621    /// App running the restore and apply systems over one player whose
622    /// velocity is `velocity`, with a perspective projection at [`BASE_FOV`].
623    fn response_app(config: Option<CameraResponseConfig>, velocity: Vec3) -> (App, Entity) {
624        let mut app = App::new();
625        app.init_resource::<Time>().add_systems(
626            Update,
627            (camera_response_restore, camera_response_apply).chain(),
628        );
629        if let Some(config) = config {
630            app.insert_resource(config);
631        }
632        let player = app
633            .world_mut()
634            .spawn((
635                Player {
636                    velocity,
637                    ..default()
638                },
639                Transform::default(),
640                Projection::Perspective(PerspectiveProjection {
641                    fov: BASE_FOV,
642                    ..default()
643                }),
644            ))
645            .id();
646        (app, player)
647    }
648
649    fn fov(app: &App, player: Entity) -> f32 {
650        match app.world().get::<Projection>(player).unwrap() {
651            Projection::Perspective(perspective) => perspective.fov,
652            _ => panic!("expected a perspective projection"),
653        }
654    }
655
656    fn rotation(app: &App, player: Entity) -> Quat {
657        app.world().get::<Transform>(player).unwrap().rotation
658    }
659
660    fn set_velocity(app: &mut App, player: Entity, velocity: Vec3) {
661        app.world_mut().get_mut::<Player>(player).unwrap().velocity = velocity;
662    }
663
664    #[test]
665    fn default_config_changes_nothing() {
666        // Default player speed is 4; move at full speed sideways.
667        for config in [None, Some(CameraResponseConfig::default())] {
668            let (mut app, player) = response_app(config, Vec3::new(4.0, 0.0, 0.0));
669            app.update();
670            app.update();
671            assert_eq!(fov(&app, player), BASE_FOV);
672            assert_eq!(rotation(&app, player), Quat::IDENTITY);
673            assert!(app.world().get::<CameraResponse>(player).is_none());
674        }
675    }
676
677    #[test]
678    fn full_speed_applies_the_full_boost() {
679        let (mut app, player) = response_app(Some(config(10.0, 0.0)), Vec3::new(0.0, 0.0, -4.0));
680        app.update(); // inserts the state component
681        app.update();
682        assert!(approx(fov(&app, player), BASE_FOV + 10_f32.to_radians()));
683        // Moving straight ahead does not lean.
684        assert_eq!(rotation(&app, player), Quat::IDENTITY);
685        let state = app.world().get::<CameraResponse>(player).unwrap();
686        assert_eq!(state.base_fov_radians(), Some(BASE_FOV));
687        assert!(approx(state.fov_boost_radians(), 10_f32.to_radians()));
688    }
689
690    #[test]
691    fn boost_does_not_accumulate_and_returns_to_base() {
692        let (mut app, player) = response_app(Some(config(10.0, 0.0)), Vec3::new(0.0, 0.0, -2.0));
693        for _ in 0..5 {
694            app.update();
695        }
696        assert!(approx(fov(&app, player), BASE_FOV + 5_f32.to_radians()));
697        set_velocity(&mut app, player, Vec3::ZERO);
698        app.update();
699        assert_eq!(fov(&app, player), BASE_FOV);
700    }
701
702    #[test]
703    fn strafing_leans_toward_the_movement_without_changing_forward() {
704        let (mut app, player) = response_app(Some(config(0.0, 5.0)), Vec3::new(4.0, 0.0, 0.0));
705        app.update();
706        app.update();
707        let transform = *app.world().get::<Transform>(player).unwrap();
708        // Up tilts toward the right (+X), the direction of movement.
709        assert!(approx(transform.up().x, 5_f32.to_radians().sin()));
710        assert!(transform.forward().distance(Vec3::NEG_Z) < 1.0e-5);
711        assert_eq!(fov(&app, player), BASE_FOV);
712
713        // Strafing the other way mirrors it, measured from the unleaned frame.
714        set_velocity(&mut app, player, Vec3::new(-4.0, 0.0, 0.0));
715        app.update();
716        let transform = *app.world().get::<Transform>(player).unwrap();
717        assert!(approx(transform.up().x, -(5_f32.to_radians().sin())));
718    }
719
720    #[test]
721    fn lean_is_removed_exactly_when_movement_stops() {
722        let (mut app, player) = response_app(Some(config(0.0, 5.0)), Vec3::new(4.0, 0.0, 0.0));
723        for _ in 0..50 {
724            app.update();
725        }
726        set_velocity(&mut app, player, Vec3::ZERO);
727        app.update();
728        assert_eq!(rotation(&app, player), Quat::IDENTITY);
729    }
730
731    #[test]
732    fn restore_runs_before_the_other_player_systems_see_the_rotation() {
733        let (mut app, player) = response_app(Some(config(0.0, 5.0)), Vec3::new(4.0, 0.0, 0.0));
734        app.update();
735        app.update();
736        assert_ne!(rotation(&app, player), Quat::IDENTITY);
737        app.world_mut()
738            .run_system_once(camera_response_restore)
739            .expect("camera_response_restore should run");
740        assert_eq!(rotation(&app, player), Quat::IDENTITY);
741    }
742
743    #[test]
744    fn disabling_restores_the_camera_on_the_next_frame() {
745        let mut c = config(10.0, 5.0);
746        c.smoothing_seconds = 10.0;
747        let (mut app, player) = response_app(Some(c), Vec3::new(4.0, 0.0, 0.0));
748        app.update();
749        for _ in 0..3 {
750            app.world_mut()
751                .resource_mut::<Time>()
752                .advance_by(std::time::Duration::from_millis(100));
753            app.update();
754        }
755        assert!(fov(&app, player) > BASE_FOV);
756        assert_ne!(rotation(&app, player), Quat::IDENTITY);
757
758        app.world_mut()
759            .resource_mut::<CameraResponseConfig>()
760            .enabled = false;
761        app.update();
762        assert_eq!(fov(&app, player), BASE_FOV);
763        assert_eq!(rotation(&app, player), Quat::IDENTITY);
764    }
765
766    #[test]
767    fn smoothing_eases_toward_the_target() {
768        let mut c = config(10.0, 0.0);
769        c.smoothing_seconds = 0.5;
770        let (mut app, player) = response_app(Some(c), Vec3::new(0.0, 0.0, -4.0));
771        app.update();
772        app.world_mut()
773            .resource_mut::<Time>()
774            .advance_by(std::time::Duration::from_millis(500));
775        app.update();
776        let expected = BASE_FOV + 10_f32.to_radians() * (1.0 - (-1.0_f32).exp());
777        assert!(approx(fov(&app, player), expected));
778    }
779
780    #[test]
781    fn external_fov_change_becomes_the_new_base() {
782        let (mut app, player) = response_app(Some(config(10.0, 0.0)), Vec3::new(0.0, 0.0, -4.0));
783        app.update();
784        app.update();
785        // A settings screen writes an absolute field of view.
786        if let Projection::Perspective(perspective) =
787            &mut *app.world_mut().get_mut::<Projection>(player).unwrap()
788        {
789            perspective.fov = 1.2;
790        }
791        app.update();
792        assert!(approx(fov(&app, player), 1.2 + 10_f32.to_radians()));
793        let state = app.world().get::<CameraResponse>(player).unwrap();
794        assert_eq!(state.base_fov_radians(), Some(1.2));
795    }
796
797    #[test]
798    fn pausing_puts_the_camera_back_and_resuming_brings_the_response_back() {
799        let (mut app, player) = response_app(Some(config(10.0, 5.0)), Vec3::new(4.0, 0.0, 0.0));
800        app.insert_resource(State::new(PauseMenuState::Playing));
801        app.update();
802        app.update();
803        assert!(fov(&app, player) > BASE_FOV);
804
805        app.insert_resource(State::new(PauseMenuState::Paused));
806        app.update();
807        assert_eq!(fov(&app, player), BASE_FOV);
808        assert_eq!(rotation(&app, player), Quat::IDENTITY);
809
810        app.insert_resource(State::new(PauseMenuState::Playing));
811        app.update();
812        assert!(approx(fov(&app, player), BASE_FOV + 10_f32.to_radians()));
813        assert_ne!(rotation(&app, player), Quat::IDENTITY);
814    }
815
816    #[test]
817    fn reference_speed_overrides_the_player_speed() {
818        let mut c = config(10.0, 0.0);
819        c.reference_speed = Some(8.0);
820        let (mut app, player) = response_app(Some(c), Vec3::new(0.0, 0.0, -4.0));
821        app.update();
822        app.update();
823        assert!(approx(fov(&app, player), BASE_FOV + 5_f32.to_radians()));
824    }
825}