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
56 changes: 41 additions & 15 deletions crates/data/src/raster/cog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -793,14 +793,32 @@ pub fn example(size: u32, tile: u32) -> Vec<u8> {
/// 10° E, 46° N in cells of 0.01°; cell (x, y) is `7 x − 3 y`.
#[doc(hidden)]
pub fn example_strips(width: u32, height: u32, rows: u32) -> Vec<u8> {
example_strips_in(width, height, rows, None)
}

/// [`example_strips`] in UTM zone 23 south (EPSG:32723) from easting 200,000 m, northing
/// 7,750,000 m (about 47.8° W, 20.3° S, 3° west of the zone's meridian), in cells of 30 m: its
/// rows lie at an angle to the map's, as a CBERS scene's do.
#[doc(hidden)]
pub fn example_strips_utm(width: u32, height: u32, rows: u32) -> Vec<u8> {
example_strips_in(width, height, rows, Some(32723))
}

/// [`example_strips`], in longitude/latitude, or in the UTM zone `utm` names.
fn example_strips_in(width: u32, height: u32, rows: u32, utm: Option<u16>) -> Vec<u8> {
use tiff::encoder::{Compression, DeflateLevel, TiffEncoder, colortype};
let values: Vec<i16> = (0..height).flat_map(|y| (0..width).map(move |x| (7 * x as i32 - 3 * y as i32) as i16)).collect();
let (cell, corner) = if utm.is_some() { (30.0, (200_000.0, 7_750_000.0)) } else { (0.01, (10.0, 46.0)) };
let keys = match utm {
Some(code) => vec![1u16, 1, 0, 2, 1024, 0, 1, 1, 3072, 0, 1, code],
None => vec![1u16, 1, 0, 2, 1024, 0, 1, 2, 2048, 0, 1, 4326],
};
let mut out = std::io::Cursor::new(Vec::new());
let made = TiffEncoder::new(&mut out).map(|e| e.with_compression(Compression::Deflate(DeflateLevel::Balanced))).and_then(|mut enc| {
let mut img = enc.new_image::<colortype::GrayI16>(width, height)?;
img.encoder().write_tag(Tag::ModelPixelScaleTag, &[0.01f64, 0.01, 0.0][..])?;
img.encoder().write_tag(Tag::ModelTiepointTag, &[0.0f64, 0.0, 0.0, 10.0, 46.0, 0.0][..])?;
img.encoder().write_tag(Tag::GeoKeyDirectoryTag, &[1u16, 1, 0, 2, 1024, 0, 1, 2, 2048, 0, 1, 4326][..])?;
img.encoder().write_tag(Tag::ModelPixelScaleTag, &[cell, cell, 0.0][..])?;
img.encoder().write_tag(Tag::ModelTiepointTag, &[0.0f64, 0.0, 0.0, corner.0, corner.1, 0.0][..])?;
img.encoder().write_tag(Tag::GeoKeyDirectoryTag, &keys[..])?;
img.rows_per_strip(rows)?;
img.write_data(&values)
});
Expand Down Expand Up @@ -859,6 +877,8 @@ pub struct Example {
pub rounded_down: bool,
/// Geographic without an EPSG code (no GeographicTypeGeoKey): read as WGS 84, said.
pub no_epsg: bool,
/// In strips of `tile` rows as wide as the image (#2592), no overviews.
pub strips: bool,
}

impl Default for Example {
Expand All @@ -884,6 +904,7 @@ impl Default for Example {
wavelengths: false,
rounded_down: false,
no_epsg: false,
strips: false,
}
}
}
Expand All @@ -896,7 +917,7 @@ pub fn example_with(e: &Example) -> Vec<u8> {
let planes = if e.planar { nb } else { 1 };
let per_chunk = nb / planes;
let mut sizes = vec![size];
while !e.no_overviews && *sizes.last().unwrap_or(&tile) > tile {
while !e.no_overviews && !e.strips && *sizes.last().unwrap_or(&tile) > tile {
let last = *sizes.last().unwrap_or(&tile);
sizes.push(if e.rounded_down { last / 2 } else { last.div_ceil(2) });
}
Expand All @@ -913,13 +934,16 @@ pub fn example_with(e: &Example) -> Vec<u8> {
.map(|&s| {
let k = size / s;
let n = s.div_ceil(tile);
// A strip is `tile` rows as wide as the image (the last one what is left).
let (count, cw) = if e.strips { (n, s) } else { (n * n, tile) };
let mut chunks = Vec::new();
for plane in 0..planes {
for i in 0..n * n {
let (tx, ty) = (i % n, i / n);
let mut c = Vec::with_capacity((tile * tile * per_chunk) as usize);
for p in 0..tile * tile {
let (x, y) = (tx * tile + p % tile, ty * tile + p / tile);
for i in 0..count {
let (tx, ty) = if e.strips { (0, i) } else { (i % n, i / n) };
let ch = if e.strips { tile.min(s - i * tile) } else { tile };
let mut c = Vec::with_capacity((cw * ch * per_chunk) as usize);
for p in 0..cw * ch {
let (x, y) = (tx * cw + p % cw, ty * tile + p / cw);
for b in 0..per_chunk {
let band = if e.planar { plane } else { b };
let v = if x < s && y < s { value(x * k, y * k, band) } else { 0 };
Expand Down Expand Up @@ -964,7 +988,7 @@ pub fn example_with(e: &Example) -> Vec<u8> {
};
let mut ifds: Vec<Vec<(u16, V)>> = Vec::new();
for (i, &s) in sizes.iter().enumerate() {
let n = (s.div_ceil(tile) * s.div_ceil(tile) * planes) as usize;
let n = (if e.strips { s.div_ceil(tile) } else { s.div_ceil(tile) * s.div_ceil(tile) } * planes) as usize;
let tagged_huge = e.huge || (e.huge_overviews && i > 0);
let mut t = vec![
(254u16, V::L(vec![if i == 0 { 0 } else { 1 }])),
Expand All @@ -987,11 +1011,13 @@ pub fn example_with(e: &Example) -> Vec<u8> {
(262, V::S(vec![if e.classes && !(e.stray && i == 0) { 3 } else { e.photometric }])),
(277, V::S(vec![nb as u16])),
(284, V::S(vec![if e.planar { 2 } else { 1 }])),
(322, V::L(vec![tile])),
(323, V::L(vec![tile])),
(324, V::L(vec![0; n])),
(325, V::L(images.get(i).map_or(vec![chunk_len; n], |c| c.iter().map(|c| c.len() as u32).collect()))),
];
let counts = V::L(images.get(i).map_or(vec![chunk_len; n], |c| c.iter().map(|c| c.len() as u32).collect()));
if e.strips {
t.extend([(273, V::L(vec![0; n])), (278, V::L(vec![tile])), (279, counts)]);
} else {
t.extend([(322, V::L(vec![tile])), (323, V::L(vec![tile])), (324, V::L(vec![0; n])), (325, counts)]);
}
// The samples past the colour ones (three of an RGB image, else one): the first alpha
// when asked, the others undefined.
let colours = if e.photometric == 2 { 3 } else { 1 };
Expand Down Expand Up @@ -1065,7 +1091,7 @@ pub fn example_with(e: &Example) -> Vec<u8> {
out.extend_from_slice(&header_len.to_le_bytes());
for (lvl, t) in ifds.iter_mut().enumerate() {
for (tag, v) in t.iter_mut() {
if *tag == 324
if (*tag == 324 || *tag == 273)
&& let V::L(offs) = v
{
for (j, o) in offs.iter_mut().enumerate() {
Expand Down
7 changes: 6 additions & 1 deletion crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5508,7 +5508,12 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult {
// and anything that doesn't answer as one is downloaded whole, as before.
let unnamed = !tiff && is_unnamed_url(url);
if (tiff || unnamed) && !scan && !super::b(p, "whole").unwrap_or(false) {
let cog = match crate::render::rustgis_tiles::cog::probe_blocking(url) {
// A data cube's file is asked for as one: a GeoTIFF in strips is drawn in place then
// (#2592), where a single one is downloaded whole.
let (_, mut look) = crate::render::rustgis_tiles::cog::split(url);
look.cube |= super::b(p, "cube") == Some(true);
let asked = crate::render::rustgis_tiles::cog::with_look(url, &look);
let cog = match crate::render::rustgis_tiles::cog::probe_blocking(&asked) {
Ok(cog) => cog,
Err(_) if unnamed => false,
Err(e) => return Err(named(e)),
Expand Down
21 changes: 20 additions & 1 deletion crates/engine/src/cmd/stac.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1000,6 +1000,15 @@ pub fn stac_cube(s: &mut Session, p: &Value) -> Result<StacCube, String> {
} else {
(level, 1)
};
// The cells read, said when they aren't the size asked (the overview nearest it, or a whole
// number of a file in strips' cells): the cube is that much finer or coarser.
if let Some(size) = size {
let got = lt.pixel_width.abs();
if (got - size).abs() > size * 1e-6 {
let show = |v: f64| format!("{v:.9}").trim_end_matches('0').trim_end_matches('.').to_string();
s.notify(format!("cellSize {} is read as {}: the files' cells nearest it", show(size), show(got)), false);
}
}
let read_tile_rows = layout.levels.get(read).map_or(1, |l| l.tile_height).div_ceil(factor).max(1);
// The area, in the files' coordinates: the box's edges, each at 32 points, as a curved grid
// (MODIS's sinusoidal) bends them. A point the system refuses (one it can't bring back,
Expand Down Expand Up @@ -1772,7 +1781,17 @@ fn add_cube(s: &mut Session, p: &Value) -> CmdResult {
m.layers.retain(|l| layers_before.contains(&l.id));
};
for (tile, by_day) in &tiles {
let urls: Vec<(f64, String)> = by_day.iter().map(|(d, u)| (*d as f64 * 86_400_000.0, format!("{u}{look}"))).collect();
// Each date's file keeps the cube's look, and says it is a data cube's: the map draws
// it in place in strips too (#2592), at every date the slider shows.
let urls: Vec<(f64, String)> = by_day
.iter()
.map(|(d, u)| {
let file = format!("{u}{look}");
let mut cube = crate::render::rustgis_tiles::cog::split(&file).1;
cube.cube = true;
(*d as f64 * 86_400_000.0, crate::render::rustgis_tiles::cog::with_look(&file, &cube))
})
.collect();
let Some((_, first)) = urls.first() else { continue };
let name = if many { format!("{base} {tile}") } else { base.clone() };
let r = match super::layer::add_url(s, &json!({"url": first, "name": name, "cube": true, "connection": p.get("connection")})) {
Expand Down
65 changes: 35 additions & 30 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34002,7 +34002,12 @@ fn a_static_collection_by_date_as_a_data_cube() {
assert!(!said.iter().any(|t| t.contains("left out, as their codes")), "codes read whole leave nothing out: {said:?}");
let tile = &s.map().tiles[0];
assert_eq!(tile.time_urls.len(), 2);
assert!(tile.time_urls[0].1.ends_with("/2024-01.tiff#range=0,100"), "the range through je:rasters' slope: {}", tile.time_urls[0].1);
// The range through je:rasters' slope, and a data cube's file (drawn in place in strips too).
assert!(
tile.time_urls[0].1.ends_with("/2024-01.tiff#range=0,100&cube=1"),
"the range through je:rasters' slope: {}",
tile.time_urls[0].1
);
// A document missing: its date is left out, and said.
let mut gap = Session::new(Project::default());
let mark = gap.notice_mark();
Expand Down Expand Up @@ -34049,6 +34054,21 @@ fn a_static_collection_by_date_as_a_data_cube() {
assert!(e.contains("1 item(s) left out, as their codes for a failed retrieval"), "{e}");
}

/// A GeoTIFF in strips too large to read in place (#2592): one strip of 1,048,576 rows, 64 MiB
/// once read, which even a data cube's file is refused for, as one that isn't cloud-optimised.
fn strips_too_large() -> Vec<u8> {
let mut file = rustgis_data::raster::cog::example_strips(16, 8, 8);
let ifd = u32::from_le_bytes(file[4..8].try_into().unwrap()) as usize;
let n = u16::from_le_bytes(file[ifd..ifd + 2].try_into().unwrap()) as usize;
for e in (0..n).map(|i| ifd + 2 + i * 12) {
// ImageLength and RowsPerStrip, both LONG.
if matches!(u16::from_le_bytes(file[e..e + 2].try_into().unwrap()), 257 | 278) {
file[e + 8..e + 12].copy_from_slice(&(1u32 << 20).to_le_bytes());
}
}
file
}

/// A STAC collection's band as a data cube on the time slider (#559), from a local API: a tile
/// layer per grid tile, each a file per date; the slider on over their dates; a fixed range in the
/// band's own units, through its scale; a tile with no date in the window drawn as nothing.
Expand Down Expand Up @@ -34122,7 +34142,7 @@ fn a_stac_data_cube_on_the_time_slider() {
// A file per date (the first item of a tile and day), the range in stored values (0.9 / 0.0001).
assert_eq!(t1.time_urls.len(), 2);
assert_eq!(t2.time_urls.len(), 1);
assert!(t1.time_urls.iter().all(|(_, u)| u.ends_with("#range=0,9000")), "{:?}", t1.time_urls);
assert!(t1.time_urls.iter().all(|(_, u)| u.ends_with("#range=0,9000&cube=1")), "{:?}", t1.time_urls);
assert!(t2.time_urls[0].1.contains("/b1.tif"));
// The slider: on, over the two dates; at the first, both tiles draw.
assert_eq!(s.run("time.info", &Value::Null).unwrap()["steps"], 2);
Expand Down Expand Up @@ -34153,22 +34173,10 @@ fn a_stac_data_cube_on_the_time_slider() {
] {
assert!(s.run("stac.addCube", &bad).is_err(), "{bad}");
}
// A file read whole (a GeoTIFF that isn't cloud-optimised) can't follow the slider: the cube
// is refused, and what it added is taken back, the view its first tile framed included.
let gt = rustgis_data::raster::GeoTransform { origin_x: 10.0, origin_y: 46.0, pixel_width: 0.5, pixel_height: -0.5 };
let plain = rustgis_data::raster::Raster::new(
"p",
2,
2,
vec![vec![1.0; 4]],
gt,
rustgis_data::raster::Crs::LonLat,
None,
rustgis_data::raster::ColorHint::Gray,
"Float32",
)
.unwrap();
let (file, _) = serve_ranges(rustgis_data::raster::geotiff::write(&plain, 0).unwrap());
// A file read whole (a GeoTIFF that can't be read in place, even as a data cube's) can't
// follow the slider: the cube is refused, and what it added is taken back, the view its first
// tile framed included.
let (file, _) = serve_ranges(strips_too_large());
let one = format!(
r#"{{"type": "Feature", "id": "p1", "collection": "cube", "bbox": [10, 45, 11, 46], "geometry": null,
"properties": {{"datetime": "2024-01-01T00:00:00Z", "bdc:tiles": ["P"]}}, "assets": {{"NDVI": {{"href": "{file}/p.tif"}}}}}}"#
Expand All @@ -34184,7 +34192,8 @@ fn a_stac_data_cube_on_the_time_slider() {
&json!({"url": format!("{plain_api}/v1"), "collection": "cube", "asset": "ndvi", "bbox": [10, 45, 11, 46], "start": "2024-01-01", "end": "2024-01-31"}),
)
.unwrap_err();
assert!(e.contains("not a cloud-optimised"), "{e}");
// Downloaded whole as such a file is, it can't be read (its strips are past the bytes).
assert!(e.contains("/p.tif"), "{e}");
assert_eq!((s.map().tiles.len(), s.map().layers.len()), (tiles, layers));
// The view tile A framed and the slider are put back too.
assert_eq!(s.map().camera, camera);
Expand Down Expand Up @@ -34252,7 +34261,7 @@ fn a_stac_data_cube_from_a_plugin_command_in_the_app() {
assert!(s.take_url_requests().is_empty(), "a cube's files are read in place, not left to the app to download");
let t1 = s.map().tiles.iter().find(|t| t.name.ends_with("T1")).unwrap();
assert_eq!(t1.time_urls.len(), 2);
assert!(t1.time_urls.iter().all(|(_, u)| u.ends_with("#range=0,9000")), "{:?}", t1.time_urls);
assert!(t1.time_urls.iter().all(|(_, u)| u.ends_with("#range=0,9000&cube=1")), "{:?}", t1.time_urls);
assert_eq!(s.map().tiles.iter().filter(|t| !t.time_urls.is_empty()).count(), 2);
assert_eq!(s.run("time.info", &Value::Null).unwrap()["steps"], 2);
s.run("time.goTo", &json!({"step": 1})).unwrap();
Expand Down Expand Up @@ -34285,14 +34294,9 @@ fn a_stac_data_cube_from_a_plugin_command_in_the_app() {
assert!(e.contains("left to the app to download") && !e.contains("not a cloud-optimised"), "{e}");
assert_eq!((s.map().tiles.len(), s.map().layers.len()), (tiles, layers));
assert!(s.take_url_requests().is_empty(), "the failed command's request is taken back with it");
// A file that isn't cloud-optimised is added all the same (its header isn't read on the
// A file that can't be read in place is added all the same (its header isn't read on the
// frame); its header's read fails, and the map drawing it says why, as for any tile layer.
let gt = rustgis_data::raster::GeoTransform { origin_x: 10.0, origin_y: 46.0, pixel_width: 0.5, pixel_height: -0.5 };
let crs = rustgis_data::raster::Crs::LonLat;
let plain =
rustgis_data::raster::Raster::new("p", 2, 2, vec![vec![1.0; 4]], gt, crs, None, rustgis_data::raster::ColorHint::Gray, "Float32")
.unwrap();
let (stripped, _) = serve_ranges(rustgis_data::raster::geotiff::write(&plain, 0).unwrap());
let (stripped, _) = serve_ranges(strips_too_large());
let one = item("p1", "P", "2024-01-01", "p1.tif").replace(&format!("{cog}/"), &format!("{stripped}/"));
let stripped_api = serve_routes(vec![("/v1/search", format!(r#"{{"type": "FeatureCollection", "features": [{one}]}}"#))], 2);
let mut flat = Session::new(Project::default());
Expand Down Expand Up @@ -34421,6 +34425,7 @@ fn an_entry_without_a_range_takes_one_from_its_files() {
assert_eq!(r["rangeFrom"], "sample");
let look = format!("#range={},{}", range[0] / 0.0001, range[1] / 0.0001);
let tile = &s.map().tiles[0];
let look = format!("{look}&cube=1");
assert!(tile.time_urls.len() == 2 && tile.time_urls.iter().all(|(_, u)| u.ends_with(&look)), "{:?} {look}", tile.time_urls);
assert_eq!(tile.attribution, "JAXA, A test dataset");
assert_eq!(
Expand All @@ -34434,7 +34439,7 @@ fn an_entry_without_a_range_takes_one_from_its_files() {
// A range given takes its place, as for any entry.
let mut t = Session::new(Project::default());
let r = crate::cmd::cube_catalog::open_entry(&mut t, &entry, &json!({"bbox": [10, 45, 11, 46], "range": [0, 0.01]})).unwrap();
assert!(r.get("rangeFrom").is_none() && t.map().tiles[0].time_urls.iter().all(|(_, u)| u.ends_with("#range=0,100")), "{r}");
assert!(r.get("rangeFrom").is_none() && t.map().tiles[0].time_urls.iter().all(|(_, u)| u.ends_with("#range=0,100&cube=1")), "{r}");
// Other text is refused, naming "auto", before anything is read.
assert!(
t.run("stac.addCube", &json!({"url": entry.url, "collection": "cube", "asset": "B1", "range": "wide"}))
Expand Down Expand Up @@ -34635,7 +34640,7 @@ fn a_catalog_entry_opens_as_its_command_would() {
.unwrap();
let urls = |s: &Session| s.map().tiles.iter().map(|t| t.time_urls.clone()).collect::<Vec<_>>();
assert_eq!(urls(&by_entry), urls(&typed), "the same files, the entry's range in stored values");
assert!(urls(&by_entry)[0].iter().all(|(_, u)| u.ends_with("#range=0,9000")));
assert!(urls(&by_entry)[0].iter().all(|(_, u)| u.ends_with("#range=0,9000&cube=1")));
// As one step: undone, the cube goes.
by_entry.run("edit.undo", &Value::Null).unwrap();
assert!(by_entry.map().tiles.is_empty());
Expand All @@ -34644,7 +34649,7 @@ fn a_catalog_entry_opens_as_its_command_would() {
crate::cmd::cube_catalog::open_entry(&mut by_entry, &entry, &json!({"bbox": [10, 45, 11, 46], "range": [0, 0.5], "name": "NDVI"}))
.unwrap();
assert_eq!(r["layers"], 1);
assert!(by_entry.map().tiles[0].time_urls.iter().all(|(_, u)| u.ends_with("#range=0,5000")));
assert!(by_entry.map().tiles[0].time_urls.iter().all(|(_, u)| u.ends_with("#range=0,5000&cube=1")));
assert_eq!(by_entry.map().tiles[0].name, "NDVI");
// Refused before anything is added: an area the entry has no data in, a period outside its
// dates, one end of the period alone.
Expand Down
Loading
Loading