Skip to main content

sciart_shared/
plume.rs

1//! Ballistic volcanic and impact plumes (M13 shared model: `io_volcanoes`,
2//! `comet_breakup`).
3//!
4//! Grains leave a vent with speed `v0` in a direction drawn uniformly (in solid angle)
5//! between two zenith angles and fly in a uniform gravity `g` with no air: every path is
6//! an exact parabola, advanced in closed form, so the apex is exactly `(v0·cos θ)²/(2g)`
7//! and a grain launched at zenith angle θ lands `v0²·sin 2θ / g` away on flat ground
8//! (IO-A1, IO-A3). A landing is reported at its exact point inside the step, then the
9//! grain is removed. Coordinates are local to the vent: `x`, `y` along the ground, `z` up.
10//!
11//! The pool has a fixed capacity (GEN-R11): a launch into a full pool is dropped.
12
13use rand::Rng;
14use sciart_core::ParticlePool;
15use sciart_core::Trig;
16
17/// One plume grain.
18#[derive(Debug, Clone, Copy, Default)]
19pub struct Grain {
20    /// Position relative to the vent (`z` up), in the scene's length unit.
21    pub pos: [f32; 3],
22    pub vel: [f32; 3],
23    /// Seconds since launch.
24    pub age: f32,
25    /// Which vent (or impact) launched it.
26    pub src: u8,
27}
28
29#[cfg(any(test, feature = "test-support"))]
30/// Apex height of a grain launched at `v0` at zenith angle `zenith` (radians).
31pub fn apex(v0: f64, g: f64, zenith: f64) -> f64 {
32    let vz = v0 * zenith.cos_det();
33    vz * vz / (2.0 * g)
34}
35
36/// Flat-ground range of a grain launched at `v0` at zenith angle `zenith`.
37pub fn range(v0: f64, g: f64, zenith: f64) -> f64 {
38    v0 * v0 * (2.0 * zenith).sin_det() / g
39}
40
41#[derive(Debug, Clone)]
42pub struct Plume {
43    pool: ParticlePool<Grain>,
44}
45
46impl Plume {
47    pub fn with_capacity(capacity: usize) -> Self {
48        Self {
49            pool: ParticlePool::with_capacity(capacity),
50        }
51    }
52
53    /// Launch one grain from `src` at speed `v0`, zenith angle uniform in solid angle over
54    /// `[zenith.0, zenith.1]` (radians) and azimuth uniform. Returns `false` when the
55    /// pool is full.
56    pub fn launch(&mut self, rng: &mut impl Rng, src: u8, v0: f32, zenith: (f32, f32)) -> bool {
57        let (c0, c1) = (zenith.0.cos_det(), zenith.1.cos_det());
58        let cz = c1 + (c0 - c1) * rng.random::<f32>();
59        let sz = (1.0 - cz * cz).max(0.0).sqrt();
60        let (sa, ca) = (std::f32::consts::TAU * rng.random::<f32>()).sin_cos_det();
61        self.pool.spawn(Grain {
62            pos: [0.0; 3],
63            vel: [v0 * sz * ca, v0 * sz * sa, v0 * cz],
64            age: 0.0,
65            src,
66        })
67    }
68
69    /// [`launch`](Self::launch), but with the azimuth drawn from `rays` evenly spaced
70    /// directions (a little jittered), so the plume shows radial filaments; `rays = 0`
71    /// is a uniform azimuth.
72    pub fn launch_rays(
73        &mut self,
74        rng: &mut impl Rng,
75        src: u8,
76        v0: f32,
77        zenith: (f32, f32),
78        rays: u32,
79    ) -> bool {
80        let (c0, c1) = (zenith.0.cos_det(), zenith.1.cos_det());
81        let cz = c1 + (c0 - c1) * rng.random::<f32>();
82        let sz = (1.0 - cz * cz).max(0.0).sqrt();
83        let turn = if rays == 0 {
84            rng.random::<f32>()
85        } else {
86            let k = rng.random_range(0..rays) as f32;
87            (k + 0.4 * (rng.random::<f32>() - 0.5)) / rays as f32
88        };
89        let (sa, ca) = (std::f32::consts::TAU * turn).sin_cos_det();
90        self.pool.spawn(Grain {
91            pos: [0.0; 3],
92            vel: [v0 * sz * ca, v0 * sz * sa, v0 * cz],
93            age: 0.0,
94            src,
95        })
96    }
97
98    /// Fly every grain for `dt` seconds under gravity `g` (down `z`); a grain that
99    /// reaches the ground (`z ≤ 0` after lift-off) is reported to `landed` at its exact
100    /// landing point and removed.
101    pub fn step(&mut self, dt: f32, g: f32, mut landed: impl FnMut(&Grain)) {
102        if !(dt.is_finite() && dt > 0.0 && g.is_finite() && g > 0.0) {
103            return;
104        }
105        self.pool.retain(|p| {
106            let z_new = p.pos[2] + p.vel[2] * dt - 0.5 * g * dt * dt;
107            if z_new <= 0.0 {
108                // The later root of z0 + vz·τ − ½gτ² = 0, clamped into the step.
109                let disc = (p.vel[2] * p.vel[2] + 2.0 * g * p.pos[2].max(0.0)).sqrt();
110                let tau = ((p.vel[2] + disc) / g).clamp(0.0, dt);
111                let mut at = *p;
112                at.pos[0] += p.vel[0] * tau;
113                at.pos[1] += p.vel[1] * tau;
114                at.pos[2] = 0.0;
115                at.vel[2] -= g * tau;
116                at.age += tau;
117                landed(&at);
118                return false;
119            }
120            p.pos[0] += p.vel[0] * dt;
121            p.pos[1] += p.vel[1] * dt;
122            p.pos[2] = z_new;
123            p.vel[2] -= g * dt;
124            p.age += dt;
125            true
126        });
127    }
128
129    pub fn iter(&self) -> impl Iterator<Item = &Grain> {
130        self.pool.iter()
131    }
132
133    #[cfg(any(test, feature = "test-support"))]
134    pub fn len(&self) -> usize {
135        self.pool.len()
136    }
137
138    // `len` became public API when the shared models got their own crate (ADR-0023);
139    // clippy's `len_without_is_empty` asks for its pair.
140    #[cfg(any(test, feature = "test-support"))]
141    pub fn is_empty(&self) -> bool {
142        self.pool.is_empty()
143    }
144
145    #[cfg(any(test, feature = "test-support"))]
146    pub fn capacity(&self) -> usize {
147        self.pool.capacity()
148    }
149
150    pub fn clear(&mut self) {
151        self.pool.clear();
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158    use sciart_core::SplitMix64;
159
160    #[test]
161    fn io_a1_grains_peak_at_the_closed_form_apex() {
162        let mut rng = SplitMix64::new(1);
163        let mut plume = Plume::with_capacity(64);
164        let (v0, g) = (1.0f32, 1.8e-3f32); // km/s and km/s²: Pele
165        for _ in 0..32 {
166            plume.launch(&mut rng, 0, v0, (0.0, 0.9));
167        }
168        let mut peak = [0.0f32; 64];
169        let zen: Vec<f32> = plume.iter().map(|p| (p.vel[2] / v0).acos()).collect();
170        let dt = 0.5;
171        for _ in 0..4000 {
172            for (k, p) in plume.iter().enumerate() {
173                peak[k] = peak[k].max(p.pos[2]);
174            }
175            plume.step(dt, g, |_| {});
176            if plume.len() < zen.len() {
177                break;
178            }
179        }
180        for (k, &z) in zen.iter().enumerate() {
181            let want = apex(f64::from(v0), f64::from(g), f64::from(z)) as f32;
182            assert!(
183                (peak[k] - want).abs() <= 0.01 * want,
184                "{} vs {want}",
185                peak[k]
186            );
187        }
188    }
189
190    #[test]
191    fn io_a3_landings_match_the_ballistic_range() {
192        let mut rng = SplitMix64::new(2);
193        let mut plume = Plume::with_capacity(8);
194        let (v0, g) = (0.5f32, 1.8e-3f32);
195        let z = std::f32::consts::FRAC_PI_4;
196        plume.launch(&mut rng, 0, v0, (z, z));
197        let mut got = None;
198        for _ in 0..10_000 {
199            plume.step(0.7, g, |p| got = Some(p.pos[0].hypot(p.pos[1])));
200            if got.is_some() {
201                break;
202            }
203        }
204        let want = range(f64::from(v0), f64::from(g), f64::from(z)) as f32;
205        let got = got.expect("the grain lands");
206        assert!((got - want).abs() < 1e-3 * want, "{got} vs {want}");
207    }
208
209    #[test]
210    fn io_a4_the_pool_never_exceeds_capacity() {
211        let mut rng = SplitMix64::new(3);
212        let mut plume = Plume::with_capacity(10);
213        let launched = (0..25)
214            .filter(|_| plume.launch(&mut rng, 0, 1.0, (0.0, 1.0)))
215            .count();
216        assert_eq!(launched, 10);
217        assert_eq!(plume.len(), plume.capacity());
218        plume.step(f32::NAN, 1.0, |_| {});
219        assert_eq!(plume.len(), 10);
220    }
221}