diff --git a/crates/map/src/camera.rs b/crates/map/src/camera.rs index f9a4b9d810..1726d0db84 100644 --- a/crates/map/src/camera.rs +++ b/crates/map/src/camera.rs @@ -352,7 +352,7 @@ impl Camera { /// fetched) coarser. A flat view is one band: itself. pub fn tilt_bands(&self, w: f64, h: f64) -> Vec { let Some(t) = self.tilt(h) else { - return vec![Band { camera: *self, width: w, height: h, depth: (1.0, 1.0) }]; + return vec![Band::flat(*self, w, h)]; }; let z_of = |v: f64| t.d - v * t.s; let v_of = |z: f64| (t.d - z) / t.s; @@ -371,9 +371,10 @@ 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)); let mut e = Extent::EMPTY; - for (u, v) in [(-hw1, v1), (hw1, v1), (-hw0, v0), (hw0, v0)] { - e.expand(self.ground_to_map(u, v)); + for c in ground { + e.expand(c); } let mut res = self.res * k; // A band squeezed on screen (far ground at a steep pitch is foreshortened up and @@ -393,7 +394,7 @@ impl Camera { let camera = Camera { center: e.center(), 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 }); + bands.push(Band { camera, width, height, depth, ground }); z0 = z1; } // A view too small to have any depth to it (or whose near and far ends meet) is one band @@ -406,6 +407,7 @@ impl 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), }); } bands @@ -505,6 +507,76 @@ 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), + /// 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], +} + +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)) } + } + + /// Whether `e` touches the band's ground (its edges count), as two convex shapes meet: no + /// line through an axis or an edge of the ground's parts them. + pub fn ground_touches(&self, e: &Extent) -> bool { + let rect = corners(e); + let apart = |n: (f64, f64)| { + let span = |ps: &[Coord; 4]| { + ps.iter().map(|p| p.x * n.0 + p.y * n.1).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), d| (lo.min(d), hi.max(d))) + }; + let (a, b) = (span(&self.ground), span(&rect)); + a.1 < b.0 || b.1 < a.0 + }; + let edges = (0..4).filter_map(|i| { + let (a, b) = (self.ground.get(i)?, self.ground.get((i + 1) % 4)?); + Some((a.y - b.y, b.x - a.x)) + }); + ![(1.0, 0.0), (0.0, 1.0)].into_iter().chain(edges).any(apart) + } + + /// The least and greatest x of the band's ground between `y0` and `y1` (its edges count): + /// the columns a row of tiles there touches it in, as [`Band::ground_touches`] finds tile + /// by tile (the ground is convex, so they run unbroken). `None` when it doesn't reach there. + pub fn ground_across(&self, y0: f64, y1: f64) -> Option<(f64, f64)> { + let mut lo = f64::INFINITY; + let mut hi = f64::NEG_INFINITY; + let mut take = |x: f64| { + lo = lo.min(x); + hi = hi.max(x); + }; + for i in 0..4 { + let (Some(a), Some(b)) = (self.ground.get(i), self.ground.get((i + 1) % 4)) else { continue }; + if (y0..=y1).contains(&a.y) { + take(a.x); + } + // Where the edge crosses the row's bottom and top. + for y in [y0, y1] { + if (a.y - y) * (b.y - y) < 0.0 { + take(a.x + (b.x - a.x) * (y - a.y) / (b.y - a.y)); + } + } + } + (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. +fn corners(e: &Extent) -> [Coord; 4] { + [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)] } /// A pitch within 0 to [`MAX_PITCH`]; one too small to see, or no number, looks straight down @@ -672,6 +744,31 @@ mod tests { assert!(c.project_raised(eu, ev, eh, w, h).is_none()); } + #[test] + 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 }; + 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"); + assert!(!b.ground_touches(&Extent::new(8.0, 8.0, 10.0, 10.0)), "in its box's corner, off the ground"); + assert!(!b.ground_touches(&Extent::new(11.0, 4.0, 12.0, 6.0)), "east of it"); + // A row across it holds the ground's x there, as the tiles touching it find it. + assert_eq!(b.ground_across(7.0, 8.0), Some((2.0, 8.0))); + assert_eq!(b.ground_across(4.0, 6.0), Some((0.0, 10.0))); + assert_eq!(b.ground_across(10.0, 11.0), Some((5.0, 5.0))); + assert_eq!(b.ground_across(11.0, 12.0), None); + for row in -2..12 { + let (y0, y1) = (f64::from(row), f64::from(row) + 1.0); + for column in -2..12 { + let (x0, x1) = (f64::from(column), f64::from(column) + 1.0); + let across = b.ground_across(y0, y1).is_some_and(|(lo, hi)| x0 <= hi && lo <= x1); + assert_eq!(across, b.ground_touches(&Extent::new(x0, y0, x1, y1)), "{column}, {row}"); + } + } + } + #[test] fn tilted_bands_cover_the_ground_nearest_and_sharpest_first() { let (w, h) = (800.0, 600.0); @@ -687,6 +784,15 @@ mod tests { for b in &bands { let (near, far) = (c.depth_y(b.depth.0, h), c.depth_y(b.depth.1, h)); assert!(far < near, "{pitch}: rows {far}..{near}"); + // Past its far edge, away from the camera, the depth grows as it says. + let [f0, f1, n0, n1] = b.ground; + let (fx, fy) = ((f0.x + f1.x) / 2.0, (f0.y + f1.y) / 2.0); + let (dx, dy) = (fx - (n0.x + n1.x) / 2.0, fy - (n0.y + n1.y) / 2.0); + 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; + assert!((depth - want).abs() < 1e-9 * want, "{pitch}: {depth} vs {want}"); } // The fast lookup agrees with the camera. let look = c.ground_lookup(w, h); @@ -705,6 +811,9 @@ mod tests { let Some(m) = c.try_to_map(w * f64::from(i) / 10.0, h * f64::from(j) / 10.0, w, h) else { continue }; let inside = bands.iter().any(|b| b.camera.extent(b.width, b.height).padded(0.0, 1e-6).contains(m)); assert!(inside, "{pitch}: ({i}, {j}) uncovered"); + // And in a band's own ground, within its box. + let at = Extent::new(m.x, m.y, m.x, m.y); + assert!(bands.iter().any(|b| b.ground_touches(&at)), "{pitch}: ({i}, {j}) off the bands' ground"); } } } @@ -716,7 +825,11 @@ mod tests { } // A flat view is one band: itself. c.set_pitch(0.0); - assert_eq!(c.tilt_bands(w, h), vec![Band { camera: c, width: w, height: h, depth: (1.0, 1.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); } #[test] diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index c296bb65bd..d68d8244ca 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -3480,6 +3480,10 @@ fn gpu_turned( let (mut partial, mut pending_in_place) = (Vec::::new(), Vec::::new()); let mut plain = true; let last = bands.len().saturating_sub(1); + // 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(); + 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. if cancel::requested() { @@ -3487,9 +3491,14 @@ fn gpu_turned( return None; } let v = band_view(view, b); - let Some(RenderOutput::Gpu(scene)) = - render_frame(map, &v, full_res_rasters, Backend::Gpu, Labels::Tilted(view, &mut candidates), false, failed_source, env) - else { + 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 (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 }))); + 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 { if cancel::requested() { map.label_lock = lock; return None; @@ -3549,6 +3558,8 @@ fn gpu_turned( cmds.extend(scene.cmds); } map.label_lock = lock; + #[cfg(test)] + TILTED_MESHED.set(Some(meshed)); // A frame stopped during its last band goes no further (see `cancel`). if cancel::requested() { return None; @@ -4541,6 +4552,49 @@ thread_local! { static BAND_WATER: std::cell::RefCell>>> = const { std::cell::RefCell::new(None) }; } +/// The band of a tilted view a GPU frame is drawn for ([`gpu_turned`]), so the frame cuts its +/// layers into tiles of that band's ground ([`mesh_tiles::Tiling::band`]). +#[derive(Clone, Copy)] +struct GpuBand { + band: rustgis_map::camera::Band, + /// 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). + grow: f64, + /// And how much more past the far edge, per map unit there and per map unit a stroke reaches + /// as tessellated ([`mesh_tiles::Tiling::spread`]). + spread: f64, + /// The mesh vertices the bands before it took of the scene's budget ([`mesh::layer_room`]): + /// the bands are one scene. The frame adds its own. + meshed: usize, +} + +thread_local! { + /// The band a GPU frame of a tilted view is being drawn for ([`GpuBand`]); `None` for any + /// other frame. + static GPU_BAND: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// The mesh vertices the last tilted GPU scene's bands took together. + #[cfg(test)] + static TILTED_MESHED: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Holds [`GPU_BAND`] while a tilted view's bands are drawn on the GPU, and puts back what was +/// there when dropped (also when a band panics). +struct GpuBandHeld(Option); + +impl GpuBandHeld { + fn hold() -> GpuBandHeld { + GpuBandHeld(GPU_BAND.with(|b| b.take())) + } +} + +impl Drop for GpuBandHeld { + fn drop(&mut self) { + let kept = self.0.take(); + GPU_BAND.with(|b| b.set(kept)); + } +} + /// Holds [`BAND_WATER`] while a tilted view's bands are drawn, and puts back what was there when /// dropped (also when a band panics). struct BandWater(Option>>); @@ -4770,11 +4824,14 @@ fn render_frame( }; // GPU meshes reach further (`GPU_CULL_MARGIN`), so the camera fast path can move them. let mesh_cull = cull_extent(view, GPU_CULL_MARGIN); - // A tilted view widens a far stroke past a tile's reach (the shader scales it by depth), so - // it keeps one mesh a layer; a flat one cuts its layers into tiles of the cull. A tilted - // view's bands are drawn as flat views (their cameras look straight down) for the shader to - // tilt, so they're told apart by what their labels are for. - let tilted = view.camera.pitch != 0.0 || matches!(labels_to, Labels::Tilted(..) | Labels::Shared); + // A flat view cuts its layers into tiles of the cull. A tilted view's bands are drawn as flat + // views (their cameras look straight down) for the shader to tilt, so they're told apart by + // what their labels are for. A GPU band (`gpu_turned`) is cut into tiles of its own ground, + // its strokes' reach grown by their depth, which the shader widens them by (`GpuBand`); a + // view drawn tilted whole, or a drape's band, keeps one mesh a layer. + let band = if gpu && matches!(labels_to, Labels::Tilted(..)) { GPU_BAND.with(std::cell::Cell::get) } else { None }; + let tilted = + view.camera.pitch != 0.0 || matches!(labels_to, Labels::Shared) || (matches!(labels_to, Labels::Tilted(..)) && band.is_none()); let mesh_tiled = (!tilted).then_some(&mesh_cull); let mesh_visible = |e: &Extent| match &globe { Some(g) => g.may_see(e), @@ -4867,7 +4924,8 @@ fn render_frame( // The GPU scene's mesh vertices so far, against its budget: a layer may take more than its // own limit only from what is left (`mesh::layer_room`). let scene_budget = if backend.is_gpu() { mesh::scene_vertices() } else { 0 }; - let mut scene_meshed = 0usize; + // A tilted view's band adds to what the bands before took: they are one scene. + let mut scene_meshed = band.map_or(0, |b| b.meshed); // The pictures flushed so far, as the CPU fallback counts them (see `Runs`). let mut runs = Runs::default(); // The see-through layers drawn as pictures of their own so far (see `GPU_ALONE`); none unless @@ -5673,7 +5731,14 @@ fn render_frame( _ => std::sync::Arc::from(Vec::new()), }; let mut made_tiles = Vec::new(); - let tiling = mesh_tiled.map(|area| mesh_tiles::Tiling { area, kept: &kept_tiles, made: &mut made_tiles }); + let tiling = mesh_tiled.map(|area| mesh_tiles::Tiling { + area, + kept: &kept_tiles, + made: &mut made_tiles, + band: band.as_ref().map(|b| &b.band), + grow: band.map_or(1.0, |b| b.grow), + spread: band.map_or(0.0, |b| b.spread), + }); let collected = mesh::collect_layer( &mut cmds, layer, @@ -5698,6 +5763,9 @@ fn render_frame( // room); one lyon refused leaves the room to the batches after it. if let Ok(used) = collected { scene_meshed = scene_meshed.saturating_add(used); + if let Some(b) = band { + GPU_BAND.with(|g| g.set(Some(GpuBand { meshed: scene_meshed, ..b }))); + } } mesh_room = match collected { Ok(used) => mesh_room.saturating_sub(used), @@ -7770,7 +7838,10 @@ fn render_tilt_drape_drawn(map: &mut Map, view: &View, margin: f64, max_side: u3 let v = View { width: w, height: h, pixels_per_point: ppp, camera, sky: false }; // The bands share the read above. 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 } }); + out.push(TiltPatch { + pixmap: r.pixmap, + band: rustgis_map::camera::Band { camera, width: w, height: h, depth: b.depth, ground: b.ground }, + }); } } map.label_display = display; @@ -8199,7 +8270,7 @@ pub fn turned_band(view: &View) -> Option { let cam = view.camera; (cam.pitch == 0.0 && cam.bearing != 0.0).then(|| { let side = view.width.hypot(view.height) + 2.0; - rustgis_map::camera::Band { camera: Camera { bearing: 0.0, ..cam }, width: side, height: side, depth: (1.0, 1.0) } + rustgis_map::camera::Band::flat(Camera { bearing: 0.0, ..cam }, side, side) }) } @@ -11559,6 +11630,94 @@ mod tests { assert!(meshes.iter().all(|v| *v <= mesh::MAX_TILE_VERTICES), "each tile within its own: {meshes:?}"); } + /// A tilted view of a layer too dense for one mesh a band is a GPU scene still: each band cuts + /// it into tiles of its own ground, each tile touching that ground, the bands sharing the + /// scene's budget. + #[test] + fn a_tilted_view_cuts_each_bands_layers_into_tiles_of_its_ground() { + // 160,000 stroked triangles a few pixels across. + let mut m = Map::new("Map"); + m.basemap = rustgis_map::Basemap::Blank; + let mut d = Dataset::new("spread", GeometryType::Polygon, vec![]); + for i in 0..400 { + for j in 0..400 { + let (x, y) = (f64::from(i) * 0.03, f64::from(j) * 0.03); + let ring = vec![Coord::new(x, y), Coord::new(x + 0.02, y), Coord::new(x, y + 0.02)]; + d.push(Some(Geometry::Polygon(vec![vec![ring]])), vec![]); + } + } + m.add_dataset(d); + let camera = Camera { center: lonlat_to_merc(Coord::new(6.0, 11.0)), res: 700.0, bearing: 10.0, pitch: 60.0 }; + let view = View { width: 1600.0, height: 1000.0, pixels_per_point: 1.0, camera, sky: false }; + let bands = view.camera.tilt_bands(view.width, view.height); + TILTED_MESHED.set(None); + let Some(RenderOutput::Gpu(scene)) = render_backend(&mut m, &view, Backend::Gpu) else { panic!("a GPU scene") }; + assert!(!cmd_kinds(&scene).contains(&"image"), "no CPU picture: {:?}", cmd_kinds(&scene)); + // Each band's meshes, told apart by the depth they are clipped to at their far edge. + let mut per_band = vec![0usize; bands.len()]; + let mut tiles = 0; + for (c, clip) in scene.cmds.iter().zip(&scene.clips) { + let gpu_scene::DrawCmd::Mesh { origin, vertices, square, .. } = c else { continue }; + let i = if clip.depth[1] == f32::MAX { + bands.len() - 1 + } else { + bands.iter().position(|b| b.depth.1 as f32 == clip.depth[1]).expect("a band's clip") + }; + per_band[i] += vertices.len(); + let Some([x0, y0, x1, y1]) = square else { continue }; + tiles += 1; + let e = + Extent::new(origin[0] + f64::from(*x0), origin[1] + f64::from(*y0), origin[0] + f64::from(*x1), origin[1] + f64::from(*y1)); + assert!(bands[i].ground_touches(&e), "band {i}'s tile {e:?} on its ground"); + } + assert!(per_band.iter().any(|v| *v > mesh::MAX_LAYER_VERTICES), "a band past one mesh's limit: {per_band:?}"); + assert!(tiles > bands.len(), "in tiles: {tiles}"); + // The bands' meshes are counted together, against the scene's budget. + assert_eq!(TILTED_MESHED.get(), Some(per_band.iter().sum::())); + } + + /// A stroke reaching less than a tile past its line is cut into tiles, but in a tilted view's + /// band, where the shader widens it by its depth past a tile's side, its layer is one mesh: + /// the band grows the stroke's reach by the depth of its far edge. + #[test] + fn a_tilted_bands_wide_stroke_reaches_as_far_as_the_shader_widens_it() { + let line = Geometry::Line(vec![vec![Coord::new(-5.0, 0.0), Coord::new(5.0, 1.0)]]); + let mut m = Map::new("Map"); + m.basemap = rustgis_map::Basemap::Blank; + m.graticule = false; + let mut d = Dataset::new("wide", GeometryType::Polyline, vec![]); + d.push(Some(line.clone()), vec![]); + let id = m.add_dataset(d); + let camera = Camera { center: lonlat_to_merc(Coord::new(0.0, 0.5)), res: 2000.0, bearing: 0.0, pitch: 50.0 }; + let view = View { width: 1200.0, height: 900.0, pixels_per_point: 1.0, camera, sky: false }; + let bands = view.camera.tilt_bands(view.width, view.height); + let near = band_view(&view, &bands[0]); + let mpp = near.camera.res / near.pixels_per_point; + let side = mesh_tiles::tile_side(mpp).expect("tiles"); + let grow = view.camera.res * bands[0].depth.1 / bands[0].camera.res; + assert!(grow > 1.5, "{grow}"); + // A width reaching less than a side as tessellated, and past it widened. + let symbol = |w: f32| Symbol { stroke_width: w, ..m.layers[0].symbol(0) }; + let reach = |w: f32| mesh::stroke_reach(&line, &symbol(w), false, near.pixels_per_point as f32, mpp); + let w = (1..4000).map(|w| w as f32 * 0.5).find(|w| reach(*w) < side && reach(*w) * grow >= side * 1.05).expect("a width"); + let wide = symbol(w); + if let Some(l) = m.layer_mut(id) { + l.renderer = rustgis_map::Renderer::Single(wide); + } + let tiled = |m: &mut Map, view: &View| { + let Some(RenderOutput::Gpu(scene)) = render_backend(m, view, Backend::Gpu) else { panic!("a GPU scene") }; + let first = scene.cmds.iter().find_map(|c| match c { + gpu_scene::DrawCmd::Mesh { square, .. } => Some(square.is_some()), + _ => None, + }); + first.expect("meshed") + }; + // Flat at the near band's scale: in tiles. + assert!(tiled(&mut m, &View { camera: Camera { pitch: 0.0, bearing: 0.0, ..near.camera }, ..near }), "flat: in tiles"); + // In the near band, widened: one mesh. + assert!(!tiled(&mut m, &view), "tilted: one mesh"); + } + /// A turned or tilted view with a layer too dense to mesh is drawn on the CPU, as the CPU /// backend draws it, and the GPU frame tried first stops at that layer: the one above it is /// never meshed (#2540). Without it, the view stays a GPU scene. @@ -11780,12 +11939,12 @@ mod tests { let reach = gpu_scene::reach(&scene.cmds); assert!(reach >= side && reach < side * 1.01, "reach {reach} vs a tile's side {side}"); - // Tilted, its bands (each drawn as a flat view for the shader to tilt) keep one mesh a - // layer: a far stroke widens past a tile's reach. + // Tilted, its bands (each drawn as a flat view for the shader to tilt) cut it into tiles + // too, each band of its own ground. let view = View { camera: Camera { pitch: 45.0, ..camera }, ..view }; let Some(RenderOutput::Gpu(scene)) = render_backend(&mut m, &view, Backend::Gpu) else { panic!("gpu scene") }; assert!(scene.tilt.is_some() && cmd_kinds(&scene).contains(&"mesh"), "a tilted scene: {:?}", cmd_kinds(&scene)); - assert!(scene.cmds.iter().all(|c| !matches!(c, gpu_scene::DrawCmd::Mesh { square: Some(_), .. })), "no tiles in a tilted view"); + assert!(scene.cmds.iter().any(|c| matches!(c, gpu_scene::DrawCmd::Mesh { square: Some(_), .. })), "tiles in a tilted view"); } #[test] diff --git a/crates/render/src/mesh.rs b/crates/render/src/mesh.rs index a151850ab0..af5f94f1e1 100644 --- a/crates/render/src/mesh.rs +++ b/crates/render/src/mesh.rs @@ -479,7 +479,7 @@ pub(crate) fn estimate_vertices(g: &Geometry, s: &Symbol, wireframe: bool) -> us /// widest it is drawn at before the scene is made again ([`tessellation_width`]), and a pixel /// at that scale beside it. 0 for a feature with no stroke (a fill, a point: markers aren't /// tiled). -fn stroke_reach(g: &Geometry, s: &Symbol, wireframe: bool, ppp: f32, map_per_px: f64) -> f64 { +pub(crate) fn stroke_reach(g: &Geometry, s: &Symbol, wireframe: bool, ppp: f32, map_per_px: f64) -> f64 { let width_px = match g { Geometry::Point(_) | Geometry::MultiPoint(_) => return 0.0, Geometry::Line(_) if s.stroke.a() > 0 => (s.stroke_width * ppp).max(0.5), @@ -500,8 +500,10 @@ fn stroke_reach(g: &Geometry, s: &Symbol, wireframe: bool, ppp: f32, map_per_px: /// draws them, their cached extents, row filter, extent cull), so the GPU draws exactly the /// features the CPU would. Its lines and polygons are cut into the tiles of the scene's cull /// ([`Tiling`], [`crate::mesh_tiles`]), those kept from an earlier scene taken as they are and -/// the rest meshed on several threads, or made one mesh when `tiling` is `None` (a tilted view, -/// whose far strokes are wider than a tile's reach); its markers follow them as one command. +/// the rest meshed on several threads, or made one mesh when `tiling` is `None` (a view drawn +/// tilted whole); its markers follow them as one command. A tilted view's band +/// ([`Tiling::band`]) makes only the tiles on its ground, its strokes reaching as far as the +/// shader widens them, and is one mesh when one reaches a tile side or more. /// Tiled, its lines and polygons are those within a tile of the cull's tiles /// ([`crate::mesh_tiles::feature_area`]), which may be more than `visible` keeps, out of view. /// `limit` is what is left of the layer's room ([`layer_room`]; its earlier batches took the @@ -572,7 +574,10 @@ pub(crate) fn collect_layer( return Err(TessError::TooDense); } } + // In a tilted view's band the shader widens a stroke by its depth, past `grow` times from + // past the far edge. let reach = stroke_reach(g, &s, wireframe, ppp, map_per_px); + let reach = tiling.as_ref().map_or(reach, |t| t.widened(reach)); farthest = farthest.max(reach); features.push(crate::mesh_tiles::Feature { geometry: g, symbol: s, estimate: n, extent: e, reach }); } @@ -581,12 +586,16 @@ pub(crate) fn collect_layer( } let tiled = match tiling { _ if features.is_empty() => Some(Ok((Vec::new(), 0))), + // A tilted view's band with a stroke reaching a tile or more past its feature is one mesh, + // as a tilted view was: widened by depth, it could reach in from one left out (past + // `near`), over ground the band shows. + Some(t) if t.band.is_some() && side.is_none_or(|side| farthest >= side) => None, Some(t) => { // A stroke reaching a tile or more past its feature could reach in from one left out // (past `near`): its tiles aren't taken again, nor kept. let keeps = side.is_some_and(|side| farthest < side); let kept = if keeps { t.kept } else { &[] }; - let made = crate::mesh_tiles::tile_meshes(&features, t.area, kept, wireframe, ppp, map_per_px, limit); + let made = crate::mesh_tiles::tile_meshes(&features, t.area, t.band, kept, wireframe, ppp, map_per_px, limit); made.map(|made| { made.map(|(tiles, used)| { let cmds = tiles.iter().filter_map(|t| t.cmd.as_ref().and_then(DrawCmd::share)).collect(); diff --git a/crates/render/src/mesh_tiles.rs b/crates/render/src/mesh_tiles.rs index 63ce1fd589..6df9676b37 100644 --- a/crates/render/src/mesh_tiles.rs +++ b/crates/render/src/mesh_tiles.rs @@ -28,6 +28,13 @@ //! stroke reaching a tile side or more past its feature (wider than about 1,000 px) could reach //! in from a feature left out, which the scene doesn't look at: a layer that has one keeps no //! tiles. +//! +//! A tilted view's bands are tiled too, each drawn as a flat view for the shader to tilt +//! ([`Tiling::band`]). A band makes only the tiles touching its own ground (its bounding box, +//! the band's cull, is much larger at a steep pitch). The shader widens a stroke by its depth, +//! so a band's strokes reach as far as at its far edge, and a stroke from past that edge, wider +//! there, a little farther ([`Tiling::widened`]); one that reaches a tile side or more that way +//! leaves its layer one mesh in that band. use std::collections::BTreeMap; use std::sync::Arc; @@ -132,6 +139,30 @@ pub(crate) struct Tiling<'a> { /// Filled with this scene's tiles, in grid order, to keep; left empty when they can't be /// taken again. pub made: &'a mut Vec, + /// A tilted view's band the scene is ([`crate::GpuBand`]): only the tiles touching its ground + /// are made, and its strokes reach as far as [`Tiling::widened`] (the shader widens them by + /// their depth). `None`, 1 and 0 for a flat scene. + pub band: Option<&'a rustgis_map::camera::Band>, + /// How many times as far as tessellated a stroke reaches at the band's far edge. + pub grow: f64, + /// How much more a stroke is widened per map unit past the far edge, per map unit it reaches + /// as tessellated: [`rustgis_map::camera::Band::depth_per_unit`] times `grow`'s scale. + pub spread: f64, +} + +impl Tiling<'_> { + /// How far a stroke reaching `reach` as tessellated reaches over the band's ground, the shader + /// widening it by its depth: `grow` times at the far edge, and more from past it, where it + /// is deeper, by as much again as it reaches there. Unbounded when it widens faster than it + /// goes away. + pub fn widened(&self, reach: f64) -> f64 { + let grown = reach * self.grow.max(1.0); + if self.spread <= 0.0 { + return grown; + } + let left = 1.0 - reach * self.spread; + if left > 0.0 { grown / left } else { f64::INFINITY } + } } /// The tiles touching `area`: their columns and rows. `None` for an area that isn't finite. @@ -167,15 +198,41 @@ pub(crate) struct Feature<'a> { pub reach: f64, } -/// The tiles touching `area` that a layer's features reach, each with the features (by index) -/// reaching it, in grid order. A tile lists every feature reaching it, wherever in the tile, so -/// its features don't hang on where `area` lies. `None` when they would be more than -/// [`MAX_TILES`], or list more than [`MAX_MEMBERS`] features in all. -fn buckets(features: &[Feature<'_>], area: &Extent, side: f64) -> Option)>> { +/// No columns of a row: an empty run. +const NO_COLUMNS: std::ops::RangeInclusive = std::ops::RangeInclusive::new(1, 0); + +/// The tiles touching `area` (and a band's ground, when it is one) that a layer's features +/// reach, each with the features (by index) reaching it, in grid order. A tile lists every +/// feature reaching it, wherever in the tile, so its features don't hang on where `area` lies. +/// `None` when they would be more than [`MAX_TILES`], or list more than [`MAX_MEMBERS`] features +/// in all. +fn buckets( + features: &[Feature<'_>], + area: &Extent, + side: f64, + band: Option<&rustgis_map::camera::Band>, +) -> Option)>> { let index = |v: f64| (v / side).floor() as i64; let (in_columns, in_rows) = grid(area, side)?; + // A band draws only its own ground: a tile off it shows nothing there, so it is neither made + // nor counted (its cull, the ground's box, is much larger at a steep pitch). Each row's + // tiles on it run unbroken, the ground being convex: their columns, by row. + let on_ground: Option>> = band.map(|b| { + in_rows + .clone() + .map(|row| { + let y = row as f64 * side; + match b.ground_across(y, y + side) { + // A tile whose edge meets the ground's touches it. + Some((lo, hi)) => ((lo / side).ceil() as i64).saturating_sub(1)..=index(hi), + None => NO_COLUMNS, + } + }) + .collect() + }); let mut tiles: BTreeMap> = BTreeMap::new(); let mut members = 0usize; + let span = |r: &std::ops::RangeInclusive| if r.is_empty() { 0 } else { r.end().saturating_sub(*r.start()).saturating_add(1) }; for (k, f) in features.iter().enumerate() { let r = f.reach; let grown = Extent::new(f.extent.min_x - r, f.extent.min_y - r, f.extent.max_x + r, f.extent.max_y + r); @@ -188,8 +245,18 @@ fn buckets(features: &[Feature<'_>], area: &Extent, side: f64) -> Option| r.end().saturating_sub(*r.start()).saturating_add(1); - let count = span(&columns).saturating_mul(span(&rows)); + // The feature's columns in a row: those on the band's ground, if it is one. + let row_columns = |row: i64| match &on_ground { + Some(on) => { + let at = usize::try_from(row.saturating_sub(*in_rows.start())).ok(); + match at.and_then(|i| on.get(i)) { + Some(on) => *columns.start().max(on.start())..=*columns.end().min(on.end()), + None => NO_COLUMNS, + } + } + None => columns.clone(), + }; + let count = rows.clone().map(|row| span(&row_columns(row))).fold(0i64, i64::saturating_add); if usize::try_from(count).map_or(true, |n| n > MAX_TILES) { return None; } @@ -198,7 +265,7 @@ fn buckets(features: &[Feature<'_>], area: &Extent, side: f64) -> Option], area: &Extent, + band: Option<&rustgis_map::camera::Band>, kept: &[MadeTile], wireframe: bool, ppp: f32, map_per_px: f64, limit: usize, ) -> Option, usize), TessError>> { - tile_meshes_on(features, area, kept, wireframe, ppp, map_per_px, limit, CAPS, None) + tile_meshes_on(features, area, band, kept, wireframe, ppp, map_per_px, limit, CAPS, None) } /// [`tile_meshes`] within `caps`, on `threads` threads, or as [`threads_for`] decides. -#[expect(clippy::too_many_arguments, reason = "the layer, the scene's area and scale, the tiles kept, the limits and the threads")] +#[expect(clippy::too_many_arguments, reason = "the layer, the scene's area, band and scale, the tiles kept, the limits and the threads")] fn tile_meshes_on( features: &[Feature<'_>], area: &Extent, + band: Option<&rustgis_map::camera::Band>, kept: &[MadeTile], wireframe: bool, ppp: f32, @@ -484,7 +553,7 @@ fn tile_meshes_on( threads: Option, ) -> Option, usize), TessError>> { let side = tile_side(map_per_px)?; - let tiles = buckets(features, area, side)?; + let tiles = buckets(features, area, side, band)?; // The tiles kept from the last scene, as meshing them again would make them. let taken: Vec> = tiles.iter().map(|(tile, _)| kept.binary_search_by(|k| k.tile.cmp(tile)).ok().and_then(|i| kept.get(i))).collect(); @@ -620,7 +689,8 @@ mod tests { let features: Vec> = geoms.iter().map(|g| feature(g, symbol(rustgis_map::Rgba::rgb(9, 99, 199), 3.0))).collect(); let area = Extent::new(-2048.0, -2048.0, 2048.0, 2048.0); let made = |threads| { - let (cmds, used) = tile_meshes_on(&features, &area, &[], false, 1.0, 1.0, usize::MAX, CAPS, Some(threads)).unwrap().unwrap(); + let (cmds, used) = + tile_meshes_on(&features, &area, None, &[], false, 1.0, 1.0, usize::MAX, CAPS, Some(threads)).unwrap().unwrap(); let cmds = commands(&cmds); let bytes: Vec> = cmds .iter() @@ -651,7 +721,7 @@ mod tests { let f = feature(&line, symbol(rustgis_map::Rgba::rgb(0, 0, 0), 2.0)); let area = Extent::new(-1024.0, -1024.0, 1024.0, 1024.0); let (all, used) = - tile_meshes_on(std::slice::from_ref(&f), &area, &[], false, 1.0, 1.0, usize::MAX, CAPS, Some(1)).unwrap().unwrap(); + tile_meshes_on(std::slice::from_ref(&f), &area, None, &[], false, 1.0, 1.0, usize::MAX, CAPS, Some(1)).unwrap().unwrap(); let all = commands(&all); assert!(tiles(&all).len() >= 4, "{}", tiles(&all).len()); assert!(used < f.estimate, "cut to the area: {used} of {}", f.estimate); @@ -659,12 +729,13 @@ mod tests { // Room for the biggest tile but not the whole estimate: it meshes. let room = used.max(biggest); assert!(room < f.estimate); - assert!(tile_meshes_on(std::slice::from_ref(&f), &area, &[], false, 1.0, 1.0, room, CAPS, Some(1)).unwrap().is_ok()); + assert!(tile_meshes_on(std::slice::from_ref(&f), &area, None, &[], false, 1.0, 1.0, room, CAPS, Some(1)).unwrap().is_ok()); // Past the limit by a vertex, or with room for each tile but not all: refused alike on // any number of threads. for limit in [used - 1, biggest.max(used / 2)] { for threads in [1, 8] { - let short = tile_meshes_on(std::slice::from_ref(&f), &area, &[], false, 1.0, 1.0, limit, CAPS, Some(threads)).unwrap(); + let short = + tile_meshes_on(std::slice::from_ref(&f), &area, None, &[], false, 1.0, 1.0, limit, CAPS, Some(threads)).unwrap(); assert!(matches!(short, Err(TessError::TooDense)), "limit {limit}, {threads} threads"); } } @@ -684,8 +755,9 @@ mod tests { let s = symbol(rustgis_map::Rgba::rgb(0, 0, 0), 1.0); let features: Vec> = lines.iter().map(|l| feature(l, s)).collect(); let area = Extent::new(10.0, 10.0, 2100.0, 500.0); - let made = - |caps: Caps, threads: usize| tile_meshes_on(&features, &area, &[], false, 1.0, 1.0, usize::MAX, caps, Some(threads)).unwrap(); + let made = |caps: Caps, threads: usize| { + tile_meshes_on(&features, &area, None, &[], false, 1.0, 1.0, usize::MAX, caps, Some(threads)).unwrap() + }; let Ok((tiles, used)) = made(CAPS, 1) else { panic!("meshed") }; let needs: Vec = tiles.iter().filter(|t| t.cmd.is_some()).map(|t| t.need).collect(); assert!(needs.len() >= 4, "{needs:?}"); @@ -709,7 +781,7 @@ mod tests { let line = Geometry::Line(vec![vec![Coord::new(510.0, 100.0), Coord::new(510.0, 300.0)]]); let wide = feature(&line, symbol(rustgis_map::Rgba::rgb(0, 0, 0), 8.0)); let area = Extent::new(-2048.0, -2048.0, 2048.0, 2048.0); - let (cmds, _) = tile_meshes(std::slice::from_ref(&wide), &area, &[], false, 1.0, 1.0, usize::MAX).unwrap().unwrap(); + let (cmds, _) = tile_meshes(std::slice::from_ref(&wide), &area, None, &[], false, 1.0, 1.0, usize::MAX).unwrap().unwrap(); let cmds = commands(&cmds); let origins: Vec<[f64; 2]> = tiles(&cmds).into_iter().map(|(o, _)| o).collect(); assert_eq!(origins, [[0.0, 0.0], [512.0, 0.0]], "its own tile and the next east"); @@ -720,7 +792,7 @@ mod tests { Coord::new(-300.0, 900.0), ]]]); let filled = feature(&square, Symbol { stroke_width: 0.0, ..symbol(rustgis_map::Rgba::rgb(9, 99, 199), 0.0) }); - let (cmds, _) = tile_meshes(std::slice::from_ref(&filled), &area, &[], false, 1.0, 1.0, usize::MAX).unwrap().unwrap(); + let (cmds, _) = tile_meshes(std::slice::from_ref(&filled), &area, None, &[], false, 1.0, 1.0, usize::MAX).unwrap().unwrap(); let cmds = commands(&cmds); let tiled = tiles(&cmds); assert_eq!(tiled.len(), 9, "the nine tiles it covers"); @@ -771,7 +843,7 @@ mod tests { let before = Extent::new(-1800.0, -1500.0, 700.0, 900.0); let after = Extent::new(-1000.0, -1100.0, 1535.0, 1300.0); let made = |area: &Extent, kept: &[MadeTile]| { - tile_meshes_on(&features, area, kept, false, 1.0, 1.0, usize::MAX, CAPS, Some(1)).unwrap().unwrap() + tile_meshes_on(&features, area, None, kept, false, 1.0, 1.0, usize::MAX, CAPS, Some(1)).unwrap().unwrap() }; let (kept, _) = made(&before, &[]); let (fresh, fresh_used) = made(&after, &[]); @@ -797,7 +869,7 @@ mod tests { } fn made_within(features: &[Feature<'_>], area: &Extent, kept: &[MadeTile], limit: usize) -> Result<(Vec, usize), TessError> { - tile_meshes_on(features, area, kept, false, 1.0, 1.0, limit, CAPS, Some(1)).unwrap() + tile_meshes_on(features, area, None, kept, false, 1.0, 1.0, limit, CAPS, Some(1)).unwrap() } #[test] @@ -811,8 +883,67 @@ mod tests { reach, }; let area = Extent::new(-4096.0, -4096.0, 4096.0, 4096.0); - let tiles = |reach| buckets(&[f(reach)], &area, 512.0).unwrap().into_iter().map(|(t, _)| (t.column, t.row)).collect::>(); + let tiles = + |reach| buckets(&[f(reach)], &area, 512.0, None).unwrap().into_iter().map(|(t, _)| (t.column, t.row)).collect::>(); assert_eq!(tiles(0.0), [(0, 0)]); assert_eq!(tiles(2.0), [(-1, -1), (0, -1), (1, -1), (-1, 0), (0, 0), (1, 0)]); } + + #[test] + fn a_bands_tiles_are_those_of_its_ground_and_only_they_count() { + use rustgis_map::camera::{Band, Camera}; + let g = Geometry::Polygon(vec![vec![vec![ + Coord::new(0.0, 0.0), + Coord::new(100.0, 0.0), + Coord::new(100.0, 100.0), + Coord::new(0.0, 0.0), + ]]]); + 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 }; + // 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)]); + assert!(buckets(std::slice::from_ref(&whole), &area, 1.0, None).is_none()); + let tiles = buckets(std::slice::from_ref(&whole), &area, 1.0, Some(&strip)).expect("within the caps"); + assert_eq!(tiles.len(), 101); + assert!(tiles.iter().all(|(t, members)| t.row == 50 && members == &[0])); + // A steep trapezoid's tiles are those touching it, edges and corners too, whatever the + // features reach. + let ground = [Coord::new(-3.2, 90.0), Coord::new(97.5, 90.0), Coord::new(60.0, 10.0), Coord::new(40.0, 10.0)]; + let trapezoid = band(ground); + let small = + |x: f64, y: f64, reach| Feature { geometry: &g, symbol, estimate: 0, extent: Extent::new(x, y, x + 3.0, y + 2.0), reach }; + let features: Vec> = + (0..30).map(|i| small(f64::from(i * 7 % 97), f64::from(i * 13 % 89), f64::from(i % 3) * 2.5)).collect(); + let side = 8.0; + let tiles = buckets(&features, &area, side, Some(&trapezoid)).expect("tiles"); + let all = buckets(&features, &area, side, None).expect("tiles"); + let on = |t: &Tile| { + let [x, y] = t.corner(side); + trapezoid.ground_touches(&Extent::new(x, y, x + side, y + side)) + }; + let want: Vec<_> = all.into_iter().filter(|(t, _)| on(t)).collect(); + assert!(!want.is_empty() && tiles.len() < 100); + assert_eq!(tiles, want); + } + + #[test] + fn a_stroke_past_a_bands_far_edge_reaches_as_far_as_its_widening_there() { + let (area, mut made) = (Extent::new(0.0, 0.0, 1.0, 1.0), Vec::new()); + let mut tiling = Tiling { area: &area, kept: &[], made: &mut made, band: None, grow: 1.0, spread: 0.0 }; + assert_eq!(tiling.widened(3.0), 3.0, "flat"); + tiling.grow = 2.0; + assert_eq!(tiling.widened(3.0), 6.0, "at the far edge"); + // Past the far edge by `s`, a stroke reaching `r` as tessellated is widened to + // `r × (grow + spread × s)`: it reaches back over the edge from as far as that is. + tiling.spread = 0.01; + let (r, s) = (3.0, tiling.widened(3.0)); + assert!((r * (tiling.grow + tiling.spread * s) - s).abs() < 1e-9, "{s}"); + assert!(s > 6.0); + // One widened faster than it goes away reaches any tile. + assert_eq!(tiling.widened(100.0), f64::INFINITY); + } }