ferravex_play/gameplay/
magazine.rs

1//! Ammunition and reload timing. A shot spends one round only on acceptance.
2//!
3//! Advance with simulation time on actual ticks. Status queries do not advance
4//! the reload or emit completion; use the result of [`Magazine::advance`] for
5//! accepted reload feedback.
6//!
7//! ```
8//! use ferravex_play::gameplay::magazine::Magazine;
9//!
10//! let mut magazine = Magazine::new(4, 6, 2.0)?;
11//! assert_eq!(magazine.capacity(), 4);
12//! assert_eq!(magazine.total_ammo(), 10);
13//! assert!(magazine.can_fire());
14//! assert!(!magazine.can_reload());
15//! assert!(magazine.fire());
16//! assert!(magazine.can_reload());
17//! assert!(magazine.reload());
18//! assert!(!magazine.can_fire());
19//! assert!(!magazine.can_reload());
20//! assert!(!magazine.advance(0.5)?);
21//! let status = magazine.reload_status().unwrap();
22//! assert_eq!(status.duration_seconds, 2.0);
23//! assert_eq!(status.remaining_seconds, 1.5);
24//! assert_eq!(status.progress, 0.25);
25//! assert_eq!(status.rounds, 1);
26//! assert!(magazine.advance(1.5)?);
27//! assert_eq!(magazine.reload_status(), None);
28//! assert!(!magazine.advance(1.0)?); // No duplicate completion.
29//! # Ok::<(), ferravex_play::gameplay::LoopError>(())
30//! ```
31use super::{LoopError, seconds};
32
33const MAX_CAPACITY: u16 = 4096;
34const MAX_RESERVE: u32 = 1_000_000;
35
36/// Read-only snapshot of an active reload, obtained with
37/// [`Magazine::reload_status`]. Ammo remains in reserve until completion.
38#[derive(Clone, Copy, Debug, PartialEq)]
39pub struct ReloadStatus {
40    /// Total duration of this reload in simulation seconds.
41    pub duration_seconds: f32,
42    /// Simulation seconds still needed, as reported by [`Magazine::remaining`].
43    pub remaining_seconds: f32,
44    /// Elapsed fraction in `0.0..=1.0`. Rounding can yield `1.0` while active;
45    /// only [`Magazine::advance`] reports completion.
46    pub progress: f32,
47    /// Rounds that would transfer at completion with the current capacity and
48    /// reserve. Reconfiguration or reserve edits can change this projection.
49    pub rounds: u16,
50}
51
52/// Bounded ammunition storage and a caller-driven reload timer.
53///
54/// Reloads and capacity changes conserve [`Self::total_ammo`]. Only an accepted
55/// shot or explicit reserve addition/removal changes that total after creation.
56#[derive(Clone, Copy, Debug)]
57pub struct Magazine {
58    capacity: u16,
59    loaded: u16,
60    reserve: u32,
61    duration: f64,
62    remaining: f64,
63}
64impl Magazine {
65    /// Creates a full magazine with additional reserve ammunition.
66    ///
67    /// Capacity must be in `1..=4096`, reserve at most `1_000_000`, and reload
68    /// duration finite and in `0.0 < reload_seconds <= 3600.0`. Invalid inputs
69    /// return [`LoopError::Invalid`].
70    pub fn new(capacity: u16, reserve: u32, reload_seconds: f32) -> Result<Self, LoopError> {
71        let duration = seconds(reload_seconds)?;
72        if capacity == 0 || capacity > MAX_CAPACITY || reserve > MAX_RESERVE || duration == 0. {
73            return Err(LoopError::Invalid);
74        }
75        Ok(Self {
76            capacity,
77            loaded: capacity,
78            reserve,
79            duration,
80            remaining: 0.,
81        })
82    }
83    /// Maximum loaded rounds. See the [module example](crate::gameplay::magazine).
84    pub fn capacity(&self) -> u16 {
85        self.capacity
86    }
87    pub fn loaded(&self) -> u16 {
88        self.loaded
89    }
90    pub fn reserve(&self) -> u32 {
91        self.reserve
92    }
93    /// Loaded plus reserve rounds, including during a reload. This is bounded
94    /// by `1_004_096`. See the [module example](crate::gameplay::magazine).
95    pub fn total_ammo(&self) -> u32 {
96        u32::from(self.loaded) + self.reserve
97    }
98    pub fn reloading(&self) -> bool {
99        self.remaining > 0.
100    }
101    pub fn remaining(&self) -> f32 {
102        self.remaining as f32
103    }
104    /// Whether a call to [`Self::fire`] would accept a shot in the current state.
105    /// See the [module example](crate::gameplay::magazine).
106    pub fn can_fire(&self) -> bool {
107        !self.reloading() && self.loaded > 0
108    }
109    /// Whether a call to [`Self::reload`] would start a new reload in the current
110    /// state. See the [module example](crate::gameplay::magazine).
111    pub fn can_reload(&self) -> bool {
112        !self.reloading() && self.loaded < self.capacity && self.reserve > 0
113    }
114    /// Inspects an active reload without consuming time or transferring ammo.
115    ///
116    /// Returns `None` before starting, after cancellation, and after completion.
117    /// The projected round count uses the current capacity and reserve, without
118    /// reserving ammo. See the [module example](crate::gameplay::magazine).
119    pub fn reload_status(&self) -> Option<ReloadStatus> {
120        self.reloading().then(|| ReloadStatus {
121            duration_seconds: self.duration as f32,
122            remaining_seconds: self.remaining(),
123            progress: (1. - self.remaining / self.duration).clamp(0., 1.) as f32,
124            rounds: self.reload_amount(),
125        })
126    }
127    pub fn fire(&mut self) -> bool {
128        if !self.can_fire() {
129            return false;
130        }
131        self.loaded -= 1;
132        true
133    }
134    pub fn reload(&mut self) -> bool {
135        if !self.can_reload() {
136            return false;
137        }
138        self.remaining = self.duration;
139        true
140    }
141    pub fn cancel_reload(&mut self) {
142        self.remaining = 0.;
143    }
144    /// Returns true exactly once when ammunition transfers at reload completion.
145    ///
146    /// Supply simulation seconds on actual ticks. Invalid deltas (non-finite,
147    /// negative, or greater than `3600.0`) leave the entire state unchanged.
148    pub fn advance(&mut self, dt: f32) -> Result<bool, LoopError> {
149        let dt = seconds(dt)?;
150        if !self.reloading() {
151            return Ok(false);
152        }
153        self.remaining = (self.remaining - dt).max(0.);
154        if self.remaining > 1e-7 {
155            return Ok(false);
156        }
157        self.remaining = 0.;
158        let amount = self.reload_amount();
159        self.loaded += amount;
160        self.reserve -= u32::from(amount);
161        Ok(true)
162    }
163    /// Changes capacity while conserving all loaded and reserve ammunition.
164    ///
165    /// Shrinking returns excess loaded rounds to reserve and reports that count.
166    /// Growing creates empty space without loading or creating rounds. A reload
167    /// keeps its timing unless the magazine becomes full, which cancels it
168    /// without a completion event. Setting the same capacity is a no-op.
169    ///
170    /// Returns [`LoopError::Invalid`] outside `1..=4096`, or
171    /// [`LoopError::Capacity`] if returned rounds would exceed the reserve bound
172    /// of `1_000_000`. Either error leaves ammo, capacity and reload untouched.
173    ///
174    /// ```
175    /// use ferravex_play::gameplay::{LoopError, magazine::Magazine};
176    ///
177    /// let mut magazine = Magazine::new(6, 10, 1.0)?;
178    /// let total = magazine.total_ammo();
179    /// assert_eq!(magazine.set_capacity(3)?, 3);
180    /// assert_eq!((magazine.loaded(), magazine.reserve()), (3, 13));
181    /// assert_eq!(magazine.total_ammo(), total);
182    /// assert_eq!(magazine.set_capacity(8)?, 0);
183    /// assert_eq!(magazine.loaded(), 3); // Growing does not refill.
184    /// assert_eq!(magazine.total_ammo(), total);
185    /// assert_eq!(magazine.set_capacity(0), Err(LoopError::Invalid));
186    /// assert_eq!(magazine.capacity(), 8);
187    /// # Ok::<(), LoopError>(())
188    /// ```
189    pub fn set_capacity(&mut self, capacity: u16) -> Result<u16, LoopError> {
190        if capacity == 0 || capacity > MAX_CAPACITY {
191            return Err(LoopError::Invalid);
192        }
193        let returned = self.loaded.saturating_sub(capacity);
194        let reserve = self
195            .reserve
196            .checked_add(u32::from(returned))
197            .filter(|n| *n <= MAX_RESERVE)
198            .ok_or(LoopError::Capacity)?;
199        self.capacity = capacity;
200        self.loaded -= returned;
201        self.reserve = reserve;
202        if self.loaded == self.capacity {
203            self.cancel_reload();
204        }
205        Ok(returned)
206    }
207    /// Adds externally supplied rounds to reserve without loading them or
208    /// changing reload timing. Increases [`Self::total_ammo`] by exactly `amount`.
209    ///
210    /// Zero is a no-op. Returns [`LoopError::Capacity`] without changes on
211    /// overflow or if the reserve would exceed `1_000_000` rounds. See
212    /// [`Self::remove_reserve`] for a transfer example.
213    pub fn add_reserve(&mut self, amount: u32) -> Result<(), LoopError> {
214        self.reserve = self
215            .reserve
216            .checked_add(amount)
217            .filter(|n| *n <= MAX_RESERVE)
218            .ok_or(LoopError::Capacity)?;
219        Ok(())
220    }
221    /// Removes exactly `amount` reserve rounds for the caller to transfer or
222    /// spend. Decreases [`Self::total_ammo`] by that amount; loaded ammo is intact.
223    ///
224    /// Zero is a no-op. Returns [`LoopError::Unavailable`] without changes when
225    /// reserve is insufficient. Removing the last reserve round cancels any
226    /// reload without completion; otherwise reload timing is preserved.
227    ///
228    /// ```
229    /// use ferravex_play::gameplay::{LoopError, magazine::Magazine};
230    ///
231    /// let mut magazine = Magazine::new(3, 5, 1.0)?;
232    /// assert!(magazine.fire());
233    /// assert!(magazine.reload());
234    /// assert_eq!(magazine.remove_reserve(6), Err(LoopError::Unavailable));
235    /// assert!(magazine.reloading());
236    /// magazine.remove_reserve(5)?; // Caller now owns these five rounds.
237    /// assert_eq!(magazine.total_ammo(), 2);
238    /// assert!(!magazine.advance(1.0)?); // Cancellation is not completion.
239    /// magazine.add_reserve(5)?; // Return the rounds without restarting reload.
240    /// assert_eq!(magazine.total_ammo(), 7);
241    /// assert!(!magazine.reloading());
242    /// # Ok::<(), LoopError>(())
243    /// ```
244    pub fn remove_reserve(&mut self, amount: u32) -> Result<(), LoopError> {
245        let reserve = self
246            .reserve
247            .checked_sub(amount)
248            .ok_or(LoopError::Unavailable)?;
249        self.reserve = reserve;
250        if self.reserve == 0 {
251            self.cancel_reload();
252        }
253        Ok(())
254    }
255
256    fn reload_amount(&self) -> u16 {
257        u32::from(self.capacity - self.loaded).min(self.reserve) as u16
258    }
259}
260#[cfg(test)]
261mod tests {
262    use super::*;
263
264    fn state(m: &Magazine) -> (u16, u16, u32, f64, f64) {
265        (m.capacity, m.loaded, m.reserve, m.duration, m.remaining)
266    }
267
268    #[test]
269    fn reloading_transfers_once_and_cancellation_conserves_ammo() {
270        let mut m = Magazine::new(3, 5, 1.).unwrap();
271        for _ in 0..3 {
272            assert!(m.fire());
273        }
274        assert!(!m.fire());
275        assert!(m.reload());
276        assert!(!m.fire());
277        m.advance(0.5).unwrap();
278        m.cancel_reload();
279        assert_eq!((m.loaded(), m.reserve()), (0, 5));
280        m.reload();
281        for _ in 0..9 {
282            assert!(!m.advance(0.1).unwrap());
283        }
284        assert!(m.advance(0.1).unwrap());
285        assert_eq!((m.loaded(), m.reserve()), (3, 2));
286        assert!(!m.advance(2.).unwrap());
287        assert!(m.add_reserve(u32::MAX).is_err());
288        assert_eq!(m.reserve(), 2);
289    }
290
291    #[test]
292    fn status_matches_actions_and_projects_a_partial_reload_without_side_effects() {
293        let mut m = Magazine::new(4, 1, 2.).unwrap();
294        assert_eq!(m.capacity(), 4);
295        assert_eq!(m.total_ammo(), 5);
296        assert!(m.can_fire());
297        assert!(!m.can_reload());
298        assert!(!m.reload());
299        assert_eq!(m.reload_status(), None);
300        assert!(m.fire());
301        assert!(m.fire());
302        assert!(m.can_reload());
303        assert!(m.reload());
304        let initial = ReloadStatus {
305            duration_seconds: 2.,
306            remaining_seconds: 2.,
307            progress: 0.,
308            rounds: 1,
309        };
310        assert_eq!(m.reload_status(), Some(initial));
311        assert!(!m.can_fire());
312        assert!(!m.can_reload());
313        assert!(!m.advance(0.5).unwrap());
314        let before = state(&m);
315        let status = ReloadStatus {
316            remaining_seconds: 1.5,
317            progress: 0.25,
318            ..initial
319        };
320        for _ in 0..3 {
321            assert_eq!(m.reload_status(), Some(status));
322            assert!(!m.fire());
323            assert!(!m.reload());
324            assert!(!m.advance(0.).unwrap());
325            assert_eq!(state(&m), before);
326        }
327        assert_eq!((m.loaded(), m.reserve(), m.total_ammo()), (2, 1, 3));
328        assert!(m.advance(2.).unwrap());
329        assert_eq!((m.loaded(), m.reserve(), m.total_ammo()), (3, 0, 3));
330        assert_eq!(m.reload_status(), None);
331        assert!(m.can_fire());
332        assert!(!m.can_reload());
333        assert!(!m.advance(2.).unwrap());
334        for _ in 0..3 {
335            assert!(m.fire());
336        }
337        assert!(!m.can_fire());
338        assert!(!m.fire());
339        assert!(!m.can_reload());
340        assert!(!m.reload());
341    }
342
343    #[test]
344    fn capacity_edits_conserve_ammo_and_do_not_fill_new_space() {
345        let mut m = Magazine::new(6, 10, 1.).unwrap();
346        let total = m.total_ammo();
347        assert_eq!(m.set_capacity(3), Ok(3));
348        assert_eq!((m.capacity(), m.loaded(), m.reserve()), (3, 3, 13));
349        assert_eq!(m.total_ammo(), total);
350        assert_eq!(m.set_capacity(8), Ok(0));
351        assert_eq!((m.capacity(), m.loaded(), m.reserve()), (8, 3, 13));
352        assert_eq!(m.total_ammo(), total);
353        assert!(m.can_reload());
354        assert_eq!(m.reload_status(), None);
355        assert!(!m.advance(1.).unwrap());
356        assert!(m.reload());
357        assert!(m.advance(1.).unwrap());
358        assert_eq!((m.loaded(), m.reserve(), m.total_ammo()), (8, 8, total));
359    }
360
361    #[test]
362    fn capacity_edits_during_reload_keep_elapsed_time_and_use_current_capacity() {
363        let mut m = Magazine::new(6, 10, 2.).unwrap();
364        for _ in 0..4 {
365            assert!(m.fire());
366        }
367        let total = m.total_ammo();
368        assert!(m.reload());
369        assert!(!m.advance(0.5).unwrap());
370        let original = m.reload_status().unwrap();
371        assert_eq!(m.set_capacity(8), Ok(0));
372        assert_eq!(
373            m.reload_status(),
374            Some(ReloadStatus {
375                rounds: 6,
376                ..original
377            })
378        );
379        assert_eq!(m.set_capacity(4), Ok(0));
380        assert_eq!(
381            m.reload_status(),
382            Some(ReloadStatus {
383                rounds: 2,
384                ..original
385            })
386        );
387        assert_eq!(m.total_ammo(), total);
388        assert!(m.advance(1.5).unwrap());
389        assert_eq!((m.loaded(), m.reserve(), m.total_ammo()), (4, 8, total));
390        assert!(!m.advance(3600.).unwrap());
391    }
392
393    #[test]
394    fn shrinking_to_or_below_loaded_cancels_without_completion() {
395        for capacity in [2, 3] {
396            let mut m = Magazine::new(6, 8, 1.).unwrap();
397            for _ in 0..3 {
398                assert!(m.fire());
399            }
400            let total = m.total_ammo();
401            assert!(m.reload());
402            assert!(!m.advance(0.25).unwrap());
403            assert_eq!(m.set_capacity(capacity), Ok(3 - capacity));
404            assert_eq!(m.total_ammo(), total);
405            assert_eq!(m.loaded(), capacity);
406            assert_eq!(m.reserve(), 8 + u32::from(3 - capacity));
407            assert!(!m.reloading());
408            assert_eq!(m.reload_status(), None);
409            assert_eq!(m.remaining(), 0.);
410            assert!(!m.advance(1.).unwrap());
411            assert!(m.fire());
412            assert!(m.reload());
413            assert_eq!(m.reload_status().unwrap().progress, 0.);
414            assert_eq!(m.remaining(), 1.);
415            assert!(m.advance(1.).unwrap());
416            assert!(!m.advance(1.).unwrap());
417            assert_eq!(m.total_ammo(), total - 1);
418        }
419    }
420
421    #[test]
422    fn failed_edits_and_invalid_time_leave_ammo_capacity_and_reload_untouched() {
423        let mut m = Magazine::new(4, 1_000_000, 1.).unwrap();
424        assert!(m.fire());
425        assert!(m.reload());
426        assert!(!m.advance(0.25).unwrap());
427        let before = state(&m);
428        for capacity in [0, 4097, u16::MAX] {
429            assert_eq!(m.set_capacity(capacity), Err(LoopError::Invalid));
430            assert_eq!(state(&m), before);
431        }
432        assert_eq!(m.set_capacity(2), Err(LoopError::Capacity));
433        assert_eq!(state(&m), before);
434        for amount in [1, u32::MAX] {
435            assert_eq!(m.add_reserve(amount), Err(LoopError::Capacity));
436            assert_eq!(state(&m), before);
437        }
438        for amount in [1_000_001, u32::MAX] {
439            assert_eq!(m.remove_reserve(amount), Err(LoopError::Unavailable));
440            assert_eq!(state(&m), before);
441        }
442        for dt in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.1, 3601.] {
443            assert_eq!(m.advance(dt), Err(LoopError::Invalid));
444            assert_eq!(state(&m), before);
445        }
446        assert_eq!(m.set_capacity(4), Ok(0));
447        assert_eq!(m.add_reserve(0), Ok(()));
448        assert_eq!(m.remove_reserve(0), Ok(()));
449        assert_eq!(state(&m), before);
450        assert!(m.advance(0.75).unwrap());
451        assert_eq!((m.loaded(), m.reserve()), (4, 999_999));
452        assert!(!m.advance(1.).unwrap());
453    }
454
455    #[test]
456    fn capacity_and_reserve_bounds_are_exact_and_overflow_never_loses_rounds() {
457        let mut m = Magazine::new(4096, 1_000_000, 1.).unwrap();
458        assert_eq!(m.total_ammo(), 1_004_096);
459        assert_eq!(m.set_capacity(4095), Err(LoopError::Capacity));
460        assert_eq!(m.total_ammo(), 1_004_096);
461        assert_eq!(m.capacity(), 4096);
462        assert_eq!(m.remove_reserve(4095), Ok(()));
463        assert_eq!(m.set_capacity(1), Ok(4095));
464        assert_eq!((m.loaded(), m.reserve()), (1, 1_000_000));
465        assert_eq!(m.total_ammo(), 1_000_001);
466        assert_eq!(m.set_capacity(4096), Ok(0));
467        assert_eq!(m.total_ammo(), 1_000_001);
468        assert_eq!(m.loaded(), 1);
469
470        let mut empty_reserve = Magazine::new(2, 0, 1.).unwrap();
471        assert_eq!(empty_reserve.add_reserve(1_000_000), Ok(()));
472        assert_eq!(empty_reserve.add_reserve(1), Err(LoopError::Capacity));
473        assert_eq!(empty_reserve.total_ammo(), 1_000_002);
474    }
475
476    #[test]
477    fn reserve_edits_update_projection_preserve_timing_and_conserve_transfers() {
478        let mut m = Magazine::new(6, 2, 2.).unwrap();
479        for _ in 0..5 {
480            assert!(m.fire());
481        }
482        assert!(m.reload());
483        assert!(!m.advance(0.5).unwrap());
484        let initial = m.reload_status().unwrap();
485        assert_eq!(initial.rounds, 2);
486        let total = m.total_ammo();
487        assert_eq!(m.add_reserve(5), Ok(()));
488        assert_eq!(m.total_ammo(), total + 5);
489        assert_eq!(
490            m.reload_status(),
491            Some(ReloadStatus {
492                rounds: 5,
493                ..initial
494            })
495        );
496        assert_eq!(m.remove_reserve(4), Ok(()));
497        assert_eq!(m.total_ammo(), total + 1);
498        assert_eq!(
499            m.reload_status(),
500            Some(ReloadStatus {
501                rounds: 3,
502                ..initial
503            })
504        );
505        assert!(m.advance(1.5).unwrap());
506        assert_eq!((m.loaded(), m.reserve(), m.total_ammo()), (4, 0, total + 1));
507        assert!(!m.advance(2.).unwrap());
508    }
509
510    #[test]
511    fn draining_reserve_cancels_and_returning_ammo_requires_a_fresh_reload() {
512        let mut m = Magazine::new(3, 5, 1.).unwrap();
513        assert!(m.fire());
514        assert!(m.reload());
515        assert!(!m.advance(0.75).unwrap());
516        assert_eq!(m.remove_reserve(5), Ok(()));
517        assert_eq!((m.loaded(), m.reserve(), m.total_ammo()), (2, 0, 2));
518        assert_eq!(m.reload_status(), None);
519        assert!(!m.reloading());
520        assert!(m.can_fire());
521        assert!(!m.can_reload());
522        assert!(!m.advance(1.).unwrap());
523        assert_eq!(m.add_reserve(5), Ok(()));
524        assert!(m.can_reload());
525        assert!(!m.advance(1.).unwrap());
526        assert!(m.reload());
527        assert_eq!(m.reload_status().unwrap().progress, 0.);
528        assert_eq!(m.remaining(), 1.);
529        assert!(m.advance(1.).unwrap());
530        assert!(!m.advance(1.).unwrap());
531        assert_eq!((m.loaded(), m.reserve(), m.total_ammo()), (3, 4, 7));
532    }
533
534    #[test]
535    fn cancellation_discards_progress_and_catch_up_completes_only_once() {
536        let mut m = Magazine::new(3, 5, 1.).unwrap();
537        assert!(m.fire());
538        assert!(m.reload());
539        assert!(!m.advance(0.75).unwrap());
540        let total = m.total_ammo();
541        m.cancel_reload();
542        m.cancel_reload();
543        assert_eq!(m.reload_status(), None);
544        assert_eq!(m.total_ammo(), total);
545        assert!(!m.advance(1.).unwrap());
546        assert!(m.reload());
547        assert_eq!(m.reload_status().unwrap().progress, 0.);
548        let mut catch_up = m;
549        for progress in [0.25, 0.5, 0.75] {
550            assert!(!m.advance(0.25).unwrap());
551            assert_eq!(m.reload_status().unwrap().progress, progress);
552        }
553        assert!(m.advance(0.25).unwrap());
554        assert!(catch_up.advance(3600.).unwrap());
555        assert_eq!(state(&m), state(&catch_up));
556        assert_eq!(m.total_ammo(), total);
557        assert!(!m.advance(0.25).unwrap());
558        assert!(!catch_up.advance(3600.).unwrap());
559    }
560
561    #[test]
562    fn status_is_finite_at_supported_duration_extremes() {
563        for duration in [f32::from_bits(1), f32::MIN_POSITIVE, 0.000_001, 3600.] {
564            let mut m = Magazine::new(1, 1, duration).unwrap();
565            assert!(m.fire());
566            assert!(m.reload());
567            assert_eq!(
568                m.reload_status(),
569                Some(ReloadStatus {
570                    duration_seconds: duration,
571                    remaining_seconds: duration,
572                    progress: 0.,
573                    rounds: 1,
574                })
575            );
576            assert!(m.advance(duration).unwrap());
577            assert_eq!(m.reload_status(), None);
578            assert_eq!((m.loaded(), m.reserve()), (1, 0));
579            assert!(!m.advance(duration).unwrap());
580        }
581    }
582}