diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 548e134dfe..644b070420 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -477,7 +477,7 @@ raster.info layer? raster.mask layer? values? min? max? inside? clear? raster.measure layer? kind points base? raster.measurements clear? -raster.mosaic inputs name? path? +raster.mosaic inputs name? path? ran? raster.process layer operation extent? polygon? selectedOnly? factor? name? ran? raster.project layer crs? cellSize? origin? extent? grid? resampling? name? path? raster.rasterize layer field? value? nodata? crs? cellSize? origin? extent? grid? name? path? ran? diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 924e61c3e5..9f0420f424 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -76,7 +76,7 @@ pub fn commands() -> Vec { C::new("raster.process", "Process", "Analyze › Raster", process).inputs(process_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"layer": raster, "operation": "clip"|"resample", "extent"?: [minLon, minLat, maxLon, maxLat] (clip; the view when omitted), "polygon"?: polygon layer (clip to its selected or all polygons; cells outside become no-data, or see-through in a raster with alpha or a three-band colour one without no-data), "selectedOnly"?: bool (clip to selected polygons when true, all when false), "factor"?: n (resample: n×n pixels become one), "name"?: output, "ran"?: (internal: a raster the app has worked out)}"#), C::new("raster.mosaic", "Mosaic Rasters", "Analyze › Raster", raster_mosaic).inputs(mosaic_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params( - r#"{"inputs": [raster layer or file path, …] (two or more, in one coordinate system and cell size; where they overlap the first wins), "name"?: output, "path"?: GeoTIFF to write the mosaic to}"#, + r#"{"inputs": [raster layer or file path, …] (two or more, in one coordinate system and cell size; where they overlap the first wins), "name"?: output, "path"?: GeoTIFF to write the mosaic to, "ran"?: (internal: a raster the app has worked out)}"#, ), C::new("raster.editPixels", "Pixel Editor", "Imagery › Imagery Tools", edit_pixels).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"layer": raster, "polygon": [[lon, lat], …], "value"?: number (no-data when omitted), "band"?: 1-based (all when omitted)}"#), @@ -173,13 +173,6 @@ fn layer_of(r: Raster) -> Result { Ok(rustgis_map::RasterLayer::from_bytes(r, fname, bytes)) } -/// Adds a raster layer; classes get unique-value colours. -pub(crate) fn add(s: &mut Session, r: Raster, classes: bool) -> CmdResult { - let n = r.name.clone(); - let layer = if classes { class_layer(r)? } else { layer_of(r)? }; - super::raster::add_raster(s, &n, layer) -} - /// A raster of classes as a layer, each class a colour of its own. pub(crate) fn class_layer(r: Raster) -> Result { let mut layer = layer_of(r)?; @@ -480,7 +473,7 @@ fn warp_to_fit(s: &mut Session, p: &Value, layer: &str, r: &Raster) -> CmdResult // A file written is the layer's source; without one the pixels are kept in the project. let rl = match &path { Some(path) => { - let wrote = super::raster::write_and_report(s, &out, 0, true, path)?; + let wrote = super::raster::write_and_report(s, &out, 0, path)?; info["path"] = json!(path); info["cog"] = wrote.get("cog").cloned().unwrap_or(Value::Null); let e = out.extent(); @@ -832,12 +825,7 @@ pub(crate) fn rasterize_work(s: &Session, p: &Value) -> Result { - let (wrote, file) = super::raster::write_cog_staged( - &out, - 0, - path, - "export the resulting layer with share.exportRaster and give \"band\" for another", - )?; + let (wrote, file) = super::raster::write_cog_staged(&out, 0, path, super::raster::RESULT_BAND)?; written = wrote.notes; staged = Some(file); info["path"] = json!(path); @@ -947,7 +935,7 @@ fn add_output(s: &mut Session, out: Raster, path: Option, classes: bool, // A file written is the layer's source; without one the pixels are kept in the project. let mut rl = match &path { Some(path) => { - let wrote = super::raster::write_and_report(s, &out, 0, true, path)?; + let wrote = super::raster::write_and_report(s, &out, 0, path)?; info["path"] = json!(path); info["cog"] = wrote.get("cog").cloned().unwrap_or(Value::Null); RasterLayer::from_path(out, path.clone()) @@ -2085,33 +2073,42 @@ pub(crate) fn mosaic_stays_in_project(s: &Session, p: &Value) -> bool { /// Merges rasters on one grid (tiles of an elevation model, say) into one, keeping their /// coordinate system and cell size; where they overlap, the first input with data wins. +/// +/// Made on another thread from the app (`workflows::IN_BACKGROUND`), with progress and Cancel +/// ([`mosaic_rasters_work`]). fn raster_mosaic(s: &mut Session, p: &Value) -> CmdResult { - let inputs = p.get("inputs").and_then(Value::as_array).ok_or("inputs is a list of raster layers or file paths")?; - if inputs.len() < 2 { - return Err("a mosaic needs two or more rasters".into()); - } - if inputs.len() > MAX_MOSAIC_INPUTS { - return Err(format!("a mosaic takes at most {MAX_MOSAIC_INPUTS} inputs")); - } - // The name given, checked before any input is read; empty when none is (the first input's then). - let given = name(p, String::new())?; - let max = rustgis_data::raster::max_samples() as i64; - let mut rs: Vec> = Vec::with_capacity(inputs.len()); - // Each input's place on the first one's grid, and the bounds of them all so far. - let mut places: Vec<(i64, i64)> = Vec::with_capacity(inputs.len()); - let (mut c0, mut r0, mut c1, mut r1) = (0i64, 0i64, 0i64, 0i64); - // Each input is checked as it is read, so a mismatched or oversized set fails before the - // rest are loaded. What reading a file left out is said once they are all read. - let mut lost: Vec<(String, String)> = Vec::new(); - for v in inputs { + super::workflows::made_or_ran(s, p, "raster.mosaic") +} + +/// A mosaic's input as the command's start reads it of the session: a layer's raster, shared, or +/// the file the work reads. +enum MosaicInput { + Layer(Arc), + File(String), +} + +impl MosaicInput { + fn of(s: &Session, v: &Value) -> Result { let n = mosaic_name(v)?; - let r = if mosaic_reads_file(s, v) { - let r = rustgis_data::raster::read_path(std::path::Path::new(n)).map_err(|e| format!("{n}: {e}"))?; - lost.extend(r.lost.iter().map(|l| (n.to_string(), l.clone()))); - Arc::new(r) - } else { - mosaic_layer(s, v)? - }; + if mosaic_reads_file(s, v) { Ok(MosaicInput::File(n.to_string())) } else { mosaic_layer(s, v).map(MosaicInput::Layer) } + } +} + +/// The inputs a mosaic has taken, each checked against the first as it is taken ([`Self::take`]), +/// then joined ([`Self::join`]). +struct Tiles { + /// The most values the mosaic may hold. + max: i64, + rs: Vec>, + /// Each input's place on the first one's grid, and the bounds of them all so far. + places: Vec<(i64, i64)>, + from: (i64, i64), + to: (i64, i64), +} + +impl Tiles { + /// Takes `r` as the next input, or says why it can't join the ones before. + fn take(&mut self, r: Arc) -> Result<(), String> { // An overview would quietly coarsen the whole mosaic. if let Some((fw, fh)) = r.overview { return Err(format!( @@ -2119,7 +2116,7 @@ fn raster_mosaic(s: &mut Session, p: &Value) -> CmdResult { r.name, r.width, r.height )); } - let first = rs.first().unwrap_or(&r); + let first = self.rs.first().unwrap_or(&r); mosaic_matches(first, &r)?; // Snapped to whole cells only when it is already within a hundredth of one. let (c, rr) = first.transform.to_pixel(r.transform.to_world(0.0, 0.0)); @@ -2131,9 +2128,10 @@ fn raster_mosaic(s: &mut Session, p: &Value) -> CmdResult { return Err(format!("{}'s cells don't line up with {}'s: resample them onto one grid first", r.name, first.name)); } let (pc, pr) = (c.round() as i64, rr.round() as i64); - (c0, r0) = if rs.is_empty() { (pc, pr) } else { (c0.min(pc), r0.min(pr)) }; - (c1, r1) = (c1.max(pc + i64::from(r.width)), r1.max(pr + i64::from(r.height))); - let (w, h) = (c1 - c0, r1 - r0); + self.from = if self.rs.is_empty() { (pc, pr) } else { (self.from.0.min(pc), self.from.1.min(pr)) }; + self.to = (self.to.0.max(pc + i64::from(r.width)), self.to.1.max(pr + i64::from(r.height))); + let (w, h) = (self.to.0 - self.from.0, self.to.1 - self.from.1); + let max = self.max; let samples = w.saturating_mul(h).saturating_mul(r.band_count().max(1) as i64); if samples > max || w > i64::from(u32::MAX) || h > i64::from(u32::MAX) { return Err(format!( @@ -2141,101 +2139,191 @@ fn raster_mosaic(s: &mut Session, p: &Value) -> CmdResult { r.band_count() )); } - places.push((pc, pr)); - rs.push(r); - } - super::raster::say_losses(s, lost); - let first = rs.first().ok_or("a mosaic needs two or more rasters")?; - let (w, h) = (c1 - c0, r1 - r0); - if w <= 0 || h <= 0 { - return Err("the mosaic would be empty".into()); - } - let (w, h) = (w as u32, h as u32); - let nodata = first.nodata.or(Some(NODATA as f64)); - let fill = nodata.map(|v| v as f32).unwrap_or(NODATA); - let mut bands = (0..first.band_count()) - .map(|_| raster::filled(w as usize, h as usize, fill)) - .collect::, _>>() - .map_err(|e| e.to_string())?; - for (r, (pc, pr)) in rs.iter().zip(&places) { - let (dc, dr) = ((pc - c0) as usize, (pr - r0) as usize); - for (out, b) in bands.iter_mut().zip(&r.bands) { - for row in 0..r.height as usize { - let (Some(src), Some(dst)) = ( - b.data.get(row * r.width as usize..(row + 1) * r.width as usize), - out.get_mut((dr + row) * w as usize + dc..(dr + row) * w as usize + dc + r.width as usize), - ) else { - continue; - }; - for (d, v) in dst.iter_mut().zip(src) { - // Earlier inputs keep their cells; later ones only fill the gaps. - if (*d == fill || d.is_nan()) && r.is_valid(*v) { - *d = *v; + self.places.push((pc, pr)); + self.rs.push(r); + Ok(()) + } + + /// The mosaic, named `given` or after its first input; what it has to say goes to `notes`. Its + /// inputs' rows are counted, each band's, and Cancel is looked at about every [`MOSAIC_PIECE`] + /// cells copied; measuring the result ([`Raster::new`]'s statistics) doesn't look. + fn join(self, given: String, notes: &mut Notes) -> Result { + let Tiles { rs, places, from: (c0, r0), to: (c1, r1), .. } = self; + let first = rs.first().ok_or("a mosaic needs two or more rasters")?; + let (w, h) = (c1 - c0, r1 - r0); + if w <= 0 || h <= 0 { + return Err("the mosaic would be empty".into()); + } + let (w, h) = (w as u32, h as u32); + let nodata = first.nodata.or(Some(NODATA as f64)); + let fill = nodata.map(|v| v as f32).unwrap_or(NODATA); + let mut bands = (0..first.band_count()) + .map(|_| raster::filled(w as usize, h as usize, fill)) + .collect::, _>>() + .map_err(|e| e.to_string())?; + let rows = rs.iter().map(|r| (r.height as usize).saturating_mul(r.band_count())).fold(0, usize::saturating_add); + rustgis_data::progress::begin(rows); + for (r, (pc, pr)) in rs.iter().zip(&places) { + let (dc, dr) = ((pc - c0) as usize, (pr - r0) as usize); + let (rows, width) = (r.height as usize, r.width as usize); + let piece = (MOSAIC_PIECE / width.max(1)).max(1); + for (out, b) in bands.iter_mut().zip(&r.bands) { + for start in (0..rows).step_by(piece) { + let end = (start + piece).min(rows); + for row in start..end { + let (Some(src), Some(dst)) = ( + b.data.get(row * width..(row + 1) * width), + out.get_mut((dr + row) * w as usize + dc..(dr + row) * w as usize + dc + width), + ) else { + continue; + }; + for (d, v) in dst.iter_mut().zip(src) { + // Earlier inputs keep their cells; later ones only fill the gaps. + if (*d == fill || d.is_nan()) && r.is_valid(*v) { + *d = *v; + } + } } + rustgis_data::progress::step(end - start).map_err(|e| e.to_string())?; } } } - } - let o = first.transform.to_world(c0 as f64, r0 as f64); - let gt = GeoTransform { origin_x: o.x, origin_y: o.y, ..first.transform }; - let mut out = Raster::new( - if given.is_empty() { format!("{}_mosaic", first.name) } else { given }, - w, - h, - bands, - gt, - first.crs, - nodata, - first.color.clone(), - first.data_type.clone(), - ) - .map_err(|e| e.to_string())?; - // Band and class names and wavelengths are the first input's, as its cells are where they - // overlap; an input giving its bands other ones is said. - out.bands.iter_mut().zip(&first.bands).for_each(|(o, i)| { - o.name = i.name.clone(); - o.classes = i.classes.clone(); - o.wavelength = i.wavelength; - }); - out.copyright = first.copyright.clone(); - // The first input's metadata accompanies its pixels; report other credits rather than - // silently dropping them or attributing every input to the first one's owner. - super::raster::say_losses( - s, - rs.iter() + let o = first.transform.to_world(c0 as f64, r0 as f64); + let gt = GeoTransform { origin_x: o.x, origin_y: o.y, ..first.transform }; + let mut out = Raster::new( + if given.is_empty() { format!("{}_mosaic", first.name) } else { given }, + w, + h, + bands, + gt, + first.crs, + nodata, + first.color.clone(), + first.data_type.clone(), + ) + .map_err(|e| e.to_string())?; + // Band and class names and wavelengths are the first input's, as its cells are where they + // overlap; an input giving its bands other ones is said. + out.bands.iter_mut().zip(&first.bands).for_each(|(o, i)| { + o.name = i.name.clone(); + o.classes = i.classes.clone(); + o.wavelength = i.wavelength; + }); + out.copyright = first.copyright.clone(); + // The first input's metadata accompanies its pixels; report other credits rather than + // silently dropping them or attributing every input to the first one's owner. + let credits = rs + .iter() .skip(1) .filter(|r| r.copyright.is_some() && r.copyright != first.copyright) .map(|r| (r.name.clone(), "its copyright differs from the first input's and is not kept in the mosaic".to_string())) - .collect(), - ); - // Cells rounded when an input was read may be among those the mosaic keeps. - out.keep_rounded_marks(rs.iter().map(|r| &**r)); - let other: Vec<&str> = rs - .iter() - .skip(1) - .filter(|r| { - r.bands - .iter() - .zip(&first.bands) - .any(|(b, f)| b.name != f.name || b.classes != f.classes || !raster::pam::same_wavelength(b.wavelength, f.wavelength)) - }) - .map(|r| r.name.as_str()) - .collect(); - if !other.is_empty() { - s.notify( - format!("{}: band names, classes or wavelengths other than {}'s, which the mosaic keeps", other.join(", "), first.name), - false, - ); + .collect(); + notes.extend(super::raster::loss_lines(credits).into_iter().map(|n| (n, false))); + // Cells rounded when an input was read may be among those the mosaic keeps. + out.keep_rounded_marks(rs.iter().map(|r| &**r)); + let other: Vec<&str> = + rs.iter() + .skip(1) + .filter(|r| { + r.bands.iter().zip(&first.bands).any(|(b, f)| { + b.name != f.name || b.classes != f.classes || !raster::pam::same_wavelength(b.wavelength, f.wavelength) + }) + }) + .map(|r| r.name.as_str()) + .collect(); + if !other.is_empty() { + let note = + format!("{}: band names, classes or wavelengths other than {}'s, which the mosaic keeps", other.join(", "), first.name); + notes.push((note, false)); + } + Ok(out) } - let path = ps(p, "path").map(str::trim).filter(|p| !p.is_empty()).map(str::to_string); - if let Some(path) = &path { - super::raster::write_and_report(s, &out, 0, false, path)?; +} + +/// About how many cells a mosaic copies between two looks at Cancel: whole rows, one at least. +const MOSAIC_PIECE: usize = 1 << 20; + +/// What `raster.mosaic` reads of the session (each input's layer, or that it is a file, the name and +/// the path), and the work that reads the files, joins the inputs, writes the GeoTIFF to `path` when +/// given and makes the layer; its notices are said once the layer is added, or with its error when +/// it fails after the inputs are read. +/// +/// Each input is checked as it is taken, in their order, so a mismatched or oversized set fails +/// before the rest are read: the layers ahead of the first file as the command starts, the rest on +/// the work's thread. Cancel is looked at between inputs and as they are copied ([`Tiles::join`]), +/// and where a file format's reader and the GeoTIFF writer look: some formats are read without a +/// look. +pub(crate) fn mosaic_rasters_work(s: &Session, p: &Value) -> Result { + let inputs = p.get("inputs").and_then(Value::as_array).ok_or("inputs is a list of raster layers or file paths")?; + if inputs.len() < 2 { + return Err("a mosaic needs two or more rasters".into()); } - let mut v = add(s, out, false)?; - if let (Some(o), Some(path)) = (v.as_object_mut(), path) { - o.insert("path".into(), json!(path)); + if inputs.len() > MAX_MOSAIC_INPUTS { + return Err(format!("a mosaic takes at most {MAX_MOSAIC_INPUTS} inputs")); } - Ok(v) + // The name given, checked before any input is read; empty when none is (the first input's then). + let given = name(p, String::new())?; + let path = ps(p, "path").map(str::trim).filter(|p| !p.is_empty()).map(str::to_string); + let mut tiles = Tiles { max: raster::max_samples() as i64, rs: Vec::new(), places: Vec::new(), from: (0, 0), to: (0, 0) }; + // What the work takes, from the first file on, up to an input that is neither a file nor a + // layer: its error comes when the work gets there, as the inputs before it may have their own. + let mut rest: Vec> = Vec::new(); + for v in inputs { + match MosaicInput::of(s, v) { + Ok(MosaicInput::Layer(r)) if rest.is_empty() => tiles.take(r)?, + Err(e) if rest.is_empty() => return Err(e), + input => { + let last = input.is_err(); + rest.push(input); + if last { + break; + } + } + } + } + Ok(Box::new(move || { + // What reading a file left out is said once they are all read. + let mut lost: Vec<(String, String)> = Vec::new(); + for input in rest { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + let r = match input? { + MosaicInput::Layer(r) => r, + MosaicInput::File(n) => { + let r = raster::read_path(std::path::Path::new(&n)).map_err(|e| format!("{n}: {e}"))?; + lost.extend(r.lost.iter().map(|l| (n.clone(), l.clone()))); + Arc::new(r) + } + }; + tiles.take(r)?; + } + let mut notes: Notes = super::raster::loss_lines(lost).into_iter().map(|n| (n, false)).collect(); + let made = (|| -> Result { + // The inputs are let go of once joined, before the file is written. + let out = tiles.join(given, &mut notes)?; + let name = out.name.clone(); + // Written beside it, the file is put in its place as the layer is added: a run cancelled + // before then leaves the file there as it was. + let wrote = path.as_deref().map(|p| super::raster::write_plain_staged(&out, 0, p, super::raster::RESULT_BAND)).transpose()?; + let layer = layer_of(out)?; + let (written, staged) = wrote.map(|(wrote, file)| (wrote.notes, file)).unzip(); + let written = written.unwrap_or_default(); + // Said with the error should its file not go in place; what the file holds then isn't. + let said: Vec = notes.iter().map(|(n, _)| n.clone()).collect(); + let notes = std::mem::take(&mut notes); + let then: super::workflows::Then = Box::new(move |s: &mut Session, _: &mut Value| { + say(s, notes); + for note in written { + s.say_written(note); + } + }); + let made = super::workflows::made_layer(name, layer, path.map(|path| json!({"path": path})), Some(then)); + Ok(match staged { + Some(file) => made.committing(file, said), + None => made, + }) + })(); + made.map_err(|e| with_notes(e, ¬es)) + })) } /// Whether `r` can join a mosaic on `first`'s grid: one coordinate system, cell size and band count. diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index d1250b9b27..c7493e8f9f 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -489,14 +489,22 @@ pub(crate) fn as_scan(p: &Value) -> Result { } } -/// Says what reading several rasters left out, each `(raster, line)`: one notice a kind (the same -/// line), naming the rasters that share it (three, then a count), as AGENTS.md's Never silent asks. +/// Says what reading several rasters left out ([`loss_lines`]), a notice a line. +pub(crate) fn say_losses(s: &mut Session, losses: Vec<(String, String)>) { + for line in loss_lines(losses) { + s.notify(line, false); + } +} + +/// What reading several rasters left out, each `(raster, line)`, as it is said: one line a kind (the +/// same line), naming the rasters that share it (three, then a count), as AGENTS.md's Never silent +/// asks. /// /// Lines that differ only in their numbers ("1 scale…", "2 scale…") are one kind. When the /// numbers are the same for every raster the kind is said once; when they differ, each raster's /// own line is said (three rasters or fewer), or the range they give, for each of them ("4 /// rasters (a, b, c, …), each: 1–2 scale…"): never summed, since a size limit isn't a count. -pub(crate) fn say_losses(s: &mut Session, losses: Vec<(String, String)>) { +pub(crate) fn loss_lines(losses: Vec<(String, String)>) -> Vec { // A line's kind: its text with each number taken out, and those numbers. A number is a run of // digits standing as a word of its own: one inside a name (`scene2024.tif`) stays text. fn kind_of(line: &str) -> (Vec<&str>, Vec) { @@ -547,13 +555,12 @@ pub(crate) fn say_losses(s: &mut Session, losses: Vec<(String, String)>) { None => kinds.push((parts_owned, numbers.iter().map(|n| (*n, *n)).collect(), vec![(name, line)])), } } + let mut lines = Vec::new(); for (parts, ranges, named) in kinds { let differ = ranges.iter().any(|(lo, hi)| lo != hi); // A few rasters whose numbers differ: each its own, so none is lost in a range. if differ && named.len() <= 3 { - for (name, line) in named { - s.notify(format!("{name}: {line}"), false); - } + lines.extend(named.into_iter().map(|(name, line)| format!("{name}: {line}"))); continue; } let names: Vec = named.into_iter().map(|(name, _)| name).collect(); @@ -572,8 +579,9 @@ pub(crate) fn say_losses(s: &mut Session, losses: Vec<(String, String)>) { } }; let each = if differ { ", each" } else { "" }; - s.notify(format!("{who}{each}: {line}"), false); + lines.push(format!("{who}{each}: {line}")); } + lines } /// Opens a raster file by path; `ignored` is said with what reading it lost (options given that @@ -1305,6 +1313,9 @@ pub(super) fn write_geotiff_with_guidance( wrote_geotiff(r, bi, path, cog, band_hint) } +/// The band instruction of a file a tool writes of its result ([`write_geotiff_with_guidance`]). +pub(super) const RESULT_BAND: &str = "export the resulting layer with share.exportRaster and give \"band\" for another"; + /// [`write_geotiff_with_guidance`]'s Cloud Optimized GeoTIFF, written beside `path` and put in /// its place when the returned file is committed (as a background run's raster is added). pub(super) fn write_cog_staged( @@ -1317,6 +1328,30 @@ pub(super) fn write_cog_staged( Ok((wrote_geotiff(r, bi, path, Some(cog), band_hint)?, staged)) } +/// [`write_geotiff_with_guidance`]'s plain GeoTIFF, written beside `path` and put in its place when +/// the returned file is committed, as [`write_cog_staged`]'s is. It is encoded in memory first, as +/// `share.exportRaster`'s plain one is; Cancel is looked at as it is encoded and every megabyte +/// written. +pub(super) fn write_plain_staged( + r: &Raster, + bi: usize, + path: &str, + band_hint: &str, +) -> Result<(super::exports::Wrote, rustgis_data::io::StagedWrite), String> { + use std::io::Write; + let bytes = raster::geotiff::write(r, bi).map_err(|e| e.to_string())?; + let look = || rustgis_data::progress::check().map_err(std::io::Error::other); + let (staged, ()) = rustgis_data::io::stage_streamed(Path::new(path), |w| { + for piece in bytes.chunks(1 << 20) { + look()?; + w.write_all(piece)?; + } + look() + }) + .map_err(|e: std::io::Error| format!("{path}: {e}"))?; + Ok((wrote_geotiff(r, bi, path, None, band_hint)?, staged)) +} + /// What writing `r`'s band `bi` to `path` says. fn wrote_geotiff( r: &Raster, @@ -1347,10 +1382,10 @@ fn wrote_geotiff( }) } -/// Writes a tool's raster file and reports the same export notes as `share.exportRaster`. -pub(super) fn write_and_report(s: &mut Session, r: &Raster, bi: usize, cog: bool, path: &str) -> Result { - let wrote = - write_geotiff_with_guidance(r, bi, cog, path, "export the resulting layer with share.exportRaster and give \"band\" for another")?; +/// Writes a tool's raster file, a Cloud Optimized GeoTIFF, and reports the same export notes as +/// `share.exportRaster`. +pub(super) fn write_and_report(s: &mut Session, r: &Raster, bi: usize, path: &str) -> Result { + let wrote = write_geotiff_with_guidance(r, bi, true, path, RESULT_BAND)?; for note in wrote.notes { s.say_written(note); } diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 25d14a376e..0727202190 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -505,6 +505,7 @@ pub(crate) const IN_BACKGROUND: &[(&str, &str, Start)] = &[ ("stac.addIndex", "Add STAC Index", super::stac_bands::index_work), ("raster.process", "Process", super::imagery::process_work), ("raster.rasterize", "Polygons to Raster", super::imagery::rasterize_work), + ("raster.mosaic", "Mosaic Rasters", super::imagery::mosaic_rasters_work), ("imagery.mosaic", "Build Mosaic", super::imagery::mosaic_work), ("dl.classify", "Deep Learning", super::deeplearning::classify_work), ("embeddings.similarity", "Satellite Embedding Similarity", super::embeddings::similarity_work), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 044be76d4b..edf66a4baf 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -20841,6 +20841,8 @@ fn plugin_mosaics_of_project_layers_need_no_files() { json!({"inputs": ["west", "east.tif"]}), json!({"inputs": ["west", "../east.tif"]}), json!({"inputs": ["west", "east"], "name": "../elevation"}), + // A run to hand over is no way round it: what is named is asked about all the same. + json!({"inputs": ["west", "east.tif"], "ran": 1}), ] { let e = forward(&mut s, "eng-mosaic", "raster.mosaic", params.clone()).unwrap_err(); assert!(e.contains("'files' permission"), "{params}: {e}"); @@ -20852,6 +20854,7 @@ fn plugin_mosaics_of_project_layers_need_no_files() { (json!({"inputs": ["west", "Countries"]}), "no raster layer 'Countries'"), (json!({"inputs": ["west", 3]}), "each input is a raster layer's name or a file path"), (json!({"inputs": vec!["west"; 10_001]}), "at most 10000 inputs"), + (json!({"inputs": ["west", "east"], "ran": 1}), "no longer kept"), ] { let e = forward(&mut s, "eng-mosaic", "raster.mosaic", params.clone()).unwrap_err(); assert!(e.contains(why) && !e.contains("permission"), "{params}: {e}"); @@ -20914,16 +20917,11 @@ fn clip_resample_and_mosaic_run_with_imagery_off() { forward(&mut s, "eng-imagery-off", id, p).unwrap(); } check(&s, "plugin"); - // As the desktop app runs clip and resample: worked out on a thread, landed, then added by the - // command. A mosaic has no such run. + // As the desktop app runs them: worked out on a thread, landed, then added by the command. #[cfg(not(target_arch = "wasm32"))] { use crate::cmd::workflows::{raster_land, raster_start}; for (id, p) in commands("app") { - if id == "raster.mosaic" { - s.run(id, &p).unwrap(); - continue; - } let run = raster_start(&mut s, id, &p).unwrap(); let ran = run.id; let made = std::thread::spawn(move || run.run(&rustgis_analysis::control::Control::new())).join().unwrap().unwrap(); @@ -53727,6 +53725,141 @@ fn raster_tools_run_on_another_thread() { assert!(runs_in_background("raster.editPixels").is_none()); } +/// Mosaic Rasters made on another thread, as the app makes it (#2907): the cells, the answer, the +/// file and what it says are those of one made here, nothing is said and no file is put in place +/// before it lands, and it is refused with the same words, whether its start or its run refuses it. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_mosaic_made_on_another_thread_is_the_one_made_here() { + use crate::cmd::workflows::{raster_land, raster_start}; + use rustgis_analysis::control::Control; + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; + let dir = std::env::temp_dir().join(format!("rustgis-mosaic-thread-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let at = |file: &str| dir.join(file).display().to_string(); + // Two bands of 10 × 10 cells, `base` and up, with a hole at the top left. + let tile = |name: &str, x0: f64, base: f32| { + let band = |b: f32| (0..100).map(|i| if i == 0 { -9999.0 } else { base + b + i as f32 }).collect::>(); + let gt = GeoTransform { origin_x: x0, origin_y: 1.0, pixel_width: 0.1, pixel_height: -0.1 }; + Raster::new(name, 10, 10, vec![band(0.0), band(0.5)], gt, Crs::LonLat, Some(-9999.0), ColorHint::Gray, "Float32").unwrap() + }; + let mut s = Session::new(Project::default()); + let mut over = tile("over", 0.5, 900.0); + over.bands[0].name = "Altitude".into(); + over.copyright = Some("Someone".into()); + for r in [tile("west", 0.0, 100.0), over, tile("off", 0.55, 0.0)] { + let (name, bytes) = (r.name.clone(), geotiff::write_all(&r).unwrap()); + crate::cmd::raster::add_raster(&mut s, &name, rustgis_map::RasterLayer::from_bytes(r, format!("{name}.tif"), bytes)).unwrap(); + } + // A file that says what its reading left out, one that lies off the grid, and one that isn't a raster. + for (file, r) in [("east.tif", tile("east", 1.0, 200.0)), ("astray.tif", tile("astray", 2.03, 0.0))] { + std::fs::write(at(file), geotiff::write_all(&r).unwrap()).unwrap(); + } + let sidecar = r#"5"#; + std::fs::write(at("east.tif.aux.xml"), sidecar).unwrap(); + std::fs::write(at("broken.tif"), b"not a raster").unwrap(); + let cells = |s: &Session, v: &Value| { + let l = s.map().layer(v["layer"].as_u64().unwrap() as u32).unwrap(); + let r = l.raster.as_ref().unwrap().data.clone().unwrap(); + let bits: Vec = r.bands.iter().flat_map(|b| b.data.iter().map(|x| x.to_bits())).collect(); + let names: Vec = r.bands.iter().map(|b| b.name.clone()).collect(); + (r.width, r.height, r.transform, r.nodata, names, bits) + }; + let said = |s: &Session, mark: u64, path: &str| -> Vec { + s.notices_since(mark).iter().map(|n| n.text.replace(path, "PATH")).collect() + }; + for (inputs, file, notices) in [ + // Where they overlap, the first wins. + (json!(["west", "over"]), None, 2), + (json!(["over", "west"]), None, 1), + (json!(["west", at("east.tif"), "over"]), None, 3), + (json!([at("east.tif"), "over", "west"]), Some("mosaic.tif"), 4), + ] { + let with = |name: &str| { + let path = file.map(|f| at(&format!("{name}_{f}"))); + (json!({"inputs": inputs, "name": name, "path": path}), path.unwrap_or("(no file)".into())) + }; + let (p, path_here) = with("here"); + let mark = s.notice_mark(); + let here = s.run("raster.mosaic", &p).unwrap(); + let said_here = said(&s, mark, &path_here); + // What the file lost, the credits left out, the band names not kept, then the file written. + assert_eq!(said_here.len(), notices, "{inputs}: {said_here:?}"); + let (p, path_there) = with("there"); + if file.is_some() { + std::fs::write(&path_there, b"before").unwrap(); + } + // Let go of once made, before it lands (a late Cancel, another project opened): the file + // there stays, and no other is left. + let files = || std::fs::read_dir(&dir).unwrap().count(); + let before = files(); + let run = raster_start(&mut s, "raster.mosaic", &p).unwrap(); + let mark = s.notice_mark(); + let made = std::thread::spawn(move || run.run(&Control::new())).join().unwrap().unwrap(); + drop(made); + assert!(file.is_none() || std::fs::read(&path_there).unwrap() == b"before", "{inputs}"); + assert_eq!(files(), before, "{inputs}: a staged file was left"); + let run = raster_start(&mut s, "raster.mosaic", &p).unwrap(); + let id = run.id; + let made = std::thread::spawn(move || run.run(&Control::new())).join().unwrap().unwrap(); + assert!(s.notices_since(mark).is_empty(), "nothing is said before it lands: {:?}", s.notices_since(mark)); + assert!(file.is_none() || std::fs::read(&path_there).unwrap() == b"before", "{inputs}: in place before it lands"); + assert_eq!(raster_land(&mut s, id, made), Ok(true)); + let there = s.finish_raster("raster.mosaic", id, &p).unwrap(); + assert_eq!(said(&s, mark, &path_there), said_here, "{inputs}"); + assert_eq!(cells(&s, &there), cells(&s, &here), "{inputs}"); + assert!((here.get("path").is_some(), there.get("path").is_some()) == (file.is_some(), file.is_some()), "{here} {there}"); + for key in ["width", "height", "bands"] { + assert_eq!(there[key], here[key], "{inputs}: {key}"); + } + if file.is_some() { + assert_eq!(std::fs::read(&path_there).unwrap(), std::fs::read(&path_here).unwrap(), "{inputs}"); + } + } + // Where it is refused first, whichever input: an error of an earlier input comes before a later + // one's, and a file that can't be written says what the inputs had to say too. + let nowhere = dir.join("no").join("such.tif").display().to_string(); + for (p, why, starts) in [ + (json!({"inputs": ["west"]}), "two or more", false), + (json!({"inputs": ["west", "nowhere"]}), "no raster layer 'nowhere'", false), + (json!({"inputs": ["west", "off", "nowhere"]}), "don't line up", false), + (json!({"inputs": ["west", "over"], "name": "n".repeat(201)}), "name", false), + (json!({"inputs": [at("gone.tif"), "nowhere"]}), "gone.tif", true), + (json!({"inputs": [at("broken.tif"), "west"]}), "broken.tif", true), + (json!({"inputs": ["west", at("east.tif"), "nowhere"]}), "no raster layer 'nowhere'", true), + (json!({"inputs": ["west", at("astray.tif"), at("gone.tif")]}), "don't line up", true), + (json!({"inputs": ["west", at("east.tif"), 3]}), "each input is a raster layer's name or a file path", true), + (json!({"inputs": ["west", at("east.tif")], "path": nowhere}), "not applied", true), + ] { + let layers = s.map().layers.len(); + let here = s.run("raster.mosaic", &p).unwrap_err(); + assert!(here.contains(why), "{p}: {here}"); + let there = match raster_start(&mut s, "raster.mosaic", &p) { + Err(e) => (e, false), + Ok(run) => (std::thread::spawn(move || run.run(&Control::new())).join().unwrap().err().unwrap(), true), + }; + assert_eq!(there, (here, starts), "{p}"); + assert_eq!(s.map().layers.len(), layers, "{p}"); + } + // A file that can't be put in place (a folder is there) is refused as the raster is added, with + // what the inputs had to say and not that it was exported. + std::fs::create_dir(at("folder.tif")).unwrap(); + let p = json!({"inputs": ["west", at("east.tif")], "path": at("folder.tif")}); + let (layers, files) = (s.map().layers.len(), std::fs::read_dir(&dir).unwrap().count()); + let mark = s.notice_mark(); + let here = s.run("raster.mosaic", &p).unwrap_err(); + assert!(here.starts_with(&at("folder.tif")) && here.contains("not applied") && !here.contains("Exported"), "{here}"); + let run = raster_start(&mut s, "raster.mosaic", &p).unwrap(); + let id = run.id; + let made = run.run(&Control::new()).unwrap(); + assert_eq!(raster_land(&mut s, id, made), Ok(true)); + assert_eq!(s.finish_raster("raster.mosaic", id, &p).unwrap_err(), here); + assert!(s.notices_since(mark).iter().all(|n| !n.text.contains("Exported")), "{:?}", s.notices_since(mark)); + assert_eq!((s.map().layers.len(), std::fs::read_dir(&dir).unwrap().count()), (layers, files)); + let _ = std::fs::remove_dir_all(&dir); +} + /// Export Features and Export Raster written on another thread, as the app writes them (#1291 /// step 3): the file, the answer and what the export says are those of one written here, nothing /// is said until it lands, and one cancelled before it starts writes nothing (a cancel in the diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index 6b706204e4..57c460e779 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -42,7 +42,8 @@ pub(super) fn long_commands(boundaries: bool) { layer.touch_geometry(); } } - s.run("layer.addDataBytes", &json!({"fileName": "dem.tif", "data": if boundaries { tiny_raster(false) } else { dem_b64() }})).unwrap(); + let data = if boundaries { tiny_raster(false) } else { dem_b64() }; + s.run("layer.addDataBytes", &json!({"fileName": "dem.tif", "data": data})).unwrap(); let dem = s.map().layers.iter().find(|l| l.is_raster()).unwrap().name.clone(); // What some of them read: a later DEM, a slope, training squares, an imagery workspace, a // two-class scene with its training polygons, and a layout. @@ -87,6 +88,7 @@ pub(super) fn long_commands(boundaries: bool) { ("raster.process", json!({"layer": dem, "operation": "resample", "factor": 4})), ("imagery.mosaic", json!({"name": "Valley"})), ("raster.rasterize", json!({"layer": "Squares", "field": "name", "cellSize": 0.0005, "path": out("burned.tif")})), + ("raster.mosaic", json!({"inputs": ["dem_later", out("tile.tif"), dem], "path": out("mosaic.tif")})), ( "dl.classify", json!({"layer": "scene", "training": "training", "classField": "class", "bands": [1, 2], "epochs": if boundaries { 2 } else { 30 }, "model": "landcover"}), @@ -114,6 +116,12 @@ pub(super) fn long_commands(boundaries: bool) { "index": "ndvi", "bbox": [10.0, 45.0, 10.02, 45.02]}), ), ]; + // A mosaic's input read from a file, and a file where it writes its own: Cancel keeps both. + { + use base64::Engine; + std::fs::write(out("tile.tif"), base64::engine::general_purpose::STANDARD.decode(&data).unwrap()).unwrap(); + std::fs::write(out("mosaic.tif"), b"before").unwrap(); + } // Every command that runs in the background is here, and only those. /// Keeps the shared fixture list in step with the production registry. fn listed<'a>(l: &[(&'a str, Value)]) -> std::collections::BTreeSet<&'a str> {