ferravex_play/ai/
squad.rs

1//! Last-known radio contacts and exclusive, expiring cover leases. The host owns
2//! faction membership, sensing, reachability and weapon authority.
3//!
4//! Inspect leases with [`SquadBoard::reservations`] and promptly release abandoned
5//! cover with [`SquadBoard::retain_reservations`]. Neither operation refreshes a
6//! lease; [`SquadBoard::advance`] ages leases using supplied simulation time.
7use super::{AiError, Candidate, VisibilityQuery, WorkBudget};
8use ferravex_math::Vec3;
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum SquadRole {
11    Assault,
12    FlankLeft,
13    FlankRight,
14    Support,
15}
16impl SquadRole {
17    pub fn for_member(id: u64) -> Self {
18        match id % 4 {
19            0 => Self::Support,
20            1 => Self::Assault,
21            2 => Self::FlankLeft,
22            _ => Self::FlankRight,
23        }
24    }
25    /// A suggested destination, never permission to move through world geometry.
26    pub fn goal(self, target: Vec3, from: Vec3, up: Vec3, radius: f32) -> Result<Vec3, AiError> {
27        if !target.is_finite()
28            || !from.is_finite()
29            || !up.is_finite()
30            || up.length_squared() < 0.5
31            || !radius.is_finite()
32            || !(0. ..=100.).contains(&radius)
33        {
34            return Err(AiError::InvalidInput);
35        }
36        let side = up
37            .normalize_or_zero()
38            .cross(target - from)
39            .normalize_or_zero()
40            * radius;
41        Ok(match self {
42            Self::FlankLeft => target + side,
43            Self::FlankRight => target - side,
44            _ => target,
45        })
46    }
47}
48#[derive(Clone, Copy, Debug)]
49pub struct RadioContact {
50    pub candidate: Candidate,
51    pub revision: u64,
52    pub age: f32,
53}
54/// A value snapshot of an active cover lease, in simulation time.
55///
56/// Changing this value does not change the board. It is not an ownership token
57/// or a guarantee of reachability, safety or continued ownership after the board
58/// changes. See [`SquadBoard::reservations`] for a compiling inspection example.
59#[derive(Clone, Copy, Debug, PartialEq)]
60pub struct CoverReservation {
61    /// Nonzero member ID supplied to [`SquadBoard::reserve`].
62    pub owner: u64,
63    /// The reserved cover point.
64    pub position: Vec3,
65    /// Remaining simulation seconds, greater than zero and at most 1.5.
66    pub remaining_seconds: f32,
67}
68#[derive(Clone, Copy, Debug)]
69struct Lease {
70    owner: u64,
71    seconds: f32,
72}
73#[derive(Clone, Debug)]
74pub struct SquadBoard<const C: usize> {
75    cover: [Vec3; C],
76    leases: [Option<Lease>; C],
77    contact: Option<RadioContact>,
78    revision: u64,
79}
80impl<const C: usize> SquadBoard<C> {
81    pub fn new(cover: [Vec3; C]) -> Result<Self, AiError> {
82        if C > 64 || cover.iter().any(|p| !p.is_finite()) {
83            return Err(AiError::InvalidConfiguration);
84        }
85        Ok(Self {
86            cover,
87            leases: [None; C],
88            contact: None,
89            revision: 0,
90        })
91    }
92    /// Call only for a validated fresh observation, never for a radio echo.
93    pub fn report(&mut self, candidate: Candidate) -> Result<(), AiError> {
94        if !candidate.position.is_finite() {
95            return Err(AiError::InvalidInput);
96        }
97        self.revision = self.revision.checked_add(1).ok_or(AiError::InvalidState)?;
98        self.contact = Some(RadioContact {
99            candidate,
100            revision: self.revision,
101            age: 0.,
102        });
103        Ok(())
104    }
105    pub fn contact(&self) -> Option<RadioContact> {
106        self.contact
107    }
108    pub fn forget(&mut self) {
109        self.contact = None;
110    }
111    /// Age contacts and leases by supplied simulation seconds.
112    ///
113    /// Call once per actual fixed tick, including while a local menu is open if
114    /// authoritative simulation continues. Leases expire when their remaining
115    /// time reaches zero; contacts expire at three seconds. Inspection and
116    /// retention do not advance time. Nonfinite `dt` or values outside `0..=60`
117    /// return [`AiError::InvalidInput`] without changing the board.
118    pub fn advance(&mut self, dt: f32) -> Result<(), AiError> {
119        if !dt.is_finite() || !(0. ..=60.).contains(&dt) {
120            return Err(AiError::InvalidInput);
121        }
122        if let Some(c) = &mut self.contact {
123            c.age += dt;
124            if c.age >= 3. {
125                self.contact = None;
126            }
127        }
128        for l in &mut self.leases {
129            if let Some(v) = l {
130                v.seconds -= dt;
131                if v.seconds <= 0. {
132                    *l = None;
133                }
134            }
135        }
136        Ok(())
137    }
138    /// Inspect active cover leases in the original cover-array order.
139    ///
140    /// Visits at most `C` slots without allocation, queries or timer changes.
141    /// An owner has at most one lease, and duplicate cover points appear at most
142    /// once. Use `find` to inspect a particular member's lease.
143    ///
144    /// ```
145    /// use ferravex_math::Vec3;
146    /// use ferravex_play::ai::{CoverReservation, SquadBoard, VisibilityQuery, WorkBudget};
147    /// struct Wall;
148    /// impl VisibilityQuery for Wall {
149    ///     fn clear(&mut self, _: Vec3, _: Vec3) -> bool { false }
150    /// }
151    /// let mut board = SquadBoard::new([Vec3::X]).unwrap();
152    /// board.reserve(7, Vec3::ZERO, Vec3::Z,
153    ///     &mut WorkBudget::new(1, 1, 0), &mut Wall, |_| true).unwrap();
154    /// board.advance(0.5).unwrap();
155    /// let lease: CoverReservation = board.reservations().find(|r| r.owner == 7).unwrap();
156    /// assert_eq!(lease.position, Vec3::X);
157    /// assert_eq!(lease.remaining_seconds, 1.0);
158    /// board.advance(1.0).unwrap();
159    /// assert!(board.reservations().next().is_none());
160    /// ```
161    pub fn reservations(&self) -> impl Iterator<Item = CoverReservation> + '_ {
162        self.leases
163            .iter()
164            .zip(&self.cover)
165            .filter_map(|(lease, &position)| {
166                lease.map(|lease| CoverReservation {
167                    owner: lease.owner,
168                    position,
169                    remaining_seconds: lease.seconds,
170                })
171            })
172    }
173    /// Immediately release leases for which `keep` returns false, returning the
174    /// number released. For example, remove members that left the squad or whose
175    /// reserved cover is no longer reachable.
176    ///
177    /// Calls `keep` once per active lease in original cover-array order, at most
178    /// `C` times. This scan allocates nothing and performs no visibility queries;
179    /// the host controls any work in `keep`. Retained leases keep their remaining
180    /// lifetime, and radio contacts are unchanged. This does not replace calling
181    /// [`Self::advance`] each simulation tick. Call before new reservations when
182    /// departed members' cover should be immediately available to their peers.
183    ///
184    /// ```
185    /// use ferravex_math::Vec3;
186    /// use ferravex_play::ai::{SquadBoard, VisibilityQuery, WorkBudget};
187    /// struct Wall;
188    /// impl VisibilityQuery for Wall {
189    ///     fn clear(&mut self, _: Vec3, _: Vec3) -> bool { false }
190    /// }
191    /// let mut board = SquadBoard::new([Vec3::X, Vec3::Z]).unwrap();
192    /// for owner in [7, 8] {
193    ///     board.reserve(owner, Vec3::ZERO, Vec3::Y,
194    ///         &mut WorkBudget::new(2, 2, 0), &mut Wall, |_| true).unwrap();
195    /// }
196    /// let active_members = [8]; // Member 7 departed without explicitly releasing.
197    /// assert_eq!(board.retain_reservations(|r| active_members.contains(&r.owner)), 1);
198    /// assert_eq!(board.reserve(9, Vec3::ZERO, Vec3::Y,
199    ///     &mut WorkBudget::new(2, 2, 0), &mut Wall, |_| true).unwrap(), Some(Vec3::X));
200    /// ```
201    pub fn retain_reservations(&mut self, mut keep: impl FnMut(CoverReservation) -> bool) -> usize {
202        let mut released = 0;
203        for (slot, &position) in self.leases.iter_mut().zip(&self.cover) {
204            if slot.is_some_and(|lease| {
205                !keep(CoverReservation {
206                    owner: lease.owner,
207                    position,
208                    remaining_seconds: lease.seconds,
209                })
210            }) {
211                *slot = None;
212                released += 1;
213            }
214        }
215        released
216    }
217    pub fn release(&mut self, owner: u64) {
218        for l in &mut self.leases {
219            if l.is_some_and(|v| v.owner == owner) {
220                *l = None;
221            }
222        }
223    }
224    /// Tests at most C candidates and one occlusion query per eligible point.
225    /// `eligible` performs cheap host checks; a successful path is still required.
226    /// Equal distances prefer the first cover-array entry; duplicate points are
227    /// considered only at their first entry. Success replaces the owner's old
228    /// lease with a 1.5-second lease. Failure leaves any existing lease unchanged,
229    /// including its remaining lifetime.
230    pub fn reserve(
231        &mut self,
232        owner: u64,
233        from: Vec3,
234        threat: Vec3,
235        budget: &mut WorkBudget,
236        query: &mut impl VisibilityQuery,
237        mut eligible: impl FnMut(Vec3) -> bool,
238    ) -> Result<Option<Vec3>, AiError> {
239        if owner == 0 || !from.is_finite() || !threat.is_finite() {
240            return Err(AiError::InvalidInput);
241        }
242        let mut best = None;
243        let mut score = f32::INFINITY;
244        for (i, p) in self.cover.iter().copied().enumerate() {
245            if !budget.candidate() {
246                break;
247            }
248            if self.cover[..i].contains(&p) {
249                continue;
250            }
251            if self.leases[i].is_some_and(|l| l.owner != owner) || !eligible(p) {
252                continue;
253            }
254            if !budget.query() {
255                break;
256            }
257            if query.clear(p, threat) {
258                continue;
259            }
260            let cost = p.distance(from);
261            if cost < score {
262                score = cost;
263                best = Some(i);
264            }
265        }
266        if let Some(i) = best {
267            self.release(owner);
268            self.leases[i] = Some(Lease {
269                owner,
270                seconds: 1.5,
271            });
272            Ok(Some(self.cover[i]))
273        } else {
274            Ok(None)
275        }
276    }
277}
278#[cfg(test)]
279mod tests {
280    use super::*;
281    struct Wall;
282    impl VisibilityQuery for Wall {
283        fn clear(&mut self, _: Vec3, _: Vec3) -> bool {
284            false
285        }
286    }
287    fn reserve_at<const C: usize>(
288        board: &mut SquadBoard<C>,
289        owner: u64,
290        from: Vec3,
291    ) -> Option<Vec3> {
292        board
293            .reserve(
294                owner,
295                from,
296                Vec3::Y,
297                &mut WorkBudget::new(64, 64, 0),
298                &mut Wall,
299                |_| true,
300            )
301            .unwrap()
302    }
303    #[test]
304    fn snapshots_preserve_cover_order_and_duplicate_exclusivity() {
305        let mut board = SquadBoard::new([Vec3::Z, Vec3::X, Vec3::Z]).unwrap();
306        assert!(board.reservations().next().is_none());
307        assert_eq!(reserve_at(&mut board, 9, Vec3::ZERO), Some(Vec3::Z));
308        assert_eq!(reserve_at(&mut board, 2, Vec3::ZERO), Some(Vec3::X));
309        assert_eq!(reserve_at(&mut board, 3, Vec3::ZERO), None);
310        board.advance(0.5).unwrap();
311        let expected = [
312            CoverReservation {
313                owner: 9,
314                position: Vec3::Z,
315                remaining_seconds: 1.,
316            },
317            CoverReservation {
318                owner: 2,
319                position: Vec3::X,
320                remaining_seconds: 1.,
321            },
322        ];
323        assert!(board.reservations().eq(expected));
324        let mut snapshot = board.reservations().next().unwrap();
325        snapshot.owner = 3;
326        snapshot.remaining_seconds = 60.;
327        assert_ne!(snapshot, board.reservations().next().unwrap());
328        assert!(board.reservations().eq(expected));
329        board.advance(1.).unwrap();
330        assert!(board.reservations().next().is_none());
331        assert_eq!(reserve_at(&mut board, 3, Vec3::ZERO), Some(Vec3::Z));
332    }
333    #[test]
334    fn retention_releases_abandoned_cover_without_refreshing_survivors_or_radio() {
335        let mut board = SquadBoard::new([Vec3::X, Vec3::Z, -Vec3::X]).unwrap();
336        board
337            .report(Candidate {
338                id: 42,
339                position: Vec3::Y,
340                groups: 1,
341            })
342            .unwrap();
343        for owner in [9, 7, 8] {
344            assert!(reserve_at(&mut board, owner, Vec3::ZERO).is_some());
345        }
346        board.advance(0.5).unwrap();
347        let contact = board.contact().unwrap();
348        let before: Vec<_> = board.reservations().collect();
349        let mut visited = Vec::new();
350        assert_eq!(
351            board.retain_reservations(|r| {
352                visited.push(r);
353                // Member 9 departed, and the third point became unreachable.
354                r.owner != 9 && r.position != -Vec3::X
355            }),
356            2
357        );
358        assert_eq!(visited, before);
359        assert!(board.reservations().eq([before[1]]));
360        let after = board.contact().unwrap();
361        assert_eq!(after.candidate.id, contact.candidate.id);
362        assert_eq!(after.candidate.position, contact.candidate.position);
363        assert_eq!(after.candidate.groups, contact.candidate.groups);
364        assert_eq!(after.revision, contact.revision);
365        assert_eq!(after.age, contact.age);
366        assert_eq!(reserve_at(&mut board, 1, Vec3::ZERO), Some(Vec3::X));
367        board.advance(1.).unwrap();
368        assert!(board.reservations().eq([CoverReservation {
369            owner: 1,
370            position: Vec3::X,
371            remaining_seconds: 0.5,
372        }]));
373    }
374    #[test]
375    fn retained_cover_still_expires_on_the_exact_simulation_boundary() {
376        let mut board = SquadBoard::new([Vec3::X]).unwrap();
377        reserve_at(&mut board, 1, Vec3::ZERO).unwrap();
378        for _ in 0..5 {
379            board.advance(0.25).unwrap();
380            assert_eq!(board.retain_reservations(|_| true), 0);
381            assert_eq!(board.reservations().count(), 1);
382        }
383        assert_eq!(board.reservations().next().unwrap().remaining_seconds, 0.25);
384        assert_eq!(reserve_at(&mut board, 2, Vec3::ZERO), None);
385        board.advance(0.).unwrap();
386        assert_eq!(board.reservations().next().unwrap().remaining_seconds, 0.25);
387        board.advance(0.25).unwrap();
388        assert!(board.reservations().next().is_none());
389        assert_eq!(reserve_at(&mut board, 2, Vec3::ZERO), Some(Vec3::X));
390    }
391    #[test]
392    fn failed_reservations_do_not_refresh_an_existing_lease() {
393        let mut board = SquadBoard::new([Vec3::X]).unwrap();
394        reserve_at(&mut board, 1, Vec3::ZERO).unwrap();
395        board.advance(1.25).unwrap();
396        let before = board.reservations().next().unwrap();
397        for mut budget in [WorkBudget::new(0, 1, 0), WorkBudget::new(1, 0, 0)] {
398            assert_eq!(
399                board.reserve(1, Vec3::ZERO, Vec3::Y, &mut budget, &mut Wall, |_| true),
400                Ok(None)
401            );
402            assert_eq!(board.reservations().next(), Some(before));
403        }
404        assert_eq!(
405            board.reserve(
406                1,
407                Vec3::ZERO,
408                Vec3::Y,
409                &mut WorkBudget::new(1, 1, 0),
410                &mut Wall,
411                |_| false,
412            ),
413            Ok(None)
414        );
415        assert_eq!(
416            board.reserve(
417                1,
418                Vec3::ZERO,
419                Vec3::Y,
420                &mut WorkBudget::new(1, 1, 0),
421                &mut super::super::Unoccluded,
422                |_| true,
423            ),
424            Ok(None)
425        );
426        for (owner, from, threat) in [
427            (0, Vec3::ZERO, Vec3::Y),
428            (1, Vec3::splat(f32::INFINITY), Vec3::Y),
429            (1, Vec3::ZERO, Vec3::splat(f32::NAN)),
430        ] {
431            let mut budget = WorkBudget::new(1, 1, 0);
432            assert_eq!(
433                board.reserve(owner, from, threat, &mut budget, &mut Wall, |_| true),
434                Err(AiError::InvalidInput)
435            );
436            assert_eq!(budget.counts(), Default::default());
437        }
438        assert_eq!(board.reservations().next(), Some(before));
439        board.advance(0.25).unwrap();
440        assert!(board.reservations().next().is_none());
441    }
442    #[test]
443    fn successful_reservation_refreshes_only_the_owners_selected_point() {
444        let mut board = SquadBoard::new([Vec3::X, Vec3::Z, -Vec3::X]).unwrap();
445        assert_eq!(reserve_at(&mut board, 1, Vec3::ZERO), Some(Vec3::X));
446        assert_eq!(reserve_at(&mut board, 2, Vec3::ZERO), Some(Vec3::Z));
447        board.advance(1.).unwrap();
448        assert_eq!(reserve_at(&mut board, 1, -Vec3::X), Some(-Vec3::X));
449        assert!(board.reservations().eq([
450            CoverReservation {
451                owner: 2,
452                position: Vec3::Z,
453                remaining_seconds: 0.5,
454            },
455            CoverReservation {
456                owner: 1,
457                position: -Vec3::X,
458                remaining_seconds: 1.5,
459            },
460        ]));
461        assert_eq!(reserve_at(&mut board, 3, Vec3::ZERO), Some(Vec3::X));
462        board.advance(0.5).unwrap();
463        assert_eq!(reserve_at(&mut board, 1, -Vec3::X), Some(-Vec3::X));
464        assert_eq!(
465            board
466                .reservations()
467                .find(|r| r.owner == 1)
468                .unwrap()
469                .remaining_seconds,
470            1.5
471        );
472        assert_eq!(
473            board
474                .reservations()
475                .find(|r| r.owner == 3)
476                .unwrap()
477                .remaining_seconds,
478            1.
479        );
480        assert!(board.reservations().all(|r| r.owner != 2));
481        board.release(1);
482        board.release(0);
483        board.release(1);
484        assert!(board.reservations().all(|r| r.owner == 3));
485    }
486    #[test]
487    fn invalid_time_leaves_reservations_and_contact_unchanged() {
488        let mut board = SquadBoard::new([Vec3::X]).unwrap();
489        reserve_at(&mut board, u64::MAX, Vec3::ZERO).unwrap();
490        board
491            .report(Candidate {
492                id: 7,
493                position: Vec3::Z,
494                groups: 1,
495            })
496            .unwrap();
497        board.advance(0.5).unwrap();
498        let before = board.reservations().next();
499        let contact = board.contact().unwrap();
500        for dt in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.25, 61.] {
501            assert_eq!(board.advance(dt), Err(AiError::InvalidInput));
502            assert_eq!(board.reservations().next(), before);
503            assert_eq!(board.contact().unwrap().age, contact.age);
504            assert_eq!(board.contact().unwrap().revision, contact.revision);
505        }
506        board.advance(60.).unwrap();
507        assert!(board.reservations().next().is_none());
508        assert!(board.contact().is_none());
509    }
510    #[test]
511    fn retention_is_bounded_and_skips_empty_released_and_expired_slots() {
512        let mut empty = SquadBoard::<0>::new([]).unwrap();
513        assert!(empty.reservations().next().is_none());
514        assert_eq!(empty.retain_reservations(|_| panic!("empty board")), 0);
515        let mut board = SquadBoard::new(std::array::from_fn::<_, 64, _>(|i| {
516            Vec3::X * (i as f32 + 1.)
517        }))
518        .unwrap();
519        for owner in 1..=64 {
520            assert!(reserve_at(&mut board, owner, Vec3::ZERO).is_some());
521        }
522        assert_eq!(board.reservations().count(), 64);
523        let mut visited = 0;
524        assert_eq!(
525            board.retain_reservations(|r| {
526                visited += 1;
527                assert_eq!(r.owner, visited);
528                false
529            }),
530            64
531        );
532        assert_eq!(visited, 64);
533        assert!(board.reservations().next().is_none());
534        assert_eq!(board.retain_reservations(|_| panic!("released board")), 0);
535        reserve_at(&mut board, 1, Vec3::ZERO).unwrap();
536        board.advance(1.5).unwrap();
537        assert_eq!(board.retain_reservations(|_| panic!("expired board")), 0);
538    }
539    #[test]
540    fn leases_are_exclusive_expire_and_respect_budget() {
541        let mut board = SquadBoard::new([Vec3::X, Vec3::Z]).unwrap();
542        let mut b = WorkBudget::new(9, 9, 0);
543        assert_eq!(
544            board
545                .reserve(1, Vec3::ZERO, Vec3::Y, &mut b, &mut Wall, |_| true)
546                .unwrap(),
547            Some(Vec3::X)
548        );
549        assert_eq!(
550            board
551                .reserve(2, Vec3::ZERO, Vec3::Y, &mut b, &mut Wall, |_| true)
552                .unwrap(),
553            Some(Vec3::Z)
554        );
555        assert_eq!(
556            board
557                .reserve(3, Vec3::ZERO, Vec3::Y, &mut b, &mut Wall, |_| true)
558                .unwrap(),
559            None
560        );
561        board.advance(1.5).unwrap();
562        assert!(
563            board
564                .reserve(
565                    3,
566                    Vec3::ZERO,
567                    Vec3::Y,
568                    &mut WorkBudget::new(0, 0, 0),
569                    &mut Wall,
570                    |_| true
571                )
572                .unwrap()
573                .is_none()
574        );
575        board.release(2);
576        assert!(
577            board
578                .reserve(3, Vec3::ZERO, Vec3::Y, &mut b, &mut Wall, |_| true)
579                .unwrap()
580                .is_some()
581        );
582    }
583    #[test]
584    fn radio_is_last_known_and_flanks_differ() {
585        let mut b = SquadBoard::<0>::new([]).unwrap();
586        b.report(Candidate {
587            id: 7,
588            position: Vec3::Z,
589            groups: 1,
590        })
591        .unwrap();
592        let rev = b.contact().unwrap().revision;
593        b.advance(1.).unwrap();
594        assert_eq!(b.contact().unwrap().revision, rev);
595        assert_eq!(b.contact().unwrap().age, 1.);
596        b.advance(2.).unwrap();
597        assert!(b.contact().is_none());
598        assert_ne!(
599            SquadRole::FlankLeft
600                .goal(Vec3::Z, Vec3::ZERO, Vec3::Y, 3.)
601                .unwrap(),
602            SquadRole::FlankRight
603                .goal(Vec3::Z, Vec3::ZERO, Vec3::Y, 3.)
604                .unwrap()
605        );
606    }
607}