From 90e1e359f167966cf56ab9ae3961fcbd75353b65 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 19:50:31 +0100 Subject: [PATCH 1/3] perf(paint): cache procedural brush textures between strokes (#11134) BrushContext::new regenerated the procedural texture and re-applied its levels for every stroke and every symmetry pass. A bounded LRU (4 entries, 16 MiB) keyed by style, size, seed and the level settings returns the identical image. Refs #11134. Co-Authored-By: Claude Sonnet 5.5 --- crates/paint/src/lib.rs | 1 + crates/paint/src/pattern_cache.rs | 90 +++++++++++++++++++++++++++++++ crates/paint/src/render.rs | 12 ++--- 3 files changed, 97 insertions(+), 6 deletions(-) create mode 100644 crates/paint/src/pattern_cache.rs diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index 214a28177d..c940bd3164 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -24,6 +24,7 @@ pub mod curve; pub mod dynamics; pub mod mixer; pub mod outline; +mod pattern_cache; pub mod presets; pub mod procedural; pub mod render; diff --git a/crates/paint/src/pattern_cache.rs b/crates/paint/src/pattern_cache.rs new file mode 100644 index 0000000000..be710fb483 --- /dev/null +++ b/crates/paint/src/pattern_cache.rs @@ -0,0 +1,90 @@ +//! A small process-wide cache for procedural brush textures. +//! +//! A stroke (and every symmetry mirror of it) used to regenerate its procedural texture in +//! [`crate::BrushContext::new`], although the image is a pure function of the style, size, seed and +//! level adjustments. The cache is bounded in entries and bytes and evicts the least recently used +//! entry first. Sampled-tip mip pyramids are not handled here (see PR #9617). +//! +//! The key holds every input of the generator plus the level adjustments (brightness, contrast, +//! invert) that are baked into the cached image, so a hit is always the image a rebuild would give. + +use std::sync::{Arc, Mutex, PoisonError}; + +use crate::brush::{PatternStyle, Texture}; +use crate::tile::PatternImage; + +const PATTERN_MAX_ENTRIES: usize = 4; +const PATTERN_MAX_BYTES: usize = 16 << 20; + +#[derive(PartialEq)] +struct PatternKey { + style: PatternStyle, + size: u32, + seed: u32, + brightness: u32, + contrast: u32, + invert: bool, +} + +struct PatternEntry { + key: PatternKey, + image: Arc, +} + +static PATTERNS: Mutex> = Mutex::new(Vec::new()); + +/// The procedural pattern `(style, size, seed)` with `t`'s levels applied, from the cache when it +/// was built recently. +pub fn procedural_pattern(style: PatternStyle, size: u32, seed: u32, t: &Texture) -> Arc { + let key = PatternKey { style, size: size.clamp(8, 1024), seed, brightness: t.brightness.to_bits(), contrast: t.contrast.to_bits(), invert: t.invert }; + { + let mut cache = PATTERNS.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(i) = cache.iter().position(|e| e.key == key) { + let e = cache.remove(i); + let image = Arc::clone(&e.image); + cache.push(e); + return image; + } + } + let mut img = crate::procedural::pattern(style, size, seed); + for v in &mut img.data { + *v = t.level(*v); + } + let image = Arc::new(img); + let bytes = |e: &PatternEntry| e.image.data.len() * 4; + if image.data.len() * 4 <= PATTERN_MAX_BYTES / 2 { + let mut cache = PATTERNS.lock().unwrap_or_else(PoisonError::into_inner); + if !cache.iter().any(|e| e.key == key) { + cache.push(PatternEntry { key, image: Arc::clone(&image) }); + } + while cache.len() > PATTERN_MAX_ENTRIES || cache.iter().map(bytes).sum::() > PATTERN_MAX_BYTES { + cache.remove(0); + } + } + image +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pattern_cache_keys_on_every_input() { + let base = Texture::default(); + let a = procedural_pattern(PatternStyle::Noise, 64, 3, &base); + assert!(Arc::ptr_eq(&a, &procedural_pattern(PatternStyle::Noise, 64, 3, &base))); + let mut fresh = crate::procedural::pattern(PatternStyle::Noise, 64, 3); + fresh.data.iter_mut().for_each(|v| *v = base.level(*v)); + assert_eq!(a.data, fresh.data); + for other in [ + procedural_pattern(PatternStyle::Canvas, 64, 3, &base), + procedural_pattern(PatternStyle::Noise, 32, 3, &base), + procedural_pattern(PatternStyle::Noise, 64, 4, &base), + procedural_pattern(PatternStyle::Noise, 64, 3, &Texture { invert: true, ..base.clone() }), + procedural_pattern(PatternStyle::Noise, 64, 3, &Texture { brightness: 0.5, ..base.clone() }), + procedural_pattern(PatternStyle::Noise, 64, 3, &Texture { contrast: 0.5, ..base.clone() }), + ] { + assert!(!Arc::ptr_eq(&a, &other)); + } + } +} diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index 83243bdafa..b0ab66f505 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -209,12 +209,12 @@ fn prepare_pattern(b: &BrushSettings) -> Option> { if !t.enabled { return None; } - let mut img = match &t.pattern { - Pattern::Procedural { style, size, seed } => crate::procedural::pattern(*style, *size, *seed), - p => match p.bitmap() { - Some(g) if g.is_valid() => PatternImage { width: g.width as usize, height: g.height as usize, data: g.to_f32() }, - _ => return None, - }, + if let Pattern::Procedural { style, size, seed } = &t.pattern { + return Some(crate::pattern_cache::procedural_pattern(*style, *size, *seed, t)); + } + let mut img = match t.pattern.bitmap() { + Some(g) if g.is_valid() => PatternImage { width: g.width as usize, height: g.height as usize, data: g.to_f32() }, + _ => return None, }; for v in &mut img.data { *v = t.level(*v); From c2a6a80b1f8b826481a6be61b7d52cd98b7d53cc Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 00:18:41 +0100 Subject: [PATCH 2/3] paint: refresh a duplicate pattern-cache key; test eviction and key separation CodeRabbit review points: a duplicate insert should promote the entry, the key-separation test could pass after the base entry was evicted, and the entry limit was untested. Co-Authored-By: Claude Sonnet 5.5 --- crates/paint/src/pattern_cache.rs | 45 +++++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 11 deletions(-) diff --git a/crates/paint/src/pattern_cache.rs b/crates/paint/src/pattern_cache.rs index be710fb483..9ceab0fb62 100644 --- a/crates/paint/src/pattern_cache.rs +++ b/crates/paint/src/pattern_cache.rs @@ -54,8 +54,13 @@ pub fn procedural_pattern(style: PatternStyle, size: u32, seed: u32, t: &Texture let bytes = |e: &PatternEntry| e.image.data.len() * 4; if image.data.len() * 4 <= PATTERN_MAX_BYTES / 2 { let mut cache = PATTERNS.lock().unwrap_or_else(PoisonError::into_inner); - if !cache.iter().any(|e| e.key == key) { - cache.push(PatternEntry { key, image: Arc::clone(&image) }); + // Another thread may have built the same key meanwhile: keep its image, but it was just asked for. + match cache.iter().position(|e| e.key == key) { + Some(i) => { + let e = cache.remove(i); + cache.push(e); + } + None => cache.push(PatternEntry { key, image: Arc::clone(&image) }), } while cache.len() > PATTERN_MAX_ENTRIES || cache.iter().map(bytes).sum::() > PATTERN_MAX_BYTES { cache.remove(0); @@ -76,15 +81,33 @@ mod tests { let mut fresh = crate::procedural::pattern(PatternStyle::Noise, 64, 3); fresh.data.iter_mut().for_each(|v| *v = base.level(*v)); assert_eq!(a.data, fresh.data); - for other in [ - procedural_pattern(PatternStyle::Canvas, 64, 3, &base), - procedural_pattern(PatternStyle::Noise, 32, 3, &base), - procedural_pattern(PatternStyle::Noise, 64, 4, &base), - procedural_pattern(PatternStyle::Noise, 64, 3, &Texture { invert: true, ..base.clone() }), - procedural_pattern(PatternStyle::Noise, 64, 3, &Texture { brightness: 0.5, ..base.clone() }), - procedural_pattern(PatternStyle::Noise, 64, 3, &Texture { contrast: 0.5, ..base.clone() }), - ] { - assert!(!Arc::ptr_eq(&a, &other)); + let variants = [ + (PatternStyle::Canvas, 64, 3, base.clone()), + (PatternStyle::Noise, 32, 3, base.clone()), + (PatternStyle::Noise, 64, 4, base.clone()), + (PatternStyle::Noise, 64, 3, Texture { invert: true, ..base.clone() }), + (PatternStyle::Noise, 64, 3, Texture { brightness: 0.5, ..base.clone() }), + (PatternStyle::Noise, 64, 3, Texture { contrast: 0.5, ..base.clone() }), + ]; + for (style, size, seed, texture) in variants { + // Look the base up again so it is the newest entry and still cached when the variant is + // asked for; a key that ignored the changed input would then hand back the base image. + procedural_pattern(PatternStyle::Noise, 64, 3, &base); + let other = procedural_pattern(style, size, seed, &texture); + assert!(!Arc::ptr_eq(&a, &other) && other.data != a.data, "{style:?} {size} {seed}"); } } + + /// The cache holds a few entries: the oldest one goes first. Seeds are used by no other test, so + /// no hit can refresh `first`. + #[test] + fn pattern_cache_evicts_the_oldest_entry_past_its_limit() { + let base = Texture::default(); + let first = procedural_pattern(PatternStyle::Noise, 16, 90_001, &base); + assert!(Arc::ptr_eq(&first, &procedural_pattern(PatternStyle::Noise, 16, 90_001, &base))); + for seed in 90_002..90_002 + PATTERN_MAX_ENTRIES as u32 { + procedural_pattern(PatternStyle::Noise, 16, seed, &base); + } + assert!(!Arc::ptr_eq(&first, &procedural_pattern(PatternStyle::Noise, 16, 90_001, &base))); + } } From 0d69d40c6b1731685cd191f9e9c6cbcfe169690d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 01:51:30 +0100 Subject: [PATCH 3/3] perf(paint): key the pattern cache on normalised levels, make the eviction test independent The key now uses the brightness and contrast values Texture::level uses (clamped, non-finite as 0, -0.0 as 0.0), so equal levels share one entry. The cache logic moves into a PatternCache struct so the eviction test runs on its own instance instead of the shared static. Co-Authored-By: Claude Sonnet 5.5 --- crates/paint/src/pattern_cache.rs | 112 +++++++++++++++++++++--------- 1 file changed, 80 insertions(+), 32 deletions(-) diff --git a/crates/paint/src/pattern_cache.rs b/crates/paint/src/pattern_cache.rs index 9ceab0fb62..421367a365 100644 --- a/crates/paint/src/pattern_cache.rs +++ b/crates/paint/src/pattern_cache.rs @@ -31,41 +31,65 @@ struct PatternEntry { image: Arc, } -static PATTERNS: Mutex> = Mutex::new(Vec::new()); +/// The entries, least recently used first. +struct PatternCache(Vec); + +impl PatternCache { + const fn new() -> Self { + Self(Vec::new()) + } + + /// The image cached for `key`, which is then the most recently used entry. + fn get(&mut self, key: &PatternKey) -> Option> { + let i = self.0.iter().position(|e| e.key == *key)?; + let e = self.0.remove(i); + let image = Arc::clone(&e.image); + self.0.push(e); + Some(image) + } + + /// Caches `image` for `key` (unless it is too big) and evicts the oldest entries past the limits. + fn insert(&mut self, key: PatternKey, image: &Arc) { + if image.data.len() * 4 > PATTERN_MAX_BYTES / 2 { + return; + } + // Another thread may have built the same key meanwhile: keep its image, but it was just asked for. + match self.0.iter().position(|e| e.key == key) { + Some(i) => { + let e = self.0.remove(i); + self.0.push(e); + } + None => self.0.push(PatternEntry { key, image: Arc::clone(image) }), + } + let bytes = |e: &PatternEntry| e.image.data.len() * 4; + while self.0.len() > PATTERN_MAX_ENTRIES || self.0.iter().map(bytes).sum::() > PATTERN_MAX_BYTES { + self.0.remove(0); + } + } +} + +static PATTERNS: Mutex = Mutex::new(PatternCache::new()); + +/// The key of `(style, size, seed)` with `t`'s levels. Brightness and contrast are keyed on the values +/// [`Texture::level`] uses (clamped, non-finite as 0, `-0.0` as `0.0`), so equal levels share an entry. +fn pattern_key(style: PatternStyle, size: u32, seed: u32, t: &Texture) -> PatternKey { + let level_bits = |v: f32| (if v.is_finite() { v.clamp(-1.0, 1.0) + 0.0 } else { 0.0 }).to_bits(); + PatternKey { style, size: size.clamp(8, 1024), seed, brightness: level_bits(t.brightness), contrast: level_bits(t.contrast), invert: t.invert } +} /// The procedural pattern `(style, size, seed)` with `t`'s levels applied, from the cache when it /// was built recently. pub fn procedural_pattern(style: PatternStyle, size: u32, seed: u32, t: &Texture) -> Arc { - let key = PatternKey { style, size: size.clamp(8, 1024), seed, brightness: t.brightness.to_bits(), contrast: t.contrast.to_bits(), invert: t.invert }; - { - let mut cache = PATTERNS.lock().unwrap_or_else(PoisonError::into_inner); - if let Some(i) = cache.iter().position(|e| e.key == key) { - let e = cache.remove(i); - let image = Arc::clone(&e.image); - cache.push(e); - return image; - } + let key = pattern_key(style, size, seed, t); + if let Some(image) = PATTERNS.lock().unwrap_or_else(PoisonError::into_inner).get(&key) { + return image; } let mut img = crate::procedural::pattern(style, size, seed); for v in &mut img.data { *v = t.level(*v); } let image = Arc::new(img); - let bytes = |e: &PatternEntry| e.image.data.len() * 4; - if image.data.len() * 4 <= PATTERN_MAX_BYTES / 2 { - let mut cache = PATTERNS.lock().unwrap_or_else(PoisonError::into_inner); - // Another thread may have built the same key meanwhile: keep its image, but it was just asked for. - match cache.iter().position(|e| e.key == key) { - Some(i) => { - let e = cache.remove(i); - cache.push(e); - } - None => cache.push(PatternEntry { key, image: Arc::clone(&image) }), - } - while cache.len() > PATTERN_MAX_ENTRIES || cache.iter().map(bytes).sum::() > PATTERN_MAX_BYTES { - cache.remove(0); - } - } + PATTERNS.lock().unwrap_or_else(PoisonError::into_inner).insert(key, &image); image } @@ -98,16 +122,40 @@ mod tests { } } - /// The cache holds a few entries: the oldest one goes first. Seeds are used by no other test, so - /// no hit can refresh `first`. + /// The cache holds a few entries: the oldest one goes first. Runs on a cache this test owns, so + /// no other test can evict or refresh an entry. #[test] fn pattern_cache_evicts_the_oldest_entry_past_its_limit() { let base = Texture::default(); - let first = procedural_pattern(PatternStyle::Noise, 16, 90_001, &base); - assert!(Arc::ptr_eq(&first, &procedural_pattern(PatternStyle::Noise, 16, 90_001, &base))); - for seed in 90_002..90_002 + PATTERN_MAX_ENTRIES as u32 { - procedural_pattern(PatternStyle::Noise, 16, seed, &base); + let mut cache = PatternCache::new(); + let key = |seed| pattern_key(PatternStyle::Noise, 16, seed, &base); + let image = |seed| Arc::new(crate::procedural::pattern(PatternStyle::Noise, 16, seed)); + let first = image(0); + cache.insert(key(0), &first); + assert!(Arc::ptr_eq(&first, &cache.get(&key(0)).unwrap())); + for seed in 1..=PATTERN_MAX_ENTRIES as u32 { + cache.insert(key(seed), &image(seed)); } - assert!(!Arc::ptr_eq(&first, &procedural_pattern(PatternStyle::Noise, 16, 90_001, &base))); + assert!(cache.get(&key(0)).is_none()); + assert!(cache.get(&key(1)).is_some()); + } + + #[test] + fn pattern_cache_shares_an_entry_between_equal_levels() { + let tex = |brightness, contrast| Texture { brightness, contrast, ..Texture::default() }; + let pairs = [ + (tex(2.0, 0.0), tex(1.0, 0.0)), + (tex(-7.5, 0.0), tex(-1.0, 0.0)), + (tex(0.0, 3.0), tex(0.0, 1.0)), + (tex(f32::NAN, 0.0), tex(0.0, 0.0)), + (tex(0.0, f32::INFINITY), tex(0.0, 0.0)), + (tex(-0.0, -0.0), tex(0.0, 0.0)), + ]; + for (a, b) in pairs { + assert!(pattern_key(PatternStyle::Noise, 64, 5, &a) == pattern_key(PatternStyle::Noise, 64, 5, &b)); + let (ia, ib) = (procedural_pattern(PatternStyle::Noise, 64, 5, &a), procedural_pattern(PatternStyle::Noise, 64, 5, &b)); + assert_eq!(ia.data, ib.data); + } + assert!(pattern_key(PatternStyle::Noise, 64, 5, &tex(0.5, 0.0)) != pattern_key(PatternStyle::Noise, 64, 5, &tex(1.0, 0.0))); } }