ferravex_play/
racing.rs

1//! Bounded polyline racing driver. Produces ordinary controls, never teleports or
2//! awards progress. Hosts pass perceived nearby traffic, not hidden rival state.
3//!
4//! Call [`RacingDriver::step`] on fixed simulation ticks, inspect
5//! [`RacingDriver::status`] for presentation, and [`RacingDriver::reset`] after a
6//! teleport, restart or path replacement. Progress is a nearest-path observation,
7//! not a lap counter or checkpoint authority. No history or path is allocated.
8use ferravex_math::Vec2;
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum RacingError {
11    /// Invalid bounds, non-finite inputs, degenerate segments or arithmetic
12    /// outside the finite range supported by the driver. State is unchanged.
13    Invalid,
14}
15#[derive(Clone, Copy, Debug)]
16pub struct DriverSettings {
17    pub cruise: f32,
18    pub minimum: f32,
19    pub lookahead: f32,
20    pub lookahead_seconds: f32,
21    pub corner_braking: f32,
22    pub lateral_acceleration: f32,
23    pub steer_gain: f32,
24    pub speed_response: f32,
25    pub half_width: f32,
26}
27impl Default for DriverSettings {
28    fn default() -> Self {
29        Self {
30            cruise: 180.,
31            minimum: 60.,
32            lookahead: 42.,
33            lookahead_seconds: 0.26,
34            corner_braking: 76.,
35            lateral_acceleration: 300.,
36            steer_gain: 2.,
37            speed_response: 20.,
38            half_width: 33.,
39        }
40    }
41}
42#[derive(Clone, Copy, Debug)]
43pub struct Rival {
44    pub position: Vec2,
45    pub velocity: Vec2,
46}
47#[derive(Clone, Copy, Debug)]
48pub struct DriverInput<'a> {
49    pub position: Vec2,
50    pub forward: Vec2,
51    pub velocity: Vec2,
52    pub rivals: &'a [Rival],
53}
54#[derive(Clone, Copy, Debug, PartialEq)]
55pub struct RacingControl {
56    pub throttle: f32,
57    pub steer: f32,
58    pub target_speed: f32,
59    pub lane: f32,
60    pub recovering: bool,
61}
62
63/// Projection onto the supplied closed path, as demonstrated by
64/// [`RacingDriver::status`]. Equal-distance segments choose the lowest index.
65/// Intersections and teleports can change the projection discontinuously; it
66/// does not establish that the driver visited any checkpoint.
67#[derive(Clone, Copy, Debug, PartialEq)]
68pub struct DriverProgress {
69    /// Start index of the closest segment, including the closing segment.
70    pub segment: usize,
71    /// Clamped fraction along that segment in `0..=1`.
72    pub segment_fraction: f32,
73    /// Distance along the path from its first vertex, in world units.
74    pub distance_along: f32,
75    /// Total length, including the closing segment, in world units.
76    pub path_length: f32,
77    /// Unsigned distance from the supplied position to its projection.
78    pub distance_to_path: f32,
79}
80
81/// Why the most recent tick looks wrong-way relative to its nearest segment.
82/// Facing means heading alignment below `-0.5`; moving means signed along-path
83/// speed below `-cruise * 0.02`. These observations also apply during an intended
84/// reverse: consult [`DriverStatus::recovery`] before showing a warning.
85/// See [`RacingDriver::status`] for an example.
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub enum WrongWayReason {
88    FacingBackward,
89    MovingBackward,
90    FacingAndMovingBackward,
91}
92
93/// Explanation of the controls returned on the most recent tick.
94/// See [`RacingDriver::status`] for an example.
95#[derive(Clone, Copy, Debug, PartialEq, Eq)]
96pub enum DriverRecovery {
97    /// Ordinary pursuit, including a deliberately zero target speed.
98    Driving,
99    /// Low speed is explained by a nearby rival's speed limit; no stuck time
100    /// accumulates while that limit is at or below `cruise * 0.02`.
101    WaitingForTraffic,
102    /// Speed is below `cruise * 0.02` despite a higher requested speed.
103    Stalled,
104    /// A bounded reverse attempt after three simulated seconds stalled.
105    Reversing,
106}
107
108/// Finite, allocation-free diagnostics for the last successful positive tick.
109/// Timers are measured after that tick; `Reversing` describes the returned
110/// controls even on the final reverse tick when the remaining time reaches zero.
111/// See [`RacingDriver::status`] for an example.
112#[derive(Clone, Copy, Debug, PartialEq)]
113pub struct DriverStatus {
114    pub progress: DriverProgress,
115    /// Normalized forward dotted with the nearest segment's direction, `-1..=1`.
116    pub heading_alignment: f32,
117    /// Velocity dotted with that direction, in world units per second.
118    pub along_speed: f32,
119    pub wrong_way: Option<WrongWayReason>,
120    pub recovery: DriverRecovery,
121    /// Consecutive low-speed seconds while ordinary controls demand movement.
122    pub stuck_seconds: f32,
123    /// Remaining time in the current one-second reverse attempt.
124    pub reverse_seconds_remaining: f32,
125}
126
127#[derive(Clone, Copy, Debug, Default)]
128pub struct RacingDriver {
129    stuck: f32,
130    reverse: f32,
131    reverse_side: f32,
132    side: f32,
133    status: Option<DriverStatus>,
134}
135impl RacingDriver {
136    pub fn new(seed: u64) -> Self {
137        Self {
138            side: if seed & 1 == 0 { 1. } else { -1. },
139            ..Self::default()
140        }
141    }
142
143    /// Clears recovery timers and the last observation, retaining the seeded
144    /// passing/recovery side. Call after teleporting, restarting or replacing
145    /// the path, before the next simulation tick. This never moves the vehicle.
146    ///
147    /// ```
148    /// use ferravex_play::racing::RacingDriver;
149    /// let mut driver = RacingDriver::new(7);
150    /// // Reset the vehicle pose/velocity in its owning simulation, then:
151    /// driver.reset();
152    /// assert_eq!(driver.status(), None);
153    /// ```
154    pub fn reset(&mut self) {
155        self.stuck = 0.;
156        self.reverse = 0.;
157        self.reverse_side = 0.;
158        self.status = None;
159    }
160
161    /// Returns the last accepted positive tick's diagnostics, or `None` before
162    /// that tick and after [`Self::reset`]. Invalid and zero-duration steps leave
163    /// this snapshot unchanged. Reading it does not advance simulation time.
164    ///
165    /// ```
166    /// use ferravex_math::Vec2;
167    /// use ferravex_play::racing::{
168    ///     DriverInput, DriverProgress, DriverRecovery, DriverSettings,
169    ///     DriverStatus, RacingDriver, WrongWayReason,
170    /// };
171    /// let path = [Vec2::ZERO, Vec2::X * 200., Vec2::splat(200.), Vec2::Y * 200.];
172    /// let mut driver = RacingDriver::new(0);
173    /// let input = DriverInput {
174    ///     position: Vec2::X * 50., forward: -Vec2::X,
175    ///     velocity: Vec2::ZERO, rivals: &[],
176    /// };
177    /// driver.step(&path, DriverSettings::default(), input, 0.25)?;
178    /// let status: DriverStatus = driver.status().unwrap();
179    /// let progress: DriverProgress = status.progress;
180    /// assert_eq!(progress.segment, 0);
181    /// assert_eq!(progress.distance_along, 50.);
182    /// assert_eq!(progress.path_length, 800.);
183    /// assert_eq!(status.wrong_way, Some(WrongWayReason::FacingBackward));
184    /// assert_eq!(status.recovery, DriverRecovery::Stalled);
185    /// assert_eq!(status.stuck_seconds, 0.25);
186    /// # Ok::<(), ferravex_play::racing::RacingError>(())
187    /// ```
188    pub fn status(&self) -> Option<DriverStatus> {
189        self.status
190    }
191
192    /// Computes controls for a closed path of 3 through 2048 vertices and at
193    /// most 32 perceived rivals. Supply fixed simulation `dt` in `0..=0.25`.
194    /// A zero-duration call previews controls without updating timers or status;
195    /// invalid inputs also leave state unchanged. All successful outputs and
196    /// observations are finite. Recovery does not count intentional stops or
197    /// waiting behind slow traffic as stalled time. An initially near-zero
198    /// reverse steering command uses the seeded side for the whole attempt so
199    /// subsequent heading changes do not undo the escape turn. Zero steer gain
200    /// still disables steering.
201    pub fn step(
202        &mut self,
203        path: &[Vec2],
204        p: DriverSettings,
205        input: DriverInput<'_>,
206        dt: f32,
207    ) -> Result<RacingControl, RacingError> {
208        let DriverInput {
209            position,
210            forward,
211            velocity,
212            rivals,
213        } = input;
214        if !(3..=2048).contains(&path.len())
215            || path.iter().any(|p| !p.is_finite())
216            || rivals.len() > 32
217            || rivals
218                .iter()
219                .any(|r| !r.position.is_finite() || !r.velocity.is_finite())
220            || !position.is_finite()
221            || !velocity.is_finite()
222            || !forward.is_finite()
223            || !forward.length_squared().is_finite()
224            || forward.length_squared() < 0.5
225            || !dt.is_finite()
226            || !(0. ..=0.25).contains(&dt)
227            || ![
228                p.cruise,
229                p.minimum,
230                p.lookahead,
231                p.lookahead_seconds,
232                p.corner_braking,
233                p.lateral_acceleration,
234                p.steer_gain,
235                p.speed_response,
236                p.half_width,
237            ]
238            .iter()
239            .all(|v| v.is_finite() && (0. ..=10000.).contains(v))
240            || p.cruise < p.minimum
241            || p.speed_response <= 0.
242            || p.lookahead <= 0.
243        {
244            return Err(RacingError::Invalid);
245        }
246        let mut nearest = 0;
247        let mut progress = 0.;
248        let mut segment_fraction = 0.;
249        let mut distance_along = 0.;
250        let mut path_length = 0.;
251        let mut best = f32::INFINITY;
252        for (i, a) in path.iter().copied().enumerate() {
253            let d = path[(i + 1) % path.len()] - a;
254            let len = d.length_squared();
255            let projection = (position - a).dot(d) / len;
256            if !len.is_finite() || len < 1e-6 || !projection.is_finite() {
257                return Err(RacingError::Invalid);
258            }
259            let fraction = projection.clamp(0., 1.);
260            let distance = position.distance_squared(a + d * fraction);
261            if !distance.is_finite() {
262                return Err(RacingError::Invalid);
263            }
264            if distance < best {
265                nearest = i;
266                progress = fraction * len.sqrt();
267                segment_fraction = fraction;
268                distance_along = path_length + progress;
269                best = distance;
270            }
271            path_length += len.sqrt();
272        }
273        let speed = velocity.length();
274        let lookahead = p.lookahead + speed * p.lookahead_seconds;
275        if !speed.is_finite() || !lookahead.is_finite() || !path_length.is_finite() {
276            return Err(RacingError::Invalid);
277        }
278        let mut distance = -progress;
279        let mut target = nearest;
280        for _ in 0..path.len() {
281            if distance >= lookahead {
282                break;
283            }
284            let next = (target + 1) % path.len();
285            distance += path[target].distance(path[next]);
286            target = next;
287        }
288        let forward = forward.normalize_or_zero();
289        let side = Vec2::new(-forward.y, forward.x);
290        let mut lane = 0.;
291        let mut traffic_limit = p.cruise;
292        for rival in rivals {
293            let delta = rival.position - position;
294            let along = delta.dot(forward);
295            let lateral = delta.dot(side);
296            let rival_speed = rival.velocity.length();
297            if !along.is_finite() || !lateral.is_finite() || !rival_speed.is_finite() {
298                return Err(RacingError::Invalid);
299            }
300            if along > 0. && along < p.lookahead && lateral.abs() < p.half_width * 0.4 {
301                lane = self.side * p.half_width * 0.28;
302                if along < p.lookahead * 0.4 {
303                    traffic_limit = traffic_limit.min(rival_speed + along * 0.5);
304                }
305            }
306        }
307        let tangent = (path[(target + 1) % path.len()] - path[target]).normalize_or_zero();
308        let desired = path[target] + Vec2::new(-tangent.y, tangent.x) * lane - position;
309        let error = forward.perp_dot(desired).atan2(forward.dot(desired));
310        let curvature = forward.perp_dot(tangent).abs() / distance.max(1.);
311        let corner_speed = (p.lateral_acceleration / curvature.max(1e-6)).sqrt();
312        let target_speed = (p.cruise - error.abs().min(1.2) * p.corner_braking)
313            .min(corner_speed)
314            .min(traffic_limit)
315            .clamp(0., p.cruise);
316        let target_speed = if rivals.is_empty() {
317            target_speed.max(p.minimum)
318        } else {
319            target_speed
320        };
321        let route_tangent = (path[(nearest + 1) % path.len()] - path[nearest]).normalize_or_zero();
322        let heading_alignment = forward.dot(route_tangent).clamp(-1., 1.);
323        let along_speed = velocity.dot(route_tangent);
324        if !along_speed.is_finite() || !error.is_finite() {
325            return Err(RacingError::Invalid);
326        }
327        let slow_speed = p.cruise * 0.02;
328        let wrong_way = match (heading_alignment < -0.5, along_speed < -slow_speed) {
329            (true, true) => Some(WrongWayReason::FacingAndMovingBackward),
330            (true, false) => Some(WrongWayReason::FacingBackward),
331            (false, true) => Some(WrongWayReason::MovingBackward),
332            (false, false) => None,
333        };
334        let mut recovery = if speed < slow_speed && traffic_limit <= slow_speed {
335            DriverRecovery::WaitingForTraffic
336        } else if speed < slow_speed && target_speed > slow_speed {
337            DriverRecovery::Stalled
338        } else {
339            DriverRecovery::Driving
340        };
341        let reverse_steer = (-error * p.steer_gain).clamp(-1., 1.);
342        let mut stuck = self.stuck;
343        let mut reverse = self.reverse;
344        let mut reverse_side = self.reverse_side;
345        if dt > 0. {
346            stuck = if reverse <= 0. && recovery == DriverRecovery::Stalled {
347                stuck + dt
348            } else {
349                0.
350            };
351            if stuck >= 3. && reverse <= 0. {
352                reverse = 1.;
353                stuck = 0.;
354                reverse_side = if reverse_steer.abs() < 0.1 {
355                    if self.side < 0. { -1. } else { 1. }
356                } else {
357                    0.
358                };
359            }
360        }
361        let recovering = reverse > 0.;
362        if recovering {
363            recovery = DriverRecovery::Reversing;
364        }
365        let control = RacingControl {
366            throttle: if recovering {
367                -0.6
368            } else {
369                ((target_speed - speed) / p.speed_response).clamp(-1., 1.)
370            },
371            steer: if recovering {
372                if reverse_side != 0. {
373                    reverse_side * p.steer_gain.min(1.)
374                } else {
375                    reverse_steer
376                }
377            } else {
378                (error * p.steer_gain).clamp(-1., 1.)
379            },
380            target_speed,
381            lane,
382            recovering,
383        };
384        if dt > 0. {
385            self.stuck = stuck;
386            self.reverse = (reverse - dt).max(0.);
387            self.reverse_side = if self.reverse > 0. { reverse_side } else { 0. };
388            self.status = Some(DriverStatus {
389                progress: DriverProgress {
390                    segment: nearest,
391                    segment_fraction,
392                    distance_along,
393                    path_length,
394                    distance_to_path: best.sqrt(),
395                },
396                heading_alignment,
397                along_speed,
398                wrong_way,
399                recovery,
400                stuck_seconds: self.stuck,
401                reverse_seconds_remaining: self.reverse,
402            });
403        }
404        Ok(control)
405    }
406}
407#[cfg(test)]
408mod tests {
409    use super::*;
410    fn path() -> [Vec2; 4] {
411        [
412            Vec2::ZERO,
413            Vec2::new(200., 0.),
414            Vec2::new(200., 200.),
415            Vec2::new(0., 200.),
416        ]
417    }
418    #[test]
419    fn traffic_and_corners_change_controls_without_teleporting() {
420        let mut d = RacingDriver::new(1);
421        let p = path();
422        let input = DriverInput {
423            position: Vec2::new(170., 0.),
424            forward: Vec2::X,
425            velocity: Vec2::X * 150.,
426            rivals: &[],
427        };
428        let a = d.step(&p, DriverSettings::default(), input, 0.01).unwrap();
429        assert!(a.target_speed < 180.);
430        let rivals = [Rival {
431            position: Vec2::new(180., 0.),
432            velocity: Vec2::X * 20.,
433        }];
434        let b = d
435            .step(
436                &p,
437                DriverSettings::default(),
438                DriverInput {
439                    rivals: &rivals,
440                    ..input
441                },
442                0.01,
443            )
444            .unwrap();
445        assert!(b.lane < 0. && b.target_speed < a.target_speed);
446    }
447    #[test]
448    fn stationary_driver_attempts_bounded_reverse() {
449        let mut d = RacingDriver::new(0);
450        let input = DriverInput {
451            position: Vec2::ZERO,
452            forward: Vec2::X,
453            velocity: Vec2::ZERO,
454            rivals: &[],
455        };
456        let mut reversed = false;
457        for _ in 0..200 {
458            reversed |= d
459                .step(&path(), DriverSettings::default(), input, 0.02)
460                .unwrap()
461                .recovering;
462        }
463        assert!(reversed);
464        assert!(
465            d.step(&[Vec2::ZERO; 3], DriverSettings::default(), input, 0.01)
466                .is_err()
467        );
468    }
469
470    fn stationary() -> DriverInput<'static> {
471        DriverInput {
472            position: Vec2::new(50., 0.),
473            forward: Vec2::X,
474            velocity: Vec2::ZERO,
475            rivals: &[],
476        }
477    }
478
479    fn tick(driver: &mut RacingDriver, input: DriverInput<'_>) -> RacingControl {
480        driver
481            .step(&path(), DriverSettings::default(), input, 0.25)
482            .unwrap()
483    }
484
485    #[test]
486    fn progress_covers_closing_segment_seam_and_equal_distance_ties() {
487        let mut driver = RacingDriver::new(0);
488        for (position, segment, segment_fraction, distance_along, distance_to_path) in [
489            (Vec2::new(50., -10.), 0, 0.25, 50., 10.),
490            (Vec2::new(-10., 50.), 3, 0.75, 750., 10.),
491            (Vec2::ZERO, 0, 0., 0., 0.),
492            (Vec2::new(200., 0.), 0, 1., 200., 0.),
493            (Vec2::splat(100.), 0, 0.5, 100., 100.),
494        ] {
495            tick(
496                &mut driver,
497                DriverInput {
498                    position,
499                    ..stationary()
500                },
501            );
502            assert_eq!(
503                driver.status().unwrap().progress,
504                DriverProgress {
505                    segment,
506                    segment_fraction,
507                    distance_along,
508                    path_length: 800.,
509                    distance_to_path,
510                }
511            );
512        }
513    }
514
515    #[test]
516    fn wrong_way_distinguishes_heading_motion_and_both_on_nearest_segment() {
517        let mut driver = RacingDriver::new(0);
518        for (forward, velocity, wrong_way) in [
519            (Vec2::X, Vec2::X * 100., None),
520            (-Vec2::X, Vec2::ZERO, Some(WrongWayReason::FacingBackward)),
521            (
522                Vec2::X,
523                -Vec2::X * 100.,
524                Some(WrongWayReason::MovingBackward),
525            ),
526            (
527                -Vec2::X,
528                -Vec2::X * 100.,
529                Some(WrongWayReason::FacingAndMovingBackward),
530            ),
531            (Vec2::X, -Vec2::X, None),
532            (Vec2::Y, Vec2::Y * 100., None),
533        ] {
534            tick(
535                &mut driver,
536                DriverInput {
537                    // Lookahead crosses a corner; wrong-way uses the local
538                    // segment rather than the future steering target's tangent.
539                    position: Vec2::new(170., 0.),
540                    forward: forward * 2.,
541                    velocity,
542                    ..stationary()
543                },
544            );
545            let status = driver.status().unwrap();
546            assert_eq!(status.wrong_way, wrong_way);
547            assert_eq!(status.heading_alignment, forward.x);
548            assert_eq!(status.along_speed, velocity.x);
549        }
550    }
551
552    #[test]
553    fn straight_obstruction_uses_seeded_reverse_steering_for_one_second() {
554        for seed in [0, 1] {
555            let mut driver = RacingDriver::new(seed);
556            for _ in 0..11 {
557                assert!(!tick(&mut driver, stationary()).recovering);
558            }
559            assert_eq!(driver.status().unwrap().stuck_seconds, 2.75);
560            for remaining in [0.75, 0.5, 0.25, 0.] {
561                let control = tick(&mut driver, stationary());
562                assert!(control.recovering);
563                assert_eq!(control.throttle, -0.6);
564                assert_eq!(control.steer, if seed == 0 { 1. } else { -1. });
565                let status = driver.status().unwrap();
566                assert_eq!(status.recovery, DriverRecovery::Reversing);
567                assert_eq!(status.stuck_seconds, 0.);
568                assert_eq!(status.reverse_seconds_remaining, remaining);
569            }
570            assert!(!tick(&mut driver, stationary()).recovering);
571            assert_eq!(driver.status().unwrap().recovery, DriverRecovery::Stalled);
572            assert_eq!(driver.status().unwrap().stuck_seconds, 0.25);
573        }
574        // Default has no passing preference; recovery still chooses a turn.
575        let mut driver = RacingDriver::default();
576        for _ in 0..12 {
577            tick(&mut driver, stationary());
578        }
579        assert_eq!(tick(&mut driver, stationary()).steer, 1.);
580    }
581
582    #[test]
583    fn escape_turn_is_held_as_heading_changes_and_respects_zero_steer_gain() {
584        for seed in [0, 1] {
585            let mut driver = RacingDriver::new(seed);
586            for _ in 0..12 {
587                tick(&mut driver, stationary());
588            }
589            let side = if seed == 0 { 1. } else { -1. };
590            // Reverse motion turns the nose away from the obstruction. Pursuit
591            // would now steer the other way and undo that escape turn.
592            let forward = Vec2::from_angle(-side * 0.2);
593            let control = tick(
594                &mut driver,
595                DriverInput {
596                    forward,
597                    velocity: forward * -10.,
598                    ..stationary()
599                },
600            );
601            assert!(control.recovering);
602            assert_eq!(control.steer, side);
603            assert_eq!(
604                driver.status().unwrap().wrong_way,
605                Some(WrongWayReason::MovingBackward)
606            );
607            let control = driver
608                .step(
609                    &path(),
610                    DriverSettings {
611                        steer_gain: 0.,
612                        ..DriverSettings::default()
613                    },
614                    stationary(),
615                    0.25,
616                )
617                .unwrap();
618            assert!(control.recovering);
619            assert_eq!(control.steer, 0.);
620        }
621    }
622
623    #[test]
624    fn waiting_for_traffic_clears_stalled_time_and_does_not_trigger_reverse() {
625        let mut driver = RacingDriver::new(1);
626        for _ in 0..11 {
627            tick(&mut driver, stationary());
628        }
629        let rivals = [Rival {
630            position: Vec2::new(52., 0.),
631            velocity: Vec2::ZERO,
632        }];
633        for _ in 0..24 {
634            let control = tick(
635                &mut driver,
636                DriverInput {
637                    rivals: &rivals,
638                    ..stationary()
639                },
640            );
641            assert!(!control.recovering);
642            assert_eq!(control.target_speed, 1.);
643            assert!(control.lane < 0.);
644            let status = driver.status().unwrap();
645            assert_eq!(status.recovery, DriverRecovery::WaitingForTraffic);
646            assert_eq!(status.stuck_seconds, 0.);
647        }
648        for _ in 0..11 {
649            assert!(!tick(&mut driver, stationary()).recovering);
650        }
651        assert!(tick(&mut driver, stationary()).recovering);
652    }
653
654    #[test]
655    fn intentionally_zero_target_and_resumed_motion_clear_stalled_time() {
656        let mut driver = RacingDriver::new(0);
657        for _ in 0..11 {
658            tick(&mut driver, stationary());
659        }
660        tick(
661            &mut driver,
662            DriverInput {
663                velocity: Vec2::X * 100.,
664                ..stationary()
665            },
666        );
667        assert_eq!(driver.status().unwrap().stuck_seconds, 0.);
668        for _ in 0..11 {
669            assert!(!tick(&mut driver, stationary()).recovering);
670        }
671        let settings = DriverSettings {
672            minimum: 0.,
673            lateral_acceleration: 0.,
674            ..DriverSettings::default()
675        };
676        for _ in 0..24 {
677            let control = driver.step(&path(), settings, stationary(), 0.25).unwrap();
678            assert_eq!(control.target_speed, 0.);
679            assert!(!control.recovering);
680            assert_eq!(driver.status().unwrap().recovery, DriverRecovery::Driving);
681            assert_eq!(driver.status().unwrap().stuck_seconds, 0.);
682        }
683    }
684
685    #[test]
686    fn reset_after_teleport_discards_recovery_and_preserves_seeded_behavior() {
687        for seed in [0, 1] {
688            let mut driver = RacingDriver::new(seed);
689            for _ in 0..12 {
690                tick(&mut driver, stationary());
691            }
692            assert_eq!(driver.status().unwrap().recovery, DriverRecovery::Reversing);
693            driver.reset();
694            driver.reset();
695            assert_eq!(driver.status(), None);
696            let rivals = [Rival {
697                position: Vec2::new(200., 62.),
698                velocity: Vec2::Y * 30.,
699            }];
700            let teleported = DriverInput {
701                position: Vec2::new(200., 50.),
702                forward: Vec2::Y,
703                velocity: Vec2::Y * 100.,
704                rivals: &rivals,
705            };
706            let mut fresh = RacingDriver::new(seed);
707            let control = tick(&mut driver, teleported);
708            assert!(!control.recovering);
709            assert_ne!(control.lane, 0.);
710            assert_eq!(control, tick(&mut fresh, teleported));
711            assert_eq!(driver.status(), fresh.status());
712            assert_eq!(driver.status().unwrap().progress.distance_along, 250.);
713            assert_eq!(driver.status().unwrap().stuck_seconds, 0.);
714            assert_eq!(driver.status().unwrap().reverse_seconds_remaining, 0.);
715        }
716    }
717
718    #[test]
719    fn zero_duration_previews_do_not_consume_stall_or_reverse_time() {
720        let mut driver = RacingDriver::new(0);
721        driver
722            .step(&path(), DriverSettings::default(), stationary(), 0.)
723            .unwrap();
724        assert_eq!(driver.status(), None);
725        for _ in 0..11 {
726            tick(&mut driver, stationary());
727        }
728        for recovering in [false, true] {
729            let before = driver.status();
730            let mut expected = driver;
731            for _ in 0..20 {
732                let control = driver
733                    .step(
734                        &path(),
735                        DriverSettings::default(),
736                        DriverInput {
737                            position: Vec2::new(200., 50.),
738                            forward: Vec2::Y,
739                            ..stationary()
740                        },
741                        0.,
742                    )
743                    .unwrap();
744                assert_eq!(control.recovering, recovering);
745                assert_eq!(driver.status(), before);
746            }
747            assert_eq!(
748                tick(&mut driver, stationary()),
749                tick(&mut expected, stationary())
750            );
751            assert_eq!(driver.status(), expected.status());
752        }
753    }
754
755    #[test]
756    fn invalid_inputs_and_geometry_overflow_leave_status_and_recovery_unchanged() {
757        let mut driver = RacingDriver::new(1);
758        for _ in 0..12 {
759            tick(&mut driver, stationary());
760        }
761        let before = driver.status();
762        let mut expected = driver;
763        let huge_path = [Vec2::ZERO, Vec2::new(f32::MAX, 0.), Vec2::new(0., f32::MAX)];
764        for invalid_path in [&[Vec2::ZERO; 3][..], &huge_path[..]] {
765            assert_eq!(
766                driver.step(invalid_path, DriverSettings::default(), stationary(), 0.25),
767                Err(RacingError::Invalid)
768            );
769        }
770        for dt in [-0.1, 0.251, f32::NAN, f32::INFINITY] {
771            assert_eq!(
772                driver.step(&path(), DriverSettings::default(), stationary(), dt),
773                Err(RacingError::Invalid)
774            );
775        }
776        for input in [
777            DriverInput {
778                position: Vec2::splat(f32::MAX),
779                ..stationary()
780            },
781            DriverInput {
782                velocity: Vec2::splat(f32::MAX),
783                ..stationary()
784            },
785            DriverInput {
786                forward: Vec2::splat(f32::MAX),
787                ..stationary()
788            },
789            DriverInput {
790                rivals: &[Rival {
791                    position: Vec2::ZERO,
792                    velocity: Vec2::splat(f32::MAX),
793                }],
794                ..stationary()
795            },
796        ] {
797            assert_eq!(
798                driver.step(&path(), DriverSettings::default(), input, 0.25),
799                Err(RacingError::Invalid)
800            );
801        }
802        assert_eq!(driver.status(), before);
803        assert_eq!(
804            tick(&mut driver, stationary()),
805            tick(&mut expected, stationary())
806        );
807        assert_eq!(driver.status(), expected.status());
808    }
809
810    #[test]
811    fn normal_straight_corner_and_traffic_controls_keep_baseline_values() {
812        let mut driver = RacingDriver::new(1);
813        let straight = tick(
814            &mut driver,
815            DriverInput {
816                velocity: Vec2::X * 100.,
817                ..stationary()
818            },
819        );
820        assert_eq!(
821            straight,
822            RacingControl {
823                throttle: 1.,
824                steer: 0.,
825                target_speed: 180.,
826                lane: 0.,
827                recovering: false,
828            }
829        );
830        let corner_input = DriverInput {
831            position: Vec2::new(170., 0.),
832            velocity: Vec2::X * 150.,
833            ..stationary()
834        };
835        let corner = tick(&mut driver, corner_input);
836        assert_eq!(corner.throttle, -1.);
837        assert_eq!(corner.steer, 1.);
838        assert!((corner.target_speed - 88.8).abs() < 1e-5);
839        assert_eq!(corner.lane, 0.);
840        assert!(!corner.recovering);
841        let rivals = [Rival {
842            position: Vec2::new(180., 0.),
843            velocity: Vec2::X * 20.,
844        }];
845        let traffic = tick(
846            &mut driver,
847            DriverInput {
848                rivals: &rivals,
849                ..corner_input
850            },
851        );
852        assert_eq!(traffic.throttle, -1.);
853        assert_eq!(traffic.steer, 1.);
854        assert_eq!(traffic.target_speed, 25.);
855        assert_eq!(traffic.lane, -33. * 0.28);
856        assert!(!traffic.recovering);
857    }
858}