From 21244bd086075f7ed019abcfd21b087d822a2e22 Mon Sep 17 00:00:00 2001 From: Logan Date: Fri, 12 Jan 2024 14:33:34 -0600 Subject: [PATCH] more async --- src/lib.rs | 3 ++- src/sim.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 4b9df3a..6f0b71e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -43,7 +43,8 @@ pub fn generate(image: ImageBuffer, Vec>) -> Vec { } pub async fn generate_async(image: ImageBuffer, Vec>) -> Vec { - let (mut sim, it) = sim::Simulation::simulate_image(500.0, 500.0, 8.0, image); + let (mut sim, it) = + sim::Simulation::simulate_image_async(500.0, 500.0, 8.0, image).await; let mut buffer = Vec::::new(); let mut encoder = gif::Encoder::new(&mut buffer, 500, 500, &[]).unwrap(); diff --git a/src/sim.rs b/src/sim.rs index 900b5e8..28101e2 100644 --- a/src/sim.rs +++ b/src/sim.rs @@ -91,6 +91,32 @@ impl Simulation { (sim, total_iterations) } + #[inline] + pub async fn simulate_image_async( + width: f32, + height: f32, + circle_radius: f32, + img: ImageBuffer, Vec>, + ) -> (Self, usize) { + let image_hash = ({ + let mut s = std::hash::DefaultHasher::new(); + img.hash(&mut s); + s.finish() + } % 1204) as usize; + let mut sim = Simulation::new(width, height, circle_radius, image_hash); + while sim.circles() < sim.max_circles { + sim.step_async().await; + } + for _ in 0..120 { + sim.step_async().await + } + let total_iterations = sim.clock; + sim.assign_colors_from_image(img); + sim.circles.clear(); + sim.clock = sim.rand_seed; + (sim, total_iterations) + } + #[inline] pub fn add_circle(&mut self, position: Vector2, velocity: Vector2) { self.circles.push(Circle { @@ -220,6 +246,24 @@ impl Simulation { }); } + #[inline] + pub async fn step_async(&mut self) { + if self.circles.len() < self.max_circles { + self.launch(); + } + if self.circles.len() < self.max_circles { + self.launch2(); + } + + (0..self.substeps).for_each(|_| { + self.constrain_rect(); + self.sort(); + self.collide(); + self.integrate(); + self.clock += 1; + }); + } + // #[inline] // pub fn draw(&self, d: &mut RaylibDrawHandle) { // self