From af7e03fc012a523e467c77e0d2e7825c5b017ce3 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Fri, 27 Nov 2026 00:59:24 -0300 Subject: [PATCH 1/3] feat(data): layer.addUrl reads only the rows of a box from a GRIB record (#3055, part 1) `"bytes"` with `"bbox"` downloads the record's first 4,096 octets, then one range for the rows of the box, and adds the cells the box touches, placed and named as in the whole record. Read by rows: one field with simple packing (GRIB1, or GRIB2 template 5.0), no bitmap, rows stored one after another. Any other record is downloaded whole and cut to the same box, with a notice naming why. Command line only for now: the app and a plugin's command refuse it by name until the off-frame download and its claim are done. Co-Authored-By: Claude Fable 5.2 --- crates/data/src/raster/grib.rs | 52 +++-- crates/data/src/raster/grib/rows.rs | 291 +++++++++++++++++++++++++++ crates/data/src/raster/grib_tests.rs | 136 +++++++++++++ crates/engine/src/cmd/layer.rs | 97 ++++++++- crates/engine/src/tests.rs | 85 ++++++++ docs/user-guide/data-formats.md | 2 +- 6 files changed, 645 insertions(+), 18 deletions(-) create mode 100644 crates/data/src/raster/grib/rows.rs diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index c53b665744..e575a08240 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -20,6 +20,9 @@ //! out). mod complex; +mod rows; + +pub use rows::{HEAD, Plan, Rows, cut, plan}; use super::{Crs, Exact, GeoTransform, Raster, Uncounted, max_samples}; use crate::{DataError, Result}; @@ -880,6 +883,20 @@ fn field_values( /// ([`field_values`]); with fewer bits there than that, an error. fn unpack( data: &[u8], + packed: (usize, u32), + scale: (f64, i64, i64), + mask: Option<&[u8]>, + at: (usize, &Grid), + uncounted: Uncounted, +) -> std::result::Result<(Vec, u64, u64), Skip> { + unpack_from(data, 0, packed, scale, mask, at, uncounted) +} + +/// [`unpack`], the first value starting `skip` bits into `data` (a run of rows cut from a data +/// section starts inside an octet when a row isn't a whole number of them). +fn unpack_from( + data: &[u8], + skip: u32, (count, bits): (usize, u32), (r, e, d): (f64, i64, i64), mask: Option<&[u8]>, @@ -889,13 +906,13 @@ fn unpack( if bits > MAX_BITS { return Err(Skip::Other(format!("values of {bits} bits"))); } - let need = (count as u64).saturating_mul(u64::from(bits)).div_ceil(8); + let need = (count as u64).saturating_mul(u64::from(bits)).saturating_add(u64::from(skip)).div_ceil(8); if (data.len() as u64) < need { return Err(Skip::Damaged("a data section shorter than its values".to_string())); } reference(r)?; let scale = scaling(r, e, d); - let mut bit = 0u64; + let mut bit = u64::from(skip); field_values(at, mask, count, uncounted, || { let x = self::bits(data, bit, bits) as f64; bit += u64::from(bits); @@ -1031,19 +1048,7 @@ fn grib1(b: &[u8], room: usize, first: Option, uncounted: Uncounted) -> st return Err(Skip::Other(format!("predefined grids (grid {})", pds[6]))); } let d = signed(pds, 26, 2); - let century = i64::from(pds[24]); - let year = (century - 1) * 100 + i64::from(pds[12]); - let name = format!( - "{}:kpds5={}:kpds6={}:kpds7={}:TR={}:P1={}:P2={}:TimeU={}", - date(year, u32::from(pds[13]), u32::from(pds[14]), u32::from(pds[15])), - pds[8], - pds[9], - be(pds, 10, 2), - pds[20], - pds[18], - pds[19], - pds[17], - ); + let name = grib1_name(pds); let gds_at = 8 + pds.len(); let gds = section1(b, gds_at)?; let grid = grib1_grid(gds)?; @@ -1091,6 +1096,23 @@ fn grib1(b: &[u8], room: usize, first: Option, uncounted: Uncounted) -> st Ok(Field { name, grid, values, rounded, past }) } +/// A GRIB1 field's band name, from its product definition section (of 28 octets or more). +fn grib1_name(pds: &[u8]) -> String { + let octet = |o: usize| pds.get(o).copied().unwrap_or(0); + let year = (i64::from(octet(24)) - 1) * 100 + i64::from(octet(12)); + format!( + "{}:kpds5={}:kpds6={}:kpds7={}:TR={}:P1={}:P2={}:TimeU={}", + date(year, u32::from(octet(13)), u32::from(octet(14)), u32::from(octet(15))), + octet(8), + octet(9), + be(pds, 10, 2), + octet(20), + octet(18), + octet(19), + octet(17), + ) +} + /// A GRIB1 grid description section: a regular latitude/longitude grid only. fn grib1_grid(g: &[u8]) -> std::result::Result { if g.len() < 28 { diff --git a/crates/data/src/raster/grib/rows.rs b/crates/data/src/raster/grib/rows.rs new file mode 100644 index 0000000000..0aaf5e0dbc --- /dev/null +++ b/crates/data/src/raster/grib/rows.rs @@ -0,0 +1,291 @@ +//! The rows of a box of one GRIB record, read from its headers and one run of its data section +//! (opengeos/RustGIS#3055): with simple packing and no bitmap, value `k` starts at bit +//! `k × bits` of the data section, so each row of the grid is one run of octets. +//! +//! Read by rows: a single field on a regular latitude/longitude grid, GRIB1 grid point data with +//! simple packing or GRIB2 template 5.0, its rows stored one after another (alternating rows +//! too), without a bitmap. Any other record gives [`Plan::Whole`] with the reason, for the caller +//! to read it whole ([`super::read_bytes`]) and [`cut`] it to the same box, and to say so. +//! +//! Not looked at when rows are read: the record's last four octets ("7777"), which reading them +//! would take another request. + +use super::{ + Field, Grid, MAX_BITS, Packing, SCAN_ALTERNATE, SCAN_J_CONSECUTIVE, Skip, bad, be, date, grib1_grid, grib1_name, grib2_grid, + grib2_packing, grib2_product, ibm, signed, to_raster, unpack_from, +}; +use crate::Result; +use crate::raster::{GeoTransform, Raster, Uncounted, max_samples}; + +/// The octets of a record read first, for [`plan`]: its sections before the values. +pub const HEAD: u64 = 4096; + +/// What reading a box's rows from a record needs. +pub enum Plan { + /// One run of the record's octets holds the rows. + Rows(Box), + /// The record can't be read by rows, and why (a phrase that starts a notice). + Whole(String), +} + +/// The rows of a box in a record: the octets to fetch, and how to read them. +pub struct Rows { + /// The first and last octets of the record that hold the rows (counted from the record's + /// first, both included). + pub run: (u64, u64), + /// The rows read, and the rows of the record's grid. + pub rows: (usize, usize), + /// The rows' own grid: the record's, of fewer rows. + grid: Grid, + /// The record's grid. + full: Grid, + /// The first of the rows, counted north up in the record's grid. + row0: usize, + /// The bits of the run's first octet before the first value. + skip: u32, + bits: u32, + scale: (f64, i64, i64), + name: String, + bbox: [f64; 4], +} + +/// What the headers of a record that can be read by rows say. +struct Found { + name: String, + grid: Grid, + bits: u32, + scale: (f64, i64, i64), + /// Where the packed values start in the record, and the octets its data section gives them. + data: (u64, u64), +} + +const LONG: &str = "headers longer than the 4,096 octets read first can't be read row by row"; +const BITMAP: &str = "a record with a bitmap isn't read row by row yet"; +const NOT_ONE: &str = "a range that isn't one whole message of one field can't be read row by row"; + +fn why(s: Skip) -> String { + match s { + Skip::Other(w) | Skip::Damaged(w) => format!("{w} can't be read row by row"), + Skip::TooLarge | Skip::OtherGrid => "this record can't be read row by row".to_string(), + } +} + +/// How to read the rows of `bbox` (`[west, south, east, north]` in degrees) from a record of +/// `len` octets whose first ones (up to [`HEAD`]) are `head`. An error for a box outside the +/// grid's latitudes, or rows of more values than memory allows. +pub fn plan(head: &[u8], len: u64, bbox: [f64; 4]) -> Result { + let found = match head.get(7) { + Some(1) if u64::from(be(head, 4, 3)) == len => grib1_head(head, len), + Some(2) if head.get(8..16).is_some_and(|l| l.iter().fold(0u64, |v, &b| (v << 8) | u64::from(b)) == len) => grib2_head(head, len), + _ => Err(NOT_ONE.to_string()), + }; + let Found { name, grid, bits, scale, data } = match found { + Ok(f) => f, + Err(why) => return Ok(Plan::Whole(why)), + }; + let whole = |why: &str| Ok(Plan::Whole(why.to_string())); + if grid.scan & SCAN_J_CONSECUTIVE != 0 { + return whole("columns stored one after another (j-consecutive scanning) can't be read row by row"); + } + if bits == 0 { + return whole("a constant field has no rows to read"); + } + let per_row = grid.ni as u64 * u64::from(bits); + if bits > MAX_BITS || data.1 < per_row.saturating_mul(grid.nj as u64).div_ceil(8) { + return whole("a data section that doesn't hold its grid's values can't be read row by row"); + } + let top = grid.north() + grid.dy / 2.0; + let Some((r0, r1)) = span(-top, grid.dy, grid.nj, -bbox[3], -bbox[1]) else { + return Err(bad(format!( + "the box's latitudes ({}° to {}°) are outside the record's grid ({}° to {}°)", + bbox[1], + bbox[3], + top - grid.nj as f64 * grid.dy, + top + ))); + }; + // The rows in the order the record stores them; alternating rows start on an even one, so each + // keeps the direction it is stored in. + let (mut j0, j1) = if grid.goes_north() { (grid.nj - 1 - r1, grid.nj - 1 - r0) } else { (r0, r1) }; + if grid.scan & SCAN_ALTERNATE != 0 { + j0 -= j0 % 2; + } + let n = j1 - j0 + 1; + if n.saturating_mul(grid.ni) > max_samples() { + return Err(bad(format!("the box's {n} rows of {} values are more than memory allows: give a smaller box", grid.ni))); + } + let (from, to) = (j0 as u64 * per_row, (j1 as u64 + 1) * per_row); + Ok(Plan::Rows(Box::new(Rows { + run: (data.0 + from / 8, data.0 + to.div_ceil(8) - 1), + rows: (n, grid.nj), + grid: Grid { nj: n, ..grid }, + full: grid, + row0: if grid.goes_north() { grid.nj - 1 - j1 } else { j0 }, + skip: (from % 8) as u32, + bits, + scale, + name, + bbox, + }))) +} + +/// A GRIB1 record's headers, when it can be read by rows; else why not. +fn grib1_head(b: &[u8], len: u64) -> std::result::Result { + let section = |at: usize| b.get(at..at + (be(b, at, 3) as usize).max(3)).ok_or(LONG); + let pds = section(8)?; + let flags = pds.get(7).copied().unwrap_or(0); + if pds.len() < 28 || flags & 0x80 == 0 { + return Err("a record without its own grid can't be read row by row".into()); + } + if flags & 0x40 != 0 { + return Err(BITMAP.into()); + } + let gds = section(8 + pds.len())?; + let grid = grib1_grid(gds).map_err(why)?; + let at = 8 + pds.len() + gds.len(); + let bds = b.get(at..at + 11).ok_or(LONG)?; + if bds[3] & 0xc0 != 0 { + return Err("spherical harmonics and second-order packing can't be read row by row".into()); + } + let size = u64::from(be(bds, 0, 3)); + if at as u64 + size + 4 != len { + return Err(NOT_ONE.into()); + } + Ok(Found { + name: grib1_name(pds), + grid, + bits: u32::from(bds[10]), + scale: (ibm(be(bds, 6, 4)), signed(bds, 4, 2), signed(pds, 26, 2)), + data: (at as u64 + 11, size.saturating_sub(11)), + }) +} + +/// A GRIB2 record's headers, when it can be read by rows; else why not. Each of sections 1 and +/// 3 to 6 once, as the whole reader asks of a field. +fn grib2_head(b: &[u8], len: u64) -> std::result::Result { + const DAMAGED: &str = "a record with damaged sections can't be read row by row"; + let (mut reference, mut grid, mut product, mut packing, mut bitmap) = (None, None::, None, None, None); + let (mut at, mut template) = (16usize, 0); + loop { + let start = b.get(at..at + 5).ok_or(LONG)?; + let size = be(start, 0, 4) as usize; + if start[4] == 7 { + let (Some(reference), Some(grid), Some(product), Some(packing), Some(255)) = (reference, grid, product, packing, bitmap) else { + return Err(if bitmap.is_some_and(|b| b != 255) { BITMAP } else { DAMAGED }.into()); + }; + let (count, r, e, d, Packing::Simple(bits)) = packing else { + return Err(format!("complex packing (template 5.{template}) can't be read row by row")); + }; + if at as u64 + size as u64 + 4 != len || size < 5 { + return Err(NOT_ONE.into()); + } + if grid.ni.checked_mul(grid.nj) != Some(count) { + return Err(DAMAGED.into()); + } + let name = format!("{reference}:discipline={}:{product}", b.get(6).copied().unwrap_or(255)); + return Ok(Found { name, grid, bits, scale: (r, e, d), data: (at as u64 + 5, size as u64 - 5) }); + } + let s = b.get(at..at.saturating_add(size)).filter(|_| size >= 5).ok_or(if size < 5 { DAMAGED } else { LONG })?; + let again = match start[4] { + 1 => reference.replace(date(i64::from(be(s, 12, 2)), be(s, 14, 1), be(s, 15, 1), be(s, 16, 1))).is_some(), + 3 => grid.replace(grib2_grid(s).map_err(why)?).is_some(), + 4 => product.replace(grib2_product(s)).is_some(), + 5 => { + template = be(s, 9, 2); + packing.replace(grib2_packing(s).map_err(why)?).is_some() + } + 6 => bitmap.replace(s.get(5).copied().unwrap_or(0)).is_some(), + _ => false, + }; + if again { + return Err(NOT_ONE.into()); + } + at += size; + } +} + +impl Rows { + /// The rows' raster, cut to the box's columns, from the octets of [`Rows::run`]: laid out as + /// the whole record is (north up, a whole turn from −180°), with its band name and notices. + pub fn read(&self, run: &[u8], name: &str) -> Result { + let points = self.grid.ni * self.grid.nj; + let at = (points, &self.grid); + let (values, rounded, past) = + unpack_from(run, self.skip, (points, self.bits), self.scale, None, at, Uncounted::new(None, None)).map_err(|s| bad(why(s)))?; + let mut r = to_raster(vec![Field { name: self.name.clone(), grid: self.grid, values, rounded, past }], name)?; + r.lost.extend(self.full.notes()); + cut_rows(r, self.full.north() + self.full.dy / 2.0, (self.row0, self.full.nj), self.bbox) + } +} + +/// A record read whole, cut to the cells a box touches (`[west, south, east, north]` in degrees): +/// what [`Rows::read`] gives of it. An error for a box outside it. +pub fn cut(r: Raster, bbox: [f64; 4]) -> Result { + let (top, rows) = (r.transform.origin_y, r.height as usize); + cut_rows(r, top, (0, rows), bbox) +} + +/// [`cut`] of `r`, rows `row0..` of a grid of `of` rows whose north edge is at `top`. +fn cut_rows(r: Raster, top: f64, (row0, of): (usize, usize), bbox: [f64; 4]) -> Result { + let (t, w, h) = (r.transform, r.width as usize, r.height as usize); + let dy = -t.pixel_height; + let columns = span(t.origin_x, t.pixel_width, w, bbox[0], bbox[2]); + let rows = span(-top, dy, of, -bbox[3], -bbox[1]).filter(|(a, b)| *a >= row0 && *b < row0 + h); + let (Some((c0, c1)), Some((r0, r1))) = (columns, rows) else { + return Err(bad(format!( + "the box ({}, {}, {}, {}) is outside the record's grid ({}, {}, {}, {})", + bbox[0], + bbox[1], + bbox[2], + bbox[3], + t.origin_x, + top - of as f64 * dy, + t.origin_x + w as f64 * t.pixel_width, + top + ))); + }; + let mut bands = Vec::with_capacity(r.bands.len()); + for b in &r.bands { + let mut band = crate::raster::grid::(c1 - c0 + 1, r1 - r0 + 1)?; + for row in r0 - row0..=r1 - row0 { + band.extend_from_slice(b.data.get(row * w + c0..=row * w + c1).unwrap_or_default()); + } + bands.push(band); + } + let size = |n: usize| u32::try_from(n).map_err(|_| bad("the grid is too large")); + let transform = GeoTransform { origin_x: t.origin_x + c0 as f64 * t.pixel_width, origin_y: top - r0 as f64 * dy, ..t }; + let mut out = Raster::new( + r.name.clone(), + size(c1 - c0 + 1)?, + size(r1 - r0 + 1)?, + bands, + transform, + r.crs, + r.nodata, + Default::default(), + "Float32", + )?; + for (b, from) in out.bands.iter_mut().zip(&r.bands) { + b.name.clone_from(&from.name); + } + // Counted over more cells than are kept: a mark, not a count. + if r.rounded.iter().any(|n| *n > 0) { + out.rounded_some = r.rounded.iter().map(|n| *n > 0).collect(); + } + out.lost = r.lost; + // A box that reaches more than a cell past the grid (a global grid's edges fall within one of + // the world's): the layer is smaller than the box, and says so. + let (east, south) = (t.origin_x + w as f64 * t.pixel_width, top - of as f64 * dy); + if bbox[0] < t.origin_x - t.pixel_width || bbox[2] > east + t.pixel_width || bbox[1] < south - dy || bbox[3] > top + dy { + out.lost.push("the box reaches past the record's grid: the layer ends where the grid does".to_string()); + } + Ok(out) +} + +/// The cells `a..=b`, of `n` cells of `step` from `origin`, that the interval from `lo` to `hi` +/// reaches into; `None` when it reaches into none. +fn span(origin: f64, step: f64, n: usize, lo: f64, hi: f64) -> Option<(usize, usize)> { + let a = ((lo - origin) / step).floor().max(0.0); + let b = (((hi - origin) / step).ceil() - 1.0).min(n as f64 - 1.0); + (a <= b).then_some((a as usize, b as usize)) +} diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index bf3f24f40c..f3d61104f6 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -1539,3 +1539,139 @@ fn hostile_complex_packing_never_panics() { } } } + +/// The rows of `bbox` of `file` (one record) as [`plan`] and [`Rows::read`] give them from its +/// first octets and one run of the others, checked against the whole record read and [`cut`]: +/// the raster, and the octets of the run. +fn by_rows(file: &[u8], bbox: [f64; 4]) -> (Raster, usize) { + let head = &file[..file.len().min(HEAD as usize)]; + let Plan::Rows(rows) = plan(head, file.len() as u64, bbox).unwrap() else { panic!("read whole") }; + let run = &file[rows.run.0 as usize..=rows.run.1 as usize]; + let got = rows.read(run, "t").unwrap(); + let want = cut(read_bytes(file, "t").unwrap(), bbox).unwrap(); + assert_eq!((got.width, got.height, got.transform), (want.width, want.height, want.transform)); + assert_eq!((&got.bands[0].data, &got.bands[0].name), (&want.bands[0].data, &want.bands[0].name)); + assert_eq!(got.lost.texts().collect::>(), want.lost.texts().collect::>()); + (got, run.len()) +} + +/// Why `file` isn't read by rows. +fn read_whole(file: &[u8]) -> String { + match plan(&file[..file.len().min(HEAD as usize)], file.len() as u64, [10.6, 56.7, 12.4, 59.3]).unwrap() { + Plan::Whole(why) => why, + Plan::Rows(_) => panic!("read by rows"), + } +} + +#[test] +fn the_rows_of_a_box_are_the_whole_record_cut_to_it() { + // Rows of 5 values: at 12 bits a row is 60 bits, so the second starts inside an octet. + for bits in [8, 12, 16] { + let x: Vec = (0..30).map(|k| (k * 37 + 5) % (1 << bits)).collect(); + // GRIB1, north to south from 60° N, 10° E: rows 1 to 3 and columns 1 and 2 of 6 × 5. + let mut g = G1::new(5, 6, x.clone()); + g.bits = bits; + let (r, run) = by_rows(&g.bytes(), [10.6, 56.7, 12.4, 59.3]); + assert_eq!((r.width, r.height, run), (2, 3, (3 * 5 * bits as usize).div_ceil(8)), "{bits} bits"); + assert_eq!(r.bands[0].data, [6, 7, 11, 12, 16, 17].map(|k| x[k] as f32), "{bits} bits"); + let t = r.transform; + assert_eq!((t.origin_x, t.origin_y), (10.5, 59.5)); + assert!(!r.lost.iter().any(|l| l.contains("reaches past")), "{:?}", r.lost); + // Alternating rows start on an even one: one more row is read, and cut. + g.scan = 0x10; + assert_eq!(by_rows(&g.bytes(), [10.6, 56.7, 12.4, 59.3]).1, (4 * 5 * bits as usize).div_ceil(8), "{bits} bits"); + // GRIB2, south to north from 10° S, 300° E in cells of 0.5°. + let mut f = F2::new(5, 6, x.clone()); + f.bits = bits; + let (r, _) = by_rows(&grib2_message(&[f]), [-59.6, -9.3, -58.9, -8.4]); + assert_eq!((r.width, r.height), (2, 3), "{bits} bits"); + let mut f = F2::new(5, 6, x); + (f.bits, f.scan) = (bits, 0x50); + by_rows(&grib2_message(&[f]), [-59.6, -9.3, -58.9, -8.4]); + } + // The first row, the last row and every row. + let g = G1::new(5, 6, (0..30).collect()); + for (bbox, rows) in [([10.6, 60.1, 12.0, 70.0], 1), ([10.6, 50.0, 12.0, 54.9], 1), ([0.0, 0.0, 20.0, 80.0], 6)] { + let r = by_rows(&g.bytes(), bbox).0; + assert_eq!(r.height, rows, "{bbox:?}"); + // Smaller than the box, and said. + assert!(r.lost.says("the box reaches past the record's grid: the layer ends where the grid does"), "{:?}", r.lost); + } + // A grid round the globe from 0°, laid out from −180° as the whole record is, with BAM's + // latitudes: its notices are the whole record's. + let mut g = G1::new(6, 3, (1..=18).collect()); + (g.lat1, g.lat2, g.lon1, g.lon2, g.di, g.dj) = (-60_000, 60_000, 0, 300_000, 60_000, 60_000); + let (r, _) = by_rows(&g.bytes(), [-100.0, -20.0, 100.0, 20.0]); + assert_eq!((r.width, r.height, r.transform.origin_x), (5, 1, -150.0)); + assert_eq!(r.bands[0].data, vec![11.0, 12.0, 7.0, 8.0, 9.0]); + assert!(r.lost.says("its earth is a sphere of radius 6,367,470 m (GRIB1's); latitudes and longitudes are read as WGS 84's")); +} + +#[test] +fn a_box_outside_the_record_is_refused_by_name() { + let file = G1::new(5, 6, (0..30).collect()).bytes(); + let e = plan(&file, file.len() as u64, [10.6, 70.0, 12.0, 80.0]).err().unwrap().to_string(); + assert!(e.contains("the box's latitudes (70° to 80°) are outside the record's grid (54.5° to 60.5°)"), "{e}"); + // Its longitudes: known once the rows are laid out. + let Plan::Rows(rows) = plan(&file, file.len() as u64, [100.0, 56.0, 110.0, 58.0]).unwrap() else { panic!("read whole") }; + let e = rows.read(&file[rows.run.0 as usize..=rows.run.1 as usize], "t").err().unwrap().to_string(); + assert!(e.contains("the box (100, 56, 110, 58) is outside the record's grid (9.5, 54.5, 14.5, 60.5)"), "{e}"); + assert!(cut(read_bytes(&file, "t").unwrap(), [100.0, 56.0, 110.0, 58.0]).is_err()); + // Fewer octets than the rows take. + assert!(rows.read(&file[rows.run.0 as usize..rows.run.1 as usize], "t").is_err()); +} + +#[test] +fn records_that_cant_be_read_by_rows_say_why() { + let x: Vec = (0..30).collect(); + let mut masked = G1::new(5, 6, x[..29].to_vec()); + masked.keep = Some((0..30).map(|k| k != 7).collect()); + assert_eq!(read_whole(&masked.bytes()), "a record with a bitmap isn't read row by row yet"); + // Read whole and cut, the masked point (row 1, column 2) has no value. + let r = cut(read_bytes(&masked.bytes(), "t").unwrap(), [10.6, 56.7, 12.4, 59.3]).unwrap(); + assert!(r.bands[0].data[1].is_nan() && r.bands[0].data[0] == 6.0, "{:?}", r.bands[0].data); + let mut masked = F2::new(5, 6, x[..29].to_vec()); + masked.keep = Some((0..30).map(|k| k != 7).collect()); + assert_eq!(read_whole(&grib2_message(&[masked])), "a record with a bitmap isn't read row by row yet"); + let complex = Cx::differenced(&[(0, 3, &[7, 0, 5, 7, 3]), (511, 0, &[0]), (0, 3, &[1])], &[100, 90], -4).message(); + assert_eq!(read_whole(&complex), "complex packing (template 5.3) can't be read row by row"); + let mut columns = G1::new(5, 6, x.clone()); + columns.scan = 0x20; + assert!(read_whole(&columns.bytes()).starts_with("columns stored one after another")); + let mut constant = G1::new(5, 6, vec![]); + constant.bits = 0; + assert_eq!(read_whole(&constant.bytes()), "a constant field has no rows to read"); + let mut second_order = G1::new(5, 6, x.clone()); + second_order.bds_flags = 0x40; + assert!(read_whole(&second_order.bytes()).starts_with("spherical harmonics and second-order packing")); + // Two messages in the range, and two fields in a message. + let mut two = G1::new(5, 6, x.clone()).bytes(); + two.extend(G1::new(5, 6, x.clone()).bytes()); + assert!(read_whole(&two).starts_with("a range that isn't one whole message of one field")); + let two = grib2_message(&[F2::new(5, 6, x.clone()), F2::new(5, 6, x)]); + assert!(read_whole(&two).starts_with("a range that isn't one whole message of one field")); +} + +#[test] +fn hostile_headers_never_panic_by_rows() { + for file in [G1::new(5, 6, (0..30).collect()).bytes(), grib2_message(&[F2::new(5, 6, (0..30).collect())])] { + for bbox in [[10.6, 56.7, 12.4, 59.3], [-59.6, -9.3, -58.9, -8.4], [-180.0, -90.0, 180.0, 90.0]] { + for n in 0..file.len() { + let _ = plan(&file[..n], file.len() as u64, bbox); + } + for i in 0..file.len() { + for x in [0x00, 0x01, 0x20, 0x7f, 0x80, 0xff] { + let mut bad = file.clone(); + bad[i] = x; + if let Ok(Plan::Rows(rows)) = plan(&bad, bad.len() as u64, bbox) { + let _ = rows.read(&[], "t"); + let run = usize::try_from(rows.run.0).ok().zip(usize::try_from(rows.run.1).ok()); + if let Some(run) = run.and_then(|(a, b)| bad.get(a..=b)) { + let _ = rows.read(run, "t"); + } + } + } + } + } + } +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index c21b95c18a..1bcb9ef2d6 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -51,7 +51,7 @@ pub fn commands() -> Vec { .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", "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)", "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: (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 (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: (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:" (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)}"#), @@ -5336,6 +5336,11 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { let scan = super::raster::as_scan(p)?; // A byte range of a GRIB file (`"bytes"`, #2428): only that range is downloaded, and read as // the file. The browser refuses it ([`byte_range`]). + // With a box (`"bbox"`, #3055), only the record's headers and the rows of the box. + #[cfg(not(target_arch = "wasm32"))] + if ["bytes", "bbox"].iter().all(|k| p.get(*k).is_some_and(|v| !v.is_null())) { + return add_url_rows(s, p, url, public); + } #[cfg(not(target_arch = "wasm32"))] if let Some(range) = byte_range(p, url)? { return add_url_range(s, p, url, range, public); @@ -5525,6 +5530,15 @@ pub const MAX_RANGE: u64 = 64 << 20; /// way. `None` without `"bytes"`. The browser refuses it: a range from another site needs that /// site's leave (CORS), which comes in a later part. pub fn byte_range(p: &Value, url: &str) -> Result, String> { + range_asked(p, url, false) +} + +/// What `"bbox"` with `"bytes"` says where the rows of a box aren't read yet: the app, whose +/// downloads run off the frame, and a plugin's command there. +const ROWS_ELSEWHERE: &str = "\"bbox\" with \"bytes\" (the rows of a box of a GRIB record) is read on the command line for now, not in the app yet: leave \"bbox\" out to read the whole record"; + +/// [`byte_range`], `rows` being whether a box may come with the range ([`add_url_rows`]). +fn range_asked(p: &Value, url: &str, rows: bool) -> Result, String> { let grib = match p.get("format") { None | Some(Value::Null) => false, Some(Value::String(f)) if f.trim().eq_ignore_ascii_case("grib") => true, @@ -5558,7 +5572,10 @@ pub fn byte_range(p: &Value, url: &str) -> Result, String> { } } let other = ["bbox", "cellSize", "as", "service", "coverage", "cube", "cog", "whole", "dates"]; - if let Some(k) = other.iter().find(|k| p.get(**k).is_some_and(|v| !v.is_null() && v.as_bool() != Some(false))) { + if let Some(k) = other.iter().skip(usize::from(rows)).find(|k| p.get(**k).is_some_and(|v| !v.is_null() && v.as_bool() != Some(false))) { + if *k == "bbox" { + return Err(ROWS_ELSEWHERE.into()); + } return Err(format!("\"bytes\" doesn't go with \"{k}\": a range is downloaded and read as a GRIB file")); } if rustgis_data::time::is_template(url) { @@ -5639,6 +5656,82 @@ fn add_url_range(s: &mut Session, p: &Value, url: &str, range: (u64, u64), publi super::raster::add_named_bytes(s, p, name, bytes, b(p, "zoom")).map_err(named) } +/// Adds the rows of a box of a GRIB record (`"bytes"` with `"bbox"`, #3055), on the command line: +/// the record's first octets ([`grib::HEAD`]), then one range for the rows of the box, cut to its +/// columns. A record that can't be read by rows ([`grib::Plan::Whole`]) is downloaded whole and +/// cut to the same box, and a notice says why. The layer keeps the box's cells as a GeoTIFF, as a +/// window of a cloud-optimised one does. Each request waits at most +/// [`cache::BLOCKING_TIMEOUT`], without a look at Cancel, as [`add_url_range`]'s one does. +/// +/// [`grib::HEAD`]: rustgis_data::raster::grib::HEAD +/// [`grib::Plan::Whole`]: rustgis_data::raster::grib::Plan::Whole +/// [`cache::BLOCKING_TIMEOUT`]: crate::render::rustgis_tiles::cache::BLOCKING_TIMEOUT +#[cfg(not(target_arch = "wasm32"))] +fn add_url_rows(s: &mut Session, p: &Value, url: &str, public: bool) -> CmdResult { + use crate::render::rustgis_tiles::cache; + use rustgis_data::raster::grib; + let Some(range) = range_asked(p, url, true)? else { return Err("\"bbox\" with \"bytes\" needs the range".into()) }; + let side = |i: usize| p.get("bbox").and_then(|b| b.get(i)).and_then(Value::as_f64); + if side(0).zip(side(2)).is_some_and(|(west, east)| west > east) { + return Err("\"bbox\": a box across the antimeridian (west greater than east) isn't read from a GRIB record yet: give one box on each side of it".into()); + } + let bbox = window_box(s, p, None)?; + if s.leave_downloads { + return Err(ROWS_ELSEWHERE.into()); + } + let named = |e: String| crate::sources::message_with_address(url, &e); + let public = public || cache::ceiling_for(url) == crate::render::rustgis_tiles::address::Reach::Public; + let fetch = |first: u64, last: u64| -> Result, String> { + let ranged = ranged_address(url, (first, last)); + let len = usize::try_from(last - first + 1).unwrap_or(usize::MAX); + let bytes = if public { + cache::download_public_within(&ranged, len, cache::BLOCKING_TIMEOUT) + } else { + cache::download_blocking_within(&ranged, len, cache::BLOCKING_TIMEOUT) + }; + let bytes = bytes.map_err(|e| range_failed(&ranged, e)).map_err(named)?; + if bytes.len() != len { + return Err(named(format!("the server answered {} octets of the {len} asked for (octets {first} to {last})", bytes.len()))); + } + Ok(bytes) + }; + let len = range.1 - range.0 + 1; + let head_end = range.0 + len.min(grib::HEAD) - 1; + let head = fetch(range.0, head_end)?; + check_range_answer(&ranged_address(url, (range.0, head_end)), &head).map_err(named)?; + let file = url_file_name(&ranged_address(url, range), &head).map_err(named)?; + let stem = Path::new(&file).file_stem().and_then(|n| n.to_str()).unwrap_or("raster"); + let octets = |n: u64| if n >= 1_000_000 { format!("{:.1} MB", n as f64 / 1e6) } else { format!("{} kB", n.div_ceil(1000)) }; + let data = |e: rustgis_data::DataError| named(e.to_string()); + let (r, note) = match grib::plan(&head, len, bbox).map_err(data)? { + grib::Plan::Rows(rows) => { + // A record no longer than its first read is all here already. + let here = usize::try_from(rows.run.0).ok().zip(usize::try_from(rows.run.1).ok()).and_then(|(a, b)| head.get(a..=b)); + let (run, read) = match here { + Some(run) => (run.to_vec(), head.len()), + None => { + let run = fetch(range.0 + rows.run.0, range.0 + rows.run.1)?; + let read = head.len() + run.len(); + (run, read) + } + }; + let r = rows.read(&run, stem).map_err(data)?; + (r, format!("read {} of {} rows ({} of {})", rows.rows.0, rows.rows.1, octets(read as u64), octets(len))) + } + grib::Plan::Whole(why) => { + let whole = if head.len() as u64 == len { head } else { fetch(range.0, range.1)? }; + let r = grib::read_bytes(&whole, stem).and_then(|r| grib::cut(r, bbox)).map_err(data)?; + (r, format!("{why}: the whole record was downloaded ({}) and cut to the box", octets(len))) + } + }; + let bytes = rustgis_data::raster::geotiff::write_all(&r).map_err(data)?; + let title = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or(stem).to_string(); + let layer = rustgis_map::RasterLayer::from_written(r, format!("{stem}.tif"), bytes); + let added = super::raster::add_raster_after(s, &title, layer, b(p, "zoom")).map_err(named)?; + s.notify(format!("{title}: {note}"), false); + Ok(added) +} + /// Whether a Shapefile's part other than its `.dbf` can be done without: it isn't there (404 or /// 410, or 403, which S3 answers for a missing object to those who can't list the bucket). A 403 /// to an address read with keys ([`keyed`]) fails instead, as they may not cover the part. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7f04e0c3c7..f4bdb2d43f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -53203,6 +53203,91 @@ fn a_plugin_commands_grib_range_is_added_when_the_app_completes_it() { assert_eq!(layer.raster.as_ref().unwrap().data.as_ref().unwrap().bands[0].data, vec![3.0, 4.0]); } +/// A GRIB1 message of a 60 × 40 grid of 1° cells from 60° N, 10° E, north to south: value `k` is +/// `k`, 16 bits each (4,884 octets, more than the 4,096 read first). +#[cfg(not(target_arch = "wasm32"))] +fn grib1_grid_message() -> Vec { + let mut m = b"GRIB\0\x13\x14\x01".to_vec(); + m.extend([0, 0, 28, 2, 7, 96, 255, 0x80, 11, 105, 0, 2, 26, 11, 18, 6, 0, 1, 0, 0, 0, 0, 0, 0, 21, 0, 0, 0]); + // Grid description: 60 × 40, 60° N 10° E to 21° N 69° E, 1°. + m.extend([0, 0, 32, 0, 255, 0, 0, 60, 0, 40, 0, 0xea, 0x60, 0, 0x27, 0x10, 0x80, 0, 0x52, 0x08, 0x01, 0x0d, 0x88]); + m.extend([0x03, 0xe8, 0x03, 0xe8, 0, 0, 0, 0, 0]); + // Binary data: 11 octets, 2,400 values and one octet of padding (4,812). + m.extend([0, 0x12, 0xcc, 8, 0, 0, 0, 0, 0, 0, 16]); + m.extend((0..2400u16).flat_map(u16::to_be_bytes)); + m.push(0); + m.extend(b"7777"); + assert_eq!(m.len(), 4884); + m +} + +/// `layer.addUrl` with `"bytes"` and `"bbox"` (#3055) asks for the record's first 4,096 octets, +/// then for the rows of the box only, and adds the cells the box touches, saying how much it +/// read. A record that can't be read by rows is downloaded whole and cut to the box, and said; +/// where rows aren't read yet (a plugin's command in the app, the app's own check) it is refused. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn the_rows_of_a_box_of_a_grib_record_are_asked_for_alone() { + let mut file = grib1_message(1, 2); + file.extend(grib1_grid_message()); + let (base, sent) = serve_ranges(file.clone()); + let count = || sent.load(std::sync::atomic::Ordering::Relaxed); + let mut s = Session::new(Project::default()); + let url = format!("{base}/run/PREC.grb"); + let cells = |s: &Session, r: &Value| { + let raster = s.map().layer(r["layer"].as_u64().unwrap() as u32).unwrap().raster.as_ref().unwrap().data.clone().unwrap(); + (raster.width, raster.height, raster.transform.origin_x, raster.transform.origin_y, raster.bands[0].data.clone()) + }; + // Rows 35 to 37 of 40, columns 1 and 2: the record's first 4,096 octets and three rows of 120. + let mark = s.notice_mark(); + let r = s.run("layer.addUrl", &json!({"url": url, "bytes": [88, 4971], "bbox": [10.6, 22.7, 12.4, 25.3], "name": "Rain"})).unwrap(); + assert_eq!(cells(&s, &r), (2, 3, 10.5, 25.5, vec![2101.0, 2102.0, 2161.0, 2162.0, 2221.0, 2222.0])); + assert_eq!(count(), 4096 + 360); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.contains(&"Rain: read 3 of 40 rows (5 kB of 5 kB)".to_string()), "{said:?}"); + assert!(!said.iter().any(|n| n.contains("whole record")), "{said:?}"); + // Rows the first read holds already, and a record no longer than it, are asked for once. + let r = s.run("layer.addUrl", &json!({"url": url, "bytes": [88, 4971], "bbox": [10.6, 56.7, 12.4, 59.3]})).unwrap(); + assert_eq!(cells(&s, &r).4, vec![61.0, 62.0, 121.0, 122.0, 181.0, 182.0]); + let r = s.run("layer.addUrl", &json!({"url": url, "bytes": [0, 87], "bbox": [9.6, 59.6, 10.4, 60.4]})).unwrap(); + assert_eq!(cells(&s, &r).4, vec![1.0]); + assert_eq!(count(), 4096 + 360 + 4096 + 88); + // Two messages in the range: downloaded whole after the first read, cut to the box, and said. + let mark = s.notice_mark(); + let r = s.run("layer.addUrl", &json!({"url": url, "bytes": [0, 4971], "bbox": [9.6, 59.6, 10.4, 60.4], "name": "Two"})).unwrap(); + assert_eq!(cells(&s, &r).4, vec![1.0]); + assert_eq!(count(), 4096 + 360 + 4096 + 88 + 4096 + 4972); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + let whole = "Two: a range that isn't one whole message of one field can't be read row by row: the whole record was downloaded (5 kB) and cut to the box"; + assert!(said.contains(&whole.to_string()), "{said:?}"); + // Refused before anything is fetched. + let before = count(); + for (bbox, more, said) in [ + (json!([170, 0, -170, 10]), json!(null), "a box across the antimeridian"), + (json!([10, 20, 5, 30]), json!(null), "a box across the antimeridian"), + (json!("here"), json!(null), "bbox is [west, south, east, north]"), + (json!([10.6, 56.7, 12.4, 59.3]), json!(1000), "doesn't go with \"cellSize\""), + ] { + let e = s.run("layer.addUrl", &json!({"url": url, "bytes": [88, 4971], "bbox": bbox, "cellSize": more})).unwrap_err(); + assert!(e.contains(said), "{bbox}: {e}"); + } + assert_eq!(count(), before); + // A box outside the record, known from its headers. + let e = s.run("layer.addUrl", &json!({"url": url, "bytes": [88, 4971], "bbox": [10, 70, 12, 80]})).unwrap_err(); + assert!(e.contains("the box's latitudes (70° to 80°) are outside the record's grid (20.5° to 60.5°)"), "{e}"); + assert_eq!(count(), before + 4096); + // The app's check of a range, and a plugin's command it runs: not read by rows yet, and said. + let asked = json!({"url": url, "bytes": [88, 4971], "bbox": [10.6, 56.7, 12.4, 59.3]}); + let e = crate::cmd::layer::byte_range(&asked, &url).unwrap_err(); + assert!(e.contains("is read on the command line for now, not in the app yet"), "{e}"); + let mut s = world(); + plugin("eng-grib-rows", &["edit", "network"]); + fetch_mode(true, true); + let e = s.run_leaving_downloads("plugin:eng-grib-rows/f", &json!({"op": "layer.addUrl", "params": asked})).unwrap_err(); + assert!(e.contains("is read on the command line for now, not in the app yet"), "{e}"); + assert!(s.take_url_requests().is_empty()); +} + /// Each page of a map series is georeferenced with its own view, not the first page's (#1191). #[test] fn a_map_series_pdf_georeferences_each_page_with_its_view() { diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 74e45c0a7a..6ee7c3a29f 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -697,7 +697,7 @@ databases](data.md#sql-queries-and-duckdb-databases). | Scans with no coordinates | an untagged `.tif` or `.png`, or a PDF page without coordinates; any `.tif`, `.png`, `.jpg`/`.jpeg` or `.pdf` with `"as": "scan"` | Add Data, or upload (`layer.addData`, `layer.addDataBytes`) | Grey or RGB(A), 8- or 16-bit pixels. An untagged TIFF or PNG opens as a scan by default; a JPEG needs `"as": "scan"` (otherwise it is a photo). `"as": "scan"` also discards a GeoTIFF's coordinates. A world file beside a TIFF, PNG or JPEG (`.tfw`, `.jgw`, `.pgw`, the four-letter `.tifw`, `.jpgw`, `.pngw`, or `.wld`), with a `.prj` beside it for the coordinate system, places it instead (a JPEG too, which is then not a photo): a turned or skewed one is resampled north up; without a `.prj`, with one RustGIS can't use, or with a world file that can't be read or places the picture nowhere it can be drawn (UTM meters with a longitude/latitude `.prj`), it stays a scan and a notice says why. `"as": "scan"` passes the world file over. World files are read for files added by their path (an upload doesn't bring the files beside it). A project reopens a picture as it was added: one that opened as a scan stays one (add it again once its `.prj` is there), and one a world file placed still opens if its `.prj` or world file is gone, at a stand-in place, with a notice saying it has no coordinates now. A world file is compared with a GeoTIFF's own tags only when both are north up (a turned GeoTIFF is resampled as it is read). A GeoTIFF keeps its own tags, and a notice says when a world file places it differently. The scan initially covers the current view and is marked not georeferenced (`georeferenced: false`) until **Georeference** places it. Export and tools needing ground coordinates refuse it until then. PNG/JPEG decoding is bounded and may reduce the image; large TIFFs can be read at reduced resolution. | | ASCII grid | `.asc` (with an optional `.prj` on desktop) | Add Data, or upload | A single numeric band with square `CELLSIZE` or separate `DX` and `DY` pixel sizes. Desktop files use the neighbouring `.prj`; uploaded and downloaded grids have no sidecar and must have coordinates that fit WGS 84 longitude/latitude. A grid with no `.prj` is read as WGS 84, and a notice says so. | | Zarr | a store's folder (`.zarr`, desktop) or web address (desktop and browser), format 2 (consolidated) or 3 | Home › Add › Add Data › Zarr… (`layer.addZarr`), Add Data on a local folder, or a `?zarr=` link | A variable's latitude/longitude (or y/x) map at the steps picked of its other dimensions (time, level), read chunk by chunk in pure Rust (blosc, zlib, gzip, zstd, LZ4; sharded arrays too). See [Zarr stores](data.md#zarr-stores). | -| GRIB | `.grb`, `.grib`, `.grb2`, `.grib2` | Add Data, or upload | Weather and climate model output, editions 1 and 2, read in pure Rust: each field on the grid of the first one read is a band, named from its message (`d=2026111800:kpds5=61:…` in GRIB1, as wgrib's inventories write it; discipline, category, number and surface in GRIB2). Simple packing, and GRIB2's complex packing with or without spatial differencing (as NCEP's GFS and CPTEC's MERGE use), on regular latitude/longitude grids, with bitmaps (points masked, or that complex packing marks missing, have no value), in any scanning order, laid out north up and, round the whole globe, from −180° (a last column that repeats the first, 360° on, is left out with a notice). Values are in the file's units (kelvin stays kelvin). Other packings (GRIB1's second-order, JPEG 2000, PNG, CCSDS) and grids are left out with a notice naming them; fields on another grid are left out with a count. A sphere's or another earth's latitudes and longitudes are read as WGS 84's, and a notice says so. One record of a large remote file is added by its octets, as its wgrib inventory gives them: `layer.addUrl` with `"bytes": [first, last]` (desktop and command line; at most 64 MB; `"format": "grib"` for an address whose name doesn't say GRIB) asks the server for that range only, and refuses a server that answers the whole file or fewer octets. | +| GRIB | `.grb`, `.grib`, `.grb2`, `.grib2` | Add Data, or upload | Weather and climate model output, editions 1 and 2, read in pure Rust: each field on the grid of the first one read is a band, named from its message (`d=2026111800:kpds5=61:…` in GRIB1, as wgrib's inventories write it; discipline, category, number and surface in GRIB2). Simple packing, and GRIB2's complex packing with or without spatial differencing (as NCEP's GFS and CPTEC's MERGE use), on regular latitude/longitude grids, with bitmaps (points masked, or that complex packing marks missing, have no value), in any scanning order, laid out north up and, round the whole globe, from −180° (a last column that repeats the first, 360° on, is left out with a notice). Values are in the file's units (kelvin stays kelvin). Other packings (GRIB1's second-order, JPEG 2000, PNG, CCSDS) and grids are left out with a notice naming them; fields on another grid are left out with a count. A sphere's or another earth's latitudes and longitudes are read as WGS 84's, and a notice says so. One record of a large remote file is added by its octets, as its wgrib inventory gives them: `layer.addUrl` with `"bytes": [first, last]` (desktop and command line; at most 64 MB; `"format": "grib"` for an address whose name doesn't say GRIB) asks the server for that range only, and refuses a server that answers the whole file or fewer octets. With `"bbox": [west, south, east, north]` (degrees, or `"view"`) beside `"bytes"`, on the command line, only the record's first 4,096 octets and the rows of the box are downloaded: the layer holds the cells the box touches, placed and named as in the whole record, and is kept in the project as a GeoTIFF; a notice says how many rows and octets were read. Rows are read alone from a record of one field with simple packing, no bitmap and rows stored one after another (alternating rows too). Any other record (a bitmap, complex packing, columns stored one after another, a constant field, headers longer than 4,096 octets, several messages or fields in the range) is downloaded whole and cut to the same box, and a notice says why. A box that reaches past the record's grid gives a layer that ends where the grid does, and a notice says so; a box outside the record is refused, and so is one across the antimeridian (west greater than east): give one box on each side. The record's closing `7777` isn't looked at when rows are read alone. In the app, `"bbox"` with `"bytes"` is refused for now. | | SRTM height tile | `.hgt` | Add Data, or upload (desktop and browser) | One 1° tile of 16-bit heights in meters, 1201 × 1201 (3 arc-seconds), 3601 × 3601 (1 arc-second) or 7201 × 7201 (0.5 arc-second), read natively; a tile larger than the memory budget (a 0.5 arc-second tile in the browser) is read at every second sample or fewer, each kept sample still at its cell's center. The file name places it (`N37W122.hgt` is the tile whose south-west corner is 37°N, 122°W; an upload keeps its name), so a file whose name isn't a tile's, or whose size is neither grid's, is refused. Samples sit on the whole-degree lines, so each is a cell centered on its point and the layer reaches half a cell past the tile's edges. WGS 84; voids (−32768) are no data, and a notice counts them. Heights are above the EGM96 geoid (mean sea level), not the ellipsoid, and a notice says so once as the layer is added. SRTM and DTED files hold one band and give their own coordinates (read as WGS 84; a DTED file naming another datum says so), so a `"crs"` or `"layer"` given for one (or kept by a project saved when these files went through GDAL) is ignored, and a notice says so. | | DTED | `.dt0`, `.dt1`, `.dt2` | Add Data, or upload (desktop and browser) | DTED levels 0, 1 and 2, read natively per MIL-PRF-89020B: the UHL header gives the south-west post, the spacing (wider in longitude at high latitudes) and the counts. Posts are cells centered on them, as for SRTM. Voids (−32767) are no data and counted in a notice. In a two's-complement file, a void stored as 0x8001 reads as −1 m and no notice counts it; a height of −1 m stored as 0xFFFF reads as no data. A column whose record lacks its 0xAA sentinel is read as no data, and a notice counts those columns; a whole cell whose longitude counts number its columns from 1 rather than 0 is read by place, and a notice counts those columns; a file with any other longitude count that doesn't match its place (leading columns left out, counts offset, or a stray count), or a record whose latitude count isn't 0, is refused, naming the record, since its heights would land in the wrong place; a column whose checksum doesn't match its heights (some producers write them wrongly) is read as stored, and a notice counts those too. Heights some producers write in two's complement rather than signed magnitude (those that would read below −16000 m) are read as two's complement, and counted in a notice. A complete cell cut short opens with its missing columns as no data, and says so. A partial cell is read in the full-grid layout of CD-ROM files, its missing posts as voids; one in the magnetic-tape layout is refused when its DSI counts only the lines that have heights. A tape cell with a height on every line counts the whole cell too, but its file is shorter than the full grid's, so it's refused as well; a partial cell cut short is refused the same way, since the two can't be told apart. The level is the one the DSI record names (the extension's when it names none, and a notice says when the two differ). A spacing other than the specification's for the level and latitude, a DSI record that disagrees with the UHL, or a horizontal datum other than WGS 84 is said. The vertical datum (EGM96, or mean sea level) is said once, as for SRTM. | | Rasters GDAL reads | `.img`, `.dem`, `.nc`, `.nc4`, `.hdf`, `.hdf5`, `.h5`, `.he5`, `.bil`, `.bsq`, `.bip`, `.envi`, `.grd`, `.rst`, `.sdat`, `.kea`, `.ers`, `.ntf`, `.nitf`, `.ecw`, `.sid`, `.gsb`, `.bt`, `.rsw` | Add Data (desktop, with [GDAL](https://gdal.org): `gdal_translate`, `gdalinfo` and `gdalwarp`; the installed build must include the driver) | Converted once to a cached cloud-optimised GeoTIFF. NetCDF/HDF variables are subdatasets: the first is added, the others named in a notice; `"layer"` picks one. Without a declared coordinate system, longitude/latitude-like coordinates use WGS 84 (0–360° longitudes are moved to −180–180°) and a notice says so, every time the file is read, not only when it is added; otherwise give `"crs"`. JPEG 2000 is listed separately above. | From 4d49d069ae26e963eeee28ad2a65d6cc64a44f4c Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Fri, 27 Nov 2026 08:13:54 -0300 Subject: [PATCH 2/3] fix(engine): "bbox": false with "bytes" reads the range as before; review round 1 - `"bbox": false` is no box, as `byte_range` reads it: the range is read as the file again, with a test. - The browser's refusal of `"bytes"` comes before the keys a range doesn't go with, so `"bbox"` there says what holds in the browser. - Values of more than 32 bits name their own reason for the whole download. - The guide says the box's notice starts a cell past the grid, and why. Co-Authored-By: Claude Fable 5.2 --- crates/data/src/raster/grib/rows.rs | 5 ++++- crates/data/src/raster/grib_tests.rs | 6 ++++++ crates/engine/src/cmd/layer.rs | 13 ++++++++----- crates/engine/src/tests.rs | 6 +++++- docs/user-guide/data-formats.md | 2 +- 5 files changed, 24 insertions(+), 8 deletions(-) diff --git a/crates/data/src/raster/grib/rows.rs b/crates/data/src/raster/grib/rows.rs index 0aaf5e0dbc..139cf8e4ef 100644 --- a/crates/data/src/raster/grib/rows.rs +++ b/crates/data/src/raster/grib/rows.rs @@ -90,8 +90,11 @@ pub fn plan(head: &[u8], len: u64, bbox: [f64; 4]) -> Result { if bits == 0 { return whole("a constant field has no rows to read"); } + if bits > MAX_BITS { + return Ok(Plan::Whole(format!("values of {bits} bits can't be read row by row"))); + } let per_row = grid.ni as u64 * u64::from(bits); - if bits > MAX_BITS || data.1 < per_row.saturating_mul(grid.nj as u64).div_ceil(8) { + if data.1 < per_row.saturating_mul(grid.nj as u64).div_ceil(8) { return whole("a data section that doesn't hold its grid's values can't be read row by row"); } let top = grid.north() + grid.dy / 2.0; diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index f3d61104f6..448b638248 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -1644,6 +1644,12 @@ fn records_that_cant_be_read_by_rows_say_why() { let mut second_order = G1::new(5, 6, x.clone()); second_order.bds_flags = 0x40; assert!(read_whole(&second_order.bytes()).starts_with("spherical harmonics and second-order packing")); + let mut wide = G1::new(5, 6, x.clone()); + wide.bits = 33; + assert_eq!(read_whole(&wide.bytes()), "values of 33 bits can't be read row by row"); + let mut short = G1::new(5, 6, x[..20].to_vec()); + short.bits = 16; + assert!(read_whole(&short.bytes()).starts_with("a data section that doesn't hold its grid's values")); // Two messages in the range, and two fields in a message. let mut two = G1::new(5, 6, x.clone()).bytes(); two.extend(G1::new(5, 6, x.clone()).bytes()); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 1bcb9ef2d6..83b3de6346 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -5336,9 +5336,10 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { let scan = super::raster::as_scan(p)?; // A byte range of a GRIB file (`"bytes"`, #2428): only that range is downloaded, and read as // the file. The browser refuses it ([`byte_range`]). - // With a box (`"bbox"`, #3055), only the record's headers and the rows of the box. + // With a box (`"bbox"`, #3055), only the record's headers and the rows of the box. A `false` + // is no box, as [`byte_range`] reads it. #[cfg(not(target_arch = "wasm32"))] - if ["bytes", "bbox"].iter().all(|k| p.get(*k).is_some_and(|v| !v.is_null())) { + if ["bytes", "bbox"].iter().all(|k| p.get(*k).is_some_and(|v| !v.is_null() && v.as_bool() != Some(false))) { return add_url_rows(s, p, url, public); } #[cfg(not(target_arch = "wasm32"))] @@ -5571,6 +5572,11 @@ fn range_asked(p: &Value, url: &str, rows: bool) -> Result, S return Err("\"bytes\" reads a range of a GRIB file (an address ending in .grb, .grib, .grb2 or .grib2, or \"format\": \"grib\"): a range of another format isn't a file".into()); } } + // The browser's refusal comes before the keys a range doesn't go with: what it says holds + // whatever else is asked. + if cfg!(target_arch = "wasm32") { + return Err("\"bytes\" works on the desktop and the command line for now: in the browser, a range from another site needs that site's leave (CORS)".into()); + } let other = ["bbox", "cellSize", "as", "service", "coverage", "cube", "cog", "whole", "dates"]; if let Some(k) = other.iter().skip(usize::from(rows)).find(|k| p.get(**k).is_some_and(|v| !v.is_null() && v.as_bool() != Some(false))) { if *k == "bbox" { @@ -5581,9 +5587,6 @@ fn range_asked(p: &Value, url: &str, rows: bool) -> Result, S if rustgis_data::time::is_template(url) { return Err("\"bytes\" doesn't go with a dated address: give the file's own address".into()); } - if cfg!(target_arch = "wasm32") { - return Err("\"bytes\" works on the desktop and the command line for now: in the browser, a range from another site needs that site's leave (CORS)".into()); - } Ok(Some((first, last))) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f4bdb2d43f..401b5247da 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -53252,11 +53252,15 @@ fn the_rows_of_a_box_of_a_grib_record_are_asked_for_alone() { let r = s.run("layer.addUrl", &json!({"url": url, "bytes": [0, 87], "bbox": [9.6, 59.6, 10.4, 60.4]})).unwrap(); assert_eq!(cells(&s, &r).4, vec![1.0]); assert_eq!(count(), 4096 + 360 + 4096 + 88); + // `"bbox": false` is no box: the range is read as the file, as before boxes. + let r = s.run("layer.addUrl", &json!({"url": url, "bytes": [0, 87], "bbox": false})).unwrap(); + assert_eq!(cells(&s, &r).4, vec![1.0, 2.0]); + assert_eq!(count(), 4096 + 360 + 4096 + 88 + 88); // Two messages in the range: downloaded whole after the first read, cut to the box, and said. let mark = s.notice_mark(); let r = s.run("layer.addUrl", &json!({"url": url, "bytes": [0, 4971], "bbox": [9.6, 59.6, 10.4, 60.4], "name": "Two"})).unwrap(); assert_eq!(cells(&s, &r).4, vec![1.0]); - assert_eq!(count(), 4096 + 360 + 4096 + 88 + 4096 + 4972); + assert_eq!(count(), 4096 + 360 + 4096 + 88 + 88 + 4096 + 4972); let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); let whole = "Two: a range that isn't one whole message of one field can't be read row by row: the whole record was downloaded (5 kB) and cut to the box"; assert!(said.contains(&whole.to_string()), "{said:?}"); diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 6ee7c3a29f..620fc86b7f 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -697,7 +697,7 @@ databases](data.md#sql-queries-and-duckdb-databases). | Scans with no coordinates | an untagged `.tif` or `.png`, or a PDF page without coordinates; any `.tif`, `.png`, `.jpg`/`.jpeg` or `.pdf` with `"as": "scan"` | Add Data, or upload (`layer.addData`, `layer.addDataBytes`) | Grey or RGB(A), 8- or 16-bit pixels. An untagged TIFF or PNG opens as a scan by default; a JPEG needs `"as": "scan"` (otherwise it is a photo). `"as": "scan"` also discards a GeoTIFF's coordinates. A world file beside a TIFF, PNG or JPEG (`.tfw`, `.jgw`, `.pgw`, the four-letter `.tifw`, `.jpgw`, `.pngw`, or `.wld`), with a `.prj` beside it for the coordinate system, places it instead (a JPEG too, which is then not a photo): a turned or skewed one is resampled north up; without a `.prj`, with one RustGIS can't use, or with a world file that can't be read or places the picture nowhere it can be drawn (UTM meters with a longitude/latitude `.prj`), it stays a scan and a notice says why. `"as": "scan"` passes the world file over. World files are read for files added by their path (an upload doesn't bring the files beside it). A project reopens a picture as it was added: one that opened as a scan stays one (add it again once its `.prj` is there), and one a world file placed still opens if its `.prj` or world file is gone, at a stand-in place, with a notice saying it has no coordinates now. A world file is compared with a GeoTIFF's own tags only when both are north up (a turned GeoTIFF is resampled as it is read). A GeoTIFF keeps its own tags, and a notice says when a world file places it differently. The scan initially covers the current view and is marked not georeferenced (`georeferenced: false`) until **Georeference** places it. Export and tools needing ground coordinates refuse it until then. PNG/JPEG decoding is bounded and may reduce the image; large TIFFs can be read at reduced resolution. | | ASCII grid | `.asc` (with an optional `.prj` on desktop) | Add Data, or upload | A single numeric band with square `CELLSIZE` or separate `DX` and `DY` pixel sizes. Desktop files use the neighbouring `.prj`; uploaded and downloaded grids have no sidecar and must have coordinates that fit WGS 84 longitude/latitude. A grid with no `.prj` is read as WGS 84, and a notice says so. | | Zarr | a store's folder (`.zarr`, desktop) or web address (desktop and browser), format 2 (consolidated) or 3 | Home › Add › Add Data › Zarr… (`layer.addZarr`), Add Data on a local folder, or a `?zarr=` link | A variable's latitude/longitude (or y/x) map at the steps picked of its other dimensions (time, level), read chunk by chunk in pure Rust (blosc, zlib, gzip, zstd, LZ4; sharded arrays too). See [Zarr stores](data.md#zarr-stores). | -| GRIB | `.grb`, `.grib`, `.grb2`, `.grib2` | Add Data, or upload | Weather and climate model output, editions 1 and 2, read in pure Rust: each field on the grid of the first one read is a band, named from its message (`d=2026111800:kpds5=61:…` in GRIB1, as wgrib's inventories write it; discipline, category, number and surface in GRIB2). Simple packing, and GRIB2's complex packing with or without spatial differencing (as NCEP's GFS and CPTEC's MERGE use), on regular latitude/longitude grids, with bitmaps (points masked, or that complex packing marks missing, have no value), in any scanning order, laid out north up and, round the whole globe, from −180° (a last column that repeats the first, 360° on, is left out with a notice). Values are in the file's units (kelvin stays kelvin). Other packings (GRIB1's second-order, JPEG 2000, PNG, CCSDS) and grids are left out with a notice naming them; fields on another grid are left out with a count. A sphere's or another earth's latitudes and longitudes are read as WGS 84's, and a notice says so. One record of a large remote file is added by its octets, as its wgrib inventory gives them: `layer.addUrl` with `"bytes": [first, last]` (desktop and command line; at most 64 MB; `"format": "grib"` for an address whose name doesn't say GRIB) asks the server for that range only, and refuses a server that answers the whole file or fewer octets. With `"bbox": [west, south, east, north]` (degrees, or `"view"`) beside `"bytes"`, on the command line, only the record's first 4,096 octets and the rows of the box are downloaded: the layer holds the cells the box touches, placed and named as in the whole record, and is kept in the project as a GeoTIFF; a notice says how many rows and octets were read. Rows are read alone from a record of one field with simple packing, no bitmap and rows stored one after another (alternating rows too). Any other record (a bitmap, complex packing, columns stored one after another, a constant field, headers longer than 4,096 octets, several messages or fields in the range) is downloaded whole and cut to the same box, and a notice says why. A box that reaches past the record's grid gives a layer that ends where the grid does, and a notice says so; a box outside the record is refused, and so is one across the antimeridian (west greater than east): give one box on each side. The record's closing `7777` isn't looked at when rows are read alone. In the app, `"bbox"` with `"bytes"` is refused for now. | +| GRIB | `.grb`, `.grib`, `.grb2`, `.grib2` | Add Data, or upload | Weather and climate model output, editions 1 and 2, read in pure Rust: each field on the grid of the first one read is a band, named from its message (`d=2026111800:kpds5=61:…` in GRIB1, as wgrib's inventories write it; discipline, category, number and surface in GRIB2). Simple packing, and GRIB2's complex packing with or without spatial differencing (as NCEP's GFS and CPTEC's MERGE use), on regular latitude/longitude grids, with bitmaps (points masked, or that complex packing marks missing, have no value), in any scanning order, laid out north up and, round the whole globe, from −180° (a last column that repeats the first, 360° on, is left out with a notice). Values are in the file's units (kelvin stays kelvin). Other packings (GRIB1's second-order, JPEG 2000, PNG, CCSDS) and grids are left out with a notice naming them; fields on another grid are left out with a count. A sphere's or another earth's latitudes and longitudes are read as WGS 84's, and a notice says so. One record of a large remote file is added by its octets, as its wgrib inventory gives them: `layer.addUrl` with `"bytes": [first, last]` (desktop and command line; at most 64 MB; `"format": "grib"` for an address whose name doesn't say GRIB) asks the server for that range only, and refuses a server that answers the whole file or fewer octets. With `"bbox": [west, south, east, north]` (degrees, or `"view"`) beside `"bytes"`, on the command line, only the record's first 4,096 octets and the rows of the box are downloaded: the layer holds the cells the box touches, placed and named as in the whole record, and is kept in the project as a GeoTIFF; a notice says how many rows and octets were read. Rows are read alone from a record of one field with simple packing, no bitmap and rows stored one after another (alternating rows too). Any other record (a bitmap, complex packing, columns stored one after another, a constant field, headers longer than 4,096 octets, several messages or fields in the range) is downloaded whole and cut to the same box, and a notice says why. A box that reaches past the record's grid gives a layer that ends where the grid does, and a notice says so once it reaches more than a cell past (a grid round the globe ends within a cell of the world's edges); a box outside the record is refused, and so is one across the antimeridian (west greater than east): give one box on each side. The record's closing `7777` isn't looked at when rows are read alone. In the app, `"bbox"` with `"bytes"` is refused for now. | | SRTM height tile | `.hgt` | Add Data, or upload (desktop and browser) | One 1° tile of 16-bit heights in meters, 1201 × 1201 (3 arc-seconds), 3601 × 3601 (1 arc-second) or 7201 × 7201 (0.5 arc-second), read natively; a tile larger than the memory budget (a 0.5 arc-second tile in the browser) is read at every second sample or fewer, each kept sample still at its cell's center. The file name places it (`N37W122.hgt` is the tile whose south-west corner is 37°N, 122°W; an upload keeps its name), so a file whose name isn't a tile's, or whose size is neither grid's, is refused. Samples sit on the whole-degree lines, so each is a cell centered on its point and the layer reaches half a cell past the tile's edges. WGS 84; voids (−32768) are no data, and a notice counts them. Heights are above the EGM96 geoid (mean sea level), not the ellipsoid, and a notice says so once as the layer is added. SRTM and DTED files hold one band and give their own coordinates (read as WGS 84; a DTED file naming another datum says so), so a `"crs"` or `"layer"` given for one (or kept by a project saved when these files went through GDAL) is ignored, and a notice says so. | | DTED | `.dt0`, `.dt1`, `.dt2` | Add Data, or upload (desktop and browser) | DTED levels 0, 1 and 2, read natively per MIL-PRF-89020B: the UHL header gives the south-west post, the spacing (wider in longitude at high latitudes) and the counts. Posts are cells centered on them, as for SRTM. Voids (−32767) are no data and counted in a notice. In a two's-complement file, a void stored as 0x8001 reads as −1 m and no notice counts it; a height of −1 m stored as 0xFFFF reads as no data. A column whose record lacks its 0xAA sentinel is read as no data, and a notice counts those columns; a whole cell whose longitude counts number its columns from 1 rather than 0 is read by place, and a notice counts those columns; a file with any other longitude count that doesn't match its place (leading columns left out, counts offset, or a stray count), or a record whose latitude count isn't 0, is refused, naming the record, since its heights would land in the wrong place; a column whose checksum doesn't match its heights (some producers write them wrongly) is read as stored, and a notice counts those too. Heights some producers write in two's complement rather than signed magnitude (those that would read below −16000 m) are read as two's complement, and counted in a notice. A complete cell cut short opens with its missing columns as no data, and says so. A partial cell is read in the full-grid layout of CD-ROM files, its missing posts as voids; one in the magnetic-tape layout is refused when its DSI counts only the lines that have heights. A tape cell with a height on every line counts the whole cell too, but its file is shorter than the full grid's, so it's refused as well; a partial cell cut short is refused the same way, since the two can't be told apart. The level is the one the DSI record names (the extension's when it names none, and a notice says when the two differ). A spacing other than the specification's for the level and latitude, a DSI record that disagrees with the UHL, or a horizontal datum other than WGS 84 is said. The vertical datum (EGM96, or mean sea level) is said once, as for SRTM. | | Rasters GDAL reads | `.img`, `.dem`, `.nc`, `.nc4`, `.hdf`, `.hdf5`, `.h5`, `.he5`, `.bil`, `.bsq`, `.bip`, `.envi`, `.grd`, `.rst`, `.sdat`, `.kea`, `.ers`, `.ntf`, `.nitf`, `.ecw`, `.sid`, `.gsb`, `.bt`, `.rsw` | Add Data (desktop, with [GDAL](https://gdal.org): `gdal_translate`, `gdalinfo` and `gdalwarp`; the installed build must include the driver) | Converted once to a cached cloud-optimised GeoTIFF. NetCDF/HDF variables are subdatasets: the first is added, the others named in a notice; `"layer"` picks one. Without a declared coordinate system, longitude/latitude-like coordinates use WGS 84 (0–360° longitudes are moved to −180–180°) and a notice says so, every time the file is read, not only when it is added; otherwise give `"crs"`. JPEG 2000 is listed separately above. | From 4e000b98443cccc553ecb6476f5098893d00e384 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Fri, 27 Nov 2026 17:05:33 -0300 Subject: [PATCH 3/3] fix(data): a box's rows count values past f32 in the box, and refuse keys they don't read - Values past the range of 32-bit floats were counted over every cell of the rows read: now over the box's cells when rows are read alone, and said as the whole record's (without a number) when the record is downloaded whole. - `"crs"`, `"layer"` and the other keys of other kinds of address were left out unsaid with a box: refused before any request, as a window refuses them. - The cut-short run is tested with a box inside the grid, so it reaches the check on the data's length. Co-Authored-By: Claude Fable 5.2 --- crates/data/src/raster/grib.rs | 15 +++++++---- crates/data/src/raster/grib/rows.rs | 25 +++++++++++++----- crates/data/src/raster/grib_tests.rs | 38 ++++++++++++++++++++++++++-- crates/engine/src/cmd/layer.rs | 6 +++++ crates/engine/src/tests.rs | 4 +++ docs/user-guide/data-formats.md | 2 +- 6 files changed, 76 insertions(+), 14 deletions(-) diff --git a/crates/data/src/raster/grib.rs b/crates/data/src/raster/grib.rs index e575a08240..c20dfd9999 100644 --- a/crates/data/src/raster/grib.rs +++ b/crates/data/src/raster/grib.rs @@ -778,15 +778,20 @@ fn to_raster(fields: Vec, name: &str) -> Result { r.rounded = rounded; } if past > 0 { - let (what, has) = if past == 1 { ("1 value".to_string(), "has") } else { (format!("{past} values"), "have") }; - r.lost.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedValue, - format!("{what} past the range of 32-bit floats (±3.4 × 10^38) {has} no value"), - )); + r.lost.push(past_note(past)); } Ok(r) } +/// What says values past `f32`'s range, in every notice about them. +const PAST: &str = "past the range of 32-bit floats (±3.4 × 10^38)"; + +/// The notice of `past` values past `f32`'s range, which have no value. +fn past_note(past: u64) -> crate::loss::Note { + let (what, has) = if past == 1 { ("1 value".to_string(), "has") } else { (format!("{past} values"), "have") }; + crate::loss::Note::loss(crate::loss::LossCode::DroppedValue, format!("{what} {PAST} {has} no value")) +} + /// Octets `o..o + n` (0-based offset `o`) of `b`, unsigned, big-endian; 0 past the end. fn be(b: &[u8], o: usize, n: usize) -> u32 { b.get(o..o + n).map_or(0, |s| s.iter().fold(0u32, |v, &x| (v << 8) | u32::from(x))) diff --git a/crates/data/src/raster/grib/rows.rs b/crates/data/src/raster/grib/rows.rs index 139cf8e4ef..33fc079c99 100644 --- a/crates/data/src/raster/grib/rows.rs +++ b/crates/data/src/raster/grib/rows.rs @@ -11,8 +11,8 @@ //! would take another request. use super::{ - Field, Grid, MAX_BITS, Packing, SCAN_ALTERNATE, SCAN_J_CONSECUTIVE, Skip, bad, be, date, grib1_grid, grib1_name, grib2_grid, - grib2_packing, grib2_product, ibm, signed, to_raster, unpack_from, + Field, Grid, MAX_BITS, PAST, Packing, SCAN_ALTERNATE, SCAN_J_CONSECUTIVE, Skip, bad, be, date, grib1_grid, grib1_name, grib2_grid, + grib2_packing, grib2_product, ibm, past_note, signed, to_raster, unpack_from, }; use crate::Result; use crate::raster::{GeoTransform, Raster, Uncounted, max_samples}; @@ -217,7 +217,7 @@ impl Rows { unpack_from(run, self.skip, (points, self.bits), self.scale, None, at, Uncounted::new(None, None)).map_err(|s| bad(why(s)))?; let mut r = to_raster(vec![Field { name: self.name.clone(), grid: self.grid, values, rounded, past }], name)?; r.lost.extend(self.full.notes()); - cut_rows(r, self.full.north() + self.full.dy / 2.0, (self.row0, self.full.nj), self.bbox) + cut_rows(r, self.full.north() + self.full.dy / 2.0, (self.row0, self.full.nj), self.bbox, true) } } @@ -225,11 +225,14 @@ impl Rows { /// what [`Rows::read`] gives of it. An error for a box outside it. pub fn cut(r: Raster, bbox: [f64; 4]) -> Result { let (top, rows) = (r.transform.origin_y, r.height as usize); - cut_rows(r, top, (0, rows), bbox) + cut_rows(r, top, (0, rows), bbox, false) } -/// [`cut`] of `r`, rows `row0..` of a grid of `of` rows whose north edge is at `top`. -fn cut_rows(r: Raster, top: f64, (row0, of): (usize, usize), bbox: [f64; 4]) -> Result { +/// [`cut`] of `r`, rows `row0..` of a grid of `of` rows whose north edge is at `top`. `unmasked`: +/// whether `r` is of simple packing without a bitmap ([`Rows::read`]'s), where a cell without a +/// value is one past `f32`'s range, so those are counted over the cells kept; else a count made +/// over the whole record is said as the record's, without the number. +fn cut_rows(r: Raster, top: f64, (row0, of): (usize, usize), bbox: [f64; 4], unmasked: bool) -> Result { let (t, w, h) = (r.transform, r.width as usize, r.height as usize); let dy = -t.pixel_height; let columns = span(t.origin_x, t.pixel_width, w, bbox[0], bbox[2]); @@ -276,6 +279,16 @@ fn cut_rows(r: Raster, top: f64, (row0, of): (usize, usize), bbox: [f64; 4]) -> out.rounded_some = r.rounded.iter().map(|n| *n > 0).collect(); } out.lost = r.lost; + if out.lost.iter().any(|n| n.as_str().contains(PAST)) { + out.lost.retain(|n| !n.as_str().contains(PAST)); + let past = out.bands.iter().flat_map(|b| &b.data).filter(|v| v.is_nan()).count(); + if !unmasked { + let said = format!("values {PAST} in the whole record have no value: any among the box's cells are empty"); + out.lost.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedValue, said)); + } else if past > 0 { + out.lost.push(past_note(past as u64)); + } + } // A box that reaches more than a cell past the grid (a global grid's edges fall within one of // the world's): the layer is smaller than the box, and says so. let (east, south) = (t.origin_x + w as f64 * t.pixel_width, top - of as f64 * dy); diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index 448b638248..43ae13ca00 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -1617,8 +1617,42 @@ fn a_box_outside_the_record_is_refused_by_name() { let e = rows.read(&file[rows.run.0 as usize..=rows.run.1 as usize], "t").err().unwrap().to_string(); assert!(e.contains("the box (100, 56, 110, 58) is outside the record's grid (9.5, 54.5, 14.5, 60.5)"), "{e}"); assert!(cut(read_bytes(&file, "t").unwrap(), [100.0, 56.0, 110.0, 58.0]).is_err()); - // Fewer octets than the rows take. - assert!(rows.read(&file[rows.run.0 as usize..rows.run.1 as usize], "t").is_err()); + // Fewer octets than the rows of a box inside the grid take. + let Plan::Rows(rows) = plan(&file, file.len() as u64, [10.0, 56.0, 12.0, 58.0]).unwrap() else { panic!("read whole") }; + assert!(rows.read(&file[rows.run.0 as usize..=rows.run.1 as usize], "t").is_ok()); + let e = rows.read(&file[rows.run.0 as usize..rows.run.1 as usize], "t").err().unwrap().to_string(); + assert!(e.contains("a data section shorter than its values"), "{e}"); +} + +/// Values past `f32`'s range are counted over the box's cells when its rows are read alone, not +/// over every cell of the rows read; a record read whole says they are the whole record's. +#[test] +fn values_past_f32_are_counted_in_the_box() { + const BOX: [f64; 4] = [10.6, 56.7, 12.4, 59.3]; + let past = |r: &Raster| r.lost.texts().filter(|t| t.contains("past the range of 32-bit floats")).map(String::from).collect::>(); + let rows_of = |file: &[u8]| { + let Plan::Rows(rows) = plan(file, file.len() as u64, BOX).unwrap() else { panic!("read whole") }; + rows.read(&file[rows.run.0 as usize..=rows.run.1 as usize], "t").unwrap() + }; + // E = 130: a packed 1 is past the range. Row 1, column 0: in the rows read, outside the box. + let mut x = vec![0u32; 30]; + x[5] = 1; + let mut g = G1::new(5, 6, x.clone()); + g.e = 130; + let r = rows_of(&g.bytes()); + assert!(past(&r).is_empty() && r.bands[0].data.iter().all(|v| *v == 0.0), "{:?}", r.lost); + // Read whole and cut, the count would be the record's: said as the record's, without one. + let whole = cut(read_bytes(&g.bytes(), "t").unwrap(), BOX).unwrap(); + let said = + "values past the range of 32-bit floats (±3.4 × 10^38) in the whole record have no value: any among the box's cells are empty"; + assert_eq!(past(&whole), vec![said.to_string()]); + // Row 1, column 1 too: one of the two is in the box. + x[6] = 1; + let mut g = G1::new(5, 6, x); + g.e = 130; + let r = rows_of(&g.bytes()); + assert_eq!(past(&r), vec!["1 value past the range of 32-bit floats (±3.4 × 10^38) has no value".to_string()]); + assert!(r.bands[0].data[0].is_nan()); } #[test] diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 83b3de6346..695b009ce5 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -5674,6 +5674,12 @@ fn add_url_rows(s: &mut Session, p: &Value, url: &str, public: bool) -> CmdResul use crate::render::rustgis_tiles::cache; use rustgis_data::raster::grib; let Some(range) = range_asked(p, url, true)? else { return Err("\"bbox\" with \"bytes\" needs the range".into()) }; + // The keys of other kinds of address, which a window doesn't read either ([`window_checks`]). + let unread: Vec<&str> = + WINDOW_UNREAD.iter().copied().filter(|k| p.get(*k).is_some_and(|v| !v.is_null() && v.as_bool() != Some(false))).collect(); + if !unread.is_empty() { + return Err(format!("{url}: the rows of a box (\"bbox\" with \"bytes\") don't read {}: leave it out", unread.join(", "))); + } let side = |i: usize| p.get("bbox").and_then(|b| b.get(i)).and_then(Value::as_f64); if side(0).zip(side(2)).is_some_and(|(west, east)| west > east) { return Err("\"bbox\": a box across the antimeridian (west greater than east) isn't read from a GRIB record yet: give one box on each side of it".into()); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 401b5247da..3845021cb0 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -53275,6 +53275,10 @@ fn the_rows_of_a_box_of_a_grib_record_are_asked_for_alone() { let e = s.run("layer.addUrl", &json!({"url": url, "bytes": [88, 4971], "bbox": bbox, "cellSize": more})).unwrap_err(); assert!(e.contains(said), "{bbox}: {e}"); } + // Keys the rows of a box don't read are refused, never left out unsaid. + let asked = json!({"url": url, "bytes": [88, 4971], "bbox": [10.6, 56.7, 12.4, 59.3], "crs": "EPSG:4674", "layer": "2"}); + let e = s.run("layer.addUrl", &asked).unwrap_err(); + assert!(e.contains("the rows of a box (\"bbox\" with \"bytes\") don't read layer, crs: leave it out"), "{e}"); assert_eq!(count(), before); // A box outside the record, known from its headers. let e = s.run("layer.addUrl", &json!({"url": url, "bytes": [88, 4971], "bbox": [10, 70, 12, 80]})).unwrap_err(); diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 620fc86b7f..f805590adb 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -697,7 +697,7 @@ databases](data.md#sql-queries-and-duckdb-databases). | Scans with no coordinates | an untagged `.tif` or `.png`, or a PDF page without coordinates; any `.tif`, `.png`, `.jpg`/`.jpeg` or `.pdf` with `"as": "scan"` | Add Data, or upload (`layer.addData`, `layer.addDataBytes`) | Grey or RGB(A), 8- or 16-bit pixels. An untagged TIFF or PNG opens as a scan by default; a JPEG needs `"as": "scan"` (otherwise it is a photo). `"as": "scan"` also discards a GeoTIFF's coordinates. A world file beside a TIFF, PNG or JPEG (`.tfw`, `.jgw`, `.pgw`, the four-letter `.tifw`, `.jpgw`, `.pngw`, or `.wld`), with a `.prj` beside it for the coordinate system, places it instead (a JPEG too, which is then not a photo): a turned or skewed one is resampled north up; without a `.prj`, with one RustGIS can't use, or with a world file that can't be read or places the picture nowhere it can be drawn (UTM meters with a longitude/latitude `.prj`), it stays a scan and a notice says why. `"as": "scan"` passes the world file over. World files are read for files added by their path (an upload doesn't bring the files beside it). A project reopens a picture as it was added: one that opened as a scan stays one (add it again once its `.prj` is there), and one a world file placed still opens if its `.prj` or world file is gone, at a stand-in place, with a notice saying it has no coordinates now. A world file is compared with a GeoTIFF's own tags only when both are north up (a turned GeoTIFF is resampled as it is read). A GeoTIFF keeps its own tags, and a notice says when a world file places it differently. The scan initially covers the current view and is marked not georeferenced (`georeferenced: false`) until **Georeference** places it. Export and tools needing ground coordinates refuse it until then. PNG/JPEG decoding is bounded and may reduce the image; large TIFFs can be read at reduced resolution. | | ASCII grid | `.asc` (with an optional `.prj` on desktop) | Add Data, or upload | A single numeric band with square `CELLSIZE` or separate `DX` and `DY` pixel sizes. Desktop files use the neighbouring `.prj`; uploaded and downloaded grids have no sidecar and must have coordinates that fit WGS 84 longitude/latitude. A grid with no `.prj` is read as WGS 84, and a notice says so. | | Zarr | a store's folder (`.zarr`, desktop) or web address (desktop and browser), format 2 (consolidated) or 3 | Home › Add › Add Data › Zarr… (`layer.addZarr`), Add Data on a local folder, or a `?zarr=` link | A variable's latitude/longitude (or y/x) map at the steps picked of its other dimensions (time, level), read chunk by chunk in pure Rust (blosc, zlib, gzip, zstd, LZ4; sharded arrays too). See [Zarr stores](data.md#zarr-stores). | -| GRIB | `.grb`, `.grib`, `.grb2`, `.grib2` | Add Data, or upload | Weather and climate model output, editions 1 and 2, read in pure Rust: each field on the grid of the first one read is a band, named from its message (`d=2026111800:kpds5=61:…` in GRIB1, as wgrib's inventories write it; discipline, category, number and surface in GRIB2). Simple packing, and GRIB2's complex packing with or without spatial differencing (as NCEP's GFS and CPTEC's MERGE use), on regular latitude/longitude grids, with bitmaps (points masked, or that complex packing marks missing, have no value), in any scanning order, laid out north up and, round the whole globe, from −180° (a last column that repeats the first, 360° on, is left out with a notice). Values are in the file's units (kelvin stays kelvin). Other packings (GRIB1's second-order, JPEG 2000, PNG, CCSDS) and grids are left out with a notice naming them; fields on another grid are left out with a count. A sphere's or another earth's latitudes and longitudes are read as WGS 84's, and a notice says so. One record of a large remote file is added by its octets, as its wgrib inventory gives them: `layer.addUrl` with `"bytes": [first, last]` (desktop and command line; at most 64 MB; `"format": "grib"` for an address whose name doesn't say GRIB) asks the server for that range only, and refuses a server that answers the whole file or fewer octets. With `"bbox": [west, south, east, north]` (degrees, or `"view"`) beside `"bytes"`, on the command line, only the record's first 4,096 octets and the rows of the box are downloaded: the layer holds the cells the box touches, placed and named as in the whole record, and is kept in the project as a GeoTIFF; a notice says how many rows and octets were read. Rows are read alone from a record of one field with simple packing, no bitmap and rows stored one after another (alternating rows too). Any other record (a bitmap, complex packing, columns stored one after another, a constant field, headers longer than 4,096 octets, several messages or fields in the range) is downloaded whole and cut to the same box, and a notice says why. A box that reaches past the record's grid gives a layer that ends where the grid does, and a notice says so once it reaches more than a cell past (a grid round the globe ends within a cell of the world's edges); a box outside the record is refused, and so is one across the antimeridian (west greater than east): give one box on each side. The record's closing `7777` isn't looked at when rows are read alone. In the app, `"bbox"` with `"bytes"` is refused for now. | +| GRIB | `.grb`, `.grib`, `.grb2`, `.grib2` | Add Data, or upload | Weather and climate model output, editions 1 and 2, read in pure Rust: each field on the grid of the first one read is a band, named from its message (`d=2026111800:kpds5=61:…` in GRIB1, as wgrib's inventories write it; discipline, category, number and surface in GRIB2). Simple packing, and GRIB2's complex packing with or without spatial differencing (as NCEP's GFS and CPTEC's MERGE use), on regular latitude/longitude grids, with bitmaps (points masked, or that complex packing marks missing, have no value), in any scanning order, laid out north up and, round the whole globe, from −180° (a last column that repeats the first, 360° on, is left out with a notice). Values are in the file's units (kelvin stays kelvin). Other packings (GRIB1's second-order, JPEG 2000, PNG, CCSDS) and grids are left out with a notice naming them; fields on another grid are left out with a count. A sphere's or another earth's latitudes and longitudes are read as WGS 84's, and a notice says so. One record of a large remote file is added by its octets, as its wgrib inventory gives them: `layer.addUrl` with `"bytes": [first, last]` (desktop and command line; at most 64 MB; `"format": "grib"` for an address whose name doesn't say GRIB) asks the server for that range only, and refuses a server that answers the whole file or fewer octets. With `"bbox": [west, south, east, north]` (degrees, or `"view"`) beside `"bytes"`, on the command line, only the record's first 4,096 octets and the rows of the box are downloaded: the layer holds the cells the box touches, placed and named as in the whole record, and is kept in the project as a GeoTIFF; a notice says how many rows and octets were read. Rows are read alone from a record of one field with simple packing, no bitmap and rows stored one after another (alternating rows too). Any other record (a bitmap, complex packing, columns stored one after another, a constant field, headers longer than 4,096 octets, several messages or fields in the range) is downloaded whole and cut to the same box, and a notice says why. A box that reaches past the record's grid gives a layer that ends where the grid does, and a notice says so once it reaches more than a cell past (a grid round the globe ends within a cell of the world's edges); a box outside the record is refused, and so is one across the antimeridian (west greater than east): give one box on each side. The record's closing `7777` isn't looked at when rows are read alone. Keys for other kinds of address (`"crs"`, `"layer"`, `"x"`, `"y"` and the like) are refused with a box. Values past the range of 32-bit floats are counted over the box's cells; in a record downloaded whole the notice says they are the whole record's. In the app, `"bbox"` with `"bytes"` is refused for now. | | SRTM height tile | `.hgt` | Add Data, or upload (desktop and browser) | One 1° tile of 16-bit heights in meters, 1201 × 1201 (3 arc-seconds), 3601 × 3601 (1 arc-second) or 7201 × 7201 (0.5 arc-second), read natively; a tile larger than the memory budget (a 0.5 arc-second tile in the browser) is read at every second sample or fewer, each kept sample still at its cell's center. The file name places it (`N37W122.hgt` is the tile whose south-west corner is 37°N, 122°W; an upload keeps its name), so a file whose name isn't a tile's, or whose size is neither grid's, is refused. Samples sit on the whole-degree lines, so each is a cell centered on its point and the layer reaches half a cell past the tile's edges. WGS 84; voids (−32768) are no data, and a notice counts them. Heights are above the EGM96 geoid (mean sea level), not the ellipsoid, and a notice says so once as the layer is added. SRTM and DTED files hold one band and give their own coordinates (read as WGS 84; a DTED file naming another datum says so), so a `"crs"` or `"layer"` given for one (or kept by a project saved when these files went through GDAL) is ignored, and a notice says so. | | DTED | `.dt0`, `.dt1`, `.dt2` | Add Data, or upload (desktop and browser) | DTED levels 0, 1 and 2, read natively per MIL-PRF-89020B: the UHL header gives the south-west post, the spacing (wider in longitude at high latitudes) and the counts. Posts are cells centered on them, as for SRTM. Voids (−32767) are no data and counted in a notice. In a two's-complement file, a void stored as 0x8001 reads as −1 m and no notice counts it; a height of −1 m stored as 0xFFFF reads as no data. A column whose record lacks its 0xAA sentinel is read as no data, and a notice counts those columns; a whole cell whose longitude counts number its columns from 1 rather than 0 is read by place, and a notice counts those columns; a file with any other longitude count that doesn't match its place (leading columns left out, counts offset, or a stray count), or a record whose latitude count isn't 0, is refused, naming the record, since its heights would land in the wrong place; a column whose checksum doesn't match its heights (some producers write them wrongly) is read as stored, and a notice counts those too. Heights some producers write in two's complement rather than signed magnitude (those that would read below −16000 m) are read as two's complement, and counted in a notice. A complete cell cut short opens with its missing columns as no data, and says so. A partial cell is read in the full-grid layout of CD-ROM files, its missing posts as voids; one in the magnetic-tape layout is refused when its DSI counts only the lines that have heights. A tape cell with a height on every line counts the whole cell too, but its file is shorter than the full grid's, so it's refused as well; a partial cell cut short is refused the same way, since the two can't be told apart. The level is the one the DSI record names (the extension's when it names none, and a notice says when the two differ). A spacing other than the specification's for the level and latitude, a DSI record that disagrees with the UHL, or a horizontal datum other than WGS 84 is said. The vertical datum (EGM96, or mean sea level) is said once, as for SRTM. | | Rasters GDAL reads | `.img`, `.dem`, `.nc`, `.nc4`, `.hdf`, `.hdf5`, `.h5`, `.he5`, `.bil`, `.bsq`, `.bip`, `.envi`, `.grd`, `.rst`, `.sdat`, `.kea`, `.ers`, `.ntf`, `.nitf`, `.ecw`, `.sid`, `.gsb`, `.bt`, `.rsw` | Add Data (desktop, with [GDAL](https://gdal.org): `gdal_translate`, `gdalinfo` and `gdalwarp`; the installed build must include the driver) | Converted once to a cached cloud-optimised GeoTIFF. NetCDF/HDF variables are subdatasets: the first is added, the others named in a notice; `"layer"` picks one. Without a declared coordinate system, longitude/latitude-like coordinates use WGS 84 (0–360° longitudes are moved to −180–180°) and a notice says so, every time the file is read, not only when it is added; otherwise give `"crs"`. JPEG 2000 is listed separately above. |