Skip to main content

fc_ui/capabilities/effects/
particle_emitter.rs

1//! Lightweight particle system using canvas painting.
2
3use gpui::{prelude::FluentBuilder as _, *};
4use std::time::Duration;
5
6#[derive(Clone)]
7pub struct Particle {
8    pub position: Point<f32>,
9    pub velocity: Point<f32>,
10    pub age: f32,
11    pub lifetime: f32,
12    pub size: f32,
13    pub color: Hsla,
14}
15
16#[derive(Clone)]
17pub struct ParticleEmitterConfig {
18    pub spawn_rate: f32,
19    pub lifetime: Duration,
20    pub velocity_range: (f32, f32),
21    pub size_range: (f32, f32),
22    pub color_start: Hsla,
23    pub color_end: Hsla,
24    pub gravity: f32,
25    pub spread_angle: f32,
26    pub max_particles: usize,
27    pub origin: Point<f32>,
28}
29
30impl Default for ParticleEmitterConfig {
31    fn default() -> Self {
32        Self {
33            spawn_rate: 10.0,
34            lifetime: Duration::from_millis(1500),
35            velocity_range: (50.0, 150.0),
36            size_range: (2.0, 6.0),
37            color_start: hsla(0.55, 0.8, 0.6, 1.0),
38            color_end: hsla(0.55, 0.8, 0.6, 0.0),
39            gravity: 80.0,
40            spread_angle: std::f32::consts::PI,
41            max_particles: 200,
42            origin: Point { x: 0.0, y: 0.0 },
43        }
44    }
45}
46
47pub struct ParticleEmitterState {
48    particles: Vec<Particle>,
49    config: ParticleEmitterConfig,
50    accumulator: f32,
51    running: bool,
52}
53
54impl ParticleEmitterState {
55    pub fn new(_cx: &mut Context<Self>) -> Self {
56        Self {
57            particles: Vec::with_capacity(200),
58            config: ParticleEmitterConfig::default(),
59            accumulator: 0.0,
60            running: false,
61        }
62    }
63
64    pub fn with_config(config: ParticleEmitterConfig, _cx: &mut Context<Self>) -> Self {
65        let cap = config.max_particles;
66        Self {
67            particles: Vec::with_capacity(cap),
68            config,
69            accumulator: 0.0,
70            running: false,
71        }
72    }
73
74    pub fn set_config(&mut self, config: ParticleEmitterConfig, cx: &mut Context<Self>) {
75        self.config = config;
76        cx.notify();
77    }
78
79    pub fn set_origin(&mut self, origin: Point<f32>, cx: &mut Context<Self>) {
80        self.config.origin = origin;
81        cx.notify();
82    }
83
84    pub fn start(&mut self, cx: &mut Context<Self>) {
85        if self.running {
86            return;
87        }
88        self.running = true;
89        self.schedule_tick(cx);
90        cx.notify();
91    }
92
93    pub fn stop(&mut self, cx: &mut Context<Self>) {
94        self.running = false;
95        cx.notify();
96    }
97
98    pub fn is_running(&self) -> bool {
99        self.running
100    }
101
102    pub fn clear(&mut self, cx: &mut Context<Self>) {
103        self.particles.clear();
104        cx.notify();
105    }
106
107    pub fn emit(&mut self, count: usize) {
108        let config = &self.config;
109        let lifetime_secs = config.lifetime.as_secs_f32();
110
111        for _ in 0..count {
112            if self.particles.len() >= config.max_particles {
113                break;
114            }
115
116            let angle_offset =
117                (pseudo_random_f32(self.particles.len() as u32) - 0.5) * config.spread_angle;
118            let speed = config.velocity_range.0
119                + pseudo_random_f32(self.particles.len() as u32 + 7)
120                    * (config.velocity_range.1 - config.velocity_range.0);
121            let particle_size = config.size_range.0
122                + pseudo_random_f32(self.particles.len() as u32 + 13)
123                    * (config.size_range.1 - config.size_range.0);
124
125            let vx = angle_offset.sin() * speed;
126            let vy = -angle_offset.cos() * speed;
127
128            self.particles.push(Particle {
129                position: config.origin,
130                velocity: Point { x: vx, y: vy },
131                age: 0.0,
132                lifetime: lifetime_secs,
133                size: particle_size,
134                color: config.color_start,
135            });
136        }
137    }
138
139    pub fn update(&mut self, dt: f32) {
140        let gravity = self.config.gravity;
141        let color_start = self.config.color_start;
142        let color_end = self.config.color_end;
143
144        for particle in &mut self.particles {
145            particle.age += dt;
146            particle.velocity.y += gravity * dt;
147            particle.position.x += particle.velocity.x * dt;
148            particle.position.y += particle.velocity.y * dt;
149
150            let t = (particle.age / particle.lifetime).clamp(0.0, 1.0);
151            particle.color = lerp_hsla(color_start, color_end, t);
152        }
153
154        self.particles.retain(|p| p.age < p.lifetime);
155    }
156
157    pub fn particles(&self) -> &[Particle] {
158        &self.particles
159    }
160
161    fn schedule_tick(&self, cx: &mut Context<Self>) {
162        if !self.running {
163            return;
164        }
165
166        cx.spawn(async |this, cx| {
167            cx.background_executor()
168                .timer(Duration::from_millis(16))
169                .await;
170
171            _ = this.update(cx, |state, cx| {
172                if !state.running {
173                    return;
174                }
175
176                let dt = 1.0 / 60.0;
177                state.accumulator += state.config.spawn_rate * dt;
178
179                let to_spawn = state.accumulator as usize;
180                state.accumulator -= to_spawn as f32;
181                state.emit(to_spawn);
182                state.update(dt);
183
184                state.schedule_tick(cx);
185                cx.notify();
186            });
187        })
188        .detach();
189    }
190}
191
192impl Render for ParticleEmitterState {
193    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
194        div()
195    }
196}
197
198struct EmitterPaintData {
199    particles: Vec<Particle>,
200}
201
202#[derive(IntoElement)]
203pub struct ParticleEmitter {
204    id: ElementId,
205    state: Entity<ParticleEmitterState>,
206    style: StyleRefinement,
207}
208
209impl ParticleEmitter {
210    pub fn new(id: impl Into<ElementId>, state: Entity<ParticleEmitterState>) -> Self {
211        Self {
212            id: id.into(),
213            state,
214            style: StyleRefinement::default(),
215        }
216    }
217
218    pub fn spawn_rate(self, rate: f32, cx: &mut App) -> Self {
219        self.state.update(cx, |s, _| s.config.spawn_rate = rate);
220        self
221    }
222
223    pub fn lifetime(self, lifetime: Duration, cx: &mut App) -> Self {
224        self.state.update(cx, |s, _| s.config.lifetime = lifetime);
225        self
226    }
227
228    pub fn velocity_range(self, range: (f32, f32), cx: &mut App) -> Self {
229        self.state
230            .update(cx, |s, _| s.config.velocity_range = range);
231        self
232    }
233
234    pub fn size_range(self, range: (f32, f32), cx: &mut App) -> Self {
235        self.state.update(cx, |s, _| s.config.size_range = range);
236        self
237    }
238
239    pub fn color_start(self, color: Hsla, cx: &mut App) -> Self {
240        self.state.update(cx, |s, _| s.config.color_start = color);
241        self
242    }
243
244    pub fn color_end(self, color: Hsla, cx: &mut App) -> Self {
245        self.state.update(cx, |s, _| s.config.color_end = color);
246        self
247    }
248
249    pub fn gravity(self, gravity: f32, cx: &mut App) -> Self {
250        self.state.update(cx, |s, _| s.config.gravity = gravity);
251        self
252    }
253
254    pub fn spread_angle(self, angle: f32, cx: &mut App) -> Self {
255        self.state.update(cx, |s, _| s.config.spread_angle = angle);
256        self
257    }
258
259    pub fn max_particles(self, max: usize, cx: &mut App) -> Self {
260        self.state.update(cx, |s, _| s.config.max_particles = max);
261        self
262    }
263
264    pub fn origin(self, origin: Point<f32>, cx: &mut App) -> Self {
265        self.state.update(cx, |s, _| s.config.origin = origin);
266        self
267    }
268}
269
270impl Styled for ParticleEmitter {
271    fn style(&mut self) -> &mut StyleRefinement {
272        &mut self.style
273    }
274}
275
276impl RenderOnce for ParticleEmitter {
277    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
278        let user_style = self.style;
279        let state = self.state.read(cx);
280        let paint_data = EmitterPaintData {
281            particles: state.particles().to_vec(),
282        };
283
284        div()
285            .id(self.id)
286            .relative()
287            .size_full()
288            .child(
289                canvas(
290                    move |_bounds, _window, _cx| paint_data,
291                    move |bounds, data, window, _cx| {
292                        paint_particles(bounds, &data, window);
293                    },
294                )
295                .absolute()
296                .inset_0()
297                .size_full(),
298            )
299            .map(|this| {
300                let mut el = this;
301                el.style().refine(&user_style);
302                el
303            })
304    }
305}
306
307fn paint_particles(bounds: Bounds<Pixels>, data: &EmitterPaintData, window: &mut Window) {
308    if bounds.size.width <= px(0.0) || bounds.size.height <= px(0.0) {
309        return;
310    }
311
312    for particle in &data.particles {
313        let x = bounds.left() + px(particle.position.x);
314        let y = bounds.top() + px(particle.position.y);
315        let half = particle.size * 0.5;
316
317        if x + px(half) < bounds.left()
318            || x - px(half) > bounds.right()
319            || y + px(half) < bounds.top()
320            || y - px(half) > bounds.bottom()
321        {
322            continue;
323        }
324
325        window.paint_quad(PaintQuad {
326            bounds: Bounds {
327                origin: point(x - px(half), y - px(half)),
328                size: gpui::size(px(particle.size), px(particle.size)),
329            },
330            corner_radii: Corners::all(px(half)),
331            background: particle.color.into(),
332            border_widths: Edges::default(),
333            border_color: transparent_black(),
334            border_style: BorderStyle::default(),
335            continuous_corners: false,
336            transform: Default::default(),
337            blend_mode: Default::default(),
338        });
339    }
340}
341
342fn lerp_hsla(a: Hsla, b: Hsla, t: f32) -> Hsla {
343    hsla(
344        a.h + (b.h - a.h) * t,
345        a.s + (b.s - a.s) * t,
346        a.l + (b.l - a.l) * t,
347        a.a + (b.a - a.a) * t,
348    )
349}
350
351fn pseudo_random_f32(seed: u32) -> f32 {
352    let mut x = seed.wrapping_add(0x9E3779B9);
353    x ^= x >> 16;
354    x = x.wrapping_mul(0x45D9F3B);
355    x ^= x >> 16;
356    (x & 0xFFFF) as f32 / 65535.0
357}