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
162 changes: 153 additions & 9 deletions crates/render/src/frame_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
//!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Memory: the cap counts top-level candidates, not what they hold.

MAX_CANDIDATES counts Vec<Candidate> entries. Each Candidate can carry more than its 464 bytes: line: Option<LinePlaces> holds fallbacks: Vec<Candidate> (other camera bands, each a full candidate), and alternatives, curves and label.text are heap-owned. The doc's "about 9.3 MB a view" is therefore only the top-level struct size, and the PR body's "plus their text, glyphs and alternative places" is not quantified. Nested fallbacks are not counted toward the 20,000 at all.

Suggestion: weight each candidate by 1 + line fallbacks + alternatives (recursively), or count fallbacks in the cap. Also give a measured figure for a layer of curved or line labels with long names, since the AGENTS.md rule asks for the layer multiple to be measured.

Confidence: medium (about 50%). I checked the struct definitions but did not measure heap use.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d9d4d16: the budget is now 16 MiB of candidates a view by Candidate::bytes, which counts text, label and alternative glyphs, curve positions, line anchors and fallbacks, not a count of top-level candidates. Line fallbacks are only filled when a tilted view merges its bands, and tilted views keep no pictures, so they are empty in a kept frame. The PR body's memory section now gives 16 MiB a view, 32 MiB for the two kept, under 0.7% of the 448k-row parcel layer. Full gate green on that commit.

//! 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};
Expand All @@ -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 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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Memory figures in the PR description don't match this cap.

The description says a view keeps "at most 20,000 candidates" (about 9.3 MB), and that a view's cap is "under 0.5%" of the 448k-row, 2.5 GB parcel layer. The code caps by bytes, at 16 MiB (16 << 20). Against 2.5 GB that is about 0.6–0.7% a view, and two views are kept, so about 32 MiB in total. The doc comment has the same arithmetic problem: 20,000 labels of 464 bytes is about 9.3 MB, not 16 MiB, so the places around each label would need about 370 bytes more on average, and the comment doesn't say so.

Please correct the description (cap in bytes, its percentage of the layer, and the two-view total). Please also either state the average bytes per label in this comment or give the measured figure, as AGENTS.md asks for a layer multiple.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PR description was updated with the byte cap after this review began: 16 MiB a view, 32 MiB for the two kept, under 0.7% of the parcel layer. The doc comment gives 16 MiB as about 20,000 point labels with the places around them, which is the same budget, not a second cap.


/// Pictures kept, one per view drawn (a map and its draft, two maps on screen).
const KEPT: usize = 2;

Expand Down Expand Up @@ -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<LayerLook>)>;

/// 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<Candidate>)>;

/// 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,
Expand Down Expand Up @@ -178,6 +196,8 @@ thread_local! {
static STARTED: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
/// Whether the last frame planned had a layer alone to composite.
static RECOMBINED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// The layers whose label candidates frames took from a kept frame.
static REUSED: std::cell::RefCell<Vec<u32>> = const { std::cell::RefCell::new(Vec::new()) };
}

#[cfg(test)]
Expand All @@ -199,10 +219,42 @@ pub(crate) struct Plan {
pub recombine: Option<Alone>,
/// The place in the drawing order of the layer to keep alone, when it is drawn so.
pub alone_at: Option<usize>,
/// 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,
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<Vec<Candidate>> {
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()
Expand Down Expand Up @@ -246,13 +298,25 @@ 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,
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.
Expand All @@ -265,36 +329,62 @@ 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,
same_view: false,
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, 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, frame, looks }
Plan { start: 0, restored: None, capture_at: Some(changed), recombine: None, alone_at, same_view: true, 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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Memory: the kept candidates are stored a second time, and the PR's figure leaves that out.

A kept view already holds a full copy of the frame's candidates in Checkpoint::candidates (lib.rs, label_candidates.clone() at capture) and in Alone::candidates. This change adds Kept::labels on top: for every layer below the capture point, its candidates are in both the checkpoint and labels. The 16 MiB cap bounds only the new labels copy, so a view's real candidate retention is the checkpoint's copy (not budgeted, as before) plus up to 16 MiB, and the PR body's "16 MiB a view, 32 MiB for the two kept" understates it.

Per AGENTS.md ("Size for real data"), please state the multiple of the layer counting the checkpoint and alone copies, and consider storing the candidates once (for example, slicing the checkpoint's vector by layer rather than cloning per layer).

Confidence about 65%: I read the struct and capture code but did not measure heap use.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 16 MiB a view is what this PR adds. The checkpoint's copy of the candidates gathered below the changed layer comes from #2564 and is unchanged here; its PR gave that cost (bounded by what the screen can place). The two hold different things: the checkpoint the frame's candidates up to one layer, this each layer's own.

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 bytes = 0;
for (key, _) in &looks {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance: keep sizes every layer's candidates on every frame, before checking the key.

The find_map closure calls Candidate::bytes(c) on each entry it scans before testing k == key. For each of the looks keys it walks given until it finds a match, so one frame costs roughly layers × candidates size walks, each walking the glyphs and alternatives of every candidate. With 15,000 labels over 10 or more layers this could be several milliseconds per frame, on the frames the PR is meant to speed up. I have not measured it (confidence about 60%).

Suggested fix: test the key first, and size only the matched entry. The keys in given are unique, so position finds the same entry as find_map:

for (key, _) in &looks {
    let Some(i) = given.iter().position(|(k, _)| k == key) else { continue };
    let b = Candidate::bytes(&given[i].1);
    if bytes + b <= MAX_LABEL_BYTES {
        bytes += b;
        labels.push(given.swap_remove(i));
    }
}

Also worth measuring with a 15,000-point layer under 10 or more layers, with the benchmark in the PR body.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 73d55b6: keep finds the layer's entry by key first and sizes only that one. Full gate green on 7de1f92.

if let Some((i, b)) = given.iter().position(|(k, _)| k == key).and_then(|i| {
let b = Candidate::bytes(&given.get(i)?.1);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance (new, about 55% confidence): every retained entry is still re-sized on every frame.

The key-first change means non-matching entries are no longer sized, but each matched entry is still walked by Candidate::bytes in every keep call, and a reused layer is walked again at lib.rs:5335 and lib.rs:5944 in the same frame. Over a settled view with many kept candidates, that is a per-frame walk of the whole retained set, not just the layers drawn fresh.

Suggested direction: store the byte count with each entry when its candidates are produced (for example (key, Vec<Candidate>, usize) in LayerLabels), so keep and the room checks read the stored number. Please measure a frame with about 15,000 labelled points before and after, since this is a per-frame cost on the path the PR speeds up.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass: sizing each kept entry once a frame is a walk over at most the 16 MiB budget, small beside the frame's drawing; caching the size beside the entry would save it.

(bytes + b <= MAX_LABEL_BYTES).then_some((i, b))
}) {
bytes += b;
labels.push(given.swap_remove(i));
}
}
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::<u64>() > MAX_PIXELS + KEPT as u64 * SPRITE_PIXELS {
Expand Down Expand Up @@ -361,11 +451,12 @@ mod tests {
/// must be the same frame; gives where the first started drawing its layers.
fn draw(map: &mut Map, view: &View) -> Option<usize> {
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::<Vec<_>>();
assert_eq!(texts(&kept), texts(&fresh), "its labels differ");
Expand Down Expand Up @@ -405,6 +496,59 @@ 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() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test coverage: the new budget path is untested.

This test covers reuse for point labels at a fixed view. Nothing exercises:

  • the MAX_LABEL_BYTES refusal, where a layer whose candidates would exceed the cap is worked out in every frame and keep drops entries that do not fit;
  • the byte estimates (Candidate::bytes, Curves::bytes, Line::bytes), which decide that refusal;
  • reuse of curved or line-fallback candidates, which carry the extra heap that the estimates count.

A small fixture with a low cap (or a cap test on keep) would pin the "works them out in every frame" behaviour. The byte estimates are quality-level, so this may wait for the release quality pass, but the refusal is new behaviour.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass, as noted on the earlier summary: a test of the budget's refusal and trimming.

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::<u32>::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::<u32>::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]);
// 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::<u32>::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::<u32>::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::<u32>::new(), "another view's");
}

#[test]
fn a_see_through_layer_is_composited_again_at_its_new_transparency() {
let (mut map, view, _, above) = map();
Expand Down
9 changes: 9 additions & 0 deletions crates/render/src/label_places.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,15 @@ impl std::fmt::Debug for Curves {
}

impl Curves {
/// 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 {
let spec = &self.spec;
let chars = spec.chars.iter().map(|c| size_of::<String>() + c.len()).sum::<usize>();
let spec = size_of::<CurveSpec>() + chars + spec.advances.len() * size_of::<f32>() + spec.line.bytes();
self.positions.len() * size_of::<f32>() + self.changes.len() * size_of::<Change>() + spec
}

pub fn new(spec: Arc<CurveSpec>, positions: Vec<f32>, locked: Option<usize>) -> Self {
Self { spec, positions, locked, changes: Vec::new() }
}
Expand Down
51 changes: 49 additions & 2 deletions crates/render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<LabelGlyph>() + g.text.len()).sum::<usize>();
candidates
.iter()
.map(|c| {
let line = c.line.as_ref().map_or(0, |l| l.anchors.len() * size_of::<Option<Coord>>() + Candidate::bytes(&l.fallbacks));
size_of::<Candidate>()
+ c.label.text.len()
+ glyphs(&c.label.glyphs)
+ c.alternatives.iter().map(|a| size_of::<LabelPlace>() + glyphs(&a.glyphs)).sum::<usize>()
+ 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 {
Expand Down Expand Up @@ -4293,6 +4313,10 @@ 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();
// 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| {
Expand Down Expand Up @@ -4849,6 +4873,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<Canvas> = 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.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_label_bytes);
let mut gave_labels: Option<Vec<Candidate>> = 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() {
Expand Down Expand Up @@ -5296,6 +5328,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 = (Candidate::bytes(&c) <= room).then(|| c.clone());
label_candidates.extend(c);
return Ok(());
}
Comment on lines +5334 to +5338

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reused candidates skip the per-frame cap, so a frame can copy about twice MAX_CANDIDATES.

The fresh path only keeps a layer's candidates when they fit in room, the cap left after the layers drawn before it. The reuse path keeps them unconditionally. A reused layer above a freshly drawn one can therefore push layer_labels past 20,000, which contradicts the doc on MAX_CANDIDATES ("A frame copies no more than this either").

Example: a kept frame holds 5k candidates for a bottom layer and 15k for a top layer. The bottom layer is restyled and now gives 15k when drawn. The top layer is reused with its 15k, so layer_labels totals 30k before keep trims it. The output is still correct, since keep trims and a dropped layer is simply worked out again. The cost is a transient memory overshoot, about 18 MB rather than 9 MB, per view.

Suggested fix: keep the reused copy only when it fits room, as the fresh path does.

Suggested change
if let Some(c) = taken.take() {
gave_labels = Some(c.clone());
label_candidates.extend(c);
return Ok(());
}
if let Some(c) = taken.take() {
gave_labels = (c.len() <= room).then(|| c.clone());
label_candidates.extend(c);
return Ok(());
}

Confidence: about 75%. I did not run this. A test would need a reused layer above a fresh one with a combined count past MAX_CANDIDATES. The new test in frame_cache.rs does not reach the cap.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d309733: a reused layer's candidates are copied only within the frame's remaining budget (room), as the fresh path does. frame_cache tests pass; full gate green on that commit.

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.
Expand Down Expand Up @@ -5329,7 +5370,6 @@ fn render_frame(
let find = if full_res_rasters { families::find } else { families::find_ready };
let class_fonts: Vec<Option<u16>> = 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(_));
Expand Down Expand Up @@ -5844,6 +5884,9 @@ fn render_frame(
}
}
}
if keeps_labels && let Some(gave) = label_candidates.get(first_label..).filter(|c| Candidate::bytes(c) <= room) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance (new, about 45% confidence): a layer that changes every frame still pays for a copy it can never reuse.

When a labelled layer is restyled continuously (a slider drag), each frame draws it fresh and gave.to_vec() deep-clones its candidates, including Strings, glyph Vecs and alternatives. Next frame the look differs again, so take_labels misses, and the copy is only replaced. That cost is up to the 16 MiB budget per frame, on top of the work of producing the candidates.

The benchmark restyles an unlabelled polygon layer under a labelled point layer, so it doesn't show this. Please time a drag of a labelled layer's own style (its label size or colour, for example) against the base branch. If the cost shows, consider only copying a layer when the frame's last layer change was not this one, or skipping the copy for a layer whose look changed since the last frame.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass. A frame can't tell whether the next one will restyle this layer again, so it keeps the candidates the drag's last step needs; the copy is bounded by the budget and costs less than working them out, which the benchmark in the description includes.

gave_labels = Some(gave.to_vec());
}
if complete_source && matches!(labels_to, Labels::Own | Labels::Turned(_)) {
compact_label_candidates(&mut label_candidates);
}
Expand Down Expand Up @@ -5897,6 +5940,10 @@ fn render_frame(
}
return None;
}
if let Some(c) = gave_labels {
layer_label_bytes += Candidate::bytes(&c);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance (minor): the same candidates are sized again.

Candidate::bytes(&c) here recomputes the number that the fresh path already computed at line 5887 for the same slice (gave). A layer's candidates are therefore walked twice in a fresh frame, plus once more in frame_cache::keep, and each walk visits glyphs and alternatives. Carrying the byte count with gave_labels (or computing it once in the closure) removes the repeat. Nit-level, about 70% confidence that it is measurable only on dense curved-label layers.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass: sizing a layer's candidates a second time is a walk over at most the 16 MiB budget, small beside working them out.

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)
{
Expand Down Expand Up @@ -5948,7 +5995,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)
Expand Down
Loading
Loading