From 0ec4775ef63ad89f6eccfc84947c2391eceefbf1 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:30:56 -0500 Subject: [PATCH] fix(path-cache): charge each snapshot for the tile buffers it alone keeps alive evict charged snapshot k for path k-1's tiles only, but snapshot k holds every pixel after k paths and shares tile handles with the others. After an older snapshot was evicted, a newer one could retain a whole older generation (full fill, one-tile stroke, full fill, one-tile stroke) and the 256 MiB cap was exceeded. Walk newest to oldest and charge only handles not already held by the live pixels, the edited snapshot or a kept newer snapshot. Also drop the debug_assert from non-test code. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/painting.rs | 2 - crates/engine/src/path_tool.rs | 103 +++++++++++++++++++++++++++------ 2 files changed, 84 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 3c90af84..dd0013b2 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -141,8 +141,6 @@ impl Session { let ts = self.ts(); let size = self.caches.get(ts).map(|c| c.size).unwrap_or((1024, 1024)); let pickup = if quick_mask { None } else { self.pickup_mode(first_uv)? }; - // PathCache reuses a path's tiles only if painting one tile reads no other. - debug_assert!(!(self.painting_paths && pickup.is_some()), "path repaints never pick up"); if pickup.is_some() { // Clone and smudge read the composite: bring it up to date first. self.update(); diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 6629c944..b73dd661 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -16,7 +16,7 @@ use texturecraft_core::{Channel, Effect, EffectKind, LayerId, Mask, MaskBackgrou use texturecraft_geom::OrbitCamera; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_paint::{BrushSettings, Lasso, fill_coverage, spline}; -use texturecraft_texel::{TILE_AREA, TileImage}; +use texturecraft_texel::TileImage; use crate::commands::{CommandSpec, always, bad, boolp, has_layer, u64p}; use crate::session::{StackTarget, Tool}; @@ -83,18 +83,48 @@ pub(crate) struct PathCache { tiles: Vec>, } +/// The identities of the tile buffers `snap` holds, added to `seen`; returns the bytes of those +/// not already there. +fn charge(snap: &Snap, seen: &mut BTreeSet) -> usize { + let mut bytes = 0; + for img in snap.values() { + for ty in 0..img.tiles_y() { + for tx in 0..img.tiles_x() { + if let Some(t) = img.tile_handle(tx, ty) + && seen.insert(Arc::as_ptr(t) as usize) + { + bytes += t.len() * 2; + } + } + } + } + bytes +} + /// Drop the snapshots past `budget` bytes, oldest first, so adding a path and editing recent /// ones stay cheap, but keep snapshot `edited` (below the path being edited, so its next live -/// repaint starts there). Snapshot k holds at most path k-1's tiles in each image; the first -/// (empty) and the last (the live pixels) cost nothing. -fn evict(snaps: &mut [Option], tiles: &[BTreeSet<(u32, u32)>], budget: usize, edited: usize) { +/// repaint starts there). Tiles are shared between snapshots and with the live pixels (the last +/// snapshot) and snapshot k holds every tile as it was after k paths, so each snapshot, newest +/// first, is charged for the tile buffers no live pixels, kept newer snapshot or `edited` already +/// hold: what freeing it would release at most. The first (empty) and the last cost nothing. +fn evict(snaps: &mut [Option], budget: usize, edited: usize) { + let mut seen = BTreeSet::new(); + for k in [snaps.len().saturating_sub(1), edited] { + if let Some(Some(snap)) = snaps.get(k) { + charge(snap, &mut seen); + } + } let mut bytes = 0; for k in (1..snaps.len().saturating_sub(1)).rev().filter(|&k| k != edited) { - if let Some(snap) = &snaps[k] { - bytes += tiles[k - 1].len() * snap.values().map(|i| TILE_AREA * i.comps() * 2).sum::(); - if bytes > budget { - snaps[k] = None; - } + let Some(Some(snap)) = snaps.get(k) else { continue }; + // Count into a copy: an evicted snapshot's tiles are not retained by it any more. + let mut with = seen.clone(); + let cost = charge(snap, &mut with); + if bytes + cost > budget { + snaps[k] = None; + } else { + bytes += cost; + seen = with; } } } @@ -479,7 +509,7 @@ impl Session { copy_tiles(&mut state, after, &c.tiles[o]); tiles.push(c.tiles[o].clone()); snaps.push(Some(state.clone())); - evict(&mut snaps, &tiles, CACHE_BYTES, prefix); + evict(&mut snaps, CACHE_BYTES, prefix); out.push(Value::Null); continue; } @@ -495,7 +525,7 @@ impl Session { state = self.take_snap(eid); tiles.push(std::mem::take(&mut self.path_tiles)); snaps.push(Some(state.clone())); - evict(&mut snaps, &tiles, CACHE_BYTES, prefix); + evict(&mut snaps, CACHE_BYTES, prefix); } self.put_snap(eid, &state); self.painting_paths = false; @@ -683,10 +713,15 @@ mod tests { fn snapshots_stay_within_the_budget() { let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); let c = s.path_cache.as_mut().unwrap(); - super::evict(&mut c.snaps, &c.tiles, usize::MAX, 0); + super::evict(&mut c.snaps, usize::MAX, 0); assert_eq!(c.snaps.iter().flatten().count(), 4); - super::evict(&mut c.snaps, &c.tiles, 0, 0); - assert!(c.snaps[0].is_some() && c.snaps[3].is_some() && c.snaps[1..3].iter().all(Option::is_none), "only the free ones stay"); + // The paths are on different tiles, so keeping every snapshot costs nothing beyond the live + // pixels: even a zero budget keeps them. + super::evict(&mut c.snaps, 0, 0); + assert_eq!(c.snaps.iter().flatten().count(), 4, "snapshots that share every tile with the live pixels are free"); + // Drop them by hand to test the repaint from the bottom. + c.snaps[1] = None; + c.snaps[2] = None; // Appending still paints the new path alone. let shape = s.paths(eid).unwrap()[0].clone(); if let Some(texturecraft_core::Effect { kind: texturecraft_core::EffectKind::Path(v), .. }) = s.doc.project.effect_mut(eid) { @@ -696,13 +731,43 @@ mod tests { assert_eq!(r.iter().map(|x| !x.is_null()).collect::>(), [false, false, false, true]); // Editing above evicted snapshots repaints from the bottom and matches a full repaint. let c = s.path_cache.as_mut().unwrap(); - super::evict(&mut c.snaps, &c.tiles, 0, 0); + assert!(c.snaps[1].is_none() && c.snaps[2].is_none()); assert_eq!(edit_row(&mut s, eid, 2, 0.81), [true; 4], "the copy of path 1 sits on repainted tiles"); - // That edit kept the snapshot below path 3 within a zero budget: its next frame starts there. + // That edit kept the snapshot below path 3 within a zero budget: its next frame starts + // there, and the snapshots above it that cost nothing keep their paths unrepainted. let c = s.path_cache.as_mut().unwrap(); - super::evict(&mut c.snaps, &c.tiles, 0, 2); - assert!(c.snaps[2].is_some() && c.snaps[1].is_none()); - assert_eq!(edit_row(&mut s, eid, 2, 0.83), [false, false, true, true], "path 4 lost its snapshot too"); + super::evict(&mut c.snaps, 0, 2); + assert!(c.snaps[2].is_some()); + assert_eq!(edit_row(&mut s, eid, 2, 0.83), [false, false, true, false], "only the edited path repaints"); + } + + /// `prev` with the tiles in `at` replaced by new handles (what painting a path does). + fn painted(prev: &super::Snap, at: &[(u32, u32)]) -> super::Snap { + let mut next = prev.clone(); + for img in next.values_mut() { + for &(x, y) in at { + img.set_tile(x, y, Some(std::sync::Arc::new(vec![1u16; texturecraft_texel::TILE_AREA * 4]))); + } + } + next + } + + #[test] + fn the_budget_counts_the_tiles_an_old_snapshot_keeps_alive() { + let all: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect(); + let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); + // A full-texture fill, a one-tile stroke, another full fill, another one-tile stroke. + let s1 = painted(&empty, &all); + let s2 = painted(&s1, &[(0, 0)]); + let s3 = painted(&s2, &all); + let s4 = painted(&s3, &[(0, 0)]); + let mut snaps = vec![Some(empty), Some(s1), Some(s2), Some(s3), Some(s4)]; + // Snapshot 3 is the edited one. Snapshot 2 alone holds 15 tiles of the first fill that + // neither the live image nor snapshot 3 has: that is over a budget of 8 tiles. + let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; + super::evict(&mut snaps, 8 * tile_bytes, 3); + assert!(snaps[3].is_some(), "the edited snapshot stays"); + assert!(snaps[2].is_none(), "snapshot 2 keeps the first fill alive, over the budget"); } #[test]