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