diff --git a/crates/map/src/look.rs b/crates/map/src/look.rs index 91d1a8a2cb..bab0c3b59c 100644 --- a/crates/map/src/look.rs +++ b/crates/map/src/look.rs @@ -37,6 +37,151 @@ pub struct LayerLook { raster: Option, } +/// `layer` without its rows, raster, caches and what else a look leaves out (see the module), +/// copied field by field: a whole copy taken first and pared down would copy, in every frame, what +/// grows with the data, such as an edit archive's whole features for every edit. +fn bare(layer: &Layer) -> Layer { + let Layer { + id, + name, + visible, + dataset, + renderer, + labels, + transparency, + min_scale, + max_scale, + definition_query, + time, + selection, + expanded, + selectable, + graphics, + blend, + mask, + display_filters, + aggregation, + extrusion, + line_strokes, + fill_layers, + no_fill, + hidden_fills, + stroke_levels, + marker_rotation, + diagram, + symbol_by, + size_by, + reference_scale, + priority, + design, + // Compared by its own look. + raster: _, + source, + // Saving back to a database or GeoPackage keeps per-row versions, which aren't drawn. + postgis: _, + gpkg: _, + synced: _, + connection, + anonymous, + instance_id, + replacement_rev, + // Caches, emptied below. + projected, + display, + display_rejected: _, + display_levels, + projected_extents, + projected_vertices, + thinned, + projected_rev, + projected_for, + projected_crs, + lonlat, + unplaced: _, + drawn: _, + view_memory: _, + geometry_kinds: _, + geometry_rev, + } = layer; + let crate::design::Design { domains, subtypes, rules, contingent, archive, templates } = design; + let mut kept = Layer { + id: *id, + name: name.clone(), + visible: *visible, + // Its rows are shared, so the copy costs a pointer; dropped below. + dataset: dataset.clone(), + renderer: renderer.clone(), + labels: labels.clone(), + transparency: *transparency, + min_scale: *min_scale, + max_scale: *max_scale, + definition_query: definition_query.clone(), + // A time binding keeps the rows its dates were read from: only what it draws by. + time: time.as_ref().map(|t| { + let mut bare = crate::time::TimeBinding::new(t.field.clone()); + bare.window = t.window; + bare + }), + selection: selection.clone(), + expanded: *expanded, + selectable: *selectable, + graphics: *graphics, + blend: *blend, + mask: mask.clone(), + display_filters: display_filters.clone(), + aggregation: *aggregation, + extrusion: extrusion.clone(), + line_strokes: line_strokes.clone(), + fill_layers: fill_layers.clone(), + no_fill: *no_fill, + hidden_fills: hidden_fills.clone(), + stroke_levels: *stroke_levels, + marker_rotation: marker_rotation.clone(), + diagram: diagram.clone(), + symbol_by: symbol_by.clone(), + size_by: size_by.clone(), + reference_scale: *reference_scale, + priority: *priority, + design: crate::design::Design { + domains: domains.clone(), + subtypes: subtypes.clone(), + rules: rules.clone(), + contingent: contingent.clone(), + // Whether edits are archived, not the whole features from before and after each. + archive: archive.as_ref().map(|_| Vec::new()), + templates: templates.clone(), + }, + raster: None, + source: source.clone(), + postgis: None, + gpkg: None, + synced: None, + connection: connection.clone(), + anonymous: *anonymous, + instance_id: *instance_id, + replacement_rev: *replacement_rev, + projected: projected.clone(), + display: display.clone(), + display_rejected: Vec::new(), + display_levels: display_levels.clone(), + projected_extents: projected_extents.clone(), + projected_vertices: *projected_vertices, + thinned: thinned.clone(), + projected_rev: *projected_rev, + projected_for: projected_for.clone(), + projected_crs: *projected_crs, + lonlat: lonlat.clone(), + unplaced: Default::default(), + drawn: false, + view_memory: Default::default(), + geometry_kinds: Default::default(), + geometry_rev: *geometry_rev, + }; + kept.dataset.features = Default::default(); + kept.clear_cache(); + kept +} + impl LayerLook { /// The look of `layer`; `None` for one whose drawing reads more than the layer holds, which no /// look can vouch for: a source read in place (its file is read again for each frame) or a @@ -51,22 +196,7 @@ impl LayerLook { None => None, }; let rows = layer.dataset.features.allocation_key(); - // Saving back to a database or GeoPackage keeps per-row versions, which aren't drawn. - let mut kept = Layer { raster: None, postgis: None, gpkg: None, synced: None, ..layer.clone() }; - kept.dataset.features = Default::default(); - kept.clear_cache(); - // What these share with the layer could hold its rows: a time binding keeps the rows its - // dates were read from. - kept.time = layer.time.as_ref().map(|t| { - let mut bare = crate::time::TimeBinding::new(t.field.clone()); - bare.window = t.window; - bare - }); - kept.view_memory = Default::default(); - // Edit archiving keeps whole features from before and after each edit, which aren't drawn. - kept.design.archive = layer.design.archive.as_ref().map(|_| Vec::new()); - kept.geometry_kinds = Default::default(); - Some(LayerLook { layer: kept, rows, raster }) + Some(LayerLook { layer: bare(layer), rows, raster }) } /// How the layer `now` was taken of differs from the one this look was taken of. diff --git a/crates/render/src/frame_cache.rs b/crates/render/src/frame_cache.rs new file mode 100644 index 0000000000..41b3a839b8 --- /dev/null +++ b/crates/render/src/frame_cache.rs @@ -0,0 +1,513 @@ +//! A screen frame's picture kept up to a layer, so the next frame of the same view draws only +//! from the first layer that changed (#1057): restyling a layer over a basemap, its tile layers +//! and the layers below it draws that layer and those above it, not the whole map again. +//! +//! A kept picture is a [`Checkpoint`]: the pixels of a frame as they stood before one of its +//! layers was drawn, with the label candidates, graphics text and tile output gathered so far. +//! What it was drawn from is kept beside it as looks ([`rustgis_map::look`]): the map's, each +//! layer's, and the frame's own (view, expression environment, tile and source generations). +//! A frame starts from the checkpoint when everything it holds still looks the same, which makes +//! it the same frame, pixel for pixel, as drawing it all again: the layers below draw first in +//! either case, from the same state. +//! +//! The layer the checkpoint stands under is the one being changed, as a slider drags: when it is +//! drawn on its own and composited (see-through or blended), its picture alone is kept too, as an +//! [`Alone`], with what the frame had gathered once it was drawn. A frame in which that layer +//! looks the same or only its transparency changed ([`Change::Transparency`]) composites that +//! picture at the layer's opacity instead of drawing the layer: the same steps a frame drawn +//! whole takes, so again the same pixels. A layer that shows a selection or graphics text isn't +//! kept alone: both are drawn after the composite, the text in the layer's opacity. +//! +//! Only flat, north-up frames for the screen keep pictures: not exports, recordings, the GPU, +//! the globe, turned or tilted views, nor maps whose layers read others while drawing (a mask, +//! labels turned square to another layer's lines, terrain water). A layer read in place from its +//! source or a raster has no look ([`LayerLook::of`]): it counts as changed in every frame, so a +//! picture is kept only from below it. + +use rustgis_data::query::Env; +use rustgis_map::look::{Change, LayerLook, MapLook}; +use tiny_skia::Pixmap; + +use crate::tiles::TileOutput; +use crate::{Candidate, PlacedLabel, Sprites, View}; + +/// The most pixels the kept pictures hold together, checkpoints and layers alone, about 66 MB: +/// two views of 3840 × 2160, or one with its layer alone; two views with their layers alone at +/// 1920 × 1080. +const MAX_PIXELS: u64 = 2 * 3840 * 2160; + +/// The most pixels one frame's marker sprites can hold ([`crate::MAX_SPRITES`] of at most +/// [`crate::MAX_SPRITE_REACH`] around their centre): about 2.5 million, 9.8 MB. Each kept view +/// may hold that beside its pictures, so the sprites never cost a view its layer alone: with them +/// the kept pictures stay within about 86 MB. +const SPRITE_PIXELS: u64 = crate::MAX_SPRITES as u64 * (2 * crate::MAX_SPRITE_REACH as u64 + 1).pow(2); + +/// Pictures kept, one per view drawn (a map and its draft, two maps on screen). +const KEPT: usize = 2; + +/// What a frame is drawn from besides its layers. +#[derive(Clone, Debug)] +pub(crate) struct Frame { + pub map: MapLook, + pub view: View, + pub style_env: Env, + pub label_env: Env, + /// [`rustgis_tiles::cache::generation`]: a tile arrived, on a map with tile layers or terrain + /// (a tile for another map's view leaves this one's pictures). + pub tiles: Option, + /// [`rustgis_map::source::generation`]: a streamed read finished, on a map with a layer read + /// from its source. + pub sources: Option, + /// The world outline's worldview, and how many shapes it had at hand, when it is drawn. + pub worldview: Option<(crate::sample_data::View, usize)>, + /// Whether the installed font families were indexed ([`crate::families::installed_now`]). + pub fonts: bool, + /// [`crate::fonts::font_generation`]: a downloaded font now draws some text. + pub font_generation: u32, + /// How many layers the map has, which labels take their priority from. + pub layers: usize, + /// What graphics text shows for `{date}` and `{time}` (the minute) and for `{layers}` (the + /// layers not of graphics), on a map with graphics ([`rustgis_map::graphics::TokenValues`]). + pub tokens: Option<(u64, usize)>, + /// The layer each tile layer is drawn over ([`rustgis_map::Map::tile_slots`]), which follows + /// the layers present as well as the tile layers' settings. + pub tile_slots: Vec>, +} + +impl Frame { + /// Whether `other` draws everything but its layers as this frame did. + fn same(&self, other: &Frame) -> bool { + let (a, b) = (&self.view, &other.view); + a.width.to_bits() == b.width.to_bits() + && a.height.to_bits() == b.height.to_bits() + && a.pixels_per_point.to_bits() == b.pixels_per_point.to_bits() + && a.camera == b.camera + && a.sky == b.sky + && self.style_env == other.style_env + && self.label_env == other.label_env + && self.tiles == other.tiles + && self.sources == other.sources + && self.worldview == other.worldview + && self.fonts == other.fonts + && self.font_generation == other.font_generation + && self.layers == other.layers + && self.tokens == other.tokens + && self.tile_slots == other.tile_slots + && self.map.same(&other.map) + } +} + +/// A frame as it stood before the layer at one place in the drawing order was drawn. +#[derive(Clone)] +pub(crate) struct Checkpoint { + pub pixels: Pixmap, + /// The marker sprites drawn so far: a layer above draws a marker from one, or straight once + /// there are as many as a frame keeps, as it would in a frame drawn whole. + pub sprites: Sprites, + /// The shapeburst budget spent so far (`gradient_fill::FRAME_BURST_PX`). + pub bursts: f32, + /// When it was drawn: one of a map with tile layers is drawn again once a failed tile may be + /// asked for again ([`rustgis_tiles::cache::RETRY`]), as the next frame drawn whole would. + pub taken: web_time::Instant, + pub candidates: Vec, + pub fixed: Vec, + pub tiles: TileOutput, +} + +/// A layer's picture alone, drawn opaque, and what the frame had gathered once the layer was drawn +/// and composited, before the tile layers over it. +#[derive(Clone)] +pub(crate) struct Alone { + pub pixels: Pixmap, + pub sprites: Sprites, + pub bursts: f32, + pub candidates: Vec, + pub fixed: Vec, + pub tiles: TileOutput, +} + +/// The looks of a frame's layers, bottom first in drawing order, by id and place in the map's list +/// (which labels take their priority from); `None` for one with no look. +pub(crate) type Looks = Vec<((u32, usize), Option)>; + +/// A kept picture and what it was drawn from. +struct Kept { + frame: Frame, + looks: Looks, + /// The place in the drawing order the checkpoint stands before. + at: usize, + checkpoint: Checkpoint, + /// The layer at `at` alone. + alone: Option, +} + +impl Kept { + /// The pixels it holds: its pictures and their marker sprites, each sprite counted once + /// though the checkpoint and the layer alone share it. + fn pixels(&self) -> u64 { + let size = |p: &Pixmap| u64::from(p.width()) * u64::from(p.height()); + let mut seen = std::collections::HashSet::new(); + let alone = self.alone.as_ref(); + let sprites = std::iter::once(&self.checkpoint.sprites) + .chain(alone.map(|a| &a.sprites)) + .flat_map(|s| s.values().flatten()) + .filter(|p| seen.insert(std::sync::Arc::as_ptr(p))) + .map(|p| size(p)) + .sum::(); + size(&self.checkpoint.pixels) + alone.map_or(0, |a| size(&a.pixels)) + sprites + } +} + +/// The kept pictures, shared by the threads that draw frames (the UI's and the one that draws +/// a view once it settles). +#[cfg(not(test))] +static PICTURES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Runs `f` on the kept pictures. +#[cfg(not(test))] +fn with_pictures(f: impl FnOnce(&mut Vec) -> R) -> R { + // A thread that panicked while holding them left nothing half done: each is replaced whole. + f(&mut PICTURES.lock().unwrap_or_else(std::sync::PoisonError::into_inner)) +} + +// Each test thread keeps its own, so tests running side by side don't take each other's. +#[cfg(test)] +thread_local! { + static PICTURES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + /// Where the last frame planned started drawing its layers. + static STARTED: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// Whether the last frame planned had a layer alone to composite. + static RECOMBINED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +#[cfg(test)] +fn with_pictures(f: impl FnOnce(&mut Vec) -> R) -> R { + PICTURES.with_borrow_mut(f) +} + +/// How a frame draws, from [`plan`]. +pub(crate) struct Plan { + /// The place in the drawing order the frame starts drawing layers from: 0 draws everything, + /// basemap included. + pub start: usize, + /// What it starts from when `start` is past 0. + pub restored: Option, + /// The place to keep the frame at, if not the one it was restored at. + pub capture_at: Option, + /// The layer at `start` alone, to composite instead of drawing it: it looks the same or only + /// its transparency changed. Kept again when the layer isn't drawn alone this time. + pub recombine: Option, + /// The place in the drawing order of the layer to keep alone, when it is drawn so. + pub alone_at: Option, + frame: Frame, + looks: Looks, +} + +/// The first place in the drawing order where `now` doesn't look as `then` did. +fn first_change(then: &Looks, now: &Looks) -> usize { + then.iter() + .zip(now) + .position(|((a, la), (b, lb))| { + a != b + || match (la, lb) { + (Some(la), Some(lb)) => la.change(lb) != Change::Same, + _ => true, + } + }) + .unwrap_or(then.len().min(now.len())) +} + +/// Whether a frame of `w` × `h` pixels can keep pictures: [`plan`] refuses one past the budget, +/// so a frame checks first rather than take the looks of its layers for nothing. +pub(crate) fn fits(w: u32, h: u32) -> bool { + (u64::from(w) * u64::from(h)).saturating_mul(KEPT as u64) <= MAX_PIXELS +} + +/// How the layer at place `at` in the drawing order differs between `then` and `now`. +fn change_at(then: &Looks, now: &Looks, at: usize) -> Change { + match (then.get(at), now.get(at)) { + (Some((a, Some(la))), Some((b, Some(lb)))) if a == b => la.change(lb), + _ => Change::Drawn, + } +} + +/// The place at which a frame keeping its picture at `at` keeps a layer alone: one with a look, +/// when a view's checkpoint and layer fit within [`MAX_PIXELS`] together. +fn alone_at(looks: &Looks, at: usize, pixels: u64) -> Option { + (pixels.saturating_mul(2) <= MAX_PIXELS && looks.get(at).is_some_and(|(_, l)| l.is_some())).then_some(at) +} + +/// How to draw `frame` with layers `looks` of `pixels` pixels: from a kept picture when one still +/// shows its bottom layers, and where to keep this one. The kept picture is taken out meanwhile; +/// [`keep`] puts the frame's back. +pub(crate) fn plan(frame: Frame, looks: Looks, pixels: u64) -> Plan { + let plan = plan_with(frame, looks, pixels); + #[cfg(test)] + STARTED.set(Some(plan.start)); + #[cfg(test)] + RECOMBINED.set(plan.recombine.is_some()); + plan +} + +/// [`plan`]. +fn plan_with(frame: Frame, looks: Looks, pixels: u64) -> Plan { + if pixels.saturating_mul(KEPT as u64) > MAX_PIXELS { + return Plan { start: 0, restored: None, capture_at: None, recombine: None, alone_at: None, frame, looks }; + } + // A picture over tile layers lasts until a tile that failed in it may be asked for again: a + // server that gave no time to come back is asked by the next draw after a minute. + let fresh = |k: &Kept| k.frame.tiles.is_none() || k.checkpoint.taken.elapsed() < rustgis_tiles::cache::RETRY; + let found = with_pictures(|kept| { + kept.retain(fresh); + kept.iter().position(|k| k.frame.same(&frame)).map(|i| kept.remove(i)) + }); + let Some(k) = found else { + // Nothing to start from: keep what lies under the first layer (the basemap, the tile + // layers below every layer), or the frame under its first changed layer next time. + let alone_at = alone_at(&looks, 0, pixels); + return Plan { start: 0, restored: None, capture_at: Some(0), recombine: None, alone_at, frame, looks }; + }; + let changed = first_change(&k.looks, &looks); + if k.at <= changed { + let capture_at = (changed > k.at && changed < looks.len()).then_some(changed); + let recombine = k.alone.filter(|_| matches!(change_at(&k.looks, &looks, k.at), Change::Same | Change::Transparency)); + let alone_at = alone_at(&looks, capture_at.unwrap_or(k.at), pixels); + Plan { start: k.at, restored: Some(k.checkpoint), capture_at, recombine, alone_at, frame, looks } + } else { + let alone_at = alone_at(&looks, changed, pixels); + Plan { start: 0, restored: None, capture_at: Some(changed), recombine: None, alone_at, frame, looks } + } +} + +/// Keeps the picture a frame drawn by `plan` ends with: `captured` when it took one, else the one +/// it started from, with the layer over it alone: `alone` when the frame drew it so, else the one +/// it was composited from. Called only for a frame drawn to the end. +pub(crate) fn keep(plan: Plan, captured: Option<(usize, Checkpoint)>, alone: Option<(usize, Alone)>) { + let Plan { start, restored, recombine, frame, looks, .. } = plan; + let Some((at, checkpoint)) = captured.or(restored.map(|c| (start, c))) else { return }; + let alone = match alone { + Some((a, alone)) if a == at => Some(alone), + _ => recombine.filter(|_| at == start), + }; + with_pictures(|kept| { + kept.retain(|k| !k.frame.same(&frame)); + if kept.len() >= KEPT { + kept.remove(0); + } + kept.push(Kept { frame, looks, at, checkpoint, alone }); + // Within the budget: the older views' layers alone go first, then the older views, then + // this view's layer alone. + while kept.iter().map(Kept::pixels).sum::() > MAX_PIXELS + KEPT as u64 * SPRITE_PIXELS { + let older = kept.len().saturating_sub(1); + if let Some(k) = kept.iter_mut().take(older).find(|k| k.alone.is_some()) { + k.alone = None; + } else if kept.len() > 1 { + kept.remove(0); + } else if let Some(k) = kept.first_mut().filter(|k| k.alone.is_some()) { + k.alone = None; + } else { + // A view whose picture and sprites alone are past the budget keeps nothing. + kept.clear(); + } + } + }); +} + +#[cfg(test)] +mod tests { + use rustgis_data::{Coord, Dataset, Field, FieldType, Geometry, GeometryType, Value}; + use rustgis_map::{Basemap, Camera, Map, Renderer, Rgba}; + + use super::*; + use crate::render; + + /// A map of a grid of labelled squares under a layer of points, and a view of it. + fn map() -> (Map, View, u32, u32) { + // The installed fonts indexed now: another test indexing them partway would change every + // frame's key (`Frame::fonts`), and the next frame would draw whole. + crate::families::installed(); + let mut squares = Dataset::new("squares", GeometryType::Polygon, vec![Field::new("name", FieldType::Text)]); + for i in 0..40 { + let (x, y) = (f64::from(i % 8) * 0.01, f64::from(i / 8) * 0.01); + let ring = vec![ + Coord::new(x, y), + Coord::new(x + 0.008, y), + Coord::new(x + 0.008, y + 0.008), + Coord::new(x, y + 0.008), + Coord::new(x, y), + ]; + let pos = rustgis_geom::lonlat_to_merc; + squares.push(Some(Geometry::Polygon(vec![vec![ring.into_iter().map(pos).collect()]])), vec![Value::Text(format!("S{i}"))]); + } + let mut points = Dataset::new("points", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + for i in 0..30 { + let c = rustgis_geom::lonlat_to_merc(Coord::new(f64::from(i % 6) * 0.013, f64::from(i / 6) * 0.009)); + points.push(Some(Geometry::Point(c)), vec![Value::Text(format!("P{i}"))]); + } + let mut map = Map::new("Map"); + map.basemap = Basemap::Blank; + map.graticule = false; + let below = map.add_dataset(squares); + let above = map.add_dataset(points); + if let Some(l) = map.layer_mut(below) { + l.labels.enabled = true; + l.labels.default.field = "name".into(); + } + let camera = Camera { center: rustgis_geom::lonlat_to_merc(Coord::new(0.04, 0.025)), res: 12.0, bearing: 0.0, pitch: 0.0 }; + (map, View { width: 200.0, height: 160.0, pixels_per_point: 1.0, camera, sky: false }, below, above) + } + + /// Draws `map` twice: as it comes after the frames before it, and again from nothing. They + /// must be the same frame; gives where the first started drawing its layers. + fn draw(map: &mut Map, view: &View) -> Option { + let kept = render(map, view).expect("drawn"); + let (started, recombined) = (STARTED.get(), RECOMBINED.get()); + let pictures = PICTURES.take(); + let fresh = render(map, view).expect("drawn"); + PICTURES.set(pictures); + RECOMBINED.set(recombined); + assert!(kept.pixmap.data() == fresh.pixmap.data(), "a frame from a kept picture differs from one drawn whole"); + let texts = |r: &crate::Rendered| r.labels.iter().map(|l| (l.text.clone(), l.x.to_bits(), l.y.to_bits())).collect::>(); + assert_eq!(texts(&kept), texts(&fresh), "its labels differ"); + started + } + + #[test] + fn a_frame_draws_from_its_first_changed_layer() { + let (mut map, view, below, above) = map(); + assert_eq!(draw(&mut map, &view), Some(0), "the first frame draws everything"); + // Restyling the layer on top draws only it, the labels of the one below still placed. + let restyle = |map: &mut Map, id: u32, rgb: (u8, u8, u8)| { + if let Some(l) = map.layer_mut(id) { + l.renderer = Renderer::Single(rustgis_map::Symbol { fill: Rgba::rgb(rgb.0, rgb.1, rgb.2), ..l.symbol(0) }); + } + }; + // The first change after a new view starts from the picture under every layer, and keeps + // one under the changed layer for the next. + restyle(&mut map, above, (200, 30, 30)); + assert_eq!(draw(&mut map, &view), Some(0)); + restyle(&mut map, above, (30, 200, 30)); + assert_eq!(draw(&mut map, &view), Some(1), "each step of a drag draws from the picture under the layer"); + restyle(&mut map, above, (30, 30, 200)); + assert_eq!(draw(&mut map, &view), Some(1)); + // Nothing changed: still from the kept picture. + assert_eq!(draw(&mut map, &view), Some(1)); + // The layer below changed: everything again. + restyle(&mut map, below, (10, 10, 120)); + assert_eq!(draw(&mut map, &view), Some(0)); + if let Some(l) = map.layer_mut(below) { + l.dataset.features.truncate(20); + } + assert_eq!(draw(&mut map, &view), Some(0), "an edit to the rows draws the layer again"); + // Moving the view draws everything. + let mut moved = view; + moved.camera.center.x += 50.0; + assert_eq!(draw(&mut map, &moved), Some(0)); + } + + #[test] + fn a_see_through_layer_is_composited_again_at_its_new_transparency() { + let (mut map, view, _, above) = map(); + let set = |map: &mut Map, t: f32| map.layer_mut(above).map(|l| l.transparency = t); + set(&mut map, 20.0); + assert_eq!(draw(&mut map, &view), Some(0)); + // The first change keeps the frame under the layer, and the layer alone. + set(&mut map, 30.0); + assert_eq!(draw(&mut map, &view), Some(0)); + assert!(!RECOMBINED.get()); + // Each further step of the drag composites that picture: the same frame as one drawn whole. + for t in [40.0, 75.0, 5.0] { + set(&mut map, t); + assert_eq!(draw(&mut map, &view), Some(1)); + assert!(RECOMBINED.get(), "{t}"); + } + // Nothing changed: composited again. + assert_eq!(draw(&mut map, &view), Some(1)); + assert!(RECOMBINED.get()); + // Opaque, it is drawn straight onto the map, which composites nothing. + set(&mut map, 0.0); + draw(&mut map, &view); + set(&mut map, 50.0); + draw(&mut map, &view); + // A colour drawn differently: the layer is drawn again, and kept alone again. + if let Some(l) = map.layer_mut(above) { + l.renderer = Renderer::Single(rustgis_map::Symbol { fill: Rgba::rgb(10, 200, 90), ..l.symbol(0) }); + } + assert_eq!(draw(&mut map, &view), Some(1)); + assert!(!RECOMBINED.get()); + set(&mut map, 60.0); + assert_eq!(draw(&mut map, &view), Some(1)); + assert!(RECOMBINED.get()); + // A selection is drawn over the composite: the layer isn't kept alone while it shows one. + if let Some(l) = map.layer_mut(above) { + l.selection = vec![0, 3]; + } + draw(&mut map, &view); + set(&mut map, 70.0); + draw(&mut map, &view); + assert!(!RECOMBINED.get(), "a layer showing a selection is drawn"); + } + + #[test] + fn a_layer_moved_in_the_list_draws_whole_though_its_drawing_order_holds() { + let (mut map, view, below, above) = map(); + // Labels on both, which take their priority from the layers' places in the list; the + // drawing order is held by the layers' depth priorities whatever the list says. + for (id, priority) in [(below, 0), (above, 1)] { + if let Some(l) = map.layer_mut(id) { + l.labels.enabled = true; + l.labels.default.field = "name".into(); + l.priority = priority; + } + } + draw(&mut map, &view); + // Changes to the layer on top keep the picture under it. + for size in [9.0, 11.0] { + if let Some(l) = map.layer_mut(above) { + l.renderer = Renderer::Single(rustgis_map::Symbol { size, ..l.symbol(0) }); + } + draw(&mut map, &view); + } + assert_eq!(draw(&mut map, &view), Some(1)); + map.layers.reverse(); + assert_eq!(draw(&mut map, &view), Some(0), "the labels below place differently"); + // A layer added to the end of the list, drawn on top by its depth priority, leaves the + // others at their places, but the label priorities of all of them count the layers. + for size in [9.0, 11.0] { + if let Some(l) = map.layer_mut(above) { + l.renderer = Renderer::Single(rustgis_map::Symbol { size, ..l.symbol(0) }); + } + draw(&mut map, &view); + } + assert_eq!(draw(&mut map, &view), Some(1)); + let Some(mut added) = map.layer(above).cloned() else { panic!("the layer above") }; + added.id = 99; + added.priority = 2; + map.layers.push(added); + assert_eq!(draw(&mut map, &view), Some(0), "the labels below rank differently"); + } + + #[test] + fn a_view_of_3840_by_2160_keeps_its_layer_alone_beside_the_marker_sprites() { + let (mut map, mut view, _, above) = map(); + (view.width, view.height) = (3840.0, 2160.0); + // The layer dragged is of point markers, drawn from sprites. + for t in [20.0, 30.0, 40.0] { + if let Some(l) = map.layer_mut(above) { + l.transparency = t; + } + draw(&mut map, &view); + } + assert!(RECOMBINED.get(), "the layer alone was kept"); + } + + #[test] + fn a_layer_with_no_look_draws_in_every_frame() { + let (mut map, view, below, _) = map(); + if let Some(l) = map.layer_mut(below) { + l.source = Some(Default::default()); + } + draw(&mut map, &view); + assert_eq!(draw(&mut map, &view), Some(0)); + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 1c5d26c4d0..b0044b49f6 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -41,6 +41,7 @@ pub mod svg; pub mod terrain; mod text; pub use text::CALLOUT_WIDTH; +mod frame_cache; pub mod tile_mesh; mod tiles; pub mod vector; @@ -761,11 +762,6 @@ fn outline_level_for(map_per_px: f64) -> usize { } } -/// The built-in world outline in longitude/latitude, for the globe. -fn world_lonlat() -> &'static Vec { - world_lonlat_of(sample_data::view()) -} - /// The world outline in view `wv`, in longitude/latitude. fn world_lonlat_of(wv: sample_data::View) -> &'static Vec { static W: [OnceLock>; sample_data::VIEW_COUNT] = [const { OnceLock::new() }; sample_data::VIEW_COUNT]; @@ -785,15 +781,15 @@ thread_local! { } /// The built-in world outline in a custom projection's coordinates (kept per projection). -fn world_in(flat: &rustgis_map::projection::Flat, key: &str) -> std::rc::Rc> { +fn world_in(wv: sample_data::View, flat: &rustgis_map::projection::Flat, key: &str) -> std::rc::Rc> { WORLD_IN.with(|cell| { - let lonlat = world_lonlat(); + let lonlat = world_lonlat_of(wv); // An outline not at hand yet is drawn empty, not kept. if lonlat.is_empty() { return std::rc::Rc::new(Vec::new()); } cell.borrow_mut() - .entry(format!("{}:{key}", sample_data::view().index())) + .entry(format!("{}:{key}", wv.index())) .or_insert_with(|| std::rc::Rc::new(lonlat.iter().map(|g| flat.project(g)).collect())) .clone() }) @@ -882,7 +878,7 @@ struct Ctx<'a> { /// Set when drawing the globe; coordinates are then longitude/latitude, not Web Mercator. globe: Option, /// Point marker sprites drawn so far, by symbol and quarter-pixel offset. - sprites: std::cell::RefCell>>>, + sprites: std::cell::RefCell, /// The pixels the frame's shapeburst fills have worked on (`gradient_fill::FRAME_BURST_PX`), /// shared by a layer's scaled context (a reference scale's) with the frame's. bursts: std::rc::Rc>, @@ -891,6 +887,9 @@ struct Ctx<'a> { /// A marker sprite's symbol and quarter-pixel offset. type SpriteKey = (Rgba, Rgba, u32, u32, Marker, u8, u8); +/// The marker sprites a frame has drawn ([`Ctx::sprites`]). +type Sprites = std::collections::HashMap>>; + impl Ctx<'_> { /// Logical screen position of a coordinate, `None` when it is behind the globe. fn screen(&self, c: Coord) -> Option<(f64, f64)> { @@ -4145,6 +4144,18 @@ fn holds_picture(cmds: &[gpu_scene::DrawCmd]) -> bool { cmds.iter().any(|c| matches!(c, gpu_scene::DrawCmd::Image { .. })) } +/// Whether a frame of `map` for `view` can start from a kept picture and keep its own +/// ([`frame_cache`]): flat and north-up, with no layer drawing from another (a mask, the swipe, +/// labels turned square to another layer's lines, terrain water). +fn keeps_pictures(map: &Map, view: &View) -> bool { + view.camera.bearing == 0.0 + && view.camera.pitch == 0.0 + && !map.projection.is_globe() + && map.swipe.is_none() + && map.view.terrain.as_ref().is_none_or(|t| t.water.is_none()) + && map.layers.iter().all(|l| l.mask.is_none() && l.labels.in_order().all(|c| c.square_to.is_none())) +} + /// Draws one north-up frame. `labels_to` says where its labels go: a turned or tilted view the /// frame stands in for places them itself (and draws their icons). `full_res_rasters` marks an /// export, which draws everything as it will stay: rasters at full resolution, and labels in @@ -4228,6 +4239,61 @@ fn render_frame( Some(g) => g.may_see(e), None => e.intersects(&mesh_cull), }; + // Bottom first; a higher depth priority draws later (on top) whatever the order. + let mut order: Vec = (0..map.layers.len()).rev().collect(); + order.sort_by_key(|i| map.layers.get(*i).map_or(0, |l| l.priority)); + // The worldview read once: the frame's key, the outline and its level must be of the same + // one, though another thread may switch it mid-frame. + let worldview = sample_data::view(); + // A screen frame starts from the picture kept of the last one, under its first changed layer + // (see `frame_cache`), and keeps its own. + let mut cached = (!pm.is_recording() + && !gpu + && !full_res_rasters + && matches!(labels_to, Labels::Own) + && frame_cache::fits(w, h) + && keeps_pictures(map, view)) + .then(|| { + let frame = frame_cache::Frame { + map: rustgis_map::look::MapLook::of(map), + view: *view, + style_env: style_env.clone(), + label_env: label_env.clone(), + tiles: (!map.tiles.is_empty() || map.view.terrain.is_some()).then(rustgis_tiles::cache::generation), + sources: map.layers.iter().any(|l| l.source.is_some()).then(rustgis_map::source::generation), + // Only when drawn: asking for an outline not at hand says so in the log. + worldview: map.draws_world_outline().then(|| (worldview, world_of(worldview).len())), + // Whether they were indexed so far, without indexing them for a map with no text. + fonts: families::installed_now().is_some(), + font_generation: fonts::font_generation(), + layers: map.layers.len(), + tokens: map.layers.iter().any(|l| l.graphics).then(|| { + let t = rustgis_map::graphics::TokenValues::of(map, scale); + (t.now / 60, t.layers) + }), + tile_slots: map.tile_slots(), + }; + // By id and place in the list, which labels take their priority from. + let looks = order + .iter() + .filter_map(|i| Some(((map.layers.get(*i)?.id, *i), rustgis_map::look::LayerLook::of(map.layers.get(*i)?)))) + .collect(); + frame_cache::plan(frame, looks, u64::from(w) * u64::from(h)) + }); + let start = cached.as_ref().map_or(0, |p| p.start); + // A frame with no kept picture to start from draws what lies under its layers. + let cold = cached.as_ref().is_none_or(|p| p.restored.is_none()); + let mut captured: Option<(usize, frame_cache::Checkpoint)> = None; + // The layer kept alone (`frame_cache::Alone`): its picture once composited, and the rest once + // it is done. + let alone_at = cached.as_ref().and_then(|p| p.alone_at); + let mut drawn_alone: Option<(usize, Pixmap)> = None; + let mut captured_alone: Option<(usize, frame_cache::Alone)> = None; + // Kept only as drawn in full so far: tiles still to come, to draw, or to ask for again after + // a failure are drawn again rather than restored as they stood. + let complete = |t: &tiles::TileOutput| { + !t.pending && t.errors.is_empty() && t.partial.is_empty() && t.pending_in_place.is_empty() && rustgis_tiles::lacking().is_none() + }; // Basemap. let (water, land, outline, grat) = map.palette(); @@ -4247,15 +4313,13 @@ fn render_frame( let pictureless = backend.is_gpu() && matches!(labels_to, Labels::Turned(_) | Labels::Tilted(..)); // Set when such a frame stops that way. let mut declined = false; - if map.draws_world_outline() { + // A frame started from a kept picture has its basemap and the tile layers under its layers. + if cold && map.draws_world_outline() { let fill = paint(land, 1.0); let stroke = (outline.a() > 0).then(|| (paint(outline, 1.0), 0.6)); - // The worldview read once: the outline and its level must be of the same one, though - // another thread may switch it mid-frame. - let worldview = sample_data::view(); - let custom_world = custom.then(|| world_in(&flat, &key)); + let custom_world = custom.then(|| world_in(worldview, &flat, &key)); let outlines: &Vec = match (&globe, &custom_world) { - (Some(_), _) => world_lonlat(), + (Some(_), _) => world_lonlat_of(worldview), (None, Some(w)) => w, (None, None) => world_of(worldview), }; @@ -4314,7 +4378,7 @@ fn render_frame( } } } - if map.graticule && grat.a() > 0 { + if cold && map.graticule && grat.a() > 0 { let p = paint(grat, 1.0); // A measured or UTM graticule's lines (#1042), else latitudes and longitudes. let grid = mapgrid::lines(map, view); @@ -4432,7 +4496,9 @@ fn render_frame( } }}; } - draw_tiles!(None); + if cold { + draw_tiles!(None); + } // Layers, bottom first. let mut label_candidates: Vec = Vec::new(); @@ -4449,6 +4515,15 @@ fn render_frame( let distance = viewing_distance(map.ground_res_at(&view.camera), view.height); // Graphics text: always drawn, and other labels keep clear of it. let mut fixed_labels: Vec = Vec::new(); + if let Some(c) = cached.as_ref().and_then(|p| p.restored.as_ref()) { + pm = Canvas::from_pixmap(c.pixels.clone()); + // What the layers below left for those above: the sprites drawn, the shapeburst budget. + ctx.sprites.borrow_mut().clone_from(&c.sprites); + ctx.bursts.set(c.bursts); + label_candidates.clone_from(&c.candidates); + fixed_labels.clone_from(&c.fixed); + tile_out = c.tiles.clone(); + } let tokens = rustgis_map::graphics::TokenValues::of(map, scale); let n_layers = map.layers.len(); // Masks: layers shown only inside another layer's polygons, or left of the swipe divider. @@ -4457,9 +4532,6 @@ fn render_frame( // Of those held in another system, the ids, noted read once a label is squared to them. let mut square_held = std::collections::HashMap::new(); let square_lines = square_lines(map, &ctx, &flat, &mut square_held); - // Bottom first; a higher depth priority draws later (on top) whatever the order. - let mut order: Vec = (0..n_layers).rev().collect(); - order.sort_by_key(|i| map.layers.get(*i).map_or(0, |l| l.priority)); let clip = map.view.clip_distance.map(|d| (view.camera.center_lonlat(), d)); // Each layer group's visibility, scale range and transparency apply to its layers, its // subgroups' too (#413, #836). @@ -4487,21 +4559,45 @@ fn render_frame( .and_then(|w| Some((map.layer_by_name(&w.layer)?.id, w.shore))); // The layer drawn last, whose tile layers go over it before the next. let mut below: Option = None; - for li in order { + for (at, li) in order.into_iter().enumerate() { // Each layer drawn is a layer of the recording (#1815); what comes between them isn't. pm.layer(None); // A frame no longer wanted stops between layers (see `cancel`). if cancel::requested() { break; } + if let Some((a, pixels)) = drawn_alone.take().filter(|_| complete(&tile_out)) { + let (candidates, fixed, tiles) = (label_candidates.clone(), fixed_labels.clone(), tile_out.clone()); + let (sprites, bursts) = (ctx.sprites.borrow().clone(), ctx.bursts.get()); + captured_alone = Some((a, frame_cache::Alone { pixels, sprites, bursts, candidates, fixed, tiles })); + } // What is drawn so far already leaves a picture, waiting or in the scene (see // `pictureless`). if pictureless && (cpu_dirty || holds_picture(&cmds)) { return None; } + // Already in the picture the frame started from, with the tile layers over them. + if at < start { + continue; + } if let Some(id) = below.take() { draw_tiles!(Some(id)); } + if cached.as_ref().is_some_and(|p| p.capture_at == Some(at)) && complete(&tile_out) { + captured = Some(( + at, + frame_cache::Checkpoint { + pixels: pm.pixels().clone(), + sprites: ctx.sprites.borrow().clone(), + bursts: ctx.bursts.get(), + // Over a restored picture, its tiles are as old as that picture. + taken: cached.as_ref().and_then(|p| p.restored.as_ref()).map_or_else(web_time::Instant::now, |c| c.taken), + candidates: label_candidates.clone(), + fixed: fixed_labels.clone(), + tiles: tile_out.clone(), + }, + )); + } below = map.layers.get(li).map(|l| l.id); // The water under the shore band, read only when its layer is drawn; shore tiles on // their way leave the frame pending, for the band to be drawn once they land. @@ -4543,6 +4639,20 @@ fn render_frame( mask, ); }; + // The layer the frame started under, kept alone: composited at its opacity now, which is + // what drawing it would end with (see `frame_cache`). + if at == start + && offscreen + && let Some(a) = cached.as_ref().and_then(|p| p.recombine.as_ref()) + { + composite(&mut pm, &a.pixels); + ctx.sprites.borrow_mut().clone_from(&a.sprites); + ctx.bursts.set(a.bursts); + label_candidates.clone_from(&a.candidates); + fixed_labels.clone_from(&a.fixed); + tile_out = a.tiles.clone(); + continue; + } if let Some(rl) = &layer.raster { if let Some(data) = &rl.data { let place = match &globe { @@ -4615,6 +4725,9 @@ fn render_frame( let mut target = Pixmap::new(w, h)?; draw_it(&mut target, 1.0); composite(&mut pm, &target); + if alone_at == Some(at) { + drawn_alone = Some((at, target)); + } } else { draw_it(pm.pixels(), opacity); } @@ -5096,6 +5209,11 @@ fn render_frame( } } else { composite(&mut pm, target.pixmap()); + // Not with a selection or graphics text, drawn over the composite, nor + // with extruded charts, placed after it. + if alone_at == Some(at) && layer.selection.is_empty() && !layer.graphics && layer.extrusion.is_none() { + drawn_alone = Some((at, target.pixmap().clone())); + } } } } @@ -5802,9 +5920,17 @@ fn render_frame( if cancel::requested() || (pictureless && (cpu_dirty || holds_picture(&cmds))) { return None; } + if let Some((a, pixels)) = drawn_alone.take().filter(|_| complete(&tile_out)) { + let (candidates, fixed, tiles) = (label_candidates.clone(), fixed_labels.clone(), tile_out.clone()); + let (sprites, bursts) = (ctx.sprites.borrow().clone(), ctx.bursts.get()); + captured_alone = Some((a, frame_cache::Alone { pixels, sprites, bursts, candidates, fixed, tiles })); + } if let Some(id) = below { draw_tiles!(Some(id)); } + if let Some(plan) = cached.take() { + frame_cache::keep(plan, captured, captured_alone); + } // A band of a tilted view: the sun's glint on the terrain's water, over the water's own fill. if matches!(labels_to, Labels::Tilted(..) | Labels::Shared) && let Some(g) = TILT_GLINT.with(|g| g.borrow().clone()) diff --git a/crates/render/src/tiles.rs b/crates/render/src/tiles.rs index 1cc45ea124..4a88492b83 100644 --- a/crates/render/src/tiles.rs +++ b/crates/render/src/tiles.rs @@ -21,7 +21,7 @@ use crate::{PlacedIcon, PlacedLabel, View}; const MOSAIC: f64 = 2048.0; /// What drawing the tile layers found. -#[derive(Default)] +#[derive(Clone, Default)] pub(crate) struct TileOutput { pub labels: Vec<(PlacedLabel, f64)>, pub attribution: Vec, diff --git a/crates/tiles/src/lib.rs b/crates/tiles/src/lib.rs index 61e877feea..28954fb61a 100644 --- a/crates/tiles/src/lib.rs +++ b/crates/tiles/src/lib.rs @@ -48,6 +48,6 @@ pub mod vector_export; pub mod warp; pub use draw::{Drawn, Frame, PlacedTiles, Placement, draw, place, place_raster}; -pub use picture::{Pace, Unfinished, pace, paced, unfinished}; +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 7e3489cdd5..190ed01a2a 100644 --- a/crates/tiles/src/picture.rs +++ b/crates/tiles/src/picture.rs @@ -171,6 +171,12 @@ pub fn pace() -> Option<(Pace, Instant)> { PACE.with(|p| p.get()).map(|p| (p.pace, p.until)) } +/// What the map being drawn on this thread lacks so far (inside [`paced`]): a picture of it kept +/// partway is unfinished too. +pub fn lacking() -> Option { + PACE.with(|p| p.get()).and_then(|p| p.lacks) +} + /// Notes, for [`paced`], what the map being drawn on this thread still lacks: a renderer drawing /// at its pace calls it when it left something out or stood something in, so the map is drawn /// again (`Next`: the next frame; `Later`: once it stops moving). Outside `paced`, nothing.