ferravex_play/
vehicle.rs

1//! Arcade ground/hover and assisted-flight motors. Outputs are candidate motion;
2//! hosts resolve collisions, terrain, boost resources and race/mission authority.
3//!
4//! Validate handling at setup with [`PlanarHandling::validate`] or
5//! [`FlightHandling::validate`]. Telemetry is a read-only snapshot and never
6//! advances the motor; feed `step` only the host's fixed simulation interval.
7//! Reset helpers clear steering momentum without inspecting the previous state,
8//! so they can also recover a motor whose public fields have become invalid.
9//! Hosts still own collision-safe spawn selection, flight position, interpolation
10//! history, camera history and gameplay resources.
11use ferravex_math::{Vec2, Vec3};
12/// A checked vehicle operation rejected its input or an unrepresentable result.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum VehicleError {
15    /// Nonfinite or out-of-range input. See the called method's documented limits.
16    Invalid,
17}
18fn valid(values: &[f32]) -> bool {
19    values
20        .iter()
21        .all(|v| v.is_finite() && (0. ..=10000.).contains(v))
22}
23fn time(dt: f32) -> bool {
24    dt.is_finite() && (0. ..=0.25).contains(&dt)
25}
26#[derive(Clone, Copy, Debug)]
27pub struct PlanarHandling {
28    pub acceleration: f32,
29    pub braking: f32,
30    pub drag: f32,
31    pub grip: f32,
32    pub max_speed: f32,
33    pub base_turn: f32,
34    pub speed_turn: f32,
35    pub turn_speed_cap: f32,
36    pub response: f32,
37}
38impl PlanarHandling {
39    /// Check that every coefficient is finite and in `0..=10000`.
40    ///
41    /// Zero is allowed, including a zero maximum speed. These are exactly the
42    /// handling limits enforced by [`PlanarState::step`]; no tuning is changed.
43    ///
44    /// ```
45    /// use ferravex_play::vehicle::{PlanarHandling, VehicleError};
46    /// let mut handling = PlanarHandling {
47    ///     acceleration: 19., braking: 30., drag: 0.62, grip: 5., max_speed: 30.,
48    ///     base_turn: 1.15, speed_turn: 0.018, turn_speed_cap: 32., response: 12.,
49    /// };
50    /// assert_eq!(handling.validate(), Ok(()));
51    /// handling.grip = -1.;
52    /// assert_eq!(handling.validate(), Err(VehicleError::Invalid));
53    /// ```
54    pub fn validate(&self) -> Result<(), VehicleError> {
55        if valid(&[
56            self.acceleration,
57            self.braking,
58            self.drag,
59            self.grip,
60            self.max_speed,
61            self.base_turn,
62            self.speed_turn,
63            self.turn_speed_cap,
64            self.response,
65        ]) {
66            Ok(())
67        } else {
68            Err(VehicleError::Invalid)
69        }
70    }
71}
72
73/// A planar motor snapshot produced by [`PlanarState::telemetry`].
74/// Distances use host world units; angles are radians and rates use seconds.
75#[derive(Clone, Copy, Debug, PartialEq)]
76pub struct PlanarTelemetry {
77    /// Unit heading; yaw zero faces positive Y in the motor's 2D plane.
78    pub forward: Vec2,
79    /// Unit right direction; yaw zero has positive X on its right.
80    pub right: Vec2,
81    /// Nonnegative velocity magnitude in world units per second.
82    pub speed: f32,
83    /// Signed velocity along the heading; negative means reversing.
84    pub forward_speed: f32,
85    /// Signed velocity to the right; negative means sliding left.
86    pub lateral_speed: f32,
87    /// Velocity angle relative to forward, in `[-PI, PI]`, positive to the right.
88    /// Exactly stationary motion reports zero; straight reverse reports +/- PI.
89    pub slip_angle: f32,
90    /// Current smoothed yaw rate in radians per second.
91    pub turn_rate: f32,
92}
93#[derive(Clone, Copy, Debug, PartialEq)]
94pub struct PlanarState {
95    pub position: Vec2,
96    pub velocity: Vec2,
97    pub yaw: f32,
98    pub turn_rate: f32,
99}
100#[derive(Clone, Copy, Debug, Default)]
101pub struct DriveInput {
102    pub throttle: f32,
103    pub steer: f32,
104    pub brake: f32,
105}
106impl PlanarState {
107    /// Read heading, speed and slip without advancing or modifying the motor.
108    ///
109    /// Returns [`VehicleError::Invalid`] if any state field is nonfinite or a
110    /// derived speed cannot be represented as a finite `f32`.
111    ///
112    /// ```
113    /// use ferravex_math::Vec2;
114    /// use ferravex_play::vehicle::PlanarState;
115    /// let motor = PlanarState {
116    ///     position: Vec2::ZERO, velocity: Vec2::new(3., 4.), yaw: 0., turn_rate: 0.,
117    /// };
118    /// let hud = motor.telemetry()?;
119    /// assert_eq!((hud.speed, hud.forward_speed, hud.lateral_speed), (5., 4., 3.));
120    /// assert!(hud.slip_angle > 0.); // Sliding to the right.
121    /// # Ok::<(), ferravex_play::vehicle::VehicleError>(())
122    /// ```
123    pub fn telemetry(&self) -> Result<PlanarTelemetry, VehicleError> {
124        if !self.position.is_finite()
125            || !self.velocity.is_finite()
126            || !self.yaw.is_finite()
127            || !self.turn_rate.is_finite()
128        {
129            return Err(VehicleError::Invalid);
130        }
131        let forward = Vec2::new(self.yaw.sin(), self.yaw.cos());
132        let right = Vec2::new(forward.y, -forward.x);
133        let speed = self.velocity.x.hypot(self.velocity.y);
134        let forward_speed = self.velocity.dot(forward);
135        let lateral_speed = self.velocity.dot(right);
136        if ![speed, forward_speed, lateral_speed]
137            .iter()
138            .all(|v| v.is_finite())
139        {
140            return Err(VehicleError::Invalid);
141        }
142        Ok(PlanarTelemetry {
143            forward,
144            right,
145            speed,
146            forward_speed,
147            lateral_speed,
148            slip_angle: if speed == 0. {
149                0.
150            } else {
151                lateral_speed.atan2(forward_speed)
152            },
153            turn_rate: self.turn_rate,
154        })
155    }
156
157    /// Replace pose and linear velocity, clearing the smoothed turn rate.
158    ///
159    /// Position, yaw and velocity must be finite, and velocity magnitude must be
160    /// at most `10000` (the largest supported handling speed). Yaw is retained as
161    /// supplied; the next step applies its usual wrapping and speed cap. Pass
162    /// [`Vec2::ZERO`] to stop. Invalid targets leave every field unchanged, while
163    /// a valid target can repair an invalid old state. No simulation tick elapses.
164    /// Reset the host's previous pose too, to avoid interpolating across a teleport.
165    ///
166    /// ```
167    /// use ferravex_math::Vec2;
168    /// use ferravex_play::vehicle::PlanarState;
169    /// let mut motor = PlanarState {
170    ///     position: Vec2::ZERO, velocity: Vec2::X * 8., yaw: 1., turn_rate: 2.,
171    /// };
172    /// motor.reset(Vec2::new(10., 20.), 0., Vec2::ZERO)?;
173    /// assert_eq!(motor.position, Vec2::new(10., 20.));
174    /// assert_eq!((motor.telemetry()?.speed, motor.turn_rate), (0., 0.));
175    /// # Ok::<(), ferravex_play::vehicle::VehicleError>(())
176    /// ```
177    pub fn reset(&mut self, position: Vec2, yaw: f32, velocity: Vec2) -> Result<(), VehicleError> {
178        if !position.is_finite()
179            || !yaw.is_finite()
180            || !velocity.is_finite()
181            || velocity.x.hypot(velocity.y) > 10000.
182        {
183            return Err(VehicleError::Invalid);
184        }
185        *self = Self {
186            position,
187            velocity,
188            yaw,
189            turn_rate: 0.,
190        };
191        Ok(())
192    }
193
194    pub fn step(
195        &mut self,
196        p: PlanarHandling,
197        input: DriveInput,
198        dt: f32,
199    ) -> Result<(), VehicleError> {
200        if !time(dt)
201            || p.validate().is_err()
202            || !self.position.is_finite()
203            || !self.velocity.is_finite()
204            || !self.yaw.is_finite()
205            || !self.turn_rate.is_finite()
206            || ![input.throttle, input.steer, input.brake]
207                .iter()
208                .all(|v| v.is_finite())
209        {
210            return Err(VehicleError::Invalid);
211        }
212        let desired = input.steer.clamp(-1., 1.)
213            * (p.base_turn + self.velocity.length().min(p.turn_speed_cap) * p.speed_turn);
214        self.turn_rate += (desired - self.turn_rate) * crate::motion::response(p.response, dt);
215        self.yaw = (self.yaw + self.turn_rate * dt).rem_euclid(std::f32::consts::TAU);
216        let forward = Vec2::new(self.yaw.sin(), self.yaw.cos());
217        let side = Vec2::new(forward.y, -forward.x);
218        self.velocity -= side * self.velocity.dot(side) * crate::motion::response(p.grip, dt);
219        self.velocity += forward * input.throttle.clamp(-1., 1.) * p.acceleration * dt;
220        let speed = self.velocity.length();
221        if speed > 0. {
222            self.velocity *= ((speed - input.brake.clamp(0., 1.) * p.braking * dt).max(0.) / speed)
223                * (-p.drag * dt).exp();
224        }
225        self.velocity = self.velocity.clamp_length_max(p.max_speed);
226        self.position += self.velocity * dt;
227        Ok(())
228    }
229}
230#[derive(Clone, Copy, Debug)]
231pub struct FlightHandling {
232    pub turn_rate: f32,
233    pub turn_response: f32,
234    pub pitch_limit: f32,
235    pub pitch_response: f32,
236    pub bank_limit: f32,
237    pub bank_response: f32,
238    pub speed_response: f32,
239}
240impl Default for FlightHandling {
241    fn default() -> Self {
242        Self {
243            turn_rate: 1.15,
244            turn_response: 9.,
245            pitch_limit: 0.58,
246            pitch_response: 4.2,
247            bank_limit: 0.7,
248            bank_response: 5.,
249            speed_response: 2.5,
250        }
251    }
252}
253impl FlightHandling {
254    /// Check finite coefficients in `0..=10000`, pitch limit in `0..=1.5`
255    /// radians and bank limit in `0..=PI` radians.
256    ///
257    /// These are exactly the handling limits enforced by [`FlightState::step`].
258    /// Zero responses are valid and freeze their corresponding smoothing.
259    ///
260    /// ```
261    /// use ferravex_play::vehicle::{FlightHandling, VehicleError};
262    /// let mut handling = FlightHandling::default();
263    /// assert_eq!(handling.validate(), Ok(()));
264    /// handling.pitch_limit = 1.6;
265    /// assert_eq!(handling.validate(), Err(VehicleError::Invalid));
266    /// ```
267    pub fn validate(&self) -> Result<(), VehicleError> {
268        if valid(&[
269            self.turn_rate,
270            self.turn_response,
271            self.pitch_limit,
272            self.pitch_response,
273            self.bank_limit,
274            self.bank_response,
275            self.speed_response,
276        ]) && self.pitch_limit <= 1.5
277            && self.bank_limit <= std::f32::consts::PI
278        {
279            Ok(())
280        } else {
281            Err(VehicleError::Invalid)
282        }
283    }
284}
285
286/// An assisted-flight snapshot produced by [`FlightState::telemetry`].
287/// This motor has no position or terrain knowledge, so altitude and clearance
288/// remain host measurements. Bank is visual and does not rotate the velocity.
289#[derive(Clone, Copy, Debug, PartialEq)]
290pub struct FlightTelemetry {
291    /// Unit heading; yaw and pitch zero face positive Z, with positive Y up.
292    pub forward: Vec3,
293    /// Candidate world velocity in units per second, before host collisions.
294    pub velocity: Vec3,
295    /// Signed speed along forward, matching [`FlightState::speed`].
296    pub speed: f32,
297    /// Nonnegative velocity magnitude in the world XZ plane.
298    pub horizontal_speed: f32,
299    /// Signed world Y velocity; positive means climbing.
300    pub vertical_speed: f32,
301    /// Pitch in radians, positive above the horizontal plane.
302    pub pitch: f32,
303    /// Visual bank in radians, matching [`FlightState::bank`].
304    pub bank: f32,
305    /// Current smoothed yaw rate in radians per second.
306    pub turn_rate: f32,
307}
308#[derive(Clone, Copy, Debug, PartialEq)]
309pub struct FlightState {
310    pub yaw: f32,
311    pub pitch: f32,
312    pub bank: f32,
313    pub turn_rate: f32,
314    pub speed: f32,
315}
316impl FlightState {
317    pub fn forward(&self) -> Vec3 {
318        Vec3::new(
319            self.yaw.sin() * self.pitch.cos(),
320            self.pitch.sin(),
321            self.yaw.cos() * self.pitch.cos(),
322        )
323    }
324
325    /// Read flight velocity and climb information without advancing the motor.
326    ///
327    /// Returns [`VehicleError::Invalid`] for any nonfinite state field or derived
328    /// velocity/speed. Finite signed speed is reported as stored, including a
329    /// negative speed assigned directly to the public state.
330    ///
331    /// ```
332    /// use ferravex_play::vehicle::FlightState;
333    /// let motor = FlightState {
334    ///     yaw: 0., pitch: 0.6_f32.asin(), bank: 0.4, turn_rate: 0., speed: 10.,
335    /// };
336    /// let hud = motor.telemetry()?;
337    /// assert!((hud.vertical_speed - 6.).abs() < 0.0001);
338    /// assert!((hud.horizontal_speed - 8.).abs() < 0.0001);
339    /// # Ok::<(), ferravex_play::vehicle::VehicleError>(())
340    /// ```
341    pub fn telemetry(&self) -> Result<FlightTelemetry, VehicleError> {
342        if ![self.yaw, self.pitch, self.bank, self.turn_rate, self.speed]
343            .iter()
344            .all(|v| v.is_finite())
345        {
346            return Err(VehicleError::Invalid);
347        }
348        let forward = self.forward();
349        let velocity = forward * self.speed;
350        let horizontal_speed = velocity.x.hypot(velocity.z);
351        if !velocity.is_finite() || !horizontal_speed.is_finite() {
352            return Err(VehicleError::Invalid);
353        }
354        Ok(FlightTelemetry {
355            forward,
356            velocity,
357            speed: self.speed,
358            horizontal_speed,
359            vertical_speed: velocity.y,
360            pitch: self.pitch,
361            bank: self.bank,
362            turn_rate: self.turn_rate,
363        })
364    }
365
366    /// Replace flight heading, pitch and speed, clearing bank and turn rate.
367    ///
368    /// Yaw must be finite and is retained without wrapping. Pitch must be finite
369    /// in `-1.5..=1.5` radians and speed in `0..=10000`; these are the motor's
370    /// supported pitch/target-speed bounds. The next step approaches its supplied
371    /// handling limits normally. Invalid targets leave every field unchanged;
372    /// valid targets can repair invalid old state. Pass speed zero to stop.
373    /// The host owns position and must reset its interpolation/camera history.
374    ///
375    /// ```
376    /// use ferravex_play::vehicle::FlightState;
377    /// let mut motor = FlightState {
378    ///     yaw: 2., pitch: -0.5, bank: 0.7, turn_rate: 1., speed: 35.,
379    /// };
380    /// motor.reset(0., 0., 24.)?;
381    /// assert_eq!((motor.bank, motor.turn_rate, motor.speed), (0., 0., 24.));
382    /// # Ok::<(), ferravex_play::vehicle::VehicleError>(())
383    /// ```
384    pub fn reset(&mut self, yaw: f32, pitch: f32, speed: f32) -> Result<(), VehicleError> {
385        if !yaw.is_finite() || !(-1.5..=1.5).contains(&pitch) || !valid(&[speed]) {
386            return Err(VehicleError::Invalid);
387        }
388        *self = Self {
389            yaw,
390            pitch,
391            bank: 0.,
392            turn_rate: 0.,
393            speed,
394        };
395        Ok(())
396    }
397
398    pub fn step(
399        &mut self,
400        p: FlightHandling,
401        turn: f32,
402        climb: f32,
403        target_speed: f32,
404        dt: f32,
405    ) -> Result<(), VehicleError> {
406        if !time(dt)
407            || p.validate().is_err()
408            || !valid(&[target_speed])
409            || ![
410                self.yaw,
411                self.pitch,
412                self.bank,
413                self.turn_rate,
414                self.speed,
415                turn,
416                climb,
417            ]
418            .iter()
419            .all(|v| v.is_finite())
420        {
421            return Err(VehicleError::Invalid);
422        }
423        let turn = turn.clamp(-1., 1.);
424        self.turn_rate +=
425            (turn * p.turn_rate - self.turn_rate) * crate::motion::response(p.turn_response, dt);
426        self.yaw += self.turn_rate * dt;
427        self.pitch += (climb.clamp(-1., 1.) * p.pitch_limit - self.pitch)
428            * crate::motion::response(p.pitch_response, dt);
429        self.bank +=
430            (-turn * p.bank_limit - self.bank) * crate::motion::response(p.bank_response, dt);
431        self.speed += (target_speed - self.speed) * crate::motion::response(p.speed_response, dt);
432        Ok(())
433    }
434}
435#[cfg(test)]
436mod tests {
437    use super::*;
438
439    fn skimmer_handling() -> PlanarHandling {
440        PlanarHandling {
441            acceleration: 19.,
442            braking: 30.,
443            drag: 0.62,
444            grip: 5.,
445            max_speed: 30.,
446            base_turn: 1.15,
447            speed_turn: 0.018,
448            turn_speed_cap: 32.,
449            response: 12.,
450        }
451    }
452
453    fn planar() -> PlanarState {
454        PlanarState {
455            position: Vec2::new(12., 30.),
456            velocity: Vec2::new(3., 4.),
457            yaw: 0.,
458            turn_rate: 0.7,
459        }
460    }
461
462    fn flight() -> FlightState {
463        FlightState {
464            yaw: 0.,
465            pitch: 0.6_f32.asin(),
466            bank: -0.3,
467            turn_rate: 0.7,
468            speed: 10.,
469        }
470    }
471
472    #[test]
473    fn planar_validation_matches_step_for_every_coefficient() {
474        assert_eq!(skimmer_handling().validate(), Ok(()));
475        for field in 0..9 {
476            for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.001, 10001.] {
477                let mut p = skimmer_handling();
478                let fields = [
479                    &mut p.acceleration,
480                    &mut p.braking,
481                    &mut p.drag,
482                    &mut p.grip,
483                    &mut p.max_speed,
484                    &mut p.base_turn,
485                    &mut p.speed_turn,
486                    &mut p.turn_speed_cap,
487                    &mut p.response,
488                ];
489                *fields[field] = value;
490                assert_eq!(p.validate(), Err(VehicleError::Invalid));
491                let mut s = planar();
492                assert_eq!(
493                    s.step(p, DriveInput::default(), 0.01),
494                    Err(VehicleError::Invalid)
495                );
496                assert_eq!(s, planar());
497            }
498        }
499        for value in [0., 10000.] {
500            let p = PlanarHandling {
501                acceleration: value,
502                braking: value,
503                drag: value,
504                grip: value,
505                max_speed: value,
506                base_turn: value,
507                speed_turn: value,
508                turn_speed_cap: value,
509                response: value,
510            };
511            assert_eq!(p.validate(), Ok(()));
512            assert_eq!(planar().step(p, DriveInput::default(), 0.01), Ok(()));
513        }
514    }
515
516    #[test]
517    fn flight_validation_matches_step_and_preserves_defaults() {
518        let p = FlightHandling::default();
519        assert_eq!(
520            [
521                p.turn_rate,
522                p.turn_response,
523                p.pitch_limit,
524                p.pitch_response,
525                p.bank_limit,
526                p.bank_response,
527                p.speed_response,
528            ],
529            [1.15, 9., 0.58, 4.2, 0.7, 5., 2.5]
530        );
531        assert_eq!(p.validate(), Ok(()));
532        for field in 0..7 {
533            for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.001, 10001.] {
534                let mut p = FlightHandling::default();
535                let fields = [
536                    &mut p.turn_rate,
537                    &mut p.turn_response,
538                    &mut p.pitch_limit,
539                    &mut p.pitch_response,
540                    &mut p.bank_limit,
541                    &mut p.bank_response,
542                    &mut p.speed_response,
543                ];
544                *fields[field] = value;
545                assert_eq!(p.validate(), Err(VehicleError::Invalid));
546                let mut s = flight();
547                assert_eq!(s.step(p, 0., 0., 24., 0.01), Err(VehicleError::Invalid));
548                assert_eq!(s, flight());
549            }
550        }
551        for (pitch_limit, bank_limit, valid) in [
552            (0., 0., true),
553            (1.5, std::f32::consts::PI, true),
554            (1.5001, 0., false),
555            (0., std::f32::consts::PI + 0.0001, false),
556        ] {
557            for value in [0., 10000.] {
558                let p = FlightHandling {
559                    turn_rate: value,
560                    turn_response: value,
561                    pitch_limit,
562                    pitch_response: value,
563                    bank_limit,
564                    bank_response: value,
565                    speed_response: value,
566                };
567                assert_eq!(p.validate().is_ok(), valid);
568                assert_eq!(flight().step(p, 0., 0., 24., 0.01).is_ok(), valid);
569            }
570        }
571    }
572
573    #[test]
574    fn planar_telemetry_reports_forward_reverse_sideways_and_stationary_motion() {
575        let mut s = planar();
576        let t = s.telemetry().unwrap();
577        assert_eq!((t.forward, t.right), (Vec2::Y, Vec2::X));
578        assert_eq!((t.speed, t.forward_speed, t.lateral_speed), (5., 4., 3.));
579        assert_eq!(t.slip_angle, 3_f32.atan2(4.));
580        assert_eq!(t.turn_rate, s.turn_rate);
581        assert_eq!(s, planar());
582        for (velocity, forward, lateral, angle) in [
583            (Vec2::ZERO, 0., 0., 0.),
584            (Vec2::Y * 8., 8., 0., 0.),
585            (-Vec2::Y * 8., -8., 0., std::f32::consts::PI),
586            (-Vec2::X * 8., 0., -8., -std::f32::consts::FRAC_PI_2),
587        ] {
588            s.velocity = velocity;
589            let t = s.telemetry().unwrap();
590            assert_eq!((t.forward_speed, t.lateral_speed), (forward, lateral));
591            assert!((t.slip_angle - angle).abs() < 1e-6);
592        }
593        s.yaw = std::f32::consts::FRAC_PI_2;
594        s.velocity = Vec2::new(4., 3.);
595        let t = s.telemetry().unwrap();
596        assert!(t.forward.abs_diff_eq(Vec2::X, 1e-6));
597        assert!(t.right.abs_diff_eq(-Vec2::Y, 1e-6));
598        assert!((t.forward_speed - 4.).abs() < 1e-6);
599        assert!((t.lateral_speed + 3.).abs() < 1e-6);
600    }
601
602    #[test]
603    fn flight_telemetry_reports_climb_descent_and_bank_independent_velocity() {
604        let mut s = flight();
605        let t = s.telemetry().unwrap();
606        assert_eq!(s, flight());
607        assert_eq!(
608            (t.speed, t.pitch, t.bank, t.turn_rate),
609            (10., s.pitch, -0.3, 0.7)
610        );
611        assert!((t.forward.length() - 1.).abs() < 1e-6);
612        assert!(t.velocity.abs_diff_eq(Vec3::new(0., 6., 8.), 1e-6));
613        assert!((t.horizontal_speed - 8.).abs() < 1e-6);
614        assert!((t.vertical_speed - 6.).abs() < 1e-6);
615        s.bank = 1.;
616        assert_eq!(s.telemetry().unwrap().velocity, t.velocity);
617        s.pitch = -s.pitch;
618        s.yaw = std::f32::consts::FRAC_PI_2;
619        let t = s.telemetry().unwrap();
620        assert!(t.velocity.abs_diff_eq(Vec3::new(8., -6., 0.), 1e-6));
621        assert!(t.vertical_speed < 0.);
622        s.speed = -10.;
623        let reversed = s.telemetry().unwrap();
624        assert_eq!(reversed.speed, -10.);
625        assert_eq!(reversed.velocity, -t.velocity);
626        assert_eq!(reversed.horizontal_speed, t.horizontal_speed);
627        s.speed = 0.;
628        let stopped = s.telemetry().unwrap();
629        assert_eq!(stopped.velocity, Vec3::ZERO);
630        assert_eq!((stopped.horizontal_speed, stopped.vertical_speed), (0., 0.));
631    }
632
633    #[test]
634    fn telemetry_rejects_nonfinite_state_and_unrepresentable_speed() {
635        for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
636            for field in 0..6 {
637                let mut s = planar();
638                let fields = [
639                    &mut s.position.x,
640                    &mut s.position.y,
641                    &mut s.velocity.x,
642                    &mut s.velocity.y,
643                    &mut s.yaw,
644                    &mut s.turn_rate,
645                ];
646                *fields[field] = value;
647                assert_eq!(s.telemetry(), Err(VehicleError::Invalid));
648            }
649            for field in 0..5 {
650                let mut s = flight();
651                let fields = [
652                    &mut s.yaw,
653                    &mut s.pitch,
654                    &mut s.bank,
655                    &mut s.turn_rate,
656                    &mut s.speed,
657                ];
658                *fields[field] = value;
659                assert_eq!(s.telemetry(), Err(VehicleError::Invalid));
660            }
661        }
662        let mut s = planar();
663        s.velocity = Vec2::splat(f32::MAX);
664        assert_eq!(s.telemetry(), Err(VehicleError::Invalid));
665        s.velocity = Vec2::X * 1e30;
666        assert_eq!(s.telemetry().unwrap().speed, 1e30);
667        s.velocity = Vec2::X * f32::from_bits(1);
668        assert_eq!(s.telemetry().unwrap().speed, f32::from_bits(1));
669    }
670
671    #[test]
672    fn planar_reset_is_atomic_and_repairs_corrupt_state() {
673        let mut s = planar();
674        for (position, yaw, velocity) in [
675            (Vec2::new(f32::NAN, 0.), 0., Vec2::ZERO),
676            (Vec2::new(0., f32::INFINITY), 0., Vec2::ZERO),
677            (Vec2::ZERO, f32::NAN, Vec2::ZERO),
678            (Vec2::ZERO, f32::INFINITY, Vec2::ZERO),
679            (Vec2::ZERO, 0., Vec2::new(0., f32::NAN)),
680            (Vec2::ZERO, 0., Vec2::new(f32::INFINITY, 0.)),
681            (Vec2::ZERO, 0., Vec2::splat(8000.)),
682            (Vec2::ZERO, 0., Vec2::splat(f32::MAX)),
683        ] {
684            assert_eq!(s.reset(position, yaw, velocity), Err(VehicleError::Invalid));
685            assert_eq!(s, planar());
686        }
687        s = PlanarState {
688            position: Vec2::splat(f32::NAN),
689            velocity: Vec2::splat(f32::INFINITY),
690            yaw: f32::NAN,
691            turn_rate: f32::NEG_INFINITY,
692        };
693        s.reset(Vec2::new(50., -20.), -2., Vec2::new(6000., 8000.))
694            .unwrap();
695        assert_eq!(s.position, Vec2::new(50., -20.));
696        assert_eq!(s.velocity, Vec2::new(6000., 8000.));
697        assert_eq!((s.yaw, s.turn_rate), (-2., 0.));
698        assert_eq!(s.telemetry().unwrap().speed, 10000.);
699        s.reset(Vec2::ZERO, 0., Vec2::ZERO).unwrap();
700        assert_eq!(s.telemetry().unwrap().speed, 0.);
701    }
702
703    #[test]
704    fn flight_reset_is_atomic_and_repairs_corrupt_state() {
705        let mut s = flight();
706        for (yaw, pitch, speed) in [
707            (f32::NAN, 0., 24.),
708            (f32::INFINITY, 0., 24.),
709            (0., f32::NAN, 24.),
710            (0., f32::INFINITY, 24.),
711            (0., -1.5001, 24.),
712            (0., 1.5001, 24.),
713            (0., 0., f32::NAN),
714            (0., 0., f32::INFINITY),
715            (0., 0., -0.001),
716            (0., 0., 10001.),
717        ] {
718            assert_eq!(s.reset(yaw, pitch, speed), Err(VehicleError::Invalid));
719            assert_eq!(s, flight());
720        }
721        s = FlightState {
722            yaw: f32::NAN,
723            pitch: f32::NAN,
724            bank: f32::NAN,
725            turn_rate: f32::INFINITY,
726            speed: f32::NEG_INFINITY,
727        };
728        for (pitch, speed) in [(-1.5, 0.), (1.5, 10000.)] {
729            s.reset(-2., pitch, speed).unwrap();
730            assert_eq!((s.yaw, s.pitch, s.speed), (-2., pitch, speed));
731            assert_eq!((s.bank, s.turn_rate), (0., 0.));
732            assert!(s.telemetry().is_ok());
733        }
734    }
735
736    #[test]
737    fn reset_and_telemetry_preserve_subsequent_fixed_tick_motion() {
738        let mut observed_planar = planar();
739        observed_planar
740            .reset(Vec2::new(5., 2.), -1., Vec2::Y * 2.)
741            .unwrap();
742        let mut reference_planar = PlanarState {
743            position: Vec2::new(5., 2.),
744            velocity: Vec2::Y * 2.,
745            yaw: -1.,
746            turn_rate: 0.,
747        };
748        let mut observed_flight = flight();
749        observed_flight.reset(-1., 0.1, 24.).unwrap();
750        let mut reference_flight = FlightState {
751            yaw: -1.,
752            pitch: 0.1,
753            bank: 0.,
754            turn_rate: 0.,
755            speed: 24.,
756        };
757        for tick in 0..120 {
758            // HUDs may be sampled several times between simulation ticks.
759            for _ in 0..3 {
760                observed_planar.telemetry().unwrap();
761                observed_flight.telemetry().unwrap();
762            }
763            let steer = if tick < 60 { 0.7 } else { -0.4 };
764            let input = DriveInput {
765                throttle: 1.,
766                steer,
767                brake: 0.2,
768            };
769            observed_planar
770                .step(skimmer_handling(), input, 1. / 60.)
771                .unwrap();
772            reference_planar
773                .step(skimmer_handling(), input, 1. / 60.)
774                .unwrap();
775            observed_flight
776                .step(FlightHandling::default(), steer, 0.2, 35., 1. / 60.)
777                .unwrap();
778            reference_flight
779                .step(FlightHandling::default(), steer, 0.2, 35., 1. / 60.)
780                .unwrap();
781            assert_eq!(observed_planar, reference_planar);
782            assert_eq!(observed_flight, reference_flight);
783        }
784    }
785
786    #[test]
787    fn brakes_stop_without_reverse_and_grip_removes_slip() {
788        let mut s = PlanarState {
789            position: Vec2::ZERO,
790            velocity: Vec2::new(10., 10.),
791            yaw: 0.,
792            turn_rate: 0.,
793        };
794        let p = PlanarHandling {
795            acceleration: 0.,
796            braking: 100.,
797            drag: 0.,
798            grip: 10.,
799            max_speed: 20.,
800            base_turn: 1.,
801            speed_turn: 0.,
802            turn_speed_cap: 20.,
803            response: 10.,
804        };
805        for _ in 0..60 {
806            s.step(
807                p,
808                DriveInput {
809                    brake: 1.,
810                    ..Default::default()
811                },
812                1. / 60.,
813            )
814            .unwrap();
815        }
816        assert!(s.velocity.length() < 0.001);
817        assert!(s.position.y >= 0.);
818        let old = s;
819        assert!(
820            s.step(
821                p,
822                DriveInput {
823                    steer: f32::NAN,
824                    ..Default::default()
825                },
826                0.1
827            )
828            .is_err()
829        );
830        assert_eq!(s, old);
831    }
832    #[test]
833    fn flight_limits_and_clock_partition() {
834        let mut a = FlightState {
835            yaw: 0.,
836            pitch: 0.,
837            bank: 0.,
838            turn_rate: 0.,
839            speed: 0.,
840        };
841        let mut b = a;
842        for _ in 0..100 {
843            a.step(FlightHandling::default(), 1., 1., 24., 0.01)
844                .unwrap();
845        }
846        for _ in 0..50 {
847            b.step(FlightHandling::default(), 1., 1., 24., 0.02)
848                .unwrap();
849        }
850        assert!((a.speed - b.speed).abs() < 0.0001);
851        assert!(a.pitch <= 0.58 && a.bank >= -0.7);
852        assert!((a.forward().length() - 1.).abs() < 0.0001);
853    }
854}