From 6f585a31cdb0ec809f28c649bccaa2f66164214a Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 13:54:37 -0300 Subject: [PATCH 1/7] perf(map): a generalised relief's shadows and sky share one smoothed grid, and its plan counts their traces (#3145) - A light grid's work keeps a weak handle on its smoothed heights: a grid of the same pixels, band, mask and size started meanwhile reads the same ones, so the shadows and the sky asked for together smooth the grid once. - A grid that failed for a plan of other traces (the sky turned on or off since) is tried again. - The memory plan (traced_bytes) adds each trace's own copy of the heights and its grid, 5 bytes a cell, beside the smoothing. Follow-up to #3145. Co-Authored-By: Claude Opus 5.5 --- crates/map/src/generalize.rs | 86 +++++++++++++++++++----- crates/map/src/raster.rs | 122 ++++++++++++++++++++++++++++++----- 2 files changed, 176 insertions(+), 32 deletions(-) diff --git a/crates/map/src/generalize.rs b/crates/map/src/generalize.rs index 89fc56ac0a..551e9c6cc9 100644 --- a/crates/map/src/generalize.rs +++ b/crates/map/src/generalize.rs @@ -88,15 +88,60 @@ const SMOOTHED_FLOOR: usize = 768 << 20; /// renderer does, and reads between the blocks' centres. The grid's edges stop the filter, a /// whole turn's too. It holds what [`smoothing_bytes`] counts (about 3 times a `Float32` layer's /// band for a grid many cells across both ways, up to about 9 times for one a row or a column -/// wide, whose filter lines are as long as itself), then the band, `together` times when that many -/// smoothings run at once (a relief's cast shadows and its sky): past what -/// [`rustgis_data::memory::planned`] gives, it is refused ([`Unlit::TooLarge`]). It looks at `stop` -/// before it holds anything and at each row and column ([`Unlit::Stopped`]). -pub fn smoothed(r: &Raster, band: usize, mask: &RasterMask, metres: f64, stop: &AtomicBool, together: usize) -> Result { +/// wide, whose filter lines are as long as itself), then the band while `traces` traces read it, +/// each with its own copy of the heights and its grid: past what [`traced_bytes`] counts for that +/// against [`rustgis_data::memory::planned`], it is refused ([`Unlit::TooLarge`]). It looks at +/// `stop` before it holds anything and at each row and column ([`Unlit::Stopped`]). +pub fn smoothed(r: &Raster, band: usize, mask: &RasterMask, metres: f64, stop: &AtomicBool, traces: usize) -> Result { let limit = rustgis_data::memory::planned(SMOOTHED_FLOOR, usize::MAX, 1); - smoothed_within(r, band, mask, metres, stop, limit, together) + #[cfg(test)] + let limit = tests_hooks::limit(&r.name).unwrap_or(limit); + #[cfg(test)] + tests_hooks::ran(&r.name); + smoothed_within(r, band, mask, metres, stop, limit, traces) } +/// The bytes a generalised relief's light grids hold for `r` over `metres` with `traces` traces +/// reading its smoothed heights: the smoothing's ([`smoothing_bytes`]), and each trace's own copy +/// of the heights (4 bytes a cell) and its grid (1). +pub fn traced_bytes(r: &Raster, metres: f64, traces: usize) -> usize { + let cells = r.width as usize * r.height as usize; + smoothing_bytes(r, metres).saturating_add(traces.max(1).saturating_mul(5).saturating_mul(cells)) +} + +/// Test hooks, by the raster's name so tests running at once don't meet: a limit in place of the +/// memory planned, and how many times a raster was smoothed. +#[cfg(test)] +mod tests_hooks { + use std::sync::Mutex; + + static LIMITS: Mutex> = Mutex::new(Vec::new()); + static RUNS: Mutex> = Mutex::new(Vec::new()); + + pub(super) fn limit(name: &str) -> Option { + LIMITS.lock().ok()?.iter().find(|(n, _)| n == name).map(|(_, l)| *l) + } + + pub(super) fn ran(name: &str) { + if let Ok(mut runs) = RUNS.lock() { + runs.push(name.into()); + } + } + + pub(crate) fn limit_for(name: &str, bytes: usize) { + if let Ok(mut limits) = LIMITS.lock() { + limits.push((name.into(), bytes)); + } + } + + pub(crate) fn smoothings_of(name: &str) -> usize { + RUNS.lock().map_or(0, |runs| runs.iter().filter(|n| *n == name).count()) + } +} + +#[cfg(test)] +pub(crate) use tests_hooks::{limit_for, smoothings_of}; + /// The blocks, rows and cells to a block's side of `r` smoothed over `metres`. fn blocks_of(r: &Raster, metres: f64) -> (i64, i64, i64) { let (w, h) = (i64::from(r.width), i64::from(r.height)); @@ -163,7 +208,7 @@ fn block_sums( Ok(()) } -/// [`smoothed`] within `limit` bytes for `together` smoothings at once. +/// [`smoothed`] within `limit` bytes for `traces` traces reading it. fn smoothed_within( r: &Raster, band: usize, @@ -171,12 +216,12 @@ fn smoothed_within( metres: f64, stop: &AtomicBool, limit: usize, - together: usize, + traces: usize, ) -> Result { let stopped = || stop.load(Ordering::Relaxed); let (w, h) = (i64::from(r.width), i64::from(r.height)); let cells = usize::try_from(w * h).map_err(|_| Unlit::NoMemory)?; - let bytes = smoothing_bytes(r, metres).saturating_mul(together.max(1)); + let bytes = traced_bytes(r, metres, traces); if bytes > limit { return Err(Unlit::TooLarge { bytes, limit }); } @@ -302,24 +347,35 @@ mod tests { assert_eq!(counts[0], (side * side) as f32); } + /// The traces' phase is planned for too: each trace's own copy of the heights and its grid, + /// 5 bytes a cell, beside the smoothing (#3448 review). + #[test] + fn the_plan_counts_each_trace_beside_the_smoothing() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 100.0 * 30.0, pixel_width: 30.0, pixel_height: -30.0 }; + let r = Raster::new("even", 100, 100, vec![vec![250.0; 10_000]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + let smoothing = smoothing_bytes(&r, 90.0); + assert_eq!(traced_bytes(&r, 90.0, 1), smoothing + 5 * 10_000); + assert_eq!(traced_bytes(&r, 90.0, 2), smoothing + 10 * 10_000); + } + /// A grid whose smoothing would hold more than the memory planned for it is refused, saying /// how much it needs and how much is planned, rather than run out of memory partway /// (AGENTS.md). All it holds is counted: the blocks, the band, and the filter's three lines, - /// which a grid one row tall makes as long as itself; and as many times as smoothings run - /// together, a relief's cast shadows and its sky each smoothing its grid (#3448 review). + /// which a grid one row tall makes as long as itself; and each trace that reads it, a + /// relief's cast shadows and its sky (#3448 review). #[test] fn a_grid_past_the_memory_planned_is_refused() { let even = |w: u32, h: u32| { let gt = GeoTransform { origin_x: 0.0, origin_y: f64::from(h) * 30.0, pixel_width: 30.0, pixel_height: -30.0 }; Raster::new("even", w, h, vec![vec![250.0; (w * h) as usize]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap() }; - let at = - |r: &Raster, limit, together| smoothed_within(r, 0, &RasterMask::default(), 90.0, &AtomicBool::new(false), limit, together); + let at = |r: &Raster, limit, traces| smoothed_within(r, 0, &RasterMask::default(), 90.0, &AtomicBool::new(false), limit, traces); let square = even(100, 100); - let need = smoothing_bytes(&square, 90.0); + let need = traced_bytes(&square, 90.0, 1); assert_eq!(at(&square, need - 1, 1).err(), Some(Unlit::TooLarge { bytes: need, limit: need - 1 })); assert!(at(&square, need, 1).is_ok()); - assert_eq!(at(&square, need, 2).err(), Some(Unlit::TooLarge { bytes: 2 * need, limit: need })); + let two = traced_bytes(&square, 90.0, 2); + assert_eq!(at(&square, need, 2).err(), Some(Unlit::TooLarge { bytes: two, limit: need })); // A row 4000 cells long: its lines are 24 bytes a cell, past the 12 a cell of the rest. let row = even(4000, 1); assert!(smoothing_bytes(&row, 90.0) >= 36 * 4000, "{}", smoothing_bytes(&row, 90.0)); diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index cfbfa0ad80..1a323df75d 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1059,6 +1059,12 @@ impl RasterLayer { _ => 0.0, }; let key = LightKey { band, grid, z_factor, mask: self.style.mask.clone(), generalize }; + // A generalised relief's shadows and sky, both asked for, each trace its smoothed heights, + // at once: their memory is planned for both. + let together = match self.style.renderer { + RasterRenderer::ShadedRelief { shadow, sky, .. } if shadow > 0.0 && sky > 0.0 => 2, + _ => 1, + }; let mut start = None; let work = { let Ok(mut jobs) = self.cast.0.lock() else { return CastShadows::None }; @@ -1067,6 +1073,9 @@ impl RasterLayer { jobs.retain(|j| j.pixels.strong_count() > 0 && !j.work.was_stopped(j.key.grid.stopped())); let pixels = Arc::downgrade(r); let same = |j: &LightJob| j.key == key && Weak::ptr_eq(&j.pixels, &pixels); + // A grid that failed for a plan of other traces (the sky turned on or off since) is + // tried again; one that landed is kept. + jobs.retain(|j| !(same(j) && j.planned_for != together && j.work.failed(j.key.grid.stopped()))); // The same owner's work for another sun, not done and not waited for, is superseded // (going back to a sun kept too): it stops, as it is dropped. Grids done are kept, for // going back. Its other kind of grid (its sky, or its shadows) is left alone. @@ -1103,21 +1112,33 @@ impl RasterLayer { } let work = Arc::new(LightWork::default()); work.on_landing(landed); - jobs.push(LightJob { key: key.clone(), pixels: Arc::downgrade(r), owner, work: work.clone() }); - start = Some((r.clone(), key)); + // The smoothed heights of a grid of the same pixels, band, mask and size worked + // out or read now, or new ones. + let shares = |j: &LightJob| { + Weak::ptr_eq(&j.pixels, &pixels) + && j.key.band == key.band + && j.key.mask == key.mask + && j.key.generalize == key.generalize + }; + let smoothing = (key.generalize > 0.0) + .then(|| jobs.iter().filter(|j| shares(j)).find_map(|j| j.smoothing.upgrade()).unwrap_or_default()); + let job = LightJob { + key: key.clone(), + pixels: Arc::downgrade(r), + smoothing: smoothing.as_ref().map_or_else(Weak::new, Arc::downgrade), + planned_for: together, + owner, + work: work.clone(), + }; + jobs.push(job); + start = Some((r.clone(), key, smoothing)); work } } }; // Started without holding the lock: a thread the system refuses runs it here. - if let Some((r, key)) = start { - // A generalised relief's shadows and sky each smooth its grid, at once when both are - // asked for: each plans for both. - let together = match self.style.renderer { - RasterRenderer::ShadedRelief { shadow, sky, .. } if shadow > 0.0 && sky > 0.0 => 2, - _ => 1, - }; - start_light(r, key, work.clone(), together); + if let Some((r, key, smoothing)) = start { + start_light(r, key, work.clone(), together, smoothing); } work.result(wait) } @@ -1187,6 +1208,9 @@ struct LightWork { landings: Mutex>>, } +/// A generalised relief's smoothed heights, worked out once for the light grids that read them. +type SharedSmoothing = std::sync::OnceLock, crate::shadow::Unlit>>; + /// The most landing calls a light grid's work keeps. const MAX_LANDINGS: usize = 32; @@ -1222,6 +1246,11 @@ impl LightWork { self.waiting.load(std::sync::atomic::Ordering::SeqCst) > 0 } + /// Whether it is done with no grid, other than stopped (`stopped`, see [`Grid::stopped`]). + fn failed(&self, stopped: &str) -> bool { + self.done.lock().is_ok_and(|d| matches!(d.as_ref(), Some(Err(e)) if e != stopped)) + } + fn finish(&self, out: Result>, String>) { if let Ok(mut done) = self.done.lock() { *done = Some(out); @@ -1273,6 +1302,11 @@ struct LightJob { key: LightKey, /// Held weakly, so their address isn't reused. pixels: Weak, + /// A generalised relief's smoothed heights its trace reads, while it is worked out or read: a + /// grid of the same pixels, band, mask and size started meanwhile reads them too (#3145). + smoothing: Weak, + /// How many traces its memory was planned for (see [`crate::generalize::traced_bytes`]). + planned_for: usize, /// Who drew it last (see [`RasterLayer::cast_shadows`]). owner: (u64, u64), work: Arc, @@ -1312,20 +1346,26 @@ pub fn hold_cast_shadows() -> std::sync::RwLockWriteGuard<'static, ()> { /// Works out a light grid: natively on a thread of its own (here if the system refuses one), /// in the browser here. -fn start_light(r: Arc, key: LightKey, work: Arc, together: usize) { +fn start_light(r: Arc, key: LightKey, work: Arc, together: usize, smoothing: Option>) { let run = move || { drop(LIGHT_HOLD.read().unwrap_or_else(|e| e.into_inner())); let threads = rustgis_data::threads::max(); let traced = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - // A generalised relief's are traced over its smoothed heights, one band with no mask. - let smoothed = if key.generalize > 0.0 { - Some(crate::generalize::smoothed(&r, key.band, &key.mask, key.generalize, &work.stop, together)?) - } else { - None + // A generalised relief's are traced over its smoothed heights, one band with no mask, + // worked out by the first of its grids to ask (stopped with it: the others then start + // again). + let smoothed = match &smoothing { + Some(cell) => Some( + cell.get_or_init(|| { + crate::generalize::smoothed(&r, key.band, &key.mask, key.generalize, &work.stop, together).map(Arc::new) + }) + .clone()?, + ), + None => None, }; let unmasked = RasterMask::default(); let (heights, band, mask) = match &smoothed { - Some(smoothed) => (smoothed, 0, &unmasked), + Some(smoothed) => (smoothed.as_ref(), 0, &unmasked), None => (r.as_ref(), key.band, &key.mask), }; match key.grid { @@ -4011,6 +4051,54 @@ mod tests { assert_ne!(*shadow, traced(&raw).0, "the tower's shadow is softened"); } + /// A generalised relief (#3145) with both cast shadows and sky asked for at once smooths its + /// grid once, for both traces, and both grids land. + #[test] + fn a_reliefs_shadows_and_sky_share_one_smoothed_grid() { + let mut rl = tower(1.0); + let name = "shares its smoothing"; + rl.data = rl.data.as_deref().cloned().map(|mut r| { + r.name = name.into(); + Arc::new(r) + }); + if let RasterRenderer::ShadedRelief { generalize, sky, .. } = &mut rl.style.renderer { + (*generalize, *sky) = (90.0, 1.0); + } + { + // Both asked while neither has started tracing. + let _hold = hold_cast_shadows(); + assert_eq!(rl.cast_shadows(false, (0, 1), || {}), CastShadows::Pending); + assert_eq!(rl.sky_view(false, (0, 1), || {}), CastShadows::Pending); + } + assert!(matches!(rl.cast_shadows(true, (0, 1), || {}), CastShadows::Ready(_))); + assert!(matches!(rl.sky_view(true, (0, 1), || {}), CastShadows::Ready(_))); + assert_eq!(crate::generalize::smoothings_of(name), 1); + } + + /// A relief's grid refused for the memory its shadows and sky would hold together is worked out + /// again once the sky is off and the shadows alone fit (#3448 review). + #[test] + fn a_grid_refused_for_two_traces_is_tried_again_for_one() { + let mut rl = tower(1.0); + let name = "refused for two"; + rl.data = rl.data.as_deref().cloned().map(|mut r| { + r.name = name.into(); + Arc::new(r) + }); + let set = |rl: &mut RasterLayer, sky_on: f64| { + if let RasterRenderer::ShadedRelief { generalize, sky, .. } = &mut rl.style.renderer { + (*generalize, *sky) = (90.0, sky_on); + } + }; + set(&mut rl, 1.0); + let r = rl.data.clone().unwrap(); + // Room for the smoothing and one trace, not two. + crate::generalize::limit_for(name, crate::generalize::traced_bytes(&r, 90.0, 1)); + assert!(matches!(rl.cast_shadows(true, (0, 1), || {}), CastShadows::Unavailable(e) if e.contains("clip"))); + set(&mut rl, 0.0); + assert!(matches!(rl.cast_shadows(true, (0, 1), || {}), CastShadows::Ready(_)), "the sky off, the shadows fit"); + } + /// A tower lit from the east, drawn as Shaded Relief with `shadow`. fn tower(shadow: f64) -> RasterLayer { let gt = GeoTransform { origin_x: 0.0, origin_y: 0.0, pixel_width: 30.0, pixel_height: -30.0 }; From 37acf564b2e6d955f616cd20a362296ee9b3c44d Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 18:55:00 -0300 Subject: [PATCH 2/7] fix(map): a shared smoothing keeps only heights, and is shared only within its plan (#3145) From review: - The shared cell kept the first smoothing's result, so a Stopped (its grid superseded, or its export cancelled) or a TooLarge for its plan was given to a grid that joined it. It now keeps only heights: a smoothing that fails keeps nothing, and the next grid smooths under its own stop and plan. - A grid shares a smoothing only when it was planned for as many traces or more, so its own trace is inside the plan checked. Follow-up to #3145. Co-Authored-By: Claude Opus 5.5 --- crates/map/src/raster.rs | 81 ++++++++++++++++++++++++++++++++++------ 1 file changed, 70 insertions(+), 11 deletions(-) diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index 1a323df75d..3c233a534e 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1113,12 +1113,13 @@ impl RasterLayer { let work = Arc::new(LightWork::default()); work.on_landing(landed); // The smoothed heights of a grid of the same pixels, band, mask and size worked - // out or read now, or new ones. + // out or read now, planned for as many traces or more, or new ones. let shares = |j: &LightJob| { Weak::ptr_eq(&j.pixels, &pixels) && j.key.band == key.band && j.key.mask == key.mask && j.key.generalize == key.generalize + && j.planned_for >= together }; let smoothing = (key.generalize > 0.0) .then(|| jobs.iter().filter(|j| shares(j)).find_map(|j| j.smoothing.upgrade()).unwrap_or_default()); @@ -1208,8 +1209,25 @@ struct LightWork { landings: Mutex>>, } -/// A generalised relief's smoothed heights, worked out once for the light grids that read them. -type SharedSmoothing = std::sync::OnceLock, crate::shadow::Unlit>>; +/// A generalised relief's smoothed heights, worked out once for the light grids that read them: +/// held while they are worked out, so a grid that reads them meanwhile waits for them. +type SharedSmoothing = Mutex>>; + +/// The smoothed heights `cell` holds, or those `smooth` works out, then kept there. Only heights are +/// kept: a smoothing stopped with the grid that started it, or refused for that grid's plan, is +/// worked out again by the next grid that reads `cell`, under its own stop and plan. +fn shared_smoothed( + cell: &SharedSmoothing, + smooth: impl FnOnce() -> Result, +) -> Result, crate::shadow::Unlit> { + let mut kept = cell.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(heights) = kept.as_ref() { + return Ok(heights.clone()); + } + let heights = Arc::new(smooth()?); + *kept = Some(heights.clone()); + Ok(heights) +} /// The most landing calls a light grid's work keeps. const MAX_LANDINGS: usize = 32; @@ -1352,15 +1370,12 @@ fn start_light(r: Arc, key: LightKey, work: Arc, together: us let threads = rustgis_data::threads::max(); let traced = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { // A generalised relief's are traced over its smoothed heights, one band with no mask, - // worked out by the first of its grids to ask (stopped with it: the others then start - // again). + // worked out by the first of its grids to ask, or by the next if that one is stopped or + // refused for its plan. let smoothed = match &smoothing { - Some(cell) => Some( - cell.get_or_init(|| { - crate::generalize::smoothed(&r, key.band, &key.mask, key.generalize, &work.stop, together).map(Arc::new) - }) - .clone()?, - ), + Some(cell) => Some(shared_smoothed(cell, || { + crate::generalize::smoothed(&r, key.band, &key.mask, key.generalize, &work.stop, together) + })?), None => None, }; let unmasked = RasterMask::default(); @@ -4075,6 +4090,50 @@ mod tests { assert_eq!(crate::generalize::smoothings_of(name), 1); } + /// A shared smoothing keeps only heights: one stopped with the grid that started it, or refused + /// for that grid's plan, is worked out again by the next grid that reads it, under its own stop + /// and plan; heights worked out are read by the next with no smoothing (#3466 review). + #[test] + fn a_shared_smoothing_keeps_only_heights() { + use crate::shadow::Unlit; + let heights = tower(0.0).data.as_deref().cloned().unwrap(); + for failed in [Unlit::Stopped, Unlit::TooLarge { bytes: 2, limit: 1 }] { + let cell = SharedSmoothing::default(); + assert_eq!(shared_smoothed(&cell, || Err(failed.clone())).err(), Some(failed.clone())); + let worked = shared_smoothed(&cell, || Ok(heights.clone())); + assert!(worked.is_ok(), "{failed:?}: smoothed again, under the next grid's stop and plan"); + let kept = shared_smoothed(&cell, || panic!("{failed:?}: kept heights are read, not smoothed again")); + assert!(kept.is_ok_and(|k| worked.is_ok_and(|w| Arc::ptr_eq(&k, &w)))); + } + } + + /// A grid planned for more traces than another's smoothing was (the sky turned on while the + /// shadows' smoothing runs) smooths under its own plan rather than read it (#3466 review). + #[test] + fn a_grid_planned_for_more_traces_smooths_on_its_own() { + let mut rl = tower(1.0); + let name = "planned for more"; + rl.data = rl.data.as_deref().cloned().map(|mut r| { + r.name = name.into(); + Arc::new(r) + }); + let set = |rl: &mut RasterLayer, sky_on: f64| { + if let RasterRenderer::ShadedRelief { generalize, sky, .. } = &mut rl.style.renderer { + (*generalize, *sky) = (90.0, sky_on); + } + }; + { + let _hold = hold_cast_shadows(); + set(&mut rl, 0.0); + assert_eq!(rl.cast_shadows(false, (0, 1), || {}), CastShadows::Pending); + set(&mut rl, 1.0); + assert_eq!(rl.sky_view(false, (0, 1), || {}), CastShadows::Pending); + } + assert!(matches!(rl.sky_view(true, (0, 1), || {}), CastShadows::Ready(_))); + assert!(matches!(rl.cast_shadows(true, (0, 1), || {}), CastShadows::Ready(_))); + assert_eq!(crate::generalize::smoothings_of(name), 2); + } + /// A relief's grid refused for the memory its shadows and sky would hold together is worked out /// again once the sky is off and the shadows alone fit (#3448 review). #[test] From 09b835e7b3d413f8dd7c060944b2b2278b94ea89 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 19:58:57 -0300 Subject: [PATCH 3/7] fix(map): a grid reading another's smoothing plans its own trace, and waits for it without blocking (#3145) From review: - A grid that reads another grid's smoothed heights now checks its own trace (its copy of the heights and its grid) against memory::planned before it traces (generalize::traces_fit). - A grid waiting for another's smoothing tries the lock and looks at its own stop and its run's Cancel meanwhile, rather than block until the other is done. Follow-up to #3145. Co-Authored-By: Claude Opus 5.5 --- crates/map/src/generalize.rs | 24 +++++++++++ crates/map/src/raster.rs | 79 +++++++++++++++++++++++++++++------- 2 files changed, 88 insertions(+), 15 deletions(-) diff --git a/crates/map/src/generalize.rs b/crates/map/src/generalize.rs index 551e9c6cc9..1275b4ad92 100644 --- a/crates/map/src/generalize.rs +++ b/crates/map/src/generalize.rs @@ -109,6 +109,16 @@ pub fn traced_bytes(r: &Raster, metres: f64, traces: usize) -> usize { smoothing_bytes(r, metres).saturating_add(traces.max(1).saturating_mul(5).saturating_mul(cells)) } +/// Whether `traces` more traces of `r` fit the memory planned, beside smoothed heights already held +/// (a grid that reads another's smoothing): each trace's own copy of the heights and its grid. +pub fn traces_fit(r: &Raster, traces: usize) -> Result<(), Unlit> { + let limit = rustgis_data::memory::planned(SMOOTHED_FLOOR, usize::MAX, 1); + #[cfg(test)] + let limit = tests_hooks::limit(&r.name).unwrap_or(limit); + let bytes = traces.saturating_mul(5).saturating_mul(r.width as usize * r.height as usize); + if bytes > limit { Err(Unlit::TooLarge { bytes, limit }) } else { Ok(()) } +} + /// Test hooks, by the raster's name so tests running at once don't meet: a limit in place of the /// memory planned, and how many times a raster was smoothed. #[cfg(test)] @@ -358,6 +368,20 @@ mod tests { assert_eq!(traced_bytes(&r, 90.0, 2), smoothing + 10 * 10_000); } + /// A grid that reads another's smoothed heights plans for its own trace: refused when the + /// trace's copy and grid don't fit (#3466 review). + #[test] + fn a_grid_reading_shared_heights_plans_its_own_trace() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 100.0 * 30.0, pixel_width: 30.0, pixel_height: -30.0 }; + let r = Raster::new("joins", 100, 100, vec![vec![250.0; 10_000]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + limit_for("joins", 5 * 10_000 - 1); + assert_eq!(traces_fit(&r, 1).err(), Some(Unlit::TooLarge { bytes: 5 * 10_000, limit: 5 * 10_000 - 1 })); + let ok = + Raster::new("joins fits", 100, 100, vec![vec![250.0; 10_000]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + limit_for("joins fits", 5 * 10_000); + assert!(traces_fit(&ok, 1).is_ok()); + } + /// A grid whose smoothing would hold more than the memory planned for it is refused, saying /// how much it needs and how much is planned, rather than run out of memory partway /// (AGENTS.md). All it holds is counted: the blocks, the band, and the filter's three lines, diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index 3c233a534e..cdb4a5de2f 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1213,20 +1213,36 @@ struct LightWork { /// held while they are worked out, so a grid that reads them meanwhile waits for them. type SharedSmoothing = Mutex>>; -/// The smoothed heights `cell` holds, or those `smooth` works out, then kept there. Only heights are -/// kept: a smoothing stopped with the grid that started it, or refused for that grid's plan, is -/// worked out again by the next grid that reads `cell`, under its own stop and plan. +/// The smoothed heights `cell` holds, and whether they were another grid's, or those `smooth` works +/// out, then kept there. Only heights are kept: a smoothing stopped with the grid that started it, +/// or refused for that grid's plan, is worked out again by the next grid that reads `cell`, under +/// its own stop and plan. A grid waiting for another's smoothing looks at its own `stop` and its +/// run's Cancel meanwhile. fn shared_smoothed( cell: &SharedSmoothing, + stop: &std::sync::atomic::AtomicBool, smooth: impl FnOnce() -> Result, -) -> Result, crate::shadow::Unlit> { - let mut kept = cell.lock().unwrap_or_else(|e| e.into_inner()); +) -> Result<(Arc, bool), crate::shadow::Unlit> { + // Waited for without blocking: a grid stopped meanwhile (superseded, its export cancelled) + // stops waiting rather than block until the other's smoothing is done. + let mut kept = loop { + match cell.try_lock() { + Ok(kept) => break kept, + Err(std::sync::TryLockError::Poisoned(e)) => break e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => { + if stop.load(std::sync::atomic::Ordering::Relaxed) || rustgis_data::progress::check().is_err() { + return Err(crate::shadow::Unlit::Stopped); + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + } + }; if let Some(heights) = kept.as_ref() { - return Ok(heights.clone()); + return Ok((heights.clone(), true)); } let heights = Arc::new(smooth()?); *kept = Some(heights.clone()); - Ok(heights) + Ok((heights, false)) } /// The most landing calls a light grid's work keeps. @@ -1373,9 +1389,17 @@ fn start_light(r: Arc, key: LightKey, work: Arc, together: us // worked out by the first of its grids to ask, or by the next if that one is stopped or // refused for its plan. let smoothed = match &smoothing { - Some(cell) => Some(shared_smoothed(cell, || { - crate::generalize::smoothed(&r, key.band, &key.mask, key.generalize, &work.stop, together) - })?), + Some(cell) => { + let (heights, read) = shared_smoothed(cell, &work.stop, || { + crate::generalize::smoothed(&r, key.band, &key.mask, key.generalize, &work.stop, together) + })?; + // Another grid's heights: its plan counted its own traces, so this one's trace + // is planned for here. + if read { + crate::generalize::traces_fit(&r, 1)?; + } + Some(heights) + } None => None, }; let unmasked = RasterMask::default(); @@ -4099,12 +4123,37 @@ mod tests { let heights = tower(0.0).data.as_deref().cloned().unwrap(); for failed in [Unlit::Stopped, Unlit::TooLarge { bytes: 2, limit: 1 }] { let cell = SharedSmoothing::default(); - assert_eq!(shared_smoothed(&cell, || Err(failed.clone())).err(), Some(failed.clone())); - let worked = shared_smoothed(&cell, || Ok(heights.clone())); - assert!(worked.is_ok(), "{failed:?}: smoothed again, under the next grid's stop and plan"); - let kept = shared_smoothed(&cell, || panic!("{failed:?}: kept heights are read, not smoothed again")); - assert!(kept.is_ok_and(|k| worked.is_ok_and(|w| Arc::ptr_eq(&k, &w)))); + let go = std::sync::atomic::AtomicBool::new(false); + assert_eq!(shared_smoothed(&cell, &go, || Err(failed.clone())).err(), Some(failed.clone())); + let worked = shared_smoothed(&cell, &go, || Ok(heights.clone())); + assert!(worked.as_ref().is_ok_and(|(_, joined)| !joined), "{failed:?}: smoothed again, under the next grid's stop and plan"); + let kept = shared_smoothed(&cell, &go, || panic!("{failed:?}: kept heights are read, not smoothed again")); + assert!(kept.is_ok_and(|(k, joined)| joined && worked.is_ok_and(|(w, _)| Arc::ptr_eq(&k, &w)))); + } + } + + /// A grid that waits for another's smoothing stops waiting when it is stopped itself, rather + /// than block until that one is done (#3466 review). + #[test] + fn a_grid_waiting_for_a_shared_smoothing_stops_with_its_own_stop() { + use std::sync::atomic::{AtomicBool, Ordering}; + let cell = Arc::new(SharedSmoothing::default()); + let smoothing = cell.lock().unwrap_or_else(|e| e.into_inner()); + let stop = Arc::new(AtomicBool::new(false)); + let (sent, got) = std::sync::mpsc::channel(); + { + let (cell, stop) = (cell.clone(), stop.clone()); + std::thread::Builder::new() + .spawn(move || { + let _ = sent.send(shared_smoothed(&cell, &stop, || Err(crate::shadow::Unlit::Failed)).err()); + }) + .expect("a thread for the waiting grid"); } + std::thread::sleep(std::time::Duration::from_millis(50)); + stop.store(true, Ordering::Relaxed); + let waited = got.recv_timeout(std::time::Duration::from_secs(5)); + drop(smoothing); + assert_eq!(waited, Ok(Some(crate::shadow::Unlit::Stopped))); } /// A grid planned for more traces than another's smoothing was (the sky turned on while the From 6cb0ad9f9be29e0a00ee680e9f597fccd4335a83 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 20:39:10 -0300 Subject: [PATCH 4/7] fix(map): a trace refused over shared heights says it is the trace, and the wait looks at its own stop only (#3145) From review: - A trace refused for memory over another grid's smoothed heights is its own case (Unlit::TraceTooLarge), said as the trace's need rather than the smoothing's; the messages are made in one place (unlit_said). - The wait for another's smoothing looks only at the grid's own stop: the light work's thread has no Cancel probe. - The wait's test sets the stop before the grid starts, with no sleep (test-hygiene). Follow-up to #3145. Co-Authored-By: Claude Opus 5.5 --- crates/map/src/generalize.rs | 4 +-- crates/map/src/raster.rs | 55 +++++++++++++++++++++++++----------- crates/map/src/shadow.rs | 3 ++ 3 files changed, 43 insertions(+), 19 deletions(-) diff --git a/crates/map/src/generalize.rs b/crates/map/src/generalize.rs index 1275b4ad92..970cbeddc6 100644 --- a/crates/map/src/generalize.rs +++ b/crates/map/src/generalize.rs @@ -116,7 +116,7 @@ pub fn traces_fit(r: &Raster, traces: usize) -> Result<(), Unlit> { #[cfg(test)] let limit = tests_hooks::limit(&r.name).unwrap_or(limit); let bytes = traces.saturating_mul(5).saturating_mul(r.width as usize * r.height as usize); - if bytes > limit { Err(Unlit::TooLarge { bytes, limit }) } else { Ok(()) } + if bytes > limit { Err(Unlit::TraceTooLarge { bytes, limit }) } else { Ok(()) } } /// Test hooks, by the raster's name so tests running at once don't meet: a limit in place of the @@ -375,7 +375,7 @@ mod tests { let gt = GeoTransform { origin_x: 0.0, origin_y: 100.0 * 30.0, pixel_width: 30.0, pixel_height: -30.0 }; let r = Raster::new("joins", 100, 100, vec![vec![250.0; 10_000]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); limit_for("joins", 5 * 10_000 - 1); - assert_eq!(traces_fit(&r, 1).err(), Some(Unlit::TooLarge { bytes: 5 * 10_000, limit: 5 * 10_000 - 1 })); + assert_eq!(traces_fit(&r, 1).err(), Some(Unlit::TraceTooLarge { bytes: 5 * 10_000, limit: 5 * 10_000 - 1 })); let ok = Raster::new("joins fits", 100, 100, vec![vec![250.0; 10_000]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); limit_for("joins fits", 5 * 10_000); diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index cdb4a5de2f..6e2056aae4 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1213,11 +1213,31 @@ struct LightWork { /// held while they are worked out, so a grid that reads them meanwhile waits for them. type SharedSmoothing = Mutex>>; +/// Why a light grid isn't drawn, after `not_drawn` (see [`Grid::not_drawn`]), for the map and exports. +fn unlit_said(not_drawn: &str, e: crate::shadow::Unlit) -> String { + use crate::shadow::Unlit; + let clip = "clip the raster to the area drawn first"; + match e { + Unlit::Failed => format!("{not_drawn}: working it out failed"), + Unlit::TooLarge { bytes, limit } => format!( + "{not_drawn}: smoothing its heights for its generalisation needs {} MiB, more than the {} MiB planned for it: {clip}", + bytes >> 20, + limit >> 20 + ), + Unlit::TraceTooLarge { bytes, limit } => format!( + "{not_drawn}: its trace over the smoothed heights needs {} MiB, more than the {} MiB planned for it: {clip}", + bytes >> 20, + limit >> 20 + ), + Unlit::Stopped | Unlit::NoMemory => format!("{not_drawn}: there isn't the memory for it"), + } +} + /// The smoothed heights `cell` holds, and whether they were another grid's, or those `smooth` works /// out, then kept there. Only heights are kept: a smoothing stopped with the grid that started it, /// or refused for that grid's plan, is worked out again by the next grid that reads `cell`, under -/// its own stop and plan. A grid waiting for another's smoothing looks at its own `stop` and its -/// run's Cancel meanwhile. +/// its own stop and plan. A grid waiting for another's smoothing looks at its own `stop` +/// meanwhile (a cancelled export that waited for it alone sets it). fn shared_smoothed( cell: &SharedSmoothing, stop: &std::sync::atomic::AtomicBool, @@ -1230,7 +1250,7 @@ fn shared_smoothed( Ok(kept) => break kept, Err(std::sync::TryLockError::Poisoned(e)) => break e.into_inner(), Err(std::sync::TryLockError::WouldBlock) => { - if stop.load(std::sync::atomic::Ordering::Relaxed) || rustgis_data::progress::check().is_err() { + if stop.load(std::sync::atomic::Ordering::Relaxed) { return Err(crate::shadow::Unlit::Stopped); } std::thread::sleep(std::time::Duration::from_millis(5)); @@ -1423,16 +1443,7 @@ fn start_light(r: Arc, key: LightKey, work: Arc, together: us work.land(); } Ok(out) => { - work.finish(out.map(Arc::new).map_err(|e| match e { - crate::shadow::Unlit::Failed => format!("{not_drawn}: working it out failed"), - crate::shadow::Unlit::TooLarge { bytes, limit } => format!( - "{not_drawn}: smoothing its heights for its generalisation needs {} MiB, more than the {} MiB planned \ - for it: clip the raster to the area drawn first", - bytes >> 20, - limit >> 20 - ), - _ => format!("{not_drawn}: there isn't the memory for it"), - })); + work.finish(out.map(Arc::new).map_err(|e| unlit_said(not_drawn, e))); work.land(); } // Said, rather than leaving an export waiting. @@ -4136,10 +4147,11 @@ mod tests { /// than block until that one is done (#3466 review). #[test] fn a_grid_waiting_for_a_shared_smoothing_stops_with_its_own_stop() { - use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::atomic::AtomicBool; let cell = Arc::new(SharedSmoothing::default()); let smoothing = cell.lock().unwrap_or_else(|e| e.into_inner()); - let stop = Arc::new(AtomicBool::new(false)); + // Stopped before it starts waiting: it must not wait for the smoothing held here. + let stop = Arc::new(AtomicBool::new(true)); let (sent, got) = std::sync::mpsc::channel(); { let (cell, stop) = (cell.clone(), stop.clone()); @@ -4149,13 +4161,22 @@ mod tests { }) .expect("a thread for the waiting grid"); } - std::thread::sleep(std::time::Duration::from_millis(50)); - stop.store(true, Ordering::Relaxed); let waited = got.recv_timeout(std::time::Duration::from_secs(5)); drop(smoothing); assert_eq!(waited, Ok(Some(crate::shadow::Unlit::Stopped))); } + /// A grid refused for its smoothing's memory and one refused for its own trace's are said by the + /// phase that doesn't fit (#3466 review). + #[test] + fn a_grid_refused_for_memory_says_which_phase() { + use crate::shadow::Unlit; + let smoothing = unlit_said("Cast shadows aren't drawn", Unlit::TooLarge { bytes: 3 << 20, limit: 2 << 20 }); + assert!(smoothing.contains("smoothing its heights") && smoothing.contains("3 MiB"), "{smoothing}"); + let trace = unlit_said("Cast shadows aren't drawn", Unlit::TraceTooLarge { bytes: 3 << 20, limit: 2 << 20 }); + assert!(trace.contains("its trace over the smoothed heights") && !trace.contains("smoothing its"), "{trace}"); + } + /// A grid planned for more traces than another's smoothing was (the sky turned on while the /// shadows' smoothing runs) smooths under its own plan rather than read it (#3466 review). #[test] diff --git a/crates/map/src/shadow.rs b/crates/map/src/shadow.rs index 9d5f3159d1..d0bb193ce5 100644 --- a/crates/map/src/shadow.rs +++ b/crates/map/src/shadow.rs @@ -57,6 +57,9 @@ pub enum Unlit { /// A generalised relief's smoothing would hold `bytes`, past the `limit` it plans for (#3145, /// see [`crate::generalize::smoothed`]). TooLarge { bytes: usize, limit: usize }, + /// A trace over another grid's smoothed heights would hold `bytes` (its copy of the heights and + /// its grid), past the `limit` planned (see [`crate::generalize::traces_fit`]). + TraceTooLarge { bytes: usize, limit: usize }, } /// The light left by cast shadows on each cell of `band` (`0` in shadow to `255` lit), row by row From b27ed13ebd4f3a70746913c4d929f69b7f43e314 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 21:20:33 -0300 Subject: [PATCH 5/7] Plan every trace on shared smoothed heights; saturate cell counts A grid that reads another's smoothed heights now counts the traces that read them in the shared cell and, past the number its first grid planned for, checks traced_bytes for all of them together rather than its own trace alone. Cell counts saturate, so they can't wrap on wasm32. Follow-up to #3145. Co-Authored-By: Claude Opus 5.5 --- crates/map/src/generalize.rs | 21 ++++---- crates/map/src/raster.rs | 97 ++++++++++++++++++++++++++---------- 2 files changed, 83 insertions(+), 35 deletions(-) diff --git a/crates/map/src/generalize.rs b/crates/map/src/generalize.rs index 970cbeddc6..cb87cd2cb4 100644 --- a/crates/map/src/generalize.rs +++ b/crates/map/src/generalize.rs @@ -105,17 +105,17 @@ pub fn smoothed(r: &Raster, band: usize, mask: &RasterMask, metres: f64, stop: & /// reading its smoothed heights: the smoothing's ([`smoothing_bytes`]), and each trace's own copy /// of the heights (4 bytes a cell) and its grid (1). pub fn traced_bytes(r: &Raster, metres: f64, traces: usize) -> usize { - let cells = r.width as usize * r.height as usize; + let cells = (r.width as usize).saturating_mul(r.height as usize); smoothing_bytes(r, metres).saturating_add(traces.max(1).saturating_mul(5).saturating_mul(cells)) } -/// Whether `traces` more traces of `r` fit the memory planned, beside smoothed heights already held -/// (a grid that reads another's smoothing): each trace's own copy of the heights and its grid. -pub fn traces_fit(r: &Raster, traces: usize) -> Result<(), Unlit> { +/// Whether `traces` traces of `r` smoothed over `metres`, reading one smoothing together (a grid +/// that reads another's), fit the memory planned: [`traced_bytes`] for them all. +pub fn traces_fit(r: &Raster, metres: f64, traces: usize) -> Result<(), Unlit> { let limit = rustgis_data::memory::planned(SMOOTHED_FLOOR, usize::MAX, 1); #[cfg(test)] let limit = tests_hooks::limit(&r.name).unwrap_or(limit); - let bytes = traces.saturating_mul(5).saturating_mul(r.width as usize * r.height as usize); + let bytes = traced_bytes(r, metres, traces); if bytes > limit { Err(Unlit::TraceTooLarge { bytes, limit }) } else { Ok(()) } } @@ -172,7 +172,7 @@ fn line_cells(cols: i64, rows: i64) -> usize { /// the smoothed band (4 a cell), and the filter's line with its two copies (24 a cell of it). pub fn smoothing_bytes(r: &Raster, metres: f64) -> usize { let (cols, rows, _) = blocks_of(r, metres); - let cells = r.width as usize * r.height as usize; + let cells = (r.width as usize).saturating_mul(r.height as usize); (8 * (cols * rows) as usize).saturating_add(16 * cols as usize).saturating_add(4 * cells).saturating_add(24 * line_cells(cols, rows)) } @@ -374,12 +374,13 @@ mod tests { fn a_grid_reading_shared_heights_plans_its_own_trace() { let gt = GeoTransform { origin_x: 0.0, origin_y: 100.0 * 30.0, pixel_width: 30.0, pixel_height: -30.0 }; let r = Raster::new("joins", 100, 100, vec![vec![250.0; 10_000]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); - limit_for("joins", 5 * 10_000 - 1); - assert_eq!(traces_fit(&r, 1).err(), Some(Unlit::TraceTooLarge { bytes: 5 * 10_000, limit: 5 * 10_000 - 1 })); + let two = traced_bytes(&r, 90.0, 2); + limit_for("joins", two - 1); + assert_eq!(traces_fit(&r, 90.0, 2).err(), Some(Unlit::TraceTooLarge { bytes: two, limit: two - 1 })); let ok = Raster::new("joins fits", 100, 100, vec![vec![250.0; 10_000]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); - limit_for("joins fits", 5 * 10_000); - assert!(traces_fit(&ok, 1).is_ok()); + limit_for("joins fits", two); + assert!(traces_fit(&ok, 90.0, 2).is_ok()); } /// A grid whose smoothing would hold more than the memory planned for it is refused, saying diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index 6e2056aae4..425578f664 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1211,7 +1211,15 @@ struct LightWork { /// A generalised relief's smoothed heights, worked out once for the light grids that read them: /// held while they are worked out, so a grid that reads them meanwhile waits for them. -type SharedSmoothing = Mutex>>; +type SharedSmoothing = Mutex>; + +/// A generalised relief's smoothed heights, how many traces read them, and how many the memory was +/// planned for together. +struct Shared { + heights: Arc, + traces: usize, + planned: usize, +} /// Why a light grid isn't drawn, after `not_drawn` (see [`Grid::not_drawn`]), for the map and exports. fn unlit_said(not_drawn: &str, e: crate::shadow::Unlit) -> String { @@ -1233,16 +1241,20 @@ fn unlit_said(not_drawn: &str, e: crate::shadow::Unlit) -> String { } } -/// The smoothed heights `cell` holds, and whether they were another grid's, or those `smooth` works -/// out, then kept there. Only heights are kept: a smoothing stopped with the grid that started it, -/// or refused for that grid's plan, is worked out again by the next grid that reads `cell`, under -/// its own stop and plan. A grid waiting for another's smoothing looks at its own `stop` -/// meanwhile (a cancelled export that waited for it alone sets it). +/// The smoothed heights `cell` holds, or those `smooth` works out, then kept there, its memory +/// planned for `traces` traces (one is this grid's). Only heights are kept: a smoothing stopped +/// with the grid that started it, or refused for that grid's plan, is worked out again by the next +/// grid that reads `cell`, under its own stop and plan. A grid that reads another's heights adds +/// its trace, and past what was planned asks `fit` whether all the traces that read them then fit +/// together, its own and the others'. A grid waiting for another's smoothing looks at its own +/// `stop` meanwhile (a cancelled export that waited for it alone sets it). fn shared_smoothed( cell: &SharedSmoothing, stop: &std::sync::atomic::AtomicBool, + traces: usize, smooth: impl FnOnce() -> Result, -) -> Result<(Arc, bool), crate::shadow::Unlit> { + fit: impl FnOnce(usize) -> Result<(), crate::shadow::Unlit>, +) -> Result, crate::shadow::Unlit> { // Waited for without blocking: a grid stopped meanwhile (superseded, its export cancelled) // stops waiting rather than block until the other's smoothing is done. let mut kept = loop { @@ -1257,12 +1269,18 @@ fn shared_smoothed( } } }; - if let Some(heights) = kept.as_ref() { - return Ok((heights.clone(), true)); + if let Some(shared) = kept.as_mut() { + let together = shared.traces.saturating_add(1); + if together > shared.planned { + fit(together)?; + shared.planned = together; + } + shared.traces = together; + return Ok(shared.heights.clone()); } let heights = Arc::new(smooth()?); - *kept = Some(heights.clone()); - Ok((heights, false)) + *kept = Some(Shared { heights: heights.clone(), traces: 1, planned: traces }); + Ok(heights) } /// The most landing calls a light grid's work keeps. @@ -1410,14 +1428,10 @@ fn start_light(r: Arc, key: LightKey, work: Arc, together: us // refused for its plan. let smoothed = match &smoothing { Some(cell) => { - let (heights, read) = shared_smoothed(cell, &work.stop, || { - crate::generalize::smoothed(&r, key.band, &key.mask, key.generalize, &work.stop, together) - })?; - // Another grid's heights: its plan counted its own traces, so this one's trace - // is planned for here. - if read { - crate::generalize::traces_fit(&r, 1)?; - } + let smooth = || crate::generalize::smoothed(&r, key.band, &key.mask, key.generalize, &work.stop, together); + // Another grid's heights: all the traces reading them, this one's too. + let fit = |traces| crate::generalize::traces_fit(&r, key.generalize, traces); + let heights = shared_smoothed(cell, &work.stop, together, smooth, fit)?; Some(heights) } None => None, @@ -4135,11 +4149,12 @@ mod tests { for failed in [Unlit::Stopped, Unlit::TooLarge { bytes: 2, limit: 1 }] { let cell = SharedSmoothing::default(); let go = std::sync::atomic::AtomicBool::new(false); - assert_eq!(shared_smoothed(&cell, &go, || Err(failed.clone())).err(), Some(failed.clone())); - let worked = shared_smoothed(&cell, &go, || Ok(heights.clone())); - assert!(worked.as_ref().is_ok_and(|(_, joined)| !joined), "{failed:?}: smoothed again, under the next grid's stop and plan"); - let kept = shared_smoothed(&cell, &go, || panic!("{failed:?}: kept heights are read, not smoothed again")); - assert!(kept.is_ok_and(|(k, joined)| joined && worked.is_ok_and(|(w, _)| Arc::ptr_eq(&k, &w)))); + let fits = |_| Ok(()); + assert_eq!(shared_smoothed(&cell, &go, 1, || Err(failed.clone()), fits).err(), Some(failed.clone())); + let worked = shared_smoothed(&cell, &go, 1, || Ok(heights.clone()), fits); + assert!(worked.is_ok(), "{failed:?}: smoothed again, under the next grid's stop and plan"); + let kept = shared_smoothed(&cell, &go, 1, || panic!("{failed:?}: kept heights are read, not smoothed again"), fits); + assert!(kept.is_ok_and(|k| worked.is_ok_and(|w| Arc::ptr_eq(&k, &w)))); } } @@ -4157,7 +4172,7 @@ mod tests { let (cell, stop) = (cell.clone(), stop.clone()); std::thread::Builder::new() .spawn(move || { - let _ = sent.send(shared_smoothed(&cell, &stop, || Err(crate::shadow::Unlit::Failed)).err()); + let _ = sent.send(shared_smoothed(&cell, &stop, 1, || Err(crate::shadow::Unlit::Failed), |_| Ok(())).err()); }) .expect("a thread for the waiting grid"); } @@ -4177,6 +4192,38 @@ mod tests { assert!(trace.contains("its trace over the smoothed heights") && !trace.contains("smoothing its"), "{trace}"); } + /// A grid that reads another's smoothed heights plans all the traces reading them together, its + /// own and the others', beside the smoothing: with room for the smoothing and one trace, a copy + /// lit by another sun that shares the smoothing is refused for its trace (#3466 review). + #[test] + fn a_grid_reading_shared_heights_plans_every_trace_on_them() { + let mut rl = tower(1.0); + let name = "two suns on one smoothing"; + rl.data = rl.data.as_deref().cloned().map(|mut r| { + r.name = name.into(); + Arc::new(r) + }); + if let RasterRenderer::ShadedRelief { generalize, .. } = &mut rl.style.renderer { + *generalize = 90.0; + } + let mut copy = rl.clone(); + if let RasterRenderer::ShadedRelief { azimuth, .. } = &mut copy.style.renderer { + *azimuth = 0.0; + } + let r = rl.data.clone().unwrap(); + crate::generalize::limit_for(name, crate::generalize::traced_bytes(&r, 90.0, 1)); + { + let _hold = hold_cast_shadows(); + assert_eq!(rl.cast_shadows(false, (0, 1), || {}), CastShadows::Pending); + assert_eq!(copy.cast_shadows(false, (9, 1), || {}), CastShadows::Pending); + } + let grids = [rl.cast_shadows(true, (0, 1), || {}), copy.cast_shadows(true, (9, 1), || {})]; + let ready = grids.iter().filter(|g| matches!(g, CastShadows::Ready(_))).count(); + let refused = grids.iter().filter(|g| matches!(g, CastShadows::Unavailable(e) if e.contains("its trace"))).count(); + assert_eq!((ready, refused), (1, 1), "one grid smooths and fits, the other's trace doesn't"); + assert_eq!(crate::generalize::smoothings_of(name), 1); + } + /// A grid planned for more traces than another's smoothing was (the sky turned on while the /// shadows' smoothing runs) smooths under its own plan rather than read it (#3466 review). #[test] From 41094d1ecc0b69b436ab1b92b004c0756fc84aff Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 22:33:58 -0300 Subject: [PATCH 6/7] Count traces on shared heights only while they run A trace on shared smoothed heights is counted while it runs and let go when it ends, so a grid joining later is planned beside the traces still running. A refusal for the traces beside it is kept only while work still reads those heights; asked again after, it is worked out anew. Tests hold traces after their smoothing, so the waiting and refusals they check happen in order; the wait's sleep is native only. Follow-up to #3145. Co-Authored-By: Claude Opus 5.5 --- crates/map/src/raster.rs | 183 +++++++++++++++++++++++++++++++++------ 1 file changed, 157 insertions(+), 26 deletions(-) diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index 425578f664..58aa444640 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1076,6 +1076,9 @@ impl RasterLayer { // A grid that failed for a plan of other traces (the sky turned on or off since) is // tried again; one that landed is kept. jobs.retain(|j| !(same(j) && j.planned_for != together && j.work.failed(j.key.grid.stopped()))); + // One refused for the traces beside it is tried again once they have ended (no work + // reads its smoothed heights): sooner, it would only be refused again. + jobs.retain(|j| !(same(j) && j.work.crowded.load(std::sync::atomic::Ordering::Relaxed) && j.smoothing.strong_count() == 0)); // The same owner's work for another sun, not done and not waited for, is superseded // (going back to a sun kept too): it stops, as it is dropped. Grids done are kept, for // going back. Its other kind of grid (its sky, or its shadows) is left alone. @@ -1207,6 +1210,9 @@ struct LightWork { /// Called once it is done: each frame or page drawn while it was to come asks to be drawn /// again (at most [`MAX_LANDINGS`] are kept; the first already redraws them all). landings: Mutex>>, + /// Refused for the traces running beside it on shared smoothed heights: tried again once + /// they have ended. + crowded: std::sync::atomic::AtomicBool, } /// A generalised relief's smoothed heights, worked out once for the light grids that read them: @@ -1217,10 +1223,22 @@ type SharedSmoothing = Mutex>; /// planned for together. struct Shared { heights: Arc, + /// The traces reading them now: each counted while it runs (see [`Tracing`]). traces: usize, planned: usize, } +/// One trace counted on shared smoothed heights while it runs: it is let go when the trace ends. +struct Tracing<'a>(&'a SharedSmoothing); + +impl Drop for Tracing<'_> { + fn drop(&mut self) { + if let Some(shared) = self.0.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + shared.traces = shared.traces.saturating_sub(1); + } + } +} + /// Why a light grid isn't drawn, after `not_drawn` (see [`Grid::not_drawn`]), for the map and exports. fn unlit_said(not_drawn: &str, e: crate::shadow::Unlit) -> String { use crate::shadow::Unlit; @@ -1242,19 +1260,20 @@ fn unlit_said(not_drawn: &str, e: crate::shadow::Unlit) -> String { } /// The smoothed heights `cell` holds, or those `smooth` works out, then kept there, its memory -/// planned for `traces` traces (one is this grid's). Only heights are kept: a smoothing stopped -/// with the grid that started it, or refused for that grid's plan, is worked out again by the next -/// grid that reads `cell`, under its own stop and plan. A grid that reads another's heights adds -/// its trace, and past what was planned asks `fit` whether all the traces that read them then fit -/// together, its own and the others'. A grid waiting for another's smoothing looks at its own +/// planned for `traces` traces (one is this grid's), and this grid's trace counted on them while +/// the [`Tracing`] lives. Only heights are kept: a smoothing stopped with the grid that started it, +/// or refused for that grid's plan, is worked out again by the next grid that reads `cell`, under +/// its own stop and plan. A grid that reads another's heights adds its trace, and past what was +/// planned asks `fit` whether all the traces reading them then fit together, its own and those +/// still running. A grid waiting for another's smoothing looks at its own /// `stop` meanwhile (a cancelled export that waited for it alone sets it). -fn shared_smoothed( - cell: &SharedSmoothing, +fn shared_smoothed<'c>( + cell: &'c SharedSmoothing, stop: &std::sync::atomic::AtomicBool, traces: usize, smooth: impl FnOnce() -> Result, fit: impl FnOnce(usize) -> Result<(), crate::shadow::Unlit>, -) -> Result, crate::shadow::Unlit> { +) -> Result<(Arc, Tracing<'c>), crate::shadow::Unlit> { // Waited for without blocking: a grid stopped meanwhile (superseded, its export cancelled) // stops waiting rather than block until the other's smoothing is done. let mut kept = loop { @@ -1262,9 +1281,14 @@ fn shared_smoothed( Ok(kept) => break kept, Err(std::sync::TryLockError::Poisoned(e)) => break e.into_inner(), Err(std::sync::TryLockError::WouldBlock) => { + #[cfg(test)] + light_hooks::saw(&format!("waits {cell:p}")); if stop.load(std::sync::atomic::Ordering::Relaxed) { return Err(crate::shadow::Unlit::Stopped); } + // Not in the browser: its one thread holds a cell only inside its own smoothing, + // so it never finds one held. + #[cfg(not(target_arch = "wasm32"))] std::thread::sleep(std::time::Duration::from_millis(5)); } } @@ -1276,16 +1300,66 @@ fn shared_smoothed( shared.planned = together; } shared.traces = together; - return Ok(shared.heights.clone()); + return Ok((shared.heights.clone(), Tracing(cell))); } let heights = Arc::new(smooth()?); *kept = Some(Shared { heights: heights.clone(), traces: 1, planned: traces }); - Ok(heights) + Ok((heights, Tracing(cell))) } /// The most landing calls a light grid's work keeps. const MAX_LANDINGS: usize = 32; +/// Test hooks for light work, by key so tests running at once don't meet: what was seen (a grid +/// waiting on a shared smoothing, a trace held, a grid done), and traces held after their +/// smoothing until released. +#[cfg(test)] +mod light_hooks { + use std::sync::{Condvar, Mutex}; + + /// How many times each key was seen, and the rasters whose traces are held. + static SEEN: Mutex<(Vec<(String, usize)>, Vec)> = Mutex::new((Vec::new(), Vec::new())); + static CHANGED: Condvar = Condvar::new(); + + pub(super) fn saw(key: &str) { + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + match seen.0.iter_mut().find(|(k, _)| k == key) { + Some((_, n)) => *n += 1, + None => seen.0.push((key.into(), 1)), + } + CHANGED.notify_all(); + } + + /// Whether `key` was seen `times` within 5 s. + pub(super) fn seen(key: &str, times: usize) -> bool { + let seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + let count = |s: &(Vec<(String, usize)>, Vec)| s.0.iter().find(|(k, _)| k == key).map_or(0, |(_, n)| *n); + let (seen, _) = + CHANGED.wait_timeout_while(seen, std::time::Duration::from_secs(5), |s| count(s) < times).unwrap_or_else(|e| e.into_inner()); + count(&seen) >= times + } + + pub(super) fn hold(name: &str) { + SEEN.lock().unwrap_or_else(|e| e.into_inner()).1.push(name.into()); + } + + pub(super) fn release(name: &str) { + SEEN.lock().unwrap_or_else(|e| e.into_inner()).1.retain(|n| n != name); + CHANGED.notify_all(); + } + + /// Waits while `name`'s traces are held, seen as "held {name}". + pub(super) fn trace(name: &str) { + let held = |s: &(Vec<(String, usize)>, Vec)| s.1.iter().any(|n| n == name); + if !held(&SEEN.lock().unwrap_or_else(|e| e.into_inner())) { + return; + } + saw(&format!("held {name}")); + let seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + drop(CHANGED.wait_while(seen, |s| held(s)).unwrap_or_else(|e| e.into_inner())); + } +} + impl LightWork { /// Calls `landed` once the work is done; nothing when it is already (the caller has it). fn on_landing(&self, landed: impl FnOnce() + Send + 'static) { @@ -1431,14 +1505,16 @@ fn start_light(r: Arc, key: LightKey, work: Arc, together: us let smooth = || crate::generalize::smoothed(&r, key.band, &key.mask, key.generalize, &work.stop, together); // Another grid's heights: all the traces reading them, this one's too. let fit = |traces| crate::generalize::traces_fit(&r, key.generalize, traces); - let heights = shared_smoothed(cell, &work.stop, together, smooth, fit)?; - Some(heights) + let (heights, tracing) = shared_smoothed(cell, &work.stop, together, smooth, fit)?; + #[cfg(test)] + light_hooks::trace(&r.name); + Some((heights, tracing)) } None => None, }; let unmasked = RasterMask::default(); let (heights, band, mask) = match &smoothed { - Some(smoothed) => (smoothed.as_ref(), 0, &unmasked), + Some((smoothed, _)) => (smoothed.as_ref(), 0, &unmasked), None => (r.as_ref(), key.band, &key.mask), }; match key.grid { @@ -1448,6 +1524,8 @@ fn start_light(r: Arc, key: LightKey, work: Arc, together: us Grid::Sky => crate::shadow::sky(heights, band, mask, key.z_factor, threads, &work.stop), } })); + // Let go before it is done: a grid refused beside it is tried again once nothing reads them. + drop(smoothing); let not_drawn = key.grid.not_drawn(); match traced { // Stopped (superseded, or its export cancelled): a frame or page drawn while it was @@ -1457,6 +1535,9 @@ fn start_light(r: Arc, key: LightKey, work: Arc, together: us work.land(); } Ok(out) => { + if matches!(out, Err(crate::shadow::Unlit::TraceTooLarge { .. })) { + work.crowded.store(true, std::sync::atomic::Ordering::Relaxed); + } work.finish(out.map(Arc::new).map_err(|e| unlit_said(not_drawn, e))); work.land(); } @@ -1466,6 +1547,8 @@ fn start_light(r: Arc, key: LightKey, work: Arc, together: us work.land(); } } + #[cfg(test)] + light_hooks::saw(&format!("done {}", r.name)); }; #[cfg(not(target_arch = "wasm32"))] { @@ -4151,9 +4234,10 @@ mod tests { let go = std::sync::atomic::AtomicBool::new(false); let fits = |_| Ok(()); assert_eq!(shared_smoothed(&cell, &go, 1, || Err(failed.clone()), fits).err(), Some(failed.clone())); - let worked = shared_smoothed(&cell, &go, 1, || Ok(heights.clone()), fits); + let worked = shared_smoothed(&cell, &go, 1, || Ok(heights.clone()), fits).map(|(h, _)| h); assert!(worked.is_ok(), "{failed:?}: smoothed again, under the next grid's stop and plan"); - let kept = shared_smoothed(&cell, &go, 1, || panic!("{failed:?}: kept heights are read, not smoothed again"), fits); + let kept = + shared_smoothed(&cell, &go, 1, || panic!("{failed:?}: kept heights are read, not smoothed again"), fits).map(|(h, _)| h); assert!(kept.is_ok_and(|k| worked.is_ok_and(|w| Arc::ptr_eq(&k, &w)))); } } @@ -4165,17 +4249,19 @@ mod tests { use std::sync::atomic::AtomicBool; let cell = Arc::new(SharedSmoothing::default()); let smoothing = cell.lock().unwrap_or_else(|e| e.into_inner()); - // Stopped before it starts waiting: it must not wait for the smoothing held here. - let stop = Arc::new(AtomicBool::new(true)); + let stop = Arc::new(AtomicBool::new(false)); let (sent, got) = std::sync::mpsc::channel(); { let (cell, stop) = (cell.clone(), stop.clone()); std::thread::Builder::new() .spawn(move || { - let _ = sent.send(shared_smoothed(&cell, &stop, 1, || Err(crate::shadow::Unlit::Failed), |_| Ok(())).err()); + let _ = sent.send(shared_smoothed(&cell, &stop, 1, || Err(crate::shadow::Unlit::Failed), |_| Ok(())).map(|_| ()).err()); }) .expect("a thread for the waiting grid"); } + // Waiting for the smoothing held here, then stopped. + assert!(light_hooks::seen(&format!("waits {:p}", &*cell), 1), "the grid waits for the held smoothing"); + stop.store(true, std::sync::atomic::Ordering::Relaxed); let waited = got.recv_timeout(std::time::Duration::from_secs(5)); drop(smoothing); assert_eq!(waited, Ok(Some(crate::shadow::Unlit::Stopped))); @@ -4212,18 +4298,63 @@ mod tests { } let r = rl.data.clone().unwrap(); crate::generalize::limit_for(name, crate::generalize::traced_bytes(&r, 90.0, 1)); - { - let _hold = hold_cast_shadows(); - assert_eq!(rl.cast_shadows(false, (0, 1), || {}), CastShadows::Pending); - assert_eq!(copy.cast_shadows(false, (9, 1), || {}), CastShadows::Pending); - } - let grids = [rl.cast_shadows(true, (0, 1), || {}), copy.cast_shadows(true, (9, 1), || {})]; - let ready = grids.iter().filter(|g| matches!(g, CastShadows::Ready(_))).count(); + // One trace held while the other grid reads the same heights. + light_hooks::hold(name); + assert_eq!(rl.cast_shadows(false, (0, 1), || {}), CastShadows::Pending); + assert_eq!(copy.cast_shadows(false, (9, 1), || {}), CastShadows::Pending); + let one_held = light_hooks::seen(&format!("held {name}"), 1) && light_hooks::seen(&format!("done {name}"), 1); + let grids = [rl.cast_shadows(false, (0, 1), || {}), copy.cast_shadows(false, (9, 1), || {})]; + light_hooks::release(name); + assert!(one_held, "one trace runs, the other is refused"); + let running = grids.iter().filter(|g| **g == CastShadows::Pending).count(); let refused = grids.iter().filter(|g| matches!(g, CastShadows::Unavailable(e) if e.contains("its trace"))).count(); - assert_eq!((ready, refused), (1, 1), "one grid smooths and fits, the other's trace doesn't"); + assert_eq!((running, refused), (1, 1), "one grid smooths and traces, the other's trace doesn't fit beside it"); assert_eq!(crate::generalize::smoothings_of(name), 1); } + /// Traces on shared smoothed heights are counted while they run: with room for two, a third + /// sun's is refused while two run, and drawn when asked again once they have ended (#3466 + /// review). + #[test] + fn a_trace_refused_beside_others_is_drawn_once_they_end() { + let mut rl = tower(1.0); + let name = "three suns on one smoothing"; + rl.data = rl.data.as_deref().cloned().map(|mut r| { + r.name = name.into(); + Arc::new(r) + }); + if let RasterRenderer::ShadedRelief { generalize, .. } = &mut rl.style.renderer { + *generalize = 90.0; + } + let lit = |azimuth: f64| { + let mut copy = rl.clone(); + if let RasterRenderer::ShadedRelief { azimuth: a, .. } = &mut copy.style.renderer { + *a = azimuth; + } + copy + }; + let suns = [(lit(0.0), (0, 1)), (lit(120.0), (5, 1)), (lit(240.0), (9, 1))]; + let r = rl.data.clone().unwrap(); + crate::generalize::limit_for(name, crate::generalize::traced_bytes(&r, 90.0, 2)); + light_hooks::hold(name); + for (sun, owner) in &suns { + assert_eq!(sun.cast_shadows(false, *owner, || {}), CastShadows::Pending); + } + // Two traces held, the third refused. + let two_held = light_hooks::seen(&format!("held {name}"), 2) && light_hooks::seen(&format!("done {name}"), 1); + let grids: Vec<_> = suns.iter().map(|(sun, owner)| sun.cast_shadows(false, *owner, || {})).collect(); + light_hooks::release(name); + assert!(two_held, "two traces run, the third is refused: {grids:?}"); + let refused = grids.iter().position(|g| matches!(g, CastShadows::Unavailable(e) if e.contains("its trace"))); + assert_eq!(grids.iter().filter(|g| **g == CastShadows::Pending).count(), 2, "{grids:?}"); + let refused = refused.expect("the third sun's trace is refused"); + for (sun, owner) in &suns { + sun.cast_shadows(true, *owner, || {}); + } + let (sun, owner) = &suns[refused]; + assert!(matches!(sun.cast_shadows(true, *owner, || {}), CastShadows::Ready(_)), "asked again once the others ended"); + } + /// A grid planned for more traces than another's smoothing was (the sky turned on while the /// shadows' smoothing runs) smooths under its own plan rather than read it (#3466 review). #[test] From 801a7ee7c8b50a02ab4683a709f12752a83f3464 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 22:58:38 -0300 Subject: [PATCH 7/7] Say what a trace refusal's bytes count The refusal of a trace beside others gave traced_bytes, the smoothing and every trace reading it, as if it were the one trace's. It now says the smoothed heights and the N traces reading them need it. Follow-up to #3145. Co-Authored-By: Claude Opus 5.5 --- crates/map/src/generalize.rs | 4 ++-- crates/map/src/raster.rs | 15 +++++++++------ crates/map/src/shadow.rs | 7 ++++--- 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/crates/map/src/generalize.rs b/crates/map/src/generalize.rs index cb87cd2cb4..b1ce932863 100644 --- a/crates/map/src/generalize.rs +++ b/crates/map/src/generalize.rs @@ -116,7 +116,7 @@ pub fn traces_fit(r: &Raster, metres: f64, traces: usize) -> Result<(), Unlit> { #[cfg(test)] let limit = tests_hooks::limit(&r.name).unwrap_or(limit); let bytes = traced_bytes(r, metres, traces); - if bytes > limit { Err(Unlit::TraceTooLarge { bytes, limit }) } else { Ok(()) } + if bytes > limit { Err(Unlit::TraceTooLarge { traces, bytes, limit }) } else { Ok(()) } } /// Test hooks, by the raster's name so tests running at once don't meet: a limit in place of the @@ -376,7 +376,7 @@ mod tests { let r = Raster::new("joins", 100, 100, vec![vec![250.0; 10_000]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); let two = traced_bytes(&r, 90.0, 2); limit_for("joins", two - 1); - assert_eq!(traces_fit(&r, 90.0, 2).err(), Some(Unlit::TraceTooLarge { bytes: two, limit: two - 1 })); + assert_eq!(traces_fit(&r, 90.0, 2).err(), Some(Unlit::TraceTooLarge { traces: 2, bytes: two, limit: two - 1 })); let ok = Raster::new("joins fits", 100, 100, vec![vec![250.0; 10_000]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); limit_for("joins fits", two); diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index 58aa444640..c34aec5678 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1250,8 +1250,8 @@ fn unlit_said(not_drawn: &str, e: crate::shadow::Unlit) -> String { bytes >> 20, limit >> 20 ), - Unlit::TraceTooLarge { bytes, limit } => format!( - "{not_drawn}: its trace over the smoothed heights needs {} MiB, more than the {} MiB planned for it: {clip}", + Unlit::TraceTooLarge { traces, bytes, limit } => format!( + "{not_drawn}: its smoothed heights and the {traces} traces reading them need {} MiB, more than the {} MiB planned for them: {clip}", bytes >> 20, limit >> 20 ), @@ -4274,8 +4274,11 @@ mod tests { use crate::shadow::Unlit; let smoothing = unlit_said("Cast shadows aren't drawn", Unlit::TooLarge { bytes: 3 << 20, limit: 2 << 20 }); assert!(smoothing.contains("smoothing its heights") && smoothing.contains("3 MiB"), "{smoothing}"); - let trace = unlit_said("Cast shadows aren't drawn", Unlit::TraceTooLarge { bytes: 3 << 20, limit: 2 << 20 }); - assert!(trace.contains("its trace over the smoothed heights") && !trace.contains("smoothing its"), "{trace}"); + let trace = unlit_said("Cast shadows aren't drawn", Unlit::TraceTooLarge { traces: 3, bytes: 3 << 20, limit: 2 << 20 }); + assert!( + trace.contains("its smoothed heights and the 3 traces reading them need 3 MiB") && !trace.contains("smoothing its"), + "{trace}" + ); } /// A grid that reads another's smoothed heights plans all the traces reading them together, its @@ -4307,7 +4310,7 @@ mod tests { light_hooks::release(name); assert!(one_held, "one trace runs, the other is refused"); let running = grids.iter().filter(|g| **g == CastShadows::Pending).count(); - let refused = grids.iter().filter(|g| matches!(g, CastShadows::Unavailable(e) if e.contains("its trace"))).count(); + let refused = grids.iter().filter(|g| matches!(g, CastShadows::Unavailable(e) if e.contains("traces reading them"))).count(); assert_eq!((running, refused), (1, 1), "one grid smooths and traces, the other's trace doesn't fit beside it"); assert_eq!(crate::generalize::smoothings_of(name), 1); } @@ -4345,7 +4348,7 @@ mod tests { let grids: Vec<_> = suns.iter().map(|(sun, owner)| sun.cast_shadows(false, *owner, || {})).collect(); light_hooks::release(name); assert!(two_held, "two traces run, the third is refused: {grids:?}"); - let refused = grids.iter().position(|g| matches!(g, CastShadows::Unavailable(e) if e.contains("its trace"))); + let refused = grids.iter().position(|g| matches!(g, CastShadows::Unavailable(e) if e.contains("traces reading them"))); assert_eq!(grids.iter().filter(|g| **g == CastShadows::Pending).count(), 2, "{grids:?}"); let refused = refused.expect("the third sun's trace is refused"); for (sun, owner) in &suns { diff --git a/crates/map/src/shadow.rs b/crates/map/src/shadow.rs index d0bb193ce5..9df83da521 100644 --- a/crates/map/src/shadow.rs +++ b/crates/map/src/shadow.rs @@ -57,9 +57,10 @@ pub enum Unlit { /// A generalised relief's smoothing would hold `bytes`, past the `limit` it plans for (#3145, /// see [`crate::generalize::smoothed`]). TooLarge { bytes: usize, limit: usize }, - /// A trace over another grid's smoothed heights would hold `bytes` (its copy of the heights and - /// its grid), past the `limit` planned (see [`crate::generalize::traces_fit`]). - TraceTooLarge { bytes: usize, limit: usize }, + /// A trace over another grid's smoothed heights doesn't fit beside the others: the smoothing + /// and the `traces` reading it (each one's copy of the heights and its grid) would hold `bytes`, + /// past the `limit` planned (see [`crate::generalize::traces_fit`]). + TraceTooLarge { traces: usize, bytes: usize, limit: usize }, } /// The light left by cast shadows on each cell of `band` (`0` in shadow to `255` lit), row by row