From 34ba091e8a2e6049ca50be177fcb21500ca01743 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Thu, 5 Nov 2026 20:44:48 +0000 Subject: [PATCH] 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.