From d4ea67703de986eb907138148751d9561ed84f7b Mon Sep 17 00:00:00 2001 From: MistyMystery Date: Wed, 4 Nov 2026 22:17:59 +0400 Subject: [PATCH 1/7] Add an asynchronous thumbnail service for layer contents, masks and effect stages The compositor renders a one-layer cut of the stack at 64 px (content in a channel, mask, or the stack up to an effect); the engine keeps an immutable snapshot, a worker thread, an LRU cache and stale-result rejection. --- crates/compose/src/lib.rs | 2 + crates/compose/src/thumb.rs | 155 +++++++++++++ crates/engine/src/lib.rs | 1 + crates/engine/src/thumbs.rs | 396 ++++++++++++++++++++++++++++++++++ crates/engine/tests/thumbs.rs | 294 +++++++++++++++++++++++++ 5 files changed, 848 insertions(+) create mode 100644 crates/compose/src/thumb.rs create mode 100644 crates/engine/src/thumbs.rs create mode 100644 crates/engine/tests/thumbs.rs diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 5e34945c..a72c0922 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -12,6 +12,7 @@ pub mod display; pub mod eval; pub mod pattern; pub mod store; +pub mod thumb; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; @@ -20,3 +21,4 @@ pub use eval::{ mask_image, pad_tiles, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; +pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/src/thumb.rs b/crates/compose/src/thumb.rs new file mode 100644 index 00000000..a5a817e0 --- /dev/null +++ b/crates/compose/src/thumb.rs @@ -0,0 +1,155 @@ +//! Small previews of one layer's content, one mask, or one effect stage, computed without +//! touching the main composite. +//! +//! Every thumbnail is the ordinary compositor run on a *cut* copy of the project: the texture +//! set's stack is replaced by the one layer, the layer is forced visible at Normal / 100 %, and +//! the layer's effect list is truncated after the effect being previewed. The evaluator is the +//! same code the viewport uses (just on a small G-buffer), so a thumbnail always agrees with +//! what the stack really computes. Nothing here mutates the caller's project. + +use texturecraft_core::{BlendMode, Channel, ChannelBlend, ChannelKind, LayerId, Project}; +use texturecraft_texel::linear_to_srgb; + +use crate::eval::{Composite, Inputs, all_tiles, composite_tiles, mask_image}; + +/// Edge length (texels) the thumbnails are computed at. +pub const THUMB_TEXELS: u32 = 64; + +/// What a thumbnail shows. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum ThumbTarget { + /// The content of a layer (content effects included, mask ignored) in `channel`. + Content { layer: LayerId, channel: Channel }, + /// The mask of a layer (an instance without its own mask shows its source's). + Mask { layer: LayerId }, + /// The result up to and including `effect`, in the layer's content (`channel`) or in its + /// mask (the channel is ignored). An effect that is hidden shows the bypassed result. + Stage { effect: LayerId, channel: Channel }, +} + +/// An 8-bit RGBA thumbnail. Alpha is 0 where the mesh does not cover the texture (the view +/// paints its own background there) and 255 elsewhere. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ThumbImage { + pub width: u32, + pub height: u32, + pub rgba: Vec, +} + +/// The thumbnail of `target`, computed at `inp.gbuf`'s size, which must be square (use a +/// [`THUMB_TEXELS`] G-buffer; None otherwise). None for an unknown layer or effect, a layer without that channel, or a +/// mask that does not exist. +pub fn render(inp: &Inputs, target: ThumbTarget) -> Option { + if inp.gbuf.width != inp.gbuf.height { + return None; + } + match target { + ThumbTarget::Content { layer, channel } => content(inp, layer, channel, None), + ThumbTarget::Mask { layer } => mask(inp, layer, None), + ThumbTarget::Stage { effect, channel } => { + let (owner, _) = inp.project.effect(effect)?; + let in_mask = inp.project.layers.get(&owner)?.mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| e.id == effect)); + if in_mask { mask(inp, owner, Some(effect)) } else { content(inp, owner, channel, Some(effect)) } + } + } +} + +/// `project` cut down to the single layer `id` of texture set `ts`: only that layer is drawn, +/// visible, Normal at full opacity in `channel` (when given). +fn solo(project: &Project, ts: usize, id: LayerId, channel: Option) -> Option { + let mut cut = project.clone(); + cut.texture_sets.get_mut(ts)?.stack = vec![id]; + let l = cut.layers.get_mut(&id)?; + l.visible = true; + if let Some(c) = channel { + *l.channels.get_mut(&c)? = ChannelBlend { mode: BlendMode::Normal, opacity: 1.0 }; + } + Some(cut) +} + +/// Keep the effects of `list` up to and including `last`. +fn truncate_after(list: &mut Vec, last: LayerId) -> bool { + match list.iter().position(|e| e.id == last) { + Some(k) => { + list.truncate(k + 1); + true + } + None => false, + } +} + +fn content(inp: &Inputs, layer: LayerId, channel: Channel, upto: Option) -> Option { + let set = inp.project.texture_set(inp.ts).ok()?; + if !set.channel_list().contains(&channel) { + return None; + } + // The layer whose content is drawn: an instance draws its source's effects. + let mut cut = solo(inp.project, inp.ts, layer, Some(channel))?; + let owner = cut.content_layer(layer)?.id; + for id in [layer, owner] { + let l = cut.layers.get_mut(&id)?; + l.mask = None; + l.visible = true; + if let Some(b) = l.channels.get_mut(&channel) { + *b = ChannelBlend { mode: BlendMode::Normal, opacity: 1.0 }; + } + } + if let Some(effect) = upto + && !truncate_after(&mut cut.layers.get_mut(&owner)?.content_effects, effect) + { + return None; + } + let cut_inp = Inputs { project: &cut, preview: None, ..*inp }; + let (w, h) = (inp.gbuf.width, inp.gbuf.height); + let mut comp = Composite::with_size(&set.channel_list(), w, h); + composite_tiles(&cut_inp, &mut comp, &all_tiles(w, h)); + Some(encode_channel(&comp, channel, inp)) +} + +fn mask(inp: &Inputs, layer: LayerId, upto: Option) -> Option { + let mut cut = solo(inp.project, inp.ts, layer, None)?; + let owner = cut.mask_owner(layer); + let m = cut.layers.get_mut(&owner)?.mask.as_mut()?; + m.enabled = true; + if let Some(effect) = upto + && !truncate_after(&mut m.effects, effect) + { + return None; + } + let cut_inp = Inputs { project: &cut, preview: None, ..*inp }; + let (w, h) = (inp.gbuf.width, inp.gbuf.height); + let gray = mask_image(&cut_inp, layer, w)?; + let mut rgba = Vec::with_capacity((w * h) as usize * 4); + for y in 0..h { + for x in 0..w { + let i = (y * w + x) as usize; + let g = gray.get(i).copied().unwrap_or(0); + rgba.extend_from_slice(&[g, g, g, if inp.gbuf.covered(i) { 255 } else { 0 }]); + } + } + Some(ThumbImage { width: w, height: h, rgba }) +} + +/// Encode the composited `channel` for display: colors linear → sRGB, signed values 0 → mid +/// gray, normal maps and scalars as stored (data channels raw). +fn encode_channel(comp: &Composite, channel: Channel, inp: &Inputs) -> ThumbImage { + let (w, h) = (comp.resolution, comp.height); + let mut rgba = Vec::with_capacity((w * h) as usize * 4); + for y in 0..h { + for x in 0..w { + let v = comp.value(channel, x, y); + let px = match channel.kind() { + ChannelKind::Color => v.map(|c| to_byte(linear_to_srgb(c.clamp(0.0, 1.0)))), + ChannelKind::Signed => v.map(|c| to_byte(c * 0.5 + 0.5)), + ChannelKind::Scalar | ChannelKind::NormalMap => v.map(to_byte), + }; + let covered = inp.gbuf.covered((y * w + x) as usize); + rgba.extend_from_slice(&[px[0], px[1], px[2], if covered { 255 } else { 0 }]); + } + } + ThumbImage { width: w, height: h, rgba } +} + +fn to_byte(v: f32) -> u8 { + if v.is_finite() { (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8 } else { 0 } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ed07d645..20aa19f9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -44,6 +44,7 @@ pub mod set_cmds; pub mod smart_masks; pub mod template_cmds; pub mod text_cmds; +pub mod thumbs; pub mod tool_cmds; pub mod uv_tile_cmds; pub mod view_cmds; diff --git a/crates/engine/src/thumbs.rs b/crates/engine/src/thumbs.rs new file mode 100644 index 00000000..6ee7dda4 --- /dev/null +++ b/crates/engine/src/thumbs.rs @@ -0,0 +1,396 @@ +//! Asynchronous layer-panel thumbnails. +//! +//! The panel asks for small previews of layer contents, masks and effect stages +//! ([`ThumbTarget`]). The work never runs on the UI thread and never touches the main composite: +//! +//! * A **snapshot** ([`ThumbSnapshot`]) is an immutable copy of what the compositor reads (the +//! project, copy-on-write pixel tiles, baked maps, images and the mesh) plus a 64 px G-buffer. +//! It is rebuilt only when the document really changed, at most every [`DEBOUNCE`] seconds +//! (a slider drag renders at that pace, not once per frame). +//! * A **worker thread** evaluates one target at a time from a snapshot with +//! [`texturecraft_compose::thumb::render`]. On wasm32 (no threads) one job runs per +//! [`ThumbService::poll`] instead. +//! * Results are kept in a small LRU **cache** ([`CACHE_ENTRIES`]). A result computed from an +//! older snapshot than the current one is dropped, so a slow job can never overwrite a newer +//! thumbnail. An entry that is out of date keeps showing until its replacement arrives. +//! * Only targets requested during the current frame are rendered: a row that scrolled away +//! before its turn is dropped from the queue. + +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, ImageStore, Inputs, PixelStore, THUMB_TEXELS, ThumbImage, ThumbTarget, thumb}; +use texturecraft_core::Project; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, UvGBuffer}; + +use crate::Session; + +/// Thumbnails kept. +pub const CACHE_ENTRIES: usize = 96; +/// Seconds between checks for a changed document while it keeps changing. +pub const DEBOUNCE: f64 = 0.12; +/// Jobs handed to the worker at once (the rest wait here, where they can still be dropped). +const IN_FLIGHT: usize = 2; + +/// An immutable copy of everything the thumbnails of one texture set read. +pub struct ThumbSnapshot { + ts: usize, + mesh_id: u64, + project: Project, + pixels: PixelStore, + baked: BakedMaps, + images: ImageStore, + mesh: Arc, + gbuf: Arc, + bounds: (Vec3, Vec3), +} + +impl ThumbSnapshot { + /// Snapshot texture set `ts` of `s`, with the G-buffer from `gbufs` (built on a miss). + pub fn new(s: &Session, ts: usize, gbufs: &mut GbufCache) -> Option { + let material = s.doc.project.texture_set(ts).ok()?.material; + let gbuf = gbufs.get(&s.mesh, s.mesh_id, material); + Some(ThumbSnapshot { + ts, + mesh_id: s.mesh_id, + project: s.doc.project.clone(), + pixels: s.doc.pixels.clone(), + baked: s.doc.baked.get(&ts).cloned().unwrap_or_default(), + images: s.images.clone(), + mesh: s.mesh.clone(), + gbuf, + bounds: s.mesh.bounds(), + }) + } + + /// Whether `s` would give the same thumbnails as this snapshot. + fn matches(&self, s: &Session, ts: usize) -> bool { + let same_pixels = self.pixels.layers.len() == s.doc.pixels.layers.len() + && self.pixels.masks.len() == s.doc.pixels.masks.len() + && self.pixels.layers.iter().all(|(k, v)| s.doc.pixels.layers.get(k) == Some(v)) + && self.pixels.masks.iter().all(|(k, v)| s.doc.pixels.masks.get(k) == Some(v)); + let none = BakedMaps::default(); + let baked = s.doc.baked.get(&ts).unwrap_or(&none); + self.ts == ts + && self.mesh_id == s.mesh_id + && self.project == s.doc.project + && same_pixels + && self.baked == *baked + && self.images.len() == s.images.len() + && self.images.iter().all(|(k, v)| s.images.get(k).is_some_and(|o| Arc::ptr_eq(o, v))) + } + + /// Render `target`: the work of one job. + pub fn render(&self, target: ThumbTarget) -> Option { + let inp = Inputs { + project: &self.project, + ts: self.ts, + mesh: &self.mesh, + gbuf: &self.gbuf, + pixels: &self.pixels, + baked: &self.baked, + preview: None, + images: &self.images, + bounds: self.bounds, + }; + thumb::render(&inp, target) + } + + /// Whether the layer or effect `target` shows still exists in the snapshot's project. + fn has(&self, target: ThumbTarget) -> bool { + has_target(&self.project, target) + } +} + +fn has_target(p: &Project, target: ThumbTarget) -> bool { + match target { + ThumbTarget::Content { layer, .. } | ThumbTarget::Mask { layer } => p.layers.contains_key(&layer), + ThumbTarget::Stage { effect, .. } => p.effect(effect).is_some(), + } +} + +/// The 64 px G-buffers built so far, per mesh and material (rasterizing is the one part of a +/// snapshot that is not just copying handles). +#[derive(Default)] +pub struct GbufCache { + map: HashMap<(u64, usize), Arc>, +} + +impl GbufCache { + fn get(&mut self, mesh: &Mesh, mesh_id: u64, material: usize) -> Arc { + if self.map.len() > 16 { + self.map.clear(); + } + self.map.entry((mesh_id, material)).or_insert_with(|| Arc::new(UvGBuffer::new(mesh, material, THUMB_TEXELS, THUMB_TEXELS))).clone() + } +} + +struct Entry { + /// None: the target has nothing to show (a layer without that channel). + image: Option>, + /// Snapshot generation it was rendered from. + generation: u64, + /// Changes whenever `image` does (views key their GPU textures on it). + version: u64, + used: u64, +} + +/// What the panel draws for one target. +#[derive(Clone)] +pub struct ThumbView { + pub image: Option>, + /// Identifies `image`; changes when a new picture arrives. + pub version: u64, + /// A newer picture is on its way. + pub pending: bool, +} + +struct Job { + snapshot: Arc, + generation: u64, + target: ThumbTarget, +} + +struct Done { + generation: u64, + target: ThumbTarget, + image: Option, +} + +#[cfg(not(target_arch = "wasm32"))] +struct Worker { + tx: std::sync::mpsc::Sender, + rx: std::sync::mpsc::Receiver, +} + +#[cfg(not(target_arch = "wasm32"))] +fn spawn_worker() -> Option { + let (tx, jobs) = std::sync::mpsc::channel::(); + let (done_tx, rx) = std::sync::mpsc::channel::(); + std::thread::Builder::new() + .name("layer-thumbs".into()) + .spawn(move || { + while let Ok(job) = jobs.recv() { + let image = job.snapshot.render(job.target); + if done_tx.send(Done { generation: job.generation, target: job.target, image }).is_err() { + break; + } + } + }) + .ok()?; + Some(Worker { tx, rx }) +} + +/// The thumbnail cache and its worker. One lives in the UI; see the module documentation. +pub struct ThumbService { + snapshot: Option>, + /// Bumps whenever the snapshot's content changes; entries and jobs carry it. + generation: u64, + /// The session revision the snapshot was last compared with. + seen: Option, + last_check: f64, + cache: HashMap, + tick: u64, + versions: u64, + queue: VecDeque, + in_flight: HashSet, + wanted: HashSet, + gbufs: GbufCache, + #[cfg(not(target_arch = "wasm32"))] + worker: Option, + #[cfg(not(target_arch = "wasm32"))] + spawned: bool, + /// Jobs run inline (wasm32, or no worker thread could start). + inline: VecDeque, + /// Pictures computed (tests, benchmarks). + pub rendered: u64, +} + +impl Default for ThumbService { + fn default() -> Self { + ThumbService { + snapshot: None, + generation: 0, + seen: None, + last_check: f64::NEG_INFINITY, + cache: HashMap::new(), + tick: 0, + versions: 0, + queue: VecDeque::new(), + in_flight: HashSet::new(), + wanted: HashSet::new(), + gbufs: GbufCache::default(), + #[cfg(not(target_arch = "wasm32"))] + worker: None, + #[cfg(not(target_arch = "wasm32"))] + spawned: false, + inline: VecDeque::new(), + rendered: 0, + } + } +} + +impl ThumbService { + pub fn new() -> ThumbService { + ThumbService::default() + } + + /// Start of a frame: forget what the last frame asked for and notice document changes. + pub fn begin_frame(&mut self, s: &Session, now: f64) { + self.wanted.clear(); + let ts = s.ts(); + if self.seen == Some(s.revision) && self.snapshot.as_ref().is_some_and(|sn| sn.ts == ts && sn.mesh_id == s.mesh_id) { + return; + } + // While the document keeps changing, compare at the debounce pace (the first look is immediate). + if self.snapshot.is_some() && now - self.last_check < DEBOUNCE { + return; + } + self.last_check = now; + if self.snapshot.as_ref().is_some_and(|sn| sn.matches(s, ts)) { + self.seen = Some(s.revision); + return; + } + self.snapshot = ThumbSnapshot::new(s, ts, &mut self.gbufs).map(Arc::new); + self.seen = Some(s.revision); + self.generation += 1; + // Jobs of the old snapshot are not worth running (those in flight are dropped on arrival). + self.queue.clear(); + self.inline.clear(); + self.in_flight.clear(); + if let Some(sn) = &self.snapshot { + self.cache.retain(|t, _| sn.has(*t)); + } else { + self.cache.clear(); + } + } + + /// Whether the displayed pictures wait for a document comparison that is still debounced. + fn checked(&self, s: &Session) -> bool { + self.seen == Some(s.revision) + } + + /// The picture for `target` (call for the rows on screen only). Queues work when the + /// picture is missing or out of date. + pub fn get(&mut self, s: &Session, target: ThumbTarget) -> ThumbView { + self.wanted.insert(target); + self.tick += 1; + let fresh = self.cache.get(&target).is_some_and(|e| e.generation == self.generation); + let checked = self.checked(s); + if !fresh && checked && self.snapshot.is_some() && !self.in_flight.contains(&target) && !self.queue.contains(&target) { + self.queue.push_back(target); + } + let tick = self.tick; + match self.cache.get_mut(&target) { + Some(e) => { + e.used = tick; + ThumbView { image: e.image.clone(), version: e.version, pending: !(fresh && checked) } + } + None => ThumbView { image: None, version: 0, pending: true }, + } + } + + /// End of a frame: take finished pictures, drop queued rows nobody asked for, hand the worker + /// its next jobs. Returns whether more work is outstanding (ask for another frame). + pub fn poll(&mut self, s: &Session) -> bool { + self.collect(); + let wanted = &self.wanted; + self.queue.retain(|t| wanted.contains(t)); + self.dispatch(); + self.trim(); + !self.queue.is_empty() || !self.in_flight.is_empty() || !self.inline.is_empty() || !self.checked(s) + } + + fn dispatch(&mut self) { + let Some(snapshot) = self.snapshot.clone() else { return }; + while self.in_flight.len() + self.inline.len() < IN_FLIGHT { + let Some(target) = self.queue.pop_front() else { break }; + let job = Job { snapshot: snapshot.clone(), generation: self.generation, target }; + self.in_flight.insert(target); + if !self.send(job) { + break; + } + } + } + + #[cfg(not(target_arch = "wasm32"))] + fn send(&mut self, job: Job) -> bool { + if !self.spawned { + self.spawned = true; + self.worker = spawn_worker(); + } + match &self.worker { + Some(w) => match w.tx.send(job) { + Ok(()) => true, + Err(e) => { + // The worker is gone: run this and the rest here. + self.worker = None; + self.inline.push_back(e.0); + true + } + }, + None => { + self.inline.push_back(job); + true + } + } + } + + #[cfg(target_arch = "wasm32")] + fn send(&mut self, job: Job) -> bool { + self.inline.push_back(job); + true + } + + fn collect(&mut self) { + let mut done: Vec = Vec::new(); + #[cfg(not(target_arch = "wasm32"))] + if let Some(w) = &self.worker { + while let Ok(d) = w.rx.try_recv() { + done.push(d); + } + } + // Without a thread one job runs per frame, so the interface keeps its pace. + if let Some(job) = self.inline.pop_front() { + let image = job.snapshot.render(job.target); + done.push(Done { generation: job.generation, target: job.target, image }); + } + for d in done { + self.rendered += 1; + // A picture of an older snapshot never replaces a newer one. + if d.generation != self.generation { + continue; + } + self.in_flight.remove(&d.target); + if !self.snapshot.as_ref().is_some_and(|sn| sn.has(d.target)) { + continue; + } + self.versions += 1; + let entry = Entry { image: d.image.map(Arc::new), generation: d.generation, version: self.versions, used: self.tick }; + self.cache.insert(d.target, entry); + } + } + + fn trim(&mut self) { + while self.cache.len() > CACHE_ENTRIES { + let Some(oldest) = self.cache.iter().filter(|(t, _)| !self.wanted.contains(t)).min_by_key(|(_, e)| e.used).map(|(t, _)| *t) else { break }; + self.cache.remove(&oldest); + } + } + + /// Entries held (tests). + pub fn cached(&self) -> usize { + self.cache.len() + } + + /// Whether `target` has a picture of the current snapshot (tests). + pub fn is_fresh(&self, target: ThumbTarget) -> bool { + self.cache.get(&target).is_some_and(|e| e.generation == self.generation) + } + + /// Whether any work is queued or running (tests). + pub fn busy(&self) -> bool { + !self.queue.is_empty() || !self.in_flight.is_empty() || !self.inline.is_empty() + } +} diff --git a/crates/engine/tests/thumbs.rs b/crates/engine/tests/thumbs.rs new file mode 100644 index 00000000..05fb52ba --- /dev/null +++ b/crates/engine/tests/thumbs.rs @@ -0,0 +1,294 @@ +//! Layer-panel thumbnails: they equal a plain CPU evaluation of the same sub-stack at 64 px, +//! follow edits, drop stale and vanished work, and only render what was asked for. + +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; +use texturecraft_engine::compose::{Composite, Inputs, ThumbImage, ThumbTarget, all_tiles, composite_tiles, mask_image}; +use texturecraft_engine::core::{Channel, ChannelKind, LayerId}; +use texturecraft_engine::geom::UvGBuffer; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::texel::linear_to_srgb; +use texturecraft_engine::thumbs::{CACHE_ENTRIES, ThumbService}; +use texturecraft_engine::{Session, execute}; + +const N: u32 = 64; + +fn session() -> Session { + Session::new_project("t", primitives::sphere(1.0, 32, 16), "builtin:sphere", None, 256).unwrap() +} + +fn id(v: Value, key: &str) -> LayerId { + LayerId(v[key].as_u64().unwrap()) +} + +/// A fill layer with two content effects (invert, then posterize) and a masked generator. +struct Stack { + layer: LayerId, + invert: LayerId, + posterize: LayerId, + gen_: LayerId, +} + +fn stack(s: &mut Session) -> Stack { + let layer = id(execute(s, "layer.add.fill", &json!({"color": "#336699", "roughness": 0.2})).unwrap(), "layer"); + let invert = id(execute(s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect"); + let posterize = id(execute(s, "effect.add.filter", &json!({"target": "content", "filter": "posterize"})).unwrap(), "effect"); + execute(s, "mask.add.black", &Value::Null).unwrap(); + let gen_ = id(execute(s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect"); + Stack { layer, invert, posterize, gen_ } +} + +fn inputs<'a>(s: &'a Session, project: &'a texturecraft_engine::core::Project, gbuf: &'a UvGBuffer) -> Inputs<'a> { + let none = Default::default(); + // Leaked: the oracle only lives for the test. + let baked: &'a _ = Box::leak(Box::new(s.doc.baked.get(&0).cloned().unwrap_or(none))); + Inputs { project, ts: 0, mesh: &s.mesh, gbuf, pixels: &s.doc.pixels, baked, preview: None, images: &s.images, bounds: s.mesh.bounds() } +} + +/// The reference: the same sub-stack built by hand and composited at 64 px with the ordinary +/// evaluator, then encoded for display. +fn oracle(s: &Session, target: ThumbTarget) -> ThumbImage { + let gbuf = UvGBuffer::new(&s.mesh, 0, N, N); + let mut p = s.doc.project.clone(); + let (layer, upto, channel) = match target { + ThumbTarget::Content { layer, channel } => (layer, None, channel), + ThumbTarget::Mask { layer } => (layer, None, Channel::BaseColor), + ThumbTarget::Stage { effect, channel } => (p.effect(effect).unwrap().0, Some(effect), channel), + }; + p.texture_sets[0].stack = vec![layer]; + let l = p.layers.get_mut(&layer).unwrap(); + l.visible = true; + let in_mask = upto.is_some_and(|e| l.mask.as_ref().is_some_and(|m| m.effects.iter().any(|x| x.id == e))) || matches!(target, ThumbTarget::Mask { .. }); + if in_mask { + let m = l.mask.as_mut().unwrap(); + m.enabled = true; + if let Some(e) = upto { + let k = m.effects.iter().position(|x| x.id == e).unwrap(); + m.effects.truncate(k + 1); + } + let gray = mask_image(&inputs(s, &p, &gbuf), layer, N).unwrap(); + let rgba = gray.iter().enumerate().flat_map(|(i, g)| [*g, *g, *g, if gbuf.covered(i) { 255 } else { 0 }]).collect(); + return ThumbImage { width: N, height: N, rgba }; + } + l.mask = None; + l.channels.insert(channel, texturecraft_engine::core::ChannelBlend::default()); + if let Some(e) = upto { + let k = l.content_effects.iter().position(|x| x.id == e).unwrap(); + l.content_effects.truncate(k + 1); + } + let channels = p.texture_set(0).unwrap().channel_list(); + let mut comp = Composite::new(&channels, N); + composite_tiles(&inputs(s, &p, &gbuf), &mut comp, &all_tiles(N, N)); + let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let mut rgba = Vec::new(); + for y in 0..N { + for x in 0..N { + let v = comp.value(channel, x, y); + let px = match channel.kind() { + ChannelKind::Color => v.map(|c| byte(linear_to_srgb(c.clamp(0.0, 1.0)))), + ChannelKind::Signed => v.map(|c| byte(c * 0.5 + 0.5)), + _ => v.map(byte), + }; + rgba.extend_from_slice(&[px[0], px[1], px[2], if gbuf.covered((y * N + x) as usize) { 255 } else { 0 }]); + } + } + ThumbImage { width: N, height: N, rgba } +} + +/// Frames of `svc` until every target is current (or a timeout). +fn settle(svc: &mut ThumbService, s: &Session, targets: &[ThumbTarget], clock: &mut f64) { + let t0 = Instant::now(); + loop { + *clock += 0.2; + svc.begin_frame(s, *clock); + for t in targets { + svc.get(s, *t); + } + svc.poll(s); + if targets.iter().all(|t| svc.is_fresh(*t)) { + return; + } + assert!(t0.elapsed() < Duration::from_secs(60), "thumbnails never settled"); + std::thread::sleep(Duration::from_millis(2)); + } +} + +fn image(svc: &mut ThumbService, s: &Session, t: ThumbTarget) -> ThumbImage { + (*svc.get(s, t).image.expect("a picture")).clone() +} + +#[test] +fn thumbnails_equal_a_cpu_evaluation_of_the_same_sub_stack() { + let mut s = session(); + let st = stack(&mut s); + let base = Channel::BaseColor; + let targets = [ + ThumbTarget::Content { layer: st.layer, channel: base }, + ThumbTarget::Content { layer: st.layer, channel: Channel::Roughness }, + ThumbTarget::Mask { layer: st.layer }, + ThumbTarget::Stage { effect: st.invert, channel: base }, + ThumbTarget::Stage { effect: st.posterize, channel: base }, + ThumbTarget::Stage { effect: st.gen_, channel: base }, + ]; + let (mut svc, mut clock) = (ThumbService::new(), 0.0); + settle(&mut svc, &s, &targets, &mut clock); + for t in targets { + assert_eq!(image(&mut svc, &s, t), oracle(&s, t), "{t:?}"); + } + // Sanity on the values themselves: the first stage is #336699 inverted (in linear light). + let inv = image(&mut svc, &s, targets[3]); + let px = inv.rgba.chunks_exact(4).find(|p| p[3] == 255).unwrap(); + let expect = |byte: f32| (linear_to_srgb(1.0 - texturecraft_engine::texel::srgb_to_linear(byte / 255.0)) * 255.0 + 0.5) as i32; + assert!((px[0] as i32 - expect(51.0)).abs() <= 1 && (px[2] as i32 - expect(153.0)).abs() <= 1, "{px:?}"); + // The mask thumbnail is gray and not flat (a position gradient on a black mask). + let m = image(&mut svc, &s, targets[2]); + let grays: Vec = m.rgba.chunks_exact(4).filter(|p| p[3] == 255).map(|p| p[0]).collect(); + assert!(grays.iter().max() != grays.iter().min()); +} + +#[test] +fn earlier_stages_never_show_later_effects_and_hidden_effects_are_bypassed() { + let mut s = session(); + let st = stack(&mut s); + let base = Channel::BaseColor; + let (first, second) = (ThumbTarget::Stage { effect: st.invert, channel: base }, ThumbTarget::Stage { effect: st.posterize, channel: base }); + let (mut svc, mut clock) = (ThumbService::new(), 0.0); + settle(&mut svc, &s, &[first, second], &mut clock); + let (a, b) = (image(&mut svc, &s, first), image(&mut svc, &s, second)); + // Hide the second effect: its stage now shows the first one's result; the first is unchanged. + execute(&mut s, "effect.set", &json!({"effect": st.posterize.0, "visible": false})).unwrap(); + settle(&mut svc, &s, &[first, second], &mut clock); + assert_eq!(image(&mut svc, &s, first), a); + assert_eq!(image(&mut svc, &s, second), a); + assert_ne!(a, b, "posterize should change something for the test to mean anything"); + // And the content thumbnail (everything) follows. + let all = ThumbTarget::Content { layer: st.layer, channel: base }; + settle(&mut svc, &s, &[all], &mut clock); + assert_eq!(image(&mut svc, &s, all), a); +} + +#[test] +fn editing_invalidates_and_unrelated_changes_do_not() { + let mut s = session(); + let st = stack(&mut s); + let t = ThumbTarget::Content { layer: st.layer, channel: Channel::BaseColor }; + let (mut svc, mut clock) = (ThumbService::new(), 0.0); + settle(&mut svc, &s, &[t], &mut clock); + let before = image(&mut svc, &s, t); + let rendered = svc.rendered; + // A camera move changes the session revision but no thumbnail input: nothing is re-rendered. + execute(&mut s, "camera.set", &json!({"yaw": 0.7})).ok(); + s.revision += 1; + for _ in 0..3 { + clock += 0.3; + svc.begin_frame(&s, clock); + svc.get(&s, t); + svc.poll(&s); + } + assert!(svc.is_fresh(t)); + assert_eq!(svc.rendered, rendered, "an unrelated change re-rendered a thumbnail"); + // An edit of the layer re-renders it, and the new picture is the new oracle. + execute(&mut s, "effect.set", &json!({"effect": st.invert.0, "visible": false})).unwrap(); + clock += 0.3; + svc.begin_frame(&s, clock); + assert!(!svc.is_fresh(t)); + settle(&mut svc, &s, &[t], &mut clock); + let after = image(&mut svc, &s, t); + assert_ne!(before, after); + assert_eq!(after, oracle(&s, t)); + // Undo brings the first picture back. + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + settle(&mut svc, &s, &[t], &mut clock); + assert_eq!(image(&mut svc, &s, t), before); +} + +#[test] +fn deleting_a_layer_with_a_pending_thumbnail_is_harmless() { + let mut s = session(); + let st = stack(&mut s); + let (a, b) = (ThumbTarget::Content { layer: st.layer, channel: Channel::BaseColor }, ThumbTarget::Mask { layer: st.layer }); + let mut svc = ThumbService::new(); + // Queue the work and hand it to the worker, then delete the layer before collecting. + svc.begin_frame(&s, 1.0); + svc.get(&s, a); + svc.get(&s, b); + svc.poll(&s); + execute(&mut s, "layer.remove", &json!({"layer": st.layer.0})).unwrap(); + let mut clock = 2.0; + for _ in 0..200 { + clock += 0.2; + svc.begin_frame(&s, clock); + // The row is gone, so nobody asks for it any more; the pending result is dropped. + svc.poll(&s); + std::thread::sleep(Duration::from_millis(2)); + } + assert!(!svc.is_fresh(a) && !svc.is_fresh(b)); + assert_eq!(svc.cached(), 0); + assert!(!svc.busy()); + // Asking for a layer that no longer exists renders nothing and does not panic either. + settle_gone(&mut svc, &s, a, &mut clock); +} + +fn settle_gone(svc: &mut ThumbService, s: &Session, t: ThumbTarget, clock: &mut f64) { + for _ in 0..20 { + *clock += 0.2; + svc.begin_frame(s, *clock); + svc.get(s, t); + svc.poll(s); + std::thread::sleep(Duration::from_millis(2)); + } + assert!(svc.get(s, t).image.is_none()); +} + +#[test] +fn a_result_of_an_older_document_never_replaces_a_newer_one() { + let mut s = session(); + let st = stack(&mut s); + let t = ThumbTarget::Content { layer: st.layer, channel: Channel::BaseColor }; + let mut svc = ThumbService::new(); + svc.begin_frame(&s, 1.0); + svc.get(&s, t); + svc.poll(&s); // the job of the first document is running + execute(&mut s, "effect.set", &json!({"effect": st.invert.0, "visible": false})).unwrap(); + let mut clock = 2.0; + settle(&mut svc, &s, &[t], &mut clock); + // Whatever the first job returned, what is shown is the current document. + assert_eq!(image(&mut svc, &s, t), oracle(&s, t)); +} + +#[test] +fn only_requested_rows_render_and_the_cache_is_bounded() { + let mut s = session(); + let layers: Vec = (0..(CACHE_ENTRIES + 30)).map(|_| id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap(), "layer")).collect(); + let target = |l: LayerId| ThumbTarget::Content { layer: l, channel: Channel::BaseColor }; + let mut svc = ThumbService::new(); + // A frame asks for six rows, the next frame (scrolled) for only one of them. + svc.begin_frame(&s, 1.0); + for l in &layers[..6] { + svc.get(&s, target(*l)); + } + svc.poll(&s); + let mut clock = 2.0; + for _ in 0..300 { + clock += 0.2; + svc.begin_frame(&s, clock); + svc.get(&s, target(layers[0])); + svc.poll(&s); + std::thread::sleep(Duration::from_millis(1)); + } + assert!(svc.is_fresh(target(layers[0]))); + // At most the rows already on their way (the in-flight limit) finished besides it. + let done = layers[..6].iter().filter(|l| svc.is_fresh(target(**l))).count(); + assert!(done <= 3, "{done} of the scrolled-away rows were rendered"); + // Scrolling through every layer keeps the cache within its limit. + for chunk in layers.chunks(12) { + let ts: Vec = chunk.iter().map(|l| target(*l)).collect(); + settle(&mut svc, &s, &ts, &mut clock); + assert!(svc.cached() <= CACHE_ENTRIES + 12, "{}", svc.cached()); + } + clock += 0.2; + svc.begin_frame(&s, clock); + svc.poll(&s); + assert!(svc.cached() <= CACHE_ENTRIES, "{}", svc.cached()); +} From 11d889dbf57c0ffb8e775a9086610e964b1d91a7 Mon Sep 17 00:00:00 2001 From: MistyMystery Date: Wed, 4 Nov 2026 22:17:59 +0400 Subject: [PATCH 2/7] Redesign the Layers panel rows with live thumbnails Layer rows are 48 points tall with alternating shades, hover, an accent edge on the selected row and a divider under each layer. Each row shows its content thumbnail (the layer's own result in the displayed channel) and its mask thumbnail, each selectable on its own; a subtitle names the layer type and effect count; blend mode and opacity stack on the right. Effects hang under their layer on tree lines in "Content effects" and "Mask effects" groups that fold without touching the document, each with a thumbnail of the stack up to and including it (a hidden effect shows what it bypasses, struck through). Folder contents indent with lines. Paint and fill thumbnails show their own coverage over a checkerboard; folders composite their children. Every size derives from layer_panel::layer_preview_size, so a preview size setting plugs in there. New strings are translated in every shipped language. --- crates/compose/src/thumb.rs | 61 ++++- crates/engine/tests/perf.rs | 47 ++++ crates/engine/tests/thumbs.rs | 47 +++- crates/ui-egui/src/dock.rs | 326 ++++++++++++++++++++------- crates/ui-egui/src/i18n/ar.rs | 8 + crates/ui-egui/src/i18n/de.rs | 8 + crates/ui-egui/src/i18n/es.rs | 8 + crates/ui-egui/src/i18n/fr.rs | 8 + crates/ui-egui/src/i18n/it.rs | 8 + crates/ui-egui/src/i18n/ja.rs | 8 + crates/ui-egui/src/i18n/ko.rs | 8 + crates/ui-egui/src/i18n/pt_br.rs | 8 + crates/ui-egui/src/i18n/zh_hans.rs | 8 + crates/ui-egui/src/layer_panel.rs | 87 +++++++ crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/tests/layers_panel.rs | 96 ++++++++ crates/ui-egui/tests/ui_snapshots.rs | 35 ++- docs/architecture.md | 20 ++ 18 files changed, 693 insertions(+), 102 deletions(-) create mode 100644 crates/ui-egui/src/layer_panel.rs create mode 100644 crates/ui-egui/tests/layers_panel.rs diff --git a/crates/compose/src/thumb.rs b/crates/compose/src/thumb.rs index a5a817e0..6a246d79 100644 --- a/crates/compose/src/thumb.rs +++ b/crates/compose/src/thumb.rs @@ -8,9 +8,9 @@ //! what the stack really computes. Nothing here mutates the caller's project. use texturecraft_core::{BlendMode, Channel, ChannelBlend, ChannelKind, LayerId, Project}; -use texturecraft_texel::linear_to_srgb; +use texturecraft_texel::{TILE, from_u16, from_u16_signed, linear_to_srgb}; -use crate::eval::{Composite, Inputs, all_tiles, composite_tiles, mask_image}; +use crate::eval::{Composite, FlatTile, Inputs, all_tiles, composite_tiles, flatten_layer, mask_image}; /// Edge length (texels) the thumbnails are computed at. pub const THUMB_TEXELS: u32 = 64; @@ -27,8 +27,9 @@ pub enum ThumbTarget { Stage { effect: LayerId, channel: Channel }, } -/// An 8-bit RGBA thumbnail. Alpha is 0 where the mesh does not cover the texture (the view -/// paints its own background there) and 255 elsewhere. +/// An 8-bit RGBA thumbnail (straight alpha). Alpha is 0 where the mesh does not cover the +/// texture and, for a paint or fill layer's content, where the layer has nothing; the view +/// paints its own background there. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ThumbImage { pub width: u32, @@ -101,11 +102,57 @@ fn content(inp: &Inputs, layer: LayerId, channel: Channel, upto: Option } let cut_inp = Inputs { project: &cut, preview: None, ..*inp }; let (w, h) = (inp.gbuf.width, inp.gbuf.height); + // A paint or fill layer shows its own coverage (transparent where nothing is painted); a + // folder shows its children composited over the channel's default. + if !cut.layers.get(&owner)?.is_group() { + let flat = flatten_layer(&cut_inp, layer, &all_tiles(w, h))?; + return Some(encode_flat(&flat, channel, w, h)); + } let mut comp = Composite::with_size(&set.channel_list(), w, h); composite_tiles(&cut_inp, &mut comp, &all_tiles(w, h)); Some(encode_channel(&comp, channel, inp)) } +/// Encode the flattened (premultiplied value, coverage) tiles of `channel`: alpha is coverage. +fn encode_flat(flat: &[FlatTile], channel: Channel, w: u32, h: u32) -> ThumbImage { + let mut rgba = vec![0u8; (w * h) as usize * 4]; + let comps = channel.components(); + let signed = channel.kind() == ChannelKind::Signed; + for (c, (tx, ty), buf) in flat { + if *c != channel { + continue; + } + for (o, px) in buf.chunks_exact(comps + 1).enumerate() { + let (x, y) = (tx * TILE + o as u32 % TILE, ty * TILE + o as u32 / TILE); + let a = px.get(comps).map_or(0.0, |v| from_u16(*v)); + if x >= w || y >= h || a <= 0.0 { + continue; + } + let mut v = [0.0f32; 3]; + for (k, slot) in v.iter_mut().enumerate() { + let raw = px.get(k.min(comps - 1)).copied().unwrap_or(0); + *slot = if signed { from_u16_signed(raw) } else { from_u16(raw) } / a; + } + let p = display(channel, v); + let i = ((y * w + x) * 4) as usize; + if let Some(d) = rgba.get_mut(i..i + 4) { + d.copy_from_slice(&[p[0], p[1], p[2], to_byte(a)]); + } + } + } + ThumbImage { width: w, height: h, rgba } +} + +/// A channel value as display bytes: colors linear → sRGB, signed values with 0 at mid gray, +/// normal maps and scalars as stored. +fn display(channel: Channel, v: [f32; 3]) -> [u8; 3] { + match channel.kind() { + ChannelKind::Color => v.map(|c| to_byte(linear_to_srgb(c.clamp(0.0, 1.0)))), + ChannelKind::Signed => v.map(|c| to_byte(c * 0.5 + 0.5)), + ChannelKind::Scalar | ChannelKind::NormalMap => v.map(to_byte), + } +} + fn mask(inp: &Inputs, layer: LayerId, upto: Option) -> Option { let mut cut = solo(inp.project, inp.ts, layer, None)?; let owner = cut.mask_owner(layer); @@ -138,11 +185,7 @@ fn encode_channel(comp: &Composite, channel: Channel, inp: &Inputs) -> ThumbImag for y in 0..h { for x in 0..w { let v = comp.value(channel, x, y); - let px = match channel.kind() { - ChannelKind::Color => v.map(|c| to_byte(linear_to_srgb(c.clamp(0.0, 1.0)))), - ChannelKind::Signed => v.map(|c| to_byte(c * 0.5 + 0.5)), - ChannelKind::Scalar | ChannelKind::NormalMap => v.map(to_byte), - }; + let px = display(channel, v); let covered = inp.gbuf.covered((y * w + x) as usize); rgba.extend_from_slice(&[px[0], px[1], px[2], if covered { 255 } else { 0 }]); } diff --git a/crates/engine/tests/perf.rs b/crates/engine/tests/perf.rs index eeee7662..e4691b6a 100644 --- a/crates/engine/tests/perf.rs +++ b/crates/engine/tests/perf.rs @@ -350,3 +350,50 @@ fn bench_8k_resize() { println!("[resize] dilation {:.2?}", t.elapsed()); drop(d); } + +/// Layer-panel thumbnails on the 4K stack: the snapshot, each kind of picture, and a whole panel. +#[test] +#[ignore] +fn bench_layer_thumbs_4k() { + use texturecraft_engine::compose::ThumbTarget; + use texturecraft_engine::core::Channel; + use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot}; + let s = stack(4096); + let ts = s.ts(); + let mut gbufs = GbufCache::default(); + let t = Instant::now(); + let snap = ThumbSnapshot::new(&s, ts, &mut gbufs).unwrap(); + let first = t.elapsed(); + let t = Instant::now(); + let _again = ThumbSnapshot::new(&s, ts, &mut gbufs).unwrap(); + let cached = t.elapsed(); + let p = &s.doc.project; + let mut targets = Vec::new(); + for l in p.layers.values() { + targets.push(("content", ThumbTarget::Content { layer: l.id, channel: Channel::BaseColor })); + if l.mask.is_some() { + targets.push(("mask", ThumbTarget::Mask { layer: l.id })); + } + for e in l.mask.iter().flat_map(|m| m.effects.iter()).chain(l.content_effects.iter()) { + targets.push(("stage", ThumbTarget::Stage { effect: e.id, channel: Channel::BaseColor })); + } + } + let mut per: std::collections::BTreeMap<&str, (Duration, usize, Duration)> = Default::default(); + let all = Instant::now(); + for (kind, target) in &targets { + let t = Instant::now(); + let _ = snap.render(*target); + let d = t.elapsed(); + let e = per.entry(kind).or_default(); + e.0 += d; + e.1 += 1; + e.2 = e.2.max(d); + } + let total = all.elapsed(); + eprintln!("layer thumbnails, 4096 set, {} layers, 64 px:", p.layers.len()); + eprintln!(" snapshot: {:.2} ms first (with the 64 px G-buffer), {:.2} ms after", first.as_secs_f64() * 1e3, cached.as_secs_f64() * 1e3); + for (kind, (sum, n, max)) in per { + eprintln!(" {kind:8} {n:3} × avg {:.2} ms, max {:.2} ms", sum.as_secs_f64() * 1e3 / n as f64, max.as_secs_f64() * 1e3); + } + eprintln!(" every target once: {:.1} ms ({} pictures)", total.as_secs_f64() * 1e3, targets.len()); +} diff --git a/crates/engine/tests/thumbs.rs b/crates/engine/tests/thumbs.rs index 05fb52ba..ff164cee 100644 --- a/crates/engine/tests/thumbs.rs +++ b/crates/engine/tests/thumbs.rs @@ -4,11 +4,11 @@ use std::time::{Duration, Instant}; use serde_json::{Value, json}; -use texturecraft_engine::compose::{Composite, Inputs, ThumbImage, ThumbTarget, all_tiles, composite_tiles, mask_image}; +use texturecraft_engine::compose::{Inputs, ThumbImage, ThumbTarget, all_tiles, flatten_layer, mask_image}; use texturecraft_engine::core::{Channel, ChannelKind, LayerId}; use texturecraft_engine::geom::UvGBuffer; use texturecraft_engine::geom::primitives; -use texturecraft_engine::texel::linear_to_srgb; +use texturecraft_engine::texel::{from_u16, from_u16_signed, linear_to_srgb}; use texturecraft_engine::thumbs::{CACHE_ENTRIES, ThumbService}; use texturecraft_engine::{Session, execute}; @@ -46,8 +46,8 @@ fn inputs<'a>(s: &'a Session, project: &'a texturecraft_engine::core::Project, g Inputs { project, ts: 0, mesh: &s.mesh, gbuf, pixels: &s.doc.pixels, baked, preview: None, images: &s.images, bounds: s.mesh.bounds() } } -/// The reference: the same sub-stack built by hand and composited at 64 px with the ordinary -/// evaluator, then encoded for display. +/// The reference: the same sub-stack cut by hand and evaluated at 64 px with the ordinary CPU +/// evaluator (the mask with `mask_image`, the content with `flatten_layer`), then encoded. fn oracle(s: &Session, target: ThumbTarget) -> ThumbImage { let gbuf = UvGBuffer::new(&s.mesh, 0, N, N); let mut p = s.doc.project.clone(); @@ -77,20 +77,27 @@ fn oracle(s: &Session, target: ThumbTarget) -> ThumbImage { let k = l.content_effects.iter().position(|x| x.id == e).unwrap(); l.content_effects.truncate(k + 1); } - let channels = p.texture_set(0).unwrap().channel_list(); - let mut comp = Composite::new(&channels, N); - composite_tiles(&inputs(s, &p, &gbuf), &mut comp, &all_tiles(N, N)); + // A paint or fill layer: its own (premultiplied value, coverage), coverage as alpha. + let flat = flatten_layer(&inputs(s, &p, &gbuf), layer, &all_tiles(N, N)).unwrap(); let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - let mut rgba = Vec::new(); - for y in 0..N { - for x in 0..N { - let v = comp.value(channel, x, y); + let mut rgba = vec![0u8; (N * N * 4) as usize]; + let comps = channel.components(); + for (_, _, buf) in flat.iter().filter(|(c, _, _)| *c == channel) { + for (i, px) in buf.chunks_exact(comps + 1).enumerate() { + let a = from_u16(px[comps]); + if a <= 0.0 { + continue; + } + let v: [f32; 3] = std::array::from_fn(|k| { + let raw = px[k.min(comps - 1)]; + (if channel.kind() == ChannelKind::Signed { from_u16_signed(raw) } else { from_u16(raw) }) / a + }); let px = match channel.kind() { ChannelKind::Color => v.map(|c| byte(linear_to_srgb(c.clamp(0.0, 1.0)))), ChannelKind::Signed => v.map(|c| byte(c * 0.5 + 0.5)), _ => v.map(byte), }; - rgba.extend_from_slice(&[px[0], px[1], px[2], if gbuf.covered((y * N + x) as usize) { 255 } else { 0 }]); + rgba[i * 4..i * 4 + 4].copy_from_slice(&[px[0], px[1], px[2], byte(a)]); } } ThumbImage { width: N, height: N, rgba } @@ -292,3 +299,19 @@ fn only_requested_rows_render_and_the_cache_is_bounded() { svc.poll(&s); assert!(svc.cached() <= CACHE_ENTRIES, "{}", svc.cached()); } + +#[test] +fn an_empty_paint_layer_is_transparent_and_a_folder_composites_its_children() { + let mut s = session(); + let paint = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap(), "layer"); + let fill = id(execute(&mut s, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer"); + let folder = id(execute(&mut s, "layer.group", &json!({"layer": fill.0})).unwrap(), "layer"); + let base = Channel::BaseColor; + let (p, f) = (ThumbTarget::Content { layer: paint, channel: base }, ThumbTarget::Content { layer: folder, channel: base }); + let (mut svc, mut clock) = (ThumbService::new(), 0.0); + settle(&mut svc, &s, &[p, f], &mut clock); + assert!(image(&mut svc, &s, p).rgba.chunks_exact(4).all(|px| px[3] == 0), "nothing painted: nothing shown"); + let folder_img = image(&mut svc, &s, f); + let px = folder_img.rgba.chunks_exact(4).find(|px| px[3] == 255).unwrap(); + assert!((px[0] as i32 - 51).abs() <= 1 && (px[2] as i32 - 153).abs() <= 1, "{px:?}"); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 3a74a80b..23b73dcb 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -4,6 +4,7 @@ use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; +use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, Source, @@ -14,6 +15,7 @@ use texturecraft_engine::{CloneFrom, StackTarget, Tool}; use crate::TextureCraftApp; use crate::i18n::{n_, tr, trf}; +use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_size, layer_row_height}; use crate::shelf::{Asset, ShelfDrag}; use crate::state::PropsTab; use crate::theme::{Tokens, caption}; @@ -168,9 +170,12 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { ui.add_space(2.0); let ts = app.session.ts(); let stack: Vec = app.session.doc.project.texture_sets.get(ts).map(|t| t.stack.iter().rev().copied().collect()).unwrap_or_default(); + let now = ui.input(|i| i.time); + app.layer_panel.begin(&app.session, now); egui::ScrollArea::vertical().id_salt("layers_scroll").auto_shrink([false, false]).show(ui, |ui| { + let mut count = 0; for id in stack { - layer_tree(app, ui, id, 0); + layer_tree(app, ui, id, 0, &mut count); } // Click on empty space deselects nothing; the space below the rows drops at the bottom. let free = ui.available_height(); @@ -195,6 +200,7 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, tk.accent)); } }); + app.layer_panel.end(ui.ctx(), &app.session); } /// Whether the selection targets the layer content (the content or one of its effects) rather @@ -252,49 +258,108 @@ fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { }); } -fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize) { +/// Layer rows alternate between two shades so neighbours read as separate items. +fn row_shade(tk: &Tokens, index: usize) -> Color32 { + if index.is_multiple_of(2) { tk.row } else { tk.row.lerp_to_gamma(tk.row_hover, 0.45) } +} + +/// Width of the blend mode / opacity column at the right of a layer row. +const RIGHT_COLUMN: f32 = 58.0; +/// Indent per folder level, and per level of the effect tree. +const INDENT: f32 = 14.0; +/// Height of the "Content effects" / "Mask effects" header rows. +const GROUP_HEADER_H: f32 = 20.0; + +/// X of the centre of the eye column at indent `level` in a row spanning from `left`. +fn level_x(left: f32, level: usize) -> f32 { + left + 7.0 + level as f32 * INDENT + 8.0 +} + +fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize, count: &mut usize) { let Some(layer) = app.session.doc.project.layers.get(&id).cloned() else { return }; - layer_row(app, ui, &layer, depth); - for e in layer.content_effects.iter().rev() { - effect_row(app, ui, &layer, &layer.content_effects, e, depth + 1, ic::SPHERE); + let index = *count; + *count += 1; + layer_row(app, ui, &layer, depth, index); + let mask_effects = layer.mask.as_ref().map_or(0, |m| m.effects.len()); + if !layer.content_effects.is_empty() { + effect_group(app, ui, &layer, depth, false, mask_effects > 0); } - if let Some(m) = &layer.mask { - for e in m.effects.iter().rev() { - effect_row(app, ui, &layer, &m.effects, e, depth + 1, ic::MAGIC_WAND); - } + if mask_effects > 0 { + effect_group(app, ui, &layer, depth, true, false); } + // A line under the layer and its effects separates it from the next layer. + let tk = Tokens::get(ui.ctx()); + let r = ui.available_rect_before_wrap(); + ui.painter().hline(r.x_range(), r.top() - 0.5, Stroke::new(1.0, tk.separator)); if let LayerKind::Group { children, collapsed } = &layer.kind && !collapsed && depth < 12 { for c in children.iter().rev() { - layer_tree(app, ui, *c, depth + 1); + layer_tree(app, ui, *c, depth + 1, count); } } } -fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize) { +/// The picture for `target` inside `rect` (drawn over the well), whether there is one yet. +fn thumb_box(ui: &Ui, app: &mut TextureCraftApp, rect: Rect, target: ThumbTarget, dim: bool) -> bool { + let tk = Tokens::get(ui.ctx()); + let p = ui.painter(); + p.rect_filled(rect, 2.0, tk.field); + // A checkerboard shows through where the layer has nothing (transparent texels). + let cells = 4; + let cell = rect.width() / cells as f32; + let check = tk.field.lerp_to_gamma(tk.row_hover, 0.6); + for y in 0..cells { + for x in (0..cells).filter(|x| (x + y) % 2 == 0) { + p.rect_filled(Rect::from_min_size(rect.min + vec2(x as f32 * cell, y as f32 * cell), vec2(cell, cell)), 0.0, check); + } + } + // Only rows on screen ask for a picture. + if ui.is_rect_visible(rect) + && let Some(tex) = app.layer_panel.texture(ui.ctx(), &app.session, target) + { + let tint = if dim { Color32::WHITE.gamma_multiply(0.4) } else { Color32::WHITE }; + ui.painter().image(tex, rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), tint); + return true; + } + false +} + +fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize, index: usize) { let tk = Tokens::get(ui.ctx()); let selected = app.session.selected_layer() == Some(layer.id); - let h = 38.0; + let content_target = selected && targets_content(app); + let size = layer_preview_size(app); + let h = layer_row_height(size); let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag()); resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &layer.name)); let p = ui.painter().clone(); - let bg = if selected && app.session.target == StackTarget::Content { + let bg = if selected { tk.row_selected } else if resp.hovered() { tk.row_hover } else { - tk.row + row_shade(&tk, index) }; - p.rect_filled(rect.shrink2(vec2(0.0, 1.0)), 2.0, bg); + p.rect_filled(rect, 0.0, bg); + // Folder contents hang off lines down the left. + let line = Stroke::new(1.0, tk.button_border.gamma_multiply(0.6)); + for level in 0..depth { + let x = level_x(rect.left(), level); + p.vline(x, rect.y_range(), line); + } + if depth > 0 { + let x = level_x(rect.left(), depth - 1); + p.hline(x..=x + INDENT * 0.5, rect.center().y, line); + } if selected { - p.rect_stroke(rect.shrink2(vec2(0.0, 1.0)), 2.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); + p.rect_filled(Rect::from_min_size(rect.min, vec2(3.0, h)), 0.0, tk.accent); } if let Some(tag) = layer.color_tag.and_then(|t| TAG_COLORS.get(t as usize)) { - p.rect_filled(Rect::from_min_size(rect.min + vec2(0.0, 1.0), vec2(3.0, h - 2.0)), 0.0, *tag); + p.rect_filled(Rect::from_min_size(rect.min + vec2(3.0, 0.0), vec2(3.0, h)), 0.0, *tag); } - let x0 = rect.left() + 6.0 + depth as f32 * 14.0; + let x0 = rect.left() + 7.0 + depth as f32 * INDENT; // Eye. let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(18.0, 18.0)); let eye_resp = ui.interact(eye, ui.scope_id().with(("eye", layer.id.0)), Sense::click()).on_hover_text(tr("Show or hide the layer")); @@ -327,29 +392,24 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } x += 14.0; } - // Thumbnail. - let thumb = Rect::from_min_size(pos2(x, rect.top() + 5.0), vec2(28.0, 28.0)); - p.rect_filled(thumb, 2.0, tk.field); - match &layer.kind { - LayerKind::Fill(f) => { - let c = match f.source(Channel::BaseColor) { - Source::Uniform(v) => v, - Source::Procedural { low, high, .. } => [(low[0] + high[0]) * 0.5, (low[1] + high[1]) * 0.5, (low[2] + high[2]) * 0.5], - Source::Image { .. } | Source::Anchor { .. } => [0.5; 3], - }; - crate::thumbs::paint_sphere(&p, thumb.center(), 12.0, c); - } - LayerKind::Paint => { - p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::PAINT_BRUSH, egui::FontId::proportional(15.0), tk.text); - } - LayerKind::Group { .. } => { - p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::FOLDER_SIMPLE, egui::FontId::proportional(16.0), tk.text); - } - LayerKind::Instance { .. } => { - p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::LINK, egui::FontId::proportional(16.0), tk.accent); - } + // Content thumbnail: the layer's own result in the displayed channel. + let ch = app.ui.layer_channel; + let thumb = Rect::from_min_size(pos2(x, rect.center().y - size * 0.5), vec2(size, size)); + let drawn = thumb_box(ui, app, thumb, ThumbTarget::Content { layer: layer.id, channel: ch }, !layer.visible); + if !drawn { + content_glyph(&p, &tk, thumb, layer); } - x = thumb.right() + 8.0; + p.rect_stroke( + thumb, + 2.0, + Stroke::new(if content_target { 1.5 } else { 1.0 }, if content_target { tk.accent } else { tk.button_border }), + egui::StrokeKind::Outside, + ); + let content_resp = ui.interact(thumb, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(tr("Select the layer content")); + if content_resp.clicked() { + app.run("layer.select", json!({"layer": layer.id.0, "target": "content"})); + } + x = thumb.right() + 4.0; // An instance draws its source's content, blending and (unless it has its own) mask. let project = &app.session.doc.project; let source = layer.instance_source().map(|src| { @@ -357,26 +417,29 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize project.layers.get(&src).map_or_else(|| tr("missing source").to_string(), |l| format!("{} · {set}", l.name)) }); let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|l| l.mask.clone()); - let blend = project.content_layer(layer.id).and_then(|l| l.blend(app.ui.layer_channel)); - // Mask thumbnail. - let right_w = 46.0; - let mask_rect = Rect::from_min_size(pos2(rect.right() - right_w - 30.0, rect.top() + 7.0), vec2(24.0, 24.0)); + let blend = project.content_layer(layer.id).and_then(|l| l.blend(ch)); + // Mask thumbnail, selectable on its own; or the slot that adds one. + let mask_rect; if let Some(m) = &mask { let mask_sel = selected && !targets_content(app); - p.rect_filled( - mask_rect, - 1.0, - if m.background == texturecraft_engine::core::MaskBackground::White { Color32::from_gray(225) } else { Color32::from_gray(18) }, - ); + mask_rect = Rect::from_min_size(pos2(x, rect.center().y - size * 0.5), vec2(size, size)); + let drawn = thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !m.enabled); + if !drawn { + p.rect_filled( + mask_rect, + 2.0, + if m.background == texturecraft_engine::core::MaskBackground::White { Color32::from_gray(225) } else { Color32::from_gray(18) }, + ); + if !m.effects.is_empty() { + p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(13.0), tk.text_dim); + } + } p.rect_stroke( mask_rect, - 1.0, + 2.0, Stroke::new(if mask_sel { 1.5 } else { 1.0 }, if mask_sel { tk.accent } else { tk.button_border }), egui::StrokeKind::Outside, ); - if !m.effects.is_empty() { - p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(11.0), tk.text_dim); - } if !m.enabled { p.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(1.5, tk.danger)); } @@ -392,19 +455,25 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } } if app.session.view == texturecraft_engine::ViewMode::Mask(layer.id) { - p.rect_stroke(mask_rect.expand(2.0), 1.0, Stroke::new(1.5, tk.warning), egui::StrokeKind::Outside); + p.rect_stroke(mask_rect.expand(2.0), 2.0, Stroke::new(1.5, tk.warning), egui::StrokeKind::Outside); } + x = mask_rect.right() + 8.0; } else { // The empty slot adds a mask to this layer. + mask_rect = Rect::from_center_size(pos2(x + 9.0, rect.center().y), vec2(18.0, 18.0)); let slot = ui.interact(mask_rect, ui.scope_id().with(("mask_slot", layer.id.0)), Sense::click()).on_hover_text(tr("Add mask")); - p.rect_stroke(mask_rect, 1.0, Stroke::new(1.0, if slot.hovered() { tk.accent } else { tk.field_border }), egui::StrokeKind::Inside); + p.rect_stroke(mask_rect, 2.0, Stroke::new(1.0, if slot.hovered() { tk.accent } else { tk.field_border }), egui::StrokeKind::Inside); if slot.hovered() { p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::PLUS, egui::FontId::proportional(12.0), tk.text); } egui::Popup::menu(&slot).show(|ui| add_mask_menu(app, ui, Some(layer.id.0))); + x = mask_rect.right() + 8.0; } - // Name (or rename editor). - let name_rect = Rect::from_min_max(pos2(x, rect.top() + 4.0), pos2(mask_rect.left() - 4.0, rect.bottom() - 4.0)); + // Blend mode and opacity of the displayed channel, stacked at the right. + let blend_rect = Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - 4.0, rect.center().y - 18.0), vec2(RIGHT_COLUMN, 17.0)); + let op_rect = Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - 4.0, rect.center().y + 1.0), vec2(RIGHT_COLUMN, 17.0)); + // Name (or rename editor) with the quieter subtitle under it. + let name_rect = Rect::from_min_max(pos2(x, rect.top() + 4.0), pos2((blend_rect.left() - 4.0).max(x + 20.0), rect.bottom() - 4.0)); let renaming = app.ui.rename.as_ref().is_some_and(|(r, _)| *r == layer.id.0); if renaming { let mut child = ui.new_child(egui::UiBuilder::new().max_rect(name_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); @@ -428,20 +497,29 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } } } else { - let galley = elided(&p, layer.name.clone(), 12.0, if layer.visible { tk.text_strong } else { tk.text_dim }, name_rect.width()); - let y = if source.is_some() { rect.center().y - 7.0 } else { rect.center().y }; - p.galley(pos2(name_rect.left(), y - galley.size().y * 0.5), galley, tk.text); - if let Some(src) = source { - let src = elided(&p, format!("{} {src}", ic::LINK_SIMPLE), 10.0, tk.text_dim, name_rect.width()); - p.galley(pos2(name_rect.left(), rect.center().y + 7.0 - src.size().y * 0.5), src, tk.text_dim); - } + let galley = elided(&p, layer.name.clone(), 12.5, if layer.visible { tk.text_strong } else { tk.text_dim }, name_rect.width()); + p.galley(pos2(name_rect.left(), rect.center().y - 2.0 - galley.size().y), galley, tk.text); + let kind = tr(match &layer.kind { + LayerKind::Paint => "Paint layer", + LayerKind::Fill(_) => "Fill layer", + LayerKind::Group { .. } => "Folder", + LayerKind::Instance { .. } => "Instance", + }); + let effects = layer.content_effects.len() + mask.as_ref().map_or(0, |m| m.effects.len()); + let subtitle = match (source, effects) { + (Some(src), _) => format!("{kind} · {} {src}", ic::LINK_SIMPLE), + (None, 0) => kind.to_string(), + (None, 1) => format!("{kind} · {}", tr("1 effect")), + (None, n) => format!("{kind} · {}", trf("{count} effects", &[("count", &n)])), + }; + let sub = elided(&p, subtitle, 10.0, tk.text_dim, name_rect.width()); + p.galley(pos2(name_rect.left(), rect.center().y + 2.0), sub, tk.text_dim); } - // Blend mode and opacity of the displayed channel. - let ch = app.ui.layer_channel; - let blend_rect = Rect::from_min_size(pos2(rect.right() - right_w - 2.0, rect.top() + 3.0), vec2(right_w, 16.0)); - let op_rect = Rect::from_min_size(pos2(rect.right() - right_w - 2.0, rect.top() + 19.0), vec2(right_w, 16.0)); if let Some(b) = blend { let br = ui.interact(blend_rect, ui.scope_id().with(("blend", layer.id.0)), Sense::click()).on_hover_text(tr("Blending mode of the displayed channel")); + if br.hovered() { + p.rect_filled(blend_rect, 2.0, tk.row_hover); + } p.text(blend_rect.right_center() - vec2(10.0, 0.0), egui::Align2::RIGHT_CENTER, b.mode.short(), egui::FontId::proportional(11.0), tk.text); p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(8.0), tk.text_dim); egui::Popup::menu(&br).show(|ui| { @@ -466,7 +544,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize child.spacing_mut().interact_size.y = op_rect.height(); child.spacing_mut().button_padding = vec2(4.0, 0.0); child.style_mut().override_text_style = Some(egui::TextStyle::Small); - let r = child.add(egui::DragValue::new(&mut op).range(0.0..=100.0).speed(0.5).max_decimals(0)); + let r = child.add(egui::DragValue::new(&mut op).range(0.0..=100.0).speed(0.5).max_decimals(0).suffix("%")); if r.changed() { app.run("layer.blend", json!({"layer": layer.id.0, "channel": ch.id(), "opacity": op / 100.0})); } @@ -474,10 +552,11 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, tr("off"), egui::FontId::proportional(11.0), tk.text_dim); } // Interaction: select, rename, drag & drop, context menu. - if resp.clicked() && !eye_resp.clicked() && !renaming { + let on_control = eye_resp.clicked() || content_resp.clicked(); + if resp.clicked() && !on_control && !renaming { app.run("layer.select", json!({"layer": layer.id.0})); } - if resp.double_clicked() && !eye_resp.clicked() && !renaming { + if resp.double_clicked() && !on_control && !renaming { app.ui.rename = Some((layer.id.0, layer.name.clone())); } if resp.drag_started() && !renaming { @@ -523,20 +602,94 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize resp.context_menu(|ui| layer_context_menu(app, ui, layer)); } +/// What a content thumbnail shows until its picture arrives (or where the layer has none). +fn content_glyph(p: &egui::Painter, tk: &Tokens, thumb: Rect, layer: &Layer) { + match &layer.kind { + LayerKind::Fill(f) => { + let c = match f.source(Channel::BaseColor) { + Source::Uniform(v) => v, + Source::Procedural { low, high, .. } => [(low[0] + high[0]) * 0.5, (low[1] + high[1]) * 0.5, (low[2] + high[2]) * 0.5], + Source::Image { .. } | Source::Anchor { .. } => [0.5; 3], + }; + crate::thumbs::paint_sphere(p, thumb.center(), thumb.width() * 0.34, c); + } + LayerKind::Paint => { + p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::PAINT_BRUSH, egui::FontId::proportional(thumb.width() * 0.45), tk.text_dim); + } + LayerKind::Group { .. } => { + p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::FOLDER_SIMPLE, egui::FontId::proportional(thumb.width() * 0.5), tk.text); + } + LayerKind::Instance { .. } => { + p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::LINK, egui::FontId::proportional(thumb.width() * 0.45), tk.accent); + } + } +} + +/// The "Content effects" or "Mask effects" header of `layer` and, unless folded, its effect rows +/// hung off tree lines. `more_below`: a second group follows, so the tree line goes on. +fn effect_group(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize, mask: bool, more_below: bool) { + let tk = Tokens::get(ui.ctx()); + let stack: &[Effect] = if mask { layer.mask.as_ref().map_or(&[], |m| &m.effects) } else { &layer.content_effects }; + let key = (layer.id.0, mask); + let folded = app.layer_panel.folded.contains(&key); + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), GROUP_HEADER_H), Sense::click()); + let label = if mask { tr("Mask effects") } else { tr("Content effects") }; + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); + let p = ui.painter().clone(); + p.rect_filled(rect, 0.0, if resp.hovered() { tk.row_hover } else { tk.panel }); + tree_lines(&p, &tk, rect, depth + 1, &[], more_below); + let x = level_x(rect.left(), depth + 1); + p.text( + pos2(x, rect.center().y), + egui::Align2::CENTER_CENTER, + if folded { ic::CARET_RIGHT } else { ic::CARET_DOWN }, + egui::FontId::proportional(10.0), + tk.text_dim, + ); + p.text(pos2(x + 10.0, rect.center().y), egui::Align2::LEFT_CENTER, label, egui::FontId::proportional(10.5), tk.text_dim); + p.text(pos2(rect.right() - 8.0, rect.center().y), egui::Align2::RIGHT_CENTER, stack.len().to_string(), egui::FontId::proportional(10.0), tk.text_dim); + if resp.on_hover_text(tr("Fold or unfold these effects")).clicked() && !app.layer_panel.folded.remove(&key) { + app.layer_panel.folded.insert(key); + } + if folded { + return; + } + let trunks: Vec = if more_below { vec![depth] } else { Vec::new() }; + for (i, e) in stack.iter().rev().enumerate() { + effect_row(app, ui, layer, stack, e, depth + 2, &trunks, i + 1 == stack.len(), mask); + } +} + +/// Tree connector of a row at indent `level`: a line down from the parent's column (to the middle +/// of the row when `more` is false, the row's end otherwise) and a tick towards the row, with +/// lines straight through for the `trunks` of ancestors that continue. +fn tree_lines(p: &egui::Painter, tk: &Tokens, rect: Rect, level: usize, trunks: &[usize], more: bool) { + let stroke = Stroke::new(1.0, tk.button_border); + for t in trunks { + p.vline(level_x(rect.left(), *t), rect.y_range(), stroke); + } + let x = level_x(rect.left(), level.saturating_sub(1)); + let end = if more { rect.bottom() } else { rect.center().y }; + p.vline(x, rect.top()..=end, stroke); + p.hline(x..=x + INDENT * 0.6, rect.center().y, stroke); +} + /// The drag-and-drop payload of an effect row (the effect id). struct EffectDrag(u64); -/// Effect `e` of `stack`, a layer's content (`glyph` sphere) or mask (`glyph` wand) effects. -fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Effect], e: &Effect, depth: usize, glyph: &str) { +/// Effect `e` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level`. +#[allow(clippy::too_many_arguments)] +fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Effect], e: &Effect, level: usize, trunks: &[usize], last: bool, in_mask: bool) { let tk = Tokens::get(ui.ctx()); let (eid, visible) = (e.id, e.visible); let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(eid); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag()); + let size = effect_preview_size(layer_preview_size(app)); + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), effect_row_height(layer_preview_size(app))), Sense::click_and_drag()); resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &e.name)); let p = ui.painter().clone(); p.rect_filled( - rect.shrink2(vec2(0.0, 1.0)), - 2.0, + rect, + 0.0, if selected { tk.row_selected } else if resp.hovered() { @@ -545,15 +698,28 @@ fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Ef tk.panel }, ); + tree_lines(&p, &tk, rect, level, trunks, !last); if selected { - p.rect_stroke(rect.shrink2(vec2(0.0, 1.0)), 2.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); + p.rect_filled(Rect::from_min_size(rect.min, vec2(3.0, rect.height())), 0.0, tk.accent); } - let x0 = rect.left() + 6.0 + depth as f32 * 14.0; + let x0 = rect.left() + 7.0 + level as f32 * INDENT; let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(16.0, 16.0)); let er = ui.interact(eye, ui.scope_id().with(("eff_eye", eid.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect")); p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(12.0), tk.text_dim); - p.text(pos2(x0 + 22.0, rect.center().y), egui::Align2::LEFT_CENTER, glyph, egui::FontId::proportional(11.0), tk.text_dim); - p.text(pos2(x0 + 38.0, rect.center().y), egui::Align2::LEFT_CENTER, &e.name, egui::FontId::proportional(11.5), tk.text); + // The stack as it is up to and including this effect; a hidden one shows what it bypasses. + let thumb = Rect::from_min_size(pos2(x0 + 22.0, rect.center().y - size * 0.5), vec2(size, size)); + let ch = app.ui.layer_channel; + if !thumb_box(ui, app, thumb, ThumbTarget::Stage { effect: eid, channel: ch }, false) { + let glyph = if in_mask { ic::MAGIC_WAND } else { ic::SPHERE }; + p.text(thumb.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(size * 0.5), tk.text_dim); + } + p.rect_stroke(thumb, 2.0, Stroke::new(1.0, tk.button_border), egui::StrokeKind::Outside); + if !visible { + p.line_segment([thumb.left_bottom(), thumb.right_top()], Stroke::new(1.5, tk.text_dim)); + } + let name_x = thumb.right() + 8.0; + let galley = elided(&p, e.name.clone(), 11.5, if visible { tk.text } else { tk.text_dim }, (rect.right() - name_x - 6.0).max(20.0)); + p.galley(pos2(name_x, rect.center().y - galley.size().y * 0.5), galley, tk.text); if er.clicked() { app.run("effect.set", json!({"effect": eid.0, "visible": !visible})); } else if resp.clicked() { diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 6ef517e9..5e8c266f 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1041,4 +1041,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "الحد الأقصى للقيمة"), ("Value Bounds Min", "الحد الأدنى للقيمة"), ("Vertex Color", "لون الرأس"), + ("Select the layer content", "تحديد محتوى الطبقة"), + ("Paint layer", "طبقة رسم"), + ("Fill layer", "طبقة تعبئة"), + ("1 effect", "تأثير واحد"), + ("{count} effects", "{count} تأثيرات"), + ("Mask effects", "تأثيرات القناع"), + ("Content effects", "تأثيرات المحتوى"), + ("Fold or unfold these effects", "طيّ هذه التأثيرات أو فردها"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index caaabb14..30693118 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1090,4 +1090,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Maximaler Grenzwert"), ("Value Bounds Min", "Minimaler Grenzwert"), ("Vertex Color", "Scheitelpunktfarbe"), + ("Select the layer content", "Ebeneninhalt auswählen"), + ("Paint layer", "Malebene"), + ("Fill layer", "Füllebene"), + ("1 effect", "1 Effekt"), + ("{count} effects", "{count} Effekte"), + ("Mask effects", "Maskeneffekte"), + ("Content effects", "Inhaltseffekte"), + ("Fold or unfold these effects", "Diese Effekte ein- oder ausklappen"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 6c8ccccb..bc8ace33 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1075,4 +1075,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Límite máximo"), ("Value Bounds Min", "Límite mínimo"), ("Vertex Color", "Color de vértice"), + ("Select the layer content", "Seleccionar el contenido de la capa"), + ("Paint layer", "Capa de pintura"), + ("Fill layer", "Capa de relleno"), + ("1 effect", "1 efecto"), + ("{count} effects", "{count} efectos"), + ("Mask effects", "Efectos de la máscara"), + ("Content effects", "Efectos del contenido"), + ("Fold or unfold these effects", "Plegar o desplegar estos efectos"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index f10bba8d..336621e9 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1099,4 +1099,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Borne maximale"), ("Value Bounds Min", "Borne minimale"), ("Vertex Color", "Couleur des sommets"), + ("Select the layer content", "Sélectionner le contenu du calque"), + ("Paint layer", "Calque de peinture"), + ("Fill layer", "Calque de remplissage"), + ("1 effect", "1 effet"), + ("{count} effects", "{count} effets"), + ("Mask effects", "Effets du masque"), + ("Content effects", "Effets du contenu"), + ("Fold or unfold these effects", "Replier ou déplier ces effets"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 1c19d597..8f92b26c 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1084,4 +1084,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Limite massimo"), ("Value Bounds Min", "Limite minimo"), ("Vertex Color", "Colore dei vertici"), + ("Select the layer content", "Seleziona il contenuto del livello"), + ("Paint layer", "Livello di pittura"), + ("Fill layer", "Livello di riempimento"), + ("1 effect", "1 effetto"), + ("{count} effects", "{count} effetti"), + ("Mask effects", "Effetti della maschera"), + ("Content effects", "Effetti del contenuto"), + ("Fold or unfold these effects", "Comprimi o espandi questi effetti"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 068603b5..52166e4a 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1069,4 +1069,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "値の上限"), ("Value Bounds Min", "値の下限"), ("Vertex Color", "頂点カラー"), + ("Select the layer content", "レイヤーの内容を選択"), + ("Paint layer", "ペイントレイヤー"), + ("Fill layer", "塗りつぶしレイヤー"), + ("1 effect", "エフェクト 1 件"), + ("{count} effects", "エフェクト {count} 件"), + ("Mask effects", "マスクのエフェクト"), + ("Content effects", "コンテンツのエフェクト"), + ("Fold or unfold these effects", "これらのエフェクトを折りたたむ/展開する"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 137d6177..18bf30a6 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1054,4 +1054,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "값 상한"), ("Value Bounds Min", "값 하한"), ("Vertex Color", "정점 색상"), + ("Select the layer content", "레이어 내용 선택"), + ("Paint layer", "페인트 레이어"), + ("Fill layer", "채우기 레이어"), + ("1 effect", "효과 1개"), + ("{count} effects", "효과 {count}개"), + ("Mask effects", "마스크 효과"), + ("Content effects", "콘텐츠 효과"), + ("Fold or unfold these effects", "이 효과들 접기/펼치기"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 99627b25..17d7cc2e 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1072,4 +1072,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Limite máximo"), ("Value Bounds Min", "Limite mínimo"), ("Vertex Color", "Cor do vértice"), + ("Select the layer content", "Selecionar o conteúdo da camada"), + ("Paint layer", "Camada de pintura"), + ("Fill layer", "Camada de preenchimento"), + ("1 effect", "1 efeito"), + ("{count} effects", "{count} efeitos"), + ("Mask effects", "Efeitos da máscara"), + ("Content effects", "Efeitos do conteúdo"), + ("Fold or unfold these effects", "Recolher ou expandir estes efeitos"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 18623ce3..4bb8705e 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1000,4 +1000,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "值上限"), ("Value Bounds Min", "值下限"), ("Vertex Color", "顶点颜色"), + ("Select the layer content", "选择图层内容"), + ("Paint layer", "绘画图层"), + ("Fill layer", "填充图层"), + ("1 effect", "1 个效果"), + ("{count} effects", "{count} 个效果"), + ("Mask effects", "蒙版效果"), + ("Content effects", "内容效果"), + ("Fold or unfold these effects", "折叠或展开这些效果"), ]; diff --git a/crates/ui-egui/src/layer_panel.rs b/crates/ui-egui/src/layer_panel.rs new file mode 100644 index 00000000..a29fa288 --- /dev/null +++ b/crates/ui-egui/src/layer_panel.rs @@ -0,0 +1,87 @@ +//! State behind the Layers panel: the thumbnail service, the GPU textures made from its pictures, +//! which effect groups are folded, and the one place the preview size is decided. + +use std::collections::{HashMap, HashSet}; +use std::time::Duration; + +use egui::{Context, TextureHandle, TextureId, TextureOptions}; +use texturecraft_engine::Session; +use texturecraft_engine::compose::ThumbTarget; +use texturecraft_engine::thumbs::{CACHE_ENTRIES, ThumbService}; + +use crate::TextureCraftApp; + +/// Edge (points) of a layer's content and mask thumbnails. The Layers "Preview size" setting +/// plugs in by changing [`layer_preview_size`]; every row measure below derives from it. +pub(crate) const LAYER_PREVIEW_SIZE: f32 = 36.0; + +/// The thumbnail edge in points, read once per row. +pub(crate) fn layer_preview_size(_app: &TextureCraftApp) -> f32 { + LAYER_PREVIEW_SIZE +} + +/// Height of a layer row for thumbnails of `size`. +pub(crate) fn layer_row_height(size: f32) -> f32 { + (size + 12.0).max(48.0) +} + +/// Edge of an effect's stage thumbnail for layer thumbnails of `size` (18 to 28 points). +pub(crate) fn effect_preview_size(size: f32) -> f32 { + (size * 0.6).clamp(18.0, 28.0) +} + +/// Height of an effect row. +pub(crate) fn effect_row_height(size: f32) -> f32 { + (effect_preview_size(size) + 4.0).max(26.0) +} + +#[derive(Default)] +pub struct LayerPanel { + service: ThumbService, + textures: HashMap, + frame: u64, + /// Folded effect groups: (layer, true for the mask's). A view setting; the document is not touched. + pub(crate) folded: HashSet<(u64, bool)>, +} + +impl LayerPanel { + /// Start drawing the panel for this frame. + pub(crate) fn begin(&mut self, session: &Session, now: f64) { + self.frame += 1; + self.service.begin_frame(session, now); + } + + /// The texture of `target`, queuing its render (call only for rows that are on screen). + pub(crate) fn texture(&mut self, ctx: &Context, session: &Session, target: ThumbTarget) -> Option { + let view = self.service.get(session, target); + let image = view.image?; + let frame = self.frame; + if let Some((version, tex, used)) = self.textures.get_mut(&target) + && *version == view.version + { + *used = frame; + return Some(tex.id()); + } + let pixels = egui::ColorImage::from_rgba_unmultiplied([image.width as usize, image.height as usize], &image.rgba); + let tex = ctx.load_texture("layer-thumb", pixels, TextureOptions::LINEAR); + let id = tex.id(); + self.textures.insert(target, (view.version, tex, frame)); + Some(id) + } + + /// Finish the frame: collect pictures and ask for another frame while work is outstanding. + pub(crate) fn end(&mut self, ctx: &Context, session: &Session) { + if self.service.poll(session) { + ctx.request_repaint_after(Duration::from_millis(40)); + } + if self.textures.len() > CACHE_ENTRIES * 2 { + let frame = self.frame; + self.textures.retain(|_, (_, _, used)| *used + 1 >= frame); + } + } + + /// The service, for tests. + pub fn service(&self) -> &ThumbService { + &self.service + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8bfc66c9..d82bea69 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,6 +16,7 @@ pub mod fonts; pub mod gpu; pub mod i18n; pub mod keymap; +pub mod layer_panel; pub mod menus; pub mod parity; pub mod profile; @@ -85,6 +86,8 @@ pub struct TextureCraftApp { pub resize: Option, pub link_cooks: Vec, pub thumbs: thumbs::Thumbs, + /// The Layers panel's thumbnails and folded groups. + pub layer_panel: layer_panel::LayerPanel, /// Last frame's viewport rect (logical points), for scripted input. pub viewport_rect: egui::Rect, pub fps: f32, @@ -145,6 +148,7 @@ impl TextureCraftApp { resize: None, link_cooks: Vec::new(), thumbs: thumbs::Thumbs::default(), + layer_panel: layer_panel::LayerPanel::default(), viewport_rect: egui::Rect::NOTHING, fps: 0.0, ui_ms: 0.0, diff --git a/crates/ui-egui/tests/layers_panel.rs b/crates/ui-egui/tests/layers_panel.rs new file mode 100644 index 00000000..facf2ab3 --- /dev/null +++ b/crates/ui-egui/tests/layers_panel.rs @@ -0,0 +1,96 @@ +//! The Layers panel rows: content and mask thumbnails select their own target, effect groups +//! fold without touching the document, and the thumbnails arrive from the worker. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::compose::ThumbTarget; +use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::{StackTarget, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +fn id(v: Value, key: &str) -> u64 { + v[key].as_u64().unwrap() +} + +/// A session whose top layer, "Masked fill", has one content effect and a mask with one effect. +fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer")); + execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": "Masked fill"})).unwrap(); + execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + execute(&mut session, "effect.add.generator", &json!({"generator": "position", "level": 0.5, "name": "Effect M"})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + (h, layer) +} + +/// Centre of the content (`mask` false) or mask thumbnail of the top-level, non-folder row +/// labelled `name`: after the 7-point edge, the 20-point eye column, then 36-point squares 4 apart. +fn thumb(h: &Harness<'_, TextureCraftApp>, name: &str, mask: bool) -> egui::Pos2 { + let row = h.get_by_label(name).rect(); + let x = row.left() + 7.0 + 20.0 + 18.0 + if mask { 40.0 } else { 0.0 }; + egui::pos2(x, row.center().y) +} + +/// The `label` header that follows the "Masked fill" row (other layers have groups too). +fn header(h: &mut Harness<'_, TextureCraftApp>, label: &str) { + let top = h.get_by_label("Masked fill").rect().top(); + let at = h.get_all_by_label(label).map(|n| n.rect()).filter(|r| r.top() > top).min_by(|a, b| a.top().total_cmp(&b.top())).unwrap().center(); + click(h, at); +} + +fn click(h: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { + h.drag_at(at); + h.drop_at(at); + h.run_steps(3); +} + +#[test] +fn mask_and_content_thumbnails_select_their_own_target() { + let (mut h, layer) = harness(); + let at = thumb(&h, "Masked fill", true); + click(&mut h, at); + assert_eq!(h.state().session.selected_layer(), Some(layer)); + assert_eq!(h.state().session.target, StackTarget::Mask, "the mask thumbnail routes to the mask"); + let at = thumb(&h, "Masked fill", false); + click(&mut h, at); + assert_eq!(h.state().session.target, StackTarget::Content, "the content thumbnail routes back"); + // Clicking an effect row still selects that effect. + let r = h.get_by_label("Effect A").rect(); + click(&mut h, egui::pos2(r.right() - 40.0, r.center().y)); + assert!(matches!(h.state().session.target, StackTarget::Effect(_))); +} + +#[test] +fn folding_an_effect_group_hides_its_rows_without_changing_the_document() { + let (mut h, _) = harness(); + let (project, undo) = (h.state().session.doc.project.clone(), h.state().session.revision); + assert!(h.query_by_label("Effect A").is_some() && h.query_by_label("Effect M").is_some()); + header(&mut h, "Content effects"); + assert!(h.query_by_label("Effect A").is_none(), "folded content effects are hidden"); + assert!(h.query_by_label("Effect M").is_some(), "the mask group stays open"); + header(&mut h, "Mask effects"); + assert!(h.query_by_label("Effect M").is_none()); + assert_eq!(h.state().session.doc.project, project); + assert_eq!(h.state().session.revision, undo, "folding is not an edit"); + header(&mut h, "Content effects"); + assert!(h.query_by_label("Effect A").is_some(), "unfolds again"); +} + +#[test] +fn visible_rows_get_their_thumbnails() { + let (mut h, layer) = harness(); + let content = ThumbTarget::Content { layer, channel: Channel::BaseColor }; + let mask = ThumbTarget::Mask { layer }; + let t0 = std::time::Instant::now(); + while !(h.state().layer_panel.service().is_fresh(content) && h.state().layer_panel.service().is_fresh(mask)) { + assert!(t0.elapsed().as_secs() < 60, "thumbnails never arrived"); + h.run_steps(1); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + // Rows, mask, and every effect stage on screen were asked for: well under the cache size. + assert!(h.state().layer_panel.service().cached() >= 4); +} diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 0f42158f..f180af43 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -127,7 +127,40 @@ fn window_snapshots() { texturecraft_engine::execute(session, id, ¶ms).unwrap(); } save(&mut harness, &output_dir, "properties-levels"); - + // Show the Layers panel thumbnails with a hidden content effect, a folder and a mask + let session = &mut harness.state_mut().session; + for (id, params) in [ + ("effect.add.filter", serde_json::json!({"target": "content", "filter": "hsl"})), + ("effect.add.filter", serde_json::json!({"target": "content", "filter": "invert"})), + ("layer.add.paint", serde_json::Value::Null), + ("layer.group", serde_json::Value::Null), + ] { + texturecraft_engine::execute(session, id, ¶ms).unwrap(); + } + let hidden = harness + .state() + .session + .doc + .project + .layers + .values() + .flat_map(|layer| layer.content_effects.iter()) + .find(|effect| effect.name == "Invert") + .map(|effect| effect.id.0); + if let Some(effect) = hidden { + texturecraft_engine::execute(&mut harness.state_mut().session, "effect.set", &serde_json::json!({"effect": effect, "visible": false})).unwrap(); + } + harness.state_mut().ui.dock.focus(Panel::Layers); + harness.set_size(egui::vec2(1600.0, 1400.0)); + for _ in 0..400 { + harness.run_steps(1); + std::thread::sleep(std::time::Duration::from_millis(10)); + if !harness.state().layer_panel.service().busy() { + break; + } + } + save(&mut harness, &output_dir, "panel-layers"); + harness.set_size(egui::vec2(1600.0, 960.0)); // Show the second path selected in Properties let session = &mut harness.state_mut().session; for (id, params) in [ diff --git a/docs/architecture.md b/docs/architecture.md index 5eda226c..2756a942 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -69,6 +69,26 @@ The CPU compositor is the reference for everything users see and export. Export (`formats::export`) reads the same composite, adds height-to-normal (Sobel) combined with the normal channel and baked normals by reoriented normal mapping, and packs channels per preset. +### Layer-panel thumbnails + +The Layers panel shows each layer's content (in the displayed channel), its mask and every effect +stage as small pictures. `compose::thumb::render` runs the same compositor on a *cut* copy of the +project: the set's stack becomes the one layer, forced visible at Normal / 100 %, without its mask +for the content, and with its effect list truncated after the previewed effect (a hidden effect +shows the result it bypasses). Paint and fill layers are flattened to (value, coverage), so empty +texels are transparent; folders composite their children. Colors are encoded linear to sRGB, data +channels raw. Everything is evaluated on a 64 px G-buffer of the mesh (painted tiles are +resampled), never at the set's resolution, and the main composite is never touched. + +`engine::thumbs::ThumbService` runs it off the UI thread: an immutable `ThumbSnapshot` (the +project, copy-on-write pixel tiles, baked maps, images and the cached 64 px G-buffer) is rebuilt +only when the document really differs (compared at most every 120 ms while it keeps changing), a +worker thread renders one job at a time (inline, one per frame, on wasm32), results of an older +snapshot are dropped, and an LRU of 96 pictures keeps the out-of-date picture on screen until its +replacement arrives. Only rows on screen ask for pictures; queued rows that scrolled away are +dropped. On a 4096 set (`perf::bench_layer_thumbs_4k`) a snapshot costs 0.02 ms, a content picture +about 2.5 ms and a whole ten-layer panel (20 pictures) about 42 ms of worker time. + ## Undo `Session::edit` snapshots the `Document` (project + pixels + baked maps + resources) before a From 75388894945ea2b8bed57248ca1ed489775f73f4 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:12:49 +0100 Subject: [PATCH 3/7] packaging(linux): refuse non-HTTPS redirects when fetching appimagetool --- packaging/linux/package.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index 51021aab..865f40ca 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -113,7 +113,7 @@ if has appimage; then if [ -z "$TOOL" ]; then TOOL="$CARGO_TARGET_DIR/appimagetool-$ARCH.AppImage" if [ ! -x "$TOOL" ]; then - curl -fsSL -o "$TOOL" "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-$ARCH.AppImage" + curl --proto '=https' -fsSL -o "$TOOL" "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-$ARCH.AppImage" chmod +x "$TOOL" fi fi From 2d0b8e6a48ffd6acae2a6fda4168da62b6e3b02b Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 06:37:12 -0500 Subject: [PATCH 4/7] Fix thumbnail previews and cache retention --- crates/compose/src/eval.rs | 2 + crates/compose/src/eval/thumbnail.rs | 30 +++ crates/compose/src/thumb.rs | 102 +++++---- crates/engine/src/thumbs.rs | 330 ++++++++++++++++++++------- crates/engine/tests/it/thumbs.rs | 213 ++++++++++++----- crates/ui-egui/src/layer_panel.rs | 57 +++++ docs/architecture.md | 24 +- 7 files changed, 559 insertions(+), 199 deletions(-) create mode 100644 crates/compose/src/eval/thumbnail.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index b43796e8..b9deb64f 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2,6 +2,8 @@ //! tile by tile in parallel. This is the reference implementation (the oracle) for the viewport //! and for export. +pub(crate) mod thumbnail; + use std::borrow::Cow; use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; diff --git a/crates/compose/src/eval/thumbnail.rs b/crates/compose/src/eval/thumbnail.rs new file mode 100644 index 00000000..92290afe --- /dev/null +++ b/crates/compose/src/eval/thumbnail.rs @@ -0,0 +1,30 @@ +//! Isolated folder evaluation with the original stack available for anchor inputs. + +use super::{Channel, ChannelKind, Composite, Inputs, LayerId, Texel, all_tiles, neighbourhood_fields, plan, tile_texels, to_u16, to_u16_signed}; + +/// Composite one layer over channel defaults, keeping anchors from the stack below it. +pub(crate) fn composite_layer(inputs: &Inputs, layer: LayerId, channel: Channel) -> Option { + let set = inputs.project.texture_set(inputs.ts).ok()?; + let channels = set.channel_list(); + let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); + let tiles = all_tiles(width, height); + let fields = neighbourhood_fields(inputs, &channels, &tiles); + let mut composite = Composite::with_size(&[channel], width, height); + let output = composite.channels.get_mut(&channel)?; + + for (tile_x, tile_y) in tiles { + let nodes = plan(inputs, &[layer], &channels, tile_x, tile_y, 0, Some(&fields)); + let full_stack = if set.stack.as_slice() == [layer] { Vec::new() } else { plan(inputs, &set.stack, &channels, tile_x, tile_y, 0, Some(&fields)) }; + for (x, y, offset) in tile_texels(inputs.gbuf, tile_x, tile_y) { + let mut texel = Texel::new(inputs, x, y, offset, 0.0); + texel.anchors_below(&full_stack, layer); + let mut values = Channel::ALL.map(Channel::default_value); + texel.eval(&nodes, &mut values); + let value = values.get(channel.index()).copied().unwrap_or_else(|| channel.default_value()); + let encoded = value.map(|component| if channel.kind() == ChannelKind::Signed { to_u16_signed(component) } else { to_u16(component) }); + output.set(x, y, &encoded[..channel.components()]); + } + } + + Some(composite) +} diff --git a/crates/compose/src/thumb.rs b/crates/compose/src/thumb.rs index cec31bd4..b4c59a15 100644 --- a/crates/compose/src/thumb.rs +++ b/crates/compose/src/thumb.rs @@ -1,8 +1,8 @@ //! Small previews of one layer's content, one mask, or one effect stage, computed without //! touching the main composite. //! -//! Every thumbnail is the ordinary compositor run on a *cut* copy of the project: the texture -//! set's stack is replaced by the one layer, the layer is forced visible at Normal / 100 %, and +//! Every thumbnail is the ordinary compositor run on a *cut* copy of the project: only the +//! requested layer is drawn, forced visible at Normal / 100 %, and //! the layer's effect list is truncated after the effect being previewed. The evaluator is the //! same code the viewport uses (just on a small G-buffer), so a thumbnail always agrees with //! what the stack really computes. Nothing here mutates the caller's project. @@ -10,7 +10,7 @@ use texturecraft_core::{BlendMode, Channel, ChannelBlend, ChannelKind, LayerId, Project}; use texturecraft_texel::{TILE, from_u16, from_u16_signed, linear_to_srgb}; -use crate::eval::{Composite, FlatTile, Inputs, all_tiles, composite_tiles, flatten_layer, mask_image}; +use crate::eval::{Composite, FlatTile, Inputs, all_tiles, flatten_layer, mask_image}; /// Edge length (texels) the thumbnails are computed at. pub const THUMB_TEXELS: u32 = 64; @@ -55,16 +55,22 @@ pub fn render(inp: &Inputs, target: ThumbTarget) -> Option { } } -/// `project` cut down to the single layer `id` of texture set `ts`: only that layer is drawn, -/// visible, Normal at full opacity in `channel` (when given). -fn solo(project: &Project, ts: usize, id: LayerId, channel: Option) -> Option { +/// Force the requested layer visible, retaining the stack needed by anchor readers. +fn solo(project: &Project, texture_set: usize, id: LayerId, channel: Option) -> Option { let mut cut = project.clone(); - cut.texture_sets.get_mut(ts)?.stack = vec![id]; - let l = cut.layers.get_mut(&id)?; - l.visible = true; - if let Some(c) = channel { - *l.channels.get_mut(&c)? = ChannelBlend { mode: BlendMode::Normal, opacity: 1.0 }; + + // Ordinary previews need no neighbouring layers or their filter allocations + if !project.render_tree(&[id]).iter().any(|layer| crate::eval::reads_anchor(project, *layer)) { + cut.texture_sets.get_mut(texture_set)?.stack = vec![id]; } + + cut.layers.get_mut(&id)?.visible = true; + if let Some(channel) = channel { + // Instances inherit channels from their source + let owner = cut.content_layer(id)?.id; + *cut.layers.get_mut(&owner)?.channels.get_mut(&channel)? = ChannelBlend { mode: BlendMode::Normal, opacity: 1.0 }; + } + Some(cut) } @@ -79,38 +85,38 @@ fn truncate_after(list: &mut Vec, last: LayerId) -> b } } -fn content(inp: &Inputs, layer: LayerId, channel: Channel, upto: Option) -> Option { - let set = inp.project.texture_set(inp.ts).ok()?; +fn content(inputs: &Inputs, layer: LayerId, channel: Channel, through_effect: Option) -> Option { + let set = inputs.project.texture_set(inputs.ts).ok()?; if !set.channel_list().contains(&channel) { return None; } - // The layer whose content is drawn: an instance draws its source's effects. - let mut cut = solo(inp.project, inp.ts, layer, Some(channel))?; + + // An instance draws its source's effects + let mut cut = solo(inputs.project, inputs.ts, layer, Some(channel))?; let owner = cut.content_layer(layer)?.id; for id in [layer, owner] { - let l = cut.layers.get_mut(&id)?; - l.mask = None; - l.visible = true; - if let Some(b) = l.channels.get_mut(&channel) { - *b = ChannelBlend { mode: BlendMode::Normal, opacity: 1.0 }; - } + let content = cut.layers.get_mut(&id)?; + content.mask = None; + content.visible = true; } - if let Some(effect) = upto + + if let Some(effect) = through_effect && !truncate_after(&mut cut.layers.get_mut(&owner)?.content_effects, effect) { return None; } - let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; - let (w, h) = (inp.gbuf.width, inp.gbuf.height); - // A paint or fill layer shows its own coverage (transparent where nothing is painted); a - // folder shows its children composited over the channel's default. + + let cut_inputs = Inputs { project: &cut, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs }; + let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); + + // Paint and fill previews retain coverage; folders composite over channel defaults if !cut.layers.get(&owner)?.is_group() { - let flat = flatten_layer(&cut_inp, layer, &all_tiles(w, h))?; - return Some(encode_flat(&flat, channel, w, h)); + let flat = flatten_layer(&cut_inputs, layer, &all_tiles(width, height))?; + return Some(encode_flat(&flat, channel, width, height)); } - let mut comp = Composite::with_size(&set.channel_list(), w, h); - composite_tiles(&cut_inp, &mut comp, &all_tiles(w, h)); - Some(encode_channel(&comp, channel, inp)) + + let comp = crate::eval::thumbnail::composite_layer(&cut_inputs, layer, channel)?; + Some(encode_channel(&comp, channel, inputs)) } /// Encode the flattened (premultiplied value, coverage) tiles of `channel`: alpha is coverage. @@ -153,28 +159,30 @@ fn display(channel: Channel, v: [f32; 3]) -> [u8; 3] { } } -fn mask(inp: &Inputs, layer: LayerId, upto: Option) -> Option { - let mut cut = solo(inp.project, inp.ts, layer, None)?; +fn mask(inputs: &Inputs, layer: LayerId, through_effect: Option) -> Option { + let mut cut = solo(inputs.project, inputs.ts, layer, None)?; let owner = cut.mask_owner(layer); - let m = cut.layers.get_mut(&owner)?.mask.as_mut()?; - m.enabled = true; - if let Some(effect) = upto - && !truncate_after(&mut m.effects, effect) + let mask = cut.layers.get_mut(&owner)?.mask.as_mut()?; + mask.enabled = true; + if let Some(effect) = through_effect + && !truncate_after(&mut mask.effects, effect) { return None; } - let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; - let (w, h) = (inp.gbuf.width, inp.gbuf.height); - let gray = mask_image(&cut_inp, layer, w)?; - let mut rgba = Vec::with_capacity((w * h) as usize * 4); - for y in 0..h { - for x in 0..w { - let i = (y * w + x) as usize; - let g = gray.get(i).copied().unwrap_or(0); - rgba.extend_from_slice(&[g, g, g, if inp.gbuf.covered(i) { 255 } else { 0 }]); + + let cut_inputs = Inputs { project: &cut, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs }; + let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); + let gray = mask_image(&cut_inputs, layer, width)?; + let mut rgba = Vec::with_capacity((width * height) as usize * 4); + for y in 0..height { + for x in 0..width { + let offset = (y * width + x) as usize; + let value = gray.get(offset).copied().unwrap_or(0); + rgba.extend_from_slice(&[value, value, value, if inputs.gbuf.covered(offset) { 255 } else { 0 }]); } } - Some(ThumbImage { width: w, height: h, rgba }) + + Some(ThumbImage { width, height, rgba }) } /// Encode the composited `channel` for display: colors linear → sRGB, signed values 0 → mid diff --git a/crates/engine/src/thumbs.rs b/crates/engine/src/thumbs.rs index e9de02a3..5378aa06 100644 --- a/crates/engine/src/thumbs.rs +++ b/crates/engine/src/thumbs.rs @@ -64,21 +64,27 @@ impl ThumbSnapshot { }) } - /// Whether `s` would give the same thumbnails as this snapshot. - fn matches(&self, s: &Session, ts: usize) -> bool { - let same_pixels = self.pixels.layers.len() == s.doc.pixels.layers.len() - && self.pixels.masks.len() == s.doc.pixels.masks.len() - && self.pixels.layers.iter().all(|(k, v)| s.doc.pixels.layers.get(k) == Some(v)) - && self.pixels.masks.iter().all(|(k, v)| s.doc.pixels.masks.get(k) == Some(v)); - let none = BakedMaps::default(); - let baked = s.doc.baked.get(&ts).unwrap_or(&none); - self.ts == ts - && self.mesh_id == s.mesh_id - && self.project == s.doc.project + /// Whether `session` would give the same thumbnails as this snapshot. + fn matches(&self, session: &Session, texture_set: usize) -> bool { + let same_pixels = self.pixels.layers.len() == session.doc.pixels.layers.len() + && self.pixels.masks.len() == session.doc.pixels.masks.len() + && self.pixels.layers.iter().all(|(key, pixels)| session.doc.pixels.layers.get(key) == Some(pixels)) + && self.pixels.masks.iter().all(|(key, pixels)| session.doc.pixels.masks.get(key) == Some(pixels)); + let empty = BakedMaps::default(); + let baked = session.doc.baked.get(&texture_set).unwrap_or(&empty); + + // Copy-on-write maps change handles on edits; float equality would scan entire bakes + let same_baked = self.baked.resolution == baked.resolution + && self.baked.maps.len() == baked.maps.len() + && self.baked.maps.iter().all(|(map, pixels)| baked.maps.get(map).is_some_and(|current| Arc::ptr_eq(pixels, current))); + + self.ts == texture_set + && self.mesh_id == session.mesh_id + && self.project == session.doc.project && same_pixels - && self.baked == *baked - && self.images.len() == s.images.len() - && self.images.iter().all(|(k, v)| s.images.get(k).is_some_and(|o| Arc::ptr_eq(o, v))) + && same_baked + && self.images.len() == session.images.len() + && self.images.iter().all(|(key, image)| session.images.get(key).is_some_and(|current| Arc::ptr_eq(current, image))) } /// Render `target`: the work of one job. @@ -195,7 +201,7 @@ pub struct ThumbService { tick: u64, versions: u64, queue: VecDeque, - in_flight: HashSet, + in_flight: HashSet<(u64, ThumbTarget)>, wanted: HashSet, gbufs: GbufCache, #[cfg(not(target_arch = "wasm32"))] @@ -238,139 +244,162 @@ impl ThumbService { } /// Start of a frame: forget what the last frame asked for and notice document changes. - pub fn begin_frame(&mut self, s: &Session, now: f64) { + pub fn begin_frame(&mut self, session: &Session, now: f64) { self.wanted.clear(); - let ts = s.ts(); - if self.seen == Some(s.revision) && self.snapshot.as_ref().is_some_and(|sn| sn.ts == ts && sn.mesh_id == s.mesh_id) { + let texture_set = session.ts(); + if self.seen == Some(session.revision) + && self.snapshot.as_ref().is_some_and(|snapshot| snapshot.ts == texture_set && snapshot.mesh_id == session.mesh_id) + { return; } - // While the document keeps changing, compare at the debounce pace (the first look is immediate). + + // Compare at the debounce pace while the document keeps changing if self.snapshot.is_some() && now - self.last_check < DEBOUNCE { return; } + self.last_check = now; - if self.snapshot.as_ref().is_some_and(|sn| sn.matches(s, ts)) { - self.seen = Some(s.revision); + if self.snapshot.as_ref().is_some_and(|snapshot| snapshot.matches(session, texture_set)) { + self.seen = Some(session.revision); return; } - self.snapshot = ThumbSnapshot::new(s, ts, &mut self.gbufs).map(Arc::new); - self.seen = Some(s.revision); - self.generation += 1; - // Jobs of the old snapshot are not worth running (those in flight are dropped on arrival). + + self.snapshot = ThumbSnapshot::new(session, texture_set, &mut self.gbufs).map(Arc::new); + self.seen = Some(session.revision); + self.generation = self.generation.wrapping_add(1); + + // Keep dispatched jobs counted until they finish, even when their snapshot is stale self.queue.clear(); - self.inline.clear(); - self.in_flight.clear(); - if let Some(sn) = &self.snapshot { - self.cache.retain(|t, _| sn.has(*t)); + for job in self.inline.drain(..) { + self.in_flight.remove(&(job.generation, job.target)); + } + + if let Some(snapshot) = &self.snapshot { + self.cache.retain(|target, _| snapshot.has(*target)); } else { self.cache.clear(); } } /// Whether the displayed pictures wait for a document comparison that is still debounced. - fn checked(&self, s: &Session) -> bool { - self.seen == Some(s.revision) + fn checked(&self, session: &Session) -> bool { + self.seen == Some(session.revision) } /// The picture for `target` (call for the rows on screen only). Queues work when the /// picture is missing or out of date. - pub fn get(&mut self, s: &Session, target: ThumbTarget) -> ThumbView { + pub fn get(&mut self, session: &Session, target: ThumbTarget) -> ThumbView { self.wanted.insert(target); - self.tick += 1; - let fresh = self.cache.get(&target).is_some_and(|e| e.generation == self.generation); - let checked = self.checked(s); - if !fresh && checked && self.snapshot.is_some() && !self.in_flight.contains(&target) && !self.queue.contains(&target) { + self.tick = self.tick.wrapping_add(1); + let fresh = self.cache.get(&target).is_some_and(|entry| entry.generation == self.generation); + let checked = self.checked(session); + if !fresh && checked && self.snapshot.is_some() && !self.in_flight.contains(&(self.generation, target)) && !self.queue.contains(&target) { self.queue.push_back(target); } - let tick = self.tick; + match self.cache.get_mut(&target) { - Some(e) => { - e.used = tick; - ThumbView { image: e.image.clone(), version: e.version, pending: !(fresh && checked) } + Some(entry) => { + entry.used = self.tick; + ThumbView { image: entry.image.clone(), version: entry.version, pending: !(fresh && checked) } } None => ThumbView { image: None, version: 0, pending: true }, } } - /// End of a frame: take finished pictures, drop queued rows nobody asked for, hand the worker - /// its next jobs. Returns whether more work is outstanding (ask for another frame). - pub fn poll(&mut self, s: &Session) -> bool { - self.collect(); - let wanted = &self.wanted; - self.queue.retain(|t| wanted.contains(t)); + /// End of a frame: collect results, discard unrequested rows, and dispatch new work. + /// Returns whether another frame is needed, including to display newly collected pictures. + pub fn poll(&mut self, session: &Session) -> bool { + let changed = self.collect(); + self.queue.retain(|target| self.wanted.contains(target)); self.dispatch(); self.trim(); - !self.queue.is_empty() || !self.in_flight.is_empty() || !self.inline.is_empty() || !self.checked(s) + + changed || !self.queue.is_empty() || !self.in_flight.is_empty() || !self.checked(session) } fn dispatch(&mut self) { let Some(snapshot) = self.snapshot.clone() else { return }; - while self.in_flight.len() + self.inline.len() < IN_FLIGHT { + + while self.in_flight.len() < IN_FLIGHT { let Some(target) = self.queue.pop_front() else { break }; let job = Job { snapshot: snapshot.clone(), generation: self.generation, target }; - self.in_flight.insert(target); - if !self.send(job) { - break; - } + self.in_flight.insert((job.generation, target)); + self.send(job); } } #[cfg(not(target_arch = "wasm32"))] - fn send(&mut self, job: Job) -> bool { + fn send(&mut self, job: Job) { if !self.spawned { self.spawned = true; self.worker = spawn_worker(); } + match &self.worker { - Some(w) => match w.tx.send(job) { - Ok(()) => true, - Err(e) => { - // The worker is gone: run this and the rest here. + Some(worker) => { + if let Err(error) = worker.tx.send(job) { + // A stopped worker cannot complete any of its outstanding jobs self.worker = None; - self.inline.push_back(e.0); - true + self.in_flight.clear(); + self.in_flight.insert((error.0.generation, error.0.target)); + self.inline.push_back(error.0); } - }, - None => { - self.inline.push_back(job); - true } + None => self.inline.push_back(job), } } #[cfg(target_arch = "wasm32")] - fn send(&mut self, job: Job) -> bool { + fn send(&mut self, job: Job) { self.inline.push_back(job); - true } - fn collect(&mut self) { - let mut done: Vec = Vec::new(); + fn collect(&mut self) -> bool { + let mut completed = Vec::new(); + let mut changed = false; #[cfg(not(target_arch = "wasm32"))] - if let Some(w) = &self.worker { - while let Ok(d) = w.rx.try_recv() { - done.push(d); + if let Some(worker) = &self.worker { + loop { + match worker.rx.try_recv() { + Ok(result) => completed.push(result), + Err(std::sync::mpsc::TryRecvError::Empty) => break, + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + // Request another frame so wanted targets retry on the inline fallback + self.worker = None; + self.in_flight.clear(); + changed = true; + break; + } + } } } - // Without a thread one job runs per frame, so the interface keeps its pace. + + // Without a thread, bound each poll to one render if let Some(job) = self.inline.pop_front() { let image = job.snapshot.render(job.target); - done.push(Done { generation: job.generation, target: job.target, image }); + completed.push(Done { generation: job.generation, target: job.target, image }); } - for d in done { - self.rendered += 1; - // A picture of an older snapshot never replaces a newer one. - if d.generation != self.generation { + + for result in completed { + self.rendered = self.rendered.wrapping_add(1); + self.in_flight.remove(&(result.generation, result.target)); + + // A picture of an older snapshot never replaces a newer one + if result.generation != self.generation { continue; } - self.in_flight.remove(&d.target); - if !self.snapshot.as_ref().is_some_and(|sn| sn.has(d.target)) { + + if !self.snapshot.as_ref().is_some_and(|snapshot| snapshot.has(result.target)) { continue; } - self.versions += 1; - let entry = Entry { image: d.image.map(Arc::new), generation: d.generation, version: self.versions, used: self.tick }; - self.cache.insert(d.target, entry); + + self.versions = self.versions.wrapping_add(1); + let entry = Entry { image: result.image.map(Arc::new), generation: result.generation, version: self.versions, used: self.tick }; + self.cache.insert(result.target, entry); + changed = true; } + + changed } fn trim(&mut self) { @@ -395,3 +424,142 @@ impl ThumbService { !self.queue.is_empty() || !self.in_flight.is_empty() || !self.inline.is_empty() } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + use texturecraft_core::Channel; + use texturecraft_geom::primitives; + + #[test] + fn unchanged_baked_handles_match_even_with_non_finite_samples() { + let mut session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let baked = session.doc.baked.entry(0).or_default(); + baked.resolution = 1; + baked.maps.insert(texturecraft_core::BakedMap::Height, Arc::new(vec![f32::NAN])); + let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap(); + + assert!(snapshot.matches(&session, 0), "unchanged shared data must not invalidate every frame"); + + let map = session.doc.baked.get_mut(&0).unwrap().maps.get_mut(&texturecraft_core::BakedMap::Height).unwrap(); + Arc::make_mut(map)[0] = 0.5; + assert!(!snapshot.matches(&session, 0), "a copy-on-write edit must invalidate the snapshot"); + } + + #[test] + #[ignore] + fn benchmark_unchanged_4k_baked_snapshot() { + let mut session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let baked = session.doc.baked.entry(0).or_default(); + baked.resolution = 4096; + baked.maps.insert(texturecraft_core::BakedMap::Normal, Arc::new(vec![0.5; 4096 * 4096 * 3])); + baked.maps.insert(texturecraft_core::BakedMap::AmbientOcclusion, Arc::new(vec![0.5; 4096 * 4096])); + let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap(); + let start = std::time::Instant::now(); + + for _ in 0..20 { + assert!(std::hint::black_box(&snapshot).matches(std::hint::black_box(&session), 0)); + } + + eprintln!("20 unchanged snapshot comparisons, 4K normal + AO (256 MiB): {:?}", start.elapsed()); + } + + #[test] + fn collecting_the_last_result_requests_a_frame_to_display_it() { + let session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor }; + let (sender, jobs) = std::sync::mpsc::channel(); + let (results, receiver) = std::sync::mpsc::channel(); + let mut service = ThumbService { worker: Some(Worker { tx: sender, rx: receiver }), spawned: true, ..Default::default() }; + service.begin_frame(&session, 0.0); + service.get(&session, target); + assert!(service.poll(&session)); + let job = jobs.try_recv().unwrap(); + results.send(Done { generation: job.generation, target, image: job.snapshot.render(target) }).unwrap(); + + service.begin_frame(&session, 0.1); + assert!(service.get(&session, target).image.is_none()); + let repaint = service.poll(&session); + + assert!(service.is_fresh(target)); + assert!(repaint, "the frame drew before collecting the final thumbnail"); + service.begin_frame(&session, 0.2); + assert!(service.get(&session, target).image.is_some()); + assert!(!service.poll(&session), "an idle cache must stop repainting"); + } + + #[test] + fn a_stopped_worker_retries_visible_targets_inline() { + let session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor }; + let (sender, jobs) = std::sync::mpsc::channel(); + let (results, receiver) = std::sync::mpsc::channel(); + let mut service = ThumbService { worker: Some(Worker { tx: sender, rx: receiver }), spawned: true, ..Default::default() }; + service.begin_frame(&session, 0.0); + service.get(&session, target); + service.poll(&session); + + // Simulate a worker that stops with a dispatched request still outstanding + drop(jobs); + drop(results); + for frame in 1..=4 { + service.begin_frame(&session, f64::from(frame)); + service.get(&session, target); + service.poll(&session); + } + + assert!(service.get(&session, target).image.is_some()); + assert!(!service.busy()); + } + + #[test] + fn edits_keep_worker_jobs_and_retained_snapshots_bounded() { + let mut session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let layer = session.selected_layer().unwrap(); + let target = ThumbTarget::Content { layer, channel: Channel::BaseColor }; + let (sender, jobs) = std::sync::mpsc::channel(); + let (results, receiver) = std::sync::mpsc::channel(); + let mut service = ThumbService { worker: Some(Worker { tx: sender, rx: receiver }), spawned: true, ..Default::default() }; + let mut snapshots = Vec::new(); + + // Hold the worker's receiver still while repeated edits each produce a new snapshot + for revision in 0..2_000 { + session.doc.pixels.layer_mut(layer, Channel::BaseColor, (128, 128)).set(0, 0, &[revision, 0, 0, u16::MAX]); + session.revision += 1; + service.begin_frame(&session, f64::from(revision)); + snapshots.push(Arc::downgrade(service.snapshot.as_ref().unwrap())); + service.get(&session, target); + service.poll(&session); + } + + let queued: Vec<_> = jobs.try_iter().collect(); + let retained = snapshots.iter().filter(|snapshot| snapshot.strong_count() > 0).count(); + let retained_pixel_bytes: usize = snapshots.iter().filter_map(std::sync::Weak::upgrade).map(|snapshot| snapshot.pixels.bytes()).sum(); + eprintln!("2,000 edits: {} queued jobs, {retained} live snapshots, {retained_pixel_bytes} retained pixel bytes", queued.len()); + assert!(queued.len() <= IN_FLIGHT, "{} queued jobs bypassed the worker limit", queued.len()); + assert!(retained <= IN_FLIGHT + 1, "{retained} document snapshots retained across edits"); + assert!(retained_pixel_bytes <= (IN_FLIGHT + 1) * texturecraft_texel::TILE_AREA * 4 * std::mem::size_of::()); + + // Finishing stale work frees a slot for the newest document, without caching old results + for job in queued { + results.send(Done { generation: job.generation, target: job.target, image: None }).unwrap(); + } + + assert_eq!(snapshots.iter().filter(|snapshot| snapshot.strong_count() > 0).count(), 1, "completed jobs release stale snapshots"); + assert!(service.poll(&session)); + assert!(!service.is_fresh(target)); + let latest = jobs.try_recv().unwrap(); + assert_eq!(latest.generation, service.generation); + results.send(Done { generation: latest.generation, target, image: latest.snapshot.render(target) }).unwrap(); + drop(latest); + assert!(service.poll(&session)); + assert!(service.is_fresh(target)); + + let image = Arc::downgrade(service.cache.get(&target).unwrap().image.as_ref().unwrap()); + drop(service); + + assert!(snapshots.iter().all(|snapshot| snapshot.upgrade().is_none()), "dropping the cache releases its last snapshot"); + assert!(image.upgrade().is_none(), "dropping the cache releases the rendered image"); + assert!(jobs.try_recv().is_err()); + } +} diff --git a/crates/engine/tests/it/thumbs.rs b/crates/engine/tests/it/thumbs.rs index 203896d3..5e795a03 100644 --- a/crates/engine/tests/it/thumbs.rs +++ b/crates/engine/tests/it/thumbs.rs @@ -40,10 +40,20 @@ fn stack(s: &mut Session) -> Stack { } fn inputs<'a>(s: &'a Session, project: &'a texturecraft_engine::core::Project, gbuf: &'a UvGBuffer) -> Inputs<'a> { - let none = Default::default(); - // Leaked: the oracle only lives for the test. - let baked: &'a _ = Box::leak(Box::new(s.doc.baked.get(&0).cloned().unwrap_or(none))); - Inputs { project, ts: 0, mesh: &s.mesh, gbuf, pixels: &s.doc.pixels, baked, block_scales: Default::default(), preview: None, images: &s.images, bounds: s.mesh.bounds() } + static EMPTY_BAKED: std::sync::LazyLock = std::sync::LazyLock::new(Default::default); + let baked = s.doc.baked.get(&0).unwrap_or(&EMPTY_BAKED); + Inputs { + project, + ts: 0, + mesh: &s.mesh, + gbuf, + pixels: &s.doc.pixels, + baked, + block_scales: Default::default(), + preview: None, + images: &s.images, + bounds: s.mesh.bounds(), + } } /// The reference: the same sub-stack cut by hand and evaluated at 64 px with the ordinary CPU @@ -56,7 +66,6 @@ fn oracle(s: &Session, target: ThumbTarget) -> ThumbImage { ThumbTarget::Mask { layer } => (layer, None, Channel::BaseColor), ThumbTarget::Stage { effect, channel } => (p.effect(effect).unwrap().0, Some(effect), channel), }; - p.texture_sets[0].stack = vec![layer]; let l = p.layers.get_mut(&layer).unwrap(); l.visible = true; let in_mask = upto.is_some_and(|e| l.mask.as_ref().is_some_and(|m| m.effects.iter().any(|x| x.id == e))) || matches!(target, ThumbTarget::Mask { .. }); @@ -127,30 +136,34 @@ fn image(svc: &mut ThumbService, s: &Session, t: ThumbTarget) -> ThumbImage { #[test] fn thumbnails_equal_a_cpu_evaluation_of_the_same_sub_stack() { - let mut s = session(); - let st = stack(&mut s); - let base = Channel::BaseColor; + let mut session = session(); + let stack = stack(&mut session); + let base_color = Channel::BaseColor; let targets = [ - ThumbTarget::Content { layer: st.layer, channel: base }, - ThumbTarget::Content { layer: st.layer, channel: Channel::Roughness }, - ThumbTarget::Mask { layer: st.layer }, - ThumbTarget::Stage { effect: st.invert, channel: base }, - ThumbTarget::Stage { effect: st.posterize, channel: base }, - ThumbTarget::Stage { effect: st.gen_, channel: base }, + ThumbTarget::Content { layer: stack.layer, channel: base_color }, + ThumbTarget::Content { layer: stack.layer, channel: Channel::Roughness }, + ThumbTarget::Mask { layer: stack.layer }, + ThumbTarget::Stage { effect: stack.invert, channel: base_color }, + ThumbTarget::Stage { effect: stack.posterize, channel: base_color }, + ThumbTarget::Stage { effect: stack.gen_, channel: base_color }, ]; - let (mut svc, mut clock) = (ThumbService::new(), 0.0); - settle(&mut svc, &s, &targets, &mut clock); - for t in targets { - assert_eq!(image(&mut svc, &s, t), oracle(&s, t), "{t:?}"); + let (mut service, mut clock) = (ThumbService::new(), 0.0); + + settle(&mut service, &session, &targets, &mut clock); + + for target in targets { + assert_eq!(image(&mut service, &session, target), oracle(&session, target), "{target:?}"); } - // Sanity on the values themselves: the first stage is #336699 inverted (in linear light). - let inv = image(&mut svc, &s, targets[3]); - let px = inv.rgba.chunks_exact(4).find(|p| p[3] == 255).unwrap(); - let expect = |byte: f32| (linear_to_srgb(1.0 - texturecraft_engine::texel::srgb_to_linear(byte / 255.0)) * 255.0 + 0.5) as i32; - assert!((px[0] as i32 - expect(51.0)).abs() <= 1 && (px[2] as i32 - expect(153.0)).abs() <= 1, "{px:?}"); - // The mask thumbnail is gray and not flat (a position gradient on a black mask). - let m = image(&mut svc, &s, targets[2]); - let grays: Vec = m.rgba.chunks_exact(4).filter(|p| p[3] == 255).map(|p| p[0]).collect(); + + // The first stage inverts #336699 in linear light + let inverted = image(&mut service, &session, targets[3]); + let pixel = inverted.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap(); + let expected = |byte: f32| (linear_to_srgb(1.0 - texturecraft_engine::texel::srgb_to_linear(byte / 255.0)) * 255.0 + 0.5) as i32; + assert!((i32::from(pixel[0]) - expected(51.0)).abs() <= 1 && (i32::from(pixel[2]) - expected(153.0)).abs() <= 1, "{pixel:?}"); + + // A position generator must produce a nonuniform mask + let mask = image(&mut service, &session, targets[2]); + let grays: Vec = mask.rgba.as_chunks::<4>().0.iter().filter(|pixel| pixel[3] == 255).map(|pixel| pixel[0]).collect(); assert!(grays.iter().max() != grays.iter().min()); } @@ -266,52 +279,130 @@ fn a_result_of_an_older_document_never_replaces_a_newer_one() { #[test] fn only_requested_rows_render_and_the_cache_is_bounded() { - let mut s = session(); - let layers: Vec = (0..(CACHE_ENTRIES + 30)).map(|_| id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap(), "layer")).collect(); - let target = |l: LayerId| ThumbTarget::Content { layer: l, channel: Channel::BaseColor }; - let mut svc = ThumbService::new(); - // A frame asks for six rows, the next frame (scrolled) for only one of them. - svc.begin_frame(&s, 1.0); - for l in &layers[..6] { - svc.get(&s, target(*l)); + let mut session = session(); + let layers: Vec = (0..(CACHE_ENTRIES + 30)).map(|_| id(execute(&mut session, "layer.add.paint", &Value::Null).unwrap(), "layer")).collect(); + let target = |layer: LayerId| ThumbTarget::Content { layer, channel: Channel::BaseColor }; + let mut service = ThumbService::new(); + + // A frame asks for six rows, then scrolling leaves only one visible + service.begin_frame(&session, 1.0); + for layer in &layers[..6] { + service.get(&session, target(*layer)); } - svc.poll(&s); + service.poll(&session); let mut clock = 2.0; for _ in 0..300 { clock += 0.2; - svc.begin_frame(&s, clock); - svc.get(&s, target(layers[0])); - svc.poll(&s); + service.begin_frame(&session, clock); + service.get(&session, target(layers[0])); + service.poll(&session); std::thread::sleep(Duration::from_millis(1)); } - assert!(svc.is_fresh(target(layers[0]))); - // At most the rows already on their way (the in-flight limit) finished besides it. - let done = layers[..6].iter().filter(|l| svc.is_fresh(target(**l))).count(); - assert!(done <= 3, "{done} of the scrolled-away rows were rendered"); - // Scrolling through every layer keeps the cache within its limit. + + assert!(service.is_fresh(target(layers[0]))); + let completed = layers[..6].iter().filter(|layer| service.is_fresh(target(**layer))).count(); + assert!(completed <= 3, "{completed} of the scrolled-away rows were rendered"); + + // Scrolling through every layer evicts pictures and releases their allocations + let mut images = Vec::new(); for chunk in layers.chunks(12) { - let ts: Vec = chunk.iter().map(|l| target(*l)).collect(); - settle(&mut svc, &s, &ts, &mut clock); - assert!(svc.cached() <= CACHE_ENTRIES + 12, "{}", svc.cached()); + let targets: Vec = chunk.iter().map(|layer| target(*layer)).collect(); + settle(&mut service, &session, &targets, &mut clock); + for target in targets { + images.push(std::sync::Arc::downgrade(&service.get(&session, target).image.unwrap())); + } + assert!(service.cached() <= CACHE_ENTRIES, "{}", service.cached()); } clock += 0.2; - svc.begin_frame(&s, clock); - svc.poll(&s); - assert!(svc.cached() <= CACHE_ENTRIES, "{}", svc.cached()); + service.begin_frame(&session, clock); + service.poll(&session); + + assert!(service.cached() <= CACHE_ENTRIES, "{}", service.cached()); + assert!(images.len() > CACHE_ENTRIES); + assert!(images.first().unwrap().upgrade().is_none(), "the oldest image was evicted"); + assert_eq!(images.iter().filter(|image| image.strong_count() > 0).count(), service.cached()); + + drop(service); + + assert!(images.iter().all(|image| image.upgrade().is_none()), "closing the cache releases every picture"); } #[test] fn an_empty_paint_layer_is_transparent_and_a_folder_composites_its_children() { - let mut s = session(); - let paint = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap(), "layer"); - let fill = id(execute(&mut s, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer"); - let folder = id(execute(&mut s, "layer.group", &json!({"layer": fill.0})).unwrap(), "layer"); - let base = Channel::BaseColor; - let (p, f) = (ThumbTarget::Content { layer: paint, channel: base }, ThumbTarget::Content { layer: folder, channel: base }); - let (mut svc, mut clock) = (ThumbService::new(), 0.0); - settle(&mut svc, &s, &[p, f], &mut clock); - assert!(image(&mut svc, &s, p).rgba.chunks_exact(4).all(|px| px[3] == 0), "nothing painted: nothing shown"); - let folder_img = image(&mut svc, &s, f); - let px = folder_img.rgba.chunks_exact(4).find(|px| px[3] == 255).unwrap(); - assert!((px[0] as i32 - 51).abs() <= 1 && (px[2] as i32 - 153).abs() <= 1, "{px:?}"); + let mut session = session(); + let paint = id(execute(&mut session, "layer.add.paint", &Value::Null).unwrap(), "layer"); + let fill = id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer"); + let folder = id(execute(&mut session, "layer.group", &json!({"layer": fill.0})).unwrap(), "layer"); + let paint_target = ThumbTarget::Content { layer: paint, channel: Channel::BaseColor }; + let folder_target = ThumbTarget::Content { layer: folder, channel: Channel::BaseColor }; + let (mut service, mut clock) = (ThumbService::new(), 0.0); + + settle(&mut service, &session, &[paint_target, folder_target], &mut clock); + + assert!(image(&mut service, &session, paint_target).rgba.as_chunks::<4>().0.iter().all(|pixel| pixel[3] == 0), "nothing painted: nothing shown"); + let folder_image = image(&mut service, &session, folder_target); + let pixel = folder_image.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap(); + assert!((i32::from(pixel[0]) - 51).abs() <= 1 && (i32::from(pixel[2]) - 153).abs() <= 1, "{pixel:?}"); +} + +#[test] +fn instances_preview_the_source_content_and_inherited_mask() { + use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot}; + + let mut session = session(); + let stack = stack(&mut session); + let instance = id(execute(&mut session, "layer.instance", &json!({"layer": stack.layer.0})).unwrap(), "layer"); + let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap(); + + for channel in [Channel::BaseColor, Channel::Roughness] { + let source = snapshot.render(ThumbTarget::Content { layer: stack.layer, channel }).unwrap(); + let preview = snapshot.render(ThumbTarget::Content { layer: instance, channel }); + + assert!(preview == Some(source), "the instance inherits {channel:?} from its source"); + } + + assert_eq!(snapshot.render(ThumbTarget::Mask { layer: instance }), snapshot.render(ThumbTarget::Mask { layer: stack.layer })); +} + +#[test] +fn thumbnails_keep_anchor_inputs_from_lower_layers() { + use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot}; + + let mut session = session(); + execute(&mut session, "layer.add.fill", &json!({"height": 0.25})).unwrap(); + let anchor = id(execute(&mut session, "effect.add.anchor", &Value::Null).unwrap(), "effect"); + let layer = id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer"); + execute(&mut session, "layer.fill.set", &json!({"channel": "roughness", "anchor": anchor.0, "anchorChannel": "height"})).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + let mask_effect = id(execute(&mut session, "effect.add.fill", &json!({"anchor": anchor.0, "anchorChannel": "height"})).unwrap(), "effect"); + let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap(); + + for target in [ + ThumbTarget::Content { layer, channel: Channel::Roughness }, + ThumbTarget::Mask { layer }, + ThumbTarget::Stage { effect: mask_effect, channel: Channel::BaseColor }, + ] { + let image = snapshot.render(target).unwrap(); + let pixel = image.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap(); + + assert!((i32::from(pixel[0]) - 64).abs() <= 1, "{target:?} must read the lower anchor's 0.25, got {pixel:?}"); + } +} + +#[test] +fn folder_thumbnails_keep_anchors_outside_the_folder() { + use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot}; + + let mut session = session(); + execute(&mut session, "layer.add.fill", &json!({"height": 0.25})).unwrap(); + let anchor = id(execute(&mut session, "effect.add.anchor", &Value::Null).unwrap(), "effect"); + let layer = id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer"); + execute(&mut session, "layer.fill.set", &json!({"channel": "roughness", "anchor": anchor.0, "anchorChannel": "height"})).unwrap(); + let folder = id(execute(&mut session, "layer.group", &json!({"layer": layer.0})).unwrap(), "layer"); + let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap(); + + let image = snapshot.render(ThumbTarget::Content { layer: folder, channel: Channel::Roughness }).unwrap(); + let pixel = image.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap(); + + assert!((i32::from(pixel[0]) - 64).abs() <= 1, "the folder must read the external anchor's 0.25, got {pixel:?}"); } diff --git a/crates/ui-egui/src/layer_panel.rs b/crates/ui-egui/src/layer_panel.rs index a29fa288..27dc5f67 100644 --- a/crates/ui-egui/src/layer_panel.rs +++ b/crates/ui-egui/src/layer_panel.rs @@ -49,6 +49,9 @@ impl LayerPanel { pub(crate) fn begin(&mut self, session: &Session, now: f64) { self.frame += 1; self.service.begin_frame(session, now); + + // Deleted layer IDs must not accumulate in panel state + self.folded.retain(|(layer, _)| session.doc.project.layers.contains_key(&texturecraft_engine::core::LayerId(*layer))); } /// The texture of `target`, queuing its render (call only for rows that are on screen). @@ -85,3 +88,57 @@ impl LayerPanel { &self.service } } + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_engine::core::{Channel, LayerId}; + use texturecraft_engine::geom::primitives; + + #[test] + fn deleted_layers_release_their_fold_state() { + let mut session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let layer = session.selected_layer().unwrap(); + let mut panel = LayerPanel::default(); + panel.folded.extend([(layer.0, false), (layer.0, true)]); + panel.begin(&session, 0.0); + assert_eq!(panel.folded.len(), 2, "existing layers keep their view settings"); + + texturecraft_engine::execute(&mut session, "layer.remove", &serde_json::json!({"layer": layer.0})).unwrap(); + panel.begin(&session, 1.0); + + assert!(panel.folded.is_empty(), "deleted layer IDs must not accumulate in view state"); + } + + #[test] + fn evicted_and_dropped_thumbnail_handles_release_textures() { + let session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let context = Context::default(); + let initial_textures = context.tex_manager().read().num_allocated(); + let mut panel = LayerPanel::default(); + let mut evicted = Vec::new(); + panel.begin(&session, 0.0); + + // Simulate scrolling through more textures than the UI cache retains + for index in 0..CACHE_ENTRIES * 2 + 1 { + let target = ThumbTarget::Content { layer: LayerId(index as u64), channel: Channel::BaseColor }; + let image = egui::ColorImage::filled([64, 64], egui::Color32::WHITE); + let texture = context.load_texture("layer-thumb", image, TextureOptions::LINEAR); + evicted.push(texture.id()); + panel.textures.insert(target, (1, texture, panel.frame)); + } + let kept = evicted.pop().unwrap(); + panel.begin(&session, 1.0); + panel.begin(&session, 2.0); + panel.textures.values_mut().find(|(_, texture, _)| texture.id() == kept).unwrap().2 = panel.frame; + panel.end(&context, &session); + + assert_eq!(context.tex_manager().read().num_allocated(), initial_textures + 1); + assert!(evicted.iter().all(|id| context.tex_manager().read().meta(*id).is_none())); + assert!(context.tex_manager().read().meta(kept).is_some()); + + drop(panel); + + assert_eq!(context.tex_manager().read().num_allocated(), initial_textures); + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 2756a942..2ddcd76b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -73,21 +73,25 @@ normal channel and baked normals by reoriented normal mapping, and packs channel The Layers panel shows each layer's content (in the displayed channel), its mask and every effect stage as small pictures. `compose::thumb::render` runs the same compositor on a *cut* copy of the -project: the set's stack becomes the one layer, forced visible at Normal / 100 %, without its mask -for the content, and with its effect list truncated after the previewed effect (a hidden effect -shows the result it bypasses). Paint and fill layers are flattened to (value, coverage), so empty -texels are transparent; folders composite their children. Colors are encoded linear to sRGB, data -channels raw. Everything is evaluated on a 64 px G-buffer of the mesh (painted tiles are -resampled), never at the set's resolution, and the main composite is never touched. +project: the requested layer is forced visible at Normal / 100 %, without its mask for content, +and with its effect list truncated after the previewed effect (a hidden effect shows the result +it bypasses). Lower layers remain available when the preview reads anchor points; only the requested +layer is drawn. Instances use their source's channels. Paint and fill layers are flattened to +(value, coverage), so empty texels are transparent; folders composite their children. Colors are +encoded linear to sRGB, data channels raw. Everything is evaluated on a 64 px G-buffer of the mesh +(painted tiles are resampled), never at the set's resolution, and the main composite is never touched. `engine::thumbs::ThumbService` runs it off the UI thread: an immutable `ThumbSnapshot` (the project, copy-on-write pixel tiles, baked maps, images and the cached 64 px G-buffer) is rebuilt only when the document really differs (compared at most every 120 ms while it keeps changing), a worker thread renders one job at a time (inline, one per frame, on wasm32), results of an older -snapshot are dropped, and an LRU of 96 pictures keeps the out-of-date picture on screen until its -replacement arrives. Only rows on screen ask for pictures; queued rows that scrolled away are -dropped. On a 4096 set (`perf::bench_layer_thumbs_4k`) a snapshot costs 0.02 ms, a content picture -about 2.5 ms and a whole ten-layer panel (20 pictures) about 42 ms of worker time. +snapshot are dropped. At most two jobs, including stale generations, retain snapshots in the worker. +Collecting a result requests another frame to display it. An LRU of 96 pictures keeps the out-of-date +picture on screen until its replacement arrives. Only rows on screen ask for pictures; queued rows +that scrolled away are dropped. Baked-map changes are checked by shared buffer identity, without +scanning full-resolution float arrays on the UI thread. Run `perf::bench_layer_thumbs_4k` in release mode to measure snapshot +construction and content, mask and stage rendering on a ten-layer 4096 set. Run +`thumbs::tests::benchmark_unchanged_4k_baked_snapshot` to measure comparisons with 256 MiB of baked maps. ## Undo From 208c645d0cea999371650f7c8738c7b325b52084 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Tue, 10 Nov 2026 06:40:11 -0500 Subject: [PATCH 5/7] Show a whole material at once: coarse first look, then the exact result Applying a material filled the model in tile by tile, and each apply made the next one slower. Now: - a big recomposite first draws a coarse look of every tile (sampled texels repeated across blocks), then refines to the exact result; - layers hidden behind an opaque layer are skipped (not when anchors or height masks are involved); - compositing and upload budgets adapt: larger when idle, smaller while the user is interacting, and uploads reserve time for conversion; - no coarse pass during a live stroke or with neighbourhood filters; - blending at full weight returns the blended value exactly. Tests: coarse-then-exact, hidden-layer culling gives identical pixels, coarse pass covers every tile, no coarse pass while a stroke is live. Co-Authored-By: Claude Sonnet 5.5 --- crates/compose/src/eval.rs | 159 ++++++++++++++++++- crates/compose/src/lib.rs | 4 +- crates/compose/tests/cache_and_instances.rs | 32 ++++ crates/core/src/blend.rs | 5 + crates/engine/src/inspect.rs | 5 + crates/engine/src/session.rs | 92 +++++++++-- crates/engine/tests/it/instances.rs | 6 +- crates/engine/tests/session.rs | 163 ++++++++++++++++++++ crates/ui-egui/src/gpu.rs | 69 ++++++++- crates/ui-egui/src/viewport.rs | 6 +- 10 files changed, 510 insertions(+), 31 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 3a9404d3..459e5daf 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -801,6 +801,22 @@ fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32 out } +/// Whether texture set `ts` has a layer with a neighbourhood filter (blur, sharpen, warp…) in +/// its mask or content: a composite then precomputes [`neighbourhood_fields`] at full +/// resolution, so even a [`composite_tiles_coarse`] is not much cheaper than the exact one. +/// The same layers as `neighbourhood_fields` looks at (it may count a hidden one). +pub fn has_neighbourhood_filters(project: &Project, ts: usize) -> bool { + let Ok(set) = project.texture_set(ts) else { return false }; + let mut order = Vec::new(); + draw_order(project, &set.stack, 0, &mut order); + let res = set.resolution; + order.iter().any(|id| { + let mask = layer_mask(project, *id).is_some_and(|m| m.enabled && neighbourhood(&m.effects, res).is_some()); + let content = project.content_layer(*id).is_some_and(|l| !l.is_group() && neighbourhood(&l.content_effects, res).is_some()); + mask || content + }) +} + /// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); @@ -897,10 +913,89 @@ fn mask_plan<'a>(inp: &Inputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32 } fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>) -> Vec> { + plan_with(inp, list, channels, tx, ty, depth, fields, false) +} + +/// [`plan`], leaving out what an opaque layer above hides when `cull` (see [`cull_hidden`]). +/// Only for lists that are evaluated whole and not looked into (no anchor or stop layer reads). +#[allow(clippy::too_many_arguments)] +fn plan_with<'a>( + inp: &Inputs<'a>, + list: &[LayerId], + channels: &[Channel], + tx: u32, + ty: u32, + depth: usize, + fields: Option<&'a Fields>, + cull: bool, +) -> Vec> { if depth > texturecraft_core::project::MAX_DEPTH { return Vec::new(); } - list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true)).collect() + let mut nodes: Vec> = list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true, cull)).collect(); + if cull { + cull_hidden(&mut nodes, channels); + } + nodes +} + +/// Whether node `n` hides everything below it in channel `ch`: it replaces the stack there at +/// every texel (full opacity, normal blend, no mask or geometry or height mask, a fill that +/// covers the whole surface with no content effects), or is a folder at full opacity holding +/// such a layer. +fn occludes(n: &Node, ch: usize) -> bool { + if n.mask.is_some() || n.parts.is_some() || n.height_mask.enabled { + return false; + } + let Some(c) = n.chans.iter().find(|c| c.ch == ch) else { return false }; + if c.opacity < 1.0 { + return false; + } + match &n.content { + Content::Fill(f) => c.blend == BlendMode::Normal && !matches!(f.projection, Projection::Decal(_)) && c.effects.is_empty() && c.start.is_none(), + Content::Group(kids) => kids.iter().any(|k| occludes(k, ch)), + Content::Paint { .. } => false, + } +} + +/// Whether `n` or a layer in it masks with its height. +fn uses_height_mask(n: &Node) -> bool { + n.height_mask.enabled || matches!(&n.content, Content::Group(kids) if kids.iter().any(uses_height_mask)) +} + +/// Take channel `ch` out of `n` (and what it holds), dropping what then draws nothing. +fn strip_channel(n: &mut Node, ch: usize) { + n.chans.retain(|c| c.ch != ch); + if let Content::Group(kids) = &mut n.content { + for k in kids.iter_mut() { + strip_channel(k, ch); + } + kids.retain(|k| !k.chans.is_empty()); + } +} + +/// Leave out the layers (per channel) that a layer above them hides completely: a stack that +/// grows by applying material after material would otherwise evaluate every one of them. The +/// result is identical. Channels with anchor points or height masks below the hiding layer +/// are left alone (they read other layers' values), and so are those under a hiding folder +/// that records an anchor point: its inner stack starts from what lies below it, so an anchor +/// under the hiding layer inside it holds the layers it hides. +fn cull_hidden(nodes: &mut Vec, channels: &[Channel]) { + for c in channels { + let ch = c.index(); + let Some(k) = nodes.iter().rposition(|n| occludes(n, ch)) else { continue }; + if nodes.get(k).is_some_and(|n| n.has_anchor) { + continue; + } + let Some(below) = nodes.get_mut(..k) else { continue }; + if below.iter().any(|n| n.has_anchor || (*c == Channel::Height && uses_height_mask(n))) { + continue; + } + for n in below.iter_mut() { + strip_channel(n, ch); + } + } + nodes.retain(|n| !n.chans.is_empty() || n.has_anchor); } /// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are @@ -915,6 +1010,7 @@ fn plan_node<'a>( depth: usize, fields: Option<&'a Fields>, kids: bool, + cull: bool, ) -> Option> { let own: &'a Layer = inp.project.layers.get(&id)?; // Instances draw their source's content (a missing source draws nothing). @@ -941,7 +1037,9 @@ fn plan_node<'a>( let content = match &layer.kind { LayerKind::Paint => Content::Paint { preview: previews(inp, PaintTarget::Layer(layer.id)) }, LayerKind::Fill(f) => Content::Fill(f), - LayerKind::Group { children, .. } => Content::Group(if kids { plan(inp, children, channels, tx, ty, depth + 1, fields) } else { Vec::new() }), + LayerKind::Group { children, .. } => { + Content::Group(if kids { plan_with(inp, children, channels, tx, ty, depth + 1, fields, cull) } else { Vec::new() }) + } // `content_layer` already followed instance links. LayerKind::Instance { .. } => return None, }; @@ -988,8 +1086,8 @@ fn plan_levels<'a>(inp: &Inputs<'a>, levels: &[Level], channels: &[Channel], tx: .iter() .enumerate() .map(|(d, l)| LevelPlan { - below: if warm { Vec::new() } else { plan(inp, &l.below, channels, tx, ty, d, Some(fields)) }, - at: plan_node(inp, l.at, channels, tx, ty, d, Some(fields), d == last), + below: if warm { Vec::new() } else { plan_with(inp, &l.below, channels, tx, ty, d, Some(fields), true) }, + at: plan_node(inp, l.at, channels, tx, ty, d, Some(fields), d == last, false), above: plan(inp, &l.above, channels, tx, ty, d, Some(fields)), }) .collect() @@ -1658,6 +1756,35 @@ pub fn composite_tiles(inp: &Inputs, out: &mut Composite, tiles: &[(u32, u32)]) composite_tiles_cached(inp, out, tiles, None); } +/// The strides a coarse composite ([`composite_tiles_coarse`]) takes, coarsest first: texels +/// per block side, one evaluated per block. Each divides the rows of a band and a tile, so a +/// block never crosses bands or tiles. A big recomposite shows them in this order before the +/// exact composite. One level: a coarse pass costs about the same at any stride (writing, +/// padding and uploading the full-resolution tiles dominate once one texel in 64 is +/// evaluated; measured 4096², 3217 tiles: 139 ms at 16, 150 at 8, 254 at 4, 2.1 s exact), so +/// a second level would only add that cost again before the exact composite. +pub const COARSE_STRIDES: [u32; 1] = [8]; + +/// A quick look at `tiles`: [`composite_tiles`] evaluating one texel in every `stride` by `stride` +/// block (its first covered texel) and repeating it over the block's covered texels (a texel only +/// depends on its own position, so the evaluated ones are exact; the rest are as blocky as a +/// lower resolution), about `stride`² times fewer evaluations. A `stride` that does not divide a band and a tile composites exactly. A later +/// [`composite_tiles`] of the same tiles gives the exact result. +pub fn composite_tiles_coarse(inp: &Inputs, out: &mut Composite, tiles: &[(u32, u32)], stride: u32) { + let Ok(set) = inp.project.texture_set(inp.ts) else { return }; + if (inp.gbuf.width, inp.gbuf.height) != (out.resolution, out.height) { + return; + } + let step = if stride > 0 && BAND.is_multiple_of(stride) && TILE.is_multiple_of(stride) { stride } else { 1 }; + let mut blocks: BTreeMap<(u32, u32), Vec<(u32, u32)>> = BTreeMap::new(); + for t in tiles { + blocks.entry((t.1 / BLOCK, t.0 / BLOCK)).or_default().push(*t); + } + for block in blocks.values() { + composite_block(inp, &set.stack, out, block, None, 0, step); + } +} + /// Tiles per side of the blocks a composite works through (bounds neighbourhood-filter memory). const BLOCK: u32 = 16; @@ -1686,7 +1813,7 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, None => 0, }; let cached = below.as_deref().zip(split.as_deref()); - let records = composite_block(inp, &set.stack, out, block, cached, quota); + let records = composite_block(inp, &set.stack, out, block, cached, quota, 1); if let Some(b) = below.as_deref_mut() { for t in block { b.touch(*t); @@ -1717,6 +1844,7 @@ fn composite_block( tiles: &[(u32, u32)], below: Option<(&BelowCache, &[Level])>, quota: usize, + step: u32, ) -> Vec<((u32, u32), Vec)> { let channels: Vec = inp.project.texture_set(inp.ts).map(|s| s.channel_list()).unwrap_or_default(); let (w, h) = (out.resolution, out.height); @@ -1746,7 +1874,7 @@ fn composite_block( let warm = cached((tx, ty)).and_then(|b| b.get(band as usize)); let record = warm.is_none() && recorded.contains(&(tx, ty)); let levels = split.map(|l| plan_levels(inp, l, &channels, tx, ty, &fields, warm.is_some())); - let nodes = if levels.is_none() { plan(inp, stack, &channels, tx, ty, 0, Some(&fields)) } else { Vec::new() }; + let nodes = if levels.is_none() { plan_with(inp, stack, &channels, tx, ty, 0, Some(&fields), true) } else { Vec::new() }; let rows = (BAND * TILE) as usize; let mut accs = vec![defaults; nlev]; let mut masks = vec![0.0f32; nlev]; @@ -1770,11 +1898,17 @@ fn composite_block( let mut bufs: Vec> = channels.iter().map(|c| vec![0u16; rows * c.components()]).collect(); let mut anchors = Vec::new(); let mut any = false; + // Coarse: per `step`-wide block of the current block row, the value of its first + // covered texel (evaluated), repeated over the block's other covered texels. + let mut sampled: Vec> = vec![None; if step > 1 { (TILE / step) as usize } else { 0 }]; for ly in band * BAND..(band + 1) * BAND { let y = ty * TILE + ly; if y >= h { break; } + if step > 1 && ly % step == 0 { + sampled.fill(None); + } for lx in 0..TILE { let x = tx * TILE + lx; if x >= w { @@ -1786,7 +1920,12 @@ fn composite_block( let ob = ((ly - band * BAND) * TILE + lx) as usize; let covered = inp.gbuf.tri.get(gi).is_some_and(|t| *t != NO_TRI); let mut acc = defaults; - if covered { + let block = if step > 1 { sampled.get_mut((lx / step) as usize) } else { None }; + let repeated = block.as_ref().and_then(|b| **b); + if covered && let Some(a) = repeated { + any = true; + acc = a; + } else if covered { any = true; let mut tex = Texel::new(inp, x, y, o, stroke_at(preview_tile, o)); // Reuse one anchor buffer per band. @@ -1818,6 +1957,12 @@ fn composite_block( anchors = tex.anchors; anchors.clear(); } + if covered + && repeated.is_none() + && let Some(slot) = block + { + *slot = Some(acc); + } for (l, buf) in lanes.iter().zip(&mut bufs) { let v = acc.get(l.ch).copied().unwrap_or([0.0; 3]); for (k, x) in v.iter().take(l.n).enumerate() { diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index fe57e611..3ec1ab94 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -19,7 +19,7 @@ pub mod store; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; pub use eval::{ - Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, - mask_at, mask_image, pad_tiles, + COARSE_STRIDES, Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, composite_tiles_coarse, + covered_tiles, effect_histogram, flatten_layer, has_neighbourhood_filters, mask_at, mask_image, pad_tiles, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index d7df0258..50d125a6 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -573,3 +573,35 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() { assert!(!check_cached(&f, 0, hot).is_empty()); } } + +/// A folder that hides the layers below it but records an anchor point inside (under its own +/// hiding layer) keeps them: its inner stack starts from them, so the anchor holds them. +#[test] +fn layers_under_a_hiding_folder_with_an_anchor_are_not_culled() { + let mut f = fixture(); + let only = |f: &mut Fixture, id: LayerId, c: Channel| f.project.layer_mut(id).unwrap().channels.retain(|x, _| *x == c); + let low = add(&mut f, 0, fill(&[(Channel::BaseColor, Source::Uniform([0.9; 3]))]), None); + only(&mut f, low, Channel::BaseColor); + let group = add(&mut f, 0, LayerKind::Group { children: vec![], collapsed: false }, None); + // Inside: a half-opacity fill recording anchor A, then an opaque fill hiding everything. + let anchored = put(&mut f, 0, Some(group), fill(&[(Channel::BaseColor, Source::Uniform([0.5; 3]))]), None); + only(&mut f, anchored, Channel::BaseColor); + blend(&mut f, anchored, BlendMode::Normal, 0.5); + let anchor = effect(&mut f, EffectKind::Anchor); + let anchor_id = anchor.id; + f.project.layer_mut(anchored).unwrap().content_effects.push(anchor); + let hiding = put(&mut f, 0, Some(group), fill(&[(Channel::BaseColor, Source::Uniform([0.1; 3]))]), None); + only(&mut f, hiding, Channel::BaseColor); + // Above the folder, roughness reads the base color held by A. + let reader = add(&mut f, 0, fill(&[(Channel::Roughness, Source::Anchor { anchor: anchor_id, channel: Channel::BaseColor })]), None); + only(&mut f, reader, Channel::Roughness); + let out = reference(&f, 0); + let rough = out.value(Channel::Roughness, 128, 128)[0]; + // A = 0.5 at half opacity over the low layer's 0.9. + assert!((rough - 0.7).abs() < 2e-3, "the anchor holds the layer under the folder: {rough}"); + assert!((out.value(Channel::BaseColor, 128, 128)[0] - 0.1).abs() < 2e-3); + // The same stack with an (unread) anchor on the low layer is never culled: identical. + let keep = effect(&mut f, EffectKind::Anchor); + f.project.layer_mut(low).unwrap().content_effects.push(keep); + assert!(reference(&f, 0) == out, "culling changed the composite"); +} diff --git a/crates/core/src/blend.rs b/crates/core/src/blend.rs index 5f165cdb..c7fa7e64 100644 --- a/crates/core/src/blend.rs +++ b/crates/core/src/blend.rs @@ -350,6 +350,11 @@ pub fn blend3(mode: BlendMode, a: [f32; 3], b: [f32; 3]) -> [f32; 3] { /// Mix `blended` over `a` by weight `w` (coverage × opacity × mask). pub fn mix3(a: [f32; 3], blended: [f32; 3], w: f32) -> [f32; 3] { + // A full-weight blend is exactly the blended value (`a + (b - a)` can be an ulp off it): what + // lies under it does not leak in, so skipping the layers it hides changes nothing at all. + if w >= 1.0 { + return blended; + } [a[0] + (blended[0] - a[0]) * w, a[1] + (blended[1] - a[1]) * w, a[2] + (blended[2] - a[2]) * w] } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 2db27946..603e7b17 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -193,5 +193,10 @@ pub fn session(s: &Session) -> Value { "history": { "undo": s.undo_label(), "redo": s.redo_label(), "depth": s.history_labels().len() }, "memoryBytes": s.memory().total(), "pendingTiles": s.pending_tiles(), + // Tiles with no look of the current composite yet, tiles shown from a coarse pass only + // (their exact composite pending), and the coarsest stride shown (0: none). + "dirtyTiles": s.caches.iter().map(|c| c.dirty.len()).sum::(), + "coarseTiles": s.caches.iter().map(|c| c.refine.len()).sum::(), + "coarsestStride": s.caches.iter().flat_map(|c| c.refine.values().copied()).max().unwrap_or(0), }) } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 64ebec69..6b721a79 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde::{Deserialize, Serialize}; -use texturecraft_compose::{BakedMaps, BelowCache, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles}; +use texturecraft_compose::{BakedMaps, BelowCache, COARSE_STRIDES, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles}; use texturecraft_core::{Channel, Layer, LayerId, LayerKind, Project, TextureSet}; use texturecraft_geom::glam::Vec2; use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer}; @@ -43,14 +43,24 @@ pub struct SetCache { /// Tiles to recomposite at low priority: what they show is already right (a committed /// stroke's live preview), but it was composited from the stroke, not the layer pixels. pub settle: BTreeSet<(u32, u32)>, + /// Tiles shown from a coarse pass ([`texturecraft_compose::composite_tiles_coarse`]) with + /// the stride they were composited at; they still need the finer ones and the exact one. A + /// big recomposite (a material applied) first looks right everywhere at a small part of the + /// cost, then sharpens level by level ([`texturecraft_compose::COARSE_STRIDES`]), each level + /// over every tile before the next, so the surface is always at one consistent level. + pub refine: BTreeMap<(u32, u32), u32>, + /// The dirty tiles go through a coarse pass: decided when a big recomposite starts and + /// kept until `dirty` drains, so its last few tiles do not go exact at the full price. + pub coarse_pass: bool, /// Tiles whose display textures must be re-uploaded. pub upload: BTreeSet<(u32, u32)>, /// Bumps on every composite change (thumbnails, exports, caches). pub revision: u64, /// Everything but the layer being edited, per tile (repaints evaluate only that layer). pub below: BelowCache, - /// Tiles per composite chunk that fit the last frame's budget (0: not measured yet). - pub chunk: usize, + /// Wall-clock milliseconds per tile of the last exact composite chunk (0: not measured + /// yet): the first chunk of a budgeted update is sized from it and that update's budget. + pub tile_ms: f64, } impl SetCache { @@ -69,10 +79,12 @@ impl SetCache { composite: Composite { block_scales: ts.block_scales(), ..Composite::with_size(&ts.channel_list(), w, h) }, dirty: all.clone(), settle: BTreeSet::new(), + refine: BTreeMap::new(), + coarse_pass: false, upload: all, revision: 0, below: BelowCache::default(), - chunk: 0, + tile_ms: 0.0, } } @@ -715,23 +727,60 @@ impl Session { carried: s.canvas.pickup.as_ref().map(|p| p.values.clone()).unwrap_or_default(), }) }); + // A coarse look first only when there is a frame budget to spread a big change over, and + // never under a live stroke (it keeps the exact, cached repaint of the hot layer). + let coarse_allowed = budget_ms.is_finite() && self.stroke.is_none(); let active = self.ts(); let order = std::iter::once(active).chain((0..self.caches.len()).filter(|ts| *ts != active)); let mut changed = false; for ts in order { let Some(cache) = self.caches.get_mut(ts) else { continue }; cache.below.set_hot(hot); - cache.below.pass = cache.dirty.len() + cache.settle.len(); + cache.below.pass = cache.dirty.len() + cache.settle.len() + cache.refine.len(); // Instances in sets of the stroke's size show the live stroke too. let preview = preview.as_ref().filter(|_| Some(cache.size) == stroke_size); - // Start at the size that fit the budget last time: with a heavy stack (smart - // materials at 8K) one tile per thread alone would take several frames' budget. - let mut chunk = if budget_ms.is_finite() && cache.chunk > 0 { cache.chunk } else { first }; + // Start at the size this budget fits at the last measured pace: with a heavy stack + // (smart materials at 8K) one tile per thread alone would take several frames' + // budget. Never above one tile per thread: work can turn heavy from one frame to the + // next. + let exact_chunk = + |cache: &SetCache| if budget_ms.is_finite() && cache.tile_ms > 0.0 { ((budget_ms / cache.tile_ms) as usize).clamp(1, first) } else { first }; + let mut chunk = exact_chunk(cache); + // A stack with neighbourhood filters computes them at full resolution even for a + // coarse composite, so it gains little from one: straight to the exact composite. + let may_coarse = coarse_allowed && !cache.dirty.is_empty() && !texturecraft_compose::has_neighbourhood_filters(&self.doc.project, ts); + // The stride of the previous chunk (1: exact), to restart the chunk size on a change. + let mut last_stride = 1; loop { if cache.dirty.is_empty() { - if cache.settle.is_empty() || clock() - start >= budget_ms.min(SETTLE_BUDGET_MS) { - break; + cache.coarse_pass = false; + } + // The work of this chunk: fresh dirty tiles (coarsest look or exact), the next + // level of the coarsest refining tiles, or settling tiles. + let (stride, refining, settling): (u32, Option, bool) = if !cache.dirty.is_empty() { + // A big change gets a coarse look first, for the whole of it. + if may_coarse && cache.dirty.len() > COARSE_MIN_TILES { + cache.coarse_pass = true; } + let coarse = may_coarse && cache.coarse_pass; + (if coarse { COARSE_STRIDES[0] } else { 1 }, None, false) + } else if let Some(at) = cache.refine.values().copied().max() { + (finer_stride(at), Some(at), false) + } else if !cache.settle.is_empty() && clock() - start < budget_ms.min(SETTLE_BUDGET_MS) { + (1, None, true) + } else { + break; + }; + // A level costs about its stride² less per texel than the exact composite: a + // new level starts at the exact pace, and the chunks grow from what it measures. + if stride != last_stride { + chunk = exact_chunk(cache); + last_stride = stride; + } + if let Some(at) = refining { + let mut level: BTreeSet<(u32, u32)> = cache.refine.iter().filter(|(_, s)| **s == at).map(|(t, _)| *t).collect(); + cache.dirty.extend(next_chunk(&mut level, chunk)); + } else if settling { // Small chunks: the settle slice of the budget is short. cache.dirty.extend(next_chunk(&mut cache.settle, chunk.min(first))); } @@ -739,6 +788,7 @@ impl Session { let tiles = next_chunk(&mut cache.dirty, chunk); for t in &tiles { cache.settle.remove(t); + cache.refine.remove(t); } let empty = BakedMaps::default(); let inputs = texturecraft_compose::Inputs { @@ -753,7 +803,12 @@ impl Session { images: &self.images, bounds: self.mesh.bounds(), }; - texturecraft_compose::composite_tiles_cached(&inputs, &mut cache.composite, &tiles, Some(&mut cache.below)); + if stride > 1 { + texturecraft_compose::composite_tiles_coarse(&inputs, &mut cache.composite, &tiles, stride); + cache.refine.extend(tiles.iter().map(|t| (*t, stride))); + } else { + texturecraft_compose::composite_tiles_cached(&inputs, &mut cache.composite, &tiles, Some(&mut cache.below)); + } // The composited tiles and the neighbours their padding reached change. let padded = pad_tiles(&mut cache.composite, &cache.dilation, &tiles); cache.upload.extend(tiles.iter().copied().chain(padded)); @@ -763,9 +818,8 @@ impl Session { let left = budget_ms - (now - start); // As many tiles as fit in what is left, at the pace of this chunk. let per_tile = (now - t0) / tiles.len().max(1) as f64; - if budget_ms.is_finite() && per_tile > 0.0 { - // Never above one tile per thread: work can turn heavy from one frame to the next. - cache.chunk = ((budget_ms / per_tile) as usize).clamp(1, first); + if budget_ms.is_finite() && per_tile > 0.0 && stride == 1 { + cache.tile_ms = per_tile; } if left <= 0.0 { return changed; @@ -782,7 +836,7 @@ impl Session { /// Tiles still waiting to be composited, over every texture set (settling ones included). pub fn pending_tiles(&self) -> usize { - self.caches.iter().map(|c| c.dirty.len() + c.settle.len()).sum() + self.caches.iter().map(|c| c.dirty.len() + c.settle.len() + c.refine.len()).sum() } /// The layer a stroke target belongs to (an effect's owner). @@ -894,6 +948,9 @@ impl Memory { /// Most tiles per composite chunk (a 1024² region). const CHUNK: usize = 256; +/// A recomposite of more tiles than this (a material applied, not a brush stroke) is shown from +/// a coarse pass first when it is spread over frames. +const COARSE_MIN_TILES: usize = 64; /// The most a budgeted update spends on settling tiles (what they show is already right). pub const SETTLE_BUDGET_MS: f64 = 6.0; @@ -912,6 +969,11 @@ fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, n: usize) -> Vec<(u32, u32)> { tiles } +/// The stride of the level after `stride` in [`COARSE_STRIDES`] (1: the exact composite). +fn finer_stride(stride: u32) -> u32 { + COARSE_STRIDES.iter().copied().find(|s| *s < stride).unwrap_or(1) +} + /// Valid texture set resolutions: powers of two from 128 to 8192. pub fn check_resolution(r: u32) -> Result { if (128..=8192).contains(&r) && r.is_power_of_two() { diff --git a/crates/engine/tests/it/instances.rs b/crates/engine/tests/it/instances.rs index b9f14bcd..f3a1b594 100644 --- a/crates/engine/tests/it/instances.rs +++ b/crates/engine/tests/it/instances.rs @@ -220,10 +220,12 @@ fn budgeted_updates_spread_work_and_end_identical() { s.caches[0].invalidate_all(); // A clock that is always over budget: one chunk per call. let mut calls = 0; + // Progress: a tile is two steps from done while dirty (coarse look, then exact), one when refining. + let steps = |s: &texturecraft_engine::Session| 2 * s.caches[0].dirty.len() + s.caches[0].refine.len() + s.caches[0].settle.len(); while s.pending_tiles() > 0 { - let before = s.pending_tiles(); + let before = steps(&s); s.update_for(0.0, || 1.0); - assert!(s.pending_tiles() < before); + assert!(steps(&s) < before); calls += 1; } assert!(calls > 1, "the work was spread over calls"); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 4dd04032..89f27beb 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -446,3 +446,166 @@ fn curvature_generators_take_a_mode_and_detail_sizes() { assert!(dirt.is_err(), "only curvature generators have a mode"); assert_eq!(execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(), inspect, "failed commands leave the project unchanged"); } + +/// A material applied over frames first looks right everywhere from a coarse pass (the sampled +/// texels are exact, the rest repeat them), then the tiles fill in to the exact composite. +#[test] +fn a_big_recomposite_shows_a_coarse_look_first_then_the_exact_one() { + let make = || { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 2048).unwrap(); + s.viewport = texturecraft_engine::geom::glam::Vec2::new(400.0, 400.0); + s.update(); + execute(&mut s, "material.apply", &json!({"material": "steel_painted_worn"})).unwrap(); + s + }; + let mut exact = make(); + exact.update(); + assert_eq!(exact.pending_tiles(), 0, "an unbudgeted update goes straight to the exact composite"); + let exact = exact.caches[0].composite.clone(); + + let mut s = make(); + let t = std::cell::Cell::new(0.0); + let clock = || { + t.set(t.get() + 2.0); + t.get() + }; + let covered = s.caches[0].covered_tiles.len(); + assert!(covered > 100, "a big change: {covered} tiles"); + while !s.caches[0].dirty.is_empty() { + s.update_for(30.0, clock); + } + assert!(s.caches[0].refine.len() > 100 && s.pending_tiles() > 0, "everything has a coarse look, the exact one is pending"); + let coarse = s.caches[0].composite.clone(); + assert_ne!(coarse, exact, "the coarse look is not the exact one"); + // Where the coarse pass sampled (a block's first covered texel, its corner where covered), it + // is exact; the others repeat the sample of their block. + let c = Channel::BaseColor; + let stride = texturecraft_engine::compose::COARSE_STRIDES[0]; + let (mut sampled, mut repeated, mut checked) = (0, 0, 0); + for y in (0..2048).step_by(7) { + for x in (0..2048).step_by(5) { + let (ax, ay) = (x - x % stride, y - y % stride); + if x == ax && y == ay { + if coarse.value(c, x, y) == exact.value(c, x, y) { + sampled += 1; + } + checked += 1; + } else if coarse.value(c, x, y) == coarse.value(c, ax, ay) { + repeated += 1; + } + } + } + assert!(checked > 100 && sampled * 10 >= checked * 9, "sampled texels are exact: {sampled} of {checked}"); + assert!(repeated > 1000, "the others repeat their sample: {repeated}"); + while s.pending_tiles() > 0 { + s.update_for(30.0, clock); + } + assert_eq!(s.caches[0].composite, exact, "the refined composite is the exact one"); +} + +/// Layers an opaque layer above hides are not evaluated: a material applied over others +/// composites exactly like the same material applied alone, in the channels it sets. +#[test] +fn layers_hidden_by_an_opaque_material_are_left_out_without_changing_the_result() { + let make = |materials: &[&str]| { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 512).unwrap(); + s.viewport = texturecraft_engine::geom::glam::Vec2::new(400.0, 400.0); + for m in materials { + execute(&mut s, "material.apply", &json!({"material": m})).unwrap(); + } + s.update(); + s.caches[0].composite.clone() + }; + let alone = make(&["gold_polished"]); + let stacked = make(&["steel_painted_worn", "copper", "gold_polished"]); + let underneath = make(&["steel_painted_worn", "copper"]); + assert_ne!(alone, underneath, "the materials differ"); + for c in [Channel::BaseColor, Channel::Roughness, Channel::Metallic] { + let (mut compared, mut differing) = (0, 0); + for y in (0..512).step_by(3) { + for x in (0..512).step_by(3) { + compared += 1; + if alone.value(c, x, y) != stacked.value(c, x, y) { + differing += 1; + } + } + } + assert!(compared > 1000 && differing == 0, "{c:?}: {differing} of {compared} texels differ"); + } +} + +/// A clock that advances 2 ms per reading, for budgeted updates. +fn ticking() -> impl Fn() -> f64 { + let t = std::cell::Cell::new(0.0); + move || { + t.set(t.get() + 2.0); + t.get() + } +} + +/// A big change goes through the coarse pass to its last tile (the decision is kept for the +/// whole pass): its tail does not go exact at the full price while the rest waits for detail. +#[test] +fn the_coarse_pass_covers_every_tile_of_a_big_change() { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 1024).unwrap(); + s.update(); + execute(&mut s, "material.apply", &json!({"material": "steel_painted_worn"})).unwrap(); + let dirty = s.caches[0].dirty.len(); + assert!(dirty > 100, "a big change: {dirty} tiles"); + // A clock always over budget: one chunk per call. + let mut calls = 0; + while !s.caches[0].dirty.is_empty() { + s.update_for(0.0, || 1.0); + let c = &s.caches[0]; + assert_eq!(c.refine.len() + c.dirty.len(), dirty, "no tile went exact during the coarse pass"); + calls += 1; + } + assert!(calls > 1, "the pass was spread over calls"); + s.update_for(0.0, || 1.0); + assert!(!s.caches[0].coarse_pass, "the pass ended with its tiles"); + let clock = ticking(); + // A small change after it goes straight to the exact composite. + let some: Vec<(u32, u32)> = s.caches[0].covered_tiles.iter().copied().take(10).collect(); + s.update(); + s.caches[0].dirty.extend(some); + s.update_for(30.0, &clock); + assert!(s.caches[0].refine.is_empty() && s.caches[0].dirty.is_empty(), "a few tiles are composited exactly"); +} + +/// Under a live stroke the compositor keeps the exact (cached) repaint: no coarse pass. +#[test] +fn no_coarse_pass_while_a_stroke_is_live() { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 1024).unwrap(); + s.update(); + s.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::new(0.5, 0.5), 1.0).unwrap(); + s.caches[0].invalidate_all(); + assert!(s.caches[0].dirty.len() > 100); + let clock = ticking(); + while !s.caches[0].dirty.is_empty() { + s.update_for(30.0, &clock); + assert!(s.caches[0].refine.is_empty(), "nothing went coarse under the stroke"); + } + s.end_stroke().unwrap(); +} + +/// A stack with a neighbourhood filter (blur) computes it at full resolution even for a coarse +/// look, which then saves little: such a stack goes straight to the exact composite. +#[test] +fn stacks_with_neighbourhood_filters_skip_the_coarse_pass() { + use texturecraft_engine::core::{Effect, EffectKind, Filter}; + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 1024).unwrap(); + s.update(); + execute(&mut s, "material.apply", &json!({"material": "copper"})).unwrap(); + s.update(); + assert!(!texturecraft_engine::compose::has_neighbourhood_filters(&s.doc.project, 0)); + let top = *s.doc.project.texture_sets[0].stack.last().unwrap(); + let id = s.doc.project.alloc_id(); + s.doc.project.layer_mut(top).unwrap().content_effects.push(Effect::new(id, EffectKind::Filter(Filter::Blur { radius: 8.0 }))); + assert!(texturecraft_engine::compose::has_neighbourhood_filters(&s.doc.project, 0)); + s.caches[0].invalidate_all(); + let clock = ticking(); + while !s.caches[0].dirty.is_empty() { + s.update_for(30.0, &clock); + assert!(s.caches[0].refine.is_empty(), "nothing went coarse"); + } +} diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 944a8ecd..7811577b 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -93,11 +93,29 @@ pub struct GpuLink { pub adapter: String, /// Most tiles waiting to be composited since compositing last caught up (progress). composite_total: usize, + /// Consecutive frames without user input (see [`frame_budgets`]). + idle_frames: u32, bake_scene: BakeSceneLink, } -/// Compositing time per frame: a full recomposite of a large texture set spreads over frames. +/// The compositing and whole-frame budgets in milliseconds after `idle_frames` frames without +/// user input: the responsive pair while the user works, the longer pair once they have stopped. +fn frame_budgets(idle_frames: u32) -> (f64, f64) { + if idle_frames >= IDLE_FRAMES_BEFORE_BOOST { (IDLE_COMPOSITE_BUDGET_MS, IDLE_FRAME_BUDGET_MS) } else { (COMPOSITE_BUDGET_MS, FRAME_BUDGET_MS) } +} + +/// Compositing time per frame while the user is working: a full recomposite of a large texture +/// set spreads over frames. const COMPOSITE_BUDGET_MS: f64 = 30.0; +/// Compositing time per frame once the user has stopped touching the app: the compositor scales +/// with the machine's cores, so a longer slice finishes sooner on a fast PC (a frame then takes +/// longer, but nothing is being dragged or painted that would feel it). +const IDLE_COMPOSITE_BUDGET_MS: f64 = 100.0; +/// [`FRAME_BUDGET_MS`] while idle: the idle compositing slice plus the usual rest of the frame. +const IDLE_FRAME_BUDGET_MS: f64 = IDLE_COMPOSITE_BUDGET_MS + (FRAME_BUDGET_MS - COMPOSITE_BUDGET_MS); +/// Frames without input (about 0.2 s at 60 fps) before the longer idle slices start, so a short +/// pause between strokes or drags keeps the responsive budget. +const IDLE_FRAMES_BEFORE_BOOST: u32 = 12; /// The most a frame spends on the scene (with the work already done this frame, such as a /// stroke's commit): compositing and display conversion leave the rest for the next frames, so /// a large (8K) texture set never stalls one frame. @@ -109,6 +127,10 @@ const UPLOAD_CHUNK: usize = 64; /// Estimated GPU upload cost of one display tile (write_texture of one 64×64 tile of one /// display kind, measured at ~5.5 µs on a desktop GPU), counted against the frame budget. const UPLOAD_MS_PER_TILE: f64 = 0.006; +/// CPU cost of converting one display tile of one kind for upload ([`tile_bytes`], measured at +/// ~6 µs: 8192 in 50 ms on a 24-thread desktop): with [`UPLOAD_MS_PER_TILE`], what a tile still +/// waiting for upload will cost this frame. +const CONVERT_MS_PER_TILE: f64 = 0.006; pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { let reset = Arc::new(AtomicBool::new(false)); @@ -140,6 +162,7 @@ pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { aux: BTreeMap::new(), adapter: format!("{} ({:?})", info.name, info.backend), composite_total: 0, + idle_frames: 0, bake_scene: BakeSceneLink::default(), } } @@ -162,13 +185,28 @@ impl GpuLink { } /// Collect everything the GPU needs this frame, running the compositor first: `bake` is what bake mode's 3D view draws besides the low poly, `spent_ms` the time this frame already took - pub fn sync(&mut self, session: &mut Session, aux_map: Option, bake: Option, shift: u32, spent_ms: f64) -> SceneSync { + pub fn sync( + &mut self, + session: &mut Session, + aux_map: Option, + bake: Option, + shift: u32, + spent_ms: f64, + user_active: bool, + ) -> SceneSync { let start_ms = crate::now_ms(); let mut queued = 0usize; - let time_left_ms = |queued: usize| FRAME_BUDGET_MS - spent_ms - (crate::now_ms() - start_ms) - queued as f64 * UPLOAD_MS_PER_TILE; + self.idle_frames = if user_active { 0 } else { self.idle_frames.saturating_add(1) }; + let (composite_budget_ms, frame_budget_ms) = frame_budgets(self.idle_frames); + let time_left_ms = |queued: usize| frame_budget_ms - spent_ms - (crate::now_ms() - start_ms) - queued as f64 * UPLOAD_MS_PER_TILE; let pending = session.pending_tiles(); self.composite_total = if pending == 0 { 0 } else { self.composite_total.max(pending) }; - session.update_for(COMPOSITE_BUDGET_MS.min(time_left_ms(0)).max(MIN_SLICE_MS), crate::now_ms); + // Tiles composited earlier and still waiting to be uploaded go first: a big change's + // coarse look is composited in a frame or two, and showing it whole matters more than + // compositing on (otherwise it appears a chunk of tiles per frame). + let backlog = session.caches.iter().map(|c| c.upload.len()).sum::() * DisplayKind::ALL.len(); + let backlog_ms = backlog as f64 * (UPLOAD_MS_PER_TILE + CONVERT_MS_PER_TILE); + session.update_for(composite_budget_ms.min(time_left_ms(0) - backlog_ms).max(MIN_SLICE_MS), crate::now_ms); let mut out = SceneSync::default(); if self.lost.swap(false, Ordering::AcqRel) { @@ -410,3 +448,26 @@ impl CallbackTrait for ViewCallback { gpu.renderer.blit_prepared(pass, self.frame.view_id); } } + +#[cfg(test)] +mod tests { + use super::*; + + /// While the user is working (or just stopped) a frame keeps the responsive budgets. + #[test] + fn budgets_stay_short_while_the_user_is_active() { + assert_eq!(frame_budgets(0), (COMPOSITE_BUDGET_MS, FRAME_BUDGET_MS)); + assert_eq!(frame_budgets(IDLE_FRAMES_BEFORE_BOOST - 1), (COMPOSITE_BUDGET_MS, FRAME_BUDGET_MS)); + } + + /// After a pause the compositor gets the longer slice, and the frame budget grows with it so the + /// display uploads keep their usual share. + #[test] + fn budgets_grow_once_the_user_is_idle() { + let (composite, frame) = frame_budgets(IDLE_FRAMES_BEFORE_BOOST); + assert_eq!(composite, IDLE_COMPOSITE_BUDGET_MS); + assert!(composite > COMPOSITE_BUDGET_MS); + assert_eq!(frame - composite, FRAME_BUDGET_MS - COMPOSITE_BUDGET_MS, "the non-compositing share of a frame is unchanged"); + assert_eq!(frame_budgets(u32::MAX), (composite, frame), "stays boosted"); + } +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f3087537..be6c87da 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -317,7 +317,11 @@ fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, mut frame: Frame let scene = match (sync.0.take(), app.gpu.as_mut()) { (Some(aux), Some(gpu_link)) => { let sync_start_ms = crate::now_ms(); - let scene = gpu_link.sync(&mut app.session, aux, bake, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms)); + // Pointer, key and scroll input all count: the compositor then keeps frames short. + let user_active = + ui.ctx().input(|i| i.pointer.is_moving() || i.pointer.any_down() || !i.events.is_empty() || i.smooth_scroll_delta != egui::Vec2::ZERO); + let scene = + gpu_link.sync(&mut app.session, aux, bake, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms), user_active); let reports = gpu_link.take_reports(); app.profiler.sync_ms += (crate::now_ms() - sync_start_ms) as f32; gpu_report_toasts(app, reports); From 4a3e5c41b443ca744181fee97105f6423f788038 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:44:42 +0100 Subject: [PATCH 6/7] Return test setup errors before assertions --- crates/engine/src/thumbs.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/thumbs.rs b/crates/engine/src/thumbs.rs index ba655be7..6cd6e2a2 100644 --- a/crates/engine/src/thumbs.rs +++ b/crates/engine/src/thumbs.rs @@ -431,8 +431,8 @@ mod tests { use texturecraft_core::Channel; use texturecraft_geom::primitives; - fn test_session() -> Session { - Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap() + fn test_session() -> crate::Result { + Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128) } fn held_worker() -> (ThumbService, std::sync::mpsc::Receiver, std::sync::mpsc::Sender) { @@ -444,7 +444,7 @@ mod tests { #[test] fn unchanged_baked_handles_match_even_with_non_finite_samples() { - let mut session = test_session(); + let mut session = test_session().unwrap(); let baked = session.doc.baked.entry(0).or_default(); baked.resolution = 1; baked.maps.insert(texturecraft_core::BakedMap::Height, Arc::new(vec![f32::NAN])); @@ -460,7 +460,7 @@ mod tests { #[test] #[ignore] fn benchmark_unchanged_4k_baked_snapshot() { - let mut session = test_session(); + let mut session = test_session().unwrap(); let baked = session.doc.baked.entry(0).or_default(); baked.resolution = 4096; baked.maps.insert(texturecraft_core::BakedMap::Normal, Arc::new(vec![0.5; 4096 * 4096 * 3])); @@ -477,7 +477,7 @@ mod tests { #[test] fn collecting_the_last_result_requests_a_frame_to_display_it() { - let session = test_session(); + let session = test_session().unwrap(); let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor }; let (mut service, jobs, results) = held_worker(); service.begin_frame(&session, 0.0); @@ -499,7 +499,7 @@ mod tests { #[test] fn a_stopped_worker_retries_visible_targets_inline() { - let session = test_session(); + let session = test_session().unwrap(); let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor }; let (mut service, jobs, results) = held_worker(); service.begin_frame(&session, 0.0); @@ -521,7 +521,7 @@ mod tests { #[test] fn edits_keep_worker_jobs_and_retained_snapshots_bounded() { - let mut session = test_session(); + let mut session = test_session().unwrap(); let layer = session.selected_layer().unwrap(); let target = ThumbTarget::Content { layer, channel: Channel::BaseColor }; let (mut service, jobs, results) = held_worker(); From d664dc239cd005b4ff7b0ea9f17bf2ad02809cdd Mon Sep 17 00:00:00 2001 From: Chris Hassebrook Date: Tue, 10 Nov 2026 16:08:27 -0500 Subject: [PATCH 7/7] Revert "Show a whole material at once: coarse first look, then the exact result" --- crates/compose/src/eval.rs | 159 +------------------ crates/compose/src/lib.rs | 4 +- crates/compose/tests/cache_and_instances.rs | 32 ---- crates/core/src/blend.rs | 5 - crates/engine/src/inspect.rs | 5 - crates/engine/src/session.rs | 92 ++--------- crates/engine/tests/it/instances.rs | 6 +- crates/engine/tests/session.rs | 163 -------------------- crates/ui-egui/src/gpu.rs | 69 +-------- crates/ui-egui/src/viewport.rs | 6 +- 10 files changed, 31 insertions(+), 510 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index a60beb6f..b8299438 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -803,22 +803,6 @@ fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32 out } -/// Whether texture set `ts` has a layer with a neighbourhood filter (blur, sharpen, warp…) in -/// its mask or content: a composite then precomputes [`neighbourhood_fields`] at full -/// resolution, so even a [`composite_tiles_coarse`] is not much cheaper than the exact one. -/// The same layers as `neighbourhood_fields` looks at (it may count a hidden one). -pub fn has_neighbourhood_filters(project: &Project, ts: usize) -> bool { - let Ok(set) = project.texture_set(ts) else { return false }; - let mut order = Vec::new(); - draw_order(project, &set.stack, 0, &mut order); - let res = set.resolution; - order.iter().any(|id| { - let mask = layer_mask(project, *id).is_some_and(|m| m.enabled && neighbourhood(&m.effects, res).is_some()); - let content = project.content_layer(*id).is_some_and(|l| !l.is_group() && neighbourhood(&l.content_effects, res).is_some()); - mask || content - }) -} - /// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); @@ -915,89 +899,10 @@ fn mask_plan<'a>(inp: &Inputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32 } fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>) -> Vec> { - plan_with(inp, list, channels, tx, ty, depth, fields, false) -} - -/// [`plan`], leaving out what an opaque layer above hides when `cull` (see [`cull_hidden`]). -/// Only for lists that are evaluated whole and not looked into (no anchor or stop layer reads). -#[allow(clippy::too_many_arguments)] -fn plan_with<'a>( - inp: &Inputs<'a>, - list: &[LayerId], - channels: &[Channel], - tx: u32, - ty: u32, - depth: usize, - fields: Option<&'a Fields>, - cull: bool, -) -> Vec> { if depth > texturecraft_core::project::MAX_DEPTH { return Vec::new(); } - let mut nodes: Vec> = list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true, cull)).collect(); - if cull { - cull_hidden(&mut nodes, channels); - } - nodes -} - -/// Whether node `n` hides everything below it in channel `ch`: it replaces the stack there at -/// every texel (full opacity, normal blend, no mask or geometry or height mask, a fill that -/// covers the whole surface with no content effects), or is a folder at full opacity holding -/// such a layer. -fn occludes(n: &Node, ch: usize) -> bool { - if n.mask.is_some() || n.parts.is_some() || n.height_mask.enabled { - return false; - } - let Some(c) = n.chans.iter().find(|c| c.ch == ch) else { return false }; - if c.opacity < 1.0 { - return false; - } - match &n.content { - Content::Fill(f) => c.blend == BlendMode::Normal && !matches!(f.projection, Projection::Decal(_)) && c.effects.is_empty() && c.start.is_none(), - Content::Group(kids) => kids.iter().any(|k| occludes(k, ch)), - Content::Paint { .. } => false, - } -} - -/// Whether `n` or a layer in it masks with its height. -fn uses_height_mask(n: &Node) -> bool { - n.height_mask.enabled || matches!(&n.content, Content::Group(kids) if kids.iter().any(uses_height_mask)) -} - -/// Take channel `ch` out of `n` (and what it holds), dropping what then draws nothing. -fn strip_channel(n: &mut Node, ch: usize) { - n.chans.retain(|c| c.ch != ch); - if let Content::Group(kids) = &mut n.content { - for k in kids.iter_mut() { - strip_channel(k, ch); - } - kids.retain(|k| !k.chans.is_empty()); - } -} - -/// Leave out the layers (per channel) that a layer above them hides completely: a stack that -/// grows by applying material after material would otherwise evaluate every one of them. The -/// result is identical. Channels with anchor points or height masks below the hiding layer -/// are left alone (they read other layers' values), and so are those under a hiding folder -/// that records an anchor point: its inner stack starts from what lies below it, so an anchor -/// under the hiding layer inside it holds the layers it hides. -fn cull_hidden(nodes: &mut Vec, channels: &[Channel]) { - for c in channels { - let ch = c.index(); - let Some(k) = nodes.iter().rposition(|n| occludes(n, ch)) else { continue }; - if nodes.get(k).is_some_and(|n| n.has_anchor) { - continue; - } - let Some(below) = nodes.get_mut(..k) else { continue }; - if below.iter().any(|n| n.has_anchor || (*c == Channel::Height && uses_height_mask(n))) { - continue; - } - for n in below.iter_mut() { - strip_channel(n, ch); - } - } - nodes.retain(|n| !n.chans.is_empty() || n.has_anchor); + list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true)).collect() } /// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are @@ -1012,7 +917,6 @@ fn plan_node<'a>( depth: usize, fields: Option<&'a Fields>, kids: bool, - cull: bool, ) -> Option> { let own: &'a Layer = inp.project.layers.get(&id)?; // Instances draw their source's content (a missing source draws nothing). @@ -1039,9 +943,7 @@ fn plan_node<'a>( let content = match &layer.kind { LayerKind::Paint => Content::Paint { preview: previews(inp, PaintTarget::Layer(layer.id)) }, LayerKind::Fill(f) => Content::Fill(f), - LayerKind::Group { children, .. } => { - Content::Group(if kids { plan_with(inp, children, channels, tx, ty, depth + 1, fields, cull) } else { Vec::new() }) - } + LayerKind::Group { children, .. } => Content::Group(if kids { plan(inp, children, channels, tx, ty, depth + 1, fields) } else { Vec::new() }), // `content_layer` already followed instance links. LayerKind::Instance { .. } => return None, }; @@ -1088,8 +990,8 @@ fn plan_levels<'a>(inp: &Inputs<'a>, levels: &[Level], channels: &[Channel], tx: .iter() .enumerate() .map(|(d, l)| LevelPlan { - below: if warm { Vec::new() } else { plan_with(inp, &l.below, channels, tx, ty, d, Some(fields), true) }, - at: plan_node(inp, l.at, channels, tx, ty, d, Some(fields), d == last, false), + below: if warm { Vec::new() } else { plan(inp, &l.below, channels, tx, ty, d, Some(fields)) }, + at: plan_node(inp, l.at, channels, tx, ty, d, Some(fields), d == last), above: plan(inp, &l.above, channels, tx, ty, d, Some(fields)), }) .collect() @@ -1758,35 +1660,6 @@ pub fn composite_tiles(inp: &Inputs, out: &mut Composite, tiles: &[(u32, u32)]) composite_tiles_cached(inp, out, tiles, None); } -/// The strides a coarse composite ([`composite_tiles_coarse`]) takes, coarsest first: texels -/// per block side, one evaluated per block. Each divides the rows of a band and a tile, so a -/// block never crosses bands or tiles. A big recomposite shows them in this order before the -/// exact composite. One level: a coarse pass costs about the same at any stride (writing, -/// padding and uploading the full-resolution tiles dominate once one texel in 64 is -/// evaluated; measured 4096², 3217 tiles: 139 ms at 16, 150 at 8, 254 at 4, 2.1 s exact), so -/// a second level would only add that cost again before the exact composite. -pub const COARSE_STRIDES: [u32; 1] = [8]; - -/// A quick look at `tiles`: [`composite_tiles`] evaluating one texel in every `stride` by `stride` -/// block (its first covered texel) and repeating it over the block's covered texels (a texel only -/// depends on its own position, so the evaluated ones are exact; the rest are as blocky as a -/// lower resolution), about `stride`² times fewer evaluations. A `stride` that does not divide a band and a tile composites exactly. A later -/// [`composite_tiles`] of the same tiles gives the exact result. -pub fn composite_tiles_coarse(inp: &Inputs, out: &mut Composite, tiles: &[(u32, u32)], stride: u32) { - let Ok(set) = inp.project.texture_set(inp.ts) else { return }; - if (inp.gbuf.width, inp.gbuf.height) != (out.resolution, out.height) { - return; - } - let step = if stride > 0 && BAND.is_multiple_of(stride) && TILE.is_multiple_of(stride) { stride } else { 1 }; - let mut blocks: BTreeMap<(u32, u32), Vec<(u32, u32)>> = BTreeMap::new(); - for t in tiles { - blocks.entry((t.1 / BLOCK, t.0 / BLOCK)).or_default().push(*t); - } - for block in blocks.values() { - composite_block(inp, &set.stack, out, block, None, 0, step); - } -} - /// Tiles per side of the blocks a composite works through (bounds neighbourhood-filter memory). const BLOCK: u32 = 16; @@ -1815,7 +1688,7 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, None => 0, }; let cached = below.as_deref().zip(split.as_deref()); - let records = composite_block(inp, &set.stack, out, block, cached, quota, 1); + let records = composite_block(inp, &set.stack, out, block, cached, quota); if let Some(b) = below.as_deref_mut() { for t in block { b.touch(*t); @@ -1846,7 +1719,6 @@ fn composite_block( tiles: &[(u32, u32)], below: Option<(&BelowCache, &[Level])>, quota: usize, - step: u32, ) -> Vec<((u32, u32), Vec)> { let channels: Vec = inp.project.texture_set(inp.ts).map(|s| s.channel_list()).unwrap_or_default(); let (w, h) = (out.resolution, out.height); @@ -1876,7 +1748,7 @@ fn composite_block( let warm = cached((tx, ty)).and_then(|b| b.get(band as usize)); let record = warm.is_none() && recorded.contains(&(tx, ty)); let levels = split.map(|l| plan_levels(inp, l, &channels, tx, ty, &fields, warm.is_some())); - let nodes = if levels.is_none() { plan_with(inp, stack, &channels, tx, ty, 0, Some(&fields), true) } else { Vec::new() }; + let nodes = if levels.is_none() { plan(inp, stack, &channels, tx, ty, 0, Some(&fields)) } else { Vec::new() }; let rows = (BAND * TILE) as usize; let mut accs = vec![defaults; nlev]; let mut masks = vec![0.0f32; nlev]; @@ -1900,17 +1772,11 @@ fn composite_block( let mut bufs: Vec> = channels.iter().map(|c| vec![0u16; rows * c.components()]).collect(); let mut anchors = Vec::new(); let mut any = false; - // Coarse: per `step`-wide block of the current block row, the value of its first - // covered texel (evaluated), repeated over the block's other covered texels. - let mut sampled: Vec> = vec![None; if step > 1 { (TILE / step) as usize } else { 0 }]; for ly in band * BAND..(band + 1) * BAND { let y = ty * TILE + ly; if y >= h { break; } - if step > 1 && ly % step == 0 { - sampled.fill(None); - } for lx in 0..TILE { let x = tx * TILE + lx; if x >= w { @@ -1922,12 +1788,7 @@ fn composite_block( let ob = ((ly - band * BAND) * TILE + lx) as usize; let covered = inp.gbuf.tri.get(gi).is_some_and(|t| *t != NO_TRI); let mut acc = defaults; - let block = if step > 1 { sampled.get_mut((lx / step) as usize) } else { None }; - let repeated = block.as_ref().and_then(|b| **b); - if covered && let Some(a) = repeated { - any = true; - acc = a; - } else if covered { + if covered { any = true; let mut tex = Texel::new(inp, x, y, o, stroke_at(preview_tile, o)); // Reuse one anchor buffer per band. @@ -1959,12 +1820,6 @@ fn composite_block( anchors = tex.anchors; anchors.clear(); } - if covered - && repeated.is_none() - && let Some(slot) = block - { - *slot = Some(acc); - } for (l, buf) in lanes.iter().zip(&mut bufs) { let v = acc.get(l.ch).copied().unwrap_or([0.0; 3]); for (k, x) in v.iter().take(l.n).enumerate() { diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 0475fb8f..46c3c6b5 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -20,8 +20,8 @@ pub mod thumb; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; pub use eval::{ - COARSE_STRIDES, Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, composite_tiles_coarse, - covered_tiles, effect_histogram, flatten_layer, has_neighbourhood_filters, mask_at, mask_image, pad_tiles, + Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, + mask_at, mask_image, pad_tiles, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 50d125a6..d7df0258 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -573,35 +573,3 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() { assert!(!check_cached(&f, 0, hot).is_empty()); } } - -/// A folder that hides the layers below it but records an anchor point inside (under its own -/// hiding layer) keeps them: its inner stack starts from them, so the anchor holds them. -#[test] -fn layers_under_a_hiding_folder_with_an_anchor_are_not_culled() { - let mut f = fixture(); - let only = |f: &mut Fixture, id: LayerId, c: Channel| f.project.layer_mut(id).unwrap().channels.retain(|x, _| *x == c); - let low = add(&mut f, 0, fill(&[(Channel::BaseColor, Source::Uniform([0.9; 3]))]), None); - only(&mut f, low, Channel::BaseColor); - let group = add(&mut f, 0, LayerKind::Group { children: vec![], collapsed: false }, None); - // Inside: a half-opacity fill recording anchor A, then an opaque fill hiding everything. - let anchored = put(&mut f, 0, Some(group), fill(&[(Channel::BaseColor, Source::Uniform([0.5; 3]))]), None); - only(&mut f, anchored, Channel::BaseColor); - blend(&mut f, anchored, BlendMode::Normal, 0.5); - let anchor = effect(&mut f, EffectKind::Anchor); - let anchor_id = anchor.id; - f.project.layer_mut(anchored).unwrap().content_effects.push(anchor); - let hiding = put(&mut f, 0, Some(group), fill(&[(Channel::BaseColor, Source::Uniform([0.1; 3]))]), None); - only(&mut f, hiding, Channel::BaseColor); - // Above the folder, roughness reads the base color held by A. - let reader = add(&mut f, 0, fill(&[(Channel::Roughness, Source::Anchor { anchor: anchor_id, channel: Channel::BaseColor })]), None); - only(&mut f, reader, Channel::Roughness); - let out = reference(&f, 0); - let rough = out.value(Channel::Roughness, 128, 128)[0]; - // A = 0.5 at half opacity over the low layer's 0.9. - assert!((rough - 0.7).abs() < 2e-3, "the anchor holds the layer under the folder: {rough}"); - assert!((out.value(Channel::BaseColor, 128, 128)[0] - 0.1).abs() < 2e-3); - // The same stack with an (unread) anchor on the low layer is never culled: identical. - let keep = effect(&mut f, EffectKind::Anchor); - f.project.layer_mut(low).unwrap().content_effects.push(keep); - assert!(reference(&f, 0) == out, "culling changed the composite"); -} diff --git a/crates/core/src/blend.rs b/crates/core/src/blend.rs index c7fa7e64..5f165cdb 100644 --- a/crates/core/src/blend.rs +++ b/crates/core/src/blend.rs @@ -350,11 +350,6 @@ pub fn blend3(mode: BlendMode, a: [f32; 3], b: [f32; 3]) -> [f32; 3] { /// Mix `blended` over `a` by weight `w` (coverage × opacity × mask). pub fn mix3(a: [f32; 3], blended: [f32; 3], w: f32) -> [f32; 3] { - // A full-weight blend is exactly the blended value (`a + (b - a)` can be an ulp off it): what - // lies under it does not leak in, so skipping the layers it hides changes nothing at all. - if w >= 1.0 { - return blended; - } [a[0] + (blended[0] - a[0]) * w, a[1] + (blended[1] - a[1]) * w, a[2] + (blended[2] - a[2]) * w] } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 603e7b17..2db27946 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -193,10 +193,5 @@ pub fn session(s: &Session) -> Value { "history": { "undo": s.undo_label(), "redo": s.redo_label(), "depth": s.history_labels().len() }, "memoryBytes": s.memory().total(), "pendingTiles": s.pending_tiles(), - // Tiles with no look of the current composite yet, tiles shown from a coarse pass only - // (their exact composite pending), and the coarsest stride shown (0: none). - "dirtyTiles": s.caches.iter().map(|c| c.dirty.len()).sum::(), - "coarseTiles": s.caches.iter().map(|c| c.refine.len()).sum::(), - "coarsestStride": s.caches.iter().flat_map(|c| c.refine.values().copied()).max().unwrap_or(0), }) } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 6b721a79..64ebec69 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde::{Deserialize, Serialize}; -use texturecraft_compose::{BakedMaps, BelowCache, COARSE_STRIDES, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles}; +use texturecraft_compose::{BakedMaps, BelowCache, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles}; use texturecraft_core::{Channel, Layer, LayerId, LayerKind, Project, TextureSet}; use texturecraft_geom::glam::Vec2; use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer}; @@ -43,24 +43,14 @@ pub struct SetCache { /// Tiles to recomposite at low priority: what they show is already right (a committed /// stroke's live preview), but it was composited from the stroke, not the layer pixels. pub settle: BTreeSet<(u32, u32)>, - /// Tiles shown from a coarse pass ([`texturecraft_compose::composite_tiles_coarse`]) with - /// the stride they were composited at; they still need the finer ones and the exact one. A - /// big recomposite (a material applied) first looks right everywhere at a small part of the - /// cost, then sharpens level by level ([`texturecraft_compose::COARSE_STRIDES`]), each level - /// over every tile before the next, so the surface is always at one consistent level. - pub refine: BTreeMap<(u32, u32), u32>, - /// The dirty tiles go through a coarse pass: decided when a big recomposite starts and - /// kept until `dirty` drains, so its last few tiles do not go exact at the full price. - pub coarse_pass: bool, /// Tiles whose display textures must be re-uploaded. pub upload: BTreeSet<(u32, u32)>, /// Bumps on every composite change (thumbnails, exports, caches). pub revision: u64, /// Everything but the layer being edited, per tile (repaints evaluate only that layer). pub below: BelowCache, - /// Wall-clock milliseconds per tile of the last exact composite chunk (0: not measured - /// yet): the first chunk of a budgeted update is sized from it and that update's budget. - pub tile_ms: f64, + /// Tiles per composite chunk that fit the last frame's budget (0: not measured yet). + pub chunk: usize, } impl SetCache { @@ -79,12 +69,10 @@ impl SetCache { composite: Composite { block_scales: ts.block_scales(), ..Composite::with_size(&ts.channel_list(), w, h) }, dirty: all.clone(), settle: BTreeSet::new(), - refine: BTreeMap::new(), - coarse_pass: false, upload: all, revision: 0, below: BelowCache::default(), - tile_ms: 0.0, + chunk: 0, } } @@ -727,60 +715,23 @@ impl Session { carried: s.canvas.pickup.as_ref().map(|p| p.values.clone()).unwrap_or_default(), }) }); - // A coarse look first only when there is a frame budget to spread a big change over, and - // never under a live stroke (it keeps the exact, cached repaint of the hot layer). - let coarse_allowed = budget_ms.is_finite() && self.stroke.is_none(); let active = self.ts(); let order = std::iter::once(active).chain((0..self.caches.len()).filter(|ts| *ts != active)); let mut changed = false; for ts in order { let Some(cache) = self.caches.get_mut(ts) else { continue }; cache.below.set_hot(hot); - cache.below.pass = cache.dirty.len() + cache.settle.len() + cache.refine.len(); + cache.below.pass = cache.dirty.len() + cache.settle.len(); // Instances in sets of the stroke's size show the live stroke too. let preview = preview.as_ref().filter(|_| Some(cache.size) == stroke_size); - // Start at the size this budget fits at the last measured pace: with a heavy stack - // (smart materials at 8K) one tile per thread alone would take several frames' - // budget. Never above one tile per thread: work can turn heavy from one frame to the - // next. - let exact_chunk = - |cache: &SetCache| if budget_ms.is_finite() && cache.tile_ms > 0.0 { ((budget_ms / cache.tile_ms) as usize).clamp(1, first) } else { first }; - let mut chunk = exact_chunk(cache); - // A stack with neighbourhood filters computes them at full resolution even for a - // coarse composite, so it gains little from one: straight to the exact composite. - let may_coarse = coarse_allowed && !cache.dirty.is_empty() && !texturecraft_compose::has_neighbourhood_filters(&self.doc.project, ts); - // The stride of the previous chunk (1: exact), to restart the chunk size on a change. - let mut last_stride = 1; + // Start at the size that fit the budget last time: with a heavy stack (smart + // materials at 8K) one tile per thread alone would take several frames' budget. + let mut chunk = if budget_ms.is_finite() && cache.chunk > 0 { cache.chunk } else { first }; loop { if cache.dirty.is_empty() { - cache.coarse_pass = false; - } - // The work of this chunk: fresh dirty tiles (coarsest look or exact), the next - // level of the coarsest refining tiles, or settling tiles. - let (stride, refining, settling): (u32, Option, bool) = if !cache.dirty.is_empty() { - // A big change gets a coarse look first, for the whole of it. - if may_coarse && cache.dirty.len() > COARSE_MIN_TILES { - cache.coarse_pass = true; + if cache.settle.is_empty() || clock() - start >= budget_ms.min(SETTLE_BUDGET_MS) { + break; } - let coarse = may_coarse && cache.coarse_pass; - (if coarse { COARSE_STRIDES[0] } else { 1 }, None, false) - } else if let Some(at) = cache.refine.values().copied().max() { - (finer_stride(at), Some(at), false) - } else if !cache.settle.is_empty() && clock() - start < budget_ms.min(SETTLE_BUDGET_MS) { - (1, None, true) - } else { - break; - }; - // A level costs about its stride² less per texel than the exact composite: a - // new level starts at the exact pace, and the chunks grow from what it measures. - if stride != last_stride { - chunk = exact_chunk(cache); - last_stride = stride; - } - if let Some(at) = refining { - let mut level: BTreeSet<(u32, u32)> = cache.refine.iter().filter(|(_, s)| **s == at).map(|(t, _)| *t).collect(); - cache.dirty.extend(next_chunk(&mut level, chunk)); - } else if settling { // Small chunks: the settle slice of the budget is short. cache.dirty.extend(next_chunk(&mut cache.settle, chunk.min(first))); } @@ -788,7 +739,6 @@ impl Session { let tiles = next_chunk(&mut cache.dirty, chunk); for t in &tiles { cache.settle.remove(t); - cache.refine.remove(t); } let empty = BakedMaps::default(); let inputs = texturecraft_compose::Inputs { @@ -803,12 +753,7 @@ impl Session { images: &self.images, bounds: self.mesh.bounds(), }; - if stride > 1 { - texturecraft_compose::composite_tiles_coarse(&inputs, &mut cache.composite, &tiles, stride); - cache.refine.extend(tiles.iter().map(|t| (*t, stride))); - } else { - texturecraft_compose::composite_tiles_cached(&inputs, &mut cache.composite, &tiles, Some(&mut cache.below)); - } + texturecraft_compose::composite_tiles_cached(&inputs, &mut cache.composite, &tiles, Some(&mut cache.below)); // The composited tiles and the neighbours their padding reached change. let padded = pad_tiles(&mut cache.composite, &cache.dilation, &tiles); cache.upload.extend(tiles.iter().copied().chain(padded)); @@ -818,8 +763,9 @@ impl Session { let left = budget_ms - (now - start); // As many tiles as fit in what is left, at the pace of this chunk. let per_tile = (now - t0) / tiles.len().max(1) as f64; - if budget_ms.is_finite() && per_tile > 0.0 && stride == 1 { - cache.tile_ms = per_tile; + if budget_ms.is_finite() && per_tile > 0.0 { + // Never above one tile per thread: work can turn heavy from one frame to the next. + cache.chunk = ((budget_ms / per_tile) as usize).clamp(1, first); } if left <= 0.0 { return changed; @@ -836,7 +782,7 @@ impl Session { /// Tiles still waiting to be composited, over every texture set (settling ones included). pub fn pending_tiles(&self) -> usize { - self.caches.iter().map(|c| c.dirty.len() + c.settle.len() + c.refine.len()).sum() + self.caches.iter().map(|c| c.dirty.len() + c.settle.len()).sum() } /// The layer a stroke target belongs to (an effect's owner). @@ -948,9 +894,6 @@ impl Memory { /// Most tiles per composite chunk (a 1024² region). const CHUNK: usize = 256; -/// A recomposite of more tiles than this (a material applied, not a brush stroke) is shown from -/// a coarse pass first when it is spread over frames. -const COARSE_MIN_TILES: usize = 64; /// The most a budgeted update spends on settling tiles (what they show is already right). pub const SETTLE_BUDGET_MS: f64 = 6.0; @@ -969,11 +912,6 @@ fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, n: usize) -> Vec<(u32, u32)> { tiles } -/// The stride of the level after `stride` in [`COARSE_STRIDES`] (1: the exact composite). -fn finer_stride(stride: u32) -> u32 { - COARSE_STRIDES.iter().copied().find(|s| *s < stride).unwrap_or(1) -} - /// Valid texture set resolutions: powers of two from 128 to 8192. pub fn check_resolution(r: u32) -> Result { if (128..=8192).contains(&r) && r.is_power_of_two() { diff --git a/crates/engine/tests/it/instances.rs b/crates/engine/tests/it/instances.rs index f3a1b594..b9f14bcd 100644 --- a/crates/engine/tests/it/instances.rs +++ b/crates/engine/tests/it/instances.rs @@ -220,12 +220,10 @@ fn budgeted_updates_spread_work_and_end_identical() { s.caches[0].invalidate_all(); // A clock that is always over budget: one chunk per call. let mut calls = 0; - // Progress: a tile is two steps from done while dirty (coarse look, then exact), one when refining. - let steps = |s: &texturecraft_engine::Session| 2 * s.caches[0].dirty.len() + s.caches[0].refine.len() + s.caches[0].settle.len(); while s.pending_tiles() > 0 { - let before = steps(&s); + let before = s.pending_tiles(); s.update_for(0.0, || 1.0); - assert!(steps(&s) < before); + assert!(s.pending_tiles() < before); calls += 1; } assert!(calls > 1, "the work was spread over calls"); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 89f27beb..4dd04032 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -446,166 +446,3 @@ fn curvature_generators_take_a_mode_and_detail_sizes() { assert!(dirt.is_err(), "only curvature generators have a mode"); assert_eq!(execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(), inspect, "failed commands leave the project unchanged"); } - -/// A material applied over frames first looks right everywhere from a coarse pass (the sampled -/// texels are exact, the rest repeat them), then the tiles fill in to the exact composite. -#[test] -fn a_big_recomposite_shows_a_coarse_look_first_then_the_exact_one() { - let make = || { - let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 2048).unwrap(); - s.viewport = texturecraft_engine::geom::glam::Vec2::new(400.0, 400.0); - s.update(); - execute(&mut s, "material.apply", &json!({"material": "steel_painted_worn"})).unwrap(); - s - }; - let mut exact = make(); - exact.update(); - assert_eq!(exact.pending_tiles(), 0, "an unbudgeted update goes straight to the exact composite"); - let exact = exact.caches[0].composite.clone(); - - let mut s = make(); - let t = std::cell::Cell::new(0.0); - let clock = || { - t.set(t.get() + 2.0); - t.get() - }; - let covered = s.caches[0].covered_tiles.len(); - assert!(covered > 100, "a big change: {covered} tiles"); - while !s.caches[0].dirty.is_empty() { - s.update_for(30.0, clock); - } - assert!(s.caches[0].refine.len() > 100 && s.pending_tiles() > 0, "everything has a coarse look, the exact one is pending"); - let coarse = s.caches[0].composite.clone(); - assert_ne!(coarse, exact, "the coarse look is not the exact one"); - // Where the coarse pass sampled (a block's first covered texel, its corner where covered), it - // is exact; the others repeat the sample of their block. - let c = Channel::BaseColor; - let stride = texturecraft_engine::compose::COARSE_STRIDES[0]; - let (mut sampled, mut repeated, mut checked) = (0, 0, 0); - for y in (0..2048).step_by(7) { - for x in (0..2048).step_by(5) { - let (ax, ay) = (x - x % stride, y - y % stride); - if x == ax && y == ay { - if coarse.value(c, x, y) == exact.value(c, x, y) { - sampled += 1; - } - checked += 1; - } else if coarse.value(c, x, y) == coarse.value(c, ax, ay) { - repeated += 1; - } - } - } - assert!(checked > 100 && sampled * 10 >= checked * 9, "sampled texels are exact: {sampled} of {checked}"); - assert!(repeated > 1000, "the others repeat their sample: {repeated}"); - while s.pending_tiles() > 0 { - s.update_for(30.0, clock); - } - assert_eq!(s.caches[0].composite, exact, "the refined composite is the exact one"); -} - -/// Layers an opaque layer above hides are not evaluated: a material applied over others -/// composites exactly like the same material applied alone, in the channels it sets. -#[test] -fn layers_hidden_by_an_opaque_material_are_left_out_without_changing_the_result() { - let make = |materials: &[&str]| { - let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 512).unwrap(); - s.viewport = texturecraft_engine::geom::glam::Vec2::new(400.0, 400.0); - for m in materials { - execute(&mut s, "material.apply", &json!({"material": m})).unwrap(); - } - s.update(); - s.caches[0].composite.clone() - }; - let alone = make(&["gold_polished"]); - let stacked = make(&["steel_painted_worn", "copper", "gold_polished"]); - let underneath = make(&["steel_painted_worn", "copper"]); - assert_ne!(alone, underneath, "the materials differ"); - for c in [Channel::BaseColor, Channel::Roughness, Channel::Metallic] { - let (mut compared, mut differing) = (0, 0); - for y in (0..512).step_by(3) { - for x in (0..512).step_by(3) { - compared += 1; - if alone.value(c, x, y) != stacked.value(c, x, y) { - differing += 1; - } - } - } - assert!(compared > 1000 && differing == 0, "{c:?}: {differing} of {compared} texels differ"); - } -} - -/// A clock that advances 2 ms per reading, for budgeted updates. -fn ticking() -> impl Fn() -> f64 { - let t = std::cell::Cell::new(0.0); - move || { - t.set(t.get() + 2.0); - t.get() - } -} - -/// A big change goes through the coarse pass to its last tile (the decision is kept for the -/// whole pass): its tail does not go exact at the full price while the rest waits for detail. -#[test] -fn the_coarse_pass_covers_every_tile_of_a_big_change() { - let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 1024).unwrap(); - s.update(); - execute(&mut s, "material.apply", &json!({"material": "steel_painted_worn"})).unwrap(); - let dirty = s.caches[0].dirty.len(); - assert!(dirty > 100, "a big change: {dirty} tiles"); - // A clock always over budget: one chunk per call. - let mut calls = 0; - while !s.caches[0].dirty.is_empty() { - s.update_for(0.0, || 1.0); - let c = &s.caches[0]; - assert_eq!(c.refine.len() + c.dirty.len(), dirty, "no tile went exact during the coarse pass"); - calls += 1; - } - assert!(calls > 1, "the pass was spread over calls"); - s.update_for(0.0, || 1.0); - assert!(!s.caches[0].coarse_pass, "the pass ended with its tiles"); - let clock = ticking(); - // A small change after it goes straight to the exact composite. - let some: Vec<(u32, u32)> = s.caches[0].covered_tiles.iter().copied().take(10).collect(); - s.update(); - s.caches[0].dirty.extend(some); - s.update_for(30.0, &clock); - assert!(s.caches[0].refine.is_empty() && s.caches[0].dirty.is_empty(), "a few tiles are composited exactly"); -} - -/// Under a live stroke the compositor keeps the exact (cached) repaint: no coarse pass. -#[test] -fn no_coarse_pass_while_a_stroke_is_live() { - let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 1024).unwrap(); - s.update(); - s.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::new(0.5, 0.5), 1.0).unwrap(); - s.caches[0].invalidate_all(); - assert!(s.caches[0].dirty.len() > 100); - let clock = ticking(); - while !s.caches[0].dirty.is_empty() { - s.update_for(30.0, &clock); - assert!(s.caches[0].refine.is_empty(), "nothing went coarse under the stroke"); - } - s.end_stroke().unwrap(); -} - -/// A stack with a neighbourhood filter (blur) computes it at full resolution even for a coarse -/// look, which then saves little: such a stack goes straight to the exact composite. -#[test] -fn stacks_with_neighbourhood_filters_skip_the_coarse_pass() { - use texturecraft_engine::core::{Effect, EffectKind, Filter}; - let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 1024).unwrap(); - s.update(); - execute(&mut s, "material.apply", &json!({"material": "copper"})).unwrap(); - s.update(); - assert!(!texturecraft_engine::compose::has_neighbourhood_filters(&s.doc.project, 0)); - let top = *s.doc.project.texture_sets[0].stack.last().unwrap(); - let id = s.doc.project.alloc_id(); - s.doc.project.layer_mut(top).unwrap().content_effects.push(Effect::new(id, EffectKind::Filter(Filter::Blur { radius: 8.0 }))); - assert!(texturecraft_engine::compose::has_neighbourhood_filters(&s.doc.project, 0)); - s.caches[0].invalidate_all(); - let clock = ticking(); - while !s.caches[0].dirty.is_empty() { - s.update_for(30.0, &clock); - assert!(s.caches[0].refine.is_empty(), "nothing went coarse"); - } -} diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 7811577b..944a8ecd 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -93,29 +93,11 @@ pub struct GpuLink { pub adapter: String, /// Most tiles waiting to be composited since compositing last caught up (progress). composite_total: usize, - /// Consecutive frames without user input (see [`frame_budgets`]). - idle_frames: u32, bake_scene: BakeSceneLink, } -/// The compositing and whole-frame budgets in milliseconds after `idle_frames` frames without -/// user input: the responsive pair while the user works, the longer pair once they have stopped. -fn frame_budgets(idle_frames: u32) -> (f64, f64) { - if idle_frames >= IDLE_FRAMES_BEFORE_BOOST { (IDLE_COMPOSITE_BUDGET_MS, IDLE_FRAME_BUDGET_MS) } else { (COMPOSITE_BUDGET_MS, FRAME_BUDGET_MS) } -} - -/// Compositing time per frame while the user is working: a full recomposite of a large texture -/// set spreads over frames. +/// Compositing time per frame: a full recomposite of a large texture set spreads over frames. const COMPOSITE_BUDGET_MS: f64 = 30.0; -/// Compositing time per frame once the user has stopped touching the app: the compositor scales -/// with the machine's cores, so a longer slice finishes sooner on a fast PC (a frame then takes -/// longer, but nothing is being dragged or painted that would feel it). -const IDLE_COMPOSITE_BUDGET_MS: f64 = 100.0; -/// [`FRAME_BUDGET_MS`] while idle: the idle compositing slice plus the usual rest of the frame. -const IDLE_FRAME_BUDGET_MS: f64 = IDLE_COMPOSITE_BUDGET_MS + (FRAME_BUDGET_MS - COMPOSITE_BUDGET_MS); -/// Frames without input (about 0.2 s at 60 fps) before the longer idle slices start, so a short -/// pause between strokes or drags keeps the responsive budget. -const IDLE_FRAMES_BEFORE_BOOST: u32 = 12; /// The most a frame spends on the scene (with the work already done this frame, such as a /// stroke's commit): compositing and display conversion leave the rest for the next frames, so /// a large (8K) texture set never stalls one frame. @@ -127,10 +109,6 @@ const UPLOAD_CHUNK: usize = 64; /// Estimated GPU upload cost of one display tile (write_texture of one 64×64 tile of one /// display kind, measured at ~5.5 µs on a desktop GPU), counted against the frame budget. const UPLOAD_MS_PER_TILE: f64 = 0.006; -/// CPU cost of converting one display tile of one kind for upload ([`tile_bytes`], measured at -/// ~6 µs: 8192 in 50 ms on a 24-thread desktop): with [`UPLOAD_MS_PER_TILE`], what a tile still -/// waiting for upload will cost this frame. -const CONVERT_MS_PER_TILE: f64 = 0.006; pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { let reset = Arc::new(AtomicBool::new(false)); @@ -162,7 +140,6 @@ pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { aux: BTreeMap::new(), adapter: format!("{} ({:?})", info.name, info.backend), composite_total: 0, - idle_frames: 0, bake_scene: BakeSceneLink::default(), } } @@ -185,28 +162,13 @@ impl GpuLink { } /// Collect everything the GPU needs this frame, running the compositor first: `bake` is what bake mode's 3D view draws besides the low poly, `spent_ms` the time this frame already took - pub fn sync( - &mut self, - session: &mut Session, - aux_map: Option, - bake: Option, - shift: u32, - spent_ms: f64, - user_active: bool, - ) -> SceneSync { + pub fn sync(&mut self, session: &mut Session, aux_map: Option, bake: Option, shift: u32, spent_ms: f64) -> SceneSync { let start_ms = crate::now_ms(); let mut queued = 0usize; - self.idle_frames = if user_active { 0 } else { self.idle_frames.saturating_add(1) }; - let (composite_budget_ms, frame_budget_ms) = frame_budgets(self.idle_frames); - let time_left_ms = |queued: usize| frame_budget_ms - spent_ms - (crate::now_ms() - start_ms) - queued as f64 * UPLOAD_MS_PER_TILE; + let time_left_ms = |queued: usize| FRAME_BUDGET_MS - spent_ms - (crate::now_ms() - start_ms) - queued as f64 * UPLOAD_MS_PER_TILE; let pending = session.pending_tiles(); self.composite_total = if pending == 0 { 0 } else { self.composite_total.max(pending) }; - // Tiles composited earlier and still waiting to be uploaded go first: a big change's - // coarse look is composited in a frame or two, and showing it whole matters more than - // compositing on (otherwise it appears a chunk of tiles per frame). - let backlog = session.caches.iter().map(|c| c.upload.len()).sum::() * DisplayKind::ALL.len(); - let backlog_ms = backlog as f64 * (UPLOAD_MS_PER_TILE + CONVERT_MS_PER_TILE); - session.update_for(composite_budget_ms.min(time_left_ms(0) - backlog_ms).max(MIN_SLICE_MS), crate::now_ms); + session.update_for(COMPOSITE_BUDGET_MS.min(time_left_ms(0)).max(MIN_SLICE_MS), crate::now_ms); let mut out = SceneSync::default(); if self.lost.swap(false, Ordering::AcqRel) { @@ -448,26 +410,3 @@ impl CallbackTrait for ViewCallback { gpu.renderer.blit_prepared(pass, self.frame.view_id); } } - -#[cfg(test)] -mod tests { - use super::*; - - /// While the user is working (or just stopped) a frame keeps the responsive budgets. - #[test] - fn budgets_stay_short_while_the_user_is_active() { - assert_eq!(frame_budgets(0), (COMPOSITE_BUDGET_MS, FRAME_BUDGET_MS)); - assert_eq!(frame_budgets(IDLE_FRAMES_BEFORE_BOOST - 1), (COMPOSITE_BUDGET_MS, FRAME_BUDGET_MS)); - } - - /// After a pause the compositor gets the longer slice, and the frame budget grows with it so the - /// display uploads keep their usual share. - #[test] - fn budgets_grow_once_the_user_is_idle() { - let (composite, frame) = frame_budgets(IDLE_FRAMES_BEFORE_BOOST); - assert_eq!(composite, IDLE_COMPOSITE_BUDGET_MS); - assert!(composite > COMPOSITE_BUDGET_MS); - assert_eq!(frame - composite, FRAME_BUDGET_MS - COMPOSITE_BUDGET_MS, "the non-compositing share of a frame is unchanged"); - assert_eq!(frame_budgets(u32::MAX), (composite, frame), "stays boosted"); - } -} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index be6c87da..f3087537 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -317,11 +317,7 @@ fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, mut frame: Frame let scene = match (sync.0.take(), app.gpu.as_mut()) { (Some(aux), Some(gpu_link)) => { let sync_start_ms = crate::now_ms(); - // Pointer, key and scroll input all count: the compositor then keeps frames short. - let user_active = - ui.ctx().input(|i| i.pointer.is_moving() || i.pointer.any_down() || !i.events.is_empty() || i.smooth_scroll_delta != egui::Vec2::ZERO); - let scene = - gpu_link.sync(&mut app.session, aux, bake, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms), user_active); + let scene = gpu_link.sync(&mut app.session, aux, bake, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms)); let reports = gpu_link.take_reports(); app.profiler.sync_ms += (crate::now_ms() - sync_start_ms) as f32; gpu_report_toasts(app, reports);