ferravex_play/camera/
follow.rs

1use super::{CameraError, nonnegative, valid_dt, weight};
2use ferravex_math::Vec2;
3fn bounded(v: Vec2) -> bool {
4    v.is_finite() && v.abs().max_element() <= 1e6
5}
6#[derive(Clone, Copy, Debug, PartialEq)]
7pub struct Limits2 {
8    pub min: Vec2,
9    pub max: Vec2,
10}
11impl Limits2 {
12    fn valid(self) -> bool {
13        bounded(self.min)
14            && bounded(self.max)
15            && self.min.x <= self.max.x
16            && self.min.y <= self.max.y
17    }
18}
19#[derive(Clone, Copy, Debug, PartialEq)]
20pub struct Follow2Settings {
21    pub offset: Vec2,
22    /// Half-size around the view center in world units. Motion inside it does not pan.
23    pub dead_zone: Vec2,
24    /// Seconds to halve the remaining distance to a stationary goal, in `0..=10`.
25    /// Zero follows immediately on a positive timestep; cuts always snap.
26    pub half_life: f32,
27    /// Prediction horizon in seconds, finite and in `0..=2`. Zero disables prediction.
28    pub look_ahead_time: f32,
29    /// Maximum length of the predicted offset in world units, finite and in `0..=1e6`.
30    /// Limits the goal prediction, not the distance from the subject to the damped center.
31    pub max_look_ahead: f32,
32    /// Bounds constrain the camera center; derive them from viewport half-extents.
33    pub limits: Option<Limits2>,
34    /// Cut when subject motion between successful updates exceeds this distance.
35    /// `None` disables automatic teleport detection; explicit snaps still work.
36    pub teleport_distance: Option<f32>,
37}
38impl Default for Follow2Settings {
39    fn default() -> Self {
40        Self {
41            offset: Vec2::ZERO,
42            dead_zone: Vec2::ZERO,
43            half_life: 0.1,
44            look_ahead_time: 0.,
45            max_look_ahead: 100.,
46            limits: None,
47            teleport_distance: Some(20.),
48        }
49    }
50}
51impl Follow2Settings {
52    fn valid(self) -> bool {
53        bounded(self.offset)
54            && bounded(self.dead_zone)
55            && self.dead_zone.min_element() >= 0.
56            && nonnegative(self.half_life, 10.)
57            && nonnegative(self.look_ahead_time, 2.)
58            && nonnegative(self.max_look_ahead, 1e6)
59            && self.limits.is_none_or(Limits2::valid)
60            && self
61                .teleport_distance
62                .is_none_or(|v| v.is_finite() && (0.001..=1e6).contains(&v))
63    }
64}
65#[derive(Clone, Copy, Debug, PartialEq)]
66pub struct Frame2 {
67    pub center: Vec2,
68    /// Discontinuity: discard any renderer interpolation from the previous frame.
69    pub cut: bool,
70}
71/// A planar follow camera. The first valid update initializes directly at its
72/// goal; subsequent updates apply the configured dead zone and half-life.
73#[derive(Clone, Copy, Debug, PartialEq)]
74pub struct Follow2 {
75    settings: Follow2Settings,
76    look_ahead_dead_zone: Vec2,
77    center: Vec2,
78    previous_subject: Vec2,
79    initialized: bool,
80    cut_next: bool,
81}
82impl Default for Follow2 {
83    fn default() -> Self {
84        Self::new(Follow2Settings::default()).unwrap()
85    }
86}
87impl Follow2 {
88    pub fn new(settings: Follow2Settings) -> Result<Self, CameraError> {
89        if !settings.valid() {
90            return Err(CameraError::InvalidSettings);
91        }
92        Ok(Self {
93            settings,
94            look_ahead_dead_zone: Vec2::ZERO,
95            center: Vec2::ZERO,
96            previous_subject: Vec2::ZERO,
97            initialized: false,
98            cut_next: false,
99        })
100    }
101    pub fn settings(&self) -> Follow2Settings {
102        self.settings
103    }
104    pub fn set_settings(&mut self, settings: Follow2Settings) -> Result<(), CameraError> {
105        if !settings.valid() {
106            return Err(CameraError::InvalidSettings);
107        }
108        self.settings = settings;
109        Ok(())
110    }
111    /// Per-axis velocity dead zone for prediction, in world units per second.
112    /// Defaults to zero; see [`Self::set_look_ahead_dead_zone`] for tuning examples.
113    pub fn look_ahead_dead_zone(&self) -> Vec2 {
114        self.look_ahead_dead_zone
115    }
116    /// Suppress low-speed look-ahead without changing positional follow tuning.
117    ///
118    /// Each component must be finite and in `0..=1e6`, otherwise this returns
119    /// [`CameraError::InvalidSettings`] without changing any camera state. Below
120    /// or at the threshold the corresponding velocity component contributes no
121    /// prediction. Above it, only the excess speed contributes, avoiding a jump
122    /// at the threshold. The resulting prediction still uses the configured
123    /// `look_ahead_time` and radial `max_look_ahead` limit. Zero restores the
124    /// original velocity prediction on that axis.
125    ///
126    /// Changing this setting retains the center and any pending cut. It takes
127    /// effect on the next update or snap, and is retained by reset and
128    /// [`Self::set_settings`]. Prediction has no velocity history, so a stop or
129    /// reversal immediately changes the goal; positional damping and the
130    /// positional dead zone still apply and may retain some previous lead.
131    ///
132    /// ```
133    /// use ferravex_math::Vec2;
134    /// use ferravex_play::camera::{Follow2, Follow2Settings};
135    /// let mut camera = Follow2::new(Follow2Settings {
136    ///     look_ahead_time: 0.5,
137    ///     max_look_ahead: 3.,
138    ///     half_life: 0.25,
139    ///     ..Default::default()
140    /// })?;
141    /// camera.set_look_ahead_dead_zone(Vec2::new(2., 0.))?;
142    /// assert_eq!(camera.look_ahead_dead_zone(), Vec2::new(2., 0.));
143    /// assert_eq!(camera.snap(Vec2::ZERO, Vec2::X * 8.)?.center, Vec2::X * 3.);
144    /// // Small residual velocity does not keep the prediction moving forward.
145    /// let stopped = camera.update(0.25, Vec2::ZERO, Vec2::X)?;
146    /// assert_eq!(stopped.center, Vec2::X * 1.5);
147    /// assert!(!stopped.cut);
148    /// # Ok::<(), ferravex_play::camera::CameraError>(())
149    /// ```
150    pub fn set_look_ahead_dead_zone(&mut self, dead_zone: Vec2) -> Result<(), CameraError> {
151        if !bounded(dead_zone) || dead_zone.min_element() < 0. {
152            return Err(CameraError::InvalidSettings);
153        }
154        self.look_ahead_dead_zone = dead_zone;
155        Ok(())
156    }
157    /// Last successful center, or `None` before initialization or after [`Self::reset`].
158    pub fn center(&self) -> Option<Vec2> {
159        self.initialized.then_some(self.center)
160    }
161    /// Forget the current center and tracking history, retaining authored settings
162    /// and the velocity look-ahead dead zone.
163    /// The next valid update initializes at its goal, even with zero elapsed time.
164    ///
165    /// ```
166    /// use ferravex_math::Vec2;
167    /// use ferravex_play::camera::Follow2;
168    /// let mut camera = Follow2::default();
169    /// camera.snap(Vec2::X * 30., Vec2::ZERO)?;
170    /// camera.reset(); // Restart before the new player spawn is available.
171    /// assert_eq!(camera.center(), None);
172    /// let frame = camera.update(0., Vec2::X * 5., Vec2::ZERO)?;
173    /// assert!(frame.cut);
174    /// assert_eq!(frame.center, Vec2::X * 5.);
175    /// # Ok::<(), ferravex_play::camera::CameraError>(())
176    /// ```
177    pub fn reset(&mut self) {
178        self.center = Vec2::ZERO;
179        self.previous_subject = Vec2::ZERO;
180        self.initialized = false;
181        self.cut_next = false;
182    }
183    /// Request a cut on the next valid update, retaining the current center until then.
184    pub fn cut(&mut self) {
185        self.cut_next = true;
186    }
187    /// Immediately place the camera for a spawn, teleport or restart.
188    ///
189    /// Applies offset, velocity look-ahead and limits without positional dead-zone lag or
190    /// damping. The returned frame is a cut; subsequent updates smooth from this
191    /// new center. Invalid input leaves all state, including pending cuts, intact.
192    ///
193    /// ```
194    /// use ferravex_math::Vec2;
195    /// use ferravex_play::camera::{Follow2, Follow2Settings};
196    /// let mut camera = Follow2::new(Follow2Settings {
197    ///     offset: Vec2::X * 4.,
198    ///     ..Default::default()
199    /// })?;
200    /// let spawn = Vec2::new(100., 20.);
201    /// let frame = camera.snap(spawn, Vec2::ZERO)?;
202    /// assert!(frame.cut);
203    /// assert_eq!(frame.center, spawn + Vec2::X * 4.);
204    /// # Ok::<(), ferravex_play::camera::CameraError>(())
205    /// ```
206    pub fn snap(&mut self, subject: Vec2, velocity: Vec2) -> Result<Frame2, CameraError> {
207        let mut next = *self;
208        next.cut();
209        let frame = next.update(0., subject, velocity)?;
210        *self = next;
211        Ok(frame)
212    }
213    /// Follow a sampled subject using elapsed seconds in `0..=0.25`.
214    ///
215    /// Negative, non-finite or larger timesteps return [`CameraError::InvalidInput`]
216    /// without changing state. For a long host suspension, explicitly [`Self::snap`]
217    /// to the current subject or bound presentation time before calling this method.
218    /// Zero time freezes damping; initialization, cuts and limits still apply.
219    pub fn update(
220        &mut self,
221        dt: f32,
222        subject: Vec2,
223        velocity: Vec2,
224    ) -> Result<Frame2, CameraError> {
225        if !valid_dt(dt) || !bounded(subject) || !bounded(velocity) {
226            return Err(CameraError::InvalidInput);
227        }
228        let cut = !self.initialized
229            || self.cut_next
230            || self
231                .settings
232                .teleport_distance
233                .is_some_and(|v| subject.distance_squared(self.previous_subject) > v * v);
234        let prediction_velocity =
235            velocity.signum() * (velocity.abs() - self.look_ahead_dead_zone).max(Vec2::ZERO);
236        let goal = subject
237            + self.settings.offset
238            + (prediction_velocity * self.settings.look_ahead_time)
239                .clamp_length_max(self.settings.max_look_ahead);
240        if !bounded(goal) {
241            return Err(CameraError::InvalidInput);
242        }
243        let mut desired = if cut { goal } else { self.center };
244        if !cut {
245            for i in 0..2 {
246                let delta = goal[i] - self.center[i];
247                if delta.abs() > self.settings.dead_zone[i] {
248                    desired[i] = goal[i] - delta.signum() * self.settings.dead_zone[i];
249                }
250            }
251        }
252        if let Some(limits) = self.settings.limits {
253            desired = desired.clamp(limits.min, limits.max);
254        }
255        let mut center = if cut {
256            desired
257        } else {
258            self.center
259                .lerp(desired, weight(dt, self.settings.half_life))
260        };
261        if let Some(limits) = self.settings.limits {
262            center = center.clamp(limits.min, limits.max);
263        }
264        if !bounded(center) {
265            return Err(CameraError::InvalidInput);
266        }
267        self.center = center;
268        self.previous_subject = subject;
269        self.initialized = true;
270        self.cut_next = false;
271        Ok(Frame2 { center, cut })
272    }
273}
274
275#[cfg(test)]
276mod journey200_057 {
277    use super::*;
278
279    fn settings() -> Follow2Settings {
280        Follow2Settings {
281            half_life: 0.25,
282            look_ahead_time: 0.5,
283            max_look_ahead: 10.,
284            teleport_distance: None,
285            ..Default::default()
286        }
287    }
288
289    #[test]
290    fn zero_velocity_dead_zone_preserves_authored_prediction() {
291        let settings = Follow2Settings {
292            offset: Vec2::new(4., -2.),
293            ..settings()
294        };
295        let mut camera = Follow2::new(settings).unwrap();
296        assert_eq!(camera.settings(), settings);
297        assert_eq!(camera.look_ahead_dead_zone(), Vec2::ZERO);
298        let subject = Vec2::new(30., 50.);
299        for velocity in [
300            Vec2::ZERO,
301            Vec2::new(-0., 0.),
302            Vec2::new(3., -4.),
303            Vec2::new(-600., 800.),
304            Vec2::splat(1e6),
305        ] {
306            let expected = subject
307                + settings.offset
308                + (velocity * settings.look_ahead_time).clamp_length_max(settings.max_look_ahead);
309            assert_eq!(camera.snap(subject, velocity).unwrap().center, expected);
310        }
311    }
312
313    #[test]
314    fn velocity_dead_zone_is_per_axis_continuous_and_radially_capped() {
315        let mut camera = Follow2::new(settings()).unwrap();
316        camera.set_look_ahead_dead_zone(Vec2::new(2., 4.)).unwrap();
317        for (velocity, expected) in [
318            (Vec2::ZERO, Vec2::ZERO),
319            (Vec2::new(1., -3.), Vec2::ZERO),
320            (Vec2::new(-2., 4.), Vec2::ZERO),
321            (Vec2::new(2.125, -4.125), Vec2::new(0.0625, -0.0625)),
322            (Vec2::new(-8., 12.), Vec2::new(-3., 4.)),
323            (Vec2::new(62., -84.), Vec2::new(6., -8.)),
324        ] {
325            let frame = camera.snap(Vec2::ZERO, velocity).unwrap();
326            assert!(frame.cut);
327            assert!(frame.center.distance(expected) < 0.00001);
328            assert!(frame.center.length() <= settings().max_look_ahead);
329        }
330        camera.set_look_ahead_dead_zone(Vec2::ZERO).unwrap();
331        assert_eq!(
332            camera.snap(Vec2::ZERO, Vec2::new(2., -4.)).unwrap().center,
333            Vec2::new(1., -2.)
334        );
335    }
336
337    #[test]
338    fn invalid_velocity_dead_zone_preserves_state_and_pending_cut() {
339        let mut camera = Follow2::new(settings()).unwrap();
340        camera.set_look_ahead_dead_zone(Vec2::splat(2.)).unwrap();
341        camera.snap(Vec2::X * 10., Vec2::X * 8.).unwrap();
342        for pending_cut in [false, true] {
343            if pending_cut {
344                camera.cut();
345            }
346            let before = camera;
347            for invalid in [
348                -f32::EPSILON,
349                f32::NAN,
350                f32::INFINITY,
351                f32::NEG_INFINITY,
352                1_000_001.,
353            ] {
354                for dead_zone in [Vec2::new(invalid, 0.), Vec2::new(0., invalid)] {
355                    assert_eq!(
356                        camera.set_look_ahead_dead_zone(dead_zone),
357                        Err(CameraError::InvalidSettings)
358                    );
359                    assert_eq!(camera, before);
360                }
361            }
362        }
363        camera.set_look_ahead_dead_zone(Vec2::splat(1e6)).unwrap();
364        assert!(camera.update(0., Vec2::ZERO, Vec2::splat(1e6)).unwrap().cut);
365        assert_eq!(camera.center(), Some(Vec2::ZERO));
366    }
367
368    #[test]
369    fn stops_and_reversals_return_monotonically_without_passing_the_new_goal() {
370        for positional_dead_zone in [0., 1.] {
371            for direction in [Vec2::X, -Vec2::X, Vec2::Y, -Vec2::Y] {
372                let mut camera = Follow2::new(Follow2Settings {
373                    dead_zone: Vec2::splat(positional_dead_zone),
374                    ..settings()
375                })
376                .unwrap();
377                camera.set_look_ahead_dead_zone(Vec2::splat(2.)).unwrap();
378                camera.snap(Vec2::ZERO, direction * 22.).unwrap();
379                // Test both an exact stop and residual velocity on either side
380                // of zero. None may extend the previous prediction.
381                for velocity in [Vec2::ZERO, direction, -direction] {
382                    let mut stopped = camera;
383                    let mut previous = 10.;
384                    for _ in 0..40 {
385                        let frame = stopped.update(0.25, Vec2::ZERO, velocity).unwrap();
386                        let lead = frame.center.dot(direction);
387                        assert!(!frame.cut);
388                        assert!(lead <= previous && lead >= positional_dead_zone);
389                        previous = lead;
390                    }
391                    assert!((previous - positional_dead_zone).abs() < 0.00001);
392                }
393                let mut previous = 10.;
394                let endpoint = -10. + positional_dead_zone;
395                for _ in 0..40 {
396                    let frame = camera.update(0.25, Vec2::ZERO, -direction * 22.).unwrap();
397                    let lead = frame.center.dot(direction);
398                    assert!(!frame.cut);
399                    assert!(lead <= previous && lead >= endpoint);
400                    previous = lead;
401                }
402                assert!((previous - endpoint).abs() < 0.00001);
403            }
404        }
405    }
406
407    #[test]
408    fn tuning_retains_center_history_and_reset_snap_cut_semantics() {
409        let settings = Follow2Settings {
410            offset: Vec2::new(4., 2.),
411            teleport_distance: Some(20.),
412            ..settings()
413        };
414        let mut camera = Follow2::new(settings).unwrap();
415        camera.snap(Vec2::X * 10., Vec2::X * 8.).unwrap();
416        let center = camera.center();
417        camera.set_look_ahead_dead_zone(Vec2::splat(2.)).unwrap();
418        assert_eq!(camera.center(), center);
419        let frame = camera.update(0., Vec2::X * 10., Vec2::X * 8.).unwrap();
420        assert_eq!(Some(frame.center), center);
421        assert!(!frame.cut);
422        camera.cut();
423        camera.set_look_ahead_dead_zone(Vec2::new(4., 2.)).unwrap();
424        assert_eq!(camera.center(), center);
425        let frame = camera.update(0., Vec2::X * 10., Vec2::X * 8.).unwrap();
426        assert!(frame.cut);
427        assert_eq!(frame.center, Vec2::new(16., 2.));
428
429        // Updating ordinary settings must not silently clear the velocity filter.
430        let settings = Follow2Settings {
431            limits: Some(Limits2 {
432                min: Vec2::ZERO,
433                max: Vec2::new(100., 50.),
434            }),
435            ..settings
436        };
437        camera.set_settings(settings).unwrap();
438        assert_eq!(camera.look_ahead_dead_zone(), Vec2::new(4., 2.));
439        let frame = camera.update(0., Vec2::X * 200., Vec2::X * 8.).unwrap();
440        assert!(frame.cut); // Existing automatic teleport detection still applies.
441        assert_eq!(frame.center, Vec2::new(100., 2.));
442
443        camera.reset();
444        assert_eq!(camera.center(), None);
445        assert_eq!(camera.settings(), settings);
446        assert_eq!(camera.look_ahead_dead_zone(), Vec2::new(4., 2.));
447        let frame = camera.update(0., Vec2::X * 10., Vec2::X * 8.).unwrap();
448        assert!(frame.cut);
449        assert_eq!(frame.center, Vec2::new(16., 2.));
450        let frame = camera.snap(Vec2::ZERO, -Vec2::X * 8.).unwrap();
451        assert!(frame.cut);
452        assert_eq!(frame.center, Vec2::new(2., 2.));
453    }
454
455    #[test]
456    fn invalid_updates_do_not_change_tuning_or_tracking_history() {
457        let mut camera = Follow2::new(settings()).unwrap();
458        camera.set_look_ahead_dead_zone(Vec2::splat(2.)).unwrap();
459        camera.snap(Vec2::ZERO, Vec2::X * 22.).unwrap();
460        camera.cut();
461        let before = camera;
462        for (dt, subject, velocity) in [
463            (-1., Vec2::ZERO, Vec2::ZERO),
464            (0.3, Vec2::ZERO, Vec2::ZERO),
465            (f32::NAN, Vec2::ZERO, Vec2::ZERO),
466            (0.1, Vec2::splat(f32::INFINITY), Vec2::ZERO),
467            (0.1, Vec2::ZERO, Vec2::splat(f32::NAN)),
468            (0.1, Vec2::ZERO, Vec2::splat(1_000_001.)),
469            (0.1, Vec2::splat(1e6), Vec2::splat(1e6)),
470        ] {
471            assert_eq!(
472                camera.update(dt, subject, velocity),
473                Err(CameraError::InvalidInput)
474            );
475            assert_eq!(camera, before);
476        }
477        assert_eq!(
478            camera.snap(Vec2::ZERO, Vec2::splat(f32::NAN)),
479            Err(CameraError::InvalidInput)
480        );
481        assert_eq!(camera, before);
482    }
483}