voxel-framework 0.13.2

A reusable voxel engine framework built on Bevy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
//! Camera response to player movement: a speed-based field-of-view boost and
//! a lean (roll) toward sideways movement.
//!
//! Both effects are configured by [`CameraResponseConfig`] and are neutral by
//! default: with the default resource the player's [`Transform`] and
//! [`Projection`] are never written by this module.
//!
//! # How it composes with the player systems
//!
//! The camera entity is the player, so its rotation is also the player's
//! orientation (movement axes, collision capsule, snap roll). The lean is
//! therefore applied only between frames:
//!
//! ```text
//! camera_response_restore → player_look → player_move → player_resolve_collision
//!     → … → camera_response_apply
//! ```
//!
//! [`camera_response_restore`] removes last frame's lean before any player
//! system reads the rotation, and [`camera_response_apply`] adds the new lean
//! after they ran. The lean is a rotation around the camera's local Z axis, so
//! the view direction (`Transform::forward`) is never changed by it; only
//! `up` and `right` are tilted for systems that read the transform outside
//! this window.
//!
//! The field of view is composed with whatever value the [`Projection`]
//! holds: the value found there is taken as the base, and a value written by
//! anything else later (a settings menu, for example) becomes the new base.
//! [`CameraResponse::base_fov_radians`] returns the base without the boost.
//!
//! While [`PauseMenuState`] is registered and not `Playing`, and while
//! [`CameraResponseConfig::enabled`] is `false`, the camera is put back to
//! its base field of view and unleaned orientation.

use bevy::prelude::*;

use super::Player;
use crate::ui::PauseMenuState;

/// Smallest field of view, in radians, that a boost may produce (1°).
const MIN_BOOSTED_FOV: f32 = std::f32::consts::PI / 180.0;

/// Largest field of view, in radians, that a boost may produce (179°).
const MAX_BOOSTED_FOV: f32 = std::f32::consts::PI * 179.0 / 180.0;

/// Largest lean, in degrees, in either direction.
const MAX_LEAN_DEGREES: f32 = 89.0;

/// Difference below which a smoothed value lands exactly on its target.
const SMOOTHING_EPSILON: f32 = 1.0e-5;

/// How the player camera responds to movement.
///
/// [`PlayerPlugin`](super::PlayerPlugin) initializes this resource with the
/// defaults, which are neutral: no field-of-view change and no lean. Insert
/// your own value to turn the effects on, and flip
/// [`enabled`](Self::enabled) at runtime (for example from an accessibility
/// setting) to turn them off without losing the tuned values:
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::prelude::*;
///
/// App::new()
///     .add_plugins(PlayerPlugin::<DefaultVoxel>::new())
///     .insert_resource(CameraResponseConfig {
///         fov_boost_degrees: 6.0,
///         lean_degrees: 2.0,
///         smoothing_seconds: 0.15,
///         ..default()
///     });
/// ```
///
/// The values are read every frame.
#[derive(Resource, Debug, Clone, Copy, PartialEq)]
pub struct CameraResponseConfig {
    /// Master switch. When `false` the camera returns to its base field of
    /// view and unleaned orientation on the next frame, without smoothing.
    /// Default `true` (the amounts below default to zero, so the default
    /// configuration still does nothing).
    pub enabled: bool,
    /// Degrees added to the vertical field of view when the player moves at
    /// the reference speed or faster; scaled linearly below it. Negative
    /// values narrow the view. The resulting field of view is kept between 1°
    /// and 179°. A non-finite value counts as `0.0`. Default `0.0`.
    pub fov_boost_degrees: f32,
    /// Degrees the camera rolls toward sideways movement when the player
    /// strafes at the reference speed or faster; scaled linearly below it.
    /// Negative values lean away from the movement. Limited to ±89°. A
    /// non-finite value counts as `0.0`. Default `0.0`.
    pub lean_degrees: f32,
    /// Time constant, in seconds, with which both effects follow their
    /// target: after this long about 63% of a change has been applied. `0.0`
    /// (the default), a negative or a non-finite value follows the target
    /// instantly, which still is as smooth as the player's own acceleration.
    pub smoothing_seconds: f32,
    /// Speed, in world units per second, at which the effects reach their
    /// full amount. `None` (the default), or a value that is not positive and
    /// finite, uses [`Player::speed`]. Set it above the base speed when a
    /// faster state (such as grounded sprinting) should be told apart.
    pub reference_speed: Option<f32>,
}

impl Default for CameraResponseConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            fov_boost_degrees: 0.0,
            lean_degrees: 0.0,
            smoothing_seconds: 0.0,
            reference_speed: None,
        }
    }
}

impl CameraResponseConfig {
    /// Field-of-view boost at full speed, in radians (`0.0` when not finite).
    fn fov_boost_radians(&self) -> f32 {
        if self.fov_boost_degrees.is_finite() {
            self.fov_boost_degrees.to_radians()
        } else {
            0.0
        }
    }

    /// Lean at full sideways speed, in radians (`0.0` when not finite).
    fn lean_radians(&self) -> f32 {
        if self.lean_degrees.is_finite() {
            self.lean_degrees
                .clamp(-MAX_LEAN_DEGREES, MAX_LEAN_DEGREES)
                .to_radians()
        } else {
            0.0
        }
    }

    /// Whether this configuration can change the camera at all.
    fn has_effect(&self) -> bool {
        self.enabled && (self.fov_boost_radians() != 0.0 || self.lean_radians() != 0.0)
    }

    /// The configured reference speed, or `player_speed` when unset or invalid.
    fn reference_speed_or(&self, player_speed: f32) -> f32 {
        self.reference_speed
            .filter(|speed| speed.is_finite() && *speed > 0.0)
            .unwrap_or(player_speed)
    }
}

/// A lean currently baked into the player's rotation.
#[derive(Debug, Clone, Copy, PartialEq)]
struct AppliedLean {
    /// Rotation around local Z that was applied, in radians.
    angle: f32,
    /// Rotation before the lean was applied.
    base_rotation: Quat,
    /// Rotation after the lean was applied.
    leaned_rotation: Quat,
}

/// Runtime state of the camera response, stored on the player entity.
///
/// [`camera_response_apply`] inserts it the first time a non-neutral
/// [`CameraResponseConfig`] is active. A game only needs it to read the
/// current values, for example to show the base field of view in its own
/// settings screen.
#[derive(Component, Debug, Clone, Default, PartialEq)]
pub struct CameraResponse {
    fov_boost: f32,
    lean: f32,
    applied_lean: Option<AppliedLean>,
    base_fov: Option<f32>,
    written_fov: Option<f32>,
}

impl CameraResponse {
    /// Field-of-view boost currently requested, in radians (after smoothing,
    /// before the 1°–179° limit on the resulting field of view).
    pub fn fov_boost_radians(&self) -> f32 {
        self.fov_boost
    }

    /// Lean currently applied, in radians, in the
    /// [`Transform::rotate_local_z`] convention: negative leans to the right.
    pub fn lean_radians(&self) -> f32 {
        self.lean
    }

    /// The field of view without the boost, in radians, as last seen on the
    /// player's perspective [`Projection`]. `None` until the response first
    /// ran on a perspective camera.
    pub fn base_fov_radians(&self) -> Option<f32> {
        self.base_fov
    }

    /// Whether nothing of the response is currently applied to the camera.
    fn is_neutral(&self) -> bool {
        self.fov_boost == 0.0
            && self.lean == 0.0
            && self.applied_lean.is_none()
            && self.written_fov == self.base_fov
    }
}

// ─── Pure math ───────────────────────────────────────────────────────────────

/// Fraction of the reference speed the player is moving at, in `[0, 1]`.
///
/// Returns `0.0` when `reference_speed` is not positive and finite or the
/// velocity is not finite.
pub(crate) fn speed_fraction(velocity: Vec3, reference_speed: f32) -> f32 {
    if !(reference_speed.is_finite() && reference_speed > 0.0) || !velocity.is_finite() {
        return 0.0;
    }
    (velocity.length() / reference_speed).clamp(0.0, 1.0)
}

/// Signed fraction of the reference speed the player is moving sideways at,
/// in `[-1, 1]`; positive is toward `right`.
///
/// Returns `0.0` when `reference_speed` is not positive and finite or an
/// input is not finite.
pub(crate) fn lateral_fraction(velocity: Vec3, right: Vec3, reference_speed: f32) -> f32 {
    if !(reference_speed.is_finite() && reference_speed > 0.0)
        || !velocity.is_finite()
        || !right.is_finite()
    {
        return 0.0;
    }
    (velocity.dot(right) / reference_speed).clamp(-1.0, 1.0)
}

/// Field-of-view boost, in radians, for a speed fraction in `[0, 1]`.
pub(crate) fn fov_boost_target(config: &CameraResponseConfig, speed_fraction: f32) -> f32 {
    config.fov_boost_radians() * speed_fraction.clamp(0.0, 1.0)
}

/// Lean, in radians, for a lateral fraction in `[-1, 1]`.
///
/// The result follows the [`Transform::rotate_local_z`] convention, in which
/// a positive angle rolls to the left, so moving right with a positive
/// [`CameraResponseConfig::lean_degrees`] gives a negative angle.
pub(crate) fn lean_target(config: &CameraResponseConfig, lateral_fraction: f32) -> f32 {
    -config.lean_radians() * lateral_fraction.clamp(-1.0, 1.0)
}

/// Moves `current` toward `target` with an exponential time constant.
///
/// A `smoothing_seconds` that is not positive and finite returns `target`.
/// Otherwise the remaining difference shrinks by `exp(-dt / smoothing_seconds)`,
/// which is independent of the frame rate, and lands exactly on `target` once
/// closer than a small epsilon.
pub(crate) fn smooth_toward(current: f32, target: f32, smoothing_seconds: f32, dt: f32) -> f32 {
    if !(smoothing_seconds.is_finite() && smoothing_seconds > 0.0) || !current.is_finite() {
        return target;
    }
    if !(dt.is_finite() && dt > 0.0) {
        return current;
    }
    let next = target + (current - target) * (-dt / smoothing_seconds).exp();
    if (next - target).abs() < SMOOTHING_EPSILON {
        target
    } else {
        next
    }
}

/// The base field of view given the value currently on the projection.
///
/// If the projection still holds what the response wrote last
/// (`written == Some(current)`), the remembered `base` stands. Any other
/// value was written by something else and becomes the new base.
pub(crate) fn resolve_base_fov(current: f32, written: Option<f32>, base: Option<f32>) -> f32 {
    match (written, base) {
        (Some(written), Some(base)) if written == current => base,
        _ => current,
    }
}

/// The field of view to write for a base value and a boost, both in radians.
///
/// A zero boost returns `base` untouched; otherwise the sum is kept between
/// 1° and 179°.
pub(crate) fn boosted_fov(base: f32, boost: f32) -> f32 {
    if boost == 0.0 {
        base
    } else {
        (base + boost).clamp(MIN_BOOSTED_FOV, MAX_BOOSTED_FOV)
    }
}

/// The rotation with an applied lean removed.
///
/// When `current` is exactly the rotation the response wrote, the stored
/// base rotation is returned, so applying and removing the lean every frame
/// accumulates no error. When something else rotated the camera in between,
/// the lean angle is rotated back out around the current local Z axis.
fn unleaned_rotation(current: Quat, applied: AppliedLean) -> Quat {
    if current == applied.leaned_rotation {
        applied.base_rotation
    } else {
        (current * Quat::from_rotation_z(-applied.angle)).normalize()
    }
}

// ─── Systems ─────────────────────────────────────────────────────────────────

/// Removes the lean that [`camera_response_apply`] added on the previous
/// frame, so the other player systems see the player's own orientation.
///
/// Must run before [`player_look`](super::player_look).
/// [`PlayerPlugin`](super::PlayerPlugin) schedules it there. It does nothing
/// when no lean is applied.
pub fn camera_response_restore(
    mut query: Query<(&mut Transform, &mut CameraResponse), With<Player>>,
) {
    let Ok((mut transform, mut state)) = query.single_mut() else {
        return;
    };
    if state.applied_lean.is_none() {
        return;
    }
    if let Some(applied) = state.applied_lean.take() {
        let rotation = unleaned_rotation(transform.rotation, applied);
        transform.rotation = rotation;
    }
}

/// Applies the speed-based field-of-view boost and the lean configured by
/// [`CameraResponseConfig`] to the player camera.
///
/// Must run after the player's look, movement and collision systems.
/// [`PlayerPlugin`](super::PlayerPlugin) schedules it after them and, unlike
/// those, keeps it running while the pause menu is open, where it puts the
/// camera back to its base field of view and orientation. Without the
/// resource, or with its default value, the system changes nothing.
///
/// The speed is the length of [`Player::velocity`]; in
/// [`PlayerMode::Grounded`](super::PlayerMode::Grounded) that is the
/// horizontal velocity, so falling does not widen the view.
pub fn camera_response_apply(
    mut commands: Commands,
    mut query: Query<(
        Entity,
        &Player,
        &mut Transform,
        Option<&mut Projection>,
        Option<&mut CameraResponse>,
    )>,
    config: Option<Res<CameraResponseConfig>>,
    time: Res<Time>,
    pause: Option<Res<State<PauseMenuState>>>,
) {
    let Ok((entity, player, mut transform, projection, state)) = query.single_mut() else {
        return;
    };
    let config = config.as_deref().copied().unwrap_or_default();
    let playing = pause.map_or(true, |s| matches!(s.get(), PauseMenuState::Playing));
    let active = config.enabled && playing;
    let wants_effect = active && config.has_effect();

    let Some(mut state) = state else {
        if wants_effect {
            commands.entity(entity).insert(CameraResponse::default());
        }
        return;
    };
    if !wants_effect && state.is_neutral() {
        return;
    }

    // Take out the previous lean first: the new one is measured against the
    // player's own orientation.
    if let Some(applied) = state.applied_lean.take() {
        let rotation = unleaned_rotation(transform.rotation, applied);
        transform.rotation = rotation;
    }

    let (fov_boost, lean) = if active {
        let reference = config.reference_speed_or(player.speed);
        let right = transform.rotation * Vec3::X;
        let fov_target = fov_boost_target(&config, speed_fraction(player.velocity, reference));
        let lean_goal = lean_target(&config, lateral_fraction(player.velocity, right, reference));
        let dt = time.delta_secs();
        (
            smooth_toward(state.fov_boost, fov_target, config.smoothing_seconds, dt),
            smooth_toward(state.lean, lean_goal, config.smoothing_seconds, dt),
        )
    } else {
        (0.0, 0.0)
    };
    state.fov_boost = fov_boost;
    state.lean = lean;

    if lean != 0.0 {
        let base_rotation = transform.rotation;
        let leaned_rotation = (base_rotation * Quat::from_rotation_z(lean)).normalize();
        transform.rotation = leaned_rotation;
        state.applied_lean = Some(AppliedLean {
            angle: lean,
            base_rotation,
            leaned_rotation,
        });
    }

    if let Some(mut projection) = projection {
        let current = match &*projection {
            Projection::Perspective(perspective) => Some(perspective.fov),
            _ => None,
        };
        if let Some(current) = current {
            let base = resolve_base_fov(current, state.written_fov, state.base_fov);
            let fov = boosted_fov(base, fov_boost);
            state.base_fov = Some(base);
            state.written_fov = Some(fov);
            if fov != current {
                if let Projection::Perspective(perspective) = &mut *projection {
                    perspective.fov = fov;
                }
            }
        }
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use bevy::ecs::system::RunSystemOnce;

    fn config(fov: f32, lean: f32) -> CameraResponseConfig {
        CameraResponseConfig {
            fov_boost_degrees: fov,
            lean_degrees: lean,
            ..default()
        }
    }

    fn approx(a: f32, b: f32) -> bool {
        (a - b).abs() < 1.0e-4
    }

    #[test]
    fn default_config_is_neutral() {
        let c = CameraResponseConfig::default();
        assert!(c.enabled);
        assert_eq!(c.fov_boost_degrees, 0.0);
        assert_eq!(c.lean_degrees, 0.0);
        assert_eq!(c.smoothing_seconds, 0.0);
        assert_eq!(c.reference_speed, None);
        assert!(!c.has_effect());
    }

    #[test]
    fn disabled_or_non_finite_config_has_no_effect() {
        let mut c = config(6.0, 2.0);
        assert!(c.has_effect());
        c.enabled = false;
        assert!(!c.has_effect());
        assert!(!config(f32::NAN, f32::INFINITY).has_effect());
    }

    #[test]
    fn speed_fraction_scales_and_clamps() {
        assert_eq!(speed_fraction(Vec3::ZERO, 4.0), 0.0);
        assert!(approx(speed_fraction(Vec3::new(0.0, 0.0, -2.0), 4.0), 0.5));
        assert_eq!(speed_fraction(Vec3::new(10.0, 0.0, 0.0), 4.0), 1.0);
    }

    #[test]
    fn speed_fraction_rejects_bad_inputs() {
        assert_eq!(speed_fraction(Vec3::X, 0.0), 0.0);
        assert_eq!(speed_fraction(Vec3::X, -1.0), 0.0);
        assert_eq!(speed_fraction(Vec3::X, f32::NAN), 0.0);
        assert_eq!(speed_fraction(Vec3::splat(f32::NAN), 4.0), 0.0);
    }

    #[test]
    fn lateral_fraction_is_signed_and_ignores_forward_motion() {
        assert!(approx(
            lateral_fraction(Vec3::new(2.0, 0.0, 0.0), Vec3::X, 4.0),
            0.5
        ));
        assert!(approx(
            lateral_fraction(Vec3::new(-2.0, 0.0, 0.0), Vec3::X, 4.0),
            -0.5
        ));
        assert_eq!(
            lateral_fraction(Vec3::new(0.0, 3.0, -4.0), Vec3::X, 4.0),
            0.0
        );
        assert_eq!(
            lateral_fraction(Vec3::new(40.0, 0.0, 0.0), Vec3::X, 4.0),
            1.0
        );
        assert_eq!(
            lateral_fraction(Vec3::new(-40.0, 0.0, 0.0), Vec3::X, 4.0),
            -1.0
        );
        assert_eq!(lateral_fraction(Vec3::X, Vec3::X, 0.0), 0.0);
    }

    #[test]
    fn fov_boost_target_scales_with_speed() {
        let c = config(10.0, 0.0);
        assert_eq!(fov_boost_target(&c, 0.0), 0.0);
        assert!(approx(fov_boost_target(&c, 0.5), 5_f32.to_radians()));
        assert!(approx(fov_boost_target(&c, 1.0), 10_f32.to_radians()));
        assert!(approx(fov_boost_target(&c, 3.0), 10_f32.to_radians()));
        assert_eq!(fov_boost_target(&config(f32::NAN, 0.0), 1.0), 0.0);
    }

    #[test]
    fn lean_target_rolls_toward_the_movement() {
        let c = config(0.0, 4.0);
        // Moving right leans right, which is a negative local-Z rotation.
        assert!(approx(lean_target(&c, 1.0), -4_f32.to_radians()));
        assert!(approx(lean_target(&c, -0.5), 2_f32.to_radians()));
        assert_eq!(lean_target(&c, 0.0), 0.0);
    }

    #[test]
    fn lean_is_limited() {
        let c = config(0.0, 500.0);
        assert!(approx(lean_target(&c, -1.0), 89_f32.to_radians()));
    }

    #[test]
    fn smoothing_zero_or_invalid_follows_instantly() {
        assert_eq!(smooth_toward(0.0, 1.0, 0.0, 0.016), 1.0);
        assert_eq!(smooth_toward(0.0, 1.0, -1.0, 0.016), 1.0);
        assert_eq!(smooth_toward(0.0, 1.0, f32::NAN, 0.016), 1.0);
        assert_eq!(smooth_toward(0.0, 1.0, f32::INFINITY, 0.016), 1.0);
    }

    #[test]
    fn smoothing_applies_the_time_constant() {
        // After one time constant, 1 - 1/e of the change is applied.
        let v = smooth_toward(0.0, 1.0, 0.5, 0.5);
        assert!(approx(v, 1.0 - (-1.0_f32).exp()));
        // No time passed: nothing moves.
        assert_eq!(smooth_toward(0.25, 1.0, 0.5, 0.0), 0.25);
    }

    #[test]
    fn smoothing_is_frame_rate_independent() {
        let one_step = smooth_toward(0.0, 1.0, 0.2, 0.1);
        let mut two_steps = 0.0;
        for _ in 0..2 {
            two_steps = smooth_toward(two_steps, 1.0, 0.2, 0.05);
        }
        assert!(approx(one_step, two_steps));
    }

    #[test]
    fn smoothing_lands_exactly_on_the_target() {
        let mut v = 0.1;
        for _ in 0..2000 {
            v = smooth_toward(v, 0.0, 0.1, 0.016);
        }
        assert_eq!(v, 0.0);
    }

    #[test]
    fn base_fov_survives_own_writes_and_follows_external_ones() {
        // First run: whatever is on the projection is the base.
        assert_eq!(resolve_base_fov(1.5, None, None), 1.5);
        // Projection still holds our write: the base stands.
        assert_eq!(resolve_base_fov(1.6, Some(1.6), Some(1.5)), 1.5);
        // Something else wrote a new value: it becomes the base.
        assert_eq!(resolve_base_fov(1.2, Some(1.6), Some(1.5)), 1.2);
    }

    #[test]
    fn boosted_fov_adds_and_clamps() {
        assert_eq!(boosted_fov(1.5, 0.0), 1.5);
        assert!(approx(boosted_fov(1.5, 0.1), 1.6));
        assert_eq!(boosted_fov(3.0, 1.0), MAX_BOOSTED_FOV);
        assert_eq!(boosted_fov(0.1, -1.0), MIN_BOOSTED_FOV);
        // A zero boost never touches an out-of-range base.
        assert_eq!(boosted_fov(3.5, 0.0), 3.5);
    }

    #[test]
    fn unleaning_an_untouched_rotation_is_exact() {
        let base_rotation = Quat::from_euler(EulerRot::YXZ, 0.7, -0.3, 0.2);
        let angle = 0.05;
        let leaned_rotation = (base_rotation * Quat::from_rotation_z(angle)).normalize();
        let applied = AppliedLean {
            angle,
            base_rotation,
            leaned_rotation,
        };
        assert_eq!(unleaned_rotation(leaned_rotation, applied), base_rotation);
    }

    #[test]
    fn unleaning_a_rotation_changed_elsewhere_rotates_the_lean_back_out() {
        let base_rotation = Quat::IDENTITY;
        let angle = 0.1;
        let leaned_rotation = base_rotation * Quat::from_rotation_z(angle);
        let applied = AppliedLean {
            angle,
            base_rotation,
            leaned_rotation,
        };
        // Something yawed the leaned camera around its own up axis.
        let yaw = Quat::from_rotation_y(0.4);
        let changed = leaned_rotation * yaw;
        let restored = unleaned_rotation(changed, applied);
        let expected = changed * Quat::from_rotation_z(-angle);
        assert!(restored.angle_between(expected) < 1.0e-4);
        assert_ne!(restored, base_rotation);
    }

    // ---- System tests (headless) ------------------------------------------

    const BASE_FOV: f32 = 1.5;

    /// App running the restore and apply systems over one player whose
    /// velocity is `velocity`, with a perspective projection at [`BASE_FOV`].
    fn response_app(config: Option<CameraResponseConfig>, velocity: Vec3) -> (App, Entity) {
        let mut app = App::new();
        app.init_resource::<Time>().add_systems(
            Update,
            (camera_response_restore, camera_response_apply).chain(),
        );
        if let Some(config) = config {
            app.insert_resource(config);
        }
        let player = app
            .world_mut()
            .spawn((
                Player {
                    velocity,
                    ..default()
                },
                Transform::default(),
                Projection::Perspective(PerspectiveProjection {
                    fov: BASE_FOV,
                    ..default()
                }),
            ))
            .id();
        (app, player)
    }

    fn fov(app: &App, player: Entity) -> f32 {
        match app.world().get::<Projection>(player).unwrap() {
            Projection::Perspective(perspective) => perspective.fov,
            _ => panic!("expected a perspective projection"),
        }
    }

    fn rotation(app: &App, player: Entity) -> Quat {
        app.world().get::<Transform>(player).unwrap().rotation
    }

    fn set_velocity(app: &mut App, player: Entity, velocity: Vec3) {
        app.world_mut().get_mut::<Player>(player).unwrap().velocity = velocity;
    }

    #[test]
    fn default_config_changes_nothing() {
        // Default player speed is 4; move at full speed sideways.
        for config in [None, Some(CameraResponseConfig::default())] {
            let (mut app, player) = response_app(config, Vec3::new(4.0, 0.0, 0.0));
            app.update();
            app.update();
            assert_eq!(fov(&app, player), BASE_FOV);
            assert_eq!(rotation(&app, player), Quat::IDENTITY);
            assert!(app.world().get::<CameraResponse>(player).is_none());
        }
    }

    #[test]
    fn full_speed_applies_the_full_boost() {
        let (mut app, player) = response_app(Some(config(10.0, 0.0)), Vec3::new(0.0, 0.0, -4.0));
        app.update(); // inserts the state component
        app.update();
        assert!(approx(fov(&app, player), BASE_FOV + 10_f32.to_radians()));
        // Moving straight ahead does not lean.
        assert_eq!(rotation(&app, player), Quat::IDENTITY);
        let state = app.world().get::<CameraResponse>(player).unwrap();
        assert_eq!(state.base_fov_radians(), Some(BASE_FOV));
        assert!(approx(state.fov_boost_radians(), 10_f32.to_radians()));
    }

    #[test]
    fn boost_does_not_accumulate_and_returns_to_base() {
        let (mut app, player) = response_app(Some(config(10.0, 0.0)), Vec3::new(0.0, 0.0, -2.0));
        for _ in 0..5 {
            app.update();
        }
        assert!(approx(fov(&app, player), BASE_FOV + 5_f32.to_radians()));
        set_velocity(&mut app, player, Vec3::ZERO);
        app.update();
        assert_eq!(fov(&app, player), BASE_FOV);
    }

    #[test]
    fn strafing_leans_toward_the_movement_without_changing_forward() {
        let (mut app, player) = response_app(Some(config(0.0, 5.0)), Vec3::new(4.0, 0.0, 0.0));
        app.update();
        app.update();
        let transform = *app.world().get::<Transform>(player).unwrap();
        // Up tilts toward the right (+X), the direction of movement.
        assert!(approx(transform.up().x, 5_f32.to_radians().sin()));
        assert!(transform.forward().distance(Vec3::NEG_Z) < 1.0e-5);
        assert_eq!(fov(&app, player), BASE_FOV);

        // Strafing the other way mirrors it, measured from the unleaned frame.
        set_velocity(&mut app, player, Vec3::new(-4.0, 0.0, 0.0));
        app.update();
        let transform = *app.world().get::<Transform>(player).unwrap();
        assert!(approx(transform.up().x, -(5_f32.to_radians().sin())));
    }

    #[test]
    fn lean_is_removed_exactly_when_movement_stops() {
        let (mut app, player) = response_app(Some(config(0.0, 5.0)), Vec3::new(4.0, 0.0, 0.0));
        for _ in 0..50 {
            app.update();
        }
        set_velocity(&mut app, player, Vec3::ZERO);
        app.update();
        assert_eq!(rotation(&app, player), Quat::IDENTITY);
    }

    #[test]
    fn restore_runs_before_the_other_player_systems_see_the_rotation() {
        let (mut app, player) = response_app(Some(config(0.0, 5.0)), Vec3::new(4.0, 0.0, 0.0));
        app.update();
        app.update();
        assert_ne!(rotation(&app, player), Quat::IDENTITY);
        app.world_mut()
            .run_system_once(camera_response_restore)
            .expect("camera_response_restore should run");
        assert_eq!(rotation(&app, player), Quat::IDENTITY);
    }

    #[test]
    fn disabling_restores_the_camera_on_the_next_frame() {
        let mut c = config(10.0, 5.0);
        c.smoothing_seconds = 10.0;
        let (mut app, player) = response_app(Some(c), Vec3::new(4.0, 0.0, 0.0));
        app.update();
        for _ in 0..3 {
            app.world_mut()
                .resource_mut::<Time>()
                .advance_by(std::time::Duration::from_millis(100));
            app.update();
        }
        assert!(fov(&app, player) > BASE_FOV);
        assert_ne!(rotation(&app, player), Quat::IDENTITY);

        app.world_mut()
            .resource_mut::<CameraResponseConfig>()
            .enabled = false;
        app.update();
        assert_eq!(fov(&app, player), BASE_FOV);
        assert_eq!(rotation(&app, player), Quat::IDENTITY);
    }

    #[test]
    fn smoothing_eases_toward_the_target() {
        let mut c = config(10.0, 0.0);
        c.smoothing_seconds = 0.5;
        let (mut app, player) = response_app(Some(c), Vec3::new(0.0, 0.0, -4.0));
        app.update();
        app.world_mut()
            .resource_mut::<Time>()
            .advance_by(std::time::Duration::from_millis(500));
        app.update();
        let expected = BASE_FOV + 10_f32.to_radians() * (1.0 - (-1.0_f32).exp());
        assert!(approx(fov(&app, player), expected));
    }

    #[test]
    fn external_fov_change_becomes_the_new_base() {
        let (mut app, player) = response_app(Some(config(10.0, 0.0)), Vec3::new(0.0, 0.0, -4.0));
        app.update();
        app.update();
        // A settings screen writes an absolute field of view.
        if let Projection::Perspective(perspective) =
            &mut *app.world_mut().get_mut::<Projection>(player).unwrap()
        {
            perspective.fov = 1.2;
        }
        app.update();
        assert!(approx(fov(&app, player), 1.2 + 10_f32.to_radians()));
        let state = app.world().get::<CameraResponse>(player).unwrap();
        assert_eq!(state.base_fov_radians(), Some(1.2));
    }

    #[test]
    fn pausing_puts_the_camera_back_and_resuming_brings_the_response_back() {
        let (mut app, player) = response_app(Some(config(10.0, 5.0)), Vec3::new(4.0, 0.0, 0.0));
        app.insert_resource(State::new(PauseMenuState::Playing));
        app.update();
        app.update();
        assert!(fov(&app, player) > BASE_FOV);

        app.insert_resource(State::new(PauseMenuState::Paused));
        app.update();
        assert_eq!(fov(&app, player), BASE_FOV);
        assert_eq!(rotation(&app, player), Quat::IDENTITY);

        app.insert_resource(State::new(PauseMenuState::Playing));
        app.update();
        assert!(approx(fov(&app, player), BASE_FOV + 10_f32.to_radians()));
        assert_ne!(rotation(&app, player), Quat::IDENTITY);
    }

    #[test]
    fn reference_speed_overrides_the_player_speed() {
        let mut c = config(10.0, 0.0);
        c.reference_speed = Some(8.0);
        let (mut app, player) = response_app(Some(c), Vec3::new(0.0, 0.0, -4.0));
        app.update();
        app.update();
        assert!(approx(fov(&app, player), BASE_FOV + 5_f32.to_radians()));
    }
}