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
49 changes: 33 additions & 16 deletions crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ pub fn commands() -> Vec<C> {
.params(r#"{"layer"?: name|id, "crs": "EPSG:… or WKT; reinterpret native coordinates, without rewriting the source file"}"#),
C::new("layer.loadAll", "Load All Features", "Layers", load_all).roles(&[]).effects(crate::policy::Effects::NONE).when(need_streamed).params(r#"{"layer"?: name|id}"#),
C::new("layer.addUrl", "Add Data From URL", "Home › Add › Add Data", add_url).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params(
r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MB), read as the file (desktop and command line): a record found in its wgrib inventory; with bbox (desktop and command line), only the rows of the box are downloaded from a record of simple packing without a bitmap, and any other record is downloaded whole and cut to the box, with a notice", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands); with bytes, the cells of a GRIB record the box touches", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km)", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG:<code> (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#,
r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MB), read as the file (desktop and command line): a record found in its wgrib inventory; with bbox (desktop and command line), only the rows of the box are downloaded from a record of simple packing without a bitmap, and any other record is downloaded whole and cut to the box, with a notice", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands); with bytes, the cells of a GRIB record the box touches", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km); a GeoTIFF in strips, which has no overviews, takes one strip and column in as many as that size holds", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG:<code> (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#,
),
C::new("layer.addDownload", "Add Downloaded Data", "Home › Add", add_download).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved).with(crate::policy::Effect::Files))
.params(r#"{"id": a download the app finished (Home › Add › Add Data › From URL), "url": its address, "name"?: text, "layer"?: text, "zoom"?: bool, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "service"?: bool (a service's features: their axes (when they came as GeoJSON) and paging are checked, and the address is kept as the layer's source), "bounds"?: [west, south, east, north] (with service: the layer's longitude/latitude bounds from its capabilities, which its axes are checked against; without bounds they are left as they come; ignored without service), "coverage"?: bool (a WCS coverage: a GeoTIFF, else the service's error, and its request kept as the layer's source), "coverageCrs"?: "EPSG:<code>" (internal, with coverage: the system service.coverage's request asks it in (its coverageCrs), for an answer that doesn't say its own, when the address doesn't say it), "drawingInfo"?: object (internal, with service: an ArcGIS layer's drawingInfo from its description, which the layer is drawn with), "geolibreProject"?: bool (internal: downloaded project JSON), "geolibreLayer"?: {"token", "record"} (internal: reserved imported layer and its saved style), "geolibreZarr"?: bool (internal: an imported Zarr slice as GeoTIFF), "connection"?: "as layer.addUrl", "anonymous"?: bool (internal: preserves a plugin-origin download's anonymous reads), "request"?: number (internal: the download a plugin command left to the app, #1202), "window"?: {"bbox", "cellSize"?, "cog"?} (internal: what a cloud-optimised GeoTIFF's window the app read off the frame asked for, for a task to read it again, #1330)}"#),
Expand Down Expand Up @@ -6715,9 +6715,10 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic::
);
(c0, c1, r0, r1)
};
let values = |l: &Level| {
// A level's window's values, taking every `step`-th column and row.
let values = |l: &Level, step: u32| {
let (c0, c1, r0, r1) = window(l);
u64::from(c1 - c0).saturating_mul(u64::from(r1 - r0)).saturating_mul(layout.bands.max(1) as u64)
u64::from((c1 - c0).div_ceil(step)).saturating_mul(u64::from((r1 - r0).div_ceil(step))).saturating_mul(layout.bands.max(1) as u64)
};
// The full image, or the coarsest overview whose cells are no larger than the size asked. A
// size finer than the full image's cells reads the full image, and says so.
Expand All @@ -6730,6 +6731,12 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic::
if c1 <= c0 || r1 <= r0 {
return Err(named("the box is outside the file".into()));
}
// A file in strips has no overviews to read coarser cells from: a cellSize coarser than the
// level's cells takes every n-th strip and column instead, as GDAL does (#2592).
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
let step = match cell {
Some(c) if layout.strips => (c * (1.0 + 1e-9) / size_of(lv)).floor().clamp(1.0, f64::from(u32::MAX)) as u32,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
_ => 1,
};
// The sides of the box past the file's edges, which the window is cut at (snapping outwards
// onto the pixels isn't a cut).
let cut: Vec<&str> = {
Expand All @@ -6747,10 +6754,17 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic::
.collect()
};
let unit = if geographic { " m" } else { " (the file's units)" };
if values(lv) > MAX_WINDOW_VALUES {
// The finest overview the window fits in, offered, never read unasked.
let take = match layout.levels.iter().skip(level).find(|l| values(l) <= MAX_WINDOW_VALUES) {
Some(l) => format!("take \"cellSize\": {} or more, or a smaller box", size_of(l).ceil()),
if values(lv, step) > MAX_WINDOW_VALUES {
// The finest overview the window fits in, offered, never read unasked; for a file in
// strips, the finest step.
let fitting = if layout.strips {
let least = (values(lv, 1) as f64 / MAX_WINDOW_VALUES as f64).sqrt() as u32;
(least.max(step + 1)..=c1.max(r1)).find(|s| values(lv, *s) <= MAX_WINDOW_VALUES).map(|s| size_of(lv) * f64::from(s))
} else {
layout.levels.iter().skip(level).find(|l| values(l, 1) <= MAX_WINDOW_VALUES).map(size_of)
};
let take = match fitting {
Some(size) => format!("take \"cellSize\": {} or more, or a smaller box", size.ceil()),
None => "take a smaller box".into(),
};
return Err(named(format!(
Expand Down Expand Up @@ -6782,27 +6796,29 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic::
band_in_time(batch.first().copied().unwrap_or(0), count, started.elapsed(), WINDOW_WAIT).map_err(named)?;
let wait = batch_wait(batch.len(), started.elapsed());
for (values, changed, past) in
cog::read_bands_counted_blocking(&info, url, level, batch, (c0, c1), (r0, r1), wait, stop).map_err(named)?
cog::read_bands_stepped_blocking(&info, url, level, batch, (c0, c1), (r0, r1), step, wait, stop).map_err(named)?
{
bands.push(values);
rounded.push(changed);
overflowed += past;
}
}
let lt = layout.transform_of(lv);
// Each value a block of `step × step` cells, the last ones cut by the window's edge.
let (width, height) = ((c1 - c0).div_ceil(step), (r1 - r0).div_ceil(step));
let mut transform = rustgis_data::raster::GeoTransform {
origin_x: lt.origin_x + f64::from(c0) * lt.pixel_width,
origin_y: lt.origin_y + f64::from(r0) * lt.pixel_height,
..lt
pixel_width: lt.pixel_width * f64::from(step),
pixel_height: lt.pixel_height * f64::from(step),
};
if bottom_up {
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
let width = (c1 - c0) as usize;
for band in &mut bands {
let rows: Vec<f32> = band.chunks(width.max(1)).rev().flatten().copied().collect();
let rows: Vec<f32> = band.chunks((width as usize).max(1)).rev().flatten().copied().collect();
*band = rows;
}
transform.origin_y = lt.origin_y + f64::from(r1) * lt.pixel_height;
transform.pixel_height = -lt.pixel_height;
transform.origin_y = lt.origin_y + (f64::from(r0) + f64::from(height) * f64::from(step)) * lt.pixel_height;
transform.pixel_height = -transform.pixel_height;
}
let color = match &layout.palette {
Some(table) if bands.len() == 1 => rustgis_data::raster::ColorHint::Palette(table.clone()),
Expand All @@ -6813,7 +6829,7 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic::
.then(|| format!("its colour table is left out: the window has {} bands, a palette has one", bands.len()));
let name = asked.name.clone().unwrap_or_else(|| cog_name(url));
let mut r =
rustgis_data::raster::Raster::new(&name, c1 - c0, r1 - r0, bands, transform, layout.crs, layout.nodata, color, layout.data_type)
rustgis_data::raster::Raster::new(&name, width, height, bands, transform, layout.crs, layout.nodata, color, layout.data_type)
.map_err(|e| named(e.to_string()))?;
if rounded.iter().any(|n| *n > 0) {
r.rounded = rounded;
Expand All @@ -6830,9 +6846,10 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic::
if let Some(described) = &layout.described {
r.apply_pam(described, rustgis_data::raster::pam::GDAL_METADATA);
}
let size = size_of(lv);
let size = size_of(lv) * f64::from(step);
let of = if level == 0 { "the full image".to_string() } else { format!("overview {level} of {}", layout.levels.len() - 1) };
let read = format!("a {} × {} window of {of}, cells of {size:.1}{unit}, read by range from its address", r.width, r.height);
let every = if step > 1 { format!(" (one strip and column in {step})") } else { String::new() };
let read = format!("a {} × {} window of {of}{every}, cells of {size:.1}{unit}, read by range from its address", r.width, r.height);
let finer = finer.map(|c| format!("cellSize {c} is finer than the file's finest cells ({size:.1}{unit}): the full image is read"));
let mut edges = Vec::new();
if !cut.is_empty() {
Expand Down
29 changes: 29 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53856,6 +53856,35 @@ fn a_window_of_a_geotiff_in_strips_comes_in_as_a_raster() {
assert_eq!((whole.width, whole.height), (300, 200));
}

/// A file in strips has no overviews: a cellSize coarser than its cells takes one strip and column
/// in so many (#2592), each value the middle cell of its block, the raster's cells that much
/// larger, and says so.
#[test]
fn a_cell_size_steps_over_the_strips_of_a_file_in_strips() {
// 300 × 200 cells of 0.01° (1,113.2 m) from 10° E, 46° N, a row a strip; cell (x, y) is
// 7 x − 3 y.
let (base, _) = serve_ranges(rustgis_data::raster::cog::example_strips(300, 200, 1));
let mut s = world();
let url = format!("{base}/cbers.tif");
let mark = s.notice_mark();
let r =
s.run("layer.addUrl", &json!({"url": url, "bbox": [10.505, 45.005, 11.005, 45.505], "cellSize": 4000, "name": "Coarse"})).unwrap();
let at = |k: &str, i: usize| u32::try_from(r["window"][k][i].as_u64().unwrap()).unwrap();
let (c0, c1, r0, r1) = (at("columns", 0), at("columns", 1), at("rows", 0), at("rows", 1));
let w = s.map().layer_by_name("Coarse").and_then(|l| l.raster.as_ref()?.data.clone()).unwrap();
assert_eq!((w.width, w.height), ((c1 - c0).div_ceil(3), (r1 - r0).div_ceil(3)), "one cell in 3: {r}");
assert!((w.transform.pixel_width - 0.03).abs() < 1e-9 && (w.transform.pixel_height + 0.03).abs() < 1e-9);
assert!((w.transform.origin_x - (10.0 + 0.01 * f64::from(c0))).abs() < 1e-9);
assert!((w.transform.origin_y - (46.0 - 0.01 * f64::from(r0))).abs() < 1e-9);
for (x, y) in [(0, 0), (4, 7), (w.width - 2, w.height - 2)] {
let (cx, cy) = (i64::from(c0 + 3 * x + 1), i64::from(r0 + 3 * y + 1));
assert_eq!(w.value(0, x.into(), y.into()), Some((7 * cx - 3 * cy) as f32), "value ({x}, {y})");
}
assert!((r["window"]["cellSize"].as_f64().unwrap() - 3339.6).abs() < 0.1, "{r}");
let said: Vec<String> = s.notices_since(mark).iter().map(|n| n.text.clone()).collect();
assert!(said.iter().any(|n| n.contains("17 × 17 window of the full image (one strip and column in 3)")), "{said:?}");
}

/// A window read for a raster made from it (AlphaEarth's similarity and change, #1720) says what
/// its header left out, as `layer.addUrl` says it when it adds the window; a clean file, nothing.
#[test]
Expand Down
Loading
Loading