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()); +}