From ee97ac63c4b61b28ee3196a3247b04ebe194abe0 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 20:49:10 +0100 Subject: [PATCH 01/11] Rasterize makes its raster on a thread of its own, and the app runs every such command there raster.rasterize joins workflows::IN_BACKGROUND (rasterize_work): the polygons, their values and the grid's parameters (grid_spec, which reads the session without changing it) are read when it starts; the grid's sizing, the burn and the GeoTIFF write run on the thread, with progress and Cancel; its notices and a text field's class table land with the layer. The app's dispatch starts every command in workflows::runs_in_background on a thread, its progress and Cancel in the Workflows pane, whoever asks (Command Search, the assistant), as reads and exports already were. Both cancellation tests and raster_tools_run_on_another_thread run it. --- crates/engine/src/cmd/imagery.rs | 563 +++++++++++++++--------- crates/engine/src/cmd/raster.rs | 8 +- crates/engine/src/cmd/workflows.rs | 1 + crates/engine/src/tests.rs | 16 +- crates/engine/src/tests/cancellation.rs | 1 + crates/engine/src/tests/held_layers.rs | 16 + crates/ui-egui/src/analysispane.rs | 40 ++ crates/ui-egui/src/lib.rs | 9 + docs/user-guide/analysis.md | 7 +- 9 files changed, 454 insertions(+), 207 deletions(-) diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 7cc5f9a639..e5bf12e5a7 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -53,7 +53,7 @@ pub fn commands() -> Vec { r#"{"layer": raster, "crs"?: EPSG code or "EPSG:n" of the output (default the layer's), "cellSize"?: number or [x, y] in the output's units (default about the layer's pixel there), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view" (default the layer's footprint), "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "resampling"?: "nearest" (default) | "bilinear" | "cubic" | "average" (the mean of the pixels whose centres fall in a cell) | "mode" (their most frequent value, the least of those tied), "name"?: new layer (default " projected"), "path"?: GeoTIFF to write it to}"#, ), C::new("raster.rasterize", "Polygons to Raster", "Analyze › Raster", rasterize).inputs(rasterize_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"layer": polygon layer (its selected or all features; a later one over an earlier), "field"?: numeric field (its values) or text field (codes 1 to n in sorted order of its values, listed in a table named after the result with classes), "value"?: number every polygon gives when there is no field (default 1), "nodata"?: number of the cells under no polygon (default 0), "crs"?: EPSG code or "EPSG:n" of the output (default the projected system the layer holds its coordinates in, else the one it was read in; degrees for a layer in degrees with neither), "cellSize"?: number or [x, y] in the output's units (required without grid), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view"; default the polygons' bounds, "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "name"?: new layer (default " raster"), "path"?: GeoTIFF to write it to}"#, + r#"{"layer": polygon layer (its selected or all features; a later one over an earlier), "field"?: numeric field (its values) or text field (codes 1 to n in sorted order of its values, listed in a table named after the result with classes), "value"?: number every polygon gives when there is no field (default 1), "nodata"?: number of the cells under no polygon (default 0), "crs"?: EPSG code or "EPSG:n" of the output (default the projected system the layer holds its coordinates in, else the one it was read in; degrees for a layer in degrees with neither), "cellSize"?: number or [x, y] in the output's units (required without grid), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view"; default the polygons' bounds, "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "name"?: new layer (default " raster"), "path"?: GeoTIFF to write it to, "ran"?: (internal: a raster the app has worked out)}"#, ), // A fit is a measurement of the points, not a project change: no undo step. C::new("raster.gcpFit", "Control Point Fit", "Imagery › Alignment", gcp_fit).roles(&[]).effects(crate::policy::Effects::NONE).view().params( @@ -311,13 +311,27 @@ fn georeference(s: &mut Session, p: &Value) -> CmdResult { /// A coordinate system given as an EPSG code or any text [`Crs::parse`] reads. fn crs_param(s: &mut Session, p: &Value, key: &str) -> Result, String> { + let (crs, warning) = crs_param_read(p, key)?; + if let Some(w) = warning { + s.warn(w); + } + Ok(crs) +} + +/// [`crs_param`] without the session: the system, and the warning to give of a typed one +/// ([`super::parse_crs`]'s). +fn crs_param_read(p: &Value, key: &str) -> Result<(Option, Option), String> { let bad = || format!("{key} is an EPSG code such as 32613 or \"EPSG:32613\""); match p.get(key) { - None | Some(Value::Null) => Ok(None), - Some(Value::String(t)) => super::parse_crs(s, t).map(Some), + None | Some(Value::Null) => Ok((None, None)), + Some(Value::String(t)) => { + let crs = Crs::parse(t)?; + let warning = rustgis_data::raster::wkt::typed_crs_note(t, crs).map(|note| format!("crs: {note}")); + Ok((Some(crs), warning)) + } Some(v) => { let code = v.as_u64().filter(|c| *c <= u64::from(u32::MAX)).ok_or_else(bad)?; - Crs::from_epsg(code as u32).map(Some).ok_or_else(|| format!("unknown coordinate system EPSG:{code}")) + Crs::from_epsg(code as u32).map(|c| (Some(c), None)).ok_or_else(|| format!("unknown coordinate system EPSG:{code}")) } } } @@ -458,12 +472,17 @@ const EXACT_WHOLE: f64 = 16_777_216.0; /// text field's code or one `value` (see `rustgis_analysis::warp::rasterize`). A new layer, and /// for a text field a table of its codes. /// -/// It runs on the thread that calls it, the app's own on the desktop: it isn't one of the commands -/// that make their raster on a thread of their own (`workflows::IN_BACKGROUND`) yet, and nothing -/// installs a probe around it, so Cancel doesn't reach it and it runs to the end. Its grid sizing -/// and burn look at Cancel (`progress::check`, `control::check`) for when it moves there, which -/// has to carry over the GeoTIFF it writes to `path` and the class table it adds. +/// Made on another thread from the app (`workflows::IN_BACKGROUND`), with progress and Cancel: +/// its grid's sizing and the burn look at Cancel ([`rasterize_work`]). fn rasterize(s: &mut Session, p: &Value) -> CmdResult { + super::workflows::made_or_ran(s, p, "raster.rasterize") +} + +/// What `raster.rasterize` reads of the session (the polygons and their values, the grid as its +/// parameters give it), and the work that sizes the grid, burns the polygons, writes the GeoTIFF to +/// `path` when given and makes the layer; once it is added, its notices are said and a text +/// field's class table is added. +pub(crate) fn rasterize_work(s: &Session, p: &Value) -> Result { let ln = rasterize_name(p)?; let l = s.map().layer_by_name(ln).filter(|l| l.raster.is_none()).ok_or_else(|| format!("no vector layer '{ln}'"))?; let ds = &l.dataset; @@ -491,126 +510,146 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { }; let path = tif_path(p)?; let out_name = name(p, format!("{ln} raster"))?; - // The features burned: the selection, else all, in the layer's order (a later one wins). - let mut rows: Vec = if l.selection.is_empty() { (0..ds.features.len()).collect() } else { l.selection.clone() }; - rows.sort_unstable(); - rows.dedup(); - let (mut no_value, mut no_polygon) = (0, 0); - let mut burns: Vec<(Vec>>, rustgis_data::Value)> = Vec::new(); + let selection = l.selection.clone(); // Burned from the system the layer holds its coordinates in (none of it converted when the - // grid is in it too). + // grid is in it too), by default onto a grid in it when it is a projected one: a geographic or + // geocentric one (an ECEF layer) has no plane for a grid, so it takes the one the layer was read + // in. Web Mercator and the world projections are planes a grid is laid on, unlike the analysis + // plane `works_in` excludes them from. let held = ds.coord_crs(); - for row in rows { - let Some(feature) = ds.features.get(row) else { continue }; - let parts = match &feature.geometry { - Some(Geometry::Polygon(polys)) => rasterops::validated_polygon_parts(polys).ok(), - _ => None, - }; - let Some(parts) = parts else { - no_polygon += 1; - continue; - }; - let v = match field { - Some((i, _)) => ds.value(row, i).clone(), - None => rustgis_data::Value::Float(value), - }; - burns.push((parts, v)); - } - // A text or date field's values become codes 1 to n, in sorted order: text by its text, dates - // and date-times by instant (one moment at two offsets is one class, labelled as first seen). - let text = field.is_some_and(|(_, ty)| ty == FieldType::Text || ty.is_temporal()); - let temporal = field.is_some_and(|(_, ty)| ty.is_temporal()); - #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] - enum ClassKey { - Instant(i64), - Text(String), - } - let key = |v: &rustgis_data::Value| if temporal { v.temporal_key().map(ClassKey::Instant) } else { text_of(v).map(ClassKey::Text) }; - let mut labels = std::collections::BTreeMap::new(); - if text { - for (_, v) in &burns { - if let (Some(k), Some(label)) = (key(v), text_of(v)) { - labels.entry(k).or_insert(label); - } - } - } - let keys: Vec = labels.keys().cloned().collect(); - let classes: Vec = labels.into_values().collect(); - // Whole numbers: codes, one value, or a field that isn't a floating-point one. - let whole_field = field.is_none_or(|(_, ty)| ty != FieldType::Double); - let what = field.and_then(|(i, _)| ds.fields.get(i)).map_or("value", |f| f.name.as_str()).to_string(); - let mut shapes = Vec::with_capacity(burns.len()); - let mut rounded = 0; - for (parts, v) in burns { - let x = if text { key(&v).and_then(|k| keys.binary_search(&k).ok()).map(|i| i as f64 + 1.0) } else { v.as_f64() }; - let Some(x) = x else { - no_value += 1; - continue; - }; - if x.abs() > f64::from(f32::MAX) { - return Err(format!("{ln}: {what} {x} is past the range of a raster's 32-bit pixels")); - } - if whole_field && x.fract() == 0.0 && x.abs() > EXACT_WHOLE { - // Only a numeric field's numbers can be given as text instead. - let hint = if field.is_some() && !text { "; a text field gives codes instead" } else { "" }; - return Err(format!("{ln}: {what} {x} is more than a raster's pixels hold exactly ({EXACT_WHOLE}){hint}")); - } - // As a pixel holds them: a value that rounds to the no-data value would be lost. - if x as f32 == nodata as f32 { - let of = if text { format!(", the code of {:?},", text_of(&v).unwrap_or_default()) } else { String::new() }; - return Err(format!("{ln}: {what} {x}{of} is the no-data value: give another nodata")); - } - rounded += usize::from(f64::from(x as f32) != x); - shapes.push(warp::Shape { parts, value: x as f32 }); - } - if shapes.is_empty() { - return Err(format!("{ln} has no polygons with a value to burn")); - } - // By default, the projected system the layer holds its coordinates in (else the one it was read in) and - // the polygons' bounds. - let held_bounds = shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).fold(Extent::EMPTY, |mut e, c| { - e.expand(*c); - e - }); - // A projected system the layer holds it in: a geographic or geocentric one (an ECEF layer) has - // no plane for a grid, so it takes the one the layer was read in. Web Mercator and the world - // projections are planes a grid is laid on, unlike the analysis plane `works_in` excludes them - // from. let projected = held != Crs::LonLat && !held.is_geographic() && !held.is_geocentric(); let crs = if projected { held } else { ds.crs.unwrap_or(Crs::LonLat) }; - let mut unsized_by = 0usize; - let grid = grid_param(s, p, crs, |crs| { - if crs == held && projected { - return Ok(([held_bounds.min_x, held_bounds.min_y, held_bounds.max_x, held_bounds.max_y], None)); - } - // Otherwise the bounds of the polygons' box in longitude/latitude, as before. A place the - // layer's system can't give there (a missing one aside) doesn't size the grid, and is - // said when the grid takes these bounds (no extent given). - let to = held.to(Crs::LonLat).map_err(|e| format!("{ln}: {e}"))?; - let mut lonlat = Extent::EMPTY; - // A conversion a vertex: Cancel is looked at every few thousand (once a probe is - // installed, see above). - for (i, c) in shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).filter(|c| c.is_finite()).enumerate() { - if i % 4096 == 0 { - rustgis_data::progress::check().map_err(|e| e.to_string())?; + let (spec, notes) = grid_spec(s, p, crs)?; + // Without a grid, its cells are given: no polygon sets a cell size. + if matches!(spec, GridSpec::Build { cell: None, .. }) { + return Err("cellSize is required: a number, or [x, y], in the output's units, or a grid".into()); + } + let extent_given = p.get("extent").is_some_and(|v| !v.is_null()); + // The layer's rows are shared, not copied: every pass over the polygons runs on the work's + // thread, which looks at Cancel as it sizes the grid and between shapes as it burns. + let ds = ds.clone(); + let ln = ln.to_string(); + Ok(Box::new(move || { + let mut notes = notes; + // What a run that fails had to say goes with its error. + let made = (|| -> Result { + // The features burned: the selection, else all, in the layer's order (a later one wins). + let mut rows: Vec = if selection.is_empty() { (0..ds.features.len()).collect() } else { selection }; + rows.sort_unstable(); + rows.dedup(); + let (mut no_value, mut no_polygon) = (0, 0); + let mut burns: Vec<(Vec>>, rustgis_data::Value)> = Vec::new(); + for (k, row) in rows.into_iter().enumerate() { + // Each checked and copied: Cancel is looked at every few thousand. + if k % 4096 == 0 { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + } + let Some(feature) = ds.features.get(row) else { continue }; + let parts = match &feature.geometry { + Some(Geometry::Polygon(polys)) => rasterops::validated_polygon_parts(polys).ok(), + _ => None, + }; + let Some(parts) = parts else { + no_polygon += 1; + continue; + }; + let v = match field { + Some((i, _)) => ds.value(row, i).clone(), + None => rustgis_data::Value::Float(value), + }; + burns.push((parts, v)); } - match to.point(*c) { - Some(c) => lonlat.expand(c), - None => unsized_by += 1, + // A text or date field's values become codes 1 to n, in sorted order: text by its text, dates + // and date-times by instant (one moment at two offsets is one class, labelled as first seen). + let text = field.is_some_and(|(_, ty)| ty == FieldType::Text || ty.is_temporal()); + let temporal = field.is_some_and(|(_, ty)| ty.is_temporal()); + #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] + enum ClassKey { + Instant(i64), + Text(String), } - } - let mut b = warp::bounds_in([lonlat.min_x, lonlat.min_y, lonlat.max_x, lonlat.max_y], crs).map_err(|e| format!("{ln}: {e}"))?; - // Taking in the vertices as the burn places them: between two datums the direct operation - // lands apart from the route through WGS 84 (half a metre for DHDN and ETRS89). - if held != Crs::LonLat - && let Some(q) = warp::placed_bounds(held, crs, &shapes).map_err(|e| format!("{ln}: {e}"))? - { - b = [b[0].min(q[0]), b[1].min(q[1]), b[2].max(q[2]), b[3].max(q[3])]; - } - Ok((b, None)) - })?; - if unsized_by > 0 && p.get("extent").is_none_or(Value::is_null) { - s.notify( + let key = + |v: &rustgis_data::Value| if temporal { v.temporal_key().map(ClassKey::Instant) } else { text_of(v).map(ClassKey::Text) }; + let mut labels = std::collections::BTreeMap::new(); + if text { + for (_, v) in &burns { + if let (Some(k), Some(label)) = (key(v), text_of(v)) { + labels.entry(k).or_insert(label); + } + } + } + let keys: Vec = labels.keys().cloned().collect(); + let classes: Vec = labels.into_values().collect(); + // Whole numbers: codes, one value, or a field that isn't a floating-point one. + let whole_field = field.is_none_or(|(_, ty)| ty != FieldType::Double); + let what = field.and_then(|(i, _)| ds.fields.get(i)).map_or("value", |f| f.name.as_str()).to_string(); + let mut shapes = Vec::with_capacity(burns.len()); + let mut rounded = 0; + for (parts, v) in burns { + let x = if text { key(&v).and_then(|k| keys.binary_search(&k).ok()).map(|i| i as f64 + 1.0) } else { v.as_f64() }; + let Some(x) = x else { + no_value += 1; + continue; + }; + if x.abs() > f64::from(f32::MAX) { + return Err(format!("{ln}: {what} {x} is past the range of a raster's 32-bit pixels")); + } + if whole_field && x.fract() == 0.0 && x.abs() > EXACT_WHOLE { + // Only a numeric field's numbers can be given as text instead. + let hint = if field.is_some() && !text { "; a text field gives codes instead" } else { "" }; + return Err(format!("{ln}: {what} {x} is more than a raster's pixels hold exactly ({EXACT_WHOLE}){hint}")); + } + // As a pixel holds them: a value that rounds to the no-data value would be lost. + if x as f32 == nodata as f32 { + let of = if text { format!(", the code of {:?},", text_of(&v).unwrap_or_default()) } else { String::new() }; + return Err(format!("{ln}: {what} {x}{of} is the no-data value: give another nodata")); + } + rounded += usize::from(f64::from(x as f32) != x); + shapes.push(warp::Shape { parts, value: x as f32 }); + } + if shapes.is_empty() { + return Err(format!("{ln} has no polygons with a value to burn")); + } + // By default, the projected system the layer holds its coordinates in (else the one it was read in) and + // the polygons' bounds. + let held_bounds = shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).fold(Extent::EMPTY, |mut e, c| { + e.expand(*c); + e + }); + let mut unsized_by = 0usize; + let grid = spec.finish(|crs| { + if crs == held && projected { + return Ok(([held_bounds.min_x, held_bounds.min_y, held_bounds.max_x, held_bounds.max_y], None)); + } + // Otherwise the bounds of the polygons' box in longitude/latitude, as before. A place the + // layer's system can't give there (a missing one aside) doesn't size the grid, and is + // said when the grid takes these bounds (no extent given). + let to = held.to(Crs::LonLat).map_err(|e| format!("{ln}: {e}"))?; + let mut lonlat = Extent::EMPTY; + // A conversion a vertex: Cancel is looked at every few thousand (once a probe is + // installed, see above). + for (i, c) in shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).filter(|c| c.is_finite()).enumerate() { + if i % 4096 == 0 { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + } + match to.point(*c) { + Some(c) => lonlat.expand(c), + None => unsized_by += 1, + } + } + let mut b = + warp::bounds_in([lonlat.min_x, lonlat.min_y, lonlat.max_x, lonlat.max_y], crs).map_err(|e| format!("{ln}: {e}"))?; + // Taking in the vertices as the burn places them: between two datums the direct operation + // lands apart from the route through WGS 84 (half a metre for DHDN and ETRS89). + if held != Crs::LonLat + && let Some(q) = warp::placed_bounds(held, crs, &shapes).map_err(|e| format!("{ln}: {e}"))? + { + b = [b[0].min(q[0]), b[1].min(q[1]), b[2].max(q[2]), b[3].max(q[3])]; + } + Ok((b, None)) + })?; + if unsized_by > 0 && !extent_given { + notes.push(( format!( "{ln}: {unsized_by} {} that can't be placed in longitude/latitude {} left out of the grid's extent: check {} coordinates and the layer's coordinate system", if unsized_by == 1 { "vertex" } else { "vertices" }, @@ -618,70 +657,120 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { if unsized_by == 1 { "its" } else { "their" } ), false, - ); - } - // The smallest pixel type the GeoTIFF writer keeps that holds every value and the no-data. - let whole = |max: f64| shapes.iter().map(|s| f64::from(s.value)).chain([nodata]).all(|v| v.fract() == 0.0 && (0.0..=max).contains(&v)); - let data_type = if whole(255.0) { - "UInt8" - } else if whole(65_535.0) { - "UInt16" - } else { - "Float32" - }; - let burned = warp::rasterize_in(&grid, held, &shapes, nodata as f32).map_err(|e| format!("{ln}: {e}"))?; - if burned.cells == 0 { - return Err(format!("no cell centre of the grid falls inside {ln}'s polygons: give a smaller cellSize, or a grid over them")); - } - let (w, h) = (u32::try_from(grid.width).map_err(|e| e.to_string())?, u32::try_from(grid.height).map_err(|e| e.to_string())?); - let out = Raster::new(&out_name, w, h, vec![burned.data], grid.transform(), grid.crs, Some(nodata), ColorHint::Gray, data_type) - .map_err(|e| e.to_string())?; - let mut info = json!({ - "name": out_name, "crs": grid.crs.label(), "width": out.width, "height": out.height, "dataType": data_type, "nodata": nodata, - "cellSize": [grid.cell_x, grid.cell_y], "corner": [grid.min_x, grid.max_y], "features": burned.burned, "cells": burned.cells, - }); - if rounded > 0 { - s.notify(format!("{ln}: {rounded} value(s) of {what} rounded to the raster's 32-bit pixels"), false); - } - let skipped = [("noValue", no_value), ("noPolygon", no_polygon), ("unplaced", burned.unplaced.len()), ("noCell", burned.missed)]; - if skipped.iter().any(|(_, n)| *n > 0) { - info["skipped"] = - skipped.iter().filter(|(_, n)| *n > 0).map(|(k, n)| (k.to_string(), json!(n))).collect::>().into(); - let mut why = Vec::new(); - if no_value > 0 { - why.push(format!("{no_value} with no value")); - } - if no_polygon > 0 { - why.push(format!("{no_polygon} with no valid polygon")); - } - if !burned.unplaced.is_empty() { - why.push(format!("{} with a part that can't be placed on the grid (any other parts were burned)", burned.unplaced.len())); - } - if burned.missed > 0 { - why.push(format!("{} that hold no cell centre (narrower than a cell, or off the grid)", burned.missed)); - } - s.notify(format!("{ln}: features skipped: {}", why.join(", ")), false); - } - // Whole numbers few enough to list are classes, drawn with unique values. - let distinct = out.bands.first().is_some_and(|b| b.stats.categories.is_some()); - let mut info = add_output(s, out, path, whole_field && distinct, info)?; - if text { - let layer = info.get("name").and_then(Value::as_str).unwrap_or(&out_name).to_string(); - let mut table = rustgis_data::Dataset::new( - free_table_name(s, &format!("{layer} classes")), - GeometryType::None, - vec![rustgis_data::Field::new("code", FieldType::Integer), rustgis_data::Field::new("value", FieldType::Text)], - ); - for (i, c) in classes.iter().enumerate() { - table.push_next(None, vec![rustgis_data::Value::Int(i as i64 + 1), rustgis_data::Value::Text(c.clone())]); - } - info["classTable"] = json!(table.name); - s.project.add_table(table); - info["classCount"] = json!(classes.len()); - // All the codes are in the table; here, as many as a unique-value legend shows. - info["classes"] = classes.iter().take(256).enumerate().map(|(i, c)| json!({"code": i + 1, "value": c})).collect(); - } - Ok(info) + )); + } + // The smallest pixel type the GeoTIFF writer keeps that holds every value and the no-data. + let whole = + |max: f64| shapes.iter().map(|s| f64::from(s.value)).chain([nodata]).all(|v| v.fract() == 0.0 && (0.0..=max).contains(&v)); + let data_type = if whole(255.0) { + "UInt8" + } else if whole(65_535.0) { + "UInt16" + } else { + "Float32" + }; + let burned = warp::rasterize_in(&grid, held, &shapes, nodata as f32).map_err(|e| format!("{ln}: {e}"))?; + if burned.cells == 0 { + return Err(format!( + "no cell centre of the grid falls inside {ln}'s polygons: give a smaller cellSize, or a grid over them" + )); + } + let (w, h) = (u32::try_from(grid.width).map_err(|e| e.to_string())?, u32::try_from(grid.height).map_err(|e| e.to_string())?); + let out = Raster::new(&out_name, w, h, vec![burned.data], grid.transform(), grid.crs, Some(nodata), ColorHint::Gray, data_type) + .map_err(|e| e.to_string())?; + let mut info = json!({ + "name": out_name, "crs": grid.crs.label(), "width": out.width, "height": out.height, "dataType": data_type, "nodata": nodata, + "cellSize": [grid.cell_x, grid.cell_y], "corner": [grid.min_x, grid.max_y], "features": burned.burned, "cells": burned.cells, + }); + if rounded > 0 { + notes.push((format!("{ln}: {rounded} value(s) of {what} rounded to the raster's 32-bit pixels"), false)); + } + let skipped = + [("noValue", no_value), ("noPolygon", no_polygon), ("unplaced", burned.unplaced.len()), ("noCell", burned.missed)]; + if skipped.iter().any(|(_, n)| *n > 0) { + info["skipped"] = skipped + .iter() + .filter(|(_, n)| *n > 0) + .map(|(k, n)| (k.to_string(), json!(n))) + .collect::>() + .into(); + let mut why = Vec::new(); + if no_value > 0 { + why.push(format!("{no_value} with no value")); + } + if no_polygon > 0 { + why.push(format!("{no_polygon} with no valid polygon")); + } + if !burned.unplaced.is_empty() { + why.push(format!( + "{} with a part that can't be placed on the grid (any other parts were burned)", + burned.unplaced.len() + )); + } + if burned.missed > 0 { + why.push(format!("{} that hold no cell centre (narrower than a cell, or off the grid)", burned.missed)); + } + notes.push((format!("{ln}: features skipped: {}", why.join(", ")), false)); + } + // Whole numbers few enough to list are classes, drawn with unique values. + let distinct = out.bands.first().is_some_and(|b| b.stats.categories.is_some()); + let e = out.extent(); + info["extent"] = json!([e.min_x, e.min_y, e.max_x, e.max_y]); + // A file written is the layer's source; without one the pixels are kept in the project. + let mut written = Vec::new(); + let mut rl = match &path { + Some(path) => { + let wrote = super::raster::write_geotiff_with_guidance( + &out, + 0, + true, + path, + "export the resulting layer with share.exportRaster and give \"band\" for another", + )?; + written = wrote.notes; + info["path"] = json!(path); + info["cog"] = wrote.answer.get("cog").cloned().unwrap_or(Value::Null); + RasterLayer::from_path(out, path.clone()) + } + None => layer_of(out)?, + }; + if whole_field + && distinct + && let Some(d) = rl.data.clone() + { + rl.style.renderer = rustgis_map::raster::unique_values(&d, 0, rustgis_map::Ramp::Harbour); + } + let notes = std::mem::take(&mut notes); + let then: super::workflows::Then = Box::new(move |s: &mut Session, v: &mut Value| { + say(s, notes); + for note in written { + s.notify_written(note); + } + // The name the layer got (another may hold the one asked for: "… raster (2)"). + let id = v.get("layer").and_then(Value::as_u64).and_then(|id| u32::try_from(id).ok()); + let layer = id.and_then(|id| s.map().layer(id)).map(|l| l.name.clone()).unwrap_or(out_name.clone()); + v["name"] = json!(layer); + if text { + let mut table = rustgis_data::Dataset::new( + free_table_name(s, &format!("{layer} classes")), + GeometryType::None, + vec![rustgis_data::Field::new("code", FieldType::Integer), rustgis_data::Field::new("value", FieldType::Text)], + ); + for (i, c) in classes.iter().enumerate() { + table.push_next(None, vec![rustgis_data::Value::Int(i as i64 + 1), rustgis_data::Value::Text(c.clone())]); + } + v["classTable"] = json!(table.name); + s.project.add_table(table); + v["classCount"] = json!(classes.len()); + // All the codes are in the table; here, as many as a unique-value legend shows. + v["classes"] = classes.iter().take(256).enumerate().map(|(i, c)| json!({"code": i + 1, "value": c})).collect(); + } + }); + let name = info.get("name").and_then(Value::as_str).unwrap_or_default().to_string(); + Ok(super::workflows::made_layer(name, rl, Some(info), Some(then))) + })(); + made.map_err(|e| with_notes(e, ¬es)) + })) } /// `base`, or `base (2)`, `base (3)`… : the first no table of the project has (whatever its case). @@ -765,9 +854,78 @@ fn grid_param( crs: Crs, natural: impl FnOnce(Crs) -> Result<([f64; 4], Option), String>, ) -> Result { + let (spec, notes) = grid_spec(s, p, crs)?; + say(s, notes); + spec.finish(natural) +} + +/// What to say: a notice, or a warning (`true`). +type Notes = Vec<(String, bool)>; + +/// `error`, with what a run had to say before it failed (`notes`). +fn with_notes(error: String, notes: &Notes) -> String { + if notes.is_empty() { + return error; + } + let said: Vec<&str> = notes.iter().map(|(n, _)| n.as_str()).collect(); + format!("{error} ({})", said.join("; ")) +} + +/// Says `notes`. +fn say(s: &mut Session, notes: Notes) { + for (note, warning) in notes { + if warning { + s.warn(note); + } else { + s.notify(note, false); + } + } +} + +/// A grid as its parameters give it, read of the session ([`grid_spec`]); what isn't given (the +/// bounds without an extent, the cell size without a cellSize) is worked out by [`GridSpec::finish`], +/// which reads nothing of the session, so a command can do it where its work runs. +enum GridSpec { + /// Another raster's grid, taken exactly. + Fixed(warp::Grid), + Build { + crs: Crs, + cell: Option<(f64, f64)>, + origin: (f64, f64), + bounds: Option<[f64; 4]>, + }, +} + +impl GridSpec { + /// The grid: `natural` gives, in its system, the bounds taken without an extent and the cell + /// size taken without a cellSize (`None`: a cellSize is required); it is asked only when one of + /// them is missing. + fn finish(self, natural: impl FnOnce(Crs) -> Result<([f64; 4], Option), String>) -> Result { + match self { + GridSpec::Fixed(g) => Ok(g), + GridSpec::Build { crs, cell, origin, bounds } => { + let (bounds, cell) = match (bounds, cell) { + (Some(b), Some(c)) => (b, c), + (b, c) => { + let (footprint, pixel) = natural(crs)?; + let cell = c + .or(pixel.map(|c| (c, c))) + .ok_or("cellSize is required: a number, or [x, y], in the output's units, or a grid")?; + (b.unwrap_or(footprint), cell) + } + }; + warp::Grid::snapped(crs, bounds, cell, origin) + } + } + } +} + +/// The grid `p` gives ([`grid_param`]), with what to say of it (a template read from its overview). +fn grid_spec(s: &Session, p: &Value, crs: Crs) -> Result<(GridSpec, Notes), String> { // A grid named as anything but a raster layer's name is refused rather than ignored. let template = project_grid(p)?; - Ok(match template { + let mut notes = Vec::new(); + let spec = match template { Some(template) => { if ["crs", "cellSize", "origin", "extent"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { return Err( @@ -777,24 +935,24 @@ fn grid_param( let t = raster_named(s, template)?; t.require_coordinates()?; if let Some((fw, fh)) = t.overview { - s.notify(format!("{template}: the grid is its {} × {} overview's, of the {fw} × {fh} raster", t.width, t.height), false); + notes + .push((format!("{template}: the grid is its {} × {} overview's, of the {fw} × {fh} raster", t.width, t.height), false)); } - warp::Grid::of(&t) + GridSpec::Fixed(warp::Grid::of(&t)) } None => { - let crs = crs_param(s, p, "crs")?.unwrap_or(crs); - let (footprint, pixel) = natural(crs)?; + let (given, warning) = crs_param_read(p, "crs")?; + notes.extend(warning.map(|w| (w, true))); + let crs = given.unwrap_or(crs); let positive = |v: &Value| v.as_f64().filter(|c| c.is_finite() && *c > 0.0); let bad_cell = "cellSize is a positive number, or [x, y], in the output's units"; let cell = match p.get("cellSize") { - None | Some(Value::Null) => { - pixel.map(|c| (c, c)).ok_or("cellSize is required: a number, or [x, y], in the output's units, or a grid")? - } + None | Some(Value::Null) => None, Some(Value::Array(a)) => match a.as_slice() { - [x, y] => (positive(x).ok_or(bad_cell)?, positive(y).ok_or(bad_cell)?), + [x, y] => Some((positive(x).ok_or(bad_cell)?, positive(y).ok_or(bad_cell)?)), _ => return Err(bad_cell.into()), }, - Some(v) => positive(v).map(|c| (c, c)).ok_or(bad_cell)?, + Some(v) => Some(positive(v).map(|c| (c, c)).ok_or(bad_cell)?), }; let origin = match p.get("origin") { None | Some(Value::Null) => (0.0, 0.0), @@ -808,7 +966,7 @@ fn grid_param( } }; let bounds = match p.get("extent") { - None | Some(Value::Null) => footprint, + None | Some(Value::Null) => None, Some(Value::String(_)) if project_extent_name(p).is_some() => { let l = project_extent_name(p).ok_or("extent layer is required")?; let layer = s.map().layer_by_name(l).filter(|l| l.raster.is_none()).ok_or_else(|| format!("no vector layer '{l}'"))?; @@ -818,21 +976,22 @@ fn grid_param( if e.is_empty() { return Err(format!("{l} has no features to take an extent from")); } - warp::bounds_in([e.min_x, e.min_y, e.max_x, e.max_y], crs)? + Some(warp::bounds_in([e.min_x, e.min_y, e.max_x, e.max_y], crs)?) } Some(v @ (Value::Array(_) | Value::String(_))) => { let area = super::catalogs::area(s, &json!({"bbox": v})).map_err(|e| e.replacen("bbox", "extent", 1))?; if area[0] > area[2] { return Err("an extent across the antimeridian: give it one side at a time".into()); } - warp::bounds_in(area, crs)? + Some(warp::bounds_in(area, crs)?) } // A number, a flag or an object isn't an extent: refused, not read as the view. Some(_) => return Err(EXTENT.into()), }; - warp::Grid::snapped(crs, bounds, cell, origin)? + GridSpec::Build { crs, cell, origin, bounds } } - }) + }; + Ok((spec, notes)) } fn is_tif(path: &str) -> bool { diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index c62ef7ecfa..614362752c 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -1167,7 +1167,13 @@ pub(super) fn write_geotiff(r: &Raster, bi: usize, cog: bool, path: &str) -> Res } /// Builds the band instruction before combining the note with any caller-supplied path or name. -fn write_geotiff_with_guidance(r: &Raster, bi: usize, cog: bool, path: &str, band_hint: &str) -> Result { +pub(super) fn write_geotiff_with_guidance( + r: &Raster, + bi: usize, + cog: bool, + path: &str, + band_hint: &str, +) -> Result { let cog = if cog { // Tiles go to the file as they are made: the whole file is never held in memory. Some(raster::cogwrite::write_file(r, bi, Path::new(path)).map_err(|e| format!("{path}: {e}"))?) diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index b5c3e85dd4..dca19b776c 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -237,6 +237,7 @@ pub(crate) const IN_BACKGROUND: &[(&str, &str, Start)] = &[ ("stac.addBands", "Add STAC Bands", super::stac_bands::bands_work), ("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), ("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 79cb03ee8c..62f3767b60 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -51239,6 +51239,8 @@ fn raster_tools_run_on_another_thread() { ("raster.process", json!({"layer": dem, "operation": "clip", "extent": [10.005, 45.005, 10.02, 45.02]})), ("raster.process", json!({"layer": dem, "operation": "resample", "factor": 4})), ("imagery.mosaic", json!({"name": "Valley"})), + ("raster.rasterize", json!({"layer": "Training", "value": 3, "cellSize": 0.0005})), + ("raster.rasterize", json!({"layer": "Training", "field": "name", "cellSize": 0.0005})), ] { assert!(runs_in_background(command).is_some(), "{command}"); let here = s.run(command, &p).unwrap(); @@ -51250,10 +51252,22 @@ fn raster_tools_run_on_another_thread() { with["ran"] = json!(id); let there = s.run(command, &with).unwrap(); assert_eq!(pixels(&s, &here), pixels(&s, &there), "{command} {p}"); + // The layer, and the names that follow its own (the first run's layer holds the one asked + // for): a class table named after it is there. + let named = ["layer", "name", "classTable"]; let besides = |v: &Value| { - v.as_object().map(|o| o.iter().filter(|(k, _)| *k != "layer").map(|(k, v)| (k.clone(), v.clone())).collect::>()) + v.as_object() + .map(|o| o.iter().filter(|(k, _)| !named.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect::>()) }; assert_eq!(besides(&here), besides(&there), "{command} {p}"); + // A name said is the one the layer got. + if let Some(name) = there["name"].as_str() { + let id = there["layer"].as_u64().unwrap() as u32; + assert_eq!(Some(name), s.map().layer(id).map(|l| l.name.as_str()), "{command}: {there}"); + } + if let Some(table) = there["classTable"].as_str() { + assert!(s.project.tables.iter().any(|t| t.name == table), "{command}: {table}"); + } // The answer is the added layer's, whatever else the command says. assert!(there["width"].is_u64() && there["bands"].is_u64(), "{command}: {there}"); let run = raster_start(&mut s, command, &p).unwrap(); diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index cb485791e5..fdc8096b09 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -86,6 +86,7 @@ pub(super) fn long_commands(boundaries: bool) { ("raster.index", json!({"layer": dem, "index": "ndvi", "nir": 1, "red": 1})), ("raster.process", json!({"layer": dem, "operation": "resample", "factor": 4})), ("imagery.mosaic", json!({"name": "Valley"})), + ("raster.rasterize", json!({"layer": "Squares", "field": "name", "cellSize": 0.0005})), ( "dl.classify", json!({"layer": "scene", "training": "training", "classField": "class", "bands": [1, 2], "epochs": if boundaries { 2 } else { 30 }, "model": "landcover"}), diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index ebc32a91ac..4f6ce5f6cc 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2435,6 +2435,22 @@ fn rasterize_sizes_its_grid_by_the_operation_that_burns() { assert!((16..=36).contains(&a["cells"].as_u64().unwrap()), "{a}"); } +/// Rasterize's default grid is the system a layer holds its coordinates in only when that is a +/// projected one: a layer held in ETRS89 degrees (EPSG:4258), read from a file in UTM 32N, is +/// burned onto a grid in UTM 32N. +#[test] +fn a_layer_held_in_degrees_is_burned_in_the_system_it_was_read_in() { + let geographic = Crs::Epsg(4258); + let ring: Vec = + [(11.0, 48.0), (11.01, 48.0), (11.01, 48.01), (11.0, 48.01), (11.0, 48.0)].iter().map(|(x, y)| Coord::new(*x, *y)).collect(); + let mut s = Session::new(Project::default()); + add_in(&mut s, "Plot", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![ring]])], geographic); + let id = s.map().layer_by_name("Plot").unwrap().id; + s.map_mut().layer_mut(id).unwrap().dataset.crs = Some(UTM); + s.run("raster.rasterize", &json!({"layer": "Plot", "cellSize": 10, "name": "Burned"})).unwrap(); + assert_eq!(grid_of(&s, "Burned").crs, UTM); +} + /// Rasterize sizes its default grid in another system by the polygons' box in longitude/latitude, /// and says how many vertices it couldn't place there, left out of that box: a polygon held in UTM /// with a vertex far beyond any place UTM holds, burned onto a grid in degrees. With an extent diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 6d5de24b21..a78461d720 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -380,6 +380,22 @@ fn background(id: &str) -> Option<(&'static str, &'static str)> { } } +/// Starts a command that makes a raster (`workflows::runs_in_background`) asked for outside the +/// pane (Command Search, the Assistant through the app): on a thread of its own, the Workflows pane +/// opened to show its progress and Cancel, as from a section; its layer is added when it lands, a +/// failure then said in the status bar. The answer says it started; one that can't start (another +/// is under way) is an error. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn start_from_dispatch(app: &mut RustGisApp, command: &'static str, name: &'static str, p: Value) -> Result { + // Opened, not toggled: a pane already open stays so. + app.ui.open_right(crate::RightPane::Workflows); + start(app, command, name, p); + match &app.workflow.job { + Some(job) if job.name == name && app.workflow.error.is_none() => Ok(json!({"started": name})), + _ => Err(app.workflow.error.clone().unwrap_or_else(|| crate::i18n::fmt("{tool} didn't start", &[("tool", tl_raw!(name))]))), + } +} + /// Starts `command` on a thread of its own; [`land_job`] applies what it made. One at a time: a /// second waits for the first to finish or be cancelled. #[cfg(not(target_arch = "wasm32"))] @@ -3027,6 +3043,30 @@ mod tests { } } + /// A command that makes a raster, asked for through the app's dispatch (Command Search, the + /// assistant) rather than a section, runs on a thread of its own too: Polygons to Raster from a + /// text field answers that it started, the pane shows it running, and its layer and class table + /// land with it. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_raster_command_from_the_dispatch_runs_on_a_thread() { + let mut app = RustGisApp::with_sample(); + // As the app runs, a frame at a time. + app.reads_off_frame = true; + let (layers, tables) = (app.session.map().layers.len(), app.session.project.tables.len()); + let started = app.run("raster.rasterize", json!({"layer": "Countries", "field": "name", "cellSize": 5})).unwrap(); + assert_eq!(started, json!({"started": "Polygons to Raster"})); + assert!(app.workflow.job.is_some(), "{:?}", app.workflow.error); + let end = std::time::Instant::now() + std::time::Duration::from_secs(60); + while land_job(&mut app) { + assert!(std::time::Instant::now() < end, "the run never landed"); + std::thread::sleep(std::time::Duration::from_millis(5)); // test-wait: polling for the workflow to land, as above + } + assert!(app.workflow.job.is_none() && app.workflow.error.is_none(), "{:?}", app.workflow.error); + assert_eq!(app.session.map().layers.len(), layers + 1); + assert_eq!(app.session.project.tables.len(), tables + 1); + } + /// Interpolate runs on a thread of its own from the pane (#1291 step 3): the pane goes on while /// it works, a second run waits for the first, and its layer lands through its command, which /// Record Task takes without the raster it handed over (a replay works it out again). diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6cb8ca8fd0..450f4bd253 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3103,6 +3103,15 @@ impl RustGisApp { let mark = self.session.notice_mark(); return exportjob::start(self, command, params).inspect_err(|e| self.command_failed(id, e, mark)); } + // A command that makes a raster grows with its input: on a thread of its own, its + // progress and Cancel in the Workflows pane, whoever asks (Command Search, the + // assistant). Run again with what it made (`ran`), it adds the raster here. + if params.get("ran").is_none_or(Value::is_null) + && let Some((command, name)) = rustgis_engine::cmd::workflows::runs_in_background(id) + { + let mark = self.session.notice_mark(); + return analysispane::start_from_dispatch(self, command, name, params).inspect_err(|e| self.command_failed(id, e, mark)); + } // Converting the labels of a layer read in place reads all of its source first, on a // thread of its own, whoever asks (a click, the assistant). if id == "labels.convert" diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 4c62c7b6c5..5c62ac033a 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -2093,9 +2093,10 @@ The Imagery tab's groups open their tools in the Workflows pane. The tab belongs million cells, or more on a computer with more memory; 32 million in the web app): a grid past that is refused before anything is burned. A layer read in place (only the part in view loaded) is refused until all its features are loaded. Taken from a raster read from its overview, the - grid is the overview's, and a notice says so. The command runs where it is called, with no Cancel - yet and no cap on its work: each polygon fills the cells it covers, so many large polygons on a - fine grid take time in proportion. + grid is the overview's, and a notice says so. In the desktop app it runs on a thread of its own, + from Command Search too, its progress and Cancel in the Workflows pane, as the Analysis + workflows that make a raster do; there is no cap on its work: each polygon fills the cells it + covers, so many large polygons on a fine grid take time in proportion. - **Classification Wizard** (unsupervised k-means) and **Classification Tools** (minimum distance from training polygons). Training polygons held in a coordinate system of their own are read as they are: a pixel's centre is converted into their system to be tested, straight by the From ff2635a7e3da33b271b2afef390bec850ca51918 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 22:53:19 +0100 Subject: [PATCH 02/11] Review: rasterize's GeoTIFF put in place as the layer is added, class table and extent layer's bounds on the thread, notes kept on refusals, a dispatched job's pane section settled first --- crates/data/src/io.rs | 9 ++ crates/data/src/raster/cogwrite.rs | 10 ++ crates/engine/src/cmd/imagery.rs | 123 ++++++++++++++++++------ crates/engine/src/cmd/raster.rs | 23 +++++ crates/engine/src/cmd/workflows.rs | 19 +++- crates/engine/src/tests.rs | 22 +++++ crates/engine/src/tests/cancellation.rs | 2 +- crates/engine/src/tests/held_layers.rs | 25 ++++- crates/ui-egui/src/analysispane.rs | 40 ++++++-- crates/ui-egui/src/lib.rs | 5 +- docs/user-guide/analysis.md | 9 +- 11 files changed, 238 insertions(+), 49 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index c5a60512d5..172b540b12 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1176,6 +1176,15 @@ pub fn stage_atomic(path: &Path, bytes: &[u8]) -> std::io::Result { stage_at(link_target(path)?, |w| w.write_all(bytes)).map(|(staged, ())| staged) } +/// [`stage_atomic`] for a write that streams: `write` fills the file beside the destination (a +/// symbolic link's target), which [`StagedWrite::commit`] installs; dropping the result discards it. +pub fn stage_streamed>( + path: &Path, + write: impl FnOnce(&mut std::io::BufWriter) -> std::result::Result, +) -> std::result::Result<(StagedWrite, T), E> { + stage_at(link_target(path)?, write) +} + /// Stages and installs a write, retaining the old file on error or cancellation. fn atomic_write_at>( path: std::path::PathBuf, diff --git a/crates/data/src/raster/cogwrite.rs b/crates/data/src/raster/cogwrite.rs index ce78a846b2..6ddb3823cf 100644 --- a/crates/data/src/raster/cogwrite.rs +++ b/crates/data/src/raster/cogwrite.rs @@ -1065,6 +1065,16 @@ pub fn write_file(r: &Raster, band: usize, path: &Path) -> Result { res } +/// [`write_file`]'s file, written and synced beside `path` but not yet in its place: the caller +/// installs it ([`crate::io::StagedWrite::commit`]) once nothing can cancel the result any more, +/// and dropping it leaves `path` as it was. +pub fn write_staged(r: &Raster, band: usize, path: &Path) -> Result<(CogInfo, crate::io::StagedWrite)> { + let (staged, info) = crate::io::stage_streamed(path, |w| write_to(r, band, Flavour::Auto, w))?; + // The last look while it is written: a Cancel that came meanwhile leaves `path` as it was. + crate::progress::check()?; + Ok((info, staged)) +} + #[cfg(test)] mod tests { use std::io::Cursor; diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index e5bf12e5a7..5d02804393 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -522,7 +522,7 @@ pub(crate) fn rasterize_work(s: &Session, p: &Value) -> Result Result { - let wrote = super::raster::write_geotiff_with_guidance( + let (wrote, file) = super::raster::write_cog_staged( &out, 0, - true, path, "export the resulting layer with share.exportRaster and give \"band\" for another", )?; written = wrote.notes; + staged = Some(file); info["path"] = json!(path); info["cog"] = wrote.answer.get("cog").cloned().unwrap_or(Value::Null); RasterLayer::from_path(out, path.clone()) @@ -740,6 +742,21 @@ pub(crate) fn rasterize_work(s: &Session, p: &Value) -> Result = classes.iter().take(256).enumerate().map(|(i, c)| json!({"code": i + 1, "value": c})).collect(); + let class_count = classes.len(); let notes = std::mem::take(&mut notes); let then: super::workflows::Then = Box::new(move |s: &mut Session, v: &mut Value| { say(s, notes); @@ -750,24 +767,20 @@ pub(crate) fn rasterize_work(s: &Session, p: &Value) -> Result made.committing(file), + None => made, + }) })(); made.map_err(|e| with_notes(e, ¬es)) })) @@ -892,10 +905,59 @@ enum GridSpec { crs: Crs, cell: Option<(f64, f64)>, origin: (f64, f64), - bounds: Option<[f64; 4]>, + bounds: Option, }, } +/// A grid's extent as given: a box in its system, or a polygon layer's features, whose bounds are +/// worked out by [`GridSpec::finish`] (where the command's work runs: they grow with the layer). +enum Bounds { + Given([f64; 4]), + /// Its selected features (`rows`), or all of them (`None`). + Layer { + name: String, + dataset: rustgis_data::Dataset, + rows: Option>, + }, +} + +impl Bounds { + /// In `crs`. + fn in_crs(self, crs: Crs) -> Result<[f64; 4], String> { + match self { + Bounds::Given(b) => Ok(b), + Bounds::Layer { name, dataset, rows } => { + let rows: Box> = match rows { + Some(rows) => Box::new(rows.into_iter()), + None => Box::new(0..dataset.features.len()), + }; + // Cancel is looked at every few thousand features; a cancelled pass stops there. + let mut cancelled = None; + let shapes = rows + .enumerate() + .map_while(|(k, row)| { + if k % 4096 == 0 + && let Err(e) = rustgis_data::progress::check() + { + cancelled = Some(e.to_string()); + return None; + } + Some(row) + }) + .filter_map(|r| dataset.features.geometry(r)); + let e = dataset.lonlat_extent_of(shapes); + if let Some(e) = cancelled { + return Err(e); + } + if e.is_empty() { + return Err(format!("{name} has no features to take an extent from")); + } + warp::bounds_in([e.min_x, e.min_y, e.max_x, e.max_y], crs) + } + } + } +} + impl GridSpec { /// The grid: `natural` gives, in its system, the bounds taken without an extent and the cell /// size taken without a cellSize (`None`: a cellSize is required); it is asked only when one of @@ -904,6 +966,7 @@ impl GridSpec { match self { GridSpec::Fixed(g) => Ok(g), GridSpec::Build { crs, cell, origin, bounds } => { + let bounds = bounds.map(|b| b.in_crs(crs)).transpose()?; let (bounds, cell) = match (bounds, cell) { (Some(b), Some(c)) => (b, c), (b, c) => { @@ -922,9 +985,17 @@ impl GridSpec { /// The grid `p` gives ([`grid_param`]), with what to say of it (a template read from its overview). fn grid_spec(s: &Session, p: &Value, crs: Crs) -> Result<(GridSpec, Notes), String> { + let mut notes = Vec::new(); + // A refusal says what was to be said before it (a typed system's warning). + match grid_spec_noting(s, p, crs, &mut notes) { + Ok(spec) => Ok((spec, notes)), + Err(e) => Err(with_notes(e, ¬es)), + } +} + +fn grid_spec_noting(s: &Session, p: &Value, crs: Crs, notes: &mut Notes) -> Result { // A grid named as anything but a raster layer's name is refused rather than ignored. let template = project_grid(p)?; - let mut notes = Vec::new(); let spec = match template { Some(template) => { if ["crs", "cellSize", "origin", "extent"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { @@ -970,20 +1041,16 @@ fn grid_spec(s: &Session, p: &Value, crs: Crs) -> Result<(GridSpec, Notes), Stri Some(Value::String(_)) if project_extent_name(p).is_some() => { let l = project_extent_name(p).ok_or("extent layer is required")?; let layer = s.map().layer_by_name(l).filter(|l| l.raster.is_none()).ok_or_else(|| format!("no vector layer '{l}'"))?; - let rows: Vec = - if layer.selection.is_empty() { (0..layer.dataset.features.len()).collect() } else { layer.selection.clone() }; - let e = layer.rows_extent(rows); - if e.is_empty() { - return Err(format!("{l} has no features to take an extent from")); - } - Some(warp::bounds_in([e.min_x, e.min_y, e.max_x, e.max_y], crs)?) + let rows = (!layer.selection.is_empty()).then(|| layer.selection.clone()); + // Its rows shared, not copied ([`Bounds::in_crs`] reads them). + Some(Bounds::Layer { name: l.to_string(), dataset: layer.dataset.clone(), rows }) } Some(v @ (Value::Array(_) | Value::String(_))) => { let area = super::catalogs::area(s, &json!({"bbox": v})).map_err(|e| e.replacen("bbox", "extent", 1))?; if area[0] > area[2] { return Err("an extent across the antimeridian: give it one side at a time".into()); } - Some(warp::bounds_in(area, crs)?) + Some(Bounds::Given(warp::bounds_in(area, crs)?)) } // A number, a flag or an object isn't an extent: refused, not read as the view. Some(_) => return Err(EXTENT.into()), @@ -991,7 +1058,7 @@ fn grid_spec(s: &Session, p: &Value, crs: Crs) -> Result<(GridSpec, Notes), Stri GridSpec::Build { crs, cell, origin, bounds } } }; - Ok((spec, notes)) + Ok(spec) } fn is_tif(path: &str) -> bool { diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 614362752c..c7a430b938 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -1182,6 +1182,29 @@ pub(super) fn write_geotiff_with_guidance( rustgis_data::io::write_atomic(Path::new(path), &bytes).map_err(|e| format!("{path}: {e}"))?; None }; + wrote_geotiff(r, bi, path, cog, band_hint) +} + +/// [`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( + r: &Raster, + bi: usize, + path: &str, + band_hint: &str, +) -> Result<(super::exports::Wrote, rustgis_data::io::StagedWrite), String> { + let (cog, staged) = raster::cogwrite::write_staged(r, bi, Path::new(path)).map_err(|e| format!("{path}: {e}"))?; + Ok((wrote_geotiff(r, bi, path, Some(cog), band_hint)?, staged)) +} + +/// What writing `r`'s band `bi` to `path` says. +fn wrote_geotiff( + r: &Raster, + bi: usize, + path: &str, + cog: Option, + band_hint: &str, +) -> Result { let note = geotiff_note(r, bi, cog.is_some(), band_hint)?; let mut v = match r.overview { Some((fw, fh)) => json!({"path": path, "width": r.width, "height": r.height, "overviewOf": [fw, fh]}), diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index dca19b776c..00737cc01d 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -143,6 +143,17 @@ pub struct Made { /// Made on another thread: the command's name and the map it was started on. ran: Option<(&'static str, u64)>, pub(crate) continuation: Option, + /// The file the work wrote, put in its place as the raster is added: a run cancelled or + /// abandoned before then leaves the file there as it was. + staged: Option, +} + +impl Made { + /// With `file` to commit as it is added. + pub(crate) fn committing(mut self, file: rustgis_data::io::StagedWrite) -> Made { + self.staged = Some(file); + self + } } /// A workflow's work once its inputs are read: it reads nothing more of the session, so it runs on @@ -170,13 +181,17 @@ pub(crate) fn made_then(raster: Raster, extra: Option, then: Option /// A layer made (styled, say), to be added as `name`. pub(crate) fn made_layer(name: String, layer: rustgis_map::RasterLayer, extra: Option, then: Option) -> Made { - Made { name, layer, extra, then, ran: None, continuation: None, inputs: Vec::new() } + Made { name, layer, extra, then, ran: None, continuation: None, inputs: Vec::new(), staged: None } } /// Adds a made raster as a layer: the command's answer is the layer's (its id, size and bands) and /// 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, .. } = m; + let Made { name, layer, extra, then, inputs, staged, .. } = m; + if let Some(file) = staged { + let path = file.destination().display().to_string(); + file.commit().map_err(|e| format!("{path}: {e}"))?; + } 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()) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 62f3767b60..490f05e778 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -28768,6 +28768,24 @@ fn raster_export_paths_report_band_class_and_credit_changes() { std::fs::remove_dir_all(dir).unwrap(); } +/// Given both an extent and a cellSize, Project Raster takes the grid as given: a source whose +/// footprint can't be placed whole in the output's system (the whole world in the south polar +/// stereographic one, which can't hold the North Pole) is projected onto it, where without them it +/// is refused for want of a footprint. +#[test] +fn raster_project_takes_a_given_grid_without_the_sources_footprint() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let mut s = Session::new(Project::default()); + let gt = GeoTransform { origin_x: -180.0, origin_y: 90.0, pixel_width: 10.0, pixel_height: -10.0 }; + let r = Raster::new("World", 36, 18, vec![vec![1.0; 36 * 18]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let bytes = rustgis_data::raster::geotiff::write(&r, 0).unwrap(); + crate::cmd::raster::add_raster(&mut s, "World", rustgis_map::RasterLayer::from_bytes(r, "World.tif".to_string(), bytes)).unwrap(); + let e = s.run("raster.project", &json!({"layer": "World", "crs": 3031})).unwrap_err(); + assert!(e.contains("can't be placed in"), "{e}"); + let v = s.run("raster.project", &json!({"layer": "World", "crs": 3031, "extent": [-180, -90, 180, -60], "cellSize": 500_000})).unwrap(); + assert!(v["width"].as_u64().is_some_and(|w| w > 0), "{v}"); +} + /// Class labels describe source values; interpolating or averaging those values drops the labels /// with a notice, while nearest, mode and palette-safe sampling retain them. #[test] @@ -51260,6 +51278,10 @@ fn raster_tools_run_on_another_thread() { .map(|o| o.iter().filter(|(k, _)| !named.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect::>()) }; assert_eq!(besides(&here), besides(&there), "{command} {p}"); + // Each run says them, or neither: only their values differ. + for key in named { + assert_eq!(here.get(key).map(Value::is_string), there.get(key).map(Value::is_string), "{command} {key}: {here} {there}"); + } // A name said is the one the layer got. if let Some(name) = there["name"].as_str() { let id = there["layer"].as_u64().unwrap() as u32; diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index fdc8096b09..6f73c42e6e 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -86,7 +86,7 @@ pub(super) fn long_commands(boundaries: bool) { ("raster.index", json!({"layer": dem, "index": "ndvi", "nir": 1, "red": 1})), ("raster.process", json!({"layer": dem, "operation": "resample", "factor": 4})), ("imagery.mosaic", json!({"name": "Valley"})), - ("raster.rasterize", json!({"layer": "Squares", "field": "name", "cellSize": 0.0005})), + ("raster.rasterize", json!({"layer": "Squares", "field": "name", "cellSize": 0.0005, "path": out("burned.tif")})), ( "dl.classify", json!({"layer": "scene", "training": "training", "classField": "class", "bands": [1, 2], "epochs": if boundaries { 2 } else { 30 }, "model": "landcover"}), diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 4f6ce5f6cc..b8c58f2c78 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2444,11 +2444,30 @@ fn a_layer_held_in_degrees_is_burned_in_the_system_it_was_read_in() { let ring: Vec = [(11.0, 48.0), (11.01, 48.0), (11.01, 48.01), (11.0, 48.01), (11.0, 48.0)].iter().map(|(x, y)| Coord::new(*x, *y)).collect(); let mut s = Session::new(Project::default()); - add_in(&mut s, "Plot", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![ring]])], geographic); + add_in(&mut s, "Plot", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![ring.clone()]])], geographic); let id = s.map().layer_by_name("Plot").unwrap().id; s.map_mut().layer_mut(id).unwrap().dataset.crs = Some(UTM); - s.run("raster.rasterize", &json!({"layer": "Plot", "cellSize": 10, "name": "Burned"})).unwrap(); - assert_eq!(grid_of(&s, "Burned").crs, UTM); + let v = s.run("raster.rasterize", &json!({"layer": "Plot", "cellSize": 10, "name": "Burned"})).unwrap(); + let r = grid_of(&s, "Burned"); + assert_eq!(r.crs, UTM); + // The grid holds the corners as converted into UTM, within a cell of them. + let to = geographic.to(UTM).unwrap(); + let corners: Vec = ring.iter().map(|c| to.point(*c).unwrap()).collect(); + let mut b = rustgis_geom::Extent::EMPTY; + corners.iter().for_each(|c| b.expand(*c)); + let t = r.transform; + let e = rustgis_geom::Extent { + min_x: t.origin_x, + max_y: t.origin_y, + max_x: t.origin_x + t.pixel_width * f64::from(r.width), + min_y: t.origin_y + t.pixel_height * f64::from(r.height), + }; + assert!(e.min_x <= b.min_x && e.min_y <= b.min_y && e.max_x >= b.max_x && e.max_y >= b.max_y, "{e:?} {b:?}"); + assert!(b.min_x - e.min_x < 10.0 && b.min_y - e.min_y < 10.0 && e.max_x - b.max_x < 10.0 && e.max_y - b.max_y < 10.0, "{e:?} {b:?}"); + // And it burns about the polygon's area in UTM (some 830,000 m²) in 10 m cells. + let area = corners.windows(2).map(|w| w[0].x * w[1].y - w[1].x * w[0].y).sum::().abs() / 2.0; + let cells = v["cells"].as_f64().unwrap(); + assert!((cells * 100.0 / area - 1.0).abs() < 0.03, "{cells} cells for {area} m²"); } /// Rasterize sizes its default grid in another system by the polygons' box in longitude/latitude, diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index a78461d720..5069deddbf 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -381,17 +381,22 @@ fn background(id: &str) -> Option<(&'static str, &'static str)> { } /// Starts a command that makes a raster (`workflows::runs_in_background`) asked for outside the -/// pane (Command Search, the Assistant through the app): on a thread of its own, the Workflows pane +/// pane through the app's dispatch (Command Search): on a thread of its own, the Workflows pane /// opened to show its progress and Cancel, as from a section; its layer is added when it lands, a /// failure then said in the status bar. The answer says it started; one that can't start (another /// is under way) is an error. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn start_from_dispatch(app: &mut RustGisApp, command: &'static str, name: &'static str, p: Value) -> Result { - // Opened, not toggled: a pane already open stays so. - app.ui.open_right(crate::RightPane::Workflows); + // Its result is shown in the section the pane shows as it starts (the first, when it never + // opened), as a run from that section's would be. + settle_section(app); start(app, command, name, p); match &app.workflow.job { - Some(job) if job.name == name && app.workflow.error.is_none() => Ok(json!({"started": name})), + Some(job) if job.name == name && app.workflow.error.is_none() => { + // Opened, not toggled: a pane already open stays so; one that didn't start doesn't open it. + app.ui.open_right(crate::RightPane::Workflows); + Ok(json!({"started": name})) + } _ => Err(app.workflow.error.clone().unwrap_or_else(|| crate::i18n::fmt("{tool} didn't start", &[("tool", tl_raw!(name))]))), } } @@ -647,10 +652,9 @@ fn picked(app: &mut RustGisApp, purpose: &str) -> Option Date: Mon, 23 Nov 2026 00:17:51 +0100 Subject: [PATCH 03/11] Review: a job cancelled after its work is done is dropped when it lands; the parity test requires names as text; a notice reindented --- crates/engine/src/cmd/imagery.rs | 16 +++++------ crates/engine/src/tests.rs | 10 +++++-- crates/ui-egui/src/analysispane.rs | 44 ++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 5d02804393..e6c2433ac2 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -650,14 +650,14 @@ pub(crate) fn rasterize_work(s: &Session, p: &Value) -> Result 0 && !extent_given { notes.push(( - format!( - "{ln}: {unsized_by} {} that can't be placed in longitude/latitude {} left out of the grid's extent: check {} coordinates and the layer's coordinate system", - if unsized_by == 1 { "vertex" } else { "vertices" }, - if unsized_by == 1 { "was" } else { "were" }, - if unsized_by == 1 { "its" } else { "their" } - ), - false, - )); + format!( + "{ln}: {unsized_by} {} that can't be placed in longitude/latitude {} left out of the grid's extent: check {} coordinates and the layer's coordinate system", + if unsized_by == 1 { "vertex" } else { "vertices" }, + if unsized_by == 1 { "was" } else { "were" }, + if unsized_by == 1 { "its" } else { "their" } + ), + false, + )); } // The smallest pixel type the GeoTIFF writer keeps that holds every value and the no-data. let whole = diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 490f05e778..eb9a0dee92 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -51278,9 +51278,13 @@ fn raster_tools_run_on_another_thread() { .map(|o| o.iter().filter(|(k, _)| !named.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect::>()) }; assert_eq!(besides(&here), besides(&there), "{command} {p}"); - // Each run says them, or neither: only their values differ. - for key in named { - assert_eq!(here.get(key).map(Value::is_string), there.get(key).map(Value::is_string), "{command} {key}: {here} {there}"); + // Each run gives the layer's id, and says the names as text, or neither: only their + // values differ. + assert!(here["layer"].is_u64() && there["layer"].is_u64(), "{command}: {here} {there}"); + for key in ["name", "classTable"] { + let said = |v: &Value| v.get(key).map(|n| n.as_str().map(|_| ()).ok_or(())); + assert_eq!(said(&here), said(&there), "{command} {key}: {here} {there}"); + assert_ne!(said(&here), Some(Err(())), "{command} {key} is not text: {here}"); } // A name said is the one the layer got. if let Some(name) = there["name"].as_str() { diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 5069deddbf..235f889eba 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -488,7 +488,20 @@ pub fn land_job(app: &mut RustGisApp) -> bool { return true; } let Some(job) = app.workflow.job.take() else { return false }; + // Cancelled once its work was done, before it landed (in the frame between): dropped, so + // nothing is added, and a file it wrote beside its destination is removed. + let cancelled = || Err(crate::i18n::fmt("{tool} was cancelled", &[("tool", tl_raw!(job.name))])); match job.kind { + JobKind::Tool { id, slot } if job.control.is_cancelled() => { + drop(take(&slot)); + gp::tool_abandon(&mut app.session, id); + show_job(app, job.section, cancelled()); + } + JobKind::Raster { id, slot, .. } if job.control.is_cancelled() => { + drop(take(&slot)); + workflows::raster_abandon(&mut app.session, id); + show_job(app, job.section, cancelled()); + } JobKind::Tool { id, slot } => { let Some(done) = take(&slot) else { return false }; let r = gp::tool_complete(&mut app.session, id, done).and_then(|_| app.finish_gp(id)); @@ -3089,6 +3102,37 @@ mod tests { assert_eq!(app.session.project.tables.len(), tables + 1); } + /// A Cancel that comes once the work is done, before the job lands, still holds: nothing is + /// added, and the GeoTIFF it wrote beside its destination is removed, the destination left as + /// it was. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_cancel_after_the_work_is_done_drops_what_it_made() { + let dir = std::env::temp_dir().join(format!("rustgis-late-cancel-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("burned.tif"); + std::fs::write(&path, b"before").unwrap(); + let mut app = RustGisApp::with_sample(); + app.reads_off_frame = true; + let layers = app.session.map().layers.len(); + let p = json!({"layer": "Countries", "field": "name", "cellSize": 5, "path": path.to_string_lossy()}); + app.run("raster.rasterize", p).unwrap(); + let end = std::time::Instant::now() + std::time::Duration::from_secs(60); + while !matches!(&app.workflow.job, Some(Job { kind: JobKind::Raster { slot, .. }, .. }) if filled(slot)) { + assert!(std::time::Instant::now() < end, "the run never finished"); + std::thread::sleep(std::time::Duration::from_millis(5)); // test-wait: polling for the worker to fill its slot + } + app.workflow.job.as_ref().unwrap().control.cancel(); + assert!(!land_job(&mut app)); + assert!(app.workflow.job.is_none()); + assert!(app.workflow.error.as_deref().is_some_and(|e| e.contains("was cancelled")), "{:?}", app.workflow.error); + assert_eq!(app.session.map().layers.len(), layers); + assert_eq!(std::fs::read(&path).unwrap(), b"before"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "a staged file was left"); + std::fs::remove_dir_all(dir).unwrap(); + } + /// Interpolate runs on a thread of its own from the pane (#1291 step 3): the pane goes on while /// it works, a second run waits for the first, and its layer lands through its command, which /// Record Task takes without the raster it handed over (a replay works it out again). From 93ce94c02356d0bdc35fb88eb4271aad318551c4 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 00:45:48 +0100 Subject: [PATCH 04/11] Review: every pass of rasterize's work looks at Cancel; the late-cancel test checks the run made its raster --- crates/engine/src/cmd/imagery.rs | 29 +++++++++++++++++++---------- crates/ui-egui/src/analysispane.rs | 5 ++++- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index e6c2433ac2..270c4a716c 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -526,7 +526,8 @@ pub(crate) fn rasterize_work(s: &Session, p: &Value) -> Result Result Result Result Result = classes.iter().take(256).enumerate().map(|(i, c)| json!({"code": i + 1, "value": c})).collect(); let class_count = classes.len(); diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 235f889eba..e4d702f78c 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -3123,7 +3123,10 @@ mod tests { assert!(std::time::Instant::now() < end, "the run never finished"); std::thread::sleep(std::time::Duration::from_millis(5)); // test-wait: polling for the worker to fill its slot } - app.workflow.job.as_ref().unwrap().control.cancel(); + // It made its raster (and wrote its file beside the destination): looked at, not taken. + let Some(Job { kind: JobKind::Raster { slot, .. }, control, .. }) = &app.workflow.job else { panic!("no raster job") }; + assert!(matches!(&*slot.lock().unwrap(), Some(Ok(_))), "the run failed"); + control.cancel(); assert!(!land_job(&mut app)); assert!(app.workflow.job.is_none()); assert!(app.workflow.error.as_deref().is_some_and(|e| e.contains("was cancelled")), "{:?}", app.workflow.error); From 432f294af4044432674ba9fc4ad6c5560560ec75 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 01:36:42 +0100 Subject: [PATCH 05/11] Review: a GeoTIFF that can't be put in place fails with the run's notes; the extent layer's vertices look at Cancel; the streamed write's buffer is a megabyte --- crates/analysis/src/rasterops.rs | 3 +- crates/data/src/io.rs | 10 ++++--- crates/engine/src/cmd/imagery.rs | 45 ++++++++++++++++++++---------- crates/engine/src/cmd/workflows.rs | 13 +++++---- crates/engine/src/tests.rs | 17 +++++++++++ 5 files changed, 62 insertions(+), 26 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 68dd220612..1fab346287 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1433,7 +1433,8 @@ pub fn transform_polygon_to_lonlat(rings: &[Vec], tr: Option<&Transformer } /// The polygon parts of a (multi-)polygon feature, checked and taken apart into rings, in the -/// system they are in: [`transform_feature_polygons_to_lonlat`] with no transformer. +/// system they are in: [`transform_feature_polygons_to_lonlat`] with no transformer. It doesn't +/// look at Cancel: a caller looping over features does, between them. pub fn validated_polygon_parts(polys: &[Vec>]) -> Result>>, PolygonTransformError> { transform_feature_polygons_to_lonlat(polys, None) } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 172b540b12..a6433ea013 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1173,7 +1173,7 @@ pub fn replace_atomic_with>( /// [`StagedWrite::commit`] installs them. Dropping the result discards the staged file. pub fn stage_atomic(path: &Path, bytes: &[u8]) -> std::io::Result { use std::io::Write; - stage_at(link_target(path)?, |w| w.write_all(bytes)).map(|(staged, ())| staged) + stage_at(link_target(path)?, 8 << 10, |w| w.write_all(bytes)).map(|(staged, ())| staged) } /// [`stage_atomic`] for a write that streams: `write` fills the file beside the destination (a @@ -1182,7 +1182,8 @@ pub fn stage_streamed>( path: &Path, write: impl FnOnce(&mut std::io::BufWriter) -> std::result::Result, ) -> std::result::Result<(StagedWrite, T), E> { - stage_at(link_target(path)?, write) + // A streamed write (a raster's tiles) goes through a buffer of a megabyte. + stage_at(link_target(path)?, 1 << 20, write) } /// Stages and installs a write, retaining the old file on error or cancellation. @@ -1190,7 +1191,7 @@ fn atomic_write_at>( path: std::path::PathBuf, write: impl FnOnce(&mut std::io::BufWriter) -> std::result::Result, ) -> std::result::Result { - let (staged, value) = stage_at(path, write)?; + let (staged, value) = stage_at(path, 8 << 10, write)?; staged.commit()?; Ok(value) } @@ -1199,6 +1200,7 @@ fn atomic_write_at>( /// and a directory sync. fn stage_at>( path: std::path::PathBuf, + buffer: usize, write: impl FnOnce(&mut std::io::BufWriter) -> std::result::Result, ) -> std::result::Result<(StagedWrite, T), E> { use std::io::Write; @@ -1224,7 +1226,7 @@ fn stage_at>( Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => return Err(error.into()), } - let mut out = std::io::BufWriter::new(file); + let mut out = std::io::BufWriter::with_capacity(buffer, file); let value = write(&mut out)?; out.flush()?; out.get_ref().sync_all()?; diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 270c4a716c..b42f5f4344 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -767,6 +767,8 @@ pub(crate) fn rasterize_work(s: &Session, p: &Value) -> Result = classes.iter().take(256).enumerate().map(|(i, c)| json!({"code": i + 1, "value": c})).collect(); let class_count = classes.len(); let notes = std::mem::take(&mut notes); + // Said with the error should its file not go in place. + let said: Vec = notes.iter().map(|(n, _)| n.clone()).chain(written.iter().cloned()).collect(); let then: super::workflows::Then = Box::new(move |s: &mut Session, v: &mut Value| { say(s, notes); for note in written { @@ -787,7 +789,7 @@ pub(crate) fn rasterize_work(s: &Session, p: &Value) -> Result made.committing(file), + Some(file) => made.committing(file, said), None => made, }) })(); @@ -940,23 +942,36 @@ impl Bounds { Some(rows) => Box::new(rows.into_iter()), None => Box::new(0..dataset.features.len()), }; - // Cancel is looked at every few thousand features; a cancelled pass stops there. + // Each vertex converted as `lonlat_extent_of` does it, Cancel looked at every few + // thousand features and vertices. + let to = dataset.lonlat_conversion()?; + let (mut e, mut seen) = (Extent::EMPTY, 0usize); let mut cancelled = None; - let shapes = rows - .enumerate() - .map_while(|(k, row)| { - if k % 4096 == 0 - && let Err(e) = rustgis_data::progress::check() + for row in rows { + if seen.is_multiple_of(4096) { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + } + seen += 1; + let Some(g) = dataset.features.geometry(row) else { continue }; + if to.is_identity() { + e = e.union(&g.extent()); + continue; + } + g.for_each_coord(|c| { + seen += 1; + if cancelled.is_some() + || (seen.is_multiple_of(4096) + && rustgis_data::progress::check().map_err(|e| cancelled = Some(e.to_string())).is_err()) { - cancelled = Some(e.to_string()); - return None; + return; } - Some(row) - }) - .filter_map(|r| dataset.features.geometry(r)); - let e = dataset.lonlat_extent_of(shapes); - if let Some(e) = cancelled { - return Err(e); + if let Some(l) = to.point(c) { + e.expand(l); + } + }); + if let Some(c) = cancelled { + return Err(c); + } } if e.is_empty() { return Err(format!("{name} has no features to take an extent from")); diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 00737cc01d..456b7e43e8 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -145,13 +145,14 @@ pub struct Made { pub(crate) continuation: Option, /// The file the work wrote, put in its place as the raster is added: a run cancelled or /// abandoned before then leaves the file there as it was. - staged: Option, + staged: Option<(rustgis_data::io::StagedWrite, Vec)>, } impl Made { - /// With `file` to commit as it is added. - pub(crate) fn committing(mut self, file: rustgis_data::io::StagedWrite) -> Made { - self.staged = Some(file); + /// With `file` to commit as it is added; `said`, what the run had to say, goes with the + /// error when it can't be (its `then` doesn't run). + pub(crate) fn committing(mut self, file: rustgis_data::io::StagedWrite, said: Vec) -> Made { + self.staged = Some((file, said)); self } } @@ -188,9 +189,9 @@ 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) = staged { + if let Some((file, said)) = staged { let path = file.destination().display().to_string(); - file.commit().map_err(|e| format!("{path}: {e}"))?; + file.commit().map_err(|e| if said.is_empty() { format!("{path}: {e}") } else { format!("{path}: {e} ({})", said.join("; ")) })?; } rustgis_data::provenance::record(inputs); let mut v = super::raster::add_raster(s, &name, layer)?; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index eb9a0dee92..ec07c7c187 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -28784,6 +28784,11 @@ fn raster_project_takes_a_given_grid_without_the_sources_footprint() { assert!(e.contains("can't be placed in"), "{e}"); let v = s.run("raster.project", &json!({"layer": "World", "crs": 3031, "extent": [-180, -90, 180, -60], "cellSize": 500_000})).unwrap(); assert!(v["width"].as_u64().is_some_and(|w| w > 0), "{v}"); + // The whole world reaches every cell of the grid, as projected: each takes its value. + let id = v["layer"].as_u64().unwrap() as u32; + let out = s.map().layer(id).and_then(|l| l.raster.as_ref()).and_then(|r| r.data.clone()).unwrap(); + assert_eq!(out.crs, rustgis_data::raster::Crs::from_epsg(3031).unwrap()); + assert!(out.bands[0].data.iter().all(|c| *c == 1.0), "{:?}", &out.bands[0].data[..8]); } /// Class labels describe source values; interpolating or averaging those values drops the labels @@ -51086,6 +51091,18 @@ fn polygons_burned_onto_a_chosen_grid() { assert!(e.contains("cellSize is required"), "{e}"); let e = s.run("raster.rasterize", &json!({"layer": "soils", "nodata": 1, "cellSize": 1})).unwrap_err(); assert!(e.contains("no-data value"), "{e}"); + // A GeoTIFF that can't be put in its place (a folder holds its name): refused, with what the + // run had to say, and nothing added. + let dir = std::env::temp_dir().join(format!("rustgis-rasterize-commit-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let taken = dir.join("soils.tif"); + std::fs::create_dir_all(taken.join("inside")).unwrap(); + let e = + s.run("raster.rasterize", &json!({"layer": "soils", "field": "unit", "cellSize": 1, "path": taken.to_string_lossy()})).unwrap_err(); + assert!(e.contains("soils.tif") && e.contains("features skipped: 1 with no value"), "{e}"); + assert_eq!((s.map().layers.len(), s.project.tables.len()), (layers, tables), "nothing added by a refused run"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "the staged file is removed"); + std::fs::remove_dir_all(dir).unwrap(); } /// A whole number past what a pixel holds is refused with advice that applies: a numeric field can From cb293761afc18c505b51f96f39ba2d03b0672150 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 03:01:55 +0100 Subject: [PATCH 06/11] Review: the dispatch test's doc names Command Search only; an extent layer with no features refused in the run, tested --- crates/engine/src/tests.rs | 6 ++++++ crates/ui-egui/src/analysispane.rs | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ec07c7c187..6e4d23f168 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -51091,6 +51091,12 @@ fn polygons_burned_onto_a_chosen_grid() { assert!(e.contains("cellSize is required"), "{e}"); let e = s.run("raster.rasterize", &json!({"layer": "soils", "nodata": 1, "cellSize": 1})).unwrap_err(); assert!(e.contains("no-data value"), "{e}"); + // An extent layer with no features: refused (as the run sizes its grid), nothing added. + crate::cmd::layer::add_dataset(&mut s, Dataset::new("nothing", GeometryType::Polygon, vec![Field::new("unit", FieldType::Text)])); + let e = s.run("raster.rasterize", &json!({"layer": "soils", "field": "unit", "cellSize": 1, "extent": "nothing"})).unwrap_err(); + assert!(e.contains("nothing has no features to take an extent from"), "{e}"); + let layers = layers + 1; + assert_eq!((s.map().layers.len(), s.project.tables.len()), (layers, tables), "nothing added by a refused run"); // A GeoTIFF that can't be put in its place (a folder holds its name): refused, with what the // run had to say, and nothing added. let dir = std::env::temp_dir().join(format!("rustgis-rasterize-commit-{}", std::process::id())); diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index e4d702f78c..21dbef2895 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -3066,8 +3066,8 @@ mod tests { } } - /// A command that makes a raster, asked for through the app's dispatch (Command Search, the - /// assistant) rather than a section, runs on a thread of its own too: Polygons to Raster from a + /// A command that makes a raster, asked for through the app's dispatch (Command Search) rather + /// than a section, runs on a thread of its own too: Polygons to Raster from a /// text field answers that it started, the pane shows it running, and its layer and class table /// land with it. #[cfg(not(target_arch = "wasm32"))] From 0c2e73537f7eef236c256cc576d4c82ab93e6367 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 04:02:54 +0100 Subject: [PATCH 07/11] Review: an extent layer's vertices that can't be placed are said --- crates/engine/src/cmd/imagery.rs | 36 +++++++++++++++++++------- crates/engine/src/tests/held_layers.rs | 27 +++++++++++++++++++ 2 files changed, 53 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index b42f5f4344..4e7de403e3 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -623,7 +623,7 @@ pub(crate) fn rasterize_work(s: &Session, p: &Value) -> Result Result<([f64; 4], Option), String>, ) -> Result { - let (spec, notes) = grid_spec(s, p, crs)?; + let (spec, mut notes) = grid_spec(s, p, crs)?; + let grid = spec.finish(&mut notes, natural); say(s, notes); - spec.finish(natural) + grid } /// What to say: a notice, or a warning (`true`). @@ -933,8 +934,9 @@ enum Bounds { } impl Bounds { - /// In `crs`. - fn in_crs(self, crs: Crs) -> Result<[f64; 4], String> { + /// In `crs`; what it has to say (an extent layer's vertices that can't be placed) goes to + /// `notes`. + fn in_crs(self, crs: Crs, notes: &mut Notes) -> Result<[f64; 4], String> { match self { Bounds::Given(b) => Ok(b), Bounds::Layer { name, dataset, rows } => { @@ -945,7 +947,7 @@ impl Bounds { // Each vertex converted as `lonlat_extent_of` does it, Cancel looked at every few // thousand features and vertices. let to = dataset.lonlat_conversion()?; - let (mut e, mut seen) = (Extent::EMPTY, 0usize); + let (mut e, mut seen, mut unplaced) = (Extent::EMPTY, 0usize, 0usize); let mut cancelled = None; for row in rows { if seen.is_multiple_of(4096) { @@ -965,14 +967,28 @@ impl Bounds { { return; } - if let Some(l) = to.point(c) { - e.expand(l); + // A missing coordinate (NaN) is no vertex to place. + match to.point(c) { + Some(l) => e.expand(l), + None if c.is_finite() => unplaced += 1, + None => {} } }); if let Some(c) = cancelled { return Err(c); } } + if unplaced > 0 { + notes.push(( + format!( + "{name}: {unplaced} {} that can't be placed in longitude/latitude {} left out of the grid's extent: check {} coordinates and the layer's coordinate system", + if unplaced == 1 { "vertex" } else { "vertices" }, + if unplaced == 1 { "was" } else { "were" }, + if unplaced == 1 { "its" } else { "their" } + ), + false, + )); + } if e.is_empty() { return Err(format!("{name} has no features to take an extent from")); } @@ -986,11 +1002,11 @@ impl GridSpec { /// The grid: `natural` gives, in its system, the bounds taken without an extent and the cell /// size taken without a cellSize (`None`: a cellSize is required); it is asked only when one of /// them is missing. - fn finish(self, natural: impl FnOnce(Crs) -> Result<([f64; 4], Option), String>) -> Result { + fn finish(self, notes: &mut Notes, natural: impl FnOnce(Crs) -> Result<([f64; 4], Option), String>) -> Result { match self { GridSpec::Fixed(g) => Ok(g), GridSpec::Build { crs, cell, origin, bounds } => { - let bounds = bounds.map(|b| b.in_crs(crs)).transpose()?; + let bounds = bounds.map(|b| b.in_crs(crs, notes)).transpose()?; let (bounds, cell) = match (bounds, cell) { (Some(b), Some(c)) => (b, c), (b, c) => { diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index b8c58f2c78..9fa213b634 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2470,6 +2470,33 @@ fn a_layer_held_in_degrees_is_burned_in_the_system_it_was_read_in() { assert!((cells * 100.0 / area - 1.0).abs() < 0.03, "{cells} cells for {area} m²"); } +/// An extent layer with a vertex that can't be placed in longitude/latitude sizes the grid +/// without it, and says so; clean input says nothing. +#[test] +fn an_extent_layers_unplaced_vertices_are_said() { + let (x0, y0) = (784_000.0, 5_401_300.0); + let square: Vec = + [(0.0, 0.0), (1000.0, 0.0), (1000.0, 1000.0), (0.0, 1000.0), (0.0, 0.0)].iter().map(|(x, y)| Coord::new(x0 + x, y0 + y)).collect(); + let far = vec![Coord::new(x0, y0), Coord::new(1e12, 1e12), Coord::new(x0, y0 + 500.0), Coord::new(x0, y0)]; + let mut s = Session::new(Project::default()); + add_in(&mut s, "Plot", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![square.clone()]])], UTM); + add_in(&mut s, "Clean", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![square]])], UTM); + add_in(&mut s, "Odd", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![far]])], UTM); + let said = |s: &Session, mark| s.notices_since(mark).iter().map(|n| n.text.clone()).collect::>(); + let mark = s.notice_mark(); + s.run("raster.rasterize", &json!({"layer": "Plot", "cellSize": 0.001, "crs": "EPSG:4326", "extent": "Clean", "name": "A"})).unwrap(); + assert!(said(&s, mark).iter().all(|n| !n.contains("left out of the grid's extent")), "{:?}", said(&s, mark)); + let mark = s.notice_mark(); + s.run("raster.rasterize", &json!({"layer": "Plot", "cellSize": 0.001, "crs": "EPSG:4326", "extent": "Odd", "name": "B"})).unwrap(); + assert!( + said(&s, mark) + .iter() + .any(|n| n.starts_with("Odd: 1 vertex that can't be placed in longitude/latitude was left out of the grid's extent")), + "{:?}", + said(&s, mark) + ); +} + /// Rasterize sizes its default grid in another system by the polygons' box in longitude/latitude, /// and says how many vertices it couldn't place there, left out of that box: a polygon held in UTM /// with a vertex far beyond any place UTM holds, burned onto a grid in degrees. With an extent From 4b00398bfb6bc41fef669f3e974261f081127f7e Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 04:43:37 +0100 Subject: [PATCH 08/11] Review: an extent layer read in place is refused --- crates/engine/src/cmd/imagery.rs | 4 ++++ crates/engine/src/tests.rs | 8 ++++++++ 2 files changed, 12 insertions(+) diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 4e7de403e3..ddd3b8ec32 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1081,6 +1081,10 @@ fn grid_spec_noting(s: &Session, p: &Value, crs: Crs, notes: &mut Notes) -> Resu Some(Value::String(_)) if project_extent_name(p).is_some() => { let l = project_extent_name(p).ok_or("extent layer is required")?; let layer = s.map().layer_by_name(l).filter(|l| l.raster.is_none()).ok_or_else(|| format!("no vector layer '{l}'"))?; + // Read in place, it holds only the part in view: its bounds wouldn't be the layer's. + if layer.dataset.windowed { + return Err(format!("{l}: load all its features first (Layers › Load All Features)")); + } let rows = (!layer.selection.is_empty()).then(|| layer.selection.clone()); // Its rows shared, not copied ([`Bounds::in_crs`] reads them). Some(Bounds::Layer { name: l.to_string(), dataset: layer.dataset.clone(), rows }) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6e4d23f168..090326f437 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -51091,6 +51091,14 @@ fn polygons_burned_onto_a_chosen_grid() { assert!(e.contains("cellSize is required"), "{e}"); let e = s.run("raster.rasterize", &json!({"layer": "soils", "nodata": 1, "cellSize": 1})).unwrap_err(); assert!(e.contains("no-data value"), "{e}"); + // An extent layer read in place holds only the part in view: refused before the run. + let mut part = Dataset::new("part", GeometryType::Polygon, vec![Field::new("unit", FieldType::Text)]); + part.push(Some(Geometry::Polygon(vec![vec![ring(0.0, 0.0, 1.0, 1.0)]])), vec![V::Text("x".into())]); + part.windowed = true; + crate::cmd::layer::add_dataset(&mut s, part); + let e = s.run("raster.rasterize", &json!({"layer": "soils", "field": "unit", "cellSize": 1, "extent": "part"})).unwrap_err(); + assert!(e.contains("part: load all its features first"), "{e}"); + let layers = layers + 1; // An extent layer with no features: refused (as the run sizes its grid), nothing added. crate::cmd::layer::add_dataset(&mut s, Dataset::new("nothing", GeometryType::Polygon, vec![Field::new("unit", FieldType::Text)])); let e = s.run("raster.rasterize", &json!({"layer": "soils", "field": "unit", "cellSize": 1, "extent": "nothing"})).unwrap_err(); From 6a7cf26f8cf1870acc44816faa0b3d81e569272d Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 05:25:40 +0100 Subject: [PATCH 09/11] Review: Project Raster's windowed extent refusal tested and described --- crates/engine/src/tests.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 090326f437..49fa863648 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -28775,6 +28775,7 @@ fn raster_export_paths_report_band_class_and_credit_changes() { #[test] fn raster_project_takes_a_given_grid_without_the_sources_footprint() { use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + use rustgis_data::{Coord, Dataset, Geometry, GeometryType}; let mut s = Session::new(Project::default()); let gt = GeoTransform { origin_x: -180.0, origin_y: 90.0, pixel_width: 10.0, pixel_height: -10.0 }; let r = Raster::new("World", 36, 18, vec![vec![1.0; 36 * 18]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); @@ -28784,6 +28785,21 @@ fn raster_project_takes_a_given_grid_without_the_sources_footprint() { assert!(e.contains("can't be placed in"), "{e}"); let v = s.run("raster.project", &json!({"layer": "World", "crs": 3031, "extent": [-180, -90, 180, -60], "cellSize": 500_000})).unwrap(); assert!(v["width"].as_u64().is_some_and(|w| w > 0), "{v}"); + // An extent layer read in place (only the part in view) is refused, as for Polygons to Raster. + let mut part = Dataset::new("part", GeometryType::Polygon, vec![]); + part.push( + Some(Geometry::Polygon(vec![vec![vec![ + Coord::new(0.0, -80.0), + Coord::new(10.0, -80.0), + Coord::new(10.0, -70.0), + Coord::new(0.0, -80.0), + ]]])), + vec![], + ); + part.windowed = true; + crate::cmd::layer::add_dataset(&mut s, part); + let e = s.run("raster.project", &json!({"layer": "World", "crs": 3031, "extent": "part", "cellSize": 500_000})).unwrap_err(); + assert!(e.contains("part: load all its features first"), "{e}"); // The whole world reaches every cell of the grid, as projected: each takes its value. let id = v["layer"].as_u64().unwrap() as u32; let out = s.map().layer(id).and_then(|l| l.raster.as_ref()).and_then(|r| r.data.clone()).unwrap(); From c1203500d8404cc06696a8a20d2ba9e48fd66bd3 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 06:05:02 +0100 Subject: [PATCH 10/11] Review: the work lets go of the layer's rows once its polygons are collected; the bounds pass only when needed; an extent with no placeable vertex says so --- crates/engine/src/cmd/imagery.rs | 22 ++++++++++++++++------ crates/engine/src/tests/held_layers.rs | 7 +++++++ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index ddd3b8ec32..1acaaeae1b 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -533,7 +533,11 @@ pub(crate) fn rasterize_work(s: &Session, p: &Value) -> Result Result { + let ds = ds.take().ok_or("the work ran twice")?; // The features burned: the selection, else all, in the layer's order (a later one wins). let mut rows: Vec = if selection.is_empty() { (0..ds.features.len()).collect() } else { selection }; rows.sort_unstable(); @@ -587,6 +591,7 @@ pub(crate) fn rasterize_work(s: &Session, p: &Value) -> Result Result 0 { + format!("{name} has no vertex that can be placed in longitude/latitude to take an extent from") + } else { + format!("{name} has no features to take an extent from") + }); } warp::bounds_in([e.min_x, e.min_y, e.max_x, e.max_y], crs) } diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 9fa213b634..f555191b69 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2495,6 +2495,13 @@ fn an_extent_layers_unplaced_vertices_are_said() { "{:?}", said(&s, mark) ); + // Only vertices that can't be placed: refused, saying so, not that it has no features. + let nowhere = vec![Coord::new(1e12, 1e12), Coord::new(2e12, 1e12), Coord::new(2e12, 2e12), Coord::new(1e12, 1e12)]; + add_in(&mut s, "Nowhere", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![nowhere]])], UTM); + let e = s + .run("raster.rasterize", &json!({"layer": "Plot", "cellSize": 0.001, "crs": "EPSG:4326", "extent": "Nowhere", "name": "C"})) + .unwrap_err(); + assert!(e.contains("Nowhere has no vertex that can be placed in longitude/latitude"), "{e}"); } /// Rasterize sizes its default grid in another system by the polygons' box in longitude/latitude, From 9b2ab65a46c335e312667126b2411ae48fc1750f Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 08:17:35 +0100 Subject: [PATCH 11/11] Rebase on main: the command surface lists rasterize's ran; written notes as main's Notes --- crates/engine/command-surface.txt | 2 +- crates/engine/src/cmd/imagery.rs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index d0f5f8118d..8e7148c2ed 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -477,7 +477,7 @@ raster.measurements clear? raster.mosaic inputs name? path? 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? +raster.rasterize layer field? value? nodata? crs? cellSize? origin? extent? grid? name? path? ran? raster.resampling layer? type raster.rotation layer? angle raster.setDefaultStyle fromLayer? layer? ramp? invert? stretch? low? high? n? resampling? reset? diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 1acaaeae1b..0755ac7bb9 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -731,7 +731,7 @@ pub(crate) fn rasterize_work(s: &Session, p: &Value) -> Result { let (wrote, file) = super::raster::write_cog_staged( @@ -774,11 +774,11 @@ pub(crate) fn rasterize_work(s: &Session, p: &Value) -> Result = notes.iter().map(|(n, _)| n.clone()).chain(written.iter().cloned()).collect(); + let said: Vec = notes.iter().map(|(n, _)| n.clone()).chain(written.texts().map(str::to_string)).collect(); let then: super::workflows::Then = Box::new(move |s: &mut Session, v: &mut Value| { say(s, notes); for note in written { - s.notify_written(note); + s.say_written(note); } // The name the layer got (another may hold the one asked for: "… raster (2)"). let id = v.get("layer").and_then(Value::as_u64).and_then(|id| u32::try_from(id).ok());