diff --git a/crates/pipeline/src/crystal.rs b/crates/pipeline/src/crystal.rs index e3caa6ae2c..586aed4d98 100644 --- a/crates/pipeline/src/crystal.rs +++ b/crates/pipeline/src/crystal.rs @@ -29,7 +29,7 @@ //! GPU kernel (`finish.wgsl`, which reads the same tables). use std::f64::consts::TAU; -use std::sync::{Arc, Condvar, Mutex, PoisonError}; +use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError}; use lightcraft_color::transfer::srgb_to_linear; use lightcraft_develop::Grain; @@ -822,17 +822,40 @@ static TILES: Cache = Mutex::new(Vec::new()); /// The tile being drawn in the background for a drag ([`tile`]): one at a time. static DRAWING: Mutex> = Mutex::new(None); +/// The tile a drawing hands to the renders waiting for it, set when it is drawn. +type Slot = Arc>>; + /// The tiles being drawn, by cache and key, and the condition their drawers signal when done: a -/// render that misses a tile another is drawing waits for it rather than drawing it again. -static IN_FLIGHT: Mutex> = Mutex::new(Vec::new()); +/// render that misses a tile another is drawing waits for it rather than drawing it again. The +/// drawer hands the tile over in its slot, so the waiters get it even if the cache has evicted it +/// by the time they wake. +static IN_FLIGHT: Mutex> = Mutex::new(Vec::new()); static DRAWN: Condvar = Condvar::new(); /// Marks a tile drawn (or failed) when dropped and wakes the renders waiting for it. -struct Drawing((usize, Key)); +struct Drawing { + id: (usize, Key), + done: Slot, +} + +impl Drawing { + /// Registers the draw of `id` in `busy` (the locked [`IN_FLIGHT`]). + fn register(busy: &mut Vec<((usize, Key), Slot)>, id: (usize, Key)) -> Drawing { + let done = Slot::default(); + busy.push((id, done.clone())); + Drawing { id, done } + } + + /// Hands `t` to the renders waiting for it (they wake when this is dropped). + fn finish(&self, t: &Arc) { + // (already set: only the first tile counts, and every drawing draws the same one) + let _ = self.done.set(t.clone()); + } +} impl Drop for Drawing { fn drop(&mut self) { - IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner).retain(|d| *d != self.0); + IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner).retain(|(d, _)| *d != self.id); DRAWN.notify_all(); } } @@ -840,11 +863,10 @@ impl Drop for Drawing { /// Registers the tile of `id` as being drawn, or `None` if another thread is drawing it. fn start_drawing(id: (usize, Key)) -> Option { let mut busy = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner); - if busy.contains(&id) { + if busy.iter().any(|(d, _)| *d == id) { return None; } - busy.push(id); - Some(Drawing(id)) + Some(Drawing::register(&mut busy, id)) } /// The tile of `key` in `cache`. @@ -883,26 +905,32 @@ fn tile_in(cache: &'static Cache, look: CrystalLook, seed: u32, wait: bool) -> O let id = (std::ptr::from_ref(cache) as usize, key); // a pool worker draws the tile itself: blocked, it could hold up the drawing it waits for // (its stack may carry a part of that drawing's parallel work); wasm has no other threads - let _drawing = if !cfg!(target_arch = "wasm32") && rayon::current_thread_index().is_none() { + let drawing = if !cfg!(target_arch = "wasm32") && rayon::current_thread_index().is_none() { // checked, waited for and registered under one lock: two renders that miss the tile // together can't both find it neither cached nor being drawn (`cached` takes the cache's // lock under this one; nothing takes them the other way round) let mut busy = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner); + let mut waited_for: Option = None; loop { - if let Some(t) = cached(cache, key) { + if let Some(t) = waited_for.as_ref().and_then(|done| done.get().cloned()).or_else(|| cached(cache, key)) { return Some(t); } - if !busy.contains(&id) { - break; - } + let Some((_, done)) = busy.iter().find(|(d, _)| *d == id) else { break }; + waited_for = Some(done.clone()); busy = DRAWN.wait(busy).unwrap_or_else(PoisonError::into_inner); } - busy.push(id); - Some(Drawing(id)) + Some(Drawing::register(&mut busy, id)) } else { start_drawing(id) }; + #[cfg(test)] + if let Some(d) = &drawing { + tests::hold_for_waiters(d); + } let t = Arc::new(CrystalTile::new(look, seed)?); + if let Some(d) = &drawing { + d.finish(&t); + } keep(cache, key, t.clone()); Some(t) } @@ -932,7 +960,9 @@ fn draw_in_background(cache: &'static Cache, key: Key, look: CrystalLook, seed: }; spawn_in_background(move || { if let Some(t) = CrystalTile::new(look, seed) { - keep(cache, key, Arc::new(t)); + let t = Arc::new(t); + marker.finish(&t); + keep(cache, key, t); } drop(marker); *DRAWING.lock().unwrap_or_else(PoisonError::into_inner) = None; @@ -950,7 +980,7 @@ fn spawn_in_background(draw: impl FnOnce() + Send + 'static) { /// Half the cores, for tiles drawn in the background (`None`: the pool couldn't be made). fn background_pool() -> Option<&'static rayon::ThreadPool> { - static POOL: std::sync::OnceLock> = std::sync::OnceLock::new(); + static POOL: OnceLock> = OnceLock::new(); POOL.get_or_init(|| { let n = std::thread::available_parallelism().map_or(2, |n| n.get()).div_ceil(2); rayon::ThreadPoolBuilder::new().num_threads(n).thread_name(|i| format!("grain-tile-{i}")).build().ok() diff --git a/crates/pipeline/src/tests_crystal.rs b/crates/pipeline/src/tests_crystal.rs index 6f2f5c27fe..b0b44c1596 100644 --- a/crates/pipeline/src/tests_crystal.rs +++ b/crates/pipeline/src/tests_crystal.rs @@ -1,5 +1,29 @@ use super::*; +/// The draws [`hold_for_waiters`] holds, by cache, and how many renders wait for each. +static HOLDS: Mutex> = Mutex::new(Vec::new()); + +/// Holds the draw of `d` until the renders [`HOLDS`] names for its cache are waiting for it (each +/// holds a clone of its slot, as do the drawing and its in-flight entry), so a test can make +/// renders miss a tile together. +pub(super) fn hold_for_waiters(d: &Drawing) { + let held = HOLDS.lock().unwrap_or_else(PoisonError::into_inner).iter().find(|(c, _)| *c == d.id.0).map(|h| h.1); + let Some(waiters) = held else { return }; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + while Arc::strong_count(&d.done) < 2 + waiters && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + +/// Waits until `n` renders wait for the draw of `d`. +fn until_waiting(d: &Drawing, n: usize) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + while Arc::strong_count(&d.done) < 2 + n { + assert!(std::time::Instant::now() < deadline, "the renders never waited"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + /// The field rendered at `long` px per long edge on an `n × n` patch starting at pixel `origin`. fn patch(tile: &CrystalTile, long: f64, n: usize, origin: usize) -> Vec { let w = (TILE_PER_LONG / long) as f32; @@ -193,7 +217,7 @@ fn a_render_waits_for_a_tile_being_drawn() { let key = key_of(look, seed); let marker = start_drawing((std::ptr::from_ref(&OWN) as usize, key)).expect("not drawn yet"); let render = std::thread::spawn(move || tile_in(&OWN, look, seed, true)); - std::thread::sleep(std::time::Duration::from_millis(200)); + until_waiting(&marker, 1); let drawn = Arc::new(CrystalTile::new(look, seed).expect("tile")); keep(&OWN, key, drawn.clone()); drop(marker); @@ -201,12 +225,38 @@ fn a_render_waits_for_a_tile_being_drawn() { assert!(Arc::ptr_eq(&got, &drawn), "the render drew the tile again"); } +/// A render waiting for a tile gets it from its drawer even when the cache evicted it before the +/// render woke. +#[test] +fn a_waiting_render_gets_the_tile_the_cache_evicted() { + static OWN: Cache = Mutex::new(Vec::new()); + let (look, seed) = (CrystalLook::new(40.0, 50.0), 0x0d4a_0004); + let key = key_of(look, seed); + let marker = start_drawing((std::ptr::from_ref(&OWN) as usize, key)).expect("not drawn yet"); + let render = std::thread::spawn(move || tile_in(&OWN, look, seed, true)); + until_waiting(&marker, 1); + let drawn = Arc::new(CrystalTile::new(look, seed).expect("tile")); + marker.finish(&drawn); + keep(&OWN, key, drawn.clone()); + // other renders' tiles push it out of the cache before the waiter wakes + for other in 1..=CACHE as u32 { + keep(&OWN, key_of(look, seed + other), drawn.clone()); + } + assert!(cached(&OWN, key).is_none(), "the tile is still cached"); + drop(marker); + let got = render.join().expect("render thread").expect("tile"); + assert!(Arc::ptr_eq(&got, &drawn), "the render drew the tile again"); +} + /// Renders that miss the same tile together draw it once: the first registers the draw and the /// others wait for it, as no gap lets a second render find it neither cached nor being drawn. +/// The first draw is held until the other renders all wait for it, so the misses overlap. #[test] fn renders_that_miss_a_tile_together_draw_it_once() { static OWN: Cache = Mutex::new(Vec::new()); const N: usize = 8; + // the first render's draw waits for the other seven to miss the tile too + HOLDS.lock().unwrap_or_else(PoisonError::into_inner).push((std::ptr::from_ref(&OWN) as usize, N - 1)); let look = CrystalLook::new(0.0, 50.0); for seed in 0x0d4a_1000..0x0d4a_1000 + 40 { let start = Arc::new(std::sync::Barrier::new(N));