Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions crates/engine/src/cmd/layout/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,11 @@ pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]>
if let Some(r) = region {
gaps.retain(|g, _| layout.element(g.frame).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0)));
}
let mut profiles: ProfileNotes =
rustgis_render::layout::profiles_not_drawn(&layout, &s.project.maps).into_iter().map(|n| (n, 1)).collect();
if let Some(r) = region {
profiles.retain(|n, _| layout.element(n.element).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0)));
}
let ((img, mut unfitted), mut charts) = rustgis_render::layout::drawn_charts(|| {
rustgis_render::layout::unfitted_legends(|| {
crate::cmd::share::saying_shadows(s, "The layout", |s| match region {
Expand All @@ -106,6 +111,9 @@ pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]>
if let Some(note) = rustgis_render::layout::sections_notice(&gaps, 1) {
s.warn(note);
}
for note in rustgis_render::layout::profiles_notice(&profiles, 1) {
s.warn(note);
}
img.encode_png().map_err(|e| e.to_string())
}

Expand Down Expand Up @@ -152,6 +160,9 @@ pub(in crate::cmd) fn chart_notice_lines_in<'a>(

/// The section lines an export doesn't draw, each with the pages it is missing from.
type SectionGaps = BTreeMap<rustgis_render::layout::SectionGap, usize>;
/// What an export's profiles say ([`rustgis_render::layout::profiles_not_drawn`]), each with the
/// pages it is said on.
type ProfileNotes = BTreeMap<rustgis_render::layout::ProfileNote, usize>;

/// What `view_map` draws when it is given a `layout`: the layout's frames' maps and their tiles,
/// as exporting it reads them, rather than the active map's. `None` without a `layout`.
Expand Down Expand Up @@ -211,6 +222,7 @@ pub(in crate::cmd::layout) fn layout_bytes_inner(
let (mut left_out, mut by_corners): (Vec<(usize, u32, String, &'static str)>, Vec<(usize, u32, String)>) = (Vec::new(), Vec::new());
let mut clipped = BTreeMap::new();
let mut gaps = SectionGaps::new();
let mut profiles = ProfileNotes::new();
let render_pages = || -> Result<(Vec<rustgis_render::pdf::Page>, Option<Vec<u8>>), String> {
let mut out = Vec::new();
let mut png = None;
Expand All @@ -236,6 +248,9 @@ pub(in crate::cmd::layout) fn layout_bytes_inner(
for gap in rustgis_render::layout::sections_not_drawn(layout, &s.project.maps) {
*gaps.entry(gap).or_default() += 1;
}
for note in rustgis_render::layout::profiles_not_drawn(layout, &s.project.maps) {
*profiles.entry(note).or_default() += 1;
}
// Each page is kept as vectors (its pictures compressed) as soon as it's drawn, within
// a memory budget.
if pdf {
Expand Down Expand Up @@ -303,6 +318,9 @@ pub(in crate::cmd::layout) fn layout_bytes_inner(
if let Some(note) = rustgis_render::layout::sections_notice(&gaps, pages.len()) {
s.warn(note);
}
for note in rustgis_render::layout::profiles_notice(&profiles, pages.len()) {
s.warn(note);
}
say_unfitted_legends(s, &unfitted);
for note in chart_notice_lines(&saved, &charts) {
s.warn(note);
Expand Down Expand Up @@ -535,6 +553,7 @@ pub(in crate::cmd::layout) fn layout_svg(s: &mut Session, li: usize, dpi: f64) -
let clipped = rustgis_render::layout::clipped_text(layout, &s.project.maps, dpi, &info);
let note = rustgis_render::layout::clipped_text_notice(layout, &clipped);
let gaps = rustgis_render::layout::sections_not_drawn(layout, &s.project.maps).into_iter().map(|g| (g, 1)).collect();
let profiles: ProfileNotes = rustgis_render::layout::profiles_not_drawn(layout, &s.project.maps).into_iter().map(|n| (n, 1)).collect();
let ((drawn, unfitted), charts) = rustgis_render::layout::drawn_charts(|| {
rustgis_render::layout::unfitted_legends(|| rustgis_render::svg::layout_svg(layout, &mut s.project.maps, dpi, &info))
});
Expand All @@ -543,6 +562,9 @@ pub(in crate::cmd::layout) fn layout_svg(s: &mut Session, li: usize, dpi: f64) -
for note in [note, rustgis_render::layout::sections_notice(&gaps, 1)].into_iter().flatten() {
s.warn(note);
}
for note in rustgis_render::layout::profiles_notice(&profiles, 1) {
s.warn(note);
}
say_unfitted_legends(s, &unfitted);
for note in chart_notes {
s.warn(note);
Expand Down
24 changes: 24 additions & 0 deletions crates/engine/src/cmd/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1280,6 +1280,30 @@ fn say_sections_not_drawn(s: &mut Session, pages: &[rustgis_render::report::Page
if let Some(note) = rustgis_render::layout::sections_notice(&gaps, 1) {
s.warn(format!("The report: {note}"));
}
say_profiles_not_drawn(s, pages, n);
}

/// Says what the profiles (#2863 part 2) of the layouts of the first `n` of `pages` say, as
/// [`say_sections_not_drawn`] says their section lines: one notice of a kind, each profile named
/// with its layout.
fn say_profiles_not_drawn(s: &mut Session, pages: &[rustgis_render::report::Page], n: usize) {
let mut seen = Vec::new();
let mut notes = std::collections::BTreeMap::new();
for page in pages.iter().take(n) {
let rustgis_render::report::Page::Layout(li) = page else { continue };
if seen.contains(li) {
continue;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
seen.push(*li);
let Some(layout) = s.project.layouts.get(*li) else { continue };
for mut note in rustgis_render::layout::profiles_not_drawn(layout, &s.project.maps) {
note.layout.clone_from(&layout.name);
notes.insert(note, 1);
}
}
for note in rustgis_render::layout::profiles_notice(&notes, 1) {
s.warn(format!("The report: {note}"));
}
}

/// Runs `f`, and returns its result with the legends it drew under a fit still cut and the charts
Expand Down
66 changes: 66 additions & 0 deletions crates/engine/src/tests/layout_profiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

use crate::{Session, sample};
use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster};
use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value as Data};
use rustgis_geom::Coord;
use rustgis_map::layout::{ElementKind, Profile, ProfileSide};
use serde_json::json;
Expand All @@ -16,6 +17,21 @@ fn put_profile(s: &mut Session, frame: u32, side: ProfileSide) -> u32 {
l.add("Profile", p.rect(at), ElementKind::Profile(p))
}

/// A layout with a frame of the sample's map round (10, 50), a raster "DEM" of one degree's hundred
/// metres of latitude over it, and the frame's id.
fn with_dem() -> (Session, u32) {
let mut s = Session::new(sample::world_project());
let (n, cell) = (400usize, 0.05);
let data = (0..n * n).map(|i| ((60.0 - ((i / n) as f64 + 0.5) * cell) * 100.0) as f32).collect();
let gt = GeoTransform { origin_x: 0.0, origin_y: 60.0, pixel_width: cell, pixel_height: -cell };
let r = Raster::new("dem", n as u32, n as u32, vec![data], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap();
s.map_mut().add_raster("DEM", rustgis_map::RasterLayer::from_path(r, "dem.tif"));
s.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap();
let frame = s.project.layouts[0].first_frame().unwrap();
s.run("layout.update", &json!({"element": frame, "center": [10, 50], "scale": 1e7})).unwrap();
(s, frame)
}

/// A profile's copy stays beside its frame, over the original, and says it took no offset.
#[test]
fn a_profiles_copy_keeps_beside_its_frame_and_says_so() {
Expand Down Expand Up @@ -50,6 +66,56 @@ fn a_box_given_to_a_profile_is_said_not_kept() {
assert!(s.notices_since(mark).is_empty(), "the frame takes its profile along");
}

fn said(s: &Session, mark: u64) -> Vec<String> {
s.notices_since(mark).iter().map(|n| n.text.clone()).collect()
}

/// A profile its page can't draw says so when the page is drawn: beside a tilted frame, one notice
/// naming it and why, from a PNG, a PDF and the picture `view_map` draws alike, and from a report
/// with its layout named.
#[test]
fn a_profile_not_drawn_is_said() {
let (mut s, frame) = with_dem();
s.run("layout.addElement", &json!({"kind": "section", "at": [10, 50], "direction": "vertical"})).unwrap();
s.run("layout.update", &json!({"element": frame, "pitch": 40})).unwrap();
let id = put_profile(&mut s, frame, ProfileSide::Right);
let notes = vec![format!(
"1 profile(s) not drawn: 'Profile' ({id}): its frame is tilted or on the globe, where a line straight on the page isn't a section of the ground"
)];
let drawn: Vec<(&str, Box<dyn Fn(&mut Session)>)> = vec![
("png", Box::new(|s| drop(crate::cmd::layout::layout_bytes(s, 0, false, 48.0, false).unwrap()))),
("pdf", Box::new(|s| drop(crate::cmd::layout::layout_bytes(s, 0, true, 48.0, true).unwrap()))),
("view", Box::new(|s| drop(crate::cmd::layout::layout_png(s, 0, 48.0, None).unwrap()))),
];
let profile_notes = |s: &Session, mark: u64| said(s, mark).into_iter().filter(|n| n.contains("profile(s)")).collect::<Vec<_>>();
for (how, export) in &drawn {
let mark = s.notice_mark();
export(&mut s);
assert_eq!(profile_notes(&s, mark), notes, "{how}");
}
let layout = s.project.layouts[0].name.clone();
let mut shops = Dataset::new("Shops", GeometryType::Point, vec![Field::new("n", FieldType::Double)]);
shops.push(Some(Geometry::Point(Coord::new(10.0, 50.0))), vec![Data::Float(1.0)]);
s.map_mut().add_dataset(shops);
s.run("report.new", &json!({"layer": "Shops", "name": "R"})).unwrap();
s.run("report.existingTemplate", &json!({"report": "R", "layout": layout, "end": true})).unwrap();
let dir = std::env::temp_dir().join(format!("rustgis-2863c-{}-{:?}", std::process::id(), std::thread::current().id()));
std::fs::create_dir_all(&dir).unwrap();
let mark = s.notice_mark();
let exported = s.run("report.export", &json!({"report": "R", "path": dir.join("r.pdf"), "dpi": 36}));
std::fs::remove_dir_all(&dir).ok();
exported.unwrap();
let why = "its frame is tilted or on the globe, where a line straight on the page isn't a section of the ground";
assert_eq!(profile_notes(&s, mark), [format!("The report: 1 profile(s) not drawn: 'Profile' ({id}) in layout '{layout}': {why}")]);
// Flat again, it is drawn, and nothing is said.
s.run("layout.update", &json!({"element": frame, "pitch": 0})).unwrap();
for (how, export) in &drawn {
let mark = s.notice_mark();
export(&mut s);
assert!(profile_notes(&s, mark).is_empty(), "{how}: {:?}", said(&s, mark));
}
}

/// The Mantiqueira of #2863: a vertical section line of a UTM 23S frame through the Pedra da Mina,
/// whose profile `profile.create` gave again within 0.11 m over 1,600 samples of the Copernicus DEM.
/// On a relief of that frame, the profile's samples and `profile.create`'s between the line's ends,
Expand Down
2 changes: 1 addition & 1 deletion crates/render/src/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -696,7 +696,7 @@ fn draw_page(
None => placeholder(&mut pm, r, "Chart", ppp),
}
}
// What it reads is worked out from 2b (`profile_samples`); it is said in 2c and drawn in 2d (#2863).
// Its curve comes in its own step (#2863 part 2d); what it reads is said meanwhile.
ElementKind::Profile(_) => placeholder(&mut pm, r, "Profile", ppp),
ElementKind::Rectangle { fill, outline, width, radius, dash } => {
// Square corners filled as before, so an existing layout draws to the same pixels.
Expand Down
103 changes: 102 additions & 1 deletion crates/render/src/layout/profile.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! A raster's profile beside its map frame (#2863 part 2): its samples along a section line, read
//! at each one's point of the page line through the frame's projection.
//! at each one's point of the page line through the frame's projection, and what keeps one from
//! being drawn.

use rustgis_map::layout::{MAX_PROFILE_SAMPLES, Profile};

Expand Down Expand Up @@ -120,6 +121,106 @@ pub fn profile_samples(layout: &Layout, maps: &[Map], p: &Profile) -> Result<(Pr
Ok((out, section.clone()))
}

/// A profile its layout doesn't draw, or draws from fewer samples than its raster's cells along
/// its section line, or with gaps where the line has no data ([`profile_samples`]).
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct ProfileNote {
/// The layout it is in, named where several are said together (a report's); empty otherwise.
pub layout: String,
pub element: u32,
pub name: String,
/// Why it isn't drawn; `None` for one drawn.
pub why: Option<String>,
/// Drawn, the cells along its section line when they are more than its samples; 0 otherwise.
pub cells: usize,
/// Drawn, its samples without a value (off its raster or over no data), and all of them.
pub blank: (usize, usize),
}

/// What `layout`'s visible profiles say as the page is now: those not drawn, and why, those read
/// at fewer samples than their raster's cells along the line, and those drawn with gaps.
pub fn profiles_not_drawn(layout: &Layout, maps: &[Map]) -> Vec<ProfileNote> {
let profiles = layout.elements.iter().filter(|e| e.visible).filter_map(|e| match &e.kind {
ElementKind::Profile(p) => Some((e, p)),
_ => None,
});
profiles
.filter_map(|(e, p)| {
let (why, cells, blank) = match profile_samples(layout, maps, p) {
Err(why) => (Some(why), 0, (0, 0)),
Ok((s, _)) => {
let blank = (s.values.iter().filter(|v| v.is_none()).count(), s.values.len());
if s.cells.is_none() && blank.0 == 0 {
return None;
}
(None, s.cells.unwrap_or(0), blank)
}
};
Some(ProfileNote { layout: String::new(), element: e.id, name: e.name.clone(), why, cells, blank })
})
.collect()
}

/// What an export of `pages` pages says of its profiles ([`profiles_not_drawn`]), each with the
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
/// pages it is on: one notice for those not drawn, each named with its reason, one for those read
/// at fewer samples than cells, and one for those drawn with gaps, each with the pages it is on
/// over several; the profiles counted, the first ten named.
pub fn profiles_notice(notes: &BTreeMap<ProfileNote, usize>, pages: usize) -> Vec<String> {
let on = |n: usize| if pages > 1 { format!(" on {n} of {pages} pages") } else { String::new() };
let list = |items: Vec<String>| {
let more = items.len().saturating_sub(10);
let mut named = items.into_iter().take(10).collect::<Vec<_>>().join("; ");
if more > 0 {
named.push_str(&format!("; and {more} more"));
}
named
};
// A profile can be missing for one reason on some pages and another on others: one profile still.
let mut missing: BTreeMap<(&str, u32, &str), Vec<String>> = BTreeMap::new();
// The most a page says of each, and the pages saying it.
let mut thinned: BTreeMap<(&str, u32, &str), (usize, usize)> = BTreeMap::new();
let mut gaps: BTreeMap<(&str, u32, &str), ((usize, usize), usize)> = BTreeMap::new();
for (n, count) in notes {
let key = (n.layout.as_str(), n.element, n.name.as_str());
match &n.why {
Some(why) => missing.entry(key).or_default().push(format!("{}: {why}", on(*count))),
None => {
if n.cells > 0 {
let (most, on) = thinned.entry(key).or_default();
(*most, *on) = ((*most).max(n.cells), *on + count);
}
if n.blank.0 > 0 {
let (most, on) = gaps.entry(key).or_default();
(*most, *on) = ((*most).max(n.blank), *on + count);
}
}
}
}
let named = |(layout, id, name): (&str, u32, &str)| {
if layout.is_empty() { format!("'{name}' ({id})") } else { format!("'{name}' ({id}) in layout '{layout}'") }
};
let mut out = Vec::new();
if !missing.is_empty() {
let count = missing.len();
let items = missing.into_iter().map(|(key, why)| format!("{}{}", named(key), why.join(","))).collect();
out.push(format!("{count} profile(s) not drawn: {}", list(items)));
}
if !thinned.is_empty() {
let count = thinned.len();
let items = thinned.into_iter().map(|(key, (cells, n))| format!("{}, across {cells} cells{}", named(key), on(n))).collect();
out.push(format!(
"{count} profile(s) read at {MAX_PROFILE_SAMPLES} samples, fewer than their raster's cells along the line: {}",
list(items)
));
}
if !gaps.is_empty() {
let count = gaps.len();
let items = gaps.into_iter().map(|(key, ((blank, all), n))| format!("{}, {blank} of {all} samples{}", named(key), on(n))).collect();
out.push(format!("{count} profile(s) drawn with gaps, where the line has no data: {}", list(items)));
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
}
out
}

#[cfg(test)]
#[path = "profile_tests.rs"]
mod tests;
Loading
Loading