From 9af2185126e2edf5833b2802ddd56a9d04859fe5 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 16:11:15 -0600 Subject: [PATCH 1/3] feat(raster): Indices over a large tiled GeoTIFF run a block at a time at full size (#2865) Indices over a layer read in place from a file too large to read whole at its full size work a block of tiles at a time: each block is read at the file's full size (`read_path_part`) and its index made. A result that fits is held as before. One too large to hold is written a row of tiles at a time to a tiled GeoTIFF with overviews (`cogwrite::TileStream`) in the project's results folder (`Survey.rgis.data`, as project format 2 places tool results, #1853 piece 5; RustGIS's own folder for a project not saved yet), and the new layer reads it in place. - The file's name is reserved before it is written, and a run cancelled, failed or never added leaves nothing behind, a folder it made included. - The installed file's revision goes with the layer, so another command can read it at once. - The run counts blocks as its progress (`control::uncounted` keeps a block's own steps from starting the count again), looks at Cancel between them, and plans its rows' memory before setting them aside. - The permission check adds that it writes a file, and a script step nobody can stop is refused rather than holding the window. --- crates/analysis/src/control.rs | 49 +++- crates/data/src/io.rs | 75 ++++- crates/data/src/raster/cogwrite.rs | 364 +++++++++++++++++++++++++ crates/data/src/raster/mod.rs | 24 +- crates/engine/src/cmd/gp.rs | 5 + crates/engine/src/cmd/imagery.rs | 5 + crates/engine/src/cmd/in_blocks.rs | 361 ++++++++++++++++++++++++ crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/cmd/workflows.rs | 35 ++- crates/engine/src/policy/effects.rs | 5 + crates/engine/src/tests/tiled_files.rs | 136 +++++++++ docs/user-guide/data.md | 10 + 12 files changed, 1056 insertions(+), 15 deletions(-) create mode 100644 crates/engine/src/cmd/in_blocks.rs diff --git a/crates/analysis/src/control.rs b/crates/analysis/src/control.rs index d8df4c50fb..1744b54136 100644 --- a/crates/analysis/src/control.rs +++ b/crates/analysis/src/control.rs @@ -25,6 +25,8 @@ pub struct Control { cancel_at_start: bool, /// How often the work looked at the flag ([`Control::looked`]). looked: AtomicU64, + /// How many [`uncounted`] parts of the work are running: their steps don't count. + quiet: AtomicU64, /// Cancelled at its `n`th look ([`Control::cancelled_at_look`]); 0 for never. #[cfg(any(test, feature = "testing"))] cancel_at_look: u64, @@ -112,12 +114,45 @@ impl rustgis_data::progress::Probe for Control { self.looked_at() } fn begin(&self, total: u64) { - self.done.store(0, Ordering::Relaxed); - self.total.store(total, Ordering::Relaxed); + if self.counting() { + self.done.store(0, Ordering::Relaxed); + self.total.store(total, Ordering::Relaxed); + } } fn advance(&self, n: u64) { - self.done.fetch_add(n, Ordering::Relaxed); + if self.counting() { + self.done.fetch_add(n, Ordering::Relaxed); + } + } +} + +impl Control { + /// Whether the work's steps count: none of it runs [`uncounted`]. + fn counting(&self) -> bool { + self.quiet.load(Ordering::Relaxed) == 0 + } +} + +/// Runs `work` without counting its steps in the progress of the run on this thread, whose looks +/// at Cancel still stop it: for a piece of a step its caller counts itself (a block of a raster +/// made a block at a time), whose own steps would start the count again at each piece. Its +/// threads ([`crate::parallel`]) share the run's control, so they don't count either. +pub fn uncounted(work: impl FnOnce() -> T) -> T { + /// Counts the part as running while it lives, also as it unwinds. + struct Quiet(Option>); + impl Drop for Quiet { + fn drop(&mut self) { + if let Some(c) = &self.0 { + c.quiet.fetch_sub(1, Ordering::Relaxed); + } + } + } + let control = current(); + if let Some(c) = &control { + c.quiet.fetch_add(1, Ordering::Relaxed); } + let _quiet = Quiet(control); + work() } /// Carries the initiating request predicate to the data writer's last commit check as well as @@ -238,7 +273,7 @@ pub(crate) fn check() -> Result<(), Cancelled> { /// Starts counting a step of `total` items (rows, features) for the progress, from none done. pub(crate) fn begin(total: usize) { CURRENT.with(|c| { - if let Some(c) = c.borrow().as_ref() { + if let Some(c) = c.borrow().as_ref().filter(|c| c.counting()) { c.done.store(0, Ordering::Relaxed); c.total.store(total as u64, Ordering::Relaxed); } @@ -249,7 +284,7 @@ pub(crate) fn begin(total: usize) { /// (its index). pub(crate) fn reached(done: usize) { CURRENT.with(|c| { - if let Some(c) = c.borrow().as_ref() { + if let Some(c) = c.borrow().as_ref().filter(|c| c.counting()) { c.done.store(done as u64, Ordering::Relaxed); } }); @@ -259,7 +294,7 @@ pub(crate) fn reached(done: usize) { /// otherwise ends one short). pub(crate) fn finish() { CURRENT.with(|c| { - if let Some(c) = c.borrow().as_ref() { + if let Some(c) = c.borrow().as_ref().filter(|c| c.counting()) { c.done.store(c.total.load(Ordering::Relaxed), Ordering::Relaxed); } }); @@ -268,7 +303,7 @@ pub(crate) fn finish() { /// Counts `n` more items of the step done. pub(crate) fn advance(n: usize) { CURRENT.with(|c| { - if let Some(c) = c.borrow().as_ref() { + if let Some(c) = c.borrow().as_ref().filter(|c| c.counting()) { c.done.fetch_add(n as u64, Ordering::Relaxed); } }); diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index ae8cf8695d..6db7769c20 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1332,6 +1332,49 @@ pub fn stage_streamed>( stage_at(link_target(path)?, 1 << 20, write) } +/// [`stage_streamed`] to a destination nothing holds yet: it is reserved first, an empty file +/// made in its place only if nothing is there (an `AlreadyExists` error otherwise, before +/// anything is written), so two writes never pick the same file. [`StagedWrite::commit`] puts +/// the file there; dropping the result, or an error, removes the reservation, and `folder` (one +/// the caller just made for it) when nothing else is in it. +pub fn stage_streamed_new>( + path: &Path, + folder: Option<&Path>, + write: impl FnOnce(&mut std::io::BufWriter) -> std::result::Result, +) -> std::result::Result<(StagedWrite, T), E> { + std::fs::OpenOptions::new().write(true).create_new(true).open(path)?; + let mut held = Reserved { path: Some(path.to_path_buf()), folder: folder.map(Path::to_path_buf) }; + let (mut staged, value) = stage_at(path.to_path_buf(), 1 << 20, write)?; + (staged.reserved, staged.folder) = (held.path.take(), held.folder.take()); + Ok((staged, value)) +} + +/// A destination reserved for a write ([`stage_streamed_new`]), and a folder made for it, removed +/// while the write isn't installed: the reservation while it is still empty, the folder while +/// nothing else is in it. +struct Reserved { + path: Option, + folder: Option, +} + +impl Drop for Reserved { + fn drop(&mut self) { + unreserve(self.path.take(), self.folder.take()); + } +} + +/// Removes a reserved destination still empty, then `folder` if nothing else is in it. +fn unreserve(path: Option, folder: Option) { + if let Some(p) = path + && std::fs::symlink_metadata(&p).is_ok_and(|m| m.is_file() && m.len() == 0) + { + let _ = std::fs::remove_file(p); + } + if let Some(f) = folder { + let _ = std::fs::remove_dir(f); + } +} + /// Stages and installs a write, retaining the old file on error or cancellation. fn atomic_write_at>( path: std::path::PathBuf, @@ -1353,7 +1396,7 @@ fn stage_at>( let tmp = temp_beside(&path)?; // Opened before the guard, so a name already taken is never removed. let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?; - let staged = StagedWrite { path, tmp: Some(tmp) }; + let staged = StagedWrite { path, tmp: Some(tmp), reserved: None, folder: None }; // The new file takes the old one's mode before any content is written, so a private file // (0600) never becomes readable by others. On Windows a new file inherits its folder's access // rules, and copying a read-only flag would only make the rename fail. @@ -1381,10 +1424,14 @@ fn stage_at>( Ok((staged, value)) } -/// An atomic write awaiting installation. An error or drop removes its temporary file. +/// An atomic write awaiting installation. An error or drop removes its temporary file, and what +/// [`stage_streamed_new`] reserved for it. pub struct StagedWrite { path: std::path::PathBuf, tmp: Option, + /// The destination reserved, and the folder made for it ([`stage_streamed_new`]). + reserved: Option, + folder: Option, } impl StagedWrite { @@ -1402,6 +1449,7 @@ impl StagedWrite { if let Some(tmp) = &self.tmp { std::fs::rename(tmp, &self.path)?; self.tmp = None; + (self.reserved, self.folder) = (None, None); sync_folder(&self.path); } Ok(()) @@ -1413,6 +1461,7 @@ impl Drop for StagedWrite { if let Some(tmp) = &self.tmp { let _ = std::fs::remove_file(tmp); } + unreserve(self.reserved.take(), self.folder.take()); } } @@ -5804,6 +5853,28 @@ mod tests { use super::*; use std::io::Write; + /// A write to a name nothing holds reserves it first: a second write to it is refused before + /// anything is written, and dropping the write removes the reservation and the folder made for + /// it; once installed, both stay (#2865). + #[test] + fn a_new_staged_file_reserves_its_name_and_leaves_nothing_when_dropped() { + use std::io::Write; + let dir = tempfile::tempdir().unwrap(); + let folder = dir.path().join("Survey.rgis.data"); + std::fs::create_dir(&folder).unwrap(); + let dest = folder.join("index.tif"); + let (staged, ()) = stage_streamed_new::<_, std::io::Error>(&dest, Some(&folder), |w| w.write_all(b"pixels")).unwrap(); + assert!(dest.is_file(), "reserved"); + let taken = stage_streamed_new::<(), std::io::Error>(&dest, None, |_| panic!("written to a name another holds")); + assert_eq!(taken.err().map(|e| e.kind()), Some(std::io::ErrorKind::AlreadyExists)); + drop(staged); + assert!(!dest.exists() && !folder.exists(), "the reservation and its folder go with it"); + std::fs::create_dir(&folder).unwrap(); + let (staged, ()) = stage_streamed_new::<_, std::io::Error>(&dest, Some(&folder), |w| w.write_all(b"pixels")).unwrap(); + staged.commit().unwrap(); + assert_eq!(std::fs::read(&dest).unwrap(), b"pixels"); + } + /// Each extra cell is counted, including empty ones, and each affected row once, preserving named data. #[test] fn csv_extra_cells_are_counted() { diff --git a/crates/data/src/raster/cogwrite.rs b/crates/data/src/raster/cogwrite.rs index 9bf687e233..d17c08eee5 100644 --- a/crates/data/src/raster/cogwrite.rs +++ b/crates/data/src/raster/cogwrite.rs @@ -1087,6 +1087,316 @@ pub fn write_staged(r: &Raster, band: usize, path: &Path) -> Result<(CogInfo, cr Ok((info, staged)) } +/// A tiled GeoTIFF of one band of 32-bit floats written a row of tiles at a time, for a raster +/// made in pieces too large to hold whole (#2865). The caller gives the full image's rows, top to +/// bottom, in as many calls as it likes ([`TileStream::put`]); each full row of tiles is +/// compressed and written as it is complete, and the rows of the overviews are made from it as +/// they go, each level averaging two by two the pixels of the one before (the pixels with a value +/// among the four, as [`write_to`] averages, but from the level before rather than the full +/// image). Its layout is a tiled GeoTIFF's, every level's directory first: not a cloud-optimised +/// one, whose tiles go smallest level first, but one this computer's reader reads in place. +/// +/// Memory: at most two rows of tiles of each level wait to be written, about +/// `width × TILE × 4 × 2 × 4 / 3` bytes, and a few compressed tiles a thread. +pub struct TileStream<'a, W: Write + Seek> { + out: &'a mut W, + levels: Vec, + /// Each level's rows given and not yet written as a row of tiles, its width each. + pending: Vec>, + /// How many rows of each level have been given. + given: Vec, + places: Vec>, + patches: Vec, + big: bool, + pos: u64, + /// The value of a pixel with none, written for pixels past the image's edge too. + nodata: f32, + /// The level kept as it is written ([`TileStream::keeping`]), and its rows so far. + kept: Option<(usize, Vec)>, + /// What the kept level is made into: the template's name, place and no-data. + template: Raster, +} + +impl<'a, W: Write + Seek> TileStream<'a, W> { + /// A stream of a `width` × `height` raster into `out` (which must be empty: offsets are from + /// its start), placed, named and with the no-data value of `template` (its first band's name, + /// its transform's corner and pixel size, its system and rights holder; its own pixels and + /// size aren't written). A template without a no-data value marks pixels with none NaN. + pub fn new(template: &Raster, width: u32, height: u32, out: &'a mut W) -> Result> { + template.require_coordinates().map_err(err)?; + let gt = template.transform; + if gt.pixel_height > 0.0 || gt.pixel_width < 0.0 { + return Err(err("only north-up rasters can be exported for now")); + } + if width == 0 || height == 0 { + return Err(err("the raster has no pixels to write")); + } + let plan = stream_plan(); + let geo = geo_keys(template)?; + let mut levels = vec![Level::new(width, height, 1)]; + while let Some(last) = levels.last().filter(|l| l.w.max(l.h) > TILE) { + if levels.len() >= MAX_LEVELS { + return Err(err("too many overviews")); + } + let (w, h, f) = (last.w.div_ceil(2), last.h.div_ceil(2), last.factor * 2); + levels.push(Level::new(w, h, f)); + } + let tiles: usize = levels.iter().map(Level::tiles).sum(); + // The worst a file can come to, as [`write_to`] reckons it. + let raw = (tiles as u64).saturating_mul(u64::from(TILE) * u64::from(TILE) * 4); + let worst = raw.saturating_add(raw / 512).saturating_add(tiles as u64 * 64).saturating_add(1 << 20); + let big = worst >= u64::from(u32::MAX); + // A header past what a reader takes at a file's start couldn't be read in place: its + // tiles' tables alone, an offset and a count each, refused before they are made. + let table_bytes = (tiles as u64).saturating_mul(if big { 16 } else { 8 }); + if table_bytes > super::cog::MAX_HEADER { + return Err(err(format!( + "its tables of {tiles} tiles ({} MB) are more than a reader takes at a file's start: clip it to a smaller area first", + table_bytes >> 20 + ))); + } + let nodata = template.nodata.map_or(f32::NAN, |d| d as f32); + let ifds: Vec> = levels + .iter() + .enumerate() + .map(|(i, lv)| { + let mut e = entries(template, &plan, lv, i == 0, &geo, big); + if i == 0 { + // What marks a pixel with none: the template's value, else NaN (its own + // pixels, which `entries` looks at, aren't the stream's). + e.retain(|e| e.tag != 42113); + e.push(ascii(42113, &template.nodata.map_or_else(|| "nan".to_string(), |d| d.to_string()))); + } + e + }) + .collect(); + let head = build_head(&ifds, big); + // A header past what a reader takes at its start couldn't be read in place. + if head.bytes.len() as u64 > super::cog::MAX_HEADER { + return Err(err(format!( + "its tables of {tiles} tiles ({} MB) are more than a reader takes at a file's start: clip it to a smaller area first", + head.bytes.len() >> 20 + ))); + } + out.seek(SeekFrom::Start(0)).map_err(err)?; + out.write_all(&head.bytes).map_err(err)?; + let n = levels.len(); + Ok(TileStream { + out, + pos: head.bytes.len() as u64, + places: levels.iter().map(|l| Vec::with_capacity(l.tiles())).collect(), + levels, + pending: vec![Vec::new(); n], + given: vec![0; n], + patches: head.patches, + big, + nodata, + kept: None, + template: template.clone(), + }) + } + + /// Keeps, as it is written, the finest level whose tiles hold at most `samples` pixels, their + /// padding counted (the coarsest when none does), which [`TileStream::finish`] gives as a + /// raster: an overview of the file to hold, the one a layer reading the file in place picks + /// with the same budget, without reading it back. + pub fn keeping(mut self, samples: usize) -> TileStream<'a, W> { + let tile = TILE as usize * TILE as usize; + let fits = self.levels.iter().position(|l| l.tiles().saturating_mul(tile) <= samples); + let level = fits.unwrap_or(self.levels.len().saturating_sub(1)); + self.kept = Some((level, Vec::new())); + self + } + + /// The most bytes a stream of a `width` × `height` image holds at once, keeping an overview of + /// at most `kept` samples ([`TileStream::keeping`]), given its rows a row of tiles at a time: + /// each level's rows waiting for their row of tiles (none at the full size, which is written + /// from the rows given; less than a row of tiles of each level after it, and the rows made + /// for it), the tiles' tables, the overview kept, and the tiles being compressed. + pub fn peak(width: u32, height: u32, kept: usize) -> u64 { + let row = u64::from(width).saturating_mul(u64::from(TILE)).saturating_mul(4); + // The tiles of every level, each with an offset and a count of 8 bytes, held three times + // as the header is laid out, and once more where each tile went. + let (mut tiles, (mut w, mut h)) = (0u64, (width, height)); + loop { + tiles = tiles.saturating_add(u64::from(w.div_ceil(TILE)).saturating_mul(u64::from(h.div_ceil(TILE)))); + if w.max(h) <= TILE { + break; + } + (w, h) = (w.div_ceil(2), h.div_ceil(2)); + } + // Each level a half the size of the one before: twice a row each at most, halving. + let levels = row.saturating_mul(2); + let tables = tiles.saturating_mul(64); + let compressing = (crate::threads::max() as u64).saturating_mul(u64::from(TILE) * u64::from(TILE) * 4 * (2 + AHEAD as u64)); + levels.saturating_add(tables).saturating_add((kept as u64).saturating_mul(4)).saturating_add(compressing) + } + + /// The full image's next rows, whole rows of its width, top to bottom: each row of tiles they + /// complete is written, and its overviews' rows made. More rows than the image has are an error. + pub fn put(&mut self, rows: &[f32]) -> Result<()> { + self.put_level(0, rows) + } + + /// [`TileStream::put`] at level `i`. + fn put_level(&mut self, i: usize, rows: &[f32]) -> Result<()> { + let Some(lv) = self.levels.get(i) else { return Ok(()) }; + let w = lv.w as usize; + if !rows.len().is_multiple_of(w) { + return Err(err("rows must be whole rows of the image's width")); + } + let count = (rows.len() / w) as u64; + let given = self.given.get(i).copied().unwrap_or(0).saturating_add(count); + if given > u64::from(lv.h) { + return Err(err(format!("more than the image's {} rows were given", lv.h))); + } + if let Some(g) = self.given.get_mut(i) { + *g = given; + } + if let Some((_, kept)) = self.kept.as_mut().filter(|(level, _)| *level == i) { + kept.try_reserve(rows.len()).map_err(|_| err("too little memory for the overview kept"))?; + kept.extend_from_slice(rows); + } + let tile_rows = TILE as usize * w; + // Taken while its rows are written, which give the next level its own. + let mut pending = self.pending.get_mut(i).map(std::mem::take).unwrap_or_default(); + let mut rest = rows; + if pending.is_empty() { + // Whole rows of tiles are written from the rows given, not copied first. + while rest.len() >= tile_rows { + let (row, after) = rest.split_at(tile_rows); + self.write_row(i, row)?; + rest = after; + } + } + pending.try_reserve(rest.len()).map_err(|_| err("too little memory for the rows of a level waiting to be written"))?; + pending.extend_from_slice(rest); + while pending.len() >= tile_rows { + self.write_row(i, pending.get(..tile_rows).unwrap_or_default())?; + pending.drain(..tile_rows); + } + if let Some(p) = self.pending.get_mut(i) { + *p = pending; + } + Ok(()) + } + + /// Writes `rows` (at most [`TILE`] of level `i`'s rows, the last row of tiles when fewer) as + /// the level's next row of tiles, then gives the next level their average two by two. + fn write_row(&mut self, i: usize, rows: &[f32]) -> Result<()> { + let Some(lv) = self.levels.get(i) else { return Ok(()) }; + let (w, across) = (lv.w as usize, lv.across as usize); + let (t, nodata) = (TILE as usize, self.nodata); + let plan = stream_plan(); + let line = t * 4; + let make = |scratch: &mut Vec, tx: usize| -> Result> { + let mut raw = Vec::with_capacity(t * t * 4); + for y in 0..t { + for x in 0..t { + let col = tx * t + x; + let v = if col < w { rows.get(y * w + col).copied().unwrap_or(nodata) } else { nodata }; + let v = if v.is_nan() { nodata } else { v }; + raw.extend_from_slice(&v.to_le_bytes()); + } + } + predict_rows(&mut raw, line, 1, Sample::Float, predictor(&plan), scratch); + Ok(miniz_oxide::deflate::compress_to_vec_zlib(&raw, DEFLATE_FAST)) + }; + let (big, out, pos, places) = (self.big, &mut *self.out, &mut self.pos, &mut self.places); + // The run's progress counts the caller's pieces, not these tiles. + crate::progress::without_counting(|| { + in_order(across, t * t * 4, err, Vec::new, make, |_, zipped| { + if !big && *pos + zipped.len() as u64 > u64::from(u32::MAX) { + return Err(err("the file is too large for classic TIFF")); + } + out.write_all(&zipped).map_err(err)?; + if let Some(p) = places.get_mut(i) { + p.push((*pos, zipped.len() as u64)); + } + *pos += zipped.len() as u64; + Ok(()) + }) + })?; + // The next level's rows: each the average of two of these (the last alone when they are + // odd), two pixels across at a time. + if i + 1 < self.levels.len() { + let half = average_rows(rows, w, nodata); + self.put_level(i + 1, &half)?; + } + Ok(()) + } + + /// Writes what is left of each level once every row is given, and fills in the tile tables: + /// what was written, and the level kept ([`TileStream::keeping`]), placed as a reader of the + /// file places it, with `overview` the full image's size when it is coarser. + pub fn finish(mut self) -> Result<(CogInfo, Option)> { + if self.given.first().copied() != self.levels.first().map(|l| u64::from(l.h)) { + return Err(err("the image's rows weren't all given")); + } + for i in 0..self.levels.len() { + let rest = self.pending.get_mut(i).map(std::mem::take).unwrap_or_default(); + if !rest.is_empty() { + self.write_row(i, &rest)?; + } + } + for (lv, p) in self.levels.iter().zip(&self.places) { + if p.len() != lv.tiles() { + return Err(err(format!("{} of the {} tiles of a level were written", p.len(), lv.tiles()))); + } + } + fill_tables(self.out, &self.patches, &self.places, self.big, self.pos, err)?; + let info = CogInfo { big: self.big, levels: self.levels.iter().map(|l| (l.w, l.h)).collect(), bytes: self.pos }; + let (Some((level, data)), Some(full)) = (self.kept, self.levels.first()) else { return Ok((info, None)) }; + let Some(lv) = self.levels.get(level) else { return Ok((info, None)) }; + let t = &self.template; + // A reader of the file spreads a coarser level over the full image's ground. + let (sx, sy) = (f64::from(full.w) / f64::from(lv.w.max(1)), f64::from(full.h) / f64::from(lv.h.max(1))); + let gt = + super::GeoTransform { pixel_width: t.transform.pixel_width * sx, pixel_height: t.transform.pixel_height * sy, ..t.transform }; + let mut r = Raster::new(t.name.clone(), lv.w, lv.h, vec![data], gt, t.crs, t.nodata, ColorHint::Gray, "Float32")?; + if level > 0 { + r.overview = Some((full.w, full.h)); + } + if let (Some(b), Some(tb)) = (r.bands.first_mut(), t.bands.first()) { + b.name.clone_from(&tb.name); + } + Ok((info, Some(r))) + } +} + +/// What a [`TileStream`] writes: one band of 32-bit floats, averaged in its overviews. +fn stream_plan() -> Plan { + Plan { bands: vec![0], sample: Sample::Float, rgb: false, alpha: None, nodata_int: None, palette: None, categorical: false } +} + +/// `rows` of `w` pixels made half the size each way: each pixel the mean of the up to four it +/// covers that have a value (not NaN, nor `nodata`), else `nodata`; an odd last row or column +/// covers itself alone. +fn average_rows(rows: &[f32], w: usize, nodata: f32) -> Vec { + let h = rows.len() / w.max(1); + let (hw, hh) = (w.div_ceil(2), h.div_ceil(2)); + let valid = |v: f32| !v.is_nan() && v != nodata; + let mut out = Vec::with_capacity(hw * hh); + for y in 0..hh { + for x in 0..hw { + let (mut sum, mut n) = (0.0f64, 0u32); + for (dy, dx) in [(0, 0), (0, 1), (1, 0), (1, 1)] { + let (yy, xx) = (2 * y + dy, 2 * x + dx); + if yy < h + && xx < w + && let Some(&v) = rows.get(yy * w + xx) + && valid(v) + { + sum += f64::from(v); + n += 1; + } + } + out.push(if n > 0 { (sum / f64::from(n)) as f32 } else { nodata }); + } + } + out +} + #[cfg(test)] mod tests { use std::io::Cursor; @@ -1102,6 +1412,60 @@ mod tests { Raster::new("t", w, h, bands, gt, Crs::from_epsg(32617).unwrap(), nodata, color, data_type).unwrap() } + /// A raster streamed in pieces of uneven rows (#2865) reads back pixel for pixel, its no-data + /// value kept, and each overview the average two by two of the level before; the layout's + /// reader finds every level. + #[test] + fn a_streamed_raster_reads_back_with_its_overviews() { + let (w, h) = (1300u32, 1100u32); + let value = |x: u32, y: u32| if (x * 7 + y * 3).is_multiple_of(97) { f32::NAN } else { (x as f32) * 0.5 - (y as f32) * 0.25 }; + let data: Vec = (0..h).flat_map(|y| (0..w).map(move |x| value(x, y))).collect(); + let template = utm(1, 1, vec![vec![0.0]], ColorHint::Gray, "Float32", Some(-9999.0)); + let mut out = Cursor::new(Vec::new()); + let mut stream = TileStream::new(&template, w, h, &mut out).unwrap(); + let mut at = 0usize; + for rows in [1usize, 300, 511, 7, 281] { + let n = rows * w as usize; + stream.put(&data[at..at + n]).unwrap(); + at += n; + } + assert!(stream.put(&data[..w as usize]).is_err(), "a row past the image"); + let (info, kept) = stream.finish().unwrap(); + assert_eq!(info.levels, vec![(1300, 1100), (650, 550), (325, 275)]); + assert!(kept.is_none(), "nothing kept unless asked"); + let bytes = out.into_inner(); + let back = geotiff::read(Cursor::new(&bytes), "back").unwrap(); + assert_eq!((back.width, back.height, back.nodata, back.transform), (w, h, Some(-9999.0), template.transform)); + for y in 0..h { + for x in 0..w { + let want = value(x, y); + let got = back.value(0, i64::from(x), i64::from(y)); + assert_eq!(got, (!want.is_nan()).then_some(want), "{x},{y}"); + } + } + // Each overview is its level before averaged two by two. + let mut before = data.iter().map(|v| if v.is_nan() { -9999.0 } else { *v }).collect::>(); + let mut bw = w as usize; + for (lw, lh) in [(650u32, 550u32), (325, 275)] { + let want = average_rows(&before, bw, -9999.0); + let level = geotiff::read_limited(geotiff::reader(Cursor::new(&bytes)).unwrap(), "o", (lw * lh) as usize, None).unwrap(); + assert_eq!((level.width, level.height), (lw, lh)); + assert_eq!(level.bands[0].data, want, "the {lw} × {lh} overview"); + (before, bw) = (want, lw as usize); + } + let Ok(crate::raster::cog::Parse::Done(layout)) = crate::raster::cog::layout(&crate::raster::cog::Sparse::default().with(0, bytes)) + else { + panic!("not a tiled GeoTIFF the reader reads in place"); + }; + assert_eq!(layout.levels.len(), 3); + // Rows that aren't whole rows, and an image left short, are errors. + let mut out = Cursor::new(Vec::new()); + let mut stream = TileStream::new(&template, w, h, &mut out).unwrap(); + assert!(stream.put(&data[..5]).is_err()); + stream.put(&data[..w as usize]).unwrap(); + assert!(stream.finish().is_err()); + } + /// 3000 × 2000 colour pixels: red rises across, green down, blue is a checker of 2 × 2 blocks. fn big_rgb() -> Raster { let (w, h) = (3000u32, 2000u32); diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index e88afcb8ae..7d59fce302 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -1456,9 +1456,13 @@ impl Part { /// 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 { + // An edge a rounding error from a pixel's edge is on it: a part made from whole pixels + // (`53248 / 83517` of the width, say, which multiplies back to `53247.99999999999`) is + // those pixels, not one more each way. + let snap = |v: f64| if (v - v.round()).abs() < 1e-6 { v.round() } else { v }; 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))) + let start = (snap(a * units).floor() as u32).min(n.saturating_sub(1)); + (start, (snap(b * units).ceil() as u32).min(n).max(start.saturating_add(1).min(n))) }; geotiff::Span { cols: edges(self.left, self.right, w, extent.0), rows: edges(self.top, self.bottom, h, extent.1) } } @@ -2162,6 +2166,22 @@ fn extent_of(transform: &GeoTransform, transformer: &Transformer, width: u32, he pub(crate) mod tests { use super::*; + /// A part made from whole pixels of a grid is those pixels, whatever the fractions round to: + /// blocks of a file next to each other share no pixel (#2865), and an edge between pixels + /// still takes both. + #[test] + fn a_part_of_whole_pixels_is_those_pixels() { + let (w, h) = (83_517u32, 78_739u32); + for (c0, c1, r0, r1) in [(53_248u32, 57_344u32, 512u32, 1024u32), (0, 4096, 78_336, 78_739), (81_920, 83_517, 0, 512)] { + let f = |v: u32, n: u32| f64::from(v) / f64::from(n); + let part = Part::new(f(c0, w), f(r0, h), f(c1, w), f(r1, h)).unwrap(); + let span = part.span((w, h), (f64::from(w), f64::from(h))); + assert_eq!((span.cols, span.rows), ((c0, c1), (r0, r1))); + } + let between = Part::new(0.25, 0.25, 0.5005, 0.5).unwrap().span((1000, 1000), (1000.0, 1000.0)); + assert_eq!((between.cols, between.rows), ((250, 501), (250, 500))); + } + #[test] fn elevation_files_are_raster_names() { for ext in ELEVATION_EXTENSIONS { diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 8acd634dc3..857c8a2894 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1681,6 +1681,11 @@ impl 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)) } } + + /// Of a file read at its full size in pieces, `rounded` of its values rounded as they were. + pub(crate) fn rounded(name: &str, rounded: u64) -> ReadNote { + ReadNote { name: name.to_string(), rounded, overview: None, part: None } + } } /// What a run says of the raster files read in place it read again from their file diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 69fd1119df..38994d087e 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1608,6 +1608,11 @@ pub(crate) fn index_work(s: &Session, p: &Value) -> Result, + /// The full image's columns and rows. + full: (u32, u32), +} + +/// The most samples a cell-by-cell command reads whole of a file, and holds of a result: +/// [`rustgis_data::raster::SAMPLES_FLOOR`], what any desktop reads whole, or under test what +/// [`BLOCKS_PAST`] sets on this thread. Not the computer's own limit, which follows what it has +/// free: the permission check and the run decide the same way however that changes between them. +fn whole_limit() -> usize { + #[cfg(test)] + if let Some(max) = BLOCKS_PAST.with(std::cell::Cell::get) { + return max; + } + rustgis_data::raster::SAMPLES_FLOOR +} + +#[cfg(test)] +thread_local! { + /// [`whole_limit`]'s limit on this thread, under test: no small fixture reaches the real one. + pub(crate) static BLOCKS_PAST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// The full size of `input`'s file, when it is a layer read in place from a file that a run +/// can't read whole at that size: its samples' bytes as read, 8 a sample (64-bit samples, which +/// the overview held may not say it has), past the 4 a sample of what a run reads whole, as the +/// GeoTIFF reader decides it. +fn too_large(input: &Input) -> Option<(u32, u32)> { + input.file()?; + let held = input.held(); + let full = held.overview?; + let samples = u64::from(full.0).saturating_mul(u64::from(full.1)).saturating_mul(held.band_count().max(1) as u64); + (samples.saturating_mul(8) > (whole_limit() as u64).saturating_mul(4)).then_some(full) +} + +/// Whether a result `full` pixels in size, one band, is too large to hold: it is then written to +/// a file and read in place, as a file that size added from this computer is. +fn written(full: (u32, u32)) -> bool { + u64::from(full.0).saturating_mul(u64::from(full.1)) > whole_limit() as u64 +} + +/// Whether command `id` with `params` writes its result to a file in the results folder: a +/// command that works in blocks ([`IN_BLOCKS`]) over a layer too large to read whole, whose +/// result is too large to hold. The permission check adds that it writes files. +pub(crate) fn writes_file(context: &impl super::InputSource, id: &str, params: &Value) -> bool { + if !IN_BLOCKS.contains(&id) { + return false; + } + let Some(name) = params.get("layer").and_then(Value::as_str) else { return false }; + Input::of(context, name).ok().as_ref().and_then(too_large).is_some_and(written) +} + +/// The plan to make `out` from `input` a block at a time, when `input` is a layer read in place +/// from a file too large to read whole at its full size ([`too_large`]); `None` otherwise, and +/// the command reads its input as before. A step of a script that nobody can stop while it runs +/// (the app's, which runs on its window's thread) is refused, as is a result too large to hold +/// when this computer gives no folder to write it to. +pub(crate) fn plan(s: &Session, input: &Input, out: &str) -> Result, String> { + let (Some(full), Some((layer, path))) = (too_large(input), input.file()) else { return Ok(None) }; + if s.steps_running > 0 && !s.stoppable { + return Err(format!( + "{layer}: its full {} × {} pixels are made a block at a time, which a script step can't do without holding the window: run it on its own", + full.0, full.1 + )); + } + let folder = match written(full) { + true => Some(folder(s).ok_or("this computer gives RustGIS no folder to write the result to: save the project first")?), + false => None, + }; + Ok(Some(Blocks { input: input.clone(), layer: layer.to_string(), path: path.to_string(), out: out.to_string(), folder, full })) +} + +/// Makes the results folder `folder` (and the folders it is in): whether this call made it, rather +/// than finding it there. +fn make_folder(folder: &Path) -> Result { + if let Some(parent) = folder.parent() { + std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?; + } + match std::fs::create_dir(folder) { + Ok(()) => Ok(true), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false), + Err(e) => Err(format!("{}: {e}", folder.display())), + } +} + +/// The project's results folder: beside the saved project, named after its file +/// (`Survey.rgis.data`), or in RustGIS's own folder for one not saved yet. `None` when the +/// computer gives none. +fn folder(s: &Session) -> Option { + match s.path.as_deref() { + Some(project) => { + let name = project.file_name().and_then(|n| n.to_str()).unwrap_or("Project"); + Some(project.parent().unwrap_or(Path::new(".")).join(format!("{name}.data"))) + } + None => rustgis_data::dirs::app_data_dir().map(|d| d.join("results")), + } +} + +impl Blocks { + /// Makes the raster: `cells` turns a block of the input (all its bands, at the file's full + /// size) into the result's values for its cells, row by row, `NODATA` for none. Each block is + /// read and made in turn, counted as the run's progress, Cancel looked at between them. A + /// result too large to hold is written a row of tiles at a time beside its place in the + /// results folder, and put there as the layer is added, which reads it in place; a run + /// cancelled, failed or never added leaves nothing behind, a folder it made included while + /// nothing else is in it (one another run wrote into too can stay, empty, once both their + /// results are gone). + pub(crate) fn run(self, cells: impl Fn(&Raster) -> Result, String>) -> Result { + let Blocks { input, layer, path, out, folder, full } = self; + let (fw, fh) = full; + let tile = cogwrite::TILE; + // What a row of blocks holds of the result and of its file's levels as they are written, + // and the tables of the file's tiles: planned before any of it is set aside. + let row_bytes = u64::from(fw).saturating_mul(u64::from(tile)).saturating_mul(4); + let need = match &folder { + // The row of blocks made, and the file's levels' rows waiting to be written (less + // than a row each way, two at most at the full size, half that at the next level…), + // the tables of its tiles, and the overview kept. + Some(_) => cogwrite::TileStream::>>::peak(fw, fh, OVERVIEW_SAMPLES).saturating_add(row_bytes), + None => u64::from(fw).saturating_mul(u64::from(fh)).saturating_mul(4).saturating_add(row_bytes), + }; + let can = (rustgis_data::raster::max_samples() as u64).saturating_mul(8); + if need > can { + return Err(format!( + "{layer}: making it a block at a time at its full {fw} × {fh} needs {} MB at once, more than this computer can give now: clip it to a smaller area first", + need >> 20 + )); + } + let _held = rustgis_data::memory::Holding::of(need); + let blocks = Source { input: &input, layer: &layer, path: &path, full }; + let Some(folder) = folder else { + // A result that fits: held whole, made a block at a time. + let mut whole = rustgis_analysis::rasterops::new_band(fw as usize, fh as usize, NODATA)?; + let (grid, crs, rounded) = blocks.each_row(&cells, |r0, rows, _| { + let at = r0 as usize * fw as usize; + if let Some(d) = whole.get_mut(at..at + rows.len()) { + d.copy_from_slice(rows); + } + Ok(()) + })?; + let r = Raster::new(out.clone(), fw, fh, vec![whole], grid, crs, Some(f64::from(NODATA)), ColorHint::Gray, "Float32") + .map_err(|e| e.to_string())?; + let notes = super::gp::tiled_read_notes(&[super::gp::ReadNote::rounded(&layer, rounded)], "its"); + let then: super::workflows::Then = Box::new(move |s: &mut Session, _: &mut Value| { + for note in notes { + s.notify(note, false); + } + }); + return super::workflows::made_then(r, None, Some(then)); + }; + // A folder this run makes goes again with a result never added, while nothing else is in + // it; one already there stays, whatever is in it. + let mut made_folder = make_folder(&folder)?; + let (mut taken, mut i, mut remade) = (None, 1u32, 0); + while i < 10_000 { + let stem = super::items::safe(&out); + let dest = folder.join(if i == 1 { format!("{stem}.tif") } else { format!("{stem} {i}.tif") }); + // The file's name is reserved before it is written: two runs never take the same one. + let wrote = rustgis_data::io::stage_streamed_new(&dest, made_folder.then_some(folder.as_path()), |w| { + let (mut sink, mut stream) = (Some(w), None); + let (_, _, rounded) = blocks + .each_row(&cells, |_, rows, (grid, crs)| { + // Placed on the file's full grid, as a read of all of it places it. + if stream.is_none() { + let t = Raster::new( + out.clone(), + 1, + 1, + vec![vec![NODATA]], + grid, + crs, + Some(f64::from(NODATA)), + ColorHint::Gray, + "Float32", + ) + .map_err(|e| e.to_string())?; + let w = sink.take().ok_or("the result's file was started twice")?; + stream = Some(cogwrite::TileStream::new(&t, fw, fh, w).map_err(|e| e.to_string())?.keeping(OVERVIEW_SAMPLES)); + } + stream.as_mut().map_or(Ok(()), |s: &mut cogwrite::TileStream<_>| s.put(rows).map_err(|e| e.to_string())) + }) + .map_err(rustgis_data::DataError::Format)?; + let (info, overview) = + stream.ok_or_else(|| rustgis_data::DataError::Format(format!("{layer}: it has no pixels")))?.finish()?; + Ok::<_, rustgis_data::DataError>((info, overview, rounded)) + }); + match wrote { + Err(rustgis_data::DataError::Io(e)) if e.kind() == std::io::ErrorKind::AlreadyExists => i += 1, + // Another run's result, never added, took the folder it made with it meanwhile: + // made again (this run's now, if it makes it), the same name tried again. + Err(rustgis_data::DataError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound && !folder.exists() && remade < 8 => { + made_folder = make_folder(&folder)?; + remade += 1; + } + Err(e) => { + if made_folder { + let _ = std::fs::remove_dir(&folder); + } + return Err(match e { + rustgis_data::DataError::Cancelled => e.to_string(), + e => format!("{}: {e}", dest.display()), + }); + } + Ok(w) => { + taken = Some((dest, w)); + break; + } + } + } + let (dest, (staged, (info, overview, rounded))) = + taken.ok_or_else(|| format!("{}: every name for {out} is taken", folder.display()))?; + rustgis_data::progress::check().map_err(|e| e.to_string())?; + // The layer holds an overview of the file, as one added from it would. + let overview = overview.ok_or("the result's overview wasn't kept")?; + let file = dest.display().to_string(); + let rl = rustgis_map::RasterLayer::tiled_file(overview, file.clone()); + let (w, h) = info.levels.first().copied().unwrap_or_default(); + let mut notes = vec![format!( + "{out}: made a block at a time from {layer} at its full {w} × {h}, and written to {file}, where the layer reads it from" + )]; + notes.extend(super::gp::tiled_read_notes(&[super::gp::ReadNote::rounded(&layer, rounded)], "its")); + let then: super::workflows::Then = Box::new(move |s: &mut Session, v: &mut Value| { + for note in notes { + s.notify(note, false); + } + if let Some(o) = v.as_object_mut() { + o.insert("path".into(), Value::String(file)); + } + }); + Ok(super::workflows::made_layer(out, rl, None, Some(then)).committing(staged, Vec::new())) + } +} + +/// A file read a block at a time ([`Source::each_row`]): the layer's input, name and file, and +/// the file's full size. +struct Source<'a> { + input: &'a Input, + layer: &'a str, + path: &'a str, + full: (u32, u32), +} + +impl Source<'_> { + /// `part` of the file, read at its full size, holding all of columns `cols` and rows `rows`, + /// with where it lies on the full grid, and its count in [`rustgis_data::memory::held`]. + fn block( + &self, + cols: (u32, u32), + rows: (u32, u32), + ) -> Result<(rustgis_data::raster::PartRead, std::sync::Arc), String> { + let (fw, fh) = self.full; + let f = |v: u32, n: u32| f64::from(v) / f64::from(n.max(1)); + let part = Part::new(f(cols.0, fw), f(rows.0, fh), f(cols.1, fw), f(rows.1, fh)) + .ok_or_else(|| format!("{}: a block of no pixels", self.layer))?; + let (read, count) = super::gp::read_tiled_part(self.layer, self.path, part, 1, self.input.held())?.ok_or_else(|| { + format!("{}: its file can't be read in blocks: it isn't the file the layer was read from any more (Reload Data)", self.layer) + })?; + let r = &read.raster; + let (ax, ay) = read.at; + if r.overview.is_some() || ax > cols.0 || ay > rows.0 || ax + r.width < cols.1 || ay + r.height < rows.1 { + return Err(format!("{}: a block of its file couldn't be read at its full size", self.layer)); + } + Ok((read, count)) + } + + /// Makes the result a row of blocks at a time: `cells` makes each block's values, and `row` + /// is given each full row of blocks (its first row, its rows of the full width, and the + /// file's full grid and system) as it is made. Each block is counted as the run's progress, its own steps not + /// ([`rustgis_analysis::control::uncounted`]), and Cancel is looked at between them. Gives the + /// full grid, its system, and how many values were rounded as they were read. + fn each_row( + &self, + cells: &impl Fn(&Raster) -> Result, String>, + mut row: impl FnMut(u32, &[f32], (rustgis_data::raster::GeoTransform, rustgis_data::raster::Crs)) -> Result<(), String>, + ) -> Result<(rustgis_data::raster::GeoTransform, rustgis_data::raster::Crs, u64), String> { + let (fw, fh) = self.full; + let tile = cogwrite::TILE; + let (across, down) = (fw.div_ceil(BLOCK_COLUMNS), fh.div_ceil(tile)); + rustgis_data::progress::begin((across as usize).saturating_mul(down as usize)); + let (mut rounded, mut placed) = (0u64, None); + for by in 0..down { + let (r0, r1) = (by * tile, ((by + 1) * tile).min(fh)); + let mut rows = rustgis_analysis::rasterops::new_band(fw as usize, (r1 - r0) as usize, NODATA)?; + for bx in 0..across { + let (c0, c1) = (bx * BLOCK_COLUMNS, ((bx + 1) * BLOCK_COLUMNS).min(fw)); + // The block's own steps don't count: the run counts blocks. + // Counted as held until its values are placed. + let ((read, _count), values) = rustgis_analysis::control::uncounted(|| -> Result<_, String> { + let read = self.block((c0, c1), (r0, r1))?; + let values = cells(&read.0.raster)?; + Ok((read, values)) + })?; + let r = &read.raster; + let (ax, ay) = read.at; + if values.len() != r.width as usize * r.height as usize { + return Err(format!("{}: a block's values aren't its pixels", self.layer)); + } + placed.get_or_insert((read.grid.0, r.crs)); + rounded = rounded.saturating_add(r.rounded.iter().sum::()); + let pw = r.width as usize; + for y in r0..r1 { + let src = (y - ay) as usize * pw + (c0 - ax) as usize; + let dst = (y - r0) as usize * fw as usize + c0 as usize; + let n = (c1 - c0) as usize; + if let (Some(s), Some(d)) = (values.get(src..src + n), rows.get_mut(dst..dst + n)) { + d.copy_from_slice(s); + } + } + rustgis_data::progress::step(1).map_err(|e| e.to_string())?; + } + let placed = placed.ok_or_else(|| format!("{}: it has no pixels", self.layer))?; + row(r0, &rows, placed)?; + } + let (grid, crs) = placed.ok_or_else(|| format!("{}: it has no pixels", self.layer))?; + Ok((grid, crs, rounded)) + } +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index ec8cf0cf73..5cfd7da7f8 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -29,6 +29,8 @@ pub mod graphics; pub mod group; pub mod history; pub mod imagery; +#[cfg(not(target_arch = "wasm32"))] +pub(crate) mod in_blocks; pub mod items; pub mod labels; pub mod layer; diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 4f6729a3e3..c00def6cfd 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -147,6 +147,12 @@ impl Input { &self.held } + /// The layer's name and its file, for a layer read in place from a file on this computer. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn file(&self) -> Option<(&str, &str)> { + self.file.as_ref().map(|(name, path)| (name.as_str(), path.as_str())) + } + /// The raster the work reads: within a run ([`reading_files`]), a layer read in place from a /// file on this computer is read again from it, at the finest level the run can hold (the /// full image when it fits), once for the run however many inputs name it; otherwise, and for @@ -413,10 +419,18 @@ pub(crate) fn made_layer(name: String, layer: rustgis_map::RasterLayer, extra: O /// what the command says besides (`extra`), and what it does then. pub(crate) fn add_made(s: &mut Session, m: Made) -> CmdResult { let Made { name, layer, extra, then, inputs, staged, .. } = m; - if let Some((file, said)) = staged { - let path = file.destination().display().to_string(); - file.commit().map_err(|e| if said.is_empty() { format!("{path}: {e}") } else { format!("{path}: {e} ({})", said.join("; ")) })?; - } + let layer = match staged { + Some((file, said)) => { + let dest = file.destination().to_path_buf(); + let path = dest.display().to_string(); + file.commit() + .map_err(|e| if said.is_empty() { format!("{path}: {e}") } else { format!("{path}: {e} ({})", said.join("; ")) })?; + #[cfg(not(target_arch = "wasm32"))] + let layer = installed(layer, &dest); + layer + } + None => layer, + }; rustgis_data::provenance::record(inputs); let mut v = super::raster::add_raster(s, &name, layer)?; if let (Some(Value::Object(more)), Some(o)) = (extra, v.as_object_mut()) { @@ -428,6 +442,19 @@ pub(crate) fn add_made(s: &mut Session, m: Made) -> CmdResult { Ok(v) } +/// `layer`, made to read the file just installed at `dest`: one read in place pairs its reads of +/// the file with the file as installed, as one added from it does, so a command can read it at +/// once. +#[cfg(not(target_arch = "wasm32"))] +fn installed(mut layer: rustgis_map::RasterLayer, dest: &std::path::Path) -> rustgis_map::RasterLayer { + if layer.tiled + && let (Some(revision), Some(held)) = (rustgis_data::raster::FileRevision::of(dest), layer.data.as_mut()) + { + std::sync::Arc::make_mut(held).set_source_revision(revision); + } + layer +} + /// What the remaps of a raster function, a chain or a suitability met: their ranges that match /// nothing, with the raster each was given for, and the first raster a remap left without a /// cell with a value. diff --git a/crates/engine/src/policy/effects.rs b/crates/engine/src/policy/effects.rs index 2f51fafb62..669e702315 100644 --- a/crates/engine/src/policy/effects.rs +++ b/crates/engine/src/policy/effects.rs @@ -94,6 +94,11 @@ pub(super) fn declared(spec: &CommandSpec, params: &Value) -> Effects { /// Adds only source reach of the actual current execution targets, without opening them. pub(super) fn command(s: &crate::cmd::InputContext<'_>, spec: &CommandSpec, params: &Value, layer: Option<&rustgis_map::Layer>) -> Effects { let mut effects = declared(spec, params); + // A result too large to hold, made a block at a time, is written to the results folder (#2865). + #[cfg(not(target_arch = "wasm32"))] + if crate::cmd::in_blocks::writes_file(s, spec.id, params) { + effects = effects.with(Effect::Files); + } effects = effects.union(match spec.id { "map.zoomToTiles" => crate::cmd::tiles::metadata_reach(s, params), "map.search" => crate::cmd::search::metadata_reach(s, params), diff --git a/crates/engine/src/tests/tiled_files.rs b/crates/engine/src/tests/tiled_files.rs index febf2a6c77..2f8a0dad12 100644 --- a/crates/engine/src/tests/tiled_files.rs +++ b/crates/engine/src/tests/tiled_files.rs @@ -451,3 +451,139 @@ fn a_clip_by_extent_reads_only_its_part_of_a_tiled_file() { 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"); } + +/// Holds files whole for a cell-by-cell command up to `max` samples on this thread while it +/// lives ([`crate::cmd::in_blocks::BLOCKS_PAST`]), then as before. +struct BlocksPast; + +impl BlocksPast { + fn at(max: usize) -> BlocksPast { + crate::cmd::in_blocks::BLOCKS_PAST.with(|c| c.set(Some(max))); + BlocksPast + } +} + +impl Drop for BlocksPast { + fn drop(&mut self) { + crate::cmd::in_blocks::BLOCKS_PAST.with(|c| c.set(None)); + } +} + +/// Indices over a layer read in place whose file is too large to read whole at its full size run +/// a block at a time (#2865): the result is the index of the file held whole, pixel for pixel, at +/// its full size. One too large to hold is written to a tiled GeoTIFF in the project's results +/// folder, which the new layer reads in place and another command can read at once, and said; the +/// Assistant asks before such a run, as it writes a file. A run cancelled at any of its checks, or +/// never added, leaves nothing behind, the folder included, and one run again makes it. A result +/// that fits is held, with no file. A script step that can't be stopped is refused. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn indices_over_a_file_too_large_to_read_whole_run_a_block_at_a_time() { + use crate::cmd::workflows::{raster_abandon, raster_land, raster_start}; + use crate::policy::{Call, Effects, Outcome, Revocation, Scope}; + struct Live; + impl Revocation for Live { + fn allows(&self, _: Effects) -> bool { + true + } + } + let d = dir("blocks"); + let path = thousandths(&d); + let ndvi = json!({"layer": "checks", "index": "ndvi", "red": 1, "nir": 2, "name": "index"}); + // The index of the file held whole. + let want = { + let mut whole = Session::new(Project::default()); + whole.run("layer.addData", &json!({"path": path})).unwrap(); + whole.run("raster.index", &ndvi).unwrap(); + raster(&whole, "index").data.clone().unwrap() + }; + let same = |got: &Raster, why: &str| { + assert_eq!((got.width, got.height, got.transform, got.nodata), (want.width, want.height, want.transform, want.nodata), "{why}"); + assert!(got.bands[0].data == want.bands[0].data, "{why}: the index of the file held whole"); + }; + let _held = HeldWhole::at(1_000_000); + let mut s = Session::new(Project::default()); + s.path = Some(d.join("Survey.rgis")); + s.run("layer.addData", &json!({"path": path})).unwrap(); + let folder = d.join("Survey.rgis.data"); + { + // Read in blocks, but a result of a million pixels fits: held, with no file. + let _blocks = BlocksPast::at(1_000_000); + let mark = s.notice_mark(); + s.run("raster.index", &ndvi).unwrap(); + let rl = raster(&s, "index"); + assert!(!rl.tiled && rl.path.is_none(), "held, with no file"); + same(rl.data.as_ref().unwrap(), "held"); + assert!(!folder.exists(), "no folder for a result held"); + assert!(!said(&s, mark).iter().any(|n| n.contains("written to"))); + s.run("layer.remove", &json!({"layer": "index"})).unwrap(); + } + let _blocks = BlocksPast::at(900_000); + // The Assistant asks before a run that writes a file. + let scope = Scope::assistant(7, std::sync::Arc::new(Live)); + assert!(matches!(s.review(&scope, &Call::command("raster.index", ndvi.clone())), Outcome::NeedsApproval(_))); + // A script step nobody can stop is refused, with what to do. + let script = format!("raster.index {ndvi}"); + let e = s.run("script.run", &json!({"script": script})).unwrap_err(); + assert!(e.contains("a block at a time") && e.contains("run it on its own"), "{e}"); + let run = |s: &mut Session, p: &serde_json::Value, control: &std::sync::Arc| { + let run = raster_start(s, "raster.index", p).unwrap(); + let id = run.id; + (id, run.run(control)) + }; + let count = rustgis_analysis::control::Control::cancelled_at_look(u64::MAX); + let (id, made) = run(&mut s, &ndvi, &count); + let looks = count.looked(); + assert!(looks > 6, "{looks} checks: it looks at Cancel between its blocks"); + // Made but never added: its file and the folder made for it go with it. + drop(made); + raster_abandon(&mut s, id); + assert!(!folder.exists(), "a result never added left {folder:?}"); + // Cancelled at its checks (a spread of them, and its last ones): nothing left. Its threads + // share the count, so a run can end with fewer checks than the count's: one that never got to + // check `n` makes its result, which goes when it isn't added. + let checks: std::collections::BTreeSet = + (1..=looks).step_by((looks as usize / 64).max(1)).chain(looks.saturating_sub(10)..=looks).collect(); + for n in checks { + let control = rustgis_analysis::control::Control::cancelled_at_look(n); + let (id, made) = run(&mut s, &ndvi, &control); + match made { + Err(e) => assert!(e.contains("cancelled"), "check {n}: {e}"), + Ok(m) => { + assert!(control.looked() < n, "check {n} of {}: not cancelled", control.looked()); + drop(m); + } + } + raster_abandon(&mut s, id); + assert!(!folder.exists(), "check {n}: left {folder:?}"); + } + // Run to the end, and added as the app adds it. + let mark = s.notice_mark(); + let (id, made) = run(&mut s, &ndvi, &rustgis_analysis::control::Control::new()); + assert!(raster_land(&mut s, id, made.unwrap()).unwrap()); + let v = s.run("raster.index", &json!({"ran": id})).unwrap(); + let file = folder.join("index.tif"); + assert_eq!(v["path"], json!(file.display().to_string())); + let rl = raster(&s, "index"); + assert!(rl.tiled, "the result is read in place from its file"); + assert_eq!(rl.path.as_deref(), Some(file.display().to_string().as_str())); + // It holds the file's overview the reader picks, as when the project is opened again. + assert_eq!(rl.data.as_ref().map(|r| (r.width, r.overview)), Some((500, Some((1000, 1000))))); + same(&rustgis_data::raster::read_path(&file).unwrap(), "written"); + let notes = said(&s, mark); + assert!( + notes.iter().any(|n| n.contains("a block at a time") && n.contains("1000 × 1000") && n.contains("Survey.rgis.data")), + "{notes:?}" + ); + // The result read in place feeds another run at once, a block at a time too. + let again = json!({"layer": "index", "index": "ndvi", "red": 1, "nir": 1, "name": "again"}); + let (id, made) = run(&mut s, &again, &rustgis_analysis::control::Control::new()); + assert!(raster_land(&mut s, id, made.unwrap()).unwrap()); + s.run("raster.index", &json!({"ran": id})).unwrap(); + assert!(folder.join("again.tif").is_file()); + // Made again, it takes a name of its own. + let (id, made) = run(&mut s, &ndvi, &rustgis_analysis::control::Control::new()); + assert!(raster_land(&mut s, id, made.unwrap()).unwrap()); + s.run("raster.index", &json!({"ran": id})).unwrap(); + assert!(folder.join("index 2.tif").is_file()); +} diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 18e36e5ee5..0020635867 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1684,6 +1684,16 @@ so reading it takes as long as decoding the whole file once. A cloud-optimised G web address is read in place instead, a tile at a time (see [Files on the web](data-formats.md#files-on-the-web)). +On the desktop, a tiled GeoTIFF on this computer too large to hold, with overviews, is read in +place too: the map draws the part in view at the level it needs. Commands that make a raster from +it read the file again as they run. **Clip** by an extent reads only the part under the extent, +at the file's full resolution when that part fits. **Indices** work a block of tiles at a time at +the file's full resolution. A result of up to 120 million pixels is held, as any other; a larger +one is written to a tiled GeoTIFF in the project's results folder beside it (`Survey.rgis.data` +for `Survey.rgis`), or in RustGIS's own folder for a project not saved yet, and the new layer +reads it in place; a notice says where it is. The other commands read the finest level of the file +they can hold, and say which. + The web app opens a picked or dropped file of up to 256 MB whole. A larger GeoTIFF is read a part at a time instead: its header, then only the tiles of the overview it opens from. A cloud-optimised file opens however large it is, as long as those parts fit in 256 MB (a 436 MB From d5adf9e9b66aa4dd98b563998b986ae1fcfa70ac Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 18:03:54 -0600 Subject: [PATCH 2/3] fix(raster): a block run cancelled while it writes its file says it was cancelled The Cancel came back as a format error prefixed with the file's path; it is read back as itself, as on the path that holds its result. Comments made clearer. --- crates/data/src/raster/cogwrite.rs | 4 +++- crates/engine/src/cmd/in_blocks.rs | 8 +++++--- crates/engine/src/tests/tiled_files.rs | 2 +- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/crates/data/src/raster/cogwrite.rs b/crates/data/src/raster/cogwrite.rs index d17c08eee5..60724a6352 100644 --- a/crates/data/src/raster/cogwrite.rs +++ b/crates/data/src/raster/cogwrite.rs @@ -1225,7 +1225,9 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { } (w, h) = (w.div_ceil(2), h.div_ceil(2)); } - // Each level a half the size of the one before: twice a row each at most, halving. + // Rows waiting at each level after the first: at most a row of tiles of that level and the + // half-size rows just made for it, each level half as wide as the one before, so two + // full-width rows hold them all. let levels = row.saturating_mul(2); let tables = tiles.saturating_mul(64); let compressing = (crate::threads::max() as u64).saturating_mul(u64::from(TILE) * u64::from(TILE) * 4 * (2 + AHEAD as u64)); diff --git a/crates/engine/src/cmd/in_blocks.rs b/crates/engine/src/cmd/in_blocks.rs index 734c27e191..cd7f2ce8be 100644 --- a/crates/engine/src/cmd/in_blocks.rs +++ b/crates/engine/src/cmd/in_blocks.rs @@ -146,7 +146,8 @@ impl Blocks { /// read and made in turn, counted as the run's progress, Cancel looked at between them. A /// result too large to hold is written a row of tiles at a time beside its place in the /// results folder, and put there as the layer is added, which reads it in place; a run - /// cancelled, failed or never added leaves nothing behind, a folder it made included while + /// cancelled, failed or never added leaves no file behind, nor the results folder when it made + /// it (not the folders around it, the project's own when it is saved) while /// nothing else is in it (one another run wrote into too can stay, empty, once both their /// results are gone). pub(crate) fn run(self, cells: impl Fn(&Raster) -> Result, String>) -> Result { @@ -223,7 +224,8 @@ impl Blocks { } stream.as_mut().map_or(Ok(()), |s: &mut cogwrite::TileStream<_>| s.put(rows).map_err(|e| e.to_string())) }) - .map_err(rustgis_data::DataError::Format)?; + // A Cancel stays one, as on the path that holds its result. + .map_err(rustgis_data::DataError::of_conversion)?; let (info, overview) = stream.ok_or_else(|| rustgis_data::DataError::Format(format!("{layer}: it has no pixels")))?.finish()?; Ok::<_, rustgis_data::DataError>((info, overview, rounded)) @@ -328,7 +330,7 @@ impl Source<'_> { for bx in 0..across { let (c0, c1) = (bx * BLOCK_COLUMNS, ((bx + 1) * BLOCK_COLUMNS).min(fw)); // The block's own steps don't count: the run counts blocks. - // Counted as held until its values are placed. + // The block's count in what is held lasts until its values are copied into the row. let ((read, _count), values) = rustgis_analysis::control::uncounted(|| -> Result<_, String> { let read = self.block((c0, c1), (r0, r1))?; let values = cells(&read.0.raster)?; diff --git a/crates/engine/src/tests/tiled_files.rs b/crates/engine/src/tests/tiled_files.rs index 2f8a0dad12..b189ae9ebc 100644 --- a/crates/engine/src/tests/tiled_files.rs +++ b/crates/engine/src/tests/tiled_files.rs @@ -548,7 +548,7 @@ fn indices_over_a_file_too_large_to_read_whole_run_a_block_at_a_time() { let control = rustgis_analysis::control::Control::cancelled_at_look(n); let (id, made) = run(&mut s, &ndvi, &control); match made { - Err(e) => assert!(e.contains("cancelled"), "check {n}: {e}"), + Err(e) => assert!(e.starts_with("Indices was cancelled"), "check {n}: {e}"), Ok(m) => { assert!(control.looked() < n, "check {n} of {}: not cancelled", control.looked()); drop(m); From 2dc197f9d880f312299ecbe7dd38aa8d5a70a14d Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 18:16:52 -0600 Subject: [PATCH 3/3] fix(raster): blocks read their exact pixels, and a block run follows the window's thread - `Part::pixels` gives a part in whole pixels of the full image, read as exactly those at the full size; `Part::span` no longer snaps edges, so a part given in fractions takes every pixel it touches. - A script step is refused only on the app's window thread (`on_window_thread`), not on every session nobody can stop: the command line and Python run it. - A result's file name is cut to 200 bytes, so its temporary name fits. - Overview pixels leave out infinite values, as the other writer does, and a row of tiles begun is finished from the rows given before whole ones are written from them. --- crates/data/src/raster/cogwrite.rs | 45 ++++++++++++++++------ crates/data/src/raster/mod.rs | 53 +++++++++++++++++++------- crates/engine/src/cmd/in_blocks.rs | 19 ++++++--- crates/engine/src/tests/tiled_files.rs | 8 +++- 4 files changed, 92 insertions(+), 33 deletions(-) diff --git a/crates/data/src/raster/cogwrite.rs b/crates/data/src/raster/cogwrite.rs index 60724a6352..fa16e6da48 100644 --- a/crates/data/src/raster/cogwrite.rs +++ b/crates/data/src/raster/cogwrite.rs @@ -1263,20 +1263,28 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { // Taken while its rows are written, which give the next level its own. let mut pending = self.pending.get_mut(i).map(std::mem::take).unwrap_or_default(); let mut rest = rows; - if pending.is_empty() { - // Whole rows of tiles are written from the rows given, not copied first. - while rest.len() >= tile_rows { - let (row, after) = rest.split_at(tile_rows); - self.write_row(i, row)?; - rest = after; + let room = |n: usize, pending: &mut Vec| { + pending.try_reserve(n).map_err(|_| err("too little memory for the rows of a level waiting to be written")) + }; + // A row of tiles begun: finished from the rows given, and written. + if !pending.is_empty() { + let (head, after) = rest.split_at(tile_rows.saturating_sub(pending.len()).min(rest.len())); + room(head.len(), &mut pending)?; + pending.extend_from_slice(head); + rest = after; + if pending.len() == tile_rows { + self.write_row(i, &pending)?; + pending.clear(); } } - pending.try_reserve(rest.len()).map_err(|_| err("too little memory for the rows of a level waiting to be written"))?; - pending.extend_from_slice(rest); - while pending.len() >= tile_rows { - self.write_row(i, pending.get(..tile_rows).unwrap_or_default())?; - pending.drain(..tile_rows); + // Whole rows of tiles are written from the rows given, not copied first. + while pending.is_empty() && rest.len() >= tile_rows { + let (row, after) = rest.split_at(tile_rows); + self.write_row(i, row)?; + rest = after; } + room(rest.len(), &mut pending)?; + pending.extend_from_slice(rest); if let Some(p) = self.pending.get_mut(i) { *p = pending; } @@ -1377,7 +1385,7 @@ fn stream_plan() -> Plan { fn average_rows(rows: &[f32], w: usize, nodata: f32) -> Vec { let h = rows.len() / w.max(1); let (hw, hh) = (w.div_ceil(2), h.div_ceil(2)); - let valid = |v: f32| !v.is_nan() && v != nodata; + let valid = |v: f32| v.is_finite() && v != nodata; let mut out = Vec::with_capacity(hw * hh); for y in 0..hh { for x in 0..hw { @@ -1414,6 +1422,19 @@ mod tests { Raster::new("t", w, h, bands, gt, Crs::from_epsg(32617).unwrap(), nodata, color, data_type).unwrap() } + /// An overview's pixel is the mean of the pixels with a value it covers: none, NaN or infinite + /// left out, an odd last row or column covering itself alone, and no-data where it covers + /// none with one. + #[test] + fn overview_rows_average_the_pixels_with_a_value() { + let nd = -9999.0; + assert_eq!(average_rows(&[1.0, f32::NAN, 5.0], 3, nd), [1.0, 5.0]); + assert_eq!(average_rows(&[f32::INFINITY, 2.0, 4.0, 6.0], 2, nd), [4.0]); + assert_eq!(average_rows(&[nd, f32::NAN, 3.0, 8.0, nd, nd], 3, nd), [8.0, 3.0]); + assert_eq!(average_rows(&[nd, nd, 1.0, 3.0], 2, nd), [2.0]); + assert_eq!(average_rows(&[nd, f32::NEG_INFINITY], 2, nd), [nd]); + } + /// A raster streamed in pieces of uneven rows (#2865) reads back pixel for pixel, its no-data /// value kept, and each overview the average two by two of the level before; the layout's /// reader finds every level. diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 7d59fce302..92f1936af3 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -1436,6 +1436,9 @@ pub struct Part { top: f64, right: f64, bottom: f64, + /// For a part given in whole pixels of the full image ([`Part::pixels`]): its columns and + /// rows (half-open), and the full image's size they are of. + pixels: Option<((u32, u32), (u32, u32), (u32, u32))>, } impl Part { @@ -1448,21 +1451,39 @@ impl Part { top, right, bottom, + pixels: None, }) } + /// The part of columns `cols` and rows `rows` (half-open) of a full image `full` in size: at + /// the full size, exactly those pixels, which fractions can't always say (`53248 / 83517` of + /// the width multiplies back to `53247.99999999999`), so parts next to each other share none; + /// at a coarser level, the pixels covering them, as [`Part::new`]'s. `None` when they leave + /// nothing of the image. + pub fn pixels(cols: (u32, u32), rows: (u32, u32), full: (u32, u32)) -> Option { + let cols = (cols.0.min(full.0), cols.1.min(full.0)); + let rows = (rows.0.min(full.1), rows.1.min(full.1)); + let f = |v: u32, n: u32| f64::from(v) / f64::from(n.max(1)); + let mut part = Part::new(f(cols.0, full.0), f(rows.0, full.1), f(cols.1, full.0), f(rows.1, full.1))?; + part.pixels = Some((cols, rows, full)); + Some(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. 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 { - // An edge a rounding error from a pixel's edge is on it: a part made from whole pixels - // (`53248 / 83517` of the width, say, which multiplies back to `53247.99999999999`) is - // those pixels, not one more each way. - let snap = |v: f64| if (v - v.round()).abs() < 1e-6 { v.round() } else { v }; + // Whole pixels of the full image, read at the full size: those pixels. + if let Some((cols, rows, full)) = self.pixels + && full == (w, h) + && extent == (f64::from(w), f64::from(h)) + { + return geotiff::Span { cols, rows }; + } let edges = |a: f64, b: f64, n: u32, units: f64| { - let start = (snap(a * units).floor() as u32).min(n.saturating_sub(1)); - (start, (snap(b * units).ceil() as u32).min(n).max(start.saturating_add(1).min(n))) + 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, extent.0), rows: edges(self.top, self.bottom, h, extent.1) } } @@ -2166,20 +2187,24 @@ fn extent_of(transform: &GeoTransform, transformer: &Transformer, width: u32, he pub(crate) mod tests { use super::*; - /// A part made from whole pixels of a grid is those pixels, whatever the fractions round to: - /// blocks of a file next to each other share no pixel (#2865), and an edge between pixels - /// still takes both. + /// A part given in whole pixels of the full image is those pixels at the full size, whatever + /// its fractions round to: blocks of a file next to each other share no pixel (#2865). A part + /// given in fractions takes every pixel it touches, however little of one, and a part in + /// pixels read at a coarser level the pixels covering them. #[test] fn a_part_of_whole_pixels_is_those_pixels() { let (w, h) = (83_517u32, 78_739u32); + let full = (f64::from(w), f64::from(h)); for (c0, c1, r0, r1) in [(53_248u32, 57_344u32, 512u32, 1024u32), (0, 4096, 78_336, 78_739), (81_920, 83_517, 0, 512)] { - let f = |v: u32, n: u32| f64::from(v) / f64::from(n); - let part = Part::new(f(c0, w), f(r0, h), f(c1, w), f(r1, h)).unwrap(); - let span = part.span((w, h), (f64::from(w), f64::from(h))); + let span = Part::pixels((c0, c1), (r0, r1), (w, h)).unwrap().span((w, h), full); assert_eq!((span.cols, span.rows), ((c0, c1), (r0, r1))); } - let between = Part::new(0.25, 0.25, 0.5005, 0.5).unwrap().span((1000, 1000), (1000.0, 1000.0)); - assert_eq!((between.cols, between.rows), ((250, 501), (250, 500))); + let half = + Part::pixels((53_248, 57_344), (512, 1024), (w, h)).unwrap().span((w.div_ceil(2), h.div_ceil(2)), (full.0 / 2.0, full.1 / 2.0)); + assert!(half.cols.0 <= 26_624 && half.cols.1 >= 28_672 && half.rows == (256, 512), "the pixels covering it: {half:?}"); + let tiny = 2f64.powi(-32); + let between = Part::new(0.5 - tiny, 0.25, 0.5 + tiny, 0.5).unwrap().span((1024, 1024), (1024.0, 1024.0)); + assert_eq!((between.cols, between.rows), ((511, 513), (256, 512)), "both pixels it touches"); } #[test] diff --git a/crates/engine/src/cmd/in_blocks.rs b/crates/engine/src/cmd/in_blocks.rs index cd7f2ce8be..8351bad7ae 100644 --- a/crates/engine/src/cmd/in_blocks.rs +++ b/crates/engine/src/cmd/in_blocks.rs @@ -101,7 +101,7 @@ pub(crate) fn writes_file(context: &impl super::InputSource, id: &str, params: & /// when this computer gives no folder to write it to. pub(crate) fn plan(s: &Session, input: &Input, out: &str) -> Result, String> { let (Some(full), Some((layer, path))) = (too_large(input), input.file()) else { return Ok(None) }; - if s.steps_running > 0 && !s.stoppable { + if s.steps_running > 0 && s.on_window_thread { return Err(format!( "{layer}: its full {} × {} pixels are made a block at a time, which a script step can't do without holding the window: run it on its own", full.0, full.1 @@ -114,6 +114,16 @@ pub(crate) fn plan(s: &Session, input: &Input, out: &str) -> Result String { + let safe = super::items::safe(name); + let end = safe.char_indices().map(|(i, c)| i + c.len_utf8()).take_while(|end| *end <= 200).last().unwrap_or(0); + safe.get(..end).unwrap_or_default().to_string() +} + /// Makes the results folder `folder` (and the folders it is in): whether this call made it, rather /// than finding it there. fn make_folder(folder: &Path) -> Result { @@ -198,7 +208,7 @@ impl Blocks { let mut made_folder = make_folder(&folder)?; let (mut taken, mut i, mut remade) = (None, 1u32, 0); while i < 10_000 { - let stem = super::items::safe(&out); + let stem = stem(&out); let dest = folder.join(if i == 1 { format!("{stem}.tif") } else { format!("{stem} {i}.tif") }); // The file's name is reserved before it is written: two runs never take the same one. let wrote = rustgis_data::io::stage_streamed_new(&dest, made_folder.then_some(folder.as_path()), |w| { @@ -294,10 +304,7 @@ impl Source<'_> { cols: (u32, u32), rows: (u32, u32), ) -> Result<(rustgis_data::raster::PartRead, std::sync::Arc), String> { - let (fw, fh) = self.full; - let f = |v: u32, n: u32| f64::from(v) / f64::from(n.max(1)); - let part = Part::new(f(cols.0, fw), f(rows.0, fh), f(cols.1, fw), f(rows.1, fh)) - .ok_or_else(|| format!("{}: a block of no pixels", self.layer))?; + let part = Part::pixels(cols, rows, self.full).ok_or_else(|| format!("{}: a block of no pixels", self.layer))?; let (read, count) = super::gp::read_tiled_part(self.layer, self.path, part, 1, self.input.held())?.ok_or_else(|| { format!("{}: its file can't be read in blocks: it isn't the file the layer was read from any more (Reload Data)", self.layer) })?; diff --git a/crates/engine/src/tests/tiled_files.rs b/crates/engine/src/tests/tiled_files.rs index b189ae9ebc..29c8ff6575 100644 --- a/crates/engine/src/tests/tiled_files.rs +++ b/crates/engine/src/tests/tiled_files.rs @@ -522,9 +522,11 @@ fn indices_over_a_file_too_large_to_read_whole_run_a_block_at_a_time() { // The Assistant asks before a run that writes a file. let scope = Scope::assistant(7, std::sync::Arc::new(Live)); assert!(matches!(s.review(&scope, &Call::command("raster.index", ndvi.clone())), Outcome::NeedsApproval(_))); - // A script step nobody can stop is refused, with what to do. + // A script step on the app's window thread is refused, with what to do. let script = format!("raster.index {ndvi}"); + s.on_window_thread = true; let e = s.run("script.run", &json!({"script": script})).unwrap_err(); + s.on_window_thread = false; assert!(e.contains("a block at a time") && e.contains("run it on its own"), "{e}"); let run = |s: &mut Session, p: &serde_json::Value, control: &std::sync::Arc| { let run = raster_start(s, "raster.index", p).unwrap(); @@ -586,4 +588,8 @@ fn indices_over_a_file_too_large_to_read_whole_run_a_block_at_a_time() { assert!(raster_land(&mut s, id, made.unwrap()).unwrap()); s.run("raster.index", &json!({"ran": id})).unwrap(); assert!(folder.join("index 2.tif").is_file()); + // A script step off any window (the command line's, Python's) runs it. + let scripted = json!({"layer": "checks", "index": "ndvi", "red": 1, "nir": 2, "name": "scripted"}); + s.run("script.run", &json!({"script": format!("raster.index {scripted}")})).unwrap(); + assert!(folder.join("scripted.tif").is_file()); }