ferravex_play/
particles.rs

1//! Bounded particles, seeded emitters, ribbons/trails and short-lived beams.
2//! Simulation and geometry use first-party math; no GPU/device dependency.
3mod beam;
4mod emitter;
5pub mod presets;
6mod ribbon;
7mod trail;
8pub use beam::*;
9pub use emitter::*;
10pub use ribbon::*;
11pub use trail::*;
12pub const MAX_PARTICLES: usize = 65536;
13pub const MAX_EFFECT_LIFETIME: f32 = 3600.;
14#[derive(Clone, Copy, Debug, PartialEq)]
15pub struct ParticleDesc {
16    pub position: [f32; 3],
17    pub velocity: [f32; 3],
18    pub acceleration: [f32; 3],
19    pub lifetime: f32,
20    pub start_color: [f32; 4],
21    pub end_color: [f32; 4],
22    pub start_size: f32,
23    pub end_size: f32,
24}
25impl Default for ParticleDesc {
26    fn default() -> Self {
27        Self {
28            position: [0.0; 3],
29            velocity: [0.0; 3],
30            acceleration: [0.0; 3],
31            lifetime: 1.0,
32            start_color: [1.0; 4],
33            end_color: [1.0, 1.0, 1.0, 0.0],
34            start_size: 1.0,
35            end_size: 0.0,
36        }
37    }
38}
39
40impl ParticleDesc {
41    pub fn validate(&self) -> Result<(), ParticleError> {
42        if !self
43            .position
44            .into_iter()
45            .chain(self.velocity)
46            .chain(self.acceleration)
47            .chain(self.start_color)
48            .chain(self.end_color)
49            .chain([self.lifetime, self.start_size, self.end_size])
50            .all(f32::is_finite)
51            || !(0.0..=MAX_EFFECT_LIFETIME).contains(&self.lifetime)
52            || self.lifetime == 0.
53            || self.start_size < 0.
54            || self.end_size < 0.
55        {
56            Err(ParticleError::InvalidParticle)
57        } else {
58            Ok(())
59        }
60    }
61}
62#[derive(Clone, Copy, Debug, Default, PartialEq)]
63pub struct ParticleMotion {
64    /// Linear drag coefficient in inverse seconds; exact constant-force solution.
65    pub drag: f32,
66    pub rotation: f32,
67    pub angular_velocity: f32,
68}
69impl ParticleMotion {
70    pub fn validate(&self) -> Result<(), ParticleError> {
71        if !self.drag.is_finite()
72            || !(0.0..=128.).contains(&self.drag)
73            || !self.rotation.is_finite()
74            || !self.angular_velocity.is_finite()
75            || self.angular_velocity.abs() > 1024.
76        {
77            Err(ParticleError::InvalidParticle)
78        } else {
79            Ok(())
80        }
81    }
82}
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub enum ParticleError {
85    Full,
86    InvalidParticle,
87    InvalidDelta,
88    InvalidCapacity,
89    Expired,
90}
91#[derive(Clone, Copy, Debug, PartialEq)]
92pub struct ParticleView {
93    pub position: [f32; 3],
94    pub velocity: [f32; 3],
95    pub color: [f32; 4],
96    pub size: f32,
97    pub rotation: f32,
98    pub normalized_age: f32,
99}
100struct Particle {
101    desc: ParticleDesc,
102    motion: ParticleMotion,
103    age: f64,
104    view: ParticleView,
105}
106impl Particle {
107    fn sample(desc: ParticleDesc, motion: ParticleMotion, age: f64) -> Option<ParticleView> {
108        let k = f64::from(motion.drag);
109        let x = k * age;
110        let (s, u) = if x < 0.0001 {
111            (
112                age * (1. - x * 0.5 + x * x / 6. - x * x * x / 24.),
113                age * age * (0.5 - x / 6. + x * x / 24. - x * x * x / 120.),
114            )
115        } else {
116            let s = -(-x).exp_m1() / k;
117            (s, (age - s) / k)
118        };
119        let decay = if k == 0. { 1. } else { (-x).exp() };
120        let position = std::array::from_fn(|i| {
121            (f64::from(desc.position[i])
122                + f64::from(desc.velocity[i]) * s
123                + f64::from(desc.acceleration[i]) * u) as f32
124        });
125        let velocity = std::array::from_fn(|i| {
126            (f64::from(desc.velocity[i]) * decay + f64::from(desc.acceleration[i]) * s) as f32
127        });
128        if !position.into_iter().chain(velocity).all(f32::is_finite) {
129            return None;
130        }
131        let t = (age / f64::from(desc.lifetime)).clamp(0., 1.);
132        Some(ParticleView {
133            position,
134            velocity,
135            color: std::array::from_fn(|i| {
136                (f64::from(desc.start_color[i]) * (1. - t) + f64::from(desc.end_color[i]) * t)
137                    as f32
138            }),
139            size: (f64::from(desc.start_size) * (1. - t) + f64::from(desc.end_size) * t) as f32,
140            rotation: ((f64::from(motion.rotation) + f64::from(motion.angular_velocity) * age)
141                % f64::from(std::f32::consts::TAU)) as f32,
142            normalized_age: t as f32,
143        })
144    }
145}
146pub struct ParticlePool {
147    particles: Vec<Particle>,
148    limit: usize,
149    dropped: u64,
150    discarded: u64,
151}
152impl ParticlePool {
153    /// Trusted convenience constructor. Use try_new for untrusted capacities.
154    pub fn new(capacity: usize) -> Self {
155        Self::try_new(capacity).expect("particle capacity <= 65536")
156    }
157    pub fn try_new(capacity: usize) -> Result<Self, ParticleError> {
158        if capacity > MAX_PARTICLES {
159            return Err(ParticleError::InvalidCapacity);
160        }
161        Ok(Self {
162            particles: Vec::with_capacity(capacity),
163            limit: capacity,
164            dropped: 0,
165            discarded: 0,
166        })
167    }
168    pub fn len(&self) -> usize {
169        self.particles.len()
170    }
171    pub fn is_empty(&self) -> bool {
172        self.particles.is_empty()
173    }
174    pub fn capacity(&self) -> usize {
175        self.limit
176    }
177    pub fn available(&self) -> usize {
178        self.limit - self.particles.len()
179    }
180    pub fn dropped(&self) -> u64 {
181        self.dropped
182    }
183    pub fn discarded(&self) -> u64 {
184        self.discarded
185    }
186    pub fn clear(&mut self) {
187        self.particles.clear();
188    }
189    pub fn reset_stats(&mut self) {
190        self.dropped = 0;
191        self.discarded = 0;
192    }
193    pub fn spawn(&mut self, desc: ParticleDesc) -> Result<(), ParticleError> {
194        self.spawn_with(desc, ParticleMotion::default())
195    }
196    pub fn spawn_with(
197        &mut self,
198        desc: ParticleDesc,
199        motion: ParticleMotion,
200    ) -> Result<(), ParticleError> {
201        self.spawn_aged(desc, motion, 0.)
202    }
203    /// Birth-time catch-up used by emitters after the existing pool was updated.
204    /// Invalid or already expired samples do not consume a slot.
205    pub fn spawn_aged(
206        &mut self,
207        desc: ParticleDesc,
208        motion: ParticleMotion,
209        age: f32,
210    ) -> Result<(), ParticleError> {
211        desc.validate()?;
212        motion.validate()?;
213        if !age.is_finite() || age < 0. {
214            return Err(ParticleError::InvalidDelta);
215        }
216        if age >= desc.lifetime {
217            return Err(ParticleError::Expired);
218        }
219        let view =
220            Particle::sample(desc, motion, f64::from(age)).ok_or(ParticleError::InvalidParticle)?;
221        if self.available() == 0 {
222            self.dropped = self.dropped.saturating_add(1);
223            return Err(ParticleError::Full);
224        }
225        self.particles.push(Particle {
226            desc,
227            motion,
228            age: f64::from(age),
229            view,
230        });
231        Ok(())
232    }
233    pub fn update(&mut self, dt: f32) -> Result<(), ParticleError> {
234        if !dt.is_finite() || dt < 0. {
235            return Err(ParticleError::InvalidDelta);
236        }
237        let mut i = 0;
238        while i < self.particles.len() {
239            let p = &mut self.particles[i];
240            p.age += f64::from(dt);
241            if p.age >= f64::from(p.desc.lifetime) {
242                self.particles.swap_remove(i);
243                continue;
244            }
245            if let Some(view) = Particle::sample(p.desc, p.motion, p.age) {
246                p.view = view;
247                i += 1;
248            } else {
249                self.discarded = self.discarded.saturating_add(1);
250                self.particles.swap_remove(i);
251            }
252        }
253        Ok(())
254    }
255    pub fn iter(&self) -> impl ExactSizeIterator<Item = ParticleView> + '_ {
256        self.particles.iter().map(|p| p.view)
257    }
258}
259#[cfg(test)]
260mod tests {
261    use super::*;
262    #[test]
263    fn capacity_is_bounded_and_expired_slots_are_reusable() {
264        let mut pool = ParticlePool::new(2);
265        pool.spawn(ParticleDesc::default()).unwrap();
266        pool.spawn(ParticleDesc::default()).unwrap();
267        assert_eq!(
268            pool.spawn(ParticleDesc::default()),
269            Err(ParticleError::Full)
270        );
271        assert_eq!(pool.dropped(), 1);
272        pool.update(1.0).unwrap();
273        assert!(pool.is_empty());
274        pool.spawn(ParticleDesc::default()).unwrap();
275        assert_eq!(pool.len(), 1);
276        assert_eq!(pool.capacity(), 2);
277    }
278    #[test]
279    fn constant_acceleration_matches_frame_partition_and_color_fades() {
280        let desc = ParticleDesc {
281            velocity: [2.0, 0.0, 0.0],
282            acceleration: [0.0, -4.0, 0.0],
283            lifetime: 2.0,
284            ..ParticleDesc::default()
285        };
286        let mut a = ParticlePool::new(1);
287        let mut b = ParticlePool::new(1);
288        a.spawn(desc).unwrap();
289        b.spawn(desc).unwrap();
290        a.update(1.0).unwrap();
291        for _ in 0..10 {
292            b.update(0.1).unwrap();
293        }
294        let av = a.iter().next().unwrap();
295        let bv = b.iter().next().unwrap();
296        assert_eq!(av.position, [2.0, -2.0, 0.0]);
297        for i in 0..3 {
298            assert!((av.position[i] - bv.position[i]).abs() < 1e-5);
299        }
300        assert_eq!(av.color[3], 0.5);
301    }
302    #[test]
303    fn invalid_values_do_not_poison_pool() {
304        let mut pool = ParticlePool::new(1);
305        assert_eq!(
306            pool.spawn(ParticleDesc {
307                lifetime: f32::NAN,
308                ..ParticleDesc::default()
309            }),
310            Err(ParticleError::InvalidParticle)
311        );
312        pool.spawn(ParticleDesc::default()).unwrap();
313        assert_eq!(pool.update(-1.0), Err(ParticleError::InvalidDelta));
314        assert_eq!(pool.iter().next().unwrap().normalized_age, 0.0);
315    }
316}