ferravex_play/particles/
trail.rs

1use super::{MAX_EFFECT_LIFETIME, RibbonPoint, RibbonSource};
2pub const MAX_TRAIL_POINTS: usize = 2048;
3#[derive(Clone, Copy, Debug, PartialEq)]
4pub struct TrailConfig {
5    pub capacity: usize,
6    pub lifetime: f32,
7    pub spacing: f32,
8    /// Motion strictly beyond this distance starts a new segment automatically.
9    /// Use [`Trail::teleport`] for discontinuities within this distance.
10    pub teleport_distance: f32,
11    pub max_per_update: u16,
12    pub fade_width: bool,
13}
14impl Default for TrailConfig {
15    fn default() -> Self {
16        Self {
17            capacity: 128,
18            lifetime: 0.6,
19            spacing: 0.08,
20            teleport_distance: 12.,
21            max_per_update: 64,
22            fade_width: true,
23        }
24    }
25}
26#[derive(Clone, Copy, Debug, Default, PartialEq)]
27pub struct TrailSample {
28    pub position: [f32; 3],
29    pub color: [f32; 4],
30    pub width: f32,
31}
32impl TrailSample {
33    fn point(self, break_before: bool) -> RibbonPoint {
34        RibbonPoint {
35            position: self.position,
36            color: self.color,
37            width: self.width,
38            break_before,
39        }
40    }
41    fn interpolate(self, b: Self, t: f64) -> Self {
42        let lerp = |a: f32, b: f32| (f64::from(a) * (1. - t) + f64::from(b) * t) as f32;
43        Self {
44            position: std::array::from_fn(|i| lerp(self.position[i], b.position[i])),
45            color: std::array::from_fn(|i| lerp(self.color[i], b.color[i])),
46            width: lerp(self.width, b.width),
47        }
48    }
49}
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub enum TrailError {
52    InvalidConfig,
53    InvalidSample,
54    InvalidDelta,
55}
56#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
57pub struct TrailStats {
58    pub sampled: u64,
59    pub expired: u64,
60    pub dropped_budget: u64,
61    pub overwritten: u64,
62    /// Automatic distance breaks and accepted explicit [`Trail::teleport`] calls.
63    pub teleports: u64,
64}
65impl TrailStats {
66    fn add(&mut self, b: Self) {
67        self.sampled = self.sampled.saturating_add(b.sampled);
68        self.expired = self.expired.saturating_add(b.expired);
69        self.dropped_budget = self.dropped_budget.saturating_add(b.dropped_budget);
70        self.overwritten = self.overwritten.saturating_add(b.overwritten);
71        self.teleports = self.teleports.saturating_add(b.teleports);
72    }
73}
74#[derive(Clone, Copy, Default)]
75struct Point {
76    point: RibbonPoint,
77    age: f64,
78}
79/// Fixed ring, distance resampling and a current head. Capacity bounds the visible
80/// point count (including that head); one extra head value is stored separately.
81/// Stops and teleports create breaks; old segments fade naturally without bridges.
82/// Use [`Self::break_segment`] or [`Self::teleport`] for explicit discontinuities,
83/// including short respawn jumps, and [`Self::clear`] to reset all trail history.
84pub struct Trail {
85    config: TrailConfig,
86    points: Vec<Point>,
87    start: usize,
88    len: usize,
89    previous: Option<TrailSample>,
90    head: Option<TrailSample>,
91    carry: f64,
92    total: TrailStats,
93}
94impl Trail {
95    pub fn new(config: TrailConfig) -> Result<Self, TrailError> {
96        if !(2..=MAX_TRAIL_POINTS).contains(&config.capacity)
97            || !config.lifetime.is_finite()
98            || !(0.0001..=MAX_EFFECT_LIFETIME).contains(&config.lifetime)
99            || !config.spacing.is_finite()
100            || !(0.0001..=1e6).contains(&config.spacing)
101            || !config.teleport_distance.is_finite()
102            || !(config.spacing..=1e6).contains(&config.teleport_distance)
103            || !(1..=256).contains(&config.max_per_update)
104        {
105            return Err(TrailError::InvalidConfig);
106        }
107        Ok(Self {
108            points: vec![Point::default(); config.capacity],
109            config,
110            start: 0,
111            len: 0,
112            previous: None,
113            head: None,
114            carry: 0.,
115            total: TrailStats::default(),
116        })
117    }
118    pub fn capacity(&self) -> usize {
119        self.config.capacity
120    }
121    pub fn len(&self) -> usize {
122        (self.len + usize::from(self.head.is_some())).min(self.config.capacity)
123    }
124    pub fn is_empty(&self) -> bool {
125        self.len() == 0
126    }
127    pub fn config(&self) -> TrailConfig {
128        self.config
129    }
130    pub fn stats(&self) -> TrailStats {
131        self.total
132    }
133    /// Removes all points and resets sampling history, retaining configuration,
134    /// backing storage and cumulative statistics. The next sample starts a new
135    /// segment with no residual spacing or connection to the old position.
136    /// Call [`Self::reset_stats`] as well to reset the statistics for a new run.
137    ///
138    /// ```
139    /// use ferravex_play::particles::{Trail, TrailConfig, TrailSample, TrailStats};
140    ///
141    /// let mut trail = Trail::new(TrailConfig::default()).unwrap();
142    /// trail.update(0.0, Some(TrailSample::default())).unwrap();
143    /// trail.clear();
144    /// assert!(trail.is_empty());
145    /// assert_eq!(trail.stats().sampled, 1);
146    /// trail.reset_stats();
147    /// assert_eq!(trail.stats(), TrailStats::default());
148    /// trail.update(0.0, Some(TrailSample::default())).unwrap();
149    /// assert!(trail.iter().next().unwrap().break_before);
150    /// ```
151    pub fn clear(&mut self) {
152        self.start = 0;
153        self.len = 0;
154        self.previous = None;
155        self.head = None;
156        self.carry = 0.;
157    }
158    pub fn reset_stats(&mut self) {
159        self.total = TrailStats::default();
160    }
161    /// Ends the current segment without advancing time or clearing old points.
162    /// The current head is retained in the ring at age zero, subject to capacity;
163    /// existing points keep their ages. The next accepted sample starts a new
164    /// segment regardless of its distance from the old head. Spacing carry is
165    /// discarded. Repeating this call without new samples is a no-op.
166    ///
167    /// Returns the operation's statistics, also added to [`Self::stats`]. A break
168    /// does not count as a teleport. Equivalent to `update(0.0, None)`, without
169    /// delta validation or aging work.
170    ///
171    /// ```
172    /// use ferravex_play::particles::{Trail, TrailConfig, TrailSample, TrailStats};
173    ///
174    /// let mut trail = Trail::new(TrailConfig::default()).unwrap();
175    /// let sample = TrailSample { color: [1.0; 4], width: 0.2, ..Default::default() };
176    /// trail.update(0.0, Some(sample)).unwrap();
177    /// trail.break_segment();
178    /// assert_eq!(trail.break_segment(), TrailStats::default());
179    /// // Even a respawn at the same position starts a disconnected segment.
180    /// trail.update(0.0, Some(sample)).unwrap();
181    /// assert!(trail.iter().last().unwrap().break_before);
182    /// ```
183    pub fn break_segment(&mut self) -> TrailStats {
184        let mut stats = TrailStats::default();
185        self.finish_segment(0., &mut stats);
186        self.total.add(stats);
187        stats
188    }
189    /// Ends the current segment and starts a new one at `sample`, even at the
190    /// same position or below the automatic teleport distance. Retains the old
191    /// head and starts the new sample at age zero, subject to ring capacity.
192    /// Existing points keep their ages and spacing carry is discarded. This
193    /// does not advance time; use [`Self::update`] to age points normally.
194    ///
195    /// Invalid samples leave all state unchanged. An accepted call counts one
196    /// teleport, including on an empty trail. Returns the operation's statistics,
197    /// also added to [`Self::stats`]. Use [`Self::clear`] to discard old segments.
198    ///
199    /// ```
200    /// use ferravex_play::particles::{Trail, TrailConfig, TrailSample};
201    ///
202    /// let mut trail = Trail::new(TrailConfig::default()).unwrap();
203    /// let sample = TrailSample { color: [1.0; 4], width: 0.2, ..Default::default() };
204    /// trail.update(0.0, Some(sample)).unwrap();
205    /// let respawn = TrailSample { position: [0.01, 0.0, 0.0], ..sample };
206    /// assert_eq!(trail.teleport(respawn).unwrap().teleports, 1);
207    /// assert_eq!(trail.len(), 2);
208    /// assert!(trail.iter().last().unwrap().break_before);
209    /// ```
210    pub fn teleport(&mut self, sample: TrailSample) -> Result<TrailStats, TrailError> {
211        if !sample.point(false).valid() {
212            return Err(TrailError::InvalidSample);
213        }
214        let mut stats = TrailStats::default();
215        self.finish_segment(0., &mut stats);
216        self.push(sample, 0., true, &mut stats);
217        self.previous = Some(sample);
218        stats.teleports = 1;
219        self.total.add(stats);
220        Ok(stats)
221    }
222    fn finish_segment(&mut self, head_age: f64, stats: &mut TrailStats) {
223        if let Some(head) = self.head.take() {
224            self.push(head, head_age, false, stats);
225        }
226        self.previous = None;
227        self.carry = 0.;
228    }
229    fn push(&mut self, sample: TrailSample, age: f64, break_before: bool, stats: &mut TrailStats) {
230        if age >= f64::from(self.config.lifetime) {
231            stats.expired += 1;
232            return;
233        }
234        let at = (self.start + self.len) % self.config.capacity;
235        self.points[at] = Point {
236            point: sample.point(break_before),
237            age,
238        };
239        if self.len == self.config.capacity {
240            self.start = (self.start + 1) % self.config.capacity;
241            stats.overwritten += 1;
242        } else {
243            self.len += 1;
244        }
245        stats.sampled += 1;
246    }
247    /// None stops emission while aging existing points. Invalid input leaves the
248    /// trail unchanged. New samples receive their within-frame birth ages.
249    /// Automatic teleports retain the previous head aged by `dt` and begin a
250    /// disconnected segment at the new sample. Use [`Self::teleport`] for smaller
251    /// jumps that must also break the trail.
252    pub fn update(
253        &mut self,
254        dt: f32,
255        sample: Option<TrailSample>,
256    ) -> Result<TrailStats, TrailError> {
257        if !dt.is_finite() || !(0.0..=60.).contains(&dt) {
258            return Err(TrailError::InvalidDelta);
259        }
260        if sample.is_some_and(|s| !s.point(false).valid()) {
261            return Err(TrailError::InvalidSample);
262        }
263        let mut stats = TrailStats::default();
264        for i in 0..self.len {
265            self.points[(self.start + i) % self.config.capacity].age += f64::from(dt);
266        }
267        while self.len > 0 && self.points[self.start].age >= f64::from(self.config.lifetime) {
268            self.start = (self.start + 1) % self.config.capacity;
269            self.len -= 1;
270            stats.expired += 1;
271        }
272        let Some(sample) = sample else {
273            self.finish_segment(f64::from(dt), &mut stats);
274            self.total.add(stats);
275            return Ok(stats);
276        };
277        let Some(previous) = self.previous else {
278            self.push(sample, 0., true, &mut stats);
279            self.previous = Some(sample);
280            self.head = None;
281            self.total.add(stats);
282            return Ok(stats);
283        };
284        let distance = previous
285            .position
286            .iter()
287            .zip(sample.position)
288            .map(|(a, b)| (f64::from(*a) - f64::from(b)).powi(2))
289            .sum::<f64>()
290            .sqrt();
291        if distance > f64::from(self.config.teleport_distance) {
292            self.finish_segment(f64::from(dt), &mut stats);
293            self.push(sample, 0., true, &mut stats);
294            self.previous = Some(sample);
295            stats.teleports += 1;
296            self.total.add(stats);
297            return Ok(stats);
298        }
299        if distance > 0. {
300            if self.len == 0 {
301                self.push(previous, f64::from(dt), true, &mut stats);
302            }
303            let total = self.carry + distance;
304            let spacing = f64::from(self.config.spacing);
305            let requested = (total / spacing).floor() as u64;
306            let count = requested.min(u64::from(self.config.max_per_update));
307            stats.dropped_budget = requested - count;
308            for i in requested - count..requested {
309                let t = (((i + 1) as f64 * spacing - self.carry) / distance).clamp(0., 1.);
310                self.push(
311                    previous.interpolate(sample, t),
312                    f64::from(dt) * (1. - t),
313                    i == requested - count && stats.dropped_budget > 0,
314                    &mut stats,
315                );
316            }
317            self.carry = (total - requested as f64 * spacing).clamp(0., spacing);
318        }
319        self.head = Some(sample);
320        self.previous = Some(sample);
321        self.total.add(stats);
322        Ok(stats)
323    }
324    pub fn iter(&self) -> impl ExactSizeIterator<Item = RibbonPoint> + '_ {
325        (0..self.len()).map(|i| self.point(i).expect("bounded trail point"))
326    }
327}
328impl RibbonSource for Trail {
329    fn point_count(&self) -> usize {
330        self.len()
331    }
332    fn point(&self, index: usize) -> Option<RibbonPoint> {
333        if index >= self.len() {
334            return None;
335        }
336        let skip = usize::from(self.head.is_some() && self.len == self.config.capacity);
337        let stored = self.len - skip;
338        if index < stored {
339            let p = self.points[(self.start + skip + index) % self.config.capacity];
340            let age = (p.age / f64::from(self.config.lifetime)).clamp(0., 1.) as f32;
341            let mut point = p.point;
342            point.color[3] *= 1. - age;
343            if self.config.fade_width {
344                point.width *= 1. - age;
345            }
346            Some(point)
347        } else {
348            self.head.map(|s| s.point(false))
349        }
350    }
351}