#[derive(Clone)]
pub struct Particle {
pub x: f64,
pub y: f64,
pub z: f64,
pub target_z: f64,
}
impl Particle {
pub fn new(x: f64, y: f64, z: f64) -> Self {
Particle {
x,
y,
z,
target_z: 0.0,
}
}
pub fn is_out_of_bounds(&self, max_x: f64, max_y: f64, min_z: f64) -> bool {
self.x < -1.0
|| self.x > max_x + 1.0
|| self.y < -1.0
|| self.y > max_y + 1.0
|| self.z < min_z
}
}
pub struct ParticleSystem {
pub particles: Vec<Particle>,
}
impl ParticleSystem {
pub fn new() -> Self {
ParticleSystem {
particles: Vec::new(),
}
}
pub fn add_particle(&mut self, particle: Particle) {
self.particles.push(particle);
}
pub fn clear(&mut self) {
self.particles.clear();
}
pub fn remove_out_of_bounds(&mut self, max_x: f64, max_y: f64, min_z: f64) {
self.particles
.retain(|p| !p.is_out_of_bounds(max_x, max_y, min_z));
}
pub fn count(&self) -> usize {
self.particles.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new_particle_fields() {
let p = Particle::new(1.5, 2.5, 10.0);
assert_eq!(p.x, 1.5);
assert_eq!(p.y, 2.5);
assert_eq!(p.z, 10.0);
assert_eq!(p.target_z, 0.0); }
#[test]
fn add_clear_count() {
let mut ps = ParticleSystem::new();
assert_eq!(ps.count(), 0);
ps.add_particle(Particle::new(0.0, 0.0, 1.0));
ps.add_particle(Particle::new(1.0, 1.0, 2.0));
assert_eq!(ps.count(), 2);
ps.clear();
assert_eq!(ps.count(), 0);
}
#[test]
fn remove_out_of_bounds_only() {
let mut ps = ParticleSystem::new();
ps.add_particle(Particle::new(0.5, 0.5, 1.0)); ps.add_particle(Particle::new(50.0, 0.5, 1.0)); ps.add_particle(Particle::new(0.5, 0.5, -10.0)); ps.remove_out_of_bounds(8.0, 8.0, -5.0);
assert_eq!(ps.count(), 1);
assert_eq!(ps.particles[0].x, 0.5);
}
#[test]
fn is_out_of_bounds_edges() {
let p = Particle::new(-2.0, 0.5, 1.0);
assert!(p.is_out_of_bounds(8.0, 8.0, -5.0));
let p = Particle::new(0.5, 0.5, -6.0);
assert!(p.is_out_of_bounds(8.0, 8.0, -5.0));
let p = Particle::new(9.5, 0.5, 1.0);
assert!(p.is_out_of_bounds(8.0, 8.0, -5.0));
let p = Particle::new(0.5, 0.5, 1.0);
assert!(!p.is_out_of_bounds(8.0, 8.0, -5.0));
}
}