From b6944824a8b3c3e0647117bfcd7e13a709fb78d9 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 21 Nov 2026 09:31:45 -0600 Subject: [PATCH 1/6] perf(render): take a layer's label candidates from the last frame of the same view (#1057) A layer drawn again in a screen frame that looks as it did, or differs only in transparency, takes the label candidates it gave the kept frame instead of working them out again. Placement still runs over all layers. A view keeps at most 20,000 candidates for its layers together. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/frame_cache.rs | 132 ++++++++++++++++++++++++++++--- crates/render/src/lib.rs | 28 ++++++- 2 files changed, 149 insertions(+), 11 deletions(-) diff --git a/crates/render/src/frame_cache.rs b/crates/render/src/frame_cache.rs index 41b3a839b8..d701f8e614 100644 --- a/crates/render/src/frame_cache.rs +++ b/crates/render/src/frame_cache.rs @@ -23,6 +23,11 @@ //! labels turned square to another layer's lines, terrain water). A layer read in place from its //! source or a raster has no look ([`LayerLook::of`]): it counts as changed in every frame, so a //! picture is kept only from below it. +//! +//! Each layer's label candidates are kept beside the picture too ([`LayerLabels`]): a layer drawn +//! again over a restored picture, or in a frame of the same view drawn whole, that looks the same +//! or only its transparency changed takes the candidates it gave last time instead of working them +//! out again. Labels are still placed over all layers, since one layer's labels can hide another's. use rustgis_data::query::Env; use rustgis_map::look::{Change, LayerLook, MapLook}; @@ -42,6 +47,13 @@ const MAX_PIXELS: u64 = 2 * 3840 * 2160; /// the kept pictures stay within about 86 MB. const SPRITE_PIXELS: u64 = crate::MAX_SPRITES as u64 * (2 * crate::MAX_SPRITE_REACH as u64 + 1).pow(2); +/// The most label candidates a view keeps for its layers together, as many as a frame's labels are +/// placed from once it compacts them (`compact_label_candidates`): about 9.3 MB a view +/// (`size_of::()` is 464 bytes), plus what they hold beside (text, glyphs curved along a +/// line, places to try). A layer whose candidates would go past it works them out in every frame. +/// A frame copies no more than this either, its layers bottom first. +pub(crate) const MAX_CANDIDATES: usize = 20_000; + /// Pictures kept, one per view drawn (a map and its draft, two maps on screen). const KEPT: usize = 2; @@ -130,10 +142,16 @@ pub(crate) struct Alone { /// (which labels take their priority from); `None` for one with no look. pub(crate) type Looks = Vec<((u32, usize), Option)>; +/// The label candidates each layer gave a frame, by the layer's id and place in the map's list, +/// before any were placed. +pub(crate) type LayerLabels = Vec<((u32, usize), Vec)>; + /// A kept picture and what it was drawn from. struct Kept { frame: Frame, looks: Looks, + /// The candidates of the layers that look as in `looks`. + labels: LayerLabels, /// The place in the drawing order the checkpoint stands before. at: usize, checkpoint: Checkpoint, @@ -178,6 +196,8 @@ thread_local! { static STARTED: std::cell::Cell> = const { std::cell::Cell::new(None) }; /// Whether the last frame planned had a layer alone to composite. static RECOMBINED: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// The layers whose label candidates frames took from a kept frame. + static REUSED: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } #[cfg(test)] @@ -199,10 +219,39 @@ pub(crate) struct Plan { pub recombine: Option, /// The place in the drawing order of the layer to keep alone, when it is drawn so. pub alone_at: Option, + /// The candidates of the layers that look the same or differ only in transparency, which + /// labels don't take: each is the same as working them out again in this frame. + labels: LayerLabels, frame: Frame, looks: Looks, } +impl Plan { + /// The label candidates the layer at place `place` in the map's list gave the frame kept, when + /// they still stand. [`keep`] keeps them again for the frames after this one. + pub(crate) fn take_labels(&mut self, id: u32, place: usize) -> Option> { + let i = self.labels.iter().position(|(k, _)| *k == (id, place))?; + #[cfg(test)] + REUSED.with_borrow_mut(|r| r.push(id)); + Some(self.labels.swap_remove(i).1) + } +} + +/// The candidates in `labels` of the layers that look in `now` as in `then`, or differ only in +/// their transparency. +fn standing_labels(labels: LayerLabels, then: &Looks, now: &Looks) -> LayerLabels { + fn look(looks: &Looks, key: (u32, usize)) -> Option<&LayerLook> { + looks.iter().find(|(k, _)| *k == key).and_then(|(_, l)| l.as_ref()) + } + labels + .into_iter() + .filter(|(key, _)| match (look(then, *key), look(now, *key)) { + (Some(a), Some(b)) => matches!(a.change(b), Change::Same | Change::Transparency), + _ => false, + }) + .collect() +} + /// The first place in the drawing order where `now` doesn't look as `then` did. fn first_change(then: &Looks, now: &Looks) -> usize { then.iter() @@ -246,13 +295,15 @@ pub(crate) fn plan(frame: Frame, looks: Looks, pixels: u64) -> Plan { STARTED.set(Some(plan.start)); #[cfg(test)] RECOMBINED.set(plan.recombine.is_some()); + #[cfg(test)] + REUSED.take(); plan } /// [`plan`]. fn plan_with(frame: Frame, looks: Looks, pixels: u64) -> Plan { if pixels.saturating_mul(KEPT as u64) > MAX_PIXELS { - return Plan { start: 0, restored: None, capture_at: None, recombine: None, alone_at: None, frame, looks }; + return Plan { start: 0, restored: None, capture_at: None, recombine: None, alone_at: None, labels: Vec::new(), frame, looks }; } // A picture over tile layers lasts until a tile that failed in it may be asked for again: a // server that gave no time to come back is asked by the next draw after a minute. @@ -265,36 +316,50 @@ fn plan_with(frame: Frame, looks: Looks, pixels: u64) -> Plan { // Nothing to start from: keep what lies under the first layer (the basemap, the tile // layers below every layer), or the frame under its first changed layer next time. let alone_at = alone_at(&looks, 0, pixels); - return Plan { start: 0, restored: None, capture_at: Some(0), recombine: None, alone_at, frame, looks }; + return Plan { start: 0, restored: None, capture_at: Some(0), recombine: None, alone_at, labels: Vec::new(), frame, looks }; }; let changed = first_change(&k.looks, &looks); + let labels = standing_labels(k.labels, &k.looks, &looks); if k.at <= changed { let capture_at = (changed > k.at && changed < looks.len()).then_some(changed); let recombine = k.alone.filter(|_| matches!(change_at(&k.looks, &looks, k.at), Change::Same | Change::Transparency)); let alone_at = alone_at(&looks, capture_at.unwrap_or(k.at), pixels); - Plan { start: k.at, restored: Some(k.checkpoint), capture_at, recombine, alone_at, frame, looks } + Plan { start: k.at, restored: Some(k.checkpoint), capture_at, recombine, alone_at, labels, frame, looks } } else { let alone_at = alone_at(&looks, changed, pixels); - Plan { start: 0, restored: None, capture_at: Some(changed), recombine: None, alone_at, frame, looks } + Plan { start: 0, restored: None, capture_at: Some(changed), recombine: None, alone_at, labels, frame, looks } } } /// Keeps the picture a frame drawn by `plan` ends with: `captured` when it took one, else the one /// it started from, with the layer over it alone: `alone` when the frame drew it so, else the one -/// it was composited from. Called only for a frame drawn to the end. -pub(crate) fn keep(plan: Plan, captured: Option<(usize, Checkpoint)>, alone: Option<(usize, Alone)>) { - let Plan { start, restored, recombine, frame, looks, .. } = plan; +/// it was composited from. `drawn` holds the label candidates of the layers the frame worked them +/// out for or took ([`Plan::take_labels`]), the others' are kept as they were. Called only for a +/// frame drawn to the end. +pub(crate) fn keep(plan: Plan, captured: Option<(usize, Checkpoint)>, alone: Option<(usize, Alone)>, drawn: LayerLabels) { + let Plan { start, restored, recombine, labels: standing, frame, looks, .. } = plan; let Some((at, checkpoint)) = captured.or(restored.map(|c| (start, c))) else { return }; let alone = match alone { Some((a, alone)) if a == at => Some(alone), _ => recombine.filter(|_| at == start), }; + // Bottom first in drawing order, as many as fit. + let mut given: LayerLabels = drawn.into_iter().chain(standing).collect(); + let mut labels: LayerLabels = Vec::new(); + let mut count = 0; + for (key, _) in &looks { + if let Some(i) = given.iter().position(|(k, c)| k == key && count + c.len() <= MAX_CANDIDATES) { + let entry = given.swap_remove(i); + count += entry.1.len(); + labels.push(entry); + } + } with_pictures(|kept| { kept.retain(|k| !k.frame.same(&frame)); if kept.len() >= KEPT { kept.remove(0); } - kept.push(Kept { frame, looks, at, checkpoint, alone }); + kept.push(Kept { frame, looks, labels, at, checkpoint, alone }); // Within the budget: the older views' layers alone go first, then the older views, then // this view's layer alone. while kept.iter().map(Kept::pixels).sum::() > MAX_PIXELS + KEPT as u64 * SPRITE_PIXELS { @@ -361,11 +426,12 @@ mod tests { /// must be the same frame; gives where the first started drawing its layers. fn draw(map: &mut Map, view: &View) -> Option { let kept = render(map, view).expect("drawn"); - let (started, recombined) = (STARTED.get(), RECOMBINED.get()); + let (started, recombined, reused) = (STARTED.get(), RECOMBINED.get(), REUSED.take()); let pictures = PICTURES.take(); let fresh = render(map, view).expect("drawn"); PICTURES.set(pictures); RECOMBINED.set(recombined); + REUSED.set(reused); assert!(kept.pixmap.data() == fresh.pixmap.data(), "a frame from a kept picture differs from one drawn whole"); let texts = |r: &crate::Rendered| r.labels.iter().map(|l| (l.text.clone(), l.x.to_bits(), l.y.to_bits())).collect::>(); assert_eq!(texts(&kept), texts(&fresh), "its labels differ"); @@ -405,6 +471,54 @@ mod tests { assert_eq!(draw(&mut map, &moved), Some(0)); } + #[test] + fn a_layer_drawn_again_takes_its_label_candidates_while_it_looks_the_same() { + let (mut map, view, below, above) = map(); + if let Some(l) = map.layer_mut(above) { + l.labels.enabled = true; + l.labels.default.field = "name".into(); + } + let restyle = |map: &mut Map, id: u32, rgb: (u8, u8, u8)| { + if let Some(l) = map.layer_mut(id) { + l.renderer = Renderer::Single(rustgis_map::Symbol { fill: Rgba::rgb(rgb.0, rgb.1, rgb.2), ..l.symbol(0) }); + } + }; + let reused = |map: &mut Map| { + draw(map, &view); + REUSED.take() + }; + assert_eq!(reused(&mut map), Vec::::new(), "the first frame works them all out"); + // The layer below restyled: the one above is drawn again over it, with its candidates. + restyle(&mut map, below, (10, 10, 120)); + assert_eq!(reused(&mut map), vec![above]); + // The layer above restyled: drawn from the picture under it, its candidates worked out. + restyle(&mut map, above, (200, 30, 30)); + assert_eq!(reused(&mut map), vec![below], "the frame was drawn whole, the layer below again"); + restyle(&mut map, above, (30, 200, 30)); + assert_eq!(reused(&mut map), Vec::::new()); + // Those of the layer below, not drawn in that frame, were kept from the one before. + restyle(&mut map, below, (120, 10, 10)); + assert_eq!(reused(&mut map), vec![above]); + // Only its transparency changed: still its candidates, which take no transparency. + if let Some(l) = map.layer_mut(above) { + l.transparency = 40.0; + } + restyle(&mut map, below, (10, 120, 10)); + assert_eq!(reused(&mut map), vec![above]); + // Labelled by another field, or a moved view: worked out again. + if let Some(l) = map.layer_mut(above) { + l.labels.default.field = "missing".into(); + } + restyle(&mut map, below, (10, 10, 10)); + assert_eq!(reused(&mut map), Vec::::new()); + restyle(&mut map, below, (20, 20, 20)); + assert_eq!(reused(&mut map), vec![above]); + let mut moved = view; + moved.camera.center.x += 50.0; + draw(&mut map, &moved); + assert_eq!(REUSED.take(), Vec::::new(), "another view's"); + } + #[test] fn a_see_through_layer_is_composited_again_at_its_new_transparency() { let (mut map, view, _, above) = map(); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 47b68864eb..0ec311e9e6 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4293,6 +4293,8 @@ fn render_frame( let alone_at = cached.as_ref().and_then(|p| p.alone_at); let mut drawn_alone: Option<(usize, Pixmap)> = None; let mut captured_alone: Option<(usize, frame_cache::Alone)> = None; + // The label candidates each layer drawn gives the frame, kept for the next (see `frame_cache`). + let mut layer_labels: frame_cache::LayerLabels = Vec::new(); // Kept only as drawn in full so far: tiles still to come, to draw, or to ask for again after // a failure are drawn again rather than restored as they stood. let complete = |t: &tiles::TileOutput| { @@ -4849,6 +4851,14 @@ fn render_frame( // An extruded layer's diagrams, drawn on a sheet of their own until the spool has drawn its // polygons. let mut extruded_charts: Option = None; + // Its label candidates, kept for a frame keeping pictures (a layer read from its source has + // no look to tell they still stand): taken from a kept frame of the same view when the layer + // looks as it did then, else worked out and kept. + let (keeps_labels, lid) = (cached.is_some() && layer.source.is_none(), layer.id); + let mut taken = cached.as_mut().filter(|_| keeps_labels).and_then(|p| p.take_labels(lid, li)); + // Copied only while the frame's copies stay within what a view keeps. + let room = frame_cache::MAX_CANDIDATES.saturating_sub(layer_labels.iter().map(|(_, c)| c.len()).sum()); + let mut gave_labels: Option> = None; let mut draw_chunk = |layer: &mut rustgis_map::Layer| -> rustgis_data::Result<()> { // A stopped frame draws no more of a layer or a streamed chunk (see `cancel`). if cancel::requested() { @@ -5296,6 +5306,15 @@ fn render_frame( } } } + // The candidates it gave a kept frame of the same view, looking as it does now: the same + // as working them out again. (Not compacted: only a layer read from its source is, and + // that keeps none.) + if let Some(c) = taken.take() { + gave_labels = Some(c.clone()); + label_candidates.extend(c); + return Ok(()); + } + let first_label = label_candidates.len(); // Each label class labels every feature its clause takes, as in ArcGIS Pro (#732), when // shown, in range and on a field the layer has (#618) or by a text expression. Its // expressions are compiled once for the drawing. @@ -5329,7 +5348,6 @@ fn render_frame( let find = if full_res_rasters { families::find } else { families::find_ready }; let class_fonts: Vec> = labels.in_order().map(|c| c.font.as_deref().and_then(find)).collect(); let classes = rustgis_map::LabelMatcher::with_env(labels, ds_ptr, label_env.clone()); - let lid = layer.id; // Whether a class labels lines along them: those take the stretch of a line in // view, wherever its label point is. let along_line = |placement: LabelPlacement, g: &Geometry| placement.along_line() && matches!(g, Geometry::Line(_)); @@ -5844,6 +5862,9 @@ fn render_frame( } } } + if keeps_labels && label_candidates.len().saturating_sub(first_label) <= room { + gave_labels = label_candidates.get(first_label..).map(<[Candidate]>::to_vec); + } if complete_source && matches!(labels_to, Labels::Own | Labels::Turned(_)) { compact_label_candidates(&mut label_candidates); } @@ -5897,6 +5918,9 @@ fn render_frame( } return None; } + if let Some(c) = gave_labels { + layer_labels.push(((lid, li), c)); + } if let (Some(spool), Some(x)) = (&mut extrusions, &layer.extrusion) && let Err(e) = spool.draw(if direct { &mut pm } else { &mut target }, ctx, x) { @@ -5948,7 +5972,7 @@ fn render_frame( draw_tiles!(Some(id)); } if let Some(plan) = cached.take() { - frame_cache::keep(plan, captured, captured_alone); + frame_cache::keep(plan, captured, captured_alone, layer_labels); } // A band of a tilted view: the sun's glint on the terrain's water, over the water's own fill. if matches!(labels_to, Labels::Tilted(..) | Labels::Shared) From d309733fab62ba596da6633f3a3dc4c7855f7b2a Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 21 Nov 2026 11:34:31 -0600 Subject: [PATCH 2/6] fix(render): a reused layer's candidates count against the frame's copy budget too Co-Authored-By: Claude Opus 5.5 --- crates/render/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 0ec311e9e6..42c6b4e67c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5310,7 +5310,7 @@ fn render_frame( // as working them out again. (Not compacted: only a layer read from its source is, and // that keeps none.) if let Some(c) = taken.take() { - gave_labels = Some(c.clone()); + gave_labels = (c.len() <= room).then(|| c.clone()); label_candidates.extend(c); return Ok(()); } From d9d4d16e2806a1ce898a24923412394f333c0919 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 21 Nov 2026 12:16:13 -0600 Subject: [PATCH 3/6] fix(render): keep label candidates from a view's second frame, within a budget of bytes A view's first frame keeps no label candidates: a frame of another view, as while panning, has no use for them, so a pan copies none. The budget counts what candidates hold beside them (text, glyphs, places to try), 16 MiB a view, rather than how many there are. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/frame_cache.rs | 60 +++++++++++++++++++++++-------- crates/render/src/label_places.rs | 5 +++ crates/render/src/lib.rs | 30 +++++++++++++--- 3 files changed, 75 insertions(+), 20 deletions(-) diff --git a/crates/render/src/frame_cache.rs b/crates/render/src/frame_cache.rs index d701f8e614..4a5eb48beb 100644 --- a/crates/render/src/frame_cache.rs +++ b/crates/render/src/frame_cache.rs @@ -47,12 +47,12 @@ const MAX_PIXELS: u64 = 2 * 3840 * 2160; /// the kept pictures stay within about 86 MB. const SPRITE_PIXELS: u64 = crate::MAX_SPRITES as u64 * (2 * crate::MAX_SPRITE_REACH as u64 + 1).pow(2); -/// The most label candidates a view keeps for its layers together, as many as a frame's labels are -/// placed from once it compacts them (`compact_label_candidates`): about 9.3 MB a view -/// (`size_of::()` is 464 bytes), plus what they hold beside (text, glyphs curved along a -/// line, places to try). A layer whose candidates would go past it works them out in every frame. -/// A frame copies no more than this either, its layers bottom first. -pub(crate) const MAX_CANDIDATES: usize = 20_000; +/// The most bytes of label candidates a view keeps for its layers together, by +/// [`Candidate::bytes`], what they hold beside them included (text, glyphs curved along a line, +/// places to try): about 20,000 point labels, each of 464 bytes and the places around it. A +/// layer whose candidates would go past it works them out in every frame. A frame copies no more +/// than this either, its layers bottom first. +pub(crate) const MAX_LABEL_BYTES: usize = 16 << 20; /// Pictures kept, one per view drawn (a map and its draft, two maps on screen). const KEPT: usize = 2; @@ -219,6 +219,9 @@ pub(crate) struct Plan { pub recombine: Option, /// The place in the drawing order of the layer to keep alone, when it is drawn so. pub alone_at: Option, + /// Whether a frame of the same view was kept: only then does it keep its label candidates, + /// which a frame of another view, as while panning, has no use for. + pub same_view: bool, /// The candidates of the layers that look the same or differ only in transparency, which /// labels don't take: each is the same as working them out again in this frame. labels: LayerLabels, @@ -303,7 +306,17 @@ pub(crate) fn plan(frame: Frame, looks: Looks, pixels: u64) -> Plan { /// [`plan`]. fn plan_with(frame: Frame, looks: Looks, pixels: u64) -> Plan { if pixels.saturating_mul(KEPT as u64) > MAX_PIXELS { - return Plan { start: 0, restored: None, capture_at: None, recombine: None, alone_at: None, labels: Vec::new(), frame, looks }; + return Plan { + start: 0, + restored: None, + capture_at: None, + recombine: None, + alone_at: None, + same_view: false, + labels: Vec::new(), + frame, + looks, + }; } // A picture over tile layers lasts until a tile that failed in it may be asked for again: a // server that gave no time to come back is asked by the next draw after a minute. @@ -316,7 +329,17 @@ fn plan_with(frame: Frame, looks: Looks, pixels: u64) -> Plan { // Nothing to start from: keep what lies under the first layer (the basemap, the tile // layers below every layer), or the frame under its first changed layer next time. let alone_at = alone_at(&looks, 0, pixels); - return Plan { start: 0, restored: None, capture_at: Some(0), recombine: None, alone_at, labels: Vec::new(), frame, looks }; + return Plan { + start: 0, + restored: None, + capture_at: Some(0), + recombine: None, + alone_at, + same_view: false, + labels: Vec::new(), + frame, + looks, + }; }; let changed = first_change(&k.looks, &looks); let labels = standing_labels(k.labels, &k.looks, &looks); @@ -324,10 +347,10 @@ fn plan_with(frame: Frame, looks: Looks, pixels: u64) -> Plan { let capture_at = (changed > k.at && changed < looks.len()).then_some(changed); let recombine = k.alone.filter(|_| matches!(change_at(&k.looks, &looks, k.at), Change::Same | Change::Transparency)); let alone_at = alone_at(&looks, capture_at.unwrap_or(k.at), pixels); - Plan { start: k.at, restored: Some(k.checkpoint), capture_at, recombine, alone_at, labels, frame, looks } + Plan { start: k.at, restored: Some(k.checkpoint), capture_at, recombine, alone_at, same_view: true, labels, frame, looks } } else { let alone_at = alone_at(&looks, changed, pixels); - Plan { start: 0, restored: None, capture_at: Some(changed), recombine: None, alone_at, labels, frame, looks } + Plan { start: 0, restored: None, capture_at: Some(changed), recombine: None, alone_at, same_view: true, labels, frame, looks } } } @@ -346,12 +369,14 @@ pub(crate) fn keep(plan: Plan, captured: Option<(usize, Checkpoint)>, alone: Opt // Bottom first in drawing order, as many as fit. let mut given: LayerLabels = drawn.into_iter().chain(standing).collect(); let mut labels: LayerLabels = Vec::new(); - let mut count = 0; + let mut bytes = 0; for (key, _) in &looks { - if let Some(i) = given.iter().position(|(k, c)| k == key && count + c.len() <= MAX_CANDIDATES) { - let entry = given.swap_remove(i); - count += entry.1.len(); - labels.push(entry); + if let Some((i, b)) = given.iter().enumerate().find_map(|(i, (k, c))| { + let b = Candidate::bytes(c); + (k == key && bytes + b <= MAX_LABEL_BYTES).then_some((i, b)) + }) { + bytes += b; + labels.push(given.swap_remove(i)); } } with_pictures(|kept| { @@ -488,6 +513,11 @@ mod tests { REUSED.take() }; assert_eq!(reused(&mut map), Vec::::new(), "the first frame works them all out"); + // A view's first frame keeps none (another view's, as while panning, would have no use for + // them); its second keeps them. + assert!(PICTURES.with_borrow(|k| k.iter().all(|k| k.labels.is_empty()))); + assert_eq!(reused(&mut map), Vec::::new()); + assert!(PICTURES.with_borrow(|k| k.iter().any(|k| !k.labels.is_empty()))); // The layer below restyled: the one above is drawn again over it, with its candidates. restyle(&mut map, below, (10, 10, 120)); assert_eq!(reused(&mut map), vec![above]); diff --git a/crates/render/src/label_places.rs b/crates/render/src/label_places.rs index e1e67a9498..3d5e3636b6 100644 --- a/crates/render/src/label_places.rs +++ b/crates/render/src/label_places.rs @@ -39,6 +39,11 @@ impl std::fmt::Debug for Curves { } impl Curves { + /// About how many bytes its positions and changes take (its spec is shared), for a budget. + pub fn bytes(&self) -> usize { + self.positions.len() * size_of::() + self.changes.len() * size_of::() + } + pub fn new(spec: Arc, positions: Vec, locked: Option) -> Self { Self { spec, positions, locked, changes: Vec::new() } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 42c6b4e67c..31f4d6a6f0 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2478,6 +2478,26 @@ struct Candidate { row: usize, } +impl Candidate { + /// About how many bytes `candidates` take, with what they hold beside them (their text, glyphs, + /// places and positions to try), for a budget (`frame_cache::MAX_LABEL_BYTES`). + fn bytes(candidates: &[Candidate]) -> usize { + let glyphs = |g: &[LabelGlyph]| g.iter().map(|g| size_of::() + g.text.len()).sum::(); + candidates + .iter() + .map(|c| { + let line = c.line.as_ref().map_or(0, |l| l.anchors.len() * size_of::>() + Candidate::bytes(&l.fallbacks)); + size_of::() + + c.label.text.len() + + glyphs(&c.label.glyphs) + + c.alternatives.iter().map(|a| size_of::() + glyphs(&a.glyphs)).sum::() + + c.curves.as_ref().map_or(0, label_places::Curves::bytes) + + line + }) + .sum() + } +} + /// Alternatives from one line stretch; band siblings retain one top-level candidate slot. #[derive(Clone, Debug, Default)] struct LinePlaces { @@ -4854,10 +4874,10 @@ fn render_frame( // Its label candidates, kept for a frame keeping pictures (a layer read from its source has // no look to tell they still stand): taken from a kept frame of the same view when the layer // looks as it did then, else worked out and kept. - let (keeps_labels, lid) = (cached.is_some() && layer.source.is_none(), layer.id); + let (keeps_labels, lid) = (cached.as_ref().is_some_and(|p| p.same_view) && layer.source.is_none(), layer.id); let mut taken = cached.as_mut().filter(|_| keeps_labels).and_then(|p| p.take_labels(lid, li)); // Copied only while the frame's copies stay within what a view keeps. - let room = frame_cache::MAX_CANDIDATES.saturating_sub(layer_labels.iter().map(|(_, c)| c.len()).sum()); + let room = frame_cache::MAX_LABEL_BYTES.saturating_sub(layer_labels.iter().map(|(_, c)| Candidate::bytes(c)).sum()); let mut gave_labels: Option> = None; let mut draw_chunk = |layer: &mut rustgis_map::Layer| -> rustgis_data::Result<()> { // A stopped frame draws no more of a layer or a streamed chunk (see `cancel`). @@ -5310,7 +5330,7 @@ fn render_frame( // as working them out again. (Not compacted: only a layer read from its source is, and // that keeps none.) if let Some(c) = taken.take() { - gave_labels = (c.len() <= room).then(|| c.clone()); + gave_labels = (Candidate::bytes(&c) <= room).then(|| c.clone()); label_candidates.extend(c); return Ok(()); } @@ -5862,8 +5882,8 @@ fn render_frame( } } } - if keeps_labels && label_candidates.len().saturating_sub(first_label) <= room { - gave_labels = label_candidates.get(first_label..).map(<[Candidate]>::to_vec); + if keeps_labels && let Some(gave) = label_candidates.get(first_label..).filter(|c| Candidate::bytes(c) <= room) { + gave_labels = Some(gave.to_vec()); } if complete_source && matches!(labels_to, Labels::Own | Labels::Turned(_)) { compact_label_candidates(&mut label_candidates); From 73d55b65f48b07dbc3d7aeff9682fbc19bd23a5c Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 21 Nov 2026 12:49:08 -0600 Subject: [PATCH 4/6] perf(render): size each layer's label candidates once a frame Co-Authored-By: Claude Opus 5.5 --- crates/render/src/frame_cache.rs | 6 +++--- crates/render/src/lib.rs | 5 ++++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/render/src/frame_cache.rs b/crates/render/src/frame_cache.rs index 4a5eb48beb..3795c0c2db 100644 --- a/crates/render/src/frame_cache.rs +++ b/crates/render/src/frame_cache.rs @@ -371,9 +371,9 @@ pub(crate) fn keep(plan: Plan, captured: Option<(usize, Checkpoint)>, alone: Opt let mut labels: LayerLabels = Vec::new(); let mut bytes = 0; for (key, _) in &looks { - if let Some((i, b)) = given.iter().enumerate().find_map(|(i, (k, c))| { - let b = Candidate::bytes(c); - (k == key && bytes + b <= MAX_LABEL_BYTES).then_some((i, b)) + if let Some((i, b)) = given.iter().position(|(k, _)| k == key).and_then(|i| { + let b = Candidate::bytes(&given.get(i)?.1); + (bytes + b <= MAX_LABEL_BYTES).then_some((i, b)) }) { bytes += b; labels.push(given.swap_remove(i)); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 31f4d6a6f0..ea758a9e45 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4315,6 +4315,8 @@ fn render_frame( let mut captured_alone: Option<(usize, frame_cache::Alone)> = None; // The label candidates each layer drawn gives the frame, kept for the next (see `frame_cache`). let mut layer_labels: frame_cache::LayerLabels = Vec::new(); + // What they take ([`Candidate::bytes`]). + let mut layer_label_bytes = 0; // Kept only as drawn in full so far: tiles still to come, to draw, or to ask for again after // a failure are drawn again rather than restored as they stood. let complete = |t: &tiles::TileOutput| { @@ -4877,7 +4879,7 @@ fn render_frame( let (keeps_labels, lid) = (cached.as_ref().is_some_and(|p| p.same_view) && layer.source.is_none(), layer.id); let mut taken = cached.as_mut().filter(|_| keeps_labels).and_then(|p| p.take_labels(lid, li)); // Copied only while the frame's copies stay within what a view keeps. - let room = frame_cache::MAX_LABEL_BYTES.saturating_sub(layer_labels.iter().map(|(_, c)| Candidate::bytes(c)).sum()); + let room = frame_cache::MAX_LABEL_BYTES.saturating_sub(layer_label_bytes); let mut gave_labels: Option> = None; let mut draw_chunk = |layer: &mut rustgis_map::Layer| -> rustgis_data::Result<()> { // A stopped frame draws no more of a layer or a streamed chunk (see `cancel`). @@ -5939,6 +5941,7 @@ fn render_frame( return None; } if let Some(c) = gave_labels { + layer_label_bytes += Candidate::bytes(&c); layer_labels.push(((lid, li), c)); } if let (Some(spool), Some(x)) = (&mut extrusions, &layer.extrusion) From 7de1f92fb8ce292847a4052860fd772b920b1acc Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 21 Nov 2026 12:51:42 -0600 Subject: [PATCH 5/6] fix(render): curved labels' text and line count in the label budget Co-Authored-By: Claude Opus 5.5 --- crates/render/src/label_places.rs | 8 ++++++-- crates/render/src/line_labels.rs | 6 ++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/render/src/label_places.rs b/crates/render/src/label_places.rs index 3d5e3636b6..5dc7660e69 100644 --- a/crates/render/src/label_places.rs +++ b/crates/render/src/label_places.rs @@ -39,9 +39,13 @@ impl std::fmt::Debug for Curves { } impl Curves { - /// About how many bytes its positions and changes take (its spec is shared), for a budget. + /// About how many bytes its positions, changes and spec take, for a budget: a spec, or the + /// line in it, shared by several candidates counts in each. pub fn bytes(&self) -> usize { - self.positions.len() * size_of::() + self.changes.len() * size_of::() + let spec = &self.spec; + let chars = spec.chars.iter().map(|c| size_of::() + c.len()).sum::(); + let spec = size_of::() + chars + spec.advances.len() * size_of::() + spec.line.bytes(); + self.positions.len() * size_of::() + self.changes.len() * size_of::() + spec } pub fn new(spec: Arc, positions: Vec, locked: Option) -> Self { diff --git a/crates/render/src/line_labels.rs b/crates/render/src/line_labels.rs index f948ef2157..4cb727b2c8 100644 --- a/crates/render/src/line_labels.rs +++ b/crates/render/src/line_labels.rs @@ -235,6 +235,12 @@ pub(super) struct Line { } impl Line { + /// About how many bytes its paths take, for a budget. + pub(super) fn bytes(&self) -> usize { + let path = |p: &Path| p.pts.len() * size_of::<(f32, f32)>() + p.along.len() * size_of::(); + size_of::() + path(&self.fwd) + path(&self.rev) + } + /// `None` for a line of fewer than two distinct points. pub(super) fn new(line: &[(f32, f32)]) -> Option { Some(Line { fwd: Path::new(line, false)?, rev: Path::new(line, true)? }) From e8b0e716f7eed4371b62421cc5a82ca4106ee117 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 21 Nov 2026 13:28:00 -0600 Subject: [PATCH 6/6] fix(render): a curved label's line counts what it holds room for Co-Authored-By: Claude Opus 5.5 --- crates/render/src/line_labels.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/render/src/line_labels.rs b/crates/render/src/line_labels.rs index 4cb727b2c8..e171beeca0 100644 --- a/crates/render/src/line_labels.rs +++ b/crates/render/src/line_labels.rs @@ -235,9 +235,10 @@ pub(super) struct Line { } impl Line { - /// About how many bytes its paths take, for a budget. + /// About how many bytes its paths take, for a budget: what they hold room for, since a candidate + /// kept shares the line rather than copying it. pub(super) fn bytes(&self) -> usize { - let path = |p: &Path| p.pts.len() * size_of::<(f32, f32)>() + p.along.len() * size_of::(); + let path = |p: &Path| p.pts.capacity() * size_of::<(f32, f32)>() + p.along.capacity() * size_of::(); size_of::() + path(&self.fwd) + path(&self.rev) }