mirror of
https://github.com/storytold/texturecraft.git
synced 2026-12-01 18:44:24 +01:00
Merge pull request #171 from justinjohn0306/paths/cache-channel-key
Path cache follow-up: skip untouched paths, cover channels and alpha images, cap memory
This commit is contained in:
5 files changed
+464
-71
No files matched your search
@@ -577,6 +577,9 @@ impl Session {
|
||||
self.doc = stroke.before;
|
||||
return Ok(());
|
||||
}
|
||||
if self.painting_paths {
|
||||
self.path_tiles.extend(stroke.canvas.dirty.iter().copied());
|
||||
}
|
||||
|
||||
let gbuf = self.caches.get(stroke.ts).map(|c| c.gbuf.clone());
|
||||
if stroke.stencil.is_some() && !with_commit_source(&stroke, gbuf.as_deref(), &self.mesh, &stroke.canvas.dirty, stencil_allows_stroke) {
|
||||
@@ -695,6 +698,9 @@ impl Session {
|
||||
|
||||
/// Commit a one-shot fill with the tool's material (one undo step), or into the quick mask.
|
||||
pub(crate) fn commit_fill(&mut self, label: &str, ts: usize, canvas: &StrokeCanvas, gray: &MaskGray) -> Result<()> {
|
||||
if self.painting_paths {
|
||||
self.path_tiles.extend(canvas.dirty.iter().copied());
|
||||
}
|
||||
if self.quick_mask.editing {
|
||||
return self.paint_fill(ts, canvas, gray);
|
||||
}
|
||||
|
||||
+441
-68
@@ -11,7 +11,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_compose::{PaintTarget, PixelStore};
|
||||
use texturecraft_compose::{ImageRes, PaintTarget, PixelStore};
|
||||
use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground, PathShape};
|
||||
use texturecraft_geom::glam::{Mat3, Vec2, Vec3};
|
||||
use texturecraft_geom::{OrbitCamera, surface_at};
|
||||
@@ -26,6 +26,9 @@ use crate::{Document, EngineError, Result, Session, cmd};
|
||||
|
||||
/// Control points kept at most.
|
||||
pub const MAX_PATH_POINTS: usize = 4096;
|
||||
/// Bytes of tiles the path cache's snapshots may hold (plus the edited path's); the oldest go
|
||||
/// first.
|
||||
const CACHE_BYTES: usize = 256 << 20;
|
||||
/// The undo step that adds a new path
|
||||
pub(crate) const NEW_PATH_LABEL: &str = "Path";
|
||||
/// Curve sampling step in viewport pixels (3D view) and texture units (2D view).
|
||||
@@ -151,23 +154,143 @@ impl PathState {
|
||||
}
|
||||
}
|
||||
|
||||
/// A path sublayer's pixels after painting its first paths (`below`), with the mesh and
|
||||
/// texture size they were painted for.
|
||||
/// Mesh id, texture size, owner layer channels, texture set channels.
|
||||
type CacheKey = (u64, Option<(u32, u32)>, Vec<Channel>, Vec<Channel>);
|
||||
/// A path sublayer's images: its mask (`None`) and each channel.
|
||||
type Snap = BTreeMap<Option<Channel>, TileImage>;
|
||||
/// A stored path and the brush alpha image it was painted with.
|
||||
type Painted = (PathShape, Option<Arc<ImageRes>>);
|
||||
|
||||
/// A path sublayer as last painted for `key`: its paths, its images after each path
|
||||
/// (`snaps[k]` after the first k; tiles are shared, so a snapshot costs only the tiles that
|
||||
/// path changed; None once [`evict`]ed) and the tiles each path painted.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct PathCache {
|
||||
pub(crate) eid: LayerId,
|
||||
// Session::invalidate_changed discards the prefix when an image it reads changes
|
||||
key: (u64, Option<(u32, u32)>),
|
||||
below: Vec<PathShape>,
|
||||
mask: Option<texturecraft_texel::TileImage>,
|
||||
layers: Vec<((LayerId, Channel), texturecraft_texel::TileImage)>,
|
||||
key: CacheKey,
|
||||
shapes: Vec<Painted>,
|
||||
snaps: Vec<Option<Snap>>,
|
||||
tiles: Vec<BTreeSet<(u32, u32)>>,
|
||||
}
|
||||
|
||||
/// The identities of the tile buffers and tile tables `snap` holds, added to `seen`; returns the
|
||||
/// bytes of those not already there. A table (one pointer per tile slot) is shared by clones until
|
||||
/// one writes, so a snapshot that diverged from the live image holds its own.
|
||||
fn charge(snap: &Snap, seen: &mut BTreeSet<usize>) -> usize {
|
||||
let mut bytes = 0;
|
||||
for img in snap.values() {
|
||||
if seen.insert(img.table_id()) {
|
||||
bytes += img.table_bytes();
|
||||
}
|
||||
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). 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.
|
||||
/// Returns the bytes the kept snapshots are charged.
|
||||
fn evict(snaps: &mut [Option<Snap>], budget: usize, edited: usize) -> 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) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Runs [`evict`] only when the snapshots may have outgrown the budget. `evict` charges every
|
||||
/// kept snapshot, so calling it after each appended path made a repaint of n paths cost n
|
||||
/// scans of up to n snapshots. A snapshot differs from the one before it only in the tiles its
|
||||
/// path painted, so those tiles bound what it adds: `held` is an upper bound on the bytes
|
||||
/// charged, and the scan runs once it passes the budget (then `held` is exact again).
|
||||
struct EvictPacer {
|
||||
held: usize,
|
||||
}
|
||||
|
||||
impl EvictPacer {
|
||||
/// Scan the snapshots kept from the previous repaint once, trimming them to the budget.
|
||||
fn start(snaps: &mut [Option<Snap>], edited: usize) -> Self {
|
||||
Self { held: evict(snaps, CACHE_BYTES, edited) }
|
||||
}
|
||||
|
||||
/// A snapshot was appended after a path that painted `tiles` tile positions of `state`'s images.
|
||||
fn appended(&mut self, snaps: &mut [Option<Snap>], edited: usize, state: &Snap, tiles: usize) {
|
||||
let tile_bytes: usize = state.values().map(|image| texturecraft_texel::TILE_AREA * image.comps() * 2).sum();
|
||||
// The new snapshot may also own a table per image (a write after the clone copies it).
|
||||
let table_bytes: usize = state.values().map(TileImage::table_bytes).sum();
|
||||
self.held = self.held.saturating_add(tiles.saturating_mul(tile_bytes)).saturating_add(table_bytes);
|
||||
if self.held > CACHE_BYTES {
|
||||
self.held = evict(snaps, CACHE_BYTES, edited);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn same_handle<T>(a: Option<&Arc<T>>, b: Option<&Arc<T>>) -> bool {
|
||||
match (a, b) {
|
||||
(Some(x), Some(y)) => Arc::ptr_eq(x, y),
|
||||
(x, y) => x.is_none() && y.is_none(),
|
||||
}
|
||||
}
|
||||
|
||||
fn same_path(a: &Painted, b: &Painted) -> bool {
|
||||
a.0 == b.0 && same_handle(a.1.as_ref(), b.1.as_ref())
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` hold the same tiles at `tiles`, by shared handle (painting a tile always
|
||||
/// gives it a new one); a missing image reads as empty.
|
||||
fn same_tiles(a: &Snap, b: &Snap, tiles: &BTreeSet<(u32, u32)>) -> bool {
|
||||
a.keys().chain(b.keys()).all(|k| {
|
||||
let (x, y) = (a.get(k), b.get(k));
|
||||
let dims = |i: &TileImage| (i.width(), i.height(), i.comps());
|
||||
x.zip(y).is_none_or(|(x, y)| dims(x) == dims(y))
|
||||
&& tiles.iter().all(|&(tx, ty)| same_handle(x.and_then(|i| i.tile_handle(tx, ty)), y.and_then(|i| i.tile_handle(tx, ty))))
|
||||
})
|
||||
}
|
||||
|
||||
/// Copy `from`'s tiles at `tiles` into `to`.
|
||||
fn copy_tiles(to: &mut Snap, from: &Snap, tiles: &BTreeSet<(u32, u32)>) {
|
||||
for (k, src) in from {
|
||||
to.entry(*k).or_insert_with(|| TileImage::new(src.width(), src.height(), src.comps()));
|
||||
}
|
||||
for (k, dst) in to.iter_mut() {
|
||||
let src = from.get(k);
|
||||
for &(x, y) in tiles {
|
||||
dst.set_tile(x, y, src.and_then(|i| i.tile_handle(x, y)).cloned());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PathCache {
|
||||
/// The image resources the cached paths painted their mask with
|
||||
pub(crate) fn images(&self) -> impl Iterator<Item = &str> + '_ {
|
||||
// Only successfully painted paths enter the prefix
|
||||
self.below.iter().filter_map(|shape| shape.paint.get("mask_image")?.as_str())
|
||||
self.shapes.iter().filter_map(|(shape, _)| shape.paint.get("mask_image")?.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -363,7 +486,7 @@ fn remove_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
shapes.remove(index);
|
||||
}
|
||||
s.render_paths(eid, index)
|
||||
s.render_paths(eid)
|
||||
})?;
|
||||
if s.tool.path.editing.is_some_and(|(e, _)| e == eid) {
|
||||
s.stop_path_edit();
|
||||
@@ -612,7 +735,7 @@ impl Session {
|
||||
if let Some(Effect { kind: EffectKind::Path(paths), .. }) = session.doc.project.effect_mut(effect) {
|
||||
paths.remove(index);
|
||||
}
|
||||
session.render_paths(effect, index)
|
||||
session.render_paths(effect)
|
||||
},
|
||||
)?;
|
||||
self.cancel_path();
|
||||
@@ -981,44 +1104,65 @@ impl Session {
|
||||
},
|
||||
_ => return Err(EngineError::Other(format!("{} is not a path sublayer", eid.0))),
|
||||
};
|
||||
let mut out = self.render_paths(eid, index)?.get(index).cloned().unwrap_or_else(|| json!({}));
|
||||
let mut out = self.render_paths(eid)?.get(index).cloned().unwrap_or_else(|| json!({}));
|
||||
out["effect"] = json!(eid.0);
|
||||
out["index"] = json!(index);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Repaint path sublayer `eid` from its stored paths, bottom to top, where paths before
|
||||
/// `from` are unchanged: their pixels come from [`PathCache`] when it holds them, and are
|
||||
/// cached for the next repaint otherwise, so editing a path repaints it and the paths above
|
||||
/// only. Runs inside the caller's undo step. Returns each painted path's report (null for
|
||||
/// the cached ones).
|
||||
fn render_paths(&mut self, eid: LayerId, from: usize) -> Result<Vec<Value>> {
|
||||
/// Repaint path sublayer `eid` from its stored paths, bottom to top. From [`PathCache`]: the
|
||||
/// paths before the first changed one keep their pixels, and an unchanged path above it
|
||||
/// whose tiles the change didn't reach keeps its painted tiles; the rest repaint. Runs
|
||||
/// inside the caller's undo step. Returns each painted path's report (null for the cached
|
||||
/// ones).
|
||||
fn render_paths(&mut self, eid: LayerId) -> Result<Vec<Value>> {
|
||||
let shapes = self.paths(eid).ok_or_else(|| EngineError::Other(format!("{} is not a path sublayer", eid.0)))?.to_vec();
|
||||
let key = (self.mesh_id, self.caches.get(self.ts()).map(|c| c.size));
|
||||
self.doc.pixels.masks.remove(&eid);
|
||||
self.doc.pixels.layers.retain(|(id, _), _| *id != eid);
|
||||
let start = match &self.path_cache {
|
||||
Some(c) if c.eid == eid && c.key == key && c.below.len() <= from && shapes.get(..c.below.len()) == Some(&c.below[..]) => {
|
||||
if let Some(m) = &c.mask {
|
||||
self.doc.pixels.masks.insert(eid, m.clone());
|
||||
}
|
||||
self.doc.pixels.layers.extend(c.layers.iter().cloned());
|
||||
c.below.len()
|
||||
}
|
||||
_ => 0,
|
||||
};
|
||||
let images = &self.images;
|
||||
let alpha = |sh: &PathShape| read_paint(sh).ok().and_then(|p| p.brush.alpha_image).and_then(|n| images.get(&n).cloned());
|
||||
let new: Vec<Painted> = shapes
|
||||
.into_iter()
|
||||
.map(|sh| {
|
||||
let a = alpha(&sh);
|
||||
(sh, a)
|
||||
})
|
||||
.collect();
|
||||
let project = &self.doc.project;
|
||||
let owner = project.effect(eid).and_then(|(o, _)| project.layer(o).ok()).map(|l| l.channels.keys().copied().collect()).unwrap_or_default();
|
||||
let set = project.texture_set(self.ts()).map(|t| t.channel_list()).unwrap_or_default();
|
||||
let key: CacheKey = (self.mesh_id, self.caches.get(self.ts()).map(|c| c.size), owner, set);
|
||||
let old = self.path_cache.take().filter(|c| c.eid == eid && c.key == key);
|
||||
let (prefix, suffix) = old.as_ref().map_or((0, 0), |c| {
|
||||
let p = c.shapes.iter().zip(&new).take_while(|(a, b)| same_path(a, b)).count();
|
||||
(p, c.shapes[p..].iter().rev().zip(new[p..].iter().rev()).take_while(|(a, b)| same_path(a, b)).count())
|
||||
});
|
||||
// Start from the last snapshot kept at or below the first changed path (the first one,
|
||||
// empty, is always kept).
|
||||
let start = old.as_ref().map_or(0, |c| (0..=prefix).rev().find(|&k| c.snaps[k].is_some()).unwrap_or(0));
|
||||
let mut snaps = old.as_ref().map_or_else(|| vec![Some(Snap::new())], |c| c.snaps[..=start].to_vec());
|
||||
let mut tiles = old.as_ref().map_or_else(Vec::new, |c| c.tiles[..start].to_vec());
|
||||
let mut state = snaps[start].clone().unwrap_or_default();
|
||||
let mut pacer = EvictPacer::start(&mut snaps, prefix);
|
||||
// Each path goes through the regular stroke and fill code with its own settings; their
|
||||
// own history entries are dropped (the caller records one step).
|
||||
let mut out = vec![Value::Null; start];
|
||||
let result = self.while_painting_paths(eid, |s| {
|
||||
let mut result = Ok(());
|
||||
for i in start..=shapes.len() {
|
||||
if i == from.min(shapes.len()) && i > start {
|
||||
let pixels = &s.doc.pixels;
|
||||
let layers = pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|(k, v)| (*k, v.clone())).collect();
|
||||
s.path_cache = Some(PathCache { eid, key, below: shapes[..i].to_vec(), mask: pixels.masks.get(&eid).cloned(), layers });
|
||||
for (j, (sh, _)) in new.iter().enumerate().skip(start) {
|
||||
// Painting is per tile: over the same tiles, an unchanged path paints the same.
|
||||
let o = if j < prefix { Some(j) } else { (j >= new.len() - suffix).then(|| j + old.as_ref().map_or(0, |c| c.shapes.len()) - new.len()) };
|
||||
if let (Some(c), Some(o)) = (&old, o)
|
||||
&& let (Some(below), Some(after)) = (&c.snaps[o], &c.snaps[o + 1])
|
||||
&& same_tiles(&state, below, &c.tiles[o])
|
||||
{
|
||||
copy_tiles(&mut state, after, &c.tiles[o]);
|
||||
tiles.push(c.tiles[o].clone());
|
||||
snaps.push(Some(state.clone()));
|
||||
pacer.appended(&mut snaps, prefix, &state, c.tiles[o].len());
|
||||
out.push(Value::Null);
|
||||
continue;
|
||||
}
|
||||
let Some(sh) = shapes.get(i) else { break };
|
||||
s.put_snap(eid, &state);
|
||||
s.path_tiles.clear();
|
||||
match s.paint_shape(sh) {
|
||||
Ok(v) => out.push(v),
|
||||
Err(e) => {
|
||||
@@ -1026,9 +1170,17 @@ impl Session {
|
||||
break;
|
||||
}
|
||||
}
|
||||
state = s.take_snap(eid);
|
||||
tiles.push(std::mem::take(&mut s.path_tiles));
|
||||
snaps.push(Some(state.clone()));
|
||||
pacer.appended(&mut snaps, prefix, &state, tiles.last().map_or(0, BTreeSet::len));
|
||||
}
|
||||
s.put_snap(eid, &state);
|
||||
result
|
||||
});
|
||||
if result.is_ok() {
|
||||
self.path_cache = Some(PathCache { eid, key, shapes: new, snaps, tiles });
|
||||
}
|
||||
result.map(|_| out)
|
||||
}
|
||||
|
||||
@@ -1054,6 +1206,24 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
fn take_snap(&self, eid: LayerId) -> Snap {
|
||||
let p = &self.doc.pixels;
|
||||
let mask = p.masks.get(&eid).map(|m| (None, m.clone()));
|
||||
mask.into_iter().chain(p.layers.iter().filter(|((id, _), _)| *id == eid).map(|((_, c), img)| (Some(*c), img.clone()))).collect()
|
||||
}
|
||||
|
||||
fn put_snap(&mut self, eid: LayerId, snap: &Snap) {
|
||||
let p = &mut self.doc.pixels;
|
||||
p.masks.remove(&eid);
|
||||
p.layers.retain(|(id, _), _| *id != eid);
|
||||
for (k, img) in snap {
|
||||
match k {
|
||||
None => p.masks.insert(eid, img.clone()),
|
||||
Some(c) => p.layers.insert((eid, *c), img.clone()),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn paint_shape(&mut self, shape: &PathShape) -> Result<Value> {
|
||||
let paint = read_paint(shape)?;
|
||||
let (camera, viewport) = paint_view(shape, &paint);
|
||||
@@ -1230,45 +1400,246 @@ mod tests {
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_repaint_matches_a_full_repaint() {
|
||||
let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap();
|
||||
/// A session with horizontal UV paths at `rows` (one path sublayer) on a 512 texture.
|
||||
fn with_paths(rows: &[f32]) -> (Session, texturecraft_core::LayerId) {
|
||||
let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 512).unwrap();
|
||||
s.update();
|
||||
execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap();
|
||||
let mut eid = 0;
|
||||
for v in [0.2, 0.5, 0.8] {
|
||||
let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.9, v + 0.05]], "commit": true})).unwrap();
|
||||
for v in rows {
|
||||
let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.9, v]], "commit": true})).unwrap();
|
||||
eid = r["committed"]["effect"].as_u64().unwrap();
|
||||
}
|
||||
let eid = texturecraft_core::LayerId(eid);
|
||||
(s, texturecraft_core::LayerId(eid))
|
||||
}
|
||||
|
||||
// Live edits of the middle path reuse the bottom path's pixels
|
||||
execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap();
|
||||
for v in [0.4, 0.45] {
|
||||
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap();
|
||||
}
|
||||
|
||||
assert_eq!(s.path_cache.as_ref().map(|c| c.below.len()), Some(1));
|
||||
|
||||
let r = s.render_paths(eid, 1).unwrap();
|
||||
|
||||
assert!(r[0].is_null() && !r[1].is_null(), "the bottom path came from the cache: {r:?}");
|
||||
|
||||
let cached = pixels(&s, eid);
|
||||
/// Move path `index` to row `v` (a live edit) and check the result against painting every
|
||||
/// path. Returns which paths were repainted.
|
||||
fn edit_row(s: &mut Session, eid: texturecraft_core::LayerId, index: usize, v: f32) -> Vec<bool> {
|
||||
execute(s, "path.edit", &json!({"effect": eid.0, "index": index})).unwrap();
|
||||
let before = s.path_cache.clone();
|
||||
execute(s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap();
|
||||
let cached = pixels(s, eid);
|
||||
s.path_cache = before;
|
||||
let painted = s.render_paths(eid).unwrap().iter().map(|r| !r.is_null()).collect();
|
||||
assert_eq!(cached, pixels(s, eid));
|
||||
s.path_cache = None;
|
||||
s.render_paths(eid, 0).unwrap();
|
||||
|
||||
assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path");
|
||||
s.render_paths(eid).unwrap();
|
||||
assert_eq!(cached, pixels(s, eid), "same pixels as painting every path");
|
||||
assert!(!cached.is_empty());
|
||||
s.stop_path_edit();
|
||||
painted
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_repaint_matches_a_full_repaint() {
|
||||
// Rows 0.2, 0.45 and 0.8 of 512 texels are in different 64-texel tile rows.
|
||||
let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]);
|
||||
assert_eq!(edit_row(&mut s, eid, 1, 0.47), [false, true, false], "only the edited path repaints");
|
||||
assert_eq!(edit_row(&mut s, eid, 0, 0.22), [true, false, false], "paths above keep their tiles");
|
||||
assert_eq!(edit_row(&mut s, eid, 0, 0.79), [true, false, true], "a path over the change repaints");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filled_path_above_an_edit_keeps_its_tiles() {
|
||||
// The stroke at row 0.2 is edited; the closed, filled path above it lies in other tiles.
|
||||
let (mut s, eid) = with_paths(&[0.2]);
|
||||
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.7], [0.5, 0.7], [0.5, 0.9], [0.1, 0.9]], "closed": true, "fill": true, "commit": true}))
|
||||
.unwrap();
|
||||
assert_eq!(edit_row(&mut s, eid, 0, 0.22), [true, false], "the fill above comes from the cache, with its pixels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_path_keeps_the_paths_above() {
|
||||
let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]);
|
||||
let before = s.path_cache.clone();
|
||||
execute(&mut s, "path.remove", &json!({"effect": eid.0, "index": 0})).unwrap();
|
||||
let cached = pixels(&s, eid);
|
||||
s.path_cache = before;
|
||||
assert!(s.render_paths(eid).unwrap().iter().all(Value::is_null), "both paths above came from the cache");
|
||||
s.path_cache = None;
|
||||
s.render_paths(eid).unwrap();
|
||||
assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_the_brush_alpha_image_repaints() {
|
||||
let (mut s, eid) = with_paths(&[0.2]);
|
||||
let img = |v: f32| std::sync::Arc::new(texturecraft_compose::ImageRes::new(2, 2, vec![[v; 4]; 4], false));
|
||||
s.images.insert("a".into(), img(1.0));
|
||||
execute(&mut s, "tool.brush", &json!({"alpha": {"image": "a"}})).unwrap();
|
||||
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.8], [0.9, 0.8]], "commit": true})).unwrap();
|
||||
s.render_paths(eid).unwrap();
|
||||
s.images.insert("a".into(), img(0.5));
|
||||
let r = s.render_paths(eid).unwrap();
|
||||
assert!(r[0].is_null() && !r[1].is_null(), "only the path using the image repaints: {r:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
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, usize::MAX, 0);
|
||||
assert_eq!(c.snaps.iter().flatten().count(), 4);
|
||||
// The paths are on different tiles, so a snapshot costs nothing beyond its own tile table
|
||||
// (the tiles are all shared with the live pixels): a budget of two tables keeps them.
|
||||
let table: usize = c.snaps[1].as_ref().unwrap().values().map(texturecraft_texel::TileImage::table_bytes).sum();
|
||||
super::evict(&mut c.snaps, 2 * table, 0);
|
||||
assert_eq!(c.snaps.iter().flatten().count(), 4, "snapshots that share every tile with the live pixels cost only their tables");
|
||||
// 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) {
|
||||
v.push(shape);
|
||||
}
|
||||
let r = s.render_paths(eid).unwrap();
|
||||
assert_eq!(r.iter().map(|x| !x.is_null()).collect::<Vec<_>>(), [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();
|
||||
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 one-table budget: its next frame starts
|
||||
// there, and the snapshots above it that cost only a table keep their paths unrepainted.
|
||||
let c = s.path_cache.as_mut().unwrap();
|
||||
let table: usize = c.snaps[2].as_ref().unwrap().values().map(texturecraft_texel::TileImage::table_bytes).sum();
|
||||
super::evict(&mut c.snaps, table, 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]
|
||||
fn appending_paths_scans_the_snapshots_only_when_the_budget_may_be_passed() {
|
||||
let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into();
|
||||
let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::<usize>();
|
||||
let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2;
|
||||
let mut snaps = vec![Some(empty.clone()), Some(painted(&empty, &[(0, 0)]))];
|
||||
let mut pacer = super::EvictPacer::start(&mut snaps, 0);
|
||||
assert_eq!(pacer.held, 0, "the first and last snapshots are free");
|
||||
// A few small paths add up to an estimate without a scan (a scan would reset it to the exact 0).
|
||||
for n in 1..=3 {
|
||||
pacer.appended(&mut snaps, 0, &empty, 1);
|
||||
assert_eq!(pacer.held, n * (tile_bytes + table), "after {n} paths");
|
||||
}
|
||||
// Past the budget the estimate gives way to an exact scan.
|
||||
pacer.appended(&mut snaps, 0, &empty, super::CACHE_BYTES / tile_bytes + 1);
|
||||
assert!(pacer.held < super::CACHE_BYTES, "scanned: {}", pacer.held);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_snapshot_is_charged_only_for_what_no_kept_snapshot_shares() {
|
||||
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();
|
||||
let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2;
|
||||
let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::<usize>();
|
||||
// Two full fills then a one-tile stroke (the live pixels). Snapshot 2 shares 15 tiles with
|
||||
// the live pixels and owns one; snapshot 1 owns the whole first fill: 16 tiles.
|
||||
let s1 = painted(&empty, &all);
|
||||
let s2 = painted(&s1, &all);
|
||||
let s3 = painted(&s2, &[(0, 0)]);
|
||||
let fresh = || vec![Some(empty.clone()), Some(s1.clone()), Some(s2.clone()), Some(s3.clone())];
|
||||
let kept = |snaps: &[Option<super::Snap>]| snaps.iter().map(Option::is_some).collect::<Vec<_>>();
|
||||
let mut snaps = fresh();
|
||||
super::evict(&mut snaps, usize::MAX, 0);
|
||||
assert_eq!(kept(&snaps), [true; 4]);
|
||||
let mut snaps = fresh();
|
||||
super::evict(&mut snaps, tile_bytes + table, 0);
|
||||
assert_eq!(kept(&snaps), [true, false, true, true], "snapshot 2 costs one tile and a table, snapshot 1 sixteen");
|
||||
let mut snaps = fresh();
|
||||
super::evict(&mut snaps, 0, 0);
|
||||
assert_eq!(kept(&snaps), [true, false, false, true], "snapshot 2 owns one tile, over a zero budget");
|
||||
// Keeping snapshot 1 (edited) makes snapshot 2 free of the tiles they share, not of its own.
|
||||
let mut snaps = fresh();
|
||||
super::evict(&mut snaps, 0, 1);
|
||||
assert_eq!(kept(&snaps), [true, true, false, true]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tile_table_of_a_diverged_snapshot_counts_once_against_the_budget() {
|
||||
// Big image: the table (one slot per tile position) outweighs a one-tile stroke.
|
||||
let empty: super::Snap = [(Some(texturecraft_core::Channel::Roughness), texturecraft_texel::TileImage::new(8192, 8192, 4))].into();
|
||||
let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::<usize>();
|
||||
assert!(table >= 128 * 128 * 8, "table {table}");
|
||||
let s1 = painted(&empty, &[(0, 0)]);
|
||||
let s2 = painted(&s1, &[(1, 0)]);
|
||||
let s3 = painted(&s2, &[(2, 0)]);
|
||||
let live = painted(&s3, &[(3, 0)]);
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
// Alone, a diverged snapshot holds its own table; charged again with the same table, it is free.
|
||||
let first = super::charge(&s2, &mut seen);
|
||||
assert!(first >= table, "charged {first}");
|
||||
assert_eq!(super::charge(&s2, &mut seen), 0);
|
||||
// Tiles alone (8 KiB each) would fit this budget; with tables only one snapshot does.
|
||||
let tile_only = texturecraft_texel::TILE_AREA * 4 * 2;
|
||||
let mut snaps = vec![Some(empty.clone()), Some(s1), Some(s2), Some(s3), Some(live)];
|
||||
super::evict(&mut snaps, 3 * tile_only, 0);
|
||||
assert!(snaps.iter().filter(|s| s.is_some()).count() < 5, "tables must evict snapshots");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_quick_mask_does_not_clip_paths() {
|
||||
let (mut s, eid) = with_paths(&[0.2, 0.8]);
|
||||
let plain = pixels(&s, eid);
|
||||
s.quick_mask.enabled = true;
|
||||
s.path_cache = None;
|
||||
s.render_paths(eid).unwrap();
|
||||
assert_eq!(plain, pixels(&s, eid));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owner_channel_change_skips_the_cache() {
|
||||
let (mut s, eid) = with_paths(&[0.3, 0.7]);
|
||||
s.render_paths(eid).unwrap();
|
||||
let owner = s.doc.project.effect(eid).unwrap().0;
|
||||
let layer = s.doc.project.layer_mut(owner).unwrap();
|
||||
let ch = *layer.channels.keys().next().unwrap();
|
||||
layer.channels.remove(&ch);
|
||||
let r = s.render_paths(eid).unwrap();
|
||||
assert!(!r[0].is_null(), "the bottom path was repainted: {r:?}");
|
||||
assert!(!s.doc.pixels.layers.contains_key(&(eid, ch)), "no pixels left in the removed channel");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_the_path_effect_releases_its_cached_tiles() {
|
||||
let (mut s, eid) = with_paths(&[0.2, 0.5, 0.8]);
|
||||
execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap();
|
||||
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.35], [0.9, 0.4]]})).unwrap();
|
||||
let cached_tiles = s.path_cache.as_ref().map_or(0, |cache| cache.layers.iter().map(|(_, image)| image.allocated_count()).sum::<usize>());
|
||||
assert!(cached_tiles > 0);
|
||||
|
||||
let held = |s: &Session| {
|
||||
s.path_cache.as_ref().map_or(0, |c| c.snaps.iter().flatten().flat_map(|snap| snap.values()).map(|i| i.allocated_count()).sum::<usize>())
|
||||
};
|
||||
assert!(held(&s) > 0);
|
||||
execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap();
|
||||
let remaining_tiles = s.path_cache.as_ref().map_or(0, |cache| cache.layers.iter().map(|(_, image)| image.allocated_count()).sum::<usize>());
|
||||
assert_eq!(remaining_tiles, 0);
|
||||
assert_eq!(held(&s), 0);
|
||||
assert!(s.path_cache.is_none(), "deleting the path effect releases its cached tiles");
|
||||
}
|
||||
|
||||
@@ -1292,14 +1663,14 @@ mod tests {
|
||||
execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap();
|
||||
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.6], [0.9, 0.6]]})).unwrap();
|
||||
|
||||
assert_eq!(s.path_cache.as_ref().map(|c| c.below.len()), Some(1), "the bottom path is cached");
|
||||
assert_eq!(s.path_cache.as_ref().map(|c| c.shapes.len()), Some(2), "the paths are cached");
|
||||
|
||||
execute(&mut s, "resource.remove", &json!({"name": image})).unwrap();
|
||||
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.65], [0.9, 0.65]]})).unwrap();
|
||||
let mask = |s: &Session| format!("{:?}", s.doc.pixels.masks.get(&eid));
|
||||
let edited = mask(&s);
|
||||
s.path_cache = None;
|
||||
s.render_paths(eid, 0).unwrap();
|
||||
s.render_paths(eid).unwrap();
|
||||
|
||||
assert_eq!(edited, mask(&s), "the bottom path paints the mask value as a full repaint does");
|
||||
}
|
||||
@@ -1311,7 +1682,9 @@ mod tests {
|
||||
let tile = Arc::new(vec![1u16; texturecraft_texel::TILE_AREA]);
|
||||
let retained = Arc::downgrade(&tile);
|
||||
image.set_tile(0, 0, Some(tile));
|
||||
session.path_cache = Some(PathCache { eid: LayerId(0), key: (0, None), below: Vec::new(), mask: Some(image), layers: Vec::new() });
|
||||
let snap: Snap = [(None, image)].into();
|
||||
session.path_cache =
|
||||
Some(PathCache { eid: LayerId(0), key: (0, None, Vec::new(), Vec::new()), shapes: Vec::new(), snaps: vec![Some(snap)], tiles: Vec::new() });
|
||||
|
||||
let result: Result<()> = session.edit("Rejected edit", |_| Err(EngineError::Other("rejected".into())));
|
||||
|
||||
|
||||
@@ -95,10 +95,10 @@ impl Session {
|
||||
}
|
||||
|
||||
/// What limits a paint stroke on `ts`: the mask and whether it is inverted (None when the
|
||||
/// quick mask is off or being edited).
|
||||
/// quick mask is off or being edited, and for paths, which repaint from what they store).
|
||||
pub(crate) fn stroke_limit(&self, ts: usize, size: (u32, u32)) -> Option<(TileImage, bool)> {
|
||||
let q = &self.quick_mask;
|
||||
(q.enabled && !q.editing).then(|| (self.quick_mask_image(ts, size), q.inverted))
|
||||
(q.enabled && !q.editing && !self.painting_paths).then(|| (self.quick_mask_image(ts, size), q.inverted))
|
||||
}
|
||||
|
||||
/// Commit a stroke into the quick mask of `ts`.
|
||||
|
||||
@@ -525,8 +525,10 @@ pub struct Session {
|
||||
pub quick_mask: crate::quick_mask::QuickMask,
|
||||
/// A path sublayer is being repainted from its paths (the only way to paint into one).
|
||||
pub(crate) painting_paths: bool,
|
||||
/// Pixels of the paths below the one being edited, so live edits skip repainting them.
|
||||
/// A path sublayer as last painted, so a repaint skips the paths an edit didn't reach.
|
||||
pub(crate) path_cache: Option<crate::path_tool::PathCache>,
|
||||
/// Tiles painted since `render_paths` cleared it (the footprint of one path).
|
||||
pub(crate) path_tiles: std::collections::BTreeSet<(u32, u32)>,
|
||||
/// A new path's live preview: the path becomes an undo step only when it is applied
|
||||
pub(crate) path_draft: Option<crate::path_draft::PathDraft>,
|
||||
/// Point changes of the path being edited: (earlier states for undo, undone states for redo)
|
||||
@@ -617,6 +619,7 @@ impl Session {
|
||||
quick_mask: Default::default(),
|
||||
painting_paths: false,
|
||||
path_cache: None,
|
||||
path_tiles: Default::default(),
|
||||
path_draft: None,
|
||||
path_steps: Default::default(),
|
||||
path: None,
|
||||
|
||||
@@ -62,6 +62,17 @@ impl TileImage {
|
||||
self.tile_index(tx, ty).and_then(|i| self.tiles.get(i)).and_then(Option::as_ref)
|
||||
}
|
||||
|
||||
/// Identity of the shared tile table: clones share it until one of them writes, so two images
|
||||
/// with the same id hold one allocation (for memory accounting).
|
||||
pub fn table_id(&self) -> usize {
|
||||
Arc::as_ptr(&self.tiles) as usize
|
||||
}
|
||||
|
||||
/// Bytes of the tile table itself (one slot per tile position), not counting the tiles.
|
||||
pub fn table_bytes(&self) -> usize {
|
||||
self.tiles.len().saturating_mul(std::mem::size_of::<Option<TileData>>())
|
||||
}
|
||||
|
||||
/// Replace a tile wholesale (None frees it).
|
||||
pub fn set_tile(&mut self, tx: u32, ty: u32, data: Option<TileData>) {
|
||||
let len = TILE_AREA * self.comps;
|
||||
|
||||
Reference in new issue
Block a user