diff --git a/crates/map/src/camera.rs b/crates/map/src/camera.rs index 1726d0db84..6f371f0d63 100644 --- a/crates/map/src/camera.rs +++ b/crates/map/src/camera.rs @@ -371,10 +371,16 @@ impl Camera { let pad = 2.0 * k; let (hw0, hw1) = (w / 2.0 * z0 / t.d + pad, w / 2.0 * z1 / t.d + pad); let (v0, v1) = (v_of(z0) + pad, v_of(z1) - pad); - let ground = [(-hw1, v1), (hw1, v1), (hw0, v0), (-hw0, v0)].map(|(u, v)| self.ground_to_map(u, v)); + // Its ground, from the centre: a pan moves the band by as much, keeping its scale and + // size to the bit, so its tiles can be taken again ([`Band`]). + let offsets = [(-hw1, v1), (hw1, v1), (hw0, v0), (-hw0, v0)].map(|(u, v)| { + let (ux, uy) = self.unrotate(u, v); + Coord::new(ux * self.res, -uy * self.res) + }); + let ground = offsets.map(|o| Coord::new(self.center.x + o.x, self.center.y + o.y)); let mut e = Extent::EMPTY; - for c in ground { - e.expand(c); + for o in offsets { + e.expand(o); } let mut res = self.res * k; // A band squeezed on screen (far ground at a steep pitch is foreshortened up and @@ -391,23 +397,35 @@ impl Camera { if side > MAX_BAND_SIDE { res *= side / MAX_BAND_SIDE; } - let camera = Camera { center: e.center(), res, bearing: 0.0, pitch: 0.0 }; + let mid = e.center(); + let camera = Camera { center: Coord::new(self.center.x + mid.x, self.center.y + mid.y), res, bearing: 0.0, pitch: 0.0 }; let (width, height) = ((e.width() / res).ceil().max(1.0), (e.height() / res).ceil().max(1.0)); let depth = (z_of(v0) / t.d, z_of(v1) / t.d); - bands.push(Band { camera, width, height, depth, ground }); + let per_unit = t.s / (t.d * self.res); + let depth_per_unit = if per_unit.is_finite() && per_unit > 0.0 { per_unit } else { 0.0 }; + bands.push(Band { camera, width, height, depth, depth_per_unit, ground }); z0 = z1; } // A view too small to have any depth to it (or whose near and far ends meet) is one band - // over its ground, as a flat view is. + // over its ground, as a flat view is: its extent ([`Camera::extent`]), worked out from the + // centre as the other bands are, so a pan keeps its scale and size to the bit. if bands.is_empty() { - let e = self.extent(w, h); - let camera = Camera { center: e.center(), res: self.res, bearing: 0.0, pitch: 0.0 }; + let mut e = Extent::EMPTY; + for (sx, sy) in [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)] { + let (u, v) = self.unproject(sx, sy, w, h).unwrap_or_else(|| self.far_point(sx, w, h)); + let (ux, uy) = self.unrotate(u, v); + e.expand(Coord::new(ux * self.res, -uy * self.res)); + } + let mid = e.center(); + let camera = + Camera { center: Coord::new(self.center.x + mid.x, self.center.y + mid.y), res: self.res, bearing: 0.0, pitch: 0.0 }; bands.push(Band { camera, width: (e.width() / self.res).ceil().max(1.0), height: (e.height() / self.res).ceil().max(1.0), depth: (1.0, 1.0), - ground: corners(&e), + depth_per_unit: 0.0, + ground: corners(&e).map(|o| Coord::new(self.center.x + o.x, self.center.y + o.y)), }); } bands @@ -507,6 +525,10 @@ pub struct Band { /// The nearest and farthest ground it holds, as multiples of the tilted camera's distance /// from the view's centre. pub depth: (f64, f64), + /// How much farther (as `depth` counts) the ground is a map unit past the band's far edge, + /// away from the camera: the depth grows evenly with the distance there. 0 in a flat view's + /// band, and where the tilt gives no finite growth. + pub depth_per_unit: f64, /// The ground it holds, map units: a convex quadrilateral (far edge first), within the /// camera's extent, which is its bounding box. pub ground: [Coord; 4], @@ -515,7 +537,7 @@ pub struct Band { impl Band { /// A flat view's one band: `camera` itself at `width`×`height`, all its ground. pub fn flat(camera: Camera, width: f64, height: f64) -> Band { - Band { camera, width, height, depth: (1.0, 1.0), ground: corners(&camera.extent(width, height)) } + Band { camera, width, height, depth: (1.0, 1.0), depth_per_unit: 0.0, ground: corners(&camera.extent(width, height)) } } /// Whether `e` touches the band's ground (its edges count), as two convex shapes meet: no @@ -560,18 +582,6 @@ impl Band { } (lo <= hi).then_some((lo, hi)) } - - /// How much farther (as [`Band::depth`] counts) the ground is a map unit past the band's far - /// edge, away from the camera: the depth grows evenly with the distance there. 0 in a flat - /// view's band. - pub fn depth_per_unit(&self) -> f64 { - let [f0, f1, n0, n1] = self.ground; - let mid = |a: Coord, b: Coord| Coord::new((a.x + b.x) / 2.0, (a.y + b.y) / 2.0); - let (far, near) = (mid(f0, f1), mid(n0, n1)); - let apart = (far.x - near.x).hypot(far.y - near.y); - let per = (self.depth.1 - self.depth.0) / apart; - if per.is_finite() && per > 0.0 { per } else { 0.0 } - } } /// An extent's corners, in turn round it. @@ -748,7 +758,14 @@ mod tests { fn a_band_touches_what_meets_its_ground_not_only_its_box() { // A diamond in the box 0..10. let ground = [Coord::new(5.0, 10.0), Coord::new(10.0, 5.0), Coord::new(5.0, 0.0), Coord::new(0.0, 5.0)]; - let b = Band { camera: Camera::new(Coord::new(5.0, 5.0), 1.0), width: 10.0, height: 10.0, depth: (1.0, 2.0), ground }; + let b = Band { + camera: Camera::new(Coord::new(5.0, 5.0), 1.0), + width: 10.0, + height: 10.0, + depth: (1.0, 2.0), + depth_per_unit: 0.0, + ground, + }; assert!(b.ground_touches(&Extent::new(4.0, 4.0, 6.0, 6.0)), "inside"); assert!(b.ground_touches(&Extent::new(-5.0, -5.0, 15.0, 15.0)), "round it"); assert!(b.ground_touches(&Extent::new(7.0, 7.0, 9.0, 9.0)), "over its north-east edge"); @@ -791,7 +808,7 @@ mod tests { let s = 0.05 * dx.hypot(dy); let past = Coord::new(fx + dx * 0.05, fy + dy * 0.05); let depth = 1.0 / c.depth_scale(past, h).unwrap(); - let want = b.depth.1 + b.depth_per_unit() * s; + let want = b.depth.1 + b.depth_per_unit * s; assert!((depth - want).abs() < 1e-9 * want, "{pitch}: {depth} vs {want}"); } // The fast lookup agrees with the camera. @@ -817,19 +834,37 @@ mod tests { } } } + // A pan moves the bands by as much, keeping their scales and sizes to the bit. + c.set_pitch(60.0); + let mut panned = c; + panned.center = Coord::new(c.center.x + 12_345.678, c.center.y - 9_876.543); + for (a, b) in c.tilt_bands(w, h).iter().zip(panned.tilt_bands(w, h)) { + assert_eq!(a.camera.res.to_bits(), b.camera.res.to_bits()); + assert_eq!((a.width, a.height, a.depth, a.depth_per_unit), (b.width, b.height, b.depth, b.depth_per_unit)); + } // Degenerate views still give a band (the last always reaching the far end). c.set_pitch(70.0); + let mut one_band = 0; for (w, h) in [(1.0, 1.0), (0.0, 0.0), (3.0, 1e-9), (800.0, 2.0)] { let bands = c.tilt_bands(w, h); assert!(!bands.is_empty() && bands.len() <= MAX_TILT_BANDS, "{w}x{h}"); + // A pan keeps them to the bit too, the one band over a view with no depth among them. + let mut panned = c; + panned.center = Coord::new(c.center.x + 12_345.678, c.center.y - 9_876.543); + for (a, b) in bands.iter().zip(panned.tilt_bands(w, h)) { + assert_eq!(a.camera.res.to_bits(), b.camera.res.to_bits(), "{w}x{h}"); + assert_eq!((a.width, a.height, a.depth, a.depth_per_unit), (b.width, b.height, b.depth, b.depth_per_unit), "{w}x{h}"); + } + one_band += usize::from(bands.len() == 1 && bands[0].depth == (1.0, 1.0)); } + assert!(one_band > 0, "a view with no depth to it"); // A flat view is one band: itself. c.set_pitch(0.0); let e = c.extent(w, h); let ground = [Coord::new(e.min_x, e.max_y), Coord::new(e.max_x, e.max_y), Coord::new(e.max_x, e.min_y), Coord::new(e.min_x, e.min_y)]; - assert_eq!(c.tilt_bands(w, h), vec![Band { camera: c, width: w, height: h, depth: (1.0, 1.0), ground }]); - assert_eq!(c.tilt_bands(w, h)[0].depth_per_unit(), 0.0); + assert_eq!(c.tilt_bands(w, h), vec![Band { camera: c, width: w, height: h, depth: (1.0, 1.0), depth_per_unit: 0.0, ground }]); + assert_eq!(c.tilt_bands(w, h)[0].depth_per_unit, 0.0); } #[test] diff --git a/crates/render/src/frame_cache.rs b/crates/render/src/frame_cache.rs index 783dcda97c..5cd44d6573 100644 --- a/crates/render/src/frame_cache.rs +++ b/crates/render/src/frame_cache.rs @@ -71,8 +71,9 @@ const KEPT: usize = 2; /// The most bytes of meshes the kept GPU checkpoints hold together ([`GpuPart`]), as /// [`crate::layer_meshes`] counts them: they share them with the scenes on screen and the meshes -/// that module keeps, so what they hold beside those is at most this, the same budget again. -const MAX_MESH_BYTES: usize = crate::layer_meshes::MAX_BYTES; +/// that module keeps, so what they hold beside those is at most this: 128 MB (32 MB in the +/// browser), that module's least budget ([`crate::layer_meshes::max_bytes`]). +const MAX_MESH_BYTES: usize = if cfg!(target_arch = "wasm32") { 32 << 20 } else { 128 << 20 }; /// What a frame is drawn from besides its layers. #[derive(Clone, Debug)] diff --git a/crates/render/src/gpu_scene.rs b/crates/render/src/gpu_scene.rs index 70156066e7..308962d037 100644 --- a/crates/render/src/gpu_scene.rs +++ b/crates/render/src/gpu_scene.rs @@ -93,11 +93,16 @@ pub struct CmdClip { pub depth: [f32; 2], /// Point markers standing upright, sized by their distance (see `render::upright_markers`). pub upright: bool, + /// Its strokes' widths and its markers' sizes, in pixels, are drawn this many times as + /// large: a long band is drawn at a lower pixel density (`render::band_view`), and its + /// meshes, sized in its pixels, are brought to the view's while drawing, not written, so the + /// meshes it keeps (`layer_meshes`) stay shared. + pub px: f32, } impl CmdClip { /// Every depth, markers as drawn. - pub const ALL: CmdClip = CmdClip { depth: [0.0, f32::MAX], upright: false }; + pub const ALL: CmdClip = CmdClip { depth: [0.0, f32::MAX], upright: false, px: 1.0 }; } /// One draw command. `Image` is a CPU-rasterized run (basemap, tiles, rasters, and layers diff --git a/crates/render/src/layer_meshes.rs b/crates/render/src/layer_meshes.rs index 051f70c5d6..73d5811b52 100644 --- a/crates/render/src/layer_meshes.rs +++ b/crates/render/src/layer_meshes.rs @@ -16,11 +16,12 @@ //! ([`crate::mesh_tiles`]): the layer's tiles still in the new scene are taken as they were //! made ([`tiles`]), and only those it brings in are meshed. //! -//! 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 +//! Screen scenes keep meshes, and so do a tilted GPU view's bands ([`BandMade`]): a pan keeps +//! each band's scale, so its tiles still on its ground are taken again. Not a turned view's +//! (sized again after), a drape's, 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`]. +//! [`max_bytes`]. use std::sync::Arc; @@ -31,13 +32,35 @@ use rustgis_map::look::{Change, LayerLook}; use crate::gpu_scene::{DrawCmd, MeshVertex, PointInstance}; use crate::mesh_tiles::MadeTile; -/// 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 meshes are mostly at most -/// [`crate::mesh::MAX_LAYER_VERTICES`] vertices, 80 MB; one cut into tiles may hold more, from the -/// scene's budget ([`crate::mesh::layer_room`]), and isn't kept past this. -pub(crate) const MAX_BYTES: usize = if cfg!(target_arch = "wasm32") { 32 << 20 } else { 128 << 20 }; +/// The most bytes of meshes kept, with what each was made from ([`ENTRY_BYTES`] and its rows): a +/// sixteenth of the computer's memory, from 128 MB (about 3.3 million vertices; a phone, a +/// computer whose memory isn't known) to 640 MB. The scene's budget +/// ([`crate::mesh::scene_vertices`]) is a sixteenth of the memory too, from 240 MB, but counts +/// vertices only, where this counts their indices and tiles as well: from about 4 GB of memory up +/// most of a scene's layers are kept, all of them when the scene is well within its budget, and a +/// pan or a tilted view's pan makes only the tiles it brings in. Below that, and on a phone, a big +/// scene keeps what fits (the near bands first, as a tilted view draws them) and a pan makes the +/// rest again, as before. 32 MB in the browser. The meshes kept are shared with the scene on +/// screen, so what this holds beside it is mostly the tiles of the last scene no longer in view. +/// 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. Read once +/// (`memory::physical`). +pub(crate) fn max_bytes() -> usize { + if cfg!(target_arch = "wasm32") { + return 32 << 20; + } + max_bytes_for(rustgis_data::memory::physical(), rustgis_data::memory::on_phone()) +} + +/// [`max_bytes`] on a computer with `memory` bytes (`None`: not known), or on a phone. +fn max_bytes_for(memory: Option, phone: bool) -> usize { + const FLOOR: usize = 128 << 20; + const CEILING: usize = 640 << 20; + if phone { + return FLOOR; + } + rustgis_data::memory::scaled(memory.map(|m| m / 4), FLOOR, CEILING, 1) +} /// 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 @@ -74,13 +97,51 @@ pub(crate) struct Made { /// Physical pixels per point, a reference scale's growth included: marker and stroke sizes. pub ppp: f32, pub wireframe: bool, + /// The band of a tilted view it was made for ([`crate::GpuBand`]); `None` for a screen scene. + pub band: Option, +} + +/// What a band of a tilted view makes its layers' meshes with ([`Made::band`]). A pan keeps a +/// band's place among the bands, its scale and its strokes' growth ([`rustgis_map::camera::Band`]), +/// so its tiles still on its ground are taken again. +#[derive(Clone, Copy, Debug)] +pub(crate) struct BandMade { + /// Which band of the view, nearest first: a layer keeps meshes for each. + pub slot: usize, + /// How far its strokes reach ([`crate::mesh_tiles::Tiling::grow`] and `spread`). + pub grow: f64, + pub spread: f64, + /// Its ground: which of its tiles there are, as the cull says for a screen scene. + pub ground: [rustgis_geom::Coord; 4], +} + +impl BandMade { + fn same_tiles(&self, other: &BandMade) -> bool { + self.slot == other.slot && self.grow.to_bits() == other.grow.to_bits() && self.spread.to_bits() == other.spread.to_bits() + } + + fn same(&self, other: &BandMade) -> bool { + let bits = |g: &[rustgis_geom::Coord; 4]| g.map(|c| [c.x.to_bits(), c.y.to_bits()]); + self.same_tiles(other) && bits(&self.ground) == bits(&other.ground) + } } 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); - extent(&self.cull) == extent(&other.cull) && self.same_tiles(other) + let band = match (&self.band, &other.band) { + (None, None) => true, + (Some(a), Some(b)) => a.same(b), + _ => false, + }; + extent(&self.cull) == extent(&other.cull) && band && self.same_tiles(other) + } + + /// Whether it is for the same view as `other`'s: a screen scene, or the same band of a tilted + /// view. A layer keeps meshes for [`VIEWS`] of each. + fn same_slot(&self, other: &Made) -> bool { + self.band.map(|b| b.slot) == other.band.map(|b| b.slot) } /// Whether a tile made from `self` is the one `other` makes of the same tile: the same but @@ -91,6 +152,11 @@ impl Made { && self.map_per_px.to_bits() == other.map_per_px.to_bits() && self.ppp.to_bits() == other.ppp.to_bits() && self.wireframe == other.wireframe + && match (&self.band, &other.band) { + (None, None) => true, + (Some(a), Some(b)) => a.same_tiles(b), + _ => false, + } } } @@ -103,8 +169,10 @@ struct Kept { 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, + /// time shown, as they applied. Shared by the layer's views that drew the same rows (a + /// tilted view's bands, a pan), so a layer holds one copy of them, not one a view; each + /// view's bytes still count them. + rows: Arc<[bool]>, /// The layer's Mesh and Points commands, sharing their data with the scenes that drew them. cmds: Vec, /// Its tiles, in grid order, sharing their meshes with `cmds`; none when it isn't tiled or @@ -239,7 +307,7 @@ pub(crate) fn take(cmds: &mut Vec, look: &LayerLook, made: &Made, rows: 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.vertices <= room + k.look.id() == look.id() && k.made.same(made) && k.look.change(look) == Change::Same && *k.rows == *rows && k.vertices <= room })?; k.used = clock; cmds.extend(k.cmds.iter().filter_map(share)); @@ -263,7 +331,7 @@ pub(crate) fn tiles(look: &LayerLook, made: &Made, rows: &[bool]) -> Arc<[MadeTi && k.look.id() == look.id() && k.made.same_tiles(made) && k.look.change(look) == Change::Same - && k.rows == rows + && *k.rows == *rows }) .max_by_key(|k| k.used) .map_or_else(|| Arc::from(Vec::new()), |k| Arc::clone(&k.tiles)) @@ -273,7 +341,7 @@ pub(crate) fn tiles(look: &LayerLook, made: &Made, rows: &[bool]) -> Arc<[MadeTi /// 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 +/// [`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. `tiles` are its tiles, to /// take again once the scene has panned ([`tiles`]). Called while a [`Scene`] is drawn. #[expect(clippy::too_many_arguments, reason = "a mesh, its tiles and what they were made from")] @@ -287,7 +355,7 @@ pub(crate) fn keep( vertices: usize, selected: usize, ) { - keep_within(MAX_BYTES, layer, look, made, rows, cmds, tiles, vertices, selected); + keep_within(max_bytes(), layer, look, made, rows, cmds, tiles, vertices, selected); } /// [`keep`], within `max` bytes. @@ -324,17 +392,21 @@ fn keep_within( let mut out: Vec = Vec::new(); let mut views: Vec<(u64, usize)> = Vec::new(); let mut shared: Option> = None; + let mut same_rows: 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_rows.is_none() && *k.rows == *rows { + same_rows = Some(Arc::clone(&k.rows)); + } if !same_look || k.made.same(&made) { if m.in_use(k) { return; } out.push(i); - } else { + } else if k.made.same_slot(&made) { views.push((k.used, i)); } } @@ -373,7 +445,8 @@ fn keep_within( 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, tiles: Arc::from(tiles), vertices, bytes, used }); + let rows = same_rows.unwrap_or_else(|| Arc::from(rows)); + m.kept.push(Kept { layer, look, made, rows, cmds, tiles: Arc::from(tiles), vertices, bytes, used }); }); } @@ -510,6 +583,150 @@ mod tests { assert_eq!(squares(&panned), squares(&afresh)); } + /// The meshes kept take a share of the computer's memory, from what a phone or an unknown + /// computer keeps to what one scene's budget holds (`memory::scaled` is tested with the + /// memory's own). + #[test] + fn the_meshes_kept_scale_with_the_memory() { + const MB: usize = 1 << 20; + const GB: u64 = 1 << 30; + for (memory, phone, want) in [ + (None, false, 128 * MB), + (Some(GB), false, 128 * MB), + (Some(4 * GB), false, 256 * MB), + (Some(8 * GB), false, 512 * MB), + (Some(64 * GB), false, 640 * MB), + (Some(8 * GB), true, 128 * MB), + ] { + assert_eq!(super::max_bytes_for(memory, phone), want, "{memory:?} bytes, phone {phone}"); + } + // From about 4 GB up this holds a scene's least budget of vertices (6 million at 40 + // bytes, `mesh::scene_vertices`); both are a sixteenth of the memory past it. + assert!(super::max_bytes_for(Some(4 * GB), false) >= 6_000_000 * 40); + assert!(super::max_bytes_for(Some(2 * GB), false) < 6_000_000 * 40); + } + + /// A tilted view's pan keeps its bands' scales: each band takes the meshes of its tiles still + /// on its ground, meshing only those the pan brings in, and the scene is the one drawn afresh + /// there, vertex for vertex. + #[test] + fn a_panned_tilted_view_takes_its_bands_tiles_still_in_it() { + super::clear(); + let mut m = Map::new("Map"); + m.basemap = rustgis_map::Basemap::Blank; + m.graticule = false; + let mut d = Dataset::new("lines", GeometryType::Polyline, vec![]); + for n in 0u32..60 { + let k = f64::from(n); + let line = vec![Coord::new(-14.0 + k * 0.5, -9.0), Coord::new(12.0 - k * 0.3, 11.0), Coord::new(-11.0, 5.0 - k * 0.2)]; + d.push(Some(Geometry::Line(vec![line])), vec![]); + } + m.add_dataset(d); + let at = |x: f64| View { + width: 1600.0, + height: 1000.0, + pixels_per_point: 1.0, + camera: Camera { center: rustgis_geom::lonlat_to_merc(Coord::new(x, -2.0)), res: 400.0, bearing: 0.0, pitch: 60.0 }, + sky: false, + }; + assert!(at(0.0).camera.tilt_bands(1600.0, 1000.0).len() >= 2, "bands"); + let first = scene(&mut m, &at(0.0)); + let panned = scene(&mut m, &at(1.5)); + let tiled = |s: &GpuScene| s.cmds.iter().filter(|c| matches!(c, DrawCmd::Mesh { square: Some(_), .. })).count(); + assert!(tiled(&first) > 8, "many tiles: {}", tiled(&first)); + let before: Vec<_> = meshes(&first).into_iter().map(|m| m.0).collect(); + let taken = meshes(&panned).iter().filter(|m| before.contains(&m.0)).count(); + assert!(taken > 0 && taken < tiled(&panned), "{taken} of {} tiles taken", tiled(&panned)); + super::clear(); + let afresh = scene(&mut m, &at(1.5)); + let values = |s: &GpuScene| meshes(s).into_iter().map(|m| (m.1, m.2)).collect::>(); + assert!(values(&panned) == values(&afresh), "the panned scene is the one drawn afresh"); + // The same view again takes every band's mesh of the layer whole. + let bands = at(1.5).camera.tilt_bands(1600.0, 1000.0).len(); + let _ = super::taken(); + let again = scene(&mut m, &at(1.5)); + assert_eq!(super::taken().len(), bands, "one whole mesh a band"); + let shared = meshes(&afresh).into_iter().map(|m| m.0).collect::>(); + assert_eq!(meshes(&again).into_iter().map(|m| m.0).collect::>(), shared); + } + + /// A tilted view's bands keep the layer's meshes one a band, sharing one copy of the rows + /// they drew; each band keeps its last two views ([`VIEWS`]), not its first. + #[test] + fn a_tilted_views_bands_share_their_rows_and_keep_two_views_each() { + super::clear(); + let mut m = Map::new("Map"); + m.basemap = rustgis_map::Basemap::Blank; + m.graticule = false; + let mut d = Dataset::new("lines", GeometryType::Polyline, vec![]); + for n in 0u32..20 { + let k = f64::from(n); + d.push(Some(Geometry::Line(vec![vec![Coord::new(-14.0 + k, -9.0), Coord::new(12.0 - k, 11.0)]])), vec![]); + } + m.add_dataset(d); + let at = |x: f64| View { + width: 1600.0, + height: 1000.0, + pixels_per_point: 1.0, + camera: Camera { center: rustgis_geom::lonlat_to_merc(Coord::new(x, -2.0)), res: 400.0, bearing: 0.0, pitch: 60.0 }, + sky: false, + }; + let bands = at(0.0).camera.tilt_bands(1600.0, 1000.0).len(); + assert!(bands >= 2, "bands"); + // (band slot, the ground's first corner, rows) of each kept mesh. + let kept = || { + super::with_meshes(|m| { + m.kept + .iter() + .filter_map(|k| k.made.band.map(|b| (b.slot, b.ground[0].x.to_bits(), Arc::clone(&k.rows)))) + .collect::>() + }) + }; + scene(&mut m, &at(0.0)); + let first = kept(); + assert_eq!(first.len(), bands, "one mesh a band"); + assert!(first.iter().all(|(_, _, r)| Arc::ptr_eq(r, &first[0].2)), "one copy of the rows"); + scene(&mut m, &at(1.0)); + scene(&mut m, &at(2.0)); + let views = |x: f64| at(x).camera.tilt_bands(1600.0, 1000.0).iter().map(|b| b.ground[0].x.to_bits()).collect::>(); + let (oldest, last) = (views(0.0), [views(1.0), views(2.0)].concat()); + let now = kept(); + for slot in 0..bands { + assert_eq!(now.iter().filter(|(s, _, _)| *s == slot).count(), 2, "band {slot} keeps two views"); + } + assert!(now.iter().all(|(_, g, _)| !oldest.contains(g) && last.contains(g)), "the last two views"); + } + + /// A long band, drawn at a lower pixel density, brings its strokes to the view's as they are + /// drawn (`CmdClip::px`), not by writing its meshes: the same view again shares the meshes + /// the last scene kept, not copies of them. + #[test] + fn a_long_bands_kept_meshes_are_shared_not_copied() { + super::clear(); + let mut m = Map::new("Map"); + m.basemap = rustgis_map::Basemap::Blank; + m.graticule = false; + let mut d = Dataset::new("lines", GeometryType::Polyline, vec![]); + for n in 0u32..20 { + let k = f64::from(n); + d.push(Some(Geometry::Line(vec![vec![Coord::new(-14.0 + k, -9.0), Coord::new(12.0 - k, 11.0)]])), vec![]); + } + m.add_dataset(d); + let view = View { + width: 1600.0, + height: 1000.0, + pixels_per_point: 4.0, + camera: Camera { center: rustgis_geom::lonlat_to_merc(Coord::new(0.0, -2.0)), res: 400.0, bearing: 0.0, pitch: 60.0 }, + sky: false, + }; + let first = scene(&mut m, &view); + assert!(first.clips.iter().any(|c| c.px > 1.0), "a band at a lower density: {:?}", first.clips); + let again = scene(&mut m, &view); + let shared = |s: &GpuScene| meshes(s).into_iter().map(|m| m.0).collect::>(); + assert!(!shared(&first).is_empty()); + assert_eq!(shared(&again), shared(&first), "the kept meshes, not copies"); + } + /// A scene stopped by a memory warning may still be drawing: what it makes after the release /// isn't kept, and a scene begun once it is done keeps again. #[test] @@ -609,6 +826,7 @@ mod tests { map_per_px: view.camera.res, ppp: 1.0, wireframe: false, + band: None, }; let mesh = |n: usize| DrawCmd::Mesh { origin: [0.0; 2], @@ -680,6 +898,7 @@ mod tests { map_per_px: view.camera.res, ppp: 1.0, wireframe: false, + band: None, }; let mesh = |n: usize| DrawCmd::Mesh { origin: [0.0; 2], diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 7a090bb8d7..d742de8c5f 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -3497,6 +3497,9 @@ fn gpu_turned( // Each band's frame cuts its layers into tiles of its own ground, the bands sharing the // scene's budget (`GpuBand`). let _held = GpuBandHeld::hold(); + // The bands are one scene: what each takes of the kept meshes stays kept while the later + // ones keep theirs (`layer_meshes`). + let _mesh_scene = layer_meshes::Scene::begin(); let mut meshed = 0usize; for (i, b) in bands.iter().enumerate() { // A stopped frame (see `cancel`) draws no further band, nor falls back to the CPU. @@ -3507,9 +3510,9 @@ fn gpu_turned( let v = band_view(view, b); let scale = view.camera.res / b.camera.res; let grow = (scale * b.depth.1).max(1.0); - let spread = scale * b.depth_per_unit(); + let spread = scale * b.depth_per_unit; let (grow, spread) = if grow.is_finite() && spread.is_finite() { (grow, spread) } else { (f64::MAX, f64::MAX) }; - GPU_BAND.with(|g| g.set(Some(GpuBand { band: *b, grow, spread, meshed }))); + GPU_BAND.with(|g| g.set(Some(GpuBand { band: *b, slot: i, grow, spread, meshed }))); let frame = render_frame(map, &v, full_res_rasters, Backend::Gpu, Labels::Tilted(view, &mut candidates), false, failed_source, env); meshed = GPU_BAND.with(|g| g.take()).map_or(meshed, |g| g.meshed); let Some(RenderOutput::Gpu(scene)) = frame else { @@ -3526,22 +3529,9 @@ fn gpu_turned( } clear = scene.clear; // A long band is drawn at a lower pixel density (`band_view`): its strokes and markers, - // sized in its pixels, are brought to the view's. - let k = (view.pixels_per_point / v.pixels_per_point.max(1e-9)) as f32; - let mut scene = scene; - if (k - 1.0).abs() > 1e-6 { - for c in &mut scene.cmds { - match c { - 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 { .. } - | DrawCmd::LiveTiles { .. } - | DrawCmd::TileMeshes { .. } => {} - } - } - } + // sized in its pixels, are brought to the view's as they are drawn (`CmdClip::px`). + let px = (view.pixels_per_point / v.pixels_per_point.max(1e-9)) as f32; + let px = if px.is_finite() && px > 0.0 { px } else { 1.0 }; for a in scene.attribution { if !attribution.contains(&a) { attribution.push(a); @@ -3567,7 +3557,7 @@ fn gpu_turned( // falls between them. let near = if i == 0 { 0.0 } else { b.depth.0 as f32 }; let far = if i == last { f32::MAX } else { b.depth.1 as f32 }; - let clip = CmdClip { depth: [near, far], upright: false }; + let clip = CmdClip { depth: [near, far], px, ..CmdClip::ALL }; clips.extend(std::iter::repeat_n(clip, scene.cmds.len())); cmds.extend(scene.cmds); } @@ -4572,6 +4562,9 @@ thread_local! { #[derive(Clone, Copy)] struct GpuBand { band: rustgis_map::camera::Band, + /// Which of the view's bands it is, nearest first: its layers' meshes are kept for the next + /// frame's band in the same place ([`layer_meshes::BandMade`]). + slot: usize, /// How many times as wide as tessellated the shader draws a stroke at the band's far edge: /// it widens strokes by their depth (`vs_mesh`), from the tilted view's scale, while the band /// tessellates them at its own (that of its near edge, or coarser). @@ -4852,10 +4845,12 @@ 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. + // A screen scene, or a tilted view's band, 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()); + let mesh_projection = + (gpu && !full_res_rasters && (matches!(labels_to, Labels::Own) || band.is_some())).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. @@ -5733,6 +5728,7 @@ fn render_frame( map_per_px, ppp: ctx.ppp, wireframe: ctx.wireframe, + band: band.map(|b| layer_meshes::BandMade { slot: b.slot, grow: b.grow, spread: b.spread, ground: b.band.ground }), }; Some((rustgis_map::look::LayerLook::of(layer)?, made)) }); @@ -7919,7 +7915,14 @@ fn render_tilt_drape_drawn(map: &mut Map, view: &View, margin: f64, max_side: u3 if let Some(RenderOutput::Cpu(r)) = render_frame(map, &v, false, Backend::Cpu, Labels::Shared, false, &mut None, &Env::default()) { out.push(TiltPatch { pixmap: r.pixmap, - band: rustgis_map::camera::Band { camera, width: w, height: h, depth: b.depth, ground: b.ground }, + band: rustgis_map::camera::Band { + camera, + width: w, + height: h, + depth: b.depth, + depth_per_unit: b.depth_per_unit, + ground: b.ground, + }, }); } } diff --git a/crates/render/src/mesh_tiles.rs b/crates/render/src/mesh_tiles.rs index 6df9676b37..ce028d8868 100644 --- a/crates/render/src/mesh_tiles.rs +++ b/crates/render/src/mesh_tiles.rs @@ -901,8 +901,14 @@ mod tests { let symbol = Symbol::default_for(rustgis_data::GeometryType::Polygon, 0); let whole = Feature { geometry: &g, symbol, estimate: 0, extent: Extent::new(0.0, 0.0, 100.0, 100.0), reach: 0.0 }; let area = Extent::new(0.0, 0.0, 100.0, 100.0); - let band = - |ground| Band { camera: Camera::new(Coord::new(50.0, 50.0), 1.0), width: 100.0, height: 100.0, depth: (1.0, 2.0), ground }; + let band = |ground| Band { + camera: Camera::new(Coord::new(50.0, 50.0), 1.0), + width: 100.0, + height: 100.0, + depth: (1.0, 2.0), + depth_per_unit: 0.0, + ground, + }; // Over its box a feature reaches more tiles than a layer may have; over its ground, a // strip across it, a row of them. let strip = band([Coord::new(0.0, 50.8), Coord::new(100.0, 50.8), Coord::new(100.0, 50.2), Coord::new(0.0, 50.2)]); diff --git a/crates/ui-egui/src/mapgpu.rs b/crates/ui-egui/src/mapgpu.rs index 5e88ac5170..a27ddfb210 100644 --- a/crates/ui-egui/src/mapgpu.rs +++ b/crates/ui-egui/src/mapgpu.rs @@ -118,10 +118,12 @@ struct CmdUniforms { scene_depth: [f32; 4], /// The fog a tilted view's ground fades into (premultiplied). fog: [f32; 4], - /// `x`: map units per physical pixel (scales stroke normals); `y`: 1 for upright markers, - /// else 0; `z`, `w`: the band's nearest and farthest depths. + /// `x`: map units per physical pixel (scales stroke normals), times the command's + /// [`CmdClip::px`]; `y`: 1 for upright markers, else 0; `z`, `w`: the band's nearest and + /// farthest depths. params: [f32; 4], - /// `x`, `y`: physical pixel size of the map view (scales marker pixel offsets); `z`: 1 when + /// `x`, `y`: physical pixel size of the map view (scales marker pixel offsets), over the + /// command's [`CmdClip::px`]; `z`: 1 when /// tilted (fog, the reach, band clipping), else 0; `w`: the reach's depth. viewport: [f32; 4], /// Extrusions: the light's direction (map units, unit length) and how far a shadow falls per @@ -140,10 +142,10 @@ impl CmdUniforms { view_proj: view_proj(cam, w, h, origin), scene_depth: [s[0][3], s[1][3], s[2][3], s[3][3]], fog: tilt.map_or([0.0; 4], |t| t.fog), - params: [(cam.res / f64::from(ppp)) as f32, if clip.upright { 1.0 } else { 0.0 }, clip.depth[0], clip.depth[1]], + params: [(cam.res / f64::from(ppp)) as f32 * clip.px, if clip.upright { 1.0 } else { 0.0 }, clip.depth[0], clip.depth[1]], viewport: [ - (w * f64::from(ppp)) as f32, - (h * f64::from(ppp)) as f32, + (w * f64::from(ppp)) as f32 / clip.px, + (h * f64::from(ppp)) as f32 / clip.px, if rustgis_engine::map::camera::normalize_pitch(cam.pitch) != 0.0 { 1.0 } else { 0.0 }, rustgis_engine::map::camera::FAR as f32, ], @@ -1858,6 +1860,22 @@ mod tests { assert!((gx - ex).abs() < 0.01 && (gy - ey).abs() < 0.01, "gpu ({gx},{gy}) vs cpu ({ex},{ey})"); } + /// A command drawn `px` times as large (a long band's, `CmdClip::px`) widens its strokes and + /// markers in the uniforms, so its mesh, which the CPU side keeps, is drawn as it is. + #[test] + fn a_commands_pixel_factor_sizes_its_strokes_and_markers() { + let cam = Camera { center: Coord::new(0.0, 0.0), res: 10.0, bearing: 0.0, pitch: 0.0 }; + let plain = CmdUniforms::new(&cam, [800.0, 600.0], 2.0, [0.0, 0.0], None, CmdClip::ALL); + let large = CmdUniforms::new(&cam, [800.0, 600.0], 2.0, [0.0, 0.0], None, CmdClip { px: 2.5, ..CmdClip::ALL }); + assert!((large.params[0] - plain.params[0] * 2.5).abs() < 1e-6, "strokes"); + assert!( + (large.viewport[0] * 2.5 - plain.viewport[0]).abs() < 1e-3 && (large.viewport[1] * 2.5 - plain.viewport[1]).abs() < 1e-3, + "markers" + ); + assert_eq!(large.params[1..], plain.params[1..]); + assert_eq!(large.viewport[2..], plain.viewport[2..]); + } + #[test] fn matches_to_screen() { // World view, a city zoom, and a custom-projection's units (e.g. UTM metres).