From 34ba091e8a2e6049ca50be177fcb21500ca01743 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Thu, 5 Nov 2026 20:44:48 +0000 Subject: [PATCH 1/3] Smart mask previews that show the mask Shelf thumbnails now show each smart mask applied with mask.smart.apply to a baked preview shape (geom::primitives::preview_orb) and read back from the compositor (compose::mask_at, a sparse read sharing mask_image's per-tile code), shaded flat white over a softly lit near-black surface. The shape bakes once on a worker; preview::smart_mask's world-noise approximation is removed. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/eval.rs | 121 ++++++++++++++++-- crates/compose/src/lib.rs | 2 +- crates/engine/src/lib.rs | 2 + crates/engine/src/mask_preview.rs | 163 ++++++++++++++++++++++++ crates/engine/src/mask_preview_pixel.rs | 14 ++ crates/engine/src/preview.rs | 20 +-- crates/engine/src/session.rs | 7 + crates/geom/src/primitives.rs | 158 ++++++++++++++++++++++- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/mask_previews.rs | 104 +++++++++++++++ crates/ui-egui/src/thumbs.rs | 30 +++-- 11 files changed, 579 insertions(+), 43 deletions(-) create mode 100644 crates/engine/src/mask_preview.rs create mode 100644 crates/engine/src/mask_preview_pixel.rs create mode 100644 crates/ui-egui/src/mask_previews.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 6c642b75..56b32cd8 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1843,31 +1843,25 @@ pub fn mask_image(inp: &Inputs, id: LayerId, size: u32) -> Option> { let (w, h) = (inp.gbuf.width, inp.gbuf.height); let all = all_tiles(w, h); let fields = neighbourhood_fields(inp, &channels, &all); - let tiles: Vec<(u32, u32, Vec)> = all + let tiles: HashMap<(u32, u32), Vec> = all .par_iter() - .filter_map(|&(tx, ty)| { - let mp = mask_plan(inp, id, mask, tx, ty, Some(&fields))?; - let full = anchor_plan(inp, id, &channels, tx, ty, Some(&fields)); + .map(|&tile| { let mut buf = vec![0u8; TILE_AREA]; - for (x, y, o) in tile_texels(inp.gbuf, tx, ty) { - let mut tex = Texel::new(inp, x, y, o, 0.0); - if !full.is_empty() { - tex.anchors_below(&full, id); - } + for (o, v) in mask_tile(inp, id, mask, &channels, &fields, tile, |_| true) { if let Some(b) = buf.get_mut(o) { - *b = (tex.mask(&mp) * 255.0 + 0.5) as u8; + *b = (v * 255.0 + 0.5) as u8; } } - Some((tx, ty, buf)) + (tile, buf) }) .collect(); + let size = size.max(1); let mut out = vec![0u8; (size * size) as usize]; - let lookup: std::collections::HashMap<(u32, u32), &Vec> = tiles.iter().map(|(x, y, b)| ((*x, *y), b)).collect(); for y in 0..size { for x in 0..size { let (sx, sy) = ((x as u64 * w as u64 / size as u64) as u32, (y as u64 * h as u64 / size as u64) as u32); - if let Some(t) = lookup.get(&(sx / TILE, sy / TILE)) + if let Some(t) = tiles.get(&(sx / TILE, sy / TILE)) && let Some(v) = t.get(((sy % TILE) * TILE + sx % TILE) as usize) && let Some(d) = out.get_mut((y * size + x) as usize) { @@ -1878,6 +1872,68 @@ pub fn mask_image(inp: &Inputs, id: LayerId, size: u32) -> Option> { Some(out) } +/// The mask of layer `id` (0..=1) at `texels` (x, y) of the texture set, in order; 0 where the +/// mesh does not cover a texel. Only the requested texels are evaluated, so a sparse read (a +/// preview's visible texels) costs a fraction of [`mask_image`]. None when the layer has no +/// enabled mask. +pub fn mask_at(inp: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option> { + let mask = layer_mask(inp.project, id).filter(|m| m.enabled)?; + let channels = inp.project.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); + // Neighbourhood effects (blur, warp) read past the requested texels, so their fields cover + // every tile, as in `mask_image` + let fields = neighbourhood_fields(inp, &channels, &all_tiles(inp.gbuf.width, inp.gbuf.height)); + + // Per tile: offset in the tile -> indices in `texels` asking for it + let mut wanted: HashMap<(u32, u32), HashMap>> = HashMap::new(); + for (i, &(x, y)) in texels.iter().enumerate() { + let offset = ((y % TILE) * TILE + x % TILE) as usize; + wanted.entry((x / TILE, y / TILE)).or_default().entry(offset).or_default().push(i); + } + let values: Vec<(usize, f32)> = wanted + .par_iter() + .flat_map_iter(|(&tile, offsets)| { + mask_tile(inp, id, mask, &channels, &fields, tile, |o| offsets.contains_key(&o)) + .into_iter() + .flat_map(move |(o, v)| offsets.get(&o).into_iter().flatten().map(move |&i| (i, v))) + }) + .collect(); + + let mut out = vec![0.0; texels.len()]; + for (i, v) in values { + if let Some(d) = out.get_mut(i) { + *d = v; + } + } + Some(out) +} + +/// Layer `id`'s enabled `mask` at the covered texels of `tile` whose offset in the tile passes +/// `wanted`, as (offset, value 0..=1); empty for a tile the mask has no plan for. +fn mask_tile( + inp: &Inputs, + id: LayerId, + mask: &Mask, + channels: &[Channel], + fields: &Fields, + (tx, ty): (u32, u32), + wanted: impl Fn(usize) -> bool, +) -> Vec<(usize, f32)> { + let Some(plan) = mask_plan(inp, id, mask, tx, ty, Some(fields)) else { return Vec::new() }; + + // Masks that read anchor points need the stack below the layer + let full = anchor_plan(inp, id, channels, tx, ty, Some(fields)); + tile_texels(inp.gbuf, tx, ty) + .filter(|&(_, _, o)| wanted(o)) + .map(|(x, y, o)| { + let mut texel = Texel::new(inp, x, y, o, 0.0); + if !full.is_empty() { + texel.anchors_below(&full, id); + } + (o, texel.mask(&plan)) + }) + .collect() +} + /// Tiles [`effect_histogram`] samples at most (a million texels). const HISTOGRAM_TILES: usize = 256; @@ -2175,6 +2231,45 @@ mod tests { assert!(vals.iter().any(|v| *v > 0.99) && vals.iter().any(|v| *v < 0.51), "{vals:?}"); } + #[test] + fn mask_at_reads_the_same_values_as_the_mask_image() { + let mut f = fixture(); + let id = fill_layer(&mut f.project, [1.0, 1.0, 1.0], 1.0); + let eid = f.project.alloc_id(); + let mut mask = Mask::new(MaskBackground::Black); + let pattern = Procedural::new(ProceduralKind::Checker); + mask.effects.push(Effect::new( + eid, + EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::default() }, + )); + f.project.layer_mut(id).unwrap().mask = Some(mask); + let maskless = f.project.alloc_id(); + let images = Default::default(); + let inp = Inputs { + project: &f.project, + ts: 0, + mesh: &f.mesh, + gbuf: &f.gbuf, + pixels: &f.pixels, + baked: &f.baked, + preview: None, + images: &images, + bounds: f.mesh.bounds(), + }; + + // Scattered texels, one twice, one outside the texture + let texels = [(0, 0), (13, 20), (63, 63), (40, 7), (13, 20), (64, 64)]; + let sparse = mask_at(&inp, id, &texels).unwrap(); + let image = mask_image(&inp, id, 64).unwrap(); + for (&(x, y), v) in texels.iter().zip(&sparse).take(5) { + let expected = f32::from(image[(y * 64 + x) as usize]) / 255.0; + assert!((v - expected).abs() <= 0.5 / 255.0 + 1e-6, "({x}, {y}): {v} vs {expected}"); + } + assert_eq!(sparse[5], 0.0, "uncovered texels read 0"); + assert!(sparse.iter().any(|v| *v > 0.99) && sparse.iter().take(5).any(|v| *v < 0.01), "{sparse:?}"); + assert!(mask_at(&inp, maskless, &texels).is_none(), "no mask, no values"); + } + #[test] fn blur_filter_softens_mask_edges() { let mut f = fixture(); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 5e34945c..ee940e06 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -17,6 +17,6 @@ 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_image, pad_tiles, + mask_at, mask_image, pad_tiles, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ed07d645..ca7cdeea 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -25,6 +25,8 @@ pub mod layer_cmds; pub mod layer_ops; pub mod link_cmds; pub mod mask_cmds; +pub mod mask_preview; +mod mask_preview_pixel; pub mod material_lib; pub mod materials; pub mod materialx_cmds; diff --git a/crates/engine/src/mask_preview.rs b/crates/engine/src/mask_preview.rs new file mode 100644 index 00000000..e7116d9d --- /dev/null +++ b/crates/engine/src/mask_preview.rs @@ -0,0 +1,163 @@ +//! Smart mask shelf previews: the real smart masks on a baked preview shape. The shape +//! ([`primitives::preview_orb`]) is baked once; each preset is then applied with +//! `mask.smart.apply`, read back from the compositor and seen from a fixed camera. + +use serde_json::json; +use texturecraft_core::{BakeResolution, BakedMap, CurvatureMethod, LayerId}; +use texturecraft_geom::glam::{Quat, Vec2, Vec3}; +use texturecraft_geom::{primitives, surface_at}; + +pub use crate::mask_preview_pixel::MaskPreviewPixel; +use crate::{EngineError, Result, Session}; + +/// Texture and bake size of the preview shape in texels (at 256 the edge lines break up). +const TEXTURE_PX: u32 = 512; +/// Camera rays per thumbnail pixel along each axis (anti-aliased outline). +const SUPERSAMPLE: usize = 2; +/// AO and thickness rays per texel (the default is 64; fewer look the same at thumbnail size). +const OCCLUSION_RAYS: u32 = 12; +/// Mesh curvature rays per texel (the default is 32; fewer look the same at thumbnail size). +const CURVATURE_RAYS: u32 = 12; +/// Mesh curvature sampling radius relative to the bounding box: wide enough that edges read as +/// lines at thumbnail size, narrow enough that the round body does not count as an edge. +const CURVATURE_RADIUS: f32 = 0.005; +/// The mesh maps the smart mask generators read. +const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; +/// Camera: looking down by this angle, turned to show the front, left and top panels. +const CAMERA_PITCH_DEG: f32 = 35.0; +const CAMERA_YAW_DEG: f32 = -34.4; + +/// What one camera sub-pixel sees: the index of its texel in the preview's texel list and the +/// view-space normal there (None where the ray misses). +type CameraSample = Option<(usize, Vec3)>; + +/// The baked preview shape and what each thumbnail sub-pixel sees. +pub struct MaskPreview { + session: Session, + layer: LayerId, + size: usize, + /// The texels (x, y) the camera sees, each once. + texels: Vec<(u32, u32)>, + /// Per sub-pixel, row-major `(size · SUPERSAMPLE)²`. + samples: Vec, +} + +impl MaskPreview { + /// Bake the preview shape once and aim the camera for `size²` thumbnails. + pub fn new(size: usize) -> Result { + let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; + let set = session.doc.project.texture_set_mut(0)?; + set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; + set.bake.high_poly.use_low_as_high = true; + set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh; + set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS; + set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS; + set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS; + set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS; + for map in BakedMap::ALL { + set.bake.maps.set_enabled(map, MAPS.contains(&map)); + } + let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; + session.bake_now(0, false)?; + + let (texels, samples) = camera_samples(&session, size * SUPERSAMPLE); + Ok(MaskPreview { session, layer, size, texels, samples }) + } + + /// Smart mask `id` per thumbnail pixel, row-major `size²`, None where the shape is not seen + /// (None for an unknown id). + pub fn render(&mut self, id: &str) -> Option>> { + crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; + // Nothing is undone here; the snapshots would pile up over the presets + self.session.undo.clear(); + let values = self.session.mask_at(self.layer, &self.texels)?; + + let fine = self.size * SUPERSAMPLE; + let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; + let pixels = (0..self.size * self.size) + .map(|i| { + let (x, y) = (i % self.size, i / self.size); + let (mut mask, mut normal, mut hits) = (0.0, Vec3::ZERO, 0.0); + for sy in 0..SUPERSAMPLE { + for sx in 0..SUPERSAMPLE { + let Some(&Some((texel, n))) = self.samples.get((y * SUPERSAMPLE + sy) * fine + x * SUPERSAMPLE + sx) else { continue }; + + mask += values.get(texel).copied().unwrap_or(0.0); + normal += n; + hits += 1.0; + } + } + (hits > 0.0).then(|| MaskPreviewPixel { mask: mask / hits, normal: normal.normalize_or_zero(), coverage: hits / sub_pixels }) + }) + .collect(); + Some(pixels) + } +} + +/// What each pixel of a `size²` orthographic view of the shape sees: the distinct texels hit, and +/// per pixel (row-major) its sample. +fn camera_samples(session: &Session, size: usize) -> (Vec<(u32, u32)>, Vec) { + let (lo, hi) = session.mesh.bounds(); + let center = (lo + hi) * 0.5; + let radius = session.mesh.positions.iter().map(|p| p.distance(center)).fold(0.0f32, f32::max); + let pitch = CAMERA_PITCH_DEG.to_radians(); + let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians()); + let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos()); + let right = turn * Vec3::X; + let up = right.cross(forward); + let max_texel = TEXTURE_PX - 1; + + let mut texels = Vec::new(); + let mut index_of = std::collections::HashMap::new(); + let samples = (0..size * size) + .map(|i| { + let ndc = Vec2::new(((i % size) as f32 + 0.5) / size as f32 * 2.0 - 1.0, 1.0 - ((i / size) as f32 + 0.5) / size as f32 * 2.0); + // Start well outside the shape so every ray enters it from the front + let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0; + let hit = session.bvh.closest(origin, forward, radius * 8.0)?; + let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?; + let texel = (((surface.uv.x * TEXTURE_PX as f32) as u32).min(max_texel), ((surface.uv.y * TEXTURE_PX as f32) as u32).min(max_texel)); + let index = *index_of.entry(texel).or_insert_with(|| { + texels.push(texel); + texels.len() - 1 + }); + let n = surface.nrm; + Some((index, Vec3::new(n.dot(right), n.dot(up), -n.dot(forward)))) + }) + .collect(); + (texels, samples) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Mean absolute difference of the masks of two previews over the pixels both see. + fn difference(a: &[Option], b: &[Option]) -> f32 { + let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect(); + pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 + } + + #[test] + fn smart_mask_previews_are_in_range_and_tell_edges_from_cavities() { + let size = 24; + let mut preview = MaskPreview::new(size).unwrap(); + for sm in crate::smart_masks::SMART_MASKS { + let px = preview.render(sm.id).unwrap_or_else(|| panic!("{}", sm.id)); + assert_eq!(px.len(), size * size, "{}", sm.id); + assert!(px[0].is_none(), "{}: the corners are outside the shape", sm.id); + let seen: Vec<&MaskPreviewPixel> = px.iter().flatten().collect(); + assert!(seen.len() > size * size / 3, "{}: the shape fills the frame", sm.id); + for p in seen { + assert!((0.0..=1.0).contains(&p.mask) && (0.0..=1.0).contains(&p.coverage) && p.coverage > 0.0, "{}: {p:?}", sm.id); + assert!(p.normal.is_finite(), "{}: {p:?}", sm.id); + } + } + + let (edges, cavities) = (preview.render("edges_sharp").unwrap(), preview.render("dirt_cavities").unwrap()); + let shows = |px: &[Option]| px.iter().flatten().any(|p| p.mask > 0.5); + assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape"); + assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); + assert!(preview.render("nope").is_none()); + } +} diff --git a/crates/engine/src/mask_preview_pixel.rs b/crates/engine/src/mask_preview_pixel.rs new file mode 100644 index 00000000..bcde5629 --- /dev/null +++ b/crates/engine/src/mask_preview_pixel.rs @@ -0,0 +1,14 @@ +//! One pixel of a smart mask preview (see [`crate::mask_preview::MaskPreview`]). + +use texturecraft_geom::glam::Vec3; + +/// The smart mask value seen at a preview pixel, with what a display needs to shade the shape. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MaskPreviewPixel { + /// Mask value (0..=1). + pub mask: f32, + /// Surface normal in view space (+X right, +Y up, +Z towards the viewer). + pub normal: Vec3, + /// Fraction of the pixel the shape covers (0..=1, anti-aliased outline). + pub coverage: f32, +} diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 3c3aa130..1dc33631 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -1,6 +1,7 @@ -//! Shelf previews: built-in materials and smart masks evaluated on a unit sphere seen from +Z, -//! without a mesh or baked maps (generators that need mesh maps are approximated with world-space -//! noise). Cheap enough for lazily rendered thumbnails. +//! Shelf previews: built-in materials evaluated on a unit sphere seen from +Z, without a mesh or +//! baked maps (generators that need mesh maps are approximated with world-space noise), and +//! library filters. Cheap enough for lazily rendered thumbnails. Smart masks have their own baked +//! preview ([`crate::mask_preview`]). use texturecraft_compose::pattern::{Coords, procedural, world_noise}; use texturecraft_core::{ @@ -183,13 +184,6 @@ pub fn filter(id: &str, size: usize) -> Option>> { ) } -/// Preview of smart mask `id`: the mask value per pixel (None for an unknown id). -pub fn smart_mask(id: &str, size: usize) -> Option>> { - let (bg, fx) = crate::smart_masks::preset(id)?; - let m = crate::smart_masks::build_mask(&mut Project::new("preview", ""), bg, fx); - Some(sphere_normals(size).map(|n| n.map(|n| mask(&m, &coords(n)))).collect()) -} - #[cfg(test)] mod tests { use super::*; @@ -202,11 +196,7 @@ mod tests { assert!(center.base.iter().chain([¢er.metallic, ¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", m.id); assert!(px[0].is_none(), "corners are outside the sphere"); } - for sm in crate::smart_masks::SMART_MASKS { - let px = smart_mask(sm.id, 16).unwrap_or_else(|| panic!("{}", sm.id)); - assert!(px.iter().flatten().all(|v| (0.0..=1.0).contains(v)), "{}", sm.id); - } - assert!(material("nope", 8).is_none() && smart_mask("nope", 8).is_none() && filter("nope", 8).is_none()); + assert!(material("nope", 8).is_none() && filter("nope", 8).is_none()); for f in crate::filter_lib::FILTERS { let px = filter(f.id, 24).unwrap_or_else(|| panic!("{}", f.id)); let center = px[12 * 24 + 12].unwrap_or_else(|| panic!("{}", f.id)); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 7ec12739..214bd69f 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -829,6 +829,13 @@ impl Session { Some(gray.iter().flat_map(|g| [*g, *g, *g, 255]).collect()) } + /// Layer `id`'s mask (0..=1) at `texels` (x, y) of its texture set, in order (None without a + /// mask); evaluates only those texels. + pub fn mask_at(&self, id: LayerId, texels: &[(u32, u32)]) -> Option> { + let (ts, _, _) = self.doc.project.locate(id)?; + self.with_inputs(ts, |inp| texturecraft_compose::mask_at(inp, id, texels)) + } + /// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's /// mask, or for a content effect the layer's `channel` (None for an unknown effect). pub fn effect_histogram(&self, effect: LayerId, channel: Channel, bins: usize) -> Option> { diff --git a/crates/geom/src/primitives.rs b/crates/geom/src/primitives.rs index 6403faed..29bad947 100644 --- a/crates/geom/src/primitives.rs +++ b/crates/geom/src/primitives.rs @@ -63,9 +63,17 @@ impl Builder { } } + /// The mesh of one material, with tangents. fn finish(self, material: &str) -> Mesh { + let mut m = self.into_mesh(material); + m.compute_tangents(); + m + } + + /// The mesh of one material, without tangents. + fn into_mesh(self, material: &str) -> Mesh { let count = self.idx.len() as u32; - let mut m = Mesh { + Mesh { positions: self.p, normals: self.n, uvs: self.uv, @@ -75,9 +83,7 @@ impl Builder { submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], materials: vec![material.into()], diagonals: self.diag, - }; - m.compute_tangents(); - m + } } } @@ -189,6 +195,132 @@ fn lathe_into(b: &mut Builder, center: Vec3, profile: &[(f32, f32)], segs: usize }); } +/// [`preview_orb`]: half-size of the cube that cuts the unit sphere flat (each face rim is the +/// circle where they meet). +const ORB_CUT: f32 = 0.8; +/// [`preview_orb`] domed panels: where the valley sits, as a fraction of the face rim radius. +const ORB_PANEL_VALLEY: f32 = 0.88; + +/// The smart mask preview shape: a sphere cut flat by a cube on six sides, on a thin round base. +/// Each feature gives one kind of mask something to show: sharp face rims (edges), a softly +/// blended left face (soft edges), domed panels inside the front, left and top faces whose valleys +/// hold dirt (cavities), a slot around the middle (cavity), the base (thin part, the seam where it +/// meets the body) and plain rounded corners (gradients). Faces +Z (front), -X (left) and +Y (top) +/// carry the panels, so the shape is made to be seen from the front left, slightly from above. +/// The body takes the top 79 % of the UV square, the base the bottom 19 %. +pub fn preview_orb() -> Mesh { + // Grid rows (columns: twice as many); fewer blur the panel walls, more cost bake time + const ROWS: usize = 300; + const BODY_UV_HEIGHT: f32 = 0.79; + const BASE_UV: UvRect = UvRect { o: Vec2::new(0.0, 0.81), s: Vec2::new(1.0, 0.19) }; + const BASE_RADIUS: f32 = 0.95; + const BASE_HALF_HEIGHT: f32 = 0.025; + const BASE_Y: f32 = -0.6; + const BASE_RIM_STEPS: usize = 12; + const BASE_SEGMENTS: usize = 256; + + let mut b = Builder::default(); + b.grid(ROWS, ROWS * 2, |i, j| { + let (u, v) = (j as f32 / (ROWS * 2) as f32, i as f32 / ROWS as f32); + let (theta, phi) = (v * PI, u * TAU + PI * 1.5); + let dir = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin()); + (dir * preview_orb_radius(dir), dir, Vec2::new(u, v * BODY_UV_HEIGHT)) + }); + + // Base: a thin disc with a rounded rim (a half circle from its top face to its bottom face) + let mut profile = vec![(0.0, BASE_HALF_HEIGHT)]; + for k in 0..=BASE_RIM_STEPS { + let a = k as f32 / BASE_RIM_STEPS as f32 * PI; + profile.push((BASE_RADIUS - BASE_HALF_HEIGHT + BASE_HALF_HEIGHT * a.sin(), BASE_HALF_HEIGHT * a.cos())); + } + profile.push((0.0, -BASE_HALF_HEIGHT)); + lathe_into(&mut b, Vec3::Y * BASE_Y, &profile, BASE_SEGMENTS, BASE_UV); + + let mut m = b.into_mesh("Preview"); + // Normals from the triangles: the panel walls are too steep for the sphere's directions + m.compute_normals(); + // Body and base both run U around the vertical axis, so the tangent is that direction (a + // fraction of the cost of the general tangent pass on this many triangles) + m.tangents = m + .positions + .iter() + .zip(&m.normals) + .map(|(p, n)| { + let around = Vec3::new(p.z, 0.0, -p.x).try_normalize().unwrap_or(Vec3::X); + (around - *n * n.dot(around)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()).extend(1.0) + }) + .collect(); + m +} + +/// Distance from the centre of the [`preview_orb`] body along unit direction `d`. +fn preview_orb_radius(d: Vec3) -> f32 { + // Rim blends: the sharp faces, and the softly blended left face + const SHARP_BLEND: f32 = 0.035; + const SOFT_BLEND: f32 = 0.18; + // Domed panels: valley depth below the face, dome rise past it; the left panel is smaller + const PANEL_DEPTH: f32 = 0.11; + const PANEL_BULGE: f32 = 0.04; + const LEFT_PANEL_SCALE: f32 = 0.9; + // Slot around the middle: centre height, half-width, edge rounding, depth; it fades out over + // this fraction of the left panel's rim + const SLOT_Y: f32 = -0.03; + const SLOT_HALF_WIDTH: f32 = 0.05; + const SLOT_ROUNDING: f32 = 0.015; + const SLOT_DEPTH: f32 = 0.12; + const SLOT_FADE: f32 = 0.04; + + let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT; + let smooth = |a: f32, b: f32, x: f32| { + let t = ((x - a) / (b - a)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) + }; + // Polynomial smooth minimum with blend radius k + let smin = |a: f32, b: f32, k: f32| { + let h = (0.5 + 0.5 * (b - a) / k).clamp(0.0, 1.0); + b + (a - b) * h - k * h * (1.0 - h) + }; + // Domed panel at `rho` (radius in face units) inside a face of rim `rim`: a steep wall from + // the rim into a valley, then a dome rising slightly past the face over the middle + let panel = |rho: f32, rim: f32| { + let valley = rim * ORB_PANEL_VALLEY; + if rho < valley { + PANEL_BULGE - (PANEL_BULGE + PANEL_DEPTH) * (rho / valley).powi(3) + } else { + -PANEL_DEPTH * (1.0 - ((rho - valley) / (rim - valley)).min(1.0)) + } + }; + let face_rho = |along: f32, u: f32, v: f32| (u * u + v * v).sqrt() / along.max(1e-3); + + // The cut: sharp rims except the softly blended left face + let mut radius = 1.0f32; + for (along, blend) in [(d.x, SHARP_BLEND), (-d.x, SOFT_BLEND), (d.y, SHARP_BLEND), (-d.y, SHARP_BLEND), (d.z, SHARP_BLEND), (-d.z, SHARP_BLEND)] { + // Directions facing away from a face stay on the sphere (9 = far past it) + let to_face = if along > 1e-3 { ORB_CUT / along } else { 9.0 }; + radius = smin(radius, to_face, blend); + } + + let a = d.abs(); + let left_rim = rim * LEFT_PANEL_SCALE; + let mut relief = 0.0; + if d.z > 0.0 && a.z >= a.x && a.z >= a.y { + relief += panel(face_rho(d.z, d.x, d.y), rim); + } + if d.x < 0.0 && a.x >= a.y && a.x >= a.z { + relief += panel(face_rho(-d.x, d.y, d.z), left_rim); + } + if d.y > 0.0 && a.y >= a.x && a.y >= a.z { + relief += panel(face_rho(d.y, d.x, d.z), rim); + } + + // Slot around the middle, stopping at the left panel + let in_left_panel = if d.x < 0.0 { 1.0 - smooth(left_rim * (1.0 - SLOT_FADE), left_rim * (1.0 + SLOT_FADE), face_rho(-d.x, d.y, d.z)) } else { 0.0 }; + let slot_band = 1.0 - smooth(SLOT_HALF_WIDTH - SLOT_ROUNDING, SLOT_HALF_WIDTH + SLOT_ROUNDING, (d.y - SLOT_Y).abs()); + relief -= SLOT_DEPTH * slot_band * (1.0 - in_left_panel); + + radius + relief +} + /// A flat disk facing up (+Y) or down, with planar UVs inside `r`. fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, r: UvRect) { let n = if up { Vec3::Y } else { Vec3::NEG_Y }; @@ -340,6 +472,8 @@ pub fn builtin(id: &str) -> Option { "plane" => plane(2.0, 16), "crate" => crate_scene(), "udim_plane" | "udimplane" => udim_plane(), + // Not offered for new projects (not in BUILTINS): the smart mask preview session's mesh + "preview_orb" => preview_orb(), _ => return None, }) } @@ -396,6 +530,22 @@ mod tests { assert_eq!(udim_plane().uv_tiles(0).into_iter().collect::>(), vec![(0, 0), (1, 0)]); } + #[test] + fn preview_orb_is_well_formed_with_domed_panels() { + let m = preview_orb(); + check(&m, 1.0); + + // Above the middle slot, the front panel's dome rises past the cut face and its valley + // sits below it + let front_depth = |rho: f32| { + let d = Vec3::new(0.0, rho, 1.0).normalize(); + preview_orb_radius(d) * d.z + }; + let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT; + let (dome, valley) = (front_depth(0.2), front_depth(rim * ORB_PANEL_VALLEY)); + assert!(dome > ORB_CUT && valley < ORB_CUT - 0.05, "dome {dome}, valley {valley}"); + } + #[test] fn material_ball_has_two_materials() { let m = material_ball(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c6112eb3..df2d1c7a 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; +mod mask_previews; pub mod menus; pub mod parity; pub mod profile; diff --git a/crates/ui-egui/src/mask_previews.rs b/crates/ui-egui/src/mask_previews.rs new file mode 100644 index 00000000..fc6018e4 --- /dev/null +++ b/crates/ui-egui/src/mask_previews.rs @@ -0,0 +1,104 @@ +//! Smart mask shelf thumbnails: every smart mask on the baked preview shape, rendered together on +//! a worker the first time the shelf asks for one (baking the shape takes about two seconds on +//! the CPU; on the web the work runs inline). + +use std::sync::mpsc::{Receiver, TryRecvError}; +use std::time::Duration; + +use egui::{Color32, ColorImage}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::mask_preview::{MaskPreview, MaskPreviewPixel}; +use texturecraft_engine::smart_masks::SMART_MASKS; +use texturecraft_engine::texel::linear_to_srgb; + +/// View-space directions of the key light (upper left) and a weaker fill (right), and how much +/// each lights the surface. +const KEY: [f32; 3] = [-0.72, 0.62, 0.3]; +const FILL: [f32; 3] = [0.7, -0.1, 0.7]; +const AMBIENT: f32 = 0.1; +const KEY_STRENGTH: f32 = 0.8; +const FILL_STRENGTH: f32 = 0.35; +/// Where the mask is empty: a near-black albedo with a faint sheen of the key light, so the +/// shape reads without looking glossy. +const UNMASKED_ALBEDO: f32 = 0.006; +const SHEEN: f32 = 0.1; +const SHEEN_EXPONENT: f32 = 40.0; +/// Where the mask is full: white, darkened at most this much where unlit. +const WHITE_SHADING: f32 = 0.2; +/// How often the shelf checks for the thumbnails while they render. +const POLL: Duration = Duration::from_millis(100); + +/// Smart mask thumbnails by id, as the worker sends them. +type Thumbnails = Vec<(&'static str, ColorImage)>; + +/// Where the smart mask thumbnails are. +#[derive(Default)] +pub enum MaskPreviews { + #[default] + NotStarted, + Rendering(Receiver), + /// Handed out (or the worker failed; the tiles keep their placeholder). + Finished, +} + +impl MaskPreviews { + /// Start rendering `size²` thumbnails on the first call; the finished thumbnails on the call + /// that finds them done (None before and after). + pub fn poll(&mut self, ctx: &egui::Context, size: usize) -> Option { + if matches!(self, MaskPreviews::NotStarted) { + *self = MaskPreviews::Rendering(crate::spawn_worker("texturecraft-mask-previews", move || render(size))); + } + let MaskPreviews::Rendering(rx) = self else { return None }; + + match rx.try_recv() { + Ok(thumbnails) => { + *self = MaskPreviews::Finished; + Some(thumbnails) + } + Err(TryRecvError::Empty) => { + ctx.request_repaint_after(POLL); + None + } + // The worker stopped without a result + Err(TryRecvError::Disconnected) => { + *self = MaskPreviews::Finished; + None + } + } + } +} + +/// Every smart mask's `size²` thumbnail (empty when the preview shape fails to bake). +fn render(size: usize) -> Thumbnails { + let mut preview = match MaskPreview::new(size) { + Ok(p) => p, + Err(e) => { + log::warn!("smart mask previews: {e}"); + return Vec::new(); + } + }; + SMART_MASKS.iter().filter_map(|m| Some((m.id, image(size, &preview.render(m.id)?)))).collect() +} + +/// A thumbnail (sRGB, transparent outside the shape) from preview pixels (row-major `size²`): +/// the mask as white over a near-black surface lit softly from the upper left. No environment +/// reflections. +fn image(size: usize, pixels: &[Option]) -> ColorImage { + let key = Vec3::from(KEY).normalize(); + let fill = Vec3::from(FILL).normalize(); + let half = (key + Vec3::Z).normalize(); + let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); + + for (out, p) in img.pixels.iter_mut().zip(pixels) { + let Some(p) = p else { continue }; + + let n = p.normal; + let shading = AMBIENT + KEY_STRENGTH * n.dot(key).max(0.0) + FILL_STRENGTH * n.dot(fill).max(0.0); + let unmasked = UNMASKED_ALBEDO * shading + SHEEN * n.dot(half).max(0.0).powf(SHEEN_EXPONENT); + let masked = 1.0 - WHITE_SHADING * (1.0 - shading.min(1.0)); + let linear = unmasked + (masked - unmasked) * p.mask.clamp(0.0, 1.0); + let gray = (linear_to_srgb(linear.clamp(0.0, 1.0)) * 255.0 + 0.5) as u8; + *out = Color32::from_rgba_unmultiplied(gray, gray, gray, (p.coverage.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + } + img +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index a2d85712..f5590b31 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -1,6 +1,7 @@ -//! Thumbnails: shaded material spheres, smart mask spheres, procedural swatches and brush alpha -//! previews, rendered on the CPU into cached egui textures (no image assets). New shelf -//! thumbnails are rendered lazily, a few per frame, so opening the shelf never stalls a frame. +//! Thumbnails: shaded material spheres, smart masks on a baked preview shape, procedural swatches +//! and brush alpha previews, rendered on the CPU into cached egui textures (no image assets). New +//! shelf thumbnails are rendered lazily, a few per frame, so opening the shelf never stalls a +//! frame; the smart mask previews render together on a worker. use std::collections::HashMap; @@ -11,6 +12,8 @@ use texturecraft_engine::paint::{BrushAlpha, BrushSettings, Shape, alphas}; use texturecraft_engine::preview::{self, Sample}; use texturecraft_engine::texel::linear_to_srgb; +use crate::mask_previews::MaskPreviews; + /// Shelf thumbnails rendered per frame at most (the rest follow on the next frames). const PER_FRAME: usize = 2; /// Shelf sphere thumbnail size in pixels. @@ -24,6 +27,7 @@ pub struct Thumbs { images: HashMap, /// (frame, thumbnails rendered in it). budget: (u64, usize), + mask_previews: MaskPreviews, } fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { @@ -161,14 +165,20 @@ impl Thumbs { self.shelf(ctx, format!("mat:{id}"), || sphere_image(SPHERE_PX, &preview::material(id, SPHERE_PX).unwrap_or_default())) } - /// Sphere thumbnail of smart mask `id`: white where the mask applies, over dark gray. + /// Thumbnail of smart mask `id` on the baked preview shape (None while the thumbnails + /// render; they all arrive together). pub fn smart_mask(&mut self, ctx: &egui::Context, id: &str) -> Option { - self.shelf(ctx, format!("mask:{id}"), || { - let px = preview::smart_mask(id, SPHERE_PX).unwrap_or_default(); - let samples: Vec> = - px.iter().map(|m| m.map(|m| Sample { base: [0.04 + 0.76 * m; 3], metallic: 0.0, roughness: 0.6, height: 0.0 })).collect(); - sphere_image(SPHERE_PX, &samples) - }) + let key = format!("mask:{id}"); + if let Some(t) = self.shelf.get(&key) { + return Some(t.clone()); + } + + for (mask_id, image) in self.mask_previews.poll(ctx, SPHERE_PX).unwrap_or_default() { + let mask_key = format!("mask:{mask_id}"); + let t = ctx.load_texture(format!("thumb_{mask_key}"), image, TextureOptions::LINEAR); + self.shelf.insert(mask_key, t); + } + self.shelf.get(&key).cloned() } /// Sphere thumbnail of library filter `id` applied to a sample material. From 63df2b56e3ec98f0a80038ea4d86976dffb692bb Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 02:13:28 +0000 Subject: [PATCH 2/3] Shelf hover preview: a big version of the thumbnail Hovering a shelf tile shows a 256 pt preview of the asset over its name, rendered on a long-lived worker (its own thread pool) once the pointer rests on the tile, newest hover first. The smart mask thumbnails and the big mask previews share one bake. Renderers take their size as a parameter; the shelf thumbnails are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lib.rs | 1 + crates/engine/src/mask_preview.rs | 110 +++---- crates/engine/src/mask_preview_camera.rs | 64 +++++ crates/engine/src/preview.rs | 47 +-- crates/ui-egui/src/i18n/ar.rs | 23 -- crates/ui-egui/src/i18n/de.rs | 29 -- crates/ui-egui/src/i18n/es.rs | 29 -- crates/ui-egui/src/i18n/fr.rs | 29 -- crates/ui-egui/src/i18n/it.rs | 29 -- crates/ui-egui/src/i18n/ja.rs | 29 -- crates/ui-egui/src/i18n/ko.rs | 26 -- crates/ui-egui/src/i18n/pt_br.rs | 29 -- crates/ui-egui/src/i18n/zh_hans.rs | 14 - crates/ui-egui/src/lib.rs | 8 +- crates/ui-egui/src/mask_preview_image.rs | 44 +++ crates/ui-egui/src/mask_previews.rs | 104 ------- crates/ui-egui/src/mask_shape.rs | 33 +++ crates/ui-egui/src/preview_image.rs | 168 +++++++++++ crates/ui-egui/src/preview_request.rs | 29 ++ crates/ui-egui/src/preview_worker.rs | 207 +++++++++++++ crates/ui-egui/src/shelf.rs | 119 +++++--- crates/ui-egui/src/shelf_preview.rs | 102 +++++++ crates/ui-egui/src/thumbs.rs | 303 ++++++++------------ crates/ui-egui/src/worker_preview.rs | 13 + crates/ui-egui/tests/shelf_hover_preview.rs | 110 +++++++ 25 files changed, 1065 insertions(+), 634 deletions(-) create mode 100644 crates/engine/src/mask_preview_camera.rs create mode 100644 crates/ui-egui/src/mask_preview_image.rs delete mode 100644 crates/ui-egui/src/mask_previews.rs create mode 100644 crates/ui-egui/src/mask_shape.rs create mode 100644 crates/ui-egui/src/preview_image.rs create mode 100644 crates/ui-egui/src/preview_request.rs create mode 100644 crates/ui-egui/src/preview_worker.rs create mode 100644 crates/ui-egui/src/shelf_preview.rs create mode 100644 crates/ui-egui/src/worker_preview.rs create mode 100644 crates/ui-egui/tests/shelf_hover_preview.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ca7cdeea..201d0eb1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -26,6 +26,7 @@ pub mod layer_ops; pub mod link_cmds; pub mod mask_cmds; pub mod mask_preview; +mod mask_preview_camera; mod mask_preview_pixel; pub mod material_lib; pub mod materials; diff --git a/crates/engine/src/mask_preview.rs b/crates/engine/src/mask_preview.rs index e7116d9d..a8e2d1e2 100644 --- a/crates/engine/src/mask_preview.rs +++ b/crates/engine/src/mask_preview.rs @@ -4,15 +4,16 @@ use serde_json::json; use texturecraft_core::{BakeResolution, BakedMap, CurvatureMethod, LayerId}; -use texturecraft_geom::glam::{Quat, Vec2, Vec3}; -use texturecraft_geom::{primitives, surface_at}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::primitives; +use crate::mask_preview_camera::MaskPreviewCamera; pub use crate::mask_preview_pixel::MaskPreviewPixel; use crate::{EngineError, Result, Session}; /// Texture and bake size of the preview shape in texels (at 256 the edge lines break up). const TEXTURE_PX: u32 = 512; -/// Camera rays per thumbnail pixel along each axis (anti-aliased outline). +/// Camera rays per preview pixel along each axis (anti-aliased outline). const SUPERSAMPLE: usize = 2; /// AO and thickness rays per texel (the default is 64; fewer look the same at thumbnail size). const OCCLUSION_RAYS: u32 = 12; @@ -23,28 +24,20 @@ const CURVATURE_RAYS: u32 = 12; const CURVATURE_RADIUS: f32 = 0.005; /// The mesh maps the smart mask generators read. const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; -/// Camera: looking down by this angle, turned to show the front, left and top panels. -const CAMERA_PITCH_DEG: f32 = 35.0; -const CAMERA_YAW_DEG: f32 = -34.4; +/// Camera views kept at most (one per preview size: the shelf thumbnail and the hover preview). +const CAMERAS_KEPT: usize = 2; -/// What one camera sub-pixel sees: the index of its texel in the preview's texel list and the -/// view-space normal there (None where the ray misses). -type CameraSample = Option<(usize, Vec3)>; - -/// The baked preview shape and what each thumbnail sub-pixel sees. +/// The baked preview shape and, per preview size, what its camera sees. pub struct MaskPreview { session: Session, layer: LayerId, - size: usize, - /// The texels (x, y) the camera sees, each once. - texels: Vec<(u32, u32)>, - /// Per sub-pixel, row-major `(size · SUPERSAMPLE)²`. - samples: Vec, + /// Camera views of the most recently used preview sizes, oldest first (traced on first use). + cameras: Vec, } impl MaskPreview { - /// Bake the preview shape once and aim the camera for `size²` thumbnails. - pub fn new(size: usize) -> Result { + /// Bake the preview shape once (previews of any size reuse it). + pub fn new() -> Result { let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; let set = session.doc.project.texture_set_mut(0)?; set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; @@ -60,27 +53,28 @@ impl MaskPreview { let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; session.bake_now(0, false)?; - let (texels, samples) = camera_samples(&session, size * SUPERSAMPLE); - Ok(MaskPreview { session, layer, size, texels, samples }) + Ok(MaskPreview { session, layer, cameras: Vec::new() }) } - /// Smart mask `id` per thumbnail pixel, row-major `size²`, None where the shape is not seen + /// Smart mask `id` per preview pixel, row-major `size²`, None where the shape is not seen /// (None for an unknown id). - pub fn render(&mut self, id: &str) -> Option>> { + pub fn render(&mut self, id: &str, size: usize) -> Option>> { crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; // Nothing is undone here; the snapshots would pile up over the presets self.session.undo.clear(); - let values = self.session.mask_at(self.layer, &self.texels)?; - let fine = self.size * SUPERSAMPLE; + let camera = camera_for(&mut self.cameras, &self.session, size)?; + let values = self.session.mask_at(self.layer, &camera.texels)?; + let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; - let pixels = (0..self.size * self.size) + let pixels = (0..size * size) .map(|i| { - let (x, y) = (i % self.size, i / self.size); + let (x, y) = (i % size, i / size); let (mut mask, mut normal, mut hits) = (0.0, Vec3::ZERO, 0.0); for sy in 0..SUPERSAMPLE { for sx in 0..SUPERSAMPLE { - let Some(&Some((texel, n))) = self.samples.get((y * SUPERSAMPLE + sy) * fine + x * SUPERSAMPLE + sx) else { continue }; + let ray = (y * SUPERSAMPLE + sy) * camera.rays_per_side + x * SUPERSAMPLE + sx; + let Some(&Some((texel, n))) = camera.samples.get(ray) else { continue }; mask += values.get(texel).copied().unwrap_or(0.0); normal += n; @@ -94,38 +88,20 @@ impl MaskPreview { } } -/// What each pixel of a `size²` orthographic view of the shape sees: the distinct texels hit, and -/// per pixel (row-major) its sample. -fn camera_samples(session: &Session, size: usize) -> (Vec<(u32, u32)>, Vec) { - let (lo, hi) = session.mesh.bounds(); - let center = (lo + hi) * 0.5; - let radius = session.mesh.positions.iter().map(|p| p.distance(center)).fold(0.0f32, f32::max); - let pitch = CAMERA_PITCH_DEG.to_radians(); - let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians()); - let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos()); - let right = turn * Vec3::X; - let up = right.cross(forward); - let max_texel = TEXTURE_PX - 1; +/// The camera view for `size²` previews of `session`'s shape, traced on first use (moved to the end +/// of `cameras`); past [`CAMERAS_KEPT`] the least recently used size goes. +fn camera_for<'a>(cameras: &'a mut Vec, session: &Session, size: usize) -> Option<&'a MaskPreviewCamera> { + let rays_per_side = size * SUPERSAMPLE; + let camera = match cameras.iter().position(|c| c.rays_per_side == rays_per_side) { + Some(i) => cameras.remove(i), + None => MaskPreviewCamera::new(session, TEXTURE_PX, rays_per_side), + }; + if cameras.len() >= CAMERAS_KEPT { + cameras.remove(0); + } - let mut texels = Vec::new(); - let mut index_of = std::collections::HashMap::new(); - let samples = (0..size * size) - .map(|i| { - let ndc = Vec2::new(((i % size) as f32 + 0.5) / size as f32 * 2.0 - 1.0, 1.0 - ((i / size) as f32 + 0.5) / size as f32 * 2.0); - // Start well outside the shape so every ray enters it from the front - let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0; - let hit = session.bvh.closest(origin, forward, radius * 8.0)?; - let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?; - let texel = (((surface.uv.x * TEXTURE_PX as f32) as u32).min(max_texel), ((surface.uv.y * TEXTURE_PX as f32) as u32).min(max_texel)); - let index = *index_of.entry(texel).or_insert_with(|| { - texels.push(texel); - texels.len() - 1 - }); - let n = surface.nrm; - Some((index, Vec3::new(n.dot(right), n.dot(up), -n.dot(forward)))) - }) - .collect(); - (texels, samples) + cameras.push(camera); + cameras.last() } #[cfg(test)] @@ -139,11 +115,11 @@ mod tests { } #[test] - fn smart_mask_previews_are_in_range_and_tell_edges_from_cavities() { + fn smart_mask_previews_are_in_range_tell_edges_from_cavities_and_render_at_any_size() { let size = 24; - let mut preview = MaskPreview::new(size).unwrap(); + let mut preview = MaskPreview::new().unwrap(); for sm in crate::smart_masks::SMART_MASKS { - let px = preview.render(sm.id).unwrap_or_else(|| panic!("{}", sm.id)); + let px = preview.render(sm.id, size).unwrap_or_else(|| panic!("{}", sm.id)); assert_eq!(px.len(), size * size, "{}", sm.id); assert!(px[0].is_none(), "{}: the corners are outside the shape", sm.id); let seen: Vec<&MaskPreviewPixel> = px.iter().flatten().collect(); @@ -154,10 +130,18 @@ mod tests { } } - let (edges, cavities) = (preview.render("edges_sharp").unwrap(), preview.render("dirt_cavities").unwrap()); + let (edges, cavities) = (preview.render("edges_sharp", size).unwrap(), preview.render("dirt_cavities", size).unwrap()); let shows = |px: &[Option]| px.iter().flatten().any(|p| p.mask > 0.5); assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape"); assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); - assert!(preview.render("nope").is_none()); + assert!(preview.render("nope", size).is_none()); + + // The same bake renders other sizes, showing the same mask + let big = preview.render("edges_sharp", size * 3).unwrap(); + let mean = |px: &[Option]| px.iter().flatten().map(|p| p.mask).sum::() / px.iter().flatten().count().max(1) as f32; + assert_eq!(big.len(), size * size * 9); + assert!((mean(&big) - mean(&edges)).abs() < 0.05, "{} vs {}", mean(&big), mean(&edges)); + preview.render("edges_sharp", size * 2).unwrap(); + assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera"); } } diff --git a/crates/engine/src/mask_preview_camera.rs b/crates/engine/src/mask_preview_camera.rs new file mode 100644 index 00000000..9787accb --- /dev/null +++ b/crates/engine/src/mask_preview_camera.rs @@ -0,0 +1,64 @@ +//! The fixed camera of the smart mask previews (see [`crate::mask_preview::MaskPreview`]) at one +//! image size. + +use std::collections::HashMap; + +use texturecraft_geom::glam::{Quat, Vec2, Vec3}; +use texturecraft_geom::surface_at; + +use crate::Session; + +/// Camera: looking down by this angle, turned to show the front, left and top panels. +const CAMERA_PITCH_DEG: f32 = 35.0; +const CAMERA_YAW_DEG: f32 = -34.4; + +/// What one camera ray sees: the index of its texel in [`MaskPreviewCamera::texels`] and the +/// view-space normal there (None where the ray misses). +pub(crate) type CameraSample = Option<(usize, Vec3)>; + +/// What each ray of a square orthographic view of the preview shape sees. +pub(crate) struct MaskPreviewCamera { + /// Rays along each side of the view. + pub rays_per_side: usize, + /// The texels (x, y) the camera sees, each once. + pub texels: Vec<(u32, u32)>, + /// Per ray, row-major `rays_per_side²`. + pub samples: Vec, +} + +impl MaskPreviewCamera { + /// Trace `rays_per_side²` rays at the shape of `session`, whose textures are `texture_px` + /// square. + pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> MaskPreviewCamera { + let (lo, hi) = session.mesh.bounds(); + let center = (lo + hi) * 0.5; + let radius = session.mesh.positions.iter().map(|p| p.distance(center)).fold(0.0f32, f32::max); + let pitch = CAMERA_PITCH_DEG.to_radians(); + let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians()); + let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos()); + let right = turn * Vec3::X; + let up = right.cross(forward); + let max_texel = texture_px.saturating_sub(1); + + let mut texels = Vec::new(); + let mut index_of = HashMap::new(); + let samples = (0..rays_per_side * rays_per_side) + .map(|i| { + let side = rays_per_side as f32; + let ndc = Vec2::new(((i % rays_per_side) as f32 + 0.5) / side * 2.0 - 1.0, 1.0 - ((i / rays_per_side) as f32 + 0.5) / side * 2.0); + // Start well outside the shape so every ray enters it from the front + let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0; + let hit = session.bvh.closest(origin, forward, radius * 8.0)?; + let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?; + let texel = (((surface.uv.x * texture_px as f32) as u32).min(max_texel), ((surface.uv.y * texture_px as f32) as u32).min(max_texel)); + let index = *index_of.entry(texel).or_insert_with(|| { + texels.push(texel); + texels.len() - 1 + }); + let n = surface.nrm; + Some((index, Vec3::new(n.dot(right), n.dot(up), -n.dot(forward)))) + }) + .collect(); + MaskPreviewCamera { rays_per_side, texels, samples } + } +} diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 1dc33631..8882b6d8 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -3,6 +3,7 @@ //! library filters. Cheap enough for lazily rendered thumbnails. Smart masks have their own baked //! preview ([`crate::mask_preview`]). +use rayon::prelude::*; use texturecraft_compose::pattern::{Coords, procedural, world_noise}; use texturecraft_core::{ Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, @@ -95,28 +96,34 @@ const CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel:: /// Preview of built-in material `id` (None for an unknown id). pub fn material(id: &str, size: usize) -> Option>> { - let mut p = Project::new("preview", ""); - let layers = build(&mut Builder { p: &mut p, channels: CHANNELS.to_vec() }, id).ok()?; - Some( - sphere_normals(size) - .map(|n| { - let c = coords(n?); - let mut acc = CHANNELS.map(Channel::default_value); - for l in layers.iter().filter(|l| l.visible) { - let LayerKind::Fill(f) = &l.kind else { continue }; - let w = l.mask.as_ref().map_or(1.0, |m| mask(m, &c)); - for (a, ch) in acc.iter_mut().zip(CHANNELS) { - if let (Some(b), Some(v)) = (l.blend(ch), f.sources.get(&ch).and_then(|s| source(s, &f.projection, &c))) { - let t = w * b.opacity.clamp(0.0, 1.0); - *a = [0, 1, 2].map(|k| a[k] + (v[k] - a[k]) * t); - } + let mut project = Project::new("preview", ""); + let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, id).ok()?; + + // Pixels evaluate independently and big previews take long on one core + let normals: Vec<_> = sphere_normals(size).collect(); + let samples = normals + .into_par_iter() + .map(|normal| { + let at = coords(normal?); + let mut values = CHANNELS.map(Channel::default_value); + for layer in layers.iter().filter(|l| l.visible) { + let LayerKind::Fill(fill) = &layer.kind else { continue }; + + let coverage = layer.mask.as_ref().map_or(1.0, |m| mask(m, &at)); + for (value, channel) in values.iter_mut().zip(CHANNELS) { + let layer_value = fill.sources.get(&channel).and_then(|s| source(s, &fill.projection, &at)); + if let (Some(blend), Some(layer_value)) = (layer.blend(channel), layer_value) { + let weight = coverage * blend.opacity.clamp(0.0, 1.0); + *value = [0, 1, 2].map(|k| value[k] + (layer_value[k] - value[k]) * weight); } } - let [base, metal, rough, height] = acc; - Some(Sample { base, metallic: metal[0], roughness: rough[0], height: height[0] }) - }) - .collect(), - ) + } + + let [base, metal, rough, height] = values; + Some(Sample { base, metallic: metal[0], roughness: rough[0], height: height[0] }) + }) + .collect(); + Some(samples) } /// `f` with its reach in texels multiplied by `k` (previews show at a fraction of 2K). diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 294e8964..6146d6d5 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "شدة الانسداد المحيطي (AO)"), ("About TextureCraft", "حول TextureCraft"), ("About TextureCraft...", "حول TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "إضافة طبقة تعبئة بهذه الصورة (أو اسحبها إلى العرض ثلاثي الأبعاد لوضعها كملصق)", - ), - ("Add a fill layer using this pattern", "إضافة طبقة تعبئة بهذا النمط"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "إضافة طبقة تعبئة بهذه المادة فوق الطبقة المحددة (أو اسحبها إلى مكدس الطبقات)", - ), ("Add an anchor point to a layer below to use its stack as a mask.", "أضف نقطة ارتكاز إلى طبقة سفلية لاستخدام مكدسها كقناع."), ("Add anchor point", "إضافة نقطة ارتكاز"), ("Add as decal (view center)", "إضافة كملصق (مركز العرض)"), @@ -51,20 +42,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "إضافة رسم"), ("Add paint layer", "إضافة طبقة رسم"), ("Add smart material from the shelf", "إضافة مادة ذكية من الرف"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "إضافة مجلد المادة الذكية فوق الطبقة المحددة (أو اسحبه إلى مكدس الطبقات)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "إضافة هذه اللمسة النهائية إلى خشونة وارتفاع الطبقة المحددة (أو اسحبها إلى طبقة)", - ), ("Add to the layer content", "إضافة إلى محتوى الطبقة"), ("Add to the mask", "إضافة إلى القناع"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "إضافة إلى محتوى الطبقة المحددة، أو إلى قناعها عند تحديد القناع (أو اسحبها إلى طبقة)", - ), ("Add white mask", "إضافة قناع أبيض"), ("Adjustments", "تعديلات"), ( @@ -663,7 +642,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "التصيير، بتتبع المسار"), ("Replace", "استبدال"), ("Replace Color", "استبدال اللون"), - ("Replace the selected layer's mask with this smart mask (or drag it onto a layer)", "استبدال قناع الطبقة المحددة بهذا القناع الذكي (أو اسحبه إلى طبقة)"), ("Replacement color", "لون الاستبدال"), ("Report a bug...", "الإبلاغ عن خطأ..."), ("Rescan the library folder", "إعادة فحص مجلد المكتبة"), @@ -824,7 +802,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "تراجع"), ("Uniform value", "قيمة موحدة"), ("Use an equirectangular .hdr or .exr image as the environment", "استخدم صورة .hdr أو .exr متساوية المستطيلات كبيئة"), - ("Use as the brush alpha (or drag it onto the viewport or brush properties)", "استخدم كألفا للفرشاة (أو اسحبها إلى منفذ العرض أو خصائص الفرشاة)"), ("Use the control channel or `texturecraft-cli render` for screenshots", "استخدم قناة التحكم أو الأمر `texturecraft-cli render` لالتقاط لقطات الشاشة"), ("Value", "القيمة"), ("Version {version}", "الإصدار {version}"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 3155e6ce..5ceb5dd5 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "AO-Intensität"), ("About TextureCraft", "Über TextureCraft"), ("About TextureCraft...", "Über TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Füllebene mit diesem Bild hinzufügen (oder in die 3D-Ansicht ziehen, um es als Decal zu platzieren)", - ), - ("Add a fill layer using this pattern", "Füllebene mit diesem Muster hinzufügen"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Füllebene mit diesem Material über der ausgewählten Ebene hinzufügen (oder in den Ebenenstapel ziehen)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "Einer darunterliegenden Ebene einen Ankerpunkt hinzufügen, um ihren Stapel als Maske zu verwenden.", @@ -54,20 +45,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Malen hinzufügen"), ("Add paint layer", "Malebene hinzufügen"), ("Add smart material from the shelf", "Smart-Material aus der Ablage hinzufügen"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Smart-Material-Ordner über der ausgewählten Ebene hinzufügen (oder in den Ebenenstapel ziehen)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Diese Oberfläche zu Rauheit und Höhe der ausgewählten Ebene hinzufügen (oder auf eine Ebene ziehen)", - ), ("Add to the layer content", "Zum Ebeneninhalt hinzufügen"), ("Add to the mask", "Zur Maske hinzufügen"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Zum Inhalt der ausgewählten Ebene hinzufügen oder zu ihrer Maske, wenn die Maske ausgewählt ist (oder auf eine Ebene ziehen)", - ), ("Add white mask", "Weiße Maske hinzufügen"), ("Adjustments", "Korrekturen"), ( @@ -702,10 +681,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Rendering, Path Tracing"), ("Replace", "Ersetzen"), ("Replace Color", "Farbe ersetzen"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Maske der ausgewählten Ebene durch diese Smart-Maske ersetzen (oder auf eine Ebene ziehen)", - ), ("Replacement color", "Ersatzfarbe"), ("Report a bug...", "Fehler melden..."), ("Rescan the library folder", "Bibliotheksordner neu einlesen"), @@ -866,10 +841,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "Rückgängig"), ("Uniform value", "Einheitlicher Wert"), ("Use an equirectangular .hdr or .exr image as the environment", "Ein equirektangulares .hdr- oder .exr-Bild als Umgebung verwenden"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Als Pinsel-Alpha verwenden (oder in das Ansichtsfenster oder die Pinseleigenschaften ziehen)", - ), ("Use the control channel or `texturecraft-cli render` for screenshots", "Für Screenshots den Steuerkanal oder `texturecraft-cli render` verwenden"), ("Value", "Wert"), ("Version {version}", "Version {version}"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 7ba164a9..f9f42e49 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "Intensidad de AO"), ("About TextureCraft", "Acerca de TextureCraft"), ("About TextureCraft...", "Acerca de TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Añadir una capa de relleno con esta imagen (o arrastrarla a la vista 3D para colocarla como calcomanía)", - ), - ("Add a fill layer using this pattern", "Añadir una capa de relleno con este patrón"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Añadir una capa de relleno con este material sobre la capa seleccionada (o arrastrarlo a la pila de capas)", - ), ("Add an anchor point to a layer below to use its stack as a mask.", "Añade un punto de anclaje a una capa inferior para usar su pila como máscara."), ("Add anchor point", "Añadir punto de anclaje"), ("Add as decal (view center)", "Añadir como calcomanía (centro de la vista)"), @@ -51,20 +42,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Añadir pintura"), ("Add paint layer", "Añadir capa de pintura"), ("Add smart material from the shelf", "Añadir material inteligente desde la biblioteca"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Añadir la carpeta del material inteligente sobre la capa seleccionada (o arrastrarla a la pila de capas)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Añadir este acabado a la rugosidad y la altura de la capa seleccionada (o arrastrarlo a una capa)", - ), ("Add to the layer content", "Añadir al contenido de la capa"), ("Add to the mask", "Añadir a la máscara"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Añadir al contenido de la capa seleccionada, o a su máscara si está seleccionada (o arrastrarlo a una capa)", - ), ("Add white mask", "Añadir máscara blanca"), ("Adjustments", "Ajustes de imagen"), ( @@ -690,10 +669,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Renderizado con trazado de trayectorias"), ("Replace", "Reemplazar"), ("Replace Color", "Reemplazar color"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Reemplazar la máscara de la capa seleccionada por esta máscara inteligente (o arrastrarla a una capa)", - ), ("Replacement color", "Color de reemplazo"), ("Report a bug...", "Informar de un error..."), ("Rescan the library folder", "Volver a examinar la carpeta de la biblioteca"), @@ -854,10 +829,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "Deshacer"), ("Uniform value", "Valor uniforme"), ("Use an equirectangular .hdr or .exr image as the environment", "Usar una imagen equirrectangular .hdr o .exr como entorno"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Usar como alfa del pincel (o arrastrarlo a la ventana gráfica o a las propiedades del pincel)", - ), ("Use the control channel or `texturecraft-cli render` for screenshots", "Usa el canal de control o `texturecraft-cli render` para las capturas"), ("Value", "Valor"), ("Version {version}", "Versión {version}"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 034d78b5..57c7194f 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -25,15 +25,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "Intensité de l'AO"), ("About TextureCraft", "À propos de TextureCraft"), ("About TextureCraft...", "À propos de TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Ajouter un calque de remplissage avec cette image (ou la glisser sur la vue 3D pour la placer comme décalque)", - ), - ("Add a fill layer using this pattern", "Ajouter un calque de remplissage avec ce motif"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Ajouter un calque de remplissage avec ce matériau au-dessus du calque sélectionné (ou le glisser dans la pile de calques)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "Ajoutez un point d'ancrage à un calque inférieur pour utiliser sa pile comme masque.", @@ -57,20 +48,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Ajouter de la peinture"), ("Add paint layer", "Ajouter un calque de peinture"), ("Add smart material from the shelf", "Ajouter un matériau intelligent depuis la bibliothèque"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Ajouter le dossier du matériau intelligent au-dessus du calque sélectionné (ou le glisser dans la pile de calques)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Ajouter cette finition à la rugosité et à la hauteur du calque sélectionné (ou la glisser sur un calque)", - ), ("Add to the layer content", "Ajouter au contenu du calque"), ("Add to the mask", "Ajouter au masque"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Ajouter au contenu du calque sélectionné, ou à son masque si le masque est sélectionné (ou le glisser sur un calque)", - ), ("Add white mask", "Ajouter un masque blanc"), ("Adjustments", "Réglages"), ( @@ -705,10 +684,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Rendu, tracé de chemins"), ("Replace", "Remplacer"), ("Replace Color", "Remplacer la couleur"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Remplacer le masque du calque sélectionné par ce masque intelligent (ou le glisser sur un calque)", - ), ("Replacement color", "Couleur de remplacement"), ("Report a bug...", "Signaler un bug..."), ("Rescan the library folder", "Réanalyser le dossier de la bibliothèque"), @@ -872,10 +847,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "Annuler"), ("Uniform value", "Valeur uniforme"), ("Use an equirectangular .hdr or .exr image as the environment", "Utiliser une image équirectangulaire .hdr ou .exr comme environnement"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Utiliser comme alpha du pinceau (ou le glisser sur la fenêtre d'affichage ou les propriétés du pinceau)", - ), ( "Use the control channel or `texturecraft-cli render` for screenshots", "Utilisez le canal de contrôle ou `texturecraft-cli render` pour les captures d'écran", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 07ce31ea..34abc28a 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "Intensità AO"), ("About TextureCraft", "Informazioni su TextureCraft"), ("About TextureCraft...", "Informazioni su TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Aggiungi un livello di riempimento con questa immagine (o trascinala nella vista 3D per posizionarla come decal)", - ), - ("Add a fill layer using this pattern", "Aggiungi un livello di riempimento con questo motivo"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Aggiungi un livello di riempimento con questo materiale sopra il livello selezionato (o trascinalo nella pila dei livelli)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "Aggiungi un punto di ancoraggio a un livello sottostante per usarne la pila come maschera.", @@ -54,20 +45,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Aggiungi pittura"), ("Add paint layer", "Aggiungi livello di pittura"), ("Add smart material from the shelf", "Aggiungi un materiale intelligente dalla libreria"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Aggiungi la cartella del materiale intelligente sopra il livello selezionato (o trascinala nella pila dei livelli)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Aggiungi questa finitura alla rugosità e all'altezza del livello selezionato (o trascinala su un livello)", - ), ("Add to the layer content", "Aggiungi al contenuto del livello"), ("Add to the mask", "Aggiungi alla maschera"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Aggiungi al contenuto del livello selezionato, o alla sua maschera se è selezionata (o trascinalo su un livello)", - ), ("Add white mask", "Aggiungi maschera bianca"), ("Adjustments", "Regolazioni"), ( @@ -699,10 +678,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Rendering, path tracing"), ("Replace", "Sostituisci"), ("Replace Color", "Sostituisci colore"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Sostituisci la maschera del livello selezionato con questa maschera intelligente (o trascinala su un livello)", - ), ("Replacement color", "Colore sostitutivo"), ("Report a bug...", "Segnala un bug..."), ("Rescan the library folder", "Ripeti la scansione della cartella della libreria"), @@ -863,10 +838,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "Annulla"), ("Uniform value", "Valore uniforme"), ("Use an equirectangular .hdr or .exr image as the environment", "Usa un'immagine equirettangolare .hdr o .exr come ambiente"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Usa come alpha del pennello (o trascinala nella viewport o nelle proprietà del pennello)", - ), ("Use the control channel or `texturecraft-cli render` for screenshots", "Usa il canale di controllo o `texturecraft-cli render` per gli screenshot"), ("Value", "Valore"), ("Version {version}", "Versione {version}"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index ac768443..2c91d7ce 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -25,15 +25,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "AO強度"), ("About TextureCraft", "TextureCraftについて"), ("About TextureCraft...", "TextureCraftについて..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "この画像で塗りつぶしレイヤーを追加 (3Dビューにドラッグするとデカールとして配置)", - ), - ("Add a fill layer using this pattern", "このパターンで塗りつぶしレイヤーを追加"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "このマテリアルの塗りつぶしレイヤーを選択中のレイヤーの上に追加 (レイヤースタックへのドラッグも可)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "下のレイヤーにアンカーポイントを追加すると、そのスタックをマスクとして使用できます。", @@ -57,20 +48,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "ペイントを追加"), ("Add paint layer", "ペイントレイヤーを追加"), ("Add smart material from the shelf", "シェルフからスマートマテリアルを追加"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "スマートマテリアルのフォルダーを選択中のレイヤーの上に追加 (レイヤースタックへのドラッグも可)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "この仕上げを選択中のレイヤーのラフネスとハイトに追加 (レイヤーへのドラッグも可)", - ), ("Add to the layer content", "レイヤーのコンテンツに追加"), ("Add to the mask", "マスクに追加"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "選択中のレイヤーのコンテンツ (マスク選択時はマスク) に追加 (レイヤーへのドラッグも可)", - ), ("Add white mask", "白マスクを追加"), ("Adjustments", "色調補正"), ( @@ -681,10 +660,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "パストレースによるレンダリング"), ("Replace", "置換"), ("Replace Color", "色の置き換え"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "選択中のレイヤーのマスクをこのスマートマスクで置換 (レイヤーへのドラッグも可)", - ), ("Replacement color", "置き換え後の色"), ("Report a bug...", "バグを報告..."), ("Rescan the library folder", "ライブラリフォルダーを再スキャン"), @@ -845,10 +820,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "元に戻す"), ("Uniform value", "均一値"), ("Use an equirectangular .hdr or .exr image as the environment", "正距円筒図法の .hdr または .exr 画像を環境として使用"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "ブラシのアルファとして使用 (ビューポートやブラシプロパティへのドラッグも可)", - ), ( "Use the control channel or `texturecraft-cli render` for screenshots", "スクリーンショットにはコントロールチャンネルまたは `texturecraft-cli render` を使用", diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 8fa260be..58a80560 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -25,15 +25,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "AO 강도"), ("About TextureCraft", "TextureCraft 정보"), ("About TextureCraft...", "TextureCraft 정보..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "이 이미지로 채우기 레이어를 추가합니다 (또는 3D 뷰로 드래그하여 데칼로 배치)", - ), - ("Add a fill layer using this pattern", "이 패턴으로 채우기 레이어를 추가합니다"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "선택한 레이어 위에 이 머티리얼로 채우기 레이어를 추가합니다 (또는 레이어 스택으로 드래그)", - ), ("Add an anchor point to a layer below to use its stack as a mask.", "아래 레이어에 앵커 포인트를 추가하면 해당 스택을 마스크로 사용할 수 있습니다."), ("Add anchor point", "앵커 포인트 추가"), ("Add as decal (view center)", "데칼로 추가 (뷰 중앙)"), @@ -54,20 +45,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "페인트 추가"), ("Add paint layer", "페인트 레이어 추가"), ("Add smart material from the shelf", "셸프에서 스마트 머티리얼 추가"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "선택한 레이어 위에 스마트 머티리얼 폴더를 추가합니다 (또는 레이어 스택으로 드래그)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "선택한 레이어의 러프니스와 높이에 이 마감을 추가합니다 (또는 레이어로 드래그)", - ), ("Add to the layer content", "레이어 콘텐츠에 추가"), ("Add to the mask", "마스크에 추가"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "선택한 레이어의 콘텐츠에 추가하거나, 마스크가 선택된 경우 마스크에 추가합니다 (또는 레이어로 드래그)", - ), ("Add white mask", "흰색 마스크 추가"), ("Adjustments", "조정"), ( @@ -672,10 +651,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "렌더링, 패스 트레이싱"), ("Replace", "대체"), ("Replace Color", "색상 바꾸기"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "선택한 레이어의 마스크를 이 스마트 마스크로 대체합니다 (또는 레이어로 드래그)", - ), ("Replacement color", "대체 색상"), ("Report a bug...", "버그 신고..."), ("Rescan the library folder", "라이브러리 폴더를 다시 검색합니다"), @@ -836,7 +811,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "실행 취소"), ("Uniform value", "균일 값"), ("Use an equirectangular .hdr or .exr image as the environment", "등장방형 .hdr 또는 .exr 이미지를 환경으로 사용합니다"), - ("Use as the brush alpha (or drag it onto the viewport or brush properties)", "브러시 알파로 사용합니다 (또는 뷰포트나 브러시 속성으로 드래그)"), ("Use the control channel or `texturecraft-cli render` for screenshots", "스크린샷은 제어 채널 또는 `texturecraft-cli render`를 사용하세요"), ("Value", "값"), ("Version {version}", "버전 {version}"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 203a94de..47e49c9c 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "Intensidade de AO"), ("About TextureCraft", "Sobre o TextureCraft"), ("About TextureCraft...", "Sobre o TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Adicionar uma camada de preenchimento com esta imagem (ou arraste-a para a vista 3D para posicioná-la como decalque)", - ), - ("Add a fill layer using this pattern", "Adicionar uma camada de preenchimento com este padrão"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Adicionar uma camada de preenchimento com este material acima da camada selecionada (ou arraste-o para a pilha de camadas)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "Adicione um ponto de ancoragem a uma camada abaixo para usar sua pilha como máscara.", @@ -54,20 +45,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Adicionar pintura"), ("Add paint layer", "Adicionar camada de pintura"), ("Add smart material from the shelf", "Adicionar material inteligente da prateleira"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Adicionar a pasta do material inteligente acima da camada selecionada (ou arraste-a para a pilha de camadas)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Adicionar este acabamento à rugosidade e à altura da camada selecionada (ou arraste-o para uma camada)", - ), ("Add to the layer content", "Adicionar ao conteúdo da camada"), ("Add to the mask", "Adicionar à máscara"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Adicionar ao conteúdo da camada selecionada, ou à sua máscara quando a máscara estiver selecionada (ou arraste-o para uma camada)", - ), ("Add white mask", "Adicionar máscara branca"), ("Adjustments", "Ajustes"), ( @@ -687,10 +666,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Renderização com path tracing"), ("Replace", "Substituir"), ("Replace Color", "Substituir cor"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Substituir a máscara da camada selecionada por esta máscara inteligente (ou arraste-a para uma camada)", - ), ("Replacement color", "Cor de substituição"), ("Report a bug...", "Relatar um bug..."), ("Rescan the library folder", "Reexaminar a pasta da biblioteca"), @@ -851,10 +826,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "Desfazer"), ("Uniform value", "Valor uniforme"), ("Use an equirectangular .hdr or .exr image as the environment", "Usar uma imagem equirretangular .hdr ou .exr como ambiente"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Usar como alpha do pincel (ou arraste-o para a viewport ou para as propriedades do pincel)", - ), ("Use the control channel or `texturecraft-cli render` for screenshots", "Use o canal de controle ou `texturecraft-cli render` para capturas de tela"), ("Value", "Valor"), ("Version {version}", "Versão {version}"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index d651ba67..8b66aead 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -19,12 +19,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "AO 强度"), ("About TextureCraft", "关于 TextureCraft"), ("About TextureCraft...", "关于 TextureCraft..."), - ("Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", "使用此图像添加填充图层(或将其拖到 3D 视图中作为贴花放置)"), - ("Add a fill layer using this pattern", "使用此图案添加填充图层"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "在所选图层上方添加使用此材质的填充图层(或将其拖入图层堆栈)", - ), ("Add an anchor point to a layer below to use its stack as a mask.", "在下方图层上添加锚点,以将其堆栈用作遮罩。"), ("Add anchor point", "添加锚点"), ("Add as decal (view center)", "添加为贴花(视图中心)"), @@ -45,14 +39,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "添加绘画"), ("Add paint layer", "添加绘画图层"), ("Add smart material from the shelf", "从资产架添加智能材质"), - ("Add the smart material folder above the selected layer (or drag it into the layer stack)", "在所选图层上方添加智能材质文件夹(或将其拖入图层堆栈)"), - ("Add this finish to the selected layer's roughness and height (or drag it onto a layer)", "将此表面处理添加到所选图层的粗糙度和高度(或将其拖到图层上)"), ("Add to the layer content", "添加到图层内容"), ("Add to the mask", "添加到遮罩"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "添加到所选图层的内容,选中遮罩时则添加到遮罩(或将其拖到图层上)", - ), ("Add white mask", "添加白色遮罩"), ("Adjustments", "调整"), ("Aligned: the offset set by the first stroke is kept. V + click sets a new source.", "对齐:保留第一笔设定的偏移。按住 V 并单击可设置新的源。"), @@ -624,7 +612,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "渲染,路径追踪"), ("Replace", "替换"), ("Replace Color", "替换颜色"), - ("Replace the selected layer's mask with this smart mask (or drag it onto a layer)", "用此智能遮罩替换所选图层的遮罩(或将其拖到图层上)"), ("Replacement color", "替换后的颜色"), ("Report a bug...", "报告错误..."), ("Rescan the library folder", "重新扫描库文件夹"), @@ -785,7 +772,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "撤销"), ("Uniform value", "统一值"), ("Use an equirectangular .hdr or .exr image as the environment", "使用等距柱状投影的 .hdr 或 .exr 图像作为环境"), - ("Use as the brush alpha (or drag it onto the viewport or brush properties)", "用作笔刷 Alpha(或将其拖到视口或笔刷属性上)"), ("Use the control channel or `texturecraft-cli render` for screenshots", "截图请使用控制通道或 `texturecraft-cli render`"), ("Value", "值"), ("Version {version}", "版本 {version}"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index df2d1c7a..59c6f40c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,12 +16,17 @@ pub mod fonts; pub mod gpu; pub mod i18n; pub mod keymap; -mod mask_previews; +mod mask_preview_image; +mod mask_shape; pub mod menus; pub mod parity; +mod preview_image; +mod preview_request; +mod preview_worker; pub mod profile; pub mod render_mode; pub mod shelf; +pub mod shelf_preview; pub mod state; pub mod theme; pub mod thumbs; @@ -31,6 +36,7 @@ pub mod viewport; pub mod web_files; pub mod widgets; pub mod windows; +mod worker_preview; use std::sync::Arc; use std::sync::atomic::Ordering; diff --git a/crates/ui-egui/src/mask_preview_image.rs b/crates/ui-egui/src/mask_preview_image.rs new file mode 100644 index 00000000..49fe70f7 --- /dev/null +++ b/crates/ui-egui/src/mask_preview_image.rs @@ -0,0 +1,44 @@ +//! Shading of the smart mask previews: the mask as white over a near-black surface. + +use egui::{Color32, ColorImage}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::mask_preview::MaskPreviewPixel; +use texturecraft_engine::texel::linear_to_srgb; + +/// View-space directions of the key light (upper left) and a weaker fill (right), and how much +/// each lights the surface. +const KEY: [f32; 3] = [-0.72, 0.62, 0.3]; +const FILL: [f32; 3] = [0.7, -0.1, 0.7]; +const AMBIENT: f32 = 0.1; +const KEY_STRENGTH: f32 = 0.8; +const FILL_STRENGTH: f32 = 0.35; +/// Where the mask is empty: a near-black albedo with a faint sheen of the key light, so the +/// shape reads without looking glossy. +const UNMASKED_ALBEDO: f32 = 0.006; +const SHEEN: f32 = 0.1; +const SHEEN_EXPONENT: f32 = 40.0; +/// Where the mask is full: white, darkened at most this much where unlit. +const WHITE_SHADING: f32 = 0.2; + +/// A smart mask preview (sRGB, transparent outside the shape) from preview pixels (row-major +/// `size²`): the mask as white over a near-black surface lit softly from the upper left. No +/// environment reflections. +pub fn mask_preview_image(size: usize, pixels: &[Option]) -> ColorImage { + let key = Vec3::from(KEY).normalize(); + let fill = Vec3::from(FILL).normalize(); + let half = (key + Vec3::Z).normalize(); + let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); + + for (out, p) in img.pixels.iter_mut().zip(pixels) { + let Some(p) = p else { continue }; + + let n = p.normal; + let shading = AMBIENT + KEY_STRENGTH * n.dot(key).max(0.0) + FILL_STRENGTH * n.dot(fill).max(0.0); + let unmasked = UNMASKED_ALBEDO * shading + SHEEN * n.dot(half).max(0.0).powf(SHEEN_EXPONENT); + let masked = 1.0 - WHITE_SHADING * (1.0 - shading.min(1.0)); + let linear = unmasked + (masked - unmasked) * p.mask.clamp(0.0, 1.0); + let gray = (linear_to_srgb(linear.clamp(0.0, 1.0)) * 255.0 + 0.5) as u8; + *out = Color32::from_rgba_unmultiplied(gray, gray, gray, (p.coverage.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + } + img +} diff --git a/crates/ui-egui/src/mask_previews.rs b/crates/ui-egui/src/mask_previews.rs deleted file mode 100644 index fc6018e4..00000000 --- a/crates/ui-egui/src/mask_previews.rs +++ /dev/null @@ -1,104 +0,0 @@ -//! Smart mask shelf thumbnails: every smart mask on the baked preview shape, rendered together on -//! a worker the first time the shelf asks for one (baking the shape takes about two seconds on -//! the CPU; on the web the work runs inline). - -use std::sync::mpsc::{Receiver, TryRecvError}; -use std::time::Duration; - -use egui::{Color32, ColorImage}; -use texturecraft_engine::geom::glam::Vec3; -use texturecraft_engine::mask_preview::{MaskPreview, MaskPreviewPixel}; -use texturecraft_engine::smart_masks::SMART_MASKS; -use texturecraft_engine::texel::linear_to_srgb; - -/// View-space directions of the key light (upper left) and a weaker fill (right), and how much -/// each lights the surface. -const KEY: [f32; 3] = [-0.72, 0.62, 0.3]; -const FILL: [f32; 3] = [0.7, -0.1, 0.7]; -const AMBIENT: f32 = 0.1; -const KEY_STRENGTH: f32 = 0.8; -const FILL_STRENGTH: f32 = 0.35; -/// Where the mask is empty: a near-black albedo with a faint sheen of the key light, so the -/// shape reads without looking glossy. -const UNMASKED_ALBEDO: f32 = 0.006; -const SHEEN: f32 = 0.1; -const SHEEN_EXPONENT: f32 = 40.0; -/// Where the mask is full: white, darkened at most this much where unlit. -const WHITE_SHADING: f32 = 0.2; -/// How often the shelf checks for the thumbnails while they render. -const POLL: Duration = Duration::from_millis(100); - -/// Smart mask thumbnails by id, as the worker sends them. -type Thumbnails = Vec<(&'static str, ColorImage)>; - -/// Where the smart mask thumbnails are. -#[derive(Default)] -pub enum MaskPreviews { - #[default] - NotStarted, - Rendering(Receiver), - /// Handed out (or the worker failed; the tiles keep their placeholder). - Finished, -} - -impl MaskPreviews { - /// Start rendering `size²` thumbnails on the first call; the finished thumbnails on the call - /// that finds them done (None before and after). - pub fn poll(&mut self, ctx: &egui::Context, size: usize) -> Option { - if matches!(self, MaskPreviews::NotStarted) { - *self = MaskPreviews::Rendering(crate::spawn_worker("texturecraft-mask-previews", move || render(size))); - } - let MaskPreviews::Rendering(rx) = self else { return None }; - - match rx.try_recv() { - Ok(thumbnails) => { - *self = MaskPreviews::Finished; - Some(thumbnails) - } - Err(TryRecvError::Empty) => { - ctx.request_repaint_after(POLL); - None - } - // The worker stopped without a result - Err(TryRecvError::Disconnected) => { - *self = MaskPreviews::Finished; - None - } - } - } -} - -/// Every smart mask's `size²` thumbnail (empty when the preview shape fails to bake). -fn render(size: usize) -> Thumbnails { - let mut preview = match MaskPreview::new(size) { - Ok(p) => p, - Err(e) => { - log::warn!("smart mask previews: {e}"); - return Vec::new(); - } - }; - SMART_MASKS.iter().filter_map(|m| Some((m.id, image(size, &preview.render(m.id)?)))).collect() -} - -/// A thumbnail (sRGB, transparent outside the shape) from preview pixels (row-major `size²`): -/// the mask as white over a near-black surface lit softly from the upper left. No environment -/// reflections. -fn image(size: usize, pixels: &[Option]) -> ColorImage { - let key = Vec3::from(KEY).normalize(); - let fill = Vec3::from(FILL).normalize(); - let half = (key + Vec3::Z).normalize(); - let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); - - for (out, p) in img.pixels.iter_mut().zip(pixels) { - let Some(p) = p else { continue }; - - let n = p.normal; - let shading = AMBIENT + KEY_STRENGTH * n.dot(key).max(0.0) + FILL_STRENGTH * n.dot(fill).max(0.0); - let unmasked = UNMASKED_ALBEDO * shading + SHEEN * n.dot(half).max(0.0).powf(SHEEN_EXPONENT); - let masked = 1.0 - WHITE_SHADING * (1.0 - shading.min(1.0)); - let linear = unmasked + (masked - unmasked) * p.mask.clamp(0.0, 1.0); - let gray = (linear_to_srgb(linear.clamp(0.0, 1.0)) * 255.0 + 0.5) as u8; - *out = Color32::from_rgba_unmultiplied(gray, gray, gray, (p.coverage.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); - } - img -} diff --git a/crates/ui-egui/src/mask_shape.rs b/crates/ui-egui/src/mask_shape.rs new file mode 100644 index 00000000..e34c5a7e --- /dev/null +++ b/crates/ui-egui/src/mask_shape.rs @@ -0,0 +1,33 @@ +//! The smart mask preview shape, baked on first use. + +use texturecraft_engine::mask_preview::MaskPreview; + +/// Whether the smart mask preview shape is baked. +#[derive(Default)] +pub enum MaskShape { + #[default] + NotBaked, + /// Boxed: the baked session is large and the enum sits in the worker for its whole life. + Baked(Box), + /// The bake failed; smart mask previews stay empty. + Failed, +} + +impl MaskShape { + /// The baked shape, baking it on the first call (about two seconds; None when it fails). + pub fn get(&mut self) -> Option<&mut MaskPreview> { + if matches!(self, MaskShape::NotBaked) { + *self = match MaskPreview::new() { + Ok(preview) => MaskShape::Baked(Box::new(preview)), + Err(e) => { + log::warn!("smart mask previews: {e}"); + MaskShape::Failed + } + }; + } + match self { + MaskShape::Baked(preview) => Some(preview), + MaskShape::NotBaked | MaskShape::Failed => None, + } + } +} diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs new file mode 100644 index 00000000..3f2321dc --- /dev/null +++ b/crates/ui-egui/src/preview_image.rs @@ -0,0 +1,168 @@ +//! The CPU renderers of the shelf previews at any size: shaded material spheres, procedural +//! swatches, alpha swatches, brush strokes and letterboxed images (no image assets). + +use egui::{Color32, ColorImage}; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::paint::alphas::{self, LibraryAlpha}; +use texturecraft_engine::paint::{BrushSettings, Shape}; +use texturecraft_engine::preview::{self, Sample}; +use texturecraft_engine::texel::linear_to_srgb; + +/// Pattern scale of the procedural swatches (repeats across the swatch). +const PROCEDURAL_SCALE: f32 = 3.0; +/// Samples per pixel along each axis of the alpha swatches. +const ALPHA_SUPERSAMPLE: usize = 2; + +/// Linear color of a surface with view-space normal `n` and these material values, lit by a key +/// light and a studio environment, seen along +Z. +pub fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { + let l = [0.45f32, 0.7, 0.55]; + let len = (l[0] * l[0] + l[1] * l[1] + l[2] * l[2]).sqrt(); + let l = l.map(|v| v / len); + let ndl = (n[0] * l[0] + n[1] * l[1] + n[2] * l[2]).max(0.0); + let ndv = n[2].max(0.0); + // View along +Z: half vector between light and view. + let h = [l[0], l[1], l[2] + 1.0]; + let hl = (h[0] * h[0] + h[1] * h[1] + h[2] * h[2]).sqrt(); + let ndh = ((n[0] * h[0] + n[1] * h[1] + n[2] * h[2]) / hl).max(0.0); + let shin = 2.0 / (rough * rough * rough * rough).max(1e-3) - 2.0; + let spec_amt = ndh.powf(shin.clamp(1.0, 4096.0)) * (shin + 2.0) / 8.0; + // A studio environment seen in the mirror direction: dark floor, bright sky, a horizon that + // blurs (and the whole environment averages out) as roughness grows. + let ry = 2.0 * ndv * n[1]; + let w = 0.06 + rough * 0.9; + let t = ((ry + w) / (2.0 * w)).clamp(0.0, 1.0); + let sharp = 0.04 + 0.03 * (ry + 1.0) + (0.2 + 0.55 * ry.max(0.0)) * t * t * (3.0 - 2.0 * t); + let env = sharp + (0.28 - sharp) * (rough * rough); + let fres = (1.0 - ndv).powi(5); + let sky = 0.35 + 0.25 * n[1]; + let mut out = [0.0; 3]; + for k in 0..3 { + let f0 = 0.04 + (base[k] - 0.04) * metal; + let f = f0 + ((1.0 - rough).max(f0) - f0) * fres; + let diffuse = base[k] * (1.0 - metal) * (ndl * 0.85 + sky * 0.5); + out[k] = diffuse * (1.0 - f) + f * env + f0 * spec_amt * ndl * 1.5; + } + out +} + +/// ACES filmic tone mapping of linear `x` (exposure folded in) to 0..=1. +pub fn aces(x: f32) -> f32 { + let v = x * 0.6; + ((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14)).clamp(0.0, 1.0) +} + +/// A shaded sphere image (sRGB, transparent outside) from per-pixel preview samples (row-major +/// `size²`, see [`preview::sphere_normals`]); height bumps the normals. +pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { + let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); + let r = (size as f32 * 0.5 - 1.0).max(0.5); + let h = |x: Option, y: Option| { + let (x, y) = (x.filter(|x| *x < size)?, y?); + samples.get(y.checked_mul(size)?.checked_add(x)?).copied().flatten().map(|s| s.height) + }; + for (i, n) in preview::sphere_normals(size).enumerate() { + let (Some(n), Some(Some(s))) = (n, samples.get(i)) else { continue }; + let (x, y) = (i % size, i / size); + let c = s.height; + // Central differences (image y points down). + let dx = h(Some(x + 1), Some(y)).unwrap_or(c) - h(x.checked_sub(1), Some(y)).unwrap_or(c); + let dy = h(Some(x), y.checked_sub(1)).unwrap_or(c) - h(Some(x), Some(y + 1)).unwrap_or(c); + let k = r * 0.5 * 1.5; + let b = [n.x - dx * k, n.y - dy * k, n.z]; + let len = (b[0] * b[0] + b[1] * b[1] + b[2] * b[2]).sqrt().max(1e-6); + let col = shade(b.map(|v| v / len), s.base, s.metallic, s.roughness).map(|v| (linear_to_srgb(aces(v * 1.4)) * 255.0 + 0.5) as u8); + let edge = ((1.0 - (n.x * n.x + n.y * n.y).sqrt()) * r).clamp(0.0, 1.0); + img.pixels[i] = Color32::from_rgba_unmultiplied(col[0], col[1], col[2], (edge * 255.0) as u8); + } + img +} + +/// Grayscale `size²` swatch of procedural `kind`. +pub fn procedural_image(kind: ProceduralKind, size: usize) -> ColorImage { + use texturecraft_engine::compose::pattern::{Coords, procedural}; + use texturecraft_engine::core::{Procedural, Projection}; + use texturecraft_engine::geom::glam::{Vec2, Vec3}; + + let pattern = Procedural { scale: PROCEDURAL_SCALE, ..Procedural::new(kind) }; + let mut img = ColorImage::filled([size, size], Color32::BLACK); + for (i, px) in img.pixels.iter_mut().enumerate() { + let uv = Vec2::new(((i % size) as f32 + 0.5) / size as f32, ((i / size) as f32 + 0.5) / size as f32); + let v = procedural(&pattern, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y }); + *px = Color32::from_gray((v.clamp(0.0, 1.0) * 255.0) as u8); + } + img +} + +/// White-on-black `size²` swatch of library alpha `alpha`. +pub fn alpha_image(alpha: &LibraryAlpha, size: usize) -> ColorImage { + let pixels = alpha.render(size, ALPHA_SUPERSAMPLE).into_iter().map(|v| Color32::from_gray((v * 255.0 + 0.5) as u8)).collect(); + ColorImage::new([size, size], pixels) +} + +/// Image resource `img` letterboxed into a `size²` square to keep its proportions, over black +/// where it is transparent. +pub fn image_preview(img: &ImageRes, size: usize) -> ColorImage { + let aspect = img.width as f32 / img.height.max(1) as f32; + let (scale_u, scale_v) = if aspect >= 1.0 { (1.0, aspect) } else { (1.0 / aspect.max(1e-6), 1.0) }; + let mut preview = ColorImage::filled([size, size], Color32::BLACK); + for y in 0..size { + for x in 0..size { + let u = ((x as f32 + 0.5) / size as f32 - 0.5) * scale_u + 0.5; + let v = ((y as f32 + 0.5) / size as f32 - 0.5) * scale_v + 0.5; + if !((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v)) { + continue; + } + + let sample = img.sample(u, v); + let alpha = sample[3]; + let encode = |c: f32| if img.srgb { (c.clamp(0.0, 1.0) * alpha.clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(c * alpha) * 255.0) as u8 }; + preview.pixels[y * size + x] = Color32::from_rgb(encode(sample[0]), encode(sample[1]), encode(sample[2])); + } + } + preview +} + +/// `b`'s stamps (shape, spacing, flow, angle, path following, jitters) along an S curve across +/// an `n`-pixel square, white on black. +pub fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage { + let library = b.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); + let radius = n as f32 * 0.11; + let shape = Shape { alpha: b.alpha, image: None, library, level: 0 }.at_radius(radius); + let curve = |t: f32| (n as f32 * (0.15 + 0.7 * t), n as f32 * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin())); + let mut cover = vec![0f32; n * n]; + // Deterministic jitter per stamp. + let rnd = |i: u32, k: u32| (i.wrapping_mul(0x9E37_79B9) ^ k.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32; + let step = (b.spacing * 2.0 * radius).max(0.5); + let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32); + let mut last = curve(0.0); + while t <= 1.0 && i < 2000 { + let p = curve(t); + travelled += (p.0 - last.0).hypot(p.1 - last.1); + last = p; + t += 0.002; + if travelled < step { + continue; + } + travelled = 0.0; + i += 1; + let r = radius * (1.0 - b.jitter_size * rnd(i, 1)); + let tangent = if b.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 }; + let angle = b.angle.to_radians() + tangent + b.jitter_angle * std::f32::consts::TAU * rnd(i, 2); + let (cx, cy) = (p.0 + b.jitter_position * radius * (rnd(i, 3) * 2.0 - 1.0), p.1 + b.jitter_position * radius * (rnd(i, 4) * 2.0 - 1.0)); + let flow = b.flow * (1.0 - b.jitter_flow * rnd(i, 5)); + let (sin, cos) = angle.sin_cos(); + let (x0, x1) = ((cx - r).floor().max(0.0) as usize, ((cx + r).ceil() as usize).min(n)); + let (y0, y1) = ((cy - r).floor().max(0.0) as usize, ((cy + r).ceil() as usize).min(n)); + for y in y0..y1 { + for x in x0..x1 { + let (dx, dy) = ((x as f32 + 0.5 - cx) / r, (cy - y as f32 - 0.5) / r); + let a = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, b.hardness, i) * flow; + let c = &mut cover[y * n + x]; + *c = 1.0 - (1.0 - *c) * (1.0 - a.clamp(0.0, 1.0)); + } + } + } + ColorImage::new([n, n], cover.into_iter().map(|v| Color32::from_gray((v * b.opacity * 255.0 + 0.5) as u8)).collect()) +} diff --git a/crates/ui-egui/src/preview_request.rs b/crates/ui-egui/src/preview_request.rs new file mode 100644 index 00000000..56e2e3b3 --- /dev/null +++ b/crates/ui-egui/src/preview_request.rs @@ -0,0 +1,29 @@ +//! A request to the shelf preview worker (see [`crate::preview_worker::PreviewWorker`]). + +use egui::ColorImage; + +use crate::mask_preview_image::mask_preview_image; +use crate::mask_shape::MaskShape; +use crate::shelf_preview::ShelfPreview; + +/// Render `preview` at `size_px²`; the answer comes back under `key`. +pub struct PreviewRequest { + pub key: String, + pub preview: ShelfPreview, + pub size_px: usize, + /// A hover preview: the worker renders the newest of these before anything else. + // The web renders each request at once, so nothing is reordered there + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub hover: bool, +} + +impl PreviewRequest { + /// The requested image (None for an unknown asset, or a smart mask when the shape fails to + /// bake); smart masks bake `shape` on first use. + pub fn render(&self, shape: &mut MaskShape) -> Option { + match &self.preview { + ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.render(id, self.size_px)?)), + preview => preview.image(self.size_px), + } + } +} diff --git a/crates/ui-egui/src/preview_worker.rs b/crates/ui-egui/src/preview_worker.rs new file mode 100644 index 00000000..cf51812e --- /dev/null +++ b/crates/ui-egui/src/preview_worker.rs @@ -0,0 +1,207 @@ +//! Renders shelf previews off the UI thread, on threads of its own (one core is left for the UI): +//! big hover previews and the smart mask thumbnails, which share one baked preview shape. On the web there are no threads: each request renders +//! inline on the UI thread (the window pauses for it). + +#[cfg(target_arch = "wasm32")] +use crate::mask_shape::MaskShape; +use crate::preview_request::PreviewRequest; + +/// A rendered preview: the request's key and its image (None when it could not be rendered). +pub type PreviewResult = (String, Option); + +/// The preview worker, started by the first request. +#[derive(Default)] +pub enum PreviewWorker { + #[default] + NotStarted, + /// The worker thread: requests go in, results come out (it ends when the requests sender is + /// dropped). + #[cfg(not(target_arch = "wasm32"))] + Running { requests: std::sync::mpsc::Sender, results: std::sync::mpsc::Receiver }, + /// The web: requests render as they are made. + #[cfg(target_arch = "wasm32")] + Inline { shape: MaskShape, results: Vec }, + /// The worker could not start or stopped; requests are refused. + // The web has no thread to stop + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + Stopped, +} + +impl PreviewWorker { + /// Queue `request`, starting the worker first if needed; false when the worker is stopped. + /// The worker repaints `ctx` when a result is ready. + pub fn request(&mut self, ctx: &egui::Context, request: PreviewRequest) -> bool { + if matches!(self, PreviewWorker::NotStarted) { + *self = PreviewWorker::start(ctx); + } + + match self { + #[cfg(not(target_arch = "wasm32"))] + PreviewWorker::Running { requests, .. } => { + if requests.send(request).is_ok() { + return true; + } + *self = PreviewWorker::Stopped; + false + } + #[cfg(target_arch = "wasm32")] + PreviewWorker::Inline { shape, results } => { + results.push((request.key.clone(), request.render(shape))); + true + } + PreviewWorker::NotStarted | PreviewWorker::Stopped => false, + } + } + + /// The results ready since the last call. + pub fn poll(&mut self) -> Vec { + match self { + #[cfg(not(target_arch = "wasm32"))] + PreviewWorker::Running { results, .. } => { + use std::sync::mpsc::TryRecvError; + + let mut ready = Vec::new(); + loop { + match results.try_recv() { + Ok(result) => ready.push(result), + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => { + log::warn!("the shelf preview worker stopped"); + *self = PreviewWorker::Stopped; + break; + } + } + } + ready + } + #[cfg(target_arch = "wasm32")] + PreviewWorker::Inline { results, .. } => std::mem::take(results), + PreviewWorker::NotStarted | PreviewWorker::Stopped => Vec::new(), + } + } + + /// Whether the worker stopped: it refuses requests and answers none of the queued ones. + pub fn is_stopped(&self) -> bool { + matches!(self, PreviewWorker::Stopped) + } + + /// Start the worker thread (Stopped when it cannot start). + #[cfg(not(target_arch = "wasm32"))] + fn start(ctx: &egui::Context) -> PreviewWorker { + use std::collections::VecDeque; + use std::sync::mpsc::channel; + + use crate::mask_shape::MaskShape; + + let (requests, request_rx) = channel::(); + let (result_tx, results) = channel(); + let ctx = ctx.clone(); + let spawned = std::thread::Builder::new().name("texturecraft-shelf-previews".into()).spawn(move || { + // Its own threads: on the global pool a big render would hold up the UI thread's work + let threads = std::thread::available_parallelism().map_or(1, |n| n.get().saturating_sub(1).max(1)); + let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|i| format!("texturecraft-preview-{i}")).build(); + if let Err(e) = &pool { + log::warn!("shelf previews share the global thread pool: {e}"); + } + let mut shape = MaskShape::default(); + let mut queue = VecDeque::new(); + loop { + // Wait for work, then take in everything sent meanwhile + if queue.is_empty() { + let Ok(request) = request_rx.recv() else { break }; + + queue.push_back(request); + } + queue.extend(request_rx.try_iter()); + + let Some(request) = next_request(&mut queue) else { continue }; + let image = match &pool { + Ok(pool) => pool.install(|| request.render(&mut shape)), + Err(_) => request.render(&mut shape), + }; + if result_tx.send((request.key, image)).is_err() { + break; + } + ctx.request_repaint(); + } + }); + + match spawned { + Ok(_) => PreviewWorker::Running { requests, results }, + Err(e) => { + log::warn!("could not start the shelf preview worker: {e}"); + PreviewWorker::Stopped + } + } + } + + /// Render inline (no threads on the web). + #[cfg(target_arch = "wasm32")] + fn start(_ctx: &egui::Context) -> PreviewWorker { + PreviewWorker::Inline { shape: MaskShape::default(), results: Vec::new() } + } +} + +/// The request to render next: the newest hover preview (the one under the pointer), else the +/// oldest request. +#[cfg(not(target_arch = "wasm32"))] +fn next_request(queue: &mut std::collections::VecDeque) -> Option { + match queue.iter().rposition(|request| request.hover) { + Some(newest_hover) => queue.remove(newest_hover), + None => queue.pop_front(), + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::time::{Duration, Instant}; + + use texturecraft_engine::materials::MATERIALS; + use texturecraft_engine::smart_masks::SMART_MASKS; + + use super::*; + use crate::shelf_preview::ShelfPreview; + + #[test] + fn requests_are_answered_and_unknown_assets_get_none() { + let ctx = egui::Context::default(); + let mut worker = PreviewWorker::default(); + let size_px = 32; + let requests = [ + ("material", ShelfPreview::Material(MATERIALS[0].id)), + ("unknown material", ShelfPreview::Material("nope")), + ("mask", ShelfPreview::SmartMask(SMART_MASKS[0].id)), + ("unknown mask", ShelfPreview::SmartMask("nope")), + ]; + for (key, preview) in requests { + assert!(worker.request(&ctx, PreviewRequest { key: key.into(), preview, size_px, hover: false }), "{key}"); + } + + let mut answers = HashMap::new(); + let start = Instant::now(); + while answers.len() < 4 && start.elapsed() < Duration::from_secs(120) { + answers.extend(worker.poll()); + std::thread::sleep(Duration::from_millis(10)); + } + + for key in ["material", "mask"] { + let image = answers.get(key).and_then(Option::as_ref).unwrap_or_else(|| panic!("{key}: {answers:?}")); + assert_eq!(image.size, [size_px, size_px], "{key}"); + } + for key in ["unknown material", "unknown mask"] { + assert!(matches!(answers.get(key), Some(None)), "{key}: {answers:?}"); + } + assert!(!worker.is_stopped()); + } + + #[test] + fn the_newest_hover_preview_goes_first_then_the_oldest_request() { + let request = |key: &str, hover| PreviewRequest { key: key.into(), preview: ShelfPreview::Material("steel"), size_px: 8, hover }; + let mut queue: std::collections::VecDeque<_> = + [request("thumbnail 1", false), request("old hover", true), request("thumbnail 2", false), request("new hover", true)].into(); + + let order: Vec = std::iter::from_fn(|| next_request(&mut queue)).map(|r| r.key).collect(); + assert_eq!(order, ["new hover", "old hover", "thumbnail 1", "thumbnail 2"]); + } +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 351219b9..27309ca9 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -19,9 +19,32 @@ use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; use crate::i18n::{tr, trf}; +use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; +use crate::thumbs::Thumbs; use crate::widgets::{dnd_release, icon_button}; +/// A shelf tile's size in points. +const TILE_WIDTH: f32 = 72.0; +const TILE_HEIGHT: f32 = 86.0; +/// Corner radius of a tile's hover and selection highlights, in points. +const TILE_ROUNDING: f32 = 3.0; +/// The thumbnail's size in a tile and its center below the tile's top, in points. +const THUMBNAIL_SIZE: f32 = 56.0; +const THUMBNAIL_CENTER_Y: f32 = 32.0; +/// A placeholder disc's radius relative to the thumbnail's width. +const PLACEHOLDER_RADIUS: f32 = 0.45; +/// A tile label's font size, its gap below the thumbnail and its total side margin, in points. +const LABEL_FONT_SIZE: f32 = 9.5; +const LABEL_GAP: f32 = 3.0; +const LABEL_MARGIN: f32 = 4.0; +/// The hover preview's size and its gap above the label, in points. +const BIG_PREVIEW_SIZE: f32 = 256.0; +const BIG_PREVIEW_LABEL_GAP: f32 = 4.0; +/// How long the pointer rests on a tile before its big preview renders, in seconds (well inside +/// the popup's delay). +const BIG_PREVIEW_DWELL: f32 = 0.1; + #[derive(Clone, Copy, PartialEq, Eq)] pub(crate) enum Tab { Materials, @@ -267,13 +290,8 @@ fn materials(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter tiles(ui, |ui| { for m in shown.iter().filter(|m| m.category == cat) { let tex = app.thumbs.material(ctx, m.id); - let hint = if m.smart { - tr("Add the smart material folder above the selected layer (or drag it into the layer stack)") - } else { - tr("Add a fill layer with this material above the selected layer (or drag it into the layer stack)") - }; let asset = Asset::Material(m.id); - if tile(ui, tex.as_ref(), m.label, hint, Some(&asset)).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Material(m.id), m.label, Some(&asset)).clicked() { apply(app, &asset); } } @@ -340,8 +358,7 @@ fn smart_masks(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filt for m in shown { let tex = app.thumbs.smart_mask(ctx, m.id); let asset = Asset::SmartMask(m.id); - let hint = tr("Replace the selected layer's mask with this smart mask (or drag it onto a layer)"); - if tile(ui, tex.as_ref(), m.label, hint, Some(&asset)).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::SmartMask(m.id), m.label, Some(&asset)).clicked() { apply(app, &asset); } } @@ -361,13 +378,8 @@ fn filters(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: tiles(ui, |ui| { for f in shown.iter().filter(|f| f.group == group) { let tex = app.thumbs.filter(ctx, f.id); - let hint = if f.mask { - tr("Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)") - } else { - tr("Add this finish to the selected layer's roughness and height (or drag it onto a layer)") - }; let asset = Asset::Filter(f.id); - if tile(ui, tex.as_ref(), tr(f.label), hint, Some(&asset)).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Filter(f.id), tr(f.label), Some(&asset)).clicked() { apply(app, &asset); } } @@ -386,7 +398,7 @@ fn brushes(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: tiles(ui, |ui| { for p in shown.iter().filter(|p| p.category == cat) { let tex = app.thumbs.brush_preset(ctx, p); - if tile(ui, tex.as_ref(), p.label, tr("Use this brush (keeps its size)"), None).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Brush(p), p.label, None).clicked() { app.run("brush.preset.apply", json!({"preset": p.id})); } } @@ -467,9 +479,9 @@ fn alpha_library(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, fi for &a in shown.iter().filter(|a| a.category == cat) { let tex = app.thumbs.alpha(ctx, a); let asset = Asset::Alpha(&a.id); - let r = tile(ui, tex.as_ref(), &a.label, tr("Use as the brush alpha (or drag it onto the viewport or brush properties)"), Some(&asset)); + let r = tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Alpha(a), &a.label, Some(&asset)); if current.as_deref() == Some(a.id.as_str()) { - ui.painter().rect_stroke(r.rect, 3.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); + ui.painter().rect_stroke(r.rect, TILE_ROUNDING, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); } if r.clicked() { apply(app, &asset); @@ -488,7 +500,7 @@ fn procedurals(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filt tiles(ui, |ui| { for k in shown { let tex = app.thumbs.procedural(ctx, k); - if tile(ui, tex.as_ref(), tr(k.label()), tr("Add a fill layer using this pattern"), None).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Procedural(k), tr(k.label()), None).clicked() { app.run("layer.add.fill", json!({"name": k.label()})); app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": k.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]})); } @@ -531,7 +543,8 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: let Some(img) = app.session.images.get(&name).cloned() else { continue }; let tex = app.thumbs.image(ctx, &name, &img); let asset = Asset::Texture(name.clone()); - let r = tile(ui, Some(&tex), &name, tr("Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)"), Some(&asset)); + let preview = || ShelfPreview::Image(name.clone(), img); + let r = tile(ui, &mut app.thumbs, Some(&tex), preview, &name, Some(&asset)); if r.clicked() { apply(app, &asset); } @@ -550,32 +563,74 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: } /// A shelf tile: thumbnail (a placeholder disc while it renders) and a wrapped label; tiles with -/// a `drag` asset can be dragged. -fn tile(ui: &mut Ui, tex: Option<&egui::TextureHandle>, label: &str, hint: &str, drag: Option<&Asset>) -> egui::Response { +/// a `drag` asset can be dragged. Hovering shows a big `preview` (made only then) over the label. +fn tile( + ui: &mut Ui, + thumbs: &mut Thumbs, + tex: Option<&egui::TextureHandle>, + preview: impl FnOnce() -> ShelfPreview, + label: &str, + drag: Option<&Asset>, +) -> egui::Response { let tk = Tokens::get(ui.ctx()); let sense = if drag.is_some() { Sense::click_and_drag() } else { Sense::click() }; - let (rect, resp) = ui.allocate_exact_size(vec2(72.0, 86.0), sense); + let (rect, resp) = ui.allocate_exact_size(vec2(TILE_WIDTH, TILE_HEIGHT), sense); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); if let Some(asset) = drag && resp.drag_started() { resp.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string() }); } - let p = ui.painter(); + + let painter = ui.painter(); if resp.hovered() || resp.dragged() { - p.rect_filled(rect, 3.0, tk.row_hover); + painter.rect_filled(rect, TILE_ROUNDING, tk.row_hover); } - let img = egui::Rect::from_center_size(rect.center_top() + vec2(0.0, 32.0), vec2(56.0, 56.0)); + let image_rect = egui::Rect::from_center_size(rect.center_top() + vec2(0.0, THUMBNAIL_CENTER_Y), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); + thumbnail(painter, tex, image_rect, &tk); + let galley = painter.layout(label.to_string(), egui::FontId::proportional(LABEL_FONT_SIZE), tk.text, rect.width() - LABEL_MARGIN); + painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tk.text); + + let big = if resp.hovered() { big_preview(ui, thumbs, preview) } else { None }; + resp.on_hover_ui(|ui| hover_preview(ui, tex, big.as_ref(), label)) +} + +/// A hovered tile's big preview: requested once the pointer has rested [`BIG_PREVIEW_DWELL`], so +/// it renders during the popup's delay but not for tiles the pointer sweeps across (None until the +/// worker renders it). +fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPreview) -> Option { + let ctx = ui.ctx(); + let size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; + let still_for = ui.input(|i| i.pointer.time_since_last_movement()); + if still_for >= BIG_PREVIEW_DWELL { + return thumbs.big(ctx, preview(), size_px); + } + + ctx.request_repaint_after_secs(BIG_PREVIEW_DWELL - still_for); + thumbs.rendered_big(ctx, &preview(), size_px) +} + +/// `tex` drawn into `rect`, or a placeholder disc while it renders. +fn thumbnail(painter: &egui::Painter, tex: Option<&egui::TextureHandle>, rect: egui::Rect, tk: &Tokens) { match tex { Some(t) => { - p.image(t.id(), img, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); + painter.image(t.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); } None => { - p.circle_filled(img.center(), img.width() * 0.45, tk.row_hover); + painter.circle_filled(rect.center(), rect.width() * PLACEHOLDER_RADIUS, tk.row_hover); } } - let galley = p.layout(label.to_string(), egui::FontId::proportional(9.5), tk.text, rect.width() - 4.0); - p.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, img.bottom() + 3.0), galley, tk.text); - resp.on_hover_ui(|ui| { - ui.label(format!("{label}: {hint}")); - }) +} + +/// A tile's hover popup: the `big` preview (the tile's `small` thumbnail scaled up until it +/// renders) over the label. +fn hover_preview(ui: &mut Ui, small: Option<&egui::TextureHandle>, big: Option<&egui::TextureHandle>, label: &str) { + let tk = Tokens::get(ui.ctx()); + ui.set_max_width(BIG_PREVIEW_SIZE); + ui.vertical_centered(|ui| { + let (rect, _) = ui.allocate_exact_size(vec2(BIG_PREVIEW_SIZE, BIG_PREVIEW_SIZE), Sense::hover()); + thumbnail(ui.painter(), big.or(small), rect, &tk); + ui.add_space(BIG_PREVIEW_LABEL_GAP); + ui.label(label); + }); } diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs new file mode 100644 index 00000000..f8cc7e3b --- /dev/null +++ b/crates/ui-egui/src/shelf_preview.rs @@ -0,0 +1,102 @@ +//! What a shelf preview shows, and how to render it at any size. + +use std::sync::Arc; + +use egui::ColorImage; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::paint::BrushSettings; +use texturecraft_engine::paint::alphas::LibraryAlpha; +use texturecraft_engine::paint::presets::BrushPreset; +use texturecraft_engine::preview; + +use crate::preview_image::{alpha_image, image_preview, procedural_image, sphere_image, stroke_preview}; + +/// The asset a shelf tile previews. +pub enum ShelfPreview { + /// A built-in material or smart material on a sphere. + Material(&'static str), + /// A smart mask on the baked preview shape (only the preview worker can render it: see + /// [`crate::preview_request::PreviewRequest::render`]). + SmartMask(&'static str), + /// A library filter on a sample material on a sphere. + Filter(&'static str), + /// A procedural pattern as a grayscale swatch. + Procedural(ProceduralKind), + /// A library brush alpha, white on black. + Alpha(&'static LibraryAlpha), + /// A brush preset's stroke along an S curve. + Brush(&'static BrushPreset), + /// An image resource by name. + Image(String, Arc), +} + +impl ShelfPreview { + /// The cache key of the preview (one per asset). + pub fn key(&self) -> String { + match self { + ShelfPreview::Material(id) => format!("mat:{id}"), + ShelfPreview::SmartMask(id) => format!("mask:{id}"), + ShelfPreview::Filter(id) => format!("filter:{id}"), + ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), + ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id), + ShelfPreview::Brush(preset) => format!("brush:{}", preset.id), + ShelfPreview::Image(name, _) => format!("image:{name}"), + } + } + + /// The preview as a `size²` image (None for an unknown material or filter id). Smart masks are + /// None here: they need the baked preview shape, which only the preview worker holds, so the + /// UI thread never bakes. + pub fn image(&self, size: usize) -> Option { + match self { + ShelfPreview::Material(id) => Some(sphere_image(size, &preview::material(id, size)?)), + ShelfPreview::SmartMask(_) => None, + ShelfPreview::Filter(id) => Some(sphere_image(size, &preview::filter(id, size)?)), + ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)), + ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), + ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size)), + ShelfPreview::Image(_, image) => Some(image_preview(image, size)), + } + } +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::filter_lib::FILTERS; + use texturecraft_engine::materials::MATERIALS; + use texturecraft_engine::paint::alphas; + use texturecraft_engine::paint::presets::PRESETS; + + use super::*; + + /// The hover preview's size at 100 % scale. + const BIG_PX: usize = 256; + + #[test] + fn every_tab_renders_a_big_preview() { + let image = ImageRes { width: 4, height: 2, rgba: vec![[0.8, 0.4, 0.2, 1.0]; 8], srgb: true }; + let previews = [ + ShelfPreview::Material(MATERIALS[0].id), + ShelfPreview::Filter(FILTERS[0].id), + ShelfPreview::Procedural(ProceduralKind::ALL[0]), + ShelfPreview::Alpha(&alphas::library()[0]), + ShelfPreview::Brush(&PRESETS[0]), + ShelfPreview::Image("image".into(), Arc::new(image)), + ]; + for preview in previews { + let key = preview.key(); + let image = preview.image(BIG_PX).unwrap_or_else(|| panic!("{key}")); + assert_eq!(image.size, [BIG_PX, BIG_PX], "{key}"); + assert!(image.pixels.iter().any(|c| c.a() > 0 && c.r().max(c.g()).max(c.b()) > 0), "{key}: something shows"); + } + + // The shaded spheres come from finite material values + let finite = |samples: Vec>| { + samples.iter().flatten().all(|s| s.base.iter().chain([&s.metallic, &s.roughness, &s.height]).all(|v| v.is_finite())) + }; + assert!(finite(preview::material(MATERIALS[0].id, BIG_PX).unwrap_or_default())); + assert!(finite(preview::filter(FILTERS[0].id, BIG_PX).unwrap_or_default())); + assert!(ShelfPreview::SmartMask("edges_sharp").image(BIG_PX).is_none(), "smart masks need the baked shape"); + } +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index f5590b31..982caa17 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -1,95 +1,51 @@ -//! Thumbnails: shaded material spheres, smart masks on a baked preview shape, procedural swatches -//! and brush alpha previews, rendered on the CPU into cached egui textures (no image assets). New -//! shelf thumbnails are rendered lazily, a few per frame, so opening the shelf never stalls a -//! frame; the smart mask previews render together on a worker. +//! Thumbnails: shelf previews (see [`crate::preview_image`]) cached as egui textures, plus small +//! shaded spheres and alpha previews drawn as shapes. New shelf thumbnails are rendered lazily, a +//! few per frame, so opening the shelf never stalls a frame; the smart mask thumbnails and the big +//! hover previews render on a worker. -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use egui::{Color32, ColorImage, Painter, Pos2, Rect, TextureHandle, TextureOptions}; use texturecraft_engine::core::ProceduralKind; use texturecraft_engine::paint::presets::BrushPreset; -use texturecraft_engine::paint::{BrushAlpha, BrushSettings, Shape, alphas}; -use texturecraft_engine::preview::{self, Sample}; +use texturecraft_engine::paint::{BrushAlpha, alphas}; use texturecraft_engine::texel::linear_to_srgb; -use crate::mask_previews::MaskPreviews; +use crate::preview_image::{aces, image_preview, shade}; +use crate::preview_request::PreviewRequest; +use crate::preview_worker::PreviewWorker; +use crate::shelf_preview::ShelfPreview; +use crate::worker_preview::WorkerPreview; /// Shelf thumbnails rendered per frame at most (the rest follow on the next frames). const PER_FRAME: usize = 2; -/// Shelf sphere thumbnail size in pixels. +/// Shelf sphere and smart mask thumbnail size in pixels. const SPHERE_PX: usize = 72; +/// Shelf procedural swatch size in pixels. +const PROCEDURAL_PX: usize = 56; +/// Shelf alpha and brush stroke swatch size in pixels. +const SWATCH_PX: usize = 64; +/// Image resource preview size in pixels. +const IMAGE_PX: usize = 64; +/// Big hover previews kept at most (the least recently shown go first). +const BIG_PREVIEWS_KEPT: usize = 32; +/// The shelf's and the brush panel's preview textures. #[derive(Default)] pub struct Thumbs { - /// Shelf thumbnails by key (`mat:`, `mask:`, `filter:`, `proc:`, `alpha:`, - /// `brush:`). + /// Shelf thumbnails by [`ShelfPreview::key`]. shelf: HashMap, images: HashMap, /// (frame, thumbnails rendered in it). budget: (u64, usize), - mask_previews: MaskPreviews, -} - -fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { - let l = [0.45f32, 0.7, 0.55]; - let len = (l[0] * l[0] + l[1] * l[1] + l[2] * l[2]).sqrt(); - let l = l.map(|v| v / len); - let ndl = (n[0] * l[0] + n[1] * l[1] + n[2] * l[2]).max(0.0); - let ndv = n[2].max(0.0); - // View along +Z: half vector between light and view. - let h = [l[0], l[1], l[2] + 1.0]; - let hl = (h[0] * h[0] + h[1] * h[1] + h[2] * h[2]).sqrt(); - let ndh = ((n[0] * h[0] + n[1] * h[1] + n[2] * h[2]) / hl).max(0.0); - let shin = 2.0 / (rough * rough * rough * rough).max(1e-3) - 2.0; - let spec_amt = ndh.powf(shin.clamp(1.0, 4096.0)) * (shin + 2.0) / 8.0; - // A studio environment seen in the mirror direction: dark floor, bright sky, a horizon that - // blurs (and the whole environment averages out) as roughness grows. - let ry = 2.0 * ndv * n[1]; - let w = 0.06 + rough * 0.9; - let t = ((ry + w) / (2.0 * w)).clamp(0.0, 1.0); - let sharp = 0.04 + 0.03 * (ry + 1.0) + (0.2 + 0.55 * ry.max(0.0)) * t * t * (3.0 - 2.0 * t); - let env = sharp + (0.28 - sharp) * (rough * rough); - let fres = (1.0 - ndv).powi(5); - let sky = 0.35 + 0.25 * n[1]; - let mut out = [0.0; 3]; - for k in 0..3 { - let f0 = 0.04 + (base[k] - 0.04) * metal; - let f = f0 + ((1.0 - rough).max(f0) - f0) * fres; - let diffuse = base[k] * (1.0 - metal) * (ndl * 0.85 + sky * 0.5); - out[k] = diffuse * (1.0 - f) + f * env + f0 * spec_amt * ndl * 1.5; - } - out -} - -fn aces(x: f32) -> f32 { - let v = x * 0.6; - ((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14)).clamp(0.0, 1.0) -} - -/// A shaded sphere image (sRGB, transparent outside) from per-pixel preview samples (row-major -/// `size²`, see [`preview::sphere_normals`]); height bumps the normals. -pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { - let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); - let r = (size as f32 * 0.5 - 1.0).max(0.5); - let h = |x: Option, y: Option| { - let (x, y) = (x.filter(|x| *x < size)?, y?); - samples.get(y.checked_mul(size)?.checked_add(x)?).copied().flatten().map(|s| s.height) - }; - for (i, n) in preview::sphere_normals(size).enumerate() { - let (Some(n), Some(Some(s))) = (n, samples.get(i)) else { continue }; - let (x, y) = (i % size, i / size); - let c = s.height; - // Central differences (image y points down). - let dx = h(Some(x + 1), Some(y)).unwrap_or(c) - h(x.checked_sub(1), Some(y)).unwrap_or(c); - let dy = h(Some(x), y.checked_sub(1)).unwrap_or(c) - h(Some(x), Some(y + 1)).unwrap_or(c); - let k = r * 0.5 * 1.5; - let b = [n.x - dx * k, n.y - dy * k, n.z]; - let len = (b[0] * b[0] + b[1] * b[1] + b[2] * b[2]).sqrt().max(1e-6); - let col = shade(b.map(|v| v / len), s.base, s.metallic, s.roughness).map(|v| (linear_to_srgb(aces(v * 1.4)) * 255.0 + 0.5) as u8); - let edge = ((1.0 - (n.x * n.x + n.y * n.y).sqrt()) * r).clamp(0.0, 1.0); - img.pixels[i] = Color32::from_rgba_unmultiplied(col[0], col[1], col[2], (edge * 255.0) as u8); - } - img + /// Renders the smart mask thumbnails and the big previews. + worker: PreviewWorker, + /// Worker-rendered previews by [`worker_key`]. + rendered: HashMap, + /// The keys of the big previews in `rendered`, least recently shown first. + big_shown: VecDeque, + /// The frame that last took in the worker's results. + received_in_pass: u64, } impl Thumbs { @@ -114,38 +70,24 @@ impl Thumbs { t } - /// Cached preview of an image resource (64 px, nearest downsample). + /// Cached preview of an image resource (64 px, letterboxed). pub fn image(&mut self, ctx: &egui::Context, name: &str, img: &texturecraft_engine::compose::ImageRes) -> TextureHandle { if let Some(t) = self.images.get(name) { return t.clone(); } - let n = 64usize; - // Letterboxed to keep its proportions, over black where it is transparent. - let aspect = img.width as f32 / img.height.max(1) as f32; - let (sx, sy) = if aspect >= 1.0 { (1.0, aspect) } else { (1.0 / aspect.max(1e-6), 1.0) }; - let mut ci = ColorImage::filled([n, n], Color32::BLACK); - for y in 0..n { - for x in 0..n { - let (u, v) = (((x as f32 + 0.5) / n as f32 - 0.5) * sx + 0.5, ((y as f32 + 0.5) / n as f32 - 0.5) * sy + 0.5); - if !((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v)) { - continue; - } - let s = img.sample(u, v); - let enc = |c: f32| if img.srgb { (c.clamp(0.0, 1.0) * s[3].clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(c * s[3]) * 255.0) as u8 }; - ci.pixels[y * n + x] = Color32::from_rgb(enc(s[0]), enc(s[1]), enc(s[2])); - } - } - let t = ctx.load_texture(format!("res_{name}"), ci, TextureOptions::LINEAR); + let t = ctx.load_texture(format!("res_{name}"), image_preview(img, IMAGE_PX), TextureOptions::LINEAR); self.images.insert(name.to_string(), t.clone()); t } - /// A cached shelf thumbnail, rendering it with `render` if this frame's budget allows (None - /// until then; a repaint is requested so it follows shortly). - fn shelf(&mut self, ctx: &egui::Context, key: String, render: impl FnOnce() -> ColorImage) -> Option { + /// A cached shelf thumbnail of `preview` at `size_px²`, rendering it if this frame's budget + /// allows (None until then; a repaint is requested so it follows shortly). + fn shelf(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { + let key = preview.key(); if let Some(t) = self.shelf.get(&key) { return Some(t.clone()); } + let frame = ctx.cumulative_pass_nr(); if self.budget.0 != frame { self.budget = (frame, 0); @@ -155,110 +97,117 @@ impl Thumbs { return None; } self.budget.1 += 1; - let t = ctx.load_texture(format!("thumb_{key}"), render(), TextureOptions::LINEAR); + + // An unknown asset shows as an empty thumbnail + let image = preview.image(size_px).unwrap_or_else(|| ColorImage::filled([size_px, size_px], Color32::TRANSPARENT)); + let t = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR); self.shelf.insert(key, t.clone()); Some(t) } - /// Sphere thumbnail of built-in material `id`. - pub fn material(&mut self, ctx: &egui::Context, id: &str) -> Option { - self.shelf(ctx, format!("mat:{id}"), || sphere_image(SPHERE_PX, &preview::material(id, SPHERE_PX).unwrap_or_default())) + /// A worker-rendered `size_px²` image of `preview`, requested on the first call (None until it + /// arrives, and for good when it cannot be rendered); `hover` previews jump the worker's queue. + fn worker_rendered(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize, hover: bool) -> Option { + self.receive(ctx); + + let key = worker_key(&preview, size_px); + if !self.rendered.contains_key(&key) { + let queued = self.worker.request(ctx, PreviewRequest { key: key.clone(), preview, size_px, hover }); + self.rendered.insert(key.clone(), if queued { WorkerPreview::Rendering } else { WorkerPreview::Failed }); + } + self.ready(&key) } - /// Thumbnail of smart mask `id` on the baked preview shape (None while the thumbnails - /// render; they all arrive together). - pub fn smart_mask(&mut self, ctx: &egui::Context, id: &str) -> Option { - let key = format!("mask:{id}"); - if let Some(t) = self.shelf.get(&key) { - return Some(t.clone()); + /// The worker-rendered preview under `key` if it arrived. + fn ready(&self, key: &str) -> Option { + match self.rendered.get(key) { + Some(WorkerPreview::Ready(t)) => Some(t.clone()), + Some(WorkerPreview::Rendering | WorkerPreview::Failed) | None => None, + } + } + + /// Take in the worker's finished previews, once per frame (dropping the ones no longer + /// wanted). + fn receive(&mut self, ctx: &egui::Context) { + let pass = ctx.cumulative_pass_nr(); + if self.received_in_pass == pass { + return; + } + self.received_in_pass = pass; + + for (key, image) in self.worker.poll() { + let Some(entry) = self.rendered.get_mut(&key) else { continue }; + + *entry = match image { + Some(image) => WorkerPreview::Ready(ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR)), + None => WorkerPreview::Failed, + }; } - for (mask_id, image) in self.mask_previews.poll(ctx, SPHERE_PX).unwrap_or_default() { - let mask_key = format!("mask:{mask_id}"); - let t = ctx.load_texture(format!("thumb_{mask_key}"), image, TextureOptions::LINEAR); - self.shelf.insert(mask_key, t); + // A stopped worker never answers the rest + if self.worker.is_stopped() { + for entry in self.rendered.values_mut().filter(|e| matches!(e, WorkerPreview::Rendering)) { + *entry = WorkerPreview::Failed; + } } - self.shelf.get(&key).cloned() + } + + /// The big hover preview of `preview`, `size_px²` (None until the worker renders it; the + /// least recently shown are dropped past [`BIG_PREVIEWS_KEPT`]). + pub fn big(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { + let key = worker_key(&preview, size_px); + self.big_shown.retain(|k| *k != key); + self.big_shown.push_back(key); + while self.big_shown.len() > BIG_PREVIEWS_KEPT { + if let Some(oldest) = self.big_shown.pop_front() { + self.rendered.remove(&oldest); + } + } + + self.worker_rendered(ctx, preview, size_px, true) + } + + /// The big preview of `preview` if the worker already rendered it (requests nothing). + pub fn rendered_big(&mut self, ctx: &egui::Context, preview: &ShelfPreview, size_px: usize) -> Option { + self.receive(ctx); + self.ready(&worker_key(preview, size_px)) + } + + /// Sphere thumbnail of built-in material `id`. + pub fn material(&mut self, ctx: &egui::Context, id: &'static str) -> Option { + self.shelf(ctx, ShelfPreview::Material(id), SPHERE_PX) + } + + /// Thumbnail of smart mask `id` on the baked preview shape (None while the worker renders + /// it). + pub fn smart_mask(&mut self, ctx: &egui::Context, id: &'static str) -> Option { + self.worker_rendered(ctx, ShelfPreview::SmartMask(id), SPHERE_PX, false) } /// Sphere thumbnail of library filter `id` applied to a sample material. - pub fn filter(&mut self, ctx: &egui::Context, id: &str) -> Option { - self.shelf(ctx, format!("filter:{id}"), || sphere_image(SPHERE_PX, &preview::filter(id, SPHERE_PX).unwrap_or_default())) + pub fn filter(&mut self, ctx: &egui::Context, id: &'static str) -> Option { + self.shelf(ctx, ShelfPreview::Filter(id), SPHERE_PX) } - /// Grayscale swatch of procedural `k`. - pub fn procedural(&mut self, ctx: &egui::Context, k: ProceduralKind) -> Option { - use texturecraft_engine::compose::pattern::{Coords, procedural}; - use texturecraft_engine::core::{Procedural, Projection}; - use texturecraft_engine::geom::glam::{Vec2, Vec3}; - self.shelf(ctx, format!("proc:{k:?}"), || { - let n = 56usize; - let pr = Procedural { scale: 3.0, ..Procedural::new(k) }; - let mut img = ColorImage::filled([n, n], Color32::BLACK); - for (i, px) in img.pixels.iter_mut().enumerate() { - let uv = Vec2::new(((i % n) as f32 + 0.5) / n as f32, ((i / n) as f32 + 0.5) / n as f32); - let v = procedural(&pr, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y }); - *px = Color32::from_gray((v.clamp(0.0, 1.0) * 255.0) as u8); - } - img - }) + /// Grayscale swatch of procedural `kind`. + pub fn procedural(&mut self, ctx: &egui::Context, kind: ProceduralKind) -> Option { + self.shelf(ctx, ShelfPreview::Procedural(kind), PROCEDURAL_PX) } - /// White-on-black swatch of library alpha `a`. - pub fn alpha(&mut self, ctx: &egui::Context, a: &alphas::LibraryAlpha) -> Option { - self.shelf(ctx, format!("alpha:{}", a.id), || { - let n = 64usize; - ColorImage::new([n, n], a.render(n, 2).into_iter().map(|v| Color32::from_gray((v * 255.0 + 0.5) as u8)).collect()) - }) + /// White-on-black swatch of library alpha `alpha`. + pub fn alpha(&mut self, ctx: &egui::Context, alpha: &'static alphas::LibraryAlpha) -> Option { + self.shelf(ctx, ShelfPreview::Alpha(alpha), SWATCH_PX) } /// A brush preset's stroke along an S curve. - pub fn brush_preset(&mut self, ctx: &egui::Context, p: &BrushPreset) -> Option { - self.shelf(ctx, format!("brush:{}", p.id), || stroke_preview(&p.applied(&BrushSettings::default()), 64)) + pub fn brush_preset(&mut self, ctx: &egui::Context, preset: &'static BrushPreset) -> Option { + self.shelf(ctx, ShelfPreview::Brush(preset), SWATCH_PX) } } -/// `b`'s stamps (shape, spacing, flow, angle, path following, jitters) along an S curve across -/// an `n`-pixel square, white on black. -fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage { - let library = b.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); - let radius = n as f32 * 0.11; - let shape = Shape { alpha: b.alpha, image: None, library, level: 0 }.at_radius(radius); - let curve = |t: f32| (n as f32 * (0.15 + 0.7 * t), n as f32 * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin())); - let mut cover = vec![0f32; n * n]; - // Deterministic jitter per stamp. - let rnd = |i: u32, k: u32| (i.wrapping_mul(0x9E37_79B9) ^ k.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32; - let step = (b.spacing * 2.0 * radius).max(0.5); - let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32); - let mut last = curve(0.0); - while t <= 1.0 && i < 2000 { - let p = curve(t); - travelled += (p.0 - last.0).hypot(p.1 - last.1); - last = p; - t += 0.002; - if travelled < step { - continue; - } - travelled = 0.0; - i += 1; - let r = radius * (1.0 - b.jitter_size * rnd(i, 1)); - let tangent = if b.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 }; - let angle = b.angle.to_radians() + tangent + b.jitter_angle * std::f32::consts::TAU * rnd(i, 2); - let (cx, cy) = (p.0 + b.jitter_position * radius * (rnd(i, 3) * 2.0 - 1.0), p.1 + b.jitter_position * radius * (rnd(i, 4) * 2.0 - 1.0)); - let flow = b.flow * (1.0 - b.jitter_flow * rnd(i, 5)); - let (sin, cos) = angle.sin_cos(); - let (x0, x1) = ((cx - r).floor().max(0.0) as usize, ((cx + r).ceil() as usize).min(n)); - let (y0, y1) = ((cy - r).floor().max(0.0) as usize, ((cy + r).ceil() as usize).min(n)); - for y in y0..y1 { - for x in x0..x1 { - let (dx, dy) = ((x as f32 + 0.5 - cx) / r, (cy - y as f32 - 0.5) / r); - let a = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, b.hardness, i) * flow; - let c = &mut cover[y * n + x]; - *c = 1.0 - (1.0 - *c) * (1.0 - a.clamp(0.0, 1.0)); - } - } - } - ColorImage::new([n, n], cover.into_iter().map(|v| Color32::from_gray((v * b.opacity * 255.0 + 0.5) as u8)).collect()) +/// The key of a worker-rendered preview: one per asset and size. +fn worker_key(preview: &ShelfPreview, size_px: usize) -> String { + format!("{}@{size_px}", preview.key()) } /// A small shaded sphere drawn with a vertex-colored mesh (layer thumbnails, previews). diff --git a/crates/ui-egui/src/worker_preview.rs b/crates/ui-egui/src/worker_preview.rs new file mode 100644 index 00000000..0252d69f --- /dev/null +++ b/crates/ui-egui/src/worker_preview.rs @@ -0,0 +1,13 @@ +//! A preview rendered by the [`crate::preview_worker::PreviewWorker`], as the thumbnail cache +//! tracks it. + +use egui::TextureHandle; + +/// Where a worker-rendered preview is. +pub enum WorkerPreview { + /// Requested; the worker has not answered yet. + Rendering, + Ready(TextureHandle), + /// The asset is unknown or the worker could not render it (the tile keeps its placeholder). + Failed, +} diff --git a/crates/ui-egui/tests/shelf_hover_preview.rs b/crates/ui-egui/tests/shelf_hover_preview.rs new file mode 100644 index 00000000..4dbaaa7b --- /dev/null +++ b/crates/ui-egui/tests/shelf_hover_preview.rs @@ -0,0 +1,110 @@ +//! Hovering a shelf tile shows a big preview of the asset over its name, rendered once the pointer +//! rests on the tile. + +use std::time::{Duration, Instant}; + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::shelf_preview::ShelfPreview; + +/// The shelf's Materials tab. +const MATERIALS_TAB: usize = 0; +/// The hover preview's size in points (pixels at this scale). +const BIG_PREVIEW_SIZE: f32 = 256.0; +/// Simulated seconds per frame, fine enough to stop between the rest and the popup's delay. +const STEP_SECONDS: f32 = 0.001; +/// The popup's delay (egui's tooltip delay) and the rest after which the big preview renders. +const POPUP_DELAY: f32 = 0.5; +const REST: f32 = 0.1; +/// Real time the worker gets to render. +const WORKER_TIMEOUT: Duration = Duration::from_secs(60); + +/// The app on the Materials tab, `step_seconds` per frame, and two materials whose names show +/// nowhere else. +fn materials_shelf(step_seconds: f32) -> (Harness<'static, TextureCraftApp>, Vec<&'static SmartMaterial>) { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_step_dt(step_seconds).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.shelf_tab = MATERIALS_TAB; + h.run_steps(4); + + let unique: Vec<_> = MATERIALS.iter().filter(|m| !m.smart && h.query_all_by_label(m.label).count() == 1).take(2).collect(); + assert_eq!(unique.len(), 2, "two materials with unique names"); + (h, unique) +} + +/// The pixel size of the largest texture (not the font atlas) the last frame drew at least +/// `min_width` points wide. +fn largest_drawn_texture(h: &Harness<'_, TextureCraftApp>, min_width: f32) -> Option<[usize; 2]> { + let textures = h.ctx.tex_manager(); + let textures = textures.read(); + h.output() + .shapes + .iter() + .filter(|clipped| clipped.shape.texture_id() != egui::TextureId::default() && clipped.shape.visual_bounding_rect().width() >= min_width) + .filter_map(|clipped| textures.meta(clipped.shape.texture_id()).map(|meta| meta.size)) + .max() +} + +/// Whether `material`'s big preview has arrived from the worker (asks for nothing). +fn big_preview_ready(h: &mut Harness<'static, TextureCraftApp>, material: &SmartMaterial) -> bool { + let ctx = h.ctx.clone(); + h.state_mut().thumbs.rendered_big(&ctx, &ShelfPreview::Material(material.id), BIG_PREVIEW_SIZE as usize).is_some() +} + +#[test] +fn hovering_a_shelf_tile_shows_its_big_preview() { + let (mut h, materials) = materials_shelf(1.0 / 4.0); + let material = materials[0]; + let tile = h.get_by_label(material.label).rect(); + assert!(largest_drawn_texture(&h, BIG_PREVIEW_SIZE).is_none(), "nothing big before the hover"); + h.get_by_label(material.label).hover(); + + // The popup's delay, then the worker + let big_px = BIG_PREVIEW_SIZE as usize; + let start = Instant::now(); + while largest_drawn_texture(&h, BIG_PREVIEW_SIZE) != Some([big_px, big_px]) && start.elapsed() < WORKER_TIMEOUT { + h.run_steps(1); + std::thread::sleep(Duration::from_millis(20)); + } + + assert_eq!(largest_drawn_texture(&h, BIG_PREVIEW_SIZE), Some([big_px, big_px]), "the popup draws the big preview"); + // The popup's name sits under the big image, below the tile + let popup_name = h.get_all_by_label(material.label).map(|n| n.rect()).find(|r| r.min.y > tile.max.y).expect("the popup shows the name"); + assert!(popup_name.min.y - tile.max.y >= BIG_PREVIEW_SIZE, "{popup_name:?} under {tile:?}"); +} + +#[test] +fn the_big_preview_renders_after_a_rest_but_not_during_a_sweep() { + let (mut h, materials) = materials_shelf(STEP_SECONDS); + let (first, second) = (materials[0], materials[1]); + let (from, to) = (h.get_by_label(first.label).rect().center(), h.get_by_label(second.label).rect().center()); + + // A sweep: the pointer moves every frame across both tiles, then leaves the shelf + let sweep_frames = 40; + for frame in 0..=sweep_frames { + h.hover_at(from.lerp(to, frame as f32 / sweep_frames as f32)); + h.run_steps(1); + } + h.hover_at(egui::pos2(900.0, 500.0)); + h.run_steps(1); + std::thread::sleep(Duration::from_secs(1)); + h.run_steps(1); + assert!(!big_preview_ready(&mut h, first) && !big_preview_ready(&mut h, second), "a sweep renders nothing"); + + // A rest: the preview renders before the popup opens + h.hover_at(from); + h.run_steps((REST * 1.2 / STEP_SECONDS) as usize); + let start = Instant::now(); + let headroom_frames = ((POPUP_DELAY - REST * 1.2) / STEP_SECONDS) as usize - 1; + for _ in 0..headroom_frames { + if big_preview_ready(&mut h, first) || start.elapsed() > WORKER_TIMEOUT { + break; + } + h.run_steps(1); + std::thread::sleep(Duration::from_millis(10)); + } + assert!(big_preview_ready(&mut h, first), "the preview rendered during the popup's delay"); + assert_eq!(h.query_all_by_label(first.label).count(), 1, "the popup is not open yet"); +} From 03a9870db20d77cf0f000567d629a3610969434c Mon Sep 17 00:00:00 2001 From: chasse20 Date: Fri, 6 Nov 2026 01:12:55 -0500 Subject: [PATCH 3/3] Fix shelf hover previews and clean up comments --- crates/engine/src/mask_preview.rs | 40 ++++++------ crates/engine/src/mask_preview_camera.rs | 19 +++--- crates/ui-egui/src/mask_preview_image.rs | 14 ++--- crates/ui-egui/src/mask_shape.rs | 10 +-- crates/ui-egui/src/preview_image.rs | 35 +++++------ crates/ui-egui/src/preview_request.rs | 10 +-- crates/ui-egui/src/preview_worker.rs | 35 +++++------ crates/ui-egui/src/shelf.rs | 43 +++++++------ crates/ui-egui/src/shelf_preview.rs | 29 ++++----- crates/ui-egui/src/thumbs.rs | 69 ++++++++++----------- crates/ui-egui/src/worker_preview.rs | 9 ++- crates/ui-egui/tests/shelf_hover_preview.rs | 62 +++++++++++++----- 12 files changed, 188 insertions(+), 187 deletions(-) diff --git a/crates/engine/src/mask_preview.rs b/crates/engine/src/mask_preview.rs index 6e3f3525..a44757fc 100644 --- a/crates/engine/src/mask_preview.rs +++ b/crates/engine/src/mask_preview.rs @@ -1,6 +1,5 @@ -//! Smart mask shelf previews: the real smart masks on a baked preview shape. The shape -//! ([`primitives::preview_orb`]) is baked once; each preset is then applied with -//! `mask.smart.apply`, read back from the compositor and seen from a fixed camera. +//! Smart mask previews share one baked [`primitives::preview_orb`] +//! Presets use `mask.smart.apply` and the compositor, matching document masks use serde_json::json; use texturecraft_core::{BakeResolution, BakedMap, CurvatureMethod, LayerId}; @@ -11,34 +10,33 @@ use crate::mask_preview_camera::MaskPreviewCamera; pub use crate::mask_preview_pixel::MaskPreviewPixel; use crate::{EngineError, Result, Session}; -/// Texture and bake size of the preview shape in texels (at 256 the edge lines break up). +/// Bake resolution in texels; 256 loses the thin edge lines const TEXTURE_PX: u32 = 512; -/// Camera rays per preview pixel along each axis (anti-aliased outline). +/// Camera rays per preview pixel along each axis (anti-aliased outline) const SUPERSAMPLE: usize = 2; -/// Bound camera samples and output allocations for shelf previews. +/// Bound camera samples and output allocations for shelf previews pub const MAX_PREVIEW_SIZE_PX: usize = 512; -/// AO and thickness rays per texel (the default is 64; fewer look the same at thumbnail size). +/// AO and thickness rays per texel; thumbnail detail needs fewer than the default const OCCLUSION_RAYS: u32 = 12; -/// Mesh curvature rays per texel (the default is 32; fewer look the same at thumbnail size). +/// Curvature rays per texel; thumbnail detail needs fewer than the default const CURVATURE_RAYS: u32 = 12; -/// Mesh curvature sampling radius relative to the bounding box: wide enough that edges read as -/// lines at thumbnail size, narrow enough that the round body does not count as an edge. +/// Radius relative to the bounding box; isolates panel edges from the round body const CURVATURE_RADIUS: f32 = 0.005; -/// The mesh maps the smart mask generators read. +/// The mesh maps the smart mask generators read const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; -/// Camera views kept at most (one per preview size: the shelf thumbnail and the hover preview). +/// Keep camera views for the thumbnail and hover preview sizes const CAMERAS_KEPT: usize = 2; -/// The baked preview shape and, per preview size, what its camera sees. +/// The baked preview shape and, per preview size, what its camera sees pub struct MaskPreview { session: Session, layer: LayerId, - /// Camera views of the most recently used preview sizes, oldest first (traced on first use). + /// Cached camera views, least recently used first cameras: Vec, } impl MaskPreview { - /// Bake the preview shape once (previews of any size reuse it). + /// Bake the preview shape once (previews of any size reuse it) pub fn new() -> Result { let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; let set = session.doc.project.texture_set_mut(0)?; @@ -58,15 +56,15 @@ impl MaskPreview { Ok(MaskPreview { session, layer, cameras: Vec::new() }) } - /// Smart mask `id` per preview pixel, row-major `size²`, None where the shape is not seen - /// Returns None for an unknown id or a size outside 1..=[`MAX_PREVIEW_SIZE_PX`]. + /// Row-major `size²` pixels, with None outside the shape + /// Returns None for unknown masks or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] pub fn render(&mut self, id: &str, size: usize) -> Option>> { if !(1..=MAX_PREVIEW_SIZE_PX).contains(&size) { return None; } crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; - // Nothing is undone here; the snapshots would pile up over the presets + // Previews need no undo history; retaining snapshots grows memory across presets self.session.undo.clear(); let camera = camera_for(&mut self.cameras, &self.session, size)?; @@ -94,8 +92,7 @@ impl MaskPreview { } } -/// The camera view for `size²` previews of `session`'s shape, traced on first use (moved to the end -/// of `cameras`); past [`CAMERAS_KEPT`] the least recently used size goes. +/// Cache one camera per preview size, evicting the least recently used view fn camera_for<'a>(cameras: &'a mut Vec, session: &Session, size: usize) -> Option<&'a MaskPreviewCamera> { let rays_per_side = size * SUPERSAMPLE; let camera = match cameras.iter().position(|c| c.rays_per_side == rays_per_side) { @@ -114,7 +111,7 @@ fn camera_for<'a>(cameras: &'a mut Vec, session: &Session, si mod tests { use super::*; - /// Mean absolute difference of the masks of two previews over the pixels both see. + /// Mean absolute difference of the masks of two previews over the pixels both see fn difference(a: &[Option], b: &[Option]) -> f32 { let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect(); pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 @@ -154,7 +151,6 @@ mod tests { assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); assert!(preview.render("nope", size).is_none()); - // The same bake renders other sizes, showing the same mask let big = preview.render("edges_sharp", size * 3).unwrap(); let mean = |px: &[Option]| px.iter().flatten().map(|p| p.mask).sum::() / px.iter().flatten().count().max(1) as f32; assert_eq!(big.len(), size * size * 9); diff --git a/crates/engine/src/mask_preview_camera.rs b/crates/engine/src/mask_preview_camera.rs index 9787accb..ea3d6d1f 100644 --- a/crates/engine/src/mask_preview_camera.rs +++ b/crates/engine/src/mask_preview_camera.rs @@ -1,5 +1,4 @@ -//! The fixed camera of the smart mask previews (see [`crate::mask_preview::MaskPreview`]) at one -//! image size. +//! Cached camera rays for one smart mask preview size use std::collections::HashMap; @@ -8,27 +7,25 @@ use texturecraft_geom::surface_at; use crate::Session; -/// Camera: looking down by this angle, turned to show the front, left and top panels. +/// Camera angles expose the front, left and top panels const CAMERA_PITCH_DEG: f32 = 35.0; const CAMERA_YAW_DEG: f32 = -34.4; -/// What one camera ray sees: the index of its texel in [`MaskPreviewCamera::texels`] and the -/// view-space normal there (None where the ray misses). +/// Index into [`MaskPreviewCamera::texels`] and view-space normal; None on a miss pub(crate) type CameraSample = Option<(usize, Vec3)>; -/// What each ray of a square orthographic view of the preview shape sees. +/// What each ray of a square orthographic view of the preview shape sees pub(crate) struct MaskPreviewCamera { - /// Rays along each side of the view. + /// Rays along each side of the view pub rays_per_side: usize, - /// The texels (x, y) the camera sees, each once. + /// The texels (x, y) the camera sees, each once pub texels: Vec<(u32, u32)>, - /// Per ray, row-major `rays_per_side²`. + /// Per ray, row-major `rays_per_side²` pub samples: Vec, } impl MaskPreviewCamera { - /// Trace `rays_per_side²` rays at the shape of `session`, whose textures are `texture_px` - /// square. + /// Trace a square orthographic view onto a `texture_px²` texture pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> MaskPreviewCamera { let (lo, hi) = session.mesh.bounds(); let center = (lo + hi) * 0.5; diff --git a/crates/ui-egui/src/mask_preview_image.rs b/crates/ui-egui/src/mask_preview_image.rs index 49fe70f7..4418d099 100644 --- a/crates/ui-egui/src/mask_preview_image.rs +++ b/crates/ui-egui/src/mask_preview_image.rs @@ -1,28 +1,24 @@ -//! Shading of the smart mask previews: the mask as white over a near-black surface. +//! Smart masks appear white against a near-black surface use egui::{Color32, ColorImage}; use texturecraft_engine::geom::glam::Vec3; use texturecraft_engine::mask_preview::MaskPreviewPixel; use texturecraft_engine::texel::linear_to_srgb; -/// View-space directions of the key light (upper left) and a weaker fill (right), and how much -/// each lights the surface. +/// View-space lighting uses an upper-left key and a weaker right fill const KEY: [f32; 3] = [-0.72, 0.62, 0.3]; const FILL: [f32; 3] = [0.7, -0.1, 0.7]; const AMBIENT: f32 = 0.1; const KEY_STRENGTH: f32 = 0.8; const FILL_STRENGTH: f32 = 0.35; -/// Where the mask is empty: a near-black albedo with a faint sheen of the key light, so the -/// shape reads without looking glossy. +/// A faint sheen reveals the unmasked shape without a glossy finish const UNMASKED_ALBEDO: f32 = 0.006; const SHEEN: f32 = 0.1; const SHEEN_EXPONENT: f32 = 40.0; -/// Where the mask is full: white, darkened at most this much where unlit. +/// Where the mask is full: white, darkened at most this much where unlit const WHITE_SHADING: f32 = 0.2; -/// A smart mask preview (sRGB, transparent outside the shape) from preview pixels (row-major -/// `size²`): the mask as white over a near-black surface lit softly from the upper left. No -/// environment reflections. +/// Shade row-major `size²` mask pixels in sRGB with a transparent background pub fn mask_preview_image(size: usize, pixels: &[Option]) -> ColorImage { let key = Vec3::from(KEY).normalize(); let fill = Vec3::from(FILL).normalize(); diff --git a/crates/ui-egui/src/mask_shape.rs b/crates/ui-egui/src/mask_shape.rs index e34c5a7e..c99a9b1c 100644 --- a/crates/ui-egui/src/mask_shape.rs +++ b/crates/ui-egui/src/mask_shape.rs @@ -1,20 +1,20 @@ -//! The smart mask preview shape, baked on first use. +//! The smart mask preview shape, baked on first use use texturecraft_engine::mask_preview::MaskPreview; -/// Whether the smart mask preview shape is baked. +/// Whether the smart mask preview shape is baked #[derive(Default)] pub enum MaskShape { #[default] NotBaked, - /// Boxed: the baked session is large and the enum sits in the worker for its whole life. + /// Box the large session to keep the unbaked worker small Baked(Box), - /// The bake failed; smart mask previews stay empty. + /// The bake failed; smart mask previews stay empty Failed, } impl MaskShape { - /// The baked shape, baking it on the first call (about two seconds; None when it fails). + /// Bake on first use; retain failure to avoid retrying every frame pub fn get(&mut self) -> Option<&mut MaskPreview> { if matches!(self, MaskShape::NotBaked) { *self = match MaskPreview::new() { diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs index 3f2321dc..f689c85d 100644 --- a/crates/ui-egui/src/preview_image.rs +++ b/crates/ui-egui/src/preview_image.rs @@ -1,5 +1,4 @@ -//! The CPU renderers of the shelf previews at any size: shaded material spheres, procedural -//! swatches, alpha swatches, brush strokes and letterboxed images (no image assets). +//! CPU renderers for shelf spheres, swatches, strokes and imported images use egui::{Color32, ColorImage}; use texturecraft_engine::compose::ImageRes; @@ -9,27 +8,25 @@ use texturecraft_engine::paint::{BrushSettings, Shape}; use texturecraft_engine::preview::{self, Sample}; use texturecraft_engine::texel::linear_to_srgb; -/// Pattern scale of the procedural swatches (repeats across the swatch). +/// Pattern scale of the procedural swatches (repeats across the swatch) const PROCEDURAL_SCALE: f32 = 3.0; -/// Samples per pixel along each axis of the alpha swatches. +/// Samples per pixel along each axis of the alpha swatches const ALPHA_SUPERSAMPLE: usize = 2; -/// Linear color of a surface with view-space normal `n` and these material values, lit by a key -/// light and a studio environment, seen along +Z. +/// Linear shading for view-space normal `n`, viewed along +Z pub fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { let l = [0.45f32, 0.7, 0.55]; let len = (l[0] * l[0] + l[1] * l[1] + l[2] * l[2]).sqrt(); let l = l.map(|v| v / len); let ndl = (n[0] * l[0] + n[1] * l[1] + n[2] * l[2]).max(0.0); let ndv = n[2].max(0.0); - // View along +Z: half vector between light and view. + // The view direction is +Z let h = [l[0], l[1], l[2] + 1.0]; let hl = (h[0] * h[0] + h[1] * h[1] + h[2] * h[2]).sqrt(); let ndh = ((n[0] * h[0] + n[1] * h[1] + n[2] * h[2]) / hl).max(0.0); let shin = 2.0 / (rough * rough * rough * rough).max(1e-3) - 2.0; let spec_amt = ndh.powf(shin.clamp(1.0, 4096.0)) * (shin + 2.0) / 8.0; - // A studio environment seen in the mirror direction: dark floor, bright sky, a horizon that - // blurs (and the whole environment averages out) as roughness grows. + // Roughness blurs the reflected horizon toward the environment average let ry = 2.0 * ndv * n[1]; let w = 0.06 + rough * 0.9; let t = ((ry + w) / (2.0 * w)).clamp(0.0, 1.0); @@ -47,14 +44,13 @@ pub fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { out } -/// ACES filmic tone mapping of linear `x` (exposure folded in) to 0..=1. +/// ACES filmic tone mapping of linear `x` (exposure folded in) to 0..=1 pub fn aces(x: f32) -> f32 { let v = x * 0.6; ((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14)).clamp(0.0, 1.0) } -/// A shaded sphere image (sRGB, transparent outside) from per-pixel preview samples (row-major -/// `size²`, see [`preview::sphere_normals`]); height bumps the normals. +/// Shade row-major `size²` samples with height bumps and a transparent background pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); let r = (size as f32 * 0.5 - 1.0).max(0.5); @@ -64,9 +60,10 @@ pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { }; for (i, n) in preview::sphere_normals(size).enumerate() { let (Some(n), Some(Some(s))) = (n, samples.get(i)) else { continue }; + let (x, y) = (i % size, i / size); let c = s.height; - // Central differences (image y points down). + // Image Y points down; the shading normal uses Y up let dx = h(Some(x + 1), Some(y)).unwrap_or(c) - h(x.checked_sub(1), Some(y)).unwrap_or(c); let dy = h(Some(x), y.checked_sub(1)).unwrap_or(c) - h(Some(x), Some(y + 1)).unwrap_or(c); let k = r * 0.5 * 1.5; @@ -79,7 +76,7 @@ pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { img } -/// Grayscale `size²` swatch of procedural `kind`. +/// Grayscale `size²` swatch of procedural `kind` pub fn procedural_image(kind: ProceduralKind, size: usize) -> ColorImage { use texturecraft_engine::compose::pattern::{Coords, procedural}; use texturecraft_engine::core::{Procedural, Projection}; @@ -95,14 +92,13 @@ pub fn procedural_image(kind: ProceduralKind, size: usize) -> ColorImage { img } -/// White-on-black `size²` swatch of library alpha `alpha`. +/// White-on-black `size²` swatch of library alpha `alpha` pub fn alpha_image(alpha: &LibraryAlpha, size: usize) -> ColorImage { let pixels = alpha.render(size, ALPHA_SUPERSAMPLE).into_iter().map(|v| Color32::from_gray((v * 255.0 + 0.5) as u8)).collect(); ColorImage::new([size, size], pixels) } -/// Image resource `img` letterboxed into a `size²` square to keep its proportions, over black -/// where it is transparent. +/// Letterbox into a `size²` square, compositing transparency over black pub fn image_preview(img: &ImageRes, size: usize) -> ColorImage { let aspect = img.width as f32 / img.height.max(1) as f32; let (scale_u, scale_v) = if aspect >= 1.0 { (1.0, aspect) } else { (1.0 / aspect.max(1e-6), 1.0) }; @@ -124,15 +120,14 @@ pub fn image_preview(img: &ImageRes, size: usize) -> ColorImage { preview } -/// `b`'s stamps (shape, spacing, flow, angle, path following, jitters) along an S curve across -/// an `n`-pixel square, white on black. +/// Preview the brush along an S curve in an `n`-pixel square pub fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage { let library = b.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); let radius = n as f32 * 0.11; let shape = Shape { alpha: b.alpha, image: None, library, level: 0 }.at_radius(radius); let curve = |t: f32| (n as f32 * (0.15 + 0.7 * t), n as f32 * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin())); let mut cover = vec![0f32; n * n]; - // Deterministic jitter per stamp. + // Stable jitter keeps the preview reproducible let rnd = |i: u32, k: u32| (i.wrapping_mul(0x9E37_79B9) ^ k.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32; let step = (b.spacing * 2.0 * radius).max(0.5); let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32); diff --git a/crates/ui-egui/src/preview_request.rs b/crates/ui-egui/src/preview_request.rs index 56e2e3b3..71c7870b 100644 --- a/crates/ui-egui/src/preview_request.rs +++ b/crates/ui-egui/src/preview_request.rs @@ -1,4 +1,4 @@ -//! A request to the shelf preview worker (see [`crate::preview_worker::PreviewWorker`]). +//! Shelf preview work submitted to [`crate::preview_worker::PreviewWorker`] use egui::ColorImage; @@ -6,20 +6,20 @@ use crate::mask_preview_image::mask_preview_image; use crate::mask_shape::MaskShape; use crate::shelf_preview::ShelfPreview; -/// Render `preview` at `size_px²`; the answer comes back under `key`. +/// Render `preview` at `size_px²`; the answer comes back under `key` pub struct PreviewRequest { pub key: String, pub preview: ShelfPreview, pub size_px: usize, - /// A hover preview: the worker renders the newest of these before anything else. + /// A hover preview: the worker renders the newest of these before anything else // The web renders each request at once, so nothing is reordered there #[cfg_attr(target_arch = "wasm32", allow(dead_code))] pub hover: bool, } impl PreviewRequest { - /// The requested image (None for an unknown asset, or a smart mask when the shape fails to - /// bake); smart masks bake `shape` on first use. + /// Render the asset, baking the mask shape on first use + /// Unknown assets and failed bakes return None pub fn render(&self, shape: &mut MaskShape) -> Option { match &self.preview { ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.render(id, self.size_px)?)), diff --git a/crates/ui-egui/src/preview_worker.rs b/crates/ui-egui/src/preview_worker.rs index cf51812e..a3d2cc8f 100644 --- a/crates/ui-egui/src/preview_worker.rs +++ b/crates/ui-egui/src/preview_worker.rs @@ -1,35 +1,33 @@ -//! Renders shelf previews off the UI thread, on threads of its own (one core is left for the UI): -//! big hover previews and the smart mask thumbnails, which share one baked preview shape. On the web there are no threads: each request renders -//! inline on the UI thread (the window pauses for it). +//! Native preview rendering uses a separate thread pool +//! Web requests render synchronously on the UI thread #[cfg(target_arch = "wasm32")] use crate::mask_shape::MaskShape; use crate::preview_request::PreviewRequest; -/// A rendered preview: the request's key and its image (None when it could not be rendered). +/// Request key and rendered image; None on failure pub type PreviewResult = (String, Option); -/// The preview worker, started by the first request. +/// The preview worker, started by the first request #[derive(Default)] pub enum PreviewWorker { #[default] NotStarted, - /// The worker thread: requests go in, results come out (it ends when the requests sender is - /// dropped). + /// Native worker; dropping the request sender ends it after pending work #[cfg(not(target_arch = "wasm32"))] Running { requests: std::sync::mpsc::Sender, results: std::sync::mpsc::Receiver }, - /// The web: requests render as they are made. + /// The web: requests render as they are made #[cfg(target_arch = "wasm32")] Inline { shape: MaskShape, results: Vec }, - /// The worker could not start or stopped; requests are refused. + /// The worker could not start or stopped; requests are refused // The web has no thread to stop #[cfg_attr(target_arch = "wasm32", allow(dead_code))] Stopped, } impl PreviewWorker { - /// Queue `request`, starting the worker first if needed; false when the worker is stopped. - /// The worker repaints `ctx` when a result is ready. + /// Submit work, starting the worker on first use; false if it has stopped + /// Native results request a repaint pub fn request(&mut self, ctx: &egui::Context, request: PreviewRequest) -> bool { if matches!(self, PreviewWorker::NotStarted) { *self = PreviewWorker::start(ctx); @@ -53,7 +51,7 @@ impl PreviewWorker { } } - /// The results ready since the last call. + /// The results ready since the last call pub fn poll(&mut self) -> Vec { match self { #[cfg(not(target_arch = "wasm32"))] @@ -80,12 +78,12 @@ impl PreviewWorker { } } - /// Whether the worker stopped: it refuses requests and answers none of the queued ones. + /// Whether the worker stopped: it refuses requests and answers none of the queued ones pub fn is_stopped(&self) -> bool { matches!(self, PreviewWorker::Stopped) } - /// Start the worker thread (Stopped when it cannot start). + /// Start the worker thread (Stopped when it cannot start) #[cfg(not(target_arch = "wasm32"))] fn start(ctx: &egui::Context) -> PreviewWorker { use std::collections::VecDeque; @@ -97,7 +95,7 @@ impl PreviewWorker { let (result_tx, results) = channel(); let ctx = ctx.clone(); let spawned = std::thread::Builder::new().name("texturecraft-shelf-previews".into()).spawn(move || { - // Its own threads: on the global pool a big render would hold up the UI thread's work + // A separate pool keeps previews from queuing ahead of the UI's work let threads = std::thread::available_parallelism().map_or(1, |n| n.get().saturating_sub(1).max(1)); let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|i| format!("texturecraft-preview-{i}")).build(); if let Err(e) = &pool { @@ -106,7 +104,6 @@ impl PreviewWorker { let mut shape = MaskShape::default(); let mut queue = VecDeque::new(); loop { - // Wait for work, then take in everything sent meanwhile if queue.is_empty() { let Ok(request) = request_rx.recv() else { break }; @@ -115,6 +112,7 @@ impl PreviewWorker { queue.extend(request_rx.try_iter()); let Some(request) = next_request(&mut queue) else { continue }; + let image = match &pool { Ok(pool) => pool.install(|| request.render(&mut shape)), Err(_) => request.render(&mut shape), @@ -135,15 +133,14 @@ impl PreviewWorker { } } - /// Render inline (no threads on the web). + /// Render inline (no threads on the web) #[cfg(target_arch = "wasm32")] fn start(_ctx: &egui::Context) -> PreviewWorker { PreviewWorker::Inline { shape: MaskShape::default(), results: Vec::new() } } } -/// The request to render next: the newest hover preview (the one under the pointer), else the -/// oldest request. +/// Prioritize the newest hover preview over older requests #[cfg(not(target_arch = "wasm32"))] fn next_request(queue: &mut std::collections::VecDeque) -> Option { match queue.iter().rposition(|request| request.hover) { diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 2617a56d..46ced908 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -26,25 +26,24 @@ use crate::theme::Tokens; use crate::thumbs::Thumbs; use crate::widgets::{dnd_release, icon_button}; -/// A shelf tile's size in points. +/// A shelf tile's size in points const TILE_WIDTH: f32 = 72.0; const TILE_HEIGHT: f32 = 86.0; -/// Corner radius of a tile's hover and selection highlights, in points. +/// Corner radius of a tile's hover and selection highlights, in points const TILE_ROUNDING: f32 = 3.0; -/// The thumbnail's size in a tile and its center below the tile's top, in points. +/// The thumbnail's size in a tile and its center below the tile's top, in points const THUMBNAIL_SIZE: f32 = 56.0; const THUMBNAIL_CENTER_Y: f32 = 32.0; -/// A placeholder disc's radius relative to the thumbnail's width. +/// A placeholder disc's radius relative to the thumbnail's width const PLACEHOLDER_RADIUS: f32 = 0.45; -/// A tile label's font size, its gap below the thumbnail and its total side margin, in points. +/// A tile label's font size, its gap below the thumbnail and its total side margin, in points const LABEL_FONT_SIZE: f32 = 9.5; const LABEL_GAP: f32 = 3.0; const LABEL_MARGIN: f32 = 4.0; -/// The hover preview's size and its gap above the label, in points. +/// The hover preview's size and its gap above the label, in points const BIG_PREVIEW_SIZE: f32 = 256.0; const BIG_PREVIEW_LABEL_GAP: f32 = 4.0; -/// How long the pointer rests on a tile before its big preview renders, in seconds (well inside -/// the popup's delay). +/// Dwell in seconds before rendering, shorter than the popup delay const BIG_PREVIEW_DWELL: f32 = 0.1; #[derive(Clone, Copy, PartialEq, Eq)] @@ -564,6 +563,7 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: tiles(ui, |ui| { for name in names { let Some(img) = app.session.images.get(&name).cloned() else { continue }; + let tex = app.thumbs.image(ctx, &name, &img); let asset = Asset::Texture(name.clone()); let preview = || ShelfPreview::Image(name.clone(), img); @@ -585,8 +585,7 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: }); } -/// A shelf tile: thumbnail (a placeholder disc while it renders) and a wrapped label; tiles with -/// a `drag` asset can be dragged. Hovering shows a big `preview` (made only then) over the label. +/// Asset tile with optional dragging and a larger hover preview fn tile( ui: &mut Ui, thumbs: &mut Thumbs, @@ -618,25 +617,26 @@ fn tile( resp.on_hover_ui(|ui| hover_preview(ui, tex, big.as_ref(), label)) } -/// A hovered tile's big preview: requested once the pointer has rested [`BIG_PREVIEW_DWELL`], so -/// it renders during the popup's delay but not for tiles the pointer sweeps across (None until the -/// worker renders it). +/// Start rendering during the popup delay once the pointer rests fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPreview) -> Option { let ctx = ui.ctx(); - let size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; let preview = preview(); - // Keep smart mask hover previews within the camera's allocation limit at high display scales. - let size_px = if matches!(&preview, ShelfPreview::SmartMask(_)) { size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { size_px }; - let still_for = ui.input(|i| i.pointer.time_since_last_movement()); - if still_for >= BIG_PREVIEW_DWELL { + let requested_size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; + + // High display scales must respect the mask camera's allocation limit + let size_px = if matches!(&preview, ShelfPreview::SmartMask(_)) { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px }; + + // Scrolling moves tiles beneath a stationary pointer + let idle_seconds = ui.input(|input| if input.is_scrolling() { 0.0 } else { input.pointer.time_since_last_movement().min(input.time_since_last_scroll()) }); + if idle_seconds >= BIG_PREVIEW_DWELL { return thumbs.big(ctx, preview, size_px); } - ctx.request_repaint_after_secs(BIG_PREVIEW_DWELL - still_for); + ctx.request_repaint_after_secs(BIG_PREVIEW_DWELL - idle_seconds); thumbs.rendered_big(ctx, &preview, size_px) } -/// `tex` drawn into `rect`, or a placeholder disc while it renders. +/// `tex` drawn into `rect`, or a placeholder disc while it renders fn thumbnail(painter: &egui::Painter, tex: Option<&egui::TextureHandle>, rect: egui::Rect, tk: &Tokens) { match tex { Some(t) => { @@ -648,8 +648,7 @@ fn thumbnail(painter: &egui::Painter, tex: Option<&egui::TextureHandle>, rect: e } } -/// A tile's hover popup: the `big` preview (the tile's `small` thumbnail scaled up until it -/// renders) over the label. +/// Use the thumbnail as a placeholder until the hover preview arrives fn hover_preview(ui: &mut Ui, small: Option<&egui::TextureHandle>, big: Option<&egui::TextureHandle>, label: &str) { let tk = Tokens::get(ui.ctx()); ui.set_max_width(BIG_PREVIEW_SIZE); diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index f8cc7e3b..a23ffb32 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -1,4 +1,4 @@ -//! What a shelf preview shows, and how to render it at any size. +//! Shelf assets and their preview renderers use std::sync::Arc; @@ -12,27 +12,26 @@ use texturecraft_engine::preview; use crate::preview_image::{alpha_image, image_preview, procedural_image, sphere_image, stroke_preview}; -/// The asset a shelf tile previews. +/// The asset a shelf tile previews pub enum ShelfPreview { - /// A built-in material or smart material on a sphere. + /// A built-in material or smart material on a sphere Material(&'static str), - /// A smart mask on the baked preview shape (only the preview worker can render it: see - /// [`crate::preview_request::PreviewRequest::render`]). + /// Smart mask rendering requires the worker's baked shape SmartMask(&'static str), - /// A library filter on a sample material on a sphere. + /// A library filter on a sample material on a sphere Filter(&'static str), - /// A procedural pattern as a grayscale swatch. + /// A procedural pattern as a grayscale swatch Procedural(ProceduralKind), - /// A library brush alpha, white on black. + /// A library brush alpha, white on black Alpha(&'static LibraryAlpha), - /// A brush preset's stroke along an S curve. + /// A brush preset's stroke along an S curve Brush(&'static BrushPreset), - /// An image resource by name. + /// An image resource by name Image(String, Arc), } impl ShelfPreview { - /// The cache key of the preview (one per asset). + /// The cache key of the preview (one per asset) pub fn key(&self) -> String { match self { ShelfPreview::Material(id) => format!("mat:{id}"), @@ -45,9 +44,8 @@ impl ShelfPreview { } } - /// The preview as a `size²` image (None for an unknown material or filter id). Smart masks are - /// None here: they need the baked preview shape, which only the preview worker holds, so the - /// UI thread never bakes. + /// Render a `size²` image; unknown assets return None + /// Smart masks return None here because their bake belongs to the worker pub fn image(&self, size: usize) -> Option { match self { ShelfPreview::Material(id) => Some(sphere_image(size, &preview::material(id, size)?)), @@ -70,7 +68,7 @@ mod tests { use super::*; - /// The hover preview's size at 100 % scale. + /// The hover preview's size at 100 % scale const BIG_PX: usize = 256; #[test] @@ -91,7 +89,6 @@ mod tests { assert!(image.pixels.iter().any(|c| c.a() > 0 && c.r().max(c.g()).max(c.b()) > 0), "{key}: something shows"); } - // The shaded spheres come from finite material values let finite = |samples: Vec>| { samples.iter().flatten().all(|s| s.base.iter().chain([&s.metallic, &s.roughness, &s.height]).all(|v| v.is_finite())) }; diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 982caa17..9ed4f73b 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -1,7 +1,6 @@ -//! Thumbnails: shelf previews (see [`crate::preview_image`]) cached as egui textures, plus small -//! shaded spheres and alpha previews drawn as shapes. New shelf thumbnails are rendered lazily, a -//! few per frame, so opening the shelf never stalls a frame; the smart mask thumbnails and the big -//! hover previews render on a worker. +//! Shelf and brush preview caches +//! Small synchronous renders are limited per frame +//! Smart masks and hover previews use [`PreviewWorker`] use std::collections::{HashMap, VecDeque}; @@ -17,39 +16,39 @@ use crate::preview_worker::PreviewWorker; use crate::shelf_preview::ShelfPreview; use crate::worker_preview::WorkerPreview; -/// Shelf thumbnails rendered per frame at most (the rest follow on the next frames). +/// Shelf thumbnails rendered per frame at most (the rest follow on the next frames) const PER_FRAME: usize = 2; -/// Shelf sphere and smart mask thumbnail size in pixels. +/// Shelf sphere and smart mask thumbnail size in pixels const SPHERE_PX: usize = 72; -/// Shelf procedural swatch size in pixels. +/// Shelf procedural swatch size in pixels const PROCEDURAL_PX: usize = 56; -/// Shelf alpha and brush stroke swatch size in pixels. +/// Shelf alpha and brush stroke swatch size in pixels const SWATCH_PX: usize = 64; -/// Image resource preview size in pixels. +/// Image resource preview size in pixels const IMAGE_PX: usize = 64; -/// Big hover previews kept at most (the least recently shown go first). +/// Big hover previews kept at most (the least recently shown go first) const BIG_PREVIEWS_KEPT: usize = 32; -/// The shelf's and the brush panel's preview textures. +/// The shelf's and the brush panel's preview textures #[derive(Default)] pub struct Thumbs { - /// Shelf thumbnails by [`ShelfPreview::key`]. + /// Shelf thumbnails by [`ShelfPreview::key`] shelf: HashMap, images: HashMap, - /// (frame, thumbnails rendered in it). + /// (frame, thumbnails rendered in it) budget: (u64, usize), - /// Renders the smart mask thumbnails and the big previews. + /// Renders the smart mask thumbnails and the big previews worker: PreviewWorker, - /// Worker-rendered previews by [`worker_key`]. + /// Worker-rendered previews by [`worker_key`] rendered: HashMap, - /// The keys of the big previews in `rendered`, least recently shown first. + /// The keys of the big previews in `rendered`, least recently shown first big_shown: VecDeque, - /// The frame that last took in the worker's results. + /// The frame that last took in the worker's results received_in_pass: u64, } impl Thumbs { - /// A larger cached texture of an image resource for the stencil overlay (up to 1024 px). + /// A larger cached texture of an image resource for the stencil overlay (up to 1024 px) pub fn stencil(&mut self, ctx: &egui::Context, name: &str, img: &texturecraft_engine::compose::ImageRes) -> TextureHandle { let key = format!("stencil:{name}"); if let Some(t) = self.images.get(&key) { @@ -70,7 +69,7 @@ impl Thumbs { t } - /// Cached preview of an image resource (64 px, letterboxed). + /// Cached preview of an image resource (64 px, letterboxed) pub fn image(&mut self, ctx: &egui::Context, name: &str, img: &texturecraft_engine::compose::ImageRes) -> TextureHandle { if let Some(t) = self.images.get(name) { return t.clone(); @@ -80,8 +79,7 @@ impl Thumbs { t } - /// A cached shelf thumbnail of `preview` at `size_px²`, rendering it if this frame's budget - /// allows (None until then; a repaint is requested so it follows shortly). + /// Render within the frame budget; deferred thumbnails request a repaint fn shelf(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { let key = preview.key(); if let Some(t) = self.shelf.get(&key) { @@ -105,8 +103,8 @@ impl Thumbs { Some(t) } - /// A worker-rendered `size_px²` image of `preview`, requested on the first call (None until it - /// arrives, and for good when it cannot be rendered); `hover` previews jump the worker's queue. + /// Request once per asset and size; return None while pending or after failure + /// Hover requests take priority in the native worker fn worker_rendered(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize, hover: bool) -> Option { self.receive(ctx); @@ -118,7 +116,7 @@ impl Thumbs { self.ready(&key) } - /// The worker-rendered preview under `key` if it arrived. + /// The worker-rendered preview under `key` if it arrived fn ready(&self, key: &str) -> Option { match self.rendered.get(key) { Some(WorkerPreview::Ready(t)) => Some(t.clone()), @@ -126,8 +124,7 @@ impl Thumbs { } } - /// Take in the worker's finished previews, once per frame (dropping the ones no longer - /// wanted). + /// Poll once per pass and discard results evicted from the cache fn receive(&mut self, ctx: &egui::Context) { let pass = ctx.cumulative_pass_nr(); if self.received_in_pass == pass { @@ -152,8 +149,7 @@ impl Thumbs { } } - /// The big hover preview of `preview`, `size_px²` (None until the worker renders it; the - /// least recently shown are dropped past [`BIG_PREVIEWS_KEPT`]). + /// Request a hover preview and evict the least recently shown beyond the cache limit pub fn big(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { let key = worker_key(&preview, size_px); self.big_shown.retain(|k| *k != key); @@ -167,45 +163,44 @@ impl Thumbs { self.worker_rendered(ctx, preview, size_px, true) } - /// The big preview of `preview` if the worker already rendered it (requests nothing). + /// The big preview of `preview` if the worker already rendered it (requests nothing) pub fn rendered_big(&mut self, ctx: &egui::Context, preview: &ShelfPreview, size_px: usize) -> Option { self.receive(ctx); self.ready(&worker_key(preview, size_px)) } - /// Sphere thumbnail of built-in material `id`. + /// Sphere thumbnail of built-in material `id` pub fn material(&mut self, ctx: &egui::Context, id: &'static str) -> Option { self.shelf(ctx, ShelfPreview::Material(id), SPHERE_PX) } - /// Thumbnail of smart mask `id` on the baked preview shape (None while the worker renders - /// it). + /// Smart mask thumbnail; None until the worker returns it pub fn smart_mask(&mut self, ctx: &egui::Context, id: &'static str) -> Option { self.worker_rendered(ctx, ShelfPreview::SmartMask(id), SPHERE_PX, false) } - /// Sphere thumbnail of library filter `id` applied to a sample material. + /// Sphere thumbnail of library filter `id` applied to a sample material pub fn filter(&mut self, ctx: &egui::Context, id: &'static str) -> Option { self.shelf(ctx, ShelfPreview::Filter(id), SPHERE_PX) } - /// Grayscale swatch of procedural `kind`. + /// Grayscale swatch of procedural `kind` pub fn procedural(&mut self, ctx: &egui::Context, kind: ProceduralKind) -> Option { self.shelf(ctx, ShelfPreview::Procedural(kind), PROCEDURAL_PX) } - /// White-on-black swatch of library alpha `alpha`. + /// White-on-black swatch of library alpha `alpha` pub fn alpha(&mut self, ctx: &egui::Context, alpha: &'static alphas::LibraryAlpha) -> Option { self.shelf(ctx, ShelfPreview::Alpha(alpha), SWATCH_PX) } - /// A brush preset's stroke along an S curve. + /// A brush preset's stroke along an S curve pub fn brush_preset(&mut self, ctx: &egui::Context, preset: &'static BrushPreset) -> Option { self.shelf(ctx, ShelfPreview::Brush(preset), SWATCH_PX) } } -/// The key of a worker-rendered preview: one per asset and size. +/// The key of a worker-rendered preview: one per asset and size fn worker_key(preview: &ShelfPreview, size_px: usize) -> String { format!("{}@{size_px}", preview.key()) } diff --git a/crates/ui-egui/src/worker_preview.rs b/crates/ui-egui/src/worker_preview.rs index 0252d69f..53767276 100644 --- a/crates/ui-egui/src/worker_preview.rs +++ b/crates/ui-egui/src/worker_preview.rs @@ -1,13 +1,12 @@ -//! A preview rendered by the [`crate::preview_worker::PreviewWorker`], as the thumbnail cache -//! tracks it. +//! Cached state of a worker-rendered preview use egui::TextureHandle; -/// Where a worker-rendered preview is. +/// A pending, ready or failed preview pub enum WorkerPreview { - /// Requested; the worker has not answered yet. + /// Requested; the worker has not answered yet Rendering, Ready(TextureHandle), - /// The asset is unknown or the worker could not render it (the tile keeps its placeholder). + /// The asset is unknown or the worker could not render it (the tile keeps its placeholder) Failed, } diff --git a/crates/ui-egui/tests/shelf_hover_preview.rs b/crates/ui-egui/tests/shelf_hover_preview.rs index 1bb9a4d7..460ed7c8 100644 --- a/crates/ui-egui/tests/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/shelf_hover_preview.rs @@ -1,5 +1,4 @@ -//! Hovering a shelf tile shows a big preview of the asset over its name, rendered once the pointer -//! rests on the tile. +//! Shelf hover previews render after a dwell and appear above the asset name use std::time::{Duration, Instant}; @@ -9,20 +8,19 @@ use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::shelf_preview::ShelfPreview; -/// The shelf's Materials tab. +/// The shelf's Materials tab const MATERIALS_TAB: usize = 0; -/// The hover preview's size in points (pixels at this scale). +/// Popup image size in logical points, independent of display scale const BIG_PREVIEW_SIZE: f32 = 256.0; -/// Simulated seconds per frame, fine enough to stop between the rest and the popup's delay. +/// Small time steps distinguish preview scheduling from popup visibility const STEP_SECONDS: f32 = 0.001; -/// The popup's delay (egui's tooltip delay) and the rest after which the big preview renders. +/// Simulated delays in seconds for the popup and preview request const POPUP_DELAY: f32 = 0.5; const REST: f32 = 0.1; -/// Real time the worker gets to render. +/// Real time the worker gets to render const WORKER_TIMEOUT: Duration = Duration::from_secs(60); -/// The app on the Materials tab, `step_seconds` per frame, and two materials whose names show -/// nowhere else. +/// Open the Materials tab and find two labels unique to shelf tiles fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static, TextureCraftApp>, Vec<&'static SmartMaterial>) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder() @@ -38,8 +36,7 @@ fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static (h, unique) } -/// The pixel size of the largest texture (not the font atlas) the last frame drew at least -/// `min_width` points wide. +/// Largest drawn texture in pixels, excluding fonts and images below `min_width` points fn largest_drawn_texture(h: &Harness<'_, TextureCraftApp>, min_width: f32) -> Option<[usize; 2]> { let textures = h.ctx.tex_manager(); let textures = textures.read(); @@ -51,7 +48,7 @@ fn largest_drawn_texture(h: &Harness<'_, TextureCraftApp>, min_width: f32) -> Op .max() } -/// Whether `material`'s big preview has arrived from the worker (asks for nothing). +/// Check the cache without submitting a preview request fn big_preview_ready(h: &mut Harness<'static, TextureCraftApp>, material: &SmartMaterial) -> bool { let ctx = h.ctx.clone(); h.state_mut().thumbs.rendered_big(&ctx, &ShelfPreview::Material(material.id), BIG_PREVIEW_SIZE as usize).is_some() @@ -65,7 +62,6 @@ fn hovering_a_shelf_tile_shows_its_big_preview() { assert!(largest_drawn_texture(&h, BIG_PREVIEW_SIZE).is_none(), "nothing big before the hover"); h.get_by_label(material.label).hover(); - // The popup's delay, then the worker let big_px = BIG_PREVIEW_SIZE as usize; let start = Instant::now(); while largest_drawn_texture(&h, BIG_PREVIEW_SIZE) != Some([big_px, big_px]) && start.elapsed() < WORKER_TIMEOUT { @@ -74,7 +70,6 @@ fn hovering_a_shelf_tile_shows_its_big_preview() { } assert_eq!(largest_drawn_texture(&h, BIG_PREVIEW_SIZE), Some([big_px, big_px]), "the popup draws the big preview"); - // The popup's name sits under the big image, below the tile let popup_name = h.get_all_by_label(material.label).map(|n| n.rect()).find(|r| r.min.y > tile.max.y).expect("the popup shows the name"); assert!(popup_name.min.y - tile.max.y >= BIG_PREVIEW_SIZE, "{popup_name:?} under {tile:?}"); } @@ -85,7 +80,7 @@ fn the_big_preview_renders_after_a_rest_but_not_during_a_sweep() { let (first, second) = (materials[0], materials[1]); let (from, to) = (h.get_by_label(first.label).rect().center(), h.get_by_label(second.label).rect().center()); - // A sweep: the pointer moves every frame across both tiles, then leaves the shelf + // Moving every frame must never satisfy the dwell delay let sweep_frames = 40; for frame in 0..=sweep_frames { h.hover_at(from.lerp(to, frame as f32 / sweep_frames as f32)); @@ -97,7 +92,7 @@ fn the_big_preview_renders_after_a_rest_but_not_during_a_sweep() { h.run_steps(1); assert!(!big_preview_ready(&mut h, first) && !big_preview_ready(&mut h, second), "a sweep renders nothing"); - // A rest: the preview renders before the popup opens + // A stationary pointer should start rendering before the popup opens h.hover_at(from); h.run_steps((REST * 1.2 / STEP_SECONDS) as usize); let start = Instant::now(); @@ -113,6 +108,41 @@ fn the_big_preview_renders_after_a_rest_but_not_during_a_sweep() { assert_eq!(h.query_all_by_label(first.label).count(), 1, "the popup is not open yet"); } +#[test] +fn scrolling_with_a_stationary_pointer_defers_the_big_preview() { + let (mut harness, materials) = materials_shelf(STEP_SECONDS, 1.0); + let material = materials[0]; + harness.get_by_label(material.label).hover(); + + // Scroll toward the top boundary to keep the same tile beneath the pointer + for _ in 0..(REST * 2.0 / STEP_SECONDS) as usize { + harness.input_mut().events.push(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, 10.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: egui::Modifiers::NONE, + }); + harness.run_steps(1); + } + assert!(harness.ctx.input(|input| input.pointer.time_since_last_movement()) >= REST, "the pointer stayed still beyond the dwell delay"); + assert_eq!(harness.query_all_by_label(material.label).count(), 1, "scrolling suppresses the popup"); + + harness.hover_at(egui::pos2(900.0, 500.0)); + harness.run_steps(1); + std::thread::sleep(Duration::from_secs(1)); + harness.run_steps(1); + assert!(!big_preview_ready(&mut harness, material), "scrolling must not submit a hover preview"); + + harness.get_by_label(material.label).hover(); + let started = Instant::now(); + while !big_preview_ready(&mut harness, material) && started.elapsed() < WORKER_TIMEOUT { + harness.run_steps(1); + std::thread::sleep(Duration::from_millis(10)); + } + assert!(big_preview_ready(&mut harness, material), "the preview renders after scrolling and pointer movement stop"); +} + #[test] fn high_dpi_smart_mask_hover_stays_within_the_renderer_limit() { use texturecraft_engine::mask_preview::MAX_PREVIEW_SIZE_PX;