Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ layout.seriesRefresh layout?
layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? font? fallback? title? allClasses? hideOther? showNoData? exclude? labels? columns? textSize? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? map? scale? center? bearing? pitch? grid? extentIndicator? border? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? hideLabels? rows? background?
locator.find locator? text limit? zoom?
map.activate name
map.addTiles url kind? name? bounds? attribution? minZoom? maxZoom? tileSize? singleImage? tms? subdomains? layers? styleLayers? opacity? blend? overlay? top? replace? id? view? start? end? unit? interval? dates? legend? connection?
map.addTiles url kind? name? bounds? attribution? minZoom? maxZoom? tileSize? singleImage? tms? subdomains? layers? styleLayers? opacity? blend? resampling? overlay? top? replace? id? view? start? end? unit? interval? dates? legend? connection?
map.basemap name keepTiles? color?
map.bodies
map.body name? basemap?
Expand Down Expand Up @@ -352,7 +352,7 @@ map.selectTiles name? index? id?
map.setBearing bearing by
map.setPitch pitch by
map.setScale scale
map.setTiles name? index? id? visible? opacity? blend? move? to? rename? bands? range? dequantize? legend? hiddenLayers? singleImage? tileSize?
map.setTiles name? index? id? visible? opacity? blend? resampling? move? to? rename? bands? range? dequantize? legend? hiddenLayers? singleImage? tileSize?
map.terrain layer? tiles? encoding? exaggeration? block? water? off?
map.thumbnail create? image? path? clear?
map.tiles
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/cmd/geolibre.rs
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,7 @@ fn finish_archive(s: &mut Session, p: &Value, bytes: Vec<u8>) -> CmdResult {
loaded.visible = t.visible;
loaded.opacity = t.opacity;
loaded.blend = t.blend;
loaded.resampling = t.resampling;
loaded.name = t.name.clone();
*t = loaded;
}
Expand Down
108 changes: 105 additions & 3 deletions crates/engine/src/cmd/tiles.rs

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ pub const CAPABILITIES: &[&str] = &[
"label-clearance",
"svg-markers",
"label-duplicates",
"tile-resampling",
];
/// An offline area keeping the versions that lost a sync or a Bring Back
/// (`OfflineArea::conflicts`, #2468): an older reader would save it again without them.
Expand Down
36 changes: 36 additions & 0 deletions crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[
("label-weight", command_weighs_labels),
("label-clearance", command_clears_labels),
("label-duplicates", command_removes_duplicate_labels),
("tile-resampling", command_resamples_tiles),
];

/// A saved `labels.placement` that has a class remove duplicates, read as the command reads it
Expand All @@ -172,6 +173,19 @@ fn command_removes_duplicate_labels(id: &str, params: &Value) -> bool {
}
}

/// A saved `map.addTiles` or `map.setTiles` drawing a tile layer's pictures nearest (#2804), read as
/// the command reads it: an older reader runs it without the key, saying nothing, so the layer would
/// stay blended. `bilinear` is what an older reader keeps.
fn command_resamples_tiles(id: &str, params: &Value) -> bool {
match id {
"map.addTiles" | "map.setTiles" => {
crate::cmd::tiles::resampling(params).ok().flatten() == Some(rustgis_map::raster::Resampling::Nearest)
}
"script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_resamples_tiles)),
_ => false,
}
}

/// A saved `labels.placement` that gives a class a clearance other than 2, read as the command
/// reads it (#2828): an older reader runs it without the key, saying nothing, so the labels would
/// keep 2 points apart as before. 2 or null is what an older reader keeps.
Expand Down Expand Up @@ -687,6 +701,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static
let (mut polygon, mut svg) = (false, false);
let (mut offline_area_id, mut paper, mut native, mut guided, mut weighed, mut cleared, mut deduped) =
(false, false, false, false, false, false, false);
let mut crisp = false;
for map in maps {
offline_area_id |= map.offline_area_id.is_some();
// A blank basemap's paper colour (#2532), which an older reader would draw and save white.
Expand All @@ -695,6 +710,8 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static
weighed |= map.layers.iter().any(label_weight);
cleared |= map.layers.iter().any(label_clearance);
deduped |= map.layers.iter().any(removes_duplicate_labels);
// A tile layer drawn nearest (#2804), which an older reader would draw and save blended.
crisp |= map.tiles.iter().any(|t| t.resampling != rustgis_map::raster::Resampling::Bilinear);
// An older reader doesn't know the MGRS graticule (#1042 piece 8): it refuses the
// project by name rather than failing to read the type.
mgrs |= map.graticule_type == rustgis_map::graticule::GraticuleType::Mgrs;
Expand Down Expand Up @@ -745,6 +762,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static
(weighed, "label-weight"),
(cleared, "label-clearance"),
(deduped, "label-duplicates"),
(crisp, "tile-resampling"),
(offline_area_id, "offline-map-area-id"),
(paper, "blank-paper"),
(native, super::NATIVE_COORDINATES),
Expand Down Expand Up @@ -862,6 +880,24 @@ mod tests {
serde_json::from_slice(bytes).unwrap()
}

/// A tile layer drawn nearest (#2804) reads back as it was and saving names `tile-resampling`;
/// one drawn blended, as an older reader would, names nothing. So does a saved step setting it.
#[test]
fn tile_resampling_fixture_reads_its_setting() {
use rustgis_map::raster::Resampling;
let fixture = Project::from_json(include_str!("../../../schema/fixtures/tile_resampling.rgis")).unwrap();
let saved = serde_json::to_value(&fixture).unwrap();
assert_eq!(saved["requires"], json!(["tile-resampling"]));
assert_eq!(fixture.maps[0].tiles[0].resampling, Resampling::Nearest);
let reopened = Project::from_json(&saved.to_string()).unwrap();
assert_eq!(serde_json::to_value(&reopened).unwrap(), saved);
let mut plain = fixture;
plain.maps[0].tiles[0].resampling = Resampling::Bilinear;
assert!(serde_json::to_value(&plain).unwrap().get("requires").is_none());
assert!(command_resamples_tiles("map.setTiles", &json!({"index": 0, "resampling": "nearest"})));
assert!(!command_resamples_tiles("map.setTiles", &json!({"index": 0, "resampling": "bilinear"})));
}

/// A saved MGRS graticule drawn on top in a color of its own (#1042 piece 8) reads back as it
/// was, and saving names all three again; a map without them names none.
#[test]
Expand Down
55 changes: 55 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23559,6 +23559,61 @@ fn identify_reports_vector_tile_features() {
let _ = std::fs::remove_dir_all(dir);
}

/// A vector tile archive draws shapes, not pictures: once it's read, `map.setTiles` refuses a
/// resampling it would ignore; one that can't be read says so, and a local picture archive takes
/// it as it's added (#2804).
#[test]
fn a_vector_archive_refuses_resampling() {
use crate::render::rustgis_tiles::{mvt, pmtiles};
let road =
mvt::Feature { id: None, kind: mvt::GeomKind::LineString, geometry: vec![vec![[0.0, 2048.0], [4096.0, 2048.0]]], props: vec![] };
let tile = mvt::encode(&mvt::Tile { layers: vec![mvt::Layer { name: "roads".into(), extent: 4096, features: vec![road] }] });
let new = pmtiles::NewArchive {
tile_type: pmtiles::TileType::Mvt,
gzipped_tiles: false,
bounds: [-180.0, -85.0, 180.0, 85.0],
metadata: json!({"vector_layers": [{"id": "roads"}]}),
};
let dir = std::env::temp_dir().join(format!("rustgis-vector-resampling-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("roads.pmtiles");
std::fs::write(&path, pmtiles::write(vec![(0, 0, 0, tile)], &new).unwrap()).unwrap();
let mut s = Session::new(Project::default());
s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap();
// The archive's header arrives in the background.
for _ in 0..500 {
if s.run("map.tiles", &json!({})).unwrap()[0].get("sourceLayers").is_some() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10)); // test-wait: the archive's header is read on another thread
}
let err = s.run("map.setTiles", &json!({"index": 0, "resampling": "nearest"})).unwrap_err();
assert!(err.contains("picture tiles"), "{err}");
assert_eq!(s.map().tiles[0].resampling, rustgis_map::raster::Resampling::Bilinear);
// One that can't be read says so.
let missing = dir.join("missing.pmtiles").display().to_string();
let err = s.run("map.addTiles", &json!({"url": missing, "kind": "pmtiles", "resampling": "nearest"})).unwrap_err();
assert!(err.contains("couldn't be read"), "{err}");
// A local archive of pictures takes it as it's added: its header is read first.
let png = {
let mut out = std::io::Cursor::new(Vec::new());
image::RgbaImage::from_pixel(4, 4, image::Rgba([90, 120, 60, 255])).write_to(&mut out, image::ImageFormat::Png).unwrap();
out.into_inner()
};
let pictures = pmtiles::NewArchive {
tile_type: pmtiles::TileType::Png,
gzipped_tiles: false,
bounds: [-180.0, -85.0, 180.0, 85.0],
metadata: json!({}),
};
let imagery = dir.join("imagery.pmtiles");
std::fs::write(&imagery, pmtiles::write(vec![(0, 0, 0, png)], &pictures).unwrap()).unwrap();
let url = imagery.display().to_string();
s.run("map.addTiles", &json!({"url": url, "kind": "pmtiles", "resampling": "nearest"})).unwrap();
assert_eq!(s.map().tiles[0].resampling, rustgis_map::raster::Resampling::Nearest);
let _ = std::fs::remove_dir_all(&dir);
}

/// A vector archive's source layers are listed by `map.tiles`; one switched off with
/// `map.setTiles {hiddenLayers}` isn't identified, the setting undoes and is kept with the project,
/// and a bad list is refused without changing anything.
Expand Down
14 changes: 14 additions & 0 deletions crates/map/src/tiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,10 @@ pub struct TileLayer {
/// hillshade).
#[serde(default, skip_serializing_if = "is_normal")]
pub blend: crate::effects::Blend,
/// How its pictures are drawn at a size other than their own: smooth (bilinear), as every
/// tile layer was before, or crisp, each of the picture's pixels a block (#2804).
#[serde(default = "smooth", skip_serializing_if = "is_smooth")]
pub resampling: crate::raster::Resampling,
Comment thread
Mavrick-F marked this conversation as resolved.
Resolved
/// The catalog entry it came from (`osm`, `esri-imagery`), when it came from one.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub id: String,
Expand Down Expand Up @@ -335,6 +339,14 @@ fn one() -> f32 {
fn is_false(b: &bool) -> bool {
!*b
}
fn smooth() -> crate::raster::Resampling {
crate::raster::Resampling::Bilinear
}

fn is_smooth(r: &crate::raster::Resampling) -> bool {
*r == smooth()
}

fn is_normal(b: &crate::effects::Blend) -> bool {
*b == crate::effects::Blend::Normal
}
Expand Down Expand Up @@ -407,6 +419,7 @@ impl TileLayer {
overlay: false,
over: None,
blend: crate::effects::Blend::Normal,
resampling: smooth(),
id: String::new(),
layers: Vec::new(),
style_layers: String::new(),
Expand Down Expand Up @@ -702,6 +715,7 @@ impl TileLayer {
overlay: _,
over: _,
blend: _,
resampling: _,
id: _,
layers: _,
style_layers: _,
Expand Down
1 change: 1 addition & 0 deletions crates/render/examples/tile_mesh_bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ fn main() {
layers: Vec::new(),
style_layers: String::new(),
hidden_layers: Vec::new(),
nearest: false,
};
for (name, lon, lat, zoom) in
[("Manhattan z14.3", -73.98, 40.75, 14.3f64), ("Manhattan z12.3", -73.98, 40.75, 12.3), ("Paris z15.3", 2.35, 48.86, 15.3)]
Expand Down
3 changes: 3 additions & 0 deletions crates/render/src/gpu_scene.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,9 @@ pub struct TileQuad {
/// The part of the picture in that square: left, top, right, bottom (0..1, top down).
pub uv: [f32; 4],
pub opacity: f32,
/// Each of the picture's pixels a block where it's drawn larger or smaller than its own size,
/// rather than blended (the layer's resampling, #2804).
pub nearest: bool,
}

impl TileQuad {
Expand Down
2 changes: 1 addition & 1 deletion crates/render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ pub mod vector;
pub use tiles::{Live, live as live_tiles};

pub use rustgis_tiles;
pub use tiles::{source_layers as tile_source_layers, spec as tile_spec, style_view};
pub use tiles::{draws_pictures as tile_draws_pictures, source_layers as tile_source_layers, spec as tile_spec, style_view};

/// Natural Earth 1:110m sample data (public domain), fetched by `build.rs` from rustgis-assets.
/// The countries in another worldview are downloaded when one is chosen, never built in.
Expand Down
20 changes: 16 additions & 4 deletions crates/render/src/native_tiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,14 +189,15 @@ pub(crate) fn draw(pm: &mut Pixmap, n: &Native, t: &TileLayer, view: &View, flat
Some(((x * k) as f32, (y * k) as f32))
};
let opacity = t.opacity.clamp(0.0, 1.0);
let quality = sampling(t);
let (mut pending, mut error) = (false, None);
for p in pictures {
// A WMTS tile past the service's coverage is routine; a WMS picture (any area asked) isn't.
let state = if matches!(n.how, How::Tiles(_)) { cache::get_tile(&p.url, Want::Image) } else { cache::get(&p.url, Want::Image) };
match state {
State::Ready(payload) => {
if let Payload::Image(img) = &*payload {
paint(pm, img, p.area, p.area, opacity, &place);
paint(pm, img, p.area, p.area, opacity, quality, &place);
}
}
State::Pending => {
Expand All @@ -209,7 +210,7 @@ pub(crate) fn draw(pm: &mut Pixmap, n: &Native, t: &TileLayer, view: &View, flat
if let Some((payload, at)) = stand_in
&& let Payload::Image(img) = &*payload
{
paint(pm, img, at, p.area, opacity, &place);
paint(pm, img, at, p.area, opacity, quality, &place);
}
}
// A WMTS tile the service doesn't have (past its coverage) is left clear, as the warped
Expand Down Expand Up @@ -292,9 +293,19 @@ pub(crate) fn paint(
area: [f64; 4],
clip: [f64; 4],
opacity: f32,
quality: FilterQuality,
place: &dyn Fn(Coord) -> Option<(f32, f32)>,
) {
paint_blended(pm, img, area, clip, opacity, tiny_skia::BlendMode::SourceOver, place);
paint_blended(pm, img, area, clip, opacity, tiny_skia::BlendMode::SourceOver, quality, place);
}

/// How a tile layer's pictures are sampled where they're drawn at another size: blended, or
/// each pixel a block (#2804).
pub(crate) fn sampling(t: &rustgis_map::TileLayer) -> FilterQuality {
match t.resampling {
rustgis_map::raster::Resampling::Nearest => FilterQuality::Nearest,
rustgis_map::raster::Resampling::Bilinear => FilterQuality::Bilinear,
}
}

/// [`paint`], combined with what is beneath by `blend`.
Expand All @@ -305,6 +316,7 @@ pub(crate) fn paint_blended(
clip: [f64; 4],
opacity: f32,
blend: tiny_skia::BlendMode,
quality: FilterQuality,
place: &dyn Fn(Coord) -> Option<(f32, f32)>,
) {
let corner = |x: f64, y: f64| place(Coord::new(x, y));
Expand All @@ -322,7 +334,7 @@ pub(crate) fn paint_blended(
}
path.close();
let Some(path) = path.finish() else { return };
let shader = Pattern::new(img.as_ref(), SpreadMode::Pad, FilterQuality::Bilinear, opacity, transform);
let shader = Pattern::new(img.as_ref(), SpreadMode::Pad, quality, opacity, transform);
// Without anti-aliasing, neighbouring pictures meet without a seam.
let paint = Paint { shader, anti_alias: false, blend_mode: blend, ..Paint::default() };
pm.fill_path(&path, &paint, FillRule::Winding, Transform::identity(), None);
Expand Down
Loading
Loading