Skip to main content

euv_core/game/particles/
impl.rs

1use super::*;
2
3/// Default radial spark burst emitter configuration.
4impl Default for ParticleEmitterConfig {
5    /// Creates a radial neon spark burst configuration.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default particle emitter config.
10    fn default() -> Self {
11        Self {
12            base_angle: 0.0,
13            spread_rad: TAU,
14            min_speed: 60.0,
15            max_speed: 220.0,
16            min_life: 0.25,
17            max_life: 0.65,
18            start_size: 4.5,
19            end_size: 0.8,
20            start_color: Color::rgba(56, 189, 248, 255),
21            end_color: Color::rgba(99, 102, 241, 0),
22            drag: 2.2,
23        }
24    }
25}
26
27/// Default 1,024-slot particle system pool.
28impl Default for ParticleSystem {
29    /// Allocates a `ParticleSystem` with 1,024 pooled slots.
30    ///
31    /// # Returns
32    ///
33    /// - `Self` - Ready particle system.
34    fn default() -> Self {
35        Self::with_capacity(1024)
36    }
37}
38
39/// Particle emission, deterministic PRNG, and active-prefix SoA kinematics for `ParticleSystem`.
40impl ParticleSystem {
41    /// Allocates a fixed-capacity `ParticleSystem` with `capacity` pre-allocated SoA slots.
42    ///
43    /// # Arguments
44    ///
45    /// - `usize` - Maximum concurrent particles.
46    ///
47    /// # Returns
48    ///
49    /// - `Self` - Pre-allocated particle system.
50    #[must_use]
51    pub fn with_capacity(capacity: usize) -> Self {
52        let cap: usize = capacity.max(16);
53        Self {
54            capacity: cap,
55            pos_x: vec![0.0; cap],
56            pos_y: vec![0.0; cap],
57            vel_x: vec![0.0; cap],
58            vel_y: vec![0.0; cap],
59            age: vec![0.0; cap],
60            lifetime: vec![0.0; cap],
61            drag: vec![0.0; cap],
62            start_size: vec![0.0; cap],
63            end_size: vec![0.0; cap],
64            start_color: vec![Color::default(); cap],
65            end_color: vec![Color::default(); cap],
66            min_remaining_life: f32::INFINITY,
67            cursor: 0,
68            rng_state: 0x9E37_79B9_7F4A_7C15,
69            gravity: Point::new(0.0, 0.0),
70            active_count: 0,
71        }
72    }
73
74    /// Generates a deterministic pseudo-random `f32` in `[0.0, 1.0)` advancing `state`.
75    ///
76    /// # Arguments
77    ///
78    /// - `&mut u64` - Mutable PRNG state word.
79    ///
80    /// # Returns
81    ///
82    /// - `f32` - Normalized random scalar.
83    #[inline(always)]
84    fn next_unit_f32_from(state: &mut u64) -> f32 {
85        let next: u64 = state
86            .wrapping_mul(6_364_136_223_846_793_005)
87            .wrapping_add(1_442_695_040_888_963_407);
88        *state = next;
89        ((next >> 40) as f32) * (1.0 / ((1_u32 << 24) as f32))
90    }
91
92    /// Emits `count` particles at `origin` using `config` into the compacted active prefix without heap allocations.
93    ///
94    /// # Arguments
95    ///
96    /// - `&Self` - Mutable particle system.
97    /// - `Point` - World-space emission origin.
98    /// - `usize` - Number of particles to emit.
99    /// - `ParticleEmitterConfig` - Emission parameters.
100    pub fn emit_burst(&mut self, origin: Point, count: usize, config: ParticleEmitterConfig) {
101        let Self {
102            capacity,
103            pos_x,
104            pos_y,
105            vel_x,
106            vel_y,
107            age,
108            lifetime,
109            drag,
110            start_size,
111            end_size,
112            start_color,
113            end_color,
114            min_remaining_life,
115            cursor,
116            rng_state,
117            active_count,
118            ..
119        } = self;
120        let cap: usize = *capacity;
121        if cap == 0 || count == 0 {
122            return;
123        }
124        let base_angle: f32 = config.get_base_angle();
125        let spread_rad: f32 = config.get_spread_rad();
126        let min_speed: f32 = config.get_min_speed();
127        let speed_span: f32 = config.get_max_speed() - min_speed;
128        let min_life: f32 = config.get_min_life();
129        let life_span: f32 = config.get_max_life() - min_life;
130        let s_size: f32 = config.get_start_size();
131        let e_size: f32 = config.get_end_size();
132        let s_col: Color = config.get_start_color();
133        let e_col: Color = config.get_end_color();
134        let p_drag: f32 = config.get_drag();
135        let ox: f32 = origin.get_x();
136        let oy: f32 = origin.get_y();
137        let mut cur_rng: u64 = *rng_state;
138        let mut live: usize = *active_count;
139        let mut cur_slot: usize = *cursor;
140        let mut min_rem: f32 = *min_remaining_life;
141        for _ in 0..count {
142            let r_ang: f32 = Self::next_unit_f32_from(&mut cur_rng);
143            let r_spd: f32 = Self::next_unit_f32_from(&mut cur_rng);
144            let r_life: f32 = Self::next_unit_f32_from(&mut cur_rng);
145            let angle: f32 = base_angle + (r_ang - 0.5) * spread_rad;
146            let speed: f32 = min_speed + speed_span * r_spd;
147            let life: f32 = (min_life + life_span * r_life).max(0.02);
148            let slot_idx: usize = if live < cap {
149                let s: usize = live;
150                live += 1;
151                s
152            } else {
153                let s: usize = cur_slot % cap;
154                cur_slot = (s + 1) % cap;
155                s
156            };
157            let (sin_a, cos_a): (f32, f32) = angle.sin_cos();
158            pos_x[slot_idx] = ox;
159            pos_y[slot_idx] = oy;
160            vel_x[slot_idx] = cos_a * speed;
161            vel_y[slot_idx] = sin_a * speed;
162            age[slot_idx] = 0.0;
163            lifetime[slot_idx] = life;
164            drag[slot_idx] = p_drag;
165            start_size[slot_idx] = s_size;
166            end_size[slot_idx] = e_size;
167            start_color[slot_idx] = s_col;
168            end_color[slot_idx] = e_col;
169            min_rem = min_rem.min(life);
170        }
171        *rng_state = cur_rng;
172        *active_count = live;
173        *cursor = cur_slot;
174        *min_remaining_life = min_rem;
175    }
176
177    /// Advances all active particles in `[0..active_count)` via auto-vectorized SoA kinematics and swap-removes expired slots.
178    ///
179    /// # Arguments
180    ///
181    /// - `&Self` - Mutable particle system.
182    /// - `f32` - Elapsed timestep in seconds.
183    ///
184    /// # Returns
185    ///
186    /// - `usize` - Number of particles still active after the update.
187    pub fn update(&mut self, dt_secs: f32) -> usize {
188        let Self {
189            pos_x,
190            pos_y,
191            vel_x,
192            vel_y,
193            age,
194            lifetime,
195            drag,
196            start_size,
197            end_size,
198            start_color,
199            end_color,
200            min_remaining_life,
201            gravity,
202            active_count,
203            ..
204        } = self;
205        let mut n: usize = *active_count;
206        if n == 0 {
207            return 0;
208        }
209        let gx_dt: f32 = gravity.get_x() * dt_secs;
210        let gy_dt: f32 = gravity.get_y() * dt_secs;
211        let neg_dt: f32 = -dt_secs;
212        let next_min_bound: f32 = *min_remaining_life - dt_secs;
213        if next_min_bound > 0.0 {
214            let px: &mut [f32] = &mut pos_x[..n];
215            let py: &mut [f32] = &mut pos_y[..n];
216            let vx: &mut [f32] = &mut vel_x[..n];
217            let vy: &mut [f32] = &mut vel_y[..n];
218            let ag: &mut [f32] = &mut age[..n];
219            let dr: &[f32] = &drag[..n];
220            for i in 0..n {
221                ag[i] += dt_secs;
222                let damp: f32 = dr[i].mul_add(neg_dt, 1.0).clamp(0.0, 1.0);
223                let nvx: f32 = (vx[i] + gx_dt) * damp;
224                let nvy: f32 = (vy[i] + gy_dt) * damp;
225                vx[i] = nvx;
226                vy[i] = nvy;
227                px[i] = nvx.mul_add(dt_secs, px[i]);
228                py[i] = nvy.mul_add(dt_secs, py[i]);
229            }
230            *min_remaining_life = next_min_bound;
231            return n;
232        }
233        let mut i: usize = 0;
234        let mut recomputed_min_rem: f32 = f32::INFINITY;
235        while i < n {
236            let next_age: f32 = age[i] + dt_secs;
237            let life: f32 = lifetime[i];
238            if next_age >= life {
239                n -= 1;
240                if i < n {
241                    pos_x[i] = pos_x[n];
242                    pos_y[i] = pos_y[n];
243                    vel_x[i] = vel_x[n];
244                    vel_y[i] = vel_y[n];
245                    age[i] = age[n];
246                    lifetime[i] = lifetime[n];
247                    drag[i] = drag[n];
248                    start_size[i] = start_size[n];
249                    end_size[i] = end_size[n];
250                    start_color[i] = start_color[n];
251                    end_color[i] = end_color[n];
252                }
253                continue;
254            }
255            let damp: f32 = drag[i].mul_add(neg_dt, 1.0).clamp(0.0, 1.0);
256            let nvx: f32 = (vel_x[i] + gx_dt) * damp;
257            let nvy: f32 = (vel_y[i] + gy_dt) * damp;
258            age[i] = next_age;
259            vel_x[i] = nvx;
260            vel_y[i] = nvy;
261            pos_x[i] = nvx.mul_add(dt_secs, pos_x[i]);
262            pos_y[i] = nvy.mul_add(dt_secs, pos_y[i]);
263            recomputed_min_rem = recomputed_min_rem.min(life - next_age);
264            i += 1;
265        }
266        *active_count = n;
267        *min_remaining_life = recomputed_min_rem;
268        n
269    }
270
271    /// Returns a snapshot of the active particle at compacted slot `index`, or `None` if `index >= active_count`.
272    ///
273    /// # Arguments
274    ///
275    /// - `&Self` - Particle system reference.
276    /// - `usize` - Active particle index in `0..active_count`.
277    ///
278    /// # Returns
279    ///
280    /// - `Option<Particle>` - Reconstructed `Particle` record for inspection.
281    #[must_use]
282    pub fn active_particle(&self, index: usize) -> Option<Particle> {
283        let Self {
284            pos_x,
285            pos_y,
286            vel_x,
287            vel_y,
288            age,
289            lifetime,
290            drag,
291            start_size,
292            end_size,
293            start_color,
294            end_color,
295            active_count,
296            ..
297        } = self;
298        if index >= *active_count {
299            return None;
300        }
301        Some(Particle {
302            active: true,
303            position: Point::new(pos_x[index], pos_y[index]),
304            velocity: Point::new(vel_x[index], vel_y[index]),
305            age: age[index],
306            lifetime: lifetime[index],
307            start_size: start_size[index],
308            end_size: end_size[index],
309            start_color: start_color[index],
310            end_color: end_color[index],
311            drag: drag[index],
312        })
313    }
314
315    /// Clears all active particles in O(1) while retaining pre-allocated SoA lane capacities.
316    ///
317    /// # Arguments
318    ///
319    /// - `&Self` - Mutable particle system.
320    pub fn clear(&mut self) {
321        let Self {
322            active_count,
323            cursor,
324            min_remaining_life,
325            ..
326        } = self;
327        *active_count = 0;
328        *cursor = 0;
329        *min_remaining_life = f32::INFINITY;
330    }
331}