Skip to content
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/raster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ pub fn commands() -> Vec<C> {
),
C::new("raster.info", "Raster Information", "Data › Information", info).view().when(need_raster).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"layer"?}"#),
C::new("share.exportRaster", "Export Raster", "Data › Information", |s, p| super::exports::write_here(s, p, "share.exportRaster")).view().when(need_exportable).inputs(export_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params(
r#"{"layer"?, "path": "*.tif", "band"?: 1.. (rasters that aren't colour ones; a colour raster writes its colour bands), "cog"?: bool (a cloud-optimised GeoTIFF: 512 px tiles, Deflate, overviews; default false, an untiled GeoTIFF), "tiles"?: "a tile layer's name, or its index (0 = top): its raster tiles (XYZ, WMTS, WMS, a raster archive) put together as an RGBA GeoTIFF in Web Mercator; by default the tile layer picked in the Layers pane, when no layer is given or active", "bbox"?: "[west, south, east, north] in degrees, for a tile layer (default: the view's)", "zoom"?: "0..30, the tiles' zoom (default: the zoom the view shows); at most 1024 tiles and 8192 pixels a side"}"#,
r#"{"layer"?, "path": "*.tif", "band"?: 1.. (rasters that aren't colour ones; a colour raster writes its colour bands), "cog"?: bool (a cloud-optimised GeoTIFF: 512 px tiles, Deflate, overviews; default false, an untiled GeoTIFF), "tiles"?: "a tile layer's name, or its index (0 = top): its raster tiles (XYZ, WMTS, WMS, a raster archive) put together as an RGBA GeoTIFF in Web Mercator; by default the tile layer picked in the Layers pane, when no layer is given or active", "bbox"?: "[west, south, east, north] in degrees, for a tile layer (default: the view's)", "zoom"?: "0..30, the tiles' zoom (default: about the zoom the view shows at one pixel a point, as on a standard-density screen); at most 1024 tiles and 8192 pixels a side"}"#,
),
]
}
Expand Down
6 changes: 4 additions & 2 deletions crates/render/src/native_tiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,10 @@ pub(crate) fn draw(pm: &mut Pixmap, n: &Native, t: &TileLayer, view: &View, flat
let (Some(a), Some(b)) = (to_native(cam.to_map(w / 2.0, h / 2.0, w, h)), to_native(cam.to_map(w / 2.0 + 1.0, h / 2.0, w, h))) else {
return (false, None);
};
// The system's units per pixel of the map's pixmap.
let per_px = (b.x - a.x).hypot(b.y - a.y) / k;
// The system's units per pixel its tiles are fetched for: the map's pixmap's on a HiDPI
// display when sharp tiles are on, up to twice a logical pixel's detail; else a logical
// pixel's (#2390).
let per_px = (b.x - a.x).hypot(b.y - a.y) / f64::from(rustgis_tiles::template::detail(k as f32));
if !(lo.0 < hi.0 && lo.1 < hi.1 && per_px.is_finite() && per_px > 0.0) {
return (false, None);
}
Expand Down
293 changes: 268 additions & 25 deletions crates/render/src/single_image.rs

Large diffs are not rendered by default.

404 changes: 394 additions & 10 deletions crates/render/src/tiles.rs

Large diffs are not rendered by default.

14 changes: 12 additions & 2 deletions crates/tiles/src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1485,6 +1485,7 @@ fn decode_with(
b,
Box::new(move |r| {
settle(match r {
// The browser read it as a picture: a failure here isn't a document.
Ok(raw) => decode_image(&raw).map(Payload::Image),
Err(b) => decode(&b, want),
})
Expand Down Expand Up @@ -2363,6 +2364,9 @@ fn payload_bytes(p: &Payload) -> usize {
}
}

/// What an image fetch whose answer is in no picture format fails with first (then why).
pub const NOT_A_PICTURE: &str = "not a picture";

/// Decodes fetched bytes.
pub fn decode(bytes: &[u8], want: Want) -> Result<Payload, String> {
if bytes.is_empty() {
Expand All @@ -2372,7 +2376,11 @@ pub fn decode(bytes: &[u8], want: Want) -> Result<Payload, String> {
return Err(format!("{} bytes is too large for a tile", bytes.len()));
}
match want {
Want::Image => decode_image(bytes).map(Payload::Image),
// An answer in no picture format (a WMS exception document) is said as such, so it is
// told from a failed fetch and from a picture that couldn't be read (one too large).
Want::Image => decode_image(bytes)
.map(Payload::Image)
.map_err(|e| if bytes.starts_with(RAW) || image::guess_format(bytes).is_ok() { e } else { format!("{NOT_A_PICTURE}: {e}") }),
Want::Vector => mvt::decode(bytes).map(Payload::Vector),
Want::Json => serde_json::from_slice(bytes).map(Payload::Json).map_err(|e| format!("not JSON: {e}")),
}
Expand Down Expand Up @@ -4714,7 +4722,9 @@ mod tests {
assert_eq!((back.width(), back.height()), (2, 2));
assert!(matches!(decode(b"{\"a\": 1}", Want::Json), Ok(Payload::Json(_))));
assert!(matches!(decode(b"", Want::Image), Ok(Payload::Empty)));
assert!(decode(b"not a picture", Want::Image).is_err());
assert!(decode(b"not a picture", Want::Image).is_err_and(|e| e.starts_with(NOT_A_PICTURE)));
// A picture that can't be read (here, cut short) is no document: said as it is.
assert!(decode(b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR", Want::Image).is_err_and(|e| !e.starts_with(NOT_A_PICTURE)));
assert!(decode(b"{", Want::Json).is_err());
}

Expand Down
35 changes: 33 additions & 2 deletions crates/tiles/src/draw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,17 @@ fn tiles_for(src: &Source, view: &Extent, frame: &Frame, zoom: f32, pending: &mu
tiles_in(src, view, None, frame, zoom, pending, error).items
}

/// The zoom of a raster source's `tile_size`-pixel tiles drawn at `frame` over `view`: by the
/// display's own pixels on a HiDPI one when sharp tiles are on (#2390), up to twice a logical
/// pixel's detail; back towards a logical pixel's zoom where the view's tiles there would pass the
/// most a source draws (a 5K or 6K display), rather than leave the view's corners out.
fn raster_zoom(frame: &Frame, view: &Extent, tile_size: u32, min_zoom: u8, max_zoom: u8) -> u8 {
let logical = template::zoom_for(frame.m_per_px * f64::from(frame.ppp), tile_size, max_zoom);
let sharp = template::zoom_for(frame.m_per_px * f64::from(frame.ppp / template::detail(frame.ppp)), tile_size, max_zoom);
// Never below the source's own coarsest zoom, which would draw nothing.
if sharp > logical { template::fitting_zoom(view, sharp, logical.max(min_zoom)) } else { sharp }
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/// The tiles of a source in view and out to `reach` (those in the cache only), with stand-ins
/// for those not here yet. Expanded destinations retain the supplying document's reach;
/// refused tiles are counted in `error` and network history without requesting or reusing bytes. Valid
Expand All @@ -624,8 +635,7 @@ pub(crate) fn tiles_in(
let (tiles, from, min_z, max_z, want, z) = match src {
Source::Raster { tiles, from, tile_size, min_zoom, max_zoom, .. }
| Source::RasterDem { tiles, from, tile_size, min_zoom, max_zoom, .. } => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance (confidence ~40%): sharp zoom also applies to Source::RasterDem.

This arm now goes through raster_zoom, so on a 2x display terrain DEM tiles take the next zoom. That is about 4x the elevation-tile requests and decodes, but DEM tiles carry no text or lines, so the "sharp text" benefit in the PR doesn't apply to them. The gain is only more elevation detail (hillshade/sampling), and the cost is paid on every HiDPI terrain layer.

If the extra elevation detail is wanted, please say so in docs/user-guide/data-formats.md, which currently lists raster DEMs as sharp without explaining why. If not, DEMs could keep the logical zoom while plain rasters use raster_zoom.

let z = template::zoom_for(frame.m_per_px * f64::from(frame.ppp), *tile_size, *max_zoom);
(tiles, from, *min_zoom, *max_zoom, Want::Image, z)
(tiles, from, *min_zoom, *max_zoom, Want::Image, raster_zoom(frame, view, *tile_size, *min_zoom, *max_zoom))
}
Source::Vector { tiles, from, min_zoom, max_zoom, .. } => {
(tiles, from, *min_zoom, *max_zoom, Want::Vector, (zoom.floor() as u8).min(*max_zoom))
Expand Down Expand Up @@ -1318,6 +1328,27 @@ fn area(r: &[(f32, f32)]) -> f32 {

#[cfg(test)]
pub(crate) mod tests {
/// On a HiDPI display a raster source takes the next zoom's tiles while the view's fit the most
/// a source draws, and goes back towards a logical pixel's zoom where they don't (#2390).
#[test]
fn sharp_raster_tiles_keep_to_the_tile_budget() {
use super::{Frame, raster_zoom, template};
// A zoom-10 logical pixel (152.9 m), at 2 device pixels a point.
let logical = 2.0 * template::HALF_WORLD / (256.0 * 1024.0);
let zoom_of = |w: f64, h: f64, ppp: f32, min: u8| {
let frame = Frame { left: 0.0, top: h * logical, m_per_px: logical / f64::from(ppp), ppp };
raster_zoom(&frame, &rustgis_geom::Extent::new(0.0, 0.0, w * logical, h * logical), 256, min, 22)
};
// A 1500 × 900 point view: 6 × 4 tiles of zoom 10, 12 × 7 of zoom 11.
assert_eq!(zoom_of(1500.0, 900.0, 1.0, 0), 10);
assert_eq!(zoom_of(1500.0, 900.0, 2.0, 0), 11);
// A 6000 × 3400 point one: 47 × 27 of zoom 11 pass 400; zoom 10's fit.
assert_eq!(zoom_of(6000.0, 3400.0, 2.0, 0), 10);
// A source drawn from zoom 11 keeps it, its tiles nearest the view's centre, rather than
// falling back to a zoom it has none of.
assert_eq!(zoom_of(6000.0, 3400.0, 2.0, 11), 11);
}

#[test]
fn refusal_counts_are_not_substring_duplicates() {
let mut error = Some("12 tiles left out: refused".to_string());
Expand Down
39 changes: 39 additions & 0 deletions crates/tiles/src/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,38 @@ pub fn covering(e: &Extent, z: u8) -> Vec<Placed> {
out
}

/// The most a raster tile's or a single picture's detail follows a HiDPI display: twice its
/// logical pixels. A 3x phone or a 300-DPI print would ask for nine times or more the tiles, and
/// the text drawn into them would come out unreadably small.
pub const MAX_DETAIL: f32 = 2.0;

static SHARP: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);

/// Turns sharp raster tiles on HiDPI displays on or off (Settings › Map Tiles; on by default):
/// raster tiles and single pictures are fetched for the display's own pixels, up to
/// [`MAX_DETAIL`], rather than for its logical ones. Their text and lines come out sharp and
/// smaller, as in a HiDPI view of the service's own map.
pub fn set_sharp(on: bool) {
SHARP.store(on, std::sync::atomic::Ordering::Relaxed);
}

/// Whether sharp raster tiles are on ([`set_sharp`]).
pub fn sharp() -> bool {
SHARP.load(std::sync::atomic::Ordering::Relaxed)
}

/// The device pixels a raster tile's or a single picture's pixel is fetched for at `ppp` device
/// pixels a logical one: `ppp` up to [`MAX_DETAIL`] when sharp tiles are on, else 1 (a pixel a
/// logical pixel, stretched over `ppp` device pixels).
pub fn detail(ppp: f32) -> f32 {
detail_with(ppp, sharp())
}

/// [`detail`] with the setting given.
pub fn detail_with(ppp: f32, sharp: bool) -> f32 {
if sharp && ppp.is_finite() { ppp.clamp(1.0, MAX_DETAIL) } else { 1.0 }
}

/// The zoom level whose `tile_size`-pixel tiles best match `m_per_px` metres per pixel, rounded
/// to the sharper level a little before halfway. Never below 0 or above `max`.
pub fn zoom_for(m_per_px: f64, tile_size: u32, max: u8) -> u8 {
Expand Down Expand Up @@ -461,6 +493,13 @@ mod tests {
assert_eq!(zoom_for(156_543.03 / 1024.0, 512, 22), 9);
assert_eq!(zoom_for(0.001, 256, 19), 19);
assert_eq!(zoom_for(f64::NAN, 256, 19), 0);
// On a 2x display a sharp view takes the next zoom; a 3x one no further (#2390).
let logical = 156_543.03 / 1024.0;
assert_eq!(zoom_for(logical / f64::from(detail_with(2.0, true)), 256, 22), 11);
assert_eq!(zoom_for(logical / f64::from(detail_with(3.0, true)), 256, 22), 11);
assert_eq!(zoom_for(logical / f64::from(detail_with(2.0, false)), 256, 22), 10);
assert_eq!(detail_with(0.5, true), 1.0, "never coarser than a logical pixel");
assert_eq!(detail_with(f32::NAN, true), 1.0);
assert!((style_zoom(78_271.517) - 0.0).abs() < 1e-3);
let e = TileId { z: 1, x: 1, y: 0 }.extent();
assert!((e.min_x - 0.0).abs() < 1e-6 && (e.max_y - HALF_WORLD).abs() < 1e-6);
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/src/chrome.rs
Original file line number Diff line number Diff line change
Expand Up @@ -893,6 +893,7 @@ pub(crate) const UI_COMMANDS: &[(&str, &str, &str)] = &[
("ui.themeReload", "Reload Themes", "Settings › Theme"),
("ui.scale", "Reset Interface Scale", "Settings › Theme"),
("ui.datumGrids", "Toggle Downloading Datum Grids", "Settings › Datum Grids"),
("ui.sharpTiles", "Toggle Sharp Tiles on HiDPI Displays", "Settings › Map Tiles"),
("ui.map.gpu", "Toggle GPU Rendering", "View"),
("ui.importShapefile", "Import Shapefile with Projection…", "Home › Add"),
("ui.measurementUnits", "Toggle Imperial Measurements", "Home › Inspect › Measure"),
Expand Down
47 changes: 47 additions & 0 deletions crates/ui-egui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -766,6 +766,9 @@ pub struct UiState {
/// Whether datum grids a coordinate system needs are downloaded from PROJ's grid server
/// (#2032 A4): off unless turned on, as it reaches a server.
pub download_grids: bool,
/// Whether raster tiles and single pictures are fetched for a HiDPI display's own pixels
/// (#2390): on unless turned off.
pub sharp_tiles: bool,
/// Key combinations the native menu bar keeps for itself (macOS: Quit, Close Window, Hide…):
/// a shortcut on one would never reach the app, so the shortcut editor refuses them.
pub reserved_shortcuts: Vec<egui::KeyboardShortcut>,
Expand Down Expand Up @@ -1041,6 +1044,7 @@ impl Default for UiState {
start_with: StartWith::Sample,
ask_layers: true,
download_grids: false,
sharp_tiles: true,
reserved_shortcuts: Vec::new(),
choosing: Vec::new(),
last_project: None,
Expand Down Expand Up @@ -1650,6 +1654,8 @@ impl RustGisApp {
self.ui.ask_layers = self.services.load_pref.as_ref().and_then(|load| load("ask_file_layers")).is_none_or(|v| v != "off");
self.ui.download_grids = self.services.load_pref.as_ref().and_then(|load| load("download_datum_grids")).is_some_and(|v| v == "on");
rustgis_engine::grids::set_enabled(self.ui.download_grids);
self.ui.sharp_tiles = self.services.load_pref.as_ref().and_then(|load| load("sharp_tiles")).is_none_or(|v| v != "off");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AGENTS.md "Never silent" (confidence ~30%): an unreadable saved value is quietly read as "on".

is_none_or(|v| v != "off") treats any stored value other than "off" as on, with no notice. The new ui.sharpTiles command refuses junk values, and the test says so, so the load path is looser than the command. A value written by a newer RustGIS would be read as on and then overwritten by the next toggle.

The same pattern is used for ask_file_file_layers in the lines above, so this may be deliberate. If it is, a short comment saying so would help. If not, mapping only "on" and "off" and keeping other values unchanged would match the rule.

rustgis_engine::render::rustgis_tiles::template::set_sharp(self.ui.sharp_tiles);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// A stored projection this version can't use means Web Mercator.
if let Some(code) = self.services.load_pref.as_ref().and_then(|load| load("start_projection"))
&& let Ok(p) = rustgis_engine::map::Projection::from_code(&code)
Expand Down Expand Up @@ -3622,6 +3628,22 @@ impl RustGisApp {
}
return Ok(json!({"on": self.ui.download_grids}));
}
// Whether raster tiles are sharp on a HiDPI display (#2390).
"ui.sharpTiles" => {
// Without `on` it toggles; a value that isn't true or false is refused.
self.ui.sharp_tiles = match p.get("on") {
None | Some(Value::Null) => !self.ui.sharp_tiles,
Some(v) => v.as_bool().ok_or("on must be true or false")?,
};
rustgis_engine::render::rustgis_tiles::template::set_sharp(self.ui.sharp_tiles);
if let Some(save) = &self.services.save_pref {
save("sharp_tiles", if self.ui.sharp_tiles { "on" } else { "off" });
}
// The map and an open layout page are drawn again with tiles at the new detail.
self.map.invalidate();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
self.layout.redraw();
return Ok(json!({"on": self.ui.sharp_tiles}));
}
"ui.recover" => return autosave::recover(self, p),
"ui.startup" => {
// `project` (#377) or, as before, `blank`; `project` wins when both are given.
Expand Down Expand Up @@ -9220,6 +9242,31 @@ mod datum_grid_setting_tests {
use rustgis_engine::{Project, Session};
use serde_json::json;

/// Sharp tiles on HiDPI displays (#2390) are on by default, kept as a choice, read at start
/// and turned off by it; a value that isn't true or false is refused.
#[test]
fn sharp_tiles_are_a_kept_choice_on_by_default() {
let saved = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let log = saved.clone();
let services = crate::Services {
load_pref: Some(Box::new(|k| (k == "sharp_tiles").then(|| "off".to_string()))),
save_pref: Some(Box::new(move |k, v| log.lock().unwrap().push((k.to_string(), v.to_string())))),
..crate::Services::default()
};
let mut app = RustGisApp::new(Session::new(Project::default())).with_services(services);
// The setting itself is shared by the tests running beside this one: only the choice is
// looked at, and it is left on.
assert!(!app.ui.sharp_tiles, "read at start");
assert_eq!(app.run("ui.sharpTiles", json!({"on": true})).unwrap(), json!({"on": true}));
assert_eq!(saved.lock().unwrap().last().cloned(), Some(("sharp_tiles".to_string(), "on".to_string())));
for junk in [json!({"on": "false"}), json!({"on": 0})] {
assert!(app.run("ui.sharpTiles", junk).is_err());
assert!(app.ui.sharp_tiles);
}
// Without a choice kept: on.
assert!(RustGisApp::new(Session::new(Project::default())).ui.sharp_tiles);
}

/// Downloading datum grids is off unless turned on (it reaches a server), and the choice is
/// kept as a preference. Turned on only by `rustgis-engine`'s own test, which reaches no
/// network: here, where other tests run beside it, it stays off.
Expand Down
12 changes: 11 additions & 1 deletion crates/ui-egui/src/ribbon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3717,7 +3717,8 @@ fn plugin_tab(app: &mut RustGisApp, ui: &mut Ui, plugin: &str) {
}
}

/// The Settings tab: theme, scale, customization, language, start-up and autosave.
/// The Settings tab: theme, scale, customization, language, start-up, datum grids, map tiles,
/// performance and autosave.
fn settings_tab(app: &mut RustGisApp, ui: &mut Ui) {
group(ui, "Theme", |ui| {
theme_menu(app, ui);
Expand Down Expand Up @@ -3769,6 +3770,15 @@ fn settings_tab(app: &mut RustGisApp, ui: &mut Ui) {
let _ = app.run("ui.datumGrids", json!({"on": on}));
}
});
group(ui, "Map Tiles", |ui| {
let mut on = app.ui.sharp_tiles;
let tip = tl!(
"On a high-resolution (HiDPI) display, fetch raster tiles and WMS pictures for the display's own pixels, up to twice the detail: text and lines in them come out sharp and smaller. Off, they are fetched for its logical pixels and stretched: softer, with larger text."
);
if ui.checkbox(&mut on, tl!("Sharp Tiles on HiDPI Displays")).on_hover_text(tip).clicked() {
let _ = app.run("ui.sharpTiles", json!({"on": on}));
}
});
// The browser has no threads to set.
if !cfg!(target_arch = "wasm32") {
group(ui, "Performance", |ui| threads_menu(app, ui));
Expand Down
Loading
Loading