From 1246b3fa4cfe43e8303084abd369cc03b2c4f637 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 13:45:30 -0600 Subject: [PATCH 1/4] feat(raster): Clip by extent reads only its part of a large tiled GeoTIFF (#2865) The GeoTIFF reader reads a part of an image: the finest level whose part fits the sample limit, decoding only the strips or tiles that hold it, its transparency mask read for the part alike (`raster::read_path_part`). A rotated or unplaced file, or one with a world file beside it, is read whole as before. Clip by extent of a layer read in place from a file reads only the part under the extent, so a small clip of a mosaic too large to hold comes out at the file's full resolution. --- crates/data/src/raster/geotiff.rs | 418 ++++++++++++++++++++----- crates/data/src/raster/mask.rs | 72 +++-- crates/data/src/raster/mod.rs | 82 ++++- crates/engine/src/cmd/gp.rs | 18 ++ crates/engine/src/cmd/imagery.rs | 21 +- crates/engine/src/cmd/workflows.rs | 34 +- crates/engine/src/tests/tiled_files.rs | 32 ++ 7 files changed, 568 insertions(+), 109 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index dfd3824e23..2c33a799b5 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -976,6 +976,46 @@ impl Seek for Unpaletted { /// Opens another reader on the same file, for decoding its chunks on more than one thread. pub(crate) type Opener<'a> = &'a (dyn Fn() -> std::io::Result> + Sync); +/// The columns and rows (half-open) of a grid read that are kept: of every `k`-th pixel of the +/// image each way, as [`decimate`] reads it, all of them for a whole image, else those of a part +/// ([`super::Part`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Span { + pub(super) cols: (u32, u32), + pub(super) rows: (u32, u32), +} + +impl Span { + /// The whole of a grid `w` × `h`. + pub(super) fn whole(w: u32, h: u32) -> Span { + Span { cols: (0, w), rows: (0, h) } + } + + pub(super) fn width(self) -> usize { + self.cols.1.saturating_sub(self.cols.0) as usize + } + + pub(super) fn height(self) -> usize { + self.rows.1.saturating_sub(self.rows.0) as usize + } + + /// Its columns and rows. + pub(super) fn size(self) -> (u32, u32) { + (self.cols.1.saturating_sub(self.cols.0), self.rows.1.saturating_sub(self.rows.0)) + } + + fn is_empty(self) -> bool { + self.width() == 0 || self.height() == 0 + } + + /// The image's pixels (half-open, every `k`-th one) within `len` of them from `at` that the + /// span's `range` (of the grid read) keeps: the first is a multiple of `k`. + pub(super) fn kept(self, range: (u32, u32), at: u64, len: u64, k: u64) -> (u64, u64) { + let start = at.max(u64::from(range.0) * k).div_ceil(k) * k; + (start, (at + len).min(u64::from(range.1) * k)) + } +} + /// How an image is cut into chunks (strips or tiles), and how they're laid out. #[derive(Clone, Copy)] struct Chunks { @@ -1024,6 +1064,7 @@ impl Chunks { (self.cw as usize).saturating_mul(self.ch as usize).saturating_mul(self.samples).saturating_mul(13) } + #[cfg(test)] fn count(&self) -> u64 { u64::from(self.per_plane) * self.planes as u64 } @@ -1054,24 +1095,62 @@ impl Chunks { (x0, y0, u64::from(self.cw).min(w.saturating_sub(x0)), u64::from(self.ch).min(h.saturating_sub(y0))) } + /// The chunk columns and rows (half-open) holding a pixel of `span` (of every `k`-th pixel + /// each way): every chunk for the whole image. + fn covering(&self, span: Span, k: u32) -> ((u64, u64), (u64, u64)) { + let k = u64::from(k.max(1)); + let reach = |(a, b): (u32, u32), size: u32, image: u32| { + // The image's pixels the span reaches, to its end: for the whole image, every chunk + // (one past its last kept pixel is still looked at, as before). + let (first, end) = (u64::from(a) * k, (u64::from(b) * k).min(u64::from(image))); + (first / u64::from(size.max(1)), end.div_ceil(u64::from(size.max(1)))) + }; + let (cols, rows) = (reach(span.cols, self.cw, self.w), reach(span.rows, self.ch, self.h)); + let down = u64::from(self.per_plane / self.across.max(1)); + ((cols.0, cols.1.min(u64::from(self.across))), (rows.0, rows.1.min(down))) + } + + /// How many chunks [`Chunks::nth`] goes through for `span`, every plane's. + fn count_in(&self, span: Span, k: u32) -> u64 { + if span.is_empty() { + return 0; + } + let ((c0, c1), (r0, r1)) = self.covering(span, k); + c1.saturating_sub(c0).saturating_mul(r1.saturating_sub(r0)).saturating_mul(self.planes as u64) + } + + /// The `p`-th chunk holding a pixel of `span` (plane by plane, then row by row), counting + /// through every plane as [`Chunks::wanted`] takes it: for the whole image, `p` itself. + fn nth(&self, p: u64, span: Span, k: u32) -> Option { + let ((c0, c1), (r0, r1)) = self.covering(span, k); + let (across, down) = (c1.checked_sub(c0).filter(|n| *n > 0)?, r1.checked_sub(r0).filter(|n| *n > 0)?); + let per_plane = across.checked_mul(down)?; + let (plane, at) = (p / per_plane, p % per_plane); + let c = (r0 + at / across).checked_mul(u64::from(self.across))?.checked_add(c0 + at % across)?; + plane.checked_mul(u64::from(self.per_plane))?.checked_add(c) + } + /// Chunk `i` (counting through every plane) as (plane, chunk index in the file), when it holds - /// a kept row and column; a chunk holding none is skipped unread. - fn wanted(&self, i: u64, k: u32) -> Option<(usize, u32)> { + /// a kept row and column of `span`; a chunk holding none is skipped unread. + fn wanted(&self, i: u64, k: u32, span: Span) -> Option<(usize, u32)> { let plane = usize::try_from(i / u64::from(self.per_plane.max(1))).ok()?; let c = u32::try_from(i % u64::from(self.per_plane.max(1))).ok()?; let (x0, y0, cols, rows) = self.span(c); let k = u64::from(k.max(1)); - if y0.div_ceil(k) * k >= y0 + rows || x0.div_ceil(k) * k >= x0 + cols { + let (xs, xe) = span.kept(span.cols, x0, cols, k); + let (ys, ye) = span.kept(span.rows, y0, rows, k); + if xs >= xe || ys >= ye { return None; } let index = u32::try_from(plane).ok()?.checked_mul(self.per_plane)?.checked_add(c)?; Some((plane, index)) } - /// Copies every `k`-th pixel each way of chunk `c` of `plane` (decoded as `values`) into - /// `bands`, each `ow` pixels wide, counting in `rounded` (by band) the pixels copied whose bit - /// is set in `changed` (from [`rounded_bits`]). Values of none of the chunk's shapes are an - /// error: a row length guessed from them would put pixels in other pixels' places. + /// Copies every `k`-th pixel each way of chunk `c` of `plane` (decoded as `values`) that + /// `span` keeps into `bands`, each the span's width, counting in `rounded` (by band) the + /// pixels copied whose bit is set in `changed` (from [`rounded_bits`]). Values of none of the + /// chunk's shapes are an error: a row length guessed from them would put pixels in other + /// pixels' places. fn place( &self, bands: &mut [Vec], @@ -1081,9 +1160,10 @@ impl Chunks { plane: usize, c: u32, k: u32, - ow: usize, + span: Span, ) -> Result<()> { let c = c % self.per_plane.max(1); + let ow = span.width(); let (x0, y0, cols, rows) = self.span(c); let k = u64::from(k.max(1)); // The chunk's row length: the data width, or the full tile width when padded. The tiff @@ -1104,10 +1184,12 @@ impl Chunks { values.len() )) })?; - let mut y = y0.div_ceil(k) * k; - while y < y0 + rows { - let mut x = x0.div_ceil(k) * k; - while x < x0 + cols { + let ((xs, xe), (ys, ye)) = (span.kept(span.cols, x0, cols, k), span.kept(span.rows, y0, rows, k)); + let (sc, sr) = (u64::from(span.cols.0), u64::from(span.rows.0)); + let mut y = ys; + while y < ye { + let mut x = xs; + while x < xe { // With `stride` one of the chunk's shapes, every position is inside `values`; the // checked arithmetic only keeps a product from being computed unchecked. let src = usize::try_from(y - y0) @@ -1115,7 +1197,7 @@ impl Chunks { .and_then(|row| row.checked_mul(stride)) .and_then(|at| at.checked_add(usize::try_from(x - x0).ok()?)) .and_then(|at| at.checked_mul(self.samples)); - let dst = (y / k) as usize * ow + (x / k) as usize; + let dst = (y / k - sr) as usize * ow + (x / k - sc) as usize; for b in 0..self.samples { let band = if self.planar { plane } else { b }; let at = src.unwrap_or(usize::MAX).saturating_add(b); @@ -1157,9 +1239,10 @@ fn limits() -> Limits { const PARALLEL_CHUNKS: u64 = 16; /// Reads an image a strip or tile at a time, keeping every `k`-th pixel each way: an overview -/// made as it is read, for a file too large to hold that has none. Returns the bands. With `k` -/// 1, the whole image a chunk at a time. With `open`, chunks are decoded on several threads, -/// each reading image `image` of its own copy of the file. +/// made as it is read, for a file too large to hold that has none. Returns the bands, of the +/// pixels `span` keeps (`None`: all of them). With `k` 1, the whole image a chunk at a time. +/// With `open`, chunks are decoded on several threads, each reading image `image` of its own +/// copy of the file. Only the chunks holding a pixel of the span are looked at. /// Progress counts chunks examined, including ones skipped by the overview. Cancel is checked /// between chunks; decoding and placing an individual chunk cannot be interrupted. fn decimate( @@ -1169,13 +1252,16 @@ fn decimate( nbands: usize, planar: bool, k: u32, + span: Option, nodata: Uncounted, open: Option<(Opener<'_>, usize, Limits)>, ) -> Result<(Vec>, &'static str, Vec)> { crate::progress::check()?; let k = k.max(1); - let (ow, oh) = (w.div_ceil(k) as usize, h.div_ceil(k) as usize); + let span = span.unwrap_or_else(|| Span::whole(w.div_ceil(k), h.div_ceil(k))); + let (ow, oh) = (span.width(), span.height()); let chunks = Chunks::new(dec, w, h, nbands, planar); + let examined = chunks.count_in(span, k); // A chunk larger than its decoder takes can't be read: said before the bands are set aside, // which can be gigabytes for a header claiming a vast image (a few hundred bytes of file, found // by fuzzing, #1952). LERC chunks go to its reader only, which holds 8 bytes a sample with a @@ -1198,32 +1284,32 @@ fn decimate( let mut bands = (0..nbands).map(|_| super::filled(ow, oh, f32::NAN)).collect::>>()?; #[cfg(not(target_arch = "wasm32"))] if let Some((open, image, limits)) = open - && chunks.count() >= PARALLEL_CHUNKS + && examined >= PARALLEL_CHUNKS { // Each thread decodes a chunk of its own. Up to the default count as before; past it (a // high setting) no more than the threads' scratch budget holds, so the peak doesn't // multiply with the setting. let affordable = 1 + crate::memory::thread_scratch() / chunks.bytes().max(1); - let chunk_count = usize::try_from(chunks.count()).unwrap_or(usize::MAX); + let chunk_count = usize::try_from(examined).unwrap_or(usize::MAX); let threads = crate::threads::max().min(affordable.max(crate::threads::default_max())).min(chunk_count); if threads > 1 { - return decimate_parallel(chunks, bands, k, (ow, oh), nodata, threads, open, image, limits); + return decimate_parallel(chunks, bands, k, span, nodata, threads, open, image, limits); } } let _ = open; - crate::progress::begin(usize::try_from(chunks.count()).unwrap_or(usize::MAX)); + crate::progress::begin(usize::try_from(examined).unwrap_or(usize::MAX)); let mut data_type = "Float32"; let mut rounded = vec![0u64; nbands]; let mut table = super::lerc::Table::default(); - for i in 0..chunks.count() { + for p in 0..examined { crate::progress::check()?; - if let Some((plane, index)) = chunks.wanted(i, k) { + if let Some((plane, index)) = chunks.nth(p, span, k).and_then(|i| chunks.wanted(i, k, span)) { let (buf, gaps) = read_chunk(dec, index, &mut table)?; let changed = rounded_bits(&buf, nodata); let (mut values, dt) = to_f32(buf, (ow, oh))?; super::lerc::blank(&mut values, gaps.as_deref()); data_type = dt; - chunks.place(&mut bands, &values, changed.as_deref(), &mut rounded, plane, index, k, ow)?; + chunks.place(&mut bands, &values, changed.as_deref(), &mut rounded, plane, index, k, span)?; } crate::progress::step(1)?; } @@ -1237,7 +1323,7 @@ fn decimate_parallel( chunks: Chunks, bands: Vec>, k: u32, - (ow, oh): (usize, usize), + span: Span, nodata: Uncounted, threads: usize, open: Opener<'_>, @@ -1246,7 +1332,9 @@ fn decimate_parallel( ) -> Result<(Vec>, &'static str, Vec)> { use std::sync::Mutex; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; - crate::progress::begin(usize::try_from(chunks.count()).unwrap_or(usize::MAX)); + let (ow, oh) = (span.width(), span.height()); + let examined = chunks.count_in(span, k); + crate::progress::begin(usize::try_from(examined).unwrap_or(usize::MAX)); crate::progress::check()?; let probe = crate::progress::current(); let next = AtomicU64::new(0); @@ -1275,11 +1363,11 @@ fn decimate_parallel( if let Err(e) = crate::progress::check() { return fail(e); } - let i = next.fetch_add(1, Ordering::Relaxed); - if i >= chunks.count() { + let p = next.fetch_add(1, Ordering::Relaxed); + if p >= examined { break; } - let Some((plane, index)) = chunks.wanted(i, k) else { + let Some((plane, index)) = chunks.nth(p, span, k).and_then(|i| chunks.wanted(i, k, span)) else { if let Err(e) = crate::progress::step(1) { return fail(e); } @@ -1297,7 +1385,7 @@ fn decimate_parallel( Ok(mut o) => { let (bands, data_type, rounded) = &mut *o; *data_type = dt; - chunks.place(bands, &values, changed.as_deref(), rounded, plane, index, k, ow) + chunks.place(bands, &values, changed.as_deref(), rounded, plane, index, k, span) } Err(_) => Err(err("a chunk couldn't be decoded")), }; @@ -1462,6 +1550,17 @@ pub(super) fn read_file_with_nodata(path: &std::path::Path, name: &str, sidecar_ read_file_with_revision(path, name, sidecar_nodata, file, revision) } +/// [`read_file_with_nodata`] of `part` of the image only, at the finest level whose part of it +/// fits [`max_samples`], decoding only the chunks that hold it (see [`read_part`]): `Ok(None)` +/// when the file can't be read by part. The raster's pixels aren't the file's whole grid, so it +/// keeps no revision of the file to pair later reads of the grid with. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn read_file_part(path: &std::path::Path, name: &str, sidecar_nodata: Option, part: super::Part) -> Result> { + let file = crate::provenance::open(path).map_err(err)?; + let revision = file.metadata().and_then(|metadata| super::file_revision::FileRevision::capture(&metadata)); + read_file_revision_part(path, name, sidecar_nodata, file, revision, Some(part)) +} + #[cfg(not(target_arch = "wasm32"))] fn load_revision_error(reason: impl std::fmt::Display) -> String { format!( @@ -1477,6 +1576,20 @@ fn read_file_with_revision( file: std::fs::File, revision: std::io::Result, ) -> Result { + read_file_revision_part(path, name, sidecar_nodata, file, revision, None)?.ok_or_else(|| err("the image couldn't be read")) +} + +/// [`read_file_with_revision`], of `part` of the image only when given (`Ok(None)` when the file +/// can't be read by part, see [`read_part`]). +#[cfg(not(target_arch = "wasm32"))] +fn read_file_revision_part( + path: &std::path::Path, + name: &str, + sidecar_nodata: Option, + file: std::fs::File, + revision: std::io::Result, + part: Option, +) -> Result> { let revision = revision.map_err(|e| e.to_string()); let open = || -> std::io::Result> { let file = crate::provenance::open(path)?; @@ -1493,7 +1606,7 @@ fn read_file_with_revision( }; let decoded = reader(std::io::BufReader::new(file)) .map_err(err) - .and_then(|r| read_limited_with_nodata(r, name, max_samples(), Some(&open), sidecar_nodata, None)); + .and_then(|r| read_image(r, name, max_samples(), Some(&open), sidecar_nodata, None, part)); // A file cut short while it is read fails to decode: the revision says whether that was a // change to wait out (Cancel is said as itself). if let Ok(original) = &revision @@ -1506,9 +1619,12 @@ fn read_file_with_revision( return Err(err(load_revision_error("The image file changed while its pixels were read"))); } } - let mut raster = decoded?; - raster.source_file = Some(revision); - Ok(raster) + let Some(mut raster) = decoded? else { return Ok(None) }; + // A part's pixels aren't the file's grid: no later read of it pairs with them. + if part.is_none() { + raster.source_file = Some(revision); + } + Ok(Some(raster)) } /// [`read`], holding at most `max` samples (the tests' small limit exercises the overviews), with @@ -1527,6 +1643,33 @@ pub(super) fn read_limited_with_nodata( sidecar_nodata: Option, asked: Option, ) -> Result { + // Only a part is ever not read. + read_image(r, name, max, open, sidecar_nodata, asked, None)?.ok_or_else(|| err("the image couldn't be read")) +} + +/// [`read_limited_with_nodata`] of `part` of the image only: the finest level (the full image, an +/// overview, or every `k`-th pixel of the full image when it has none fine enough) whose part +/// fits `max`, its part read out to whole pixels, decoding only the strips or tiles that hold it. +/// Its transparency mask is read for the part alike. `Ok(None)` when the image can't be read by +/// part: a rotated or skewed one (read resampled north up), or one without coordinates (placed, +/// if at all, by a world file once read). Its no-data value, coordinate system and band +/// descriptions are the whole image's. `overview`, when the level isn't the full image, is the +/// part's size in the full image's pixels. +#[cfg(test)] +pub(super) fn read_part(r: Reader<'_>, name: &str, max: usize, part: super::Part) -> Result> { + read_image(r, name, max, None, None, None, Some(part)) +} + +/// [`read_limited_with_nodata`], or of `part` of the image only ([`read_part`]). +fn read_image( + r: Reader<'_>, + name: &str, + max: usize, + open: Option>, + sidecar_nodata: Option, + asked: Option, + part: Option, +) -> Result> { // The full image says whether it is read as a palette image, whichever image is read, as a // COG window has it: a grey full image's stray colour table colours nothing, nor do palette // overviews of it. @@ -1536,6 +1679,11 @@ pub(super) fn read_limited_with_nodata( let mut dec = Decoder::new(r).map_err(err)?.with_limits(limits.clone()); let (full_w, full_h) = dec.dimensions().map_err(err)?; let geo = geo_tags(&mut dec)?; + // A turned image is resampled north up whole, and one without coordinates may be placed by a + // world file: neither is read by part. + if part.is_some() && (geo.affine.is_some() || !geo.referenced) { + return Ok(None); + } // The no-data value whose pixels aren't counted as rounded. let uncounted = Uncounted::new(geo.nodata_exact, sidecar_nodata); // The bands' descriptions GDAL keeps in the file (an `.aux.xml` sidecar's are applied after). @@ -1561,6 +1709,8 @@ pub(super) fn read_limited_with_nodata( // The decoded image is held at its own pixel size before conversion to f32, so bound bytes // as well as samples. let fits = |w: u32, h: u32, spp: usize, bytes: usize| { + // Of a part, its pixels at that size. + let (w, h) = part.map_or((w, h), |p| p.span(w, h).size()); let n = (w as usize).saturating_mul(h as usize).saturating_mul(spp); n <= max && n.saturating_mul(bytes) <= max.saturating_mul(4) }; @@ -1691,7 +1841,10 @@ pub(super) fn read_limited_with_nodata( other => return Err(err(format!("{other:?} images aren't supported"))), }; let planar = dec.find_tag_unsigned::(Tag::PlanarConfiguration).ok().flatten() == Some(2); - let n = (w as usize) * (h as usize); + // The pixels kept of the grid read (`w` × `h`): a part's, else all of them. + let span = part.map(|p| p.span(w, h)); + let (ow, oh) = span.map_or((w, h), Span::size); + let n = (ow as usize) * (oh as usize); // Extra samples the decoder leaves out can make padded edge tiles spill into the next row // when read whole (issue #162). Read those tile by tile. An RGBI image the patched reader // shows as grey (see `Unpaletted`) keeps its fourth sample and doesn't need this. @@ -1714,7 +1867,7 @@ pub(super) fn read_limited_with_nodata( // The decoder has no LERC codec: such an image is read a chunk at a time, every chunk decoded // by [`super::lerc`] (#1818). let lerc = super::lerc::is_lerc(&mut dec); - let whole = if decimate_by > 1 || extra_samples || planar_tiles || chunked || lerc { + let whole = if decimate_by > 1 || extra_samples || planar_tiles || chunked || lerc || span.is_some() { None } else { let mut buf = DecodingResult::U8(Vec::new()); @@ -1739,7 +1892,7 @@ pub(super) fn read_limited_with_nodata( } } } - let (values, dt) = to_f32(buf, (w as usize, h as usize))?; + let (values, dt) = to_f32(buf, (ow as usize, oh as usize))?; if values.len() < n.saturating_mul(nbands) { return Err(err("couldn't read every band")); } @@ -1750,14 +1903,14 @@ pub(super) fn read_limited_with_nodata( } else if planar { let mut bands = Vec::new(); for plane in values.chunks(n).take(nbands) { - let mut band = super::room(n, w as usize, h as usize)?; + let mut band = super::room(n, ow as usize, oh as usize)?; band.extend_from_slice(plane); bands.push(band); } bands } else { // One pass over the interleaved pixels. - let mut bands = (0..nbands).map(|_| super::room(n, w as usize, h as usize)).collect::>>>()?; + let mut bands = (0..nbands).map(|_| super::room(n, ow as usize, oh as usize)).collect::>>>()?; for px in values.chunks(nbands).take(n) { for (band, v) in bands.iter_mut().zip(px) { band.push(*v); @@ -1771,7 +1924,7 @@ pub(super) fn read_limited_with_nodata( let (iw, ih) = if decimate_by > 1 { (full_w, full_h) } else { (w, h) }; let open = open.map(|o| (o, image, limits)); // Already one vector per band. - decimate(&mut dec, iw, ih, nbands, planar, decimate_by, uncounted, open)? + decimate(&mut dec, iw, ih, nbands, planar, decimate_by, span, uncounted, open)? }; let rounded = if rounded.iter().any(|n| *n > 0) { rounded } else { Vec::new() }; @@ -1782,7 +1935,7 @@ pub(super) fn read_limited_with_nodata( // reprojection are. One that can't be read leaves them as stored, and says so. let mut mask_lost = None; match super::mask::find(&mut dec, image, if decimate_by > 1 { (full_w, full_h) } else { (w, h) }) { - super::mask::Found::At(m) => match super::mask::read(&mut dec, m, decimate_by) { + super::mask::Found::At(m) => match super::mask::read(&mut dec, m, decimate_by, span) { Ok(opaque) if opaque.len() == n => { for band in &mut bands { for (v, _) in band.iter_mut().zip(&opaque).filter(|(_, o)| !**o) { @@ -1813,7 +1966,7 @@ pub(super) fn read_limited_with_nodata( if let Some(p) = &described { r.apply_pam(p, super::pam::GDAL_METADATA); } - return Ok(r); + return Ok(Some(r)); } let mut transform = geo.transform; // How many full-image pixels one pixel read spans, across and down. @@ -1876,6 +2029,16 @@ pub(super) fn read_limited_with_nodata( } } }; + // A part: its corner, and its size in the full image's pixels when it is coarser. + let (w, h, overview) = match span { + Some(span) => { + transform.origin_x += f64::from(span.cols.0) * transform.pixel_width; + transform.origin_y += f64::from(span.rows.0) * transform.pixel_height; + let file = |n: u32, by: f64| (f64::from(n) * by).round().clamp(1.0, f64::from(u32::MAX)) as u32; + (ow, oh, overview.map(|_| (file(ow, sx), file(oh, sy)))) + } + None => (w, h, overview), + }; let mut r = Raster::new(name, w, h, bands, transform, crs, geo.nodata, color, data_type)?; r.overview = overview; // A turned image is resampled to a grid of its own: its pixels are no longer the file's. @@ -1892,7 +2055,7 @@ pub(super) fn read_limited_with_nodata( if let Some(p) = &described { r.apply_pam(p, super::pam::GDAL_METADATA); } - Ok(r) + Ok(Some(r)) } /// What turning a rotated or skewed image north up says ([`super::north_up`]): its pixels are @@ -2375,12 +2538,12 @@ mod tests { } reader(Cursor::new(bytes.clone())) }; - let side = 16usize.div_ceil(k as usize); + let side = 16u32.div_ceil(k); decimate_parallel( chunks, - vec![vec![f32::NAN; side * side]], + vec![vec![f32::NAN; (side * side) as usize]], k, - (side, side), + Span::whole(side, side), Uncounted::new(None, None), 2, &open, @@ -2388,7 +2551,7 @@ mod tests { Limits::default(), ) } else { - decimate(&mut dec, 16, 16, 1, false, k, Uncounted::new(None, None), None) + decimate(&mut dec, 16, 16, 1, false, k, None, Uncounted::new(None, None), None) }; if let Some(after) = after { assert!(matches!(got, Err(DataError::Cancelled)), "parallel={parallel}, k={k}, after={after}: {got:?}"); @@ -2420,7 +2583,8 @@ mod tests { } /// Every `k`-th pixel each way, whatever the chunks' shape and whether the edge ones are - /// padded: the same pixels, in the same places. + /// padded: the same pixels, in the same places; of a part of the grid, its pixels alone, from + /// the chunks that hold it. #[test] fn decimation_keeps_the_same_pixels_whatever_the_chunk_shape() { let value = |x: u32, y: u32, s: usize| (y * 1000 + x * 10) as f32 + s as f32; @@ -2428,24 +2592,38 @@ mod tests { for padded in [false, true] { for k in 1..=9u32 { let chunks = chunk_grid(13, 8, cw, ch, 2); - let (ow, oh) = (13u32.div_ceil(k) as usize, 8u32.div_ceil(k) as usize); - let mut bands = vec![vec![f32::NAN; ow * oh]; 2]; - for i in 0..chunks.count() { - let Some((plane, index)) = chunks.wanted(i, k) else { continue }; - let (x0, y0) = ((index % chunks.across) * cw, (index / chunks.across) * ch); - let (dw, rows) = if padded { (cw, ch) } else { (cw.min(13 - x0), ch.min(8 - y0)) }; - let mut values = Vec::new(); - for y in y0..y0 + rows { - for x in x0..x0 + dw { - values.extend([value(x, y, 0), value(x, y, 1)]); + let (gw, gh) = (13u32.div_ceil(k), 8u32.div_ceil(k)); + for span in [ + Span::whole(gw, gh), + Span { cols: (gw / 3, gw), rows: (gh / 2, gh) }, + Span { cols: (1.min(gw - 1), gw.min(2)), rows: (0, 1) }, + ] { + let (ow, oh) = (span.width(), span.height()); + let mut bands = vec![vec![f32::NAN; ow * oh]; 2]; + let mut read = 0; + for p in 0..chunks.count_in(span, k) { + let Some((plane, index)) = chunks.nth(p, span, k).and_then(|i| chunks.wanted(i, k, span)) else { continue }; + read += 1; + let (x0, y0) = ((index % chunks.across) * cw, (index / chunks.across) * ch); + let (dw, rows) = if padded { (cw, ch) } else { (cw.min(13 - x0), ch.min(8 - y0)) }; + let mut values = Vec::new(); + for y in y0..y0 + rows { + for x in x0..x0 + dw { + values.extend([value(x, y, 0), value(x, y, 1)]); + } } + chunks.place(&mut bands, &values, None, &mut [0, 0], plane, index, k, span).unwrap(); } - chunks.place(&mut bands, &values, None, &mut [0, 0], plane, index, k, ow).unwrap(); - } - for (s, band) in bands.iter().enumerate() { - let want: Vec = - (0..oh as u32).flat_map(|r| (0..ow as u32).map(move |c| (c * k, r * k))).map(|(x, y)| value(x, y, s)).collect(); - assert_eq!(band, &want, "chunks of {cw} × {ch}, padded {padded}, every {k}th, band {s}"); + for (s, band) in bands.iter().enumerate() { + let want: Vec = (span.rows.0..span.rows.1) + .flat_map(|r| (span.cols.0..span.cols.1).map(move |c| (c * k, r * k))) + .map(|(x, y)| value(x, y, s)) + .collect(); + assert_eq!(band, &want, "chunks of {cw} × {ch}, padded {padded}, every {k}th, {span:?}, band {s}"); + } + // No chunk is read that holds none of the part's pixels. + let holding = (0..chunks.count()).filter(|i| chunks.wanted(*i, k, span).is_some()).count(); + assert_eq!(read, holding, "chunks of {cw} × {ch}, every {k}th, {span:?}"); } } } @@ -2506,12 +2684,14 @@ mod tests { for wide in [true, false] { let chunks = if wide { chunk_grid(u32::MAX, 1, k, 1, 1) } else { chunk_grid(1, u32::MAX, 1, k, 1) }; assert_eq!(chunks.count(), 4096); - assert!((0..4096).all(|i| chunks.wanted(i, k) == Some((0, i as u32)))); + let span = if wide { Span::whole(4096, 1) } else { Span::whole(1, 4096) }; + assert!((0..4096).all(|i| chunks.wanted(i, k, span) == Some((0, i as u32)))); + assert_eq!(chunks.count_in(span, k), 4096); // The last chunk holds one pixel fewer than the others; its first is kept. let mut values = vec![0.0f32; k as usize - 1]; values[0] = 7.0; let mut band = vec![vec![f32::NAN; 4096]]; - chunks.place(&mut band, &values, None, &mut [0], 0, 4095, k, if wide { 4096 } else { 1 }).unwrap(); + chunks.place(&mut band, &values, None, &mut [0], 0, 4095, k, span).unwrap(); assert_eq!(band[0].iter().filter(|v| !v.is_nan()).count(), 1, "wide {wide}"); assert_eq!(band[0][4095], 7.0, "wide {wide}"); } @@ -2526,12 +2706,12 @@ mod tests { let chunks = chunk_grid(u32::MAX, 1, 3, 1, 1); let last = chunks.across - 1; assert_eq!(chunks.span(last), (4_294_967_292, 0, 3, 1)); - assert_eq!(chunks.wanted(u64::from(last), 1 << 20), None); - assert_eq!(chunks.wanted(u64::from(last), 2), Some((0, last))); + assert_eq!(chunks.wanted(u64::from(last), 1 << 20, Span::whole(4096, 1)), None); + assert_eq!(chunks.wanted(u64::from(last), 2, Span::whole(1 << 31, 1)), Some((0, last))); // Every second pixel keeps 4,294,967,292 and 4,294,967,294; the output isn't made (it would // hold 2 GiB): the walk ending is what is checked. let mut bands = vec![Vec::new()]; - chunks.place(&mut bands, &[1.0, 2.0, 3.0], None, &mut [0], 0, last, 2, 1 << 31).unwrap(); + chunks.place(&mut bands, &[1.0, 2.0, 3.0], None, &mut [0], 0, last, 2, Span::whole(1 << 31, 1)).unwrap(); assert!(bands[0].is_empty()); // Chunks of no width or height, and an image of no width, are nothing, not a division by 0. let none = chunk_grid(0, 0, 1, 1, 1); @@ -2546,12 +2726,12 @@ mod tests { // One 4 × 2 tile; 5 values make neither 4 × 2 nor any padded shape. let chunks = chunk_grid(4, 2, 4, 2, 1); let mut bands = vec![vec![f32::NAN; 8]]; - let e = chunks.place(&mut bands, &[1.0, 2.0, 3.0, 4.0, 5.0], None, &mut [0], 0, 0, 1, 4).unwrap_err().to_string(); + let e = chunks.place(&mut bands, &[1.0, 2.0, 3.0, 4.0, 5.0], None, &mut [0], 0, 0, 1, Span::whole(4, 2)).unwrap_err().to_string(); assert!(e.contains("decodes to 5 values, not the 4 × 2 pixels"), "{e}"); assert!(bands[0].iter().all(|v| v.is_nan()), "nothing placed from a refused chunk"); // All 8 are placed where they belong. let all: Vec = (0..8).map(|v| v as f32).collect(); - chunks.place(&mut bands, &all, None, &mut [0], 0, 0, 1, 4).unwrap(); + chunks.place(&mut bands, &all, None, &mut [0], 0, 0, 1, Span::whole(4, 2)).unwrap(); assert_eq!(bands[0], all); } @@ -3444,6 +3624,102 @@ mod tests { assert_eq!((r.width, r.height), (501, 501)); } + /// A part of a tiled file (#2865) is the pixels, place, no-data, system and band names of + /// the whole file read at the same level then cut to it: the full image when the part fits, + /// the finest overview whose part does when it doesn't, and every other pixel of a file + /// without overviews. Only the tiles that hold it are read. + #[test] + fn a_part_is_the_whole_file_read_at_its_level_then_cut_to_it() { + use super::super::Part; + use super::super::cog::{Example, example_with}; + /// A file's reader, counting the bytes read from it. + struct Counting(std::io::Cursor>, std::rc::Rc>); + impl Read for Counting { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let n = self.0.read(buf)?; + self.1.set(self.1.get() + n as u64); + Ok(n) + } + } + impl Seek for Counting { + fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result { + self.0.seek(to) + } + } + let base = Example { size: 1024, tile: 128, ..Example::default() }; + let cases = [ + Example { bands: 3, wavelengths: true, ..base }, + Example { bands: 2, planar: true, ..base }, + Example { int8: true, ..base }, + Example { bottom_up: true, ..base }, + Example { no_overviews: true, ..base }, + ]; + // Columns 307 to 431 and rows 563 to 922 of the full image. + let part = Part::new(0.3, 0.55, 0.42, 0.9).unwrap(); + for e in cases { + let file = example_with(&e); + let bands = usize::from(e.bands); + // The part fits at full size; then only at half size (an overview, or every other + // pixel); the whole file is read at that size to compare. + for (part_max, whole_max, size) in [(200_000 * bands, 1024 * 1024 * bands, 1024), (20_000 * bands, 512 * 512 * bands, 512)] { + let read = std::rc::Rc::new(std::cell::Cell::new(0)); + let r = read_part(reader(Counting(std::io::Cursor::new(file.clone()), read.clone())).unwrap(), "part", part_max, part) + .unwrap() + .expect("read by part"); + let whole = read_limited(reader(std::io::Cursor::new(&file)).unwrap(), "whole", whole_max, None).unwrap(); + assert_eq!(whole.width, size, "{e:?}"); + let at = |v: f64, origin: f64, px: f64| ((v - origin) / px).round() as i64; + let (c0, r0) = ( + at(r.transform.origin_x, whole.transform.origin_x, whole.transform.pixel_width), + at(r.transform.origin_y, whole.transform.origin_y, whole.transform.pixel_height), + ); + let scale = 1024 / size; + let expected = (307 / scale, (431u32).div_ceil(scale), 563 / scale, (922u32).div_ceil(scale)); + let got = (c0 as u32, c0 as u32 + r.width, r0 as u32, r0 as u32 + r.height); + assert_eq!(got, expected, "{e:?} at {size}"); + assert_eq!( + (r.transform.pixel_width, r.transform.pixel_height), + (whole.transform.pixel_width, whole.transform.pixel_height) + ); + assert_eq!( + (r.crs, r.nodata, r.color.clone(), r.data_type.clone(), r.step), + (whole.crs, whole.nodata, whole.color.clone(), whole.data_type.clone(), whole.step) + ); + let names = |r: &Raster| r.bands.iter().map(|b| (b.name.clone(), b.wavelength)).collect::>(); + assert_eq!(names(&r), names(&whole), "{e:?}"); + for b in 0..r.band_count() { + for y in 0..i64::from(r.height) { + for x in 0..i64::from(r.width) { + assert_eq!(r.value(b, x, y), whole.value(b, x + c0, y + r0), "{e:?} at {size}: band {b} at {x},{y}"); + } + } + } + // Its size in the full image's pixels when coarser, as an overview of it. + let full = |n: u32| n * scale; + assert_eq!(r.overview, (size < 1024).then(|| (full(r.width), full(r.height))), "{e:?}"); + assert!(read.get() < file.len() as u64 / 4, "{e:?} at {size}: {} bytes of {} read", read.get(), file.len()); + } + } + } + + /// A rotated file is resampled north up whole, and one without coordinates may be placed by a + /// world file: neither is read by part, for the caller to read whole. + #[test] + fn a_turned_or_unplaced_file_is_not_read_by_part() { + let part = super::super::Part::new(0.0, 0.0, 0.5, 0.5).unwrap(); + let data: Vec = (0..64 * 64).map(|i| (i % 251) as u8).collect(); + // A TIFF with no GeoTIFF tags: a scan. + let mut scan = std::io::Cursor::new(Vec::new()); + tiff::encoder::TiffEncoder::new(&mut scan).unwrap().write_image::(64, 64, &data).unwrap(); + let scan = scan.into_inner(); + // Georeferenced, the same pixels are. + assert!(read_part(reader(std::io::Cursor::new(grey8(64, 64, &data, None))).unwrap(), "placed", 1 << 20, part).unwrap().is_some()); + assert!(read_part(reader(std::io::Cursor::new(&scan)).unwrap(), "scan", 1 << 20, part).unwrap().is_none()); + let m = [30.0, 5.0, 0.0, 400_000.0, 3.0, -30.0, 0.0, 5_000_000.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]; + let turned = tests_support::matrix_tiff(m, false); + assert!(read_part(reader(std::io::Cursor::new(&turned)).unwrap(), "turned", 1 << 20, part).unwrap().is_none()); + } + #[test] fn a_striped_file_read_in_parts_is_read_to_its_end() { // No overviews and in strips: every strip is needed, and reads stop at the file's end. diff --git a/crates/data/src/raster/mask.rs b/crates/data/src/raster/mask.rs index 291f1eb689..5b15aee4ee 100644 --- a/crates/data/src/raster/mask.rs +++ b/crates/data/src/raster/mask.rs @@ -7,6 +7,7 @@ use std::io::{Read, Seek, SeekFrom}; use tiff::decoder::Decoder; use tiff::tags::Tag; +use super::geotiff::Span; use crate::{DataError, Result}; /// Most bytes in a chunk, compressed or decoded. @@ -68,9 +69,9 @@ pub(super) fn find(dec: &mut Decoder, image: usize, size: (u3 } /// Which pixels of the mask image at `index` are opaque, for every `step`-th pixel of it across and -/// down (row by row, `ceil(width / step)` × `ceil(height / step)` of them). A mask that can't be -/// read is an error saying why. -pub(super) fn read(dec: &mut Decoder, index: usize, step: u32) -> Result> { +/// down (row by row, `ceil(width / step)` × `ceil(height / step)` of them), or of those `span` +/// keeps of them. A mask that can't be read is an error saying why. +pub(super) fn read(dec: &mut Decoder, index: usize, step: u32, span: Option) -> Result> { dec.seek_to_image(index).map_err(err)?; let (w, h) = dec.dimensions().map_err(err)?; // An absent tag is its default; one that can't be read is an error, not a default. @@ -107,7 +108,8 @@ pub(super) fn read(dec: &mut Decoder, index: usize, step: u32 .filter(|n| offsets.len() >= *n && counts.len() >= *n) .ok_or_else(|| err("a transparency mask's chunk index is shorter than its image"))?; let row_bytes = (cw as usize).div_ceil(8); - let (ow, oh) = (w.div_ceil(step) as usize, h.div_ceil(step) as usize); + let span = span.unwrap_or_else(|| Span::whole(w.div_ceil(step), h.div_ceil(step))); + let (ow, oh) = (span.width(), span.height()); let mut out = super::filled(ow, oh, false)?; let step = u64::from(step); for c in 0..n { @@ -115,8 +117,8 @@ pub(super) fn read(dec: &mut Decoder, index: usize, step: u32 let (x0, y0) = ((c as u64 % across) * u64::from(cw), (c as u64 / across) * u64::from(ch)); let tile = Tile { x0, y0, dw: u64::from(cw).min(u64::from(w).saturating_sub(x0)), dh: u64::from(ch).min(u64::from(h).saturating_sub(y0)) }; - // No sampled pixel inside the chunk: skipped. - if tile.first(step).is_none() { + // No sampled pixel of the span inside the chunk: skipped. + if tile.first(step, span).is_none() { continue; } // A tile holds every row, padded; a strip only the image's. @@ -144,7 +146,7 @@ pub(super) fn read(dec: &mut Decoder, index: usize, step: u32 if (decoded.len() as u64) < (row_bytes as u64).saturating_mul(tile.dh) { return Err(err("a transparency mask's chunk is shorter than its image")); } - tile.sample(&mut out, ow, step, &decoded, row_bytes, lsb_first); + tile.sample(&mut out, span, step, &decoded, row_bytes, lsb_first); } Ok(out) } @@ -160,32 +162,34 @@ struct Tile { } impl Tile { - /// The first sampled column and row at or after the chunk's corner, if the chunk holds any - /// sampled pixel (every `step`-th column and row from the image's corner). - fn first(self, step: u64) -> Option<(u64, u64)> { - let (sx, sy) = (self.x0.div_ceil(step) * step, self.y0.div_ceil(step) * step); - (sx < self.x0 + self.dw && sy < self.y0 + self.dh).then_some((sx, sy)) + /// The sampled columns and rows (half-open) of the chunk that `span` keeps, if it holds any + /// (every `step`-th column and row from the image's corner). + fn first(self, step: u64, span: Span) -> Option<((u64, u64), (u64, u64))> { + let (xs, ys) = (span.kept(span.cols, self.x0, self.dw, step), span.kept(span.rows, self.y0, self.dh, step)); + (xs.0 < xs.1 && ys.0 < ys.1).then_some((xs, ys)) } - /// Puts the chunk's sampled pixels into `out`, `ow` to a row: `decoded` is its rows of - /// `row_bytes` bytes, a pixel a bit, the first of a byte its high bit unless `lsb_first`. - fn sample(self, out: &mut [bool], ow: usize, step: u64, decoded: &[u8], row_bytes: usize, lsb_first: bool) { - let Some((sx, sy)) = self.first(step) else { return }; + /// Puts the chunk's sampled pixels that `span` keeps into `out`, the span's width to a row: + /// `decoded` is its rows of `row_bytes` bytes, a pixel a bit, the first of a byte its high bit + /// unless `lsb_first`. + fn sample(self, out: &mut [bool], span: Span, step: u64, decoded: &[u8], row_bytes: usize, lsb_first: bool) { + let Some(((sx, ex), (sy, ey))) = self.first(step, span) else { return }; + let (ow, sc, sr) = (span.width(), u64::from(span.cols.0), u64::from(span.rows.0)); let by = usize::try_from(step).unwrap_or(usize::MAX); - for y in (sy..self.y0 + self.dh).step_by(by) { + for y in (sy..ey).step_by(by) { let row = usize::try_from(y - self.y0) .ok() .and_then(|r| r.checked_mul(row_bytes)) .and_then(|at| decoded.get(at..)) .unwrap_or_default(); - for x in (sx..self.x0 + self.dw).step_by(by) { + for x in (sx..ex).step_by(by) { let (bx, bit) = (usize::try_from((x - self.x0) / 8).unwrap_or(usize::MAX), (x - self.x0) % 8); let Some(byte) = row.get(bx) else { continue }; let on = if lsb_first { byte >> bit & 1 } else { byte >> (7 - bit) & 1 } == 1; - let at = usize::try_from(y / step) + let at = usize::try_from(y / step - sr) .ok() .and_then(|r| r.checked_mul(ow)) - .and_then(|at| at.checked_add(usize::try_from(x / step).ok()?)); + .and_then(|at| at.checked_add(usize::try_from(x / step - sc).ok()?)); if let Some(slot) = at.and_then(|at| out.get_mut(at)) { *slot = on; } @@ -273,15 +277,22 @@ mod tests { fn check(bytes: Vec) { let mut dec = Decoder::new(std::io::Cursor::new(bytes)).expect("decoder"); assert!(matches!(find(&mut dec, 0, (10, 7)), Found::At(0))); - let all = read(&mut dec, 0, 1).expect("mask"); + let all = read(&mut dec, 0, 1, None).expect("mask"); assert_eq!(all.len(), 70); assert!(all.iter().enumerate().all(|(i, on)| *on == ((i % 10 + i / 10) % 2 == 0))); // Every third pixel, from the corner. - let some = read(&mut dec, 0, 3).expect("sampled mask"); + let some = read(&mut dec, 0, 3, None).expect("sampled mask"); assert_eq!(some.len(), 4 * 3); for (i, on) in some.iter().enumerate() { assert_eq!(*on, ((i % 4 * 3 + i / 4 * 3) % 2) == 0, "{i}"); } + // A part of it, columns 3 to 8 and rows 2 to 6, alone; and of every other pixel. + for (step, span) in [(1, Span { cols: (3, 8), rows: (2, 6) }), (2, Span { cols: (1, 4), rows: (1, 4) })] { + let part = read(&mut dec, 0, step, Some(span)).expect("a part of the mask"); + let want: Vec = + (span.rows.0..span.rows.1).flat_map(|y| (span.cols.0..span.cols.1).map(move |x| (x * step + y * step) % 2 == 0)).collect(); + assert_eq!(part, want, "every {step}th, {span:?}"); + } } #[test] @@ -311,14 +322,14 @@ mod tests { fn a_short_or_missing_chunk_is_an_error_not_a_panic() { let rows = rows(); let mut dec = Decoder::new(std::io::Cursor::new(striped(10, 7, 7, 1, &[rows[..5].concat()]))).expect("decoder"); - assert!(read(&mut dec, 0, 1).is_err()); + assert!(read(&mut dec, 0, 1, None).is_err()); } /// A packbits run that lacks its value byte is a short chunk, not eight transparent pixels. #[test] fn a_packbits_run_without_its_byte_is_a_short_chunk() { let mut dec = Decoder::new(std::io::Cursor::new(striped(8, 8, 8, 32773, &[vec![0xF9]]))).expect("decoder"); - assert!(read(&mut dec, 0, 1).is_err()); + assert!(read(&mut dec, 0, 1, None).is_err()); } /// A damaged image directory chain is said, not taken for a file without a mask. @@ -339,23 +350,24 @@ mod tests { #[test] fn tiles_of_an_image_as_wide_as_u32_holds_are_sampled_and_the_walk_ends() { let step = 1u64 << 20; + let span = Span::whole(4096, 4096); let last = Tile { x0: 4095 << 20, y0: 0, dw: (1 << 20) - 1, dh: 1 }; - assert_eq!(last.first(step), Some((4095 << 20, 0))); + assert_eq!(last.first(step, span), Some(((4095 << 20, (1 << 32) - 1), (0, 1)))); for lsb_first in [false, true] { let mut row = vec![0u8; 1 << 17]; row[0] = if lsb_first { 0x01 } else { 0x80 }; let mut out = vec![false; 4096]; - last.sample(&mut out, 4096, step, &row, row.len(), lsb_first); + last.sample(&mut out, Span::whole(4096, 1), step, &row, row.len(), lsb_first); assert_eq!(out.iter().filter(|on| **on).count(), 1, "lsb_first {lsb_first}"); assert!(out[4095], "lsb_first {lsb_first}"); } // Three pixels from 4,294,967,292: the next multiple of 2^20 is 2^32, past them. let end = Tile { x0: u64::from(u32::MAX) - 3, y0: 0, dw: 3, dh: 1 }; - assert_eq!(end.first(step), None); + assert_eq!(end.first(step, span), None); let tall = Tile { x0: 0, y0: u64::from(u32::MAX) - 3, dw: 1, dh: 3 }; - assert_eq!(tall.first(step), None); + assert_eq!(tall.first(step, span), None); let mut out = vec![false; 4]; - end.sample(&mut out, 4, step, &[0xff], 1, false); + end.sample(&mut out, Span::whole(4, 1), step, &[0xff], 1, false); assert_eq!(out, [false; 4]); } @@ -364,7 +376,7 @@ mod tests { #[test] fn a_mask_too_large_to_hold_is_an_error() { let mut dec = Decoder::new(std::io::Cursor::new(striped(u32::MAX, u32::MAX, u32::MAX, 1, &[vec![0]]))).expect("decoder"); - let e = read(&mut dec, 0, 1).unwrap_err().to_string(); + let e = read(&mut dec, 0, 1, None).unwrap_err().to_string(); assert!(e.contains("not enough memory"), "{e}"); } } diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index b40be5344a..78ee3797f6 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -715,7 +715,8 @@ pub struct Raster { /// The original local GeoTIFF's revision or capture failure, retained with these pixels and never serialized. #[cfg(not(target_arch = "wasm32"))] source_file: Option>, - /// Whether the pixels come from a reduced-resolution overview. + /// Whether the pixels come from a reduced-resolution overview: the size, in the file's pixels, + /// of what was read (the file's, or a part's, [`read_path_part`]). pub overview: Option<(u32, u32)>, /// With `overview`, whether the pixels are every `step`-th of the file's, from its top-left /// corner (a picture too large to read whole): each then spans exactly `step` of its pixels, @@ -1425,6 +1426,85 @@ fn read_path_placing(path: &Path, world: bool) -> Result { Ok(r) } +/// Part of a raster file's image: its left, top, right and bottom edges as fractions of the +/// image's width and height from its top-left corner, 0 to 1. Every level of a file (its full +/// image and its overviews) covers the same ground, so a part is the same ground at each. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Part { + left: f64, + top: f64, + right: f64, + bottom: f64, +} + +impl Part { + /// The part between these edges, each cut to the image; `None` when they aren't numbers or + /// leave nothing of it. + pub fn new(left: f64, top: f64, right: f64, bottom: f64) -> Option { + let [left, top, right, bottom] = [left, top, right, bottom].map(|v| v.clamp(0.0, 1.0)); + ([left, top, right, bottom].iter().all(|v| v.is_finite()) && left < right && top < bottom).then_some(Part { + left, + top, + right, + bottom, + }) + } + + /// The columns and rows of a grid `w` × `h` the part covers, out to whole pixels: one at + /// least, of a grid that has any. + fn span(self, w: u32, h: u32) -> geotiff::Span { + let edges = |a: f64, b: f64, n: u32| { + let n64 = f64::from(n); + let start = ((a * n64).floor() as u32).min(n.saturating_sub(1)); + (start, ((b * n64).ceil() as u32).min(n).max(start.saturating_add(1).min(n))) + }; + geotiff::Span { cols: edges(self.left, self.right, w), rows: edges(self.top, self.bottom, h) } + } +} + +/// `part` of the GeoTIFF at `path`, as [`read_path`] reads the file but holding only that part, +/// at the finest level whose part fits [`max_samples`]: the full image when it does, read from +/// the strips or tiles that hold it alone. The `.aux.xml` beside it is applied as it is to the +/// whole file. `Ok(None)` when the file isn't read so: not a GeoTIFF, one with a world file +/// beside it, or one [`geotiff`] can't read by part (rotated, skewed or without coordinates). +/// Read the whole file then. A part read at a coarser level says it with `overview`, the part's +/// size in the file's pixels. +#[cfg(not(target_arch = "wasm32"))] +pub fn read_path_part(path: &Path, part: Part) -> Result> { + let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); + if !matches!(ext.as_str(), "tif" | "tiff") { + return Ok(None); + } + if !std::fs::metadata(path)?.is_file() { + return Err(DataError::Format(format!("{} is not a regular file", path.display()))); + } + // A world file is compared with the file's whole grid as it is read: read whole. + if world::beside(path).is_some() { + return Ok(None); + } + let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("raster").to_string(); + let pam = pam::read(path); + let sidecar_nodata = pam.as_ref().and_then(pam::Pam::nodata); + let Some(mut r) = geotiff::read_file_part(path, &name, sidecar_nodata, part)? else { return Ok(None) }; + // As [`read_path_placing`]: read again with the no-data the bands it has give, so the + // rounded count leaves out just its pixels. + let applied = pam.as_ref().map(|p| p.nodata_within(r.bands.len())); + if let Some(nd) = applied + && nd != sidecar_nodata + && r.nodata.is_none() + && matches!(r.data_type.as_str(), "UInt32" | "Int32" | "UInt64" | "Int64" | "Float64") + { + drop(r); + let Some(again) = geotiff::read_file_part(path, &name, nd, part)? else { return Ok(None) }; + r = again; + } + if let Some(p) = &pam { + r.apply_pam(p, pam::SIDECAR); + } + r.source = Some(path.display().to_string()); + Ok(Some(r)) +} + /// A picture at `path` with the world file beside it applied (#2075). A scan is placed by it, in /// the coordinate system of the `.prj` beside it. Whatever goes wrong (no `.prj`, one that can't /// be used, a world file that can't be read, or one that places it nowhere it can be drawn), the diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 18451b5b71..4f5dee81ef 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1630,6 +1630,24 @@ pub(crate) fn tiled_inputs( Ok(read) } +/// `part` of the raster file read in place at `path` (layer `name`'s), read from the file at the +/// finest level whose part the run can hold, in its turn ([`tiled_turn`]), with its count in +/// [`rustgis_data::memory::held`]; `None` when the file can't be read by part (read it whole with +/// [`read_tiled`]). Never kept for a batch: another item's part is another part. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_tiled_part( + name: &str, + path: &str, + part: rustgis_data::raster::Part, +) -> Result, std::sync::Arc)>, String> { + let _turn = tiled_turn().map_err(|e| format!("{name}: {e}"))?; + let Some(r) = rustgis_data::raster::read_path_part(std::path::Path::new(path), part).map_err(|e| format!("{name}: {e}"))? else { + return Ok(None); + }; + let bytes: usize = r.bands.iter().map(|b| b.data.len().saturating_mul(4)).sum(); + Ok(Some((std::sync::Arc::new(r), std::sync::Arc::new(rustgis_data::memory::Holding::of(bytes as u64))))) +} + /// What a run says of the raster files read in place it read again from their file /// ([`read_tiled`]), each with its layer's name: one notice of each kind, naming each raster. /// `whose` says whose results are built on values rounded as they were read. diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 07b00c94fb..8c1bfa8984 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1753,11 +1753,16 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result r.read_part(part)?, + None => r.read()?, + }; let (cols, rows) = extent_window(&r, &e)?; super::workflows::made(clip_window(&r, cols, rows, None, out)?, None) })) @@ -1840,6 +1845,18 @@ fn extent_window(r: &Raster, e: &Extent) -> Result<(std::ops::Range, std::o Ok((c0..c1, r0..r1)) } +/// The part of a raster's ground under a longitude/latitude box ([`extent_window`]), as fractions +/// of its width and height, a pixel of its file wider each way so a file read at a finer level +/// than `r` still holds every pixel the box touches: the part a clip of it reads. +fn extent_part(r: &Raster, e: &Extent) -> Option { + let px = edge_pixels(r, e)?; + let (w, h) = (f64::from(r.width.max(1)), f64::from(r.height.max(1))); + let (fw, fh) = r.overview.map_or((w, h), |(fw, fh)| (f64::from(fw.max(1)), f64::from(fh.max(1)))); + let (x0, x1) = px.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), p| (a.min(p.0), b.max(p.0))); + let (y0, y1) = px.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), p| (a.min(p.1), b.max(p.1))); + rustgis_data::raster::Part::new(x0 / w - 1.0 / fw, y0 / h - 1.0 / fh, x1 / w + 1.0 / fw, y1 / h + 1.0 / fh) +} + /// Most inputs a mosaic takes. const MAX_MOSAIC_INPUTS: usize = 10_000; diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index b4f07fc9d9..1168a7cd33 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -156,12 +156,12 @@ impl Input { if let Some((name, path)) = &self.file && RUN_READS.with(|r| r.borrow().is_some()) { - let kept = RUN_READS.with(|r| r.borrow().as_ref().and_then(|read| read.iter().find(|k| k.0 == *path).cloned())); + let kept = RUN_READS.with(|r| r.borrow().as_ref().and_then(|read| read.iter().find(|k| k.0.as_ref() == Some(path)).cloned())); let (_, _, raster, count) = match kept { Some(k) => k, None => { let (raster, count) = super::gp::read_tiled(name, path)?; - let k = (path.clone(), name.clone(), raster, count); + let k = (Some(path.clone()), name.clone(), raster, count); RUN_READS.with(|r| { if let Some(read) = r.borrow_mut().as_mut() { read.push(k.clone()); @@ -177,6 +177,29 @@ impl Input { let _ = &self.file; Ok(Read { raster: self.held.clone(), _count: None }) } + + /// The raster the work reads, for work that uses only `part` of it: within a run, a layer read + /// in place from a GeoTIFF on this computer reads only that part of its file, out to whole + /// pixels, at the finest level whose part the run can hold, decoding only the strips or tiles + /// that hold it (`rustgis_data::raster::read_path_part`). A part isn't kept for the run's other + /// inputs. A file that can't be read by part, and any other layer, give [`Input::read`]. + pub(crate) fn read_part(&self, part: rustgis_data::raster::Part) -> Result { + #[cfg(not(target_arch = "wasm32"))] + if let Some((name, path)) = &self.file + && RUN_READS.with(|r| r.borrow().is_some()) + && let Some((raster, count)) = super::gp::read_tiled_part(name, path, part)? + { + RUN_READS.with(|r| { + if let Some(read) = r.borrow_mut().as_mut() { + read.push((None, name.clone(), raster.clone(), count.clone())); + } + }); + return Ok(Read { raster, _count: Some(count) }); + } + #[cfg(target_arch = "wasm32")] + let _ = part; + self.read() + } } /// A raster a command's work reads ([`Input::read`]), counted in @@ -193,10 +216,11 @@ impl std::ops::Deref for Read { } } -/// A raster file read in place that a run read ([`RUN_READS`]): its path, its layer's name, the -/// raster read and its count in [`rustgis_data::memory::held`]. +/// A raster file read in place that a run read ([`RUN_READS`]): its path (`None` for a part of it, +/// [`Input::read_part`], which no other input takes), its layer's name, the raster read and its +/// count in [`rustgis_data::memory::held`]. #[cfg(not(target_arch = "wasm32"))] -type RunRead = (String, String, std::sync::Arc, std::sync::Arc); +type RunRead = (Option, String, std::sync::Arc, std::sync::Arc); #[cfg(not(target_arch = "wasm32"))] thread_local! { diff --git a/crates/engine/src/tests/tiled_files.rs b/crates/engine/src/tests/tiled_files.rs index 4d917198d7..a9a05828a5 100644 --- a/crates/engine/src/tests/tiled_files.rs +++ b/crates/engine/src/tests/tiled_files.rs @@ -358,3 +358,35 @@ fn a_run_that_panics_reads_no_file_after_it() { assert_eq!(within, 1024, "the file, within the run"); assert_eq!(input.read().unwrap().width, 512, "the overview the layer holds, after the run"); } + +/// Clip by extent of a layer read in place reads only the part of its file under the extent +/// (#2865): the clip is the one made of the file held whole, and the file isn't read whole for it. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_clip_by_extent_reads_only_its_part_of_a_tiled_file() { + let d = dir("clip"); + let path = checkerboard(&d); + let clip = json!({"layer": "checks", "operation": "clip", "extent": [10.3, 45.55, 10.42, 45.9], "name": "clip"}); + // Held whole, as a file this size is. + let mut whole = Session::new(Project::default()); + whole.run("layer.addData", &json!({"path": path})).unwrap(); + assert!(!raster(&whole, "checks").tiled); + whole.run("raster.process", &clip).unwrap(); + let _held = HeldWhole::at(1_000_000); + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": path})).unwrap(); + assert!(raster(&s, "checks").tiled); + let reads = || crate::cmd::gp::TILED_READS.with(std::cell::Cell::get); + let (before, mark) = (reads(), s.notice_mark()); + s.run("raster.process", &clip).unwrap(); + assert_eq!(reads(), before, "the file isn't read whole"); + let (got, want) = (raster(&s, "clip").data.clone().unwrap(), raster(&whole, "clip").data.clone().unwrap()); + // 0.12° by 0.35° of a 1024-pixel degree, at the file's full size. + assert_eq!((got.width, got.height, got.overview), (124, 359, None)); + assert_eq!((got.width, got.height, got.transform), (want.width, want.height, want.transform)); + for (g, w) in got.bands.iter().zip(&want.bands) { + assert!(g.data == w.data, "band {}", g.name); + } + let notes = said(&s, mark); + assert!(!notes.iter().any(|n| n.contains("finest level")), "{notes:?}"); +} From a7eabce043dc7633f489d82ef76d4e625d2cdfdf Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 14:33:21 -0600 Subject: [PATCH 2/4] fix(raster): a part's window is found on its whole grid, within a clip's share of memory - Every k-th pixel of a file whose size k doesn't divide: the part is found on the image's extent in the grid's pixels, not the grid's size, so no column it covers is left out. - `read_path_part` says where the part lies in the grid it was read from; Clip finds its window on that grid, as a whole read does, and moves it onto the part in whole pixels, so an edge on a pixel's edge isn't rounded into the next pixel. - A file no longer the revision the layer was read from is read whole, and so is one whose part doesn't hold the window. - Clip reads a part within a third of what a run holds (the part, its clip, and the clip's file at once), and a part isn't kept for the run past its clip: only what the run says of it is. --- crates/data/src/raster/geotiff.rs | 166 +++++++++++++++---------- crates/data/src/raster/mod.rs | 57 +++++---- crates/engine/src/cmd/gp.rs | 58 ++++++--- crates/engine/src/cmd/imagery.rs | 75 +++++++++-- crates/engine/src/cmd/workflows.rs | 63 +++++++--- crates/engine/src/tests/tiled_files.rs | 88 ++++++++++--- 6 files changed, 353 insertions(+), 154 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 2c33a799b5..4772228677 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1551,14 +1551,26 @@ pub(super) fn read_file_with_nodata(path: &std::path::Path, name: &str, sidecar_ } /// [`read_file_with_nodata`] of `part` of the image only, at the finest level whose part of it -/// fits [`max_samples`], decoding only the chunks that hold it (see [`read_part`]): `Ok(None)` -/// when the file can't be read by part. The raster's pixels aren't the file's whole grid, so it -/// keeps no revision of the file to pair later reads of the grid with. +/// fits `max` samples, decoding only the chunks that hold it (see [`read_part`]): `Ok(None)` when +/// the file can't be read by part, or isn't the revision `same_as` was read from. The raster's +/// pixels aren't the file's whole grid, so it keeps no revision of the file to pair later reads of +/// the grid with. #[cfg(not(target_arch = "wasm32"))] -pub(super) fn read_file_part(path: &std::path::Path, name: &str, sidecar_nodata: Option, part: super::Part) -> Result> { +pub(super) fn read_file_part( + path: &std::path::Path, + name: &str, + sidecar_nodata: Option, + part: super::Part, + max: usize, + same_as: Option<&Raster>, +) -> Result> { let file = crate::provenance::open(path).map_err(err)?; + // The part is of the image `same_as` was read from: of another, it would be another place. + if same_as.is_some_and(|r| r.check_original_handle(&file).is_err()) { + return Ok(None); + } let revision = file.metadata().and_then(|metadata| super::file_revision::FileRevision::capture(&metadata)); - read_file_revision_part(path, name, sidecar_nodata, file, revision, Some(part)) + read_file_revision_part(path, name, sidecar_nodata, file, revision, Some(part), max) } #[cfg(not(target_arch = "wasm32"))] @@ -1576,7 +1588,9 @@ fn read_file_with_revision( file: std::fs::File, revision: std::io::Result, ) -> Result { - read_file_revision_part(path, name, sidecar_nodata, file, revision, None)?.ok_or_else(|| err("the image couldn't be read")) + read_file_revision_part(path, name, sidecar_nodata, file, revision, None, max_samples())? + .map(|p| p.raster) + .ok_or_else(|| err("the image couldn't be read")) } /// [`read_file_with_revision`], of `part` of the image only when given (`Ok(None)` when the file @@ -1589,7 +1603,8 @@ fn read_file_revision_part( file: std::fs::File, revision: std::io::Result, part: Option, -) -> Result> { + max: usize, +) -> Result> { let revision = revision.map_err(|e| e.to_string()); let open = || -> std::io::Result> { let file = crate::provenance::open(path)?; @@ -1604,9 +1619,8 @@ fn read_file_revision_part( } reader(std::io::BufReader::new(file)) }; - let decoded = reader(std::io::BufReader::new(file)) - .map_err(err) - .and_then(|r| read_image(r, name, max_samples(), Some(&open), sidecar_nodata, None, part)); + let decoded = + reader(std::io::BufReader::new(file)).map_err(err).and_then(|r| read_image(r, name, max, Some(&open), sidecar_nodata, None, part)); // A file cut short while it is read fails to decode: the revision says whether that was a // change to wait out (Cancel is said as itself). if let Ok(original) = &revision @@ -1619,12 +1633,12 @@ fn read_file_revision_part( return Err(err(load_revision_error("The image file changed while its pixels were read"))); } } - let Some(mut raster) = decoded? else { return Ok(None) }; + let Some(mut read) = decoded? else { return Ok(None) }; // A part's pixels aren't the file's grid: no later read of it pairs with them. if part.is_none() { - raster.source_file = Some(revision); + read.raster.source_file = Some(revision); } - Ok(Some(raster)) + Ok(Some(read)) } /// [`read`], holding at most `max` samples (the tests' small limit exercises the overviews), with @@ -1644,7 +1658,7 @@ pub(super) fn read_limited_with_nodata( asked: Option, ) -> Result { // Only a part is ever not read. - read_image(r, name, max, open, sidecar_nodata, asked, None)?.ok_or_else(|| err("the image couldn't be read")) + read_image(r, name, max, open, sidecar_nodata, asked, None)?.map(|p| p.raster).ok_or_else(|| err("the image couldn't be read")) } /// [`read_limited_with_nodata`] of `part` of the image only: the finest level (the full image, an @@ -1656,7 +1670,7 @@ pub(super) fn read_limited_with_nodata( /// descriptions are the whole image's. `overview`, when the level isn't the full image, is the /// part's size in the full image's pixels. #[cfg(test)] -pub(super) fn read_part(r: Reader<'_>, name: &str, max: usize, part: super::Part) -> Result> { +pub(super) fn read_part(r: Reader<'_>, name: &str, max: usize, part: super::Part) -> Result> { read_image(r, name, max, None, None, None, Some(part)) } @@ -1669,7 +1683,7 @@ fn read_image( sidecar_nodata: Option, asked: Option, part: Option, -) -> Result> { +) -> Result> { // The full image says whether it is read as a palette image, whichever image is read, as a // COG window has it: a grey full image's stray colour table colours nothing, nor do palette // overviews of it. @@ -1708,9 +1722,11 @@ fn read_image( let bytes = sample_bytes(&mut dec); // The decoded image is held at its own pixel size before conversion to f32, so bound bytes // as well as samples. - let fits = |w: u32, h: u32, spp: usize, bytes: usize| { + // `w` × `h` pixels whose image spans `extent` of them each way (every k-th pixel's grid + // passes the image's edge when k doesn't divide its size). + let fits = |w: u32, h: u32, extent: (f64, f64), spp: usize, bytes: usize| { // Of a part, its pixels at that size. - let (w, h) = part.map_or((w, h), |p| p.span(w, h).size()); + let (w, h) = part.map_or((w, h), |p| p.span((w, h), extent).size()); let n = (w as usize).saturating_mul(h as usize).saturating_mul(spp); n <= max && n.saturating_mul(bytes) <= max.saturating_mul(4) }; @@ -1720,7 +1736,7 @@ fn read_image( let mut decimate_by = 1u32; // The image read: 0, the full one, or an overview. let mut image = 0; - if !fits(w, h, spp, bytes) { + if !fits(w, h, (f64::from(w), f64::from(h)), spp, bytes) { // The largest overview that fits, whatever order the images are in; a damaged image // ends the search rather than the open. let mut best: Option<(usize, u32, u32)> = None; @@ -1741,7 +1757,7 @@ fn read_image( // would read as another kind of image: the full image is read sparsely instead. if ospp == spp && extra_alpha(&mut dec) == full_alpha - && fits(ow, oh, ospp, obytes) + && fits(ow, oh, (f64::from(ow), f64::from(oh)), ospp, obytes) && best.is_none_or(|(_, bw, bh)| ow as u64 * oh as u64 > bw as u64 * bh as u64) { best = Some((index, ow, oh)); @@ -1749,7 +1765,7 @@ fn read_image( } // Every k-th pixel of the full image, the fewest left out that fit. let mut k = 2u32; - while !fits(full_w.div_ceil(k), full_h.div_ceil(k), spp, 4) { + while !fits(full_w.div_ceil(k), full_h.div_ceil(k), (f64::from(full_w) / f64::from(k), f64::from(full_h) / f64::from(k)), spp, 4) { k = k.saturating_mul(2); if k > 1 << 20 { break; @@ -1842,7 +1858,14 @@ fn read_image( }; let planar = dec.find_tag_unsigned::(Tag::PlanarConfiguration).ok().flatten() == Some(2); // The pixels kept of the grid read (`w` × `h`): a part's, else all of them. - let span = part.map(|p| p.span(w, h)); + // The image's extent in the grid's pixels: every k-th pixel's grid passes its edge when k + // doesn't divide its size. + let extent = if decimate_by > 1 { + (f64::from(full_w) / f64::from(decimate_by), f64::from(full_h) / f64::from(decimate_by)) + } else { + (f64::from(w), f64::from(h)) + }; + let span = part.map(|p| p.span((w, h), extent)); let (ow, oh) = span.map_or((w, h), Span::size); let n = (ow as usize) * (oh as usize); // Extra samples the decoder leaves out can make padded edge tiles spill into the next row @@ -1966,7 +1989,8 @@ fn read_image( if let Some(p) = &described { r.apply_pam(p, super::pam::GDAL_METADATA); } - return Ok(Some(r)); + let grid = (r.transform, w, h); + return Ok(Some(super::PartRead { raster: r, at: (0, 0), grid })); } let mut transform = geo.transform; // How many full-image pixels one pixel read spans, across and down. @@ -2029,6 +2053,8 @@ fn read_image( } } }; + // The grid read, whole, as a whole read of it places it. + let grid = (transform, w, h); // A part: its corner, and its size in the full image's pixels when it is coarser. let (w, h, overview) = match span { Some(span) => { @@ -2055,7 +2081,8 @@ fn read_image( if let Some(p) = &described { r.apply_pam(p, super::pam::GDAL_METADATA); } - Ok(Some(r)) + let at = span.map_or((0, 0), |s| (s.cols.0, s.rows.0)); + Ok(Some(super::PartRead { raster: r, at, grid })) } /// What turning a rotated or skewed image north up says ([`super::north_up`]): its pixels are @@ -3627,7 +3654,9 @@ mod tests { /// A part of a tiled file (#2865) is the pixels, place, no-data, system and band names of /// the whole file read at the same level then cut to it: the full image when the part fits, /// the finest overview whose part does when it doesn't, and every other pixel of a file - /// without overviews. Only the tiles that hold it are read. + /// without overviews (a file whose size two doesn't divide too, whose last pixel read passes + /// its edge). It covers all the ground asked for, says where it lies in the grid read, and + /// only the tiles that hold it are read. #[test] fn a_part_is_the_whole_file_read_at_its_level_then_cut_to_it() { use super::super::Part; @@ -3653,51 +3682,60 @@ mod tests { Example { int8: true, ..base }, Example { bottom_up: true, ..base }, Example { no_overviews: true, ..base }, + Example { size: 1001, no_overviews: true, ..base }, ]; - // Columns 307 to 431 and rows 563 to 922 of the full image. - let part = Part::new(0.3, 0.55, 0.42, 0.9).unwrap(); + // The parts: one inside, and one reaching the image's right and bottom edges. + let parts = [Part::new(0.3, 0.55, 0.42, 0.9).unwrap(), Part::new(0.987, 0.9, 1.0, 1.0).unwrap()]; for e in cases { let file = example_with(&e); - let bands = usize::from(e.bands); - // The part fits at full size; then only at half size (an overview, or every other - // pixel); the whole file is read at that size to compare. - for (part_max, whole_max, size) in [(200_000 * bands, 1024 * 1024 * bands, 1024), (20_000 * bands, 512 * 512 * bands, 512)] { - let read = std::rc::Rc::new(std::cell::Cell::new(0)); - let r = read_part(reader(Counting(std::io::Cursor::new(file.clone()), read.clone())).unwrap(), "part", part_max, part) - .unwrap() - .expect("read by part"); - let whole = read_limited(reader(std::io::Cursor::new(&file)).unwrap(), "whole", whole_max, None).unwrap(); - assert_eq!(whole.width, size, "{e:?}"); - let at = |v: f64, origin: f64, px: f64| ((v - origin) / px).round() as i64; - let (c0, r0) = ( - at(r.transform.origin_x, whole.transform.origin_x, whole.transform.pixel_width), - at(r.transform.origin_y, whole.transform.origin_y, whole.transform.pixel_height), - ); - let scale = 1024 / size; - let expected = (307 / scale, (431u32).div_ceil(scale), 563 / scale, (922u32).div_ceil(scale)); - let got = (c0 as u32, c0 as u32 + r.width, r0 as u32, r0 as u32 + r.height); - assert_eq!(got, expected, "{e:?} at {size}"); - assert_eq!( - (r.transform.pixel_width, r.transform.pixel_height), - (whole.transform.pixel_width, whole.transform.pixel_height) - ); - assert_eq!( - (r.crs, r.nodata, r.color.clone(), r.data_type.clone(), r.step), - (whole.crs, whole.nodata, whole.color.clone(), whole.data_type.clone(), whole.step) - ); - let names = |r: &Raster| r.bands.iter().map(|b| (b.name.clone(), b.wavelength)).collect::>(); - assert_eq!(names(&r), names(&whole), "{e:?}"); - for b in 0..r.band_count() { - for y in 0..i64::from(r.height) { - for x in 0..i64::from(r.width) { - assert_eq!(r.value(b, x, y), whole.value(b, x + c0, y + r0), "{e:?} at {size}: band {b} at {x},{y}"); + let (bands, size) = (usize::from(e.bands), e.size as usize); + for part in parts { + // The part fits at full size; then only at half size (an overview, or every other + // pixel); the whole file is read at that size to compare. + let (pw, ph) = part.span((e.size, e.size), (f64::from(e.size), f64::from(e.size))).size(); + let at_full = pw as usize * ph as usize * bands; + for (part_max, whole_max, half) in + [(at_full, size * size * bands, false), (at_full - 1, size.div_ceil(2).pow(2) * bands, true)] + { + let read = std::rc::Rc::new(std::cell::Cell::new(0)); + let p = read_part(reader(Counting(std::io::Cursor::new(file.clone()), read.clone())).unwrap(), "part", part_max, part) + .unwrap() + .expect("read by part"); + let whole = read_limited(reader(std::io::Cursor::new(&file)).unwrap(), "whole", whole_max, None).unwrap(); + let r = &p.raster; + let at = format!("{e:?}, {part:?}, half {half}"); + assert_eq!(whole.width as usize, if half { size.div_ceil(2) } else { size }, "{at}"); + assert_eq!(p.grid, (whole.transform, whole.width, whole.height), "{at}"); + let (c0, r0) = (i64::from(p.at.0), i64::from(p.at.1)); + let gt = r.transform; + assert!((gt.origin_x - whole.transform.to_world(c0 as f64, r0 as f64).x).abs() < 1e-9, "{at}"); + assert_eq!((gt.pixel_width, gt.pixel_height), (whole.transform.pixel_width, whole.transform.pixel_height)); + // Every place asked for is on it: the part of the full image's ground, in the + // grid's pixels (the full image's size over how many of its pixels one spans). + let (sx, sy) = whole.file_pixels(); + let (ex, ey) = (f64::from(e.size) / sx, f64::from(e.size) / sy); + assert!(c0 as f64 <= part.left * ex + 1e-9, "{at}: starts past the part"); + assert!(c0 as f64 + f64::from(r.width) >= part.right * ex - 1e-9, "{at}: ends before the part does"); + assert!(r0 as f64 <= part.top * ey + 1e-9, "{at}: starts below the part"); + assert!(r0 as f64 + f64::from(r.height) >= part.bottom * ey - 1e-9, "{at}: ends above the part's end"); + assert_eq!( + (r.crs, r.nodata, r.color.clone(), r.data_type.clone(), r.step), + (whole.crs, whole.nodata, whole.color.clone(), whole.data_type.clone(), whole.step) + ); + let names = |r: &Raster| r.bands.iter().map(|b| (b.name.clone(), b.wavelength)).collect::>(); + assert_eq!(names(r), names(&whole), "{at}"); + for b in 0..r.band_count() { + for y in 0..i64::from(r.height) { + for x in 0..i64::from(r.width) { + assert_eq!(r.value(b, x, y), whole.value(b, x + c0, y + r0), "{at}: band {b} at {x},{y}"); + } } } + // Its size in the full image's pixels when coarser, as an overview of it. + let scale = |n: u32, by: f64| (f64::from(n) * by).round() as u32; + assert_eq!(r.overview, half.then(|| (scale(r.width, sx), scale(r.height, sy))), "{at}"); + assert!(read.get() < file.len() as u64 / 4, "{at}: {} bytes of {} read", read.get(), file.len()); } - // Its size in the full image's pixels when coarser, as an overview of it. - let full = |n: u32| n * scale; - assert_eq!(r.overview, (size < 1024).then(|| (full(r.width), full(r.height))), "{e:?}"); - assert!(read.get() < file.len() as u64 / 4, "{e:?} at {size}: {} bytes of {} read", read.get(), file.len()); } } } diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 78ee3797f6..62fc9503dc 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -1451,26 +1451,40 @@ impl Part { } /// The columns and rows of a grid `w` × `h` the part covers, out to whole pixels: one at - /// least, of a grid that has any. - fn span(self, w: u32, h: u32) -> geotiff::Span { - let edges = |a: f64, b: f64, n: u32| { - let n64 = f64::from(n); - let start = ((a * n64).floor() as u32).min(n.saturating_sub(1)); - (start, ((b * n64).ceil() as u32).min(n).max(start.saturating_add(1).min(n))) + /// least, of a grid that has any. The image spans `extent` of the grid's pixels each way: + /// its size, or for every k-th pixel of it its size over k, which the grid's last pixel + /// passes when k doesn't divide it. + fn span(self, (w, h): (u32, u32), extent: (f64, f64)) -> geotiff::Span { + let edges = |a: f64, b: f64, n: u32, units: f64| { + let start = ((a * units).floor() as u32).min(n.saturating_sub(1)); + (start, ((b * units).ceil() as u32).min(n).max(start.saturating_add(1).min(n))) }; - geotiff::Span { cols: edges(self.left, self.right, w), rows: edges(self.top, self.bottom, h) } + geotiff::Span { cols: edges(self.left, self.right, w, extent.0), rows: edges(self.top, self.bottom, h, extent.1) } } } +/// A part of a raster file read ([`read_path_part`]): its pixels, and where they lie in the grid +/// they were read from, so a window found on that grid ([`GeoTransform::to_pixel`]) is placed on +/// the part in whole pixels, without rounding again. +pub struct PartRead { + pub raster: Raster, + /// The part's first column and row in the grid read. + pub at: (u32, u32), + /// The grid read (the full image, an overview, or every k-th pixel of it), whole: its + /// transform, columns and rows, as a read of all of it places them. + pub grid: (GeoTransform, u32, u32), +} + /// `part` of the GeoTIFF at `path`, as [`read_path`] reads the file but holding only that part, -/// at the finest level whose part fits [`max_samples`]: the full image when it does, read from -/// the strips or tiles that hold it alone. The `.aux.xml` beside it is applied as it is to the -/// whole file. `Ok(None)` when the file isn't read so: not a GeoTIFF, one with a world file -/// beside it, or one [`geotiff`] can't read by part (rotated, skewed or without coordinates). -/// Read the whole file then. A part read at a coarser level says it with `overview`, the part's -/// size in the file's pixels. +/// at the finest level whose part fits `max` samples: the full image when it does, read from the +/// strips or tiles that hold it alone. The `.aux.xml` beside it is applied as it is to the whole +/// file. `Ok(None)` when the file isn't read so: not a GeoTIFF, one with a world file beside it, +/// one [`geotiff`] can't read by part (rotated, skewed or without coordinates), or, with +/// `same_as`, no longer the revision of the file that raster was read from, which the part was +/// found on. Read the whole file then. A part read at a coarser level says it with `overview`, +/// the part's size in the file's pixels. #[cfg(not(target_arch = "wasm32"))] -pub fn read_path_part(path: &Path, part: Part) -> Result> { +pub fn read_path_part(path: &Path, part: Part, max: usize, same_as: Option<&Raster>) -> Result> { let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); if !matches!(ext.as_str(), "tif" | "tiff") { return Ok(None); @@ -1485,7 +1499,8 @@ pub fn read_path_part(path: &Path, part: Part) -> Result> { let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("raster").to_string(); let pam = pam::read(path); let sidecar_nodata = pam.as_ref().and_then(pam::Pam::nodata); - let Some(mut r) = geotiff::read_file_part(path, &name, sidecar_nodata, part)? else { return Ok(None) }; + let Some(mut read) = geotiff::read_file_part(path, &name, sidecar_nodata, part, max, same_as)? else { return Ok(None) }; + let r = &mut read.raster; // As [`read_path_placing`]: read again with the no-data the bands it has give, so the // rounded count leaves out just its pixels. let applied = pam.as_ref().map(|p| p.nodata_within(r.bands.len())); @@ -1494,15 +1509,15 @@ pub fn read_path_part(path: &Path, part: Part) -> Result> { && r.nodata.is_none() && matches!(r.data_type.as_str(), "UInt32" | "Int32" | "UInt64" | "Int64" | "Float64") { - drop(r); - let Some(again) = geotiff::read_file_part(path, &name, nd, part)? else { return Ok(None) }; - r = again; + drop(read); + let Some(again) = geotiff::read_file_part(path, &name, nd, part, max, same_as)? else { return Ok(None) }; + read = again; } if let Some(p) = &pam { - r.apply_pam(p, pam::SIDECAR); + read.raster.apply_pam(p, pam::SIDECAR); } - r.source = Some(path.display().to_string()); - Ok(Some(r)) + read.raster.source = Some(path.display().to_string()); + Ok(Some(read)) } /// A picture at `path` with the world file beside it applied (#2075). A scan is placed by it, in diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 4f5dee81ef..0c526fa47a 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1615,7 +1615,7 @@ pub(crate) fn tiled_inputs( } let (r, count) = read_tiled(&l.name, path)?; held.push(count); - said.push((l.name.clone(), r.clone())); + said.push(ReadNote::of(&l.name, &r)); read.insert(key, r); } } @@ -1630,37 +1630,57 @@ pub(crate) fn tiled_inputs( Ok(read) } -/// `part` of the raster file read in place at `path` (layer `name`'s), read from the file at the -/// finest level whose part the run can hold, in its turn ([`tiled_turn`]), with its count in -/// [`rustgis_data::memory::held`]; `None` when the file can't be read by part (read it whole with -/// [`read_tiled`]). Never kept for a batch: another item's part is another part. +/// `part` of the raster file read in place at `path` (layer `name`'s, which holds `held`), read +/// from the file at the finest level whose part fits `max` samples, in its turn ([`tiled_turn`]), +/// with its count in [`rustgis_data::memory::held`]; `None` when the file can't be read by part, +/// or is no longer the revision `held` was read from (read it whole with [`read_tiled`]). Never +/// kept for a batch: another item's part is another part. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read_tiled_part( name: &str, path: &str, part: rustgis_data::raster::Part, -) -> Result, std::sync::Arc)>, String> { + max: usize, + held: &rustgis_data::raster::Raster, +) -> Result)>, String> { let _turn = tiled_turn().map_err(|e| format!("{name}: {e}"))?; - let Some(r) = rustgis_data::raster::read_path_part(std::path::Path::new(path), part).map_err(|e| format!("{name}: {e}"))? else { - return Ok(None); - }; - let bytes: usize = r.bands.iter().map(|b| b.data.len().saturating_mul(4)).sum(); - Ok(Some((std::sync::Arc::new(r), std::sync::Arc::new(rustgis_data::memory::Holding::of(bytes as u64))))) + let read = + rustgis_data::raster::read_path_part(std::path::Path::new(path), part, max, Some(held)).map_err(|e| format!("{name}: {e}"))?; + let Some(read) = read else { return Ok(None) }; + let bytes: usize = read.raster.bands.iter().map(|b| b.data.len().saturating_mul(4)).sum(); + Ok(Some((read, std::sync::Arc::new(rustgis_data::memory::Holding::of(bytes as u64))))) +} + +/// What a run says of a raster file read in place it read again from its file ([`read_tiled`]): +/// its layer's name, how many of its values were rounded as it was read, and, read coarser than +/// the file, its size and the file's (or the part's) in the file's pixels. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone)] +pub(crate) struct ReadNote { + name: String, + rounded: u64, + overview: Option<((u32, u32), (u32, u32))>, +} + +#[cfg(not(target_arch = "wasm32"))] +impl ReadNote { + pub(crate) fn of(name: &str, r: &rustgis_data::raster::Raster) -> ReadNote { + ReadNote { name: name.to_string(), rounded: r.rounded.iter().sum(), overview: r.overview.map(|full| ((r.width, r.height), full)) } + } } /// What a run says of the raster files read in place it read again from their file -/// ([`read_tiled`]), each with its layer's name: one notice of each kind, naming each raster. -/// `whose` says whose results are built on values rounded as they were read. +/// ([`read_tiled`]): one notice of each kind, naming each raster. `whose` says whose results are +/// built on values rounded as they were read. #[cfg(not(target_arch = "wasm32"))] -pub(crate) fn tiled_read_notes(read: &[(String, std::sync::Arc)], whose: &str) -> Vec { +pub(crate) fn tiled_read_notes(read: &[ReadNote], whose: &str) -> Vec { let (mut rounded, mut overviews) = (Vec::new(), Vec::new()); - for (name, r) in read { - let n: u64 = r.rounded.iter().sum(); - if n > 0 { + for ReadNote { name, rounded: n, overview } in read { + if *n > 0 { rounded.push(format!("{name} {n}")); } - if let Some((fw, fh)) = r.overview { - overviews.push(format!("{name} at its {} × {} overview of the {fw} × {fh} raster", r.width, r.height)); + if let Some(((w, h), (fw, fh))) = overview { + overviews.push(format!("{name} at its {w} × {h} overview of the {fw} × {fh} raster")); } } let mut notes = Vec::new(); diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 8c1bfa8984..783c0a4130 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1717,7 +1717,7 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result 0 { messages.push(format!("{pl}: skipped {skipped} feature(s) with invalid polygon geometry")); @@ -1757,14 +1757,31 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result r.read_part(part)?, + // A third of what a run holds: the part, its clip, and the clip's file at once. + let input = match part { + Some(part) => r.read_part(part, rustgis_data::raster::max_samples() / 3)?, None => r.read()?, }; - let (cols, rows) = extent_window(&r, &e)?; - super::workflows::made(clip_window(&r, cols, rows, None, out)?, None) + // The part goes before the clip is written as a file. + let clipped = match part_window(&input, bounds, &e)? { + Some((cols, rows, corner)) => { + let clipped = clip_window(&input, cols, rows, None, corner, out)?; + drop(input); + clipped + } + // A part that doesn't hold all of the window (the file isn't as the layer + // found it): the whole file, as before. + None => { + drop(input); + let whole = r.read()?; + let (cols, rows) = extent_window(&whole, &e)?; + clip_window(&whole, cols, rows, None, None, out)? + } + }; + super::workflows::made(clipped, None) })) } "resample" => { @@ -1834,17 +1851,44 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result Result<(std::ops::Range, std::ops::Range), String> { - let px = edge_pixels(r, e).ok_or("the extent can't be placed on the raster")?; + grid_window(r, &r.transform, (r.width, r.height), r.extent(), e) +} + +/// [`extent_window`] on a grid of `r`'s system: its transform `gt` and size, its ground `bounds`. +fn grid_window( + r: &Raster, + gt: &GeoTransform, + (w, h): (u32, u32), + bounds: Extent, + e: &Extent, +) -> Result<(std::ops::Range, std::ops::Range), String> { + let px = edge_pixels_on(r, gt, bounds, e).ok_or("the extent can't be placed on the raster")?; let c0 = px.iter().map(|p| p.0).fold(f64::INFINITY, f64::min).floor().max(0.0) as u32; - let c1 = px.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max).ceil().min(r.width as f64) as u32; + let c1 = px.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max).ceil().min(f64::from(w)) as u32; let r0 = px.iter().map(|p| p.1).fold(f64::INFINITY, f64::min).floor().max(0.0) as u32; - let r1 = px.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max).ceil().min(r.height as f64) as u32; + let r1 = px.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max).ceil().min(f64::from(h)) as u32; if c1 <= c0 || r1 <= r0 { return Err("the extent doesn't overlap the raster".into()); } Ok((c0..c1, r0..r1)) } +/// [`extent_window`] of a part of a file ([`super::workflows::Input::read_part`]), found on the +/// whole grid it was read from (whose ground is `bounds`), as a whole read finds it, then moved +/// onto the part in whole pixels, with its corner on that grid: `None` when the part doesn't hold +/// all of it. A raster read whole gives its own, and no corner. +fn part_window(r: &super::workflows::Read, bounds: Extent, e: &Extent) -> Result, String> { + let Some(((c, row), (gt, w, h))) = r.place() else { return extent_window(r, e).map(|(cols, rows)| Some((cols, rows, None))) }; + let (cols, rows) = grid_window(r, >, (w, h), bounds, e)?; + let inside = cols.start >= c && rows.start >= row && cols.end <= c + r.width && rows.end <= row + r.height; + let corner = gt.to_world(f64::from(cols.start), f64::from(rows.start)); + Ok(inside.then(|| (cols.start - c..cols.end - c, rows.start - row..rows.end - row, Some(corner)))) +} + +/// A window of a raster's columns and rows, and its corner when found on another grid +/// ([`part_window`]). +type PartWindow = (std::ops::Range, std::ops::Range, Option); + /// The part of a raster's ground under a longitude/latitude box ([`extent_window`]), as fractions /// of its width and height, a pixel of its file wider each way so a file read at a finer level /// than `r` still holds every pixel the box touches: the part a clip of it reads. @@ -2090,12 +2134,14 @@ fn mosaic_matches(first: &Raster, r: &Raster) -> Result<(), String> { /// the cells outside its source (`rustgis_analysis::warp`): in a raster with alpha they are /// see-through, 0 in every band, and a three-band colour raster with neither alpha nor no-data gains an alpha /// band for them, so an 8-bit image stays 8-bit (#1731). Otherwise they are its no-data, or -/// -3.4e38 when it has none. +/// -3.4e38 when it has none. Its corner is `corner` when given (found on the whole grid a part of +/// a file was read from, as a clip of all of it places it), else the window's on `r`. fn clip_window( r: &Raster, cols: std::ops::Range, rows: std::ops::Range, mask: Option<&[bool]>, + corner: Option, name: String, ) -> Result { r.require_coordinates()?; @@ -2128,7 +2174,7 @@ fn clip_window( let valued = |i: usize| r.bands.iter().any(|b| b.data.get(at(i)).is_some_and(|v| !v.is_nan())); bands.push(rasterops::per_index(wu * h as usize, wu, n, || (), |_, i| if kept(i) && valued(i) { 255.0 } else { 0.0 })?); } - let o = r.transform.to_world(f64::from(cols.start), f64::from(rows.start)); + let o = corner.unwrap_or_else(|| r.transform.to_world(f64::from(cols.start), f64::from(rows.start))); let gt = GeoTransform { origin_x: o.x, origin_y: o.y, ..r.transform }; let color = if add_alpha { ColorHint::Rgb { alpha: true } } else { r.color.clone() }; let mut out = Raster::new(name, w, h, bands, gt, r.crs, nodata, color, r.data_type.clone()).map_err(|e| e.to_string())?; @@ -2156,6 +2202,11 @@ fn point(v: &Value) -> Result { /// A window made from the places left would leave out part of the box, so a box reaching that far /// is first cut to the raster's own bounds, where its system takes places. fn edge_pixels(r: &Raster, e: &Extent) -> Option> { + edge_pixels_on(r, &r.transform, r.extent(), e) +} + +/// [`edge_pixels`] on a grid of `r`'s system: its transform `gt`, its ground `bounds`. +fn edge_pixels_on(r: &Raster, gt: &GeoTransform, bounds: Extent, e: &Extent) -> Option> { const N: u32 = 16; let at = |e: &Extent| -> Option> { (0..=N) @@ -2166,11 +2217,11 @@ fn edge_pixels(r: &Raster, e: &Extent) -> Option> { }) // Robinson's widest parallel is the equator, even when the uniform samples miss it. .chain([Coord::new(e.min_x, 0.0_f64.max(e.min_y).min(e.max_y)), Coord::new(e.max_x, 0.0_f64.max(e.min_y).min(e.max_y))]) - .map(|c| r.transformer().from_lonlat(c).map(|w| r.transform.to_pixel(w))) + .map(|c| r.transformer().from_lonlat(c).map(|w| gt.to_pixel(w))) .collect() }; at(e).or_else(|| { - let b = r.extent(); + let b = bounds; let (w, s, east, n) = (e.min_x.max(b.min_x), e.min_y.max(b.min_y), e.max_x.min(b.max_x), e.max_y.min(b.max_y)); (w <= east && s <= n).then(|| at(&Extent::new(w, s, east, n))).flatten() }) diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 1168a7cd33..19abdaedd3 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -156,48 +156,54 @@ impl Input { if let Some((name, path)) = &self.file && RUN_READS.with(|r| r.borrow().is_some()) { - let kept = RUN_READS.with(|r| r.borrow().as_ref().and_then(|read| read.iter().find(|k| k.0.as_ref() == Some(path)).cloned())); - let (_, _, raster, count) = match kept { + let kept = RUN_READS.with(|r| { + r.borrow().as_ref().and_then(|read| read.iter().find(|k| k.path.as_ref() == Some(path)).and_then(|k| k.kept.clone())) + }); + let (raster, count) = match kept { Some(k) => k, None => { let (raster, count) = super::gp::read_tiled(name, path)?; - let k = (Some(path.clone()), name.clone(), raster, count); + let note = super::gp::ReadNote::of(name, &raster); RUN_READS.with(|r| { if let Some(read) = r.borrow_mut().as_mut() { - read.push(k.clone()); + read.push(RunRead { path: Some(path.clone()), kept: Some((raster.clone(), count.clone())), note }); } }); - k + (raster, count) } }; - return Ok(Read { raster, _count: Some(count) }); + return Ok(Read { raster, _count: Some(count), place: None }); } // The browser has no files to read by path: none is read in place from one there. #[cfg(target_arch = "wasm32")] let _ = &self.file; - Ok(Read { raster: self.held.clone(), _count: None }) + Ok(Read { raster: self.held.clone(), _count: None, place: None }) } /// The raster the work reads, for work that uses only `part` of it: within a run, a layer read /// in place from a GeoTIFF on this computer reads only that part of its file, out to whole - /// pixels, at the finest level whose part the run can hold, decoding only the strips or tiles - /// that hold it (`rustgis_data::raster::read_path_part`). A part isn't kept for the run's other - /// inputs. A file that can't be read by part, and any other layer, give [`Input::read`]. - pub(crate) fn read_part(&self, part: rustgis_data::raster::Part) -> Result { + /// pixels, at the finest level whose part fits `max` samples, decoding only the strips or tiles + /// that hold it (`rustgis_data::raster::read_path_part`), with where it lies in the grid read + /// ([`Read::place`]). A part isn't kept for the run's other inputs: only what the run says of + /// it is. A file that can't be read by part, or that is no longer the one the layer was read + /// from, and any other layer, give [`Input::read`]. + pub(crate) fn read_part(&self, part: rustgis_data::raster::Part, max: usize) -> Result { #[cfg(not(target_arch = "wasm32"))] if let Some((name, path)) = &self.file && RUN_READS.with(|r| r.borrow().is_some()) - && let Some((raster, count)) = super::gp::read_tiled_part(name, path, part)? + && let Some((read, count)) = super::gp::read_tiled_part(name, path, part, max, &self.held)? { + let rustgis_data::raster::PartRead { raster, at, grid } = read; + let note = super::gp::ReadNote::of(name, &raster); RUN_READS.with(|r| { if let Some(read) = r.borrow_mut().as_mut() { - read.push((None, name.clone(), raster.clone(), count.clone())); + read.push(RunRead { path: None, kept: None, note }); } }); - return Ok(Read { raster, _count: Some(count) }); + return Ok(Read { raster: std::sync::Arc::new(raster), _count: Some(count), place: Some((at, grid)) }); } #[cfg(target_arch = "wasm32")] - let _ = part; + let _ = (part, max); self.read() } } @@ -207,6 +213,20 @@ impl Input { pub(crate) struct Read { raster: std::sync::Arc, _count: Option>, + /// For a part of a file ([`Input::read_part`]), its first column and row in the grid read, + /// and that grid whole: its transform, columns and rows. + place: Option, +} + +/// Where a part of a raster file lies in the grid it was read from ([`Read::place`]). +pub(crate) type Place = ((u32, u32), (rustgis_data::raster::GeoTransform, u32, u32)); + +impl Read { + /// Where the raster lies in the grid it was read from, for a part of a file + /// ([`Input::read_part`]); `None` for a raster read whole. + pub(crate) fn place(&self) -> Option { + self.place + } } impl std::ops::Deref for Read { @@ -217,10 +237,15 @@ impl std::ops::Deref for Read { } /// A raster file read in place that a run read ([`RUN_READS`]): its path (`None` for a part of it, -/// [`Input::read_part`], which no other input takes), its layer's name, the raster read and its -/// count in [`rustgis_data::memory::held`]. +/// [`Input::read_part`], which no other input takes), the raster read and its count in +/// [`rustgis_data::memory::held`], kept for the run's other inputs naming the file (not a part's), +/// and what the run says of it. #[cfg(not(target_arch = "wasm32"))] -type RunRead = (Option, String, std::sync::Arc, std::sync::Arc); +struct RunRead { + path: Option, + kept: Option<(std::sync::Arc, std::sync::Arc)>, + note: super::gp::ReadNote, +} #[cfg(not(target_arch = "wasm32"))] thread_local! { @@ -273,7 +298,7 @@ pub(crate) fn reading_files(name: &str, work: impl FnOnce() -> Result)> = read.into_iter().map(|(_, name, r, _)| (name, r)).collect(); + let read: Vec = read.into_iter().map(|r| r.note).collect(); let notes: Vec = super::gp::tiled_read_notes(&read, "its").into_iter().map(|n| format!("{name}: {n}")).collect(); if notes.is_empty() { return Ok(made); diff --git a/crates/engine/src/tests/tiled_files.rs b/crates/engine/src/tests/tiled_files.rs index a9a05828a5..9117bd3727 100644 --- a/crates/engine/src/tests/tiled_files.rs +++ b/crates/engine/src/tests/tiled_files.rs @@ -359,34 +359,84 @@ fn a_run_that_panics_reads_no_file_after_it() { assert_eq!(input.read().unwrap().width, 512, "the overview the layer holds, after the run"); } +/// A 1000-pixel RGB tiled GeoTIFF over 10°–11° E, 45°–46° N, its pixels a thousandth of a degree +/// (which binary fractions don't hold exactly, so a window found from another origin can round +/// another way), with its 500 overview: values vary across, down, and pixel by pixel. +fn thousandths(dir: &std::path::Path) -> String { + const N: u32 = 1000; + let at = |f: fn(u32, u32) -> f32| (0..N * N).map(|i| f(i % N, i / N)).collect::>(); + let bands = vec![at(|x, y| ((x * 7 + y * 13) % 256) as f32), at(|x, _| (x / 4) as f32), at(|_, y| (y / 4) as f32)]; + let gt = GeoTransform { origin_x: 10.0, origin_y: 46.0, pixel_width: 0.001, pixel_height: -0.001 }; + let r = Raster::new("checks", N, N, bands, gt, Crs::LonLat, None, ColorHint::Rgb { alpha: false }, "UInt8").unwrap(); + let path = dir.join("checks.tif"); + let info = rustgis_data::raster::cogwrite::write_file(&r, 0, &path).unwrap(); + assert_eq!(info.levels, vec![(N, N), (N / 2, N / 2)], "the fixture's levels"); + path.display().to_string() +} + /// Clip by extent of a layer read in place reads only the part of its file under the extent -/// (#2865): the clip is the one made of the file held whole, and the file isn't read whole for it. +/// (#2865): the clip is the one made of the file held whole, to the pixel, and the file isn't +/// read whole for it. A file replaced since the layer read it is read whole, so the clip is of the +/// file as it is. #[cfg(not(target_arch = "wasm32"))] #[test] fn a_clip_by_extent_reads_only_its_part_of_a_tiled_file() { let d = dir("clip"); - let path = checkerboard(&d); - let clip = json!({"layer": "checks", "operation": "clip", "extent": [10.3, 45.55, 10.42, 45.9], "name": "clip"}); - // Held whole, as a file this size is. - let mut whole = Session::new(Project::default()); - whole.run("layer.addData", &json!({"path": path})).unwrap(); - assert!(!raster(&whole, "checks").tiled); - whole.run("raster.process", &clip).unwrap(); + let path = thousandths(&d); + let clip = |extent: [f64; 4]| json!({"layer": "checks", "operation": "clip", "extent": extent, "name": "clip"}); + // The same clip of the file held whole, as a file this size is. + let whole = |extent: [f64; 4]| { + // Held whole, whatever limit this thread has set meanwhile. + let limit = HELD_WHOLE.with(|c| c.replace(None)); + let mut whole = Session::new(Project::default()); + whole.run("layer.addData", &json!({"path": path})).unwrap(); + assert!(!raster(&whole, "checks").tiled); + whole.run("raster.process", &clip(extent)).unwrap(); + HELD_WHOLE.with(|c| c.set(limit)); + raster(&whole, "clip").data.clone().unwrap() + }; let _held = HeldWhole::at(1_000_000); let mut s = Session::new(Project::default()); s.run("layer.addData", &json!({"path": path})).unwrap(); assert!(raster(&s, "checks").tiled); let reads = || crate::cmd::gp::TILED_READS.with(std::cell::Cell::get); - let (before, mark) = (reads(), s.notice_mark()); - s.run("raster.process", &clip).unwrap(); - assert_eq!(reads(), before, "the file isn't read whole"); - let (got, want) = (raster(&s, "clip").data.clone().unwrap(), raster(&whole, "clip").data.clone().unwrap()); - // 0.12° by 0.35° of a 1024-pixel degree, at the file's full size. - assert_eq!((got.width, got.height, got.overview), (124, 359, None)); - assert_eq!((got.width, got.height, got.transform), (want.width, want.height, want.transform)); - for (g, w) in got.bands.iter().zip(&want.bands) { - assert!(g.data == w.data, "band {}", g.name); + let extents = + [[10.3, 45.55, 10.42, 45.9], [10.123, 45.456, 10.789, 45.9], [10.007, 45.003, 10.509, 45.611], [10.25, 45.5, 10.5, 45.75]]; + for extent in extents { + let (before, mark) = (reads(), s.notice_mark()); + s.run("layer.remove", &json!({"layer": "clip"})).ok(); + s.run("raster.process", &clip(extent)).unwrap(); + assert_eq!(reads(), before, "the file isn't read whole"); + let (got, want) = (raster(&s, "clip").data.clone().unwrap(), whole(extent)); + assert_eq!(got.overview, None, "{extent:?}: at the file's full size"); + assert_eq!((got.width, got.height, got.transform), (want.width, want.height, want.transform), "{extent:?}"); + for (g, w) in got.bands.iter().zip(&want.bands) { + assert!(g.data == w.data, "{extent:?}: band {}", g.name); + } + let notes = said(&s, mark); + assert!(!notes.iter().any(|n| n.contains("finest level")), "{notes:?}"); } - let notes = said(&s, mark); - assert!(!notes.iter().any(|n| n.contains("finest level")), "{notes:?}"); + // The file replaced by one a twentieth of a degree east: read whole, and clipped where it is. + const N: u32 = 1000; + let shifted = Raster::new( + "checks", + N, + N, + vec![(0..N * N).map(|i| (i % 251) as f32).collect()], + GeoTransform { origin_x: 10.05, origin_y: 46.0, pixel_width: 0.001, pixel_height: -0.001 }, + Crs::LonLat, + None, + ColorHint::Gray, + "UInt8", + ) + .unwrap(); + rustgis_data::raster::cogwrite::write_file(&shifted, 0, std::path::Path::new(&path)).unwrap(); + let extent = [10.3, 45.55, 10.42, 45.9]; + s.run("layer.remove", &json!({"layer": "clip"})).ok(); + let before = reads(); + s.run("raster.process", &clip(extent)).unwrap(); + assert_eq!(reads(), before + 1, "a replaced file is read whole"); + let (got, want) = (raster(&s, "clip").data.clone().unwrap(), whole(extent)); + assert_eq!((got.width, got.height, got.transform), (want.width, want.height, want.transform)); + assert!(got.bands[0].data == want.bands[0].data, "the clip is of the file as it is now"); } From 7805b36058f7b5d58593378f0e19bc8cf27bfdef Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 14:56:10 -0600 Subject: [PATCH 3/4] fix(raster): a part's window uses its own grid's bounds, its read planned in its turn - `PartRead` gives the bounds of the grid read: every k-th pixel's grid can pass the held overview's, and a box cut to those lost a column. - The file's revision is taken once and compared with the layer's, the same one the read is then checked against. - A part's limit is a share of what a run holds, planned once the read has its turn, with the reads before it counted. - What a run says of a part (an overview, rounded values) is said only once the clip uses it, not for a part put aside for the whole file. --- crates/data/src/raster/file_revision.rs | 5 ++ crates/data/src/raster/geotiff.rs | 14 +++-- crates/data/src/raster/mod.rs | 3 ++ crates/engine/src/cmd/gp.rs | 12 +++-- crates/engine/src/cmd/imagery.rs | 29 +++++----- crates/engine/src/cmd/workflows.rs | 70 +++++++++++++++++-------- 6 files changed, 89 insertions(+), 44 deletions(-) diff --git a/crates/data/src/raster/file_revision.rs b/crates/data/src/raster/file_revision.rs index 8363d998e4..085ef7a77a 100644 --- a/crates/data/src/raster/file_revision.rs +++ b/crates/data/src/raster/file_revision.rs @@ -73,6 +73,11 @@ impl super::Raster { original.check_metadata(&metadata) } + /// Whether this raster's pixels came from the file at `revision`, as it was then. + pub(crate) fn is_from(&self, revision: &FileRevision) -> bool { + matches!(&self.source_file, Some(Ok(original)) if original == revision) + } + /// Checks fresh metadata from this open handle against the original source. /// This does not verify that the live path still names the handle; check_original_file does. pub fn check_original_handle(&self, file: &std::fs::File) -> std::result::Result<(), String> { diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 4772228677..89ff03dbce 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1565,11 +1565,14 @@ pub(super) fn read_file_part( same_as: Option<&Raster>, ) -> Result> { let file = crate::provenance::open(path).map_err(err)?; + let revision = file.metadata().and_then(|metadata| super::file_revision::FileRevision::capture(&metadata)); // The part is of the image `same_as` was read from: of another, it would be another place. - if same_as.is_some_and(|r| r.check_original_handle(&file).is_err()) { + // The revision compared is the one the read is checked against as it goes. + if let Some(r) = same_as + && !revision.as_ref().is_ok_and(|rev| r.is_from(rev)) + { return Ok(None); } - let revision = file.metadata().and_then(|metadata| super::file_revision::FileRevision::capture(&metadata)); read_file_revision_part(path, name, sidecar_nodata, file, revision, Some(part), max) } @@ -1989,8 +1992,8 @@ fn read_image( if let Some(p) = &described { r.apply_pam(p, super::pam::GDAL_METADATA); } - let grid = (r.transform, w, h); - return Ok(Some(super::PartRead { raster: r, at: (0, 0), grid })); + let (grid, bounds) = ((r.transform, w, h), r.extent()); + return Ok(Some(super::PartRead { raster: r, at: (0, 0), grid, bounds })); } let mut transform = geo.transform; // How many full-image pixels one pixel read spans, across and down. @@ -2082,7 +2085,8 @@ fn read_image( r.apply_pam(p, super::pam::GDAL_METADATA); } let at = span.map_or((0, 0), |s| (s.cols.0, s.rows.0)); - Ok(Some(super::PartRead { raster: r, at, grid })) + let bounds = if span.is_some() { super::extent_of(&grid.0, r.transformer(), grid.1, grid.2) } else { r.extent() }; + Ok(Some(super::PartRead { raster: r, at, grid, bounds })) } /// What turning a rotated or skewed image north up says ([`super::north_up`]): its pixels are diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 62fc9503dc..311b57b86b 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -1473,6 +1473,9 @@ pub struct PartRead { /// The grid read (the full image, an overview, or every k-th pixel of it), whole: its /// transform, columns and rows, as a read of all of it places them. pub grid: (GeoTransform, u32, u32), + /// That grid's longitude/latitude bounds, as [`Raster::extent`] finds a raster's: every k-th + /// pixel's grid can pass the image's edge. + pub bounds: Extent, } /// `part` of the GeoTIFF at `path`, as [`read_path`] reads the file but holding only that part, diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 0c526fa47a..f38bcd3fdd 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1631,19 +1631,21 @@ pub(crate) fn tiled_inputs( } /// `part` of the raster file read in place at `path` (layer `name`'s, which holds `held`), read -/// from the file at the finest level whose part fits `max` samples, in its turn ([`tiled_turn`]), -/// with its count in [`rustgis_data::memory::held`]; `None` when the file can't be read by part, -/// or is no longer the revision `held` was read from (read it whole with [`read_tiled`]). Never -/// kept for a batch: another item's part is another part. +/// from the file at the finest level whose part fits `1 / share` of what a run can hold, in its +/// turn ([`tiled_turn`]), with its count in [`rustgis_data::memory::held`]; `None` when the file +/// can't be read by part, or is no longer the revision `held` was read from (read it whole with +/// [`read_tiled`]). Never kept for a batch: another item's part is another part. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read_tiled_part( name: &str, path: &str, part: rustgis_data::raster::Part, - max: usize, + share: usize, held: &rustgis_data::raster::Raster, ) -> Result)>, String> { let _turn = tiled_turn().map_err(|e| format!("{name}: {e}"))?; + // Planned in its turn, with what the reads before it hold counted. + let max = rustgis_data::raster::max_samples() / share.max(1); let read = rustgis_data::raster::read_path_part(std::path::Path::new(path), part, max, Some(held)).map_err(|e| format!("{name}: {e}"))?; let Some(read) = read else { return Ok(None) }; diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 783c0a4130..69fd1119df 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1757,17 +1757,17 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result r.read_part(part, rustgis_data::raster::max_samples() / 3)?, + Some(part) => r.read_part(part, 3)?, None => r.read()?, }; // The part goes before the clip is written as a file. - let clipped = match part_window(&input, bounds, &e)? { + let clipped = match part_window(&input, &e)? { Some((cols, rows, corner)) => { + input.used(); let clipped = clip_window(&input, cols, rows, None, corner, out)?; drop(input); clipped @@ -1874,15 +1874,20 @@ fn grid_window( } /// [`extent_window`] of a part of a file ([`super::workflows::Input::read_part`]), found on the -/// whole grid it was read from (whose ground is `bounds`), as a whole read finds it, then moved -/// onto the part in whole pixels, with its corner on that grid: `None` when the part doesn't hold -/// all of it. A raster read whole gives its own, and no corner. -fn part_window(r: &super::workflows::Read, bounds: Extent, e: &Extent) -> Result, String> { - let Some(((c, row), (gt, w, h))) = r.place() else { return extent_window(r, e).map(|(cols, rows)| Some((cols, rows, None))) }; - let (cols, rows) = grid_window(r, >, (w, h), bounds, e)?; - let inside = cols.start >= c && rows.start >= row && cols.end <= c + r.width && rows.end <= row + r.height; - let corner = gt.to_world(f64::from(cols.start), f64::from(rows.start)); - Ok(inside.then(|| (cols.start - c..cols.end - c, rows.start - row..rows.end - row, Some(corner)))) +/// whole grid it was read from, as a whole read finds it, then moved onto the part in whole +/// pixels, with its corner on that grid: `None` when the part doesn't hold all of it. A raster +/// read whole gives its own, and no corner. +fn part_window(r: &super::workflows::Read, e: &Extent) -> Result, String> { + // Only the desktop reads a part of a file. + #[cfg(not(target_arch = "wasm32"))] + if let Some(place) = r.place() { + let ((c, row), (gt, w, h)) = (place.at, place.grid); + let (cols, rows) = grid_window(r, >, (w, h), place.bounds, e)?; + let inside = cols.start >= c && rows.start >= row && cols.end <= c + r.width && rows.end <= row + r.height; + let corner = gt.to_world(f64::from(cols.start), f64::from(rows.start)); + return Ok(inside.then(|| (cols.start - c..cols.end - c, rows.start - row..rows.end - row, Some(corner)))); + } + extent_window(r, e).map(|(cols, rows)| Some((cols, rows, None))) } /// A window of a raster's columns and rows, and its corner when found on another grid diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 19abdaedd3..43e3b5f347 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -177,33 +177,34 @@ impl Input { // The browser has no files to read by path: none is read in place from one there. #[cfg(target_arch = "wasm32")] let _ = &self.file; - Ok(Read { raster: self.held.clone(), _count: None, place: None }) + Ok(Read { + raster: self.held.clone(), + _count: None, + #[cfg(not(target_arch = "wasm32"))] + place: None, + }) } /// The raster the work reads, for work that uses only `part` of it: within a run, a layer read /// in place from a GeoTIFF on this computer reads only that part of its file, out to whole - /// pixels, at the finest level whose part fits `max` samples, decoding only the strips or tiles - /// that hold it (`rustgis_data::raster::read_path_part`), with where it lies in the grid read - /// ([`Read::place`]). A part isn't kept for the run's other inputs: only what the run says of - /// it is. A file that can't be read by part, or that is no longer the one the layer was read - /// from, and any other layer, give [`Input::read`]. - pub(crate) fn read_part(&self, part: rustgis_data::raster::Part, max: usize) -> Result { + /// pixels, at the finest level whose part fits `1 / share` of what the run can hold, decoding + /// only the strips or tiles that hold it (`rustgis_data::raster::read_path_part`), with where + /// it lies in the grid read ([`Read::place`]). A part isn't kept for the run's other inputs, + /// and the run says what it says of it only once the work uses it ([`Read::used`]). A file + /// that can't be read by part, or that is no longer the one the layer was read from, and any + /// other layer, give [`Input::read`]. + pub(crate) fn read_part(&self, part: rustgis_data::raster::Part, share: usize) -> Result { #[cfg(not(target_arch = "wasm32"))] if let Some((name, path)) = &self.file && RUN_READS.with(|r| r.borrow().is_some()) - && let Some((read, count)) = super::gp::read_tiled_part(name, path, part, max, &self.held)? + && let Some((read, count)) = super::gp::read_tiled_part(name, path, part, share, &self.held)? { - let rustgis_data::raster::PartRead { raster, at, grid } = read; + let rustgis_data::raster::PartRead { raster, at, grid, bounds } = read; let note = super::gp::ReadNote::of(name, &raster); - RUN_READS.with(|r| { - if let Some(read) = r.borrow_mut().as_mut() { - read.push(RunRead { path: None, kept: None, note }); - } - }); - return Ok(Read { raster: std::sync::Arc::new(raster), _count: Some(count), place: Some((at, grid)) }); + return Ok(Read { raster: std::sync::Arc::new(raster), _count: Some(count), place: Some(Place { at, grid, bounds, note }) }); } #[cfg(target_arch = "wasm32")] - let _ = (part, max); + let _ = (part, share); self.read() } } @@ -213,19 +214,44 @@ impl Input { pub(crate) struct Read { raster: std::sync::Arc, _count: Option>, - /// For a part of a file ([`Input::read_part`]), its first column and row in the grid read, - /// and that grid whole: its transform, columns and rows. + /// For a part of a file ([`Input::read_part`]), where it lies in the grid it was read from. + #[cfg(not(target_arch = "wasm32"))] place: Option, } -/// Where a part of a raster file lies in the grid it was read from ([`Read::place`]). -pub(crate) type Place = ((u32, u32), (rustgis_data::raster::GeoTransform, u32, u32)); +/// Where a part of a raster file lies in the grid it was read from ([`Read::place`]), and what +/// the run says of it once the work uses it ([`Read::used`]). +#[cfg(not(target_arch = "wasm32"))] +pub(crate) struct Place { + /// The part's first column and row in the grid. + pub(crate) at: (u32, u32), + /// The grid, whole: its transform, columns and rows. + pub(crate) grid: (rustgis_data::raster::GeoTransform, u32, u32), + /// The grid's longitude/latitude bounds. + pub(crate) bounds: rustgis_geom::Extent, + note: super::gp::ReadNote, +} impl Read { /// Where the raster lies in the grid it was read from, for a part of a file /// ([`Input::read_part`]); `None` for a raster read whole. - pub(crate) fn place(&self) -> Option { - self.place + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn place(&self) -> Option<&Place> { + self.place.as_ref() + } + + /// Says, once the run's raster is added, what is said of a part of a file the work went on to + /// use (read at a coarser level, values rounded as it was read): a part it put aside for the + /// whole file says nothing. A raster read whole says its own as it is read. + pub(crate) fn used(&self) { + #[cfg(not(target_arch = "wasm32"))] + if let Some(place) = &self.place { + RUN_READS.with(|r| { + if let Some(read) = r.borrow_mut().as_mut() { + read.push(RunRead { path: None, kept: None, note: place.note.clone() }); + } + }); + } } } From c7779686a6a30810fd1bf3c7e3eed7d1ab7d9d04 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 15:39:39 -0600 Subject: [PATCH 4/4] fix(raster): a part read from an overview names the file's size and the part's MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The notice said "at its W × H overview of the P × Q raster", P × Q being the part's size in the file's pixels. `PartRead` now gives the file's full size, and a part's notice names the level, the file and the part: "at its 500 × 500 overview of the 1000 × 1000 raster, a 62 × 177 part of it". --- crates/data/src/raster/geotiff.rs | 4 ++-- crates/data/src/raster/mod.rs | 5 ++++- crates/engine/src/cmd/gp.rs | 24 ++++++++++++++++++++---- crates/engine/src/cmd/workflows.rs | 4 ++-- crates/engine/src/tests/tiled_files.rs | 11 +++++++++++ 5 files changed, 39 insertions(+), 9 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 89ff03dbce..d39ba90360 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1993,7 +1993,7 @@ fn read_image( r.apply_pam(p, super::pam::GDAL_METADATA); } let (grid, bounds) = ((r.transform, w, h), r.extent()); - return Ok(Some(super::PartRead { raster: r, at: (0, 0), grid, bounds })); + return Ok(Some(super::PartRead { raster: r, at: (0, 0), grid, bounds, full: (full_w, full_h) })); } let mut transform = geo.transform; // How many full-image pixels one pixel read spans, across and down. @@ -2086,7 +2086,7 @@ fn read_image( } let at = span.map_or((0, 0), |s| (s.cols.0, s.rows.0)); let bounds = if span.is_some() { super::extent_of(&grid.0, r.transformer(), grid.1, grid.2) } else { r.extent() }; - Ok(Some(super::PartRead { raster: r, at, grid, bounds })) + Ok(Some(super::PartRead { raster: r, at, grid, bounds, full: (full_w, full_h) })) } /// What turning a rotated or skewed image north up says ([`super::north_up`]): its pixels are diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 311b57b86b..e88afcb8ae 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -1110,7 +1110,8 @@ impl Raster { /// How many of the file's pixels one pixel read spans, across and down: exactly `step` for /// every `step`-th pixel, an overview's size over the file's, else 1. (`overview` stays the - /// file's own size, which `step` needn't divide, so a reader at a step goes by `step`.) + /// size of what was read in the file's pixels, the file's or a part's, which `step` needn't + /// divide, so a reader at a step goes by `step`.) pub fn file_pixels(&self) -> (f64, f64) { if self.step > 1 { return (f64::from(self.step), f64::from(self.step)); @@ -1476,6 +1477,8 @@ pub struct PartRead { /// That grid's longitude/latitude bounds, as [`Raster::extent`] finds a raster's: every k-th /// pixel's grid can pass the image's edge. pub bounds: Extent, + /// The file's full image, its columns and rows (the raster's `overview` is the part's). + pub full: (u32, u32), } /// `part` of the GeoTIFF at `path`, as [`read_path`] reads the file but holding only that part, diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index f38bcd3fdd..8acd634dc3 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1646,6 +1646,8 @@ pub(crate) fn read_tiled_part( let _turn = tiled_turn().map_err(|e| format!("{name}: {e}"))?; // Planned in its turn, with what the reads before it hold counted. let max = rustgis_data::raster::max_samples() / share.max(1); + #[cfg(test)] + let max = PART_SAMPLES.with(std::cell::Cell::get).unwrap_or(max); let read = rustgis_data::raster::read_path_part(std::path::Path::new(path), part, max, Some(held)).map_err(|e| format!("{name}: {e}"))?; let Some(read) = read else { return Ok(None) }; @@ -1655,19 +1657,29 @@ pub(crate) fn read_tiled_part( /// What a run says of a raster file read in place it read again from its file ([`read_tiled`]): /// its layer's name, how many of its values were rounded as it was read, and, read coarser than -/// the file, its size and the file's (or the part's) in the file's pixels. +/// the file, the level's size and the file's, and for a part of the file +/// ([`read_tiled_part`]) the part's size at that level. #[cfg(not(target_arch = "wasm32"))] #[derive(Clone)] pub(crate) struct ReadNote { name: String, rounded: u64, overview: Option<((u32, u32), (u32, u32))>, + part: Option<(u32, u32)>, } #[cfg(not(target_arch = "wasm32"))] impl ReadNote { pub(crate) fn of(name: &str, r: &rustgis_data::raster::Raster) -> ReadNote { - ReadNote { name: name.to_string(), rounded: r.rounded.iter().sum(), overview: r.overview.map(|full| ((r.width, r.height), full)) } + let overview = r.overview.map(|full| ((r.width, r.height), full)); + ReadNote { name: name.to_string(), rounded: r.rounded.iter().sum(), overview, part: None } + } + + /// Of a part of a file ([`read_tiled_part`]): read from a level `level` pixels in size of the + /// file's `full` image. + pub(crate) fn of_part(name: &str, r: &rustgis_data::raster::Raster, level: (u32, u32), full: (u32, u32)) -> ReadNote { + let overview = r.overview.map(|_| (level, full)); + ReadNote { name: name.to_string(), rounded: r.rounded.iter().sum(), overview, part: Some((r.width, r.height)) } } } @@ -1677,12 +1689,13 @@ impl ReadNote { #[cfg(not(target_arch = "wasm32"))] pub(crate) fn tiled_read_notes(read: &[ReadNote], whose: &str) -> Vec { let (mut rounded, mut overviews) = (Vec::new(), Vec::new()); - for ReadNote { name, rounded: n, overview } in read { + for ReadNote { name, rounded: n, overview, part } in read { if *n > 0 { rounded.push(format!("{name} {n}")); } if let Some(((w, h), (fw, fh))) = overview { - overviews.push(format!("{name} at its {w} × {h} overview of the {fw} × {fh} raster")); + let part = part.map_or_else(String::new, |(pw, ph)| format!(", a {pw} × {ph} part of it")); + overviews.push(format!("{name} at its {w} × {h} overview of the {fw} × {fh} raster{part}")); } } let mut notes = Vec::new(); @@ -1801,6 +1814,9 @@ thread_local! { /// How many raster files read in place [`tiled_inputs`] has read from their file on this /// thread, under test. pub(crate) static TILED_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The most samples [`read_tiled_part`] reads of a part on this thread, under test: no small + /// fixture reaches the real limit. + pub(crate) static PART_SAMPLES: std::cell::Cell> = const { std::cell::Cell::new(None) }; } /// Whether a batch's reads are kept on this thread now ([`BATCH_READS`]), under test. diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 43e3b5f347..4f6729a3e3 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -199,8 +199,8 @@ impl Input { && RUN_READS.with(|r| r.borrow().is_some()) && let Some((read, count)) = super::gp::read_tiled_part(name, path, part, share, &self.held)? { - let rustgis_data::raster::PartRead { raster, at, grid, bounds } = read; - let note = super::gp::ReadNote::of(name, &raster); + let rustgis_data::raster::PartRead { raster, at, grid, bounds, full } = read; + let note = super::gp::ReadNote::of_part(name, &raster, (grid.1, grid.2), full); return Ok(Read { raster: std::sync::Arc::new(raster), _count: Some(count), place: Some(Place { at, grid, bounds, note }) }); } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/tests/tiled_files.rs b/crates/engine/src/tests/tiled_files.rs index 9117bd3727..febf2a6c77 100644 --- a/crates/engine/src/tests/tiled_files.rs +++ b/crates/engine/src/tests/tiled_files.rs @@ -416,6 +416,17 @@ fn a_clip_by_extent_reads_only_its_part_of_a_tiled_file() { let notes = said(&s, mark); assert!(!notes.iter().any(|n| n.contains("finest level")), "{notes:?}"); } + // A part too large for what the run holds is read from an overview, and said, with its size. + crate::cmd::gp::PART_SAMPLES.with(|c| c.set(Some(40_000))); + let mark = s.notice_mark(); + s.run("layer.remove", &json!({"layer": "clip"})).ok(); + s.run("raster.process", &clip([10.3, 45.55, 10.42, 45.9])).unwrap(); + crate::cmd::gp::PART_SAMPLES.with(|c| c.set(None)); + let got = raster(&s, "clip").data.clone().unwrap(); + assert_eq!((got.width, got.height), (60, 176), "the part at the 500 overview"); + let notes = said(&s, mark); + let note = "Process: read at the finest level each can hold: checks at its 500 × 500 overview of the 1000 × 1000 raster, a 62 × 177 part of it"; + assert!(notes.iter().any(|n| n == note), "{notes:?}"); // The file replaced by one a twentieth of a degree east: read whole, and clipped where it is. const N: u32 = 1000; let shifted = Raster::new(