diff --git a/crates/render/src/approximations.rs b/crates/render/src/approximations.rs index 5a47279947..d9757ab0ac 100644 --- a/crates/render/src/approximations.rs +++ b/crates/render/src/approximations.rs @@ -1,5 +1,6 @@ //! What frames drew otherwise than their layers ask (Never silent): a dashed line drawn solid, -//! a fill left off a block diagram's walls, ground with no height taken as 0 under a block. +//! a fill left off a block diagram's walls, ground with no height taken as 0 under a block, and, +//! in an export's drawing, a layer drawn from less than it needs (the map view says its own). //! //! The drawing code has no session to tell, and a frame comes many times a second, so a frame //! keeps what it approximated on the thread drawing it, one notice per layer and kind (its key), diff --git a/crates/render/src/frame_cache.rs b/crates/render/src/frame_cache.rs index 5b64f115d9..bea46d95c7 100644 --- a/crates/render/src/frame_cache.rs +++ b/crates/render/src/frame_cache.rs @@ -912,6 +912,34 @@ mod tests { assert_eq!(opacities(&scene), vec![100], "the raster, the squares and the points in one picture"); } + /// Drawing again gives no more of a tile layer whose server has none of its tiles in view, so a + /// frame with one is kept: restyling a layer over it draws that layer, and the layer is still said. + #[test] + fn a_frame_with_a_tile_layer_without_a_tile_in_view_is_kept() { + let (mut map, view, _, above) = map(); + crate::tiles::tests::serve(); + map.tiles.push(rustgis_map::TileLayer::new("Gone", rustgis_map::TileKind::Raster, "https://tiles.test/gone/kept/{z}/{x}/{y}.png")); + crate::render_complete(&mut map, &view).expect("drawn"); + // Another test's tiles landing meanwhile rightly draw the frame whole: a drag they fell + // in is done again. + let mut started = None; + for drag in 0..50u8 { + let before = rustgis_tiles::cache::generation(); + for step in 0..4u8 { + if let Some(l) = map.layer_mut(above) { + l.renderer = Renderer::Single(rustgis_map::Symbol { fill: Rgba::rgb(drag, 200, 30 + step), ..l.symbol(0) }); + } + started = draw(&mut map, &view); + } + if rustgis_tiles::cache::generation() == before { + break; + } + } + assert_eq!(started, Some(1), "a drag draws from the picture under the layer"); + let r = render(&mut map, &view).expect("drawn"); + assert!(r.tile_errors.iter().any(|e| e.starts_with("Gone: none of the tiles in view")), "{:?}", r.tile_errors); + } + #[test] fn a_layer_with_no_look_draws_in_every_frame() { let (mut map, view, below, _) = map(); diff --git a/crates/render/src/gpu_scene.rs b/crates/render/src/gpu_scene.rs index 3161502beb..70156066e7 100644 --- a/crates/render/src/gpu_scene.rs +++ b/crates/render/src/gpu_scene.rs @@ -55,11 +55,14 @@ pub struct GpuScene { pub tiles_pending: bool, /// Streamed layers are still reading the view: drawing again later shows them. pub data_pending: bool, - /// Tile layers that couldn't be drawn, and why. + /// Layers that couldn't be drawn in full, or whose server has none of their tiles in view, and why. pub tile_errors: Vec, + /// Those of `tile_errors` that say a layer's server has none of its tiles in view: a view drawn + /// in parts says one only when every part does. + pub absent: Vec, /// Raster layers read in place drawn from less than the view needs (a coarser level, tiles - /// they couldn't read), by id, their errors among `tile_errors`: an export refuses them. - pub partial: Vec, + /// they couldn't read), by id, each with its error (also in `tile_errors`): an export refuses them. + pub partial: Vec<(u32, String)>, /// Raster layers read in place whose tiles are still on their way, by id: drawn again as /// they land; an export that can't wait refuses them. pub pending_in_place: Vec, diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 1e0fefbad9..94eedc0d80 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -2938,9 +2938,12 @@ fn a_page_says_why_a_frame_drew_no_cast_shadows() { r.overview = Some((1000, 10)); rl.data = Some(std::sync::Arc::new(r)); let (_, said) = crate::shadows_said(|| colorbar_page(&map, Orientation::Horizontal, false, "")); + // And that its picture is less than the page needs: its file can't be read here. + let undrawn = "a layer couldn't be drawn in full, so parts of it may be empty or coarse: dem: dem.tif: "; let said = said.notices; - assert_eq!(said.len(), 1, "{said:?}"); + assert_eq!(said.len(), 2, "{said:?}"); assert!(said[0].starts_with("dem: ") && said[0].contains("read in place"), "{said:?}"); + assert!(said[1].starts_with(undrawn), "{said:?}"); // What the map view's frame said is not a page's: a clean page drawn after it says nothing. let camera = rustgis_map::Camera { center: rustgis_geom::lonlat_to_merc(Coord::new(0.5, 0.5)), res: 2000.0, bearing: 0.0, pitch: 0.0 }; crate::render(&mut map, &crate::View { width: 64.0, height: 64.0, pixels_per_point: 1.0, camera, sky: false }); @@ -2949,6 +2952,48 @@ fn a_page_says_why_a_frame_drew_no_cast_shadows() { assert!(said.notices.is_empty(), "{said:?}"); } +/// An export refused for a raster read in place says that raster's own reason, not that of a layer +/// whose name goes on from its name with a colon. +#[test] +fn a_refused_export_says_the_refused_layers_own_reason() { + crate::tiles::tests::serve(); + let mut map = ramp_map(rustgis_map::raster::RasterRenderer::Rgb { red: 0, green: 0, blue: 0 }, rustgis_map::raster::Stretch::MinMax); + let rl = map.layers.iter_mut().find_map(|l| l.raster.as_mut()).unwrap(); + rl.in_place = true; + let mut r = (**rl.data.as_ref().unwrap()).clone(); + r.overview = Some((1000, 10)); + rl.data = Some(std::sync::Arc::new(r)); + // Fails, and is drawn (and so said) before the raster. + let failing = "https://tiles.test/unknown-refused/{z}/{x}/{y}.png"; + map.tiles = vec![rustgis_map::TileLayer::new("dem: tiles", rustgis_map::TileKind::Raster, failing)]; + let camera = rustgis_map::Camera { center: rustgis_geom::lonlat_to_merc(Coord::new(0.5, 0.995)), res: 100.0, bearing: 0.0, pitch: 0.0 }; + let view = crate::View { width: 64.0, height: 64.0, pixels_per_point: 1.0, camera, sky: false }; + let drawn = crate::render_complete(&mut map, &view).unwrap(); + assert!(drawn.tile_errors.first().is_some_and(|e| e.starts_with("dem: tiles: ")), "{:?}", drawn.tile_errors); + // Nor that of one named as its error begins. + map.tiles.insert(0, rustgis_map::TileLayer::new("dem: dem.tif", rustgis_map::TileKind::Raster, failing)); + let refused = crate::render_png(&mut map, &view).unwrap_err(); + assert_eq!(refused, "dem: dem.tif: only http:// and https:// addresses are fetched, so the image isn't written"); +} + +/// A map PDF says a raster read in place that is drawn from less than it needs: unlike a PNG or a +/// GeoTIFF, it doesn't refuse one. +#[test] +fn a_map_pdf_says_a_raster_read_in_place_drawn_from_less() { + let mut map = ramp_map(rustgis_map::raster::RasterRenderer::Rgb { red: 0, green: 0, blue: 0 }, rustgis_map::raster::Stretch::MinMax); + let rl = map.layers.iter_mut().find_map(|l| l.raster.as_mut()).unwrap(); + rl.in_place = true; + let mut r = (**rl.data.as_ref().unwrap()).clone(); + r.overview = Some((1000, 10)); + rl.data = Some(std::sync::Arc::new(r)); + let camera = rustgis_map::Camera { center: rustgis_geom::lonlat_to_merc(Coord::new(0.5, 0.995)), res: 100.0, bearing: 0.0, pitch: 0.0 }; + let view = crate::View { width: 64.0, height: 64.0, pixels_per_point: 1.0, camera, sky: false }; + let (pdf, said) = crate::shadows_said(|| crate::render_drawing(&mut map, &view)); + assert!(pdf.is_ok()); + let undrawn = "a layer couldn't be drawn in full, so parts of it may be empty or coarse: dem: dem.tif: "; + assert_eq!(said.notices.iter().filter(|n| n.starts_with(undrawn)).count(), 1, "{:?}", said.notices); +} + /// A page with maps showing copies of one relief (each layer the first of its map, so with the /// same id), each under its own sun, drawn again until it has no shadows to come, as the /// Layout view draws it while they land. Panics if it never settles. @@ -5655,6 +5700,7 @@ fn a_frames_attribution_keeps_clear_of_its_grid_labels() { tiles_pending: false, data_pending: false, tile_errors: Vec::new(), + absent: Vec::new(), partial: Vec::new(), pending_in_place: Vec::new(), recorded: None, diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index d882334ae9..5284ead4a9 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -46,9 +46,11 @@ mod text; pub use text::CALLOUT_WIDTH; mod frame_cache; mod layer_meshes; +mod tile_errors; pub mod tile_mesh; mod tiles; pub mod vector; +pub use tile_errors::{tile_error_kind, tile_error_notices}; pub use tiles::{Live, live as live_tiles}; pub use rustgis_tiles; @@ -558,11 +560,14 @@ pub struct Rendered { pub tiles_pending: bool, /// Streamed layers are still reading the view: drawing again later shows them. pub data_pending: bool, - /// Tile layers that couldn't be drawn, and why. + /// Layers that couldn't be drawn in full, or whose server has none of their tiles in view, and why. pub tile_errors: Vec, + /// Those of `tile_errors` that say a layer's server has none of its tiles in view: a view drawn + /// in parts says one only when every part does. + pub absent: Vec, /// Raster layers read in place drawn from less than the view needs (a coarser level, tiles - /// they couldn't read), by id, their errors among `tile_errors`: an export refuses them. - pub partial: Vec, + /// they couldn't read), by id, each with its error (also in `tile_errors`): an export refuses them. + pub partial: Vec<(u32, String)>, /// Raster layers read in place whose tiles are still on their way, by id: drawn again as /// they land; an export that can't wait refuses them. pub pending_in_place: Vec, @@ -2903,7 +2908,8 @@ fn render_tilted( let mut kept: Vec<(View, (f64, f64), Pixmap)> = Vec::new(); let last = bands_of.len().saturating_sub(1); 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()); + let (mut partial, mut pending_in_place) = (Vec::<(u32, String)>::new(), Vec::::new()); + let mut absences = tile_errors::Bands::default(); 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() { @@ -2932,6 +2938,7 @@ fn render_tilted( return None; } // Preserve the upstream best-effort band path for ordinary providers. + absences.unknown(); continue; }; for a in r.attribution { @@ -2939,14 +2946,15 @@ fn render_tilted( attribution.push(a); } } - for e in r.tile_errors { + absences.band(&r.absent); + for e in r.tile_errors.into_iter().filter(|e| !r.absent.contains(e)) { if !tile_errors.contains(&e) { tile_errors.push(e); } } - for id in r.partial { - if !partial.contains(&id) { - partial.push(id); + for (id, why) in r.partial { + if !partial.iter().any(|(had, _)| *had == id) { + partial.push((id, why)); } } for id in r.pending_in_place { @@ -2989,6 +2997,8 @@ fn render_tilted( } } let unplaced = if map.label_display.show_unplaced { placed.unplaced } else { Vec::new() }; + let absent = absences.finish(); + tile_errors.extend(absent.iter().cloned()); Some(Rendered { pixmap: pm.into_pixmap(), labels: placed.labels, @@ -2997,6 +3007,7 @@ fn render_tilted( tiles_pending, data_pending, tile_errors, + absent, partial, pending_in_place, recorded: None, @@ -3453,7 +3464,10 @@ fn gpu_turned( let mut candidates = Vec::new(); let (mut cmds, mut clips) = (Vec::new(), Vec::new()); let (mut attribution, mut tiles_pending, mut tile_errors, mut clear) = (Vec::::new(), false, Vec::::new(), [0.0; 4]); - let (mut partial, mut pending_in_place) = (Vec::::new(), Vec::::new()); + let (mut partial, mut pending_in_place) = (Vec::<(u32, String)>::new(), Vec::::new()); + // No band says a layer has no tile in view: a map with tile layers isn't drawn here + // (`gpu_may_turn`). + let absent = Vec::new(); let mut plain = true; let last = bands.len().saturating_sub(1); for (i, b) in bands.iter().enumerate() { @@ -3505,9 +3519,9 @@ fn gpu_turned( tile_errors.push(e); } } - for id in scene.partial { - if !partial.contains(&id) { - partial.push(id); + for (id, why) in scene.partial { + if !partial.iter().any(|(had, _)| *had == id) { + partial.push((id, why)); } } for id in scene.pending_in_place { @@ -3562,6 +3576,7 @@ fn gpu_turned( tiles_pending, data_pending, tile_errors, + absent, partial, pending_in_place, tilt, @@ -5326,10 +5341,10 @@ fn render_frame( Err(e) => { let e = format!("{}: {e}", layer.name); if !tile_out.errors.contains(&e) { - tile_out.errors.push(e); + tile_out.errors.push(e.clone()); } - if !tile_out.partial.contains(&layer.id) { - tile_out.partial.push(layer.id); + if !tile_out.partial.iter().any(|(id, _)| *id == layer.id) { + tile_out.partial.push((layer.id, e)); } } }, @@ -7144,7 +7159,8 @@ fn render_frame( } let attribution = tile_out.attribution; let tiles_pending = tile_out.pending; - let tile_errors = tile_out.errors; + let absent = tile_out.absent; + let tile_errors: Vec = tile_out.errors.into_iter().chain(absent.iter().cloned()).collect(); let partial = tile_out.partial; let pending_in_place = tile_out.pending_in_place; match backend { @@ -7161,6 +7177,7 @@ fn render_frame( tiles_pending, data_pending, tile_errors, + absent, partial, pending_in_place, recorded, @@ -7190,6 +7207,7 @@ fn render_frame( tiles_pending, data_pending, tile_errors, + absent, partial, pending_in_place, tilt: None, @@ -8800,7 +8818,7 @@ fn take_said() -> ShadowsSaid { let mut notices = take_shadow_notices(); let mut keys = notices.clone(); for (kind, e) in approximations::take_keyed(&[]) { - let key = format!("approximated\0{kind}"); + let key = notice_key(&kind); if !keys.contains(&key) { keys.push(key); notices.push(e); @@ -8809,6 +8827,15 @@ fn take_said() -> ShadowsSaid { ShadowsSaid { notices, keys, to_come: SHADOWS_TO_COME.with(|c| c.replace(false)) } } +/// Starts the kind of what an export or page says of a layer drawn from less than it needs; what +/// follows is the key the map view says that layer's error under ([`tile_error_notices`]). +const UNDRAWN: &str = "\0undrawn\0"; + +/// The key a notice of `kind` is said once under, by the map view and the pages alike. +pub fn notice_key(kind: &str) -> String { + kind.strip_prefix(UNDRAWN).map_or_else(|| format!("approximated\0{kind}"), str::to_string) +} + /// What frames drawn on this thread approximated since the last call, and what map view frames /// drawn on worker threads handed over to `relays` ([`ApproximationRelay::hand_over`]), each kind /// once, as (kind, notice): what the map view says after each frame it shows, each kind once a @@ -8908,8 +8935,21 @@ fn complete(map: &mut Map, view: &View, record: bool, failed_source: &mut Option let before = (SHADOWS_TO_COME.with(|c| c.replace(false)), take_shadow_notices()); let r = complete_passes(map, view, record, failed_source, env); SHADOWS_TO_COME.with(|c| c.set(before.0 || c.get())); + let drawn = take_shadow_notices(); + // A layer drawn from less than it needs (a tile layer whose tiles failed, a raster read in + // place drawn from a coarser level) leaves its part empty or coarse, which in a finished + // picture passes for the map: whoever this draws for says it (see `shadows_said`), each layer + // and kind once. Cast shadows left out are said as such. + for e in r.iter().flat_map(|r| &r.tile_errors).filter(|e| !drawn.contains(e)) { + for (key, notice) in tile_error_notices(map, e) { + approximations::note( + format!("{UNDRAWN}{key}"), + format!("a layer couldn't be drawn in full, so parts of it may be empty or coarse: {notice}"), + ); + } + } let mut notices = before.1; - for e in take_shadow_notices() { + for e in drawn { if !notices.contains(&e) { notices.push(e); } @@ -9065,7 +9105,7 @@ pub fn render_placed(map: &mut Map, view: &View) -> Result { let approximated = approximations::take(); approximations::restore(approximated_before); let r = r?; - let tile_errors: Vec<&String> = r.tile_errors.iter().filter(|e| !shadows.contains(e)).collect(); + // Tile layers that couldn't be drawn are among what it approximated (see `complete`). let mut gaps = shadows; gaps.extend(approximated); if to_come { @@ -9083,14 +9123,6 @@ pub fn render_placed(map: &mut Map, view: &View) -> Result { .to_string(), ); } - if let Some(first) = tile_errors.first() { - let n = tile_errors.len(); - gaps.push(if n == 1 { - format!("a tile layer couldn't be drawn, so its part is empty: {first}") - } else { - format!("{n} tile layers couldn't be drawn, so their parts are empty; the first: {first}") - }); - } revisions.finish(map, None, Some(Placed { pixmap: r.pixmap, credits: r.attribution, gaps }), "could not draw the map") } @@ -9108,12 +9140,7 @@ fn render_exported(map: &mut Map, view: &View) -> Result { if let Some(l) = r.pending_in_place.first().and_then(|id| map.layers.iter().find(|l| l.id == *id)) { return Err(format!("{}: its tiles are still on their way: export again once the map has drawn it", l.name)); } - if let Some(l) = r.partial.first().and_then(|id| map.layers.iter().find(|l| l.id == *id)) { - // Its own error, named by the layer, says why; else the general one. - let why = r.tile_errors.iter().find(|e| e.starts_with(&format!("{}: ", l.name))).cloned(); - let why = why.unwrap_or_else(|| { - format!("{}: drawn from less than the view needs (a coarser level, or tiles that couldn't be read)", l.name) - }); + if let Some((_, why)) = r.partial.first() { return Err(format!("{why}, so the image isn't written")); } Ok(r) diff --git a/crates/render/src/native_tiles.rs b/crates/render/src/native_tiles.rs index a30e1318eb..7da414a891 100644 --- a/crates/render/src/native_tiles.rs +++ b/crates/render/src/native_tiles.rs @@ -144,9 +144,19 @@ fn stand_ins(base: &str, how: &How, at: &At) -> Vec<(String, [f64; 4])> { } } -/// Draws the layer over `pm` (the view's pixels), its pictures asked for: whether some are still -/// on their way, and the error of one that failed. -pub(crate) fn draw(pm: &mut Pixmap, n: &Native, t: &TileLayer, view: &View, flat: &Flat) -> (bool, Option) { +/// What drawing a layer in the map's system found. +#[derive(Default)] +pub(crate) struct Found { + /// Some of its pictures are still on their way. + pub pending: bool, + /// The error of one that failed. + pub error: Option, + /// That its server has none of its tiles in view (see [`rustgis_tiles::Drawn::absent`]). + pub absent: Option, +} + +/// Draws the layer over `pm` (the view's pixels), its pictures asked for. +pub(crate) fn draw(pm: &mut Pixmap, n: &Native, t: &TileLayer, view: &View, flat: &Flat) -> Found { let cam = view.camera; let (w, h, k) = (view.width, view.height, view.pixels_per_point.max(0.01)); let tr = &n.transformer; @@ -163,20 +173,20 @@ pub(crate) fn draw(pm: &mut Pixmap, n: &Native, t: &TileLayer, view: &View, flat } } let (Some(a), Some(b)) = (to_native(cam.to_map(w / 2.0, h / 2.0, w, h)), to_native(cam.to_map(w / 2.0 + 1.0, h / 2.0, w, h))) else { - return (false, None); + return Found::default(); }; // The system's units per pixel its tiles are fetched for: the map's pixmap's on a HiDPI // display when sharp tiles are on, up to twice a logical pixel's detail; else a logical // pixel's (#2390). let per_px = (b.x - a.x).hypot(b.y - a.y) / f64::from(rustgis_tiles::template::detail(k as f32)); if !(lo.0 < hi.0 && lo.1 < hi.1 && per_px.is_finite() && per_px > 0.0) { - return (false, None); + return Found::default(); } let mut area = [lo.0, lo.1, hi.0, hi.1]; if let Some(l) = n.area { area = [area[0].max(l[0]), area[1].max(l[1]), area[2].min(l[2]), area[3].min(l[3])]; if !(area[0] < area[2] && area[1] < area[3]) { - return (false, None); + return Found::default(); } } let pictures = match &n.how { @@ -191,6 +201,7 @@ pub(crate) fn draw(pm: &mut Pixmap, n: &Native, t: &TileLayer, view: &View, flat let opacity = t.opacity.clamp(0.0, 1.0); let quality = sampling(t); let (mut pending, mut error) = (false, None); + let (asked, mut not_there, mut first_status) = (pictures.len(), 0, None); for p in pictures { // A WMTS tile past the service's coverage is routine; a WMS picture (any area asked) isn't. let state = if matches!(n.how, How::Tiles(_)) { cache::get_tile(&p.url, Want::Image) } else { cache::get(&p.url, Want::Image) }; @@ -216,11 +227,15 @@ pub(crate) fn draw(pm: &mut Pixmap, n: &Native, t: &TileLayer, view: &View, flat // A WMTS tile the service doesn't have (past its coverage) is left clear, as the warped // tiles leave it; any other failure, and a WMS's 4xx (it draws any area), is the // layer's error. - State::Failed(e) if matches!(n.how, How::Tiles(_)) && rustgis_tiles::warp::missing(&e) => {} + State::Failed(e) if matches!(n.how, How::Tiles(_)) && rustgis_tiles::warp::missing(&e) => { + not_there += 1; + first_status = first_status.or_else(|| cache::http_status(&e)); + } State::Failed(e) => error = Some(e), } } - (pending, error) + let absent = first_status.filter(|_| not_there == asked).map(rustgis_tiles::none_on_the_server); + Found { pending, error, absent } } /// A WMS layer's own tiles over `area`: at the power of two of the system's units per pixel at diff --git a/crates/render/src/tile_errors.rs b/crates/render/src/tile_errors.rs new file mode 100644 index 0000000000..58c8723e30 --- /dev/null +++ b/crates/render/src/tile_errors.rs @@ -0,0 +1,150 @@ +//! What the errors of a drawing's layers are said as, by the map view and by every export alike. + +use rustgis_map::Map; + +/// The notices for a drawing's error, one for each of its kinds (joined by "; "), each with the +/// key it is said once under: its layer and its kind without counts ([`tile_error_kind`]), as the +/// counts change each time the map moves or a page is drawn again. +pub fn tile_error_notices(map: &Map, e: &str) -> Vec<(String, String)> { + let (layer, why) = error_layer(map, e); + why.split("; ") + .map(|kind| { + let notice = if layer.is_empty() { kind.to_string() } else { format!("{layer}: {kind}") }; + (format!("{layer}\0{}", tile_error_kind(kind)), notice) + }) + .collect() +} + +/// A drawing's error (`"{layer}: {why}"`, see [`crate::Rendered::tile_errors`]) as the layer it names +/// and why. The layer is the longest name of `map`'s tile or data layers the error starts with, +/// so a layer named "Imagery: 2020" isn't taken for one named "Imagery". An error naming none of +/// them is split at its first ": "; one without any is all why. +fn error_layer<'a>(map: &Map, e: &'a str) -> (&'a str, &'a str) { + let named = map + .tiles + .iter() + .map(|t| t.name.as_str()) + .chain(map.layers.iter().map(|l| l.name.as_str())) + .filter_map(|n| Some((e.get(..n.len())?, e.strip_prefix(n)?.strip_prefix(": ")?))) + .max_by_key(|(layer, _)| layer.len()); + named.or_else(|| e.split_once(": ")).unwrap_or(("", e)) +} + +/// What the bands of a tilted view say of layers whose server has none of their tiles in view: the +/// view says it of a layer only when every band does, as one that drew some of its tiles, or is +/// still waiting for them, shows the others' ground to be past its coverage or not known yet. +#[derive(Default)] +pub(crate) struct Bands(Option>); + +impl Bands { + /// A band that says `absent`. + pub(crate) fn band(&mut self, absent: &[String]) { + match &mut self.0 { + Some(all) => all.retain(|e| absent.iter().any(|other| without_status(other) == without_status(e))), + None => self.0 = Some(absent.to_vec()), + } + } + + /// A band that couldn't be drawn, which might have had some of any layer's tiles. + pub(crate) fn unknown(&mut self) { + self.0 = Some(Vec::new()); + } + + /// What every band says. + pub(crate) fn finish(self) -> Vec { + self.0.unwrap_or_default() + } +} + +/// An absence without the status it was answered with and what follows from that: a server may +/// answer 404 for one band's tiles and 410 for another's, and has neither. +fn without_status(absent: &str) -> &str { + absent.rsplit_once(" (HTTP ").map_or(absent, |(what, _)| what) +} + +/// Tile error reason `e` without its counts of tiles ("12 tiles left out", "3 tiles are partial", +/// "2 warped tile components left out" each become `#`) or what follows the host in the +/// addresses it names (each tile's differs, by its z/x/y): what it says beside them, the layer, +/// the server and the reason, is its kind. +pub fn tile_error_kind(e: &str) -> String { + let unaddressed = without_urls(e); + let mut out = String::with_capacity(unaddressed.len()); + let mut rest = unaddressed.as_str(); + while let Some(i) = rest.find(|c: char| c.is_ascii_digit()) { + let (head, tail) = rest.split_at(i); + out.push_str(head); + let n = tail.find(|c: char| !c.is_ascii_digit()).unwrap_or(tail.len()); + let (digits, after) = tail.split_at(n); + let starts_word = !out.ends_with(|c: char| c.is_alphanumeric() || c == '.' || c == ','); + if starts_word && (after.starts_with(" tiles ") || after.starts_with(" warped tile")) { + out.push('#'); + } else { + out.push_str(digits); + } + rest = after; + } + out.push_str(rest); + out +} + +/// `e` with the rest of each web address in it after its host (`http://` or `https://`, any case, +/// up to the next space or its end) replaced by `/…`: the path and query, which name the tile, +/// go; the server stays, so another server's failure is a kind of its own. +fn without_urls(e: &str) -> String { + // ASCII lower case keeps each byte where it is, so positions in it are positions in `e`. + let lower = e.to_ascii_lowercase(); + let mut out = String::with_capacity(e.len()); + let mut at = 0; + while let Some(i) = lower[at..].find("http://").into_iter().chain(lower[at..].find("https://")).min().map(|i| at + i) { + out.push_str(&e[at..i]); + let end = e[i..].find(char::is_whitespace).map_or(e.len(), |n| i + n); + let url = &e[i..end]; + let host_from = url.find("://").map_or(0, |n| n + 3); + let host_end = url[host_from..].find(['/', '?', '#']).map_or(url.len(), |n| host_from + n); + out.push_str(&url[..host_end]); + if host_end < url.len() { + out.push_str("/…"); + } + at = end; + } + out.push_str(&e[at..]); + out +} + +#[cfg(test)] +mod tests { + use rustgis_map::{Map, TileKind, TileLayer}; + + /// Bands agree on what has no tile in view whatever status each was answered with, and on each + /// of a layer's sources by itself. + #[test] + fn bands_agree_whatever_the_status() { + let of = |source: &str, status| format!("L: its source \"{source}\": {}", rustgis_tiles::none_on_the_server(status)); + let mut bands = super::Bands::default(); + bands.band(&[of("a", 404), of("b", 404)]); + bands.band(&[of("a", 410)]); + assert_eq!(bands.finish(), [of("a", 404)]); + } + + /// An error is said under the layer it names, whatever colons the name holds, each kind under + /// a key of its own that no count changes. + #[test] + fn errors_are_said_under_the_layers_own_name() { + let mut map = Map::new("Map"); + map.tiles = ["Imagery", "Imagery: 2020", "Imagery: 2021"] + .map(|n| TileLayer::new(n, TileKind::Raster, "https://t.test/{z}/{x}/{y}")) + .to_vec(); + let said = |e: &str| super::tile_error_notices(&map, e); + let a = said("Imagery: 2020: 3 tiles left out: refused; sprite left out"); + assert_eq!( + a.iter().map(|(_, n)| n.as_str()).collect::>(), + ["Imagery: 2020: 3 tiles left out: refused", "Imagery: 2020: sprite left out"] + ); + let b = said("Imagery: 2021: 3 tiles left out: refused; sprite left out"); + assert!(a.iter().all(|(k, _)| b.iter().all(|(other, _)| k != other)), "{a:?} {b:?}"); + assert_eq!(a, said("Imagery: 2020: 3 tiles left out: refused; sprite left out")); + assert_eq!(a[0].0, said("Imagery: 2020: 9 tiles left out: refused")[0].0, "another count, the same kind"); + assert_eq!(said("Roads: refused")[0].1, "Roads: refused", "no such layer: its first colon"); + assert_eq!(said("refused")[0].1, "refused"); + } +} diff --git a/crates/render/src/tiles.rs b/crates/render/src/tiles.rs index 9f3555cbd6..765e99a830 100644 --- a/crates/render/src/tiles.rs +++ b/crates/render/src/tiles.rs @@ -27,9 +27,12 @@ pub(crate) struct TileOutput { pub attribution: Vec, pub pending: bool, pub errors: Vec, + /// Layers whose server has none of their tiles in view: said with the errors, but drawing + /// again gives no more, so a frame with one is kept as any other (see `frame_cache`). + pub absent: Vec, /// Raster layers read in place drawn from less than the view needs (a coarser level, tiles - /// they couldn't read), by id: shown, with the error among `errors`; an export refuses them. - pub partial: Vec, + /// they couldn't read), by id, each with its error (also in `errors`): shown; an export refuses them. + pub partial: Vec<(u32, String)>, /// Raster layers read in place whose tiles are still on their way, by id. pub pending_in_place: Vec, } @@ -45,6 +48,7 @@ impl TileOutput { } self.pending |= o.pending; self.errors.extend(o.errors); + self.absent.extend(o.absent); } } @@ -349,7 +353,9 @@ fn live_inner(spec: &Spec, opacity: f32, view: &View) -> Option { let coarse = Frame { m_per_px: frame.m_per_px * 8.0, ..frame }; let _ = rustgis_tiles::place_raster(spec, opacity, &coarse, &fetch, &fetch); let origin = [view.camera.center.x, view.camera.center.y]; - Some(Live { quads: p.tiles.iter().map(|q| quad(q, origin)).collect(), pending: p.pending, error: p.error }) + let said: Vec = p.error.into_iter().chain(p.absent).collect(); + let error = (!said.is_empty()).then(|| said.join("; ")); + Some(Live { quads: p.tiles.iter().map(|q| quad(q, origin)).collect(), pending: p.pending, error }) } /// Draws the map's visible tile layers at `which` (indices, top first), bottom first. With @@ -395,7 +401,7 @@ pub(crate) fn draw( *g.dirty = true; } let attribution = if t.attribution.trim().is_empty() { Vec::new() } else { vec![t.attribution.clone()] }; - collect(rustgis_tiles::Drawn { labels: Vec::new(), attribution, pending, error }, t, &mut out); + collect(rustgis_tiles::Drawn { labels: Vec::new(), attribution, pending, error, absent: None }, t, &mut out); continue; } // A vector tile style as meshes, made once a tile and level and drawn at any zoom @@ -413,8 +419,13 @@ pub(crate) fn draw( if !tiles.is_empty() { g.cmds.push(DrawCmd::TileMeshes { tiles }); } - let d = - rustgis_tiles::Drawn { labels: v.labels, attribution: v.attribution, pending: v.pending || waiting, error: v.error }; + let d = rustgis_tiles::Drawn { + labels: v.labels, + attribution: v.attribution, + pending: v.pending || waiting, + error: v.error, + absent: None, + }; collect(d, t, &mut out); continue; } @@ -435,7 +446,13 @@ pub(crate) fn draw( 0 }; g.cmds.push(DrawCmd::LiveTiles { name: t.name.clone(), spec: s, opacity: t.opacity, archive_revision }); - let d = rustgis_tiles::Drawn { labels: Vec::new(), attribution: p.attribution, pending: p.pending, error: p.error }; + let d = rustgis_tiles::Drawn { + labels: Vec::new(), + attribution: p.attribution, + pending: p.pending, + error: p.error, + absent: p.absent, + }; collect(d, t, &mut out); continue; } @@ -451,7 +468,13 @@ pub(crate) fn draw( if !p.tiles.is_empty() { g.cmds.push(DrawCmd::Tiles { origin, tiles: p.tiles.iter().map(|q| quad(q, origin)).collect() }); } - let d = rustgis_tiles::Drawn { labels: p.labels, attribution: p.attribution, pending: p.pending, error: p.error }; + let d = rustgis_tiles::Drawn { + labels: p.labels, + attribution: p.attribution, + pending: p.pending, + error: p.error, + absent: p.absent, + }; collect(d, t, &mut out); continue; } @@ -490,7 +513,7 @@ pub(crate) fn draw( run.clear(); if let Some((pending, error)) = crate::single_image::draw(pm, &req, t, view, flat) { let attribution = if t.attribution.trim().is_empty() { Vec::new() } else { vec![t.attribution.clone()] }; - collect(rustgis_tiles::Drawn { labels: Vec::new(), attribution, pending, error }, t, &mut out); + collect(rustgis_tiles::Drawn { labels: Vec::new(), attribution, pending, error, absent: None }, t, &mut out); continue; } } @@ -503,9 +526,9 @@ pub(crate) fn draw( }; mosaic(pm, &run, view, place, &mut out); run.clear(); - let (pending, error) = crate::native_tiles::draw(pm, &n, t, view, flat); + let crate::native_tiles::Found { pending, error, absent } = crate::native_tiles::draw(pm, &n, t, view, flat); let attribution = if t.attribution.trim().is_empty() { Vec::new() } else { vec![t.attribution.clone()] }; - collect(rustgis_tiles::Drawn { labels: Vec::new(), attribution, pending, error }, t, &mut out); + collect(rustgis_tiles::Drawn { labels: Vec::new(), attribution, pending, error, absent }, t, &mut out); } mosaic(pm, &run, view, place, &mut out); out @@ -524,6 +547,10 @@ fn collect(d: rustgis_tiles::Drawn, t: &TileLayer, out: &mut TileOutput) { if let Some(e) = d.error { out.errors.push(format!("{name}: {e}")); } + if let Some(e) = d.absent { + // One for each of a style's sources: a tilted view's bands may agree on some of them. + out.absent.extend(e.split("; ").map(|e| format!("{name}: {e}"))); + } // The layer's opacity fades its text and icons as it fades the rest of what it draws (#1358). let _layer = crate::approximations::NamedLayer::new(name); out.labels.extend(d.labels.into_iter().filter_map(tile_label).map(|(l, p)| (fade(l, t.opacity), p))); @@ -988,7 +1015,22 @@ pub(crate) mod tests { let _ = tx.send(done); return; } - if url.starts_with("https://tiles.test/red/") || url.starts_with("https://tiles.test/split/11/") { + // Under `gone/`, a retired service: no tile at all. Under `edge/`, one with the + // tiles of even columns only, as at its coverage's edge. + let column = ["https://tiles.test/edge/", "https://wmts.test/edge/"] + .iter() + .find_map(|p| url.strip_prefix(p)) + .and_then(|p| p.split('/').nth(1)?.parse::().ok()); + let gone = ["https://tiles.test/gone/", "https://wmts.test/gone/"].iter().any(|p| url.starts_with(p)); + // Under `deep/`, one with no tile above zoom 8. + let deep = url.strip_prefix("https://tiles.test/deep/").and_then(|p| p.split('/').next()?.parse::().ok()); + if gone || deep.is_some_and(|z| z < 8) || column.is_some_and(|x| x % 2 == 1) { + done(Err("http status: 404".into())); + } else if url.starts_with("https://tiles.test/red/") + || url.starts_with("https://tiles.test/split/11/") + || column.is_some() + || deep.is_some() + { done(Ok(color(220, 20, 20))); } else if url.starts_with("https://tiles.test/split/13/") { done(Ok(color(20, 20, 220))); @@ -1055,6 +1097,11 @@ pub(crate) mod tests { } else if url == "https://tiles.test/style.json" { let style = r##"{"version": 8, "sources": {}, "layers": [{"id": "bg", "type": "background", "paint": {"background-color": "#2050e0"}}]}"##; done(Ok(style.as_bytes().to_vec())); + } else if let Some(there) = url.strip_prefix("https://tiles.test/gone-style/") { + let source = |kind: &str| serde_json::json!({"type": "raster", "tiles": [format!("https://tiles.test/{kind}/{{z}}/{{x}}/{{y}}.png")]}); + let style = serde_json::json!({"version": 8, "sources": {"there": source(there), "retired": source("gone")}, + "layers": [{"id": "a", "type": "raster", "source": "there"}, {"id": "b", "type": "raster", "source": "retired"}]}); + done(Ok(serde_json::to_vec(&style).unwrap())); } else if url == "https://tiles.test/missing-source-style.json" { let style = serde_json::json!({"version": 8, "sources": { @@ -1727,6 +1774,160 @@ pub(crate) mod tests { assert!(!live.quads.is_empty(), "the valid raster layer still draws"); } + /// A tile layer whose server has none of the tiles in view (a retired service) says so, in the + /// drawing and in an export of it; one missing only some, as at its coverage's edge, doesn't. + #[test] + fn a_tile_layer_without_a_tile_in_view_says_so() { + serve(); + // Centred where columns 33 and 34 of zoom 6 meet (67 and 68 of zoom 7): an odd and an + // even column in view at either. + let camera = Camera { center: lonlat_to_merc(Coord::new(11.25, 50.0)), res: 2000.0, bearing: 0.0, pitch: 0.0 }; + let view = View { width: 200.0, height: 100.0, pixels_per_point: 1.0, camera, sky: false }; + let mut map = Map::new("Map"); + map.basemap = rustgis_map::Basemap::Blank; + map.tiles.push(TileLayer::new("Retired", TileKind::Raster, "https://tiles.test/gone/{z}/{x}/{y}.png")); + let r = crate::render_complete(&mut map, &view).unwrap(); + let [error] = &r.tile_errors[..] else { panic!("{:?}", r.tile_errors) }; + assert!(error.starts_with("Retired: none of the tiles in view are on the server (HTTP 404): "), "{error}"); + let (png, said) = crate::shadows_said(|| crate::render_png(&mut map, &view)); + assert!(png.is_ok()); + assert_eq!(said.notices, [format!("a layer couldn't be drawn in full, so parts of it may be empty or coarse: {error}")]); + // Under the key the map view says it under: between them, they say it once. + let keys: Vec = crate::tile_error_notices(&map, error).into_iter().map(|(key, _)| key).collect(); + assert_eq!(said.keys, keys); + let (placed, _) = crate::shadows_said(|| crate::render_placed(&mut map, &view)); + assert_eq!( + placed.unwrap().gaps, + [format!("a layer couldn't be drawn in full, so parts of it may be empty or coarse: {error}")], + "said once" + ); + + map.tiles = vec![TileLayer::new("Edge", TileKind::Raster, "https://tiles.test/edge/{z}/{x}/{y}.png")]; + let r = crate::render_complete(&mut map, &view).unwrap(); + assert!(r.tile_errors.is_empty(), "{:?}", r.tile_errors); + let (_, said) = crate::shadows_said(|| crate::render_png(&mut map, &view)); + assert!(said.notices.is_empty(), "{:?}", said.notices); + // Some of it drew: red where an even column's tile is, clear where an odd one's isn't. + let reds = (0..200).filter(|x| r.pixmap.pixel(*x, 50).is_some_and(|p| p.red() > 200 && p.green() < 60)).count(); + assert!(reds > 0 && reds < 200, "{reds}"); + } + + /// A WMTS layer drawn in the map's own system says when its server has none of its tiles in + /// view; one missing only some doesn't. + #[test] + fn a_wmts_layer_in_its_own_system_without_a_tile_in_view_says_so() { + use rustgis_data::ogc::warp::{Grid, Matrix, Warp}; + serve(); + let matrix = + Matrix { id: "m0".into(), left: 2_420_000.0, top: 1_350_000.0, cell: 5.0, tile_w: 256, tile_h: 256, cols: 5000, rows: 5000 }; + let says = |kind: &str| { + let url = Warp { epsg: 2056, grid: Grid::Tiles(vec![matrix.clone()]), area: None, systems: Vec::new() } + .address(&format!("https://wmts.test/{kind}/{{nm}}/{{ncol}}/{{nrow}}.png")); + let mut map = Map::new("Map"); + map.basemap = rustgis_map::Basemap::Blank; + map.graticule = false; + map.tiles.push(TileLayer::new("WMTS", TileKind::Raster, url)); + map.set_projection(Projection::Custom("EPSG:2056".into())); + let center = map.to_map(Coord::new(7.4474, 46.948)).unwrap(); + let view = View { + width: 800.0, + height: 100.0, + pixels_per_point: 1.0, + camera: Camera { center, res: 5.0, bearing: 0.0, pitch: 0.0 }, + sky: false, + }; + let r = crate::render_complete(&mut map, &view).unwrap(); + let reds = (0..800).filter(|x| r.pixmap.pixel(*x, 50).is_some_and(|p| p.red() > 200 && p.green() < 60)).count(); + (r.tile_errors, reds) + }; + let (said, reds) = says("gone"); + assert!(matches!(&said[..], [e] if e.starts_with("WMTS: none of the tiles in view are on the server (HTTP 404)")), "{said:?}"); + assert_eq!(reds, 0); + let (said, reds) = says("edge"); + assert!(said.is_empty(), "{said:?}"); + assert!(reds > 0 && reds < 800, "some of its tiles are there: {reds}"); + } + + /// A tilted view, drawn in bands, says that a layer has no tile in view only when no band has + /// one: a far band past a layer's coverage, drawn at a lower zoom, says nothing of the view. + #[test] + fn a_tilted_view_says_a_layer_has_no_tile_only_of_all_its_bands() { + use crate::{Backend, RenderOutput}; + serve(); + let camera = Camera { center: lonlat_to_merc(Coord::new(11.25, 50.0)), res: 300.0, bearing: 0.0, pitch: 65.0 }; + let view = View { width: 300.0, height: 300.0, pixels_per_point: 1.0, camera, sky: false }; + assert!(camera.tilt_bands(view.width, view.height).len() > 1, "drawn in bands"); + let says = |kind: &str| { + let mut map = Map::new("Map"); + map.basemap = rustgis_map::Basemap::Blank; + map.graticule = false; + map.tiles.push(TileLayer::new("Layer", TileKind::Raster, format!("https://tiles.test/{kind}/{{z}}/{{x}}/{{y}}.png"))); + let drawn = crate::render_complete(&mut map, &view).unwrap(); + let reds = drawn.pixmap.pixels().iter().filter(|p| p.red() > 200 && p.green() < 60).count(); + let cpu = drawn.tile_errors; + // Asked of the GPU, a tilted map with a tile layer is drawn on the CPU too. + let Some(RenderOutput::Cpu(asked)) = crate::render_backend(&mut map, &view, Backend::Gpu) else { panic!("a CPU frame") }; + (cpu, asked.tile_errors, reds) + }; + let none = |e: &Vec| matches!(&e[..], [e] if e.starts_with("Layer: none of the tiles in view")); + let (cpu, gpu, reds) = says("gone"); + assert!(none(&cpu) && none(&gpu) && reds == 0, "{cpu:?} {gpu:?} {reds}"); + let (cpu, gpu, reds) = says("deep"); + assert!(cpu.is_empty() && gpu.is_empty() && reds > 0, "{cpu:?} {gpu:?} {reds}"); + } + + /// A style of several sources names the one without a tile in view: the others drew theirs. + #[test] + fn a_style_names_its_source_without_a_tile_in_view() { + serve(); + let camera = Camera { center: lonlat_to_merc(Coord::new(11.25, 50.0)), res: 2000.0, bearing: 0.0, pitch: 0.0 }; + let view = View { width: 200.0, height: 100.0, pixels_per_point: 1.0, camera, sky: false }; + let mut map = Map::new("Map"); + map.basemap = rustgis_map::Basemap::Blank; + map.tiles.push(TileLayer::new("Style", TileKind::Style, "https://tiles.test/gone-style/red")); + let r = crate::render_complete(&mut map, &view).unwrap(); + let said = "Style: its source \"retired\": none of the tiles in view are on the server (HTTP 404)"; + assert!(matches!(&r.tile_errors[..], [e] if e.starts_with(said)), "{:?}", r.tile_errors); + assert!(r.pixmap.pixel(100, 50).is_some_and(|p| p.red() > 200 && p.green() < 60), "the other source drew"); + let live = place_said(&map.tiles[0], &view); + assert_eq!(live.as_deref(), r.tile_errors[0].strip_prefix("Style: "), "placed for the GPU, the same"); + // Both of them: each said by itself. + map.tiles = vec![TileLayer::new("Style", TileKind::Style, "https://tiles.test/gone-style/gone")]; + let said = crate::render_complete(&mut map, &view).unwrap().tile_errors; + let of = |id: &str| said.iter().filter(|e| e.starts_with(&format!("Style: its source \"{id}\": none of the tiles"))).count(); + assert_eq!((said.len(), of("there"), of("retired")), (2, 1, 1), "{said:?}"); + } + + /// What a raster tile layer placed for the GPU says. + fn place_said(t: &TileLayer, view: &View) -> Option { + // It fetches past the view: asked again once those are here. + super::live(&super::spec(t), 1.0, view)?; + rustgis_tiles::cache::wait(std::time::Duration::from_secs(60)); + super::live(&super::spec(t), 1.0, view).and_then(|l| l.error) + } + + /// What a PNG export of `tiles` (name, address) says. + fn export_says(tiles: &[(&str, &str)]) -> Vec { + serve(); + let camera = Camera { center: lonlat_to_merc(Coord::new(11.25, 50.0)), res: 2000.0, bearing: 0.0, pitch: 0.0 }; + let view = View { width: 200.0, height: 100.0, pixels_per_point: 1.0, camera, sky: false }; + let mut map = Map::new("Map"); + map.basemap = rustgis_map::Basemap::Blank; + map.tiles = tiles.iter().map(|(name, url)| TileLayer::new(*name, TileKind::Raster, *url)).collect(); + crate::shadows_said(|| crate::render_png(&mut map, &view)).1.notices + } + + /// Two layers of one name that fail differently are both said. + #[test] + fn same_named_layers_failing_differently_are_both_said() { + let said = export_says(&[ + ("Twin", "https://tiles.test/gone/{z}/{x}/{y}.png"), + ("Twin", "https://tiles.test/unknown-twin/{z}/{x}/{y}.png"), + ]); + assert!(said.iter().any(|n| n.contains("Twin: none of the tiles in view")), "{said:?}"); + assert!(said.iter().any(|n| n.contains("tiles left out: 404")), "{said:?}"); + } + /// A view across the antimeridian on the globe draws the tiles on both sides of it: the /// mosaic once ran from the westernmost point sampled east of 180° to the easternmost west /// of it, and left out the strip between 180° and the nearest sample (#223). diff --git a/crates/tiles/src/cache.rs b/crates/tiles/src/cache.rs index e59970d5b0..597a83645e 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -6937,7 +6937,8 @@ Connection: close assert!(crate::s3::prepare(&child).is_err()); } - /// A cached DNS refusal reaches the drawing, while ordinary missing tiles stay quiet. + /// A cached DNS refusal reaches the drawing, while a missing tile is said only as the server + /// having none of the tiles in view, not as a failure of its own. #[test] fn cached_destination_failures_reach_raster_drawing() { let _turn = turn(); @@ -6959,7 +6960,9 @@ Connection: close draw_cached_raster(&url, from.clone()); wait(std::time::Duration::from_secs(2)); let (image, drawn) = draw_cached_raster(&url, from.clone()); + let missing = crate::draw::none_on_the_server(404); assert_eq!(drawn.error.is_some(), case == "local", "{case}: {:?}", drawn.error); + assert_eq!(drawn.absent, (case == "missing").then_some(missing), "{case}"); assert_eq!(image.pixel(32, 32).unwrap().alpha() > 0, case == "public"); } } diff --git a/crates/tiles/src/draw.rs b/crates/tiles/src/draw.rs index 6de12bcc25..01ad79e74f 100644 --- a/crates/tiles/src/draw.rs +++ b/crates/tiles/src/draw.rs @@ -50,6 +50,9 @@ pub struct Drawn { /// Some of it is still on its way: drawing again later shows more. pub pending: bool, pub error: Option, + /// That its server has none of its tiles in view ([`none_on_the_server`]): said as an error is, + /// but drawing again gives no more. + pub absent: Option, } /// Retains each distinct refusal alongside any earlier source or sprite warning. @@ -82,6 +85,8 @@ pub(crate) struct TileSelection { pub(crate) mesh_gaps: bool, /// A failed or partial read may supply more pixels after the tile cache changes. pub(crate) retry: bool, + /// See [`Drawn::absent`]. + pub(crate) absent: Option, } /// What of a resolved style was left out, as a drawing's error (the style still draws): what @@ -172,7 +177,7 @@ pub fn draw(pm: &mut Pixmap, spec: &Spec, opacity: f32, frame: &Frame, labels: b let (w, h) = (pm.width(), pm.height()); // A style drawing vector shapes draws them from tile pictures drawn once (see `picture`): // a map moving across them only puts them in place. - if let Some(pictures) = crate::picture::cover(&r, frame, &frame.extent(w, h), None, &mut out.pending, &mut out.error) { + if let Some(pictures) = crate::picture::cover(&r, frame, &frame.extent(w, h), None, &mut out.pending, &mut out.error, &mut out.absent) { for it in &pictures { // A picture already holds its raster layers as their `raster-resampling` drew them // (crisp blocks for `nearest`): placed between its zoom levels it is blended as the @@ -288,6 +293,9 @@ pub(crate) fn draw_layers( let reach = Extent::new(view.min_x - pad, view.min_y - pad, view.max_x + pad, view.max_y + pad); let selected = tiles_in(src, &reach, None, frame, zoom, &mut out.pending, &mut out.error); retry |= selected.retry; + if let Some(none) = selected.absent { + add_error(&mut out.absent, of_source(r, src_id, none)); + } items.insert(src_id.to_string(), selected.items); } let Some(list) = items.get(src_id) else { continue }; @@ -372,6 +380,9 @@ pub struct PlacedTiles { pub attribution: Vec, pub pending: bool, pub error: Option, + /// That its server has none of its tiles in view ([`none_on_the_server`]): said as an error is, + /// but drawing again gives no more. + pub absent: Option, } /// `spec` as placed tiles over `view` (fetching those missing) and out to `reach` (only those @@ -422,7 +433,7 @@ fn place_as( } // Without pictures, a style drawing shapes is left to the check below (no raster layers only). if let Some(pictures) = - pictures.then(|| crate::picture::cover(&r, frame, view, Some(reach), &mut out.pending, &mut out.error)).flatten() + pictures.then(|| crate::picture::cover(&r, frame, view, Some(reach), &mut out.pending, &mut out.error, &mut out.absent)).flatten() { let opacity = opacity.clamp(0.0, 1.0); out.tiles = @@ -451,6 +462,9 @@ fn place_as( if !items.contains_key(src_id) { let Some(src) = r.style.sources.iter().find(|s| s.0 == src_id).map(|s| &s.1) else { continue }; let list = tiles_in(src, view, Some(reach), frame, zoom, &mut out.pending, &mut out.error); + if let Some(none) = list.absent { + add_error(&mut out.absent, of_source(&r, src_id, none)); + } items.insert(src_id, list.items); } let o = (layer.raster_opacity(zoom) * opacity).clamp(0.0, 1.0); @@ -630,7 +644,10 @@ fn raster_zoom(frame: &Frame, view: &Extent, tile_size: u32, min_zoom: u8, max_z /// The tiles of a source in view and out to `reach` (those in the cache only), with stand-ins /// for those not here yet. Expanded destinations retain the supplying document's reach; /// refused tiles are counted in `error` and network history without requesting or reusing bytes. Valid -/// tiles still draw, even when another shard of the same source is refused. +/// tiles still draw, even when another shard of the same source is refused. A picture tile the +/// server hasn't (404, 410) is routine past a source's coverage and left clear unsaid, but when +/// the server has none of those in view, which is how a moved or retired service looks, that +/// is its `absent` ([`none_on_the_server`]). pub(crate) fn tiles_in( src: &Source, view: &Extent, @@ -640,6 +657,8 @@ pub(crate) fn tiles_in( pending: &mut bool, error: &mut Option, ) -> TileSelection { + // Only a source of pictures says it has no tile in view (see `none_on_the_server`). + let pictures = matches!(src, Source::Raster { .. }); let (tiles, from, min_z, max_z, want, z) = match src { Source::Raster { tiles, from, tile_size, min_zoom, max_zoom, .. } | Source::RasterDem { tiles, from, tile_size, min_zoom, max_zoom, .. } => { @@ -648,10 +667,10 @@ pub(crate) fn tiles_in( Source::Vector { tiles, from, min_zoom, max_zoom, .. } => { (tiles, from, *min_zoom, *max_zoom, Want::Vector, (zoom.floor() as u8).min(*max_zoom)) } - Source::Other => return TileSelection { items: Vec::new(), mesh_gaps: true, retry: false }, + Source::Other => return TileSelection { items: Vec::new(), mesh_gaps: true, retry: false, absent: None }, }; if tiles.is_empty() || z < min_z || zoom + 0.5 < f32::from(min_z) { - return TileSelection { items: Vec::new(), mesh_gaps: true, retry: false }; + return TileSelection { items: Vec::new(), mesh_gaps: true, retry: false, absent: None }; } // A mosaic over half the world wide (the globe's, a world projection's) takes the zoom whose // tiles all fit, as its far edges are in view; a flat view keeps those nearest its centre. @@ -686,6 +705,8 @@ pub(crate) fn tiles_in( let mut retry = false; let mut partial = 0; let mut first_partial = None; + // Tiles in view asked for, and those of them the server hasn't (404, 410). + let (mut asked, mut not_there, mut first_status) = (0, 0, None); // A missing tile is stood in for by its nearest ancestor in the cache and, for raster tiles, // by its children in the cache, the ancestor only in the quarters they leave: zooming in, the // tiles of the zoom being passed through are often missing while those of the zoom it ends @@ -714,6 +735,7 @@ pub(crate) fn tiles_in( let area = p.extent(); // A tile merely touching the view's edge has no visible pixels. let visible = area.min_x < view.max_x && area.max_x > view.min_x && area.min_y < view.max_y && area.max_y > view.min_y; + asked += usize::from(visible); let u = match url(p.id) { Ok(Some(u)) => u, Ok(None) => continue, @@ -756,6 +778,9 @@ pub(crate) fn tiles_in( if !cache::routine_tile_failure(&e) { omitted += 1; first_error.get_or_insert(e); + } else if let Some(status) = cache::http_status(&e).filter(|_| visible) { + not_there += 1; + first_status.get_or_insert(status); } } State::Pending => { @@ -775,7 +800,41 @@ pub(crate) fn tiles_in( if let Some(reason) = first_partial { add_error(error, format!("{partial} tiles are partial (first: {reason})")); } - TileSelection { items: stand_ins, mesh_gaps, retry } + let absent = first_status.filter(|_| pictures && not_there == asked).map(none_on_the_server); + TileSelection { items: stand_ins, mesh_gaps, retry, absent } +} + +/// What says that source `id` has no tile in view: named in a style of several, as the others may +/// have drawn theirs. +fn of_source(r: &Resolved, id: &str, none: String) -> String { + if r.style.sources.len() < 2 { + return none; + } + let at = r.style.sources.iter().position(|(s, _)| s == id).map_or(0, |i| i + 1); + format!("its source \"{}\": {none}", source_name(id, at)) +} + +/// Source `id`, a style's own text, as a notice names it: at most 60 characters, and without what a +/// drawing's errors are split at. When any of it is left out it ends in "…" and the source's place +/// in the style (`at`), as another's name may begin the same. +fn source_name(id: &str, at: usize) -> String { + let name: String = id.chars().filter(|c| !c.is_control() && *c != ';').take(60).collect(); + if name == id { name } else { format!("{name}… ({at})") } +} + +/// What to say of a picture source whose server has none of the tiles in view, answering +/// `status` (404 or 410): a moved or retired service draws nothing, as does a view wholly past a +/// source's coverage or its deepest zoom, and each looks like an empty map. Without their count, +/// which changes with every pan: the map view says each kind of a layer's error once. Vector and +/// elevation sources aren't said: their servers often answer 404 for every tile with nothing in +/// it, as over the sea. +pub fn none_on_the_server(status: u16) -> String { + let why = match status { + 404 | 410 => ": the service may have moved or been retired, or have nothing here at this scale", + // A WMTS tile's other refusals, such as a request it doesn't understand. + _ => "", + }; + format!("none of the tiles in view are on the server (HTTP {status}){why}") } /// The nearest ancestor of a missing tile already in the cache, clipped to the missing tile. @@ -1359,6 +1418,44 @@ pub(crate) mod tests { assert_eq!(zoom_of(6000.0, 3400.0, 2.0, 11), 11); } + #[test] + fn a_source_name_says_when_it_is_shortened() { + assert_eq!(super::source_name("satellite", 1), "satellite"); + assert_eq!(super::source_name(&"é".repeat(60), 2), "é".repeat(60)); + assert_eq!(super::source_name(&"é".repeat(61), 3), "é".repeat(60) + "… (3)"); + assert_eq!(super::source_name("a; b", 4), "a b… (4)"); + let long = "x".repeat(60); + assert_ne!(super::source_name(&format!("{long}a"), 1), super::source_name(&format!("{long}b"), 2), "each is said"); + } + + /// A source of pictures with no tile in view says so; one of elevations or vector tiles, whose + /// servers answer 404 for every empty tile, doesn't. + #[test] + fn only_a_picture_source_says_it_has_no_tile_in_view() { + use crate::cache; + let _turn = cache::turn(); + cache::set_fetcher(|_, done| done(Err("http status: 404".into()))); + // Only a status that says it isn't there is put down to that. + assert!(super::none_on_the_server(410).contains("retired") && !super::none_on_the_server(400).contains("retired")); + for kind in ["raster", "raster-dem", "vector"] { + let doc = serde_json::json!({"version": 8, "layers": [], + "sources": {"s": {"type": kind, "maxzoom": 0, "tiles": [format!("http://no-tile.example/{kind}/{{z}}/{{x}}/{{y}}")]}}}); + let style = crate::style::Style::parse(&doc).unwrap(); + let src = &style.sources.first().unwrap().1; + let frame = world_frame(); + let ask = || { + let (mut pending, mut error) = (false, None); + let selected = super::tiles_in(src, &frame.extent(64, 64), None, &frame, 0.0, &mut pending, &mut error); + assert_eq!(error, None, "{kind}: not a failure"); + (pending, selected.absent) + }; + assert_eq!(ask(), (true, None), "{kind}: still on their way"); + cache::wait(std::time::Duration::from_secs(60)); + let said = (kind == "raster").then(|| super::none_on_the_server(404)); + assert_eq!(ask(), (false, said), "{kind}"); + } + } + #[test] fn refusal_counts_are_not_substring_duplicates() { let mut error = Some("12 tiles left out: refused".to_string()); diff --git a/crates/tiles/src/lib.rs b/crates/tiles/src/lib.rs index 28954fb61a..54d898dfbe 100644 --- a/crates/tiles/src/lib.rs +++ b/crates/tiles/src/lib.rs @@ -47,7 +47,7 @@ pub mod usgis; pub mod vector_export; pub mod warp; -pub use draw::{Drawn, Frame, PlacedTiles, Placement, draw, place, place_raster}; +pub use draw::{Drawn, Frame, PlacedTiles, Placement, draw, none_on_the_server, place, place_raster}; pub use picture::{Pace, Unfinished, lacking, pace, paced, unfinished}; pub use source::{Kind, Spec}; pub use symbols::{Collide, Label, LabelIcon}; diff --git a/crates/tiles/src/picture.rs b/crates/tiles/src/picture.rs index 441a0b3987..bfd01d2bf3 100644 --- a/crates/tiles/src/picture.rs +++ b/crates/tiles/src/picture.rs @@ -228,6 +228,7 @@ pub(crate) fn cover( reach: Option<&Extent>, pending: &mut bool, error: &mut Option, + absent: &mut Option, ) -> Option> { let ppp = frame.ppp; if !(ppp.is_finite() && ppp > 0.0 && frame.m_per_px.is_finite() && frame.m_per_px > 0.0) || view.width() > template::HALF_WORLD { @@ -265,6 +266,9 @@ pub(crate) fn cover( let mut visible = Drawn::default(); draw_layers(None, (0, 0), view, r, &picture_frame, Pass::Shapes, &mut visible); *pending |= visible.pending; + if let Some(none) = visible.absent { + crate::draw::add_error(absent, none); + } if let Some(reason) = visible.error { crate::draw::add_error(error, reason); } @@ -539,6 +543,18 @@ fn draw_one(r: &Resolved, p: &Placed, side: u32, m_per_px: f64, ppp: f32, reach: #[cfg(test)] mod tests { + /// [`super::cover`], for tests that don't ask what its server has none of. + fn cover( + r: &Arc, + frame: &Frame, + view: &Extent, + reach: Option<&Extent>, + pending: &mut bool, + error: &mut Option, + ) -> Option> { + super::cover(r, frame, view, reach, pending, error, &mut None) + } + /// Pattern failures follow prepared pixels, while absent patterns leave no sprite warning. #[test] fn rounded_picture_patterns_report_sprite_failures() { diff --git a/crates/ui-egui/src/mapgpu.rs b/crates/ui-egui/src/mapgpu.rs index e8aec069b3..5e88ac5170 100644 --- a/crates/ui-egui/src/mapgpu.rs +++ b/crates/ui-egui/src/mapgpu.rs @@ -2060,6 +2060,7 @@ mod tests { tiles_pending: false, data_pending: false, tile_errors: vec![], + absent: vec![], partial: vec![], pending_in_place: vec![], tilt: None, @@ -2764,6 +2765,7 @@ mod tests { tiles_pending: false, data_pending: false, tile_errors: vec![], + absent: vec![], partial: vec![], pending_in_place: vec![], tilt: None, diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index dddaf738d0..b5dde3008d 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -1976,69 +1976,17 @@ fn show_frame( /// Says a tile layer's error ("{layer}: {why}", its kinds joined by "; ") once a project for each /// layer and kind of error, each kind a notice of its own: the count of tiles in the view a kind /// may carry ("12 tiles left out: …") changes with every pan or zoom, so it is said under its kind -/// ([`tile_error_kind`]), with the count it had then, rather than again for each new count. +/// ([`rustgis_engine::render::tile_error_kind`]), with the count it had then, rather than again for each new count. /// Another kind of error, or another layer's, is said all the same. `said` is the map view's /// [`MapView::tile_errors`]. pub(crate) fn say_tile_error(said: &mut std::collections::HashSet, session: &mut rustgis_engine::Session, error: String) { - let (layer, why) = error.split_once(": ").map_or(("", error.as_str()), |(l, w)| (l, w)); - for kind in why.split("; ") { - let notice = if layer.is_empty() { kind.to_string() } else { format!("{layer}: {kind}") }; - // The layer's name as it is: only the reason loses its counts. - if said.insert(format!("{layer}\0{}", tile_error_kind(kind))) { + for (key, notice) in rustgis_engine::render::tile_error_notices(session.map(), &error) { + if said.insert(key) { session.notify(notice, true); } } } -/// Tile error reason `e` without its counts of tiles ("12 tiles left out", "3 tiles are partial", -/// "2 warped tile components left out" each become `#`) or what follows the host in the -/// addresses it names (each tile's differs, by its z/x/y): what it says beside them, the layer, -/// the server and the reason, is its kind. -fn tile_error_kind(e: &str) -> String { - let unaddressed = without_urls(e); - let mut out = String::with_capacity(unaddressed.len()); - let mut rest = unaddressed.as_str(); - while let Some(i) = rest.find(|c: char| c.is_ascii_digit()) { - let (head, tail) = rest.split_at(i); - out.push_str(head); - let n = tail.find(|c: char| !c.is_ascii_digit()).unwrap_or(tail.len()); - let (digits, after) = tail.split_at(n); - let starts_word = !out.ends_with(|c: char| c.is_alphanumeric() || c == '.' || c == ','); - if starts_word && (after.starts_with(" tiles ") || after.starts_with(" warped tile")) { - out.push('#'); - } else { - out.push_str(digits); - } - rest = after; - } - out.push_str(rest); - out -} - -/// `e` with the rest of each web address in it after its host (`http://` or `https://`, any case, -/// up to the next space or its end) replaced by `/…`: the path and query, which name the tile, -/// go; the server stays, so another server's failure is a kind of its own. -fn without_urls(e: &str) -> String { - // ASCII lower case keeps each byte where it is, so positions in it are positions in `e`. - let lower = e.to_ascii_lowercase(); - let mut out = String::with_capacity(e.len()); - let mut at = 0; - while let Some(i) = lower[at..].find("http://").into_iter().chain(lower[at..].find("https://")).min().map(|i| at + i) { - out.push_str(&e[at..i]); - let end = e[i..].find(char::is_whitespace).map_or(e.len(), |n| i + n); - let url = &e[i..end]; - let host_from = url.find("://").map_or(0, |n| n + 3); - let host_end = url[host_from..].find(['/', '?', '#']).map_or(url.len(), |n| host_from + n); - out.push_str(&url[..host_end]); - if host_end < url.len() { - out.push_str("/…"); - } - at = end; - } - out.push_str(&e[at..]); - out -} - /// Says, once a project each, what the map view's frames drew otherwise than their layers ask /// (a dashed line drawn solid, a fill left off a block diagram's walls, see /// [`rustgis_engine::render::take_approximations`]), each kind with the count it had when first @@ -2046,7 +1994,7 @@ fn without_urls(e: &str) -> String { fn say_approximations(app: &mut RustGisApp) { let relays = [&app.map.tilt_settle.relay, &app.map.motion_frame.relay, &app.map.tilt_drape.relay]; for (kind, e) in rustgis_engine::render::take_approximations(&relays) { - if app.map.tile_errors.insert(format!("approximated\0{kind}")) { + if app.map.tile_errors.insert(rustgis_engine::render::notice_key(&kind)) { app.session.warn(e); } } @@ -5359,7 +5307,8 @@ mod tile_redraw_tests { /// layer and kind; another kind or another layer's is said all the same (#2639). #[test] fn tile_errors_are_said_once_a_layer_and_kind_whatever_their_counts() { - use super::{say_tile_error, tile_error_kind}; + use super::say_tile_error; + use rustgis_engine::render::tile_error_kind; assert_eq!(tile_error_kind("Tiles: 12 tiles left out: refused"), "Tiles: # tiles left out: refused"); assert_eq!(tile_error_kind("Tiles: 3 tiles are partial (first: HTTP 404)"), "Tiles: # tiles are partial (first: HTTP 404)"); assert_eq!(tile_error_kind("Layer 12: 2 warped tile components left out: x"), "Layer 12: # warped tile components left out: x"); @@ -5397,6 +5346,21 @@ mod tile_redraw_tests { say_tile_error(&mut app.map.tile_errors, &mut app.session, "2024 tiles west: missing source".into()); say_tile_error(&mut app.map.tile_errors, &mut app.session, "2025 tiles west: missing source".into()); assert_eq!(said(&app, mark).len(), 2); + // And those whose names share what comes before their first colon, each kind of both. + for name in ["Imagery: 2020", "Imagery: 2021"] { + app.session.map_mut().tiles.push(rustgis_engine::map::TileLayer::new( + name, + rustgis_engine::map::TileKind::Raster, + "https://tiles.test/{z}/{x}/{y}.png", + )); + } + let mark = app.session.notice_mark(); + for name in ["Imagery: 2020", "Imagery: 2021"] { + say_tile_error(&mut app.map.tile_errors, &mut app.session, format!("{name}: 3 tiles left out: refused; sprite left out")); + } + let kinds = ["3 tiles left out: refused", "sprite left out"]; + let each: Vec = ["Imagery: 2020", "Imagery: 2021"].iter().flat_map(|n| kinds.map(|k| format!("{n}: {k}"))).collect(); + assert_eq!(said(&app, mark), each); } /// What the map view's frames approximated is said once a project each (#2639). diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index 8fa08cf50f..e21bf776d3 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -23,10 +23,17 @@ said. An export holds at most 8000 points a side, PNG or GeoTIFF: with no `width` or `height`, a larger view is cut to its middle; a `width` or `height` past 8000 is drawn at 8000, holding less ground than asked (the whole view still fits). Either way the -export says so. In a GeoTIFF, -tiles still on their way when the export stops waiting, streamed layers still reading the view, -and tile layers that can't be drawn leave gaps that would pass for data, so its export warns -about them. The web app's Export Map downloads a PNG. A projection +export says so. + +Every export (a PNG, a GeoTIFF, a map PDF or a layout) warns about a layer it couldn't draw in full, +such as a raster tile layer whose server has none of the tiles in view. Vector tiles, elevation +(hillshade, color relief and 3D terrain) and WMTS layers warped to Web Mercator don't say yet that +their server has none. A PNG, a GeoTIFF, and a map PDF too large to be kept as vectors aren't +written at all with a raster read in place that couldn't be drawn in full. + +In a GeoTIFF, tiles still on their way when the export stops waiting and streamed layers still +reading the view leave gaps that would pass for data too, so its export warns about them. The web +app's Export Map downloads a PNG. A projection whose parameters GeoTIFF's keys can't hold (Mollweide, for example) is refused too: switch the map to an EPSG projection first.