From c2f7e3bfccaaece5602964c1eccb50bbca068a45 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 11 Nov 2026 01:32:20 -0500 Subject: [PATCH 1/6] perf(ui): draw a flat map's settled frame off the UI thread (#1750) After a pan or zoom the map view showed the last frame shifted and scaled, then, once the motion stopped, drew the exact frame on the UI thread: the window froze for the whole render (30-50 ms with the 1:10m countries, far longer for a detailed layer), and scroll zooming, which stops and starts, hit that again and again. A flat, north-up map whose frame differs from the one on screen only by its camera now goes through the worker the globe, tilted and tiled maps use (tilt_settle). The last frame stays on screen meanwhile (no preview), and the new one is swapped in when it lands. A change to the map itself (a command, an edit, a layer shown) is still drawn at once, and the browser, with one thread, draws it inline as before. A frame that goes out of date while it is drawn is stopped: the worker installs a flag (render::cancel) the renderer reads between layers and every 2048 features of a layer, and a stopped frame comes back as cancelled, not as one that couldn't be drawn, so its key is drawn again. Moving the map again stops the job, freeing the worker for the frame of where the map comes to rest. Part of #1750. --- crates/render/src/cancel.rs | 71 +++++++++++++++++++++++ crates/render/src/lib.rs | 13 +++++ crates/ui-egui/src/mapview.rs | 93 +++++++++++++++++++++++++++++-- crates/ui-egui/src/tilt_settle.rs | 92 +++++++++++++++++++++++++----- 4 files changed, 248 insertions(+), 21 deletions(-) create mode 100644 crates/render/src/cancel.rs diff --git a/crates/render/src/cancel.rs b/crates/render/src/cancel.rs new file mode 100644 index 0000000000..f748789f08 --- /dev/null +++ b/crates/render/src/cancel.rs @@ -0,0 +1,71 @@ +//! Stopping a frame no longer wanted (#1750). The desktop app draws a settled flat map's frame on a +//! worker; when the map moves again before it is done, the frame is out of date. The worker +//! installs a flag on its thread ([`install`]) and sets it to stop: the renderer looks at it between +//! layers and every [`EVERY`] features of a layer, and a frame stopped that way comes back as +//! `None`. With none installed (an export, the CLI, the browser) frames always finish. + +use std::cell::RefCell; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +/// How many features of a layer are drawn between looks at the flag. +pub(crate) const EVERY: usize = 2048; + +thread_local! { + static FLAG: RefCell>> = const { RefCell::new(None) }; +} + +/// Makes `flag` stop the frames drawn on this thread until the guard is dropped, which puts back +/// the one before. +pub fn install(flag: Arc) -> Installed { + Installed(FLAG.with(|f| f.replace(Some(flag)))) +} + +/// Puts back the flag before when dropped (see [`install`]). +pub struct Installed(Option>); + +impl Drop for Installed { + fn drop(&mut self) { + let before = self.0.take(); + let _ = FLAG.try_with(|f| f.replace(before)); + } +} + +/// Whether the frame being drawn on this thread was asked to stop. +pub(crate) fn requested() -> bool { + FLAG.with(|f| f.borrow().as_ref().is_some_and(|flag| flag.load(Ordering::Relaxed))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_flag_stops_frames_on_its_thread_only_while_installed() { + let flag = Arc::new(AtomicBool::new(false)); + assert!(!requested()); + { + let _guard = install(flag.clone()); + assert!(!requested()); + flag.store(true, Ordering::Relaxed); + assert!(requested()); + // Another thread draws on. + assert!(!std::thread::spawn(requested).join().unwrap_or(true)); + } + assert!(!requested()); + } + + #[test] + fn a_stopped_frame_is_no_frame() { + let mut map = rustgis_map::Map::new("m"); + if let Some(d) = crate::world_dataset("Countries", crate::sample_data::COUNTRIES) { + map.add_dataset(d); + } + let view = crate::View { width: 64.0, height: 48.0, pixels_per_point: 1.0, camera: rustgis_map::Camera::world(), sky: false }; + let flag = Arc::new(AtomicBool::new(false)); + let _guard = install(flag.clone()); + assert!(crate::render(&mut map, &view).is_some()); + flag.store(true, Ordering::Relaxed); + assert!(crate::render(&mut map, &view).is_none()); + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 7e89144c27..c569f7e888 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6,6 +6,7 @@ //! the labels too, for export and the command line. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod cancel; mod canvas; mod diagrams; mod effects; @@ -1979,6 +1980,10 @@ fn render_with_backend(map: &mut Map, view: &View, full_res_rasters: bool, backe fn render_any(map: &mut Map, view: &View, full_res_rasters: bool, backend: Backend, record: bool) -> Option { let revisions = archive_revisions([&*map]); let output = render_pass(map, view, full_res_rasters, backend, record); + // A frame stopped part-way (see `cancel`) is no frame. + if cancel::requested() { + return None; + } revisions.current([&*map]).then_some(output).flatten() } @@ -3776,6 +3781,10 @@ fn render_frame( // The layer drawn last, whose tile layers go over it before the next. let mut below: Option = None; for li in order { + // A frame no longer wanted stops between layers (see `cancel`). + if cancel::requested() { + break; + } if let Some(id) = below.take() { draw_tiles!(Some(id)); } @@ -4167,6 +4176,10 @@ fn render_frame( let has_fills = layer.has_fills(); let mut stacked: Vec<(&[Vec], Symbol, &[LineStroke])> = Vec::new(); for (row, g) in drawn.iter().enumerate() { + // And every few thousand features of a large layer. + if row % cancel::EVERY == 0 && row > 0 && cancel::requested() { + break; + } let Some(g) = g else { continue }; let e = extents.get(row).copied().unwrap_or_else(|| g.extent()); // A point's marks, shifted from it, may show while the point is off the view. diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 6106eeba5e..b7e06de93b 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -943,12 +943,29 @@ fn main_view(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { app.map.callout_lonlat.clear(); app.map.callout_map.clear(); } - let settling = (tilted || globe_view || tiled_flat) && !moving && app.ws.playing.is_none() && !hold; + // A flat, north-up map's exact frame after a pan or zoom is drawn off the UI thread too + // (#1750): its last frame, shifted and scaled, stays on screen until the new one arrives, and + // moving again stops it. A change to the map itself (an edit, a layer shown or hidden, a + // resize) is still drawn at once, so it shows without waiting. The browser has one thread: there + // the worker draws it at once, as before. + let flat_settle = cfg!(not(target_arch = "wasm32")) + && !globe_view + && cam.bearing == 0.0 + && cam.pitch == 0.0 + && app.session.map().tiles.is_empty() + && (app.map.texture.is_some() || app.map.gpu_frame.is_some()) + && app.map.key.is_some_and(|k| k.rev == key.rev && k.size == key.size && k.sources == key.sources && (k.cam != key.cam || k.draft)); + let settling = (tilted || globe_view || tiled_flat || flat_settle) && !moving && app.ws.playing.is_none() && !hold; let mut tilt_draped = tilt_draped; // A frame finishing during a new gesture is obsolete. Drain it now so it neither holds - // the worker slot nor keeps screenshot/idle waiters waiting for a frame we will not show. - if !settling && let Some((_, done)) = app.map.tilt_settle.take() { - app.session.map_mut().adopt_caches(&done.map); + // the worker slot nor keeps screenshot/idle waiters waiting for a frame we will not show; + // one still being drawn is stopped, so the worker is free once the map rests again. + if !settling { + if let Some((_, done)) = app.map.tilt_settle.take() { + app.session.map_mut().adopt_caches(&done.map); + } else if app.map.tilt_settle.busy() { + app.map.tilt_settle.cancel(); + } } // A GPU scene that re-projects (no pictures) of this map, at this size: a camera move needs // no picture drawn on the CPU meanwhile. One whose tile layers are all live, without labels @@ -977,7 +994,8 @@ fn main_view(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { if let Some((k, done)) = app.map.tilt_settle.take() { app.session.map_mut().adopt_caches(&done.map); // A frame of this view that couldn't be drawn isn't tried again: nothing is to fill. - if same_view(k, key) && done.rendered.is_none() && done.archives.current([&done.map]) { + // (One stopped part-way just wasn't wanted any more.) + if same_view(k, key) && done.rendered.is_none() && !done.cancelled && done.archives.current([&done.map]) { app.map.filling = false; } // One drawn before tiles or data arrived still shows; the next follows. So does one @@ -1027,7 +1045,7 @@ fn main_view(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { draped = app.map.drape.prepare(ui.ctx(), app.session.map_mut(), drape_key, tiles, w, h, ppp, time); } else if tilted { tilt_draped = app.map.tilt_drape.prepare(ui.ctx(), app.session.map_mut(), drape_key, tiles, w, h, ppp, time); - } else if app.map.preview_attempt != Some(key) && !reprojects && !(keep_frame && app.map.tilt_settle.busy()) { + } else if app.map.preview_attempt != Some(key) && !reprojects && !flat_settle && !(keep_frame && app.map.tilt_settle.busy()) { // A kept frame waits for the exact one; if that couldn't be drawn, a preview. // A small preview shows a visibility change immediately. The exact frame is // already on its way. Even a failed preview is attempted only once per key. @@ -5149,6 +5167,69 @@ mod tests { assert_ne!(shown_layers(&app.session), before, "a layer hidden"); } + /// A flat map's exact frame after a pan or zoom is drawn off the UI thread (#1750): its last + /// frame stays on screen (no preview) while the worker draws, moving again stops the worker, + /// and the frame for where the map rests arrives. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_flat_maps_settled_frame_is_drawn_off_the_ui_thread() { + let _turn = crate::fetching::turn(); + let app = RustGisApp::with_sample(); + let mut h = + egui_kittest::Harness::builder().with_size(vec2(900.0, 550.0)).with_step_dt(0.000_05).with_max_steps(10_000).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + let cam_of = |st: &RustGisApp| { + let c = st.session.map().camera; + ((c.center.x * 100.0) as i64, (c.center.y * 100.0) as i64) + }; + let exact = |h: &mut egui_kittest::Harness<'_, RustGisApp>, what: &str| { + let end = std::time::Instant::now() + std::time::Duration::from_secs(30); + loop { + h.step(); + let st = h.state(); + if st.map.key.is_some_and(|k| k.rev == st.session.revision && !k.draft && (k.cam.0, k.cam.1) == cam_of(st)) + && !st.map.tilt_settle.busy() + { + break; + } + assert!(std::time::Instant::now() < end, "{what}"); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + }; + exact(&mut h, "the first frame did not arrive"); + assert!(h.state().session.map().tiles.is_empty(), "the sample has no tile layers"); + // A pan (the camera moved as a drag moves it, not by a command, which changes the map's + // revision) come to rest: the frame is drawn on the worker, the last one stays meanwhile. + let before = h.state().map.key.expect("a frame"); + let shift = |h: &mut egui_kittest::Harness<'_, RustGisApp>, px: f64| { + let cam = &mut h.state_mut().session.map_mut().camera; + cam.center.x += cam.res * px; + }; + shift(&mut h, 200.0); + h.step(); + assert!(h.state().map.tilt_settle.busy(), "the pan's frame is drawn on the worker"); + assert_eq!(h.state().map.key, Some(before), "the last frame stays on screen, no preview"); + // Moving again stops it; once the map rests, the frame for where it is arrives. + h.state_mut().map.last_interaction = f64::MAX; + shift(&mut h, 150.0); + h.step(); + let end = std::time::Instant::now() + std::time::Duration::from_secs(30); + while h.state().map.tilt_settle.busy() { + assert!(std::time::Instant::now() < end, "the stopped frame never came back"); + std::thread::sleep(std::time::Duration::from_millis(2)); + h.step(); + } + h.state_mut().map.last_interaction = -10.0; + exact(&mut h, "the frame of the resting map did not arrive"); + assert_eq!(h.state().map.key.map(|k| k.rev), Some(before.rev)); + } + /// #1051: changing a layer's transparency over a tiled basemap kept the exact frame on /// screen until the next one arrived; it showed a coarse preview of the whole map, basemap /// included, so every step of a slider drag made the map flicker. diff --git a/crates/ui-egui/src/tilt_settle.rs b/crates/ui-egui/src/tilt_settle.rs index d65f5fbb11..4e9c3bdbfd 100644 --- a/crates/ui-egui/src/tilt_settle.rs +++ b/crates/ui-egui/src/tilt_settle.rs @@ -1,6 +1,7 @@ -//! Exact globe, tilted and tiled flat frames, composed off the UI thread. Such a frame takes a few -//! hundred milliseconds for a large view; composed on the UI thread it froze the map just as it came -//! to rest. A copy of the map is drawn on a worker instead (the copy shares its features and +//! Exact globe, tilted and tiled flat frames, and a flat map's frame after a pan or zoom (#1750), +//! composed off the UI thread. Such a frame takes a few hundred milliseconds for a large view; +//! composed on the UI thread it froze the map just as it came to rest. A frame that goes out of +//! date while it is drawn (the map moves again) is stopped ([`TiltSettle::cancel`]). A copy of the map is drawn on a worker instead (the copy shares its features and //! caches, so it costs pointers), while the drape (see `tilt_drape`) stays on screen until the //! frame is ready. GPU scenes are composed here too, then uploaded on the UI thread. In the //! browser there are no threads: the frame is drawn at once, its tile pictures a frame's worth at @@ -21,13 +22,15 @@ pub(crate) struct Done { pub ms: u64, /// Tile pictures stand in for others, or are still to be drawn: it is drawn again. pub incomplete: bool, + /// It was stopped part-way ([`TiltSettle::cancel`]): no frame, but nothing wrong with it. + pub cancelled: bool, pub archives: render::ArchiveRevision, } /// The frame being drawn (at most one at a time), and what it is for. pub(crate) struct TiltSettle { #[cfg(not(target_arch = "wasm32"))] - job: Option<(K, std::sync::mpsc::Receiver)>, + job: Option<(K, std::sync::mpsc::Receiver, Stop)>, #[cfg(target_arch = "wasm32")] ready: Option<(K, Done)>, /// The last frame that couldn't be drawn (the renderer panicked): it isn't tried again. @@ -46,8 +49,12 @@ impl Default for TiltSettle { } } -fn draw(mut map: Map, view: View, backend: Backend) -> Done { +/// A job's stop flag (see `render::cancel`). +type Stop = std::sync::Arc; + +fn draw(mut map: Map, view: View, backend: Backend, stop: Stop) -> Done { let t0 = web_time::Instant::now(); + let _stop = render::cancel::install(stop.clone()); let archives = render::archive_revisions([&map]); // On the UI thread in the browser, a frame's worth of tile pictures at a time; on a worker // natively, all of them. @@ -59,7 +66,8 @@ fn draw(mut map: Map, view: View, backend: Backend) -> Done { }; #[cfg(not(target_arch = "wasm32"))] let (rendered, incomplete) = (render::render_backend(&mut map, &view, backend), false); - Done { rendered, view, map, ms: t0.elapsed().as_millis() as u64, incomplete, archives } + let cancelled = stop.load(std::sync::atomic::Ordering::Relaxed); + Done { rendered, view, map, ms: t0.elapsed().as_millis() as u64, incomplete, cancelled, archives } } impl TiltSettle { @@ -74,7 +82,7 @@ impl TiltSettle { /// The key of the frame being drawn (or drawn and not yet taken). pub fn key(&self) -> Option { #[cfg(not(target_arch = "wasm32"))] - return self.job.as_ref().map(|(k, _)| *k); + return self.job.as_ref().map(|(k, ..)| *k); #[cfg(target_arch = "wasm32")] return self.ready.as_ref().map(|(k, _)| *k); } @@ -88,12 +96,25 @@ impl TiltSettle { /// Builds a CPU frame or GPU scene on the worker; GPU resources are uploaded by the UI. pub fn start_backend(&mut self, ctx: &egui::Context, key: K, map: Map, view: View, backend: Backend) { - self.start_with(ctx, key, move || draw(map, view, backend)); + let stop = Stop::default(); + let flag = stop.clone(); + self.start_with(ctx, key, stop, move || draw(map, view, backend, flag)); + } + + /// Asks the frame being drawn to stop (it is out of date): the renderer looks between layers + /// and every few thousand features, so the worker is free again soon. The stopped frame is + /// still handed back by [`TiltSettle::take`], with no picture and `cancelled` set, and its key + /// may be drawn again. In the browser frames are drawn at once: there is nothing to stop. + pub fn cancel(&mut self) { + #[cfg(not(target_arch = "wasm32"))] + if let Some((.., stop)) = &self.job { + stop.store(true, std::sync::atomic::Ordering::Relaxed); + } } /// Starts `work` drawing the frame keyed `key` (see [`TiltSettle::start`]). A panic in it /// gives no frame, and the key isn't tried again. - fn start_with(&mut self, ctx: &egui::Context, key: K, work: impl FnOnce() -> Done + Send + 'static) { + fn start_with(&mut self, ctx: &egui::Context, key: K, stop: Stop, work: impl FnOnce() -> Done + Send + 'static) { if self.busy() || self.failed == Some(key) { return; } @@ -114,12 +135,14 @@ impl TiltSettle { ctx.request_repaint(); }); match spawned { - Ok(_) => self.job = Some((key, rx)), + Ok(_) => self.job = Some((key, rx, stop)), Err(_) => self.failed = Some(key), } } #[cfg(target_arch = "wasm32")] { + // Drawn at once: nothing is left to stop. + let _ = stop; match std::panic::catch_unwind(work) { Ok(done) => self.ready = Some((key, done)), Err(_) => self.failed = Some(key), @@ -132,13 +155,13 @@ impl TiltSettle { pub fn take(&mut self) -> Option<(K, Done)> { #[cfg(not(target_arch = "wasm32"))] let done = { - let (_, rx) = self.job.as_ref()?; + let (_, rx, _) = self.job.as_ref()?; match rx.try_recv() { - Ok(done) => self.job.take().map(|(k, _)| (k, done)), + Ok(done) => self.job.take().map(|(k, ..)| (k, done)), Err(std::sync::mpsc::TryRecvError::Empty) => None, // The worker ended without an answer. Err(std::sync::mpsc::TryRecvError::Disconnected) => { - self.failed = self.job.take().map(|(k, _)| k); + self.failed = self.job.take().map(|(k, ..)| k); None } } @@ -147,6 +170,7 @@ impl TiltSettle { let done = self.ready.take(); if let Some((k, d)) = &done && d.rendered.is_none() + && !d.cancelled && d.archives.current([&d.map]) { self.failed = Some(*k); @@ -186,13 +210,51 @@ mod tests { assert!(s.take().is_none()); } + /// A frame stopped part-way comes back without a picture, isn't taken for one that failed, + /// and frees the worker for the next. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_stopped_frame_comes_back_cancelled_and_can_be_drawn_again() { + let ctx = egui::Context::default(); + let map = Map::new("m"); + let view = View { width: 64.0, height: 48.0, pixels_per_point: 1.0, camera: map.camera, sky: true }; + let mut s = TiltSettle::default(); + // The work waits until it is stopped, as a long frame would still be drawing. + let stop = Stop::default(); + let seen = stop.clone(); + let (m, v) = (map.clone(), view); + s.start_with(&ctx, 3u8, stop, move || { + while !seen.load(std::sync::atomic::Ordering::Relaxed) { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + draw(m, v, Backend::Cpu, seen) + }); + assert!(s.busy()); + s.cancel(); + let end = std::time::Instant::now() + std::time::Duration::from_secs(30); + let done = loop { + if let Some(d) = s.take() { + break d; + } + assert!(std::time::Instant::now() < end, "the stopped frame never came back"); + std::thread::sleep(std::time::Duration::from_millis(5)); + }; + assert_eq!(done.0, 3); + assert!(done.1.cancelled && done.1.rendered.is_none()); + assert!(!s.busy()); + // The same frame is drawn when asked again. + s.start(&ctx, 3u8, map, view); + assert!(s.busy(), "a stopped frame was taken for one that couldn't be drawn"); + s.cancel(); + } + #[test] fn a_frame_that_cant_be_drawn_isnt_tried_again() { let ctx = egui::Context::default(); let map = Map::new("m"); let view = View { width: 64.0, height: 48.0, pixels_per_point: 1.0, camera: Camera { pitch: 60.0, ..Camera::world() }, sky: true }; let mut s = TiltSettle::default(); - s.start_with(&ctx, 1u8, || panic!("the renderer failed")); + s.start_with(&ctx, 1u8, Stop::default(), || panic!("the renderer failed")); let end = std::time::Instant::now() + std::time::Duration::from_secs(30); while s.busy() { assert!(s.take().is_none()); @@ -224,7 +286,7 @@ mod tests { } }); let mut s = TiltSettle::default(); - s.start_with(&ctx, 1u8, || panic!("the renderer failed")); + s.start_with(&ctx, 1u8, Stop::default(), || panic!("the renderer failed")); assert!(wake.recv_timeout(std::time::Duration::from_secs(30)).is_ok(), "never woken"); assert!(s.take().is_none()); assert!(!s.busy(), "the woken frame found the job still running"); From dd9790ae13882af9a1f836634f40393b40441505 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 11 Nov 2026 01:54:33 -0500 Subject: [PATCH 2/6] fix(render): stop a frame between streamed chunks, before its labels (#1750) A stopped frame now reads no further chunk of a streamed layer (the stop isn't taken for a source error), draws no more of a layer, and returns before its tiles, labels and effects. The flag check can't panic in thread teardown. The map view falls back to a preview when the worker couldn't draw a flat frame, not only while it is busy. --- crates/render/src/cancel.rs | 22 ++++++++-- crates/render/src/lib.rs | 19 ++++++++ crates/render/src/stream_tests.rs | 72 +++++++++++++++++++++++++++++++ crates/ui-egui/src/mapview.rs | 7 ++- crates/ui-egui/src/tilt_settle.rs | 5 ++- 5 files changed, 119 insertions(+), 6 deletions(-) diff --git a/crates/render/src/cancel.rs b/crates/render/src/cancel.rs index f748789f08..8cdb20d5f2 100644 --- a/crates/render/src/cancel.rs +++ b/crates/render/src/cancel.rs @@ -1,8 +1,12 @@ //! Stopping a frame no longer wanted (#1750). The desktop app draws a settled flat map's frame on a //! worker; when the map moves again before it is done, the frame is out of date. The worker //! installs a flag on its thread ([`install`]) and sets it to stop: the renderer looks at it between -//! layers and every [`EVERY`] features of a layer, and a frame stopped that way comes back as -//! `None`. With none installed (an export, the CLI, the browser) frames always finish. +//! layers, before each chunk of a streamed layer and every [`EVERY`] features of a layer, and a +//! frame stopped that way comes back as `None`, without its tiles, labels or effects worked out. +//! With none installed (an export, the CLI, the browser) frames always finish. The flag is the +//! thread's own: threads the renderer starts for a part of the frame (a raster's rows) don't look +//! at it, and finish their part. A long step without a look (projecting or thinning a layer's +//! geometry for the first time, a raster) runs to its end. use std::cell::RefCell; use std::sync::Arc; @@ -33,7 +37,14 @@ impl Drop for Installed { /// Whether the frame being drawn on this thread was asked to stop. pub(crate) fn requested() -> bool { - FLAG.with(|f| f.borrow().as_ref().is_some_and(|flag| flag.load(Ordering::Relaxed))) + // Never during the thread's teardown: no frame is drawn that late. + FLAG.try_with(|f| f.borrow().as_ref().is_some_and(|flag| flag.load(Ordering::Relaxed))).unwrap_or(false) +} + +#[cfg(test)] +thread_local! { + /// Features drawn on this test thread, to see a stopped frame stop drawing. + pub(crate) static DRAWN: std::cell::Cell = const { std::cell::Cell::new(0) }; } #[cfg(test)] @@ -64,8 +75,13 @@ mod tests { let view = crate::View { width: 64.0, height: 48.0, pixels_per_point: 1.0, camera: rustgis_map::Camera::world(), sky: false }; let flag = Arc::new(AtomicBool::new(false)); let _guard = install(flag.clone()); + DRAWN.set(0); assert!(crate::render(&mut map, &view).is_some()); + assert!(DRAWN.get() > 100, "{} countries drawn", DRAWN.get()); + // Stopped, it draws no feature at all, not just hands back nothing. flag.store(true, Ordering::Relaxed); + DRAWN.set(0); assert!(crate::render(&mut map, &view).is_none()); + assert_eq!(DRAWN.get(), 0); } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index c569f7e888..138c9a5a89 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -3960,6 +3960,10 @@ fn render_frame( // polygons. let mut extruded_charts: Option = None; let mut draw_chunk = |layer: &mut rustgis_map::Layer| -> rustgis_data::Result<()> { + // A stopped frame draws no more of a layer or a streamed chunk (see `cancel`). + if cancel::requested() { + return Ok(()); + } // The definition query and the display filters that apply at this scale (a feature draws // only if it matches all of them). let mut rows = layer.drawn_rows(scale); @@ -4180,6 +4184,8 @@ fn render_frame( if row % cancel::EVERY == 0 && row > 0 && cancel::requested() { break; } + #[cfg(test)] + cancel::DRAWN.set(cancel::DRAWN.get() + 1); let Some(g) = g else { continue }; let e = extents.get(row).copied().unwrap_or_else(|| g.extent()); // A point's marks, shifted from it, may show while the point is off the view. @@ -4780,6 +4786,10 @@ fn render_frame( // All coordinates are read here: filtering only to the viewport can change labels, // shadows and screen-space effects whose geometry lies beyond its boundary. let result = visit_complete(source.as_ref(), &mut |features| { + // A frame no longer wanted reads no further (see `cancel`). + if cancel::requested() { + return Err(rustgis_data::DataError::Cancelled); + } chunk.clear_cache(); chunk.selection = features.iter().enumerate().filter_map(|(r, f)| selected_order.contains_key(&f.id).then_some(r)).collect(); @@ -4791,6 +4801,10 @@ fn render_frame( Ok(()) }); if let Err(e) = result { + // Stopped, not failed: the source is fine. + if cancel::requested() { + return None; + } if let Some(s) = &mut layer.source { s.error = Some(e.to_string()); } @@ -4833,6 +4847,11 @@ fn render_frame( cpu_dirty = true; } } + // A frame stopped part-way (see `cancel`) is no frame: its tiles, labels and effects aren't + // worth working out. + if cancel::requested() { + return None; + } if let Some(id) = below { draw_tiles!(Some(id)); } diff --git a/crates/render/src/stream_tests.rs b/crates/render/src/stream_tests.rs index 7135971cef..516bc8ec52 100644 --- a/crates/render/src/stream_tests.rs +++ b/crates/render/src/stream_tests.rs @@ -1436,3 +1436,75 @@ fn streamed_extrusions_keep_their_charts_on_top() { assert!(n * 10 >= whole * 9, "chunks of {size}: {n} chart px, {whole} resident"); } } + +/// A frame stopped while a streamed layer is read reads no further chunk (#1750), and the stop +/// isn't taken for a failure of the source. +#[test] +fn a_stopped_frame_reads_no_further_chunk_and_leaves_its_source_unfailed() { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + /// Chunks that set the frame's stop flag once the first is drawn. + struct StopAfterFirst { + chunks: Chunks, + stop: Arc, + } + impl FeatureSource for StopAfterFirst { + fn info(&self) -> &SourceInfo { + self.chunks.info() + } + fn read(&self, r: &Request) -> rustgis_data::Result { + self.chunks.read(r) + } + fn streams_chunks(&self) -> bool { + true + } + fn visit_chunks( + &self, + e: Option, + n: usize, + visit: &mut dyn FnMut(Vec) -> rustgis_data::Result<()>, + ) -> rustgis_data::Result { + self.chunks.visit_chunks(e, n, &mut |chunk| { + let r = visit(chunk); + self.stop.store(true, Ordering::Relaxed); + r + }) + } + } + let mut m = Map::new("m"); + if let Some(d) = world_dataset("Countries", sample_data::COUNTRIES) { + m.add_dataset(d); + } + let ds = m.layers[0].dataset.clone(); + assert!(ds.features.len() > 100); + let info = SourceInfo { + name: ds.name.clone(), + format: "test", + geometry_type: ds.geometry_type, + fields: ds.fields.clone(), + extent: ds.extent(), + count: Some(ds.features.len() as u64), + crs: "EPSG:4326".into(), + indexed: true, + notes: Vec::new(), + zm_dropped: false, + }; + let stop = Arc::new(AtomicBool::new(false)); + let mut layer = m.layers[0].clone(); + layer.dataset.features = ds.features.iter().take(1).cloned().collect::>().into(); + layer.source = Some(SourceLayer::from_path( + "test.shp", + None, + Box::new(StopAfterFirst { chunks: Chunks { info, ds, size: 20 }, stop: stop.clone() }), + )); + m.layers[0] = layer; + let view = View { width: 64.0, height: 48.0, pixels_per_point: 1.0, camera: Camera::world(), sky: false }; + settle(&mut m, &view); + stop.store(false, Ordering::Relaxed); + let _guard = crate::cancel::install(stop.clone()); + crate::cancel::DRAWN.set(0); + assert!(render(&mut m, &view).is_none(), "a stopped frame is no frame"); + let drawn = crate::cancel::DRAWN.get(); + assert!(drawn <= 20, "{drawn} features drawn: the read went on past the first chunk"); + assert!(m.layers[0].source.as_ref().is_some_and(|s| s.error.is_none()), "a stop isn't a source error"); +} diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index b7e06de93b..e50225209b 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -1045,7 +1045,12 @@ fn main_view(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { draped = app.map.drape.prepare(ui.ctx(), app.session.map_mut(), drape_key, tiles, w, h, ppp, time); } else if tilted { tilt_draped = app.map.tilt_drape.prepare(ui.ctx(), app.session.map_mut(), drape_key, tiles, w, h, ppp, time); - } else if app.map.preview_attempt != Some(key) && !reprojects && !flat_settle && !(keep_frame && app.map.tilt_settle.busy()) { + } else if app.map.preview_attempt != Some(key) + && !reprojects + // The last frame, shifted, stands in while the worker draws; if it couldn't, a preview. + && !(flat_settle && app.map.tilt_settle.busy()) + && !(keep_frame && app.map.tilt_settle.busy()) + { // A kept frame waits for the exact one; if that couldn't be drawn, a preview. // A small preview shows a visibility change immediately. The exact frame is // already on its way. Even a failed preview is attempted only once per key. diff --git a/crates/ui-egui/src/tilt_settle.rs b/crates/ui-egui/src/tilt_settle.rs index 4e9c3bdbfd..d48ab3fef6 100644 --- a/crates/ui-egui/src/tilt_settle.rs +++ b/crates/ui-egui/src/tilt_settle.rs @@ -101,8 +101,9 @@ impl TiltSettle { self.start_with(ctx, key, stop, move || draw(map, view, backend, flag)); } - /// Asks the frame being drawn to stop (it is out of date): the renderer looks between layers - /// and every few thousand features, so the worker is free again soon. The stopped frame is + /// Asks the frame being drawn to stop (it is out of date): the renderer looks between layers, + /// before each chunk of a streamed layer and every 2048 features (see `render::cancel`), so + /// the worker is free again soon. The stopped frame is /// still handed back by [`TiltSettle::take`], with no picture and `cancelled` set, and its key /// may be drawn again. In the browser frames are drawn at once: there is nothing to stop. pub fn cancel(&mut self) { From 517940d5c4af7ac48e3c2c2badba04144d938a57 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 11 Nov 2026 02:09:09 -0500 Subject: [PATCH 3/6] fix(ui): a frame is cancelled only if it came back without a picture (#1750) --- crates/ui-egui/src/tilt_settle.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tilt_settle.rs b/crates/ui-egui/src/tilt_settle.rs index d48ab3fef6..4d276ee98e 100644 --- a/crates/ui-egui/src/tilt_settle.rs +++ b/crates/ui-egui/src/tilt_settle.rs @@ -66,7 +66,9 @@ fn draw(mut map: Map, view: View, backend: Backend, stop: Stop) -> Done { }; #[cfg(not(target_arch = "wasm32"))] let (rendered, incomplete) = (render::render_backend(&mut map, &view, backend), false); - let cancelled = stop.load(std::sync::atomic::Ordering::Relaxed); + // Stopped only if it came back without a picture: a stop after the renderer's last look + // leaves a finished frame. + let cancelled = rendered.is_none() && stop.load(std::sync::atomic::Ordering::Relaxed); Done { rendered, view, map, ms: t0.elapsed().as_millis() as u64, incomplete, cancelled, archives } } From 51b61fc3482fe4ff5a9faf99e0d30eb272bb28c0 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 11 Nov 2026 02:25:54 -0500 Subject: [PATCH 4/6] fix(ui, render): stop tilted frames between bands; draw a failed flat frame on the UI thread (#1750) A stopped tilted frame (CPU or GPU) now returns before its next band, its drape and warp, and before the GPU path's CPU fallback. A flat frame the worker couldn't draw (a refused thread, a panic) is drawn on the UI thread as before instead of leaving the preview. --- crates/render/src/cancel.rs | 8 ++++++++ crates/render/src/lib.rs | 14 ++++++++++++++ crates/ui-egui/src/mapview.rs | 5 ++++- crates/ui-egui/src/tilt_settle.rs | 7 +++++++ 4 files changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/render/src/cancel.rs b/crates/render/src/cancel.rs index 8cdb20d5f2..a630136ea0 100644 --- a/crates/render/src/cancel.rs +++ b/crates/render/src/cancel.rs @@ -83,5 +83,13 @@ mod tests { DRAWN.set(0); assert!(crate::render(&mut map, &view).is_none()); assert_eq!(DRAWN.get(), 0); + // So does a tilted one, drawn band by band. + let tilted = crate::View { camera: rustgis_map::Camera { pitch: 60.0, ..rustgis_map::Camera::world() }, ..view }; + DRAWN.set(0); + assert!(crate::render(&mut map, &tilted).is_none()); + assert_eq!(DRAWN.get(), 0); + flag.store(false, Ordering::Relaxed); + assert!(crate::render(&mut map, &tilted).is_some()); + assert!(DRAWN.get() > 0); } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 138c9a5a89..5c3c3815ea 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2356,6 +2356,11 @@ fn render_tilted(map: &mut Map, view: &View, full_res_rasters: bool, sources_rea let (mut attribution, mut tiles_pending, mut tile_errors) = (Vec::::new(), false, Vec::::new()); let (mut partial, mut pending_in_place) = (Vec::::new(), Vec::::new()); for (i, b) in bands_of.into_iter().enumerate() { + // A stopped frame (see `cancel`) draws no further band, nor its drape or warp. + if cancel::requested() { + map.label_lock = lock; + return None; + } let v = band_view(view, &b); let Some(RenderOutput::Cpu(r)) = render_frame(map, &v, full_res_rasters, Backend::Cpu, Labels::Tilted(view, &mut candidates), false) @@ -2635,10 +2640,19 @@ fn gpu_turned(map: &mut Map, view: &View, full_res_rasters: bool, sources_ready: let mut plain = true; let last = bands.len().saturating_sub(1); for (i, b) in bands.iter().enumerate() { + // A stopped frame (see `cancel`) draws no further band, nor falls back to the CPU. + if cancel::requested() { + map.label_lock = lock; + return None; + } let v = band_view(view, b); let Some(RenderOutput::Gpu(scene)) = render_frame(map, &v, full_res_rasters, Backend::Gpu, Labels::Tilted(view, &mut candidates), false) else { + if cancel::requested() { + map.label_lock = lock; + return None; + } plain = false; break; }; diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index e50225209b..e2d423ab2a 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -954,7 +954,10 @@ fn main_view(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { && cam.pitch == 0.0 && app.session.map().tiles.is_empty() && (app.map.texture.is_some() || app.map.gpu_frame.is_some()) - && app.map.key.is_some_and(|k| k.rev == key.rev && k.size == key.size && k.sources == key.sources && (k.cam != key.cam || k.draft)); + && app.map.key.is_some_and(|k| k.rev == key.rev && k.size == key.size && k.sources == key.sources && (k.cam != key.cam || k.draft)) + // A frame the worker couldn't draw (it panicked, or the system refused its thread) is + // drawn on the UI thread, as before: a refused thread costs smoothness, not the frame. + && !app.map.tilt_settle.failed(key); let settling = (tilted || globe_view || tiled_flat || flat_settle) && !moving && app.ws.playing.is_none() && !hold; let mut tilt_draped = tilt_draped; // A frame finishing during a new gesture is obsolete. Drain it now so it neither holds diff --git a/crates/ui-egui/src/tilt_settle.rs b/crates/ui-egui/src/tilt_settle.rs index 4d276ee98e..6365360096 100644 --- a/crates/ui-egui/src/tilt_settle.rs +++ b/crates/ui-egui/src/tilt_settle.rs @@ -81,6 +81,12 @@ impl TiltSettle { return self.ready.is_some(); } + /// Whether the frame keyed `key` couldn't be drawn here (the worker panicked, or the system + /// refused its thread): it isn't tried again, so the caller draws it another way. + pub fn failed(&self, key: K) -> bool { + self.failed == Some(key) + } + /// The key of the frame being drawn (or drawn and not yet taken). pub fn key(&self) -> Option { #[cfg(not(target_arch = "wasm32"))] @@ -264,6 +270,7 @@ mod tests { assert!(std::time::Instant::now() < end, "the worker never ended"); std::thread::sleep(std::time::Duration::from_millis(5)); } + assert!(s.failed(1u8) && !s.failed(2u8)); s.start(&ctx, 1u8, map.clone(), view); assert!(!s.busy(), "the same frame was tried again"); s.start(&ctx, 2u8, map, view); From e02ee7ab3a1c3d10e83cf2a4cb8b02597c821ae1 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 11 Nov 2026 02:45:49 -0500 Subject: [PATCH 5/6] fix(render, ui): look at a stop by vertices too; after a tilted frame's last band (#1750) A layer of a few heavy features (a detailed coastline) now stops every 65,536 vertices as well as every 2048 features; a tilted frame stopped during its last band skips its drape and warp; a flat worker the system refuses asks for the frame that draws it on the UI thread. --- crates/render/src/cancel.rs | 9 +++++++-- crates/render/src/lib.rs | 14 ++++++++++++-- crates/ui-egui/src/mapview.rs | 4 ++++ crates/ui-egui/src/tilt_settle.rs | 3 ++- 4 files changed, 25 insertions(+), 5 deletions(-) diff --git a/crates/render/src/cancel.rs b/crates/render/src/cancel.rs index a630136ea0..2619ff4158 100644 --- a/crates/render/src/cancel.rs +++ b/crates/render/src/cancel.rs @@ -1,8 +1,9 @@ //! Stopping a frame no longer wanted (#1750). The desktop app draws a settled flat map's frame on a //! worker; when the map moves again before it is done, the frame is out of date. The worker //! installs a flag on its thread ([`install`]) and sets it to stop: the renderer looks at it between -//! layers, before each chunk of a streamed layer and every [`EVERY`] features of a layer, and a -//! frame stopped that way comes back as `None`, without its tiles, labels or effects worked out. +//! layers, between a tilted view's bands, before each chunk of a streamed layer and every +//! [`EVERY`] features or [`EVERY_VERTICES`] vertices of a layer, and a frame stopped that way comes +//! back as `None`, without its tiles, labels or effects worked out. //! With none installed (an export, the CLI, the browser) frames always finish. The flag is the //! thread's own: threads the renderer starts for a part of the frame (a raster's rows) don't look //! at it, and finish their part. A long step without a look (projecting or thinning a layer's @@ -15,6 +16,10 @@ use std::sync::atomic::{AtomicBool, Ordering}; /// How many features of a layer are drawn between looks at the flag. pub(crate) const EVERY: usize = 2048; +/// How many vertices of a layer are drawn between looks at the flag, so a layer of a few heavy +/// features (a detailed coastline) stops part-way too. +pub(crate) const EVERY_VERTICES: usize = 65_536; + thread_local! { static FLAG: RefCell>> = const { RefCell::new(None) }; } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 5c3c3815ea..60137c2cbc 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2416,6 +2416,10 @@ fn render_tilted(map: &mut Map, view: &View, full_res_rasters: bool, sources_rea } } map.label_lock = lock; + // A frame stopped during its last band goes no further (see `cancel`). + if cancel::requested() { + return None; + } match &ground { Some(g) => { drape_terrain(pm.pixels(), view, map, &kept, g); @@ -4193,14 +4197,20 @@ fn render_frame( // Polygons with stacked fills (patterns) draw them in place of their single fill. let has_fills = layer.has_fills(); let mut stacked: Vec<(&[Vec], Symbol, &[LineStroke])> = Vec::new(); + // Vertices drawn since the stop was last looked at (see `cancel`). + let mut since_look = 0usize; for (row, g) in drawn.iter().enumerate() { - // And every few thousand features of a large layer. - if row % cancel::EVERY == 0 && row > 0 && cancel::requested() { + // And every few thousand features, or vertices, of a large layer. + if (row % cancel::EVERY == 0 && row > 0 || since_look >= cancel::EVERY_VERTICES) && cancel::requested() { break; } + if since_look >= cancel::EVERY_VERTICES { + since_look = 0; + } #[cfg(test)] cancel::DRAWN.set(cancel::DRAWN.get() + 1); let Some(g) = g else { continue }; + since_look += rustgis_map::lod::vertices(g); let e = extents.get(row).copied().unwrap_or_else(|| g.extent()); // A point's marks, shifted from it, may show while the point is off the view. let marked_in = || { diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index e2d423ab2a..f22a24ba10 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -1038,6 +1038,10 @@ fn main_view(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { } let backend = if gpu_ok { rustgis_engine::render::Backend::GpuLive } else { rustgis_engine::render::Backend::Cpu }; app.map.tilt_settle.start_backend(ui.ctx(), key, app.session.map().clone(), view, backend); + // A worker the system refused wakes no frame: the next draws it here. + if flat_settle && app.map.tilt_settle.failed(key) { + ui.ctx().request_repaint(); + } } let shown = (app.map.texture.is_some() || app.map.gpu_frame.is_some()) && app.map.key.is_some_and(|k| same_view(Key { draft: false, ..k }, key)); diff --git a/crates/ui-egui/src/tilt_settle.rs b/crates/ui-egui/src/tilt_settle.rs index 6365360096..61788d4440 100644 --- a/crates/ui-egui/src/tilt_settle.rs +++ b/crates/ui-egui/src/tilt_settle.rs @@ -110,7 +110,8 @@ impl TiltSettle { } /// Asks the frame being drawn to stop (it is out of date): the renderer looks between layers, - /// before each chunk of a streamed layer and every 2048 features (see `render::cancel`), so + /// before each chunk of a streamed layer, every 2048 features or 65,536 vertices and between + /// a tilted view's bands (see `render::cancel`), so /// the worker is free again soon. The stopped frame is /// still handed back by [`TiltSettle::take`], with no picture and `cancelled` set, and its key /// may be drawn again. In the browser frames are drawn at once: there is nothing to stop. From bbead6e41d773e3f15756d962c3df7776159df57 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 11 Nov 2026 03:11:12 -0500 Subject: [PATCH 6/6] fix(render): skip a stopped chunk's labels; stop after the GPU band loop (#1750) --- crates/render/src/cancel.rs | 2 +- crates/render/src/lib.rs | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/render/src/cancel.rs b/crates/render/src/cancel.rs index 2619ff4158..dfb1707bda 100644 --- a/crates/render/src/cancel.rs +++ b/crates/render/src/cancel.rs @@ -7,7 +7,7 @@ //! With none installed (an export, the CLI, the browser) frames always finish. The flag is the //! thread's own: threads the renderer starts for a part of the frame (a raster's rows) don't look //! at it, and finish their part. A long step without a look (projecting or thinning a layer's -//! geometry for the first time, a raster) runs to its end. +//! geometry for the first time, a raster, a single feature's path) runs to its end. use std::cell::RefCell; use std::sync::Arc; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 60137c2cbc..bd2d33b213 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2712,6 +2712,10 @@ fn gpu_turned(map: &mut Map, view: &View, full_res_rasters: bool, sources_ready: cmds.extend(scene.cmds); } map.label_lock = lock; + // A frame stopped during its last band goes no further (see `cancel`). + if cancel::requested() { + return None; + } if !plain { return None; } @@ -4407,6 +4411,10 @@ fn render_frame( } else { Vec::new() }; + // A stopped frame places no labels for the rest of the layer (see `cancel`). + if cancel::requested() { + return Ok(()); + } if label_fields.iter().any(Option::is_some) { let label_factor = layer.size_factor(label_scale); // Each class's font, where it is installed. An export (`full_res_rasters`: see