From eecf66d990bcb4e57d07d93a662c01d86c080f30 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 21 Nov 2026 17:26:00 -0600 Subject: [PATCH 1/2] perf(render): keep each layer's GPU mesh between scenes of the same view (#1057) A GPU scene keeps each layer's tessellated mesh for the next scene of the same view, and takes it again while the layer looks as it did (rustgis_map::look), draws the same rows, from the same geometry copy, in the same projection, view and pixel scale. Restyling, editing or filtering one layer tessellates that layer again, not every layer. The meshes are shared (Arc) between the scenes that draw them, and the GPU map keeps the buffers it uploaded for them by their address, so the layers that look the same are not uploaded again either. A pan or a zoom still makes every mesh again: the GPU map moves a scene over the ground it was drawn for (scene_covers), which a kept mesh panned to no longer reaches, and a zoom changes the 0.35 px decimation. The kept meshes hold at most 128 MiB (32 MiB in the browser), two views a layer and one look a layer; none a scene being drawn uses goes. vector_layers_bench gains a restyle sequence and takes several files. Co-Authored-By: Claude Opus 5.5 --- crates/render/examples/vector_layers_bench.rs | 73 ++- crates/render/src/gpu_scene.rs | 11 +- crates/render/src/layer_meshes.rs | 569 ++++++++++++++++++ crates/render/src/lib.rs | 68 ++- crates/render/src/mesh.rs | 20 +- crates/ui-egui/src/mapgpu.rs | 149 ++++- 6 files changed, 815 insertions(+), 75 deletions(-) create mode 100644 crates/render/src/layer_meshes.rs diff --git a/crates/render/examples/vector_layers_bench.rs b/crates/render/examples/vector_layers_bench.rs index e07d335942..435cfd0c03 100644 --- a/crates/render/examples/vector_layers_bench.rs +++ b/crates/render/examples/vector_layers_bench.rs @@ -2,14 +2,18 @@ //! layer of a GeoPackage, and its heaviest layers alone, at 1× and 2× pixel scale, each frame the //! exact frame drawn once the map rests. //! -//! `cargo run --release -p rustgis-render --example vector_layers_bench -- map.gpkg` +//! `cargo run --release -p rustgis-render --example vector_layers_bench -- map.gpkg [more files]` //! //! - **whole:** the whole map, four times (the first builds its level of detail); //! - **zoom:** from the whole map to about a metre a point over its centre, 1.5× a step, and back //! out (the way out finds the levels of detail built on the way in, those still kept); //! - **pan 10 m / pan 3 m:** west to east across it at 10 and 3 Web Mercator metres a point, a //! quarter of the view a step, so every frame brings new features in; -//! - **tilt 10 m:** the same pan at 10 m, tilted 60°. +//! - **tilt 10 m:** the same pan at 10 m, tilted 60°; +//! - **restyle:** the top layer's fill colour changed in each of 8 frames of one view, over the +//! whole map and at 10 m a point (#1057), then the same with every layer renamed in each frame +//! too, so that none looks as it did: what each frame drew before a frame kept what still +//! stands (the picture under the changed layer on the CPU, each layer's mesh on the GPU). //! //! `BENCH_BACKEND=gpu` times the GPU scene instead (`Backend::Gpu`): what the CPU does for a GPU //! frame, tessellating the layers the GPU draws and drawing the rest into pictures, not the @@ -68,10 +72,11 @@ fn fail(why: impl std::fmt::Display) -> ! { } fn main() { - let Some(path) = std::env::args().nth(1) else { - eprintln!("usage: vector_layers_bench map.gpkg"); + let paths: Vec = std::env::args().skip(1).collect(); + if paths.is_empty() { + eprintln!("usage: vector_layers_bench map.gpkg [more files]"); return; - }; + } // `BENCH_THREADS=1` draws on one thread (the user's thread setting), to compare. if let Some(n) = std::env::var("BENCH_THREADS").ok().and_then(|n| n.parse().ok()) && let Err(e) = rustgis_data::threads::set_max(Some(n)) @@ -89,17 +94,19 @@ fn main() { } println!("{} threads, {} backend", rustgis_data::threads::max(), if backend.is_gpu() { "GPU" } else { "CPU" }); let t = std::time::Instant::now(); - let file = std::path::Path::new(&path); - let names = match rustgis_data::source::layers(file) { - Ok(n) => n, - Err(e) => fail(format!("{path}: {e}")), - }; - // Every table, or no run: "all layers" would time fewer. + // Every table of every file, or no run: "all layers" would time fewer. let mut read = Vec::new(); - for name in names { - match rustgis_data::source::open_path(file, Some(&name)).and_then(|src| rustgis_data::source::materialize(src.as_ref())) { - Ok((d, _)) => read.push(d), - Err(e) => fail(format!("{name}: {e}")), + for path in &paths { + let file = std::path::Path::new(path); + let names = match rustgis_data::source::layers(file) { + Ok(n) => n, + Err(e) => fail(format!("{path}: {e}")), + }; + for name in names { + match rustgis_data::source::open_path(file, Some(&name)).and_then(|src| rustgis_data::source::materialize(src.as_ref())) { + Ok((d, _)) => read.push(d), + Err(e) => fail(format!("{name}: {e}")), + } } } println!("read {} layers in {:.1} s", read.len(), t.elapsed().as_secs_f64()); @@ -122,7 +129,7 @@ fn main() { if !(extent.min_x.is_finite() && extent.max_x.is_finite() && extent.min_y.is_finite() && extent.max_y.is_finite()) || (extent.max_x <= extent.min_x && extent.max_y <= extent.min_y) { - fail(format!("{path}: no features with an extent to fit the views to")); + fail("no features with an extent to fit the views to"); } let (lo, hi) = (lonlat_to_merc(Coord::new(extent.min_x, extent.min_y)), lonlat_to_merc(Coord::new(extent.max_x, extent.max_y))); @@ -130,7 +137,7 @@ fn main() { // Web Mercator units a pixel showing all of it across 1920 points (a 2× screen shows the same). let whole = ((hi.x - lo.x) / 1920.0).max((hi.y - lo.y) / 1080.0); if !(whole.is_finite() && whole > 0.0) { - fail(format!("{path}: an extent that doesn't project to Web Mercator (not longitude/latitude?)")); + fail("an extent that doesn't project to Web Mercator (not longitude/latitude?)"); } println!( "extent {:.3},{:.3} to {:.3},{:.3}; whole map at {whole:.1} Mercator m a point", @@ -219,6 +226,26 @@ fn main() { let max = s.last().copied().unwrap_or(0.0); format!("{:>3} frames, median {median:6.0} ms, slowest {max:6.0} ms, total {:7.0} ms", s.len(), s.iter().sum::()) }; + // The top layer's fill changed in each frame; with `all`, every layer renamed too. + let restyle = |m: &mut Map, cam: Camera, ppp: f64, all: bool| -> Vec<(f64, Drawn)> { + let Some(top) = ids.last().copied() else { return Vec::new() }; + (0..8u8) + .map(|i| { + if let Some(l) = m.layer_mut(top) { + let fill = rustgis_map::Rgba::rgb(40 + i * 20, 120, 200 - i * 20); + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { fill, ..l.symbol(0) }); + } + if all { + for id in &ids { + if let Some(l) = m.layer_mut(*id) { + l.name = format!("{} {i}", l.name.trim_end_matches(|c: char| c.is_ascii_digit() || c == ' ')); + } + } + } + run_drawn(m, &[cam], ppp).remove(0) + }) + .collect() + }; show(&mut m, None); // `BENCH_ONLY` that names no pixel scale and sequence stops the run, not runs everything. if let Ok(only) = std::env::var("BENCH_ONLY") { @@ -263,6 +290,18 @@ fn main() { } } } + show(&mut m, None); + for ppp in [1.0f64, 2.0] { + for res in [whole, 10.0] { + for all in [false, true] { + let drawn = restyle(&mut m, camera(centre, res), ppp, all); + // The first frame of a view keeps; the next seven take what still stands. + let times: Vec = drawn.iter().skip(1).map(|d| d.0).collect(); + let what = if all { "every layer changed" } else { "the top layer restyled" }; + println!("{ppp}x restyle at {res:.1} m, {what}: {}{}", summary(×), scenes(&drawn)); + } + } + } // The layers a GPU scene draws on the CPU: each alone, over the whole map and at 3 m, flat; // after the sequences, so it warms no cache they time. if backend.is_gpu() { diff --git a/crates/render/src/gpu_scene.rs b/crates/render/src/gpu_scene.rs index 6eb8fd3a69..180e570023 100644 --- a/crates/render/src/gpu_scene.rs +++ b/crates/render/src/gpu_scene.rs @@ -104,10 +104,13 @@ pub enum DrawCmd { /// Screen-sized premultiplied RGBA, drawn covering the whole map view. The pixmap is /// moved in, not copied — flushing the CPU accumulator doesn't pay a full-screen `to_vec`. Image { pixmap: tiny_skia::Pixmap }, - /// Tessellated polygon fills and line/ring strokes of one layer run. - Mesh { origin: [f64; 2], vertices: Vec, indices: Vec }, - /// Point markers: instances of a small set of unit-space shape templates. - Points { origin: [f64; 2], instances: Vec }, + /// Tessellated polygon fills and line/ring strokes of one layer run. Shared: a layer that looks + /// as it did keeps its mesh from one scene to the next (`layer_meshes`), and the GPU keeps the + /// buffers of a mesh it has uploaded while the mesh lives. + Mesh { origin: [f64; 2], vertices: Arc>, indices: Arc> }, + /// Point markers: instances of a small set of unit-space shape templates, shared as + /// [`DrawCmd::Mesh`] is. + Points { origin: [f64; 2], instances: Arc> }, /// Extruded features standing up in a tilted view: roofs and walls, lit and drawn with a /// depth buffer (as MapLibre's fill extrusions), or, with `shadows`, the shadows they cast /// on the ground, drawn under every feature. diff --git a/crates/render/src/layer_meshes.rs b/crates/render/src/layer_meshes.rs new file mode 100644 index 0000000000..7122e90345 --- /dev/null +++ b/crates/render/src/layer_meshes.rs @@ -0,0 +1,569 @@ +//! Each layer's GPU mesh kept from one scene to the next (#1057): restyling, editing or +//! filtering one layer of a map drawn on the GPU tessellates that layer again, not every layer. +//! +//! A layer's mesh ([`crate::mesh::collect_layer`]) is made from the layer, the geometry copy it +//! draws, the rows it draws, and the view: which features reach it (the GPU's cull, wider than +//! the view so the camera can move the scene), the 0.35 px decimation, the stroke widths in +//! pixels and where f32 holds its vertices. A kept mesh is taken again when all of those are +//! as they were: the layer by its look ([`LayerLook`]), the rest by [`Made`] and the rows drawn. +//! The mesh taken is then the one tessellating the layer again would make, vertex for vertex. +//! +//! A pan or a zoom makes the layers again. The GPU map moves a scene with the camera over the +//! ground it was drawn for, so a scene must reach past the view as far as a new one would; a +//! kept mesh panned to doesn't. Zoomed in, its decimation would be coarser than a new one's, and +//! zoomed out it reaches less far. +//! +//! Only screen scenes keep meshes, not a turned or tilted view's bands (their own views, sized +//! again after) nor exports, and only layers with a look: a layer read from its source draws +//! what each read gives. The meshes are shared with the scenes that draw them (`Arc`), so a +//! scene shown costs no more; what this keeps beside it is the last scene's meshes, within +//! [`MAX_BYTES`]. + +use std::sync::Arc; + +use rustgis_geom::Extent; +use rustgis_map::Projection; +use rustgis_map::look::{Change, LayerLook}; + +use crate::gpu_scene::{DrawCmd, MeshVertex, PointInstance}; + +/// The most bytes of meshes kept, with what each was made from ([`ENTRY_BYTES`] and its rows): +/// about 3.3 million vertices on the desktop and 0.8 million in the browser. Past it, the meshes +/// used longest ago go first, but never one a scene being drawn has used ([`Scene`]): when the +/// newest doesn't fit beside those, it isn't kept. A layer's mesh is at most +/// [`crate::mesh::MAX_LAYER_VERTICES`] vertices, 80 MB. +pub(crate) const MAX_BYTES: usize = if cfg!(target_arch = "wasm32") { 32 << 20 } else { 128 << 20 }; + +/// What a kept mesh is counted as holding beside its data and rows: its layer's look (the +/// layer's settings, its renderer's classes among them) and the rest of the entry. A layer's +/// selection, which the look copies, is counted on top. A look can hold more (its fields' value +/// lists, say), but a layer keeps one, shared by its views, and drops the meshes of a look it no +/// longer has: what this holds of a layer's settings is one copy of them at most. +const ENTRY_BYTES: usize = 16 << 10; + +/// The views a layer keeps meshes for: the one on screen and the one before it (a map and its +/// split view, say). +const VIEWS: usize = 2; + +/// Which copy of a layer's geometry its mesh is made from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Drawn { + /// Its rows projected, as they are. + Projected, + /// Thinned for the view's level of detail ([`rustgis_map::lod`]). + Thinned(Option), + /// The display copy of that level, from longitude/latitude rows. + Display(Option), +} + +/// What a layer's mesh is made from besides the layer and its rows. +#[derive(Clone, Debug)] +pub(crate) struct Made { + /// The map's projection, which the geometry copies are in. + pub projection: Projection, + pub drawn: Drawn, + /// The features kept: those reaching this extent (`GPU_CULL_MARGIN` around the view). + pub cull: Extent, + /// Map units per physical pixel: the decimation, the stroke widths and the f32 reach. + pub map_per_px: f64, + /// Physical pixels per point, a reference scale's growth included: marker and stroke sizes. + pub ppp: f32, + pub wireframe: bool, +} + +impl Made { + /// Whether a mesh made from `self` is the one `other` makes. + fn same(&self, other: &Made) -> bool { + let extent = |e: &Extent| [e.min_x, e.min_y, e.max_x, e.max_y].map(f64::to_bits); + self.projection == other.projection + && self.drawn == other.drawn + && extent(&self.cull) == extent(&other.cull) + && self.map_per_px.to_bits() == other.map_per_px.to_bits() + && self.ppp.to_bits() == other.ppp.to_bits() + && self.wireframe == other.wireframe + } +} + +/// One layer's mesh and what it was made from. +struct Kept { + /// The live layer it was made for ([`rustgis_map::Layer::instance_id`]: a layer's id repeats + /// from map to map). + layer: u64, + /// Shared by the layer's views: a layer keeps one look, the one it was last drawn with. + look: Arc, + made: Made, + /// The rows drawn: the definition query, the display filters at the view's scale and the + /// time shown, as they applied. + rows: Vec, + /// The layer's Mesh and Points commands, sharing their data with the scenes that drew them. + cmds: Vec, + /// The mesh's vertices, which the layer's vertex limit counts. + vertices: usize, + bytes: usize, + /// When it was last taken or kept ([`Meshes::clock`]). + used: u64, +} + +#[derive(Default)] +struct Meshes { + kept: Vec, + clock: u64, + /// The scenes being drawn ([`Scene`]), by number, with the clock when each began. + drawing: Vec<(u64, u64)>, + scenes: u64, +} + +impl Meshes { + /// Whether a scene being drawn may have used `k`: taken or kept since the first of them began. + fn in_use(&self, k: &Kept) -> bool { + self.drawing.iter().map(|d| d.1).min().is_some_and(|began| k.used > began) + } +} + +/// A command sharing `cmd`'s data, when it is a mesh or points. +fn share(cmd: &DrawCmd) -> Option { + match cmd { + DrawCmd::Mesh { origin, vertices, indices } => { + Some(DrawCmd::Mesh { origin: *origin, vertices: Arc::clone(vertices), indices: Arc::clone(indices) }) + } + DrawCmd::Points { origin, instances } => Some(DrawCmd::Points { origin: *origin, instances: Arc::clone(instances) }), + _ => None, + } +} + +/// The bytes `cmds` hold, as allocated. +fn bytes_of(cmds: &[DrawCmd]) -> usize { + cmds.iter() + .map(|c| match c { + DrawCmd::Mesh { vertices, indices, .. } => { + vertices.capacity() * std::mem::size_of::() + indices.capacity() * std::mem::size_of::() + } + DrawCmd::Points { instances, .. } => instances.capacity() * std::mem::size_of::(), + _ => 0, + }) + .sum() +} + +/// The kept meshes, shared by the threads that draw scenes (the UI's and the one that draws a +/// view once it settles). +#[cfg(not(test))] +static MESHES: std::sync::Mutex = std::sync::Mutex::new(Meshes { kept: Vec::new(), clock: 0, drawing: Vec::new(), scenes: 0 }); + +/// Runs `f` on the kept meshes. +#[cfg(not(test))] +fn with_meshes(f: impl FnOnce(&mut Meshes) -> R) -> R { + // A thread that panicked while holding them left nothing half done: each is replaced whole. + f(&mut MESHES.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 MESHES: std::cell::RefCell = std::cell::RefCell::new(Meshes::default()); + /// The layers whose meshes scenes took, by id. + static TAKEN: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +#[cfg(test)] +fn with_meshes(f: impl FnOnce(&mut Meshes) -> R) -> R { + MESHES.with_borrow_mut(f) +} + +/// A scene being drawn, from [`Scene::begin`] until it is dropped (when the scene is done, +/// stopped or failed): while it lasts, no mesh a scene being drawn has used goes, though another +/// scene drawn at the same time (on the UI's thread and a worker's) keeps meshes too. +pub(crate) struct Scene(u64); + +impl Scene { + pub(crate) fn begin() -> Scene { + with_meshes(|m| { + m.scenes += 1; + let n = m.scenes; + m.drawing.push((n, m.clock)); + Scene(n) + }) + } +} + +impl Drop for Scene { + fn drop(&mut self) { + let n = self.0; + with_meshes(|m| m.drawing.retain(|d| d.0 != n)); + } +} + +/// The commands of the mesh kept for the layer that looks as `look`, made as `made` from `rows`, +/// pushed onto `cmds`, and its vertices; `None`, pushing nothing, when none is kept. +pub(crate) fn take(cmds: &mut Vec, look: &LayerLook, made: &Made, rows: &[bool]) -> Option { + let vertices = with_meshes(|m| { + m.clock += 1; + let clock = m.clock; + let k = m + .kept + .iter_mut() + .find(|k| k.look.id() == look.id() && k.made.same(made) && k.look.change(look) == Change::Same && k.rows == rows)?; + k.used = clock; + cmds.extend(k.cmds.iter().filter_map(share)); + Some(k.vertices) + })?; + #[cfg(test)] + TAKEN.with_borrow_mut(|t| t.push(look.id())); + Some(vertices) +} + +/// Keeps `cmds` (a layer's Mesh and Points commands, of `vertices` vertices) for the next scene, +/// in place of what the live layer `layer` had kept for the same view, and of its oldest view past +/// [`VIEWS`]; `selected` is how many rows the layer has selected, which its look holds. See +/// [`MAX_BYTES`] for what goes when they don't all fit: nothing goes unless this is kept. A layer +/// with nothing in view keeps nothing: it is quick to find so again. Called while a [`Scene`] is +/// drawn. +pub(crate) fn keep(layer: u64, look: LayerLook, made: Made, rows: &[bool], cmds: &[DrawCmd], vertices: usize, selected: usize) { + keep_within(MAX_BYTES, layer, look, made, rows, cmds, vertices, selected); +} + +/// [`keep`], within `max` bytes. +#[expect(clippy::too_many_arguments, reason = "a mesh, what it was made from, and the budget it is kept within")] +fn keep_within(max: usize, layer: u64, look: LayerLook, made: Made, rows: &[bool], cmds: &[DrawCmd], vertices: usize, selected: usize) { + let cmds: Vec = cmds.iter().filter_map(share).collect(); + let bytes = bytes_of(&cmds) + .saturating_add(rows.len()) + .saturating_add(ENTRY_BYTES) + .saturating_add(selected.saturating_mul(std::mem::size_of::())); + if cmds.is_empty() || bytes > max { + return; + } + with_meshes(|m| { + // What goes for this one, worked out before anything goes: the layer's meshes of another + // look (they no longer match), the one of this view, and past `VIEWS` its oldest; none + // that a scene being drawn uses. + let mut out: Vec = Vec::new(); + let mut views: Vec<(u64, usize)> = Vec::new(); + let mut shared: Option> = None; + for (i, k) in m.kept.iter().enumerate().filter(|(_, k)| k.layer == layer) { + let same_look = k.look.change(&look) == Change::Same; + if same_look && shared.is_none() { + shared = Some(Arc::clone(&k.look)); + } + if !same_look || k.made.same(&made) { + if m.in_use(k) { + return; + } + out.push(i); + } else { + views.push((k.used, i)); + } + } + if views.len() >= VIEWS { + views.sort_unstable(); + for (_, i) in views.iter().take(views.len() + 1 - VIEWS) { + if m.kept.get(*i).is_some_and(|k| m.in_use(k)) { + return; + } + out.push(*i); + } + } + // Kept only beside what the scenes being drawn use, which stays; then the meshes used + // longest ago go first. + let in_use: usize = m.kept.iter().filter(|k| m.in_use(k)).map(|k| k.bytes).sum(); + if in_use.saturating_add(bytes) > max { + return; + } + let mut total: usize = m.kept.iter().enumerate().filter(|(i, _)| !out.contains(i)).map(|(_, k)| k.bytes).sum::(); + total = total.saturating_add(bytes); + let mut old: Vec<(u64, usize)> = + m.kept.iter().enumerate().filter(|(i, k)| !out.contains(i) && !m.in_use(k)).map(|(i, k)| (k.used, i)).collect(); + old.sort_unstable(); + for (_, i) in old { + if total <= max { + break; + } + total = total.saturating_sub(m.kept.get(i).map_or(0, |k| k.bytes)); + out.push(i); + } + out.sort_unstable_by(|a, b| b.cmp(a)); + out.dedup(); + for i in out { + m.kept.swap_remove(i); + } + m.clock += 1; + let used = m.clock; + let look = shared.unwrap_or_else(|| Arc::new(look)); + m.kept.push(Kept { layer, look, made, rows: rows.to_vec(), cmds, vertices, bytes, used }); + }); +} + +/// The layers whose meshes scenes took since the last call, by id. +#[cfg(test)] +pub(crate) fn taken() -> Vec { + TAKEN.take() +} + +/// Forgets the meshes kept on this test thread. +#[cfg(test)] +pub(crate) fn clear() { + MESHES.with_borrow_mut(|m| m.kept.clear()); + TAKEN.take(); +} + +/// The bytes the meshes kept on this test thread hold. +#[cfg(test)] +pub(crate) fn kept_bytes() -> usize { + MESHES.with_borrow(|m| m.kept.iter().map(|k| k.bytes).sum()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gpu_scene::GpuScene; + use crate::{Backend, RenderOutput, View, render_backend}; + use rustgis_data::{Dataset, Geometry, GeometryType}; + use rustgis_geom::{Coord, Extent}; + use rustgis_map::{Camera, Map, Renderer, Rgba, Symbol}; + + fn square(x: f64, s: f64) -> Geometry { + Geometry::Polygon(vec![vec![vec![Coord::new(x, 0.0), Coord::new(x + s, 0.0), Coord::new(x + s, s), Coord::new(x, s)]]]) + } + + /// A map of two polygon layers drawn on the GPU, `a` under `b`, and a view of them. + fn two_layers() -> (Map, u32, u32, View) { + let mut m = Map::new("Map"); + // Only the layers' meshes: no basemap or grid. + m.basemap = rustgis_map::Basemap::Blank; + m.graticule = false; + let mut layer = |name: &str, x: f64| { + let mut d = Dataset::new(name, GeometryType::Polygon, vec![]); + d.push(Some(square(x, 1.0)), vec![]); + m.add_dataset(d) + }; + let (a, b) = (layer("a", 0.0), layer("b", 2.0)); + let camera = Camera { center: rustgis_geom::lonlat_to_merc(Coord::new(1.5, 0.5)), res: 2000.0, bearing: 0.0, pitch: 0.0 }; + (m, a, b, View { width: 400.0, height: 300.0, pixels_per_point: 1.0, camera, sky: false }) + } + + /// The GPU scene of `view`; a frame drawn on the CPU instead fails the test. + fn scene(m: &mut Map, view: &View) -> GpuScene { + match render_backend(m, view, Backend::Gpu) { + Some(RenderOutput::Gpu(s)) => s, + _ => panic!("no GPU scene"), + } + } + + /// Each Mesh command's vertices and indices, by address and by value. + fn meshes(s: &GpuScene) -> Vec<(*const Vec, Vec<[u32; 4]>, Vec)> { + s.cmds + .iter() + .filter_map(|c| match c { + DrawCmd::Mesh { vertices, indices, .. } => Some(( + Arc::as_ptr(vertices), + vertices + .iter() + .map(|v| [v.position[0].to_bits(), v.position[1].to_bits(), v.color[0].to_bits(), v.stroke_px.to_bits()]) + .collect(), + indices.to_vec(), + )), + _ => None, + }) + .collect() + } + + /// Gives layer `id` one symbol filled with `fill`. + fn restyle(m: &mut Map, id: u32, fill: Rgba) { + if let Some(l) = m.layers.iter_mut().find(|l| l.id == id) { + l.renderer = Renderer::Single(Symbol { fill, ..l.symbol(0) }); + } + } + + /// A scene of the same view after one layer was restyled takes the other's mesh, shared + /// with the last scene, and tessellates the restyled one again: the same commands, vertex for + /// vertex, as a scene drawn with nothing kept. + #[test] + fn a_layer_that_looks_the_same_keeps_its_mesh() { + clear(); + let (mut m, a, b, view) = two_layers(); + let first = meshes(&scene(&mut m, &view)); + assert_eq!(first.len(), 2, "one mesh a layer"); + assert!(taken().is_empty(), "the first scene keeps, takes nothing"); + assert!(kept_bytes() > 0); + restyle(&mut m, b, Rgba::rgb(200, 0, 0)); + let second = meshes(&scene(&mut m, &view)); + assert_eq!(taken(), vec![a], "only the layer that looks the same"); + assert_eq!(second[0].0, first[0].0, "a's mesh is shared with the last scene"); + assert_ne!(second[1].0, first[1].0, "b's is made again"); + assert_ne!(second[1].1, first[1].1, "in its new colour"); + clear(); + let fresh = meshes(&scene(&mut m, &view)); + let values = |ms: &[(*const Vec, Vec<[u32; 4]>, Vec)]| { + ms.iter().map(|(_, v, i)| (v.clone(), i.clone())).collect::>() + }; + assert_eq!(values(&second), values(&fresh), "the same scene as one made from nothing"); + // Unchanged, the next scene takes both. + let _ = scene(&mut m, &view); + assert_eq!(taken(), vec![a, b]); + } + + /// A pan, a zoom, an edit to a layer's rows or its definition query each make the mesh + /// again; so does an export, which keeps nothing. + #[test] + fn a_moved_view_or_a_changed_layer_makes_its_mesh_again() { + clear(); + let (mut m, a, b, view) = two_layers(); + let _ = scene(&mut m, &view); + let mut panned = view; + panned.camera.center.x += 50.0 * view.camera.res; + let _ = scene(&mut m, &panned); + assert!(taken().is_empty(), "a pan"); + let _ = scene(&mut m, &view); + assert_eq!(taken(), vec![a, b], "back where it was kept"); + let mut zoomed = view; + zoomed.camera.res *= 0.9; + let _ = scene(&mut m, &zoomed); + assert!(taken().is_empty(), "a zoom"); + // A layer keeps two views: the zoomed one put out the panned one, not this one. + let _ = scene(&mut m, &panned); + assert!(taken().is_empty(), "the panned view's went"); + let _ = scene(&mut m, &zoomed); + assert_eq!(taken(), vec![a, b]); + let _ = scene(&mut m, &view); + assert!(taken().is_empty(), "made again for the view"); + if let Some(l) = m.layers.iter_mut().find(|l| l.id == a) { + l.dataset.push(Some(square(0.2, 0.5)), vec![]); + } + let _ = scene(&mut m, &view); + assert_eq!(taken(), vec![b], "a's rows were edited"); + if let Some(l) = m.layers.iter_mut().find(|l| l.id == b) { + l.definition_query = Some("1 = 0".into()); + } + let _ = scene(&mut m, &view); + assert_eq!(taken(), vec![a], "b's definition query changed"); + let bytes = kept_bytes(); + let _ = crate::render(&mut m, &view); + assert_eq!(kept_bytes(), bytes, "the CPU renderer keeps no meshes"); + } + + /// Meshes that don't all fit: a scene keeps what fits and never puts out a mesh it uses + /// itself, so the next scenes take those same meshes rather than each pushing out the next one + /// the scene needs. One with nothing in view keeps nothing. + #[test] + fn a_scene_keeps_the_meshes_it_uses_when_they_dont_all_fit() { + clear(); + let (mut m, a, b, view) = two_layers(); + let mut d = Dataset::new("c", GeometryType::Polygon, vec![]); + d.push(Some(square(4.0, 1.0)), vec![]); + let c = m.add_dataset(d); + let made = Made { + projection: m.projection.clone(), + drawn: Drawn::Projected, + cull: view.camera.extent(view.width, view.height), + map_per_px: view.camera.res, + ppp: 1.0, + wireframe: false, + }; + let mesh = |n: usize| DrawCmd::Mesh { + origin: [0.0; 2], + vertices: Arc::new(vec![bytemuck::Zeroable::zeroed(); n]), + indices: Arc::new(Vec::new()), + }; + let one = bytes_of(&[mesh(4096)]) + ENTRY_BYTES + 1; + // Room for two of the three. + let max = one * 5 / 2; + let look = |m: &Map, id: u32| m.layers.iter().find(|l| l.id == id).and_then(LayerLook::of).expect("look"); + let live = |m: &Map, id: u32| m.layers.iter().find(|l| l.id == id).map_or(0, |l| l.instance_id()); + let draw = |m: &Map, sizes: [usize; 3]| -> Vec { + let _scene = Scene::begin(); + [a, b, c] + .into_iter() + .zip(sizes) + .filter(|(id, n)| { + let taken = take(&mut Vec::new(), &look(m, *id), &made, &[true]).is_some(); + if !taken { + keep_within(max, live(m, *id), look(m, *id), made.clone(), &[true], &[mesh(*n)], *n, 0); + } + taken + }) + .map(|(id, _)| id) + .collect() + }; + let even = [4096; 3]; + assert!(draw(&m, even).is_empty()); + assert_eq!(draw(&m, even), vec![a, b], "the first two, kept by the first scene"); + restyle(&mut m, c, Rgba::rgb(200, 0, 0)); + assert_eq!(draw(&m, even), vec![a, b], "the third, restyled, doesn't put them out"); + assert!(kept_bytes() <= max); + // One that doesn't fit beside those the scene uses puts none out first: here the second, + // too big beside the first, leaves the third kept. + clear(); + let uneven = [6000, 5000, 3000]; + assert!(draw(&m, uneven).is_empty()); + assert_eq!(draw(&m, uneven), vec![a, c]); + assert_eq!(draw(&m, uneven), vec![a, c]); + // With another scene still drawing (begun first, on another thread), the same. + clear(); + let first = Scene::begin(); + assert!(draw(&m, even).is_empty()); + assert_eq!(draw(&m, even), vec![a, b]); + drop(first); + // Nothing in view: nothing kept, nothing put out. + let _scene = Scene::begin(); + let bytes = kept_bytes(); + keep_within(max, live(&m, a), look(&m, a), made.clone(), &[true], &[], 0, 0); + assert_eq!(kept_bytes(), bytes); + } + + /// A mesh is kept only when nothing it would put out is still in use, and it puts nothing out + /// unless it is kept: a third view too big beside what a scene uses leaves the layer's two + /// views; a mesh kept by one scene isn't replaced by another drawing the same view at the same + /// time; and two maps' layers of the same id keep their meshes apart. + #[test] + fn a_mesh_kept_puts_out_only_what_no_scene_uses() { + clear(); + let (m, a, b, view) = two_layers(); + let at = |dx: f64| Made { + projection: m.projection.clone(), + drawn: Drawn::Projected, + cull: { + let e = view.camera.extent(view.width, view.height); + Extent::new(e.min_x + dx, e.min_y, e.max_x + dx, e.max_y) + }, + map_per_px: view.camera.res, + ppp: 1.0, + wireframe: false, + }; + let mesh = |n: usize| DrawCmd::Mesh { + origin: [0.0; 2], + vertices: Arc::new(vec![bytemuck::Zeroable::zeroed(); n]), + indices: Arc::new(Vec::new()), + }; + let size = |n: usize| bytes_of(&[mesh(n)]) + ENTRY_BYTES + 1; + let max = size(6000) + size(3000) + size(500); + let layer = |m: &Map, id: u32| m.layers.iter().find(|l| l.id == id).expect("layer").clone(); + let (la, lb) = (layer(&m, a), layer(&m, b)); + let look = |l: &rustgis_map::Layer| LayerLook::of(l).expect("look"); + let keep_at = + |l: &rustgis_map::Layer, dx: f64, n: usize| keep_within(max, l.instance_id(), look(l), at(dx), &[true], &[mesh(n)], n, 0); + let has = |l: &rustgis_map::Layer, dx: f64| take(&mut Vec::new(), &look(l), &at(dx), &[true]); + { + let _old = Scene::begin(); + keep_at(&la, 0.0, 500); + keep_at(&la, 1.0, 3000); + } + let _scene = Scene::begin(); + keep_at(&lb, 0.0, 6000); + // A third view of `a` would put out its oldest, but doesn't fit beside `b`'s, in use. + keep_at(&la, 2.0, 4000); + assert_eq!((has(&la, 0.0), has(&la, 1.0), has(&la, 2.0)), (Some(500), Some(3000), None)); + // Kept again for the same view while in use: the first stays. + keep_at(&la, 0.0, 400); + assert_eq!(has(&la, 0.0), Some(500)); + drop(_scene); + // Another map's layer of the same id keeps its own. + clear(); + let (m2, a2, ..) = two_layers(); + let other = layer(&m2, a2); + assert_eq!(other.id, la.id); + let _scene = Scene::begin(); + keep_at(&la, 0.0, 500); + keep_at(&other, 0.0, 400); + keep_at(&other, 1.0, 400); + assert_eq!((has(&la, 0.0), has(&other, 0.0)), (Some(500), Some(400))); + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 1e534d64dd..691d3778f5 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -42,6 +42,7 @@ pub mod terrain; mod text; pub use text::CALLOUT_WIDTH; mod frame_cache; +mod layer_meshes; pub mod tile_mesh; mod tiles; pub mod vector; @@ -3132,8 +3133,8 @@ fn gpu_turned( if (k - 1.0).abs() > 1e-6 { for c in &mut scene.cmds { match c { - DrawCmd::Mesh { vertices, .. } => vertices.iter_mut().for_each(|v| v.stroke_px *= k), - DrawCmd::Points { instances, .. } => instances.iter_mut().for_each(|p| p.radius_px *= k), + DrawCmd::Mesh { vertices, .. } => std::sync::Arc::make_mut(vertices).iter_mut().for_each(|v| v.stroke_px *= k), + DrawCmd::Points { instances, .. } => std::sync::Arc::make_mut(instances).iter_mut().for_each(|p| p.radius_px *= k), DrawCmd::Image { .. } | DrawCmd::Extrusion { .. } | DrawCmd::Tiles { .. } @@ -3196,7 +3197,7 @@ fn gpu_turned( .flat_map(|m| mesh::marker_instances(m.at, origin, &m.symbol, ppp, m.selected.then_some(SELECTION))) .collect(); if !instances.is_empty() { - cmds.push(DrawCmd::Points { origin, instances }); + cmds.push(DrawCmd::Points { origin, instances: std::sync::Arc::new(instances) }); clips.push(CmdClip { upright: true, ..CmdClip::ALL }); } let unplaced = if map.label_display.show_unplaced { placed.unplaced } else { Vec::new() }; @@ -4263,6 +4264,11 @@ fn render_frame( Some(g) => g.may_see(e), None => e.intersects(&mesh_cull), }; + // A screen scene keeps each layer's mesh for the next of the same view, and takes those still + // standing (see `layer_meshes`): the map's projection, which the meshes are in, when it does. + let mesh_projection = (gpu && !full_res_rasters && matches!(labels_to, Labels::Own)).then(|| map.projection.clone()); + // The meshes this scene takes and keeps stay kept while it is drawn. + let _mesh_scene = mesh_projection.is_some().then(layer_meshes::Scene::begin); // 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)); @@ -5030,18 +5036,50 @@ fn render_frame( if gpu_layer { flush_acc(pm.pixels(), &mut cmds, &mut cpu_dirty) .ok_or_else(|| rustgis_data::DataError::Format("cannot allocate render target".into()))?; - let collected = mesh::collect_layer( - &mut cmds, - layer, - &drawn, - extents, - &rows, - &mesh_visible, - ctx.wireframe, - ctx.ppp, - map_per_px, - mesh_room, - ); + // Kept from the last scene of this view when the layer looks as it did (a layer read + // from its source has no look, and draws in batches). + let keeping = mesh_projection.as_ref().filter(|_| !complete_source).and_then(|projection| { + let level = rustgis_map::lod::level(thin_tol); + let drawn_copy = if display_only { + layer_meshes::Drawn::Display(level) + } else if std::ptr::eq(layer.thinned_cache(thin_tol), layer.projected_cache()) { + layer_meshes::Drawn::Projected + } else { + layer_meshes::Drawn::Thinned(level) + }; + let made = layer_meshes::Made { + projection: projection.clone(), + drawn: drawn_copy, + cull: mesh_cull, + map_per_px, + ppp: ctx.ppp, + wireframe: ctx.wireframe, + }; + Some((rustgis_map::look::LayerLook::of(layer)?, made)) + }); + let before = cmds.len(); + let collected = match keeping.as_ref().and_then(|(look, made)| layer_meshes::take(&mut cmds, look, made, &rows)) { + Some(used) => Ok(used), + None => { + let collected = mesh::collect_layer( + &mut cmds, + layer, + &drawn, + extents, + &rows, + &mesh_visible, + ctx.wireframe, + ctx.ppp, + map_per_px, + mesh_room, + ); + if let (Ok(used), Some((look, made))) = (collected, keeping) { + let kept = cmds.get(before..).unwrap_or_default(); + layer_meshes::keep(layer.instance_id(), look, made, &rows, kept, used, layer.selection.len()); + } + collected + } + }; // Once a batch is too dense, the layer's later ones fall back too (they get no // room); one lyon refused leaves the room to the batches after it. mesh_room = match collected { diff --git a/crates/render/src/mesh.rs b/crates/render/src/mesh.rs index e41cbf0a06..0cdc0174d0 100644 --- a/crates/render/src/mesh.rs +++ b/crates/render/src/mesh.rs @@ -5,6 +5,8 @@ //! the camera fast path shows it at (strokes are tessellated at the widest of those, see //! [`tessellation_width`]). +use std::sync::Arc; + use lyon::path::Path; use lyon::tessellation::{ BuffersBuilder, FillGeometryBuilder, FillOptions, FillRule, FillTessellator, FillVertex, GeometryBuilder, LineCap, LineJoin, @@ -496,10 +498,10 @@ pub(crate) fn collect_layer( } let used = v.len(); if !i.is_empty() { - cmds.push(DrawCmd::Mesh { origin, vertices: v, indices: i }); + cmds.push(DrawCmd::Mesh { origin, vertices: Arc::new(v), indices: Arc::new(i) }); } if !pts.is_empty() { - cmds.push(DrawCmd::Points { origin, instances: pts }); + cmds.push(DrawCmd::Points { origin, instances: Arc::new(pts) }); } Ok(used) } @@ -509,10 +511,12 @@ pub(crate) fn collect_layer( pub(crate) fn collect_highlight(cmds: &mut Vec, g: &Geometry, s: &Symbol, ppp: f32, map_per_px: f64) -> Result<(), TessError> { let origin = origin_for(&g.extent(), map_per_px)?; match g { - Geometry::Point(c) => cmds.push(DrawCmd::Points { origin, instances: marker_instances(*c, origin, s, ppp, Some(SELECTION)) }), + Geometry::Point(c) => { + cmds.push(DrawCmd::Points { origin, instances: Arc::new(marker_instances(*c, origin, s, ppp, Some(SELECTION))) }) + } Geometry::MultiPoint(cs) => { let instances: Vec = cs.iter().flat_map(|c| marker_instances(*c, origin, s, ppp, Some(SELECTION))).collect(); - cmds.push(DrawCmd::Points { origin, instances }); + cmds.push(DrawCmd::Points { origin, instances: Arc::new(instances) }); } Geometry::Line(parts) => { let (mut v, mut i) = (Vec::new(), Vec::new()); @@ -523,7 +527,7 @@ pub(crate) fn collect_highlight(cmds: &mut Vec, g: &Geometry, s: &Symbo )?; extend_mesh(&mut v, &mut i, stroke_lines(parts, origin, premul(s.stroke), s.stroke_width * ppp, map_per_px, NO_LIMIT))?; if !i.is_empty() { - cmds.push(DrawCmd::Mesh { origin, vertices: v, indices: i }); + cmds.push(DrawCmd::Mesh { origin, vertices: Arc::new(v), indices: Arc::new(i) }); } } Geometry::Polygon(polys) => { @@ -531,7 +535,7 @@ pub(crate) fn collect_highlight(cmds: &mut Vec, g: &Geometry, s: &Symbo extend_mesh(&mut v, &mut i, fill_polygon(polys, origin, premul(SELECTION.with_alpha(40)), map_per_px, NO_LIMIT))?; extend_mesh(&mut v, &mut i, stroke_rings(polys, origin, premul(SELECTION), 2.0 * ppp, map_per_px, NO_LIMIT))?; if !i.is_empty() { - cmds.push(DrawCmd::Mesh { origin, vertices: v, indices: i }); + cmds.push(DrawCmd::Mesh { origin, vertices: Arc::new(v), indices: Arc::new(i) }); } } } @@ -555,7 +559,7 @@ pub(crate) fn collect_basemap( extend_mesh(&mut v, &mut i, stroke_rings(polys, origin, premul(outline), 0.6 * ppp, map_per_px, NO_LIMIT))?; } if !i.is_empty() { - cmds.push(DrawCmd::Mesh { origin, vertices: v, indices: i }); + cmds.push(DrawCmd::Mesh { origin, vertices: Arc::new(v), indices: Arc::new(i) }); } Ok(()) } @@ -574,7 +578,7 @@ pub(crate) fn collect_graticule( let (mut v, mut i) = (Vec::new(), Vec::new()); extend_mesh(&mut v, &mut i, stroke_lines(lines, origin, premul(grat), width * ppp, map_per_px, NO_LIMIT))?; if !i.is_empty() { - cmds.push(DrawCmd::Mesh { origin, vertices: v, indices: i }); + cmds.push(DrawCmd::Mesh { origin, vertices: Arc::new(v), indices: Arc::new(i) }); } Ok(()) } diff --git a/crates/ui-egui/src/mapgpu.rs b/crates/ui-egui/src/mapgpu.rs index 9c1b3d360d..2480586252 100644 --- a/crates/ui-egui/src/mapgpu.rs +++ b/crates/ui-egui/src/mapgpu.rs @@ -264,6 +264,8 @@ pub(crate) struct GpuMapRenderer { tile_textures: std::sync::Mutex, /// The vector tile meshes uploaded so far, kept across scenes. tile_meshes: std::sync::Mutex, + /// The layers' meshes and markers the latest scene uploaded, for the next to share. + layer_buffers: std::sync::Mutex, /// The live raster tile layers' pictures and per-frame instances (#635). pub(crate) live: std::sync::Mutex, /// The last frame left live tile pictures to upload: draw again. @@ -546,6 +548,7 @@ impl GpuMapRenderer { samples, tile_textures: Default::default(), tile_meshes: Default::default(), + layer_buffers: Default::default(), live: std::sync::Mutex::new(crate::tilelayer::LiveTiles::new(device, scene_format, samples, DEPTH_FORMAT)), live_backlog: std::sync::atomic::AtomicBool::new(false), } @@ -827,6 +830,53 @@ impl TileMeshBuffers { } } +/// The layers' meshes and markers on the GPU, by the address of their data, which the renderer +/// shares from scene to scene while a layer looks as it did (`render::layer_meshes`): a scene +/// draws those from the buffers an earlier one uploaded (the map's or a split view's). Both are +/// held weakly: a buffer lives as long as a scene that draws it, so these cost no GPU memory +/// beside the scenes on screen, and none once the map leaves the GPU. +#[derive(Default)] +struct LayerBuffers { + by_data: std::collections::HashMap, +} + +struct LayerBuffer { + data: std::sync::Weak, + buffer: std::sync::Weak>, +} + +impl LayerBuffers { + /// The buffer holding `data`, uploaded the first time a scene draws it. + fn buffer( + &mut self, + device: &wgpu::Device, + data: &Arc>, + label: &'static str, + usage: wgpu::BufferUsages, + ) -> Arc> { + let key = Arc::as_ptr(data) as usize; + // While the data lives its address is its own: the weak reference keeps another from it. + if let Some(b) = self.by_data.get_mut(&key) + && b.data.upgrade().is_some_and(|d| Arc::as_ptr(&d).cast::<()>() as usize == key) + && let Some(buffer) = b.buffer.upgrade() + { + return buffer; + } + let buffer = Arc::new(owned_buffer( + device, + &wgpu::util::BufferInitDescriptor { label: Some(label), contents: bytemuck::cast_slice(data.as_slice()), usage }, + )); + let shared: Arc = data.clone(); + self.by_data.insert(key, LayerBuffer { data: Arc::downgrade(&shared), buffer: Arc::downgrade(&buffer) }); + buffer + } + + /// Ends a scene: forgets the buffers no scene draws any longer, and those of data gone. + fn end_scene(&mut self) { + self.by_data.retain(|_, b| b.data.strong_count() > 0 && b.buffer.strong_count() > 0); + } +} + /// One tile of an uploaded vector tile layer. pub(crate) struct MeshTileDraw { mesh: Arc, @@ -961,17 +1011,19 @@ fn record_scene(r: &GpuMapRenderer, draws: &[SceneDraw], clear: [f32; 4], tgt: & /// One uploaded draw command. pub(crate) enum SceneDraw { + /// A layer's mesh, its buffers shared with the scenes before it while it looks the same. Mesh { - vertices: Owned, - indices: Owned, + vertices: Arc>, + indices: Arc>, index_count: u32, uniforms: Owned, bind: wgpu::BindGroup, origin: [f64; 2], clip: CmdClip, }, + /// A layer's markers, shared as a mesh's buffers are. Points { - instances: Owned, + instances: Arc>, count: u32, uniforms: Owned, bind: wgpu::BindGroup, @@ -1194,6 +1246,7 @@ impl SceneBuffers { let tilt = scene.tilt.as_ref(); let mut tile_textures = r.tile_textures.lock().unwrap_or_else(|e| e.into_inner()); let mut tile_meshes = r.tile_meshes.lock().unwrap_or_else(|e| e.into_inner()); + let mut layer_buffers = r.layer_buffers.lock().unwrap_or_else(|e| e.into_inner()); if let Some(t) = tilt.filter(|t| t.camera.pitch != 0.0) { let u = BackdropUniforms::new(&camera, size, ppp, scene.clear, t); let uniforms = owned_buffer( @@ -1236,22 +1289,8 @@ impl SceneBuffers { ], }); draws.push(SceneDraw::Mesh { - vertices: owned_buffer( - device, - &wgpu::util::BufferInitDescriptor { - label: Some("mapgpu_mesh_vertices"), - contents: bytemuck::cast_slice(vertices), - usage: wgpu::BufferUsages::VERTEX, - }, - ), - indices: owned_buffer( - device, - &wgpu::util::BufferInitDescriptor { - label: Some("mapgpu_mesh_indices"), - contents: bytemuck::cast_slice(indices), - usage: wgpu::BufferUsages::INDEX, - }, - ), + vertices: layer_buffers.buffer(device, vertices, "mapgpu_mesh_vertices", wgpu::BufferUsages::VERTEX), + indices: layer_buffers.buffer(device, indices, "mapgpu_mesh_indices", wgpu::BufferUsages::INDEX), index_count: indices.len() as u32, uniforms, bind, @@ -1281,14 +1320,7 @@ impl SceneBuffers { ], }); draws.push(SceneDraw::Points { - instances: owned_buffer( - device, - &wgpu::util::BufferInitDescriptor { - label: Some("mapgpu_point_instances"), - contents: bytemuck::cast_slice(instances), - usage: wgpu::BufferUsages::VERTEX, - }, - ), + instances: layer_buffers.buffer(device, instances, "mapgpu_point_instances", wgpu::BufferUsages::VERTEX), count: instances.len() as u32, uniforms, bind, @@ -1466,6 +1498,7 @@ impl SceneBuffers { } tile_textures.end_scene(); tile_meshes.end_scene(); + layer_buffers.end_scene(); let tiles_live = !live.is_empty() && !has_images && !has_tiles && !scene.cmds.iter().any(|c| matches!(c, DrawCmd::TileMeshes { .. })); let reach = gpu_scene::reach(&scene.cmds); @@ -1775,8 +1808,11 @@ mod tests { let limits = wgpu::Limits { max_buffer_size: 1024, max_texture_dimension_2d: 2048, ..Default::default() }; let mesh = |nv: usize, ni: usize| DrawCmd::Mesh { origin: [0.0, 0.0], - vertices: vec![MeshVertex { position: [0.0, 0.0], normal: [0.0, 0.0], color: [0.0; 4], stroke_px: 0.0, _pad: 0.0 }; nv], - indices: vec![0u32; ni], + vertices: Arc::new(vec![ + MeshVertex { position: [0.0, 0.0], normal: [0.0, 0.0], color: [0.0; 4], stroke_px: 0.0, _pad: 0.0 }; + nv + ]), + indices: Arc::new(vec![0u32; ni]), }; assert!(cmd_fits(&limits, &mesh(4, 6)), "small mesh fits"); assert!(!cmd_fits(&limits, &mesh(100, 6)), "a vertex buffer over max_buffer_size declines"); @@ -1840,10 +1876,19 @@ mod tests { let scene = GpuScene { clear: [0.0, 0.0, 0.0, 1.0], cmds: vec![ - DrawCmd::Mesh { origin: [0.0, 0.0], vertices: vec![v(0.0, 0.0), v(100.0, 0.0), v(0.0, 100.0)], indices: vec![0, 1, 2] }, + DrawCmd::Mesh { + origin: [0.0, 0.0], + vertices: Arc::new(vec![v(0.0, 0.0), v(100.0, 0.0), v(0.0, 100.0)]), + indices: Arc::new(vec![0, 1, 2]), + }, DrawCmd::Points { origin: [0.0, 0.0], - instances: vec![PointInstance { position: [10.0, 10.0], color: [0.0, 1.0, 0.0, 1.0], radius_px: 4.0, shape: 0 }], + instances: Arc::new(vec![PointInstance { + position: [10.0, 10.0], + color: [0.0, 1.0, 0.0, 1.0], + radius_px: 4.0, + shape: 0, + }]), }, DrawCmd::Image { pixmap: rustgis_engine::render::Pixmap::new(1, 1).expect("pixmap") }, ], @@ -1861,6 +1906,48 @@ mod tests { let sb = SceneBuffers::from_scene(&rs.device, &rs.queue, &r, &scene, Camera::world(), [400.0, 300.0], 1.0).expect("fits the device"); assert_eq!(sb.draws.len(), 3); + // The next scene sharing the layers' data (a layer that looks as it did) draws from the + // buffers this one uploaded; new data, as a restyled layer's, is uploaded again. + let buffers = |sb: &SceneBuffers| -> Vec<*const Owned> { + sb.draws + .iter() + .flat_map(|d| match d { + SceneDraw::Mesh { vertices, indices, .. } => vec![Arc::as_ptr(vertices), Arc::as_ptr(indices)], + SceneDraw::Points { instances, .. } => vec![Arc::as_ptr(instances)], + _ => vec![], + }) + .collect() + }; + let again = GpuScene { cmds: scene.cmds.iter().filter_map(share).collect(), ..scene }; + let next = SceneBuffers::from_scene(&rs.device, &rs.queue, &r, &again, Camera::world(), [400.0, 300.0], 1.0).expect("fits"); + assert_eq!(buffers(&next), buffers(&sb), "shared"); + let copied = GpuScene { + cmds: again + .cmds + .iter() + .filter_map(|c| match c { + DrawCmd::Mesh { origin, vertices, indices } => { + Some(DrawCmd::Mesh { origin: *origin, vertices: Arc::new(vertices.to_vec()), indices: Arc::new(indices.to_vec()) }) + } + _ => share(c), + }) + .collect(), + ..again + }; + let last = SceneBuffers::from_scene(&rs.device, &rs.queue, &r, &copied, Camera::world(), [400.0, 300.0], 1.0).expect("fits"); + let (was, now) = (buffers(&next), buffers(&last)); + assert!(was[0] != now[0] && was[1] != now[1] && was[2] == now[2], "only the mesh is uploaded again"); + } + + /// A command sharing `cmd`'s data, for a mesh or markers. + fn share(cmd: &DrawCmd) -> Option { + match cmd { + DrawCmd::Mesh { origin, vertices, indices } => { + Some(DrawCmd::Mesh { origin: *origin, vertices: vertices.clone(), indices: indices.clone() }) + } + DrawCmd::Points { origin, instances } => Some(DrawCmd::Points { origin: *origin, instances: instances.clone() }), + _ => None, + } } // ---- CPU↔GPU pixel parity: render the same map through both backends and compare ---- From e5a1168a0ad54d8772b7cf97dcdf982c27f62dcc Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 21 Nov 2026 18:09:40 -0600 Subject: [PATCH 2/2] fix(render): let go of the kept meshes of layers gone (#1057) Every frame, on the GPU or not, first drops the kept meshes whose layer's rows are no longer held: the layer removed, its map or project closed, or its rows edited since. No scene could take them again, and up to the cache's cap stayed resident after a map was closed. Co-Authored-By: Claude Opus 5.5 --- crates/map/src/look.rs | 6 ++++++ crates/render/src/layer_meshes.rs | 30 ++++++++++++++++++++++++++++++ crates/render/src/lib.rs | 1 + 3 files changed, 37 insertions(+) diff --git a/crates/map/src/look.rs b/crates/map/src/look.rs index bad16783fe..2830323574 100644 --- a/crates/map/src/look.rs +++ b/crates/map/src/look.rs @@ -325,6 +325,12 @@ impl LayerLook { pub fn id(&self) -> u32 { self.layer.id } + + /// Whether the rows it was taken of are still held: once the layer is removed, its map or + /// project closed, or its rows edited, nothing can look as this look again. + pub fn rows_held(&self) -> bool { + self.rows.strong_count() > 0 + } } /// Whether two time bindings show the same rows: the same field through the same window (what diff --git a/crates/render/src/layer_meshes.rs b/crates/render/src/layer_meshes.rs index 7122e90345..1374c204ba 100644 --- a/crates/render/src/layer_meshes.rs +++ b/crates/render/src/layer_meshes.rs @@ -185,6 +185,17 @@ impl Scene { } } +/// Lets go of the meshes of layers gone (removed, their map or project closed, their rows edited +/// since: what they were made of no longer exists), which no scene can take again. Every frame +/// calls it, on the GPU or not, so a closed map's meshes go with the next frame drawn. +pub(crate) fn let_go() { + with_meshes(|m| { + if m.kept.iter().any(|k| !k.look.rows_held()) { + m.kept.retain(|k| k.look.rows_held()); + } + }); +} + impl Drop for Scene { fn drop(&mut self) { let n = self.0; @@ -566,4 +577,23 @@ mod tests { keep_at(&other, 1.0, 400); assert_eq!((has(&la, 0.0), has(&other, 0.0)), (Some(500), Some(400))); } + + /// A map closed lets go of its layers' meshes with the next frame drawn, of any map and on + /// any renderer; a layer edited lets go of the mesh of its rows before the edit. + #[test] + fn a_closed_map_lets_go_of_its_meshes() { + clear(); + let (mut m, a, _, view) = two_layers(); + let _ = scene(&mut m, &view); + let both = kept_bytes(); + assert!(both > 0); + if let Some(l) = m.layers.iter_mut().find(|l| l.id == a) { + l.dataset.push(Some(square(0.2, 0.5)), vec![]); + } + let _ = crate::render(&mut Map::new("Other"), &view); + assert!(kept_bytes() < both, "the edited layer's old mesh went"); + drop(m); + let _ = crate::render(&mut Map::new("Other"), &view); + assert_eq!(kept_bytes(), 0); + } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 691d3778f5..9a326bef7e 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4266,6 +4266,7 @@ fn render_frame( }; // A screen scene keeps each layer's mesh for the next of the same view, and takes those still // standing (see `layer_meshes`): the map's projection, which the meshes are in, when it does. + layer_meshes::let_go(); let mesh_projection = (gpu && !full_res_rasters && matches!(labels_to, Labels::Own)).then(|| map.projection.clone()); // The meshes this scene takes and keeps stay kept while it is drawn. let _mesh_scene = mesh_projection.is_some().then(layer_meshes::Scene::begin);