ferravex_play/
attributes.rs

1//! Bounded attribute modifiers and timed status effects, with explicit stacking.
2//! Periodic pulses report work to the host; the host applies authoritative damage.
3//!
4//! Inspection copies the current simulation state without advancing time or
5//! consuming pulses. Feed [`EffectSet::advance`] from fixed simulation ticks.
6//!
7//! ```
8//! use ferravex_play::attributes::{EffectSet, EffectSpec, Periodic, Stacking};
9//!
10//! let mut effects = EffectSet::<4>::new().unwrap();
11//! assert!(effects.is_empty());
12//! let mut burn = EffectSpec::modifier(7, 0, 1.0, 2.0);
13//! burn.stacking = Stacking::Stack(3);
14//! burn.periodic = Some(Periodic { interval: 0.5, amount: 2.0 });
15//! effects.apply(burn, 0).unwrap();
16//! effects.apply(burn, 0).unwrap();
17//! effects.advance(0.125).unwrap();
18//!
19//! let status = effects.status(7).unwrap();
20//! assert_eq!(effects.len(), 1);
21//! assert_eq!(status.spec.seconds, 2.0);
22//! assert_eq!(status.remaining_seconds, 1.875);
23//! assert_eq!(status.stacks, 2);
24//! assert_eq!(status.periodic_elapsed_seconds, Some(0.125));
25//! assert_eq!(status.periodic_progress(), Some(0.25));
26//! assert_eq!(status.seconds_until_pulse(), Some(0.375));
27//! assert_eq!(effects.iter().next(), Some(status));
28//! ```
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub enum AttributeError {
31    Invalid,
32    Capacity,
33    Incompatible,
34}
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub enum Stacking {
37    Refresh,
38    Strongest,
39    Stack(u8),
40}
41#[derive(Clone, Copy, Debug, PartialEq)]
42pub struct Periodic {
43    pub interval: f32,
44    pub amount: f32,
45}
46#[derive(Clone, Copy, Debug, PartialEq)]
47pub struct EffectSpec {
48    pub key: u32,
49    pub attribute: u16,
50    pub tags: u64,
51    pub seconds: f32,
52    pub additive: f32,
53    pub multiplier: f32,
54    /// Explicit strength ordering avoids confusing a stronger slow with a larger multiplier.
55    pub strength: f32,
56    pub stacking: Stacking,
57    pub periodic: Option<Periodic>,
58}
59impl EffectSpec {
60    pub fn modifier(key: u32, attribute: u16, multiplier: f32, seconds: f32) -> Self {
61        Self {
62            key,
63            attribute,
64            tags: 0,
65            seconds,
66            additive: 0.,
67            multiplier,
68            strength: (1. - multiplier).abs(),
69            stacking: Stacking::Refresh,
70            periodic: None,
71        }
72    }
73    fn valid(self) -> bool {
74        self.key != 0
75            && valid_duration(self.seconds)
76            && self.additive.is_finite()
77            && self.additive.abs() <= 1e6
78            && self.multiplier.is_finite()
79            && (0. ..=4.).contains(&self.multiplier)
80            && self.strength.is_finite()
81            && (0. ..=1e6).contains(&self.strength)
82            && !matches!(self.stacking,Stacking::Stack(n) if n==0||n>8)
83            && self.periodic.is_none_or(|p| {
84                p.interval.is_finite()
85                    && (0.01..=3600.).contains(&p.interval)
86                    && p.amount.is_finite()
87                    && p.amount.abs() <= 1e6
88            })
89    }
90}
91
92fn valid_duration(seconds: f32) -> bool {
93    seconds.is_finite() && (0.0001..=3600.).contains(&seconds)
94}
95
96/// A copied view of one active effect; editing it cannot change the set.
97///
98/// Times retain the simulation's `f64` precision. See the [module example](crate::attributes)
99/// for inspection alongside periodic pulses.
100#[derive(Clone, Copy, Debug, PartialEq)]
101pub struct EffectStatus {
102    /// The currently applied specification. Its duration is the last accepted
103    /// specification's duration, not the effect's age or total lifetime.
104    pub spec: EffectSpec,
105    /// Simulation seconds until expiry. This may exceed `spec.seconds` after a
106    /// duration refresh or reapplication of a shorter specification.
107    pub remaining_seconds: f64,
108    /// Number of active stacks, including the first application.
109    pub stacks: u8,
110    /// Elapsed seconds in the current pulse interval, or `None` for a
111    /// nonperiodic effect. Refreshes preserve this phase.
112    pub periodic_elapsed_seconds: Option<f64>,
113}
114
115impl EffectStatus {
116    /// Fraction of the current pulse interval elapsed, or `None` for a
117    /// nonperiodic effect. Views returned by the set yield a value in `[0, 1)`.
118    pub fn periodic_progress(&self) -> Option<f64> {
119        let periodic = self.spec.periodic?;
120        Some(self.periodic_elapsed_seconds? / f64::from(periodic.interval))
121    }
122
123    /// Seconds to the next pulse boundary, or `None` for a nonperiodic effect.
124    /// This does not guarantee another pulse: the effect may expire first.
125    /// Inspection does not advance time or consume a pulse.
126    pub fn seconds_until_pulse(&self) -> Option<f64> {
127        let periodic = self.spec.periodic?;
128        Some(f64::from(periodic.interval) - self.periodic_elapsed_seconds?)
129    }
130}
131
132#[derive(Clone, Copy, Debug)]
133struct Active {
134    spec: EffectSpec,
135    remaining: f64,
136    phase: f64,
137    stacks: u8,
138}
139impl Active {
140    fn status(&self) -> EffectStatus {
141        EffectStatus {
142            spec: self.spec,
143            remaining_seconds: self.remaining,
144            stacks: self.stacks,
145            periodic_elapsed_seconds: self.spec.periodic.map(|_| self.phase),
146        }
147    }
148}
149#[derive(Clone, Copy, Debug)]
150pub struct Pulse {
151    pub key: u32,
152    pub attribute: u16,
153    pub count: u32,
154    pub amount: f64,
155}
156#[derive(Clone, Debug)]
157pub struct EffectSet<const N: usize> {
158    effects: [Option<Active>; N],
159}
160impl<const N: usize> EffectSet<N> {
161    pub fn new() -> Result<Self, AttributeError> {
162        if N == 0 || N > 32 {
163            return Err(AttributeError::Capacity);
164        }
165        Ok(Self { effects: [None; N] })
166    }
167
168    /// Number of active effect keys (not the sum of their stacks), at most `N`.
169    pub fn len(&self) -> usize {
170        self.effects.iter().flatten().count()
171    }
172
173    /// Whether there are no active effects.
174    pub fn is_empty(&self) -> bool {
175        self.effects.iter().all(Option::is_none)
176    }
177
178    /// Copies the active status for `key`; missing, expired and zero keys yield
179    /// `None`. See the [module example](crate::attributes) for the view's fields.
180    pub fn status(&self, key: u32) -> Option<EffectStatus> {
181        self.effects
182            .iter()
183            .flatten()
184            .find(|active| active.spec.key == key)
185            .map(Active::status)
186    }
187
188    /// Iterates over copied statuses without allocation, scanning at most `N`
189    /// slots. Order is stable slot order, not key or application order: removal
190    /// leaves a vacancy and a new key reuses the first vacancy. Refreshes retain
191    /// their slot. Holding a copied status does not borrow or track the set.
192    pub fn iter(
193        &self,
194    ) -> impl DoubleEndedIterator<Item = EffectStatus> + std::iter::FusedIterator + '_ {
195        self.effects.iter().flatten().map(Active::status)
196    }
197
198    /// Applies a specification without changing any effect on error or immunity
199    /// rejection. Compatible reapplications preserve periodic phase and never
200    /// shorten remaining time. A weaker `Strongest` application returns `true`
201    /// but leaves the active effect unchanged, including its duration.
202    pub fn apply(&mut self, spec: EffectSpec, immune_tags: u64) -> Result<bool, AttributeError> {
203        if !spec.valid() {
204            return Err(AttributeError::Invalid);
205        }
206        if spec.tags & immune_tags != 0 {
207            return Ok(false);
208        }
209        if let Some(active) = self
210            .effects
211            .iter_mut()
212            .flatten()
213            .find(|e| e.spec.key == spec.key)
214        {
215            if active.spec.attribute != spec.attribute
216                || active.spec.stacking != spec.stacking
217                || active.spec.periodic.map(|p| p.interval) != spec.periodic.map(|p| p.interval)
218            {
219                return Err(AttributeError::Incompatible);
220            }
221            match spec.stacking {
222                Stacking::Refresh => {
223                    active.spec = spec;
224                    active.remaining = active.remaining.max(f64::from(spec.seconds));
225                }
226                Stacking::Strongest => {
227                    if spec.strength >= active.spec.strength {
228                        active.spec = spec;
229                        active.remaining = active.remaining.max(f64::from(spec.seconds));
230                    }
231                }
232                Stacking::Stack(max) => {
233                    active.stacks = active.stacks.saturating_add(1).min(max);
234                    active.spec = spec;
235                    active.remaining = active.remaining.max(f64::from(spec.seconds));
236                }
237            }
238            return Ok(true);
239        }
240        let slot = self
241            .effects
242            .iter_mut()
243            .find(|e| e.is_none())
244            .ok_or(AttributeError::Capacity)?;
245        *slot = Some(Active {
246            spec,
247            remaining: f64::from(spec.seconds),
248            phase: 0.,
249            stacks: 1,
250        });
251        Ok(true)
252    }
253
254    /// Ensures an existing effect has at least `seconds` remaining, without
255    /// changing its specification, stacks or periodic phase. This never adds
256    /// an effect and works at capacity. It does not recheck immunity: the host
257    /// decides whether to refresh an already active effect.
258    ///
259    /// Zero keys and nonfinite durations or durations outside `0.0001..=3600.0`
260    /// return [`AttributeError::Invalid`] before any change, even for missing
261    /// keys. Valid missing keys return `Ok(false)`; present keys return `Ok(true)`
262    /// even if their remaining duration already meets the requested minimum.
263    ///
264    /// ```
265    /// use ferravex_play::attributes::{AttributeError, EffectSet, EffectSpec, Stacking};
266    /// let mut effects = EffectSet::<1>::new().unwrap();
267    /// let mut slow = EffectSpec::modifier(1, 0, 0.5, 1.0);
268    /// slow.stacking = Stacking::Stack(3);
269    /// effects.apply(slow, 0).unwrap();
270    /// effects.advance(0.5).unwrap();
271    /// assert_eq!(effects.refresh_duration(1, 2.0), Ok(true));
272    /// let status = effects.status(1).unwrap();
273    /// assert_eq!(status.remaining_seconds, 2.0);
274    /// assert_eq!(status.stacks, 1);
275    /// assert_eq!(status.spec, slow);
276    /// assert_eq!(effects.refresh_duration(1, f32::NAN), Err(AttributeError::Invalid));
277    /// assert_eq!(effects.status(1), Some(status));
278    /// assert_eq!(effects.refresh_duration(2, 1.0), Ok(false));
279    /// ```
280    pub fn refresh_duration(&mut self, key: u32, seconds: f32) -> Result<bool, AttributeError> {
281        if key == 0 || !valid_duration(seconds) {
282            return Err(AttributeError::Invalid);
283        }
284        let Some(active) = self
285            .effects
286            .iter_mut()
287            .flatten()
288            .find(|active| active.spec.key == key)
289        else {
290            return Ok(false);
291        };
292        active.remaining = active.remaining.max(f64::from(seconds));
293        Ok(true)
294    }
295    /// At most N pulse reports regardless of dt; elapsed periodic ticks aggregate.
296    /// Refreshing an effect preserves its pulse phase, preventing refresh starvation.
297    pub fn advance(&mut self, dt: f32) -> Result<[Option<Pulse>; N], AttributeError> {
298        if !dt.is_finite() || !(0. ..=60.).contains(&dt) {
299            return Err(AttributeError::Invalid);
300        }
301        let mut pulses = [None; N];
302        for (slot, out) in self.effects.iter_mut().zip(pulses.iter_mut()) {
303            let Some(active) = slot else { continue };
304            let elapsed = f64::from(dt).min(active.remaining);
305            if let Some(periodic) = active.spec.periodic {
306                active.phase += elapsed;
307                let period = f64::from(periodic.interval);
308                let count = ((active.phase + 1e-9) / period).floor() as u32;
309                active.phase = (active.phase - f64::from(count) * period).max(0.);
310                if count > 0 {
311                    *out = Some(Pulse {
312                        key: active.spec.key,
313                        attribute: active.spec.attribute,
314                        count,
315                        amount: f64::from(periodic.amount)
316                            * f64::from(count)
317                            * f64::from(active.stacks),
318                    });
319                }
320            }
321            active.remaining -= elapsed;
322            if active.remaining <= 1e-9 {
323                *slot = None;
324            }
325        }
326        Ok(pulses)
327    }
328    /// Additive-then-multiplicative evaluation, clamped to host bounds.
329    pub fn value(
330        &self,
331        attribute: u16,
332        base: f32,
333        min: f32,
334        max: f32,
335    ) -> Result<f32, AttributeError> {
336        if ![base, min, max]
337            .iter()
338            .all(|v| v.is_finite() && v.abs() <= 1e9)
339            || min > max
340        {
341            return Err(AttributeError::Invalid);
342        }
343        let mut add = 0f64;
344        let mut scale = 1f64;
345        for e in self
346            .effects
347            .iter()
348            .flatten()
349            .filter(|e| e.spec.attribute == attribute)
350        {
351            add += f64::from(e.spec.additive) * f64::from(e.stacks);
352            scale *= f64::from(e.spec.multiplier).powi(i32::from(e.stacks));
353        }
354        Ok(((f64::from(base) + add) * scale).clamp(f64::from(min), f64::from(max)) as f32)
355    }
356    pub fn tags(&self) -> u64 {
357        self.effects
358            .iter()
359            .flatten()
360            .fold(0, |tags, e| tags | e.spec.tags)
361    }
362    pub fn remaining(&self, key: u32) -> f32 {
363        self.effects
364            .iter()
365            .flatten()
366            .find(|e| e.spec.key == key)
367            .map_or(0., |e| e.remaining as f32)
368    }
369    /// Removes all stacks for `key` and returns their final status in one
370    /// operation. Missing, expired and zero keys return `None` without changes.
371    /// Other effects retain their slots and state; removal emits no pulse.
372    /// Reapplying a removed key starts at one stack with a fresh pulse phase.
373    ///
374    /// ```
375    /// use ferravex_play::attributes::{EffectSet, EffectSpec};
376    /// let mut effects = EffectSet::<1>::new().unwrap();
377    /// effects.apply(EffectSpec::modifier(7, 0, 0.5, 2.0), 0).unwrap();
378    /// effects.advance(0.5).unwrap();
379    /// let removed = effects.take(7).unwrap();
380    /// assert_eq!(removed.remaining_seconds, 1.5);
381    /// assert_eq!(removed.periodic_progress(), None);
382    /// assert!(effects.is_empty());
383    /// assert_eq!(effects.take(7), None);
384    /// ```
385    pub fn take(&mut self, key: u32) -> Option<EffectStatus> {
386        self.effects
387            .iter_mut()
388            .find(|e| e.is_some_and(|s| s.spec.key == key))
389            .and_then(Option::take)
390            .map(|active| active.status())
391    }
392
393    /// Removes all stacks for `key`, returning whether it was present.
394    /// Use [`Self::take`] to also inspect the removed status.
395    pub fn remove(&mut self, key: u32) -> bool {
396        self.take(key).is_some()
397    }
398    pub fn clear(&mut self) {
399        self.effects.fill(None)
400    }
401}
402#[derive(Clone, Copy, Debug)]
403pub struct Vitals {
404    health: f32,
405    maximum: f32,
406    shield: f32,
407    armor: f32,
408    resistance: [f32; 8],
409}
410#[derive(Clone, Copy, Debug, PartialEq)]
411pub struct Damage {
412    pub shield: f32,
413    pub health: f32,
414    pub killed: bool,
415}
416impl Vitals {
417    pub fn new(
418        health: f32,
419        shield: f32,
420        armor: f32,
421        resistance: [f32; 8],
422    ) -> Result<Self, AttributeError> {
423        if ![health, shield, armor]
424            .iter()
425            .all(|v| v.is_finite() && (0. ..=1e9).contains(v))
426            || health == 0.
427            || !resistance
428                .iter()
429                .all(|r| r.is_finite() && (0. ..=1.).contains(r))
430        {
431            return Err(AttributeError::Invalid);
432        }
433        Ok(Self {
434            health,
435            maximum: health,
436            shield,
437            armor,
438            resistance,
439        })
440    }
441    pub fn health(&self) -> f32 {
442        self.health
443    }
444    pub fn shield(&self) -> f32 {
445        self.shield
446    }
447    pub fn heal(&mut self, amount: f32) -> Result<(), AttributeError> {
448        if !amount.is_finite() || amount < 0. {
449            return Err(AttributeError::Invalid);
450        }
451        self.health = (self.health + amount).min(self.maximum);
452        Ok(())
453    }
454    /// Resistance, then flat armor, then shield, then health. Unknown damage kinds fail.
455    pub fn damage(&mut self, amount: f32, kind: usize) -> Result<Damage, AttributeError> {
456        if !amount.is_finite() || !(0. ..=1e9).contains(&amount) || kind >= 8 {
457            return Err(AttributeError::Invalid);
458        }
459        let effective = (amount * (1. - self.resistance[kind]) - self.armor).max(0.);
460        let shield = effective.min(self.shield);
461        let health = (effective - shield).min(self.health);
462        let was_alive = self.health > 0.;
463        self.shield -= shield;
464        self.health -= health;
465        Ok(Damage {
466            shield,
467            health,
468            killed: was_alive && self.health == 0.,
469        })
470    }
471}
472#[cfg(test)]
473mod tests {
474    use super::*;
475
476    fn burn(key: u32, stacking: Stacking) -> EffectSpec {
477        EffectSpec {
478            tags: 2,
479            stacking,
480            periodic: Some(Periodic {
481                interval: 0.25,
482                amount: 2.,
483            }),
484            ..EffectSpec::modifier(key, 0, 0.5, 2.)
485        }
486    }
487
488    #[test]
489    fn status_views_report_stacks_and_periodic_progress_without_consuming_pulses() {
490        let mut effects = EffectSet::<2>::new().unwrap();
491        let spec = burn(1, Stacking::Stack(3));
492        effects.apply(spec, 0).unwrap();
493        effects.apply(spec, 0).unwrap();
494        effects
495            .apply(EffectSpec::modifier(2, 1, 1., 2.), 0)
496            .unwrap();
497        let initial = effects.status(1).unwrap();
498        assert_eq!(initial.spec, spec);
499        assert_eq!(initial.remaining_seconds, 2.);
500        assert_eq!(initial.stacks, 2);
501        assert_eq!(initial.periodic_elapsed_seconds, Some(0.));
502        assert_eq!(initial.periodic_progress(), Some(0.));
503        assert_eq!(initial.seconds_until_pulse(), Some(0.25));
504        let plain = effects.status(2).unwrap();
505        assert_eq!(plain.periodic_elapsed_seconds, None);
506        assert_eq!(plain.periodic_progress(), None);
507        assert_eq!(plain.seconds_until_pulse(), None);
508
509        let pulses = effects.advance(0.625).unwrap();
510        assert_eq!(pulses[0].unwrap().count, 2);
511        assert_eq!(pulses[0].unwrap().amount, 8.);
512        assert!(pulses[1].is_none());
513        let halfway = effects.status(1).unwrap();
514        assert_eq!(halfway.remaining_seconds, 1.375);
515        assert_eq!(halfway.periodic_elapsed_seconds, Some(0.125));
516        assert_eq!(halfway.periodic_progress(), Some(0.5));
517        assert_eq!(halfway.seconds_until_pulse(), Some(0.125));
518        for _ in 0..4 {
519            assert_eq!(effects.iter().next(), Some(halfway));
520            assert_eq!(effects.status(1), Some(halfway));
521        }
522        assert!(effects.advance(0.).unwrap().iter().all(Option::is_none));
523        assert_eq!(effects.status(1), Some(halfway));
524        let pulse = effects.advance(0.125).unwrap()[0].unwrap();
525        assert_eq!((pulse.count, pulse.amount), (1, 4.));
526        assert_eq!(effects.status(1).unwrap().periodic_progress(), Some(0.));
527        // A copied view remains the state it captured, even after advancement.
528        assert_eq!(initial.remaining_seconds, 2.);
529        assert_eq!(halfway.periodic_progress(), Some(0.5));
530        let pulse = effects.advance(60.).unwrap()[0].unwrap();
531        assert_eq!((pulse.count, pulse.amount), (5, 20.));
532        assert!(effects.is_empty());
533        assert_eq!(effects.status(1), None);
534        assert_eq!(effects.iter().next(), None);
535    }
536
537    #[test]
538    fn iteration_is_bounded_and_preserves_slots_across_removal_and_reuse() {
539        assert!(matches!(
540            EffectSet::<0>::new(),
541            Err(AttributeError::Capacity)
542        ));
543        assert!(matches!(
544            EffectSet::<33>::new(),
545            Err(AttributeError::Capacity)
546        ));
547        let mut effects = EffectSet::<32>::new().unwrap();
548        assert!(effects.is_empty());
549        assert_eq!(effects.len(), 0);
550        assert_eq!(effects.iter().next_back(), None);
551        assert_eq!(effects.status(0), None);
552        for key in 1..=32 {
553            effects
554                .apply(EffectSpec::modifier(key, 0, 1., 1.), 0)
555                .unwrap();
556        }
557        assert_eq!(effects.len(), 32);
558        assert!(!effects.is_empty());
559        assert_eq!(effects.iter().count(), 32);
560        assert_eq!(effects.status(33), None);
561        assert_eq!(
562            effects.apply(EffectSpec::modifier(33, 0, 1., 1.), 0),
563            Err(AttributeError::Capacity)
564        );
565        assert_eq!(effects.take(2).unwrap().spec.key, 2);
566        assert_eq!(effects.len(), 31);
567        effects
568            .apply(EffectSpec::modifier(33, 0, 1., 1.), 0)
569            .unwrap();
570        effects.refresh_duration(1, 2.).unwrap();
571        effects
572            .apply(EffectSpec::modifier(3, 0, 0.5, 2.), 0)
573            .unwrap();
574        {
575            let mut iter = effects.iter();
576            assert_eq!(iter.next().unwrap().spec.key, 1);
577            assert_eq!(iter.next_back().unwrap().spec.key, 32);
578            assert_eq!(iter.next().unwrap().spec.key, 33);
579            for key in 3..32 {
580                assert_eq!(iter.next().unwrap().spec.key, key);
581            }
582            assert_eq!(iter.next(), None);
583            assert_eq!(iter.next_back(), None);
584            assert_eq!(iter.next(), None);
585        }
586        effects.clear();
587        assert_eq!(effects.len(), 0);
588        assert!(effects.is_empty());
589        assert_eq!(effects.iter().next(), None);
590        assert_eq!(effects.status(1), None);
591    }
592
593    #[test]
594    fn duration_refresh_keeps_spec_stacks_phase_and_other_effects_at_capacity() {
595        let mut effects = EffectSet::<2>::new().unwrap();
596        let spec = burn(1, Stacking::Stack(3));
597        effects.apply(spec, 0).unwrap();
598        effects.apply(spec, 0).unwrap();
599        effects.apply(burn(2, Stacking::Strongest), 0).unwrap();
600        effects.advance(0.125).unwrap();
601        let before = effects.status(1).unwrap();
602        let other = effects.status(2).unwrap();
603        assert_eq!(effects.refresh_duration(1, 3.), Ok(true));
604        assert_eq!(
605            effects.status(1),
606            Some(EffectStatus {
607                remaining_seconds: 3.,
608                ..before
609            })
610        );
611        assert_eq!(effects.status(2), Some(other));
612        assert_eq!(effects.refresh_duration(1, 0.5), Ok(true));
613        assert_eq!(effects.status(1).unwrap().remaining_seconds, 3.);
614        assert_eq!(effects.value(0, 100., 0., 100.).unwrap(), 12.5);
615        assert_eq!(effects.advance(0.125).unwrap()[0].unwrap().amount, 4.);
616        assert_eq!(effects.refresh_duration(1, 3600.), Ok(true));
617        assert_eq!(effects.remaining(1), 3600.);
618        assert_eq!(effects.refresh_duration(1, 0.0001), Ok(true));
619        assert_eq!(effects.remaining(1), 3600.);
620    }
621
622    #[test]
623    fn invalid_or_missing_refreshes_and_invalid_advancement_leave_all_state_intact() {
624        let mut effects = EffectSet::<2>::new().unwrap();
625        effects.apply(burn(1, Stacking::Stack(3)), 0).unwrap();
626        effects.apply(burn(2, Stacking::Refresh), 0).unwrap();
627        effects.advance(0.125).unwrap();
628        let before: Vec<_> = effects.iter().collect();
629        for seconds in [
630            f32::NAN,
631            f32::INFINITY,
632            f32::NEG_INFINITY,
633            -1.,
634            0.,
635            0.00001,
636            3601.,
637        ] {
638            for key in [1, 3] {
639                assert_eq!(
640                    effects.refresh_duration(key, seconds),
641                    Err(AttributeError::Invalid)
642                );
643                assert_eq!(effects.iter().collect::<Vec<_>>(), before);
644            }
645        }
646        assert_eq!(
647            effects.refresh_duration(0, 1.),
648            Err(AttributeError::Invalid)
649        );
650        assert_eq!(effects.refresh_duration(3, 1.), Ok(false));
651        assert_eq!(effects.iter().collect::<Vec<_>>(), before);
652        for dt in [f32::NAN, f32::INFINITY, -0.01, 61.] {
653            assert!(matches!(effects.advance(dt), Err(AttributeError::Invalid)));
654            assert_eq!(effects.iter().collect::<Vec<_>>(), before);
655        }
656        effects.advance(2.).unwrap();
657        assert_eq!(effects.refresh_duration(1, 1.), Ok(false));
658        assert!(effects.is_empty());
659    }
660
661    #[test]
662    fn reapplication_errors_and_immunity_are_transactional_in_status_views() {
663        let mut effects = EffectSet::<1>::new().unwrap();
664        let spec = burn(1, Stacking::Stack(3));
665        effects.apply(spec, 0).unwrap();
666        effects.advance(0.125).unwrap();
667        let before = effects.status(1);
668        for invalid in [
669            EffectSpec {
670                seconds: f32::NAN,
671                ..spec
672            },
673            EffectSpec {
674                additive: f32::INFINITY,
675                ..spec
676            },
677            EffectSpec {
678                periodic: Some(Periodic {
679                    interval: 0.,
680                    amount: 2.,
681                }),
682                ..spec
683            },
684        ] {
685            assert_eq!(effects.apply(invalid, 0), Err(AttributeError::Invalid));
686            assert_eq!(effects.status(1), before);
687        }
688        for incompatible in [
689            EffectSpec {
690                attribute: 1,
691                ..spec
692            },
693            EffectSpec {
694                stacking: Stacking::Stack(2),
695                ..spec
696            },
697            EffectSpec {
698                periodic: None,
699                ..spec
700            },
701            EffectSpec {
702                periodic: Some(Periodic {
703                    interval: 0.5,
704                    amount: 2.,
705                }),
706                ..spec
707            },
708        ] {
709            assert_eq!(
710                effects.apply(incompatible, 0),
711                Err(AttributeError::Incompatible)
712            );
713            assert_eq!(effects.status(1), before);
714        }
715        assert_eq!(effects.apply(spec, 2), Ok(false));
716        assert_eq!(effects.apply(EffectSpec { key: 2, ..spec }, 2), Ok(false));
717        assert_eq!(
718            effects.apply(EffectSpec { key: 2, ..spec }, 0),
719            Err(AttributeError::Capacity)
720        );
721        assert_eq!(effects.status(1), before);
722
723        let replacement = EffectSpec {
724            seconds: 0.5,
725            tags: 4,
726            periodic: Some(Periodic {
727                interval: 0.25,
728                amount: 3.,
729            }),
730            ..spec
731        };
732        for _ in 0..5 {
733            effects.apply(replacement, 0).unwrap();
734        }
735        let status = effects.status(1).unwrap();
736        assert_eq!(status.spec, replacement);
737        assert_eq!(status.remaining_seconds, before.unwrap().remaining_seconds);
738        assert_eq!(status.periodic_elapsed_seconds, Some(0.125));
739        assert_eq!(status.stacks, 3);
740        assert_eq!(effects.tags(), 4);
741        assert_eq!(effects.advance(0.125).unwrap()[0].unwrap().amount, 9.);
742    }
743
744    #[test]
745    fn strongest_views_keep_weaker_refreshes_out_and_accept_equal_strength() {
746        let mut effects = EffectSet::<1>::new().unwrap();
747        let spec = burn(1, Stacking::Strongest);
748        effects.apply(spec, 0).unwrap();
749        effects.advance(0.125).unwrap();
750        let before = effects.status(1).unwrap();
751        let weaker = EffectSpec {
752            strength: 0.1,
753            seconds: 3.,
754            ..spec
755        };
756        assert_eq!(effects.apply(weaker, 0), Ok(true));
757        assert_eq!(effects.status(1), Some(before));
758        let stronger = EffectSpec {
759            strength: 0.75,
760            multiplier: 0.25,
761            seconds: 0.5,
762            ..spec
763        };
764        effects.apply(stronger, 0).unwrap();
765        assert_eq!(
766            effects.status(1),
767            Some(EffectStatus {
768                spec: stronger,
769                ..before
770            })
771        );
772        let equal = EffectSpec {
773            seconds: 3.,
774            ..stronger
775        };
776        effects.apply(equal, 0).unwrap();
777        assert_eq!(
778            effects.status(1),
779            Some(EffectStatus {
780                spec: equal,
781                remaining_seconds: 3.,
782                ..before
783            })
784        );
785    }
786
787    #[test]
788    fn take_returns_final_state_and_reapplication_starts_fresh() {
789        let mut effects = EffectSet::<2>::new().unwrap();
790        let spec = burn(1, Stacking::Stack(3));
791        effects.apply(spec, 0).unwrap();
792        effects.apply(spec, 0).unwrap();
793        effects
794            .apply(
795                EffectSpec {
796                    tags: 4,
797                    ..burn(2, Stacking::Refresh)
798                },
799                0,
800            )
801            .unwrap();
802        effects.advance(0.125).unwrap();
803        let removed = effects.status(1).unwrap();
804        let other = effects.status(2).unwrap();
805        assert_eq!(effects.take(0), None);
806        assert_eq!(effects.take(3), None);
807        assert_eq!(effects.take(1), Some(removed));
808        assert_eq!(effects.take(1), None);
809        assert!(!effects.remove(1));
810        assert_eq!(effects.status(1), None);
811        assert_eq!(effects.status(2), Some(other));
812        assert_eq!(effects.len(), 1);
813        assert_eq!(effects.tags(), 4);
814        assert_eq!(effects.value(0, 100., 0., 100.).unwrap(), 50.);
815        effects.apply(spec, 0).unwrap();
816        let fresh = effects.status(1).unwrap();
817        assert_eq!(fresh.stacks, 1);
818        assert_eq!(fresh.remaining_seconds, 2.);
819        assert_eq!(fresh.periodic_elapsed_seconds, Some(0.));
820        let pulses = effects.advance(0.125).unwrap();
821        assert!(pulses[0].is_none());
822        assert_eq!(pulses[1].unwrap().count, 1);
823        assert!(effects.remove(1));
824        assert!(effects.remove(2));
825        assert!(effects.is_empty());
826        assert!(effects.advance(1.).unwrap().iter().all(Option::is_none));
827    }
828
829    #[test]
830    fn views_keep_f64_time_and_do_not_promise_pulses_past_expiry() {
831        let mut effects = EffectSet::<1>::new().unwrap();
832        effects.apply(burn(1, Stacking::Refresh), 0).unwrap();
833        effects.advance(0.1).unwrap();
834        let status = effects.status(1).unwrap();
835        assert_eq!(status.remaining_seconds, 2. - f64::from(0.1f32));
836        assert_eq!(status.periodic_elapsed_seconds, Some(f64::from(0.1f32)));
837        assert_eq!(status.seconds_until_pulse(), Some(0.25 - f64::from(0.1f32)));
838        effects.clear();
839        effects
840            .apply(
841                EffectSpec {
842                    seconds: 0.125,
843                    ..burn(1, Stacking::Refresh)
844                },
845                0,
846            )
847            .unwrap();
848        let status = effects.status(1).unwrap();
849        assert!(status.seconds_until_pulse().unwrap() > status.remaining_seconds);
850        assert!(effects.advance(1.).unwrap()[0].is_none());
851        assert_eq!(effects.take(1), None);
852        assert!(effects.is_empty());
853    }
854
855    #[test]
856    fn slows_stack_refresh_and_expire_without_mutating_base() {
857        let mut s = EffectSet::<4>::new().unwrap();
858        let slow = EffectSpec::modifier(1, 0, 0.5, 1.);
859        s.apply(slow, 0).unwrap();
860        s.advance(0.5).unwrap();
861        s.apply(slow, 0).unwrap();
862        assert_eq!(s.value(0, 100., 0., 1000.).unwrap(), 50.);
863        let mut stacked = EffectSpec::modifier(2, 0, 0.5, 1.);
864        stacked.stacking = Stacking::Stack(2);
865        for _ in 0..10 {
866            s.apply(stacked, 0).unwrap();
867        }
868        assert_eq!(s.value(0, 100., 0., 1000.).unwrap(), 12.5);
869        s.advance(1.).unwrap();
870        assert_eq!(s.value(0, 100., 0., 1000.).unwrap(), 100.);
871    }
872    #[test]
873    fn periodic_refresh_does_not_starve_and_stops_at_expiry() {
874        let mut s = EffectSet::<1>::new().unwrap();
875        let mut burn = EffectSpec::modifier(1, 0, 1., 1.);
876        burn.periodic = Some(Periodic {
877            interval: 0.25,
878            amount: 2.,
879        });
880        s.apply(burn, 0).unwrap();
881        s.advance(0.125).unwrap();
882        s.apply(burn, 0).unwrap();
883        assert_eq!(s.advance(0.125).unwrap()[0].unwrap().amount, 2.);
884        assert_eq!(s.advance(10.).unwrap()[0].unwrap().count, 3);
885        assert_eq!(s.remaining(1), 0.);
886    }
887    #[test]
888    fn resistance_shield_damage_and_rejection_conserve_health() {
889        let mut r = [0.; 8];
890        r[1] = 0.5;
891        let mut v = Vitals::new(100., 10., 2., r).unwrap();
892        let hit = v.damage(40., 1).unwrap();
893        assert_eq!(
894            hit,
895            Damage {
896                shield: 10.,
897                health: 8.,
898                killed: false
899            }
900        );
901        assert_eq!((v.health(), v.shield()), (92., 0.));
902        assert!(v.damage(f32::NAN, 1).is_err());
903        assert_eq!(v.health(), 92.);
904        v.heal(1000.).unwrap();
905        assert_eq!(v.health(), 100.);
906    }
907    #[test]
908    fn immunity_capacity_strongest_and_invalid_edits_are_explicit() {
909        let mut s = EffectSet::<1>::new().unwrap();
910        let mut slow = EffectSpec::modifier(1, 0, 0.5, 1.);
911        slow.tags = 2;
912        slow.stacking = Stacking::Strongest;
913        assert!(!s.apply(slow, 2).unwrap());
914        s.apply(slow, 0).unwrap();
915        slow.multiplier = 0.8;
916        slow.strength = 0.2;
917        s.apply(slow, 0).unwrap();
918        assert_eq!(s.value(0, 100., 0., 100.).unwrap(), 50.);
919        slow.key = 2;
920        assert_eq!(s.apply(slow, 0), Err(AttributeError::Capacity));
921        slow.multiplier = f32::NAN;
922        assert!(s.apply(slow, 0).is_err());
923        assert_eq!(s.tags(), 2);
924        assert!(s.remove(1));
925    }
926}