From 098602ec49483222a71cf6cdb3c98875f54f851a Mon Sep 17 00:00:00 2001 From: Agapenordev <120006055+Agapenordev@users.noreply.github.com> Date: Sun, 1 Nov 2026 21:05:50 +0100 Subject: [PATCH 01/60] Never crash importing meshes with many materials MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every texture set (one per mesh material) allocated full-size display textures (base color, emissive, ORM, normal, height, aux, with mips) as soon as it was created: ~130 MB of GPU memory per set at the default 2048 import size. A 16-material OBJ ran a 4 GB laptop GPU out of memory and wgpu's default error handler panicked, closing the app. - Display and aux textures start as 1×1 neutral placeholders and get their full size with the first non-neutral tile (or aux image), so an import costs no GPU memory until its sets are painted. - That allocation runs in an error scope: on failure the texture keeps its placeholder (no retry per tile), the failure is logged and the UI shows a toast naming the texture set and the Viewport ▸ Texture resolution setting. Painting and export are unaffected. - The app installs an uncaptured-error handler that logs and reports wgpu errors as toasts instead of panicking. - The GPU path tracer takes each set's size from its largest texture, since any kind (base color included) may now be a placeholder. Tests: 40 sets of 2048 allocate nothing until painted, one painted kind allocates alone, the aux texture allocates on its first upload, painted placeholders render, and the GPU tracer matches the CPU with a default base color beside varying roughness (fails with the old size logic). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/automation/src/render.rs | 2 +- crates/render/Cargo.toml | 1 + crates/render/src/gpu_trace.rs | 40 ++++++++++- crates/render/src/renderer.rs | 110 +++++++++++++++++++++-------- crates/render/tests/headless.rs | 44 ++++++++++++ crates/ui-egui/src/gpu.rs | 45 +++++++++++- crates/ui-egui/src/i18n/de.rs | 5 ++ crates/ui-egui/src/i18n/es.rs | 5 ++ crates/ui-egui/src/i18n/fr.rs | 5 ++ crates/ui-egui/src/i18n/it.rs | 5 ++ crates/ui-egui/src/i18n/ja.rs | 5 ++ crates/ui-egui/src/i18n/ko.rs | 5 ++ crates/ui-egui/src/i18n/pt_br.rs | 5 ++ crates/ui-egui/src/i18n/zh_hans.rs | 5 ++ crates/ui-egui/src/viewport.rs | 16 +++++ 16 files changed, 265 insertions(+), 34 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index eaa5c6d6..e5d4279f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3970,6 +3970,7 @@ dependencies = [ "bytemuck", "half", "image", + "log", "pollster 0.4.0", "rayon", "texturecraft-bake", diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index e98ccbf9..4621d6a0 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -77,7 +77,7 @@ impl Gpu { _ => None, }; if let Some(rgba) = aux { - h.renderer.upload_aux(&h.queue, ts, res, &rgba); + h.renderer.upload_aux(&h.device, &h.queue, ts, res, &rgba); } } } diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 95b91c29..b287a19f 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -17,6 +17,7 @@ texturecraft-bake = { workspace = true } wgpu = { workspace = true } bytemuck = { workspace = true } half = { workspace = true } +log = { workspace = true } rayon = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 4ea0f472..0f25ed4f 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -439,7 +439,8 @@ impl GpuTracer { let mut info: Vec<[f32; 3]> = sets .iter() .map(|s| { - let dims = s.first().map_or((1, 1), |t| (t.width(), t.height())); + // The set's size is its largest texture's; any kind may still be a 1×1 placeholder. + let dims = s.iter().fold((1, 1), |(w, h), t| (t.width().max(w), t.height().max(h))); let small = s.iter().enumerate().filter(|(_, t)| (t.width(), t.height()) != dims).fold(0u32, |m, (k, _)| m | 1 << k); [dims.0 as f32, dims.1 as f32, small as f32] }) @@ -821,6 +822,43 @@ mod tests { } } + #[test] + fn gpu_reads_full_size_channels_beside_placeholders() { + // Base color stays at its default (a 1×1 placeholder texture) while roughness varies + // across the surface (a full-size texture): the tracer must still read every texel of it. + use Channel::*; + let Some((mut h, mut t)) = gpu() else { return }; + let mut composite = Composite::new(&[Roughness, Metallic], 64); + for y in 0..64 { + for x in 0..64 { + let rough = if x < 32 { 0.05 } else { 0.9 }; + composite.channels.get_mut(&Roughness).unwrap().set(x, y, &[texturecraft_texel::to_u16(rough)]); + composite.channels.get_mut(&Metallic).unwrap().set(x, y, &[texturecraft_texel::to_u16(1.0)]); + } + } + h.renderer.set_texture_sets(&h.device, &h.queue, &[((64, 64), 0)], 1); + for (tx, ty) in all_tiles(64, 64) { + for k in DisplayKind::ALL { + h.renderer.upload_tile(&h.device, &h.queue, 0, k, tx, ty, &tile_bytes(&composite, &BakedMaps::default(), k, tx, ty)); + } + } + let sizes: Vec = h.renderer.display_textures()[0].iter().map(|t| t.width()).collect(); + assert_eq!(sizes[0], 1, "base color stays a placeholder"); + assert_eq!(sizes[1], 64, "roughness and metallic are full size"); + let mesh = Arc::new(primitives::sphere(1.0, 32, 16)); + let bvh = Arc::new(Bvh::new(&mesh)); + let env = crate::ibl::environment("Studio Contrast", 256); + let scene = TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0 }], Arc::new(env), 0.0); + let d = TraceDisplay { exposure: 1.0, aces: true, env_opacity: 0.5, denoise: false }; + let settings = TraceSettings { bounces: 4 }; + let (_, _, gpu) = t.render(&h.device, &h.queue, &h.renderer, &scene, &camera(), &settings, &d, [48, 36], 1024).unwrap(); + let mut cpu = Tracer::new(48, 36); + for _ in 0..1024 { + cpu.pass(&scene, &camera(), &settings); + } + assert_region_means_match("varying roughness, default base color", &gpu, &cpu.rgba8(&d), 48, 36, 3.0); + } + /// Mean luminance of each 6×6 block of two RGBA8 renders agrees within `tol` 8-bit levels. fn assert_region_means_match(name: &str, a: &[u8], b: &[u8], w: usize, h: usize, tol: f32) { let lum = |img: &[u8], x: usize, y: usize| { diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 5fd4ac14..d840a998 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -30,6 +30,7 @@ use texturecraft_geom::glam::{Mat4, Vec3}; use texturecraft_geom::{Mesh, OrbitCamera}; use texturecraft_texel::TILE; +use crate::gpu_trace::scoped; use crate::ibl; use crate::subdivide::{self, Vertex}; @@ -327,10 +328,15 @@ struct SetGpu { /// Display textures hold the set at `size >> shift`: halved until they fit the device. shift: u32, /// The display textures in [`DisplayKind::ALL`] order, then the aux (mesh map) texture. - /// [`lazy`] kinds stay 1×1 until a tile with a non-default value arrives. + /// Each starts as a 1×1 neutral placeholder and gets its full size with the first tile (or + /// aux image) that holds something else, so a mesh with many materials costs no GPU memory + /// until its sets are painted. tex: Vec, bind_group: wgpu::BindGroup, mips_dirty: Vec, + /// Textures whose full-size allocation failed (out of GPU memory): they keep their + /// placeholder until the set is re-created, instead of retrying on every tile. + failed: Vec, } /// Vertex and index buffers with their draws (first index, count, material). @@ -477,6 +483,9 @@ pub struct Renderer { black: wgpu::TextureView, /// [`DisplayKind::default_texel`] in [`DisplayKind::ALL`] order. default_texels: Vec>, + /// Texture sets whose display textures could not be allocated (out of GPU memory) since + /// [`Renderer::take_memory_failures`]. + memory_failures: Vec, accum_pipeline: wgpu::RenderPipeline, env: Tex, env_name: String, @@ -530,11 +539,8 @@ pub(crate) fn display_format(k: DisplayKind) -> wgpu::TextureFormat { } } -/// Textures of the optional lobe channels: most sets never use them, so they cost no memory or -/// bandwidth (a 1×1 neutral texture) until painted. -fn lazy(k: DisplayKind) -> bool { - matches!(k, DisplayKind::Lobes | DisplayKind::Sheen | DisplayKind::Extra) -} +/// Texel of the aux texture before a mesh map or mask is shown. +const AUX_NEUTRAL: [u8; 4] = [128, 128, 128, 255]; /// A `w × h` texture filled with `texel`. fn neutral_tex(device: &wgpu::Device, queue: &wgpu::Queue, (w, h): (u32, u32), format: wgpu::TextureFormat, mips: u32, texel: &[u8]) -> Tex { @@ -557,6 +563,14 @@ fn neutral_tex(device: &wgpu::Device, queue: &wgpu::Queue, (w, h): (u32, u32), f t } +/// Record that texture set `ts` could not get a display texture (`error` says which). +fn memory_failed(failures: &mut Vec, ts: usize, error: &str) { + log::warn!("cannot allocate the display texture of {error}"); + if !failures.contains(&ts) { + failures.push(ts); + } +} + /// Bytes per write when filling a texture with one texel. const NEUTRAL_BAND_BYTES: usize = 8 << 20; @@ -946,6 +960,7 @@ impl Renderer { shadow, black, default_texels: DisplayKind::ALL.map(DisplayKind::default_texel).to_vec(), + memory_failures: Vec::new(), env, env_name: String::new(), sh: [[0.0; 4]; 9], @@ -1077,20 +1092,13 @@ impl Renderer { if self.sets.get(i).is_some_and(|s| s.size == size && s.shift == shift) { continue; } - let dims = display_dims(size, shift); - let mut tex: Vec = DisplayKind::ALL - .iter() - .zip(&self.default_texels) - .map(|(k, texel)| { - let (d, mips) = if lazy(*k) { ((1, 1), 1) } else { (dims, mip_count(dims.0.max(dims.1))) }; - neutral_tex(device, queue, d, display_format(*k), mips, texel) - }) - .collect(); - let aux = aux_size(size); - tex.push(neutral_tex(device, queue, (aux, aux), wgpu::TextureFormat::Rgba8Unorm, mip_count(aux), &[128, 128, 128, 255])); + // Placeholders only: full-size textures come with the first non-neutral upload. + let mut tex: Vec = + DisplayKind::ALL.iter().zip(&self.default_texels).map(|(k, texel)| neutral_tex(device, queue, (1, 1), display_format(*k), 1, texel)).collect(); + tex.push(neutral_tex(device, queue, (1, 1), wgpu::TextureFormat::Rgba8Unorm, 1, &AUX_NEUTRAL)); let bind_group = set_bind_group(device, &self.set_bgl, &self.sampler, &tex); let n = tex.len(); - let gpu = SetGpu { size, shift, tex, bind_group, mips_dirty: vec![true; n] }; + let gpu = SetGpu { size, shift, tex, bind_group, mips_dirty: vec![true; n], failed: vec![false; n] }; if i < self.sets.len() { self.sets[i] = gpu; } else { @@ -1119,16 +1127,27 @@ impl Renderer { return; } let dims = display_dims(set.size, set.shift); - if t.texture.width() < dims.0 { - // A lazy placeholder: neutral tiles change nothing, the first real one allocates it. - if bytes.chunks_exact(texel.len()).all(|px| px == texel.as_slice()) { + if t.texture.width() < dims.0 || t.texture.height() < dims.1 { + // A placeholder: neutral tiles change nothing, the first real one allocates it. + if set.failed.get(ki).copied().unwrap_or(true) || bytes.chunks_exact(texel.len()).all(|px| px == texel.as_slice()) { return; } - let full = neutral_tex(device, queue, dims, display_format(kind), mip_count(dims.0.max(dims.1)), texel); - if let Some(slot) = set.tex.get_mut(ki) { - *slot = full; + let what = format!("texture set {} ({kind:?}, {}×{})", ts + 1, dims.0, dims.1); + match scoped(device, &what, || neutral_tex(device, queue, dims, display_format(kind), mip_count(dims.0.max(dims.1)), texel)) { + Ok(full) => { + if let Some(slot) = set.tex.get_mut(ki) { + *slot = full; + } + set.bind_group = set_bind_group(device, &self.set_bgl, &self.sampler, &set.tex); + } + Err(e) => { + if let Some(f) = set.failed.get_mut(ki) { + *f = true; + } + memory_failed(&mut self.memory_failures, ts, &e); + return; + } } - set.bind_group = set_bind_group(device, &self.set_bgl, &self.sampler, &set.tex); } let Some(t) = set.tex.get(ki) else { return }; // Downscaled sets take every `step`-th texel of the tile. @@ -1158,14 +1177,39 @@ impl Renderer { } } - /// Upload the aux (mesh map / debug) texture of a set: RGBA8, `size × size`. - pub fn upload_aux(&mut self, queue: &wgpu::Queue, ts: usize, size: u32, rgba: &[u8]) { + /// Upload the aux (mesh map / debug) texture of a set: RGBA8, `size × size` with `size` from + /// [`aux_size`]. The first upload allocates it. + pub fn upload_aux(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, ts: usize, size: u32, rgba: &[u8]) { let Some(set) = self.sets.get_mut(ts) else { return }; + let want = aux_size(set.size); + let ai = set.tex.len().saturating_sub(1); let Some(t) = set.tex.last() else { return }; - let (w, h) = (t.texture.width(), t.texture.height()); - if size != w || rgba.len() < (w * h * 4) as usize { + if size != want || rgba.len() < (size as usize) * (size as usize) * 4 { return; } + if t.texture.width() != size { + if set.failed.get(ai).copied().unwrap_or(true) { + return; + } + let what = format!("texture set {} (mesh map view, {size}×{size})", ts + 1); + match scoped(device, &what, || neutral_tex(device, queue, (size, size), wgpu::TextureFormat::Rgba8Unorm, mip_count(size), &AUX_NEUTRAL)) { + Ok(full) => { + if let Some(slot) = set.tex.last_mut() { + *slot = full; + } + set.bind_group = set_bind_group(device, &self.set_bgl, &self.sampler, &set.tex); + } + Err(e) => { + if let Some(f) = set.failed.get_mut(ai) { + *f = true; + } + memory_failed(&mut self.memory_failures, ts, &e); + return; + } + } + } + let Some(t) = set.tex.last() else { return }; + let (w, h) = (t.texture.width(), t.texture.height()); queue.write_texture( wgpu::TexelCopyTextureInfo { texture: &t.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, rgba, @@ -1178,7 +1222,13 @@ impl Renderer { } } - /// Size of the aux texture of a set. + /// Texture sets whose display textures could not be allocated since the last call (out of + /// GPU memory: they show neutral values where they could not be allocated). + pub fn take_memory_failures(&mut self) -> Vec { + std::mem::take(&mut self.memory_failures) + } + + /// Size of the aux texture of a set (1 until a mesh map or mask was shown). pub fn aux_size(&self, ts: usize) -> Option { self.sets.get(ts).and_then(|s| s.tex.last()).map(|t| t.texture.width()) } diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 8ef1b897..864c70c3 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -734,3 +734,47 @@ fn refraction_shows_the_scene_behind_transmissive_surfaces() { let frosted = render(&mut h, &refr, "refr_frosted_checker"); assert!(detail(&frosted, &ball) < detail(&clear, &ball), "frosted glass blurs the scene behind"); } + +/// Kinds in [`DisplayKind::ALL`] order with each set's display texture widths, then the aux width. +fn widths(h: &Headless) -> Vec> { + h.renderer.display_textures().iter().map(|s| s.iter().map(|t| t.width()).collect()).collect() +} + +#[test] +fn texture_sets_take_no_gpu_memory_until_painted() { + // A mesh with many materials (one texture set each) must not reserve full-size textures + // for every set up front: that ran a 4 GB GPU out of memory, and wgpu's handler aborted. + let Some((mut h, _)) = setup() else { return }; + let sets: Vec<((u32, u32), usize)> = (0..40).map(|m| ((2048, 2048), m)).collect(); + h.renderer.set_texture_sets(&h.device, &h.queue, &sets, 40); + assert!(widths(&h).iter().flatten().all(|w| *w == 1), "every display texture starts as a 1×1 placeholder"); + assert!((0..40).all(|ts| h.renderer.aux_size(ts) == Some(1)), "so does every aux texture"); + // A neutral tile changes nothing; the first painted one allocates that kind alone. + let kind = DisplayKind::BaseColor; + let neutral = kind.default_texel().repeat(64 * 64); + h.renderer.upload_tile(&h.device, &h.queue, 3, kind, 0, 0, &neutral); + assert_eq!(widths(&h)[3][0], 1); + h.renderer.upload_tile(&h.device, &h.queue, 3, kind, 0, 0, &[200, 30, 30, 255].repeat(64 * 64)); + let w = widths(&h); + assert_eq!(w[3][0], 2048, "the painted kind is full size"); + assert!(w[3][1..].iter().all(|w| *w == 1) && w[2].iter().all(|w| *w == 1), "nothing else was allocated"); + // The aux texture is allocated by its first upload, at the set's aux size only. + h.renderer.upload_aux(&h.device, &h.queue, 3, 512, &[0; 512 * 512 * 4]); + assert_eq!(h.renderer.aux_size(3), Some(1), "a wrong aux size is ignored"); + h.renderer.upload_aux(&h.device, &h.queue, 3, 2048, &[90; 2048 * 2048 * 4]); + assert_eq!(h.renderer.aux_size(3), Some(2048)); + assert!(h.renderer.take_memory_failures().is_empty()); +} + +#[test] +fn painted_placeholders_render_like_full_textures() { + // A set painted in one kind renders that paint whether the other kinds are placeholders. + let Some((mut h, frame)) = setup() else { return }; + let before = render(&mut h, &frame, "placeholders"); + fill(&mut h, &[0, 1], DisplayKind::BaseColor, &[220, 40, 40, 255]); + let red = render(&mut h, &frame, "painted_base_color"); + let (w, hgt) = (frame.size[0], frame.size[1]); + let [r0, g0, _] = before.at(w / 2, hgt / 2); + let [r1, g1, _] = red.at(w / 2, hgt / 2); + assert!(r1 > r0 && g1 < g0, "the painted base color shows: {:?} → {:?}", before.at(w / 2, hgt / 2), red.at(w / 2, hgt / 2)); +} diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 97c952a8..e94056f1 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -43,11 +43,25 @@ pub struct GpuState { pub renderer: Renderer, /// Raised when texture-set textures were recreated: the UI must upload every tile again. pub reset: Arc, + pub reports: Arc>, } +/// Problems the GPU side hands to the UI, which shows them as toasts. +#[derive(Default)] +pub struct GpuReports { + /// Texture sets whose display textures could not be allocated (out of GPU memory). + pub memory: Vec, + /// wgpu errors no error scope caught (logged instead of wgpu's default panic). + pub errors: Vec, +} + +/// Most distinct uncaptured GPU errors kept until the UI shows them. +const MAX_GPU_ERRORS: usize = 8; + /// UI-side bookkeeping of what the GPU already has. pub struct GpuLink { pub reset: Arc, + pub reports: Arc>, /// Raised when a view callback was dropped before the GPU applied its scene sync (the /// frame was never painted, e.g. a WebGPU surface not ready yet): send everything again. pub lost: Arc, @@ -80,11 +94,24 @@ const UPLOAD_MS_PER_TILE: f64 = 0.006; pub fn init(rs: &egui_wgpu::RenderState) -> GpuLink { let reset = Arc::new(AtomicBool::new(false)); + let reports = Arc::new(Mutex::new(GpuReports::default())); + // wgpu's default handler panics on any error no scope caught (an out-of-memory texture, a + // driver hiccup): report it instead, so the user keeps the session. + let sink = reports.clone(); + rs.device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| { + log::error!("GPU error: {e}"); + let mut r = sink.lock().unwrap_or_else(PoisonError::into_inner); + let text = e.to_string(); + if r.errors.len() < MAX_GPU_ERRORS && !r.errors.contains(&text) { + r.errors.push(text); + } + })); let renderer = Renderer::new(&rs.device, &rs.queue, rs.target_format); - rs.renderer.write().callback_resources.insert(GpuState { renderer, reset: reset.clone() }); + rs.renderer.write().callback_resources.insert(GpuState { renderer, reset: reset.clone(), reports: reports.clone() }); let info = rs.adapter.get_info(); GpuLink { reset, + reports, lost: Arc::new(AtomicBool::new(false)), mesh_id: 0, sets: Vec::new(), @@ -97,6 +124,11 @@ pub fn init(rs: &egui_wgpu::RenderState) -> GpuLink { } impl GpuLink { + /// What the GPU side reported since the last call (see [`GpuReports`]). + pub fn take_reports(&self) -> GpuReports { + std::mem::take(&mut *self.reports.lock().unwrap_or_else(PoisonError::into_inner)) + } + /// Collect everything the GPU needs this frame (runs the compositor first). /// Compositing progress (0..1) while tiles wait to be composited. pub fn composite_progress(&self, s: &Session) -> Option { @@ -264,7 +296,16 @@ impl CallbackTrait for ViewCallback { gpu.renderer.upload_tile(device, queue, *ts, *k, *tx, *ty, bytes); } for (ts, size, bytes) in &sync.aux { - gpu.renderer.upload_aux(queue, *ts, *size, bytes); + gpu.renderer.upload_aux(device, queue, *ts, *size, bytes); + } + let failed = gpu.renderer.take_memory_failures(); + if !failed.is_empty() { + let mut r = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner); + for ts in failed { + if !r.memory.contains(&ts) { + r.memory.push(ts); + } + } } } gpu.renderer.prepare(device, queue, encoder, &self.frame); diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ce534a6f..dd5cfe38 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -979,4 +979,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Fensterrahmen und Fenstertasten des Betriebssystems statt der eigenen Titelleiste von TextureCraft verwenden", ), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower Settings ▸ Viewport ▸ Texture resolution. Painting and export are not affected.", + "Nicht genug GPU-Speicher, um das Texturset \"{name}\" vollständig anzuzeigen: Einstellungen ▸ Ansichtsfenster ▸ Texturauflösung verringern. Malen und Export sind nicht betroffen.", + ), + ("GPU error: {error}", "GPU-Fehler: {error}"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 2b57afd8..e3e413c6 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -964,4 +964,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Usar el marco y los botones de ventana del sistema operativo en lugar de la barra de título propia de TextureCraft", ), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower Settings ▸ Viewport ▸ Texture resolution. Painting and export are not affected.", + "No hay suficiente memoria de GPU para mostrar el conjunto de texturas \"{name}\" por completo: reduce Ajustes ▸ Ventana gráfica ▸ Resolución de texturas. La pintura y la exportación no se ven afectadas.", + ), + ("GPU error: {error}", "Error de GPU: {error}"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 0e72b031..3a54805a 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -979,4 +979,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Utiliser le cadre et les boutons de fenêtre du système d'exploitation au lieu de la barre de titre de TextureCraft", ), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower Settings ▸ Viewport ▸ Texture resolution. Painting and export are not affected.", + "Mémoire GPU insuffisante pour afficher entièrement l'ensemble de textures \"{name}\" : réduisez Paramètres ▸ Affichage ▸ Résolution des textures. La peinture et l'export ne sont pas affectés.", + ), + ("GPU error: {error}", "Erreur GPU : {error}"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 9260b188..9f33c0e3 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -973,4 +973,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Usa la cornice e i pulsanti della finestra del sistema operativo invece della barra del titolo di TextureCraft", ), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower Settings ▸ Viewport ▸ Texture resolution. Painting and export are not affected.", + "Memoria GPU insufficiente per mostrare per intero il set di texture \"{name}\": riduci Impostazioni ▸ Viewport ▸ Risoluzione texture. Pittura ed esportazione non sono interessate.", + ), + ("GPU error: {error}", "Errore GPU: {error}"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 2e333ab9..169c749b 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -946,4 +946,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "TextureCraft 独自のタイトルバーの代わりに、OS のウィンドウ枠とボタンを使います", ), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower Settings ▸ Viewport ▸ Texture resolution. Painting and export are not affected.", + "GPU メモリが不足しているため、テクスチャセット「{name}」を完全には表示できません:設定 ▸ ビューポート ▸ テクスチャ解像度 を下げてください。ペイントと書き出しには影響しません。", + ), + ("GPU error: {error}", "GPU エラー: {error}"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 3945c9a9..d67fa29d 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -931,4 +931,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "TextureCraft 자체 제목 표시줄 대신 운영 체제의 창 테두리와 버튼을 사용합니다", ), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower Settings ▸ Viewport ▸ Texture resolution. Painting and export are not affected.", + "GPU 메모리가 부족하여 텍스처 세트 \"{name}\"을(를) 모두 표시할 수 없습니다: 설정 ▸ 뷰포트 ▸ 텍스처 해상도를 낮추세요. 페인팅과 내보내기에는 영향이 없습니다.", + ), + ("GPU error: {error}", "GPU 오류: {error}"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 788df7f9..146a6c19 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -961,4 +961,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Usar a moldura e os botões de janela do sistema operacional em vez da barra de título própria do TextureCraft", ), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower Settings ▸ Viewport ▸ Texture resolution. Painting and export are not affected.", + "Memória de GPU insuficiente para mostrar o conjunto de texturas \"{name}\" por completo: reduza Configurações ▸ Viewport ▸ Resolução das texturas. A pintura e a exportação não são afetadas.", + ), + ("GPU error: {error}", "Erro de GPU: {error}"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 3de5246c..92158583 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -877,4 +877,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "使用操作系统的窗口边框和按钮,而不是 TextureCraft 自己的标题栏", ), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower Settings ▸ Viewport ▸ Texture resolution. Painting and export are not affected.", + "GPU 内存不足,无法完整显示纹理集“{name}”:请降低 设置 ▸ 视口 ▸ 纹理分辨率。绘制和导出不受影响。", + ), + ("GPU error: {error}", "GPU 错误:{error}"), ]; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 06011755..76e97d06 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -95,6 +95,20 @@ fn shade(app: &TextureCraftApp) -> Shade { } } +/// Show what the GPU side reported (each message once while its toast is up). +fn gpu_report_toasts(app: &mut TextureCraftApp, reports: crate::gpu::GpuReports) { + let names: Vec = reports.memory.iter().filter_map(|ts| app.session.doc.project.texture_sets.get(*ts).map(|t| t.name.clone())).collect(); + let texts = names + .iter() + .map(|name| trf("Not enough GPU memory to show texture set \"{name}\" fully: lower Settings ▸ Viewport ▸ Texture resolution. Painting and export are not affected.", &[("name", name)])) + .chain(reports.errors.iter().map(|e| trf("GPU error: {error}", &[("error", e)]))); + for text in texts.collect::>() { + if !app.toasts.iter().any(|t| t.text == text) { + app.toast(text, true); + } + } +} + /// This frame's scene sync (compositing and GPU uploads), run by the first view drawn, after /// that view handled its input: a stroke shows in the frame it is painted, not the next. pub struct PendingSync(Option>); @@ -105,7 +119,9 @@ fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, frame: Frame, sy (Some(aux), Some(g)) => { let t0 = crate::now_ms(); let scene = g.sync(&mut app.session, aux, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms)); + let reports = g.take_reports(); app.profiler.sync_ms += (crate::now_ms() - t0) as f32; + gpu_report_toasts(app, reports); // Display tiles left for later frames (the frame budget ran out). if app.session.caches.iter().any(|c| !c.upload.is_empty()) { ui.ctx().request_repaint(); From ae211ff5901981189ad2ce9bb30a797fe3255b9e Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sun, 1 Nov 2026 15:09:02 -0500 Subject: [PATCH 02/60] feat(export): MaterialX (.mtlx) OpenPBR material per texture set file.exportTextures takes `materialX: true` and, next to the textures, writes one `_.mtlx` per texture set: an open_pbr_surface whose inputs read tiledimage nodes, inside a surfacematerial. It follows the "OpenPBR (separate maps)" preset's inputs (base, metalness, roughness, anisotropy, coat, fuzz, transmission, subsurface, emission, opacity, normal through a normalmap node, height as a displacement shader). Colour maps are tagged srgb_texture; data maps are linear. UDIM sets use the filename token. A set with no OpenPBR map, or DirectX normals (the normalmap node reads OpenGL), is reported in `warnings`. Written from the ASWF MaterialX 1.39 and OpenPBR Surface specifications, in pure Rust with no MaterialX library. Engine tests cover a two-set export, UDIM and the off/warn paths. Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 2 +- crates/engine/src/file_cmds.rs | 46 +++++- crates/engine/tests/materialx.rs | 74 +++++++++ crates/formats/src/lib.rs | 2 + crates/formats/src/materialx.rs | 275 +++++++++++++++++++++++++++++++ 5 files changed, 396 insertions(+), 3 deletions(-) create mode 100644 crates/engine/tests/materialx.rs create mode 100644 crates/formats/src/materialx.rs diff --git a/ROADMAP.md b/ROADMAP.md index b739669d..6e7a41ea 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -19,7 +19,7 @@ end to end today (engine + UI + automation + tests), not what is planned. | Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — | | Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Hardware ray tracing | | Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — | -| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, `$udim` tiles, OBJ, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | +| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, `$udim` tiles, **MaterialX** (`file.exportTextures` with `materialX`: a `.mtlx` OpenPBR material per set, `` aware), OBJ, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | | UI and UX | 8 | 95% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, **shortcut editor** with conflict detection, tooltips with shortcuts; all menu items live ([docs/parity.md](docs/parity.md)); **9 UI languages** with CJK fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations | | Platforms | 4 | 75% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish | | **Total** | **100** | **≈ 93%** | | | diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 32ae6b49..f489582c 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -42,7 +42,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset)} → {files, warnings}", always, export_textures ), @@ -418,11 +418,53 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { std::fs::create_dir_all(&dir).map_err(|e| bad("file.exportTextures", format!("cannot create {dir}: {e}")))?; let files = s.export_files(&sets, &opts)?; let warnings: Vec = files.iter().flat_map(|f| f.warnings.iter().cloned()).collect(); - let written = texturecraft_formats::write_files(&files, std::path::Path::new(&dir)).map_err(fe)?; + let mut warnings = warnings; + let mut written = texturecraft_formats::write_files(&files, std::path::Path::new(&dir)).map_err(fe)?; + if p.get("materialX").and_then(Value::as_bool).unwrap_or(false) { + written.extend(write_materialx(s, &sets, &opts, std::path::Path::new(&dir), &mut warnings)?); + } s.log.push(format!("Exported {} textures to {dir}", written.len())); Ok(json!({ "files": written.iter().map(|p| p.display().to_string()).collect::>(), "warnings": warnings })) } +/// One `_.mtlx` per texture set, next to the textures `opts` just wrote: the +/// OpenPBR inputs those textures feed (see `texturecraft_formats::materialx`). UDIM sets name +/// their files with the `` token. Sets with no recognised map are skipped with a warning. +#[cfg(not(target_arch = "wasm32"))] +fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std::path::Path, warnings: &mut Vec) -> Result> { + use texturecraft_formats::materialx::{self, Texture}; + let mesh_name = stem_of(s.doc.project.mesh.trim_start_matches("builtin:")); + if opts.normal_format == Some(NormalFormat::DirectX) { + warnings.push("MaterialX: the normalmap node reads OpenGL (+Y) normals; this export wrote DirectX normals, so flip the green channel".into()); + } + let mut out = Vec::new(); + for &ts in sets { + let set = s.doc.project.texture_set(ts).map_err(|e| EngineError::Other(e.to_string()))?; + let mut textures: Vec = Vec::new(); + for f in texturecraft_formats::list_outputs(&s.doc.project, ts, &mesh_name, opts).map_err(fe)? { + let Some(input) = opts.preset.maps.get(f.map).and_then(|m| materialx::input_of_template(&m.file)) else { continue }; + // The first tile stands for all of them: 1001 -> . + let file = match f.tile { + Some(t) => f.name.replacen(&format!(".{t}."), "..", 1), + None => f.name.clone(), + }; + if !textures.iter().any(|t| t.input == input) { + textures.push(Texture { input: input.to_owned(), file }); + } + } + if textures.is_empty() { + warnings.push(format!("MaterialX: texture set \"{}\" has no OpenPBR maps; use the \"OpenPBR (separate maps)\" preset", set.name)); + continue; + } + let stem = texturecraft_formats::export::sanitize_file_stem(&format!("{mesh_name}_{}", set.name)); + let path = dir.join(format!("{stem}.mtlx")); + std::fs::write(&path, materialx::write(&format!("{mesh_name}_{}", set.name), &textures, None)) + .map_err(|e| bad("file.exportTextures", format!("cannot write {}: {e}", path.display())))?; + out.push(path); + } + Ok(out) +} + #[cfg(not(target_arch = "wasm32"))] fn export_mesh(s: &mut Session, p: &Value) -> Result { let path = native::path_param(p, "path", "file.exportMesh")?; diff --git a/crates/engine/tests/materialx.rs b/crates/engine/tests/materialx.rs new file mode 100644 index 00000000..02de5528 --- /dev/null +++ b/crates/engine/tests/materialx.rs @@ -0,0 +1,74 @@ +//! `file.exportTextures` with `materialX: true`: a `.mtlx` OpenPBR material next to the textures. + +use serde_json::{Value, json}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +const OPENPBR: &str = "OpenPBR (separate maps)"; + +fn temp(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("tc_mtlx_{tag}_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + dir +} + +fn export(s: &mut Session, dir: &std::path::Path, preset: &str, mtlx: bool) -> Value { + execute(s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": preset, "materialX": mtlx})).unwrap() +} + +fn files(r: &Value) -> Vec { + r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect() +} + +#[test] +fn writes_a_material_that_names_the_exported_textures() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let dir = temp("ball"); + let r = export(&mut s, &dir, OPENPBR, true); + let all = files(&r); + let mtlx: Vec<&String> = all.iter().filter(|f| f.ends_with(".mtlx")).collect(); + assert_eq!(mtlx.len(), s.set_count(), "one material per texture set: {all:?}"); + for path in mtlx { + let set = path.rsplit(['/', '\\']).next().unwrap().trim_end_matches(".mtlx").to_string(); + let text = std::fs::read_to_string(path).unwrap(); + assert!(text.contains("= 3, "base colour, roughness and normal at least: {text}"); + assert!(text.contains("name=\"base_color\"") && text.contains("name=\"geometry_normal\""), "{text}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn off_by_default_and_warns_without_openpbr_maps() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let dir = temp("off"); + assert!(!files(&export(&mut s, &dir, OPENPBR, false)).iter().any(|f| f.ends_with(".mtlx"))); + let _ = std::fs::remove_dir_all(&dir); + let dir = temp("other"); + let r = export(&mut s, &dir, "Document channels + Normal + AO", true); + assert!(!files(&r).iter().any(|f| f.ends_with(".mtlx"))); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("OpenPBR")), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn udim_sets_use_the_udim_token() { + let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + let dir = temp("udim"); + let r = export(&mut s, &dir, OPENPBR, true); + let all = files(&r); + let mtlx = all.iter().find(|f| f.ends_with(".mtlx")).unwrap_or_else(|| panic!("no .mtlx in {all:?}")); + let text = std::fs::read_to_string(mtlx).unwrap(); + assert!(text.contains(".<UDIM>.png"), "{text}"); + assert!(!text.contains(".1001.") && !text.contains(".1002."), "{text}"); + assert!(all.iter().any(|f| f.ends_with(".1001.png")) && all.iter().any(|f| f.ends_with(".1002.png"))); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 249ff0f7..7ddd7577 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -12,6 +12,7 @@ //! - [`export`]: texture export from a texture set's composite through [`ExportPreset`]s (file //! name templates, channel packing, virtual maps such as the final normal, padding, resizing) //! to PNG, JPEG, TGA, TIFF, BMP, WebP, EXR and HDR bytes. +//! - [`materialx`]: a MaterialX (`.mtlx`) OpenPBR document for an exported texture set. //! - [`presets`]: the built-in export presets and JSON (de)serialization of user presets. //! - [`project_file`]: the `.tcraft` project zip (project JSON, sparse lossless pixel tiles, //! baked maps, the original mesh and a thumbnail). @@ -23,6 +24,7 @@ pub mod export; pub mod image_res; +pub mod materialx; pub mod mesh_export; pub mod mesh_import; pub mod presets; diff --git a/crates/formats/src/materialx.rs b/crates/formats/src/materialx.rs new file mode 100644 index 00000000..d178f7b7 --- /dev/null +++ b/crates/formats/src/materialx.rs @@ -0,0 +1,275 @@ +//! MaterialX documents for exported texture sets, written from the ASWF MaterialX specification +//! (version 1.39) and the OpenPBR Surface specification. Pure Rust: no MaterialX library is +//! linked, and nothing is read from any other application. +//! +//! [`write`] takes a material's name and the texture files an export produced, each tagged with +//! the OpenPBR input it feeds, and gives the text of a `.mtlx` file: an `open_pbr_surface` shader +//! whose inputs read `tiledimage` nodes, wrapped in a `surfacematerial`. The inputs are the ones +//! the built-in "OpenPBR (separate maps)" export preset writes ([`INPUTS`]); `height` becomes a +//! `displacement` shader on the material and `geometry_normal` goes through a `normalmap` node +//! (OpenGL, +Y up, which is what that node expects). +//! +//! Colour textures (base, fuzz and emission colour) are tagged `srgb_texture`; every data map is +//! left untagged (linear). UDIM sets write the `` filename token MaterialX defines. +//! Texture file names are relative to the document. + +use std::collections::HashSet; +use std::fmt::Write as _; + +/// How an OpenPBR input is typed in the document. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// `color3` from an sRGB texture. + Color, + /// `float` from a linear texture. + Float, + /// `vector3` through a `normalmap` node. + Normal, + /// `float` driving a `displacement` shader. + Height, +} + +/// The OpenPBR inputs the export writes, in document order. Names are the file-name suffixes of +/// the built-in OpenPBR preset's maps (`$mesh_$textureSet_`). +pub const INPUTS: &[(&str, Kind)] = &[ + ("base_color", Kind::Color), + ("base_metalness", Kind::Float), + ("specular_roughness", Kind::Float), + ("specular_roughness_anisotropy", Kind::Float), + ("coat_weight", Kind::Float), + ("coat_roughness", Kind::Float), + ("fuzz_weight", Kind::Float), + ("fuzz_color", Kind::Color), + ("fuzz_roughness", Kind::Float), + ("transmission_weight", Kind::Float), + ("subsurface_weight", Kind::Float), + ("emission_color", Kind::Color), + ("geometry_opacity", Kind::Float), + ("geometry_normal", Kind::Normal), + ("height", Kind::Height), +]; + +/// The file-name prefix of the built-in OpenPBR preset's maps. +const PREFIX: &str = "$mesh_$textureSet_"; + +/// One exported texture: the OpenPBR input it feeds and the file (relative to the `.mtlx`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Texture { + pub input: String, + pub file: String, +} + +/// The OpenPBR input a preset map's file template feeds (`$mesh_$textureSet_base_color` → +/// `base_color`), or None for templates this module has no place for. +pub fn input_of_template(template: &str) -> Option<&'static str> { + let suffix = template.strip_prefix(PREFIX)?; + INPUTS.iter().find(|(n, _)| *n == suffix).map(|(n, _)| *n) +} + +fn kind_of(input: &str) -> Option { + INPUTS.iter().find(|(n, _)| *n == input).map(|(_, k)| *k) +} + +/// A MaterialX name: letters, digits and underscores, not starting with a digit. +pub fn node_name(s: &str) -> String { + let mut out: String = s.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect(); + if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) { + out.insert(0, '_'); + } + out +} + +fn esc(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + c if c.is_control() => out.push(' '), + c => out.push(c), + } + } + out +} + +fn image_name(input: &str) -> String { + format!("image_{}", node_name(input)) +} + +/// The text of a MaterialX document for `name` with the given textures. `physical_size_cm` goes +/// into the material's `doc` attribute. Inputs this module has no place for are skipped, and so +/// are repeats of one input (the first wins). +pub fn write(name: &str, textures: &[Texture], physical_size_cm: Option<[f32; 2]>) -> String { + let base = node_name(name); + let mut seen = HashSet::new(); + let tex: Vec<(&Texture, Kind)> = textures.iter().filter_map(|t| kind_of(&t.input).map(|k| (t, k))).filter(|(t, _)| seen.insert(t.input.as_str())).collect(); + let has = |i: &str| tex.iter().any(|(t, _)| t.input == i); + let mut x = String::new(); + let _ = writeln!(x, ""); + let _ = writeln!(x, ""); + + let shader = format!("OPBR_{base}"); + let _ = writeln!(x, " ", esc(&shader)); + for (t, kind) in &tex { + let (ty, node) = match kind { + Kind::Color => ("color3", image_name(&t.input)), + Kind::Float => ("float", image_name(&t.input)), + Kind::Normal => ("vector3", "normalmap".to_owned()), + Kind::Height => continue, + }; + let _ = writeln!(x, " ", t.input); + } + if has("emission_color") { + let _ = writeln!(x, " "); + } + let _ = writeln!(x, " "); + + for (t, kind) in &tex { + let (ty, space) = match kind { + Kind::Color => ("color3", Some("srgb_texture")), + Kind::Normal => ("vector3", None), + Kind::Float | Kind::Height => ("float", None), + }; + let node = image_name(&t.input); + let _ = writeln!(x, " "); + match space { + Some(space) => { + let _ = writeln!(x, " ", esc(&t.file)); + } + None => { + let _ = writeln!(x, " ", esc(&t.file)); + } + } + let _ = writeln!(x, " "); + } + if has("geometry_normal") { + let _ = writeln!(x, " "); + let _ = writeln!(x, " ", image_name("geometry_normal")); + let _ = writeln!(x, " "); + } + if has("height") { + let _ = writeln!(x, " "); + let _ = writeln!(x, " ", image_name("height")); + let _ = writeln!(x, " "); + let _ = writeln!(x, " "); + } + + let doc = match physical_size_cm { + Some([w, h]) if w.is_finite() && h.is_finite() => format!(" doc=\"Tiles every {w} x {h} cm\""), + _ => String::new(), + }; + let _ = writeln!(x, " ", esc(&base)); + let _ = writeln!(x, " ", esc(&shader)); + if has("height") { + let _ = writeln!(x, " "); + } + let _ = writeln!(x, " "); + let _ = writeln!(x, ""); + x +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tex(input: &str, file: &str) -> Texture { + Texture { input: input.into(), file: file.into() } + } + + /// Every start tag is closed or self-closed, in order: enough to catch a malformed writer. + fn balanced(xml: &str) -> bool { + let mut stack: Vec = Vec::new(); + let mut rest = xml; + while let Some(i) = rest.find('<') { + let Some(j) = rest.get(i..).and_then(|r| r.find('>')) else { return false }; + let Some(tag) = rest.get(i + 1..i + j) else { return false }; + rest = rest.get(i + j + 1..).unwrap_or(""); + if tag.starts_with('?') || tag.starts_with('!') { + continue; + } + if let Some(name) = tag.strip_prefix('/') { + if stack.pop().as_deref() != Some(name.trim()) { + return false; + } + } else if !tag.ends_with('/') { + stack.push(tag.split_whitespace().next().unwrap_or("").to_owned()); + } + } + stack.is_empty() + } + + #[test] + fn a_full_material_maps_every_input() { + let t: Vec = INPUTS.iter().map(|(n, _)| tex(n, &format!("stone_{n}.png"))).collect(); + let x = write("Stone", &t, Some([100.0, 50.0])); + assert!(balanced(&x), "{x}"); + for want in [ + "", + "name=\"base_color\" type=\"color3\" nodename=\"image_base_color\"", + "name=\"base_metalness\" type=\"float\" nodename=\"image_base_metalness\"", + "name=\"specular_roughness\" type=\"float\" nodename=\"image_specular_roughness\"", + "name=\"coat_weight\" type=\"float\" nodename=\"image_coat_weight\"", + "name=\"fuzz_color\" type=\"color3\" nodename=\"image_fuzz_color\"", + "name=\"transmission_weight\" type=\"float\"", + "name=\"subsurface_weight\" type=\"float\"", + "name=\"geometry_opacity\" type=\"float\" nodename=\"image_geometry_opacity\"", + "name=\"geometry_normal\" type=\"vector3\" nodename=\"normalmap\"", + "name=\"emission_color\" type=\"color3\" nodename=\"image_emission_color\"", + "name=\"emission_luminance\" type=\"float\" value=\"1\"", + "value=\"stone_base_color.png\" colorspace=\"srgb_texture\"", + "value=\"stone_emission_color.png\" colorspace=\"srgb_texture\"", + "", + "", + "name=\"displacementshader\"", + "", + ] { + assert!(x.contains(want), "missing {want}\n{x}"); + } + // Data textures carry no colour space, and height is not an OpenPBR input. + assert!(x.contains("value=\"stone_specular_roughness.png\" />")); + assert!(!x.contains("name=\"height\"")); + } + + #[test] + fn only_what_is_there_is_written() { + let x = write("m", &[tex("specular_roughness", "r.png")], None); + assert!(balanced(&x)); + assert!(!x.contains("base_color") && !x.contains("normalmap") && !x.contains("displacement") && !x.contains("emission_luminance")); + assert!(x.contains("")); + let none = write("m", &[], None); + assert!(balanced(&none) && none.contains("&\"c", &[tex("base_color", "x\"&<'>..png")], Some([f32::NAN, 1.0])); + assert!(balanced(&x.replace("<UDIM>", "UDIM")), "{x}"); + assert!(x.contains("value=\"x"&<'>.<UDIM>.png\"")); + assert!(!x.contains("doc="), "a non-finite size is left out"); + assert!(x.contains("OPBR_a_b___c")); + } +} From 93aa3b8eabb5250fb75c9b0142b35653007816a4 Mon Sep 17 00:00:00 2001 From: Agapenordev <120006055+Agapenordev@users.noreply.github.com> Date: Sun, 1 Nov 2026 21:19:58 +0100 Subject: [PATCH 03/60] Paint through a selected filter instead of refusing the stroke Adding a filter from the shelf selects it. Every stroke after that was refused with "the selected effect is not a paint effect" until the user re-selected the layer, and on a fresh project's empty "Layer 1" the filter itself showed no change, so filters looked broken. - With a non-paint effect selected, a stroke paints what lies beneath it: the nearest paint effect below it in the same stack, else the paint layer's own pixels (content), or a new mask paint effect inserted just below it (mask). The new paint goes through the filter. - A filter on a fill layer's content still cannot be painted, with an error that says why. - The shelf tells the user when a filter lands on a paint layer that has nothing painted yet. Tests cover each case and fail on the old code. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/painting.rs | 35 ++++++++- crates/engine/tests/filters.rs | 111 +++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 4 ++ crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 4 ++ crates/ui-egui/src/i18n/ko.rs | 4 ++ crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/shelf.rs | 28 +++++++- 11 files changed, 188 insertions(+), 3 deletions(-) create mode 100644 crates/engine/tests/filters.rs diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 741fac6c..f1d43b96 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -57,7 +57,10 @@ impl Session { let content = self.doc.project.layer(owner)?.content_effects.iter().any(|x| x.id == e); Ok(if content { PaintTarget::Layer(e) } else { PaintTarget::Mask(e) }) } - _ => Err(EngineError::Other("the selected effect is not a paint effect".into())), + // A filter (or another effect) is selected, e.g. just added from the shelf: paint + // what lies beneath it, so the new paint goes through it. + Some((owner, _)) => self.paint_target_below(owner, e), + None => Err(EngineError::Other("the selected effect is not a paint effect".into())), }, StackTarget::Mask => { let eid = self.doc.project.alloc_id(); @@ -72,6 +75,36 @@ impl Session { } } + /// What a stroke paints while non-paint effect `effect` of layer `owner` is selected: the + /// nearest paint effect below it in the same stack, else the paint layer's own pixels (for + /// content) or a new paint effect inserted just below it (for a mask). + fn paint_target_below(&mut self, owner: LayerId, effect: LayerId) -> Result { + let eid = self.doc.project.alloc_id(); + let layer = self.doc.project.layer_mut(owner)?; + let below = |effects: &[Effect], at: usize| effects.get(..at).and_then(|b| b.iter().rev().find(|x| matches!(x.kind, EffectKind::Paint))).map(|x| x.id); + if let Some(at) = layer.content_effects.iter().position(|x| x.id == effect) { + if let Some(id) = below(&layer.content_effects, at) { + return Ok(PaintTarget::Layer(id)); + } + return if matches!(layer.kind, LayerKind::Paint) { + Ok(PaintTarget::Layer(owner)) + } else { + Err(EngineError::Other(format!( + "\"{}\" is a {} layer: paint on a paint layer or on its mask (a filter changes what lies below it)", + layer.name, + layer.kind.name() + ))) + }; + } + let mask = layer.mask.as_mut().ok_or_else(|| EngineError::Other("the selected effect is not a paint effect".into()))?; + let at = mask.effects.iter().position(|x| x.id == effect).ok_or_else(|| EngineError::Other("the selected effect is not a paint effect".into()))?; + if let Some(id) = below(&mask.effects, at) { + return Ok(PaintTarget::Mask(id)); + } + mask.effects.insert(at, Effect::new(eid, EffectKind::Paint)); + Ok(PaintTarget::Mask(eid)) + } + fn stroke_values(&self, target: PaintTarget) -> BTreeMap { let ts = self.ts(); let Ok(set) = self.doc.project.texture_set(ts) else { return BTreeMap::new() }; diff --git a/crates/engine/tests/filters.rs b/crates/engine/tests/filters.rs new file mode 100644 index 00000000..12e4e3cd --- /dev/null +++ b/crates/engine/tests/filters.rs @@ -0,0 +1,111 @@ +//! Painting while a filter is selected (it is selected right after the shelf adds it): the +//! stroke paints what lies beneath the filter, so the new paint goes through it. + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, EffectKind, LayerId}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, StackTarget, execute}; + +const RES: f32 = 256.0; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + s.camera.yaw = 0.0; + s.camera.pitch = 0.0; + s.update(); + s +} + +/// Base color of the composite under a viewport point. +fn color_at(s: &mut Session, x: f32, y: f32) -> [f32; 3] { + s.update(); + let hit = s.pick(Vec2::new(x, y), s.viewport).unwrap(); + s.caches[0].composite.value(Channel::BaseColor, (hit.uv.x * RES) as u32, (hit.uv.y * RES) as u32) +} + +fn brush(s: &mut Session, color: [f32; 3]) { + execute(s, "tool.paint", &Value::Null).unwrap(); + execute(s, "tool.material", &json!({"channel": "baseColor", "color": color})).unwrap(); + execute(s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap(); +} + +fn dab(s: &mut Session) -> Result { + execute(s, "tool.stroke", &json!({"points": [[200, 200]]})).map_err(|e| e.to_string()) +} + +fn add_filter(s: &mut Session, filter: &str, target: &str) -> LayerId { + execute(s, "effect.add.filter", &json!({"filter": filter, "target": target})).unwrap(); + let StackTarget::Effect(e) = s.target else { panic!("adding a filter selects it: {:?}", s.target) }; + e +} + +fn kinds(effects: &[texturecraft_engine::core::Effect]) -> Vec<&'static str> { + effects.iter().map(|e| if matches!(e.kind, EffectKind::Paint) { "paint" } else { "other" }).collect() +} + +#[test] +fn a_selected_content_filter_paints_its_paint_layer_through_it() { + let mut s = session(); + let layer = s.selected_layer().unwrap(); + add_filter(&mut s, "invert", "content"); + brush(&mut s, [1.0, 0.0, 0.0]); + dab(&mut s).expect("painting with the filter selected works"); + let v = color_at(&mut s, 200.0, 200.0); + assert!(v[0] < 0.15 && v[1] > 0.85 && v[2] > 0.85, "red paint shows inverted (cyan): {v:?}"); + assert!(s.doc.pixels.layers.keys().any(|(id, _)| *id == layer), "the paint landed in the layer's own pixels"); + // One undo step removes the stroke and leaves the filter. + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(!s.doc.pixels.layers.iter().any(|((id, _), img)| *id == layer && img.allocated_count() > 0)); + assert_eq!(s.doc.project.layer(layer).unwrap().content_effects.len(), 1); +} + +#[test] +fn a_selected_content_filter_paints_the_paint_effect_below_it() { + let mut s = session(); + let layer = s.selected_layer().unwrap(); + execute(&mut s, "effect.add.paint", &json!({"target": "content"})).unwrap(); + let StackTarget::Effect(paint) = s.target else { panic!("{:?}", s.target) }; + add_filter(&mut s, "invert", "content"); + brush(&mut s, [1.0, 0.0, 0.0]); + dab(&mut s).unwrap(); + assert!(s.doc.pixels.layers.iter().any(|((id, _), img)| *id == paint && img.allocated_count() > 0), "painted into the paint effect"); + assert!(!s.doc.pixels.layers.iter().any(|((id, _), img)| *id == layer && img.allocated_count() > 0), "not into the layer below it"); + let v = color_at(&mut s, 200.0, 200.0); + assert!(v[0] < 0.15 && v[1] > 0.85, "through the filter: {v:?}"); +} + +#[test] +fn a_selected_filter_on_a_fill_layer_explains_why_it_cannot_paint() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.4, 0.8]})).unwrap(); + add_filter(&mut s, "invert", "content"); + brush(&mut s, [1.0, 0.0, 0.0]); + let e = dab(&mut s).unwrap_err(); + assert!(e.contains("fill layer"), "{e}"); +} + +#[test] +fn a_selected_mask_filter_paints_a_mask_paint_effect_below_it() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + let layer = s.selected_layer().unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + add_filter(&mut s, "invert", "mask"); + let mask = |s: &Session| s.doc.project.layer(layer).unwrap().mask.clone().unwrap().effects; + assert_eq!(kinds(&mask(&s)), ["other"]); + // Black mask, inverted: the red fill shows everywhere. + assert!(color_at(&mut s, 200.0, 200.0)[0] > 0.85); + brush(&mut s, [1.0, 1.0, 1.0]); + s.tool.mask_value = 1.0; + dab(&mut s).expect("painting the mask with its filter selected works"); + assert_eq!(kinds(&mask(&s)), ["paint", "other"], "a paint effect was inserted below the filter"); + // White paint goes through the invert: the fill disappears where it was painted only. + let painted = color_at(&mut s, 200.0, 200.0); + let elsewhere = color_at(&mut s, 120.0, 200.0); + assert!(painted[0] < 0.6 && elsewhere[0] > 0.85, "painted {painted:?}, elsewhere {elsewhere:?}"); + // The next stroke reuses that paint effect. + dab(&mut s).unwrap(); + assert_eq!(kinds(&mask(&s)), ["paint", "other"]); +} diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ce534a6f..39e8e1ad 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -979,4 +979,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Fensterrahmen und Fenstertasten des Betriebssystems statt der eigenen Titelleiste von TextureCraft verwenden", ), + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ist noch nicht bemalt: Der Filter verändert, was du darauf malst."), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 2b57afd8..7755c3ec 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -964,4 +964,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Usar el marco y los botones de ventana del sistema operativo en lugar de la barra de título propia de TextureCraft", ), + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" aún no tiene pintura: el filtro cambia lo que pintes en ella."), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 0e72b031..0779832f 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -979,4 +979,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Utiliser le cadre et les boutons de fenêtre du système d'exploitation au lieu de la barre de titre de TextureCraft", ), + ( + "\"{layer}\" has no paint yet: the filter changes what you paint on it.", + "\"{layer}\" n'a pas encore de peinture : le filtre modifie ce que vous y peignez.", + ), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 9260b188..973c993a 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -973,4 +973,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Usa la cornice e i pulsanti della finestra del sistema operativo invece della barra del titolo di TextureCraft", ), + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" non è ancora dipinto: il filtro modifica ciò che vi dipingi."), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 2e333ab9..56c871c3 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -946,4 +946,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "TextureCraft 独自のタイトルバーの代わりに、OS のウィンドウ枠とボタンを使います", ), + ( + "\"{layer}\" has no paint yet: the filter changes what you paint on it.", + "「{layer}」にはまだペイントがありません:フィルターはこのレイヤーにペイントした内容を変化させます。", + ), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 3945c9a9..a99fdc24 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -931,4 +931,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "TextureCraft 자체 제목 표시줄 대신 운영 체제의 창 테두리와 버튼을 사용합니다", ), + ( + "\"{layer}\" has no paint yet: the filter changes what you paint on it.", + "\"{layer}\"에 아직 페인트가 없습니다: 필터는 이 레이어에 칠하는 내용을 바꿉니다.", + ), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 788df7f9..ceacb367 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -961,4 +961,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Usar a moldura e os botões de janela do sistema operacional em vez da barra de título própria do TextureCraft", ), + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ainda não tem pintura: o filtro altera o que você pintar nela."), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 3de5246c..4c70de38 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -877,4 +877,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "使用操作系统的窗口边框和按钮,而不是 TextureCraft 自己的标题栏", ), + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "“{layer}”尚未绘制:滤镜会改变你在其上绘制的内容。"), ]; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 0abcbe68..d18819d2 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -15,7 +15,7 @@ use texturecraft_engine::smart_masks::SMART_MASKS; use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; -use crate::i18n::tr; +use crate::i18n::{tr, trf}; use crate::theme::Tokens; use crate::widgets::{dnd_release, icon_button}; @@ -75,7 +75,17 @@ pub fn apply(app: &mut TextureCraftApp, asset: &Asset) { let (cmd, params) = match asset { Asset::Material(id) => ("material.apply", json!({"material": id})), Asset::SmartMask(id) => ("mask.smart.apply", json!({"name": id})), - Asset::Filter(id) => ("effect.add.filter", json!({"filter": id, "target": if crate::dock::targets_content(app) { "content" } else { "mask" }})), + Asset::Filter(id) => { + let content = crate::dock::targets_content(app); + if app.run("effect.add.filter", json!({"filter": id, "target": if content { "content" } else { "mask" }})).is_some() + && content + && let Some(name) = unpainted_paint_layer(app) + { + // Otherwise the filter seems to do nothing: it has nothing to change yet. + app.toast(trf("\"{layer}\" has no paint yet: the filter changes what you paint on it.", &[("layer", &name)]), false); + } + return; + } Asset::Alpha(id) => ("tool.brush", json!({"alpha": {"library": id}})), Asset::Library(path) => ("material.load", json!({"path": path})), Asset::Texture(name) => ("layer.add.image", json!({"name": name})), @@ -83,6 +93,20 @@ pub fn apply(app: &mut TextureCraftApp, asset: &Asset) { app.run(cmd, params); } +/// The selected layer's name when it is a paint layer with nothing painted (in itself or in its +/// content paint effects). +fn unpainted_paint_layer(app: &TextureCraftApp) -> Option { + use texturecraft_engine::core::{EffectKind, LayerKind}; + let s = &app.session; + let layer = s.selected_layer().and_then(|id| s.doc.project.content_layer(id))?; + if !matches!(layer.kind, LayerKind::Paint) { + return None; + } + let ids: Vec<_> = std::iter::once(layer.id).chain(layer.content_effects.iter().filter(|e| matches!(e.kind, EffectKind::Paint)).map(|e| e.id)).collect(); + let painted = s.doc.pixels.layers.iter().any(|((id, _), img)| ids.contains(id) && img.allocated_count() > 0); + (!painted).then(|| layer.name.clone()) +} + /// What a view accepts from the shelf. #[derive(Clone, Copy, PartialEq, Eq)] pub enum DropZone { From c89a9870e132bd58da68f9e2e4a23a8ad6a0ec19 Mon Sep 17 00:00:00 2001 From: Kushagra Kumar Date: Mon, 2 Nov 2026 01:59:03 +0530 Subject: [PATCH 04/60] feat(app): support multi-GPU selection and discrete adapter preference (#49) --- apps/texturecraft/src/gpu.rs | 244 ++++++++++++++++++++++++++++++++++ apps/texturecraft/src/main.rs | 48 ++++++- 2 files changed, 288 insertions(+), 4 deletions(-) create mode 100644 apps/texturecraft/src/gpu.rs diff --git a/apps/texturecraft/src/gpu.rs b/apps/texturecraft/src/gpu.rs new file mode 100644 index 00000000..77886c3f --- /dev/null +++ b/apps/texturecraft/src/gpu.rs @@ -0,0 +1,244 @@ +//! Graphics adapter selection and multi-GPU configuration (#49). +//! +//! On machines with multiple GPUs (e.g. hybrid laptops or dual-GPU desktops with Intel/AMD iGPU and +//! NVIDIA/AMD dGPU), TextureCraft must allow users to select which graphics processor renders the +//! 3D viewport, and default to the high-performance discrete GPU for real-time PBR shading. +//! +//! Selection priority: +//! 1. Window surface support: adapters that cannot present to the surface are ranked last. +//! 2. Explicit filter: `--gpu ` CLI option or `WGPU_ADAPTER_NAME` environment variable (case-insensitive substring). +//! 3. Hardware before software: physical GPUs before software/CPU rasterizers (llvmpipe, lavapipe, WARP). +//! 4. Backend preference: native backends (Vulkan, Metal, DX12) before OpenGL. +//! 5. Power preference: [`wgpu::PowerPreference::HighPerformance`] (default for 3D painting) prefers discrete GPUs, +//! [`wgpu::PowerPreference::LowPower`] prefers integrated GPUs, and [`wgpu::PowerPreference::None`] preserves system order. + +use std::sync::Arc; + +use eframe::NativeOptions; +use eframe::egui_wgpu::WgpuSetup; +use eframe::wgpu::{self, Backend, DeviceType, PowerPreference}; + +/// Environment variable for choosing an adapter by name or substring. +pub const ADAPTER_NAME_ENV: &str = "WGPU_ADAPTER_NAME"; + +/// Environment variable for power preference (`high`, `low`, `none`). +pub const POWER_PREF_ENV: &str = "WGPU_POWER_PREF"; + +/// Parses a power preference string from CLI or environment variable. +pub fn parse_power_preference(s: &str) -> Result { + match s.trim().to_ascii_lowercase().as_str() { + "high" | "highperformance" | "high-performance" => Ok(PowerPreference::HighPerformance), + "low" | "lowpower" | "low-power" => Ok(PowerPreference::LowPower), + "none" | "default" => Ok(PowerPreference::None), + other => Err(format!("invalid power preference `{other}`: expected `high`, `low`, or `none`")), + } +} + +/// A graphics adapter candidate inspected during adapter selection. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Candidate { + pub name: String, + pub vendor: u32, + pub device: u32, + pub device_type: DeviceType, + pub backend: Backend, + pub surface_supported: bool, +} + +impl Candidate { + pub fn new(adapter: &wgpu::Adapter, surface: Option<&wgpu::Surface<'_>>) -> Self { + let info = adapter.get_info(); + Self { + name: info.name, + vendor: info.vendor, + device: info.device, + device_type: info.device_type, + backend: info.backend, + surface_supported: surface.is_none_or(|s| adapter.is_surface_supported(s)), + } + } + + /// Whether this candidate matches the given search filter (by name or backend). + pub fn matches_filter(&self, filter: &str) -> bool { + let filter_lower = filter.to_ascii_lowercase(); + self.name.to_ascii_lowercase().contains(&filter_lower) || format!("{:?}", self.backend).to_ascii_lowercase().contains(&filter_lower) + } + + /// Whether this is a CPU or software rasterizer. + pub fn is_software(&self) -> bool { + self.device_type == DeviceType::Cpu + || self.name.to_ascii_lowercase().contains("llvmpipe") + || self.name.to_ascii_lowercase().contains("lavapipe") + || self.name.to_ascii_lowercase().contains("warp") + } +} + +/// Chooses the best adapter index from the candidates based on filter, power preference, and surface support. +pub fn pick_adapter_index(candidates: &[Candidate], named_filter: Option<&str>, power: PowerPreference) -> Option { + if candidates.is_empty() { + return None; + } + + candidates + .iter() + .enumerate() + .min_by_key(|(orig_idx, c)| { + // Surface support is required; unsupported adapters rank last. + let surface_penalty = !c.surface_supported; + + // Explicit named filter (e.g. --gpu nvidia, WGPU_ADAPTER_NAME=3080). + let name_penalty = match named_filter { + Some(filter) => !c.matches_filter(filter), + None => false, + }; + + // Hardware GPUs before software/CPU rasterizers. + let software_penalty = c.is_software(); + + // Native backends before OpenGL. + let backend_rank = match c.backend { + Backend::Vulkan | Backend::Metal | Backend::Dx12 => 0, + Backend::Gl => 1, + _ => 2, + }; + + // Power preference ranking. + let power_rank = match power { + PowerPreference::HighPerformance => match c.device_type { + DeviceType::DiscreteGpu => 0, + DeviceType::IntegratedGpu => 1, + DeviceType::Other => 2, + DeviceType::VirtualGpu => 3, + DeviceType::Cpu => 4, + }, + PowerPreference::LowPower => match c.device_type { + DeviceType::IntegratedGpu => 0, + DeviceType::DiscreteGpu => 1, + DeviceType::Other => 2, + DeviceType::VirtualGpu => 3, + DeviceType::Cpu => 4, + }, + PowerPreference::None => match c.device_type { + DeviceType::Cpu => 1, + _ => 0, + }, + }; + + (surface_penalty, name_penalty, software_penalty, power_rank, backend_rank, *orig_idx) + }) + .map(|(idx, _)| idx) +} + +/// Configures `options` with adapter selection honoring `--gpu`, `WGPU_ADAPTER_NAME`, and `WGPU_POWER_PREF`. +pub fn configure(options: &mut NativeOptions, cli_gpu: Option, cli_power: Option) { + let effective_filter = cli_gpu.or_else(|| std::env::var(ADAPTER_NAME_ENV).ok()); + let effective_power = + cli_power.or_else(|| std::env::var(POWER_PREF_ENV).ok().and_then(|s| parse_power_preference(&s).ok())).unwrap_or(PowerPreference::HighPerformance); + + if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { + create.power_preference = effective_power; + + let filter = effective_filter.clone(); + create.native_adapter_selector = Some(Arc::new(move |adapters, surface| { + let candidates: Vec = adapters.iter().map(|a| Candidate::new(a, surface)).collect(); + + for (idx, c) in candidates.iter().enumerate() { + log::info!("graphics adapter #{idx}: {} ({:?}, {:?}, surface supported: {})", c.name, c.device_type, c.backend, c.surface_supported); + } + + let chosen_idx = pick_adapter_index(&candidates, filter.as_deref(), effective_power) + .ok_or_else(|| "no graphics adapter found that can present to the window".to_string())?; + + let chosen = &candidates[chosen_idx]; + log::info!("selected graphics adapter: {} ({:?}, {:?})", chosen.name, chosen.device_type, chosen.backend); + + adapters.get(chosen_idx).cloned().ok_or_else(|| "selected adapter index out of range".to_string()) + })); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dummy_candidate(name: &str, device_type: DeviceType, backend: Backend, surface_supported: bool) -> Candidate { + Candidate { name: name.to_string(), vendor: 0, device: 0, device_type, backend, surface_supported } + } + + #[test] + fn parses_power_preferences_correctly() { + assert_eq!(parse_power_preference("high").unwrap(), PowerPreference::HighPerformance); + assert_eq!(parse_power_preference("high-performance").unwrap(), PowerPreference::HighPerformance); + assert_eq!(parse_power_preference("low").unwrap(), PowerPreference::LowPower); + assert_eq!(parse_power_preference("low-power").unwrap(), PowerPreference::LowPower); + assert_eq!(parse_power_preference("none").unwrap(), PowerPreference::None); + assert_eq!(parse_power_preference("default").unwrap(), PowerPreference::None); + assert!(parse_power_preference("invalid").is_err()); + } + + #[test] + fn high_performance_default_prefers_discrete_gpu() { + let candidates = vec![ + dummy_candidate("AMD Radeon 660M", DeviceType::IntegratedGpu, Backend::Vulkan, true), + dummy_candidate("NVIDIA GeForce RTX 2050", DeviceType::DiscreteGpu, Backend::Vulkan, true), + ]; + + let selected = pick_adapter_index(&candidates, None, PowerPreference::HighPerformance); + assert_eq!(selected, Some(1)); + } + + #[test] + fn low_power_prefers_integrated_gpu() { + let candidates = vec![ + dummy_candidate("AMD Radeon 660M", DeviceType::IntegratedGpu, Backend::Vulkan, true), + dummy_candidate("NVIDIA GeForce RTX 2050", DeviceType::DiscreteGpu, Backend::Vulkan, true), + ]; + + let selected = pick_adapter_index(&candidates, None, PowerPreference::LowPower); + assert_eq!(selected, Some(0)); + } + + #[test] + fn named_filter_selects_specific_gpu() { + let candidates = vec![ + dummy_candidate("Intel(R) UHD Graphics 770", DeviceType::IntegratedGpu, Backend::Vulkan, true), + dummy_candidate("NVIDIA GeForce RTX 3080", DeviceType::DiscreteGpu, Backend::Vulkan, true), + dummy_candidate("AMD Radeon RX 7900 XTX", DeviceType::DiscreteGpu, Backend::Vulkan, true), + ]; + + // Match by "3080" + let selected = pick_adapter_index(&candidates, Some("3080"), PowerPreference::HighPerformance); + assert_eq!(selected, Some(1)); + + // Match by "intel" + let selected_intel = pick_adapter_index(&candidates, Some("intel"), PowerPreference::HighPerformance); + assert_eq!(selected_intel, Some(0)); + + // Match by "7900" + let selected_amd = pick_adapter_index(&candidates, Some("7900"), PowerPreference::HighPerformance); + assert_eq!(selected_amd, Some(2)); + } + + #[test] + fn unsupported_surface_is_ranked_last() { + let candidates = vec![ + dummy_candidate("NVIDIA GeForce RTX 3080", DeviceType::DiscreteGpu, Backend::Vulkan, false), + dummy_candidate("Intel(R) UHD Graphics 770", DeviceType::IntegratedGpu, Backend::Vulkan, true), + ]; + + // Even with HighPerformance, RTX 3080 cannot present to the surface, so Intel is chosen. + let selected = pick_adapter_index(&candidates, None, PowerPreference::HighPerformance); + assert_eq!(selected, Some(1)); + } + + #[test] + fn hardware_gpu_preferred_over_software() { + let candidates = vec![ + dummy_candidate("llvmpipe (LLVM 18.1.8, 256 bits)", DeviceType::Cpu, Backend::Vulkan, true), + dummy_candidate("Intel(R) UHD Graphics 620", DeviceType::IntegratedGpu, Backend::Vulkan, true), + ]; + + let selected = pick_adapter_index(&candidates, None, PowerPreference::HighPerformance); + assert_eq!(selected, Some(1)); + } +} diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index e1cbb6c2..09825f2a 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -6,6 +6,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod control_server; +mod gpu; mod window_frame; use texturecraft_engine::Session; @@ -32,11 +33,17 @@ struct Args { file: Option, control: Option, empty: bool, + gpu: Option, + power_pref: Option, } fn parse_args() -> Result, String> { - let mut args = Args { file: None, control: None, empty: false }; - let mut it = std::env::args().skip(1); + parse_args_from(std::env::args().skip(1)) +} + +fn parse_args_from>(it: I) -> Result, String> { + let mut args = Args { file: None, control: None, empty: false, gpu: None, power_pref: None }; + let mut it = it.into_iter(); while let Some(a) = it.next() { match a.as_str() { "--version" | "-V" => { @@ -44,13 +51,24 @@ fn parse_args() -> Result, String> { return Ok(None); } "--help" | "-h" => { - println!("{}\n\nUsage: texturecraft [project.tcraft | mesh file] [--control ] [--empty]", version()); + println!( + "{}\n\nUsage: texturecraft [project.tcraft | mesh file] [--control ] [--gpu ] [--power-pref ] [--empty]", + version() + ); return Ok(None); } "--control" => { let p = it.next().ok_or("--control needs a port")?; args.control = Some(p.parse().map_err(|_| format!("invalid port `{p}`"))?); } + "--gpu" => { + let g = it.next().ok_or("--gpu needs a GPU name or pattern")?; + args.gpu = Some(g); + } + "--power-pref" => { + let p = it.next().ok_or("--power-pref needs high, low, or none")?; + args.power_pref = Some(gpu::parse_power_preference(&p)?); + } "--empty" => args.empty = true, f if !f.starts_with('-') => args.file = Some(f.to_string()), other => return Err(format!("unknown option `{other}`")), @@ -168,7 +186,8 @@ fn main() { viewport = viewport.with_icon(i); } let viewport = title_bar.viewport(viewport); - let options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() }; + let mut options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() }; + gpu::configure(&mut options, args.gpu, args.power_pref); let control = args.control; let r = eframe::run_native( APP_NAME, @@ -202,6 +221,27 @@ fn main() { mod tests { use super::*; + #[test] + fn parses_gpu_and_power_preference_args() { + let args = parse_args_from(["--gpu".to_string(), "nvidia".to_string()]).unwrap().unwrap(); + assert_eq!(args.gpu.as_deref(), Some("nvidia")); + assert_eq!(args.power_pref, None); + + let args = parse_args_from(["--power-pref".to_string(), "high".to_string()]).unwrap().unwrap(); + assert_eq!(args.power_pref, Some(eframe::wgpu::PowerPreference::HighPerformance)); + + let args = parse_args_from(["--power-pref".to_string(), "low".to_string(), "--gpu".to_string(), "3080".to_string()]).unwrap().unwrap(); + assert_eq!(args.power_pref, Some(eframe::wgpu::PowerPreference::LowPower)); + assert_eq!(args.gpu.as_deref(), Some("3080")); + } + + #[test] + fn rejects_missing_or_invalid_gpu_args() { + assert!(parse_args_from(["--gpu".to_string()]).is_err()); + assert!(parse_args_from(["--power-pref".to_string()]).is_err()); + assert!(parse_args_from(["--power-pref".to_string(), "unrecognized".to_string()]).is_err()); + } + #[test] fn the_system_title_bar_setting_is_read_from_eframes_settings_file() { let path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id())); From fbacf65c680a4dc3179ba68fe5e1d192eff57565 Mon Sep 17 00:00:00 2001 From: Kushagra Kumar Date: Mon, 2 Nov 2026 02:09:01 +0530 Subject: [PATCH 05/60] fix(app): refine adapter selection error handling and priority ordering (#49) --- apps/texturecraft/src/gpu.rs | 46 ++++++++++++++++++++++++++++------- apps/texturecraft/src/main.rs | 5 +++- 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/apps/texturecraft/src/gpu.rs b/apps/texturecraft/src/gpu.rs index 77886c3f..4d48a2ff 100644 --- a/apps/texturecraft/src/gpu.rs +++ b/apps/texturecraft/src/gpu.rs @@ -8,9 +8,9 @@ //! 1. Window surface support: adapters that cannot present to the surface are ranked last. //! 2. Explicit filter: `--gpu ` CLI option or `WGPU_ADAPTER_NAME` environment variable (case-insensitive substring). //! 3. Hardware before software: physical GPUs before software/CPU rasterizers (llvmpipe, lavapipe, WARP). -//! 4. Backend preference: native backends (Vulkan, Metal, DX12) before OpenGL. -//! 5. Power preference: [`wgpu::PowerPreference::HighPerformance`] (default for 3D painting) prefers discrete GPUs, +//! 4. Power preference: [`wgpu::PowerPreference::HighPerformance`] (default for 3D painting) prefers discrete GPUs, //! [`wgpu::PowerPreference::LowPower`] prefers integrated GPUs, and [`wgpu::PowerPreference::None`] preserves system order. +//! 5. Backend preference: native backends (Vulkan, Metal, DX12) before OpenGL. use std::sync::Arc; @@ -95,10 +95,11 @@ pub fn pick_adapter_index(candidates: &[Candidate], named_filter: Option<&str>, // Hardware GPUs before software/CPU rasterizers. let software_penalty = c.is_software(); - // Native backends before OpenGL. - let backend_rank = match c.backend { - Backend::Vulkan | Backend::Metal | Backend::Dx12 => 0, - Backend::Gl => 1, + // Native backends before OpenGL (except when preserving system order). + let backend_rank = match (power, c.backend) { + (PowerPreference::None, _) => 0, + (_, Backend::Vulkan | Backend::Metal | Backend::Dx12) => 0, + (_, Backend::Gl) => 1, _ => 2, }; @@ -130,10 +131,15 @@ pub fn pick_adapter_index(candidates: &[Candidate], named_filter: Option<&str>, } /// Configures `options` with adapter selection honoring `--gpu`, `WGPU_ADAPTER_NAME`, and `WGPU_POWER_PREF`. -pub fn configure(options: &mut NativeOptions, cli_gpu: Option, cli_power: Option) { +pub fn configure(options: &mut NativeOptions, cli_gpu: Option, cli_power: Option) -> Result<(), String> { let effective_filter = cli_gpu.or_else(|| std::env::var(ADAPTER_NAME_ENV).ok()); - let effective_power = - cli_power.or_else(|| std::env::var(POWER_PREF_ENV).ok().and_then(|s| parse_power_preference(&s).ok())).unwrap_or(PowerPreference::HighPerformance); + let effective_power = match cli_power { + Some(p) => p, + None => match std::env::var(POWER_PREF_ENV) { + Ok(val) => parse_power_preference(&val)?, + Err(_) => PowerPreference::HighPerformance, + }, + }; if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { create.power_preference = effective_power; @@ -150,11 +156,22 @@ pub fn configure(options: &mut NativeOptions, cli_gpu: Option, cli_power .ok_or_else(|| "no graphics adapter found that can present to the window".to_string())?; let chosen = &candidates[chosen_idx]; + if !chosen.surface_supported { + return Err("no graphics adapter found that can present to the window".to_string()); + } + + if let Some(ref f) = filter + && !chosen.matches_filter(f) + { + log::warn!("no graphics adapter matched filter `{f}`; fell back to {}", chosen.name); + } + log::info!("selected graphics adapter: {} ({:?}, {:?})", chosen.name, chosen.device_type, chosen.backend); adapters.get(chosen_idx).cloned().ok_or_else(|| "selected adapter index out of range".to_string()) })); } + Ok(()) } #[cfg(test)] @@ -198,6 +215,17 @@ mod tests { assert_eq!(selected, Some(0)); } + #[test] + fn none_power_preference_preserves_enumerated_order() { + let candidates = vec![ + dummy_candidate("GPU A (GL)", DeviceType::DiscreteGpu, Backend::Gl, true), + dummy_candidate("GPU B (Vulkan)", DeviceType::DiscreteGpu, Backend::Vulkan, true), + ]; + + let selected = pick_adapter_index(&candidates, None, PowerPreference::None); + assert_eq!(selected, Some(0)); + } + #[test] fn named_filter_selects_specific_gpu() { let candidates = vec![ diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 09825f2a..7358b0ab 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -187,7 +187,10 @@ fn main() { } let viewport = title_bar.viewport(viewport); let mut options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() }; - gpu::configure(&mut options, args.gpu, args.power_pref); + if let Err(e) = gpu::configure(&mut options, args.gpu, args.power_pref) { + eprintln!("texturecraft: {e}"); + std::process::exit(2); + } let control = args.control; let r = eframe::run_native( APP_NAME, From 7fdd9be0a39507e9aad8f4d52f57ddf127b9036d Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 04:07:37 +0700 Subject: [PATCH 06/60] Text: draw text in any installed font as a brush alpha or a decal resource.text draws one or more lines of text, shaped with harfrust (kerning, ligatures, joined scripts) from the font's outlines (skrifa) and filled by a non-zero scanline rasterizer, cropped to the ink, as an image resource: white for the brush alpha, or a color for a decal. text.fonts lists the installed families and styles, read from each font file's name table only (246 families in 80 ms here); Ubuntu Light and Hack from the UI's built-in fonts are always there and are the fallback in the browser. - Properties > Alpha > Text: the text, a font and style, Use as brush alpha and Place as decal (in the tool's base color). - Image alphas keep their proportions (their longer side spans the stamp), so a line of text stays a line; image thumbnails are letterboxed and show alpha. - harfrust 0.12 and skrifa 0.44 are the versions egui already builds, so the lockfile gains no packages. Fixes #40 --- ATTRIBUTION.md | 2 +- Cargo.lock | 4 + Cargo.toml | 5 + ROADMAP.md | 2 +- crates/engine/Cargo.toml | 1 + crates/engine/src/commands.rs | 1 + crates/engine/src/lib.rs | 1 + crates/engine/src/text_cmds.rs | 108 ++++++++++++ crates/engine/tests/session.rs | 22 +++ crates/formats/src/fonts.rs | 197 ++++++++++++++++++++++ crates/formats/src/image_res.rs | 14 ++ crates/formats/src/lib.rs | 5 +- crates/paint/Cargo.toml | 5 + crates/paint/src/brush.rs | 9 +- crates/paint/src/lib.rs | 4 +- crates/paint/src/text.rs | 254 +++++++++++++++++++++++++++++ crates/ui-egui/src/dock.rs | 59 ++++++- crates/ui-egui/src/i18n/de.rs | 5 + crates/ui-egui/src/i18n/es.rs | 5 + crates/ui-egui/src/i18n/fr.rs | 5 + crates/ui-egui/src/i18n/it.rs | 5 + crates/ui-egui/src/i18n/ja.rs | 5 + crates/ui-egui/src/i18n/ko.rs | 5 + crates/ui-egui/src/i18n/pt_br.rs | 5 + crates/ui-egui/src/i18n/zh_hans.rs | 5 + crates/ui-egui/src/state.rs | 15 ++ crates/ui-egui/src/thumbs.rs | 11 +- docs/control-protocol.md | 3 +- docs/features.md | 3 + 29 files changed, 754 insertions(+), 11 deletions(-) create mode 100644 crates/engine/src/text_cmds.rs create mode 100644 crates/formats/src/fonts.rs create mode 100644 crates/paint/src/text.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index ffba2154..c26f317a 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -32,7 +32,7 @@ These come from Rust crate dependencies (not files in this repository) and keep | Asset | Used for | Author | Source | License | |---|---|---|---|---| | Phosphor Icons (regular), via the `egui-phosphor` crate (vendored in `vendor/egui-phosphor` for egui 0.37) | Every UI icon (tools, layers, panels) | Phosphor Icons (Helena Zhang, Tobias Fried) | https://phosphoricons.com, https://github.com/amPerl/egui-phosphor | MIT (icons); crate MIT OR Apache-2.0 | -| egui default fonts (Ubuntu-Light, Hack, Noto Emoji, emoji-icon-font), via `epaint_default_fonts` | UI text | Canonical / Source Foundry / Google / Jessie Jung | https://github.com/emilk/egui | Ubuntu Font Licence 1.0, MIT + Bitstream Vera License, OFL 1.1, MIT | +| egui default fonts (Ubuntu-Light, Hack, Noto Emoji, emoji-icon-font), via `epaint_default_fonts` | UI text; Ubuntu Light and Hack also as the built-in fonts for text alphas and decals | Canonical / Source Foundry / Google / Jessie Jung | https://github.com/emilk/egui | Ubuntu Font Licence 1.0, MIT + Bitstream Vera License, OFL 1.1, MIT | | Only in builds made with `CRAFT_FONTS_DIR`: Inter Regular and SemiBold (desktop and web), from storytold/craft-fonts' Latin catalog (`crates/ui-egui/build.rs`) | Interface text | The Inter Project Authors | https://github.com/storytold/craft-fonts (pinned sources in its `fonts/latin-manifest.txt` and `ATTRIBUTION.md`) | OFL 1.1 | | Only in builds made with `CRAFT_FONTS_DIR`: BIZ UDPGothic Regular (desktop and web) and Noto Sans CJK SC Regular (desktop), from storytold/craft-fonts (`crates/ui-egui/build.rs`) | Japanese and Chinese UI text | The BIZ UDGothic Project Authors (Morisawa Inc.); The Noto Project Authors | https://github.com/storytold/craft-fonts (pinned sources in its `fonts/manifest.txt` and `ATTRIBUTION.md`) | OFL 1.1 | diff --git a/Cargo.lock b/Cargo.lock index 0ffcb743..2b82f9d8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3904,6 +3904,7 @@ dependencies = [ name = "texturecraft-engine" version = "0.2.0" dependencies = [ + "epaint_default_fonts", "image", "rayon", "serde", @@ -3957,8 +3958,11 @@ dependencies = [ name = "texturecraft-paint" version = "0.2.0" dependencies = [ + "epaint_default_fonts", + "harfrust", "rayon", "serde", + "skrifa 0.44.0", "texturecraft-compose", "texturecraft-core", "texturecraft-geom", diff --git a/Cargo.toml b/Cargo.toml index 520785e9..9c44cd2f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +32,11 @@ serde_json = "1" glam = { version = "0.30", features = ["serde", "bytemuck"] } bytemuck = { version = "1", features = ["derive"] } rayon = "1" +# Text alphas: shaping and glyph outlines, the versions egui's text layout already builds. +harfrust = "0.12" +skrifa = { version = "0.44", default-features = false, features = ["std"] } +# The UI's built-in fonts (Ubuntu Light, Hack): text alphas fall back to them without system fonts. +epaint_default_fonts = "0.37" log = "0.4" image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tga", "tiff", "exr", "hdr", "bmp", "webp"] } half = "2" diff --git a/ROADMAP.md b/ROADMAP.md index b739669d..b632e821 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -14,7 +14,7 @@ end to end today (engine + UI + automation + tests), not what is planned. | Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | | Texture sets | 6 | 95% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile**, one texture per tile at its own size, `$udim` export), list with visibility, sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | Filter radii and height slopes of a tile smaller than its atlas block follow the block | | Layer stack | 16 | 96% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels, invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; smart masks; mask view (Alt+click); duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **27 library filters** (adjustments, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | -| Painting tools | 14 | 88% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **particle brush** | Pen tilt (not exposed by the windowing layer) | +| Painting tools | 14 | 88% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt (not exposed by the windowing layer) | | Materials and assets | 8 | 86% | 48 procedural materials (incl. car paint, velvet, brushed steel, skin, wax), 21 smart materials, 18 smart masks, **67 procedural brush alphas**, 22 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | | Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — | | Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Hardware ray tracing | diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 9e769306..5c189493 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -17,6 +17,7 @@ texturecraft-paint = { workspace = true } texturecraft-bake = { workspace = true } texturecraft-formats = { workspace = true } rayon = { workspace = true } +epaint_default_fonts = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 1d6b0cb8..b8938a19 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -73,6 +73,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::smart_masks::specs()); v.extend(crate::filter_lib::specs()); v.extend(crate::decal_cmds::specs()); + v.extend(crate::text_cmds::specs()); v }) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2afa239..2f2e6920 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -35,6 +35,7 @@ pub mod session; pub mod set_cmds; pub mod smart_masks; pub mod template_cmds; +pub mod text_cmds; pub mod tool_cmds; pub mod uv_tile_cmds; pub mod view_cmds; diff --git a/crates/engine/src/text_cmds.rs b/crates/engine/src/text_cmds.rs new file mode 100644 index 00000000..fbc4705b --- /dev/null +++ b/crates/engine/src/text_cmds.rs @@ -0,0 +1,108 @@ +//! Text: an image resource drawn from text in an installed font (or a built-in one), to stamp +//! with the brush as its alpha or to place as a decal. + +use serde_json::{Value, json}; +use texturecraft_paint::text::render_text; + +use crate::commands::{CommandSpec, always, bad, color_param, f32p, strp}; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![ + cmd!("text.fonts", "List fonts", [], None, "{} — the installed font families with their styles, and the built-in ones", always, |_, _| Ok(fonts())), + cmd!( + "resource.text", + "Add text", + [], + None, + "{text (lines split at \\n), font?: family (text.fonts; default a common sans-serif), style?: e.g. Bold (default Regular), size?: 8..1024 texels per em (default 256), color?: [r,g,b] linear or \"#rrggbb\" (default white), name?} — draws the text as an image resource with an alpha (white for tool.brush {alpha: {image}}, colored for layer.add.decal)", + always, + add_text + ), + ] +} + +/// Fonts bundled with the app (egui's), used when nothing is installed or in the browser. +const BUILT_IN: [(&str, &[u8]); 2] = [("Ubuntu Light", epaint_default_fonts::UBUNTU_LIGHT), ("Hack", epaint_default_fonts::HACK_REGULAR)]; +/// Families tried, in order, when no font is asked for. +const DEFAULT_FAMILIES: [&str; 6] = ["Arial", "Segoe UI", "Helvetica", "Liberation Sans", "DejaVu Sans", "Noto Sans"]; +/// Largest font file read. +#[cfg(not(target_arch = "wasm32"))] +const MAX_FONT_BYTES: u64 = 128 << 20; + +#[cfg(not(target_arch = "wasm32"))] +fn installed() -> &'static [texturecraft_formats::fonts::FontFace] { + static FONTS: std::sync::OnceLock> = std::sync::OnceLock::new(); + FONTS.get_or_init(texturecraft_formats::fonts::system_fonts) +} + +fn fonts() -> Value { + #[cfg(not(target_arch = "wasm32"))] + let families = { + let mut out: Vec<(String, Vec)> = Vec::new(); + for f in installed() { + match out.last_mut() { + Some((family, styles)) if *family == f.family => styles.push(f.style.clone()), + _ => out.push((f.family.clone(), vec![f.style.clone()])), + } + } + out + }; + #[cfg(target_arch = "wasm32")] + let families: Vec<(String, Vec)> = Vec::new(); + json!({ + "installed": families.into_iter().map(|(family, styles)| json!({"family": family, "styles": styles})).collect::>(), + "builtIn": BUILT_IN.map(|(name, _)| name), + }) +} + +/// The bytes and face index of `family` in `style` (a regular face when the style is missing), +/// or the first default family installed, else the built-in font. +fn font_bytes(family: Option<&str>, style: Option<&str>) -> Result<(std::borrow::Cow<'static, [u8]>, u32)> { + let is = |a: &str, b: &str| a.eq_ignore_ascii_case(b); + if let Some((_, bytes)) = BUILT_IN.iter().find(|(name, _)| family.is_some_and(|f| is(f, name))) { + return Ok((std::borrow::Cow::Borrowed(bytes), 0)); + } + #[cfg(not(target_arch = "wasm32"))] + { + let faces = installed(); + let pick = |family: &str| { + let of: Vec<_> = faces.iter().filter(|f| is(&f.family, family)).collect(); + let regular = ["Regular", "Normal", "Book", "Roman"]; + let found = style.and_then(|s| of.iter().find(|f| is(&f.style, s))); + found.or_else(|| of.iter().find(|f| regular.iter().any(|r| is(&f.style, r)))).or(of.first()).copied() + }; + let face = match family { + Some(f) => Some(pick(f).ok_or_else(|| bad("resource.text", format!("no font family `{f}` (see text.fonts)")))?), + None => DEFAULT_FAMILIES.iter().find_map(|f| pick(f)), + }; + if let Some(face) = face { + let size = std::fs::metadata(&face.path).map(|m| m.len()).unwrap_or(u64::MAX); + if size > MAX_FONT_BYTES { + return Err(bad("resource.text", format!("{} is too large", face.path.display()))); + } + let bytes = std::fs::read(&face.path).map_err(|e| bad("resource.text", format!("cannot read {}: {e}", face.path.display())))?; + return Ok((std::borrow::Cow::Owned(bytes), face.index)); + } + } + #[cfg(target_arch = "wasm32")] + let _ = style; + match family { + Some(f) => Err(bad("resource.text", format!("no font family `{f}` (see text.fonts)"))), + None => Ok((std::borrow::Cow::Borrowed(BUILT_IN[0].1), 0)), + } +} + +fn add_text(s: &mut Session, p: &Value) -> Result { + let cmd = "resource.text"; + let text = strp(p, "text").ok_or_else(|| bad(cmd, "`text` is required"))?; + let (font, index) = font_bytes(strp(p, "font"), strp(p, "style"))?; + let size = f32p(p, "size").unwrap_or(256.0).clamp(8.0, 1024.0); + let img = render_text(&font, index, text, size).map_err(|e| bad(cmd, e))?; + let rgb = color_param(p, "color").unwrap_or([1.0; 3]).map(|c| (texturecraft_texel::linear_to_srgb(c.clamp(0.0, 1.0)) * 255.0).round() as u8); + let png = texturecraft_formats::coverage_png(img.width, img.height, &img.coverage, rgb).map_err(|e| bad(cmd, e.to_string()))?; + // The resource is named after the text (its first line, shortened) unless a name is given. + let label: String = strp(p, "name").unwrap_or_else(|| text.lines().next().unwrap_or_default()).chars().take(32).collect(); + let name = s.import_resource_bytes(&format!("Text {}.png", label.trim()), png)?; + Ok(json!({ "name": name, "width": img.width, "height": img.height })) +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index bd7fd4a8..85d1075a 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -165,6 +165,28 @@ fn image_resources_fill_layers_and_round_trip() { assert!(s.import_resource_bytes("bad.png", vec![1, 2, 3]).is_err()); } +#[test] +fn text_becomes_a_brush_alpha_and_a_decal() { + let mut s = session(); + let fonts = execute(&mut s, "text.fonts", &Value::Null).unwrap(); + assert_eq!(fonts["builtIn"][0], "Ubuntu Light"); + let r = execute(&mut s, "resource.text", &json!({"text": "TEXT\nCRAFT", "font": "ubuntu light", "size": 64})).unwrap(); + let name = r["name"].as_str().unwrap().to_string(); + assert_eq!(name, "Text_TEXT.png"); + assert!(r["width"].as_u64().unwrap() > r["height"].as_u64().unwrap() / 2, "two short lines"); + // White with the glyphs in alpha. + let img = s.images[&name].clone(); + assert!(img.rgba.iter().any(|t| t[3] > 0.99) && img.rgba.iter().any(|t| t[3] == 0.0) && img.rgba.iter().all(|t| t[0] == 1.0)); + // As the brush alpha it paints (keeping its proportions), and it places as a decal. + execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 40, "alpha": {"image": name}})).unwrap(); + assert!(execute(&mut s, "tool.click", &json!({"x": 200, "y": 200})).is_ok()); + assert!(execute(&mut s, "layer.add.decal", &json!({"image": name})).unwrap()["layer"].as_u64().is_some()); + for bad in [json!({}), json!({"text": " "}), json!({"text": "x", "font": "No Such Font"})] { + assert!(execute(&mut s, "resource.text", &bad).is_err(), "{bad}"); + } +} + #[test] fn projection_tool_paints_the_stencil_colors() { let mut s = session(); diff --git a/crates/formats/src/fonts.rs b/crates/formats/src/fonts.rs new file mode 100644 index 00000000..b047ba49 --- /dev/null +++ b/crates/formats/src/fonts.rs @@ -0,0 +1,197 @@ +//! Installed fonts, for text alphas: the faces (family and style) of every TrueType or OpenType +//! file (and collection) in the system's font folders, read from each file's `name` table only, +//! so listing hundreds of fonts stays quick. Native only; the browser has no font folders. + +use std::io::{Read, Seek, SeekFrom}; +use std::path::{Path, PathBuf}; + +/// One face of an installed font file. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct FontFace { + pub family: String, + pub style: String, + pub path: PathBuf, + /// Face index in a collection (`.ttc`), else 0. + pub index: u32, +} + +/// Files and faces visited at most (a font folder is never this large, a wrong one may be). +const MAX_FILES: usize = 20_000; +const MAX_FACES_PER_FILE: u32 = 64; +const MAX_NAME_TABLE: u32 = 1 << 20; + +/// The installed fonts' faces, sorted by family then style. +pub fn system_fonts() -> Vec { + let mut files = Vec::new(); + for dir in font_dirs() { + collect(&dir, 0, &mut files); + } + let mut faces: Vec = files.iter().flat_map(|p| faces_of(p).unwrap_or_default()).collect(); + faces.sort(); + faces.dedup_by(|a, b| a.family == b.family && a.style == b.style); + faces +} + +fn font_dirs() -> Vec { + let home = std::env::var_os("HOME").map(PathBuf::from); + if cfg!(windows) { + let mut v = vec![PathBuf::from(std::env::var_os("WINDIR").unwrap_or_else(|| "C:\\Windows".into())).join("Fonts")]; + v.extend(std::env::var_os("LOCALAPPDATA").map(|d| PathBuf::from(d).join("Microsoft\\Windows\\Fonts"))); + v + } else if cfg!(target_os = "macos") { + let mut v = vec![PathBuf::from("/System/Library/Fonts"), PathBuf::from("/Library/Fonts")]; + v.extend(home.map(|h| h.join("Library/Fonts"))); + v + } else { + let mut v = vec![PathBuf::from("/usr/share/fonts"), PathBuf::from("/usr/local/share/fonts")]; + v.extend(home.iter().flat_map(|h| [h.join(".local/share/fonts"), h.join(".fonts")])); + v + } +} + +/// Font files under `dir` (a few levels deep). +fn collect(dir: &Path, depth: usize, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for e in entries.flatten() { + if out.len() >= MAX_FILES { + return; + } + let path = e.path(); + match e.file_type() { + Ok(t) if t.is_dir() && depth < 4 => collect(&path, depth + 1, out), + Ok(t) if t.is_file() => { + let ext = path.extension().and_then(|x| x.to_str()).unwrap_or_default().to_ascii_lowercase(); + if matches!(ext.as_str(), "ttf" | "otf" | "ttc" | "otc") { + out.push(path); + } + } + _ => {} + } + } +} + +/// The faces of the font file at `path` (each face of a collection). +pub fn faces_of(path: &Path) -> std::io::Result> { + let mut f = std::fs::File::open(path)?; + let mut at = |offset: u64, len: usize| -> std::io::Result> { + f.seek(SeekFrom::Start(offset))?; + let mut buf = vec![0; len]; + f.read_exact(&mut buf)?; + Ok(buf) + }; + let head = at(0, 12)?; + let offsets: Vec = if head.get(..4) == Some(b"ttcf") { + let n = u32_at(&head, 8).unwrap_or(0).min(MAX_FACES_PER_FILE); + let table = at(12, 4 * n as usize)?; + (0..n as usize).filter_map(|i| u32_at(&table, 4 * i)).map(u64::from).collect() + } else { + vec![0] + }; + let mut faces = Vec::new(); + for (index, offset) in offsets.into_iter().enumerate() { + let dir = at(offset, 12)?; + let tables = at(offset + 12, 16 * usize::from(u16_at(&dir, 4).unwrap_or(0)))?; + let Some(rec) = tables.chunks_exact(16).find(|r| r.get(..4) == Some(b"name")) else { continue }; + let (Some(off), Some(len)) = (u32_at(rec, 8), u32_at(rec, 12)) else { continue }; + let names = at(u64::from(off), len.min(MAX_NAME_TABLE) as usize)?; + let name = |ids: [u16; 2]| ids.iter().find_map(|id| name_string(&names, *id)); + if let Some(family) = name([16, 1]) { + let style = name([17, 2]).unwrap_or_else(|| "Regular".into()); + faces.push(FontFace { family, style, path: path.to_path_buf(), index: index as u32 }); + } + } + Ok(faces) +} + +fn u16_at(b: &[u8], o: usize) -> Option { + Some(u16::from_be_bytes(b.get(o..o.checked_add(2)?)?.try_into().ok()?)) +} + +fn u32_at(b: &[u8], o: usize) -> Option { + Some(u32::from_be_bytes(b.get(o..o.checked_add(4)?)?.try_into().ok()?)) +} + +/// Name `id` of a `name` table, in English when it has several languages: Windows and Unicode +/// records are UTF-16BE, Macintosh ones single-byte (read as Latin-1). +fn name_string(t: &[u8], id: u16) -> Option { + let (count, base) = (usize::from(u16_at(t, 2)?), usize::from(u16_at(t, 4)?)); + let mut best: Option<(u8, String)> = None; + for r in (0..count).filter_map(|i| t.get(6 + 12 * i..18 + 12 * i)) { + let (platform, language, name_id) = (u16_at(r, 0)?, u16_at(r, 4)?, u16_at(r, 6)?); + let (len, off) = (usize::from(u16_at(r, 8)?), usize::from(u16_at(r, 10)?)); + let Some(bytes) = t.get(base + off..base + off + len) else { continue }; + if name_id != id { + continue; + } + let (rank, s) = match platform { + 3 | 0 => { + let s = String::from_utf16_lossy(&bytes.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect::>()); + (if language == 0x409 { 0 } else { 1 }, s) + } + 1 => (if language == 0 { 2 } else { 3 }, bytes.iter().map(|b| char::from(*b)).collect()), + _ => continue, + }; + let s = s.trim().to_string(); + if !s.is_empty() && best.as_ref().is_none_or(|(r, _)| rank < *r) { + best = Some((rank, s)); + } + } + best.map(|(_, s)| s) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A `name` table with the given (platform, language, name id, bytes) records. + fn name_table(records: &[(u16, u16, u16, Vec)]) -> Vec { + let base = 6 + 12 * records.len(); + let mut t: Vec = [0u16, records.len() as u16, base as u16].iter().flat_map(|v| v.to_be_bytes()).collect(); + let mut strings: Vec = Vec::new(); + for (platform, language, id, bytes) in records { + for v in [*platform, 1, *language, *id, bytes.len() as u16, strings.len() as u16] { + t.extend(v.to_be_bytes()); + } + strings.extend(bytes); + } + t.extend(strings); + t + } + + fn utf16(s: &str) -> Vec { + s.encode_utf16().flat_map(u16::to_be_bytes).collect() + } + + #[test] + fn names_prefer_english_windows_records() { + let t = + name_table(&[(1, 0, 1, b"Mac Name".to_vec()), (3, 0x407, 1, utf16("Deutsch")), (3, 0x409, 1, utf16("Plain Sans")), (3, 0x409, 2, utf16("Bold"))]); + assert_eq!(name_string(&t, 1).as_deref(), Some("Plain Sans")); + assert_eq!(name_string(&t, 2).as_deref(), Some("Bold")); + assert_eq!(name_string(&t, 16), None); + // Truncated or hostile tables give nothing rather than panicking. + for n in 0..t.len() { + let _ = name_string(&t[..n], 1); + } + assert_eq!(name_string(&[0xff; 64], 1), None); + } + + #[test] + fn faces_of_a_file_and_garbage() { + let dir = std::env::temp_dir().join(format!("tc-fonts-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("font.ttf"); + // A font file with only a name table: offset table, one table record, the table. + let names = name_table(&[(3, 0x409, 1, utf16("Plain Sans")), (3, 0x409, 2, utf16("Italic"))]); + let mut file: Vec = [0x0001_0000u32.to_be_bytes().to_vec(), 1u16.to_be_bytes().to_vec(), vec![0; 6]].concat(); + file.extend(b"name"); + file.extend([0u32, 28, names.len() as u32].iter().flat_map(|v| v.to_be_bytes())); + file.extend(&names); + std::fs::write(&path, &file).unwrap(); + let faces = faces_of(&path).unwrap(); + assert_eq!((faces[0].family.as_str(), faces[0].style.as_str(), faces[0].index), ("Plain Sans", "Italic", 0)); + std::fs::write(&path, b"garbage").unwrap(); + assert!(faces_of(&path).is_err() || faces_of(&path).unwrap().is_empty()); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/formats/src/image_res.rs b/crates/formats/src/image_res.rs index 9d1a7654..9b67aaf8 100644 --- a/crates/formats/src/image_res.rs +++ b/crates/formats/src/image_res.rs @@ -29,6 +29,17 @@ pub fn decode_image(bytes: &[u8]) -> Result { Ok(DecodedImage { width, height, rgba, srgb }) } +/// PNG bytes of an `rgb` (sRGB) image whose alpha is `coverage` (`width × height`, top row first): +/// drawn text as an image resource. +pub fn coverage_png(width: u32, height: u32, coverage: &[u8], rgb: [u8; 3]) -> Result> { + let rgba: Vec = coverage.iter().flat_map(|a| [rgb[0], rgb[1], rgb[2], *a]).collect(); + let img = image::RgbaImage::from_raw(width, height, rgba) + .ok_or_else(|| FormatError::Invalid(format!("{} coverage values for {width}x{height}", coverage.len())))?; + let mut png = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| FormatError::Invalid(e.to_string()))?; + Ok(png) +} + #[cfg(test)] mod tests { use super::*; @@ -44,5 +55,8 @@ mod tests { assert!((d.rgba[1][0] - 60.0 / 255.0).abs() < 1e-3); assert!(decode_image(b"not an image").is_err()); assert!(decode_image(&png[..png.len() / 2]).is_err()); + let text = decode_image(&coverage_png(2, 1, &[0, 255], [255; 3]).unwrap()).unwrap(); + assert_eq!(text.rgba, vec![[1.0, 1.0, 1.0, 0.0], [1.0; 4]]); + assert!(coverage_png(2, 2, &[0], [255; 3]).is_err()); } } diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 249ff0f7..3af93ab2 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -15,6 +15,7 @@ //! - [`presets`]: the built-in export presets and JSON (de)serialization of user presets. //! - [`project_file`]: the `.tcraft` project zip (project JSON, sparse lossless pixel tiles, //! baked maps, the original mesh and a thumbnail). +//! - `fonts`: the installed fonts' families and styles (native only), for text alphas. //! //! Every reader takes untrusted bytes and returns an error, never panics. Byte-based functions //! work everywhere (including the web build); path-based ones are native only. @@ -22,6 +23,8 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod export; +#[cfg(not(target_arch = "wasm32"))] +pub mod fonts; pub mod image_res; pub mod mesh_export; pub mod mesh_import; @@ -31,7 +34,7 @@ pub mod project_file; pub use export::{ Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapSpec, Padding, PlannedFile, SourceRef, VirtualMap, list_outputs, render_maps, }; -pub use image_res::{DecodedImage, decode_image}; +pub use image_res::{DecodedImage, coverage_png, decode_image}; pub use mesh_export::{GlbTextures, UsdExport, UsdFormat, glb_bytes, glb_export_options, obj_bytes, usd_bytes, usd_export_options}; pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_high_poly_bytes, import_mesh_bytes, self_contained_mesh}; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/paint/Cargo.toml b/crates/paint/Cargo.toml index 6cc99089..0b4bb7af 100644 --- a/crates/paint/Cargo.toml +++ b/crates/paint/Cargo.toml @@ -14,4 +14,9 @@ texturecraft-texel = { workspace = true } texturecraft-geom = { workspace = true } texturecraft-compose = { workspace = true } rayon = { workspace = true } +harfrust = { workspace = true } +skrifa = { workspace = true } serde = { workspace = true } + +[dev-dependencies] +epaint_default_fonts = { workspace = true } diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index 626f0fb7..7bcd4334 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -112,12 +112,15 @@ impl Shape<'_> { } } -/// An image as a brush alpha: luminance × alpha over the stamp square (−1..1, y up), 0 outside. +/// An image as a brush alpha: luminance × alpha, its longer side across the stamp square (−1..1, +/// y up) so it keeps its proportions (a line of text stays a line), 0 outside. pub fn image_alpha(img: &ImageRes, lx: f32, ly: f32) -> f32 { - if !(lx.abs() <= 1.0 && ly.abs() <= 1.0) { + let aspect = img.width as f32 / img.height.max(1) as f32; + let (x, y) = if aspect >= 1.0 { (lx, ly * aspect) } else { (lx / aspect.max(1e-6), ly) }; + if !(x.abs() <= 1.0 && y.abs() <= 1.0) { return 0.0; } - let [r, g, b, a] = img.sample(lx * 0.5 + 0.5, 0.5 - ly * 0.5); + let [r, g, b, a] = img.sample(x * 0.5 + 0.5, 0.5 - y * 0.5); ((0.2126 * r + 0.7152 * g + 0.0722 * b) * a).clamp(0.0, 1.0) } diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index fa689f5c..143ab29a 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -6,7 +6,8 @@ //! see ([`EyeDepth`]); [`commit`] blends the finished stroke into layer pixels. Clone and smudge //! strokes carry channel values ([`pickup`]) instead of painting the tool's material. //! [`path`] samples the Path tool's curves and lasso coverage; [`particles`] runs the particle -//! brush; [`alphas`] is the built-in library of procedural brush alphas. +//! brush; [`alphas`] is the built-in library of procedural brush alphas; [`text`] draws text for +//! text alphas and decals. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -18,6 +19,7 @@ pub mod path; pub mod pickup; pub mod raster; pub mod stroke; +pub mod text; pub mod visibility; pub use brush::{Alignment, BrushAlpha, BrushSettings, Particles, Shape, Symmetry, image_alpha}; diff --git a/crates/paint/src/text.rs b/crates/paint/src/text.rs new file mode 100644 index 00000000..15d9cf26 --- /dev/null +++ b/crates/paint/src/text.rs @@ -0,0 +1,254 @@ +//! Text as a coverage image, for brush alphas and decals: each line shaped with harfrust +//! (kerning, ligatures, joined scripts), drawn from the font's outlines (skrifa) and filled with +//! a non-zero scanline rasterizer, lines centered. + +use harfrust::{FontRef, ShapeOptions, ShaperData, UnicodeBuffer}; +use skrifa::MetadataProvider; +use skrifa::instance::{LocationRef, Size}; +use skrifa::outline::{DrawSettings, OutlinePen}; + +/// Longest text drawn (characters). +pub const MAX_TEXT_CHARS: usize = 1000; +/// Largest side of a text image (texels); bigger layouts are drawn smaller to fit. +pub const MAX_TEXT_SIDE: u32 = 4096; +/// Vertical samples per texel row. +const SUBROWS: usize = 4; + +/// A shaped glyph: its id and pen position (font units). +type Placed = (u32, f32, f32); + +/// Coverage 0..=255 per texel, rows top to bottom. +#[derive(Clone, Debug, PartialEq)] +pub struct TextImage { + pub width: u32, + pub height: u32, + pub coverage: Vec, +} + +/// Draw `text` (one or more lines) with face `index` of `font` at `px` texels per em, cropped to +/// the ink with a margin of a tenth of an em. +pub fn render_text(font: &[u8], index: u32, text: &str, px: f32) -> Result { + let text = text.trim_end(); + if text.trim().is_empty() { + return Err("the text is empty".into()); + } + if text.chars().count() > MAX_TEXT_CHARS { + return Err(format!("the text is longer than {MAX_TEXT_CHARS} characters")); + } + let font = FontRef::from_index(font, index).map_err(|e| format!("not a usable font: {e}"))?; + // Layout in font units; `scale` turns them into texels. + let m = font.metrics(Size::unscaled(), LocationRef::default()); + let upem = f32::from(m.units_per_em.max(1)); + let line = (m.ascent - m.descent + m.leading).max(upem * 0.5); + let data = ShaperData::new(&font); + let shaper = data.shaper(&font).build(); + let mut lines: Vec<(f32, Vec)> = Vec::new(); + for t in text.lines() { + let mut buffer = UnicodeBuffer::new(); + buffer.push_str(t); + buffer.guess_segment_properties(); + let shaped = shaper.shape(buffer, ShapeOptions::new()); + let mut x = 0.0; + let mut glyphs = Vec::new(); + for (info, pos) in shaped.glyph_infos().iter().zip(shaped.glyph_positions()) { + glyphs.push((info.glyph_id, x + pos.x_offset as f32, pos.y_offset as f32)); + x += pos.x_advance as f32; + } + lines.push((x, glyphs)); + } + let widest = lines.iter().map(|(w, _)| *w).fold(0.0, f32::max); + let px = px.clamp(4.0, 1024.0); + // Outlines in texels (y down) at the shaped positions, lines centered on the widest. + let outlines = font.outline_glyphs(); + let mut pen = Edges { scale: px / upem, ..Edges::default() }; + for (row, (line_width, glyphs)) in lines.iter().enumerate() { + let left = (widest - line_width) * 0.5; + for &(id, x, y) in glyphs { + let Some(glyph) = outlines.get(skrifa::GlyphId::new(id)) else { continue }; + pen.origin = ((left + x) * pen.scale, (line * row as f32 - y) * pen.scale); + // A glyph that can't be drawn is left out rather than failing the text. + let _ = glyph.draw(DrawSettings::unhinted(Size::unscaled(), LocationRef::default()), &mut pen); + pen.close(); + } + } + // The image is the ink's bounds plus the margin (accents and descenders never clip), scaled + // down when that is too large. + let points = || pen.edges.iter().flat_map(|e| [(e[0], e[1]), (e[2], e[3])]); + let lo = points().fold((f32::MAX, f32::MAX), |a, p| (a.0.min(p.0), a.1.min(p.1))); + let hi = points().fold((f32::MIN, f32::MIN), |a, p| (a.0.max(p.0), a.1.max(p.1))); + if pen.edges.is_empty() || !(lo.0.is_finite() && hi.0.is_finite() && lo.1.is_finite() && hi.1.is_finite()) { + return Err("the font draws nothing for this text".into()); + } + let margin = px * 0.1; + let (w, h) = (hi.0 - lo.0 + 2.0 * margin, hi.1 - lo.1 + 2.0 * margin); + let fit = (MAX_TEXT_SIDE as f32 / w.max(h)).min(1.0); + let edges: Vec<[f32; 4]> = pen + .edges + .iter() + .map(|e| [(e[0] - lo.0 + margin) * fit, (e[1] - lo.1 + margin) * fit, (e[2] - lo.0 + margin) * fit, (e[3] - lo.1 + margin) * fit]) + .collect(); + let (width, height) = ((w * fit).ceil().max(1.0) as u32, (h * fit).ceil().max(1.0) as u32); + Ok(TextImage { width, height, coverage: fill(&edges, width as usize, height as usize) }) +} + +/// Line segments (texel space, y down) collected from glyph outlines: font units times `scale` +/// from `origin`, curves flattened. +#[derive(Default)] +struct Edges { + scale: f32, + origin: (f32, f32), + start: (f32, f32), + at: (f32, f32), + edges: Vec<[f32; 4]>, +} + +impl Edges { + fn map(&self, x: f32, y: f32) -> (f32, f32) { + (self.origin.0 + x * self.scale, self.origin.1 - y * self.scale) + } + + fn segment(&mut self, to: (f32, f32)) { + if to != self.at { + self.edges.push([self.at.0, self.at.1, to.0, to.1]); + } + self.at = to; + } + + /// Flatten a curve given as a point function of t in 0..1, finer for longer curves. + fn curve(&mut self, control_length: f32, point: impl Fn(f32) -> (f32, f32)) { + let steps = (control_length.sqrt() * 2.0).clamp(2.0, 64.0) as usize; + for i in 1..=steps { + self.segment(point(i as f32 / steps as f32)); + } + } +} + +fn dist(a: (f32, f32), b: (f32, f32)) -> f32 { + (a.0 - b.0).hypot(a.1 - b.1) +} + +impl OutlinePen for Edges { + fn move_to(&mut self, x: f32, y: f32) { + self.close(); + self.start = self.map(x, y); + self.at = self.start; + } + + fn line_to(&mut self, x: f32, y: f32) { + let p = self.map(x, y); + self.segment(p); + } + + fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) { + let (p0, c, p) = (self.at, self.map(cx0, cy0), self.map(x, y)); + self.curve(dist(p0, c) + dist(c, p), |t| { + let s = 1.0 - t; + (s * s * p0.0 + 2.0 * s * t * c.0 + t * t * p.0, s * s * p0.1 + 2.0 * s * t * c.1 + t * t * p.1) + }); + } + + fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) { + let (p0, c0, c1, p) = (self.at, self.map(cx0, cy0), self.map(cx1, cy1), self.map(x, y)); + self.curve(dist(p0, c0) + dist(c0, c1) + dist(c1, p), |t| { + let s = 1.0 - t; + let (a, b, c, d) = (s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t); + (a * p0.0 + b * c0.0 + c * c1.0 + d * p.0, a * p0.1 + b * c0.1 + c * c1.1 + d * p.1) + }); + } + + fn close(&mut self) { + self.segment(self.start); + } +} + +/// Non-zero winding coverage of closed `edges` over a `w × h` grid: [`SUBROWS`] scanlines per +/// row, each span's ends spread over the texels they cross. +fn fill(edges: &[[f32; 4]], w: usize, h: usize) -> Vec { + let mut acc = vec![0f32; w * h]; + // Edges by their top, and the ones the current scanline may cross. + let mut sorted: Vec<[f32; 4]> = edges.iter().copied().filter(|e| e[1] != e[3]).collect(); + sorted.sort_by(|a, b| a[1].min(a[3]).total_cmp(&b[1].min(b[3]))); + let (mut next, mut active) = (0, Vec::new()); + let mut crossings: Vec<(f32, i32)> = Vec::new(); + for row in 0..h { + for sub in 0..SUBROWS { + let y = row as f32 + (sub as f32 + 0.5) / SUBROWS as f32; + while let Some(e) = sorted.get(next).filter(|e| e[1].min(e[3]) <= y) { + active.push(*e); + next += 1; + } + active.retain(|e| e[1].max(e[3]) > y); + crossings.clear(); + for &[x0, y0, x1, y1] in &active { + if (y0 <= y) != (y1 <= y) { + crossings.push((x0 + (y - y0) / (y1 - y0) * (x1 - x0), if y1 > y0 { 1 } else { -1 })); + } + } + crossings.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut winding = 0; + for pair in crossings.windows(2) { + winding += pair[0].1; + if winding != 0 { + span(&mut acc[row * w..(row + 1) * w], pair[0].0, pair[1].0); + } + } + } + } + acc.iter().map(|c| (c / SUBROWS as f32 * 255.0).round().clamp(0.0, 255.0) as u8).collect() +} + +/// Add the covered length of `x0..x1` to each texel of `row`. +fn span(row: &mut [f32], x0: f32, x1: f32) { + let (x0, x1) = (x0.clamp(0.0, row.len() as f32), x1.clamp(0.0, row.len() as f32)); + if x1 <= x0 { + return; + } + for (i, c) in row.iter_mut().enumerate().take(x1.ceil() as usize).skip(x0.floor() as usize) { + *c += (x1.min(i as f32 + 1.0) - x0.max(i as f32)).max(0.0); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn spans_spread_partial_texels() { + let mut row = [0.0; 4]; + span(&mut row, 0.5, 2.25); + assert_eq!(row, [0.5, 1.0, 0.25, 0.0]); + // A square drawn either way round fills the same texels. + let square = |cw: bool| { + let p = [(1.0, 1.0), (3.0, 1.0), (3.0, 3.0), (1.0, 3.0)]; + let p: Vec<_> = if cw { p.to_vec() } else { p.iter().rev().copied().collect() }; + (0..4).map(|i| [p[i].0, p[i].1, p[(i + 1) % 4].0, p[(i + 1) % 4].1]).collect::>() + }; + let a = fill(&square(true), 4, 4); + assert_eq!(a, fill(&square(false), 4, 4)); + assert_eq!((a[5], a[0], a[3 * 4 + 3]), (255, 0, 0), "inside full, outside empty"); + } + + #[test] + fn text_is_laid_out_and_filled() { + let font = epaint_default_fonts::UBUNTU_LIGHT; + let one = render_text(font, 0, "H", 64.0).unwrap(); + let two = render_text(font, 0, "HH", 64.0).unwrap(); + let lines = render_text(font, 0, "H\nH", 64.0).unwrap(); + assert!(two.width > one.width && two.height == one.height); + assert!(lines.height > one.height && lines.width == one.width, "lines stack"); + let ink = |t: &TextImage| t.coverage.iter().map(|c| u32::from(*c)).sum::(); + assert!(ink(&two) > ink(&one) * 19 / 10 && ink(&two) < ink(&one) * 21 / 10, "two H, twice the ink"); + assert!(one.coverage.contains(&255) && one.coverage.contains(&0)); + // The margin stays clear; huge sizes are drawn to fit. + assert!(one.coverage[..one.width as usize].iter().all(|c| *c == 0)); + let big = render_text(font, 0, &"W".repeat(400), 1024.0).unwrap(); + assert!(big.width <= MAX_TEXT_SIDE && big.height >= 1); + } + + #[test] + fn bad_input_is_an_error() { + assert!(render_text(b"not a font", 0, "Hi", 64.0).is_err()); + assert!(render_text(b"", 0, " ", 64.0).is_err()); + assert!(render_text(b"", 0, &"x".repeat(MAX_TEXT_CHARS + 1), 64.0).is_err()); + } +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index d69cdbcf..5bce3896 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1106,7 +1106,8 @@ fn alpha_tile(ui: &mut Ui, on: bool, label: &str, paint: impl FnOnce(&egui::Pain p.rect_stroke(rect, 3.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); } paint(p, Rect::from_center_size(rect.center() - vec2(0.0, 7.0), vec2(40.0, 40.0))); - p.text(rect.center_bottom() - vec2(0.0, 6.0), egui::Align2::CENTER_CENTER, label, egui::FontId::proportional(9.5), tk.viewport_text); + let name = elided(p, label, 9.5, tk.viewport_text, rect.width() - 4.0); + p.galley(rect.center_bottom() - vec2(name.size().x * 0.5, 6.0 + name.size().y * 0.5), name, tk.viewport_text); resp.on_hover_text(label) } @@ -1155,6 +1156,62 @@ fn alpha_section(app: &mut TextureCraftApp, ui: &mut Ui) { } ui.label(RichText::new(tr("More in Assets > Alphas: click one, or drag it here")).size(10.0).color(tk.text_dim)); crate::shelf::drop_target(app, ui, &zone.response, crate::shelf::DropZone::Brush); + section(ui, "sec_text", tr("Text"), true, |ui| text_section(app, ui)); +} + +/// Text drawn in a font, as the brush alpha or a decal (`resource.text`). +fn text_section(app: &mut TextureCraftApp, ui: &mut Ui) { + if app.ui.text.fonts.is_empty() + && let Some(f) = app.run("text.fonts", Value::Null) + { + let installed = f["installed"].as_array().into_iter().flatten().map(|v| { + let styles = v["styles"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(); + (v["family"].as_str().unwrap_or_default().to_string(), styles) + }); + let built_in = f["builtIn"].as_array().into_iter().flatten().filter_map(Value::as_str).map(|n| (n.to_string(), Vec::new())); + app.ui.text.fonts = installed.chain(built_in).collect(); + } + // A decal shows the text in the tool's base color; an alpha must stay white. + let color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([1.0; 3]); + let t = &mut app.ui.text; + ui.add(egui::TextEdit::multiline(&mut t.text).desired_rows(2).desired_width(f32::INFINITY).hint_text(tr("Text"))); + let shown = if t.font.is_empty() { tr("Default").to_string() } else { t.font.clone() }; + combo(ui, tr("Font"), shown, |ui| { + if ui.selectable_label(t.font.is_empty(), tr("Default")).clicked() { + (t.font, t.style) = (String::new(), String::new()); + } + for (family, _) in &t.fonts { + if ui.selectable_label(t.font == *family, family).clicked() { + (t.font, t.style) = (family.clone(), String::new()); + } + } + }); + let styles = t.fonts.iter().find(|(f, _)| *f == t.font).map(|(_, s)| s.clone()).unwrap_or_default(); + if styles.len() > 1 { + let shown = if t.style.is_empty() { tr("Default").to_string() } else { t.style.clone() }; + combo(ui, tr("Style"), shown, |ui| { + for s in styles { + ui.selectable_value(&mut t.style, s.clone(), s); + } + }); + } + let mut params = json!({"text": t.text, "font": (!t.font.is_empty()).then_some(&t.font), "style": (!t.style.is_empty()).then_some(&t.style)}); + let ready = !t.text.trim().is_empty(); + ui.horizontal_wrapped(|ui| { + let alpha = ui.add_enabled(ready, egui::Button::new(tr("Use as brush alpha"))).clicked(); + let decal = ui.add_enabled(ready, egui::Button::new(tr("Place as decal"))).clicked(); + if decal { + params["color"] = json!(color); + } + if (alpha || decal) + && let Some(name) = app.run("resource.text", params).and_then(|r| r["name"].as_str().map(str::to_string)) + { + match alpha { + true => app.run("tool.brush", json!({"alpha": {"image": name}})), + false => app.run("layer.add.decal", json!({"image": name})), + }; + } + }); } fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) { diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ce534a6f..145ce28f 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -979,4 +979,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Fensterrahmen und Fenstertasten des Betriebssystems statt der eigenen Titelleiste von TextureCraft verwenden", ), + ("Text", "Text"), + ("Font", "Schrift"), + ("Style", "Schnitt"), + ("Use as brush alpha", "Als Pinsel-Alpha verwenden"), + ("Place as decal", "Als Decal platzieren"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 2b57afd8..bce1f3e4 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -964,4 +964,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Usar el marco y los botones de ventana del sistema operativo en lugar de la barra de título propia de TextureCraft", ), + ("Text", "Texto"), + ("Font", "Fuente"), + ("Style", "Estilo"), + ("Use as brush alpha", "Usar como alfa del pincel"), + ("Place as decal", "Colocar como calcomanía"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 0e72b031..3caf55f5 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -979,4 +979,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Utiliser le cadre et les boutons de fenêtre du système d'exploitation au lieu de la barre de titre de TextureCraft", ), + ("Text", "Texte"), + ("Font", "Police"), + ("Style", "Style"), + ("Use as brush alpha", "Utiliser comme alpha du pinceau"), + ("Place as decal", "Placer en décalque"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 9260b188..179d225f 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -973,4 +973,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Usa la cornice e i pulsanti della finestra del sistema operativo invece della barra del titolo di TextureCraft", ), + ("Text", "Testo"), + ("Font", "Carattere"), + ("Style", "Stile"), + ("Use as brush alpha", "Usa come alpha del pennello"), + ("Place as decal", "Posiziona come decal"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 2e333ab9..146bf9b0 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -946,4 +946,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "TextureCraft 独自のタイトルバーの代わりに、OS のウィンドウ枠とボタンを使います", ), + ("Text", "テキスト"), + ("Font", "フォント"), + ("Style", "スタイル"), + ("Use as brush alpha", "ブラシのアルファとして使用"), + ("Place as decal", "デカールとして配置"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 3945c9a9..c4cd3511 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -931,4 +931,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "TextureCraft 자체 제목 표시줄 대신 운영 체제의 창 테두리와 버튼을 사용합니다", ), + ("Text", "텍스트"), + ("Font", "글꼴"), + ("Style", "스타일"), + ("Use as brush alpha", "브러시 알파로 사용"), + ("Place as decal", "데칼로 배치"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 788df7f9..1e5e1a50 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -961,4 +961,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Usar a moldura e os botões de janela do sistema operacional em vez da barra de título própria do TextureCraft", ), + ("Text", "Texto"), + ("Font", "Fonte"), + ("Style", "Estilo"), + ("Use as brush alpha", "Usar como alpha do pincel"), + ("Place as decal", "Colocar como decalque"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 3de5246c..e299df09 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -877,4 +877,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "使用操作系统的窗口边框和按钮,而不是 TextureCraft 自己的标题栏", ), + ("Text", "文字"), + ("Font", "字体"), + ("Style", "样式"), + ("Use as brush alpha", "用作笔刷 Alpha"), + ("Place as decal", "作为贴花放置"), ]; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 2e137e13..603b4a91 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -15,6 +15,18 @@ pub enum Mode { Rendering, } +/// The Alpha tab's text: what to draw and in which font (empty: the default font). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct TextUi { + pub text: String, + pub font: String, + pub style: String, + /// Installed and built-in families with their styles (`text.fonts`), read when first shown. + #[serde(skip)] + pub fonts: Vec<(String, Vec)>, +} + /// Rendering mode settings. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] @@ -209,6 +221,8 @@ pub struct UiState { #[serde(default)] pub shelf_tab: usize, pub props_tab: PropsTab, + #[serde(default)] + pub text: TextUi, /// Layer being renamed and the edit buffer. pub rename: Option<(u64, String)>, pub new_project: NewProject, @@ -263,6 +277,7 @@ impl Default for UiState { shelf_filter: String::new(), shelf_tab: 0, props_tab: PropsTab::Brush, + text: TextUi::default(), rename: None, new_project: NewProject::default(), uv_wireframe: true, diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index d372ffa9..2322b100 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -114,11 +114,18 @@ impl Thumbs { 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 s = img.sample((x as f32 + 0.5) / n as f32, (y as f32 + 0.5) / n as f32); - let enc = |v: f32| if img.srgb { (v.clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(v) * 255.0) as u8 }; + 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])); } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 5b34d50b..14dd6de4 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -109,7 +109,8 @@ print(call("command.run", {"id": "layer.add.fill", "params": {"color": [0.8, 0.1 Through `command_run`, every `file.*` command but `file.close` (and `file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir` (`resource.import`, -`material.save`, `material.load`, …), in both modes: use the workspace tools below. +`material.save`, `material.load`, …), in both modes: use the workspace tools below. `resource.text` +takes a font family, not a path: it reads only the system's font folders. | Tool | Params | Notes | |---|---|---| diff --git a/docs/features.md b/docs/features.md index 02cfd08c..fc853fcf 100644 --- a/docs/features.md +++ b/docs/features.md @@ -14,6 +14,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA straight lines, and painting directly in the **2D UV view**. - **Geometry decals:** drop an image on the surface, then move, scale and turn its frame; it stays an editable fill layer. +- **Text** in any installed font (or the built-in ones), shaped for every script with kerning and + ligatures, one or more lines: stamp it with the brush as its alpha, or place it as a decal in the + tool's base color (Properties › Alpha › Text). - **Quick mask** (Y): paint a temporary mask (U to edit, Ctrl+Shift+I to invert) that protects everything outside it while you paint. - **Every channel at once:** base color, metallic, roughness, height, normal, emissive, opacity, From 50ce39fd5122e7d05dbfb59d099209d4ea7d8fac Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 04:09:36 +0700 Subject: [PATCH 07/60] Text: Arabic labels for the text controls --- crates/ui-egui/src/i18n/ar.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 0320cbf7..e35cb5a2 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -924,4 +924,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "استخدام إطار وأزرار نافذة نظام التشغيل بدلاً من شريط عنوان TextureCraft الخاص", ), + ("Text", "نص"), + ("Font", "الخط"), + ("Style", "النمط"), + ("Use as brush alpha", "استخدام كألفا للفرشاة"), + ("Place as decal", "وضع كملصق"), ]; From 3591e027587aefbb8c2670d0f62e0d5e827e65cb Mon Sep 17 00:00:00 2001 From: Agapenordev <120006055+Agapenordev@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:12:12 +0100 Subject: [PATCH 08/60] Address review: WebGPU verdicts, repaints, lasting memory notice MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Allocation checks never take an unanswered error scope as success: native backends block on the verdict; the browser's WebGPU answers later, so the full-size texture waits beside the bound placeholder (tiles go into it under discarded scopes) and Renderer::prepare installs it on success, or keeps the placeholder and reports the set on failure. The UI keeps drawing frames while a verdict is pending. - The GPU side wakes the UI when it records an uncaptured error or an allocation failure, so the notice shows even when the app is idle; failures are collected after prepare, where late verdicts land. - Sets the GPU could not hold share one sticky notice (dismissible, listing them) instead of a six-second toast each, since they are not retried. - The out-of-memory error is reported as the cause rather than the follow-on invalid-texture error. - The notice no longer uses "▸", which the UI fonts lack (egui panics on a missing glyph). Tests: a late texture stays unbound until accepted; a late rejection keeps the placeholder and is reported once; a verdict that never comes counts as a failure. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/render/Cargo.toml | 4 + crates/render/src/gpu_trace.rs | 48 +++++++ crates/render/src/renderer.rs | 221 ++++++++++++++++++++++++----- crates/ui-egui/src/gpu.rs | 32 +++-- crates/ui-egui/src/i18n/de.rs | 8 +- crates/ui-egui/src/i18n/es.rs | 8 +- crates/ui-egui/src/i18n/fr.rs | 8 +- crates/ui-egui/src/i18n/it.rs | 8 +- crates/ui-egui/src/i18n/ja.rs | 8 +- crates/ui-egui/src/i18n/ko.rs | 8 +- crates/ui-egui/src/i18n/pt_br.rs | 8 +- crates/ui-egui/src/i18n/zh_hans.rs | 8 +- crates/ui-egui/src/lib.rs | 29 +++- crates/ui-egui/src/viewport.rs | 43 +++++- 15 files changed, 372 insertions(+), 70 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e5d4279f..3c5e4612 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3978,6 +3978,7 @@ dependencies = [ "texturecraft-core", "texturecraft-geom", "texturecraft-texel", + "wasm-bindgen-futures", "wgpu", ] diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index b287a19f..080f12ba 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -23,5 +23,9 @@ rayon = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] pollster = "0.4" +# The browser's WebGPU resolves error scopes later: their results are awaited on the page. +[target.'cfg(target_arch = "wasm32")'.dependencies] +wasm-bindgen-futures = "0.4" + [dev-dependencies] image = { workspace = true } diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 0f25ed4f..775fc026 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -140,6 +140,54 @@ pub(crate) fn scoped(device: &wgpu::Device, what: &str, f: impl FnOnce() -> T } } +/// What [`checked`] knows right after the call. +pub(crate) enum Checked { + /// wgpu answered at once (native backends, WebGL): the value, or what went wrong. + Done(Result), + /// The browser's WebGPU answers later: the value, possibly invalid, and where the answer + /// arrives (`None` for success). Don't use the value until it arrives. (Native backends + /// never answer late; the renderer's tests build this variant by hand.) + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + Later(T, std::sync::mpsc::Receiver>), +} + +/// [`scoped`] for work whose errors may arrive later: never takes an unanswered scope as success. +pub(crate) fn checked(device: &wgpu::Device, what: &str, f: impl FnOnce() -> T) -> Checked { + let oom = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let invalid = device.push_error_scope(wgpu::ErrorFilter::Validation); + let out = f(); + let (invalid, oom) = (invalid.pop(), oom.pop()); + let what = what.to_string(); + let mut answer = Box::pin(async move { + let invalid = invalid.await; + let oom = oom.await; + // An allocation that ran out of memory also makes later calls on it invalid: the + // out-of-memory error is the cause. + oom.or(invalid).map(|e| format!("{what}: {e}")) + }); + #[cfg(not(target_arch = "wasm32"))] + { + Checked::Done(match pollster::block_on(answer.as_mut()) { + Some(e) => Err(e), + None => Ok(out), + }) + } + #[cfg(target_arch = "wasm32")] + { + match answer.as_mut().poll(&mut Context::from_waker(Waker::noop())) { + Poll::Ready(Some(e)) => Checked::Done(Err(e)), + Poll::Ready(None) => Checked::Done(Ok(out)), + Poll::Pending => { + let (tx, rx) = std::sync::mpsc::channel(); + wasm_bindgen_futures::spawn_local(async move { + let _ = tx.send(answer.await); + }); + Checked::Later(out, rx) + } + } + } +} + pub(crate) fn entry(binding: u32, ty: wgpu::BindingType) -> wgpu::BindGroupLayoutEntry { wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty, count: None } } diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index d840a998..63250283 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -30,7 +30,7 @@ use texturecraft_geom::glam::{Mat4, Vec3}; use texturecraft_geom::{Mesh, OrbitCamera}; use texturecraft_texel::TILE; -use crate::gpu_trace::scoped; +use crate::gpu_trace::{Checked, checked}; use crate::ibl; use crate::subdivide::{self, Vertex}; @@ -337,6 +337,58 @@ struct SetGpu { /// Textures whose full-size allocation failed (out of GPU memory): they keep their /// placeholder until the set is re-created, instead of retrying on every tile. failed: Vec, + /// Full-size textures the browser's WebGPU has not yet confirmed: tiles go into them while + /// the placeholder stays bound (see [`Renderer::resolve_pending`]). + pending: Vec>, +} + +/// A full-size texture waiting for WebGPU's verdict on its allocation. +struct PendingTex { + tex: Tex, + /// `None` for success, else what went wrong. (A mutex: the renderer is shared with the + /// paint callback, so it must be `Sync`.) + answer: std::sync::Mutex>>, +} + +/// Swap `tex` in for slot `slot` of `set` (bound at once; its mips are rebuilt). +fn install(set: &mut SetGpu, slot: usize, tex: Tex, device: &wgpu::Device, layout: &wgpu::BindGroupLayout, sampler: &wgpu::Sampler) { + if let Some(s) = set.tex.get_mut(slot) { + *s = tex; + } + set.bind_group = set_bind_group(device, layout, sampler, &set.tex); + if let Some(d) = set.mips_dirty.get_mut(slot) { + *d = true; + } +} + +/// Give slot `slot` of `set` (texture set `ts`) the full-size texture `checked` allocated: +/// installed when wgpu accepted it, kept pending while WebGPU has not answered, or (out of GPU +/// memory) left as the placeholder with the failure recorded. False when there is nothing to +/// write into. +fn grow( + set: &mut SetGpu, + ts: usize, + slot: usize, + checked: Checked, + ctx: (&wgpu::Device, &wgpu::BindGroupLayout, &wgpu::Sampler), + failures: &mut Vec, +) -> bool { + match checked { + Checked::Done(Ok(full)) => install(set, slot, full, ctx.0, ctx.1, ctx.2), + Checked::Done(Err(e)) => { + if let Some(f) = set.failed.get_mut(slot) { + *f = true; + } + memory_failed(failures, ts, &e); + return false; + } + Checked::Later(tex, answer) => { + if let Some(p) = set.pending.get_mut(slot) { + *p = Some(PendingTex { tex, answer: std::sync::Mutex::new(answer) }); + } + } + } + true } /// Vertex and index buffers with their draws (first index, count, material). @@ -1098,7 +1150,7 @@ impl Renderer { tex.push(neutral_tex(device, queue, (1, 1), wgpu::TextureFormat::Rgba8Unorm, 1, &AUX_NEUTRAL)); let bind_group = set_bind_group(device, &self.set_bgl, &self.sampler, &tex); let n = tex.len(); - let gpu = SetGpu { size, shift, tex, bind_group, mips_dirty: vec![true; n], failed: vec![false; n] }; + let gpu = SetGpu { size, shift, tex, bind_group, mips_dirty: vec![true; n], failed: vec![false; n], pending: (0..n).map(|_| None).collect() }; if i < self.sets.len() { self.sets[i] = gpu; } else { @@ -1127,29 +1179,24 @@ impl Renderer { return; } let dims = display_dims(set.size, set.shift); - if t.texture.width() < dims.0 || t.texture.height() < dims.1 { + let awaiting = set.pending.get(ki).is_some_and(Option::is_some); + if !awaiting && (t.texture.width() < dims.0 || t.texture.height() < dims.1) { // A placeholder: neutral tiles change nothing, the first real one allocates it. if set.failed.get(ki).copied().unwrap_or(true) || bytes.chunks_exact(texel.len()).all(|px| px == texel.as_slice()) { return; } let what = format!("texture set {} ({kind:?}, {}×{})", ts + 1, dims.0, dims.1); - match scoped(device, &what, || neutral_tex(device, queue, dims, display_format(kind), mip_count(dims.0.max(dims.1)), texel)) { - Ok(full) => { - if let Some(slot) = set.tex.get_mut(ki) { - *slot = full; - } - set.bind_group = set_bind_group(device, &self.set_bgl, &self.sampler, &set.tex); - } - Err(e) => { - if let Some(f) = set.failed.get_mut(ki) { - *f = true; - } - memory_failed(&mut self.memory_failures, ts, &e); - return; - } + let full = checked(device, &what, || neutral_tex(device, queue, dims, display_format(kind), mip_count(dims.0.max(dims.1)), texel)); + if !grow(set, ts, ki, full, (device, &self.set_bgl, &self.sampler), &mut self.memory_failures) { + return; } } - let Some(t) = set.tex.get(ki) else { return }; + // While WebGPU has not confirmed the full-size texture, tiles go into it (its errors, if + // it is invalid, are dropped with these scopes) and the placeholder stays bound. + let pending = set.pending.get(ki).and_then(Option::as_ref).map(|p| &p.tex); + let Some(t) = pending.or(set.tex.get(ki)) else { return }; + let oom = pending.is_some().then(|| device.push_error_scope(wgpu::ErrorFilter::OutOfMemory)); + let invalid = pending.is_some().then(|| device.push_error_scope(wgpu::ErrorFilter::Validation)); // Downscaled sets take every `step`-th texel of the tile. let (step, n) = (1usize << set.shift.min(6), TILE >> set.shift.min(6)); let small: Vec; @@ -1171,6 +1218,9 @@ impl Renderer { wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(n * bpt), rows_per_image: Some(n) }, wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, ); + // Innermost scope first. + drop(invalid); + drop(oom); self.content_rev += 1; if let Some(d) = set.mips_dirty.get_mut(ki) { *d = true; @@ -1187,35 +1237,30 @@ impl Renderer { if size != want || rgba.len() < (size as usize) * (size as usize) * 4 { return; } - if t.texture.width() != size { + let awaiting = set.pending.get(ai).is_some_and(Option::is_some); + if !awaiting && t.texture.width() != size { if set.failed.get(ai).copied().unwrap_or(true) { return; } let what = format!("texture set {} (mesh map view, {size}×{size})", ts + 1); - match scoped(device, &what, || neutral_tex(device, queue, (size, size), wgpu::TextureFormat::Rgba8Unorm, mip_count(size), &AUX_NEUTRAL)) { - Ok(full) => { - if let Some(slot) = set.tex.last_mut() { - *slot = full; - } - set.bind_group = set_bind_group(device, &self.set_bgl, &self.sampler, &set.tex); - } - Err(e) => { - if let Some(f) = set.failed.get_mut(ai) { - *f = true; - } - memory_failed(&mut self.memory_failures, ts, &e); - return; - } + let full = checked(device, &what, || neutral_tex(device, queue, (size, size), wgpu::TextureFormat::Rgba8Unorm, mip_count(size), &AUX_NEUTRAL)); + if !grow(set, ts, ai, full, (device, &self.set_bgl, &self.sampler), &mut self.memory_failures) { + return; } } - let Some(t) = set.tex.last() else { return }; + let pending = set.pending.get(ai).and_then(Option::as_ref).map(|p| &p.tex); + let Some(t) = pending.or(set.tex.last()) else { return }; let (w, h) = (t.texture.width(), t.texture.height()); + let oom = pending.is_some().then(|| device.push_error_scope(wgpu::ErrorFilter::OutOfMemory)); + let invalid = pending.is_some().then(|| device.push_error_scope(wgpu::ErrorFilter::Validation)); queue.write_texture( wgpu::TexelCopyTextureInfo { texture: &t.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, rgba, wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 4), rows_per_image: Some(h) }, wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, ); + drop(invalid); + drop(oom); self.content_rev += 1; if let Some(d) = set.mips_dirty.last_mut() { *d = true; @@ -1228,6 +1273,40 @@ impl Renderer { std::mem::take(&mut self.memory_failures) } + /// Whether a full-size texture still waits for WebGPU's verdict: keep drawing frames, since + /// [`Renderer::prepare`] installs it (or reports the failure) once the answer is in. + pub fn awaiting_gpu(&self) -> bool { + self.sets.iter().any(|s| s.pending.iter().any(Option::is_some)) + } + + /// Install the pending full-size textures WebGPU accepted; drop the ones it rejected (their + /// placeholder stays and the failure is reported). + fn resolve_pending(&mut self, device: &wgpu::Device) { + for (ts, set) in self.sets.iter_mut().enumerate() { + for slot in 0..set.pending.len() { + let poll = |p: &PendingTex| p.answer.lock().unwrap_or_else(std::sync::PoisonError::into_inner).try_recv(); + let verdict = match set.pending.get(slot).and_then(Option::as_ref).map(poll) { + None | Some(Err(std::sync::mpsc::TryRecvError::Empty)) => continue, + Some(Ok(v)) => v, + Some(Err(std::sync::mpsc::TryRecvError::Disconnected)) => Some(format!("texture set {}: the GPU never answered", ts + 1)), + }; + let Some(p) = set.pending.get_mut(slot).and_then(Option::take) else { continue }; + match verdict { + None => { + install(set, slot, p.tex, device, &self.set_bgl, &self.sampler); + self.content_rev += 1; + } + Some(e) => { + if let Some(f) = set.failed.get_mut(slot) { + *f = true; + } + memory_failed(&mut self.memory_failures, ts, &e); + } + } + } + } + } + /// Size of the aux texture of a set (1 until a mesh map or mask was shown). pub fn aux_size(&self, ts: usize) -> Option { self.sets.get(ts).and_then(|s| s.tex.last()).map(|t| t.texture.width()) @@ -1549,6 +1628,7 @@ impl Renderer { /// `shade.taa` that repeats the previous one adds a jittered sample to the average instead, /// and renders nothing once [`TAA_SAMPLES`] are in. pub fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, frame: &Frame) { + self.resolve_pending(device); self.generate_mips(device, encoder); let rev = self.content_rev; let sample = match self.views.get(&frame.view_id) { @@ -1891,3 +1971,76 @@ impl Renderer { self.views.remove(&id); } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::headless::Headless; + + /// A headless renderer with one 256² texture set, and the base color slot's full-size + /// texture handed over as WebGPU would: allocated, with its verdict still to come. + fn awaiting() -> Option<(Headless, std::sync::mpsc::Sender>)> { + let Ok(mut h) = Headless::new() else { + eprintln!("skipping: no GPU adapter"); + return None; + }; + h.renderer.set_texture_sets(&h.device, &h.queue, &[((256, 256), 0)], 1); + let (tx, rx) = std::sync::mpsc::channel(); + let full = neutral_tex(&h.device, &h.queue, (256, 256), display_format(DisplayKind::BaseColor), mip_count(256), &[0, 0, 0, 255]); + let r = &mut h.renderer; + let set = r.sets.get_mut(0).unwrap(); + assert!(grow(set, 0, 0, Checked::Later(full, rx), (&h.device, &r.set_bgl, &r.sampler), &mut r.memory_failures)); + Some((h, tx)) + } + + fn base_width(h: &Headless) -> u32 { + h.renderer.display_textures()[0][0].width() + } + + fn prepare(h: &mut Headless) { + let mut enc = h.device.create_command_encoder(&Default::default()); + h.renderer.resolve_pending(&h.device); + h.renderer.generate_mips(&h.device, &mut enc); + h.queue.submit([enc.finish()]); + } + + #[test] + fn a_late_texture_stays_unbound_until_accepted() { + let Some((mut h, tx)) = awaiting() else { return }; + assert!(h.renderer.awaiting_gpu()); + // Tiles go into the pending texture; the placeholder stays bound and nothing is retried. + h.renderer.upload_tile(&h.device, &h.queue, 0, DisplayKind::BaseColor, 0, 0, &[200, 30, 30, 255].repeat(64 * 64)); + prepare(&mut h); + assert_eq!(base_width(&h), 1, "no verdict yet: the placeholder stays bound"); + assert!(h.renderer.awaiting_gpu()); + tx.send(None).unwrap(); + prepare(&mut h); + assert_eq!(base_width(&h), 256, "accepted: installed"); + assert!(!h.renderer.awaiting_gpu()); + assert!(h.renderer.take_memory_failures().is_empty()); + } + + #[test] + fn a_late_rejection_keeps_the_placeholder_and_is_reported() { + let Some((mut h, tx)) = awaiting() else { return }; + tx.send(Some("texture set 1 (BaseColor, 256×256): Out of Memory".into())).unwrap(); + prepare(&mut h); + assert_eq!(base_width(&h), 1); + assert!(!h.renderer.awaiting_gpu()); + assert_eq!(h.renderer.take_memory_failures(), vec![0]); + // The failed kind is not allocated again by later tiles. + h.renderer.upload_tile(&h.device, &h.queue, 0, DisplayKind::BaseColor, 1, 0, &[200, 30, 30, 255].repeat(64 * 64)); + prepare(&mut h); + assert_eq!(base_width(&h), 1); + assert!(!h.renderer.awaiting_gpu()); + } + + #[test] + fn a_verdict_that_never_comes_counts_as_a_failure() { + let Some((mut h, tx)) = awaiting() else { return }; + drop(tx); + prepare(&mut h); + assert_eq!(base_width(&h), 1); + assert_eq!(h.renderer.take_memory_failures(), vec![0]); + } +} diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index e94056f1..77db5727 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -44,6 +44,8 @@ pub struct GpuState { /// Raised when texture-set textures were recreated: the UI must upload every tile again. pub reset: Arc, pub reports: Arc>, + /// Wakes the UI when the GPU side has something to report. + pub ctx: egui::Context, } /// Problems the GPU side hands to the UI, which shows them as toasts. @@ -92,12 +94,12 @@ const UPLOAD_CHUNK: usize = 64; /// display kind, measured at ~5.5 µs on a desktop GPU), counted against the frame budget. const UPLOAD_MS_PER_TILE: f64 = 0.006; -pub fn init(rs: &egui_wgpu::RenderState) -> GpuLink { +pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { let reset = Arc::new(AtomicBool::new(false)); let reports = Arc::new(Mutex::new(GpuReports::default())); // wgpu's default handler panics on any error no scope caught (an out-of-memory texture, a // driver hiccup): report it instead, so the user keeps the session. - let sink = reports.clone(); + let (sink, wake) = (reports.clone(), ctx.clone()); rs.device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| { log::error!("GPU error: {e}"); let mut r = sink.lock().unwrap_or_else(PoisonError::into_inner); @@ -105,9 +107,11 @@ pub fn init(rs: &egui_wgpu::RenderState) -> GpuLink { if r.errors.len() < MAX_GPU_ERRORS && !r.errors.contains(&text) { r.errors.push(text); } + // The UI may be idle: draw a frame to show it. + wake.request_repaint(); })); let renderer = Renderer::new(&rs.device, &rs.queue, rs.target_format); - rs.renderer.write().callback_resources.insert(GpuState { renderer, reset: reset.clone(), reports: reports.clone() }); + rs.renderer.write().callback_resources.insert(GpuState { renderer, reset: reset.clone(), reports: reports.clone(), ctx: ctx.clone() }); let info = rs.adapter.get_info(); GpuLink { reset, @@ -298,17 +302,23 @@ impl CallbackTrait for ViewCallback { for (ts, size, bytes) in &sync.aux { gpu.renderer.upload_aux(device, queue, *ts, *size, bytes); } - let failed = gpu.renderer.take_memory_failures(); - if !failed.is_empty() { - let mut r = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner); - for ts in failed { - if !r.memory.contains(&ts) { - r.memory.push(ts); - } + } + // Also installs (or rejects) full-size textures WebGPU answered for since last frame. + gpu.renderer.prepare(device, queue, encoder, &self.frame); + let failed = gpu.renderer.take_memory_failures(); + if !failed.is_empty() { + let mut r = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner); + for ts in failed { + if !r.memory.contains(&ts) { + r.memory.push(ts); } } + // This frame's report drain already ran: the next frame shows the toast. + gpu.ctx.request_repaint(); + } + if gpu.renderer.awaiting_gpu() { + gpu.ctx.request_repaint(); } - gpu.renderer.prepare(device, queue, encoder, &self.frame); let ppp = screen.pixels_per_point; let r = self.rect; gpu.renderer.set_blit_rect(queue, self.frame.view_id, [r.min.x * ppp, r.min.y * ppp, r.width() * ppp, r.height() * ppp], screen.size_in_pixels); diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index dd5cfe38..e995d501 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -980,8 +980,12 @@ pub const TABLE: &[(&str, &str)] = &[ "Fensterrahmen und Fenstertasten des Betriebssystems statt der eigenen Titelleiste von TextureCraft verwenden", ), ( - "Not enough GPU memory to show texture set \"{name}\" fully: lower Settings ▸ Viewport ▸ Texture resolution. Painting and export are not affected.", - "Nicht genug GPU-Speicher, um das Texturset \"{name}\" vollständig anzuzeigen: Einstellungen ▸ Ansichtsfenster ▸ Texturauflösung verringern. Malen und Export sind nicht betroffen.", + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Nicht genug GPU-Speicher, um das Texturset \"{name}\" vollständig anzuzeigen: Verringere in den Einstellungen die Texturauflösung des Ansichtsfensters. Malen und Export sind nicht betroffen.", ), ("GPU error: {error}", "GPU-Fehler: {error}"), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Nicht genug GPU-Speicher, um {count} Texturesets vollständig anzuzeigen ({names}): Verringere in den Einstellungen die Texturauflösung des Ansichtsfensters. Malen und Export sind nicht betroffen.", + ), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index e3e413c6..8061df7b 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -965,8 +965,12 @@ pub const TABLE: &[(&str, &str)] = &[ "Usar el marco y los botones de ventana del sistema operativo en lugar de la barra de título propia de TextureCraft", ), ( - "Not enough GPU memory to show texture set \"{name}\" fully: lower Settings ▸ Viewport ▸ Texture resolution. Painting and export are not affected.", - "No hay suficiente memoria de GPU para mostrar el conjunto de texturas \"{name}\" por completo: reduce Ajustes ▸ Ventana gráfica ▸ Resolución de texturas. La pintura y la exportación no se ven afectadas.", + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "No hay suficiente memoria de GPU para mostrar el conjunto de texturas \"{name}\" por completo: reduce en Ajustes la resolución de texturas de la ventana gráfica. La pintura y la exportación no se ven afectadas.", ), ("GPU error: {error}", "Error de GPU: {error}"), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "No hay suficiente memoria de GPU para mostrar por completo {count} conjuntos de texturas ({names}): reduce en Ajustes la resolución de texturas de la ventana gráfica. La pintura y la exportación no se ven afectadas.", + ), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 3a54805a..34edc4d7 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -980,8 +980,12 @@ pub const TABLE: &[(&str, &str)] = &[ "Utiliser le cadre et les boutons de fenêtre du système d'exploitation au lieu de la barre de titre de TextureCraft", ), ( - "Not enough GPU memory to show texture set \"{name}\" fully: lower Settings ▸ Viewport ▸ Texture resolution. Painting and export are not affected.", - "Mémoire GPU insuffisante pour afficher entièrement l'ensemble de textures \"{name}\" : réduisez Paramètres ▸ Affichage ▸ Résolution des textures. La peinture et l'export ne sont pas affectés.", + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Mémoire GPU insuffisante pour afficher entièrement l'ensemble de textures \"{name}\" : réduisez la résolution des textures de l'affichage dans les Paramètres. La peinture et l'export ne sont pas affectés.", ), ("GPU error: {error}", "Erreur GPU : {error}"), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Mémoire GPU insuffisante pour afficher entièrement {count} ensembles de textures ({names}) : réduisez la résolution des textures de l'affichage dans les Paramètres. La peinture et l'export ne sont pas affectés.", + ), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 9f33c0e3..aea9b276 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -974,8 +974,12 @@ pub const TABLE: &[(&str, &str)] = &[ "Usa la cornice e i pulsanti della finestra del sistema operativo invece della barra del titolo di TextureCraft", ), ( - "Not enough GPU memory to show texture set \"{name}\" fully: lower Settings ▸ Viewport ▸ Texture resolution. Painting and export are not affected.", - "Memoria GPU insufficiente per mostrare per intero il set di texture \"{name}\": riduci Impostazioni ▸ Viewport ▸ Risoluzione texture. Pittura ed esportazione non sono interessate.", + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Memoria GPU insufficiente per mostrare per intero il set di texture \"{name}\": riduci nelle Impostazioni la risoluzione texture della viewport. Pittura ed esportazione non sono interessate.", ), ("GPU error: {error}", "Errore GPU: {error}"), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Memoria GPU insufficiente per mostrare per intero {count} set di texture ({names}): riduci nelle Impostazioni la risoluzione texture della viewport. Pittura ed esportazione non sono interessate.", + ), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 169c749b..0e359b0e 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -947,8 +947,12 @@ pub const TABLE: &[(&str, &str)] = &[ "TextureCraft 独自のタイトルバーの代わりに、OS のウィンドウ枠とボタンを使います", ), ( - "Not enough GPU memory to show texture set \"{name}\" fully: lower Settings ▸ Viewport ▸ Texture resolution. Painting and export are not affected.", - "GPU メモリが不足しているため、テクスチャセット「{name}」を完全には表示できません:設定 ▸ ビューポート ▸ テクスチャ解像度 を下げてください。ペイントと書き出しには影響しません。", + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "GPU メモリが不足しているため、テクスチャセット「{name}」を完全には表示できません:設定でビューポートのテクスチャ解像度を下げてください。ペイントと書き出しには影響しません。", ), ("GPU error: {error}", "GPU エラー: {error}"), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "GPU メモリが不足しているため、{count} 個のテクスチャセット({names})を完全には表示できません:設定でビューポートのテクスチャ解像度を下げてください。ペイントと書き出しには影響しません。", + ), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index d67fa29d..cdae3e38 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -932,8 +932,12 @@ pub const TABLE: &[(&str, &str)] = &[ "TextureCraft 자체 제목 표시줄 대신 운영 체제의 창 테두리와 버튼을 사용합니다", ), ( - "Not enough GPU memory to show texture set \"{name}\" fully: lower Settings ▸ Viewport ▸ Texture resolution. Painting and export are not affected.", - "GPU 메모리가 부족하여 텍스처 세트 \"{name}\"을(를) 모두 표시할 수 없습니다: 설정 ▸ 뷰포트 ▸ 텍스처 해상도를 낮추세요. 페인팅과 내보내기에는 영향이 없습니다.", + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "GPU 메모리가 부족하여 텍스처 세트 \"{name}\"을(를) 모두 표시할 수 없습니다: 설정에서 뷰포트의 텍스처 해상도를 낮추세요. 페인팅과 내보내기에는 영향이 없습니다.", ), ("GPU error: {error}", "GPU 오류: {error}"), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "GPU 메모리가 부족하여 텍스처 세트 {count}개({names})를 모두 표시할 수 없습니다: 설정에서 뷰포트의 텍스처 해상도를 낮추세요. 페인팅과 내보내기에는 영향이 없습니다.", + ), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 146a6c19..7f579f49 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -962,8 +962,12 @@ pub const TABLE: &[(&str, &str)] = &[ "Usar a moldura e os botões de janela do sistema operacional em vez da barra de título própria do TextureCraft", ), ( - "Not enough GPU memory to show texture set \"{name}\" fully: lower Settings ▸ Viewport ▸ Texture resolution. Painting and export are not affected.", - "Memória de GPU insuficiente para mostrar o conjunto de texturas \"{name}\" por completo: reduza Configurações ▸ Viewport ▸ Resolução das texturas. A pintura e a exportação não são afetadas.", + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Memória de GPU insuficiente para mostrar o conjunto de texturas \"{name}\" por completo: reduza nas Configurações a resolução das texturas da viewport. A pintura e a exportação não são afetadas.", ), ("GPU error: {error}", "Erro de GPU: {error}"), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Memória de GPU insuficiente para mostrar por completo {count} conjuntos de texturas ({names}): reduza nas Configurações a resolução das texturas da viewport. A pintura e a exportação não são afetadas.", + ), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 92158583..732ffebf 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -878,8 +878,12 @@ pub const TABLE: &[(&str, &str)] = &[ "使用操作系统的窗口边框和按钮,而不是 TextureCraft 自己的标题栏", ), ( - "Not enough GPU memory to show texture set \"{name}\" fully: lower Settings ▸ Viewport ▸ Texture resolution. Painting and export are not affected.", - "GPU 内存不足,无法完整显示纹理集“{name}”:请降低 设置 ▸ 视口 ▸ 纹理分辨率。绘制和导出不受影响。", + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "GPU 内存不足,无法完整显示纹理集“{name}”:请在设置中降低视口的纹理分辨率。绘制和导出不受影响。", ), ("GPU error: {error}", "GPU 错误:{error}"), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "GPU 内存不足,无法完整显示 {count} 个纹理集({names}):请在设置中降低视口的纹理分辨率。绘制和导出不受影响。", + ), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bd53bd98..cbbbbfb9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -70,6 +70,8 @@ pub struct TextureCraftApp { pub gpu: Option, pub control: Option>, pub toasts: Vec, + /// Texture sets the GPU could not hold, and the text of the one sticky toast naming them. + pub(crate) gpu_memory: (Vec, Option), pub bake: Option, pub resize: Option, pub thumbs: thumbs::Thumbs, @@ -110,7 +112,7 @@ impl TextureCraftApp { // Bakes cast their rays on a GPU device of their own (created on the first bake). #[cfg(not(target_arch = "wasm32"))] texturecraft_engine::bake_cmds::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); - let gpu = cc.wgpu_render_state.as_ref().map(gpu::init); + let gpu = cc.wgpu_render_state.as_ref().map(|rs| gpu::init(rs, &cc.egui_ctx)); // The first run speaks the OS (or browser) language. let ui = cc.storage.and_then(|s| eframe::get_value::(s, "ui")).unwrap_or_else(|| { let mut ui = UiState::default(); @@ -124,6 +126,7 @@ impl TextureCraftApp { gpu, control: None, toasts: Vec::new(), + gpu_memory: (Vec::new(), None), bake: None, resize: None, thumbs: thumbs::Thumbs::default(), @@ -170,6 +173,12 @@ impl TextureCraftApp { self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 } }); } + /// An error toast that stays until the user dismisses it (for a problem that persists and + /// is reported once, like a texture set the GPU could not hold). + pub fn toast_sticky(&mut self, text: impl Into) { + self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY }); + } + /// Start baking texture sets in the background (one after another). pub fn start_bake(&mut self, sets: Vec) { if self.bake.is_some() || sets.is_empty() { @@ -465,10 +474,14 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { if app.toasts.is_empty() { return; } - ctx.request_repaint_after(std::time::Duration::from_millis(250)); + // Expiring toasts need frames to disappear on time; sticky ones wait for a click. + if app.toasts.iter().any(|t| t.until.is_finite()) { + ctx.request_repaint_after(std::time::Duration::from_millis(250)); + } let tk = theme::Tokens::get(ctx); + let mut dismissed = None; egui::Area::new(egui::Id::unique("toasts")).anchor(egui::Align2::RIGHT_BOTTOM, egui::vec2(-16.0, -36.0)).show(ctx, |ui| { - for t in &app.toasts { + for (i, t) in app.toasts.iter().enumerate() { egui::Frame::NONE .fill(tk.panel) .stroke(egui::Stroke::new(1.0, if t.error { tk.danger } else { tk.accent })) @@ -477,9 +490,17 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { .inner_margin(egui::Margin::symmetric(10, 6)) .show(ui, |ui| { ui.set_max_width(360.0); - ui.label(egui::RichText::new(&t.text).color(tk.text_strong)); + ui.horizontal_top(|ui| { + ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap()); + if t.until.is_infinite() && widgets::icon_button(ui, egui_phosphor::regular::X, i18n::tr("Dismiss"), false, 18.0).clicked() { + dismissed = Some(i); + } + }); }); ui.add_space(4.0); } }); + if let Some(i) = dismissed.filter(|i| *i < app.toasts.len()) { + app.toasts.remove(i); + } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 76e97d06..cd5f288c 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -98,17 +98,50 @@ fn shade(app: &TextureCraftApp) -> Shade { /// Show what the GPU side reported (each message once while its toast is up). fn gpu_report_toasts(app: &mut TextureCraftApp, reports: crate::gpu::GpuReports) { let names: Vec = reports.memory.iter().filter_map(|ts| app.session.doc.project.texture_sets.get(*ts).map(|t| t.name.clone())).collect(); - let texts = names - .iter() - .map(|name| trf("Not enough GPU memory to show texture set \"{name}\" fully: lower Settings ▸ Viewport ▸ Texture resolution. Painting and export are not affected.", &[("name", name)])) - .chain(reports.errors.iter().map(|e| trf("GPU error: {error}", &[("error", e)]))); - for text in texts.collect::>() { + if !names.is_empty() { + // One sticky notice for every set the GPU could not hold (they are not retried, so the + // notice stays until dismissed); after a dismissal, a new one names only the new sets. + let (sets, shown) = &mut app.gpu_memory; + let current = shown.take().filter(|text| app.toasts.iter().any(|t| &t.text == text)); + match ¤t { + Some(text) => app.toasts.retain(|t| &t.text != text), + None => sets.clear(), + } + for n in names { + if !sets.contains(&n) { + sets.push(n); + } + } + let text = match sets.as_slice() { + [one] => trf( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + &[("name", one)], + ), + many => { + let mut list = many.iter().take(MAX_NAMED_SETS).map(|n| format!("\"{n}\"")).collect::>().join(", "); + if many.len() > MAX_NAMED_SETS { + list.push_str(", ..."); + } + trf( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + &[("count", &many.len()), ("names", &list)], + ) + } + }; + app.gpu_memory.1 = Some(text.clone()); + app.toast_sticky(text); + } + for e in &reports.errors { + let text = trf("GPU error: {error}", &[("error", e)]); if !app.toasts.iter().any(|t| t.text == text) { app.toast(text, true); } } } +/// Texture sets a GPU memory notice names before "...". +const MAX_NAMED_SETS: usize = 5; + /// This frame's scene sync (compositing and GPU uploads), run by the first view drawn, after /// that view handled its input: a stroke shows in the frame it is painted, not the next. pub struct PendingSync(Option>); From 96b179ccfcd4cd365476ece6d9a4f87373e6cf7f Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 04:15:55 +0700 Subject: [PATCH 09/60] Start window: new, open or a recent project at launch The app opens on the sample project, which left no obvious place to pick a project. A start window now offers New project, Open, the recent projects and Continue with the sample project, with Show at startup (also Settings > Interface > Start window). It opens at launch in the desktop and web apps, but not when a file is given on the command line or the app runs with --control. Labels translated into the other nine UI languages; a UI test covers New project, Continue and the startup setting. --- README.md | 2 +- apps/texturecraft-web/src/web.rs | 1 + apps/texturecraft/src/main.rs | 3 ++ crates/ui-egui/src/i18n/ar.rs | 4 ++ crates/ui-egui/src/i18n/de.rs | 4 ++ crates/ui-egui/src/i18n/es.rs | 4 ++ crates/ui-egui/src/i18n/fr.rs | 4 ++ crates/ui-egui/src/i18n/it.rs | 4 ++ crates/ui-egui/src/i18n/ja.rs | 4 ++ crates/ui-egui/src/i18n/ko.rs | 4 ++ crates/ui-egui/src/i18n/pt_br.rs | 4 ++ crates/ui-egui/src/i18n/zh_hans.rs | 4 ++ crates/ui-egui/src/state.rs | 6 +++ crates/ui-egui/src/windows.rs | 70 ++++++++++++++++++++++++++++ crates/ui-egui/tests/start_window.rs | 30 ++++++++++++ docs/features.md | 2 + 16 files changed, 149 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/tests/start_window.rs diff --git a/README.md b/README.md index e6a08036..b9772d80 100644 --- a/README.md +++ b/README.md @@ -151,7 +151,7 @@ cd apps/texturecraft-web && trunk serve # web build cargo xtask ci # fmt, clippy, tests, layering, wasm ``` -You need Rust 1.95 or newer. The app opens with a baked sample project; **File ▸ New project** starts +You need Rust 1.95 or newer. The app opens with a baked sample project and a start window (new project, open, recent projects); **File ▸ New project** starts from a built-in mesh, a project template or your own mesh file (UVs are generated if it has none). Japanese, Chinese, Korean and Arabic interface text uses the fonts of diff --git a/apps/texturecraft-web/src/web.rs b/apps/texturecraft-web/src/web.rs index 96bbc70c..37752314 100644 --- a/apps/texturecraft-web/src/web.rs +++ b/apps/texturecraft-web/src/web.rs @@ -54,6 +54,7 @@ async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> { options, Box::new(|cc| { let mut app = TextureCraftApp::new(cc, session); + app.ui.windows.start = app.ui.prefs.start_window; if let Some(rs) = &cc.wgpu_render_state { let backend = rs.adapter.get_info().backend; log::info!("TextureCraft: wgpu backend {backend:?}"); diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index e1cbb6c2..905a9d85 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -170,6 +170,8 @@ fn main() { let viewport = title_bar.viewport(viewport); let options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() }; let control = args.control; + // The start window offers new, open and recent projects, unless a file was given or a script drives the app. + let start = args.file.is_none() && control.is_none(); let r = eframe::run_native( APP_NAME, options, @@ -181,6 +183,7 @@ fn main() { let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_))); let mut app = TextureCraftApp::new(cc, session); app.title_bar = title_bar; + app.ui.windows.start = start && app.ui.prefs.start_window; if let Some(port) = control { app.control = Some(control_server::start(port, cc.egui_ctx.clone())); } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 0320cbf7..3b2c060a 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -924,4 +924,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "استخدام إطار وأزرار نافذة نظام التشغيل بدلاً من شريط عنوان TextureCraft الخاص", ), + ("Start window", "نافذة البدء"), + ("Show at startup", "إظهار عند بدء التشغيل"), + ("Continue with the sample project", "المتابعة مع المشروع النموذجي"), + ("No recent projects yet", "لا توجد مشاريع حديثة بعد"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ce534a6f..fb59610b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -979,4 +979,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Fensterrahmen und Fenstertasten des Betriebssystems statt der eigenen Titelleiste von TextureCraft verwenden", ), + ("Start window", "Startfenster"), + ("Show at startup", "Beim Start anzeigen"), + ("Continue with the sample project", "Mit dem Beispielprojekt fortfahren"), + ("No recent projects yet", "Noch keine zuletzt geöffneten Projekte"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 2b57afd8..fbb8cef2 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -964,4 +964,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Usar el marco y los botones de ventana del sistema operativo en lugar de la barra de título propia de TextureCraft", ), + ("Start window", "Ventana de inicio"), + ("Show at startup", "Mostrar al iniciar"), + ("Continue with the sample project", "Continuar con el proyecto de ejemplo"), + ("No recent projects yet", "Aún no hay proyectos recientes"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 0e72b031..f24a379f 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -979,4 +979,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Utiliser le cadre et les boutons de fenêtre du système d'exploitation au lieu de la barre de titre de TextureCraft", ), + ("Start window", "Fenêtre de démarrage"), + ("Show at startup", "Afficher au démarrage"), + ("Continue with the sample project", "Continuer avec le projet d'exemple"), + ("No recent projects yet", "Aucun projet récent pour l'instant"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 9260b188..00d2706a 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -973,4 +973,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Usa la cornice e i pulsanti della finestra del sistema operativo invece della barra del titolo di TextureCraft", ), + ("Start window", "Finestra iniziale"), + ("Show at startup", "Mostra all'avvio"), + ("Continue with the sample project", "Continua con il progetto di esempio"), + ("No recent projects yet", "Ancora nessun progetto recente"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 2e333ab9..845812ce 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -946,4 +946,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "TextureCraft 独自のタイトルバーの代わりに、OS のウィンドウ枠とボタンを使います", ), + ("Start window", "スタートウィンドウ"), + ("Show at startup", "起動時に表示"), + ("Continue with the sample project", "サンプルプロジェクトで続ける"), + ("No recent projects yet", "最近のプロジェクトはまだありません"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 3945c9a9..efec5624 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -931,4 +931,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "TextureCraft 자체 제목 표시줄 대신 운영 체제의 창 테두리와 버튼을 사용합니다", ), + ("Start window", "시작 창"), + ("Show at startup", "시작 시 표시"), + ("Continue with the sample project", "샘플 프로젝트로 계속"), + ("No recent projects yet", "아직 최근 프로젝트가 없습니다"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 788df7f9..ff1268ee 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -961,4 +961,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Usar a moldura e os botões de janela do sistema operacional em vez da barra de título própria do TextureCraft", ), + ("Start window", "Janela inicial"), + ("Show at startup", "Mostrar ao iniciar"), + ("Continue with the sample project", "Continuar com o projeto de exemplo"), + ("No recent projects yet", "Nenhum projeto recente ainda"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 3de5246c..c44cf1b6 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -877,4 +877,8 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "使用操作系统的窗口边框和按钮,而不是 TextureCraft 自己的标题栏", ), + ("Start window", "启动窗口"), + ("Show at startup", "启动时显示"), + ("Continue with the sample project", "继续使用示例项目"), + ("No recent projects yet", "暂无最近的项目"), ]; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 2e137e13..cfae41bc 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -61,6 +61,9 @@ pub struct Windows { /// Browser File › Export Mesh: the download format choice. #[serde(default)] pub export_mesh: bool, + /// The start window: new, open, recent projects (the app opens it at launch). + #[serde(skip)] + pub start: bool, } /// Edit › Settings. @@ -82,6 +85,8 @@ pub struct Prefs { pub accent: crate::theme::Accent, /// The system draws the window's title bar instead of TextureCraft (desktop; read at startup). pub system_title_bar: bool, + /// Show the start window at launch. + pub start_window: bool, } impl Default for Prefs { @@ -94,6 +99,7 @@ impl Default for Prefs { brightness: crate::theme::Brightness::default(), accent: crate::theme::Accent::default(), system_title_bar: false, + start_window: true, } } } diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 2ecafdd6..eab0046e 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -18,6 +18,7 @@ use crate::theme::{Accent, Brightness, Tokens, caption}; use crate::widgets::{color_swatch, combo, icon_button, primary_button, slider}; pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + start(app, ctx); new_project(app, ctx); about(app, ctx); settings(app, ctx); @@ -236,6 +237,72 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { }); } +/// What the start window was asked for. +enum Start { + Menu(&'static str), + Recent(String), + Close, +} + +/// The start window: a new project, a project file or a recent one, or the sample that is open. +fn start(app: &mut TextureCraftApp, ctx: &egui::Context) { + if !app.ui.windows.start { + return; + } + let tk = Tokens::get(ctx); + let mut open = true; + let mut action = None; + dialog("start", "TextureCraft", &mut open).min_width(380.0).show(ctx, |ui| { + ui.horizontal(|ui| { + if ui.add(primary_button(ui, tr("New project..."))).clicked() { + action = Some(Start::Menu("ui.newProject")); + } + if ui.button(tr("Open...")).clicked() { + action = Some(Start::Menu("file.open")); + } + }); + if file_dialogs_available() { + ui.add_space(8.0); + ui.label(caption(tr("Recent projects"))); + if app.ui.recent.is_empty() { + ui.label(RichText::new(tr("No recent projects yet")).color(tk.text_dim)); + } + for path in &app.ui.recent { + let name = std::path::Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or(path); + if ui + .add(egui::Button::selectable(false, format!("{} {name}", ic::FILE)).min_size(vec2(ui.available_width(), 0.0))) + .on_hover_text(path) + .clicked() + { + action = Some(Start::Recent(path.clone())); + } + } + } + ui.add_space(8.0); + ui.separator(); + ui.horizontal(|ui| { + ui.checkbox(&mut app.ui.prefs.start_window, tr("Show at startup")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Continue with the sample project")).clicked() { + action = Some(Start::Close); + } + }); + }); + }); + if let Some(a) = action { + app.ui.windows.start = false; + match a { + Start::Menu(id) => crate::menus::invoke(app, ctx, id), + #[cfg(not(target_arch = "wasm32"))] + Start::Recent(path) => open_path(app, &path), + _ => {} + } + } + if !open { + app.ui.windows.start = false; + } +} + fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.new_project { return; @@ -408,6 +475,9 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { .on_hover_text(tr("Use the operating system's window frame and buttons instead of TextureCraft's own title bar")); ui.end_row(); } + ui.label(tr("Start window")); + ui.checkbox(&mut p.start_window, tr("Show at startup")); + ui.end_row(); }); ui.add_space(8.0); ui.label(caption(tr("Viewport"))); diff --git a/crates/ui-egui/tests/start_window.rs b/crates/ui-egui/tests/start_window.rs new file mode 100644 index 00000000..9c5415b4 --- /dev/null +++ b/crates/ui-egui/tests/start_window.rs @@ -0,0 +1,30 @@ +//! The start window: New project opens its dialog, Continue keeps the open project, and the +//! startup choice is a setting. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_ui_egui::TextureCraftApp; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.windows.start = true; + h.run_steps(3); + h +} + +#[test] +fn start_window_choices() { + let mut h = harness(); + h.get_by_label("New project...").click(); + h.run_steps(3); + assert!(!h.state().ui.windows.start && h.state().ui.windows.new_project, "New project opens its dialog"); + + let mut h = harness(); + h.get_by_label("Show at startup").click(); + h.get_by_label("Continue with the sample project").click(); + h.run_steps(3); + assert!(!h.state().ui.windows.start && !h.state().ui.windows.new_project); + assert!(!h.state().ui.prefs.start_window, "unticked: not shown next time"); + assert_eq!(h.state().session.doc.project.texture_sets.len(), 2, "the sample stays open"); +} diff --git a/docs/features.md b/docs/features.md index cbec3d46..34c4e70f 100644 --- a/docs/features.md +++ b/docs/features.md @@ -103,6 +103,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA strip, and Settings › Interface › System title bar for the system's frame instead. - **Dockable, tabbed and floating panels**, saved layouts, and panels that reopen where you closed them. +- A **start window** at launch: a new project, a project file, a recent project or the sample + (Settings › Interface › Start window). - A **shortcut editor** with conflict detection, and every shortcut shown in its tooltip. - **10 languages:** English, French, German, Spanish, Portuguese, Italian, Japanese, Chinese, Korean and Arabic, switchable live. From 1d885c8df1f2fd48149643edf92e98b3b53c4017 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 04:28:17 +0700 Subject: [PATCH 10/60] Brushes: 18 brush presets in the shelf, and your own The Assets shelf has a Brushes tab: presets grouped as Basic (hard, soft, airbrush, square, dots), Wear and grunge (dry brush, chalk, spray, grunge, splatter, scratches, chips, cracks, drips) and Details (stars, stitches, rivets, fur), each with a preview of its stroke. A click sets the stroke (alpha, spacing, flow, hardness, angle, path following, jitters, particles) and keeps the brush's size, alignment, culling, symmetry and lazy mouse. My brushes saves the current brush as a .tcbrush file in the brushes folder and lists them. Commands: brush.preset.list, brush.preset.apply {preset}, brush.preset.save {path} and brush.preset.load {path} (an image alpha from another project is dropped). Labels translated into the other nine UI languages. --- ROADMAP.md | 2 +- crates/engine/src/brush_preset_cmds.rs | 85 +++++++++++ crates/engine/src/commands.rs | 1 + crates/engine/src/lib.rs | 1 + crates/engine/tests/session.rs | 27 ++++ crates/paint/src/lib.rs | 4 +- crates/paint/src/presets.rs | 203 +++++++++++++++++++++++++ crates/ui-egui/src/i18n/ar.rs | 5 + crates/ui-egui/src/i18n/de.rs | 5 + crates/ui-egui/src/i18n/es.rs | 5 + crates/ui-egui/src/i18n/fr.rs | 5 + crates/ui-egui/src/i18n/it.rs | 5 + crates/ui-egui/src/i18n/ja.rs | 5 + crates/ui-egui/src/i18n/ko.rs | 5 + crates/ui-egui/src/i18n/pt_br.rs | 5 + crates/ui-egui/src/i18n/zh_hans.rs | 5 + crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/shelf.rs | 82 +++++++++- crates/ui-egui/src/thumbs.rs | 54 ++++++- docs/features.md | 2 + 20 files changed, 504 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/brush_preset_cmds.rs create mode 100644 crates/paint/src/presets.rs diff --git a/ROADMAP.md b/ROADMAP.md index 007c96bd..738e195c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -15,7 +15,7 @@ end to end today (engine + UI + automation + tests), not what is planned. | Texture sets | 6 | 95% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile**, one texture per tile at its own size, `$udim` export), list with visibility, sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | Filter radii and height slopes of a tile smaller than its atlas block follow the block | | Layer stack | 16 | 96% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels, invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; smart masks; mask view (Alt+click); duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **27 library filters** (adjustments, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | | Painting tools | 14 | 88% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **particle brush** | Pen tilt (not exposed by the windowing layer) | -| Materials and assets | 8 | 86% | 48 procedural materials (incl. car paint, velvet, brushed steel, skin, wax), 21 smart materials, 18 smart masks, **67 procedural brush alphas**, 22 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | +| Materials and assets | 8 | 86% | 48 procedural materials (incl. car paint, velvet, brushed steel, skin, wax), 21 smart materials, 18 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 22 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | | Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — | | Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Hardware ray tracing | | Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — | diff --git a/crates/engine/src/brush_preset_cmds.rs b/crates/engine/src/brush_preset_cmds.rs new file mode 100644 index 00000000..0ebfa070 --- /dev/null +++ b/crates/engine/src/brush_preset_cmds.rs @@ -0,0 +1,85 @@ +//! Brush presets: the built-in ones, and the user's own saved as `.tcbrush` files (the brush +//! settings as JSON). Applying or loading one changes the stroke and keeps the brush's size. + +use serde_json::{Value, json}; +use texturecraft_paint::BrushSettings; +use texturecraft_paint::presets::{PRESETS, find_preset, with_stroke_of}; + +use crate::commands::{CommandSpec, always, bad, strp}; +use crate::tool_cmds::brush_json; +use crate::{Result, Session, cmd}; + +/// File extension of a saved brush preset. +pub const BRUSH_EXT: &str = "tcbrush"; +/// Largest preset file read. +#[cfg(not(target_arch = "wasm32"))] +const MAX_BYTES: u64 = 1 << 20; + +pub fn specs() -> Vec { + vec![ + cmd!("brush.preset.list", "List brush presets", [], None, "{} — the built-in presets: id, label, category", always, |_, _| Ok(list())), + cmd!( + "brush.preset.apply", + "Apply brush preset", + [], + None, + "{preset: id or label (brush.preset.list)} — sets the stroke (alpha, spacing, flow, hardness, jitters…), keeps the size", + always, + apply + ), + cmd!("brush.preset.save", "Save brush preset", [], None, "{path} — the current brush as a .tcbrush file", always, save), + cmd!("brush.preset.load", "Load brush preset", [], None, "{path} — a .tcbrush file's stroke on the brush, keeping the size", always, load), + ] +} + +fn list() -> Value { + json!(PRESETS.iter().map(|p| json!({"id": p.id, "label": p.label, "category": p.category})).collect::>()) +} + +fn apply(s: &mut Session, p: &Value) -> Result { + let name = strp(p, "preset").ok_or_else(|| bad("brush.preset.apply", "`preset` is required"))?; + let preset = find_preset(name).ok_or_else(|| bad("brush.preset.apply", format!("unknown brush preset `{name}` (see brush.preset.list)")))?; + set(s, preset.applied(&s.tool.brush)) +} + +fn set(s: &mut Session, brush: BrushSettings) -> Result { + s.tool.brush = brush; + s.revision = s.revision.wrapping_add(1); + Ok(brush_json(s)) +} + +#[cfg(not(target_arch = "wasm32"))] +fn save(s: &mut Session, p: &Value) -> Result { + let path = strp(p, "path").ok_or_else(|| bad("brush.preset.save", "`path` is required"))?; + let bytes = serde_json::to_vec_pretty(&s.tool.brush).map_err(|e| bad("brush.preset.save", e.to_string()))?; + std::fs::write(path, bytes).map_err(|e| bad("brush.preset.save", format!("cannot write {path}: {e}")))?; + Ok(json!({ "path": path })) +} + +#[cfg(not(target_arch = "wasm32"))] +fn load(s: &mut Session, p: &Value) -> Result { + use std::io::Read as _; + let cmd = "brush.preset.load"; + let path = strp(p, "path").ok_or_else(|| bad(cmd, "`path` is required"))?; + let mut bytes = Vec::new(); + std::fs::File::open(path).and_then(|f| f.take(MAX_BYTES + 1).read_to_end(&mut bytes)).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?; + if bytes.len() as u64 > MAX_BYTES { + return Err(bad(cmd, format!("{path} is too large for a brush preset"))); + } + let mut from: BrushSettings = serde_json::from_slice(&bytes).map_err(|e| bad(cmd, format!("{path} is not a brush preset: {e}")))?; + // An image alpha belongs to the project that saved it. + if from.alpha_image.as_ref().is_some_and(|n| !s.images.contains_key(n)) { + from.alpha_image = None; + } + set(s, with_stroke_of(&s.tool.brush, &from)) +} + +#[cfg(target_arch = "wasm32")] +fn save(_: &mut Session, _: &Value) -> Result { + Err(bad("brush.preset.save", "file paths are not available in the browser")) +} + +#[cfg(target_arch = "wasm32")] +fn load(_: &mut Session, _: &Value) -> Result { + Err(bad("brush.preset.load", "file paths are not available in the browser")) +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 1d6b0cb8..55e9ebaf 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -57,6 +57,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::instance_cmds::specs()); v.extend(crate::mask_cmds::specs()); v.extend(crate::tool_cmds::specs()); + v.extend(crate::brush_preset_cmds::specs()); v.extend(crate::path_tool::specs()); v.extend(crate::view_cmds::specs()); v.extend(crate::camera_cmds::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2afa239..cb1d7445 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -9,6 +9,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod bake_cmds; +pub mod brush_preset_cmds; pub mod camera_cmds; pub mod commands; pub mod decal_cmds; diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index bd7fd4a8..f33c9b78 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -165,6 +165,33 @@ fn image_resources_fill_layers_and_round_trip() { assert!(s.import_resource_bytes("bad.png", vec![1, 2, 3]).is_err()); } +#[test] +fn brush_presets_apply_save_and_load() { + let mut s = session(); + let list = execute(&mut s, "brush.preset.list", &Value::Null).unwrap(); + assert!(list.as_array().unwrap().len() >= 12); + execute(&mut s, "tool.brush", &json!({"size": 30})).unwrap(); + let b = execute(&mut s, "brush.preset.apply", &json!({"preset": "Scratches"})).unwrap(); + assert_eq!((b["alpha"]["library"].as_str(), b["followPath"].as_bool()), (Some("scratches"), Some(true))); + assert!((b["size"].as_f64().unwrap() - 30.0).abs() < 1e-3, "presets keep the size"); + assert!(execute(&mut s, "tool.stroke", &json!({"points": [[160, 200], [240, 200]]})).unwrap()["stamps"].as_u64().unwrap() > 0); + // Saved and loaded back onto another brush, the stroke returns and the size stays. + let path = std::env::temp_dir().join(format!("tc-brush-{}.tcbrush", std::process::id())); + let path = path.to_str().unwrap(); + execute(&mut s, "brush.preset.save", &json!({"path": path})).unwrap(); + execute(&mut s, "brush.preset.apply", &json!({"preset": "basic_soft"})).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 10})).unwrap(); + let b = execute(&mut s, "brush.preset.load", &json!({"path": path})).unwrap(); + assert_eq!(b["alpha"]["library"], "scratches"); + assert!((b["size"].as_f64().unwrap() - 10.0).abs() < 1e-3); + std::fs::write(path, b"{}").unwrap(); + assert!(execute(&mut s, "brush.preset.load", &json!({"path": path})).is_err()); + let _ = std::fs::remove_file(path); + for bad in [json!({}), json!({"preset": "nope"})] { + assert!(execute(&mut s, "brush.preset.apply", &bad).is_err()); + } +} + #[test] fn projection_tool_paints_the_stencil_colors() { let mut s = session(); diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index fa689f5c..136c6c3c 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -6,7 +6,8 @@ //! see ([`EyeDepth`]); [`commit`] blends the finished stroke into layer pixels. Clone and smudge //! strokes carry channel values ([`pickup`]) instead of painting the tool's material. //! [`path`] samples the Path tool's curves and lasso coverage; [`particles`] runs the particle -//! brush; [`alphas`] is the built-in library of procedural brush alphas. +//! brush; [`alphas`] is the built-in library of procedural brush alphas and [`presets`] the built-in +//! brush presets. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -16,6 +17,7 @@ pub mod commit; pub mod particles; pub mod path; pub mod pickup; +pub mod presets; pub mod raster; pub mod stroke; pub mod visibility; diff --git a/crates/paint/src/presets.rs b/crates/paint/src/presets.rs new file mode 100644 index 00000000..72f537e6 --- /dev/null +++ b/crates/paint/src/presets.rs @@ -0,0 +1,203 @@ +//! Built-in brush presets: how a brush strokes (shape, spacing, flow, hardness, jitters, path +//! following, particles). Applying one keeps the brush's size, alignment, culling, symmetry and +//! lazy mouse, so a preset changes the stroke, not the setup. + +use crate::brush::{BrushAlpha, BrushSettings}; + +/// A named stroke recipe on top of the default stroke. +pub struct BrushPreset { + pub id: &'static str, + pub label: &'static str, + pub category: &'static str, + recipe: fn(&mut BrushSettings), +} + +impl BrushPreset { + /// `brush` with this preset's stroke. + pub fn applied(&self, brush: &BrushSettings) -> BrushSettings { + let mut b = with_stroke_of(brush, &BrushSettings::default()); + (self.recipe)(&mut b); + b.sanitized() + } +} + +/// `brush` with the stroke of `from` (shape, flow, opacity, spacing, hardness, angle, path +/// following, jitters and particles): what a preset sets. +pub fn with_stroke_of(brush: &BrushSettings, from: &BrushSettings) -> BrushSettings { + BrushSettings { + flow: from.flow, + opacity: from.opacity, + spacing: from.spacing, + hardness: from.hardness, + angle: from.angle, + follow_path: from.follow_path, + jitter_size: from.jitter_size, + jitter_angle: from.jitter_angle, + jitter_flow: from.jitter_flow, + jitter_position: from.jitter_position, + alpha: from.alpha, + alpha_image: from.alpha_image.clone(), + alpha_library: from.alpha_library.clone(), + particles: from.particles, + ..brush.clone() + } + .sanitized() +} + +/// A preset by id or label (case, spaces, `_` and `-` ignored). +pub fn find_preset(name: &str) -> Option<&'static BrushPreset> { + let n = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-'], ""); + PRESETS.iter().find(|p| n(p.id) == n(name) || n(p.label) == n(name)) +} + +const BASIC: &str = "Basic"; +const GRUNGE: &str = "Wear and grunge"; +const DETAIL: &str = "Details"; + +fn library(b: &mut BrushSettings, id: &str) { + b.alpha_library = Some(id.to_string()); +} + +/// Every built-in preset, in shelf order. +pub const PRESETS: [BrushPreset; 18] = [ + BrushPreset { id: "basic_hard", label: "Basic hard", category: BASIC, recipe: |b| b.hardness = 0.95 }, + BrushPreset { id: "basic_soft", label: "Basic soft", category: BASIC, recipe: |b| (b.hardness, b.flow) = (0.0, 0.6) }, + BrushPreset { id: "airbrush", label: "Airbrush", category: BASIC, recipe: |b| (b.hardness, b.flow, b.spacing) = (0.0, 0.12, 0.04) }, + BrushPreset { id: "square", label: "Square", category: BASIC, recipe: |b| (b.alpha, b.hardness, b.follow_path) = (BrushAlpha::Square, 0.9, true) }, + BrushPreset { id: "dots", label: "Dots", category: BASIC, recipe: |b| (b.hardness, b.spacing) = (0.9, 1.6) }, + BrushPreset { + id: "dry_brush", + label: "Dry brush", + category: GRUNGE, + recipe: |b| (b.alpha, b.follow_path, b.spacing, b.flow) = (BrushAlpha::Streaks, true, 0.04, 0.5), + }, + BrushPreset { + id: "chalk", + label: "Chalk", + category: GRUNGE, + recipe: |b| { + library(b, "sponge"); + (b.jitter_angle, b.spacing, b.flow) = (1.0, 0.15, 0.7); + }, + }, + BrushPreset { + id: "spray", + label: "Spray", + category: GRUNGE, + recipe: |b| (b.alpha, b.jitter_angle, b.jitter_size, b.spacing) = (BrushAlpha::Spray, 1.0, 0.3, 0.3), + }, + BrushPreset { + id: "grunge", + label: "Grunge", + category: GRUNGE, + recipe: |b| (b.alpha, b.jitter_angle, b.jitter_size, b.spacing) = (BrushAlpha::Grunge, 1.0, 0.4, 0.4), + }, + BrushPreset { + id: "splatter", + label: "Splatter", + category: GRUNGE, + recipe: |b| { + library(b, "splatter"); + (b.jitter_angle, b.jitter_size, b.jitter_position, b.spacing) = (1.0, 0.5, 1.5, 1.2); + }, + }, + BrushPreset { + id: "scratches", + label: "Scratches", + category: GRUNGE, + recipe: |b| { + library(b, "scratches"); + (b.follow_path, b.jitter_angle, b.spacing) = (true, 0.1, 0.5); + }, + }, + BrushPreset { + id: "chips", + label: "Chips", + category: GRUNGE, + recipe: |b| { + library(b, "chips"); + (b.jitter_angle, b.jitter_size, b.jitter_position, b.spacing) = (1.0, 0.5, 1.0, 0.8); + }, + }, + BrushPreset { + id: "cracks", + label: "Cracks", + category: GRUNGE, + recipe: |b| { + library(b, "cracks"); + (b.jitter_angle, b.spacing) = (1.0, 0.9); + }, + }, + BrushPreset { + id: "drips", + label: "Drips", + category: GRUNGE, + recipe: |b| { + (b.hardness, b.flow) = (0.7, 0.6); + b.particles.enabled = true; + }, + }, + BrushPreset { + id: "stars", + label: "Stars", + category: DETAIL, + recipe: |b| { + library(b, "star_5"); + (b.jitter_size, b.jitter_angle, b.jitter_position, b.spacing) = (0.6, 1.0, 2.0, 1.5); + }, + }, + BrushPreset { + id: "stitches", + label: "Stitches", + category: DETAIL, + recipe: |b| { + library(b, "stitches"); + (b.follow_path, b.spacing) = (true, 0.9); + }, + }, + BrushPreset { + id: "rivets", + label: "Rivets", + category: DETAIL, + recipe: |b| { + library(b, "rivet"); + b.spacing = 2.0; + }, + }, + BrushPreset { + id: "fur", + label: "Fur", + category: DETAIL, + recipe: |b| { + library(b, "fur"); + (b.follow_path, b.jitter_angle, b.spacing) = (true, 0.15, 0.3); + }, + }, +]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn presets_are_unique_valid_and_keep_the_setup() { + let mut ids: Vec<&str> = PRESETS.iter().map(|p| p.id).collect(); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), PRESETS.len()); + let mine = + BrushSettings { size: 0.1, lazy: 12.0, backface_culling: false, jitter_size: 1.0, alpha_image: Some("x.png".into()), ..BrushSettings::default() }; + for p in &PRESETS { + let b = p.applied(&mine); + assert_eq!(b, b.sanitized(), "{}", p.id); + assert_eq!((b.size, b.lazy, b.backface_culling, b.alpha_image.as_deref()), (0.1, 12.0, false, None), "{}", p.id); + if let Some(id) = &b.alpha_library { + assert!(crate::alphas::find(id).is_some(), "{}: library alpha {id}", p.id); + } + assert_eq!(find_preset(p.label).map(|f| f.id), Some(p.id)); + } + assert_eq!(find_preset("basic hard").map(|p| p.id), Some("basic_hard")); + assert!(find_preset("nope").is_none()); + assert_eq!(PRESETS[0].applied(&mine).jitter_size, 0.0, "jitters reset"); + } +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 0320cbf7..715adf68 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -924,4 +924,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "استخدام إطار وأزرار نافذة نظام التشغيل بدلاً من شريط عنوان TextureCraft الخاص", ), + ("Brushes", "الفرش"), + ("My brushes", "فرشي"), + ("Use this brush (keeps its size)", "استخدام هذه الفرشاة (مع الحفاظ على حجمها)"), + ("Brush name", "اسم الفرشاة"), + ("Save current brush", "حفظ الفرشاة الحالية"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ce534a6f..7663fce2 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -979,4 +979,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Fensterrahmen und Fenstertasten des Betriebssystems statt der eigenen Titelleiste von TextureCraft verwenden", ), + ("Brushes", "Pinsel"), + ("My brushes", "Meine Pinsel"), + ("Use this brush (keeps its size)", "Diesen Pinsel verwenden (Größe bleibt)"), + ("Brush name", "Pinselname"), + ("Save current brush", "Aktuellen Pinsel speichern"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 2b57afd8..b64c6c80 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -964,4 +964,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Usar el marco y los botones de ventana del sistema operativo en lugar de la barra de título propia de TextureCraft", ), + ("Brushes", "Pinceles"), + ("My brushes", "Mis pinceles"), + ("Use this brush (keeps its size)", "Usar este pincel (conserva su tamaño)"), + ("Brush name", "Nombre del pincel"), + ("Save current brush", "Guardar el pincel actual"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 0e72b031..495fb5f2 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -979,4 +979,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Utiliser le cadre et les boutons de fenêtre du système d'exploitation au lieu de la barre de titre de TextureCraft", ), + ("Brushes", "Pinceaux"), + ("My brushes", "Mes pinceaux"), + ("Use this brush (keeps its size)", "Utiliser ce pinceau (garde sa taille)"), + ("Brush name", "Nom du pinceau"), + ("Save current brush", "Enregistrer le pinceau actuel"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 9260b188..48267b99 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -973,4 +973,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Usa la cornice e i pulsanti della finestra del sistema operativo invece della barra del titolo di TextureCraft", ), + ("Brushes", "Pennelli"), + ("My brushes", "I miei pennelli"), + ("Use this brush (keeps its size)", "Usa questo pennello (mantiene la dimensione)"), + ("Brush name", "Nome del pennello"), + ("Save current brush", "Salva il pennello attuale"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 2e333ab9..e46e909a 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -946,4 +946,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "TextureCraft 独自のタイトルバーの代わりに、OS のウィンドウ枠とボタンを使います", ), + ("Brushes", "ブラシ一覧"), + ("My brushes", "マイブラシ"), + ("Use this brush (keeps its size)", "このブラシを使用(サイズはそのまま)"), + ("Brush name", "ブラシ名"), + ("Save current brush", "現在のブラシを保存"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 3945c9a9..86b5c144 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -931,4 +931,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "TextureCraft 자체 제목 표시줄 대신 운영 체제의 창 테두리와 버튼을 사용합니다", ), + ("Brushes", "브러시 목록"), + ("My brushes", "내 브러시"), + ("Use this brush (keeps its size)", "이 브러시 사용 (크기 유지)"), + ("Brush name", "브러시 이름"), + ("Save current brush", "현재 브러시 저장"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 788df7f9..8d8fa32e 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -961,4 +961,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "Usar a moldura e os botões de janela do sistema operacional em vez da barra de título própria do TextureCraft", ), + ("Brushes", "Pincéis"), + ("My brushes", "Meus pincéis"), + ("Use this brush (keeps its size)", "Usar este pincel (mantém o tamanho)"), + ("Brush name", "Nome do pincel"), + ("Save current brush", "Salvar o pincel atual"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 3de5246c..c17b9e82 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -877,4 +877,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "使用操作系统的窗口边框和按钮,而不是 TextureCraft 自己的标题栏", ), + ("Brushes", "笔刷库"), + ("My brushes", "我的笔刷"), + ("Use this brush (keeps its size)", "使用此笔刷(保留大小)"), + ("Brush name", "笔刷名称"), + ("Save current brush", "保存当前笔刷"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bd53bd98..5aa9f754 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -78,6 +78,8 @@ pub struct TextureCraftApp { pub fps: f32, /// User smart materials found in the library folder (refreshed on demand). pub library: Option>, + /// User brush presets found in the brushes folder (refreshed on demand). + pub brushes: Option>, /// Rendering mode's path tracer. pub render: render_mode::RenderView, /// Smoothed CPU time spent building the UI per frame (ms). @@ -132,6 +134,7 @@ impl TextureCraftApp { ui_ms: 0.0, profiler: profile::Profiler::default(), library: None, + brushes: None, render: render_mode::RenderView::default(), last_paint_point: None, placing_decal: None, diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 0abcbe68..e6366b9f 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -11,6 +11,7 @@ use texturecraft_engine::core::ProceduralKind; use texturecraft_engine::filter_lib::FILTERS; use texturecraft_engine::materials::MATERIALS; use texturecraft_engine::paint::alphas; +use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; use texturecraft_engine::smart_masks::SMART_MASKS; use texturecraft_render::ibl::ENVIRONMENTS; @@ -25,6 +26,7 @@ pub(crate) enum Tab { Smart, Masks, Filters, + Brushes, Alphas, Procedurals, Environments, @@ -32,11 +34,12 @@ pub(crate) enum Tab { } /// The shelf tabs: icon and (English, translated where shown) name. -pub(crate) const TABS: [(Tab, &str, &str); 8] = [ +pub(crate) const TABS: [(Tab, &str, &str); 9] = [ (Tab::Materials, ic::SPHERE, "Materials"), (Tab::Smart, ic::STACK, "Smart materials"), (Tab::Masks, ic::CIRCLE_HALF, "Smart masks"), (Tab::Filters, ic::FUNNEL, "Filters"), + (Tab::Brushes, ic::PAINT_BRUSH_BROAD, "Brushes"), (Tab::Alphas, ic::SHAPES, "Alphas"), (Tab::Procedurals, ic::CHECKERBOARD, "Procedurals"), (Tab::Environments, ic::SUN_HORIZON, "Environments"), @@ -158,6 +161,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { } Tab::Masks => smart_masks(app, ui, &ctx, &filter, title), Tab::Filters => filters(app, ui, &ctx, &filter, title), + Tab::Brushes => brushes(app, ui, &ctx, &filter, title), Tab::Alphas => alpha_library(app, ui, &ctx, &filter, title), Tab::Procedurals => procedurals(app, ui, &ctx, &filter, title), Tab::Environments => environments(app, ui, &filter, title), @@ -332,6 +336,82 @@ fn filters(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: } } +/// Brush presets, grouped by category, then the user's own: a click sets the brush's stroke +/// (alpha, spacing, flow, jitters…) and keeps its size. +fn brushes(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { + let shown: Vec<&BrushPreset> = PRESETS.iter().filter(|p| matches(filter, &[p.label, p.category, p.id])).collect(); + if !shown.is_empty() { + title(ui, name); + for cat in categories(&shown, |p| p.category) { + header(ui, cat); + 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() { + app.run("brush.preset.apply", json!({"preset": p.id})); + } + } + }); + } + } + my_brushes(app, ui, filter); +} + +/// The user's saved brush presets (desktop brushes folder) and saving the current brush there. +#[cfg(not(target_arch = "wasm32"))] +fn my_brushes(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { + use texturecraft_engine::brush_preset_cmds::BRUSH_EXT; + let dir = crate::user_dir("brushes"); + if app.brushes.is_none() { + let mut files: Vec = std::fs::read_dir(&dir) + .map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == BRUSH_EXT)).collect()) + .unwrap_or_default(); + files.sort(); + app.brushes = Some(files); + } + let files = app.brushes.clone().unwrap_or_default(); + let name = |f: &std::path::PathBuf| f.file_stem().and_then(|s| s.to_str()).unwrap_or("brush").to_string(); + let shown: Vec<_> = files.iter().filter(|f| matches(filter, &[&name(f)])).collect(); + if !filter.is_empty() && shown.is_empty() { + return; + } + ui.horizontal(|ui| { + header(ui, tr("My brushes")); + if ui.small_button(ic::ARROW_CLOCKWISE).on_hover_text(tr("Rescan the library folder")).clicked() { + app.brushes = None; + } + }); + for f in shown { + if ui + .add(egui::Button::selectable(false, format!("{} {}", ic::PAINT_BRUSH_BROAD, name(f)))) + .on_hover_text(tr("Use this brush (keeps its size)")) + .clicked() + { + app.run("brush.preset.load", json!({"path": f.display().to_string()})); + } + } + ui.horizontal(|ui| { + let id = ui.make_persistent_id("brush_preset_name"); + let mut new_name: String = ui.data_mut(|d| d.get_temp(id)).unwrap_or_default(); + ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(110.0)); + let file = texturecraft_engine::formats::export::sanitize_file_stem(new_name.trim()); + if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() { + let path = dir.join(format!("{file}.{BRUSH_EXT}")); + // A folder that can't be made fails the save, which reports it. + let _ = std::fs::create_dir_all(&dir); + if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_some() { + new_name.clear(); + app.brushes = None; + } + } + ui.data_mut(|d| d.insert_temp(id, new_name)); + }); + ui.add_space(6.0); +} + +#[cfg(target_arch = "wasm32")] +fn my_brushes(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {} + /// The built-in alpha library, grouped by category; the brush's alpha is outlined. fn alpha_library(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) { let tk = Tokens::get(ctx); diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index d372ffa9..08f6dcc0 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -6,7 +6,8 @@ use std::collections::HashMap; use egui::{Color32, ColorImage, Painter, Pos2, Rect, TextureHandle, TextureOptions}; use texturecraft_engine::core::ProceduralKind; -use texturecraft_engine::paint::{BrushAlpha, alphas}; +use texturecraft_engine::paint::presets::BrushPreset; +use texturecraft_engine::paint::{BrushAlpha, BrushSettings, Shape, alphas}; use texturecraft_engine::preview::{self, Sample}; use texturecraft_engine::texel::linear_to_srgb; @@ -17,7 +18,8 @@ const SPHERE_PX: usize = 72; #[derive(Default)] pub struct Thumbs { - /// Shelf thumbnails by key (`mat:`, `mask:`, `filter:`, `proc:`, `alpha:`). + /// Shelf thumbnails by key (`mat:`, `mask:`, `filter:`, `proc:`, `alpha:`, + /// `brush:`). shelf: HashMap, images: HashMap, /// (frame, thumbnails rendered in it). @@ -192,6 +194,54 @@ impl Thumbs { ColorImage::new([n, n], a.render(n, 2).into_iter().map(|v| Color32::from_gray((v * 255.0 + 0.5) as u8)).collect()) }) } + + /// 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)) + } +} + +/// `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()) } /// A small shaded sphere drawn with a vertex-colored mesh (layer thumbnails, previews). diff --git a/docs/features.md b/docs/features.md index cbec3d46..f6ea6819 100644 --- a/docs/features.md +++ b/docs/features.md @@ -8,6 +8,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA angle, flow and position jitter; tangent or camera alignment, angle fade, backface culling, lazy mouse, X/Y/Z mirror and radial symmetry (copies paint the far side too) and pen pressure. **67 procedural brush alphas** in their own shelf tab, or any imported image as the alpha. + **18 brush presets** (basic, wear and grunge, details) in the shelf's Brushes tab set the + stroke and keep the size; save your own brushes there too. - **Tools:** paint, eraser, **projection** with image stencils (hold S to move, turn and scale the stencil), polygon fill (triangle, UV island or the whole mesh), **path** and **lasso fill**, a **particle brush**, **smudge**, **clone** (V + click sets the source), color picker, Shift+click From af2d42ca0af488ef15e5f6e626f9783ae7beb447 Mon Sep 17 00:00:00 2001 From: Agapenordev <120006055+Agapenordev@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:35:40 +0100 Subject: [PATCH 11/60] Arabic: GPU memory and GPU error notices main gained the Arabic table (#47) after this branch started; every key must be translated there too. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/ar.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 0320cbf7..49ff9ca4 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -924,4 +924,13 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "استخدام إطار وأزرار نافذة نظام التشغيل بدلاً من شريط عنوان TextureCraft الخاص", ), + ("GPU error: {error}", "خطأ في GPU: {error}"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "لا توجد ذاكرة GPU كافية لعرض مجموعة الخامات \"{name}\" كاملة: خفّض دقة الخامة لمنفذ العرض في الإعدادات. لا يتأثر الرسم والتصدير.", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "لا توجد ذاكرة GPU كافية لعرض {count} من مجموعات الخامات كاملة ({names}): خفّض دقة الخامة لمنفذ العرض في الإعدادات. لا يتأثر الرسم والتصدير.", + ), ]; From 77b685403fa7dde176900bb58f4b24f2adf10d34 Mon Sep 17 00:00:00 2001 From: Agapenordev <120006055+Agapenordev@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:46:12 +0100 Subject: [PATCH 12/60] Arabic: the empty-layer filter hint main gained the Arabic table (#47) after this branch started; every key must be translated there too. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/ar.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 0320cbf7..7f5f9b97 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -924,4 +924,5 @@ pub const TABLE: &[(&str, &str)] = &[ "Use the operating system's window frame and buttons instead of TextureCraft's own title bar", "استخدام إطار وأزرار نافذة نظام التشغيل بدلاً من شريط عنوان TextureCraft الخاص", ), + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "لا يوجد رسم على \"{layer}\" بعد: يغيّر المرشح ما ترسمه عليها."), ]; From 355b7e7fd5c7b98347c2c512d08b3ae33bd9db67 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 04:52:35 +0700 Subject: [PATCH 13/60] Close the brush preset test after the merge --- crates/engine/tests/session.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 41ebc5e2..5e22e610 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -189,6 +189,10 @@ fn brush_presets_apply_save_and_load() { let _ = std::fs::remove_file(path); for bad in [json!({}), json!({"preset": "nope"})] { assert!(execute(&mut s, "brush.preset.apply", &bad).is_err()); + } +} + +#[test] fn text_becomes_a_brush_alpha_and_a_decal() { let mut s = session(); let fonts = execute(&mut s, "text.fonts", &Value::Null).unwrap(); From eea71c679070890b05238550490406dd979bbe3f Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 05:08:15 +0700 Subject: [PATCH 14/60] Docs: roadmap estimate after text, brush presets and the start window Painting tools 88 to 90% (text in any font as an alpha or a decal), materials and assets 86 to 88% (18 brush presets and user presets), the total about 94%; the viewport and UI rows mention polygon wireframes and the start window. --- ROADMAP.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index ebbd0257..17640da4 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,7 +4,7 @@ TextureCraft aims for 1:1 parity with Adobe Substance 3D Painter's texturing wor performance, a smaller footprint, every feature drivable by agents (MCP, CLI, control channel), and builds for Windows, macOS, Linux, FreeBSD and the web. -## Honest parity estimate (2026-11-01) +## Honest parity estimate (2026-11-02) Weighted by how much of a professional's daily work each area carries. "Done" counts what works end to end today (engine + UI + automation + tests), not what is planned. @@ -14,15 +14,15 @@ end to end today (engine + UI + automation + tests), not what is planned. | Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | | Texture sets | 6 | 95% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile**, one texture per tile at its own size, `$udim` export), list with visibility, sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | Filter radii and height slopes of a tile smaller than its atlas block follow the block | | Layer stack | 16 | 96% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels, invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; smart masks; mask view (Alt+click); duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **27 library filters** (adjustments, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | -| Painting tools | 14 | 88% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt (not exposed by the windowing layer) | -| Materials and assets | 8 | 86% | 48 procedural materials (incl. car paint, velvet, brushed steel, skin, wax), 21 smart materials, 18 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 22 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | +| Painting tools | 14 | 90% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt (not exposed by the windowing layer) | +| Materials and assets | 8 | 88% | 48 procedural materials (incl. car paint, velvet, brushed steel, skin, wax), 21 smart materials, 18 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 22 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | | Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — | -| Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Hardware ray tracing | +| Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Hardware ray tracing | | Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — | | Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, `$udim` tiles, OBJ, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | -| UI and UX | 8 | 95% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, **shortcut editor** with conflict detection, tooltips with shortcuts; all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations | +| UI and UX | 8 | 95% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, a **start window** (new, open, recent projects), **shortcut editor** with conflict detection, tooltips with shortcuts; all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations | | Platforms | 4 | 75% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish | -| **Total** | **100** | **≈ 93%** | | | +| **Total** | **100** | **≈ 94%** | | | Beyond the reference app: every command is available to agents through MCP, the CLI and the app's control channel (MCP workspace tools cover every file action: projects, meshes, high polys and From 16e70a0145a898b877cd95ab7a73abfff6fbc392 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:27:52 -0500 Subject: [PATCH 15/60] feat(export): choose the colour space of exported colour maps New texturecraft_texel::ColorSpace (sRGB, Linear Rec.709, ACEScg, ACES2065-1): the matrices are derived at first use from the published primaries and white points (BT.709, ACES S-2014-004, SMPTE ST 2065-1) with Bradford adaptation, so nothing is copied from a colour-management library. ExportOptions::color_space (command and dialog: `colorSpace`) converts the colour maps on their way out; data maps (normal, height, roughness...) are never converted. None keeps today's behaviour: sRGB in 8/16-bit files, linear Rec.709 in float files. A linear space in an integer file is written without the sRGB curve; ACEScg and ACES2065-1 in integer files warn that values outside 0-1 are clamped (EXR and HDR keep them). `$colorSpace` in a file name template now also says ACEScg / ACES2065-1. The export dialog gets a Color space combo (label translated in all ten languages). Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 2 +- crates/engine/src/file_cmds.rs | 10 +- crates/engine/tests/export_colour_space.rs | 57 ++++++ crates/formats/src/export/mod.rs | 54 ++++- crates/formats/src/export/tests.rs | 79 ++++++++ crates/texel/src/colorspace.rs | 217 +++++++++++++++++++++ crates/texel/src/lib.rs | 2 + crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/state.rs | 4 + crates/ui-egui/src/windows.rs | 12 ++ 18 files changed, 439 insertions(+), 7 deletions(-) create mode 100644 crates/engine/tests/export_colour_space.rs create mode 100644 crates/texel/src/colorspace.rs diff --git a/ROADMAP.md b/ROADMAP.md index 17640da4..7972d22e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -19,7 +19,7 @@ end to end today (engine + UI + automation + tests), not what is planned. | Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — | | Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Hardware ray tracing | | Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — | -| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, `$udim` tiles, OBJ, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | +| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, **colour space** of the colour maps (sRGB, Linear Rec.709, ACEScg, ACES2065-1; data maps never converted), `$udim` tiles, OBJ, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | | UI and UX | 8 | 95% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, a **start window** (new, open, recent projects), **shortcut editor** with conflict detection, tooltips with shortcuts; all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations | | Platforms | 4 | 75% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish | | **Total** | **100** | **≈ 94%** | | | diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 32ae6b49..4f0c253a 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -42,7 +42,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1)}", always, export_textures ), @@ -60,7 +60,7 @@ pub fn specs() -> Vec { "List export outputs", [], None, - "{preset?: name or preset object, ts?, format?, bitDepth?, size?} → [{ts, map, file, format, bitDepth, warnings}]", + "{preset?: name or preset object, ts?, format?, bitDepth?, size?, colorSpace?} → [{ts, map, file, format, bitDepth, warnings}]", always, plan ), @@ -256,6 +256,12 @@ pub fn export_options(s: &Session, p: &Value, cmd: &str) -> Result return Err(bad(cmd, format!("unknown normal format `{other}`"))), None => None, }; + if let Some(name) = strp(p, "colorSpace") { + o.color_space = Some( + texturecraft_texel::ColorSpace::from_name(name) + .ok_or_else(|| bad(cmd, format!("unknown colorSpace `{name}` (sRGB, Linear Rec.709, ACEScg or ACES2065-1)")))?, + ); + } Ok(o) } diff --git a/crates/engine/tests/export_colour_space.rs b/crates/engine/tests/export_colour_space.rs new file mode 100644 index 00000000..d1985ec8 --- /dev/null +++ b/crates/engine/tests/export_colour_space.rs @@ -0,0 +1,57 @@ +//! `file.exportTextures` / `export.plan` with `colorSpace`. + +use serde_json::{Value, json}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::texel::ColorSpace; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); + execute(&mut s, "layer.add.fill", &json!({ "color": [0.8, 0.2, 0.1] })).unwrap(); + s +} + +fn export(s: &mut Session, tag: &str, extra: Value) -> (Value, std::path::PathBuf) { + let dir = std::env::temp_dir().join(format!("tc_export_cs_{tag}_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut p = json!({ "dir": dir.display().to_string(), "preset": "glTF PBR Metal Roughness", "format": "exr", "bitDepth": 32, "padding": "infinite" }); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + (execute(s, "file.exportTextures", &p).unwrap(), dir) +} + +fn first_pixel(path: &std::path::Path) -> [f32; 3] { + let img = image::open(path).unwrap().to_rgb32f(); + // The plane's UV layout covers the whole image; read its middle. + let px = img.get_pixel(img.width() / 2, img.height() / 2); + [px[0], px[1], px[2]] +} + +#[test] +fn colour_maps_are_written_in_the_chosen_space() { + let mut s = session(); + let (plain, dir_plain) = export(&mut s, "plain", json!({})); + let (aces, dir_aces) = export(&mut s, "aces", json!({ "colorSpace": "ACEScg" })); + let base = + |r: &Value| std::path::PathBuf::from(r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).find(|f| f.contains("BaseColor")).unwrap()); + let (a, b) = (first_pixel(&base(&plain)), first_pixel(&base(&aces))); + let want = ColorSpace::AcesCg.from_linear_rec709(a); + assert!((0..3).all(|k| (b[k] - want[k]).abs() < 1e-3), "{b:?} vs {want:?}"); + assert!((0..3).any(|k| (a[k] - b[k]).abs() > 0.01), "the colour actually changed: {a:?} vs {b:?}"); + for d in [dir_plain, dir_aces] { + let _ = std::fs::remove_dir_all(d); + } +} + +#[test] +fn the_plan_reports_the_space_and_clamping_and_bad_names_are_errors() { + let mut s = session(); + let plan = execute(&mut s, "export.plan", &json!({ "preset": "glTF PBR Metal Roughness", "colorSpace": "ACEScg" })).unwrap(); + assert!(plan.as_array().unwrap().iter().any(|f| f["warnings"].as_array().is_some_and(|w| !w.is_empty())), "8-bit ACEScg warns: {plan}"); + let float = execute(&mut s, "export.plan", &json!({ "preset": "glTF PBR Metal Roughness", "colorSpace": "ACEScg", "format": "exr" })).unwrap(); + assert!(float.as_array().unwrap().iter().all(|f| f["warnings"].as_array().is_some_and(Vec::is_empty)), "{float}"); + for bad in ["Display P3", "", "Rec.2020"] { + assert!(execute(&mut s, "export.plan", &json!({ "preset": "glTF PBR Metal Roughness", "colorSpace": bad })).is_err(), "{bad:?}"); + } +} diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index d5ff31c6..38f22880 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -20,7 +20,7 @@ use serde::{Deserialize, Serialize}; use texturecraft_compose::{BakedMaps, Composite}; use texturecraft_core::{AoMixing, BakedMap, Channel, ChannelKind, NormalFormat, NormalMixing, Project, TextureSet}; use texturecraft_geom::glam::Vec3; -use texturecraft_texel::{DilationMap, linear_to_srgb}; +use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb}; use crate::{FormatError, MAX_IMAGE_SIZE, Result}; @@ -323,11 +323,31 @@ pub struct ExportOptions { /// UV-tiled sets: one image of the whole tile atlas per map instead of a file per tile /// (for formats without UDIM support, with the mesh's UVs in atlas space). pub atlas: bool, + /// The colour space of the colour maps (data maps are never converted); None writes sRGB + /// into 8/16-bit files and linear Rec.709 into float files (EXR, HDR). + #[serde(skip)] + pub color_space: Option, +} + +impl ExportOptions { + /// The colour space colour maps are written in when `format` is used. + pub fn space_for(&self, format: FileFormat) -> ColorSpace { + self.color_space.unwrap_or(if format.is_float() { ColorSpace::LinearRec709 } else { ColorSpace::Srgb }) + } } impl ExportOptions { pub fn new(preset: ExportPreset) -> ExportOptions { - ExportOptions { preset, format_override: None, bit_depth_override: None, padding: Padding::Infinite, size: None, normal_format: None, atlas: false } + ExportOptions { + preset, + format_override: None, + bit_depth_override: None, + padding: Padding::Infinite, + size: None, + normal_format: None, + atlas: false, + color_space: None, + } } } @@ -462,7 +482,14 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export } let format = opts.format_override.unwrap_or(map.format); let bit_depth = format.depth(opts.bit_depth_override.unwrap_or(map.bit_depth)); - let color_space = if is_color(map) && !format.is_float() { "sRGB" } else { "linear" }; + let space = opts.space_for(format); + let color_space = match (is_color(map), space) { + (false, _) | (true, ColorSpace::LinearRec709) => "linear", + (true, ColorSpace::Srgb) => "sRGB", + (true, other) => other.name(), + }; + // Integer files clamp to 0-1, which wide-gamut linear colour can leave. + let clamps = is_color(map) && !format.is_float() && matches!(space, ColorSpace::AcesCg | ColorSpace::Aces2065); // One file per UV tile: names without `$udim` get it appended. let template = if tiles.iter().any(Option::is_some) && !map.file.contains("$udim") { format!("{}.$udim", map.file) } else { map.file.clone() }; for &tile in &tiles { @@ -477,6 +504,13 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let ext = format.extension(); let mut name = format!("{stem}.{ext}"); let mut warnings = Vec::new(); + if clamps { + warnings.push(format!( + "{} colours outside 0-1 are clamped in {} files; use EXR or HDR to keep them", + space.name(), + format.extension().to_uppercase() + )); + } // Case-insensitive: Windows and macOS file systems are. let mut k = 2; while used.contains(&name.to_ascii_lowercase()) { @@ -697,7 +731,19 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result = lay.iter().map(|(d, _)| *d != Dest::A && is_color(map) && !p.format.is_float()).collect(); + // Colour maps leave linear Rec.709 for the chosen space. sRGB in integer files is + // encoded by `encode`; every other case is converted here (float sRGB included). + let space = opts.space_for(p.format); + let rgb = lay.len() >= 3 && lay.iter().take(3).map(|(d, _)| *d).eq([Dest::R, Dest::G, Dest::B]); + let mut data = data; + if is_color(map) && rgb && (space != ColorSpace::Srgb || p.format.is_float()) && space != ColorSpace::LinearRec709 { + data.par_chunks_mut(n).for_each(|px| { + if let [r, g, b, ..] = px { + [*r, *g, *b] = space.from_linear_rec709([*r, *g, *b]); + } + }); + } + let srgb: Vec = lay.iter().map(|(d, _)| *d != Dest::A && is_color(map) && !p.format.is_float() && space == ColorSpace::Srgb).collect(); let mut warnings = p.warnings; let bytes = encode(p.format, p.bit_depth, size, n, &data, &srgb, &mut warnings)?; Ok(ExportedFile { name: p.name, bytes, width: size.0, height: size.1, warnings }) diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index c8c53407..babd96db 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -509,3 +509,82 @@ fn lobe_channels_export_as_document_maps_and_gltf_extension_maps() { let plain = Fx::new(&default_channels()).render_preset("glTF PBR Metal Roughness"); assert!(!plain.iter().any(|f| f.name.contains("Clearcoat") || f.name.contains("Sheen")), "sets without the lobes export no extension maps"); } + +#[test] +fn colour_space_converts_colour_maps_only() { + let fx = Fx::new(&default_channels()); + let preset = builtin_preset("glTF PBR Metal Roughness").unwrap(); + let want_at = |space: ColorSpace, x, y| space.from_linear_rec709(fx.comp.value(Channel::BaseColor, x, y)); + // ACEScg in a float EXR: the base colour is the converted triple, above-1 values aside. + let mut exr = ExportOptions::new(preset.clone()); + exr.format_override = Some(FileFormat::Exr); + exr.bit_depth_override = Some(32); + exr.color_space = Some(ColorSpace::AcesCg); + let files = fx.render(&exr); + let img = decode(find(&files, "_BaseColor.exr")).to_rgb32f(); + for (x, y) in [(0, 0), (10, 40), (63, 63)] { + let (px, want) = (img.get_pixel(x, y), want_at(ColorSpace::AcesCg, x, y)); + assert!((0..3).all(|k| (px[k] - want[k]).abs() < 1e-4), "({x},{y}) {px:?} vs {want:?}"); + } + // Data maps are never converted: roughness and metalness (packed in the ORM map) are as before. + let default_files = + fx.render(&ExportOptions { format_override: Some(FileFormat::Exr), bit_depth_override: Some(32), ..ExportOptions::new(preset.clone()) }); + assert_eq!(find(&files, "OcclusionRoughnessMetallic").bytes, find(&default_files, "OcclusionRoughnessMetallic").bytes); + assert_eq!(find(&files, "_Normal").bytes, find(&default_files, "_Normal").bytes); + assert_ne!(find(&files, "_BaseColor").bytes, find(&default_files, "_BaseColor").bytes); + + // Linear Rec.709 in an 8-bit PNG: the values are written without the sRGB curve. + let mut lin = ExportOptions::new(preset.clone()); + lin.color_space = Some(ColorSpace::LinearRec709); + let png = decode(find(&fx.render(&lin), "_BaseColor.png")); + let v = fx.comp.value(Channel::BaseColor, 10, 40); + for k in 0..3 { + assert!((png.get_pixel(10, 40)[k] as f32 - v[k] * 255.0).abs() <= 1.0, "[{k}]"); + } + // The default is unchanged: sRGB for integer files (None and explicit sRGB agree). + let default_png = fx.render(&ExportOptions::new(preset.clone())); + let mut srgb = ExportOptions::new(preset.clone()); + srgb.color_space = Some(ColorSpace::Srgb); + assert_eq!(find(&default_png, "_BaseColor.png").bytes, find(&fx.render(&srgb), "_BaseColor.png").bytes); + // An explicit sRGB in a float file is encoded once, not twice. + let mut float_srgb = ExportOptions::new(preset); + float_srgb.format_override = Some(FileFormat::Exr); + float_srgb.bit_depth_override = Some(32); + float_srgb.color_space = Some(ColorSpace::Srgb); + let px = *decode(find(&fx.render(&float_srgb), "_BaseColor.exr")).to_rgb32f().get_pixel(10, 40); + assert!((px[0] - linear_to_srgb(v[0])).abs() < 1e-4, "{px:?}"); +} + +#[test] +fn colour_space_names_the_files_and_warns_when_integer_files_clamp() { + let fx = Fx::new(&default_channels()); + let named = ExportPreset { + name: "named".into(), + maps: vec![MapSpec { + file: "$textureSet_$channel_$colorSpace".into(), + format: FileFormat::Png, + bit_depth: 8, + channels: vec![ + (Dest::R, SourceRef::Channel { channel: Channel::BaseColor, component: 0 }), + (Dest::G, SourceRef::Channel { channel: Channel::BaseColor, component: 1 }), + (Dest::B, SourceRef::Channel { channel: Channel::BaseColor, component: 2 }), + ], + }], + }; + let plan = |space: Option, format: Option| { + let opts = ExportOptions { color_space: space, format_override: format, ..ExportOptions::new(named.clone()) }; + list_outputs(&fx.project, 0, "sphere", &opts).unwrap().remove(0) + }; + assert!(plan(None, None).name.ends_with("_sRGB.png") && plan(None, Some(FileFormat::Exr)).name.ends_with("_linear.exr"), "defaults keep their names"); + assert!(plan(Some(ColorSpace::LinearRec709), None).name.ends_with("_linear.png")); + let aces = plan(Some(ColorSpace::AcesCg), None); + assert!(aces.name.ends_with("_ACEScg.png"), "{}", aces.name); + assert!(aces.warnings.iter().any(|w| w.contains("clamped")), "{:?}", aces.warnings); + assert!(plan(Some(ColorSpace::AcesCg), Some(FileFormat::Exr)).warnings.is_empty(), "float files keep the values"); + assert!(plan(None, None).warnings.is_empty() && plan(Some(ColorSpace::LinearRec709), None).warnings.is_empty()); + // The planned names are the rendered names. + let opts = ExportOptions { color_space: Some(ColorSpace::Aces2065), ..ExportOptions::new(named) }; + let names: Vec = fx.render(&opts).into_iter().map(|f| f.name).collect(); + assert_eq!(names, list_outputs(&fx.project, 0, "sphere", &opts).unwrap().into_iter().map(|p| p.name).collect::>()); + assert!(names[0].ends_with("_ACES2065-1.png"), "{names:?}"); +} diff --git a/crates/texel/src/colorspace.rs b/crates/texel/src/colorspace.rs new file mode 100644 index 00000000..a685cba5 --- /dev/null +++ b/crates/texel/src/colorspace.rs @@ -0,0 +1,217 @@ +//! Built-in colour spaces as plain maths: sRGB, linear Rec.709, ACEScg and ACES2065-1. +//! +//! The conversion matrices are derived at first use from the published primaries and white points +//! (ITU-R BT.709, ACES S-2014-004 for AP1, SMPTE ST 2065-1 for AP0) with Bradford chromatic +//! adaptation, so nothing is copied from a colour-management library. TextureCraft's colour +//! channels are linear Rec.709 internally; this module converts them for export. +//! +//! Only colour is converted. Data (normal, height, roughness...) has no colour space and never +//! goes through here. + +use std::sync::OnceLock; + +use crate::linear_to_srgb; + +/// The colour space of exported colour images. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum ColorSpace { + /// sRGB-encoded (display-referred, 0–1), Rec.709 primaries. + #[default] + Srgb, + /// Scene-linear Rec.709 / sRGB primaries, D65. + LinearRec709, + /// Scene-linear ACES AP1 primaries. + AcesCg, + /// Scene-linear ACES AP0 primaries (the archival interchange space). + Aces2065, +} + +impl ColorSpace { + pub const ALL: [ColorSpace; 4] = [ColorSpace::Srgb, ColorSpace::LinearRec709, ColorSpace::AcesCg, ColorSpace::Aces2065]; + + pub fn name(self) -> &'static str { + match self { + ColorSpace::Srgb => "sRGB", + ColorSpace::LinearRec709 => "Linear Rec.709", + ColorSpace::AcesCg => "ACEScg", + ColorSpace::Aces2065 => "ACES2065-1", + } + } + + /// A space by name, ignoring case, spaces and punctuation ("linear rec709", "ap1", "srgb_texture"). + pub fn from_name(name: &str) -> Option { + let key: String = name.chars().filter(|c| c.is_ascii_alphanumeric()).collect::().to_ascii_lowercase(); + Some(match key.as_str() { + "srgb" | "srgbtexture" => ColorSpace::Srgb, + "linearrec709" | "linearsrgb" | "linear" | "rec709" => ColorSpace::LinearRec709, + "acescg" | "ap1" => ColorSpace::AcesCg, + "aces20651" | "aces2065" | "ap0" | "aces" => ColorSpace::Aces2065, + _ => return None, + }) + } + + /// Whether values are scene-linear light. + pub fn is_linear(self) -> bool { + self != ColorSpace::Srgb + } + + fn primaries(self) -> Primaries { + match self { + ColorSpace::Srgb | ColorSpace::LinearRec709 => REC709, + ColorSpace::AcesCg => AP1, + ColorSpace::Aces2065 => AP0, + } + } + + /// Linear Rec.709 `rgb` as values in this space: the primaries are converted, and sRGB + /// also gets its transfer curve (clamped to 0–1). Linear spaces keep values outside 0–1. + /// Non-finite input becomes 0. + pub fn from_linear_rec709(self, rgb: [f32; 3]) -> [f32; 3] { + let rgb = rgb.map(|v| if v.is_finite() { v } else { 0.0 }); + let out = match matrix_to(self) { + Some(m) => [0, 1, 2].map(|i| m[i][0] * rgb[0] + m[i][1] * rgb[1] + m[i][2] * rgb[2]), + None => rgb, + }; + if self == ColorSpace::Srgb { out.map(linear_to_srgb) } else { out } + } +} + +type M3 = [[f64; 3]; 3]; + +#[derive(Clone, Copy)] +struct Primaries { + r: [f64; 2], + g: [f64; 2], + b: [f64; 2], + white: [f64; 2], +} + +const D65: [f64; 2] = [0.3127, 0.3290]; +const D60_ACES: [f64; 2] = [0.32168, 0.33767]; +const REC709: Primaries = Primaries { r: [0.640, 0.330], g: [0.300, 0.600], b: [0.150, 0.060], white: D65 }; +const AP1: Primaries = Primaries { r: [0.713, 0.293], g: [0.165, 0.830], b: [0.128, 0.044], white: D60_ACES }; +const AP0: Primaries = Primaries { r: [0.7347, 0.2653], g: [0.0, 1.0], b: [0.0001, -0.0770], white: D60_ACES }; + +const BRADFORD: M3 = [[0.8951, 0.2664, -0.1614], [-0.7502, 1.7135, 0.0367], [0.0389, -0.0685, 1.0296]]; + +fn mul(a: &M3, b: &M3) -> M3 { + let mut o = [[0.0; 3]; 3]; + for (i, row) in o.iter_mut().enumerate() { + for (j, v) in row.iter_mut().enumerate() { + *v = (0..3).map(|k| a[i][k] * b[k][j]).sum(); + } + } + o +} + +fn apply(m: &M3, v: [f64; 3]) -> [f64; 3] { + [0, 1, 2].map(|i| m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2]) +} + +fn inverse(m: &M3) -> Option { + let c = |r: usize, c: usize| { + let (r1, r2) = ((r + 1) % 3, (r + 2) % 3); + let (c1, c2) = ((c + 1) % 3, (c + 2) % 3); + m[r1][c1] * m[r2][c2] - m[r1][c2] * m[r2][c1] + }; + let det = m[0][0] * c(0, 0) + m[0][1] * c(0, 1) + m[0][2] * c(0, 2); + if det.abs() < 1e-12 || !det.is_finite() { + return None; + } + let mut o = [[0.0; 3]; 3]; + for (i, row) in o.iter_mut().enumerate() { + for (j, v) in row.iter_mut().enumerate() { + *v = c(j, i) / det; + } + } + Some(o) +} + +fn xy_to_xyz(xy: [f64; 2]) -> [f64; 3] { + [xy[0] / xy[1], 1.0, (1.0 - xy[0] - xy[1]) / xy[1]] +} + +/// RGB (linear) to XYZ for a set of primaries, scaled so white maps to the white point. +fn rgb_to_xyz(p: &Primaries) -> Option { + let (r, g, b) = (xy_to_xyz(p.r), xy_to_xyz(p.g), xy_to_xyz(p.b)); + let cols = [[r[0], g[0], b[0]], [r[1], g[1], b[1]], [r[2], g[2], b[2]]]; + let s = apply(&inverse(&cols)?, xy_to_xyz(p.white)); + Some([[r[0] * s[0], g[0] * s[1], b[0] * s[2]], [r[1] * s[0], g[1] * s[1], b[1] * s[2]], [r[2] * s[0], g[2] * s[1], b[2] * s[2]]]) +} + +/// Bradford chromatic adaptation from one white point to another. +fn adapt(from: [f64; 2], to: [f64; 2]) -> Option { + let (cs, cd) = (apply(&BRADFORD, xy_to_xyz(from)), apply(&BRADFORD, xy_to_xyz(to))); + let scale = [[cd[0] / cs[0], 0.0, 0.0], [0.0, cd[1] / cs[1], 0.0], [0.0, 0.0, cd[2] / cs[2]]]; + Some(mul(&inverse(&BRADFORD)?, &mul(&scale, &BRADFORD))) +} + +/// The matrix from linear Rec.709 to the linear primaries of `to` (cached). +fn matrix_to(to: ColorSpace) -> Option<[[f32; 3]; 3]> { + static CACHE: OnceLock<[Option<[[f32; 3]; 3]>; 4]> = OnceLock::new(); + let table = CACHE.get_or_init(|| { + ColorSpace::ALL.map(|s| { + let (from, to) = (REC709, s.primaries()); + let m = mul(&inverse(&rgb_to_xyz(&to)?)?, &mul(&adapt(from.white, to.white)?, &rgb_to_xyz(&from)?)); + Some(m.map(|r| r.map(|v| v as f32))) + }) + }); + let i = ColorSpace::ALL.iter().position(|s| *s == to)?; + table.get(i).copied().flatten() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::srgb_to_linear; + + fn close(a: [f32; 3], b: [f32; 3], tol: f32) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() <= tol) + } + + #[test] + fn white_stays_white_in_every_linear_space() { + for s in [ColorSpace::LinearRec709, ColorSpace::AcesCg, ColorSpace::Aces2065] { + assert!(close(s.from_linear_rec709([1.0; 3]), [1.0; 3], 1e-4), "{s:?}"); + } + assert!(close(ColorSpace::Srgb.from_linear_rec709([1.0; 3]), [1.0; 3], 1e-5)); + } + + #[test] + fn rec709_primaries_in_acescg_match_published_values() { + // Rec.709 red in ACEScg (AP1, D60): the widely published 0.6131 0.0702 0.0206. + assert!(close(ColorSpace::AcesCg.from_linear_rec709([1.0, 0.0, 0.0]), [0.6131, 0.0702, 0.0206], 2e-3)); + // And in ACES2065-1 (AP0): 0.4397 0.0897 0.0175. + assert!(close(ColorSpace::Aces2065.from_linear_rec709([1.0, 0.0, 0.0]), [0.4397, 0.0897, 0.0175], 2e-3)); + } + + #[test] + fn grey_stays_neutral_and_srgb_is_the_transfer_curve() { + for s in ColorSpace::ALL { + let o = s.from_linear_rec709([0.18; 3]); + assert!(close(o, [o[0]; 3], 1e-4), "{s:?} {o:?}"); + } + assert!(close(ColorSpace::Srgb.from_linear_rec709([0.5; 3]), [linear_to_srgb(0.5); 3], 1e-6)); + assert!((srgb_to_linear(ColorSpace::Srgb.from_linear_rec709([0.25; 3])[0]) - 0.25).abs() < 1e-5); + assert_eq!(ColorSpace::LinearRec709.from_linear_rec709([0.3, 2.0, -1.0]), [0.3, 2.0, -1.0], "linear Rec.709 is the identity, values above 1 kept"); + } + + #[test] + fn hostile_values_stay_finite() { + for s in ColorSpace::ALL { + assert!(s.from_linear_rec709([f32::NAN, f32::INFINITY, f32::NEG_INFINITY]).iter().all(|v| v.is_finite()), "{s:?}"); + } + } + + #[test] + fn names_round_trip_and_aliases_work() { + for s in ColorSpace::ALL { + assert_eq!(ColorSpace::from_name(s.name()), Some(s)); + } + assert_eq!(ColorSpace::from_name("srgb_texture"), Some(ColorSpace::Srgb)); + assert_eq!(ColorSpace::from_name("AP1"), Some(ColorSpace::AcesCg)); + assert_eq!(ColorSpace::from_name("linear"), Some(ColorSpace::LinearRec709)); + assert_eq!(ColorSpace::from_name("nope"), None); + assert!(!ColorSpace::Srgb.is_linear() && ColorSpace::AcesCg.is_linear()); + } +} diff --git a/crates/texel/src/lib.rs b/crates/texel/src/lib.rs index 329ffaa4..982ca101 100644 --- a/crates/texel/src/lib.rs +++ b/crates/texel/src/lib.rs @@ -6,10 +6,12 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod colorspace; pub mod dilate; pub mod noise; pub mod tile; +pub use colorspace::ColorSpace; pub use dilate::DilationMap; pub use tile::{TILE, TILE_AREA, TileData, TileImage, from_u16, from_u16_signed, to_u16, to_u16_signed}; diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 976d68cb..79b7654e 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -521,6 +521,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal from height", "ناظم من الارتفاع"), ("Normal map combine", "دمج خرائط النواظم"), ("Normal map detail", "تفاصيل خريطة النواظم"), + ("Color space", "فضاء الألوان"), ("Normal map format", "صيغة خريطة النواظم"), ("Normal map inverse detail", "عكس تفاصيل خريطة النواظم"), ("Normal: painting uses the flat normal", "عادي: يستخدم الرسم الناظم المسطح"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 383fd770..bbbc7189 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -548,6 +548,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal from height", "Normale aus Höhe"), ("Normal map combine", "Normal-Map kombinieren"), ("Normal map detail", "Normal-Map-Detail"), + ("Color space", "Farbraum"), ("Normal map format", "Normal-Map-Format"), ("Normal map inverse detail", "Normal-Map-Detail invertiert"), ("Normal: painting uses the flat normal", "Normale: Malen verwendet die flache Normale"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index d2bbe0f8..eca8e7da 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -542,6 +542,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal from height", "Normal desde altura"), ("Normal map combine", "Combinar mapa de normales"), ("Normal map detail", "Detalle de mapa de normales"), + ("Color space", "Espacio de color"), ("Normal map format", "Formato del mapa de normales"), ("Normal map inverse detail", "Detalle inverso de mapa de normales"), ("Normal: painting uses the flat normal", "Normal: la pintura usa la normal plana"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 07cf9981..3130c83c 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -551,6 +551,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal from height", "Normale depuis la hauteur"), ("Normal map combine", "Normales : combinaison"), ("Normal map detail", "Normales : détail"), + ("Color space", "Espace colorimétrique"), ("Normal map format", "Format de carte de normales"), ("Normal map inverse detail", "Normales : détail inverse"), ("Normal: painting uses the flat normal", "Normal : la peinture utilise la normale plate"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index d4818eca..114c49d2 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -548,6 +548,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal from height", "Normale da altezza"), ("Normal map combine", "Combina mappa normali"), ("Normal map detail", "Dettaglio mappa normali"), + ("Color space", "Spazio colore"), ("Normal map format", "Formato mappa normali"), ("Normal map inverse detail", "Dettaglio inverso mappa normali"), ("Normal: painting uses the flat normal", "Normale: la pittura usa la normale piatta"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 62c1c15d..b61b239b 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -533,6 +533,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal from height", "ハイトからノーマル"), ("Normal map combine", "ノーマルマップ合成"), ("Normal map detail", "ノーマルマップ ディテール"), + ("Color space", "カラースペース"), ("Normal map format", "ノーマルマップ形式"), ("Normal map inverse detail", "ノーマルマップ 逆ディテール"), ("Normal: painting uses the flat normal", "ノーマル: ペイントにはフラットな法線を使用"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index ec37113c..806b41bf 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -527,6 +527,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal from height", "높이에서 노멀"), ("Normal map combine", "노멀 맵 결합"), ("Normal map detail", "노멀 맵 디테일"), + ("Color space", "색 공간"), ("Normal map format", "노멀 맵 형식"), ("Normal map inverse detail", "노멀 맵 역 디테일"), ("Normal: painting uses the flat normal", "노멀: 평면 노멀로 페인팅합니다"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 5db5da19..1835047a 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -539,6 +539,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal from height", "Normal a partir da altura"), ("Normal map combine", "Combinação de mapa normal"), ("Normal map detail", "Detalhe de mapa normal"), + ("Color space", "Espaço de cor"), ("Normal map format", "Formato do mapa normal"), ("Normal map inverse detail", "Detalhe inverso de mapa normal"), ("Normal: painting uses the flat normal", "Normal: a pintura usa a normal plana"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 895dfc20..5e67cb03 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -482,6 +482,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal from height", "由高度生成法线"), ("Normal map combine", "法线贴图合并"), ("Normal map detail", "法线贴图细节"), + ("Color space", "色彩空间"), ("Normal map format", "法线贴图格式"), ("Normal map inverse detail", "法线贴图反向细节"), ("Normal: painting uses the flat normal", "法线:绘画使用平坦法线"), diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 287be1a3..e335c705 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -167,6 +167,9 @@ pub struct ExportUi { pub size: u32, /// "" (project), openGl or directX. pub normal_format: String, + /// "" (by file format: sRGB, or linear for float files), or a colour space name. + #[serde(default)] + pub color_space: String, /// Texture sets excluded from export. pub skip: Vec, pub tab: u8, @@ -189,6 +192,7 @@ impl Default for ExportUi { dilation: 16, size: 0, normal_format: String::new(), + color_space: String::new(), skip: Vec::new(), tab: 0, draft: None, diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index eab0046e..adfc1cf2 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -1063,6 +1063,9 @@ pub(crate) fn export_params(app: &TextureCraftApp) -> serde_json::Value { if !e.normal_format.is_empty() { p["normalFormat"] = json!(e.normal_format); } + if !e.color_space.is_empty() { + p["colorSpace"] = json!(e.color_space); + } p } @@ -1162,6 +1165,15 @@ fn export_settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, presets: &[textur } }); ui.end_row(); + ui.label(tr("Color space")); + let shown = if app.ui.export.color_space.is_empty() { tr("Default") } else { app.ui.export.color_space.as_str() }; + egui::ComboBox::from_id_salt("exp_cs").selected_text(shown).show_ui(ui, |ui| { + ui.selectable_value(&mut app.ui.export.color_space, String::new(), tr("Default")); + for name in ["sRGB", "Linear Rec.709", "ACEScg", "ACES2065-1"] { + ui.selectable_value(&mut app.ui.export.color_space, name.to_string(), name); + } + }); + ui.end_row(); }); } From 8a281d7f2c767a150b9c4d09edd7a4112c0fe325 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 1 Nov 2026 22:30:06 +0000 Subject: [PATCH 16/60] Bake: thickness max occluder distance defaults to 0.1 Thickness is the mean hit distance divided by the max occluder distance, so the old shared default of 0.25 of the bounding box diagonal turned most thin parts of a model nearly black, and long rays reached geometry behind single-sided parts. 0.1 is the default in Adobe's public baker documentation. AO and bent normals keep 0.25. Co-Authored-By: Claude Opus 5.5 --- crates/core/src/project.rs | 3 ++- crates/engine/tests/bake.rs | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index ca2ee2ec..a722b855 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -230,7 +230,8 @@ impl Default for BakeSettings { ao: RaySettings::default(), ao_ignore_backface: false, ao_self_occlusion: SelfOcclusion::Always, - thickness: RaySettings::default(), + // Thickness is hit distance / max distance: long rays turn thin parts almost black. + thickness: RaySettings { max_distance: 0.1, ..RaySettings::default() }, bent_normal: RaySettings::default(), curvature_strength: 1.0, curvature_from_normal: false, diff --git a/crates/engine/tests/bake.rs b/crates/engine/tests/bake.rs index e209094f..41940f54 100644 --- a/crates/engine/tests/bake.rs +++ b/crates/engine/tests/bake.rs @@ -143,7 +143,7 @@ fn per_map_ray_settings_round_trip() { let b = s.doc.project.texture_sets[0].bake.clone(); assert_eq!(b.ao, RaySettings { rays: 48, max_distance: 0.5, spread: 90.0, distribution: RayDistribution::Uniform }); assert!(b.ao_ignore_backface && b.ao_self_occlusion == SelfOcclusion::SameMeshName); - assert_eq!((b.thickness.rays, b.thickness.spread, b.thickness.max_distance), (12, 45.0, 0.25)); + assert_eq!((b.thickness.rays, b.thickness.spread, b.thickness.max_distance), (12, 45.0, 0.1)); assert_eq!((b.bent_normal.rays, b.bent_normal.max_distance, b.bent_normal.spread), (6, 0.1, 180.0)); assert_eq!((b.curvature_radius, b.position_mode, b.direction_mode), (3, PositionMode::BoundingSphere, DirectionMode::Positive)); assert_eq!(r[0]["settings"]["ao"]["selfOcclusion"], "sameMeshName"); From e17381089133b69bb95cb7ceb6000f71b7955271 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 05:31:07 +0700 Subject: [PATCH 17/60] Docs: command_run also allows file.removeUnused Fixes #73. --- docs/control-protocol.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 14dd6de4..593b14f9 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -107,8 +107,8 @@ print(call("command.run", {"id": "layer.add.fill", "params": {"color": [0.8, 0.1 own files, so the path tools are unavailable there; `project_save` without a path invokes File › Save. -Through `command_run`, every `file.*` command but `file.close` (and `file.reimportMesh` without -a `path`) is refused, and so is any command given a `path` or `dir` (`resource.import`, +Through `command_run`, every `file.*` command but `file.close` and `file.removeUnused` (and +`file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir` (`resource.import`, `material.save`, `material.load`, …), in both modes: use the workspace tools below. `resource.text` takes a font family, not a path: it reads only the system's font folders. From 963008635c6471cf2bd3da691b953e0530446ef2 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 05:34:40 +0700 Subject: [PATCH 18/60] display.set: refuse unknown environment names The built-in environment list moves to core (render re-exports it), so the engine can name the valid ones in the error. Fixes #65. --- crates/core/src/project.rs | 3 +++ crates/engine/src/view_cmds.rs | 8 ++++++++ crates/render/src/ibl.rs | 3 +-- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index ca2ee2ec..11472a34 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -568,6 +568,9 @@ impl Default for Camera { } } +/// Built-in environments, in menu order. +pub const ENVIRONMENTS: [&str; 6] = ["Studio Soft", "Studio Contrast", "Overcast", "Sunset", "Warehouse", "Night"]; + /// Prefix of [`DisplaySettings::environment`] naming an image resource. pub const ENV_RESOURCE_PREFIX: &str = "resource:"; diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index b157dc90..2237a698 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -1,6 +1,7 @@ //! Edit, viewport and display commands. use serde_json::{Value, json}; +use texturecraft_core::project::ENVIRONMENTS; use texturecraft_core::{BakedMap, Channel, ToneMapping}; use texturecraft_geom::glam::Vec3; @@ -164,6 +165,9 @@ fn display(s: &mut Session, p: &Value) -> Result { { return Err(bad("display.set", format!("no image resource `{name}` (import it with resource.import)"))); } + if let Some(e) = env.as_deref().filter(|e| !e.starts_with(texturecraft_core::project::ENV_RESOURCE_PREFIX) && !ENVIRONMENTS.contains(e)) { + return Err(bad("display.set", format!("unknown environment `{e}`: one of {}, or resource:", ENVIRONMENTS.join(", ")))); + } let d = &mut s.doc.project.display; if let Some(e) = env { d.environment = e; @@ -234,6 +238,10 @@ mod tests { fn hdr_resources_become_the_environment() { let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); assert!(execute(&mut s, "display.set", &json!({"environment": "resource:sky.hdr"})).is_err(), "unknown resources are rejected"); + let e = execute(&mut s, "display.set", &json!({"environment": "nonexistent"})).unwrap_err().to_string(); + assert!(e.contains("Studio Soft"), "unknown environments are rejected with the valid names: {e}"); + assert_eq!(s.doc.project.display.environment, "Studio Soft"); + execute(&mut s, "display.set", &json!({"environment": "Night"})).unwrap(); let img = image::Rgb32FImage::from_fn(64, 32, |_, y| image::Rgb([if y < 8 { 40.0 } else { 0.5 }; 3])); let mut hdr = Vec::new(); image::DynamicImage::ImageRgb32F(img).write_to(&mut std::io::Cursor::new(&mut hdr), image::ImageFormat::Hdr).unwrap(); diff --git a/crates/render/src/ibl.rs b/crates/render/src/ibl.rs index d4c9fc8b..5c6b59db 100644 --- a/crates/render/src/ibl.rs +++ b/crates/render/src/ibl.rs @@ -18,8 +18,7 @@ pub struct EnvImage { pub data: Vec<[f32; 3]>, } -/// Built-in environments, in menu order. -pub const ENVIRONMENTS: [&str; 6] = ["Studio Soft", "Studio Contrast", "Overcast", "Sunset", "Warehouse", "Night"]; +pub use texturecraft_core::project::ENVIRONMENTS; pub fn dir_of(u: f32, v: f32) -> Vec3 { let (theta, phi) = (v * PI, u * TAU); From b5a34048feccd538c65974400e5ae074c64cf87d Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 05:37:47 +0700 Subject: [PATCH 19/60] USD export: the primvar reader's varname is a string usdchecker's ARKit profile expects inputs:varname as a string, not a token. The crate writer gains string values (the STRINGS table). Fixes #62. --- crates/formats/src/mesh_export/usd.rs | 6 ++++-- crates/formats/src/mesh_export/usdc.rs | 13 +++++++++++++ crates/formats/src/mesh_import/usd/tests.rs | 10 +++++++++- 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index 1232373f..1e14039e 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -83,6 +83,7 @@ pub fn usd_export_options() -> ExportOptions { #[derive(Clone, Debug, PartialEq)] pub(crate) enum UsdValue { Token(String), + Str(String), Int(i32), Double(f64), Asset(String), @@ -277,7 +278,8 @@ fn material(path: &str, id: &str, files: &[(usize, String)]) -> UsdPrim { let mut st = UsdPrim::new("st", "Shader"); st.attrs = vec![ UsdAttr::new("info:id", "token", Some(UsdValue::Token("UsdPrimvarReader_float2".into()))).uniform(), - UsdAttr::new("inputs:varname", "token", Some(UsdValue::Token("st".into()))), + // A string, not a token: usdchecker's ARKit profile refuses a token here. + UsdAttr::new("inputs:varname", "string", Some(UsdValue::Str("st".into()))), UsdAttr::new("outputs:result", "float2", None), ]; mat.children.push(st); @@ -355,7 +357,7 @@ fn usda_value(s: &mut String, v: &UsdValue) { s.push(']'); }; match v { - UsdValue::Token(t) => { + UsdValue::Token(t) | UsdValue::Str(t) => { let _ = write!(s, "\"{t}\""); } UsdValue::Int(i) => { diff --git a/crates/formats/src/mesh_export/usdc.rs b/crates/formats/src/mesh_export/usdc.rs index 3bb987ea..35900e28 100644 --- a/crates/formats/src/mesh_export/usdc.rs +++ b/crates/formats/src/mesh_export/usdc.rs @@ -57,6 +57,18 @@ impl Writer { i } + /// Index of `s` in the string table (which holds token indices). + fn string(&mut self, s: &str) -> u32 { + let t = self.token(s); + match self.strings.iter().position(|x| *x == t) { + Some(i) => i as u32, + None => { + self.strings.push(t); + (self.strings.len() - 1) as u32 + } + } + } + fn add_path(&mut self, parent: usize, parent_text: &str, name: &str, prop: bool) -> (usize, String) { let text = match (prop, parent_text) { (true, _) => format!("{parent_text}.{name}"), @@ -127,6 +139,7 @@ impl Writer { Ok(match v { UsdValue::Token(t) => rep(ty::TOKEN, codec::IS_INLINED, u64::from(self.token(t))), UsdValue::Asset(a) => rep(ty::ASSET_PATH, codec::IS_INLINED, u64::from(self.token(a))), + UsdValue::Str(s) => rep(ty::STRING, codec::IS_INLINED, u64::from(self.string(s))), UsdValue::Int(i) => rep(ty::INT, codec::IS_INLINED, u64::from(*i as u32)), UsdValue::Double(d) => { let at = self.offset(); diff --git a/crates/formats/src/mesh_import/usd/tests.rs b/crates/formats/src/mesh_import/usd/tests.rs index e5da5cb8..1797093b 100644 --- a/crates/formats/src/mesh_import/usd/tests.rs +++ b/crates/formats/src/mesh_import/usd/tests.rs @@ -344,7 +344,15 @@ fn usda_usdc_and_usdz_round_trip_with_textures() { && !text.contains("Red_Clearcoat"), "a coat exports with its roughness; no coat (black) drops both" ); - round_trip(&m, UsdFormat::Usdc, "usdc", &textures); + // The primvar reader's varname is a string (usdchecker --arkit refuses a token), in both encodings. + assert!(text.contains("string inputs:varname = \"st\""), "{text}"); + let usdc = round_trip(&m, UsdFormat::Usdc, "usdc", &textures); + let layer = super::usdc::read(&usdc, &mut super::Budget::new()).unwrap(); + let varnames: Vec<&super::Prop> = layer.prims.iter().filter_map(|p| p.props.get("inputs:varname")).collect(); + assert!(!varnames.is_empty()); + for v in varnames { + assert_eq!((v.type_name.as_str(), v.value.clone()), ("string", Some(super::Val::Tok(vec!["st".into()])))); + } let usdz = round_trip(&m, UsdFormat::Usdz, "usdz", &textures); let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&usdz)).unwrap(); let names: Vec = zip.file_names().map(|n| n.unwrap().into_owned()).collect(); From c4353cc8d00a2a1336d8a84ed160ccca380c3a10 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 05:41:00 +0700 Subject: [PATCH 20/60] CLI: --automation-read-root / --automation-write-root for mcp and serve The spelling the other crafting apps use; the same as --read-root / --write-root. Fixes #57. --- apps/texturecraft-cli/src/main.rs | 11 +++++++---- apps/texturecraft-cli/tests/cli.rs | 18 ++++++++++++++++++ docs/control-protocol.md | 4 +++- 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/apps/texturecraft-cli/src/main.rs b/apps/texturecraft-cli/src/main.rs index ec1e4f2d..b03174c1 100644 --- a/apps/texturecraft-cli/src/main.rs +++ b/apps/texturecraft-cli/src/main.rs @@ -38,7 +38,8 @@ USAGE: New project; --sample bakes and applies a smart material to every texture set. texturecraft-cli mcp [--bridge ] [--token ] [--read-root ] [--write-root ] MCP server on stdio: headless (file access only below the roots), or bridged to - `texturecraft --control `. + `texturecraft --control `. --automation-read-root / --automation-write-root are + the same as --read-root / --write-root (mcp and serve). texturecraft-cli serve [--port ] [--read-root ] [--write-root ] JSON lines ({\"id\",\"method\",\"params\"}) on stdio, or on 127.0.0.1: with a token. @@ -57,8 +58,8 @@ const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[ ("export", &["--preset", "--format", "--padding", "--size"], &[]), ("render", &["--size", "--view", "--camera", "--yaw", "--pitch", "--samples", "--bounces"], &["--cpu"]), ("new", &["--resolution"], &["--sample"]), - ("mcp", &["--bridge", "--token", "--read-root", "--write-root"], &[]), - ("serve", &["--port", "--read-root", "--write-root"], &[]), + ("mcp", &["--bridge", "--token", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]), + ("serve", &["--port", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]), ]; struct Args { @@ -367,7 +368,9 @@ fn new(a: &Args) -> R { } fn workspace(a: &Args) -> Result { - let (r, w) = (a.get("--read-root").map(Path::new), a.get("--write-root").map(Path::new)); + // `--automation-*-root` is the spelling the other crafting apps use. + let root = |k: &str| a.get(&format!("--automation-{k}")).or_else(|| a.get(&format!("--{k}"))).map(Path::new); + let (r, w) = (root("read-root"), root("write-root")); if r.is_none() && w.is_none() { return Ok(Filesystem::Denied); } diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index 254eabb4..7232e2b7 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -97,6 +97,24 @@ fn info_on_a_mesh_reports_uvs() { let _ = std::fs::remove_dir_all(&d); } +#[test] +fn serve_takes_the_automation_root_spelling_too() { + use std::io::Write as _; + let d = tmp("automation-root"); + let mut child = Command::new(env!("CARGO_BIN_EXE_texturecraft-cli")) + .args(["serve", "--automation-write-root", p(&d)]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + child.stdin.take().unwrap().write_all(b"{\"id\":1,\"method\":\"project.save\",\"params\":{\"path\":\"a.tcraft\"}}\n").unwrap(); + let out = child.wait_with_output().unwrap(); + let reply: Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(reply["ok"], true, "{reply}"); + assert!(d.join("a.tcraft").is_file()); + let _ = std::fs::remove_dir_all(&d); +} + #[test] fn render_writes_a_png() { let d = tmp("render"); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 14dd6de4..3123ce2e 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -100,7 +100,9 @@ print(call("command.run", {"id": "layer.add.fill", "params": {"color": [0.8, 0.1 - **Headless** (default): an in-process session that starts on the material ball (1024). Files are reachable only below the roots given at launch, as forward-slash paths relative to them: `--read-root ` for `project_open` / `mesh_import` / `mesh_reimport` / `bake_mesh_add`, - `--write-root ` for `project_save` / `material_save` / `textures_export` / `mesh_export`. Without roots there is no file access. `..`, absolute + `--write-root ` for `project_save` / `material_save` / `textures_export` / `mesh_export` + (`--automation-read-root` / `--automation-write-root`, as in the other crafting apps, are the + same flags). Without roots there is no file access. `..`, absolute paths, drive letters, device names and symlink or junction escapes are refused. - **Bridge**: `--bridge ` forwards to a running `texturecraft --control ` (token from `--token`, `TEXTURECRAFT_CONTROL_TOKEN` or the app's token file). The app reads and writes its From f47638d78231e3dc5a02fd5381e12cdd02c8de7b Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 05:42:55 +0700 Subject: [PATCH 21/60] CLI: say that new --sample bakes its mesh maps at up to 1024 px The baked maps are most of a sample project's size, so a 2048 sample is as large as a 1024 one; the usage and the control protocol now say so. Fixes #66. --- apps/texturecraft-cli/src/main.rs | 4 +++- docs/control-protocol.md | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/texturecraft-cli/src/main.rs b/apps/texturecraft-cli/src/main.rs index ec1e4f2d..ee35afa0 100644 --- a/apps/texturecraft-cli/src/main.rs +++ b/apps/texturecraft-cli/src/main.rs @@ -35,7 +35,9 @@ USAGE: camera saved in the project (camera.add); --samples path traces it instead (Rendering mode), on the GPU when it has compute shaders, else (or with --cpu) on the CPU. texturecraft-cli new > [--resolution ] [--sample] - New project; --sample bakes and applies a smart material to every texture set. + New project; --sample bakes and applies a smart material to every texture set. The + sample's mesh maps are baked at the resolution up to 1024 px (most of the file's size), + so a 2048 sample project is as large as a 1024 one. texturecraft-cli mcp [--bridge ] [--token ] [--read-root ] [--write-root ] MCP server on stdio: headless (file access only below the roots), or bridged to `texturecraft --control `. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 14dd6de4..d3710d6b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -218,7 +218,7 @@ texturecraft-cli --version # TextureCraft 0.1. texturecraft-cli info model.glb # triangles, materials, UV report texturecraft-cli info project.tcraft # texture sets, layers, baked maps texturecraft-cli commands --filter mask -texturecraft-cli new builtin:material_ball ball.tcraft --resolution 1024 --sample +texturecraft-cli new builtin:material_ball ball.tcraft --resolution 1024 --sample # mesh maps baked at ≤ 1024 px texturecraft-cli new model.glb model.tcraft --resolution 2048 texturecraft-cli run ball.tcraft layer.add.fill '{"color":"#c08040","metallic":1}' -o ball.tcraft texturecraft-cli batch script.json From 2d1047eb36c38ed65039525965d772af17beb454 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 05:46:55 +0700 Subject: [PATCH 22/60] Decals: an up parameter, and an upright rule that never degenerates layer.add.decal and layer.decal.set take up: [x, y, z]. Without it the decal keeps the view's up, and when that runs along the surface normal (a top face seen from a level camera) it takes the view direction, so the far edge is up, instead of an arbitrary perpendicular. Fixes #64. --- crates/engine/src/decal_cmds.rs | 22 ++++++++++++++++------ crates/engine/tests/painter_gaps.rs | 20 ++++++++++++++++++++ 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/decal_cmds.rs b/crates/engine/src/decal_cmds.rs index 5c1c4ab0..1221a8c9 100644 --- a/crates/engine/src/decal_cmds.rs +++ b/crates/engine/src/decal_cmds.rs @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "Add decal", [], None, - "{image: resource name, x?, y?: viewport pixels (default: the view center), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z], size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} — a fill layer projecting the image from a frame placed on the surface", + "{image: resource name, x?, y?: viewport pixels (default: the view center), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z], up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round", always, add ), @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Edit decal", [], None, - "{layer?, x?, y?, viewport? | position?, normal? (re-place it), size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?, merge?: true continues the previous Edit decal undo step (drags)}", + "{layer?, x?, y?, viewport? | position?, normal? (re-place it), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?, merge?: true continues the previous Edit decal undo step (drags)}", has_layer, set ), @@ -81,9 +81,16 @@ fn size_param(p: &Value, aspect: f32, diag: f32) -> Option<[f32; 2]> { size.iter().all(|x| x.is_finite()).then(|| size.map(|x| x.clamp(diag * 1e-4, diag * 10.0))) } -/// The camera's up direction (decals are placed upright on screen). -fn screen_up(s: &Session) -> Vec3 { - s.camera.view().inverse().transform_vector3(Vec3::Y) +/// The decal's up direction: `up` when given, else the camera's (decals are placed upright on +/// screen), or where the camera looks when that is along `normal` (a top face seen from the +/// front: its far edge is up, as on a table). +fn decal_up(s: &Session, cmd: &str, p: &Value, normal: Vec3) -> Result { + if p.get("up").is_some() { + return vec3(p, "up").filter(|u| u.cross(normal).length_squared() > 1e-8).ok_or_else(|| bad(cmd, "`up` must be [x, y, z], not along the normal")); + } + let to_world = s.camera.view().inverse(); + let up = to_world.transform_vector3(Vec3::Y); + Ok(if up.normalize_or_zero().cross(normal).length_squared() > 1e-4 { up } else { to_world.transform_vector3(Vec3::NEG_Z) }) } fn add(s: &mut Session, p: &Value) -> Result { @@ -97,7 +104,7 @@ fn add(s: &mut Session, p: &Value) -> Result { let decal = Decal { center: center.to_array(), normal: normal.to_array(), - up: screen_up(s).to_array(), + up: decal_up(s, cmd, p, normal)?.to_array(), size, rotation: f32p(p, "rotation").unwrap_or(0.0).rem_euclid(360.0), offset: [0.0; 2], @@ -132,6 +139,9 @@ fn set(s: &mut Session, p: &Value) -> Result { if let Some((center, normal)) = placement(s, cmd, p, true)? { (d.center, d.normal, d.offset) = (center.to_array(), normal.to_array(), [0.0; 2]); } + if p.get("up").is_some() { + d.up = decal_up(s, cmd, p, Vec3::from(d.normal))?.to_array(); + } if let Some(size) = size_param(p, d.size[0] / d.size[1].max(1e-6), diag) { d.size = size; } diff --git a/crates/engine/tests/painter_gaps.rs b/crates/engine/tests/painter_gaps.rs index 4073f94d..fc82a4e5 100644 --- a/crates/engine/tests/painter_gaps.rs +++ b/crates/engine/tests/painter_gaps.rs @@ -188,6 +188,26 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() { assert!(!red(at(&mut s, Channel::BaseColor, 170.0, 180.0))); } +#[test] +fn a_decal_takes_its_up_from_the_params_or_a_rule_that_never_degenerates() { + let mut s = session(); + let name = s.import_resource_bytes("logo.png", png(8, 4, |x, _| if x < 4 { [255, 0, 0, 255] } else { [0, 0, 255, 255] })).unwrap(); + let top = json!({"image": name, "position": [0.0, 1.0, 0.0], "normal": [0.0, 1.0, 0.0]}); + let up = |r: &Value| [0, 1, 2].map(|i| r["decal"]["up"][i].as_f64().unwrap() as f32); + let mut with_up = top.clone(); + with_up["up"] = json!([0.0, 0.0, -1.0]); + assert_eq!(up(&execute(&mut s, "layer.add.decal", &with_up).unwrap()), [0.0, 0.0, -1.0]); + with_up["up"] = json!([0.0, 2.0, 0.0]); + assert!(execute(&mut s, "layer.add.decal", &with_up).is_err(), "an up along the normal is refused"); + // A level camera's up is the top face's normal: the decal's up is where the camera looks. + execute(&mut s, "camera.set", &json!({"yaw": 90.0, "pitch": 0.0})).unwrap(); + let forward = s.camera.view().inverse().transform_vector3(texturecraft_engine::geom::glam::Vec3::NEG_Z); + let u = up(&execute(&mut s, "layer.add.decal", &top).unwrap()); + assert!((texturecraft_engine::geom::glam::Vec3::from(u) - forward).length() < 1e-4, "{u:?} vs {forward}"); + let r = execute(&mut s, "layer.decal.set", &json!({"up": [1.0, 0.0, 0.0]})).unwrap(); + assert_eq!(up(&r), [1.0, 0.0, 0.0]); +} + #[test] fn clone_copies_the_selected_layer_alone_when_asked() { let mut s = session(); From e3bc63d1cacaf7ebcfba16317fd10ae63721cd4d Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 05:56:33 +0700 Subject: [PATCH 23/60] Projects keep the names of a mesh's unnamed parts on reopen Parts a mesh file leaves unnamed are named after the file. The project stored the mesh as mesh. and read it back under that name, so a reopened quad.gltf named its part "mesh" and geometry masks on "quad" hid their layer. The project now keeps the imported file's name (mesh_file) and reads the stored mesh under it, on open and on a pathless reimport. Older projects read as before. Fixes #76. --- crates/core/src/project.rs | 5 +++ crates/engine/src/file_cmds.rs | 69 +++++++++++++++++++++++++++++++--- 2 files changed, 69 insertions(+), 5 deletions(-) diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index ca2ee2ec..422dc0a9 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -613,6 +613,10 @@ pub struct Project { pub name: String, /// Path of the mesh inside the project file (or a built-in primitive id `builtin:`). pub mesh: String, + /// File name the mesh was imported from (`quad.gltf`). The stored mesh is read again under + /// it, so parts the file leaves unnamed get the same name (from it) as on import. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub mesh_file: String, pub normal_format: NormalFormat, pub texture_sets: Vec, pub layers: BTreeMap, @@ -629,6 +633,7 @@ impl Project { format_version: FORMAT_VERSION, name: name.into(), mesh: mesh.into(), + mesh_file: String::new(), normal_format: NormalFormat::OpenGl, texture_sets: Vec::new(), layers: BTreeMap::new(), diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 32ae6b49..4a1f5513 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -4,7 +4,7 @@ use serde_json::{Value, json}; #[cfg(not(target_arch = "wasm32"))] use texturecraft_core::PROJECT_EXT; -use texturecraft_core::{NormalFormat, TextureSet}; +use texturecraft_core::{NormalFormat, Project, TextureSet}; use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, Padding, ProjectFile}; use texturecraft_geom::{Mesh, primitives}; @@ -79,6 +79,18 @@ fn stem_of(name: &str) -> String { std::path::Path::new(name).file_stem().and_then(|e| e.to_str()).unwrap_or("Untitled").to_string() } +/// The leaf of an imported mesh file's name (kept in [`Project::mesh_file`]). +fn leaf_of(name: &str) -> String { + std::path::Path::new(name).file_name().and_then(|e| e.to_str()).unwrap_or_default().to_string() +} + +/// Read the project's stored mesh `bytes` (extension `ext`) under the name it was imported +/// with, so its unnamed parts keep their names (and the geometry masks that use them). +fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8]) -> Result { + let stem = std::path::Path::new(&project.mesh_file).file_stem().and_then(|s| s.to_str()).filter(|s| !s.is_empty()).unwrap_or("mesh"); + texturecraft_formats::import_mesh_bytes(&format!("{stem}.{ext}"), bytes).map_err(fe) +} + impl Session { /// The working mesh as Wavefront OBJ (with its own UVs, UDIM tiles included). pub fn mesh_obj_bytes(&self) -> Vec { @@ -122,6 +134,7 @@ impl Session { let imported = texturecraft_formats::import_mesh_bytes(file_name, bytes).map_err(fe)?; let ext = ext_of(file_name); let mut s = Session::new_project_tiled(name, imported.mesh, &format!("mesh.{ext}"), Some((ext, bytes.to_vec())), resolution, uv_tiles)?; + s.doc.project.mesh_file = leaf_of(file_name); s.doc.project.cameras = imported.cameras; s.log.extend(imported.report.warnings.iter().cloned()); s.log.push(format!( @@ -143,7 +156,7 @@ impl Session { pub fn from_project_file(pf: ProjectFile) -> Result { let mesh = match (&pf.mesh, pf.project.mesh.strip_prefix("builtin:")) { (_, Some(id)) => primitives::builtin(id).ok_or_else(|| EngineError::Other(format!("unknown built-in mesh `{id}`")))?, - (Some((ext, bytes)), None) => texturecraft_formats::import_mesh_bytes(&format!("mesh.{ext}"), bytes).map_err(fe)?.mesh, + (Some((ext, bytes)), None) => read_stored_mesh(&pf.project, ext, bytes)?.mesh, (None, None) => return Err(EngineError::Other("the project has no mesh".into())), }; check_materials(&pf.project, &mesh)?; @@ -384,14 +397,14 @@ impl Session { /// With `preserve_strokes`, painted pixels follow the surface where the UVs changed. Replies /// like `file.reimportMesh`: `{preserved?}`. pub fn reimport_mesh(&mut self, file: Option, preserve_strokes: bool) -> Result { - let (mesh, source, warnings) = match file { + let (mesh, source, warnings, mesh_file) = match file { Some(f) => { let m = texturecraft_formats::import_mesh_bytes(&f.name, &f.bytes).map_err(fe)?.mesh; - (m, Some((ext_of(&f.name), f.bytes)), f.warnings) + (m, Some((ext_of(&f.name), f.bytes)), f.warnings, leaf_of(&f.name)) } None => match &self.mesh_source { Some((ext, bytes)) => { - (texturecraft_formats::import_mesh_bytes(&format!("mesh.{ext}"), bytes).map_err(fe)?.mesh, self.mesh_source.clone(), Vec::new()) + (read_stored_mesh(&self.doc.project, ext, bytes)?.mesh, self.mesh_source.clone(), Vec::new(), self.doc.project.mesh_file.clone()) } None => return Err(bad("file.reimportMesh", "built-in meshes can't be reimported; give `path`")), }, @@ -400,6 +413,7 @@ impl Session { let mut doc = self.doc.clone(); if let Some((ext, _)) = &source { doc.project.mesh = format!("mesh.{ext}"); + doc.project.mesh_file = mesh_file; } let mut next = Session::new(doc, mesh, source)?; next.log.extend(warnings); @@ -555,4 +569,49 @@ mod tests { } let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn unnamed_parts_keep_their_names_and_masks_through_save_and_reopen() { + // A GLB quad whose mesh and node have no name: its one part is named after the file. + let mut bin: Vec = [-1.0f32, -1.0, 0.0, 1.0, -1.0, 0.0, 1.0, 1.0, 0.0, -1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0] + .iter() + .flat_map(|f| f.to_le_bytes()) + .chain([0u16, 1, 2, 0, 2, 3].iter().flat_map(|i| i.to_le_bytes())) + .collect(); + bin.resize(92, 0); + let mut gltf = json!({ + "asset": {"version": "2.0"}, "buffers": [{"byteLength": 92}], + "bufferViews": [{"buffer": 0, "byteOffset": 0, "byteLength": 48}, {"buffer": 0, "byteOffset": 48, "byteLength": 32}, {"buffer": 0, "byteOffset": 80, "byteLength": 12}], + "accessors": [{"bufferView": 0, "componentType": 5126, "count": 4, "type": "VEC3", "min": [-1, -1, 0], "max": [1, 1, 0]}, + {"bufferView": 1, "componentType": 5126, "count": 4, "type": "VEC2"}, {"bufferView": 2, "componentType": 5123, "count": 6, "type": "SCALAR"}], + "meshes": [{"primitives": [{"attributes": {"POSITION": 0, "TEXCOORD_0": 1}, "indices": 2}]}], + "nodes": [{"mesh": 0}], "scenes": [{"nodes": [0]}], "scene": 0 + }) + .to_string() + .into_bytes(); + gltf.resize(gltf.len().div_ceil(4) * 4, b' '); + let mut glb = b"glTF".to_vec(); + glb.extend(2u32.to_le_bytes()); + glb.extend(((12 + 8 + gltf.len() + 8 + bin.len()) as u32).to_le_bytes()); + glb.extend((gltf.len() as u32).to_le_bytes()); + glb.extend(b"JSON"); + glb.extend(gltf); + glb.extend((bin.len() as u32).to_le_bytes()); + glb.extend(b"BIN\0"); + glb.extend(bin); + let mut s = Session::from_mesh_bytes("dir/quad.glb", &glb, 128, "quad").unwrap(); + let parts = |s: &mut Session| crate::execute(s, "textureSet.parts", &Value::Null).unwrap(); + assert_eq!(parts(&mut s), json!(["quad"])); + crate::execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + crate::execute(&mut s, "layer.set", &json!({"geometryMask": ["quad"]})).unwrap(); + let mut back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(parts(&mut back), json!(["quad"]), "the reopened mesh names its part as the import did"); + crate::execute(&mut back, "file.reimportMesh", &Value::Null).unwrap(); + assert_eq!(parts(&mut back), json!(["quad"]), "and so does a reimport of the stored mesh"); + // Projects saved before the file name was kept read the mesh as before. + let mut old = back.project_file(); + old.project.mesh_file.clear(); + let mut old = Session::from_project_bytes(&texturecraft_formats::save_project_bytes(&old).unwrap()).unwrap(); + assert_eq!(parts(&mut old), json!(["mesh"])); + } } From 056a089551e3fc2d5cb147cd2e08363340b050d5 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 06:11:11 +0700 Subject: [PATCH 24/60] Viewport: show the baked normal map The viewport's normal texture held only the painted Normal channel, so a baked normal map changed the export but not the view. Display tiles now re-orient the painted normal onto the baked one, as export does (core::blend::rnm, now public). Fixes #54. --- crates/compose/src/display.rs | 33 ++++++++++++++++++++++++++++++--- crates/core/src/blend.rs | 5 +++-- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs index f82af292..96294c4a 100644 --- a/crates/compose/src/display.rs +++ b/crates/compose/src/display.rs @@ -169,13 +169,23 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 let (n, sheen_rough) = (get(Channel::Normal), scalar8(Channel::SheenRoughness)); for i in 0..TILE_AREA { let px = &mut out[i * 4..i * 4 + 4]; - match n { - Some(t) => { + // The baked normal is the base the painted normal details sit on (as in export). + let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); + let base = baked.sample(BakedMap::Normal, x, y, res); + match (n, base) { + (Some(t), None) => { for (k, d) in px.iter_mut().take(3).enumerate() { *d = u8_of(t.get(i * 3 + k).copied().unwrap_or(0)); } } - None => px[..3].copy_from_slice(&[128, 128, 255]), + (detail, Some(base)) => { + let detail = detail.map_or([0.5, 0.5, 1.0], |t| [0, 1, 2].map(|k| t.get(i * 3 + k).map_or(0.0, |v| *v as f32 / 65535.0))); + let v = texturecraft_core::blend::rnm(base, detail); + for (d, v) in px.iter_mut().zip(v) { + *d = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + } + } + (None, None) => px[..3].copy_from_slice(&[128, 128, 255]), } px[3] = sheen_rough(i); } @@ -231,6 +241,23 @@ mod tests { assert_eq!(half::f16::from_le_bytes([h[2], h[3]]).to_f32(), half::f16::from_f32(0.04).to_f32(), "default F0"); } + #[test] + fn the_baked_normal_is_the_base_of_the_shown_normal() { + // A baked normal tilted to +X (packed), 64² like the set. + let tilted = [0.8f32, 0.5, 0.9]; + let baked = BakedMaps { resolution: 64, maps: [(BakedMap::Normal, std::sync::Arc::new(tilted.repeat(64 * 64)))].into_iter().collect() }; + let shown = |comp: &Composite| tile_bytes(comp, &baked, DisplayKind::Normal, 0, 0)[..3].to_vec(); + let pack = |v: [f32; 3]| v.map(|x| (x * 255.0 + 0.5) as u8).to_vec(); + // No normal channel: the baked normal as it is. + assert_eq!(shown(&Composite::new(&[], 64)), pack(tilted)); + // A flat painted normal leaves it; a painted detail is re-oriented onto it. + let mut comp = Composite::new(&[Channel::Normal], 64); + comp.channels.get_mut(&Channel::Normal).unwrap().set(0, 0, &[to_u16(0.5), to_u16(0.5), to_u16(1.0)]); + assert!(shown(&comp).iter().zip(pack(tilted)).all(|(a, b)| (*a as i32 - b as i32).abs() <= 1), "{:?}", shown(&comp)); + comp.channels.get_mut(&Channel::Normal).unwrap().set(0, 0, &[to_u16(0.5), to_u16(0.8), to_u16(0.9)]); + assert_eq!(shown(&comp), pack(texturecraft_core::blend::rnm(tilted, [0.5, 0.8, 0.9]))); + } + #[test] fn glossiness_shows_as_roughness_and_specular_rides_in_height() { let mut comp = Composite::new(&[Channel::Glossiness, Channel::Specular], 64); diff --git a/crates/core/src/blend.rs b/crates/core/src/blend.rs index e43fd4b8..5f165cdb 100644 --- a/crates/core/src/blend.rs +++ b/crates/core/src/blend.rs @@ -313,8 +313,9 @@ fn pack(n: [f32; 3]) -> [f32; 3] { n.map(|v| v / len * 0.5 + 0.5) } -/// Reoriented normal mapping (Barré-Brisebois & Hill): `detail` re-oriented onto `base`. -fn rnm(base: [f32; 3], detail: [f32; 3]) -> [f32; 3] { +/// Reoriented normal mapping (Barré-Brisebois & Hill): `detail` re-oriented onto `base` (both +/// packed into 0..1, as is the result). +pub fn rnm(base: [f32; 3], detail: [f32; 3]) -> [f32; 3] { let t = unpack(base); let t = [t[0], t[1], t[2] + 1.0]; let u = unpack(detail); From d3bc91700f2bd63ef0d3c0ed5b5ecd5f38818aef Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 06:17:58 +0700 Subject: [PATCH 25/60] Effect sliders apply what they were dragged or clicked to The sliders of a selected effect (opacity, generator, levels, HSL, filters, fill patterns) re-read their value from the document each frame and applied it when the drag stopped, but on that frame the pointer no longer drags, so the old value was applied again; a click on the track was never applied. slider_edit remembers the dragged value for the release frame and reports clicks and typed values too. Fixes #46. --- crates/ui-egui/src/dock.rs | 40 ++++++++--------- crates/ui-egui/src/widgets.rs | 25 ++++++++++- crates/ui-egui/src/windows.rs | 4 +- crates/ui-egui/tests/effect_sliders.rs | 62 ++++++++++++++++++++++++++ 4 files changed, 107 insertions(+), 24 deletions(-) create mode 100644 crates/ui-egui/tests/effect_sliders.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 41332911..63125d4b 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -16,7 +16,7 @@ use crate::i18n::{n_, tr, trf}; use crate::shelf::{Asset, ShelfDrag}; use crate::state::PropsTab; use crate::theme::{Tokens, caption}; -use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, section, slider}; +use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, section, slider, slider_edit}; const TAG_COLORS: [Color32; 8] = [ Color32::from_rgb(0xc0, 0x40, 0x40), @@ -852,10 +852,10 @@ fn height_mask_section(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { } ui.add_enabled_ui(hm.enabled, |ui| { let (mut contrast, mut offset) = (hm.contrast, hm.offset); - if slider(ui, tr("Contrast"), &mut contrast, 0.0..=16.0, 2).drag_stopped() { + if slider_edit(ui, tr("Contrast"), &mut contrast, 0.0..=16.0, 2) { app.run("layer.set", json!({"layer": id, "heightMask": {"contrast": contrast}})); } - if slider(ui, tr("Height offset"), &mut offset, -1.0..=1.0, 2).drag_stopped() { + if slider_edit(ui, tr("Height offset"), &mut offset, -1.0..=1.0, 2) { app.run("layer.set", json!({"layer": id, "heightMask": {"offset": offset}})); } }); @@ -1368,7 +1368,7 @@ fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: Projection::Cylindrical { scale, .. } => (*scale, "cylindrical"), Projection::Decal(_) => return, }; - if slider(ui, tr("Scale / tiling"), &mut scale, 0.01..=20.0, 2).drag_stopped() { + if slider_edit(ui, tr("Scale / tiling"), &mut scale, 0.01..=20.0, 2) { app.run("layer.fill.projection", with(base, json!({"projection": proj_id, "scale": scale}))); } } @@ -1395,7 +1395,7 @@ fn decal_editor(app: &mut TextureCraftApp, ui: &mut Ui, d: &Decal, layer: LayerI ]; let mut done = false; for ((label, range), x) in rows.into_iter().zip(v.iter_mut()) { - done |= slider(ui, label, x, range, 3).drag_stopped(); + done |= slider_edit(ui, label, x, range, 3); } if done { app.run("layer.decal.set", json!({"layer": layer.0, "size": [v[0], v[1]], "rotation": v[2], "offset": [v[3], v[4]], "depth": v[5]})); @@ -1472,11 +1472,11 @@ fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Valu ); let mut s = pattern.scale; let mut con = pattern.contrast; - let r1 = slider(ui, tr("Pattern scale"), &mut s, 0.1..=100.0, 1); - let r2 = slider(ui, tr("Contrast"), &mut con, 0.0..=8.0, 2); + let r1 = slider_edit(ui, tr("Pattern scale"), &mut s, 0.1..=100.0, 1); + let r2 = slider_edit(ui, tr("Contrast"), &mut con, 0.0..=8.0, 2); let mut seed = pattern.seed as f32; - let r3 = slider(ui, tr("Seed"), &mut seed, 0.0..=999.0, 0); - if r1.drag_stopped() || r2.drag_stopped() || r3.drag_stopped() { + let r3 = slider_edit(ui, tr("Seed"), &mut seed, 0.0..=999.0, 0); + if r1 || r2 || r3 { app.run( "layer.fill.set", set(json!({"procedural": pattern.kind.label(), "scale": s, "contrast": con, "seed": seed as u64, "low": low, "high": high})), @@ -1525,7 +1525,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: }); }); let mut op = e.opacity; - if slider(ui, tr("Opacity"), &mut op, 0.0..=1.0, 2).drag_stopped() { + if slider_edit(ui, tr("Opacity"), &mut op, 0.0..=1.0, 2) { app.run("effect.set", json!({"effect": id, "opacity": op})); } ui.separator(); @@ -1542,13 +1542,13 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: } }); let (mut level, mut soft, mut noise, mut ns) = (g.level, g.softness, g.noise_amount, g.noise_scale); - let r1 = slider(ui, tr("Level"), &mut level, 0.0..=1.0, 2); - let r2 = slider(ui, tr("Softness"), &mut soft, 0.0..=1.0, 2); - let r3 = slider(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); - let r4 = slider(ui, tr("Noise scale"), &mut ns, 0.1..=64.0, 1); + let r1 = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); + let r2 = slider_edit(ui, tr("Softness"), &mut soft, 0.0..=1.0, 2); + let r3 = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); + let r4 = slider_edit(ui, tr("Noise scale"), &mut ns, 0.1..=64.0, 1); let mut inv = g.invert; let r5 = ui.checkbox(&mut inv, tr("Invert")); - if r1.drag_stopped() || r2.drag_stopped() || r3.drag_stopped() || r4.drag_stopped() || r5.changed() { + if r1 || r2 || r3 || r4 || r5.changed() { app.run("effect.set", json!({"effect": id, "level": level, "softness": soft, "noise": noise, "noiseScale": ns, "invert": inv})); } if !app.session.doc.baked.contains_key(&app.session.ts()) { @@ -1564,7 +1564,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: let mut done = false; for (i, label) in labels.iter().enumerate() { let range = if i == 2 { 0.1..=5.0 } else { 0.0..=1.0 }; - done |= slider(ui, label, &mut v[i], range, 2).drag_stopped(); + done |= slider_edit(ui, label, &mut v[i], range, 2); } if done { app.run("effect.set", json!({"effect": id, "inLow": v[0], "inHigh": v[1], "gamma": v[2], "outLow": v[3], "outHigh": v[4]})); @@ -1592,7 +1592,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: match source { Source::Uniform(v) => { let mut x = v[0]; - if slider(ui, tr("Value"), &mut x, 0.0..=1.0, 2).drag_stopped() { + if slider_edit(ui, tr("Value"), &mut x, 0.0..=1.0, 2) { app.run("effect.set", json!({"effect": id, "value": x})); } } @@ -1652,7 +1652,7 @@ fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter ui.label(caption(tr(f.label()))); if let Filter::Hsl { hue, .. } = f { let mut h = hue * 360.0; - if slider(ui, tr("Hue shift (degrees)"), &mut h, -180.0..=180.0, 0).drag_stopped() { + if slider_edit(ui, tr("Hue shift (degrees)"), &mut h, -180.0..=180.0, 0) { set(app, "hue", json!(h / 360.0)); } } @@ -1664,7 +1664,7 @@ fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter } else { 2 }; - if slider(ui, tr(label), &mut v, lo..=hi, decimals).drag_stopped() { + if slider_edit(ui, tr(label), &mut v, lo..=hi, decimals) { set(app, key, json!(v)); } } @@ -1676,7 +1676,7 @@ fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter let mut v = *rgb; let mut done = false; for (x, name) in v.iter_mut().zip([tr("Cyan / red"), tr("Magenta / green"), tr("Yellow / blue")]) { - done |= slider(ui, name, x, -1.0..=1.0, 2).drag_stopped(); + done |= slider_edit(ui, name, x, -1.0..=1.0, 2); } if done { set(app, key, json!(v)); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 35598b99..ae9f5981 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -14,11 +14,23 @@ pub fn dnd_release(resp: &Response) -> Option, decimals: usize) -> Response { + slider_inner(ui, label, value, range, decimals).0 +} + +/// [`slider`] for a value re-read from the document every frame: true on the frame an edit is +/// done (a drag released, a click on the track, a typed value), with `value` holding the result. +pub fn slider_edit(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> bool { + slider_inner(ui, label, value, range, decimals).1 +} + +fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (Response, bool) { let tk = Tokens::get(ui.ctx()); let (lo, hi) = (*range.start(), *range.end()); let w = ui.available_width(); + let mut done = false; ui.horizontal(|ui| { ui.label(RichText::new(label).color(tk.text)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -29,6 +41,7 @@ pub fn slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeI && v.is_finite() { *value = v.clamp(lo, hi); + done = true; } }); }); @@ -38,14 +51,22 @@ pub fn slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeI { let t = ((p.x - rect.left() - 5.0) / (rect.width() - 10.0).max(1.0)).clamp(0.0, 1.0); let v = lo + (hi - lo) * t; + // Remembered for the release frame, where the pointer no longer drags. + ui.data_mut(|d| d.insert_temp(resp.id, v)); if (v - *value).abs() > f32::EPSILON { *value = v; resp.mark_changed(); } } + if resp.drag_stopped() || resp.clicked() { + if let Some(v) = ui.data_mut(|d| d.remove_temp::(resp.id)) { + *value = v; + } + done = true; + } let t = if hi > lo { ((*value - lo) / (hi - lo)).clamp(0.0, 1.0) } else { 0.0 }; track(ui, &resp, rect.left() + 5.0..=rect.right() - 5.0, rect.center().y, t, 2.0, 4.5); - resp + (resp, done) } /// A small inline slider for the top tool bar: "Label value" above a short track. diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index eab0046e..417c8057 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -15,7 +15,7 @@ use crate::i18n::LANGUAGES; use crate::i18n::{tr, trf}; use crate::state::Mode; use crate::theme::{Accent, Brightness, Tokens, caption}; -use crate::widgets::{color_swatch, combo, icon_button, primary_button, slider}; +use crate::widgets::{color_swatch, combo, icon_button, primary_button, slider, slider_edit}; pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { start(app, ctx); @@ -204,7 +204,7 @@ pub(crate) fn shader(app: &mut TextureCraftApp, ui: &mut Ui) { let ts = app.session.ts(); if let Some(set) = app.session.doc.project.texture_sets.get(ts) { let mut hs = set.height_strength; - if slider(ui, tr("Height to normal strength"), &mut hs, 0.0..=10.0, 2).drag_stopped() { + if slider_edit(ui, tr("Height to normal strength"), &mut hs, 0.0..=10.0, 2) { app.run("textureSet.settings", json!({"ts": ts, "heightStrength": hs})); } } diff --git a/crates/ui-egui/tests/effect_sliders.rs b/crates/ui-egui/tests/effect_sliders.rs new file mode 100644 index 00000000..a4bb3915 --- /dev/null +++ b/crates/ui-egui/tests/effect_sliders.rs @@ -0,0 +1,62 @@ +//! The sliders of a selected effect (opacity, generator, levels…) apply what they were dragged +//! or clicked to. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{EffectKind, LayerId}; +use texturecraft_ui_egui::TextureCraftApp; + +/// The sample session with its first generator effect selected, and that effect's id. +fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let (layer, effect) = session + .doc + .project + .layers + .values() + .find_map(|l| { + let mask = l.mask.iter().flat_map(|m| m.effects.iter()); + l.content_effects.iter().chain(mask).find(|e| matches!(e.kind, EffectKind::Generator(_))).map(|e| (l.id, e.id)) + }) + .unwrap(); + texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + (h, effect) +} + +fn opacity(h: &Harness<'_, TextureCraftApp>, effect: LayerId) -> f32 { + h.state().session.doc.project.effect(effect).unwrap().1.opacity +} + +/// The track under the slider labelled `label` (the row below the label). +fn track(h: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Rect { + let l = h.get_by_label(label).rect(); + egui::Rect::from_min_max(egui::pos2(l.left() + 6.0, l.bottom() + 6.0), egui::pos2(l.left() + 200.0, l.bottom() + 14.0)) +} + +#[test] +fn dragging_the_effect_opacity_applies_it() { + let (mut h, effect) = harness(); + assert_eq!(opacity(&h, effect), 1.0); + let t = track(&h, "Opacity"); + h.drag_at(egui::pos2(t.right(), t.center().y)); + h.run_steps(2); + h.hover_at(egui::pos2(t.left() + 20.0, t.center().y)); + h.run_steps(2); + h.drop_at(egui::pos2(t.left() + 20.0, t.center().y)); + h.run_steps(3); + assert!(opacity(&h, effect) < 0.5, "the dragged opacity applies: {}", opacity(&h, effect)); +} + +#[test] +fn clicking_the_effect_opacity_applies_it() { + let (mut h, effect) = harness(); + let t = track(&h, "Opacity"); + let at = egui::pos2(t.left() + 20.0, t.center().y); + h.drag_at(at); + h.drop_at(at); + h.run_steps(3); + assert!(opacity(&h, effect) < 0.5, "a click on the track applies: {}", opacity(&h, effect)); +} From 7e78a2cba6b8a18a133780493ac33837d6b19816 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 06:02:22 +0700 Subject: [PATCH 26/60] Material channels: Alt+click keeps one channel Alt+click on a channel of a fill's or the brush's Material section turns that channel on and every other one off (one undo step for a fill). tool.material and layer.fill.set take solo: true for the same. Fixes #74. --- crates/engine/src/layer_cmds.rs | 14 +++++++++++--- crates/engine/src/tool_cmds.rs | 13 ++++++++++++- crates/engine/tests/painter_gaps.rs | 13 +++++++++++++ crates/ui-egui/src/dock.rs | 13 +++++++++---- crates/ui-egui/src/i18n.rs | 1 + crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + docs/features.md | 1 + 15 files changed, 56 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index e7831f12..e7575baf 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Set fill source", [], None, - "{layer? | effect?: content fill effect id, channel, color?|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?|image?|anchor?: anchor effect id, anchorChannel?, enabled?}", + "{layer? | effect?: content fill effect id, channel, color?|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?|image?|anchor?: anchor effect id, anchorChannel?, enabled?, solo?: true (this channel on, every other one off)}", has_layer, fill_set ), @@ -303,7 +303,9 @@ fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> { fn fill_set(s: &mut Session, p: &Value) -> Result { let target = fill_target(s, p, "layer.fill.set")?; let ch = channel_param("layer.fill.set", p, "channel")?.ok_or_else(|| bad("layer.fill.set", "`channel` is required"))?; - let enabled = boolp(p, "enabled"); + // `solo`: this channel on, every other one off. + let solo = boolp(p, "solo") == Some(true); + let enabled = if solo { Some(true) } else { boolp(p, "enabled") }; let source = if let Some(kind) = strp(p, "procedural") { let kind = ProceduralKind::parse(kind).ok_or_else(|| bad("layer.fill.set", format!("unknown procedural `{kind}`")))?; let mut pr = Procedural::new(kind); @@ -336,7 +338,7 @@ fn fill_set(s: &mut Session, p: &Value) -> Result { } else if enabled.is_some() { None } else { - return Err(bad("layer.fill.set", "give `color`, `value`, `procedural`, `image`, `anchor` or `enabled`")); + return Err(bad("layer.fill.set", "give `color`, `value`, `procedural`, `image`, `anchor`, `enabled` or `solo`")); }; s.edit("Set fill", |s| { let f = fill_mut(s, target)?; @@ -348,6 +350,9 @@ fn fill_set(s: &mut Session, p: &Value) -> Result { FillTarget::Effect(_) => { let src = source.unwrap_or_else(|| f.source(ch)); f.sources.insert(ch, src); + if solo { + f.sources.retain(|c, _| *c == ch); + } } FillTarget::Layer(id) => { if let Some(src) = source { @@ -359,6 +364,9 @@ fn fill_set(s: &mut Session, p: &Value) -> Result { } else { l.channels.entry(ch).or_default(); } + if solo { + l.channels.retain(|c, _| *c == ch); + } } } Ok(()) diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 465726f2..7fa5fdab 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -42,7 +42,15 @@ pub fn specs() -> Vec { "procedural": BrushAlpha::ALL.map(BrushAlpha::label), "library": alphas::library().iter().map(|a| json!({"id": a.id, "label": a.label, "category": a.category})).collect::>(), }))), - cmd!("tool.material", "Tool material", [], None, "{channel, color?|value?, enabled?} or {maskValue?: 0..1}", always, material), + cmd!( + "tool.material", + "Tool material", + [], + None, + "{channel, color?|value?, enabled?, solo?: true (paint this channel only)} or {maskValue?: 0..1}", + always, + material + ), cmd!( "tool.stencil", "Projection stencil", @@ -232,6 +240,9 @@ fn material(s: &mut Session, p: &Value) -> Result { } None => {} } + if boolp(p, "solo") == Some(true) { + s.tool.enabled = std::iter::once(c).collect(); + } } s.revision = s.revision.wrapping_add(1); Ok(json!({ diff --git a/crates/engine/tests/painter_gaps.rs b/crates/engine/tests/painter_gaps.rs index fc82a4e5..48f0b3de 100644 --- a/crates/engine/tests/painter_gaps.rs +++ b/crates/engine/tests/painter_gaps.rs @@ -152,6 +152,19 @@ fn geometry_masks_limit_layers_to_mesh_parts() { assert!(texel(&mut s, 0.1, 0.9) && texel(&mut s, 0.6, 0.4)); } +#[test] +fn solo_keeps_one_material_channel() { + let mut s = session(); + let r = execute(&mut s, "tool.material", &json!({"channel": "roughness", "solo": true})).unwrap(); + assert_eq!(r["enabled"], json!(["roughness"]), "the brush paints roughness only"); + let fill = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer"); + assert!(s.doc.project.layer(fill).unwrap().channels.len() > 1); + execute(&mut s, "layer.fill.set", &json!({"channel": "metallic", "solo": true})).unwrap(); + assert_eq!(s.doc.project.layer(fill).unwrap().channels.keys().copied().collect::>(), [Channel::Metallic]); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.layer(fill).unwrap().channels.len() > 1, "one undo step"); +} + #[test] fn decals_project_an_image_from_a_frame_placed_on_the_surface() { let mut s = session(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 41332911..cc54ae8c 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1222,6 +1222,9 @@ fn text_section(app: &mut TextureCraftApp, ui: &mut Ui) { }); } +/// Tooltip of the material channel chips. +pub(crate) const SOLO_HINT: &str = "Click: turn this channel on or off. Alt+click: this channel only"; + fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); ui.label(caption(tr("Material"))); @@ -1229,8 +1232,9 @@ fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) { ui.horizontal_wrapped(|ui| { for c in &chans { let on = app.session.tool.enabled.contains(c); - if chip(ui, tr(c.short()), on).clicked() { - app.run("tool.material", json!({"channel": c.id(), "enabled": !on})); + if chip(ui, tr(c.short()), on).on_hover_text(tr(SOLO_HINT)).clicked() { + let solo = ui.input(|i| i.modifiers.alt); + app.run("tool.material", json!({"channel": c.id(), "enabled": solo || !on, "solo": solo})); } } }); @@ -1328,8 +1332,9 @@ fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value ui.horizontal_wrapped(|ui| { for c in &chans { let enabled = on.contains(c); - if chip(ui, tr(c.short()), enabled).clicked() { - app.run("layer.fill.set", with(base, json!({"channel": c.id(), "enabled": !enabled}))); + if chip(ui, tr(c.short()), enabled).on_hover_text(tr(SOLO_HINT)).clicked() { + let solo = ui.input(|i| i.modifiers.alt); + app.run("layer.fill.set", with(base, json!({"channel": c.id(), "enabled": solo || !enabled, "solo": solo}))); } } }); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index f89b7644..04c7a3d9 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -184,6 +184,7 @@ mod tests { "Anchor point", "Layer mask", texturecraft_engine::camera_cmds::DEFAULT_CAMERA, + crate::dock::SOLO_HINT, ]); k.retain(|s| !s.is_empty() && !UNTRANSLATED.contains(s)); k diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 976d68cb..2c289b30 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -938,4 +938,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "النمط"), ("Use as brush alpha", "استخدام كألفا للفرشاة"), ("Place as decal", "وضع كملصق"), + ("Click: turn this channel on or off. Alt+click: this channel only", "انقر: تشغيل هذه القناة أو إيقافها. Alt+نقر: هذه القناة فقط"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 383fd770..cad4fbe9 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -993,4 +993,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "Schnitt"), ("Use as brush alpha", "Als Pinsel-Alpha verwenden"), ("Place as decal", "Als Decal platzieren"), + ("Click: turn this channel on or off. Alt+click: this channel only", "Klick: diesen Kanal ein- oder ausschalten. Alt+Klick: nur diesen Kanal"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index d2bbe0f8..f337d2ca 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -978,4 +978,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "Estilo"), ("Use as brush alpha", "Usar como alfa del pincel"), ("Place as decal", "Colocar como calcomanía"), + ("Click: turn this channel on or off. Alt+click: this channel only", "Clic: activa o desactiva este canal. Alt+clic: solo este canal"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 07cf9981..d6db4b27 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -993,4 +993,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "Style"), ("Use as brush alpha", "Utiliser comme alpha du pinceau"), ("Place as decal", "Placer en décalque"), + ("Click: turn this channel on or off. Alt+click: this channel only", "Clic : active ou désactive ce canal. Alt+clic : ce canal uniquement"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index d4818eca..622b40a4 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -987,4 +987,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "Stile"), ("Use as brush alpha", "Usa come alpha del pennello"), ("Place as decal", "Posiziona come decal"), + ("Click: turn this channel on or off. Alt+click: this channel only", "Clic: attiva o disattiva questo canale. Alt+clic: solo questo canale"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 62c1c15d..91e5eabd 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -960,4 +960,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "スタイル"), ("Use as brush alpha", "ブラシのアルファとして使用"), ("Place as decal", "デカールとして配置"), + ("Click: turn this channel on or off. Alt+click: this channel only", "クリック: このチャンネルのオン/オフ。Alt+クリック: このチャンネルのみ"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index ec37113c..26e0c66b 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -945,4 +945,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "스타일"), ("Use as brush alpha", "브러시 알파로 사용"), ("Place as decal", "데칼로 배치"), + ("Click: turn this channel on or off. Alt+click: this channel only", "클릭: 이 채널 켜기/끄기. Alt+클릭: 이 채널만"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 5db5da19..001e4f49 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -975,4 +975,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "Estilo"), ("Use as brush alpha", "Usar como alpha do pincel"), ("Place as decal", "Colocar como decalque"), + ("Click: turn this channel on or off. Alt+click: this channel only", "Clique: liga ou desliga este canal. Alt+clique: só este canal"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 895dfc20..d6e09df7 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -891,4 +891,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "样式"), ("Use as brush alpha", "用作笔刷 Alpha"), ("Place as decal", "作为贴花放置"), + ("Click: turn this channel on or off. Alt+click: this channel only", "单击:打开或关闭此通道。Alt+单击:仅此通道"), ]; diff --git a/docs/features.md b/docs/features.md index 0b3ab198..a55b2590 100644 --- a/docs/features.md +++ b/docs/features.md @@ -45,6 +45,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Fill layers** take uniform values, **22 procedurals** (clouds, cells, grunge, scratches, wood grain, bricks, fabric weave, leather grain, marble veins, Voronoi, paint chips…) or your own **images**, through UV, tri-planar, planar, spherical, cylindrical or decal projection. + Alt+click a material channel (of a fill or the brush) to keep that channel alone. - **54 materials** (metals from measured reflectance, car paint, brushed anisotropic steel, velvet, skin, wax, glass, woods, stone, plastics, fabric, leather, ceramic, rust, cork, paper), **21 smart materials** (rusted iron, worn paint, oxidized copper, bronze statue, weathered wood, mossy From 69df38ffea7b0533c424921d06b4541d99ac78da Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 06:10:58 +0700 Subject: [PATCH 27/60] Texture Set List: show all, hide all, invert, and focus on one set An eye menu above the list shows, hides or inverts every texture set; the focus button shows only the active one, and shows them all again when pressed a second time. textureSet.visibility {mode} does the same for agents. Fixes #72. --- crates/engine/src/set_cmds.rs | 47 ++++++++++++++++++++++++++++++ crates/ui-egui/src/dock.rs | 17 +++++++++++ crates/ui-egui/src/i18n/ar.rs | 5 ++++ crates/ui-egui/src/i18n/de.rs | 5 ++++ crates/ui-egui/src/i18n/es.rs | 5 ++++ crates/ui-egui/src/i18n/fr.rs | 5 ++++ crates/ui-egui/src/i18n/it.rs | 5 ++++ crates/ui-egui/src/i18n/ja.rs | 5 ++++ crates/ui-egui/src/i18n/ko.rs | 5 ++++ crates/ui-egui/src/i18n/pt_br.rs | 5 ++++ crates/ui-egui/src/i18n/zh_hans.rs | 5 ++++ 11 files changed, 109 insertions(+) diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index d311b65d..c793f443 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -28,6 +28,15 @@ pub fn specs() -> Vec { cmd!("textureSet.channel.add", "Add channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, true)), cmd!("textureSet.channel.remove", "Remove channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, false)), cmd!("textureSet.visible", "Toggle texture set visibility", [], None, "{ts?, visible?}", always, visible), + cmd!( + "textureSet.visibility", + "Show or hide texture sets", + [], + None, + "{mode: showAll|hideAll|invert|solo, ts?} → {visible: [bool per set]}; solo shows only `ts` (the active set), or every set again when it already was the only one", + always, + visibility + ), cmd!("textureSet.rename", "Rename texture set", [], None, "{ts?, name}", always, rename), cmd!("textureSet.settings", "Texture set settings", [], None, "{ts?, description?, heightStrength?, normalFormat?: openGl|directX}", always, settings), cmd!( @@ -214,6 +223,25 @@ fn visible(s: &mut Session, p: &Value) -> Result { Ok(json!({ "visible": v })) } +fn visibility(s: &mut Session, p: &Value) -> Result { + let cmd = "textureSet.visibility"; + let ts = ts_param(s, p, cmd)?; + let mode = strp(p, "mode").filter(|m| ["showAll", "hideAll", "invert", "solo"].contains(m)); + let mode = mode.ok_or_else(|| bad(cmd, "`mode` must be showAll, hideAll, invert or solo"))?; + let sets = &mut s.doc.project.texture_sets; + let solo = sets.iter().enumerate().all(|(i, t)| t.visible == (i == ts)); + for (i, t) in sets.iter_mut().enumerate() { + t.visible = match mode { + "showAll" => true, + "hideAll" => false, + "invert" => !t.visible, + _ => solo || i == ts, + }; + } + s.revision = s.revision.wrapping_add(1); + Ok(json!({ "visible": s.doc.project.texture_sets.iter().map(|t| t.visible).collect::>() })) +} + fn rename(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, "textureSet.rename")?; let name = strp(p, "name") @@ -251,3 +279,22 @@ fn settings(s: &mut Session, p: &Value) -> Result { })?; Ok(Value::Null) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn visibility_shows_hides_inverts_and_solos() { + // The material ball has two texture sets. + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let mut run = |p: Value| crate::execute(&mut s, "textureSet.visibility", &p).map(|r| r["visible"].clone()); + assert_eq!(run(json!({"mode": "hideAll"})).unwrap(), json!([false, false])); + assert_eq!(run(json!({"mode": "solo", "ts": 1})).unwrap(), json!([false, true])); + assert_eq!(run(json!({"mode": "solo", "ts": 1})).unwrap(), json!([true, true]), "solo again shows every set"); + assert_eq!(run(json!({"mode": "solo", "ts": 0})).unwrap(), json!([true, false])); + assert_eq!(run(json!({"mode": "invert"})).unwrap(), json!([false, true])); + assert_eq!(run(json!({"mode": "showAll"})).unwrap(), json!([true, true])); + assert!(run(json!({"mode": "sideways"})).is_err() && run(json!({"mode": "solo", "ts": 9})).is_err()); + } +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 05811849..dd9191bb 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -47,6 +47,23 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) { }) .collect(); let active = app.session.ts(); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + ui.menu_button(RichText::new(ic::EYE).size(14.0), |ui| { + for (label, mode) in [(tr("Show all"), "showAll"), (tr("Hide all"), "hideAll"), (tr("Invert show/hide"), "invert")] { + if ui.button(label).clicked() { + app.run("textureSet.visibility", json!({ "mode": mode })); + ui.close(); + } + } + }) + .response + .on_hover_text(tr("Show or hide texture sets")); + let solo = sets.iter().enumerate().all(|(i, s)| s.2 == (i == active)); + if icon_button(ui, ic::FRAME_CORNERS, tr("Focus: show only the active texture set"), solo && sets.len() > 1, 22.0).clicked() { + app.run("textureSet.visibility", json!({ "mode": "solo" })); + } + }); egui::ScrollArea::vertical().id_salt("ts_scroll").show(ui, |ui| { for (i, (name, size, visible)) in sets.into_iter().enumerate() { let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 2c289b30..5fb79fb2 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -939,4 +939,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Use as brush alpha", "استخدام كألفا للفرشاة"), ("Place as decal", "وضع كملصق"), ("Click: turn this channel on or off. Alt+click: this channel only", "انقر: تشغيل هذه القناة أو إيقافها. Alt+نقر: هذه القناة فقط"), + ("Show all", "إظهار الكل"), + ("Hide all", "إخفاء الكل"), + ("Invert show/hide", "عكس الإظهار/الإخفاء"), + ("Show or hide texture sets", "إظهار مجموعات الخامات أو إخفاؤها"), + ("Focus: show only the active texture set", "تركيز: إظهار مجموعة الخامات النشطة فقط"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index cad4fbe9..e2d9ed89 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -994,4 +994,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Use as brush alpha", "Als Pinsel-Alpha verwenden"), ("Place as decal", "Als Decal platzieren"), ("Click: turn this channel on or off. Alt+click: this channel only", "Klick: diesen Kanal ein- oder ausschalten. Alt+Klick: nur diesen Kanal"), + ("Show all", "Alle einblenden"), + ("Hide all", "Alle ausblenden"), + ("Invert show/hide", "Ein-/Ausblenden umkehren"), + ("Show or hide texture sets", "Texturesets ein- oder ausblenden"), + ("Focus: show only the active texture set", "Fokus: nur das aktive Textureset zeigen"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index f337d2ca..e9927174 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -979,4 +979,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Use as brush alpha", "Usar como alfa del pincel"), ("Place as decal", "Colocar como calcomanía"), ("Click: turn this channel on or off. Alt+click: this channel only", "Clic: activa o desactiva este canal. Alt+clic: solo este canal"), + ("Show all", "Mostrar todo"), + ("Hide all", "Ocultar todo"), + ("Invert show/hide", "Invertir mostrar/ocultar"), + ("Show or hide texture sets", "Mostrar u ocultar conjuntos de texturas"), + ("Focus: show only the active texture set", "Enfoque: mostrar solo el conjunto de texturas activo"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index d6db4b27..92f25811 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -994,4 +994,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Use as brush alpha", "Utiliser comme alpha du pinceau"), ("Place as decal", "Placer en décalque"), ("Click: turn this channel on or off. Alt+click: this channel only", "Clic : active ou désactive ce canal. Alt+clic : ce canal uniquement"), + ("Show all", "Tout afficher"), + ("Hide all", "Tout masquer"), + ("Invert show/hide", "Inverser afficher/masquer"), + ("Show or hide texture sets", "Afficher ou masquer les ensembles de textures"), + ("Focus: show only the active texture set", "Focus : n'afficher que l'ensemble de textures actif"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 622b40a4..9c71748f 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -988,4 +988,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Use as brush alpha", "Usa come alpha del pennello"), ("Place as decal", "Posiziona come decal"), ("Click: turn this channel on or off. Alt+click: this channel only", "Clic: attiva o disattiva questo canale. Alt+clic: solo questo canale"), + ("Show all", "Mostra tutto"), + ("Hide all", "Nascondi tutto"), + ("Invert show/hide", "Inverti mostra/nascondi"), + ("Show or hide texture sets", "Mostra o nascondi i set di texture"), + ("Focus: show only the active texture set", "Focus: mostra solo il set di texture attivo"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 91e5eabd..c3d9ccad 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -961,4 +961,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Use as brush alpha", "ブラシのアルファとして使用"), ("Place as decal", "デカールとして配置"), ("Click: turn this channel on or off. Alt+click: this channel only", "クリック: このチャンネルのオン/オフ。Alt+クリック: このチャンネルのみ"), + ("Show all", "すべて表示"), + ("Hide all", "すべて非表示"), + ("Invert show/hide", "表示/非表示を反転"), + ("Show or hide texture sets", "テクスチャセットの表示/非表示"), + ("Focus: show only the active texture set", "フォーカス: アクティブなテクスチャセットのみ表示"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 26e0c66b..6182b57a 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -946,4 +946,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Use as brush alpha", "브러시 알파로 사용"), ("Place as decal", "데칼로 배치"), ("Click: turn this channel on or off. Alt+click: this channel only", "클릭: 이 채널 켜기/끄기. Alt+클릭: 이 채널만"), + ("Show all", "모두 표시"), + ("Hide all", "모두 숨기기"), + ("Invert show/hide", "표시/숨기기 반전"), + ("Show or hide texture sets", "텍스처 세트 표시 또는 숨기기"), + ("Focus: show only the active texture set", "포커스: 활성 텍스처 세트만 표시"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 001e4f49..a430655c 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -976,4 +976,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Use as brush alpha", "Usar como alpha do pincel"), ("Place as decal", "Colocar como decalque"), ("Click: turn this channel on or off. Alt+click: this channel only", "Clique: liga ou desliga este canal. Alt+clique: só este canal"), + ("Show all", "Mostrar tudo"), + ("Hide all", "Ocultar tudo"), + ("Invert show/hide", "Inverter mostrar/ocultar"), + ("Show or hide texture sets", "Mostrar ou ocultar conjuntos de texturas"), + ("Focus: show only the active texture set", "Foco: mostrar só o conjunto de texturas ativo"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index d6e09df7..e1fc3780 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -892,4 +892,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Use as brush alpha", "用作笔刷 Alpha"), ("Place as decal", "作为贴花放置"), ("Click: turn this channel on or off. Alt+click: this channel only", "单击:打开或关闭此通道。Alt+单击:仅此通道"), + ("Show all", "全部显示"), + ("Hide all", "全部隐藏"), + ("Invert show/hide", "反转显示/隐藏"), + ("Show or hide texture sets", "显示或隐藏纹理集"), + ("Focus: show only the active texture set", "聚焦:仅显示当前纹理集"), ]; From 2d8c34c055d812ca41d270189734b4f03aae39e5 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 06:20:17 +0700 Subject: [PATCH 28/60] Features: the texture set visibility controls --- docs/features.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/features.md b/docs/features.md index a55b2590..76289221 100644 --- a/docs/features.md +++ b/docs/features.md @@ -64,7 +64,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile and one texture per tile on export (`$udim`). - **Texture sets** from 128 to 8192 px per material, resampled when you change them, with 21 - channel types to add or remove. + channel types to add or remove. Show, hide or invert them all at once, or **focus** on the + active one. - **Projects** are a single `.tcraft` file: the mesh, every layer (sparse and lossless), baked maps and imported images. **Project templates** start new work from a saved setup. From 2b7ed060bea1401830147ea3ec75a59235c4016c Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 07:08:16 +0700 Subject: [PATCH 29/60] Docs: roadmap after today's fixes --- ROADMAP.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 17640da4..f9f04f38 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -12,12 +12,12 @@ end to end today (engine + UI + automation + tests), not what is planned. | Area | Weight | Done | What works | Main gaps | |---|---:|---:|---|---| | Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | -| Texture sets | 6 | 95% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile**, one texture per tile at its own size, `$udim` export), list with visibility, sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | Filter radii and height slopes of a tile smaller than its atlas block follow the block | -| Layer stack | 16 | 96% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels, invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; smart masks; mask view (Alt+click); duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **27 library filters** (adjustments, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | +| Texture sets | 6 | 95% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile**, one texture per tile at its own size, `$udim` export), list with visibility (show or hide all, invert, **focus** on one set), sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | Filter radii and height slopes of a tile smaller than its atlas block follow the block | +| Layer stack | 16 | 96% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels, invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **27 library filters** (adjustments, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | | Painting tools | 14 | 90% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt (not exposed by the windowing layer) | | Materials and assets | 8 | 88% | 48 procedural materials (incl. car paint, velvet, brushed steel, skin, wax), 21 smart materials, 18 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 22 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | | Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — | -| Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Hardware ray tracing | +| Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, the baked normal map under the painted normal, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Hardware ray tracing | | Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — | | Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, `$udim` tiles, OBJ, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | | UI and UX | 8 | 95% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, a **start window** (new, open, recent projects), **shortcut editor** with conflict detection, tooltips with shortcuts; all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations | From cecc5141ad7b461caf10132f227f5d794f644199 Mon Sep 17 00:00:00 2001 From: Agapenordev <120006055+Agapenordev@users.noreply.github.com> Date: Mon, 2 Nov 2026 01:24:39 +0100 Subject: [PATCH 30/60] Translations: GPU notices in their alphabetical place The tables are sorted by English key with new strings appended at the end, so every open PR that adds strings conflicts there. These keys now sit in their sorted slots, away from the shared tail. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/ar.rs | 18 +++++++++--------- crates/ui-egui/src/i18n/de.rs | 18 +++++++++--------- crates/ui-egui/src/i18n/es.rs | 18 +++++++++--------- crates/ui-egui/src/i18n/fr.rs | 18 +++++++++--------- crates/ui-egui/src/i18n/it.rs | 18 +++++++++--------- crates/ui-egui/src/i18n/ja.rs | 18 +++++++++--------- crates/ui-egui/src/i18n/ko.rs | 18 +++++++++--------- crates/ui-egui/src/i18n/pt_br.rs | 18 +++++++++--------- crates/ui-egui/src/i18n/zh_hans.rs | 18 +++++++++--------- 9 files changed, 81 insertions(+), 81 deletions(-) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 358f157a..d81740ba 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -329,6 +329,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("From template", "من قالب"), ("From template / project", "من قالب / مشروع"), ("Full", "كامل"), + ("GPU error: {error}", "خطأ في GPU: {error}"), ("Geometry mask", "قناع هندسي"), ( "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", @@ -524,6 +525,14 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal map format", "صيغة خريطة النواظم"), ("Normal map inverse detail", "عكس تفاصيل خريطة النواظم"), ("Normal: painting uses the flat normal", "عادي: يستخدم الرسم الناظم المسطح"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "لا توجد ذاكرة GPU كافية لعرض مجموعة الخامات \"{name}\" كاملة: خفّض دقة الخامة لمنفذ العرض في الإعدادات. لا يتأثر الرسم والتصدير.", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "لا توجد ذاكرة GPU كافية لعرض {count} من مجموعات الخامات كاملة ({names}): خفّض دقة الخامة لمنفذ العرض في الإعدادات. لا يتأثر الرسم والتصدير.", + ), ("Not exported: no source in this texture set", "لم يتم التصدير: لا يوجد مصدر في مجموعة الخامات هذه"), ("Not saved: {error}", "لم يتم الحفظ: {error}"), ("Off", "معطل"), @@ -938,13 +947,4 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "النمط"), ("Use as brush alpha", "استخدام كألفا للفرشاة"), ("Place as decal", "وضع كملصق"), - ("GPU error: {error}", "خطأ في GPU: {error}"), - ( - "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", - "لا توجد ذاكرة GPU كافية لعرض مجموعة الخامات \"{name}\" كاملة: خفّض دقة الخامة لمنفذ العرض في الإعدادات. لا يتأثر الرسم والتصدير.", - ), - ( - "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", - "لا توجد ذاكرة GPU كافية لعرض {count} من مجموعات الخامات كاملة ({names}): خفّض دقة الخامة لمنفذ العرض في الإعدادات. لا يتأثر الرسم والتصدير.", - ), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 4585ddff..d8ab521b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -350,6 +350,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("From template", "Aus Vorlage"), ("From template / project", "Aus Vorlage / Projekt"), ("Full", "Voll"), + ("GPU error: {error}", "GPU-Fehler: {error}"), ("Geometry mask", "Geometriemaske"), ( "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", @@ -551,6 +552,14 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal map format", "Normal-Map-Format"), ("Normal map inverse detail", "Normal-Map-Detail invertiert"), ("Normal: painting uses the flat normal", "Normale: Malen verwendet die flache Normale"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Nicht genug GPU-Speicher, um das Texturset \"{name}\" vollständig anzuzeigen: Verringere in den Einstellungen die Texturauflösung des Ansichtsfensters. Malen und Export sind nicht betroffen.", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Nicht genug GPU-Speicher, um {count} Texturesets vollständig anzuzeigen ({names}): Verringere in den Einstellungen die Texturauflösung des Ansichtsfensters. Malen und Export sind nicht betroffen.", + ), ("Not exported: no source in this texture set", "Nicht exportiert: keine Quelle in diesem Texturset"), ("Not saved: {error}", "Nicht gespeichert: {error}"), ("Off", "Aus"), @@ -993,13 +1002,4 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "Schnitt"), ("Use as brush alpha", "Als Pinsel-Alpha verwenden"), ("Place as decal", "Als Decal platzieren"), - ( - "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", - "Nicht genug GPU-Speicher, um das Texturset \"{name}\" vollständig anzuzeigen: Verringere in den Einstellungen die Texturauflösung des Ansichtsfensters. Malen und Export sind nicht betroffen.", - ), - ("GPU error: {error}", "GPU-Fehler: {error}"), - ( - "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", - "Nicht genug GPU-Speicher, um {count} Texturesets vollständig anzuzeigen ({names}): Verringere in den Einstellungen die Texturauflösung des Ansichtsfensters. Malen und Export sind nicht betroffen.", - ), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 8e76c6ca..06d2f6eb 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -344,6 +344,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("From template", "Desde la plantilla"), ("From template / project", "Desde la plantilla / el proyecto"), ("Full", "Completa"), + ("GPU error: {error}", "Error de GPU: {error}"), ("Geometry mask", "Máscara de geometría"), ( "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", @@ -545,6 +546,14 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal map format", "Formato del mapa de normales"), ("Normal map inverse detail", "Detalle inverso de mapa de normales"), ("Normal: painting uses the flat normal", "Normal: la pintura usa la normal plana"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "No hay suficiente memoria de GPU para mostrar el conjunto de texturas \"{name}\" por completo: reduce en Ajustes la resolución de texturas de la ventana gráfica. La pintura y la exportación no se ven afectadas.", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "No hay suficiente memoria de GPU para mostrar por completo {count} conjuntos de texturas ({names}): reduce en Ajustes la resolución de texturas de la ventana gráfica. La pintura y la exportación no se ven afectadas.", + ), ("Not exported: no source in this texture set", "No exportado: no hay origen en este conjunto de texturas"), ("Not saved: {error}", "No guardado: {error}"), ("Off", "Desactivado"), @@ -978,13 +987,4 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "Estilo"), ("Use as brush alpha", "Usar como alfa del pincel"), ("Place as decal", "Colocar como calcomanía"), - ( - "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", - "No hay suficiente memoria de GPU para mostrar el conjunto de texturas \"{name}\" por completo: reduce en Ajustes la resolución de texturas de la ventana gráfica. La pintura y la exportación no se ven afectadas.", - ), - ("GPU error: {error}", "Error de GPU: {error}"), - ( - "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", - "No hay suficiente memoria de GPU para mostrar por completo {count} conjuntos de texturas ({names}): reduce en Ajustes la resolución de texturas de la ventana gráfica. La pintura y la exportación no se ven afectadas.", - ), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index a9de5cdc..6efe6ab4 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -350,6 +350,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("From template", "Selon le modèle"), ("From template / project", "Selon le modèle / projet"), ("Full", "Pleine"), + ("GPU error: {error}", "Erreur GPU : {error}"), ("Geometry mask", "Masque de géométrie"), ( "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", @@ -554,6 +555,14 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal map format", "Format de carte de normales"), ("Normal map inverse detail", "Normales : détail inverse"), ("Normal: painting uses the flat normal", "Normal : la peinture utilise la normale plate"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Mémoire GPU insuffisante pour afficher entièrement l'ensemble de textures \"{name}\" : réduisez la résolution des textures de l'affichage dans les Paramètres. La peinture et l'export ne sont pas affectés.", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Mémoire GPU insuffisante pour afficher entièrement {count} ensembles de textures ({names}) : réduisez la résolution des textures de l'affichage dans les Paramètres. La peinture et l'export ne sont pas affectés.", + ), ("Not exported: no source in this texture set", "Non exporté : aucune source dans cet ensemble de textures"), ("Not saved: {error}", "Non enregistré : {error}"), ("Off", "Désactivé"), @@ -993,13 +1002,4 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "Style"), ("Use as brush alpha", "Utiliser comme alpha du pinceau"), ("Place as decal", "Placer en décalque"), - ( - "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", - "Mémoire GPU insuffisante pour afficher entièrement l'ensemble de textures \"{name}\" : réduisez la résolution des textures de l'affichage dans les Paramètres. La peinture et l'export ne sont pas affectés.", - ), - ("GPU error: {error}", "Erreur GPU : {error}"), - ( - "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", - "Mémoire GPU insuffisante pour afficher entièrement {count} ensembles de textures ({names}) : réduisez la résolution des textures de l'affichage dans les Paramètres. La peinture et l'export ne sont pas affectés.", - ), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 83cb9b3c..b02a06e9 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -350,6 +350,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("From template", "Da modello"), ("From template / project", "Da modello / progetto"), ("Full", "Piena"), + ("GPU error: {error}", "Errore GPU: {error}"), ("Geometry mask", "Maschera geometria"), ( "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", @@ -551,6 +552,14 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal map format", "Formato mappa normali"), ("Normal map inverse detail", "Dettaglio inverso mappa normali"), ("Normal: painting uses the flat normal", "Normale: la pittura usa la normale piatta"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Memoria GPU insufficiente per mostrare per intero il set di texture \"{name}\": riduci nelle Impostazioni la risoluzione texture della viewport. Pittura ed esportazione non sono interessate.", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Memoria GPU insufficiente per mostrare per intero {count} set di texture ({names}): riduci nelle Impostazioni la risoluzione texture della viewport. Pittura ed esportazione non sono interessate.", + ), ("Not exported: no source in this texture set", "Non esportato: nessuna sorgente in questo set di texture"), ("Not saved: {error}", "Non salvato: {error}"), ("Off", "Disattivato"), @@ -987,13 +996,4 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "Stile"), ("Use as brush alpha", "Usa come alpha del pennello"), ("Place as decal", "Posiziona come decal"), - ( - "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", - "Memoria GPU insufficiente per mostrare per intero il set di texture \"{name}\": riduci nelle Impostazioni la risoluzione texture della viewport. Pittura ed esportazione non sono interessate.", - ), - ("GPU error: {error}", "Errore GPU: {error}"), - ( - "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", - "Memoria GPU insufficiente per mostrare per intero {count} set di texture ({names}): riduci nelle Impostazioni la risoluzione texture della viewport. Pittura ed esportazione non sono interessate.", - ), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 7c8228c6..ea00637e 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -338,6 +338,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("From template", "テンプレートから"), ("From template / project", "テンプレート / プロジェクトから"), ("Full", "フル"), + ("GPU error: {error}", "GPU エラー: {error}"), ("Geometry mask", "ジオメトリマスク"), ( "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", @@ -536,6 +537,14 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal map format", "ノーマルマップ形式"), ("Normal map inverse detail", "ノーマルマップ 逆ディテール"), ("Normal: painting uses the flat normal", "ノーマル: ペイントにはフラットな法線を使用"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "GPU メモリが不足しているため、テクスチャセット「{name}」を完全には表示できません:設定でビューポートのテクスチャ解像度を下げてください。ペイントと書き出しには影響しません。", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "GPU メモリが不足しているため、{count} 個のテクスチャセット({names})を完全には表示できません:設定でビューポートのテクスチャ解像度を下げてください。ペイントと書き出しには影響しません。", + ), ("Not exported: no source in this texture set", "エクスポートされません: このテクスチャセットにソースがありません"), ("Not saved: {error}", "保存されていません: {error}"), ("Off", "オフ"), @@ -960,13 +969,4 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "スタイル"), ("Use as brush alpha", "ブラシのアルファとして使用"), ("Place as decal", "デカールとして配置"), - ( - "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", - "GPU メモリが不足しているため、テクスチャセット「{name}」を完全には表示できません:設定でビューポートのテクスチャ解像度を下げてください。ペイントと書き出しには影響しません。", - ), - ("GPU error: {error}", "GPU エラー: {error}"), - ( - "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", - "GPU メモリが不足しているため、{count} 個のテクスチャセット({names})を完全には表示できません:設定でビューポートのテクスチャ解像度を下げてください。ペイントと書き出しには影響しません。", - ), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index e712064c..d89d1f02 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -332,6 +332,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("From template", "템플릿 기준"), ("From template / project", "템플릿 / 프로젝트 기준"), ("Full", "전체"), + ("GPU error: {error}", "GPU 오류: {error}"), ("Geometry mask", "지오메트리 마스크"), ( "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", @@ -530,6 +531,14 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal map format", "노멀 맵 형식"), ("Normal map inverse detail", "노멀 맵 역 디테일"), ("Normal: painting uses the flat normal", "노멀: 평면 노멀로 페인팅합니다"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "GPU 메모리가 부족하여 텍스처 세트 \"{name}\"을(를) 모두 표시할 수 없습니다: 설정에서 뷰포트의 텍스처 해상도를 낮추세요. 페인팅과 내보내기에는 영향이 없습니다.", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "GPU 메모리가 부족하여 텍스처 세트 {count}개({names})를 모두 표시할 수 없습니다: 설정에서 뷰포트의 텍스처 해상도를 낮추세요. 페인팅과 내보내기에는 영향이 없습니다.", + ), ("Not exported: no source in this texture set", "내보내지 않음: 이 텍스처 세트에 소스가 없습니다"), ("Not saved: {error}", "저장되지 않음: {error}"), ("Off", "끄기"), @@ -945,13 +954,4 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "스타일"), ("Use as brush alpha", "브러시 알파로 사용"), ("Place as decal", "데칼로 배치"), - ( - "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", - "GPU 메모리가 부족하여 텍스처 세트 \"{name}\"을(를) 모두 표시할 수 없습니다: 설정에서 뷰포트의 텍스처 해상도를 낮추세요. 페인팅과 내보내기에는 영향이 없습니다.", - ), - ("GPU error: {error}", "GPU 오류: {error}"), - ( - "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", - "GPU 메모리가 부족하여 텍스처 세트 {count}개({names})를 모두 표시할 수 없습니다: 설정에서 뷰포트의 텍스처 해상도를 낮추세요. 페인팅과 내보내기에는 영향이 없습니다.", - ), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 02d7f6ec..835e0fc7 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -344,6 +344,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("From template", "Do modelo"), ("From template / project", "Do modelo / projeto"), ("Full", "Completa"), + ("GPU error: {error}", "Erro de GPU: {error}"), ("Geometry mask", "Máscara de geometria"), ( "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", @@ -542,6 +543,14 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal map format", "Formato do mapa normal"), ("Normal map inverse detail", "Detalhe inverso de mapa normal"), ("Normal: painting uses the flat normal", "Normal: a pintura usa a normal plana"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Memória de GPU insuficiente para mostrar o conjunto de texturas \"{name}\" por completo: reduza nas Configurações a resolução das texturas da viewport. A pintura e a exportação não são afetadas.", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Memória de GPU insuficiente para mostrar por completo {count} conjuntos de texturas ({names}): reduza nas Configurações a resolução das texturas da viewport. A pintura e a exportação não são afetadas.", + ), ("Not exported: no source in this texture set", "Não exportado: sem origem neste conjunto de texturas"), ("Not saved: {error}", "Não salvo: {error}"), ("Off", "Desligado"), @@ -975,13 +984,4 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "Estilo"), ("Use as brush alpha", "Usar como alpha do pincel"), ("Place as decal", "Colocar como decalque"), - ( - "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", - "Memória de GPU insuficiente para mostrar o conjunto de texturas \"{name}\" por completo: reduza nas Configurações a resolução das texturas da viewport. A pintura e a exportação não são afetadas.", - ), - ("GPU error: {error}", "Erro de GPU: {error}"), - ( - "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", - "Memória de GPU insuficiente para mostrar por completo {count} conjuntos de texturas ({names}): reduza nas Configurações a resolução das texturas da viewport. A pintura e a exportação não são afetadas.", - ), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 71b44f58..bf5ef300 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -299,6 +299,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("From template", "基于模板"), ("From template / project", "基于模板 / 项目"), ("Full", "完整"), + ("GPU error: {error}", "GPU 错误:{error}"), ("Geometry mask", "几何遮罩"), ( "GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading.", @@ -485,6 +486,14 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal map format", "法线贴图格式"), ("Normal map inverse detail", "法线贴图反向细节"), ("Normal: painting uses the flat normal", "法线:绘画使用平坦法线"), + ( + "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "GPU 内存不足,无法完整显示纹理集“{name}”:请在设置中降低视口的纹理分辨率。绘制和导出不受影响。", + ), + ( + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "GPU 内存不足,无法完整显示 {count} 个纹理集({names}):请在设置中降低视口的纹理分辨率。绘制和导出不受影响。", + ), ("Not exported: no source in this texture set", "未导出:此纹理集中没有来源"), ("Not saved: {error}", "未保存:{error}"), ("Off", "关"), @@ -891,13 +900,4 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "样式"), ("Use as brush alpha", "用作笔刷 Alpha"), ("Place as decal", "作为贴花放置"), - ( - "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", - "GPU 内存不足,无法完整显示纹理集“{name}”:请在设置中降低视口的纹理分辨率。绘制和导出不受影响。", - ), - ("GPU error: {error}", "GPU 错误:{error}"), - ( - "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", - "GPU 内存不足,无法完整显示 {count} 个纹理集({names}):请在设置中降低视口的纹理分辨率。绘制和导出不受影响。", - ), ]; From aff63b567caafe4f3d05646ed5c8b49c93d95ae5 Mon Sep 17 00:00:00 2001 From: Agapenordev <120006055+Agapenordev@users.noreply.github.com> Date: Mon, 2 Nov 2026 01:25:06 +0100 Subject: [PATCH 31/60] Translations: the filter hint in its alphabetical place The tables are sorted by English key with new strings appended at the end, so every open PR that adds strings conflicts there. This key now sits in its sorted slot, away from the shared tail. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/ar.rs | 2 +- crates/ui-egui/src/i18n/de.rs | 2 +- crates/ui-egui/src/i18n/es.rs | 2 +- crates/ui-egui/src/i18n/fr.rs | 8 ++++---- crates/ui-egui/src/i18n/it.rs | 2 +- crates/ui-egui/src/i18n/ja.rs | 8 ++++---- crates/ui-egui/src/i18n/ko.rs | 8 ++++---- crates/ui-egui/src/i18n/pt_br.rs | 2 +- crates/ui-egui/src/i18n/zh_hans.rs | 2 +- 9 files changed, 18 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 538e8d4f..a3a96d61 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1,6 +1,7 @@ //! Arabic UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "لا يوجد رسم على \"{layer}\" بعد: يغيّر المرشح ما ترسمه عليها."), ("0 turns autosave off. Copies go to {folder}", "0 يعطل الحفظ التلقائي. تُحفظ النُسخ في {folder}"), ("2D view only", "عرض ثنائي الأبعاد فقط"), ("32 bits (float)", "32 بت (فاصلة عائمة)"), @@ -938,5 +939,4 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "النمط"), ("Use as brush alpha", "استخدام كألفا للفرشاة"), ("Place as decal", "وضع كملصق"), - ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "لا يوجد رسم على \"{layer}\" بعد: يغيّر المرشح ما ترسمه عليها."), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 11ea530b..06529f78 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1,6 +1,7 @@ //! German UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ist noch nicht bemalt: Der Filter verändert, was du darauf malst."), ("0 turns autosave off. Copies go to {folder}", "0 deaktiviert die automatische Speicherung. Kopien werden in {folder} abgelegt"), ("2D view only", "Nur 2D-Ansicht"), ("32 bits (float)", "32 Bit (Float)"), @@ -993,5 +994,4 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "Schnitt"), ("Use as brush alpha", "Als Pinsel-Alpha verwenden"), ("Place as decal", "Als Decal platzieren"), - ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ist noch nicht bemalt: Der Filter verändert, was du darauf malst."), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 985602e5..cf23978c 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1,6 +1,7 @@ //! Spanish UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" aún no tiene pintura: el filtro cambia lo que pintes en ella."), ("0 turns autosave off. Copies go to {folder}", "0 desactiva el autoguardado. Las copias se guardan en {folder}"), ("2D view only", "Solo vista 2D"), ("32 bits (float)", "32 bits (float)"), @@ -978,5 +979,4 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "Estilo"), ("Use as brush alpha", "Usar como alfa del pincel"), ("Place as decal", "Colocar como calcomanía"), - ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" aún no tiene pintura: el filtro cambia lo que pintes en ella."), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index ae6e2441..d31dde2c 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1,6 +1,10 @@ //! French UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ( + "\"{layer}\" has no paint yet: the filter changes what you paint on it.", + "\"{layer}\" n'a pas encore de peinture : le filtre modifie ce que vous y peignez.", + ), ("0 turns autosave off. Copies go to {folder}", "0 désactive la sauvegarde automatique. Les copies vont dans {folder}"), ("2D view only", "Vue 2D seule"), ("32 bits (float)", "32 bits (flottant)"), @@ -993,8 +997,4 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "Style"), ("Use as brush alpha", "Utiliser comme alpha du pinceau"), ("Place as decal", "Placer en décalque"), - ( - "\"{layer}\" has no paint yet: the filter changes what you paint on it.", - "\"{layer}\" n'a pas encore de peinture : le filtre modifie ce que vous y peignez.", - ), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 0094dd7f..2e9cec92 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1,6 +1,7 @@ //! Italian UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" non è ancora dipinto: il filtro modifica ciò che vi dipingi."), ("0 turns autosave off. Copies go to {folder}", "0 disattiva il salvataggio automatico. Le copie vengono salvate in {folder}"), ("2D view only", "Solo vista 2D"), ("32 bits (float)", "32 bit (float)"), @@ -987,5 +988,4 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "Stile"), ("Use as brush alpha", "Usa come alpha del pennello"), ("Place as decal", "Posiziona come decal"), - ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" non è ancora dipinto: il filtro modifica ciò che vi dipingi."), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 1d8ef58b..5119fe91 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1,6 +1,10 @@ //! Japanese UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ( + "\"{layer}\" has no paint yet: the filter changes what you paint on it.", + "「{layer}」にはまだペイントがありません:フィルターはこのレイヤーにペイントした内容を変化させます。", + ), ("0 turns autosave off. Copies go to {folder}", "0で自動保存をオフにします。コピーの保存先: {folder}"), ("2D view only", "2Dビューのみ"), ("32 bits (float)", "32ビット (浮動小数点)"), @@ -960,8 +964,4 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "スタイル"), ("Use as brush alpha", "ブラシのアルファとして使用"), ("Place as decal", "デカールとして配置"), - ( - "\"{layer}\" has no paint yet: the filter changes what you paint on it.", - "「{layer}」にはまだペイントがありません:フィルターはこのレイヤーにペイントした内容を変化させます。", - ), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f8c84321..8c65b16e 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1,6 +1,10 @@ //! Korean UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ( + "\"{layer}\" has no paint yet: the filter changes what you paint on it.", + "\"{layer}\"에 아직 페인트가 없습니다: 필터는 이 레이어에 칠하는 내용을 바꿉니다.", + ), ("0 turns autosave off. Copies go to {folder}", "0으로 설정하면 자동 저장이 꺼집니다. 사본 저장 위치: {folder}"), ("2D view only", "2D 뷰만"), ("32 bits (float)", "32비트 (float)"), @@ -945,8 +949,4 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "스타일"), ("Use as brush alpha", "브러시 알파로 사용"), ("Place as decal", "데칼로 배치"), - ( - "\"{layer}\" has no paint yet: the filter changes what you paint on it.", - "\"{layer}\"에 아직 페인트가 없습니다: 필터는 이 레이어에 칠하는 내용을 바꿉니다.", - ), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index ef08152f..124d24c9 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1,6 +1,7 @@ //! Brazilian Portuguese UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ainda não tem pintura: o filtro altera o que você pintar nela."), ("0 turns autosave off. Copies go to {folder}", "0 desativa o salvamento automático. As cópias vão para {folder}"), ("2D view only", "Apenas vista 2D"), ("32 bits (float)", "32 bits (float)"), @@ -975,5 +976,4 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "Estilo"), ("Use as brush alpha", "Usar como alpha do pincel"), ("Place as decal", "Colocar como decalque"), - ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ainda não tem pintura: o filtro altera o que você pintar nela."), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 22a01bbd..f0744499 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1,6 +1,7 @@ //! Simplified Chinese UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "“{layer}”尚未绘制:滤镜会改变你在其上绘制的内容。"), ("0 turns autosave off. Copies go to {folder}", "设为 0 可关闭自动保存。副本保存到 {folder}"), ("2D view only", "仅 2D 视图"), ("32 bits (float)", "32 位(浮点)"), @@ -891,5 +892,4 @@ pub const TABLE: &[(&str, &str)] = &[ ("Style", "样式"), ("Use as brush alpha", "用作笔刷 Alpha"), ("Place as decal", "作为贴花放置"), - ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "“{layer}”尚未绘制:滤镜会改变你在其上绘制的内容。"), ]; From 7a59356a338978c11ccb81f8f20a72cfbf04bcae Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:26:57 -0500 Subject: [PATCH 32/60] test: remove the MaterialX export scratch folders when the test ends Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/tests/materialx.rs | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/crates/engine/tests/materialx.rs b/crates/engine/tests/materialx.rs index 02de5528..1ff77912 100644 --- a/crates/engine/tests/materialx.rs +++ b/crates/engine/tests/materialx.rs @@ -6,10 +6,26 @@ use texturecraft_engine::{Session, execute}; const OPENPBR: &str = "OpenPBR (separate maps)"; -fn temp(tag: &str) -> std::path::PathBuf { +/// A scratch folder that is removed when it goes out of scope, so a failing test leaves nothing behind. +struct Scratch(std::path::PathBuf); + +impl std::ops::Deref for Scratch { + type Target = std::path::Path; + fn deref(&self) -> &std::path::Path { + &self.0 + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn temp(tag: &str) -> Scratch { let dir = std::env::temp_dir().join(format!("tc_mtlx_{tag}_{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); - dir + Scratch(dir) } fn export(s: &mut Session, dir: &std::path::Path, preset: &str, mtlx: bool) -> Value { @@ -43,7 +59,6 @@ fn writes_a_material_that_names_the_exported_textures() { assert!(refs >= 3, "base colour, roughness and normal at least: {text}"); assert!(text.contains("name=\"base_color\"") && text.contains("name=\"geometry_normal\""), "{text}"); } - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -51,12 +66,10 @@ fn off_by_default_and_warns_without_openpbr_maps() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); let dir = temp("off"); assert!(!files(&export(&mut s, &dir, OPENPBR, false)).iter().any(|f| f.ends_with(".mtlx"))); - let _ = std::fs::remove_dir_all(&dir); let dir = temp("other"); let r = export(&mut s, &dir, "Document channels + Normal + AO", true); assert!(!files(&r).iter().any(|f| f.ends_with(".mtlx"))); assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("OpenPBR")), "{r}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -70,5 +83,4 @@ fn udim_sets_use_the_udim_token() { assert!(text.contains(".<UDIM>.png"), "{text}"); assert!(!text.contains(".1001.") && !text.contains(".1002."), "{text}"); assert!(all.iter().any(|f| f.ends_with(".1001.png")) && all.iter().any(|f| f.ends_with(".1002.png"))); - let _ = std::fs::remove_dir_all(&dir); } From fe2e1545a60f5d66ffbcff20973e8f4505f9faba Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 07:36:27 +0700 Subject: [PATCH 33/60] Layers: Ctrl+C, Ctrl+X and Ctrl+V copy, cut and paste a layer The desktop and web shells deliver these keys as clipboard events, not key presses, so the layer shortcuts never fired. Outside a text field the clipboard events now run the shortcuts bound to Ctrl+C, Ctrl+X and Ctrl+V. Copying a layer by shortcut puts its name on the system clipboard, since Ctrl+V only reaches the app while that holds text or an image. Layer rows carry their name for screen readers and tests. Fixes #90, fixes #94. --- crates/ui-egui/src/dock.rs | 1 + crates/ui-egui/src/menus.rs | 26 +++++++++++++- crates/ui-egui/tests/layer_clipboard.rs | 45 +++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/tests/layer_clipboard.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index dd9191bb..b5cdf217 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -277,6 +277,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let selected = app.session.selected_layer() == Some(layer.id); let h = 38.0; let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag()); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &layer.name)); let p = ui.painter().clone(); let bg = if selected && app.session.target == StackTarget::Content { tk.row_selected diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index bad5be7a..6cf976a1 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -255,12 +255,13 @@ fn menu_item(app: &mut TextureCraftApp, ctx: &egui::Context, ui: &mut egui::Ui, /// plus the fixed brush keys. /// Keys pressed in a floating panel's own OS window run the shortcuts the main window's keys do. #[cfg(not(target_arch = "wasm32"))] -pub fn forwarded_shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context, events: Vec, _modifiers: Modifiers) { +pub fn forwarded_shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context, events: Vec, held: Modifiers) { if crate::keymap::capturing(ctx) { return; } let active = crate::keymap::active(&app.ui.keymap); for event in events { + let event = clipboard_key(&event, held).unwrap_or(event); let egui::Event::Key { key, pressed: true, repeat: false, modifiers, .. } = event else { continue }; let Some((id, _)) = active.iter().find(|(_, sc)| sc.logical_key == key && modifiers.matches_logically(sc.modifiers)) else { continue }; invoke(app, ctx, id); @@ -271,6 +272,10 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { if crate::keymap::capturing(ctx) || (ctx.memory(|m| m.focused().is_some()) && ctx.egui_wants_keyboard_input()) { return; } + ctx.input_mut(|i| { + let keys: Vec<_> = i.events.iter().filter_map(|e| clipboard_key(e, i.modifiers)).collect(); + i.events.extend(keys); + }); if !ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. }))) { return; } @@ -295,6 +300,25 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } }); for id in fire { + if matches!(id, "layer.copy" | "layer.cut") + && let Some(layer) = app.session.selected_layer().and_then(|l| app.session.doc.project.layers.get(&l)) + { + // Ctrl+V reaches the app only while the system clipboard holds text or an image. + ctx.copy_text(layer.name.clone()); + } invoke(app, ctx, id); } } + +/// The desktop and web shells turn Ctrl+C, Ctrl+X and Ctrl+V (and Ctrl+Insert, Shift+Delete, +/// Shift+Insert) into clipboard events instead of key presses. Outside a text field they are the +/// shortcuts bound to Ctrl+C, Ctrl+X and Ctrl+V (copy, cut and paste a layer by default). +fn clipboard_key(event: &egui::Event, held: Modifiers) -> Option { + let key = match event { + egui::Event::Copy => Key::C, + egui::Event::Cut => Key::X, + egui::Event::Paste(_) | egui::Event::PasteImage(_) => Key::V, + _ => return None, + }; + Some(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: held | Modifiers::COMMAND }) +} diff --git a/crates/ui-egui/tests/layer_clipboard.rs b/crates/ui-egui/tests/layer_clipboard.rs new file mode 100644 index 00000000..3db97ca2 --- /dev/null +++ b/crates/ui-egui/tests/layer_clipboard.rs @@ -0,0 +1,45 @@ +//! Ctrl+C, Ctrl+X and Ctrl+V on a layer clicked in the stack. The desktop and web shells deliver +//! these keys as clipboard events, not key presses, so the tests send those events. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::LayerId; +use texturecraft_ui_egui::TextureCraftApp; + +/// The sample session with its selected layer clicked in the stack, and that layer. +fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + let layer = h.state().session.selected_layer().unwrap(); + let name = h.state().session.doc.project.layers[&layer].name.clone(); + h.get_by_label(&name).click(); + h.run_steps(3); + (h, layer) +} + +fn count(h: &Harness<'_, TextureCraftApp>) -> usize { + h.state().session.doc.project.layers.len() +} + +#[test] +fn ctrl_x_cuts_the_clicked_layer() { + let (mut h, layer) = harness(); + h.event(egui::Event::Cut); + h.run_steps(3); + assert!(!h.state().session.doc.project.layers.contains_key(&layer), "Ctrl+X removes the layer"); + assert!(h.state().session.clipboard.is_some(), "and keeps it on the layer clipboard"); +} + +#[test] +fn ctrl_c_then_ctrl_v_pastes_a_copy() { + let (mut h, _) = harness(); + let before = count(&h); + h.event(egui::Event::Copy); + h.run_steps(3); + assert!(h.state().session.clipboard.is_some(), "Ctrl+C copies the layer"); + // The shell sends the system clipboard's text with the paste; Ctrl+C put the layer name there. + h.event(egui::Event::Paste("Layer".into())); + h.run_steps(3); + assert!(count(&h) > before, "Ctrl+V pastes the layer"); +} From 85c749bb1b9a86743ce644f9a4b6c695054fa7f3 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 07:41:01 +0700 Subject: [PATCH 34/60] Ask to save unsaved changes when the app closes Closing the window (or File > Quit) with unsaved changes now keeps the app open and asks: Save, Don't save or Cancel. A cancelled or failed save keeps the app and the dialog open. Strings translated into all nine other UI languages. Fixes #100. --- crates/ui-egui/src/i18n/ar.rs | 3 ++ crates/ui-egui/src/i18n/de.rs | 3 ++ crates/ui-egui/src/i18n/es.rs | 3 ++ crates/ui-egui/src/i18n/fr.rs | 3 ++ crates/ui-egui/src/i18n/it.rs | 3 ++ crates/ui-egui/src/i18n/ja.rs | 3 ++ crates/ui-egui/src/i18n/ko.rs | 3 ++ crates/ui-egui/src/i18n/pt_br.rs | 3 ++ crates/ui-egui/src/i18n/zh_hans.rs | 3 ++ crates/ui-egui/src/state.rs | 3 ++ crates/ui-egui/src/windows.rs | 46 +++++++++++++++++++++ crates/ui-egui/tests/close_unsaved.rs | 59 +++++++++++++++++++++++++++ docs/features.md | 3 +- 13 files changed, 137 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/tests/close_unsaved.rs diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 5fb79fb2..9ce7ad03 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -944,4 +944,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert show/hide", "عكس الإظهار/الإخفاء"), ("Show or hide texture sets", "إظهار مجموعات الخامات أو إخفاؤها"), ("Focus: show only the active texture set", "تركيز: إظهار مجموعة الخامات النشطة فقط"), + ("Unsaved changes", "تغييرات غير محفوظة"), + ("Don't save", "عدم الحفظ"), + ("Save the changes to {name} before closing?", "هل تريد حفظ التغييرات في {name} قبل الإغلاق؟"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index e2d9ed89..eb50e2ff 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -999,4 +999,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert show/hide", "Ein-/Ausblenden umkehren"), ("Show or hide texture sets", "Texturesets ein- oder ausblenden"), ("Focus: show only the active texture set", "Fokus: nur das aktive Textureset zeigen"), + ("Unsaved changes", "Ungespeicherte Änderungen"), + ("Don't save", "Nicht speichern"), + ("Save the changes to {name} before closing?", "Änderungen an {name} vor dem Schließen speichern?"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index e9927174..c415b5f9 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -984,4 +984,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert show/hide", "Invertir mostrar/ocultar"), ("Show or hide texture sets", "Mostrar u ocultar conjuntos de texturas"), ("Focus: show only the active texture set", "Enfoque: mostrar solo el conjunto de texturas activo"), + ("Unsaved changes", "Cambios sin guardar"), + ("Don't save", "No guardar"), + ("Save the changes to {name} before closing?", "¿Guardar los cambios de {name} antes de cerrar?"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 92f25811..404f7451 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -999,4 +999,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert show/hide", "Inverser afficher/masquer"), ("Show or hide texture sets", "Afficher ou masquer les ensembles de textures"), ("Focus: show only the active texture set", "Focus : n'afficher que l'ensemble de textures actif"), + ("Unsaved changes", "Modifications non enregistrées"), + ("Don't save", "Ne pas enregistrer"), + ("Save the changes to {name} before closing?", "Enregistrer les modifications de {name} avant de fermer ?"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 9c71748f..3734112b 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -993,4 +993,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert show/hide", "Inverti mostra/nascondi"), ("Show or hide texture sets", "Mostra o nascondi i set di texture"), ("Focus: show only the active texture set", "Focus: mostra solo il set di texture attivo"), + ("Unsaved changes", "Modifiche non salvate"), + ("Don't save", "Non salvare"), + ("Save the changes to {name} before closing?", "Salvare le modifiche a {name} prima di chiudere?"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index c3d9ccad..62e3f15b 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -966,4 +966,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert show/hide", "表示/非表示を反転"), ("Show or hide texture sets", "テクスチャセットの表示/非表示"), ("Focus: show only the active texture set", "フォーカス: アクティブなテクスチャセットのみ表示"), + ("Unsaved changes", "未保存の変更"), + ("Don't save", "保存しない"), + ("Save the changes to {name} before closing?", "閉じる前に {name} の変更を保存しますか?"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 6182b57a..d8b614f5 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -951,4 +951,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert show/hide", "표시/숨기기 반전"), ("Show or hide texture sets", "텍스처 세트 표시 또는 숨기기"), ("Focus: show only the active texture set", "포커스: 활성 텍스처 세트만 표시"), + ("Unsaved changes", "저장되지 않은 변경 사항"), + ("Don't save", "저장 안 함"), + ("Save the changes to {name} before closing?", "닫기 전에 {name}의 변경 사항을 저장할까요?"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index a430655c..9d1d9523 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -981,4 +981,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert show/hide", "Inverter mostrar/ocultar"), ("Show or hide texture sets", "Mostrar ou ocultar conjuntos de texturas"), ("Focus: show only the active texture set", "Foco: mostrar só o conjunto de texturas ativo"), + ("Unsaved changes", "Alterações não salvas"), + ("Don't save", "Não salvar"), + ("Save the changes to {name} before closing?", "Salvar as alterações em {name} antes de fechar?"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index e1fc3780..c62467da 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -897,4 +897,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert show/hide", "反转显示/隐藏"), ("Show or hide texture sets", "显示或隐藏纹理集"), ("Focus: show only the active texture set", "聚焦:仅显示当前纹理集"), + ("Unsaved changes", "未保存的更改"), + ("Don't save", "不保存"), + ("Save the changes to {name} before closing?", "关闭前是否保存对 {name} 的更改?"), ]; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 287be1a3..6670c608 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -76,6 +76,9 @@ pub struct Windows { /// The start window: new, open, recent projects (the app opens it at launch). #[serde(skip)] pub start: bool, + /// Closing with unsaved changes: save, don't save or cancel (desktop). + #[serde(skip)] + pub confirm_close: bool, } /// Edit › Settings. diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 417c8057..8a8ba0b6 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -29,6 +29,52 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if app.ui.mode == Mode::Baking { bake_bar(app, ctx); } + #[cfg(not(target_arch = "wasm32"))] + confirm_close(app, ctx); +} + +/// Closing the app with unsaved changes asks whether to save them first. +#[cfg(not(target_arch = "wasm32"))] +fn confirm_close(app: &mut TextureCraftApp, ctx: &egui::Context) { + if app.session.modified && ctx.input(|i| i.viewport().close_requested()) { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + app.ui.windows.confirm_close = true; + } + if !app.ui.windows.confirm_close { + return; + } + let mut open = true; + let mut save = None; + let mut cancel = false; + dialog("confirm_close", tr("Unsaved changes"), &mut open).show(ctx, |ui| { + ui.label(trf("Save the changes to {name} before closing?", &[("name", &app.session.doc.project.name)])); + ui.add_space(8.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.add(primary_button(ui, tr("Save"))).clicked() { + save = Some(true); + } + if ui.button(tr("Don't save")).clicked() { + save = Some(false); + } + if ui.button(tr("Cancel")).clicked() { + cancel = true; + } + }); + }); + app.ui.windows.confirm_close = open && !cancel; + match save { + Some(true) => { + file_action(app, ctx, "file.save"); + } + // Closing anyway: the changes are let go. + Some(false) => app.session.modified = false, + None => return, + } + // A cancelled or failed save keeps the app and this dialog open. + if !app.session.modified { + app.ui.windows.confirm_close = false; + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } } /// A titled tool window; `id` keeps its place across UI languages. diff --git a/crates/ui-egui/tests/close_unsaved.rs b/crates/ui-egui/tests/close_unsaved.rs new file mode 100644 index 00000000..88811700 --- /dev/null +++ b/crates/ui-egui/tests/close_unsaved.rs @@ -0,0 +1,59 @@ +//! Closing the app with unsaved changes asks whether to save them first. + +use egui::{ViewportCommand, ViewportEvent, ViewportId}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_ui_egui::TextureCraftApp; + +fn harness(modified: bool) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.modified = modified; + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + h +} + +/// The window's close button, for one frame. +fn request_close(h: &mut Harness<'_, TextureCraftApp>) { + h.input_mut().viewports.entry(ViewportId::ROOT).or_default().events.push(ViewportEvent::Close); + h.step(); + h.input_mut().viewports.entry(ViewportId::ROOT).or_default().events.clear(); +} + +/// The viewport commands of the last frame. +fn sent(h: &Harness<'_, TextureCraftApp>, cmd: &ViewportCommand) -> bool { + h.output().viewport_output.get(&ViewportId::ROOT).is_some_and(|v| v.commands.contains(cmd)) +} + +#[test] +fn closing_with_changes_asks_and_dont_save_closes() { + let mut h = harness(true); + request_close(&mut h); + assert!(sent(&h, &ViewportCommand::CancelClose), "the close waits for an answer"); + h.run_steps(2); + assert!(h.state().ui.windows.confirm_close, "the dialog is open"); + h.get_by_label("Don't save").click(); + h.step(); + assert!(sent(&h, &ViewportCommand::Close), "Don't save closes the app"); + assert!(!h.state().ui.windows.confirm_close); +} + +#[test] +fn cancel_keeps_the_app_open() { + let mut h = harness(true); + request_close(&mut h); + h.run_steps(2); + h.get_by_label("Cancel").click(); + h.step(); + assert!(!sent(&h, &ViewportCommand::Close)); + assert!(!h.state().ui.windows.confirm_close, "Cancel closes the dialog"); + assert!(h.state().session.modified, "and keeps the changes"); +} + +#[test] +fn closing_without_changes_does_not_ask() { + let mut h = harness(false); + request_close(&mut h); + assert!(!sent(&h, &ViewportCommand::CancelClose)); + assert!(!h.state().ui.windows.confirm_close); +} diff --git a/docs/features.md b/docs/features.md index 76289221..1408a242 100644 --- a/docs/features.md +++ b/docs/features.md @@ -67,7 +67,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA channel types to add or remove. Show, hide or invert them all at once, or **focus** on the active one. - **Projects** are a single `.tcraft` file: the mesh, every layer (sparse and lossless), baked maps - and imported images. **Project templates** start new work from a saved setup. + and imported images. **Project templates** start new work from a saved setup. Closing the app + with unsaved changes asks whether to save them first. ## Bake and export From 0a13426b6d168345d678941b119ba2d8b14dbd3d Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 07:45:24 +0700 Subject: [PATCH 35/60] Color picker: keep the popup in place while the color changes The picker's R, G and B values were its widest row, so the popup grew and shrank as they gained or lost digits; anchored at the right edge of the Properties panel, the whole picker slid sideways under the cursor. The square and hue slider are now wider than that row at any value. Fixes #93. --- crates/ui-egui/src/widgets.rs | 2 ++ crates/ui-egui/tests/color_picker.rs | 35 ++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 crates/ui-egui/tests/color_picker.rs diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index ae9f5981..eb9469e8 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -208,6 +208,8 @@ pub fn color_swatch(ui: &mut Ui, id: &str, linear: &mut [f32; 3], width: f32) -> let mut changed = false; // Open state lives in memory (`toggle_id` above); `from_response` alone shows it always. egui::Popup::from_response(&resp).id(popup).open_memory(None).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + // Wider than the R, G, B row at any value, so the popup keeps one size and place. + ui.spacing_mut().slider_width = 275.0; if egui::color_picker::color_picker_color32(ui, &mut c, egui::color_picker::Alpha::Opaque) { let lin = [c.r(), c.g(), c.b()].map(|v| texturecraft_engine::texel::srgb_to_linear(v as f32 / 255.0)); *linear = lin; diff --git a/crates/ui-egui/tests/color_picker.rs b/crates/ui-egui/tests/color_picker.rs new file mode 100644 index 00000000..dd9bbf53 --- /dev/null +++ b/crates/ui-egui/tests/color_picker.rs @@ -0,0 +1,35 @@ +//! The color picker popup keeps its place while the color changes. + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_ui_egui::{theme, widgets}; + +/// The left edge of the picker's R value. +fn r_left(h: &Harness<'_, [f32; 3]>) -> f32 { + h.get_all_by_role(Role::SpinButton).next().unwrap().rect().left() +} + +#[test] +fn the_popup_stays_put_while_the_color_changes() { + // A swatch at the right edge of the window, like the Properties panel's. + // The picker's copy button is an emoji the bundled fonts do not draw. + let mut h = Harness::builder().with_size(egui::vec2(800.0, 600.0)).allow_missing_glyphs().build_ui_state( + |ui, color: &mut [f32; 3]| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| { + widgets::color_swatch(ui, "color", color, 120.0); + }); + }, + [1.0; 3], + ); + theme::apply(&h.ctx, theme::Brightness::default(), theme::Accent::default()); + h.run_steps(2); + let swatch = egui::pos2(800.0 - 60.0, 9.0); + h.drag_at(swatch); + h.drop_at(swatch); + h.run_steps(3); + let bright = r_left(&h); + *h.state_mut() = [0.001; 3]; + h.run_steps(3); + assert_eq!(r_left(&h), bright, "the picker does not move when R, G and B lose digits"); +} From 8b3cd4db7fd836720f5ecbef33248a2e168a34ff Mon Sep 17 00:00:00 2001 From: Agapenordev <120006055+Agapenordev@users.noreply.github.com> Date: Mon, 2 Nov 2026 01:50:07 +0100 Subject: [PATCH 36/60] Toasts fit the window; a sticky one can always be dismissed Review: the text wrapped at the full width with the dismiss button after it, so on a narrow window the toast spilled past the screen edge, and a long notice could grow taller than the window and clip its button. Toasts are now at most the window's width (and 360 points), the text wraps in the width the button leaves and scrolls past a share of the window's height, and long texture set names are shortened in the GPU memory notice. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 19 ++++++++++++++++--- crates/ui-egui/src/viewport.rs | 8 +++++++- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6b89dbb6..a4c368da 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -483,6 +483,11 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { } let tk = theme::Tokens::get(ctx); let mut dismissed = None; + // Toasts fit the window: at most 360 points wide and, for their text, a part of its height + // (longer text scrolls), so a sticky toast's dismiss button always stays on screen. + let screen = ctx.content_rect().size(); + let max_width = (screen.x - 52.0).clamp(120.0, 360.0); + let max_text_height = (screen.y * 0.35).clamp(48.0, 220.0); egui::Area::new(egui::Id::unique("toasts")).anchor(egui::Align2::RIGHT_BOTTOM, egui::vec2(-16.0, -36.0)).show(ctx, |ui| { for (i, t) in app.toasts.iter().enumerate() { egui::Frame::NONE @@ -492,10 +497,18 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { .shadow(ui.visuals().popup_shadow) .inner_margin(egui::Margin::symmetric(10, 6)) .show(ui, |ui| { - ui.set_max_width(360.0); + ui.set_max_width(max_width); + let sticky = t.until.is_infinite(); ui.horizontal_top(|ui| { - ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap()); - if t.until.is_infinite() && widgets::icon_button(ui, egui_phosphor::regular::X, i18n::tr("Dismiss"), false, 18.0).clicked() { + // The text wraps in the width the dismiss button leaves. + let width = if sticky { max_width - 28.0 } else { max_width }; + ui.allocate_ui_with_layout(egui::vec2(width, 0.0), egui::Layout::top_down(egui::Align::Min), |ui| { + egui::ScrollArea::vertical().id_salt(("toast", i)).max_height(max_text_height).show(ui, |ui| { + ui.set_max_width(width); + ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap()); + }); + }); + if sticky && widgets::icon_button(ui, egui_phosphor::regular::X, i18n::tr("Dismiss"), false, 18.0).clicked() { dismissed = Some(i); } }); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index cd5f288c..3535965d 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -118,7 +118,11 @@ fn gpu_report_toasts(app: &mut TextureCraftApp, reports: crate::gpu::GpuReports) &[("name", one)], ), many => { - let mut list = many.iter().take(MAX_NAMED_SETS).map(|n| format!("\"{n}\"")).collect::>().join(", "); + let short = |n: &String| match n.char_indices().nth(MAX_NAME_CHARS) { + Some((cut, _)) => format!("\"{}...\"", &n[..cut]), + None => format!("\"{n}\""), + }; + let mut list = many.iter().take(MAX_NAMED_SETS).map(short).collect::>().join(", "); if many.len() > MAX_NAMED_SETS { list.push_str(", ..."); } @@ -141,6 +145,8 @@ fn gpu_report_toasts(app: &mut TextureCraftApp, reports: crate::gpu::GpuReports) /// Texture sets a GPU memory notice names before "...". const MAX_NAMED_SETS: usize = 5; +/// Characters of a set name in that notice (long names are cut, with "..."). +const MAX_NAME_CHARS: usize = 32; /// This frame's scene sync (compositing and GPU uploads), run by the first view drawn, after /// that view handled its input: a stroke shows in the frame it is painted, not the next. From 3fea0f6c620424c2651b261973fa4bcec13aef17 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 07:53:46 +0700 Subject: [PATCH 37/60] Materials: twill for denim and carbon fiber, a pile for velvet Carbon Fiber, Fabric Cotton, Denim and Velvet were all the same plain weave in different colours. A new Twill weave pattern (2/2: diagonal ribs, the weft darker than the warp) now gives Denim its diagonal and Carbon Fiber its light and dark tows under a clear coat; Velvet is a soft pile with no weave under its sheen; Fabric Cotton keeps the plain weave. Twill weave is also a fill pattern, translated into all nine other UI languages. Fixes #97. --- crates/compose/src/pattern.rs | 30 +++++++++++++++++++++++++----- crates/core/src/layer.rs | 6 +++++- crates/engine/src/materials.rs | 19 +++++++++++++------ crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + docs/features.md | 2 +- 13 files changed, 53 insertions(+), 13 deletions(-) diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs index e03685b7..9ca2a3da 100644 --- a/crates/compose/src/pattern.rs +++ b/crates/compose/src/pattern.rs @@ -67,17 +67,22 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 { let d = f.x.min(1.0 - f.x).min(f.y.min(1.0 - f.y)); smoothstep(0.015, 0.035, d) * (0.9 + 0.1 * noise::cell_hash(c.x as i32, c.y as i32, 0, seed)) } - ProceduralKind::Weave => { - // Plain weave: in each cell the thread on top alternates (warp along X, weft along Y); - // the top thread shows its round cross-section, bulging mid-span. + ProceduralKind::Weave | ProceduralKind::Twill => { + // Warp along X, weft along Y: in each cell the thread on top shows its round + // cross-section, bulging mid-span. A plain weave alternates every cell; a 2/2 twill + // floats over two cells and steps one cell per row, so the floats line up in diagonal + // ribs, the weft darker than the warp. let c = (p * 2.0).floor(); let f = p * 2.0 - c; let pi = std::f32::consts::PI; - let warp_on_top = (c.x as i32 + c.y as i32).rem_euclid(2) == 0; + let twill = kind == ProceduralKind::Twill; + let (period, warp_cells) = if twill { (4, 2) } else { (2, 1) }; + let warp_on_top = (c.x as i32).wrapping_add(c.y as i32).rem_euclid(period) < warp_cells; let (across, along) = if warp_on_top { (f.y, f.x) } else { (f.x, f.y) }; let thread = (pi * across).sin().max(0.0).sqrt() * (0.8 + 0.2 * (pi * along).sin()); + let tone = if twill && !warp_on_top { 0.55 } else { 1.0 }; let fiber = noise::value([p.x * 40.0, p.y * 40.0, p.z], seed); - (thread * (0.88 + 0.12 * fiber)).clamp(0.0, 1.0) + (thread * tone * (0.88 + 0.12 * fiber)).clamp(0.0, 1.0) } ProceduralKind::Leather => { let w = noise::perlin((p * 0.7).to_array(), seed ^ 0x2D) - 0.5; @@ -351,6 +356,21 @@ mod tests { assert!(decal_uv(&Decal { size: [f32::NAN; 2], ..d }, Vec3::ZERO, z).is_none()); } + #[test] + fn twill_floats_run_in_diagonal_ribs() { + // The value at the centre of cell (x, y); cells are half a unit. + let at = |k, x: i32, y: i32| raw(k, Vec3::new(x as f32 * 0.5 + 0.25, y as f32 * 0.5 + 0.25, 0.0), 3); + for y in 1..8 { + let warp: Vec = (0..8).map(|x| at(ProceduralKind::Twill, x, y) > 0.7).collect(); + assert_eq!(warp.iter().filter(|w| **w).count(), 4, "row {y}: half the floats are warp"); + for x in 0..7 { + assert_eq!(warp[x as usize], at(ProceduralKind::Twill, x + 1, y - 1) > 0.7, "the rib continues diagonally at ({x}, {y})"); + } + } + // A plain weave shows every top thread alike. + assert!((0..8).all(|x| at(ProceduralKind::Weave, x, 0) > 0.7)); + } + #[test] fn every_pattern_varies() { for k in ProceduralKind::ALL { diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index ca558a8d..12671b85 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -228,6 +228,8 @@ pub enum ProceduralKind { Tiles, /// Plain fabric weave. Weave, + /// 2/2 twill: diagonal ribs, the warp brighter than the weft (denim, carbon fiber). + Twill, /// Leather grain: pebbled cells with creases. Leather, /// Hammered metal dimples. @@ -249,7 +251,7 @@ pub enum ProceduralKind { } impl ProceduralKind { - pub const ALL: [ProceduralKind; 22] = [ + pub const ALL: [ProceduralKind; 23] = [ ProceduralKind::Clouds, ProceduralKind::Perlin, ProceduralKind::Noise, @@ -263,6 +265,7 @@ impl ProceduralKind { ProceduralKind::Bricks, ProceduralKind::Tiles, ProceduralKind::Weave, + ProceduralKind::Twill, ProceduralKind::Leather, ProceduralKind::Hammered, ProceduralKind::Brushed, @@ -288,6 +291,7 @@ impl ProceduralKind { ProceduralKind::Bricks => "Bricks", ProceduralKind::Tiles => "Tiles", ProceduralKind::Weave => "Fabric weave", + ProceduralKind::Twill => "Twill weave", ProceduralKind::Leather => "Leather grain", ProceduralKind::Hammered => "Hammered", ProceduralKind::Brushed => "Brushed lines", diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index 0863dbcc..18c54577 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -357,15 +357,21 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { "plastic_glossy" | "plastic_matte" | "ceramic" => one(b, dielectric(rgb(m.base), clouds_rough(9))), "plastic_textured" => one(b, plus(dielectric(rgb(m.base), gray(P::Leather, 40.0, 5, 0.66, 0.5)), height(gray(P::Leather, 40.0, 5, -0.01, 0.0)))), "rubber" => one(b, dielectric(pat(P::Noise, 0.5, 3, 1.0, [0.025; 3], [0.035; 3]), gray(P::Noise, 0.5, 3, 0.84, 0.94))), - "carbon_fiber" => { - one(b, plus(dielectric(pat(P::Weave, 24.0, 1, 1.0, [0.01, 0.01, 0.012], [0.06, 0.06, 0.065]), u(r)), height(gray(P::Weave, 24.0, 1, 0.0, 0.006)))) - } + // Twill-woven tows under a clear coat: the warp catches the light, the weft stays dark. + "carbon_fiber" => one( + b, + plus( + dielectric(pat(P::Twill, 12.0, 1, 1.0, [0.004, 0.004, 0.005], [0.08, 0.08, 0.085]), gray(P::Twill, 12.0, 1, 0.5, 0.28)), + [(CoatWeight, u(1.0)), (CoatRoughness, u(r * 0.2)), (Height, gray(P::Twill, 12.0, 1, 0.0, 0.002))], + ), + ), // ---- Fabric and leather ------------------------------------------------------------- "fabric" => { one(b, plus(dielectric(pat(P::Weave, 18.0, 2, 1.0, [0.27, 0.29, 0.34], [0.6, 0.62, 0.7]), u(r)), height(gray(P::Weave, 18.0, 2, -0.01, 0.0)))) } + // Indigo twill: diagonal ribs. "denim" => { - one(b, plus(dielectric(pat(P::Weave, 22.0, 5, 1.0, [0.02, 0.03, 0.08], [0.12, 0.16, 0.3]), u(r)), height(gray(P::Weave, 22.0, 5, -0.01, 0.0)))) + one(b, plus(dielectric(pat(P::Twill, 22.0, 5, 1.0, [0.015, 0.025, 0.07], [0.15, 0.2, 0.38]), u(r)), height(gray(P::Twill, 22.0, 5, -0.01, 0.0)))) } "leather" => one( b, @@ -384,8 +390,9 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { "velvet" => one( b, plus( - dielectric(pat(P::Weave, 30.0, 3, 1.0, [0.07, 0.008, 0.05], m.base), u(r)), - [(SheenWeight, u(1.0)), (SheenColor, rgb([0.95, 0.55, 0.85])), (SheenRoughness, u(0.35)), (Height, gray(P::Weave, 30.0, 3, -0.004, 0.0))], + // A pile, not a weave: soft crushed patches under a bright sheen. + dielectric(pat(P::Clouds, 3.0, 3, 1.0, [0.06, 0.006, 0.045], m.base), u(r)), + [(SheenWeight, u(1.0)), (SheenColor, rgb([0.95, 0.55, 0.85])), (SheenRoughness, u(0.35)), (Height, gray(P::Noise, 1.0, 3, -0.002, 0.0))], ), ), // ---- Coated and translucent --------------------------------------------------------- diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 5fb79fb2..d2955ba2 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -944,4 +944,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert show/hide", "عكس الإظهار/الإخفاء"), ("Show or hide texture sets", "إظهار مجموعات الخامات أو إخفاؤها"), ("Focus: show only the active texture set", "تركيز: إظهار مجموعة الخامات النشطة فقط"), + ("Twill weave", "نسيج مائل"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index e2d9ed89..e6be33c2 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -999,4 +999,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert show/hide", "Ein-/Ausblenden umkehren"), ("Show or hide texture sets", "Texturesets ein- oder ausblenden"), ("Focus: show only the active texture set", "Fokus: nur das aktive Textureset zeigen"), + ("Twill weave", "Köperbindung"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index e9927174..2e5cebf6 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -984,4 +984,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert show/hide", "Invertir mostrar/ocultar"), ("Show or hide texture sets", "Mostrar u ocultar conjuntos de texturas"), ("Focus: show only the active texture set", "Enfoque: mostrar solo el conjunto de texturas activo"), + ("Twill weave", "Tejido de sarga"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 92f25811..1de8d2bc 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -999,4 +999,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert show/hide", "Inverser afficher/masquer"), ("Show or hide texture sets", "Afficher ou masquer les ensembles de textures"), ("Focus: show only the active texture set", "Focus : n'afficher que l'ensemble de textures actif"), + ("Twill weave", "Armure sergé"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 9c71748f..5199e099 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -993,4 +993,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert show/hide", "Inverti mostra/nascondi"), ("Show or hide texture sets", "Mostra o nascondi i set di texture"), ("Focus: show only the active texture set", "Focus: mostra solo il set di texture attivo"), + ("Twill weave", "Tessuto a saia"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index c3d9ccad..1ba0636f 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -966,4 +966,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert show/hide", "表示/非表示を反転"), ("Show or hide texture sets", "テクスチャセットの表示/非表示"), ("Focus: show only the active texture set", "フォーカス: アクティブなテクスチャセットのみ表示"), + ("Twill weave", "綾織り"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 6182b57a..7ad33529 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -951,4 +951,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert show/hide", "표시/숨기기 반전"), ("Show or hide texture sets", "텍스처 세트 표시 또는 숨기기"), ("Focus: show only the active texture set", "포커스: 활성 텍스처 세트만 표시"), + ("Twill weave", "능직"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index a430655c..3aba606d 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -981,4 +981,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert show/hide", "Inverter mostrar/ocultar"), ("Show or hide texture sets", "Mostrar ou ocultar conjuntos de texturas"), ("Focus: show only the active texture set", "Foco: mostrar só o conjunto de texturas ativo"), + ("Twill weave", "Tecido sarja"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index e1fc3780..7e076f1d 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -897,4 +897,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert show/hide", "反转显示/隐藏"), ("Show or hide texture sets", "显示或隐藏纹理集"), ("Focus: show only the active texture set", "聚焦:仅显示当前纹理集"), + ("Twill weave", "斜纹织物"), ]; diff --git a/docs/features.md b/docs/features.md index 76289221..5e7c4d27 100644 --- a/docs/features.md +++ b/docs/features.md @@ -43,7 +43,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA gradients, all with world-space noise), filters, ID color selection and compare. Alt+click a mask to view it alone. - **Fill layers** take uniform values, **22 procedurals** (clouds, cells, grunge, scratches, wood - grain, bricks, fabric weave, leather grain, marble veins, Voronoi, paint chips…) or your own + grain, bricks, fabric weave, twill, leather grain, marble veins, Voronoi, paint chips…) or your own **images**, through UV, tri-planar, planar, spherical, cylindrical or decal projection. Alt+click a material channel (of a fill or the brush) to keep that channel alone. - **54 materials** (metals from measured reflectance, car paint, brushed anisotropic steel, From 8efd62aeaae5e689c42c8d4d83fc04c876e4f738 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 07:59:35 +0700 Subject: [PATCH 38/60] Viewport: no ghost edges in the subsurface blur Skin and other scattering materials showed copies of the silhouette running parallel to it: the blur's taps sit pixels apart when the mean free path is wide on screen, and a tap that left the mesh dropped out of the sum, so the light stepped at every tap spacing from the edge. Taps are now shifted per pixel and per accumulated frame, and a tap across a depth discontinuity takes the centre's light instead of dropping out. Fixes #86. --- crates/render/src/renderer.rs | 2 +- crates/render/src/shaders/fx.wgsl | 16 +++++++++++----- crates/render/src/shaders/post.wgsl | 2 +- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 60a8c39c..b09036e4 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -1584,7 +1584,7 @@ impl Renderer { b: [fx(s.vignette), fx(s.sharpen), fx(s.grain), BLOOM_THRESHOLD], c: dof_c, d: sss_d, - e: [flag(cam.ortho), 0.0, 0.0, 0.0], + e: [flag(cam.ortho), sample as f32, 0.0, 0.0], }; let Some(v) = self.targets(device, frame.view_id, frame.size, bloom, fx_on, refraction) else { return }; queue.write_buffer(&v.globals, 0, bytemuck::bytes_of(&raw)); diff --git a/crates/render/src/shaders/fx.wgsl b/crates/render/src/shaders/fx.wgsl index cdd3963c..333664ce 100644 --- a/crates/render/src/shaders/fx.wgsl +++ b/crates/render/src/shaders/fx.wgsl @@ -22,7 +22,8 @@ fn texel_at(t: texture_2d, p: vec2) -> vec4 { // ---- Subsurface scattering: a separable bilateral blur (Jimenez et al., "Separable Subsurface // Scattering", 2015) of the scattering diffuse light, a Gaussian per color channel as wide as -// its mean free path, cut off across depth discontinuities. +// its mean free path. A tap across a depth discontinuity (or off the mesh) takes the centre's +// light instead, so no tap drops out of the sum as it crosses a silhouette. const SSS_TAPS: i32 = 8; @@ -41,17 +42,22 @@ fn sss_blur(p: vec2, dir: vec2) -> vec4 { let stride = dir * (smax * 3.0 / f32(SSS_TAPS)); let depth_range = 3.0 * max(post.d.x, max(post.d.y, post.d.z)); let inv = 1.0 / (2.0 * sigma * sigma + vec3(1e-4)); + // Wide blurs space their taps pixels apart: shifting them per pixel (interleaved gradient + // noise) and per accumulated frame turns what would show as copies of edges into fine grain. + let ign = fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); + let jitter = fract(ign + post.e.y * 0.618034) - 0.5; var sum = c.rgb; var wsum = vec3(1.0); for (var k = -SSS_TAPS; k <= SSS_TAPS; k++) { if (k == 0) { continue; } - let t = texel_at(src, p + stride * f32(k)); - let x = f32(k) * smax * 3.0 / f32(SSS_TAPS); + let o = f32(k) + jitter; + let t = texel_at(src, p + stride * o); + let x = o * smax * 3.0 / f32(SSS_TAPS); let wd = select(0.0, max(1.0 - abs(t.a - c.a) / depth_range, 0.0), t.a > 0.0); - let w = exp(-x * x * inv) * wd; - sum += t.rgb * w; + let w = exp(-x * x * inv); + sum += mix(c.rgb, t.rgb, wd) * w; wsum += w; } return vec4(sum / wsum, c.a); diff --git a/crates/render/src/shaders/post.wgsl b/crates/render/src/shaders/post.wgsl index 7a0c7d62..6eb30868 100644 --- a/crates/render/src/shaders/post.wgsl +++ b/crates/render/src/shaders/post.wgsl @@ -7,7 +7,7 @@ struct Post { b: vec4, // x vignette, y sharpen, z grain, w bloom threshold c: vec4, // depth of field (fx.wgsl): x circle of confusion at infinity (pixels), y focus depth, z largest circle radius (pixels), w accumulation sample d: vec4, // subsurface blur (fx.wgsl): xyz mean free path per channel (world units), w pixels per world unit at depth 1 - e: vec4, // x orthographic camera (1: pixels per world unit don't fall off with depth), yzw - + e: vec4, // x orthographic camera (1: pixels per world unit don't fall off with depth), y accumulation sample, zw - }; @group(0) @binding(3) var post: Post; From 98e282b70d0f0d25e9ba9d50bc8178f73e370a68 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 08:10:21 +0700 Subject: [PATCH 39/60] Polygon fill: UV island mode follows the UVs across split vertices UV island fill grew the island through shared vertex indices. Imported meshes often split vertices along hard edges, or give every face its own, while the UVs run on; the fill then stopped at single polygons. Triangles that share an edge in UV space now form the island. Fixes #51. --- crates/engine/src/painting.rs | 58 +++++++++++++++++++++++++++-------- 1 file changed, 46 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 741fac6c..9d58ce3f 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -483,13 +483,18 @@ impl Session { FillMode::Triangle => [tri].into_iter().collect(), FillMode::Mesh => m.triangles_of(material).map(|t| t as u32).collect(), FillMode::UvIsland => { - // Triangles sharing vertex indices form a UV island (seams split vertices). - let mut by_vertex: BTreeMap> = BTreeMap::new(); + // Triangles sharing an edge in UV space form a UV island: imported meshes often + // split vertices along hard edges (or per face) where the UVs run on, so shared + // vertex indices alone break an island into its polygons. + let corner = |i: usize| m.uvs.get(i).map(|uv| [(uv.x * 1e5).round() as i64, (uv.y * 1e5).round() as i64]); + let edges = |t: usize| match m.tri(t).map(|v| v.map(corner)) { + Some([Some(a), Some(b), Some(c)]) => [(a, b), (b, c), (c, a)].map(|(p, q)| (p.min(q), p.max(q))).to_vec(), + _ => Vec::new(), + }; + let mut by_edge: BTreeMap<_, Vec> = BTreeMap::new(); for t in m.triangles_of(material) { - if let Some(v) = m.tri(t) { - for i in v { - by_vertex.entry(i).or_default().push(t as u32); - } + for e in edges(t) { + by_edge.entry(e).or_default().push(t as u32); } } let mut seen = BTreeSet::new(); @@ -498,12 +503,10 @@ impl Session { if !seen.insert(t) { continue; } - if let Some(v) = m.tri(t as usize) { - for i in v { - for n in by_vertex.get(&i).map(Vec::as_slice).unwrap_or(&[]) { - if !seen.contains(n) { - stack.push(*n); - } + for e in edges(t as usize) { + for n in by_edge.get(&e).map(Vec::as_slice).unwrap_or(&[]) { + if !seen.contains(n) { + stack.push(*n); } } } @@ -573,3 +576,34 @@ fn with_commit_source( let carried = st.canvas.pickup.as_ref().map(|p| &p.values); f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried }) } + +#[cfg(test)] +mod tests { + use texturecraft_geom::glam::{Vec2, Vec3}; + use texturecraft_geom::mesh::Mesh; + use texturecraft_geom::primitives; + + use crate::session::{FillMode, Session}; + + #[test] + fn uv_island_fill_follows_uvs_across_split_vertices() { + // Two copies of a plane, each triangle with its own three vertices (as hard edges or + // per-face imports leave a mesh), the second copy apart in UV space. + let plane = primitives::plane(2.0, 4); + let (mut positions, mut uvs) = (Vec::::new(), Vec::::new()); + for shift in [0.0, 0.5] { + for i in plane.indices.iter().map(|i| *i as usize) { + positions.push(plane.positions[i] + Vec3::Y * shift); + uvs.push(plane.uvs[i] * 0.5 + shift); + } + } + let indices = (0..positions.len() as u32).collect(); + let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap(); + let n = plane.triangle_count(); + assert_eq!(mesh.vertex_count(), 6 * n, "no vertex is shared"); + let mut s = Session::new_project("t", mesh, "test", None, 128).unwrap(); + s.tool.fill_mode = FillMode::UvIsland; + assert_eq!(s.fill_set(0, 0).len(), n, "the whole first island"); + assert_eq!(s.fill_set(n as u32, 0).len(), n, "only the second island"); + } +} From f48d5b6ba41dc080ec4de9386712bd0f46503475 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 08:24:29 +0700 Subject: [PATCH 40/60] Ask to save before opening, starting or closing another project New project, Open, a recent project, a dropped file, Open sample project and Close replaced a project with unsaved changes without a word. They now wait on the same Save / Don't save / Cancel dialog as quitting, and go ahead once the changes are saved or let go. --- crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/menus.rs | 6 +++ crates/ui-egui/src/state.rs | 14 ++++++- crates/ui-egui/src/windows.rs | 54 +++++++++++++++++++-------- crates/ui-egui/tests/close_unsaved.rs | 28 +++++++++++--- docs/features.md | 5 ++- 14 files changed, 91 insertions(+), 25 deletions(-) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 9ce7ad03..9038f41e 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -947,4 +947,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "تغييرات غير محفوظة"), ("Don't save", "عدم الحفظ"), ("Save the changes to {name} before closing?", "هل تريد حفظ التغييرات في {name} قبل الإغلاق؟"), + ("Save the changes to {name} first?", "هل تريد حفظ التغييرات في {name} أولًا؟"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index eb50e2ff..33a659a9 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1002,4 +1002,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "Ungespeicherte Änderungen"), ("Don't save", "Nicht speichern"), ("Save the changes to {name} before closing?", "Änderungen an {name} vor dem Schließen speichern?"), + ("Save the changes to {name} first?", "Änderungen an {name} zuerst speichern?"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index c415b5f9..2622b67d 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -987,4 +987,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "Cambios sin guardar"), ("Don't save", "No guardar"), ("Save the changes to {name} before closing?", "¿Guardar los cambios de {name} antes de cerrar?"), + ("Save the changes to {name} first?", "¿Guardar primero los cambios de {name}?"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 404f7451..5e95e20c 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1002,4 +1002,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "Modifications non enregistrées"), ("Don't save", "Ne pas enregistrer"), ("Save the changes to {name} before closing?", "Enregistrer les modifications de {name} avant de fermer ?"), + ("Save the changes to {name} first?", "Enregistrer d'abord les modifications de {name} ?"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 3734112b..769fe223 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -996,4 +996,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "Modifiche non salvate"), ("Don't save", "Non salvare"), ("Save the changes to {name} before closing?", "Salvare le modifiche a {name} prima di chiudere?"), + ("Save the changes to {name} first?", "Salvare prima le modifiche a {name}?"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 62e3f15b..523048f0 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -969,4 +969,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "未保存の変更"), ("Don't save", "保存しない"), ("Save the changes to {name} before closing?", "閉じる前に {name} の変更を保存しますか?"), + ("Save the changes to {name} first?", "先に {name} の変更を保存しますか?"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index d8b614f5..ca38a29d 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -954,4 +954,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "저장되지 않은 변경 사항"), ("Don't save", "저장 안 함"), ("Save the changes to {name} before closing?", "닫기 전에 {name}의 변경 사항을 저장할까요?"), + ("Save the changes to {name} first?", "먼저 {name}의 변경 사항을 저장할까요?"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 9d1d9523..47807f08 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -984,4 +984,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "Alterações não salvas"), ("Don't save", "Não salvar"), ("Save the changes to {name} before closing?", "Salvar as alterações em {name} antes de fechar?"), + ("Save the changes to {name} first?", "Salvar primeiro as alterações em {name}?"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index c62467da..9b6144f4 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -900,4 +900,5 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "未保存的更改"), ("Don't save", "不保存"), ("Save the changes to {name} before closing?", "关闭前是否保存对 {name} 的更改?"), + ("Save the changes to {name} first?", "是否先保存对 {name} 的更改?"), ]; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 6cf976a1..d5e5fe3c 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -117,6 +117,12 @@ pub fn implemented(id: &str) -> bool { /// Invoke a menu item (menus, shortcuts, palette, control channel `ui.menu.invoke`). pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { + #[cfg(not(target_arch = "wasm32"))] + if matches!(id, "ui.newProject" | "file.open" | "file.close" | "project.sample") + && crate::windows::ask_to_save(app, crate::state::Unsaved::Command(id.into())) + { + return; + } if let Some(panel) = crate::docking::view_panel(id) { app.ui.dock.toggle(panel); return; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 6670c608..ef0ab709 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -76,9 +76,19 @@ pub struct Windows { /// The start window: new, open, recent projects (the app opens it at launch). #[serde(skip)] pub start: bool, - /// Closing with unsaved changes: save, don't save or cancel (desktop). + /// What waits on the unsaved-changes dialog: save, don't save or cancel (desktop). #[serde(skip)] - pub confirm_close: bool, + pub unsaved: Option, +} + +/// An action that replaces or ends the project, held while the project has unsaved changes. +#[derive(Clone, Debug, PartialEq)] +pub enum Unsaved { + Quit, + /// A menu command (New project, Open, Close, Open sample project). + Command(String), + /// Open this project or mesh file. + Open(String), } /// Edit › Settings. diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 8a8ba0b6..68fd1214 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -30,24 +30,35 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { bake_bar(app, ctx); } #[cfg(not(target_arch = "wasm32"))] - confirm_close(app, ctx); + unsaved(app, ctx); } -/// Closing the app with unsaved changes asks whether to save them first. +/// Hold `then` (quitting, opening or closing a project) behind the unsaved-changes dialog when +/// the project has unsaved changes; false when it can go ahead now. #[cfg(not(target_arch = "wasm32"))] -fn confirm_close(app: &mut TextureCraftApp, ctx: &egui::Context) { - if app.session.modified && ctx.input(|i| i.viewport().close_requested()) { +pub(crate) fn ask_to_save(app: &mut TextureCraftApp, then: crate::state::Unsaved) -> bool { + if app.session.modified { + app.ui.windows.unsaved = Some(then); + } + app.session.modified +} + +/// Quitting, opening or closing a project with unsaved changes asks whether to save them first. +#[cfg(not(target_arch = "wasm32"))] +fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { + use crate::state::Unsaved; + if ctx.input(|i| i.viewport().close_requested()) && ask_to_save(app, Unsaved::Quit) { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); - app.ui.windows.confirm_close = true; - } - if !app.ui.windows.confirm_close { - return; } + let Some(then) = app.ui.windows.unsaved.clone() else { return }; let mut open = true; let mut save = None; let mut cancel = false; - dialog("confirm_close", tr("Unsaved changes"), &mut open).show(ctx, |ui| { - ui.label(trf("Save the changes to {name} before closing?", &[("name", &app.session.doc.project.name)])); + let name: [(&str, &dyn std::fmt::Display); 1] = [("name", &app.session.doc.project.name)]; + let question = + if then == Unsaved::Quit { trf("Save the changes to {name} before closing?", &name) } else { trf("Save the changes to {name} first?", &name) }; + dialog("unsaved", tr("Unsaved changes"), &mut open).show(ctx, |ui| { + ui.label(question); ui.add_space(8.0); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui.add(primary_button(ui, tr("Save"))).clicked() { @@ -61,19 +72,26 @@ fn confirm_close(app: &mut TextureCraftApp, ctx: &egui::Context) { } }); }); - app.ui.windows.confirm_close = open && !cancel; + if !open || cancel { + app.ui.windows.unsaved = None; + } match save { Some(true) => { file_action(app, ctx, "file.save"); } - // Closing anyway: the changes are let go. + // Going ahead anyway: the changes are let go. Some(false) => app.session.modified = false, None => return, } - // A cancelled or failed save keeps the app and this dialog open. - if !app.session.modified { - app.ui.windows.confirm_close = false; - ctx.send_viewport_cmd(egui::ViewportCommand::Close); + // A cancelled or failed save keeps the project and this dialog open. + if app.session.modified { + return; + } + app.ui.windows.unsaved = None; + match then { + Unsaved::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close), + Unsaved::Command(id) => crate::menus::invoke(app, ctx, &id), + Unsaved::Open(path) => open_path(app, &path), } } @@ -1045,6 +1063,10 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> /// Open a project or mesh by path (menus, Recent projects, drag and drop). #[cfg(not(target_arch = "wasm32"))] pub fn open_path(app: &mut TextureCraftApp, path: &str) { + #[cfg(not(target_arch = "wasm32"))] + if ask_to_save(app, crate::state::Unsaved::Open(path.into())) { + return; + } if app.run("file.open", json!({"path": path})).is_some() { remember(app, path); app.ui.mode = Mode::Painting; diff --git a/crates/ui-egui/tests/close_unsaved.rs b/crates/ui-egui/tests/close_unsaved.rs index 88811700..468634cc 100644 --- a/crates/ui-egui/tests/close_unsaved.rs +++ b/crates/ui-egui/tests/close_unsaved.rs @@ -1,9 +1,11 @@ -//! Closing the app with unsaved changes asks whether to save them first. +//! Closing the app, or opening or closing a project, with unsaved changes asks whether to save +//! them first. use egui::{ViewportCommand, ViewportEvent, ViewportId}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::Unsaved; fn harness(modified: bool) -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); @@ -31,11 +33,11 @@ fn closing_with_changes_asks_and_dont_save_closes() { request_close(&mut h); assert!(sent(&h, &ViewportCommand::CancelClose), "the close waits for an answer"); h.run_steps(2); - assert!(h.state().ui.windows.confirm_close, "the dialog is open"); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the dialog is open"); h.get_by_label("Don't save").click(); h.step(); assert!(sent(&h, &ViewportCommand::Close), "Don't save closes the app"); - assert!(!h.state().ui.windows.confirm_close); + assert!(h.state().ui.windows.unsaved.is_none()); } #[test] @@ -46,7 +48,7 @@ fn cancel_keeps_the_app_open() { h.get_by_label("Cancel").click(); h.step(); assert!(!sent(&h, &ViewportCommand::Close)); - assert!(!h.state().ui.windows.confirm_close, "Cancel closes the dialog"); + assert!(h.state().ui.windows.unsaved.is_none(), "Cancel closes the dialog"); assert!(h.state().session.modified, "and keeps the changes"); } @@ -55,5 +57,21 @@ fn closing_without_changes_does_not_ask() { let mut h = harness(false); request_close(&mut h); assert!(!sent(&h, &ViewportCommand::CancelClose)); - assert!(!h.state().ui.windows.confirm_close); + assert!(h.state().ui.windows.unsaved.is_none()); +} + +#[test] +fn closing_the_project_with_changes_asks_first() { + let mut h = harness(true); + h.state_mut().session.doc.project.name = "Edited".into(); + let name = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.name.clone(); + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "file.close"); + h.run_steps(4); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Command("file.close".into())), "the dialog is open"); + assert_eq!(name(&h), "Edited", "the project stays until answered"); + h.get_by_label("Don't save").click(); + h.run_steps(2); + assert_ne!(name(&h), "Edited", "Don't save closes the project"); + assert!(h.state().ui.windows.unsaved.is_none() && !h.state().session.modified); } diff --git a/docs/features.md b/docs/features.md index 1408a242..44d5b4de 100644 --- a/docs/features.md +++ b/docs/features.md @@ -67,8 +67,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA channel types to add or remove. Show, hide or invert them all at once, or **focus** on the active one. - **Projects** are a single `.tcraft` file: the mesh, every layer (sparse and lossless), baked maps - and imported images. **Project templates** start new work from a saved setup. Closing the app - with unsaved changes asks whether to save them first. + and imported images. **Project templates** start new work from a saved setup. Closing the app, + or opening, starting or closing another project, with unsaved changes asks whether to save them + first. ## Bake and export From 4f8a2f0828cbf39b85571e7edfaa41898719fd6a Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 08:28:30 +0700 Subject: [PATCH 41/60] Docs: roadmap after the issue fixes --- ROADMAP.md | 4 ++-- docs/features.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index f9f04f38..bd816e59 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -11,11 +11,11 @@ end to end today (engine + UI + automation + tests), not what is planned. | Area | Weight | Done | What works | Main gaps | |---|---:|---:|---|---| -| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | +| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project, recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | | Texture sets | 6 | 95% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile**, one texture per tile at its own size, `$udim` export), list with visibility (show or hide all, invert, **focus** on one set), sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | Filter radii and height slopes of a tile smaller than its atlas block follow the block | | Layer stack | 16 | 96% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels, invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **27 library filters** (adjustments, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | | Painting tools | 14 | 90% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt (not exposed by the windowing layer) | -| Materials and assets | 8 | 88% | 48 procedural materials (incl. car paint, velvet, brushed steel, skin, wax), 21 smart materials, 18 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 22 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | +| Materials and assets | 8 | 88% | 48 procedural materials (incl. car paint, velvet, brushed steel, skin, wax), 21 smart materials, 18 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 23 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | | Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — | | Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, the baked normal map under the painted normal, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Hardware ray tracing | | Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — | diff --git a/docs/features.md b/docs/features.md index b863cc9b..ab63c13a 100644 --- a/docs/features.md +++ b/docs/features.md @@ -42,7 +42,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA **mesh-map generators** (edge wear, dirt, thin areas, curvature, AO, position and direction gradients, all with world-space noise), filters, ID color selection and compare. Alt+click a mask to view it alone. -- **Fill layers** take uniform values, **22 procedurals** (clouds, cells, grunge, scratches, wood +- **Fill layers** take uniform values, **23 procedurals** (clouds, cells, grunge, scratches, wood grain, bricks, fabric weave, twill, leather grain, marble veins, Voronoi, paint chips…) or your own **images**, through UV, tri-planar, planar, spherical, cylindrical or decal projection. Alt+click a material channel (of a fill or the brush) to keep that channel alone. From d736ffa9af65c53f6f3994ad53c1e6a7b3e6568b Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 09:23:59 +0700 Subject: [PATCH 42/60] Levels: a histogram of what the effect reads The Levels effect's properties now show a histogram of its input, the mask below it or (on layer content) a channel picked above it, with the input range marked. effect.histogram {effect, channel?, bins?} gives agents the same counts. Large sets are sampled (at most 256 tiles), so the cost stays flat up to 8K. --- crates/compose/src/eval.rs | 75 ++++++++++++++++++++++++++ crates/compose/src/lib.rs | 4 +- crates/engine/src/layer_ops.rs | 17 +----- crates/engine/src/mask_cmds.rs | 27 +++++++++- crates/engine/src/session.rs | 25 ++++++--- crates/engine/tests/content_effects.rs | 32 +++++++++++ crates/ui-egui/src/dock.rs | 35 +++++++++++- crates/ui-egui/src/widgets.rs | 25 +++++++++ crates/ui-egui/tests/effect_sliders.rs | 25 ++++++++- crates/ui-egui/tests/ui_snapshots.rs | 12 +++++ docs/control-protocol.md | 2 + docs/features.md | 3 +- 12 files changed, 255 insertions(+), 27 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 719c66d4..6ba8e33e 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1846,6 +1846,81 @@ pub fn mask_image(inp: &Inputs, id: LayerId, size: u32) -> Option> { Some(out) } +/// Tiles [`effect_histogram`] samples at most (a million texels). +const HISTOGRAM_TILES: usize = 256; + +/// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's mask +/// below it, or (a content effect) the layer's `channel` below it where the layer has content, +/// color components pooled and signed values mapped to 0..1. Over the texels the mesh covers +/// (in an even sample of tiles on large sets); None for an unknown effect. +pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: usize) -> Option> { + let (owner, _) = inp.project.effect(effect)?; + let bins = bins.max(1); + // Evaluate the layer forced visible, its mask enabled, cut just below the effect. + let mut cut = inp.project.clone(); + let l = cut.layers.get_mut(&owner)?; + l.visible = true; + let in_mask = match l.mask.as_mut().and_then(|m| m.effects.iter().position(|e| e.id == effect).map(|k| (m, k))) { + Some((m, k)) => { + m.enabled = true; + m.effects.truncate(k); + true + } + None => { + let k = l.content_effects.iter().position(|e| e.id == effect)?; + l.content_effects.truncate(k); + false + } + }; + let cut_inp = Inputs { project: &cut, preview: None, ..*inp }; + let channels = cut.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); + // An even sample of at most HISTOGRAM_TILES tiles keeps the cost flat up to 8K. + let all = all_tiles(inp.gbuf.width, inp.gbuf.height); + let tiles: Vec<(u32, u32)> = all.iter().copied().step_by(all.len().div_ceil(HISTOGRAM_TILES).max(1)).collect(); + let fields = neighbourhood_fields(&cut_inp, &channels, &tiles); + let bin = |v: f32| ((v.clamp(0.0, 1.0) * bins as f32) as usize).min(bins - 1); + let hist = tiles + .par_iter() + .map(|&(tx, ty)| { + let mut h = vec![0u32; bins]; + let nodes = plan(&cut_inp, &[owner], &channels, tx, ty, 0, Some(&fields)); + let Some(n) = nodes.first() else { return h }; + let c = n.chans.iter().find(|c| Channel::ALL.get(c.ch) == Some(&channel)); + let full = anchor_plan(&cut_inp, owner, &channels, tx, ty, Some(&fields)); + for (x, y, o) in tile_texels(inp.gbuf, tx, ty) { + let mut tex = Texel::new(&cut_inp, x, y, o, 0.0); + if !full.is_empty() { + tex.anchors_below(&full, owner); + } + if in_mask { + if let Some(m) = &n.mask + && let Some(b) = h.get_mut(bin(tex.mask(m))) + { + *b += 1; + } + } else if let Some(c) = c + && let Some((v, _)) = tex.content(&n.content, c) + { + // As levels reads them (`per_unit`); normal maps pass through levels unchanged. + let (vals, signed) = match c.kind { + ChannelKind::Color => (&v[..], false), + ChannelKind::Scalar => (&v[..1], false), + ChannelKind::Signed => (&v[..1], true), + ChannelKind::NormalMap => (&v[..0], false), + }; + for x in vals { + if let Some(b) = h.get_mut(bin(if signed { x * 0.5 + 0.5 } else { *x })) { + *b += 1; + } + } + } + } + h + }) + .reduce(|| vec![0u32; bins], |a, b| a.iter().zip(&b).map(|(x, y)| x.saturating_add(*y)).collect()); + Some(hist) +} + /// One flattened tile of one channel: (channel, tile, premultiplied value + coverage data). pub type FlatTile = (Channel, (u32, u32), Vec); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 5435acdb..5e34945c 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -16,7 +16,7 @@ pub mod store; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; pub use eval::{ - Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, flatten_layer, mask_image, - pad_tiles, + Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, + mask_image, pad_tiles, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index 8291409e..0d260063 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -194,21 +194,8 @@ impl Session { /// Layer `id` of texture set `ts` alone (content times mask) as premultiplied tiles per /// channel over the set's covered tiles. None for folders or a set not ready. pub(crate) fn flatten(&self, ts: usize, id: LayerId) -> Option> { - let cache = self.caches.get(ts)?; - let tiles: Vec<(u32, u32)> = cache.covered_tiles.iter().copied().collect(); - let empty = Default::default(); - let inputs = texturecraft_compose::Inputs { - project: &self.doc.project, - ts, - mesh: &self.mesh, - gbuf: &cache.gbuf, - pixels: &self.doc.pixels, - baked: self.doc.baked.get(&ts).unwrap_or(&empty), - preview: None, - images: &self.images, - bounds: self.mesh.bounds(), - }; - texturecraft_compose::flatten_layer(&inputs, id, &tiles) + let tiles: Vec<(u32, u32)> = self.caches.get(ts)?.covered_tiles.iter().copied().collect(); + self.with_inputs(ts, |inp| texturecraft_compose::flatten_layer(inp, id, &tiles)) } } diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 9122b158..c2a15850 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -6,7 +6,7 @@ use texturecraft_core::{ Source, }; -use crate::commands::{CommandSpec, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; +use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; use crate::layer_cmds::projection_from; use crate::session::StackTarget; use crate::{EngineError, Result, Session, cmd}; @@ -99,6 +99,15 @@ pub fn specs() -> Vec { set ), cmd!("effect.remove", "Remove effect", [], None, "{effect}", has_layer, remove_effect), + cmd!( + "effect.histogram", + "Effect input histogram", + [], + None, + "{effect, channel?: for content effects (default: the layer's first channel), bins?: 2..256 (64)} → {target: mask|content, channel?, bins: [count per bucket over 0..1]}", + always, + histogram + ), ] } @@ -373,6 +382,22 @@ fn effect_id(p: &Value, cmd: &str) -> Result { u64p(p, "effect").map(LayerId).ok_or_else(|| bad(cmd, "`effect` id is required")) } +/// The distribution of the values entering an effect (what a levels effect remaps). +fn histogram(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "effect.histogram"; + let eid = effect_id(p, CMD)?; + let (owner, _) = s.doc.project.effect(eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?; + let l = s.doc.project.layer(owner)?; + let content = l.content_effects.iter().any(|e| e.id == eid); + let channel = match channel_param(CMD, p, "channel")? { + Some(c) => c, + None => l.channels.keys().next().copied().unwrap_or(Channel::BaseColor), + }; + let bins = u64p(p, "bins").unwrap_or(64).clamp(2, 256) as usize; + let counts = s.effect_histogram(eid, channel, bins).ok_or_else(|| bad(CMD, "the texture set is not ready"))?; + Ok(if content { json!({"target": "content", "channel": channel.id(), "bins": counts}) } else { json!({"target": "mask", "bins": counts}) }) +} + fn set(s: &mut Session, p: &Value) -> Result { let eid = effect_id(p, "effect.set")?; let blend = blend_param("effect.set", p, "blend")?; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index fa239848..14891a8f 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -773,12 +773,12 @@ impl Session { self.caches.get_mut(ts).map(|c| std::mem::take(&mut c.upload).into_iter().collect()).unwrap_or_default() } - /// Grayscale RGBA8 of layer `id`'s mask at `size²` for the mask view (None without a mask). - pub fn mask_view_rgba(&self, id: LayerId, size: u32) -> Option> { - let (ts, _, _) = self.doc.project.locate(id)?; + /// `f` on the compositor inputs of texture set `ts` (without a live stroke; None for a set + /// not ready). + pub(crate) fn with_inputs(&self, ts: usize, f: impl FnOnce(&texturecraft_compose::Inputs) -> Option) -> Option { let cache = self.caches.get(ts)?; let empty = BakedMaps::default(); - let inputs = texturecraft_compose::Inputs { + f(&texturecraft_compose::Inputs { project: &self.doc.project, ts, mesh: &self.mesh, @@ -788,11 +788,24 @@ impl Session { preview: None, images: &self.images, bounds: self.mesh.bounds(), - }; - let gray = texturecraft_compose::mask_image(&inputs, id, size)?; + }) + } + + /// Grayscale RGBA8 of layer `id`'s mask at `size²` for the mask view (None without a mask). + pub fn mask_view_rgba(&self, id: LayerId, size: u32) -> Option> { + let (ts, _, _) = self.doc.project.locate(id)?; + let gray = self.with_inputs(ts, |inp| texturecraft_compose::mask_image(inp, id, size))?; Some(gray.iter().flat_map(|g| [*g, *g, *g, 255]).collect()) } + /// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's + /// mask, or for a content effect the layer's `channel` (None for an unknown effect). + pub fn effect_histogram(&self, effect: LayerId, channel: Channel, bins: usize) -> Option> { + let (owner, _) = self.doc.project.effect(effect)?; + let (ts, _, _) = self.doc.project.locate(owner)?; + self.with_inputs(ts, |inp| texturecraft_compose::effect_histogram(inp, effect, channel, bins)) + } + pub fn baked(&self, ts: usize) -> Option<&BakedMaps> { self.doc.baked.get(&ts) } diff --git a/crates/engine/tests/content_effects.rs b/crates/engine/tests/content_effects.rs index 74011e9e..b8f865a2 100644 --- a/crates/engine/tests/content_effects.rs +++ b/crates/engine/tests/content_effects.rs @@ -111,3 +111,35 @@ fn painting_into_a_content_paint_effect() { assert!(s.doc.pixels.layer(LayerId(e), Channel::Roughness).is_none()); assert!(center(&mut s, Channel::Roughness)[0] > 0.85); } + +#[test] +fn histogram_counts_what_an_effect_reads() { + let mut s = session(); + let hist = |s: &mut Session, p: Value| { + let r = execute(s, "effect.histogram", &p).unwrap(); + let bins: Vec = r["bins"].as_array().unwrap().iter().map(|b| b.as_u64().unwrap()).collect(); + (r["target"].as_str().unwrap().to_string(), bins) + }; + // Only the bucket holding the value is filled. + let one = |bins: &[u64], k: usize| bins.iter().enumerate().all(|(i, b)| (*b > 0) == (i == k)); + execute(&mut s, "layer.add.fill", &json!({"color": [0.25, 0.25, 0.25], "roughness": 0.75})).unwrap(); + let lv = id(execute(&mut s, "effect.add.levels", &json!({"target": "content", "inLow": 0.5})).unwrap(), "effect"); + execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(); + let (target, bins) = hist(&mut s, json!({"effect": lv, "channel": "roughness", "bins": 4})); + assert_eq!(target, "content"); + assert!(one(&bins, 3), "roughness 0.75: {bins:?}"); + // The effect itself and those above it are left out; the default channel is the first. + let (_, bins) = hist(&mut s, json!({"effect": lv, "bins": 4})); + assert!(one(&bins, 1), "base color 0.25, components pooled: {bins:?}"); + assert_eq!(bins.iter().sum::() % 3, 0); + // A mask's levels reads the mask below it. + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"target": "mask", "value": 0.3})).unwrap(); + let ml = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect"); + let (target, bins) = hist(&mut s, json!({"effect": ml, "bins": 4})); + assert_eq!(target, "mask"); + assert!(one(&bins, 1), "mask 0.3: {bins:?}"); + assert_eq!(hist(&mut s, json!({"effect": ml})).1.len(), 64); + assert!(execute(&mut s, "effect.histogram", &json!({"effect": 999_999})).is_err()); + assert!(execute(&mut s, "effect.histogram", &json!({"effect": lv, "channel": "nope"})).is_err()); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index b5cdf217..ba2ddcfd 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -16,7 +16,7 @@ use crate::i18n::{n_, tr, trf}; use crate::shelf::{Asset, ShelfDrag}; use crate::state::PropsTab; use crate::theme::{Tokens, caption}; -use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, section, slider, slider_edit}; +use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, slider, slider_edit}; const TAG_COLORS: [Color32; 8] = [ Color32::from_rgb(0xc0, 0x40, 0x40), @@ -1582,6 +1582,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: } EffectKind::Levels(l) => { ui.label(caption(tr("Levels"))); + levels_histogram(app, ui, layer, eid, (l.in_low, l.in_high)); let mut v = [l.in_low, l.in_high, l.gamma, l.out_low, l.out_high]; let labels = [tr("Input low"), tr("Input high"), tr("Gamma"), tr("Output low"), tr("Output high")]; let mut done = false; @@ -1664,6 +1665,38 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: } } +/// The histogram of what levels effect `eid` of `layer` remaps (its mask, or a content channel +/// picked here), with the input range marked. Recomputed after a document change once no +/// pointer button is held, so dragging a slider keeps the last one. +fn levels_histogram(app: &TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId, range: (f32, f32)) { + let mut channel = layer.channels.keys().next().copied().unwrap_or(Channel::BaseColor); + if layer.content_effects.iter().any(|e| e.id == eid) { + let pick = egui::Id::unique(("levels_channel", eid.0)); + let chans: Vec = layer.channels.keys().copied().filter(|c| c.kind() != texturecraft_engine::core::ChannelKind::NormalMap).collect(); + channel = ui.data(|d| d.get_temp(pick)).filter(|c| chans.contains(c)).or(chans.first().copied()).unwrap_or(channel); + combo(ui, tr("Channel"), tr(channel.label()), |ui| { + for c in chans { + if ui.selectable_label(c == channel, tr(c.label())).clicked() { + ui.data_mut(|d| d.insert_temp(pick, c)); + } + } + }); + } + let key = egui::Id::unique(("levels_histogram", eid.0, channel)); + let rev = app.session.revision; + let counts = match ui.data(|d| d.get_temp::<(u64, std::sync::Arc>)>(key)) { + Some((r, h)) if r == rev || ui.input(|i| i.pointer.any_down()) => Some(h), + _ => app.session.effect_histogram(eid, channel, 64).map(|h| { + let h = std::sync::Arc::new(h); + ui.data_mut(|d| d.insert_temp(key, (rev, h.clone()))); + h + }), + }; + if let Some(counts) = counts { + histogram(ui, &counts, range); + } +} + /// The parameters of filter effect `id`. fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter) { let tk = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index eb9469e8..fdce1602 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -105,6 +105,31 @@ fn track(ui: &Ui, resp: &Response, x: std::ops::RangeInclusive, y: f32, t: p.circle(egui::pos2(xk, y), knob, tk.panel, Stroke::new(1.5, ring)); } +/// A histogram of `counts` (buckets over 0..1, scaled to the fullest) in a field-colored well +/// the width of the panel, the part of 0..1 outside `range` dimmed. +pub fn histogram(ui: &mut Ui, counts: &[u32], range: (f32, f32)) -> Response { + let tk = Tokens::get(ui.ctx()); + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 56.0), Sense::hover()); + let p = ui.painter_at(rect); + p.rect(rect, CornerRadius::same(tk.radius), tk.field, Stroke::new(1.0, tk.field_border), egui::StrokeKind::Inside); + let inner = rect.shrink(3.0); + let max = counts.iter().copied().max().unwrap_or(0).max(1) as f32; + let w = inner.width() / counts.len().max(1) as f32; + for (i, c) in counts.iter().enumerate() { + let h = inner.height() * *c as f32 / max; + let x = inner.left() + i as f32 * w; + p.rect_filled(egui::Rect::from_min_max(egui::pos2(x, inner.bottom() - h), egui::pos2(x + w, inner.bottom())), 0.0, tk.text_dim); + } + let x = |t: f32| inner.left() + inner.width() * t.clamp(0.0, 1.0); + let shade = tk.field.gamma_multiply(0.7); + p.rect_filled(egui::Rect::from_x_y_ranges(inner.left()..=x(range.0), inner.y_range()), 0.0, shade); + p.rect_filled(egui::Rect::from_x_y_ranges(x(range.1)..=inner.right(), inner.y_range()), 0.0, shade); + for t in [range.0, range.1] { + p.line_segment([egui::pos2(x(t), inner.top()), egui::pos2(x(t), inner.bottom())], Stroke::new(1.0, tk.accent)); + } + resp +} + /// One line of `text` cut with "…" to fit `max_width`, for list rows that shrink with their panel. pub fn elided(painter: &egui::Painter, text: impl Into, size: f32, color: Color32, max_width: f32) -> std::sync::Arc { let mut job = egui::text::LayoutJob::simple_singleline(text.into(), egui::FontId::proportional(size), color); diff --git a/crates/ui-egui/tests/effect_sliders.rs b/crates/ui-egui/tests/effect_sliders.rs index a4bb3915..8ddc5dd8 100644 --- a/crates/ui-egui/tests/effect_sliders.rs +++ b/crates/ui-egui/tests/effect_sliders.rs @@ -1,8 +1,9 @@ //! The sliders of a selected effect (opacity, generator, levels…) apply what they were dragged //! or clicked to. +use egui::accesskit::Role; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{Queryable, by}; use serde_json::json; use texturecraft_engine::core::{EffectKind, LayerId}; use texturecraft_ui_egui::TextureCraftApp; @@ -50,6 +51,28 @@ fn dragging_the_effect_opacity_applies_it() { assert!(opacity(&h, effect) < 0.5, "the dragged opacity applies: {}", opacity(&h, effect)); } +/// The combo box in the row of the "Channel" label. +fn channel_picker<'a>(h: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { + let row = h.get_by_label("Channel").rect().center().y; + h.get_all(by().role(Role::ComboBox)).find(|n| (n.rect().center().y - row).abs() < 4.0).unwrap() +} + +/// A content levels effect offers a channel for its histogram; picking one keeps it selected. +#[test] +fn content_levels_pick_the_histogram_channel() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"color": [0.5, 0.2, 0.1], "roughness": 0.6})).unwrap(); + texturecraft_engine::execute(&mut session, "effect.add.levels", &json!({"target": "content"})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + assert_eq!(channel_picker(&h).value().as_deref(), Some("Base color"), "the layer's first channel"); + channel_picker(&h).click(); + h.run_steps(2); + h.get_by_label("Roughness").click(); + h.run_steps(3); + assert_eq!(channel_picker(&h).value().as_deref(), Some("Roughness"), "the picked channel stays"); +} + #[test] fn clicking_the_effect_opacity_applies_it() { let (mut h, effect) = harness(); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 803d6d05..2a44f4ff 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -61,4 +61,16 @@ fn window_snapshots() { h.state_mut().ui.windows.export = false; h.state_mut().ui.windows.settings = true; save(&mut h, &dir, "window-settings"); + h.state_mut().ui.windows.settings = false; + // A mask's levels effect over clouds: the histogram in Properties. + let s = &mut h.state_mut().session; + for (id, p) in [ + ("layer.add.fill", serde_json::json!({"color": [0.8, 0.3, 0.1]})), + ("mask.add.black", serde_json::Value::Null), + ("effect.add.fill", serde_json::json!({"target": "mask", "procedural": "clouds"})), + ("effect.add.levels", serde_json::json!({"target": "mask", "inLow": 0.3, "inHigh": 0.8})), + ] { + texturecraft_engine::execute(s, id, &p).unwrap(); + } + save(&mut h, &dir, "properties-levels"); } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 7245bb61..86d84ea2 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -13,6 +13,8 @@ Everything TextureCraft does is an engine command with a stable id (`layer.add.f Programmatic calls never open dialogs: a command runs with its defaults. Only `ui.menu.invoke` behaves like a menu click. `session.inspect` shows every layer, mask, effect, fill source and painted tile count, so an agent can verify its work without a screenshot. +`effect.histogram {effect, channel?, bins?}` counts the values an effect reads (a levels +effect's input), so an agent can pick its input range from the data. ## Control channel (desktop app) diff --git a/docs/features.md b/docs/features.md index 090fdf77..fb077956 100644 --- a/docs/features.md +++ b/docs/features.md @@ -36,7 +36,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA contrast/luminosity, color balance, gradient map, posterize, clamp, invert, threshold, grayscale, replace color, edge detect, normal invert, baked lighting, blur, directional and slope blur, sharpen, high pass, bevel, glow, warp, directional warp, mosaic and four material - finishes), fills and paint. + finishes), fills and paint. **Levels** shows a histogram of what it reads (the mask below it, + or a content channel you pick) with its input range marked. **Anchor points** record the stack at a layer so masks and fills higher up can react to it. - **Masks** with a white or black background and a stack of effects: painted strokes, fills, **mesh-map generators** (edge wear, dirt, thin areas, curvature, AO, position and direction From 5f890e584e6c0ef545b23eee3087ad9d677a2ecc Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 09:32:25 +0700 Subject: [PATCH 43/60] Web: ask to save before replacing the project or closing the tab The browser build threw unsaved changes away on New project, Open, Close, Open sample project or a dropped file, and when the tab closed. They now wait on the desktop's Save / Don't save / Cancel dialog (Save downloads the project), and closing or reloading the tab with unsaved changes makes the browser ask first. --- apps/texturecraft-web/Cargo.toml | 2 +- apps/texturecraft-web/src/web.rs | 21 +++++++++++++++++- crates/ui-egui/src/lib.rs | 5 ++++- crates/ui-egui/src/menus.rs | 1 - crates/ui-egui/src/state.rs | 5 ++++- crates/ui-egui/src/web_files.rs | 31 +++++++++++++++++++++------ crates/ui-egui/src/windows.rs | 8 +++---- crates/ui-egui/tests/close_unsaved.rs | 15 +++++++++++++ docs/features.md | 3 ++- 9 files changed, 75 insertions(+), 16 deletions(-) diff --git a/apps/texturecraft-web/Cargo.toml b/apps/texturecraft-web/Cargo.toml index b2d47259..e5512768 100644 --- a/apps/texturecraft-web/Cargo.toml +++ b/apps/texturecraft-web/Cargo.toml @@ -24,4 +24,4 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", " wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" -web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location", "KeyboardEvent", "EventTarget", "AddEventListenerOptions"] } +web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location", "KeyboardEvent", "BeforeUnloadEvent", "EventTarget", "AddEventListenerOptions"] } diff --git a/apps/texturecraft-web/src/web.rs b/apps/texturecraft-web/src/web.rs index 37752314..bc1372a5 100644 --- a/apps/texturecraft-web/src/web.rs +++ b/apps/texturecraft-web/src/web.rs @@ -1,5 +1,6 @@ //! The eframe web runner: canvas lookup, backend selection, the loading screen's startup steps, -//! browser shortcuts the app takes over, and startup errors shown in the page. +//! browser shortcuts the app takes over, the unsaved-changes guard on close, and startup errors +//! shown in the page. use texturecraft_engine::Session; use texturecraft_ui_egui::TextureCraftApp; @@ -14,6 +15,7 @@ const PROGRESS_ID: &str = "texturecraft_progress"; pub fn start() { eframe::WebLogger::init(log::LevelFilter::Info).ok(); capture_app_shortcuts(); + guard_unsaved_changes(); wasm_bindgen_futures::spawn_local(async { let Some(document) = web_sys::window().and_then(|w| w.document()) else { log::error!("no document"); @@ -118,6 +120,23 @@ fn capture_app_shortcuts() { on_key.forget(); } +/// Closing or reloading the tab with unsaved changes makes the browser ask first (it shows its +/// own message; pages can't word it). +fn guard_unsaved_changes() { + let Some(window) = web_sys::window() else { return }; + let on_unload = Closure::::new(|e: web_sys::BeforeUnloadEvent| { + if texturecraft_ui_egui::web_files::unsaved() { + e.prevent_default(); + // Browsers that predate `preventDefault` here read the return value. + e.set_return_value("unsaved"); + } + }); + if let Err(e) = window.add_event_listener_with_callback("beforeunload", on_unload.as_ref().unchecked_ref()) { + log::warn!("couldn't guard unsaved changes on close: {e:?}"); + } + on_unload.forget(); +} + /// The baked sample project, or an empty material ball if that fails. Texture and bake sizes are /// kept small: the web build composites and bakes on one thread (bake 256 took ~12 s to start on a /// fast desktop CPU, 128 ~7.5 s). diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5aa9f754..e6e99567 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -381,7 +381,10 @@ impl eframe::App for TextureCraftApp { self.autosave(now); i18n::set_language(&self.ui.prefs.language); #[cfg(target_arch = "wasm32")] - keymap::sync_captured(&self.ui.keymap); + { + keymap::sync_captured(&self.ui.keymap); + web_files::sync_unsaved(self); + } self.fonts.update(ctx, i18n::current().code, self.ui.windows.settings); menus::shortcuts(self, ctx); profile::drive(self, ctx); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index d5e5fe3c..3f83a1ad 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -117,7 +117,6 @@ pub fn implemented(id: &str) -> bool { /// Invoke a menu item (menus, shortcuts, palette, control channel `ui.menu.invoke`). pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { - #[cfg(not(target_arch = "wasm32"))] if matches!(id, "ui.newProject" | "file.open" | "file.close" | "project.sample") && crate::windows::ask_to_save(app, crate::state::Unsaved::Command(id.into())) { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index ef0ab709..6db973dd 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -76,7 +76,7 @@ pub struct Windows { /// The start window: new, open, recent projects (the app opens it at launch). #[serde(skip)] pub start: bool, - /// What waits on the unsaved-changes dialog: save, don't save or cancel (desktop). + /// What waits on the unsaved-changes dialog: save, don't save or cancel. #[serde(skip)] pub unsaved: Option, } @@ -88,7 +88,10 @@ pub enum Unsaved { /// A menu command (New project, Open, Close, Open sample project). Command(String), /// Open this project or mesh file. + #[cfg(not(target_arch = "wasm32"))] Open(String), + /// Open a project or mesh file's bytes (picked or dropped in the browser): its name and bytes. + Load(String, std::sync::Arc>), } /// Edit › Settings. diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 371a646a..3a7f9d6c 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -53,7 +53,7 @@ pub fn poll(app: &mut TextureCraftApp) { for (name, bytes, pick) in picked { let done = match pick { Pick::Open => { - load(app, &name, &bytes); + load(app, &name, bytes); continue; } Pick::Environment => app.session.import_resource_bytes(&name, bytes).map(|res| use_environment(app, &res)), @@ -106,12 +106,12 @@ fn use_environment(app: &mut TextureCraftApp, name: &str) { } /// Import an image as a project resource, or replace the session with a `.tcraft` project or a -/// mesh file's bytes (errors become toasts). -pub fn load(app: &mut TextureCraftApp, name: &str, bytes: &[u8]) { +/// mesh file's bytes, after asking to save unsaved changes (errors become toasts). +pub fn load(app: &mut TextureCraftApp, name: &str, bytes: Vec) { let path = std::path::Path::new(name); let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); if IMAGE_EXTS.contains(&ext.as_str()) { - match app.session.import_resource_bytes(name, bytes.to_vec()) { + match app.session.import_resource_bytes(name, bytes) { Ok(res) => { app.ui.dock.focus(crate::docking::Panel::Assets); app.toast(trf("Imported {name}", &[("name", &res)]), false); @@ -120,8 +120,12 @@ pub fn load(app: &mut TextureCraftApp, name: &str, bytes: &[u8]) { } return; } + let bytes = std::sync::Arc::new(bytes); + if crate::windows::ask_to_save(app, crate::state::Unsaved::Load(name.into(), bytes.clone())) { + return; + } let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("Untitled"); - let next = if ext == PROJECT_EXT { Session::from_project_bytes(bytes) } else { Session::from_mesh_bytes(name, bytes, MESH_RESOLUTION, stem) }; + let next = if ext == PROJECT_EXT { Session::from_project_bytes(&bytes) } else { Session::from_mesh_bytes(name, &bytes, MESH_RESOLUTION, stem) }; match next { Ok(next) => { app.session.switch_to(next); @@ -183,7 +187,9 @@ fn zip_files(files: &[ExportedFile]) -> Result, String> { } #[cfg(target_arch = "wasm32")] -pub use web::{download, export_mesh, export_textures, import_bake_mesh, import_environment, import_images, import_preset, open, save_project}; +pub use web::{ + download, export_mesh, export_textures, import_bake_mesh, import_environment, import_images, import_preset, open, save_project, sync_unsaved, unsaved, +}; #[cfg(target_arch = "wasm32")] mod web { @@ -191,6 +197,19 @@ mod web { use serde_json::Value; use wasm_bindgen::JsCast as _; + /// Whether the project has unsaved changes, for the page's `beforeunload` listener. + static UNSAVED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + + /// Refresh [`unsaved`] (once per frame). + pub fn sync_unsaved(app: &TextureCraftApp) { + UNSAVED.store(app.session.modified, std::sync::atomic::Ordering::Relaxed); + } + + /// Whether closing or reloading the page would lose unsaved changes. + pub fn unsaved() -> bool { + UNSAVED.load(std::sync::atomic::Ordering::Relaxed) + } + /// File › Open: the browser's file picker; the file loads on a later frame (see [`poll`]). pub fn open(ctx: &egui::Context) { pick(ctx, tr("Projects and meshes"), OPEN_EXTS, false, Pick::Open); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 68fd1214..6d44fc5f 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -29,13 +29,11 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if app.ui.mode == Mode::Baking { bake_bar(app, ctx); } - #[cfg(not(target_arch = "wasm32"))] unsaved(app, ctx); } /// Hold `then` (quitting, opening or closing a project) behind the unsaved-changes dialog when /// the project has unsaved changes; false when it can go ahead now. -#[cfg(not(target_arch = "wasm32"))] pub(crate) fn ask_to_save(app: &mut TextureCraftApp, then: crate::state::Unsaved) -> bool { if app.session.modified { app.ui.windows.unsaved = Some(then); @@ -43,8 +41,8 @@ pub(crate) fn ask_to_save(app: &mut TextureCraftApp, then: crate::state::Unsaved app.session.modified } -/// Quitting, opening or closing a project with unsaved changes asks whether to save them first. -#[cfg(not(target_arch = "wasm32"))] +/// Quitting, opening or closing a project with unsaved changes asks whether to save them first +/// (in the browser, Save downloads the project). fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { use crate::state::Unsaved; if ctx.input(|i| i.viewport().close_requested()) && ask_to_save(app, Unsaved::Quit) { @@ -91,7 +89,9 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { match then { Unsaved::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close), Unsaved::Command(id) => crate::menus::invoke(app, ctx, &id), + #[cfg(not(target_arch = "wasm32"))] Unsaved::Open(path) => open_path(app, &path), + Unsaved::Load(name, bytes) => crate::web_files::load(app, &name, std::sync::Arc::unwrap_or_clone(bytes)), } } diff --git a/crates/ui-egui/tests/close_unsaved.rs b/crates/ui-egui/tests/close_unsaved.rs index 468634cc..9f518f18 100644 --- a/crates/ui-egui/tests/close_unsaved.rs +++ b/crates/ui-egui/tests/close_unsaved.rs @@ -60,6 +60,21 @@ fn closing_without_changes_does_not_ask() { assert!(h.state().ui.windows.unsaved.is_none()); } +/// A project picked or dropped in the browser arrives as bytes; it waits on the same dialog. +#[test] +fn a_dropped_project_waits_on_the_dialog() { + let mut h = harness(true); + let dropped = texturecraft_engine::Session::new_project("Dropped", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + texturecraft_ui_egui::web_files::load(h.state_mut(), "dropped.tcraft", dropped.to_project_bytes().unwrap()); + h.run_steps(4); + assert!(matches!(h.state().ui.windows.unsaved, Some(Unsaved::Load(ref name, _)) if name == "dropped.tcraft"), "the dialog is open"); + assert_ne!(h.state().session.doc.project.name, "Dropped", "the project stays until answered"); + h.get_by_label("Don't save").click(); + h.run_steps(2); + assert_eq!(h.state().session.doc.project.name, "Dropped", "Don't save opens it"); + assert!(h.state().ui.windows.unsaved.is_none()); +} + #[test] fn closing_the_project_with_changes_asks_first() { let mut h = harness(true); diff --git a/docs/features.md b/docs/features.md index 090fdf77..4fd44e27 100644 --- a/docs/features.md +++ b/docs/features.md @@ -69,7 +69,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Projects** are a single `.tcraft` file: the mesh, every layer (sparse and lossless), baked maps and imported images. **Project templates** start new work from a saved setup. Closing the app, or opening, starting or closing another project, with unsaved changes asks whether to save them - first. + first (in the browser too, where Save downloads the project and closing or reloading the tab + asks before the changes are lost). ## Bake and export From 5e37a93e45c62aeb299b8be5ce6fa0c1987157ac Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 09:40:21 +0700 Subject: [PATCH 44/60] Color picker: our own picker with a copy icon from the icon set The picker's copy button was an emoji the bundled fonts don't draw, and it lives inside egui's picker. The swatch now opens a compact picker of its own: R, G and B values with a Phosphor copy button, a saturation/value square and a hue strip. Hue and saturation survive black, white and grays. The copy tooltip is translated into all nine other UI languages. --- crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/widgets.rs | 77 +++++++++++++++++++++++++++- crates/ui-egui/tests/color_picker.rs | 66 +++++++++++++++++++----- 11 files changed, 136 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 8abd47fe..c5594df2 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -186,6 +186,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast", "التباين"), ("Contrast/Luminosity", "التباين / الإضاءة"), ("Converted maps", "الخرائط المحوّلة"), + ("Copy RGB values", "نسخ قيم RGB"), ("Copy from", "نسخ من"), ("Copy layer(s)", "نسخ الطبقة (الطبقات)"), ("Copy the selected layer alone (its empty parts copy nothing)", "نسخ الطبقة المحددة وحدها (الأجزاء الفارغة لا تنسخ شيئاً)"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 5a8b20e2..24f53398 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -198,6 +198,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast", "Kontrast"), ("Contrast/Luminosity", "Kontrast/Luminanz"), ("Converted maps", "Konvertierte Maps"), + ("Copy RGB values", "RGB-Werte kopieren"), ("Copy from", "Kopieren aus"), ("Copy layer(s)", "Ebene(n) kopieren"), ("Copy the selected layer alone (its empty parts copy nothing)", "Nur die ausgewählte Ebene kopieren (ihre leeren Bereiche kopieren nichts)"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index b100dba9..8a8aeb41 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -195,6 +195,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast", "Contraste"), ("Contrast/Luminosity", "Contraste/Luminosidad"), ("Converted maps", "Mapas convertidos"), + ("Copy RGB values", "Copiar los valores RGB"), ("Copy from", "Copiar de"), ("Copy layer(s)", "Copiar capa(s)"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copiar solo la capa seleccionada (sus partes vacías no copian nada)"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 486621d8..48dc5041 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -198,6 +198,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast", "Contraste"), ("Contrast/Luminosity", "Contraste/Luminosité"), ("Converted maps", "Cartes converties"), + ("Copy RGB values", "Copier les valeurs RVB"), ("Copy from", "Copier depuis"), ("Copy layer(s)", "Copier le(s) calque(s)"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copier uniquement le calque sélectionné (ses parties vides ne copient rien)"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 3044f373..7bf2ccf8 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -201,6 +201,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast", "Contrasto"), ("Contrast/Luminosity", "Contrasto/Luminosità"), ("Converted maps", "Mappe convertite"), + ("Copy RGB values", "Copia i valori RGB"), ("Copy from", "Copia da"), ("Copy layer(s)", "Copia livello/i"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copia solo il livello selezionato (le sue parti vuote non copiano nulla)"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index db9a40f8..0bd7b115 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -198,6 +198,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast", "コントラスト"), ("Contrast/Luminosity", "コントラスト/輝度"), ("Converted maps", "変換マップ"), + ("Copy RGB values", "RGB 値をコピー"), ("Copy from", "コピー元"), ("Copy layer(s)", "レイヤーをコピー"), ("Copy the selected layer alone (its empty parts copy nothing)", "選択中のレイヤーのみをコピー (空の部分は何もコピーしない)"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index a8951370..1a9d3a98 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -189,6 +189,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast", "대비"), ("Contrast/Luminosity", "대비/광도"), ("Converted maps", "변환된 맵"), + ("Copy RGB values", "RGB 값 복사"), ("Copy from", "복사 원본"), ("Copy layer(s)", "레이어 복사"), ("Copy the selected layer alone (its empty parts copy nothing)", "선택한 레이어만 복사합니다 (빈 부분은 복사되지 않음)"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index e238c6ac..122d1160 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -195,6 +195,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast", "Contraste"), ("Contrast/Luminosity", "Contraste/Luminosidade"), ("Converted maps", "Mapas convertidos"), + ("Copy RGB values", "Copiar os valores RGB"), ("Copy from", "Copiar de"), ("Copy layer(s)", "Copiar camada(s)"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copiar apenas a camada selecionada (suas partes vazias não copiam nada)"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 9a093a9f..974deb55 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -168,6 +168,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast", "对比度"), ("Contrast/Luminosity", "对比度/亮度"), ("Converted maps", "转换贴图"), + ("Copy RGB values", "复制 RGB 值"), ("Copy from", "复制自"), ("Copy layer(s)", "复制图层"), ("Copy the selected layer alone (its empty parts copy nothing)", "仅复制所选图层(其空白部分不复制任何内容)"), diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index eb9469e8..86cc4310 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -209,8 +209,7 @@ pub fn color_swatch(ui: &mut Ui, id: &str, linear: &mut [f32; 3], width: f32) -> // Open state lives in memory (`toggle_id` above); `from_response` alone shows it always. egui::Popup::from_response(&resp).id(popup).open_memory(None).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { // Wider than the R, G, B row at any value, so the popup keeps one size and place. - ui.spacing_mut().slider_width = 275.0; - if egui::color_picker::color_picker_color32(ui, &mut c, egui::color_picker::Alpha::Opaque) { + if color_picker(ui, popup.with("picker"), &mut c, 275.0) { let lin = [c.r(), c.g(), c.b()].map(|v| texturecraft_engine::texel::srgb_to_linear(v as f32 / 255.0)); *linear = lin; changed = true; @@ -219,6 +218,80 @@ pub fn color_swatch(ui: &mut Ui, id: &str, linear: &mut [f32; 3], width: f32) -> changed } +/// A color picker `width` wide: R, G, B (sRGB 0–255) with a copy button, a saturation/value +/// square and a hue strip. Returns true when the color changed. +fn color_picker(ui: &mut Ui, id: egui::Id, c: &mut Color32, width: f32) -> bool { + use egui::ecolor::{hsv_from_rgb, rgb_from_hsv}; + let tk = Tokens::get(ui.ctx()); + let mut srgb = [c.r(), c.g(), c.b()]; + let hsv_of = |srgb: [u8; 3]| hsv_from_rgb(srgb.map(|v| v as f32 / 255.0)); + // Remembered with the color it was for, so hue and saturation survive black, white and grays. + let (mut h, mut s, mut v) = ui.data(|d| d.get_temp::<(Color32, (f32, f32, f32))>(id)).filter(|(k, _)| k == c).map_or_else(|| hsv_of(srgb), |(_, hsv)| hsv); + let mut typed = false; + let mut dragged = false; + ui.horizontal(|ui| { + for (x, prefix) in srgb.iter_mut().zip(["R ", "G ", "B "]) { + typed |= ui.add(egui::DragValue::new(x).speed(0.5).prefix(prefix)).changed(); + } + if icon_button(ui, egui_phosphor::regular::COPY, crate::i18n::tr("Copy RGB values"), false, 20.0).clicked() { + ui.copy_text(format!("{}, {}, {}", srgb[0], srgb[1], srgb[2])); + } + }); + if typed { + (h, s, v) = hsv_of(srgb); + } + let border = Stroke::new(1.0, tk.field_border); + // Saturation across, value up. + let (rect, resp) = ui.allocate_exact_size(vec2(width, width), Sense::click_and_drag()); + if let Some(p) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.clicked()) { + (s, v) = (((p.x - rect.left()) / rect.width()).clamp(0.0, 1.0), 1.0 - ((p.y - rect.top()) / rect.height()).clamp(0.0, 1.0)); + dragged = true; + } + gradient(ui.painter(), rect, |x, y| rgb_from_hsv((h, x, 1.0 - y))); + ui.painter().rect_stroke(rect, 0.0, border, egui::StrokeKind::Inside); + let at = rect.lerp_inside(vec2(s, 1.0 - v)); + ui.painter().circle_stroke(at, 5.0, Stroke::new(2.0, Color32::WHITE)); + ui.painter().circle_stroke(at, 6.5, Stroke::new(1.0, Color32::BLACK)); + let (rect, resp) = ui.allocate_exact_size(vec2(width, 16.0), Sense::click_and_drag()); + if let Some(p) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.clicked()) { + h = ((p.x - rect.left()) / rect.width()).clamp(0.0, 1.0); + dragged = true; + } + gradient(ui.painter(), rect, |x, _| rgb_from_hsv((x, 1.0, 1.0))); + ui.painter().rect_stroke(rect, 0.0, border, egui::StrokeKind::Inside); + let x = rect.left() + rect.width() * h; + ui.painter().rect_stroke(egui::Rect::from_x_y_ranges(x - 2.0..=x + 2.0, rect.y_range()), 1.0, Stroke::new(1.5, Color32::WHITE), egui::StrokeKind::Middle); + if dragged { + srgb = rgb_from_hsv((h, s, v)).map(|x| (x * 255.0 + 0.5) as u8); + } + let next = Color32::from_rgb(srgb[0], srgb[1], srgb[2]); + ui.data_mut(|d| d.insert_temp(id, (next, (h, s, v)))); + let changed = next != *c; + *c = next; + changed +} + +/// Fill `rect` with `rgb(x, y)` (sRGB 0..1 over 0..1 across and down), as a shaded mesh. +fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) -> [f32; 3]) { + const N: u32 = 24; + let mut mesh = egui::Mesh::default(); + for j in 0..=N { + for i in 0..=N { + let (x, y) = (i as f32 / N as f32, j as f32 / N as f32); + let [r, g, b] = rgb(x, y).map(|c| (c.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + mesh.colored_vertex(rect.lerp_inside(vec2(x, y)), Color32::from_rgb(r, g, b)); + } + } + for j in 0..N { + for i in 0..N { + let k = j * (N + 1) + i; + mesh.add_triangle(k, k + 1, k + N + 1); + mesh.add_triangle(k + 1, k + N + 2, k + N + 1); + } + } + painter.add(mesh); +} + /// Panel title row with optional trailing content. pub fn panel_header(ui: &mut Ui, title: &str, trailing: impl FnOnce(&mut Ui)) { ui.horizontal(|ui| { diff --git a/crates/ui-egui/tests/color_picker.rs b/crates/ui-egui/tests/color_picker.rs index dd9bbf53..6457a749 100644 --- a/crates/ui-egui/tests/color_picker.rs +++ b/crates/ui-egui/tests/color_picker.rs @@ -1,35 +1,73 @@ -//! The color picker popup keeps its place while the color changes. +//! The color picker popup keeps its place while the color changes, picks from its square and hue +//! strip, and copies its values. use egui::accesskit::Role; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use texturecraft_ui_egui::{theme, widgets}; -/// The left edge of the picker's R value. -fn r_left(h: &Harness<'_, [f32; 3]>) -> f32 { - h.get_all_by_role(Role::SpinButton).next().unwrap().rect().left() -} - -#[test] -fn the_popup_stays_put_while_the_color_changes() { - // A swatch at the right edge of the window, like the Properties panel's. - // The picker's copy button is an emoji the bundled fonts do not draw. - let mut h = Harness::builder().with_size(egui::vec2(800.0, 600.0)).allow_missing_glyphs().build_ui_state( +/// A swatch at the right edge of the window, like the Properties panel's, with its picker open. +fn open_picker(color: [f32; 3]) -> Harness<'static, [f32; 3]> { + let mut h = Harness::builder().with_size(egui::vec2(800.0, 600.0)).build_ui_state( |ui, color: &mut [f32; 3]| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| { widgets::color_swatch(ui, "color", color, 120.0); }); }, - [1.0; 3], + color, ); + h.ctx.set_fonts(theme::font_definitions()); theme::apply(&h.ctx, theme::Brightness::default(), theme::Accent::default()); h.run_steps(2); let swatch = egui::pos2(800.0 - 60.0, 9.0); h.drag_at(swatch); h.drop_at(swatch); h.run_steps(3); - let bright = r_left(&h); + h +} + +/// The picker's R value. +fn r_value(h: &Harness<'_, [f32; 3]>) -> egui::Rect { + h.get_all_by_role(Role::SpinButton).next().unwrap().rect() +} + +/// Click at `p` and let the picker apply it. +fn click(h: &mut Harness<'_, [f32; 3]>, p: egui::Pos2) { + h.drag_at(p); + h.drop_at(p); + h.run_steps(3); +} + +#[test] +fn the_popup_stays_put_while_the_color_changes() { + let mut h = open_picker([1.0; 3]); + let bright = r_value(&h).left(); *h.state_mut() = [0.001; 3]; h.run_steps(3); - assert_eq!(r_left(&h), bright, "the picker does not move when R, G and B lose digits"); + assert_eq!(r_value(&h).left(), bright, "the picker does not move when R, G and B lose digits"); +} + +#[test] +fn the_square_and_the_hue_strip_pick_the_color() { + let mut h = open_picker([1.0; 3]); + // The square starts a row below the values; its bottom-left corner is black. + let r = r_value(&h); + let square = egui::Rect::from_min_size(egui::pos2(r.left() + 1.0, r.bottom() + 8.0), egui::vec2(273.0, 273.0)); + click(&mut h, square.left_bottom() + egui::vec2(2.0, -6.0)); + assert!(h.state().iter().all(|c| *c < 0.01), "black: {:?}", h.state()); + // Full saturation and value, then a hue a third of the way along: green. + click(&mut h, square.right_top() + egui::vec2(-1.0, 1.0)); + let strip = square.bottom() + 14.0; + click(&mut h, egui::pos2(square.left() + 275.0 / 3.0, strip)); + let [r, g, b] = *h.state(); + assert!(g > 0.9 && r < 0.05 && b < 0.05, "green: {:?}", h.state()); +} + +#[test] +fn the_copy_button_copies_the_rgb_values() { + let mut h = open_picker([1.0, 0.0, 0.0]); + h.get_by_label("Copy RGB values").click(); + h.step(); + let copied = h.output().platform_output.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(t) if t == "255, 0, 0")); + assert!(copied, "{:?}", h.output().platform_output.commands); } From 83b8a13131d72205145d421f9e2b6202df7411dc Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 09:44:28 +0700 Subject: [PATCH 45/60] Levels histogram: sample every column, and read masks of empty layers An odd tile stride: a power of two divides the row length on power-of-two sets and read the same few columns. A mask is planned on its own, so a paint layer with nothing painted still shows its mask's histogram. --- crates/compose/src/eval.rs | 42 +++++++++++++++++++------- crates/engine/tests/content_effects.rs | 6 ++++ 2 files changed, 37 insertions(+), 11 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 6ba8e33e..b2386a6e 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1849,6 +1849,15 @@ pub fn mask_image(inp: &Inputs, id: LayerId, size: u32) -> Option> { /// Tiles [`effect_histogram`] samples at most (a million texels). const HISTOGRAM_TILES: usize = 256; +/// The tiles [`effect_histogram`] reads: an even sample of at most [`HISTOGRAM_TILES`], which +/// keeps the cost flat up to 8K. The stride is odd: a power of two would divide the row length +/// and sample the same few columns. +fn histogram_tiles(width: u32, height: u32) -> Vec<(u32, u32)> { + let all = all_tiles(width, height); + let stride = all.len().div_ceil(HISTOGRAM_TILES).max(1) | 1; + all.into_iter().step_by(stride).collect() +} + /// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's mask /// below it, or (a content effect) the layer's `channel` below it where the layer has content, /// color components pooled and signed values mapped to 0..1. Over the texels the mesh covers @@ -1874,31 +1883,31 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u }; let cut_inp = Inputs { project: &cut, preview: None, ..*inp }; let channels = cut.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); - // An even sample of at most HISTOGRAM_TILES tiles keeps the cost flat up to 8K. - let all = all_tiles(inp.gbuf.width, inp.gbuf.height); - let tiles: Vec<(u32, u32)> = all.iter().copied().step_by(all.len().div_ceil(HISTOGRAM_TILES).max(1)).collect(); + let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height); let fields = neighbourhood_fields(&cut_inp, &channels, &tiles); let bin = |v: f32| ((v.clamp(0.0, 1.0) * bins as f32) as usize).min(bins - 1); let hist = tiles .par_iter() .map(|&(tx, ty)| { let mut h = vec![0u32; bins]; - let nodes = plan(&cut_inp, &[owner], &channels, tx, ty, 0, Some(&fields)); - let Some(n) = nodes.first() else { return h }; - let c = n.chans.iter().find(|c| Channel::ALL.get(c.ch) == Some(&channel)); + // The mask is planned on its own: a layer with nothing drawn plans no node. + let mask = if in_mask { layer_mask(&cut, owner).and_then(|m| mask_plan(&cut_inp, owner, m, tx, ty, Some(&fields))) } else { None }; + let nodes = if in_mask { Vec::new() } else { plan(&cut_inp, &[owner], &channels, tx, ty, 0, Some(&fields)) }; + let content = nodes.first().and_then(|n| n.chans.iter().find(|c| Channel::ALL.get(c.ch) == Some(&channel)).map(|c| (n, c))); + if mask.is_none() && content.is_none() { + return h; + } let full = anchor_plan(&cut_inp, owner, &channels, tx, ty, Some(&fields)); for (x, y, o) in tile_texels(inp.gbuf, tx, ty) { let mut tex = Texel::new(&cut_inp, x, y, o, 0.0); if !full.is_empty() { tex.anchors_below(&full, owner); } - if in_mask { - if let Some(m) = &n.mask - && let Some(b) = h.get_mut(bin(tex.mask(m))) - { + if let Some(m) = &mask { + if let Some(b) = h.get_mut(bin(tex.mask(m))) { *b += 1; } - } else if let Some(c) = c + } else if let Some((n, c)) = content && let Some((v, _)) = tex.content(&n.content, c) { // As levels reads them (`per_unit`); normal maps pass through levels unchanged. @@ -2037,6 +2046,17 @@ mod tests { (0..3).all(|i| (a[i] - b[i]).abs() < 2e-4) } + #[test] + fn histogram_samples_spread_over_every_column() { + assert_eq!(histogram_tiles(1024, 1024), all_tiles(1024, 1024), "small sets are read whole"); + for size in [2048, 4096, 8192] { + let tiles = histogram_tiles(size, size); + let columns: std::collections::BTreeSet = tiles.iter().map(|t| t.0).collect(); + assert!(tiles.len() <= HISTOGRAM_TILES, "{size}: {} tiles", tiles.len()); + assert!(columns.len() as u32 >= size / TILE / 2, "{size}: only {} columns", columns.len()); + } + } + #[test] fn empty_stack_gives_channel_defaults() { let f = fixture(); diff --git a/crates/engine/tests/content_effects.rs b/crates/engine/tests/content_effects.rs index b8f865a2..3ffec06f 100644 --- a/crates/engine/tests/content_effects.rs +++ b/crates/engine/tests/content_effects.rs @@ -140,6 +140,12 @@ fn histogram_counts_what_an_effect_reads() { assert_eq!(target, "mask"); assert!(one(&bins, 1), "mask 0.3: {bins:?}"); assert_eq!(hist(&mut s, json!({"effect": ml})).1.len(), 64); + // A paint layer with nothing painted yet still has its mask. + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"target": "mask", "value": 0.6})).unwrap(); + let pl = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect"); + assert!(one(&hist(&mut s, json!({"effect": pl, "bins": 4})).1, 2), "an empty paint layer's mask"); assert!(execute(&mut s, "effect.histogram", &json!({"effect": 999_999})).is_err()); assert!(execute(&mut s, "effect.histogram", &json!({"effect": lv, "channel": "nope"})).is_err()); } From a185e5f951c44e633e5e700960cee8c7f68a0f0b Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 09:52:09 +0700 Subject: [PATCH 46/60] Filters: histogram scan, range and shift Three adjustment filters for masks and content: Histogram Scan slides a ramp through the values (contrast narrows it to a step), Histogram Range squeezes them towards a position, and Histogram Shift offsets them with wrap-around. Names and parameters are translated into all nine other UI languages. --- crates/core/src/layer.rs | 44 ++++++++++++++++++++++++++++++ crates/engine/src/filter_lib.rs | 18 ++++++++++++ crates/engine/src/mask_cmds.rs | 2 +- crates/ui-egui/src/i18n/ar.rs | 5 ++++ crates/ui-egui/src/i18n/de.rs | 5 ++++ crates/ui-egui/src/i18n/es.rs | 5 ++++ crates/ui-egui/src/i18n/fr.rs | 5 ++++ crates/ui-egui/src/i18n/it.rs | 5 ++++ crates/ui-egui/src/i18n/ja.rs | 5 ++++ crates/ui-egui/src/i18n/ko.rs | 5 ++++ crates/ui-egui/src/i18n/pt_br.rs | 5 ++++ crates/ui-egui/src/i18n/zh_hans.rs | 5 ++++ docs/features.md | 10 +++---- 13 files changed, 113 insertions(+), 6 deletions(-) diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 12671b85..ed263910 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -535,6 +535,21 @@ pub enum Filter { min: f32, max: f32, }, + /// A ramp slid through the values: those above `position` go towards white, those below + /// towards black, over a width `contrast` (0..1) narrows to a hard step. + HistogramScan { + position: f32, + contrast: f32, + }, + /// The values squeezed towards `position`: `range` 1 keeps them, 0 sets them all to it. + HistogramRange { + range: f32, + position: f32, + }, + /// The values offset by `offset` (−1..1), wrapping around past white and black. + HistogramShift { + offset: f32, + }, /// Shift each texel's lookup along a noise vector field: `intensity` in texels at 2K, /// `scale` noise features per UV unit. Warp { @@ -742,6 +757,22 @@ impl Filter { let (lo, hi) = (min.min(*max), min.max(*max)); per_unit(kind, v, |x| x.max(lo).min(hi)) } + Filter::HistogramScan { position, contrast } => { + let width = (1.0 - contrast.clamp(0.0, 1.0)).max(1e-3); + per_unit(kind, v, |x| unit((x - position) / width + 0.5)) + } + Filter::HistogramRange { range, position } => per_unit(kind, v, |x| unit(position + (x - position) * range)), + Filter::HistogramShift { offset } => per_unit(kind, v, |x| { + // Wrapped by hand: `rem_euclid` would also send white (1 + 0) to black. + let y = unit(x) + offset.clamp(-1.0, 1.0); + unit(if y > 1.0 { + y - 1.0 + } else if y < 0.0 { + y + 1.0 + } else { + y + }) + }), Filter::Grayscale => match kind { ChannelKind::Color => [lum(v); 3], _ => v, @@ -793,6 +824,9 @@ impl Filter { Filter::GradientMap { .. } => "Gradient Map", Filter::Posterize { .. } => "Posterize", Filter::Clamp { .. } => "Clamp", + Filter::HistogramScan { .. } => "Histogram Scan", + Filter::HistogramRange { .. } => "Histogram Range", + Filter::HistogramShift { .. } => "Histogram Shift", Filter::Warp { .. } => "Warp", Filter::DirectionalBlur { .. } => "Blur Directional", Filter::SlopeBlur { .. } => "Slope Blur", @@ -968,6 +1002,16 @@ mod tests { assert_eq!(Filter::GradientMap { colors: vec![] }.point(c, [0.3; 3]), None, "an empty gradient changes nothing"); assert!(close(Filter::Posterize { levels: 2.0 }.point(c, [0.2, 0.6, 0.9]).unwrap(), [0.0, 1.0, 1.0])); assert!(close(Filter::Clamp { min: 0.8, max: 0.3 }.point(c, [0.1, 0.5, 0.9]).unwrap(), [0.3, 0.5, 0.8]), "swapped bounds never panic"); + let scan = |position, contrast| Filter::HistogramScan { position, contrast }.point(c, [0.2, 0.5, 0.9]).unwrap(); + assert!(close(scan(0.5, 0.0), [0.2, 0.5, 0.9]), "a full-width ramp at the middle keeps the values"); + assert!(close(scan(0.4, 1.0), [0.0, 1.0, 1.0]), "full contrast is a step at the position"); + assert!(close(scan(0.7, 0.5), [0.0, 0.1, 0.9])); + let range = |range, position| Filter::HistogramRange { range, position }.point(c, [0.2, 0.5, 0.9]).unwrap(); + assert!(close(range(1.0, 0.3), [0.2, 0.5, 0.9]) && close(range(0.0, 0.3), [0.3; 3])); + assert!(close(range(0.5, 0.5), [0.35, 0.5, 0.7])); + let shift = |offset| Filter::HistogramShift { offset }.point(c, [0.0, 0.5, 1.0]).unwrap(); + assert!(close(shift(0.0), [0.0, 0.5, 1.0]), "no offset keeps white white"); + assert!(close(shift(0.25), [0.25, 0.75, 0.25]) && close(shift(-0.25), [0.75, 0.25, 0.75])); let cb = Filter::ColorBalance { shadows: [0.2, 0.0, 0.0], midtones: [0.0; 3], highlights: [0.0, 0.0, 0.2] }; assert!(cb.point(c, [0.05; 3]).unwrap()[0] > 0.2 && cb.point(c, [0.95; 3]).unwrap()[2] > 0.99); assert!(close(Filter::Invert.point(ChannelKind::Signed, [0.5; 3]).unwrap(), [-0.5; 3])); diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index 75849e7a..f3168c9d 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -31,6 +31,9 @@ pub const FILTERS: &[FilterDef] = &[ def("gradientMap", "Gradient Map", "Adjustments", true), def("posterize", "Posterize", "Adjustments", true), def("clamp", "Clamp", "Adjustments", true), + def("histogramScan", "Histogram Scan", "Adjustments", true), + def("histogramRange", "Histogram Range", "Adjustments", true), + def("histogramShift", "Histogram Shift", "Adjustments", true), def("invert", "Invert", "Adjustments", true), def("threshold", "Threshold", "Adjustments", true), def("grayscale", "Grayscale", "Adjustments", false), @@ -96,6 +99,9 @@ pub fn build(id: &str, p: &Value) -> Result { "gradientMap" => Filter::GradientMap { colors: vec![[0.02, 0.02, 0.04], [0.45, 0.16, 0.05], [1.0, 0.85, 0.55]] }, "posterize" => Filter::Posterize { levels: 4.0 }, "clamp" => Filter::Clamp { min: 0.2, max: 0.8 }, + "histogramScan" => Filter::HistogramScan { position: 0.5, contrast: 0.5 }, + "histogramRange" => Filter::HistogramRange { range: 0.5, position: 0.5 }, + "histogramShift" => Filter::HistogramShift { offset: 0.25 }, "warp" => Filter::Warp { intensity: 16.0, scale: 4.0, seed: 1 }, "blurDirectional" => Filter::DirectionalBlur { radius: 16.0, angle: 0.0 }, "slopeBlur" => Filter::SlopeBlur { radius: 16.0, scale: 4.0, seed: 1 }, @@ -151,6 +157,9 @@ pub fn scalar_params(f: &Filter) -> Vec<(&'static str, &'static str, f32, f32, f } Filter::Posterize { levels } => vec![("levels", "Steps", *levels, 2.0, 64.0)], Filter::Clamp { min, max } => vec![("min", "Minimum", *min, 0.0, 1.0), ("max", "Maximum", *max, 0.0, 1.0)], + Filter::HistogramScan { position, contrast } => vec![("position", "Position", *position, 0.0, 1.0), ("contrast", "Contrast", *contrast, 0.0, 1.0)], + Filter::HistogramRange { range, position } => vec![("range", "Range", *range, 0.0, 1.0), ("position", "Position", *position, 0.0, 1.0)], + Filter::HistogramShift { offset } => vec![("offset", "Offset", *offset, -1.0, 1.0)], Filter::Warp { intensity, scale, seed } => { vec![ ("intensity", "Intensity (texels at 2K)", *intensity, 0.0, 128.0), @@ -250,6 +259,15 @@ pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> { set(min, "min", 0.0, 1.0); set(max, "max", 0.0, 1.0); } + Filter::HistogramScan { position, contrast } => { + set(position, "position", 0.0, 1.0); + set(contrast, "contrast", 0.0, 1.0); + } + Filter::HistogramRange { range, position } => { + set(range, "range", 0.0, 1.0); + set(position, "position", 0.0, 1.0); + } + Filter::HistogramShift { offset } => set(offset, "offset", -1.0, 1.0), Filter::Warp { intensity, scale, seed: s } => { set(intensity, "intensity", 0.0, 256.0); set(scale, "scale", 0.01, 1000.0); diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 9122b158..9b39dca6 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Add filter", ["Layers", "Effects"], None, - "{layer?, target?: mask|content, name?, filter?: id from filter.list (invert, threshold, blur, sharpen, hsl, levels, contrastLuminosity, colorBalance, gradientMap, posterize, clamp, warp, blurDirectional, slopeBlur, matFinishGrind|Raw|Sanded|Hammered), level?, radius?, amount?, hue?: turns -1..1, saturation?, lightness?, contrast?, luminosity?, shadows?|midtones?|highlights?: [r,g,b] -1..1, colors?: [[r,g,b]|\"#rrggbb\", ...], levels?, min?, max?, intensity?, scale?, seed?, angle?} — material finishes go on the content", + "{layer?, target?: mask|content, name?, filter?: id from filter.list (invert, threshold, blur, sharpen, hsl, levels, contrastLuminosity, colorBalance, gradientMap, posterize, clamp, histogramScan|Range|Shift, warp, blurDirectional, slopeBlur, matFinishGrind|Raw|Sanded|Hammered), level?, radius?, amount?, hue?: turns -1..1, saturation?, lightness?, contrast?, luminosity?, shadows?|midtones?|highlights?: [r,g,b] -1..1, colors?: [[r,g,b]|\"#rrggbb\", ...], levels?, min?, max?, position?, range?, offset?, intensity?, scale?, seed?, angle?} — material finishes go on the content", has_layer, add_filter ), diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 8abd47fe..5f232772 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -372,6 +372,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("High poly mesh suffix", "لاحقة المجسم عالي الدقة"), ("High poly: {name}", "عالي الدقة: {name}"), ("Highlights", "المناطق المضيئة"), + ("Histogram Range", "نطاق المدرج التكراري"), + ("Histogram Scan", "مسح المدرج التكراري"), + ("Histogram Shift", "إزاحة المدرج التكراري"), ("History", "السجل"), ( "Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", @@ -527,6 +530,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Not exported: no source in this texture set", "لم يتم التصدير: لا يوجد مصدر في مجموعة الخامات هذه"), ("Not saved: {error}", "لم يتم الحفظ: {error}"), ("Off", "معطل"), + ("Offset", "إزاحة"), ("Offset right", "إزاحة لليمين"), ("Offset up", "إزاحة لأعلى"), ("Offsets the textures by the height channel, at the height to normal strength", "يزيح الخامات وفق قناة الارتفاع، بقوة تحويل الارتفاع إلى ناظم"), @@ -609,6 +613,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Radial copies", "نُسخ دائرية"), ("Radius (texels at 2K)", "نصف القطر (تكسل بدقة 2K)"), ("RENDERING", "التصيير"), + ("Range", "النطاق"), ("Rebind any menu item, tool or command", "إعادة ربط أي عنصر قائمة، أو أداة أو أمر"), ("Recent projects", "المشاريع الأخيرة"), ( diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 5a8b20e2..cf3ffba2 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -393,6 +393,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("High poly mesh suffix", "Suffix für High-Poly-Mesh"), ("High poly: {name}", "High-Poly: {name}"), ("Highlights", "Lichter"), + ("Histogram Range", "Histogrammbereich"), + ("Histogram Scan", "Histogramm-Scan"), + ("Histogram Shift", "Histogramm-Verschiebung"), ("History", "Verlauf"), ( "Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", @@ -554,6 +557,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Not exported: no source in this texture set", "Nicht exportiert: keine Quelle in diesem Texturset"), ("Not saved: {error}", "Nicht gespeichert: {error}"), ("Off", "Aus"), + ("Offset", "Versatz"), ("Offset right", "Versatz rechts"), ("Offset up", "Versatz oben"), ( @@ -645,6 +649,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Radial copies", "Radiale Kopien"), ("Radius (texels at 2K)", "Radius (Texel bei 2K)"), ("RENDERING", "RENDERING"), + ("Range", "Bereich"), ("Rebind any menu item, tool or command", "Beliebige Menüeinträge, Werkzeuge oder Befehle neu belegen"), ("Recent projects", "Letzte Projekte"), ( diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index b100dba9..2e2a843b 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -387,6 +387,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("High poly mesh suffix", "Sufijo de malla high poly"), ("High poly: {name}", "High poly: {name}"), ("Highlights", "Iluminaciones"), + ("Histogram Range", "Rango de histograma"), + ("Histogram Scan", "Barrido de histograma"), + ("Histogram Shift", "Desplazamiento de histograma"), ("History", "Historial"), ( "Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", @@ -548,6 +551,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Not exported: no source in this texture set", "No exportado: no hay origen en este conjunto de texturas"), ("Not saved: {error}", "No guardado: {error}"), ("Off", "Desactivado"), + ("Offset", "Desplazamiento"), ("Offset right", "Desplazamiento a la derecha"), ("Offset up", "Desplazamiento hacia arriba"), ( @@ -636,6 +640,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Radial copies", "Copias radiales"), ("Radius (texels at 2K)", "Radio (téxeles a 2K)"), ("RENDERING", "RENDERIZADO"), + ("Range", "Rango"), ("Rebind any menu item, tool or command", "Reasignar cualquier elemento de menú, herramienta o comando"), ("Recent projects", "Proyectos recientes"), ( diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 486621d8..7ed03e59 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -393,6 +393,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("High poly mesh suffix", "Suffixe du maillage high poly"), ("High poly: {name}", "High poly : {name}"), ("Highlights", "Tons clairs"), + ("Histogram Range", "Plage d'histogramme"), + ("Histogram Scan", "Balayage d'histogramme"), + ("Histogram Shift", "Décalage d'histogramme"), ("History", "Historique"), ( "Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", @@ -557,6 +560,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Not exported: no source in this texture set", "Non exporté : aucune source dans cet ensemble de textures"), ("Not saved: {error}", "Non enregistré : {error}"), ("Off", "Désactivé"), + ("Offset", "Décalage"), ("Offset right", "Décalage vers la droite"), ("Offset up", "Décalage vers le haut"), ( @@ -645,6 +649,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Radial copies", "Copies radiales"), ("Radius (texels at 2K)", "Rayon (texels en 2K)"), ("RENDERING", "RENDU"), + ("Range", "Plage"), ("Rebind any menu item, tool or command", "Réattribuer n'importe quel élément de menu, outil ou commande"), ("Recent projects", "Projets récents"), ( diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 3044f373..d60f8f58 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -393,6 +393,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("High poly mesh suffix", "Suffisso mesh high poly"), ("High poly: {name}", "High poly: {name}"), ("Highlights", "Luci"), + ("Histogram Range", "Intervallo istogramma"), + ("Histogram Scan", "Scansione istogramma"), + ("Histogram Shift", "Spostamento istogramma"), ("History", "Cronologia"), ( "Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", @@ -554,6 +557,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Not exported: no source in this texture set", "Non esportato: nessuna sorgente in questo set di texture"), ("Not saved: {error}", "Non salvato: {error}"), ("Off", "Disattivato"), + ("Offset", "Scostamento"), ("Offset right", "Offset a destra"), ("Offset up", "Offset in alto"), ( @@ -645,6 +649,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Radial copies", "Copie radiali"), ("Radius (texels at 2K)", "Raggio (texel a 2K)"), ("RENDERING", "RENDERING"), + ("Range", "Intervallo"), ("Rebind any menu item, tool or command", "Riassegna qualsiasi voce di menu, strumento o comando"), ("Recent projects", "Progetti recenti"), ( diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index db9a40f8..5425a551 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -378,6 +378,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("High poly mesh suffix", "ハイポリメッシュの接尾辞"), ("High poly: {name}", "ハイポリ: {name}"), ("Highlights", "ハイライト"), + ("Histogram Range", "ヒストグラム範囲"), + ("Histogram Scan", "ヒストグラムスキャン"), + ("Histogram Shift", "ヒストグラムシフト"), ("History", "履歴"), ( "Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", @@ -539,6 +542,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Not exported: no source in this texture set", "エクスポートされません: このテクスチャセットにソースがありません"), ("Not saved: {error}", "保存されていません: {error}"), ("Off", "オフ"), + ("Offset", "オフセット"), ("Offset right", "右オフセット"), ("Offset up", "上オフセット"), ( @@ -624,6 +628,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Radial copies", "放射状コピー"), ("Radius (texels at 2K)", "半径 (2K時のテクセル)"), ("RENDERING", "レンダリング"), + ("Range", "範囲"), ("Rebind any menu item, tool or command", "メニュー項目、ツール、コマンドのショートカットを再割り当て"), ("Recent projects", "最近使ったプロジェクト"), ( diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index a8951370..ade48472 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -375,6 +375,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("High poly mesh suffix", "하이 폴리 메시 접미사"), ("High poly: {name}", "하이 폴리: {name}"), ("Highlights", "밝은 영역"), + ("Histogram Range", "히스토그램 범위"), + ("Histogram Scan", "히스토그램 스캔"), + ("Histogram Shift", "히스토그램 이동"), ("History", "히스토리"), ( "Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", @@ -533,6 +536,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Not exported: no source in this texture set", "내보내지 않음: 이 텍스처 세트에 소스가 없습니다"), ("Not saved: {error}", "저장되지 않음: {error}"), ("Off", "끄기"), + ("Offset", "오프셋"), ("Offset right", "오른쪽 오프셋"), ("Offset up", "위쪽 오프셋"), ("Offsets the textures by the height channel, at the height to normal strength", "높이-노멀 변환 강도로 높이 채널에 따라 텍스처를 오프셋합니다"), @@ -615,6 +619,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Radial copies", "방사형 복사본"), ("Radius (texels at 2K)", "반경 (2K 기준 텍셀)"), ("RENDERING", "렌더링"), + ("Range", "범위"), ("Rebind any menu item, tool or command", "메뉴 항목, 도구 또는 명령의 단축키를 다시 지정합니다"), ("Recent projects", "최근 프로젝트"), ( diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index e238c6ac..349cdd8d 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -387,6 +387,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("High poly mesh suffix", "Sufixo da malha high poly"), ("High poly: {name}", "High poly: {name}"), ("Highlights", "Realces"), + ("Histogram Range", "Intervalo do histograma"), + ("Histogram Scan", "Varredura do histograma"), + ("Histogram Shift", "Deslocamento do histograma"), ("History", "Histórico"), ( "Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", @@ -545,6 +548,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Not exported: no source in this texture set", "Não exportado: sem origem neste conjunto de texturas"), ("Not saved: {error}", "Não salvo: {error}"), ("Off", "Desligado"), + ("Offset", "Deslocamento"), ("Offset right", "Deslocamento à direita"), ("Offset up", "Deslocamento para cima"), ( @@ -633,6 +637,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Radial copies", "Cópias radiais"), ("Radius (texels at 2K)", "Raio (texels em 2K)"), ("RENDERING", "RENDERIZAÇÃO"), + ("Range", "Intervalo"), ("Rebind any menu item, tool or command", "Reatribuir qualquer item de menu, ferramenta ou comando"), ("Recent projects", "Projetos recentes"), ( diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 9a093a9f..cc9b84b3 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -339,6 +339,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("High poly mesh suffix", "高模网格后缀"), ("High poly: {name}", "高模:{name}"), ("Highlights", "高光"), + ("Histogram Range", "直方图范围"), + ("Histogram Scan", "直方图扫描"), + ("Histogram Shift", "直方图偏移"), ("History", "历史记录"), ("Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.", "按住 S:左键拖动旋转,右键拖动缩放,中键拖动移动模板。"), ("Hold V and click the mesh to set the clone source", "按住 V 并单击网格以设置仿制源"), @@ -488,6 +491,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Not exported: no source in this texture set", "未导出:此纹理集中没有来源"), ("Not saved: {error}", "未保存:{error}"), ("Off", "关"), + ("Offset", "偏移"), ("Offset right", "向右偏移"), ("Offset up", "向上偏移"), ("Offsets the textures by the height channel, at the height to normal strength", "按高度通道偏移纹理,偏移量取决于高度转法线强度"), @@ -567,6 +571,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Radial copies", "径向副本"), ("Radius (texels at 2K)", "半径(2K 下的纹素数)"), ("RENDERING", "渲染"), + ("Range", "范围"), ("Rebind any menu item, tool or command", "重新绑定任意菜单项、工具或命令"), ("Recent projects", "最近的项目"), ( diff --git a/docs/features.md b/docs/features.md index 090fdf77..bfd16641 100644 --- a/docs/features.md +++ b/docs/features.md @@ -32,11 +32,11 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA duplicate, group, flatten, cut, copy and paste across texture sets, and **geometry masks** that show a layer only on the mesh parts you pick (right-click a layer, or click parts with the **Geometry mask** tool, 8). -- **Filters and content effects** on any layer or mask: **28 filters** (HSL, levels, - contrast/luminosity, color balance, gradient map, posterize, clamp, invert, threshold, - grayscale, replace color, edge detect, normal invert, baked lighting, blur, directional and - slope blur, sharpen, high pass, bevel, glow, warp, directional warp, mosaic and four material - finishes), fills and paint. +- **Filters and content effects** on any layer or mask: **31 filters** (HSL, levels, + contrast/luminosity, color balance, gradient map, posterize, clamp, histogram scan, range and + shift, invert, threshold, grayscale, replace color, edge detect, normal invert, baked lighting, + blur, directional and slope blur, sharpen, high pass, bevel, glow, warp, directional warp, + mosaic and four material finishes), fills and paint. **Anchor points** record the stack at a layer so masks and fills higher up can react to it. - **Masks** with a white or black background and a stack of effects: painted strokes, fills, **mesh-map generators** (edge wear, dirt, thin areas, curvature, AO, position and direction From 332cfa407038878f8e452d1763cb0fd746cb4921 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 10:00:24 +0700 Subject: [PATCH 47/60] Levels histogram: bound the neighbourhood work under a filter A neighbourhood field covers the bounding box of its tiles, and a scattered sample spans the whole set, so on an 8K set a blur below the levels effect evaluated everything. With such a filter below, each sampled tile now builds its own field. --- crates/compose/src/eval.rs | 19 +++++++-- crates/engine/src/materials.rs | 54 ++++++++++++++++++++++++-- crates/engine/tests/content_effects.rs | 8 ++++ 3 files changed, 74 insertions(+), 7 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index b2386a6e..e4404588 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1884,20 +1884,31 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u let cut_inp = Inputs { project: &cut, preview: None, ..*inp }; let channels = cut.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height); - let fields = neighbourhood_fields(&cut_inp, &channels, &tiles); + // A field covers the bounding box of the tiles it is built for, which for a scattered sample + // is the whole set: with a neighbourhood filter below, each tile gets its own. + let probe = neighbourhood_fields(&cut_inp, &channels, tiles.get(..1).unwrap_or_default()); + let shared = probe.is_empty().then_some(probe); let bin = |v: f32| ((v.clamp(0.0, 1.0) * bins as f32) as usize).min(bins - 1); let hist = tiles .par_iter() .map(|&(tx, ty)| { + let own; + let fields = match &shared { + Some(f) => f, + None => { + own = neighbourhood_fields(&cut_inp, &channels, &[(tx, ty)]); + &own + } + }; let mut h = vec![0u32; bins]; // The mask is planned on its own: a layer with nothing drawn plans no node. - let mask = if in_mask { layer_mask(&cut, owner).and_then(|m| mask_plan(&cut_inp, owner, m, tx, ty, Some(&fields))) } else { None }; - let nodes = if in_mask { Vec::new() } else { plan(&cut_inp, &[owner], &channels, tx, ty, 0, Some(&fields)) }; + let mask = if in_mask { layer_mask(&cut, owner).and_then(|m| mask_plan(&cut_inp, owner, m, tx, ty, Some(fields))) } else { None }; + let nodes = if in_mask { Vec::new() } else { plan(&cut_inp, &[owner], &channels, tx, ty, 0, Some(fields)) }; let content = nodes.first().and_then(|n| n.chans.iter().find(|c| Channel::ALL.get(c.ch) == Some(&channel)).map(|c| (n, c))); if mask.is_none() && content.is_none() { return h; } - let full = anchor_plan(&cut_inp, owner, &channels, tx, ty, Some(&fields)); + let full = anchor_plan(&cut_inp, owner, &channels, tx, ty, Some(fields)); for (x, y, o) in tile_texels(inp.gbuf, tx, ty) { let mut tex = Texel::new(&cut_inp, x, y, o, 0.0); if !full.is_empty() { diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index 18c54577..34e57a6b 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -65,6 +65,9 @@ pub const MATERIALS: &[SmartMaterial] = &[ m("chrome", "Chrome", METAL, [0.55, 0.556, 0.554], 1.0, 0.05), m("titanium", "Titanium", METAL, [0.542, 0.497, 0.449], 1.0, 0.32), m("nickel", "Nickel", METAL, [0.66, 0.609, 0.526], 1.0, 0.25), + m("platinum", "Platinum", METAL, [0.673, 0.637, 0.585], 1.0, 0.2), + m("zinc", "Zinc", METAL, [0.664, 0.824, 0.85], 1.0, 0.38), + m("cobalt", "Cobalt", METAL, [0.662, 0.655, 0.634], 1.0, 0.3), m("galvanized", "Steel Galvanized", METAL, [0.69, 0.71, 0.72], 1.0, 0.4), m("rust", "Rust", METAL, [0.3, 0.1, 0.03], 0.0, 0.85), // Woods. @@ -73,6 +76,7 @@ pub const MATERIALS: &[SmartMaterial] = &[ m("wood_walnut", "Walnut", WOOD, [0.12, 0.06, 0.03], 0.0, 0.5), m("wood_pine", "Pine", WOOD, [0.52, 0.33, 0.16], 0.0, 0.65), m("plywood", "Plywood", WOOD, [0.55, 0.38, 0.21], 0.0, 0.75), + m("bark", "Bark", WOOD, [0.14, 0.1, 0.07], 0.0, 0.9), m("wood_painted", "Wood Painted", WOOD, [0.61, 0.59, 0.54], 0.0, 0.48), // Stone, masonry and earth. m("concrete", "Concrete", STONE, [0.27, 0.26, 0.25], 0.0, 0.9), @@ -86,6 +90,8 @@ pub const MATERIALS: &[SmartMaterial] = &[ m("slate", "Slate", STONE, [0.11, 0.115, 0.13], 0.0, 0.72), m("sandstone", "Sandstone", STONE, [0.52, 0.38, 0.23], 0.0, 0.9), m("terrazzo", "Terrazzo", STONE, [0.7, 0.69, 0.66], 0.0, 0.3), + m("sand", "Sand", STONE, [0.52, 0.41, 0.26], 0.0, 0.95), + m("mud", "Mud", STONE, [0.12, 0.08, 0.05], 0.0, 0.6), // Plastics, rubber, composites. m("plastic_glossy", "Plastic Glossy", PLASTIC, [0.8, 0.12, 0.08], 0.0, 0.16), m("plastic_matte", "Plastic Matte", PLASTIC, [0.18, 0.18, 0.19], 0.0, 0.6), @@ -102,12 +108,15 @@ pub const MATERIALS: &[SmartMaterial] = &[ m("ceramic", "Ceramic White", GLASS, [0.8, 0.8, 0.78], 0.0, 0.08), m("glass", "Glass Clear", GLASS, [0.88, 0.9, 0.9], 0.0, 0.03), m("glass_frosted", "Glass Frosted", GLASS, [0.84, 0.88, 0.88], 0.0, 0.45), + m("ice", "Ice", GLASS, [0.72, 0.82, 0.88], 0.0, 0.12), m("car_paint", "Car Paint", PLASTIC, [0.45, 0.025, 0.03], 0.0, 0.4), // Organic. m("skin", "Skin", ORGANIC, [0.56, 0.35, 0.27], 0.0, 0.5), m("wax", "Candle Wax", ORGANIC, [0.8, 0.72, 0.55], 0.0, 0.35), m("cork", "Cork", ORGANIC, [0.36, 0.21, 0.1], 0.0, 0.85), m("paper", "Paper", ORGANIC, [0.82, 0.81, 0.77], 0.0, 0.92), + m("snow", "Snow", ORGANIC, [0.85, 0.87, 0.9], 0.0, 0.6), + m("bone", "Bone", ORGANIC, [0.7, 0.63, 0.5], 0.0, 0.55), // Smart materials. sm("steel_painted_worn", "Steel Painted Worn", METAL, [0.42, 0.06, 0.04], 0.2, 0.45), sm("steel_painted_rust", "Steel Painted Rust Leaks", METAL, [0.62, 0.62, 0.6], 0.1, 0.5), @@ -232,10 +241,11 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { let clouds_rough = |seed: u32| gray(P::Clouds, 6.0, seed, r * 0.85, (r * 1.2).min(1.0)); match m.id { // ---- Metals ------------------------------------------------------------------------- - "steel" | "steel_dark" | "iron" | "copper" | "brass" | "bronze" | "gold_polished" | "silver" | "aluminium" | "chrome" | "nickel" => { - plain_metal(b, clouds_rough(7)) - } + "steel" | "steel_dark" | "iron" | "copper" | "brass" | "bronze" | "gold_polished" | "silver" | "aluminium" | "chrome" | "nickel" | "platinum" + | "cobalt" => plain_metal(b, clouds_rough(7)), "steel_stainless" | "aluminium_brushed" | "titanium" => plain_metal(b, gray(P::Brushed, 3.0, 3, r * 0.75, r * 1.25)), + // Zinc plate: large crystalline spangles. + "zinc" => one(b, metal(pat(P::Voronoi, 6.0, 21, 1.0, m.base.map(|v| v * 0.86), m.base), gray(P::Voronoi, 6.0, 21, r * 1.2, r * 0.8))), // Brushing lines run along X; the highlights stretch across them (a quarter turn). "steel_brushed_aniso" => one( b, @@ -275,6 +285,18 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { } // Stone chips in a pale binder, polished flat. "terrazzo" => one(b, dielectric(pat(P::Voronoi, 18.0, 9, 1.0, [0.55, 0.55, 0.53], [0.85, 0.84, 0.8]), gray(P::Voronoi, 18.0, 9, 0.34, 0.26))), + // Fine grains in soft wind ripples. + "sand" => { + one(b, plus(dielectric(pat(P::Noise, 1.0, 27, 1.0, [0.42, 0.32, 0.19], [0.6, 0.48, 0.31]), u(0.95)), height(gray(P::Perlin, 4.0, 27, -0.012, 0.0)))) + } + // Wet where it is low and dark, drier and rougher on the crests. + "mud" => one( + b, + plus( + dielectric(pat(P::Clouds, 3.0, 29, 1.0, [0.05, 0.035, 0.02], [0.17, 0.12, 0.075]), gray(P::Clouds, 3.0, 29, 0.25, 0.85)), + height(gray(P::Clouds, 3.0, 29, -0.03, 0.0)), + ), + ), "cork" => { one(b, plus(dielectric(pat(P::Noise, 6.0, 17, 1.0, [0.25, 0.14, 0.06], [0.45, 0.28, 0.13]), u(0.85)), height(gray(P::Pores, 20.0, 17, -0.01, 0.0)))) } @@ -310,6 +332,11 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { ), ), "plywood" => one(b, dielectric(pat(P::Wood, 1.2, 15, 0.6, [0.42, 0.27, 0.13], [0.66, 0.47, 0.27]), gray(P::Wood, 1.2, 15, 0.8, 0.7))), + // Deep furrows between darker, lichen-gray ridges. + "bark" => one( + b, + plus(dielectric(pat(P::Streaks, 3.0, 25, 1.4, [0.05, 0.035, 0.025], [0.24, 0.2, 0.15]), u(0.9)), height(gray(P::Streaks, 3.0, 25, -0.06, 0.0))), + ), "wood_painted" => one( b, plus( @@ -413,6 +440,27 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { "wax" => one(b, plus(dielectric(pat(P::Clouds, 2.0, 11, 1.0, [0.74, 0.66, 0.5], m.base), clouds_rough(11)), [(ScatterWeight, u(1.0))])), // ---- Glass (the Transmission channel; the base color tints the light going through) ---- "glass" => one(b, plus(dielectric(rgb(m.base), u(r)), [(Transmission, u(1.0))])), + // Clear with cloudy patches of trapped air. + "ice" => one( + b, + plus(dielectric(pat(P::Clouds, 4.0, 31, 1.0, m.base, [0.84, 0.88, 0.9]), clouds_rough(31)), [(Transmission, gray(P::Clouds, 4.0, 31, 0.9, 0.5))]), + ), + // Bright, rough and slightly translucent. + "snow" => one( + b, + plus( + dielectric(pat(P::Clouds, 4.0, 33, 1.0, [0.8, 0.82, 0.86], [0.88, 0.89, 0.9]), gray(P::Noise, 1.0, 33, 0.5, 0.7)), + [(ScatterWeight, u(0.5)), (Height, gray(P::Perlin, 3.0, 33, -0.02, 0.0))], + ), + ), + // Porous, ivory to tan, with a little light under the surface. + "bone" => one( + b, + plus( + dielectric(pat(P::Clouds, 5.0, 35, 1.0, [0.58, 0.5, 0.37], m.base), clouds_rough(35)), + [(ScatterWeight, u(0.3)), (Height, gray(P::Pores, 16.0, 35, -0.006, 0.0))], + ), + ), "glass_frosted" => one(b, plus(dielectric(rgb(m.base), gray(P::Noise, 1.0, 2, 0.4, 0.5)), [(Transmission, u(1.0))])), // ---- Smart materials ---------------------------------------------------------------- "steel_painted_worn" => { diff --git a/crates/engine/tests/content_effects.rs b/crates/engine/tests/content_effects.rs index 3ffec06f..0134b4c0 100644 --- a/crates/engine/tests/content_effects.rs +++ b/crates/engine/tests/content_effects.rs @@ -140,6 +140,14 @@ fn histogram_counts_what_an_effect_reads() { assert_eq!(target, "mask"); assert!(one(&bins, 1), "mask 0.3: {bins:?}"); assert_eq!(hist(&mut s, json!({"effect": ml})).1.len(), 64); + // Below a blur, every tile builds its own neighbourhood field; the texels counted stay the same. + let texels: u64 = bins.iter().sum(); + execute(&mut s, "effect.remove", &json!({"effect": ml})).unwrap(); + execute(&mut s, "effect.add.filter", &json!({"target": "mask", "filter": "blur", "radius": 4})).unwrap(); + let ml = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect"); + let (_, blurred) = hist(&mut s, json!({"effect": ml, "bins": 4})); + assert_eq!(blurred.iter().sum::(), texels); + assert_eq!(blurred.iter().enumerate().max_by_key(|(_, b)| **b).map(|(i, _)| i), Some(1), "{blurred:?}"); // A paint layer with nothing painted yet still has its mask. execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); execute(&mut s, "mask.add.black", &Value::Null).unwrap(); From d103cc3cfd9aa3200b397ced092552dc23275c65 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 10:02:34 +0700 Subject: [PATCH 48/60] Leave the material library out of this branch The new materials belong to their own change. --- crates/engine/src/materials.rs | 54 ++-------------------------------- 1 file changed, 3 insertions(+), 51 deletions(-) diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index 34e57a6b..18c54577 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -65,9 +65,6 @@ pub const MATERIALS: &[SmartMaterial] = &[ m("chrome", "Chrome", METAL, [0.55, 0.556, 0.554], 1.0, 0.05), m("titanium", "Titanium", METAL, [0.542, 0.497, 0.449], 1.0, 0.32), m("nickel", "Nickel", METAL, [0.66, 0.609, 0.526], 1.0, 0.25), - m("platinum", "Platinum", METAL, [0.673, 0.637, 0.585], 1.0, 0.2), - m("zinc", "Zinc", METAL, [0.664, 0.824, 0.85], 1.0, 0.38), - m("cobalt", "Cobalt", METAL, [0.662, 0.655, 0.634], 1.0, 0.3), m("galvanized", "Steel Galvanized", METAL, [0.69, 0.71, 0.72], 1.0, 0.4), m("rust", "Rust", METAL, [0.3, 0.1, 0.03], 0.0, 0.85), // Woods. @@ -76,7 +73,6 @@ pub const MATERIALS: &[SmartMaterial] = &[ m("wood_walnut", "Walnut", WOOD, [0.12, 0.06, 0.03], 0.0, 0.5), m("wood_pine", "Pine", WOOD, [0.52, 0.33, 0.16], 0.0, 0.65), m("plywood", "Plywood", WOOD, [0.55, 0.38, 0.21], 0.0, 0.75), - m("bark", "Bark", WOOD, [0.14, 0.1, 0.07], 0.0, 0.9), m("wood_painted", "Wood Painted", WOOD, [0.61, 0.59, 0.54], 0.0, 0.48), // Stone, masonry and earth. m("concrete", "Concrete", STONE, [0.27, 0.26, 0.25], 0.0, 0.9), @@ -90,8 +86,6 @@ pub const MATERIALS: &[SmartMaterial] = &[ m("slate", "Slate", STONE, [0.11, 0.115, 0.13], 0.0, 0.72), m("sandstone", "Sandstone", STONE, [0.52, 0.38, 0.23], 0.0, 0.9), m("terrazzo", "Terrazzo", STONE, [0.7, 0.69, 0.66], 0.0, 0.3), - m("sand", "Sand", STONE, [0.52, 0.41, 0.26], 0.0, 0.95), - m("mud", "Mud", STONE, [0.12, 0.08, 0.05], 0.0, 0.6), // Plastics, rubber, composites. m("plastic_glossy", "Plastic Glossy", PLASTIC, [0.8, 0.12, 0.08], 0.0, 0.16), m("plastic_matte", "Plastic Matte", PLASTIC, [0.18, 0.18, 0.19], 0.0, 0.6), @@ -108,15 +102,12 @@ pub const MATERIALS: &[SmartMaterial] = &[ m("ceramic", "Ceramic White", GLASS, [0.8, 0.8, 0.78], 0.0, 0.08), m("glass", "Glass Clear", GLASS, [0.88, 0.9, 0.9], 0.0, 0.03), m("glass_frosted", "Glass Frosted", GLASS, [0.84, 0.88, 0.88], 0.0, 0.45), - m("ice", "Ice", GLASS, [0.72, 0.82, 0.88], 0.0, 0.12), m("car_paint", "Car Paint", PLASTIC, [0.45, 0.025, 0.03], 0.0, 0.4), // Organic. m("skin", "Skin", ORGANIC, [0.56, 0.35, 0.27], 0.0, 0.5), m("wax", "Candle Wax", ORGANIC, [0.8, 0.72, 0.55], 0.0, 0.35), m("cork", "Cork", ORGANIC, [0.36, 0.21, 0.1], 0.0, 0.85), m("paper", "Paper", ORGANIC, [0.82, 0.81, 0.77], 0.0, 0.92), - m("snow", "Snow", ORGANIC, [0.85, 0.87, 0.9], 0.0, 0.6), - m("bone", "Bone", ORGANIC, [0.7, 0.63, 0.5], 0.0, 0.55), // Smart materials. sm("steel_painted_worn", "Steel Painted Worn", METAL, [0.42, 0.06, 0.04], 0.2, 0.45), sm("steel_painted_rust", "Steel Painted Rust Leaks", METAL, [0.62, 0.62, 0.6], 0.1, 0.5), @@ -241,11 +232,10 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { let clouds_rough = |seed: u32| gray(P::Clouds, 6.0, seed, r * 0.85, (r * 1.2).min(1.0)); match m.id { // ---- Metals ------------------------------------------------------------------------- - "steel" | "steel_dark" | "iron" | "copper" | "brass" | "bronze" | "gold_polished" | "silver" | "aluminium" | "chrome" | "nickel" | "platinum" - | "cobalt" => plain_metal(b, clouds_rough(7)), + "steel" | "steel_dark" | "iron" | "copper" | "brass" | "bronze" | "gold_polished" | "silver" | "aluminium" | "chrome" | "nickel" => { + plain_metal(b, clouds_rough(7)) + } "steel_stainless" | "aluminium_brushed" | "titanium" => plain_metal(b, gray(P::Brushed, 3.0, 3, r * 0.75, r * 1.25)), - // Zinc plate: large crystalline spangles. - "zinc" => one(b, metal(pat(P::Voronoi, 6.0, 21, 1.0, m.base.map(|v| v * 0.86), m.base), gray(P::Voronoi, 6.0, 21, r * 1.2, r * 0.8))), // Brushing lines run along X; the highlights stretch across them (a quarter turn). "steel_brushed_aniso" => one( b, @@ -285,18 +275,6 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { } // Stone chips in a pale binder, polished flat. "terrazzo" => one(b, dielectric(pat(P::Voronoi, 18.0, 9, 1.0, [0.55, 0.55, 0.53], [0.85, 0.84, 0.8]), gray(P::Voronoi, 18.0, 9, 0.34, 0.26))), - // Fine grains in soft wind ripples. - "sand" => { - one(b, plus(dielectric(pat(P::Noise, 1.0, 27, 1.0, [0.42, 0.32, 0.19], [0.6, 0.48, 0.31]), u(0.95)), height(gray(P::Perlin, 4.0, 27, -0.012, 0.0)))) - } - // Wet where it is low and dark, drier and rougher on the crests. - "mud" => one( - b, - plus( - dielectric(pat(P::Clouds, 3.0, 29, 1.0, [0.05, 0.035, 0.02], [0.17, 0.12, 0.075]), gray(P::Clouds, 3.0, 29, 0.25, 0.85)), - height(gray(P::Clouds, 3.0, 29, -0.03, 0.0)), - ), - ), "cork" => { one(b, plus(dielectric(pat(P::Noise, 6.0, 17, 1.0, [0.25, 0.14, 0.06], [0.45, 0.28, 0.13]), u(0.85)), height(gray(P::Pores, 20.0, 17, -0.01, 0.0)))) } @@ -332,11 +310,6 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { ), ), "plywood" => one(b, dielectric(pat(P::Wood, 1.2, 15, 0.6, [0.42, 0.27, 0.13], [0.66, 0.47, 0.27]), gray(P::Wood, 1.2, 15, 0.8, 0.7))), - // Deep furrows between darker, lichen-gray ridges. - "bark" => one( - b, - plus(dielectric(pat(P::Streaks, 3.0, 25, 1.4, [0.05, 0.035, 0.025], [0.24, 0.2, 0.15]), u(0.9)), height(gray(P::Streaks, 3.0, 25, -0.06, 0.0))), - ), "wood_painted" => one( b, plus( @@ -440,27 +413,6 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { "wax" => one(b, plus(dielectric(pat(P::Clouds, 2.0, 11, 1.0, [0.74, 0.66, 0.5], m.base), clouds_rough(11)), [(ScatterWeight, u(1.0))])), // ---- Glass (the Transmission channel; the base color tints the light going through) ---- "glass" => one(b, plus(dielectric(rgb(m.base), u(r)), [(Transmission, u(1.0))])), - // Clear with cloudy patches of trapped air. - "ice" => one( - b, - plus(dielectric(pat(P::Clouds, 4.0, 31, 1.0, m.base, [0.84, 0.88, 0.9]), clouds_rough(31)), [(Transmission, gray(P::Clouds, 4.0, 31, 0.9, 0.5))]), - ), - // Bright, rough and slightly translucent. - "snow" => one( - b, - plus( - dielectric(pat(P::Clouds, 4.0, 33, 1.0, [0.8, 0.82, 0.86], [0.88, 0.89, 0.9]), gray(P::Noise, 1.0, 33, 0.5, 0.7)), - [(ScatterWeight, u(0.5)), (Height, gray(P::Perlin, 3.0, 33, -0.02, 0.0))], - ), - ), - // Porous, ivory to tan, with a little light under the surface. - "bone" => one( - b, - plus( - dielectric(pat(P::Clouds, 5.0, 35, 1.0, [0.58, 0.5, 0.37], m.base), clouds_rough(35)), - [(ScatterWeight, u(0.3)), (Height, gray(P::Pores, 16.0, 35, -0.006, 0.0))], - ), - ), "glass_frosted" => one(b, plus(dielectric(rgb(m.base), gray(P::Noise, 1.0, 2, 0.4, 0.5)), [(Transmission, u(1.0))])), // ---- Smart materials ---------------------------------------------------------------- "steel_painted_worn" => { From 4913131cf746c2f96e77a27f4c9e4ced1d3563cc Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 10:09:29 +0700 Subject: [PATCH 49/60] Materials: platinum, zinc, cobalt, bark, sand, mud, ice, snow and bone Nine procedural materials for the shelf: three metals from measured reflectance (zinc with crystalline spangles), bark with deep furrows, fine-grained sand, mud with glossy wet patches, ice with cloudy air pockets under transmission, and snow and bone with a little subsurface scattering. --- crates/engine/src/materials.rs | 55 ++++++++++++++++++++++++++++++++-- docs/features.md | 5 ++-- 2 files changed, 55 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index 18c54577..0b87a4e6 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -65,6 +65,9 @@ pub const MATERIALS: &[SmartMaterial] = &[ m("chrome", "Chrome", METAL, [0.55, 0.556, 0.554], 1.0, 0.05), m("titanium", "Titanium", METAL, [0.542, 0.497, 0.449], 1.0, 0.32), m("nickel", "Nickel", METAL, [0.66, 0.609, 0.526], 1.0, 0.25), + m("platinum", "Platinum", METAL, [0.673, 0.637, 0.585], 1.0, 0.2), + m("zinc", "Zinc", METAL, [0.664, 0.824, 0.85], 1.0, 0.38), + m("cobalt", "Cobalt", METAL, [0.662, 0.655, 0.634], 1.0, 0.3), m("galvanized", "Steel Galvanized", METAL, [0.69, 0.71, 0.72], 1.0, 0.4), m("rust", "Rust", METAL, [0.3, 0.1, 0.03], 0.0, 0.85), // Woods. @@ -73,6 +76,7 @@ pub const MATERIALS: &[SmartMaterial] = &[ m("wood_walnut", "Walnut", WOOD, [0.12, 0.06, 0.03], 0.0, 0.5), m("wood_pine", "Pine", WOOD, [0.52, 0.33, 0.16], 0.0, 0.65), m("plywood", "Plywood", WOOD, [0.55, 0.38, 0.21], 0.0, 0.75), + m("bark", "Bark", WOOD, [0.14, 0.1, 0.07], 0.0, 0.9), m("wood_painted", "Wood Painted", WOOD, [0.61, 0.59, 0.54], 0.0, 0.48), // Stone, masonry and earth. m("concrete", "Concrete", STONE, [0.27, 0.26, 0.25], 0.0, 0.9), @@ -86,6 +90,8 @@ pub const MATERIALS: &[SmartMaterial] = &[ m("slate", "Slate", STONE, [0.11, 0.115, 0.13], 0.0, 0.72), m("sandstone", "Sandstone", STONE, [0.52, 0.38, 0.23], 0.0, 0.9), m("terrazzo", "Terrazzo", STONE, [0.7, 0.69, 0.66], 0.0, 0.3), + m("sand", "Sand", STONE, [0.52, 0.41, 0.26], 0.0, 0.95), + m("mud", "Mud", STONE, [0.12, 0.08, 0.05], 0.0, 0.6), // Plastics, rubber, composites. m("plastic_glossy", "Plastic Glossy", PLASTIC, [0.8, 0.12, 0.08], 0.0, 0.16), m("plastic_matte", "Plastic Matte", PLASTIC, [0.18, 0.18, 0.19], 0.0, 0.6), @@ -102,12 +108,15 @@ pub const MATERIALS: &[SmartMaterial] = &[ m("ceramic", "Ceramic White", GLASS, [0.8, 0.8, 0.78], 0.0, 0.08), m("glass", "Glass Clear", GLASS, [0.88, 0.9, 0.9], 0.0, 0.03), m("glass_frosted", "Glass Frosted", GLASS, [0.84, 0.88, 0.88], 0.0, 0.45), + m("ice", "Ice", GLASS, [0.72, 0.82, 0.88], 0.0, 0.12), m("car_paint", "Car Paint", PLASTIC, [0.45, 0.025, 0.03], 0.0, 0.4), // Organic. m("skin", "Skin", ORGANIC, [0.56, 0.35, 0.27], 0.0, 0.5), m("wax", "Candle Wax", ORGANIC, [0.8, 0.72, 0.55], 0.0, 0.35), m("cork", "Cork", ORGANIC, [0.36, 0.21, 0.1], 0.0, 0.85), m("paper", "Paper", ORGANIC, [0.82, 0.81, 0.77], 0.0, 0.92), + m("snow", "Snow", ORGANIC, [0.85, 0.87, 0.9], 0.0, 0.6), + m("bone", "Bone", ORGANIC, [0.7, 0.63, 0.5], 0.0, 0.55), // Smart materials. sm("steel_painted_worn", "Steel Painted Worn", METAL, [0.42, 0.06, 0.04], 0.2, 0.45), sm("steel_painted_rust", "Steel Painted Rust Leaks", METAL, [0.62, 0.62, 0.6], 0.1, 0.5), @@ -232,10 +241,11 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { let clouds_rough = |seed: u32| gray(P::Clouds, 6.0, seed, r * 0.85, (r * 1.2).min(1.0)); match m.id { // ---- Metals ------------------------------------------------------------------------- - "steel" | "steel_dark" | "iron" | "copper" | "brass" | "bronze" | "gold_polished" | "silver" | "aluminium" | "chrome" | "nickel" => { - plain_metal(b, clouds_rough(7)) - } + "steel" | "steel_dark" | "iron" | "copper" | "brass" | "bronze" | "gold_polished" | "silver" | "aluminium" | "chrome" | "nickel" | "platinum" + | "cobalt" => plain_metal(b, clouds_rough(7)), "steel_stainless" | "aluminium_brushed" | "titanium" => plain_metal(b, gray(P::Brushed, 3.0, 3, r * 0.75, r * 1.25)), + // Zinc plate: large crystalline spangles. + "zinc" => one(b, metal(pat(P::Voronoi, 6.0, 21, 1.0, m.base.map(|v| v * 0.8), m.base), gray(P::Voronoi, 6.0, 21, r * 1.5, r * 0.6))), // Brushing lines run along X; the highlights stretch across them (a quarter turn). "steel_brushed_aniso" => one( b, @@ -275,6 +285,19 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { } // Stone chips in a pale binder, polished flat. "terrazzo" => one(b, dielectric(pat(P::Voronoi, 18.0, 9, 1.0, [0.55, 0.55, 0.53], [0.85, 0.84, 0.8]), gray(P::Voronoi, 18.0, 9, 0.34, 0.26))), + // Fine grains in soft wind ripples. + "sand" => one( + b, + plus(dielectric(pat(P::Noise, 12.0, 27, 1.0, [0.42, 0.32, 0.19], [0.6, 0.48, 0.31]), u(0.95)), height(gray(P::Perlin, 4.0, 27, -0.012, 0.0))), + ), + // Glossy wet patches over rougher, drier mud. + "mud" => one( + b, + plus( + dielectric(pat(P::Clouds, 3.0, 29, 1.0, [0.05, 0.035, 0.02], [0.17, 0.12, 0.075]), gray(P::Grunge, 3.0, 29, 0.85, 0.2)), + height(gray(P::Clouds, 3.0, 29, -0.03, 0.0)), + ), + ), "cork" => { one(b, plus(dielectric(pat(P::Noise, 6.0, 17, 1.0, [0.25, 0.14, 0.06], [0.45, 0.28, 0.13]), u(0.85)), height(gray(P::Pores, 20.0, 17, -0.01, 0.0)))) } @@ -310,6 +333,11 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { ), ), "plywood" => one(b, dielectric(pat(P::Wood, 1.2, 15, 0.6, [0.42, 0.27, 0.13], [0.66, 0.47, 0.27]), gray(P::Wood, 1.2, 15, 0.8, 0.7))), + // Dark, deep furrows between gray-brown ridges. + "bark" => one( + b, + plus(dielectric(pat(P::Streaks, 8.0, 25, 1.4, [0.13, 0.105, 0.08], [0.03, 0.022, 0.015]), u(0.9)), height(gray(P::Streaks, 8.0, 25, 0.0, -0.06))), + ), "wood_painted" => one( b, plus( @@ -413,6 +441,27 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { "wax" => one(b, plus(dielectric(pat(P::Clouds, 2.0, 11, 1.0, [0.74, 0.66, 0.5], m.base), clouds_rough(11)), [(ScatterWeight, u(1.0))])), // ---- Glass (the Transmission channel; the base color tints the light going through) ---- "glass" => one(b, plus(dielectric(rgb(m.base), u(r)), [(Transmission, u(1.0))])), + // Clear with cloudy patches of trapped air. + "ice" => one( + b, + plus(dielectric(pat(P::Clouds, 4.0, 31, 1.0, m.base, [0.84, 0.88, 0.9]), clouds_rough(31)), [(Transmission, gray(P::Clouds, 4.0, 31, 0.9, 0.5))]), + ), + // Bright, rough and slightly translucent. + "snow" => one( + b, + plus( + dielectric(pat(P::Clouds, 4.0, 33, 1.0, [0.8, 0.82, 0.86], [0.88, 0.89, 0.9]), gray(P::Noise, 1.0, 33, 0.5, 0.7)), + [(ScatterWeight, u(0.5)), (Height, gray(P::Perlin, 3.0, 33, -0.02, 0.0))], + ), + ), + // Porous, ivory to tan, with a little light under the surface. + "bone" => one( + b, + plus( + dielectric(pat(P::Clouds, 5.0, 35, 1.0, [0.58, 0.5, 0.37], m.base), clouds_rough(35)), + [(ScatterWeight, u(0.3)), (Height, gray(P::Pores, 16.0, 35, -0.006, 0.0))], + ), + ), "glass_frosted" => one(b, plus(dielectric(rgb(m.base), gray(P::Noise, 1.0, 2, 0.4, 0.5)), [(Transmission, u(1.0))])), // ---- Smart materials ---------------------------------------------------------------- "steel_painted_worn" => { diff --git a/docs/features.md b/docs/features.md index 4fd44e27..f200fe82 100644 --- a/docs/features.md +++ b/docs/features.md @@ -46,8 +46,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA grain, bricks, fabric weave, twill, leather grain, marble veins, Voronoi, paint chips…) or your own **images**, through UV, tri-planar, planar, spherical, cylindrical or decal projection. Alt+click a material channel (of a fill or the brush) to keep that channel alone. -- **54 materials** (metals from measured reflectance, car paint, brushed anisotropic steel, - velvet, skin, wax, glass, woods, stone, plastics, fabric, leather, ceramic, rust, cork, paper), **21 smart +- **63 materials** (metals from measured reflectance, car paint, brushed anisotropic steel, + velvet, skin, wax, glass, ice, woods, bark, stone, sand, mud, snow, bone, plastics, fabric, + leather, ceramic, rust, cork, paper), **21 smart materials** (rusted iron, worn paint, oxidized copper, bronze statue, weathered wood, mossy brick and stone, sun-faded paint…) and **18 smart masks**, all procedural, so they work at any resolution. Drag them from the tabbed, searchable shelf onto the layer stack or straight onto From 6c93db99c67222e21cd0f7449319d0a8f1f90c7e Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 10:12:32 +0700 Subject: [PATCH 50/60] Docs: roadmap after the levels histogram, web save prompt, filters and materials --- ROADMAP.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index bd816e59..724e3a28 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -11,17 +11,17 @@ end to end today (engine + UI + automation + tests), not what is planned. | Area | Weight | Done | What works | Main gaps | |---|---:|---:|---|---| -| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project, recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | +| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project (in the browser too, and before the tab closes), recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | | Texture sets | 6 | 95% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile**, one texture per tile at its own size, `$udim` export), list with visibility (show or hide all, invert, **focus** on one set), sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | Filter radii and height slopes of a tile smaller than its atlas block follow the block | -| Layer stack | 16 | 96% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels, invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **27 library filters** (adjustments, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | +| Layer stack | 16 | 97% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels (with a histogram of its input), invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **30 library filters** (adjustments incl. histogram scan, range and shift, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | | Painting tools | 14 | 90% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt (not exposed by the windowing layer) | -| Materials and assets | 8 | 88% | 48 procedural materials (incl. car paint, velvet, brushed steel, skin, wax), 21 smart materials, 18 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 23 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | +| Materials and assets | 8 | 90% | 63 procedural materials (incl. car paint, velvet, brushed steel, skin, wax, ice, snow, bark), 21 smart materials, 18 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 23 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | | Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — | | Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, the baked normal map under the painted normal, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Hardware ray tracing | | Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — | | Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, `$udim` tiles, OBJ, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | -| UI and UX | 8 | 95% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, a **start window** (new, open, recent projects), **shortcut editor** with conflict detection, tooltips with shortcuts; all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations | -| Platforms | 4 | 75% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish | +| UI and UX | 8 | 96% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, a **start window** (new, open, recent projects), **shortcut editor** with conflict detection, tooltips with shortcuts, a compact color picker (saturation/value square, hue strip, copyable RGB); all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations | +| Platforms | 4 | 76% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish | | **Total** | **100** | **≈ 94%** | | | Beyond the reference app: every command is available to agents through MCP, the CLI and the app's From d5c2f793fd5e9bb31d59df08847bb066331ade67 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 10:39:41 +0700 Subject: [PATCH 51/60] Histogram Scan: full contrast is a threshold At contrast 1 the narrowest ramp still sent a value equal to the position to mid gray. It now matches Threshold: the position and everything above it go to white. --- crates/core/src/layer.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index ed263910..6975e1b3 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -757,6 +757,8 @@ impl Filter { let (lo, hi) = (min.min(*max), min.max(*max)); per_unit(kind, v, |x| x.max(lo).min(hi)) } + // Full contrast is a threshold: the position itself goes to white. + Filter::HistogramScan { position, contrast } if *contrast >= 1.0 => per_unit(kind, v, |x| if x >= *position { 1.0 } else { 0.0 }), Filter::HistogramScan { position, contrast } => { let width = (1.0 - contrast.clamp(0.0, 1.0)).max(1e-3); per_unit(kind, v, |x| unit((x - position) / width + 0.5)) @@ -1005,6 +1007,7 @@ mod tests { let scan = |position, contrast| Filter::HistogramScan { position, contrast }.point(c, [0.2, 0.5, 0.9]).unwrap(); assert!(close(scan(0.5, 0.0), [0.2, 0.5, 0.9]), "a full-width ramp at the middle keeps the values"); assert!(close(scan(0.4, 1.0), [0.0, 1.0, 1.0]), "full contrast is a step at the position"); + assert!(close(scan(0.5, 1.0), [0.0, 1.0, 1.0]), "the position itself goes to white"); assert!(close(scan(0.7, 0.5), [0.0, 0.1, 0.9])); let range = |range, position| Filter::HistogramRange { range, position }.point(c, [0.2, 0.5, 0.9]).unwrap(); assert!(close(range(1.0, 0.3), [0.2, 0.5, 0.9]) && close(range(0.0, 0.3), [0.3; 3])); From 0d2f1873cda17c5d767828b2839e9aeacb4b2c79 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:13:00 +0700 Subject: [PATCH 52/60] Effects: drag to reorder, duplicate Effect rows in the layer stack can be dragged within their stack (a drop lands above the row, or below it from its lower half), and their context menu duplicates an effect just above itself, painted pixels included. effect.move {effect, index} and effect.duplicate {effect} give agents the same. --- crates/engine/src/mask_cmds.rs | 56 +++++++++++++++++++++++++- crates/engine/tests/content_effects.rs | 39 ++++++++++++++++++ crates/ui-egui/src/dock.rs | 47 +++++++++++++++++---- crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/tests/effect_rows.rs | 48 ++++++++++++++++++++++ docs/control-protocol.md | 4 +- docs/features.md | 3 +- 15 files changed, 195 insertions(+), 11 deletions(-) create mode 100644 crates/ui-egui/tests/effect_rows.rs diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index f570c0c9..90d54c0b 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use texturecraft_core::{ BlendMode, Channel, CompareOp, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, Procedural, ProceduralKind, - Source, + Project, Source, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -99,6 +99,8 @@ pub fn specs() -> Vec { set ), cmd!("effect.remove", "Remove effect", [], None, "{effect}", has_layer, remove_effect), + cmd!("effect.duplicate", "Duplicate effect", [], None, "{effect} → {effect} (the copy, just above it, pixels included)", has_layer, duplicate_effect), + cmd!("effect.move", "Move effect", [], None, "{effect, index: position in its stack, 0 = bottom (applied first)}", has_layer, move_effect), cmd!( "effect.histogram", "Effect input histogram", @@ -456,6 +458,58 @@ fn set(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// The stack (a mask's or a layer's content effects) holding effect `eid`, and its position there. +fn stack_of(project: &mut Project, eid: LayerId) -> Option<(&mut Vec, usize)> { + project.layers.values_mut().find_map(|l| { + l.mask.iter_mut().map(|m| &mut m.effects).chain(std::iter::once(&mut l.content_effects)).find_map(|list| { + let i = list.iter().position(|e| e.id == eid)?; + Some((list, i)) + }) + }) +} + +fn duplicate_effect(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "effect.duplicate"; + let eid = effect_id(p, CMD)?; + let new = s.edit("Duplicate effect", |s| { + let new = s.doc.project.alloc_id(); + let (list, i) = stack_of(&mut s.doc.project, eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?; + let mut e = list.get(i).cloned().ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?; + e.id = new; + e.name = format!("{} copy", e.name); + list.insert(i + 1, e); + // Painted effects keep their pixels (copy-on-write tiles: cheap). + let px = &mut s.doc.pixels; + if let Some(img) = px.masks.get(&eid).cloned() { + px.masks.insert(new, img); + } + for c in Channel::ALL { + if let Some(img) = px.layer(eid, c).cloned() { + px.layers.insert((new, c), img); + } + } + Ok(new) + })?; + if s.target == StackTarget::Effect(eid) { + s.target = StackTarget::Effect(new); + } + Ok(json!({ "effect": new.0 })) +} + +fn move_effect(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "effect.move"; + let eid = effect_id(p, CMD)?; + let index = u64p(p, "index").ok_or_else(|| bad(CMD, "`index` is required"))?; + s.edit("Move effect", |s| { + let (list, i) = stack_of(&mut s.doc.project, eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?; + let e = list.remove(i); + let to = usize::try_from(index).unwrap_or(usize::MAX).min(list.len()); + list.insert(to, e); + Ok(()) + })?; + Ok(Value::Null) +} + fn remove_effect(s: &mut Session, p: &Value) -> Result { let eid = effect_id(p, "effect.remove")?; s.edit("Remove effect", |s| { diff --git a/crates/engine/tests/content_effects.rs b/crates/engine/tests/content_effects.rs index 0134b4c0..d67300f7 100644 --- a/crates/engine/tests/content_effects.rs +++ b/crates/engine/tests/content_effects.rs @@ -112,6 +112,45 @@ fn painting_into_a_content_paint_effect() { assert!(center(&mut s, Channel::Roughness)[0] > 0.85); } +#[test] +fn effects_move_within_their_stack_and_duplicate_with_their_pixels() { + let mut s = session(); + let layer = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3})).unwrap(), "layer"); + let paint = id(execute(&mut s, "effect.add.paint", &json!({"target": "content"})).unwrap(), "effect"); + execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.9})).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); + let fill = id(execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.2})).unwrap(), "effect"); + let order = |s: &Session| s.doc.project.layer(LayerId(layer)).unwrap().content_effects.iter().map(|e| e.id.0).collect::>(); + assert!(close(center(&mut s, Channel::Roughness), [0.2; 3]), "the fill covers the paint"); + // To the bottom, the paint shows again; an index past the end means the top. + execute(&mut s, "effect.move", &json!({"effect": fill, "index": 0})).unwrap(); + assert_eq!(order(&s), [fill, paint]); + assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "{:?}", center(&mut s, Channel::Roughness)); + execute(&mut s, "effect.move", &json!({"effect": fill, "index": 99})).unwrap(); + assert_eq!(order(&s), [paint, fill]); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(order(&s), [fill, paint]); + assert!(execute(&mut s, "effect.move", &json!({"effect": fill})).is_err(), "index is required"); + assert!(execute(&mut s, "effect.move", &json!({"effect": 999_999, "index": 0})).is_err()); + // A duplicate sits just above its original with the painted pixels, and takes the selection. + execute(&mut s, "layer.select", &json!({"layer": layer, "target": paint})).unwrap(); + let copy = id(execute(&mut s, "effect.duplicate", &json!({"effect": paint})).unwrap(), "effect"); + assert_eq!(order(&s), [fill, paint, copy]); + assert_eq!(s.target, StackTarget::Effect(LayerId(copy))); + assert!(s.doc.project.effect(LayerId(copy)).unwrap().1.name.ends_with(" copy")); + execute(&mut s, "effect.remove", &json!({"effect": paint})).unwrap(); + assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "the copy keeps the strokes"); + assert!(execute(&mut s, "effect.duplicate", &json!({"effect": 999_999})).is_err()); + // Mask effects move within the mask. + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + let a = id(execute(&mut s, "effect.add.fill", &json!({"target": "mask", "value": 0.3})).unwrap(), "effect"); + let b = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect"); + execute(&mut s, "effect.move", &json!({"effect": b, "index": 0})).unwrap(); + let mask: Vec = s.doc.project.layer(LayerId(layer)).unwrap().mask.as_ref().unwrap().effects.iter().map(|e| e.id.0).collect(); + assert_eq!(mask, [b, a]); +} + #[test] fn histogram_counts_what_an_effect_reads() { let mut s = session(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index ba2ddcfd..018f06cf 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -5,7 +5,7 @@ use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, Decal, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, ProceduralKind, Source, + BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, ProceduralKind, Source, }; use texturecraft_engine::filter_lib::{FILTERS, scalar_params}; use texturecraft_engine::paint::{BrushAlpha, alphas}; @@ -255,11 +255,11 @@ fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize) let Some(layer) = app.session.doc.project.layers.get(&id).cloned() else { return }; layer_row(app, ui, &layer, depth); for e in layer.content_effects.iter().rev() { - effect_row(app, ui, &layer, e.id, &e.name, e.visible, depth + 1, ic::SPHERE); + effect_row(app, ui, &layer, &layer.content_effects, e, depth + 1, ic::SPHERE); } if let Some(m) = &layer.mask { for e in m.effects.iter().rev() { - effect_row(app, ui, &layer, e.id, &e.name, e.visible, depth + 1, ic::MAGIC_WAND); + effect_row(app, ui, &layer, &m.effects, e, depth + 1, ic::MAGIC_WAND); } } if let LayerKind::Group { children, collapsed } = &layer.kind @@ -522,12 +522,16 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize resp.context_menu(|ui| layer_context_menu(app, ui, layer)); } -/// One effect of a layer's content (`glyph` sphere) or mask (`glyph` wand) stack. -#[allow(clippy::too_many_arguments)] -fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId, name: &str, visible: bool, depth: usize, glyph: &str) { +/// The drag-and-drop payload of an effect row (the effect id). +struct EffectDrag(u64); + +/// Effect `e` of `stack`, a layer's content (`glyph` sphere) or mask (`glyph` wand) effects. +fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Effect], e: &Effect, depth: usize, glyph: &str) { let tk = Tokens::get(ui.ctx()); + let (eid, visible) = (e.id, e.visible); let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(eid); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag()); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &e.name)); let p = ui.painter().clone(); p.rect_filled( rect.shrink2(vec2(0.0, 1.0)), @@ -548,13 +552,40 @@ fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerI let er = ui.interact(eye, ui.scope_id().with(("eff_eye", eid.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect")); p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(12.0), tk.text_dim); p.text(pos2(x0 + 22.0, rect.center().y), egui::Align2::LEFT_CENTER, glyph, egui::FontId::proportional(11.0), tk.text_dim); - p.text(pos2(x0 + 38.0, rect.center().y), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(11.5), tk.text); + p.text(pos2(x0 + 38.0, rect.center().y), egui::Align2::LEFT_CENTER, &e.name, egui::FontId::proportional(11.5), tk.text); if er.clicked() { app.run("effect.set", json!({"effect": eid.0, "visible": !visible})); } else if resp.clicked() { app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); } + // Drag to reorder within the stack: a drop lands above this row, or below it from its lower half. + if resp.drag_started() { + resp.dnd_set_drag_payload(EffectDrag(eid.0)); + } + let pos = |id: u64| stack.iter().position(|x| x.id.0 == id); + let below = ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| p.y > rect.center().y); + if resp.dnd_hover_payload::().is_some_and(|src| src.0 != eid.0 && pos(src.0).is_some()) { + let y = if below { rect.bottom() } else { rect.top() }; + p.line_segment([pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(2.0, tk.accent)); + } + if let Some(src) = dnd_release::(&resp) + && let (Some(from), Some(to)) = (pos(src.0), pos(eid.0)) + && from != to + { + // Rows list the stack top first, so above this row is the next index up. + let index = match (from < to, below) { + (true, false) | (false, true) => to, + (true, true) => to - 1, + (false, false) => to + 1, + }; + app.run("effect.move", json!({"effect": src.0, "index": index})); + } resp.context_menu(|ui| { + if ui.button(tr("Duplicate effect")).clicked() { + app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); + app.run("effect.duplicate", json!({"effect": eid.0})); + ui.close(); + } if ui.button(tr("Remove effect")).clicked() { app.run("effect.remove", json!({"effect": eid.0})); ui.close(); diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 75c795b3..ebd718d3 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -264,6 +264,7 @@ pub const TABLE: &[(&str, &str)] = &[ "اسحب الإطار لتحريك الملصق، أو الزاوية لتغيير حجمه، أو المقبض الدائري لتدويره", ), ("Dry streaks", "خطوط جافة"), + ("Duplicate effect", "تكرار التأثير"), ("Duplicate layer(s)", "تكرار الطبقة (الطبقات)"), ("Duplicate the selected template", "تكرار القالب المحدد"), ("Edge Detect", "اكتشاف الحواف"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index b0341184..6e6fa352 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -282,6 +282,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Rahmen ziehen, um das Decal zu verschieben, eine Ecke zum Skalieren, den runden Griff zum Drehen", ), ("Dry streaks", "Trockene Schlieren"), + ("Duplicate effect", "Effekt duplizieren"), ("Duplicate layer(s)", "Ebene(n) duplizieren"), ("Duplicate the selected template", "Ausgewählte Vorlage duplizieren"), ("Edge Detect", "Kantenerkennung"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index df2151d9..4f6fc01a 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -279,6 +279,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Arrastra el marco para mover la calcomanía, una esquina para escalarla y el tirador redondo para girarla", ), ("Dry streaks", "Trazos secos"), + ("Duplicate effect", "Duplicar efecto"), ("Duplicate layer(s)", "Duplicar capa(s)"), ("Duplicate the selected template", "Duplicar la plantilla seleccionada"), ("Edge Detect", "Detección de bordes"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 2b943710..2cdf3974 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -282,6 +282,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Faites glisser le cadre pour déplacer le décalque, un coin pour le mettre à l'échelle, la poignée ronde pour le faire pivoter", ), ("Dry streaks", "Traînées sèches"), + ("Duplicate effect", "Dupliquer l'effet"), ("Duplicate layer(s)", "Dupliquer le(s) calque(s)"), ("Duplicate the selected template", "Dupliquer le modèle sélectionné"), ("Edge Detect", "Détection des contours"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 5192aef7..0d3f774e 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -285,6 +285,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Trascina il riquadro per spostare la decal, un angolo per scalarla, la maniglia rotonda per ruotarla", ), ("Dry streaks", "Striature secche"), + ("Duplicate effect", "Duplica effetto"), ("Duplicate layer(s)", "Duplica livello/i"), ("Duplicate the selected template", "Duplica il modello selezionato"), ("Edge Detect", "Rilevamento bordi"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 9b1d9be9..ab32816f 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -273,6 +273,7 @@ pub const TABLE: &[(&str, &str)] = &[ "テクスチャセット「{set}」の {name} を描画します。ソースへの編集はすべてのインスタンスに反映されます。", ), ("Dry streaks", "かすれ"), + ("Duplicate effect", "エフェクトを複製"), ("Duplicate layer(s)", "レイヤーを複製"), ("Duplicate the selected template", "選択中のテンプレートを複製"), ("Edge Detect", "エッジ検出"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index df30e1a5..af73d445 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -270,6 +270,7 @@ pub const TABLE: &[(&str, &str)] = &[ "텍스처 세트 \"{set}\"의 {name}을(를) 그립니다. 원본을 편집하면 모든 인스턴스에 반영됩니다.", ), ("Dry streaks", "마른 붓자국"), + ("Duplicate effect", "이펙트 복제"), ("Duplicate layer(s)", "레이어 복제"), ("Duplicate the selected template", "선택한 템플릿을 복제합니다"), ("Edge Detect", "가장자리 검출"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 097a6e00..e80c78f0 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -279,6 +279,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Arraste o quadro para mover o decalque, um canto para redimensioná-lo e a alça redonda para girá-lo", ), ("Dry streaks", "Estrias secas"), + ("Duplicate effect", "Duplicar efeito"), ("Duplicate layer(s)", "Duplicar camada(s)"), ("Duplicate the selected template", "Duplicar o modelo selecionado"), ("Edge Detect", "Detecção de bordas"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index b21bebf9..4e2b7200 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -240,6 +240,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Drags the layer stack's values along the stroke into the selected layer.", "沿笔画将图层堆栈的值拖入所选图层。"), ("Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", "绘制纹理集“{set}”的 {name}。对源的编辑会显示在每个实例中。"), ("Dry streaks", "干笔条纹"), + ("Duplicate effect", "创建效果副本"), ("Duplicate layer(s)", "创建图层副本"), ("Duplicate the selected template", "创建所选模板的副本"), ("Edge Detect", "边缘检测"), diff --git a/crates/ui-egui/tests/effect_rows.rs b/crates/ui-egui/tests/effect_rows.rs new file mode 100644 index 00000000..218eb0cc --- /dev/null +++ b/crates/ui-egui/tests/effect_rows.rs @@ -0,0 +1,48 @@ +//! Effect rows in the layer stack: dragging one reorders its stack. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +fn id(v: Value, key: &str) -> u64 { + v[key].as_u64().unwrap() +} + +/// Drag the row labelled `from` onto the upper (`below` false) or lower half of the row `to`. +fn drag(h: &mut Harness<'_, TextureCraftApp>, from: &str, to: &str, below: bool) { + let start = h.get_by_label(from).rect().center(); + let r = h.get_by_label(to).rect(); + let end = egui::pos2(r.center().x, if below { r.bottom() - 4.0 } else { r.top() + 4.0 }); + h.drag_at(start); + h.run_steps(2); + h.hover_at(end); + h.run_steps(2); + h.drop_at(end); + h.run_steps(3); +} + +#[test] +fn dragging_an_effect_row_reorders_its_stack() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let mut add = + |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); + let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C")); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + let order = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); + assert_eq!(order(&h), [a, b, c]); + // The rows list the top first: C, B, A. A dropped on C's upper half goes to the top. + drag(&mut h, "Effect A", "Effect C", false); + assert_eq!(order(&h), [b, c, a]); + // A dropped on B's lower half goes back to the bottom. + drag(&mut h, "Effect A", "Effect B", true); + assert_eq!(order(&h), [a, b, c]); + // C dropped on A's upper half lands between A and B. + drag(&mut h, "Effect C", "Effect A", false); + assert_eq!(order(&h), [a, c, b]); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 86d84ea2..5e63c7f8 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -14,7 +14,9 @@ Programmatic calls never open dialogs: a command runs with its defaults. Only `u behaves like a menu click. `session.inspect` shows every layer, mask, effect, fill source and painted tile count, so an agent can verify its work without a screenshot. `effect.histogram {effect, channel?, bins?}` counts the values an effect reads (a levels -effect's input), so an agent can pick its input range from the data. +effect's input), so an agent can pick its input range from the data. `effect.move {effect, +index}` reorders an effect within its stack (0 = bottom) and `effect.duplicate {effect}` copies +one just above itself. ## Control channel (desktop app) diff --git a/docs/features.md b/docs/features.md index 5043fcac..90ecf3a3 100644 --- a/docs/features.md +++ b/docs/features.md @@ -42,7 +42,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Masks** with a white or black background and a stack of effects: painted strokes, fills, **mesh-map generators** (edge wear, dirt, thin areas, curvature, AO, position and direction gradients, all with world-space noise), filters, ID color selection and compare. Alt+click a - mask to view it alone. + mask to view it alone. Drag an effect to reorder its stack, or right-click it to duplicate it + (painted strokes included). - **Fill layers** take uniform values, **23 procedurals** (clouds, cells, grunge, scratches, wood grain, bricks, fabric weave, twill, leather grain, marble veins, Voronoi, paint chips…) or your own **images**, through UV, tri-planar, planar, spherical, cylindrical or decal projection. From cc90af09e06c8ee22544f1756da655b8074057d6 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:15:03 +0700 Subject: [PATCH 53/60] MaterialX export: tag colour maps with their file's colour space, write the .mtlx atomically, warn on clashing set names Float files (EXR, HDR) hold linear values, so their colour maps are tagged lin_rec709 instead of srgb_texture. The .mtlx goes through formats::write_atomic, and a set whose name sanitises to an earlier set's file name is skipped with a warning instead of overwriting it. --- crates/engine/src/file_cmds.rs | 22 ++++++++++++++++------ crates/engine/tests/materialx.rs | 22 ++++++++++++++++++++++ crates/formats/src/materialx.rs | 19 +++++++++++++++---- 3 files changed, 53 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index f489582c..22cc5259 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -417,8 +417,7 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { let sets = sets_param(s, p, "file.exportTextures")?; std::fs::create_dir_all(&dir).map_err(|e| bad("file.exportTextures", format!("cannot create {dir}: {e}")))?; let files = s.export_files(&sets, &opts)?; - let warnings: Vec = files.iter().flat_map(|f| f.warnings.iter().cloned()).collect(); - let mut warnings = warnings; + let mut warnings: Vec = files.iter().flat_map(|f| f.warnings.iter().cloned()).collect(); let mut written = texturecraft_formats::write_files(&files, std::path::Path::new(&dir)).map_err(fe)?; if p.get("materialX").and_then(Value::as_bool).unwrap_or(false) { written.extend(write_materialx(s, &sets, &opts, std::path::Path::new(&dir), &mut warnings)?); @@ -429,7 +428,8 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { /// One `_.mtlx` per texture set, next to the textures `opts` just wrote: the /// OpenPBR inputs those textures feed (see `texturecraft_formats::materialx`). UDIM sets name -/// their files with the `` token. Sets with no recognised map are skipped with a warning. +/// their files with the `` token. Sets with no recognised map, or whose name gives the +/// same file name as an earlier set's, are skipped with a warning. #[cfg(not(target_arch = "wasm32"))] fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std::path::Path, warnings: &mut Vec) -> Result> { use texturecraft_formats::materialx::{self, Texture}; @@ -438,6 +438,7 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std: warnings.push("MaterialX: the normalmap node reads OpenGL (+Y) normals; this export wrote DirectX normals, so flip the green channel".into()); } let mut out = Vec::new(); + let mut stems = std::collections::HashSet::new(); for &ts in sets { let set = s.doc.project.texture_set(ts).map_err(|e| EngineError::Other(e.to_string()))?; let mut textures: Vec = Vec::new(); @@ -448,8 +449,10 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std: Some(t) => f.name.replacen(&format!(".{t}."), "..", 1), None => f.name.clone(), }; + // Float files hold linear values; 8/16-bit colour maps are sRGB encoded. + let colorspace = if f.format.is_float() { "lin_rec709" } else { "srgb_texture" }; if !textures.iter().any(|t| t.input == input) { - textures.push(Texture { input: input.to_owned(), file }); + textures.push(Texture { input: input.to_owned(), file, colorspace }); } } if textures.is_empty() { @@ -457,9 +460,16 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std: continue; } let stem = texturecraft_formats::export::sanitize_file_stem(&format!("{mesh_name}_{}", set.name)); + // Case-insensitive: Windows and macOS file systems are. + if !stems.insert(stem.to_ascii_lowercase()) { + warnings.push(format!( + "MaterialX: texture set \"{}\" exports as \"{stem}\" like an earlier set, so its .mtlx was not written; rename one of them", + set.name + )); + continue; + } let path = dir.join(format!("{stem}.mtlx")); - std::fs::write(&path, materialx::write(&format!("{mesh_name}_{}", set.name), &textures, None)) - .map_err(|e| bad("file.exportTextures", format!("cannot write {}: {e}", path.display())))?; + texturecraft_formats::write_atomic(&path, materialx::write(&format!("{mesh_name}_{}", set.name), &textures, None).as_bytes()).map_err(fe)?; out.push(path); } Ok(out) diff --git a/crates/engine/tests/materialx.rs b/crates/engine/tests/materialx.rs index 1ff77912..b3e4520f 100644 --- a/crates/engine/tests/materialx.rs +++ b/crates/engine/tests/materialx.rs @@ -72,6 +72,28 @@ fn off_by_default_and_warns_without_openpbr_maps() { assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("OpenPBR")), "{r}"); } +#[test] +fn float_colour_maps_are_tagged_linear() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let dir = temp("exr"); + let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": OPENPBR, "format": "exr", "materialX": true})).unwrap(); + let mtlx = files(&r).into_iter().find(|f| f.ends_with(".mtlx")).unwrap(); + let text = std::fs::read_to_string(mtlx).unwrap(); + assert!(text.contains("_base_color.exr\" colorspace=\"lin_rec709\"") && !text.contains("srgb_texture"), "{text}"); +} + +#[test] +fn sets_with_the_same_file_name_warn_instead_of_overwriting() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + assert!(s.set_count() >= 2); + execute(&mut s, "textureSet.rename", &json!({"ts": 0, "name": "a b"})).unwrap(); + execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "A_B"})).unwrap(); + let dir = temp("clash"); + let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": OPENPBR, "ts": "all", "materialX": true})).unwrap(); + assert_eq!(files(&r).iter().filter(|f| f.ends_with(".mtlx")).count(), s.set_count() - 1, "{r}"); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("\"A_B\"")), "{r}"); +} + #[test] fn udim_sets_use_the_udim_token() { let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); diff --git a/crates/formats/src/materialx.rs b/crates/formats/src/materialx.rs index d178f7b7..d1c0edce 100644 --- a/crates/formats/src/materialx.rs +++ b/crates/formats/src/materialx.rs @@ -9,8 +9,9 @@ //! `displacement` shader on the material and `geometry_normal` goes through a `normalmap` node //! (OpenGL, +Y up, which is what that node expects). //! -//! Colour textures (base, fuzz and emission colour) are tagged `srgb_texture`; every data map is -//! left untagged (linear). UDIM sets write the `` filename token MaterialX defines. +//! Colour textures (base, fuzz and emission colour) are tagged with their file's colour space +//! (`srgb_texture` for 8/16-bit files, `lin_rec709` for float ones); every data map is left +//! untagged (linear). UDIM sets write the `` filename token MaterialX defines. //! Texture file names are relative to the document. use std::collections::HashSet; @@ -57,6 +58,9 @@ const PREFIX: &str = "$mesh_$textureSet_"; pub struct Texture { pub input: String, pub file: String, + /// The MaterialX colour space of the file's values (`srgb_texture`, `lin_rec709`, ...); + /// used for colour inputs only, data maps are always linear. + pub colorspace: &'static str, } /// The OpenPBR input a preset map's file template feeds (`$mesh_$textureSet_base_color` → @@ -129,7 +133,7 @@ pub fn write(name: &str, textures: &[Texture], physical_size_cm: Option<[f32; 2] for (t, kind) in &tex { let (ty, space) = match kind { - Kind::Color => ("color3", Some("srgb_texture")), + Kind::Color => ("color3", Some(t.colorspace)), Kind::Normal => ("vector3", None), Kind::Float | Kind::Height => ("float", None), }; @@ -176,7 +180,7 @@ mod tests { use super::*; fn tex(input: &str, file: &str) -> Texture { - Texture { input: input.into(), file: file.into() } + Texture { input: input.into(), file: file.into(), colorspace: "srgb_texture" } } /// Every start tag is closed or self-closed, in order: enough to catch a malformed writer. @@ -244,6 +248,13 @@ mod tests { assert!(balanced(&none) && none.contains(""), "{x}"); + } + #[test] fn unknown_and_repeated_inputs_are_skipped() { let x = write("m", &[tex("ambient_occlusion", "ao.png"), tex("base_color", "a.png"), tex("base_color", "b.png")], None); From 76b24c4e3d8861a09763a55760b0686c1a236510 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:24:24 +0700 Subject: [PATCH 54/60] Export colour space: tag MaterialX colour maps with it, warn when a colour map is not converted The .mtlx tags colour textures with the export's colour space: srgb_texture, lin_rec709, acescg, or lin_ap0_scene for ACES2065-1 (MaterialX 1.39 has no AP0 space; the export warns). A colour map packed into one channel (L) is not converted and now says so. The $colorSpace variable's description lists every value. --- crates/engine/src/file_cmds.rs | 6 ++++-- crates/engine/tests/materialx.rs | 19 +++++++++++++++++++ crates/formats/src/export/mod.rs | 9 ++++++--- crates/formats/src/export/tests.rs | 9 +++++++++ crates/formats/src/materialx.rs | 19 ++++++++++++++++--- 5 files changed, 54 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 60d83cf9..8f808ec3 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -457,6 +457,9 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std: if opts.normal_format == Some(NormalFormat::DirectX) { warnings.push("MaterialX: the normalmap node reads OpenGL (+Y) normals; this export wrote DirectX normals, so flip the green channel".into()); } + if opts.color_space == Some(texturecraft_texel::ColorSpace::Aces2065) { + warnings.push("MaterialX: version 1.39 has no ACES2065-1 colour space; the colour maps are tagged lin_ap0_scene, its name in later versions, which older readers may not know".into()); + } let mut out = Vec::new(); let mut stems = std::collections::HashSet::new(); for &ts in sets { @@ -469,8 +472,7 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std: Some(t) => f.name.replacen(&format!(".{t}."), "..", 1), None => f.name.clone(), }; - // Float files hold linear values; 8/16-bit colour maps are sRGB encoded. - let colorspace = if f.format.is_float() { "lin_rec709" } else { "srgb_texture" }; + let colorspace = materialx::colorspace_name(opts.space_for(f.format)); if !textures.iter().any(|t| t.input == input) { textures.push(Texture { input: input.to_owned(), file, colorspace }); } diff --git a/crates/engine/tests/materialx.rs b/crates/engine/tests/materialx.rs index b3e4520f..35ba658a 100644 --- a/crates/engine/tests/materialx.rs +++ b/crates/engine/tests/materialx.rs @@ -82,6 +82,25 @@ fn float_colour_maps_are_tagged_linear() { assert!(text.contains("_base_color.exr\" colorspace=\"lin_rec709\"") && !text.contains("srgb_texture"), "{text}"); } +#[test] +fn colour_maps_are_tagged_with_the_export_colour_space() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + for (space, tag, warns) in [("ACEScg", "acescg", false), ("ACES2065-1", "lin_ap0_scene", true), ("sRGB", "srgb_texture", false)] { + let dir = temp(tag); + let r = execute( + &mut s, + "file.exportTextures", + &json!({"dir": dir.display().to_string(), "preset": OPENPBR, "format": "exr", "colorSpace": space, "materialX": true}), + ) + .unwrap(); + let mtlx = files(&r).into_iter().find(|f| f.ends_with(".mtlx")).unwrap(); + let text = std::fs::read_to_string(mtlx).unwrap(); + assert!(text.contains(&format!("_base_color.exr\" colorspace=\"{tag}\"")), "{space}: {text}"); + let warned = r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("ACES2065-1")); + assert_eq!(warned, warns, "{space}: {r}"); + } +} + #[test] fn sets_with_the_same_file_name_warn_instead_of_overwriting() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 38f22880..e4010f20 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -41,7 +41,7 @@ pub const FILE_TOKENS: [(&str, &str); 6] = [ ("$textureSet", "Texture set name"), ("$project", "Project name"), ("$channel", "Channel or map id"), - ("$colorSpace", "sRGB or linear"), + ("$colorSpace", "Colour maps: sRGB, linear, ACEScg or ACES2065-1; data maps: linear"), ("$udim", "UV tile number (1001 for sets without UV tiles)"), ]; @@ -736,15 +736,18 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result= 3 && lay.iter().take(3).map(|(d, _)| *d).eq([Dest::R, Dest::G, Dest::B]); let mut data = data; - if is_color(map) && rgb && (space != ColorSpace::Srgb || p.format.is_float()) && space != ColorSpace::LinearRec709 { + let mut warnings = p.warnings; + let convert = is_color(map) && (space != ColorSpace::Srgb || p.format.is_float()) && space != ColorSpace::LinearRec709; + if convert && rgb { data.par_chunks_mut(n).for_each(|px| { if let [r, g, b, ..] = px { [*r, *g, *b] = space.from_linear_rec709([*r, *g, *b]); } }); + } else if convert { + warnings.push(format!("\"{}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", p.name, space.name())); } let srgb: Vec = lay.iter().map(|(d, _)| *d != Dest::A && is_color(map) && !p.format.is_float() && space == ColorSpace::Srgb).collect(); - let mut warnings = p.warnings; let bytes = encode(p.format, p.bit_depth, size, n, &data, &srgb, &mut warnings)?; Ok(ExportedFile { name: p.name, bytes, width: size.0, height: size.1, warnings }) }) diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index babd96db..c4966585 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -588,3 +588,12 @@ fn colour_space_names_the_files_and_warns_when_integer_files_clamp() { assert_eq!(names, list_outputs(&fx.project, 0, "sphere", &opts).unwrap().into_iter().map(|p| p.name).collect::>()); assert!(names[0].ends_with("_ACES2065-1.png"), "{names:?}"); } + +#[test] +fn colour_packed_into_one_channel_warns_instead_of_converting_silently() { + let fx = Fx::new(&default_channels()); + let preset = ExportPreset { name: "l".into(), maps: vec![gray_map("$textureSet_red", SourceRef::Channel { channel: Channel::BaseColor, component: 0 })] }; + let opts = |space| ExportOptions { color_space: space, format_override: Some(FileFormat::Exr), ..ExportOptions::new(preset.clone()) }; + assert!(fx.render(&opts(Some(ColorSpace::AcesCg)))[0].warnings.iter().any(|w| w.contains("ACEScg"))); + assert!(fx.render(&opts(None))[0].warnings.is_empty(), "linear Rec.709 needs no conversion"); +} diff --git a/crates/formats/src/materialx.rs b/crates/formats/src/materialx.rs index d1c0edce..e7440328 100644 --- a/crates/formats/src/materialx.rs +++ b/crates/formats/src/materialx.rs @@ -9,14 +9,15 @@ //! `displacement` shader on the material and `geometry_normal` goes through a `normalmap` node //! (OpenGL, +Y up, which is what that node expects). //! -//! Colour textures (base, fuzz and emission colour) are tagged with their file's colour space -//! (`srgb_texture` for 8/16-bit files, `lin_rec709` for float ones); every data map is left -//! untagged (linear). UDIM sets write the `` filename token MaterialX defines. +//! Colour textures (base, fuzz and emission colour) are tagged with the colour space they were +//! exported in ([`colorspace_name`]); every data map is left untagged (linear). UDIM sets write the `` filename token MaterialX defines. //! Texture file names are relative to the document. use std::collections::HashSet; use std::fmt::Write as _; +use texturecraft_texel::ColorSpace; + /// How an OpenPBR input is typed in the document. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Kind { @@ -63,6 +64,18 @@ pub struct Texture { pub colorspace: &'static str, } +/// The MaterialX colour space of colour maps written in `space`. MaterialX 1.39 defines no +/// ACES2065-1 (AP0) space: it gets `lin_ap0_scene`, its name in later versions of the +/// specification, which 1.39 readers may not know. +pub fn colorspace_name(space: ColorSpace) -> &'static str { + match space { + ColorSpace::Srgb => "srgb_texture", + ColorSpace::LinearRec709 => "lin_rec709", + ColorSpace::AcesCg => "acescg", + ColorSpace::Aces2065 => "lin_ap0_scene", + } +} + /// The OpenPBR input a preset map's file template feeds (`$mesh_$textureSet_base_color` → /// `base_color`), or None for templates this module has no place for. pub fn input_of_template(template: &str) -> Option<&'static str> { From f6bd07e4d6d6d8e2b72ec413e660aa21ecc4333e Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:32:20 +0700 Subject: [PATCH 55/60] Mesh maps: use an image instead of a bake Each mesh map slot of the Texture Set Settings takes an image resource: drop one from the Assets panel on the slot, or pick it from the slot's menu, which also clears the slot. The image is resampled to the size of the set's other mesh maps (or its bake size), its values read as data, a normal map in the project's normal format. textureSet.meshMap.set {ts?, map, image} and textureSet.meshMap.clear {ts?, map} give agents the same. --- crates/engine/src/commands.rs | 1 + crates/engine/src/lib.rs | 1 + crates/engine/src/meshmap_cmds.rs | 98 ++++++++++++++++++++++++++++ crates/engine/tests/painter_gaps.rs | 38 ++++++++++- crates/ui-egui/src/dock.rs | 35 +++++++++- crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 4 ++ crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 4 ++ crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/tests/ui_snapshots.rs | 5 ++ docs/control-protocol.md | 2 +- docs/features.md | 4 +- 17 files changed, 192 insertions(+), 7 deletions(-) create mode 100644 crates/engine/src/meshmap_cmds.rs diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index ec5c2917..ef18af36 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -63,6 +63,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::camera_cmds::specs()); v.extend(crate::quick_mask::specs()); v.extend(crate::set_cmds::specs()); + v.extend(crate::meshmap_cmds::specs()); v.extend(crate::uv_tile_cmds::specs()); v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index d8928166..8016a5d0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -22,6 +22,7 @@ pub mod layer_ops; pub mod mask_cmds; pub mod material_lib; pub mod materials; +pub mod meshmap_cmds; pub mod painting; pub mod path_tool; // Mesh reimport reads files: native only. diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs new file mode 100644 index 00000000..1a42a362 --- /dev/null +++ b/crates/engine/src/meshmap_cmds.rs @@ -0,0 +1,98 @@ +//! Mesh map slots of the Texture Set Settings: use an image resource as a mesh map (baked in +//! another app, or edited by hand) instead of baking it, or clear a slot. + +use std::sync::Arc; + +use rayon::prelude::*; +use serde_json::{Value, json}; +use texturecraft_compose::ImageRes; +use texturecraft_core::{BakedMap, MAX_RESOLUTION, NormalFormat}; + +use crate::commands::{CommandSpec, always, bad, strp}; +use crate::set_cmds::ts_param; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![ + cmd!( + "textureSet.meshMap.set", + "Use image as mesh map", + [], + None, + "{ts?, map: mesh map id (normal_base, ambient_occlusion, curvature, id, height…), image: resource name} → {map, resolution} — resampled to the size of the set's other mesh maps (or its bake size); a normal map is read in the project's normal format", + always, + set + ), + cmd!("textureSet.meshMap.clear", "Clear mesh map", [], None, "{ts?, map}", always, clear), + ] +} + +fn map_param(p: &Value, cmd: &str) -> Result { + let id = strp(p, "map").ok_or_else(|| bad(cmd, "`map` is required"))?; + BakedMap::parse(id).ok_or_else(|| bad(cmd, format!("unknown mesh map `{id}`"))) +} + +fn set(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "textureSet.meshMap.set"; + let ts = ts_param(s, p, CMD)?; + let map = map_param(p, CMD)?; + let name = strp(p, "image").ok_or_else(|| bad(CMD, "`image` (an image resource name) is required"))?; + let img = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?; + let set = s.doc.project.texture_set(ts)?; + // shortcut: one image spans the whole set; UV-tiled sets would need one image per tile. + if !set.uv_tiles.is_empty() { + return Err(bad(CMD, format!("\"{}\" has UV tiles: mesh maps from images need a set without them", set.name))); + } + // Every mesh map of a set shares one size: the other maps', or what a bake would make. + let res = s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()).map_or(set.bake.resolution, |b| b.resolution); + if !(1..=MAX_RESOLUTION).contains(&res) { + return Err(bad(CMD, format!("mesh map size {res} is not in 1..={MAX_RESOLUTION}"))); + } + let directx = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX; + let data = resample(&img, map.components(), res, directx); + s.edit("Use image as mesh map", |s| { + let entry = s.doc.baked.entry(ts).or_default(); + entry.resolution = res; + entry.maps.insert(map, Arc::new(data)); + s.doc.project.texture_set_mut(ts)?.baked.insert(map); + Ok(()) + })?; + Ok(json!({ "map": map.id(), "resolution": res })) +} + +/// `img` as `res` × `res` texels of `comps` values each, as stored in the file (mesh maps hold +/// data, not colors, so nothing is linearized); `flip_green` reads a DirectX normal map. +fn resample(img: &ImageRes, comps: usize, res: u32, flip_green: bool) -> Vec { + let n = res as usize; + let mut out = vec![0.0; n * n * comps]; + out.par_chunks_mut(n * comps).enumerate().for_each(|(y, row)| { + let v = (y as f32 + 0.5) / res as f32; + for (x, texel) in row.chunks_exact_mut(comps).enumerate() { + let mut c = img.sample((x as f32 + 0.5) / res as f32, v); + if flip_green { + c[1] = 1.0 - c[1]; + } + for (o, c) in texel.iter_mut().zip(c) { + *o = c; + } + } + }); + out +} + +fn clear(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "textureSet.meshMap.clear"; + let ts = ts_param(s, p, CMD)?; + let map = map_param(p, CMD)?; + if !s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) { + return Err(bad(CMD, format!("texture set {ts} has no {} map", map.label()))); + } + s.edit("Clear mesh map", |s| { + if let Some(b) = s.doc.baked.get_mut(&ts) { + b.maps.remove(&map); + } + s.doc.project.texture_set_mut(ts)?.baked.remove(&map); + Ok(()) + })?; + Ok(Value::Null) +} diff --git a/crates/engine/tests/painter_gaps.rs b/crates/engine/tests/painter_gaps.rs index 48f0b3de..f6fbfdc2 100644 --- a/crates/engine/tests/painter_gaps.rs +++ b/crates/engine/tests/painter_gaps.rs @@ -1,6 +1,6 @@ //! The filter library, geometry decals, cloning from the selected layer, placing saved smart -//! materials, anchors inside a content stack and instances across texture set resolutions, -//! through engine commands. +//! materials, anchors inside a content stack, instances across texture set resolutions and mesh +//! maps from images, through engine commands. use serde_json::{Value, json}; use texturecraft_engine::core::{Channel, EffectKind, Filter, LayerId, LayerKind, Projection}; @@ -375,3 +375,37 @@ fn geometry_mask_tool_toggles_the_clicked_part() { assert_eq!(s.doc.project.layer(layer).unwrap().geometry_mask, Some(vec!["Lid".to_string()])); assert!(execute(&mut s, "tool.click", &json!({"x": 1, "y": 1})).is_err(), "nothing under the point"); } + +#[test] +fn images_fill_mesh_map_slots() { + use texturecraft_engine::core::BakedMap; + let mut s = session(); + // Dark on the left, light on the right. + let ao = s.import_resource_bytes("ao.png", png(8, 8, |x, _| if x < 4 { [64, 64, 64, 255] } else { [192, 192, 192, 255] })).unwrap(); + let r = execute(&mut s, "textureSet.meshMap.set", &json!({"map": "ambient_occlusion", "image": ao})).unwrap(); + let res = s.doc.project.texture_sets[0].bake.resolution; + assert_eq!(r, json!({"map": "ambient_occlusion", "resolution": res})); + assert!(s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion)); + let sample = |s: &Session, m: BakedMap, x: u32| s.baked(0).unwrap().sample(m, x, 50, 100).unwrap(); + assert!((sample(&s, BakedMap::AmbientOcclusion, 10)[0] - 64.0 / 255.0).abs() < 1e-3, "raw file values, not linearized"); + assert!((sample(&s, BakedMap::AmbientOcclusion, 90)[0] - 192.0 / 255.0).abs() < 1e-3); + // A normal map is read in the project's normal format (DirectX: green flipped). + execute(&mut s, "textureSet.settings", &json!({"normalFormat": "directX"})).unwrap(); + let n = s.import_resource_bytes("n.png", png(2, 2, |_, _| [128, 64, 255, 255])).unwrap(); + execute(&mut s, "textureSet.meshMap.set", &json!({"map": "normal", "image": n})).unwrap(); + let v = sample(&s, BakedMap::Normal, 50); + assert!((v[1] - (1.0 - 64.0 / 255.0)).abs() < 1e-3 && (v[2] - 1.0).abs() < 1e-3, "{v:?}"); + // Clearing empties the slot (one undo step); bad params are errors. + execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambient_occlusion"})).unwrap(); + assert!(s.baked(0).unwrap().sample(BakedMap::AmbientOcclusion, 0, 0, 100).is_none()); + assert!(!s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion)); + assert!(execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambient_occlusion"})).is_err(), "already empty"); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion)); + assert!(execute(&mut s, "textureSet.meshMap.set", &json!({"map": "nope", "image": ao})).is_err()); + assert!(execute(&mut s, "textureSet.meshMap.set", &json!({"map": "curvature", "image": "missing.png"})).is_err()); + assert!(execute(&mut s, "textureSet.meshMap.set", &json!({"map": "curvature"})).is_err()); + // The maps are saved with the project. + let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(back.doc.baked, s.doc.baked); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index ba2ddcfd..0a3c947d 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -762,10 +762,10 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { } }); }); - let baked = app.session.doc.baked.get(&ts); + let images: Vec = app.session.doc.resources.keys().cloned().collect(); for m in BakedMap::ALL { - let present = baked.is_some_and(|b| b.maps.contains_key(&m)); - ui.horizontal(|ui| { + let present = app.session.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&m)); + let row = ui.horizontal(|ui| { let (r, _) = ui.allocate_exact_size(vec2(26.0, 26.0), Sense::hover()); ui.painter().rect_filled(r, 2.0, if present { mesh_map_color(m) } else { tk.button }); ui.vertical(|ui| { @@ -776,7 +776,36 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { .color(tk.text_dim), ); }); + // An image resource instead of a bake, or no map. + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.menu_button(RichText::new(ic::DOTS_THREE).size(13.0), |ui| { + ui.label(caption(tr("Images"))); + for name in &images { + if ui.button(name).clicked() { + app.run("textureSet.meshMap.set", json!({"ts": ts, "map": m.id(), "image": name})); + ui.close(); + } + } + if ui.button(tr("Import...")).clicked() { + crate::menus::invoke(app, ui.ctx(), "resource.import"); + ui.close(); + } + ui.separator(); + if ui.add_enabled(present, egui::Button::new(tr("Clear"))).clicked() { + app.run("textureSet.meshMap.clear", json!({"ts": ts, "map": m.id()})); + ui.close(); + } + }); + }); }); + // A shelf image dropped on the row becomes this mesh map. + let resp = row.response.interact(Sense::hover()).on_hover_text(tr("Drop an image from the Assets panel here to use it as this mesh map")); + if resp.dnd_hover_payload::().is_some_and(|d| matches!(d.asset, Asset::Texture(_))) { + ui.painter().rect_stroke(resp.rect.shrink(1.0), 3.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside); + } + if let Some(Asset::Texture(name)) = dnd_release::(&resp).map(|d| d.asset.clone()) { + app.run("textureSet.meshMap.set", json!({"ts": ts, "map": m.id(), "image": name})); + } } }); } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 75c795b3..60a24624 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -263,6 +263,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", "اسحب الإطار لتحريك الملصق، أو الزاوية لتغيير حجمه، أو المقبض الدائري لتدويره", ), + ("Drop an image from the Assets panel here to use it as this mesh map", "أفلت صورة من لوحة الأصول هنا لاستخدامها كخريطة المجسم هذه"), ("Dry streaks", "خطوط جافة"), ("Duplicate layer(s)", "تكرار الطبقة (الطبقات)"), ("Duplicate the selected template", "تكرار القالب المحدد"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index b0341184..b750471d 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -281,6 +281,10 @@ pub const TABLE: &[(&str, &str)] = &[ "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", "Rahmen ziehen, um das Decal zu verschieben, eine Ecke zum Skalieren, den runden Griff zum Drehen", ), + ( + "Drop an image from the Assets panel here to use it as this mesh map", + "Ein Bild aus dem Assets-Panel hier ablegen, um es als diese Mesh-Map zu verwenden", + ), ("Dry streaks", "Trockene Schlieren"), ("Duplicate layer(s)", "Ebene(n) duplizieren"), ("Duplicate the selected template", "Ausgewählte Vorlage duplizieren"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index df2151d9..23366253 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -278,6 +278,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", "Arrastra el marco para mover la calcomanía, una esquina para escalarla y el tirador redondo para girarla", ), + ("Drop an image from the Assets panel here to use it as this mesh map", "Suelta aquí una imagen del panel Recursos para usarla como este mapa de malla"), ("Dry streaks", "Trazos secos"), ("Duplicate layer(s)", "Duplicar capa(s)"), ("Duplicate the selected template", "Duplicar la plantilla seleccionada"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 2b943710..8fe9ccbb 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -281,6 +281,10 @@ pub const TABLE: &[(&str, &str)] = &[ "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", "Faites glisser le cadre pour déplacer le décalque, un coin pour le mettre à l'échelle, la poignée ronde pour le faire pivoter", ), + ( + "Drop an image from the Assets panel here to use it as this mesh map", + "Déposez ici une image du panneau Ressources pour l'utiliser comme cette carte de maillage", + ), ("Dry streaks", "Traînées sèches"), ("Duplicate layer(s)", "Dupliquer le(s) calque(s)"), ("Duplicate the selected template", "Dupliquer le modèle sélectionné"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 5192aef7..62ec183b 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -284,6 +284,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", "Trascina il riquadro per spostare la decal, un angolo per scalarla, la maniglia rotonda per ruotarla", ), + ("Drop an image from the Assets panel here to use it as this mesh map", "Rilascia qui un'immagine dal pannello Risorse per usarla come questa mappa mesh"), ("Dry streaks", "Striature secche"), ("Duplicate layer(s)", "Duplica livello/i"), ("Duplicate the selected template", "Duplica il modello selezionato"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 9b1d9be9..7dc6e6e1 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -272,6 +272,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", "テクスチャセット「{set}」の {name} を描画します。ソースへの編集はすべてのインスタンスに反映されます。", ), + ("Drop an image from the Assets panel here to use it as this mesh map", "アセットパネルから画像をここにドロップすると、このメッシュマップとして使用します"), ("Dry streaks", "かすれ"), ("Duplicate layer(s)", "レイヤーを複製"), ("Duplicate the selected template", "選択中のテンプレートを複製"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index df30e1a5..f9c167e7 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -269,6 +269,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", "텍스처 세트 \"{set}\"의 {name}을(를) 그립니다. 원본을 편집하면 모든 인스턴스에 반영됩니다.", ), + ("Drop an image from the Assets panel here to use it as this mesh map", "에셋 패널의 이미지를 여기에 놓으면 이 메시 맵으로 사용합니다"), ("Dry streaks", "마른 붓자국"), ("Duplicate layer(s)", "레이어 복제"), ("Duplicate the selected template", "선택한 템플릿을 복제합니다"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 097a6e00..dc7521c3 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -278,6 +278,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Drag the frame to move the decal, a corner to scale it, the round handle to turn it", "Arraste o quadro para mover o decalque, um canto para redimensioná-lo e a alça redonda para girá-lo", ), + ("Drop an image from the Assets panel here to use it as this mesh map", "Solte aqui uma imagem do painel Recursos para usá-la como este mapa de malha"), ("Dry streaks", "Estrias secas"), ("Duplicate layer(s)", "Duplicar camada(s)"), ("Duplicate the selected template", "Duplicar o modelo selecionado"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index b21bebf9..41136b04 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -239,6 +239,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Drag the frame to move the decal, a corner to scale it, the round handle to turn it", "拖动边框移动贴花,拖动角缩放,拖动圆形手柄旋转"), ("Drags the layer stack's values along the stroke into the selected layer.", "沿笔画将图层堆栈的值拖入所选图层。"), ("Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", "绘制纹理集“{set}”的 {name}。对源的编辑会显示在每个实例中。"), + ("Drop an image from the Assets panel here to use it as this mesh map", "将资产面板中的图像拖放到此处,用作此网格贴图"), ("Dry streaks", "干笔条纹"), ("Duplicate layer(s)", "创建图层副本"), ("Duplicate the selected template", "创建所选模板的副本"), diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 2a44f4ff..ee2d8676 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -62,6 +62,11 @@ fn window_snapshots() { h.state_mut().ui.windows.settings = true; save(&mut h, &dir, "window-settings"); h.state_mut().ui.windows.settings = false; + // The mesh map slots, each with its menu of images (a tall window shows them all). + h.state_mut().ui.dock.focus(Panel::TextureSetSettings); + h.set_size(egui::vec2(1600.0, 1800.0)); + save(&mut h, &dir, "panel-texture-set-settings"); + h.set_size(egui::vec2(1600.0, 960.0)); // A mask's levels effect over clouds: the histogram in Properties. let s = &mut h.state_mut().session; for (id, p) in [ diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 86d84ea2..f8048861 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -129,7 +129,7 @@ takes a font family, not a path: it reads only the system's font folders. | `mesh_reimport` | `{path?, preserveStrokes?}` | Reimport the mesh from a file, or (no path) from the project's own copy; bridge mode supports only the latter | | `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (usda / usdc textures next to it) → `{path, textures?}` | | `bake_mesh_add` | `{path, cage?}` | Add a high-definition mesh for baking, or set the cage → `{name, meshes}` | -| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil` | +| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot) | | `material_save` | `{path, layer?, name?}` | A layer or folder as a `.tcmat` smart material below the write root | | `material_load` | `{path}` | Add a `.tcmat` smart material above the selection | | `textures_export` | `{dir, preset?, ts?, format?, padding?, size?}` | Writes files below the write root | diff --git a/docs/features.md b/docs/features.md index 5043fcac..7b858cfe 100644 --- a/docs/features.md +++ b/docs/features.md @@ -79,7 +79,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Bake mesh maps** on the GPU (ray traced, about 12× the CPU path) or on every CPU core: ambient occlusion, curvature, thickness, world-space normal, position, ID, bent normals, opacity, color and direction maps, and normal and height maps from high-poly meshes, with a cage, ray distances - and matching by mesh name. + and matching by mesh name. Or **use your own images** as mesh maps (baked in another app, or + edited): drop one from the Assets panel on a slot of the Texture Set Settings, or pick it from + the slot's menu. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in From d71cdfa3ca9f400f476c85a334bf5153b7861ecd Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:35:32 +0700 Subject: [PATCH 56/60] Undo: never leave a removed effect selected Undoing an effect's add or duplicate took the selected effect away and left the selection on it, so the row lost its highlight and strokes had no target. The selection now falls back to the stack the effect was in. --- crates/engine/src/session.rs | 8 ++++++++ crates/engine/tests/content_effects.rs | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 14891a8f..baf012b6 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -629,6 +629,14 @@ impl Session { self.modified = true; self.revision = self.revision.wrapping_add(1); self.invalidate_changed(other); + // An undone add or duplicate takes the selected effect away: select the stack it was in. + if let StackTarget::Effect(e) = self.target + && self.doc.project.effect(e).is_none() + { + let p = &other.project; + let content = p.effect(e).and_then(|(owner, _)| p.layers.get(&owner)).is_some_and(|l| l.content_effects.iter().any(|x| x.id == e)); + self.target = if content { StackTarget::Content } else { StackTarget::Mask }; + } } // ----------------------------------------------------------------------------------------- diff --git a/crates/engine/tests/content_effects.rs b/crates/engine/tests/content_effects.rs index d67300f7..dca2378b 100644 --- a/crates/engine/tests/content_effects.rs +++ b/crates/engine/tests/content_effects.rs @@ -139,6 +139,10 @@ fn effects_move_within_their_stack_and_duplicate_with_their_pixels() { assert_eq!(order(&s), [fill, paint, copy]); assert_eq!(s.target, StackTarget::Effect(LayerId(copy))); assert!(s.doc.project.effect(LayerId(copy)).unwrap().1.name.ends_with(" copy")); + // Undoing it leaves no missing effect selected, but the stack it was in. + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.target, StackTarget::Content); + execute(&mut s, "edit.redo", &Value::Null).unwrap(); execute(&mut s, "effect.remove", &json!({"effect": paint})).unwrap(); assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "the copy keeps the strokes"); assert!(execute(&mut s, "effect.duplicate", &json!({"effect": 999_999})).is_err()); From 410cf3a14f8a4d17f01a1c703ac98a3642023dcd Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:48:32 +0700 Subject: [PATCH 57/60] Brush: Ctrl+drag sets size, hardness, flow and angle Ctrl (Cmd on macOS) + right-drag in the 3D or 2D view changes the brush size (left/right) and hardness (up/down), Ctrl + left-drag its flow and angle, instead of orbiting or painting. The brush cursor stays where the drag began, with the values beside it, and the Brush properties name the gesture. --- crates/ui-egui/src/dock.rs | 2 + crates/ui-egui/src/i18n/ar.rs | 4 ++ crates/ui-egui/src/i18n/de.rs | 4 ++ crates/ui-egui/src/i18n/es.rs | 4 ++ crates/ui-egui/src/i18n/fr.rs | 4 ++ crates/ui-egui/src/i18n/it.rs | 4 ++ crates/ui-egui/src/i18n/ja.rs | 4 ++ crates/ui-egui/src/i18n/ko.rs | 4 ++ crates/ui-egui/src/i18n/pt_br.rs | 4 ++ crates/ui-egui/src/i18n/zh_hans.rs | 4 ++ crates/ui-egui/src/viewport.rs | 85 +++++++++++++++++++++++++--- crates/ui-egui/tests/brush_drag.rs | 46 +++++++++++++++ crates/ui-egui/tests/ui_snapshots.rs | 12 ++++ docs/features.md | 2 + 14 files changed, 175 insertions(+), 8 deletions(-) create mode 100644 crates/ui-egui/tests/brush_drag.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index ba2ddcfd..2891f723 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1027,6 +1027,8 @@ fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) { fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { let b = &mut app.session.tool.brush; ui.label(caption(tr("Brush"))); + let hint = tr("Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle."); + ui.label(RichText::new(hint).size(10.5).color(Tokens::get(ui.ctx()).text_dim)); section(ui, "sec_size", tr("Size"), true, |ui| { let mut size = b.size / 0.25 * 100.0; if slider(ui, tr("Size"), &mut size, 0.05..=100.0, 1).changed() { diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 75c795b3..f7fa1ea8 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -206,6 +206,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Crate", "صندوق"), ("Create", "إنشاء"), ("Create smart material", "إنشاء مادة ذكية"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "Ctrl+السحب بالزر الأيمن في عرض يضبط الحجم والصلابة، وCtrl+السحب بالزر الأيسر يضبط التدفق والزاوية.", + ), ("Cube", "مكعب"), ("Current layer", "الطبقة الحالية"), ("Curvature", "الانحناء"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index b0341184..4aa3f940 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -218,6 +218,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Crate", "Kiste"), ("Create", "Erstellen"), ("Create smart material", "Smart-Material erstellen"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "Strg+Ziehen mit RMT in einer Ansicht stellt Größe und Härte ein, Strg+Ziehen mit LMT Fluss und Winkel.", + ), ("Cube", "Würfel"), ("Current layer", "Aktuelle Ebene"), ("Curvature", "Krümmung"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index df2151d9..dbbaae73 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -215,6 +215,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Crate", "Caja"), ("Create", "Crear"), ("Create smart material", "Crear material inteligente"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "Ctrl+arrastrar con botón der. en una vista ajusta el tamaño y la dureza; Ctrl+arrastrar con botón izq., el flujo y el ángulo.", + ), ("Cube", "Cubo"), ("Current layer", "Capa actual"), ("Curvature", "Curvatura"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 2b943710..2a0ccd36 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -218,6 +218,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Crate", "Caisse"), ("Create", "Créer"), ("Create smart material", "Créer un matériau intelligent"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "Ctrl+glisser (clic droit) dans une vue règle la taille et la dureté, Ctrl+glisser (clic gauche) le flux et l'angle.", + ), ("Cube", "Cube"), ("Current layer", "Calque actuel"), ("Curvature", "Courbure"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 5192aef7..d5d907c4 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -221,6 +221,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Crate", "Cassa"), ("Create", "Crea"), ("Create smart material", "Crea materiale intelligente"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "Ctrl+trascina con il tasto destro in una vista per regolare dimensione e durezza, con il sinistro flusso e angolo.", + ), ("Cube", "Cubo"), ("Current layer", "Livello corrente"), ("Curvature", "Curvatura"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 9b1d9be9..65e3df29 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -218,6 +218,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Crate", "木箱"), ("Create", "作成"), ("Create smart material", "スマートマテリアルを作成"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "ビューでCtrl+右ドラッグでサイズと硬さ、Ctrl+左ドラッグでフローと角度を設定します。", + ), ("Cube", "立方体"), ("Current layer", "現在のレイヤー"), ("Curvature", "曲率"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index df30e1a5..9ddec591 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -209,6 +209,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Crate", "상자"), ("Create", "만들기"), ("Create smart material", "스마트 머티리얼 만들기"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "뷰에서 Ctrl+오른쪽 드래그로 크기와 경도를, Ctrl+왼쪽 드래그로 흐름과 각도를 설정합니다.", + ), ("Cube", "큐브"), ("Current layer", "현재 레이어"), ("Curvature", "곡률"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 097a6e00..65b65087 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -215,6 +215,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Crate", "Caixote"), ("Create", "Criar"), ("Create smart material", "Criar material inteligente"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "Ctrl+arrastar com botão direito em uma vista ajusta o tamanho e a dureza; Ctrl+arrastar com botão esquerdo, o fluxo e o ângulo.", + ), ("Cube", "Cubo"), ("Current layer", "Camada atual"), ("Curvature", "Curvatura"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index b21bebf9..b21f8549 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -188,6 +188,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Crate", "箱子"), ("Create", "创建"), ("Create smart material", "创建智能材质"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "在视图中按住 Ctrl 右键拖动可调整大小和硬度,Ctrl 左键拖动可调整流量和角度。", + ), ("Cube", "立方体"), ("Current layer", "当前图层"), ("Curvature", "曲率"), diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 06011755..a88fe262 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -199,14 +199,16 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin app.session.viewport = Vec2::new(size.x.max(16.0), size.y.max(16.0)); let (alt, shift) = ui.input(|i| (i.modifiers.alt, i.modifiers.shift)); let local = |p: egui::Pos2| Vec2::new(p.x - rect.left(), p.y - rect.top()); - let navigating = alt || ui.input(|i| i.pointer.middle_down() || i.pointer.secondary_down()); + let adjusting = brush_drag(app, ui, &resp); + let navigating = !adjusting && (alt || ui.input(|i| i.pointer.middle_down() || i.pointer.secondary_down())); // Navigation (S + drag manipulates the projection stencil instead, below). let delta = ui.input(|i| i.pointer.delta()); let s_held = ui.input(|i| i.key_down(egui::Key::S)) && !ui.ctx().egui_wants_keyboard_input(); let stencil_drag = s_held && app.session.tool.stencil.is_some(); - if stencil_drag { - // The stencil moves, turns and scales instead of the camera (handled below). + if stencil_drag || adjusting { + // The stencil moves, turns and scales instead of the camera (handled below), or the + // brush changes. } else if resp.dragged_by(PointerButton::Middle) { app.session.camera.pan(delta.x / size.y, delta.y / size.y); } else if alt && resp.dragged_by(PointerButton::Primary) { @@ -302,8 +304,15 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // The selected decal's frame and handles: drag to move, scale or turn it. let decal_drag = !alt && !s_held && !v_held && !focus_pick && placing.is_none() && touch.is_none() && decal_input(app, ui, &resp, rect); // Painting. - let painting = - app.ui.mode == crate::state::Mode::Painting && !alt && !s_held && !v_held && !focus_pick && placing.is_none() && touch.is_none() && !decal_drag; + let painting = app.ui.mode == crate::state::Mode::Painting + && !alt + && !adjusting + && !s_held + && !v_held + && !focus_pick + && placing.is_none() + && touch.is_none() + && !decal_drag; let path_tool = app.session.tool.tool == Tool::Path; let vp = app.session.viewport; let show = |app: &TextureCraftApp, p: Vec3| project(app, rect, p); @@ -368,8 +377,9 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if app.ui.mode == crate::state::Mode::Painting && !navigating && resp.hovered() - && matches!(app.session.tool.tool, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path) - && let Some(hp) = resp.hover_pos() + && brush_tool(app.session.tool.tool) + // While a Ctrl+drag changes the brush, its cursor stays where the drag began. + && let Some(hp) = if adjusting { ui.input(|i| i.pointer.press_origin()) } else { resp.hover_pos() } && let Some(hit) = app.session.pick(local(hp), app.session.viewport) { ui.ctx().set_cursor_icon(egui::CursorIcon::None); @@ -392,6 +402,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } stencil_overlay(app, ui, rect); decal_overlay(app, ui, rect); + brush_readout(app, ui, &resp, adjusting); if app.session.quick_mask.editing { ui.painter_at(rect).text( rect.left_top() + vec2(12.0, 40.0), @@ -754,6 +765,62 @@ fn clone_marker(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3) { } } +/// Tools that paint with the brush (and show its cursor). +fn brush_tool(t: Tool) -> bool { + matches!(t, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path) +} + +/// Ctrl (Cmd on macOS) + drag in a view changes the brush instead of painting or navigating: a +/// right drag its size (left/right) and hardness (up/down), a left drag its flow and angle. True +/// while Ctrl is held with a brush tool and no stroke is under way. +fn brush_drag(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response) -> bool { + let held = + app.ui.mode == crate::state::Mode::Painting && brush_tool(app.session.tool.tool) && !app.session.stroke_active() && ui.input(|i| i.modifiers.command); + if held && let Some(right) = brush_drag_button(resp) { + adjust_brush(&mut app.session.tool.brush, right, ui.input(|i| i.pointer.delta())); + } + held +} + +/// The button of a drag on `resp`: Some(true) right, Some(false) left. +fn brush_drag_button(resp: &egui::Response) -> Option { + let right = resp.dragged_by(PointerButton::Secondary); + (right || resp.dragged_by(PointerButton::Primary)).then_some(right) +} + +/// While a Ctrl+drag changes the brush, its values beside where the drag began (drawn over the +/// view; the tool bar and Properties show them too). +fn brush_readout(app: &TextureCraftApp, ui: &Ui, resp: &egui::Response, adjusting: bool) { + let Some(right) = brush_drag_button(resp).filter(|_| adjusting) else { return }; + let Some(at) = ui.input(|i| i.pointer.press_origin()) else { return }; + // The pointer would cover the values; the brush cursor stays where the drag began. + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + let b = &app.session.tool.brush; + let text = if right { + format!("{} {:.1} {} {:.0}", tr("Size"), b.size / 0.25 * 100.0, tr("Hardness"), b.hardness * 100.0) + } else { + format!("{} {:.0} {} {:.0}°", tr("Flow"), b.flow * 100.0, tr("Angle"), b.angle) + }; + let tk = Tokens::get(ui.ctx()); + let p = ui.painter_at(resp.rect); + let g = p.layout_no_wrap(text, egui::FontId::proportional(12.0), tk.text_strong); + let r = Rect::from_min_size(at + vec2(18.0, -30.0), g.size()).expand2(vec2(6.0, 3.0)); + p.rect_filled(r, 3.0, tk.panel); + p.galley(r.min + vec2(6.0, 3.0), g, tk.text_strong); +} + +/// Brush change for a Ctrl+drag by `d` points: `right` sets the size (x) and hardness (y), else +/// the flow (x) and angle (y); dragging up raises hardness and angle. +fn adjust_brush(b: &mut texturecraft_engine::paint::BrushSettings, right: bool, d: egui::Vec2) { + if right { + b.size = (b.size * (1.0 + d.x * 0.005)).clamp(0.0005, 0.25); + b.hardness = (b.hardness - d.y * 0.005).clamp(0.0, 0.999); + } else { + b.flow = (b.flow + d.x * 0.005).clamp(0.0, 1.0); + b.angle = (b.angle - d.y * 0.5 + 180.0).rem_euclid(360.0) - 180.0; + } +} + fn brush_cursor(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3, nrm: Vec3) { let (lo, hi) = app.session.mesh.bounds(); let r = app.session.tool.brush.size * (hi - lo).length(); @@ -791,6 +858,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let resp = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag()); let size = rect.size(); let alt = ui.input(|i| i.modifiers.alt); + let adjusting = brush_drag(app, ui, &resp); let delta = ui.input(|i| i.pointer.delta()); if resp.dragged_by(PointerButton::Middle) || (alt && resp.dragged_by(PointerButton::Primary)) { app.ui.uv_pan[0] += delta.x / size.x * 2.0; @@ -836,7 +904,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let uv = to_uv(p); app.run("tool.cloneSource", json!({"uv": [uv.x, uv.y]})); } - let painting = app.ui.mode == crate::state::Mode::Painting && !alt && !v_held; + let painting = app.ui.mode == crate::state::Mode::Painting && !alt && !adjusting && !v_held; if painting && path_tool { path_input(app, ui, &resp, true, |_, p| Some(to_uv(p).extend(0.0)), show); } else if painting { @@ -898,6 +966,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if app.ui.mode == crate::state::Mode::Painting && path_tool { path_overlay(app, ui, rect, &resp, true, show); } + brush_readout(app, ui, &resp, adjusting); view_header(app, ui, rect, "v2d"); axis_gizmo(ui, rect, app, true); let name = app.session.doc.project.texture_sets.get(ts).map(|t| t.name.clone()).unwrap_or_default(); diff --git a/crates/ui-egui/tests/brush_drag.rs b/crates/ui-egui/tests/brush_drag.rs new file mode 100644 index 00000000..9a8b1d10 --- /dev/null +++ b/crates/ui-egui/tests/brush_drag.rs @@ -0,0 +1,46 @@ +//! Ctrl+drag in the 3D view changes the brush instead of painting or orbiting. + +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use texturecraft_ui_egui::TextureCraftApp; + +/// Drag with `button` from `from` by `by` in a few moves. +fn drag(h: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: Pos2, by: egui::Vec2, modifiers: Modifiers) { + h.event(Event::ModifiersChanged(modifiers)); + h.hover_at(from); + h.event(Event::PointerButton { pos: from, button, pressed: true, modifiers }); + h.run_steps(2); + for k in 1..=4 { + h.hover_at(from + by * (k as f32 / 4.0)); + h.run_steps(1); + } + h.event(Event::PointerButton { pos: from + by, button, pressed: false, modifiers }); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(3); +} + +#[test] +fn ctrl_drag_changes_the_brush_instead_of_painting_or_orbiting() { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + let c = h.state().viewport_rect.center(); + let (brush, yaw, history) = { + let s = &h.state().session; + (s.tool.brush.clone(), s.camera.yaw, s.history_labels().len()) + }; + // Right drag to the right and up: a bigger, harder brush; the camera stays. + drag(&mut h, PointerButton::Secondary, c, vec2(80.0, -40.0), Modifiers::COMMAND); + let b = h.state().session.tool.brush.clone(); + assert!(b.size > brush.size && b.hardness > brush.hardness, "{} {} → {} {}", brush.size, brush.hardness, b.size, b.hardness); + assert_eq!(h.state().session.camera.yaw, yaw, "no orbit"); + // Left drag to the left and up: less flow, a turned brush, and no stroke. + drag(&mut h, PointerButton::Primary, c, vec2(-80.0, -40.0), Modifiers::COMMAND); + let b2 = h.state().session.tool.brush.clone(); + assert!(b2.flow < b.flow && b2.angle != b.angle, "{} {} → {} {}", b.flow, b.angle, b2.flow, b2.angle); + assert_eq!(h.state().session.history_labels().len(), history, "nothing painted"); + // Without Ctrl, a right drag orbits again and the brush keeps its values. + drag(&mut h, PointerButton::Secondary, c, vec2(80.0, -40.0), Modifiers::NONE); + assert_ne!(h.state().session.camera.yaw, yaw); + assert_eq!(h.state().session.tool.brush, b2); +} diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 2a44f4ff..8b4dae9b 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -73,4 +73,16 @@ fn window_snapshots() { texturecraft_engine::execute(s, id, &p).unwrap(); } save(&mut h, &dir, "properties-levels"); + // Ctrl+right drag in the 3D view: the brush cursor where it began and the readout. + let c = h.state().viewport_rect.center(); + let (m, button) = (egui::Modifiers::COMMAND, egui::PointerButton::Secondary); + h.event(egui::Event::ModifiersChanged(m)); + h.event(egui::Event::PointerButton { pos: c, button, pressed: true, modifiers: m }); + for k in 1..=4 { + h.hover_at(c + egui::vec2(15.0 * k as f32, -8.0 * k as f32)); + h.run_steps(1); + } + save(&mut h, &dir, "brush-ctrl-drag"); + h.event(egui::Event::PointerButton { pos: c, button, pressed: false, modifiers: m }); + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); } diff --git a/docs/features.md b/docs/features.md index 5043fcac..a1795141 100644 --- a/docs/features.md +++ b/docs/features.md @@ -7,6 +7,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Brushes** with size, flow, stroke opacity, spacing, hardness, angle and follow path; size, angle, flow and position jitter; tangent or camera alignment, angle fade, backface culling, lazy mouse, X/Y/Z mirror and radial symmetry (copies paint the far side too) and pen pressure. + Ctrl+drag in a view sets them on the fly: right-drag the size and hardness, left-drag the flow + and angle. **67 procedural brush alphas** in their own shelf tab, or any imported image as the alpha. **18 brush presets** (basic, wear and grunge, details) in the shelf's Brushes tab set the stroke and keep the size; save your own brushes there too. From b133186641b545d580a563468f8164a1565bd5da Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 12:00:09 +0700 Subject: [PATCH 58/60] History: click a step to return to it The History panel lists every undone step too (dimmed, next first) and a click on any step goes back or forward to it, the current one highlighted. edit.undo and edit.redo take {steps?} for the same jump. --- crates/engine/src/session.rs | 4 +++ crates/engine/src/view_cmds.rs | 47 ++++++++++++++++++++++++--- crates/engine/tests/session.rs | 24 ++++++++++++++ crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/windows.rs | 25 ++++++++++---- crates/ui-egui/tests/history_panel.rs | 36 ++++++++++++++++++++ docs/control-protocol.md | 3 ++ docs/features.md | 1 + 16 files changed, 137 insertions(+), 12 deletions(-) create mode 100644 crates/ui-egui/tests/history_panel.rs diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 14891a8f..de97ce6a 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -601,6 +601,10 @@ impl Session { pub fn redo_label(&self) -> Option<&str> { self.redo.last().map(|(l, _)| l.as_str()) } + /// The undone steps, the next one to redo first. + pub fn redo_labels(&self) -> Vec { + self.redo.iter().rev().map(|(l, _)| l.clone()).collect() + } pub fn history_labels(&self) -> Vec { self.undo.iter().map(|(l, _)| l.clone()).collect() } diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index 2237a698..b39c876d 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -5,7 +5,7 @@ use texturecraft_core::project::ENVIRONMENTS; use texturecraft_core::{BakedMap, Channel, ToneMapping}; use texturecraft_geom::glam::Vec3; -use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp}; +use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p}; use crate::session::ViewMode; use crate::{Result, Session, cmd}; @@ -35,14 +35,51 @@ pub fn specs() -> Vec { pub(crate) fn edit_specs() -> Vec { vec![ - cmd!("edit.undo", "Undo", ["Edit"], Some("Ctrl+Z"), "{}", can_undo, |s, _| Ok(json!({ "undone": s.undo()? }))), - cmd!("edit.redo", "Redo", ["Edit"], Some("Ctrl+Y"), "{}", can_redo, |s, _| Ok(json!({ "redone": s.redo()? }))), - cmd!("edit.history", "History", [], None, "{}", always, |s, _| Ok( - json!({ "undo": s.history_labels(), "redo": s.redo.iter().rev().map(|(l, _)| l.clone()).collect::>() }) + cmd!( + "edit.undo", + "Undo", + ["Edit"], + Some("Ctrl+Z"), + "{steps?: 1 (as many as there are)} → {undone: the last step undone, steps}", + can_undo, + |s, p| { + let (last, n) = repeat(s, p, Session::undo)?; + Ok(json!({ "undone": last, "steps": n })) + } + ), + cmd!( + "edit.redo", + "Redo", + ["Edit"], + Some("Ctrl+Y"), + "{steps?: 1 (as many as there are)} → {redone: the last step redone, steps}", + can_redo, + |s, p| { + let (last, n) = repeat(s, p, Session::redo)?; + Ok(json!({ "redone": last, "steps": n })) + } + ), + cmd!("edit.history", "History", [], None, "{} → {undo: steps, oldest first, redo: undone steps, next first}", always, |s, _| Ok( + json!({ "undo": s.history_labels(), "redo": s.redo_labels() }) )), ] } +/// Run `step` (undo or redo) `steps` times (default 1) or until the history runs out: the last +/// step's label and how many ran (the History panel jumps to a step this way). +fn repeat(s: &mut Session, p: &Value, step: fn(&mut Session) -> Result) -> Result<(String, u64)> { + let steps = u64p(p, "steps").unwrap_or(1).max(1); + let mut last = step(s)?; + let mut n = 1; + while n < steps + && let Ok(l) = step(s) + { + last = l; + n += 1; + } + Ok((last, n)) +} + fn frame(s: &mut Session, _: &Value) -> Result { let (lo, hi) = s.mesh.bounds(); s.camera.frame(lo, hi); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 5e22e610..02be7a8d 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -69,6 +69,30 @@ fn layer_rename_and_undo() { assert_eq!(s.doc.project.layer(layer_id).unwrap().name, "Custom Paint"); } +#[test] +fn undo_and_redo_jump_several_steps() { + let mut s = session(); + let layer = s.selected_layer().unwrap(); + let name = |s: &Session| s.doc.project.layer(layer).unwrap().name.clone(); + let first = name(&s); + for n in ["A", "B", "C"] { + execute(&mut s, "layer.rename", &json!({"name": n})).unwrap(); + } + let base = s.history_labels().len() - 3; + // Two back to "A": the undone steps wait to be redone, next first. + assert_eq!(execute(&mut s, "edit.undo", &json!({"steps": 2})).unwrap(), json!({"undone": "Rename layer", "steps": 2})); + assert_eq!(name(&s), "A"); + assert_eq!(s.redo_labels().len(), 2); + assert_eq!(execute(&mut s, "edit.history", &Value::Null).unwrap()["redo"].as_array().unwrap().len(), 2); + // Forward past the end stops at "C"; back past the start stops at the first state. + assert_eq!(execute(&mut s, "edit.redo", &json!({"steps": 99})).unwrap()["steps"], 2); + assert_eq!(name(&s), "C"); + let r = execute(&mut s, "edit.undo", &json!({"steps": 1_000_000})).unwrap(); + assert_eq!(r["steps"].as_u64().unwrap() as usize, base + 3); + assert_eq!(name(&s), first); + assert!(execute(&mut s, "edit.undo", &json!({"steps": 2})).is_err(), "nothing left to undo"); +} + #[test] fn polygon_fill_and_color_picker() { let mut s = session(); diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 60a24624..d9659ae5 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -657,6 +657,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "تغيير الحجم"), ("Restore every default shortcut", "استعادة كل الاختصارات الافتراضية"), ("Return to painting mode", "العودة إلى نمط الرسم"), + ("Return to this step", "العودة إلى هذه الخطوة"), ("Right-click a layer > Create smart material", "انقر بزر الفأرة الأيمن على طبقة > إنشاء مادة ذكية"), ("Rotation", "التدوير"), ("Rotation (degrees)", "التدوير (بالدرجات)"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index b750471d..0be0cc4b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -699,6 +699,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "Größe wird geändert"), ("Restore every default shortcut", "Alle Standard-Tastenkürzel wiederherstellen"), ("Return to painting mode", "Zurück zum Malmodus"), + ("Return to this step", "Zu diesem Schritt zurückkehren"), ("Right-click a layer > Create smart material", "Rechtsklick auf eine Ebene > Smart-Material erstellen"), ("Rotation", "Drehung"), ("Rotation (degrees)", "Drehung (Grad)"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 23366253..0c73dcd0 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -687,6 +687,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "Redimensionando"), ("Restore every default shortcut", "Restaurar todos los atajos predeterminados"), ("Return to painting mode", "Volver al modo de pintura"), + ("Return to this step", "Volver a este paso"), ("Right-click a layer > Create smart material", "Clic derecho en una capa > Crear material inteligente"), ("Rotation", "Rotación"), ("Rotation (degrees)", "Rotación (grados)"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 8fe9ccbb..6dea9b52 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -699,6 +699,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "Redimensionnement"), ("Restore every default shortcut", "Restaurer tous les raccourcis par défaut"), ("Return to painting mode", "Revenir au mode peinture"), + ("Return to this step", "Revenir à cette étape"), ("Right-click a layer > Create smart material", "Clic droit sur un calque > Créer un matériau intelligent"), ("Rotation", "Rotation"), ("Rotation (degrees)", "Rotation (degrés)"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 62ec183b..c837665d 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -696,6 +696,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "Ridimensionamento"), ("Restore every default shortcut", "Ripristina tutte le scorciatoie predefinite"), ("Return to painting mode", "Torna alla modalità pittura"), + ("Return to this step", "Torna a questo passaggio"), ("Right-click a layer > Create smart material", "Clic destro su un livello > Crea materiale intelligente"), ("Rotation", "Rotazione"), ("Rotation (degrees)", "Rotazione (gradi)"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 7dc6e6e1..e11cb5ed 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -675,6 +675,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "サイズ変更中"), ("Restore every default shortcut", "すべてのショートカットをデフォルトに戻す"), ("Return to painting mode", "ペイントモードに戻る"), + ("Return to this step", "このステップに戻る"), ("Right-click a layer > Create smart material", "レイヤーを右クリック > スマートマテリアルを作成"), ("Rotation", "回転"), ("Rotation (degrees)", "回転 (度)"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f9c167e7..225316a4 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -666,6 +666,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "크기 조정 중"), ("Restore every default shortcut", "모든 기본 단축키를 복원합니다"), ("Return to painting mode", "페인팅 모드로 돌아가기"), + ("Return to this step", "이 단계로 돌아가기"), ("Right-click a layer > Create smart material", "레이어 마우스 오른쪽 클릭 > 스마트 머티리얼 만들기"), ("Rotation", "회전"), ("Rotation (degrees)", "회전 (도)"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index dc7521c3..4a2cb7a9 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -684,6 +684,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "Redimensionando"), ("Restore every default shortcut", "Restaurar todos os atalhos padrão"), ("Return to painting mode", "Voltar ao modo de pintura"), + ("Return to this step", "Voltar a esta etapa"), ("Right-click a layer > Create smart material", "Clique com o botão direito em uma camada > Criar material inteligente"), ("Rotation", "Rotação"), ("Rotation (degrees)", "Rotação (graus)"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 41136b04..471c4f3c 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -615,6 +615,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "正在调整大小"), ("Restore every default shortcut", "恢复所有默认快捷键"), ("Return to painting mode", "返回绘画模式"), + ("Return to this step", "返回到此步骤"), ("Right-click a layer > Create smart material", "右键单击图层 > 创建智能材质"), ("Rotation", "旋转"), ("Rotation (degrees)", "旋转(度)"), diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 6d44fc5f..8fa3de0e 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -281,16 +281,27 @@ pub(crate) fn shader(app: &mut TextureCraftApp, ui: &mut Ui) { /// The History panel body (a dock tab). pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); - let labels = app.session.history_labels(); + let (done, undone) = (app.session.history_labels(), app.session.redo_labels()); + // A click on a step goes back (or forward) to it: steps to undo, or to redo when negative. + let mut jump = 0i64; egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| { - ui.label(RichText::new(tr("Project opened")).color(tk.text_dim)); - for l in &labels { - ui.label(l); - } - if let Some(r) = app.session.redo_label() { - ui.label(RichText::new(trf("{action} (undone)", &[("action", &r)])).color(tk.text_dim)); + let n = done.len() as i64; + let rows = std::iter::once(RichText::new(tr("Project opened")).color(tk.text_dim)) + .chain(done.iter().map(RichText::new)) + .chain(undone.iter().map(|l| RichText::new(trf("{action} (undone)", &[("action", l)])).color(tk.text_dim))); + for (i, text) in rows.enumerate() { + // Row i is the state after i steps. + let steps = n - i as i64; + if ui.selectable_label(steps == 0, text).on_hover_text(tr("Return to this step")).clicked() { + jump = steps; + } } }); + if jump > 0 { + app.run("edit.undo", json!({ "steps": jump })); + } else if jump < 0 { + app.run("edit.redo", json!({ "steps": -jump })); + } ui.horizontal(|ui| { if ui.add_enabled(app.session.can_undo(), egui::Button::new(format!("{} {}", ic::ARROW_COUNTER_CLOCKWISE, tr("Undo")))).clicked() { app.run("edit.undo", json!({})); diff --git a/crates/ui-egui/tests/history_panel.rs b/crates/ui-egui/tests/history_panel.rs new file mode 100644 index 00000000..b3f134f0 --- /dev/null +++ b/crates/ui-egui/tests/history_panel.rs @@ -0,0 +1,36 @@ +//! A click on a step of the History panel goes back or forward to it. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; + +#[test] +fn clicking_a_history_step_returns_to_it() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = session.selected_layer().unwrap(); + for name in ["Step A", "Step B", "Step C"] { + texturecraft_engine::execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": name})).unwrap(); + } + let done = session.history_labels().len(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.dock.focus(Panel::History); + h.run_steps(4); + let name = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].name.clone(); + // The first state: everything undone, and listed as undone. + h.get_by_label("Project opened").click(); + h.run_steps(3); + assert!(!h.state().session.can_undo()); + assert_eq!(h.state().session.redo_labels().len(), done); + // The first undone row is the next step: one redo. + h.get_all_by_label("Rename layer (undone)").next().unwrap().click(); + h.run_steps(3); + assert_eq!(h.state().session.history_labels().len(), 1); + assert_eq!(h.state().session.redo_labels().len(), done - 1); + // The last undone row: all the way forward again. + h.get_all_by_label("Rename layer (undone)").last().unwrap().click(); + h.run_steps(3); + assert_eq!(name(&h), "Step C"); + assert!(!h.state().session.can_redo()); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index f8048861..5d59d5d1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -16,6 +16,9 @@ painted tile count, so an agent can verify its work without a screenshot. `effect.histogram {effect, channel?, bins?}` counts the values an effect reads (a levels effect's input), so an agent can pick its input range from the data. +`edit.undo {steps?}` and `edit.redo {steps?}` go back or forward several steps at once (as far +as the history reaches); `edit.history` lists the steps done and the undone ones, next first. + ## Control channel (desktop app) ```sh diff --git a/docs/features.md b/docs/features.md index 7b858cfe..d76b0a55 100644 --- a/docs/features.md +++ b/docs/features.md @@ -120,6 +120,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - A **start window** at launch: a new project, a project file, a recent project or the sample (Settings › Interface › Start window). - A **shortcut editor** with conflict detection, and every shortcut shown in its tooltip. +- A **History** panel: click any step to go back to it, or forward again to an undone one. - **10 languages:** English, French, German, Spanish, Portuguese, Italian, Japanese, Chinese, Korean and Arabic, switchable live. - **In the browser:** the same app compiled to WebAssembly, on WebGPU or WebGL2, with touch From 4ca9f424f438c5350d08082c01153838bc61f3be Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 12:13:39 +0700 Subject: [PATCH 59/60] Effects: copy, cut and paste between layers An effect's context menu copies, cuts and pastes it, and Ctrl+C, Ctrl+X and Ctrl+V act on a selected effect (pasting a copied one above the selected effect, or on top of the selected content or mask). Painted strokes come along, resampled to the target set; generators and other one-stack effects go to their stack, and a fill reading an anchor point needs one below its new layer. effect.copy, effect.cut and effect.paste share the layer clipboard. --- crates/engine/src/commands.rs | 1 + crates/engine/src/effect_clipboard.rs | 128 ++++++++++++++++++++++++ crates/engine/src/instance_cmds.rs | 1 + crates/engine/src/layer_ops.rs | 8 +- crates/engine/src/lib.rs | 1 + crates/engine/src/mask_cmds.rs | 2 +- crates/engine/src/session.rs | 2 +- crates/engine/tests/content_effects.rs | 47 ++++++++- crates/ui-egui/src/dock.rs | 32 ++++-- crates/ui-egui/src/i18n/ar.rs | 3 + crates/ui-egui/src/i18n/de.rs | 3 + crates/ui-egui/src/i18n/es.rs | 3 + crates/ui-egui/src/i18n/fr.rs | 3 + crates/ui-egui/src/i18n/it.rs | 3 + crates/ui-egui/src/i18n/ja.rs | 3 + crates/ui-egui/src/i18n/ko.rs | 3 + crates/ui-egui/src/i18n/pt_br.rs | 3 + crates/ui-egui/src/i18n/zh_hans.rs | 3 + crates/ui-egui/src/menus.rs | 16 ++- crates/ui-egui/tests/layer_clipboard.rs | 17 ++++ docs/control-protocol.md | 3 +- docs/features.md | 2 +- 22 files changed, 269 insertions(+), 18 deletions(-) create mode 100644 crates/engine/src/effect_clipboard.rs diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index ef18af36..2f78bc1a 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -56,6 +56,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::layer_ops::specs()); v.extend(crate::instance_cmds::specs()); v.extend(crate::mask_cmds::specs()); + v.extend(crate::effect_clipboard::specs()); v.extend(crate::tool_cmds::specs()); v.extend(crate::brush_preset_cmds::specs()); v.extend(crate::path_tool::specs()); diff --git a/crates/engine/src/effect_clipboard.rs b/crates/engine/src/effect_clipboard.rs new file mode 100644 index 00000000..748ecd7f --- /dev/null +++ b/crates/engine/src/effect_clipboard.rs @@ -0,0 +1,128 @@ +//! Copy and paste effects between layers, masks and texture sets. The clipboard is the layer +//! clipboard: it holds a layer or an effect. + +use serde_json::{Value, json}; +use texturecraft_core::{EffectKind, LayerId, Mask, MaskBackground, Source}; + +use crate::commands::{CommandSpec, bad, has_layer, layer_param, strp, u64p}; +use crate::layer_ops::{empty_texel, fit}; +use crate::mask_cmds::{anchor_source, content_target}; +use crate::session::StackTarget; +use crate::{EngineError, Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![ + cmd!("effect.copy", "Copy effect", [], None, "{effect?: the selected effect}", has_layer, copy), + cmd!("effect.cut", "Cut effect", [], None, "{effect?: the selected effect}", has_layer, cut), + cmd!( + "effect.paste", + "Paste effect", + [], + None, + "{layer?, target?: mask|content (default: the selection's stack)} → {effect} — above the selected effect, or on top of the stack", + can_paste, + paste + ), + ] +} + +/// The copied effect, if the clipboard holds one. +fn clipboard_effect(s: &Session) -> Option { + s.clipboard.as_ref().and_then(|(doc, id)| doc.project.effect(*id).map(|_| *id)) +} + +fn can_paste(s: &Session) -> std::result::Result<(), String> { + match clipboard_effect(s) { + Some(_) if s.selected_layer().is_some() => Ok(()), + Some(_) => Err("select a layer to paste the effect on".into()), + None => Err("the clipboard holds no effect".into()), + } +} + +fn copy(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "effect.copy"; + let eid = match (u64p(p, "effect"), s.target) { + (Some(e), _) => LayerId(e), + (None, StackTarget::Effect(e)) => e, + (None, _) => return Err(bad(CMD, "`effect` is required (no effect is selected)")), + }; + if s.doc.project.effect(eid).is_none() { + return Err(bad(CMD, format!("no effect {}", eid.0))); + } + s.clipboard = Some((s.doc.clone(), eid)); + Ok(json!({ "copied": eid.0 })) +} + +fn cut(s: &mut Session, p: &Value) -> Result { + let eid = copy(s, p)?["copied"].clone(); + crate::execute(s, "effect.remove", &json!({ "effect": eid }))?; + Ok(json!({ "cut": eid })) +} + +fn paste(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "effect.paste"; + let (src, eid) = s.clipboard.clone().ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; + let effect = src.project.effect(eid).map(|(_, e)| e.clone()).ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; + let layer = layer_param(s, CMD, p)?; + // The selected effect's stack, or the content or mask the selection targets. + let selected = match s.target { + StackTarget::Effect(x) if s.selected_layer() == Some(layer) => Some(x), + _ => None, + }; + let in_content = |s: &Session, x: LayerId| { + s.doc.project.effect(x).and_then(|(o, _)| s.doc.project.layers.get(&o)).is_some_and(|l| l.content_effects.iter().any(|e| e.id == x)) + }; + let asked = strp(p, "target").is_some(); + let content = match selected { + _ if asked => content_target(p, CMD)?, + Some(x) => in_content(s, x), + None => s.target == StackTarget::Content && s.selected_layer() == Some(layer), + }; + // Effects that fit one stack only go there, unless another was asked for. + let content = match effect.kind.content_only() { + Some(only) if only != content && asked => { + return Err(bad(CMD, format!("{} effects go on the {}", effect.kind.name(), if only { "layer content" } else { "mask" }))); + } + Some(only) => only, + None => content, + }; + // An instance's content and (unless it has its own) mask belong to its source. + let owner = if content { s.doc.project.content_layer(layer).map_or(layer, |l| l.id) } else { s.doc.project.mask_owner(layer) }; + let owner_layer = s.doc.project.layer(owner)?; + if content && owner_layer.is_group() { + return Err(EngineError::Other(format!("\"{}\" is a folder: content effects go on paint and fill layers", owner_layer.name))); + } + // A fill reading an anchor point needs one below its new layer. + if let EffectKind::Fill { source: Source::Anchor { anchor, channel }, .. } = &effect.kind { + anchor_source(s, CMD, owner, *anchor, *channel)?; + } + let (ts, _, _) = s.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the layer is not in a stack"))?; + let (size, channels) = s.doc.project.texture_set(ts).map(|t| (t.size(), t.channel_list()))?; + let new = s.edit("Paste effect", |s| { + let new = s.doc.project.alloc_id(); + let l = s.doc.project.layer_mut(owner)?; + let list = if content { + &mut l.content_effects + } else { + let bg = if matches!(effect.kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White }; + &mut l.mask.get_or_insert_with(|| Mask::new(bg)).effects + }; + let at = selected.and_then(|x| list.iter().position(|e| e.id == x)).map_or(list.len(), |i| i + 1); + list.insert(at, texturecraft_core::Effect { id: new, ..effect.clone() }); + // Painted pixels come along, resampled to the set's size (a mask's paint stays a mask's). + if let Some(img) = src.pixels.masks.get(&eid).filter(|_| !content) { + s.doc.pixels.masks.insert(new, fit(img, size, &[0, 0])); + } + for c in channels.iter().copied().filter(|_| content) { + if let Some(img) = src.pixels.layer(eid, c) { + s.doc.pixels.layers.insert((new, c), fit(img, size, &empty_texel(c))); + } + } + if let Some((lts, _, _)) = s.doc.project.locate(layer) { + s.selected.insert(lts, layer); + } + s.target = StackTarget::Effect(new); + Ok(new) + })?; + Ok(json!({ "effect": new.0 })) +} diff --git a/crates/engine/src/instance_cmds.rs b/crates/engine/src/instance_cmds.rs index 255a69c3..a9307883 100644 --- a/crates/engine/src/instance_cmds.rs +++ b/crates/engine/src/instance_cmds.rs @@ -69,6 +69,7 @@ fn instance(s: &mut Session, p: &Value) -> Result { fn can_paste_instance(s: &Session) -> std::result::Result<(), String> { match &s.clipboard { Some((_, id)) if s.doc.project.locate(*id).is_some() => Ok(()), + Some((doc, id)) if doc.project.effect(*id).is_some() => Err("the clipboard holds an effect (effect.paste)".into()), Some(_) => Err("the copied layer is no longer in the project (paste it instead)".into()), None => Err("the layer clipboard is empty".into()), } diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index 0d260063..9493009b 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -36,7 +36,11 @@ pub fn specs() -> Vec { } fn can_paste(s: &Session) -> std::result::Result<(), String> { - if s.clipboard.is_some() { Ok(()) } else { Err("the layer clipboard is empty".into()) } + match &s.clipboard { + Some((doc, id)) if doc.project.layers.contains_key(id) => Ok(()), + Some(_) => Err("the clipboard holds an effect (effect.paste)".into()), + None => Err("the layer clipboard is empty".into()), + } } /// Encoded "nothing painted" texel for a channel image (value 0, coverage 0). @@ -47,7 +51,7 @@ pub(crate) fn empty_texel(c: Channel) -> Vec { v } -fn fit(img: &TileImage, (w, h): (u32, u32), empty: &[u16]) -> TileImage { +pub(crate) fn fit(img: &TileImage, (w, h): (u32, u32), empty: &[u16]) -> TileImage { if (img.width(), img.height()) == (w, h) { img.clone() } else { img.resampled(w, h, empty) } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8016a5d0..678f66e0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -13,6 +13,7 @@ pub mod brush_preset_cmds; pub mod camera_cmds; pub mod commands; pub mod decal_cmds; +pub mod effect_clipboard; pub mod file_cmds; pub mod filter_lib; pub mod inspect; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 90d54c0b..5d7ecd2f 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -211,7 +211,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { /// Whether `effect.add.*` targets the layer content (`target: "content"`) or its mask (the /// default). -fn content_target(p: &Value, cmd: &str) -> Result { +pub(crate) fn content_target(p: &Value, cmd: &str) -> Result { match strp(p, "target") { None | Some("mask") => Ok(false), Some("content") => Ok(true), diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index baf012b6..fff6ee18 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -333,7 +333,7 @@ pub struct Session { /// Viewport size (pixels) used by scripted strokes. pub viewport: Vec2, pub(crate) stroke: Option, - /// Layer clipboard: a document snapshot and the copied layer. + /// Layer clipboard: a document snapshot and the copied layer (or effect). pub clipboard: Option<(Document, LayerId)>, /// Decoded image resources (rebuilt from `doc.resources` by `Session::sync_images`). pub images: texturecraft_compose::ImageStore, diff --git a/crates/engine/tests/content_effects.rs b/crates/engine/tests/content_effects.rs index dca2378b..e6c75e1e 100644 --- a/crates/engine/tests/content_effects.rs +++ b/crates/engine/tests/content_effects.rs @@ -1,7 +1,7 @@ //! Content effects, HSL and anchor points through engine commands. use serde_json::{Value, json}; -use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::core::{Channel, EffectKind, LayerId}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, StackTarget, execute}; @@ -155,6 +155,51 @@ fn effects_move_within_their_stack_and_duplicate_with_their_pixels() { assert_eq!(mask, [b, a]); } +#[test] +fn effects_copy_and_paste_between_layers_and_stacks() { + let mut s = session(); + let low = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3})).unwrap(), "layer"); + let paint = id(execute(&mut s, "effect.add.paint", &json!({"target": "content"})).unwrap(), "effect"); + execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.9})).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); + assert_eq!(execute(&mut s, "effect.copy", &Value::Null).unwrap(), json!({"copied": paint}), "the selected effect"); + assert!(execute(&mut s, "layer.paste", &Value::Null).is_err(), "the clipboard holds an effect, not a layer"); + // Onto the content of a fill above that covers the first: its strokes come along. + let high = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3})).unwrap(), "layer"); + let pasted = id(execute(&mut s, "effect.paste", &Value::Null).unwrap(), "effect"); + assert_eq!(s.target, StackTarget::Effect(LayerId(pasted))); + assert!(s.doc.pixels.layer(LayerId(pasted), Channel::Roughness).is_some()); + execute(&mut s, "effect.remove", &json!({"effect": paint})).unwrap(); + assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "{:?}", center(&mut s, Channel::Roughness)); + // Above the selected effect. + let inv = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect"); + execute(&mut s, "effect.copy", &json!({"effect": inv})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": high, "target": pasted})).unwrap(); + let again = id(execute(&mut s, "effect.paste", &Value::Null).unwrap(), "effect"); + let order: Vec = s.doc.project.layer(LayerId(high)).unwrap().content_effects.iter().map(|e| e.id.0).collect(); + assert_eq!(order, [pasted, again, inv]); + // A generator goes on a mask (made for it) even with the content selected; asking for the + // content is an error. Cut removes the original. + execute(&mut s, "layer.select", &json!({"layer": high})).unwrap(); + let generator = id(execute(&mut s, "effect.add.generator", &Value::Null).unwrap(), "effect"); + execute(&mut s, "effect.cut", &json!({"effect": generator})).unwrap(); + assert!(s.doc.project.effect(LayerId(generator)).is_none()); + execute(&mut s, "layer.select", &json!({"layer": low})).unwrap(); + assert!(execute(&mut s, "effect.paste", &json!({"target": "content"})).is_err()); + execute(&mut s, "effect.paste", &Value::Null).unwrap(); + let mask = &s.doc.project.layer(LayerId(low)).unwrap().mask; + assert!(mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| matches!(e.kind, EffectKind::Generator(_))))); + // A fill reading an anchor point needs one below its new layer. + execute(&mut s, "layer.select", &json!({"layer": low})).unwrap(); + let anchor = id(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap(), "effect"); + execute(&mut s, "layer.select", &json!({"layer": high})).unwrap(); + let reader = id(execute(&mut s, "effect.add.fill", &json!({"target": "mask", "anchor": anchor})).unwrap(), "effect"); + execute(&mut s, "effect.copy", &json!({"effect": reader})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": low})).unwrap(); + assert!(execute(&mut s, "effect.paste", &Value::Null).is_err(), "the anchor is on the layer itself"); +} + #[test] fn histogram_counts_what_an_effect_reads() { let mut s = session(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index cc3a648c..537f787a 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -581,14 +581,26 @@ fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Ef app.run("effect.move", json!({"effect": src.0, "index": index})); } resp.context_menu(|ui| { - if ui.button(tr("Duplicate effect")).clicked() { - app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); - app.run("effect.duplicate", json!({"effect": eid.0})); - ui.close(); - } - if ui.button(tr("Remove effect")).clicked() { - app.run("effect.remove", json!({"effect": eid.0})); - ui.close(); + let keymap = app.ui.keymap.clone(); + let paste = crate::menus::enabled(app, "effect.paste"); + // The clipboard items show the layer clipboard's shortcuts, which act on a selected effect. + for (label, id, keys, enabled) in [ + (tr("Copy effect"), "effect.copy", Some("layer.copy"), true), + (tr("Cut effect"), "effect.cut", Some("layer.cut"), true), + (tr("Paste effect"), "effect.paste", Some("layer.paste"), paste), + (tr("Duplicate effect"), "effect.duplicate", None, true), + (tr("Remove effect"), "effect.remove", None, true), + ] { + let mut b = egui::Button::new(label); + if let Some(sc) = keys.and_then(|k| crate::keymap::shortcut_of(&keymap, k)) { + b = b.shortcut_text(sc); + } + if ui.add_enabled(enabled, b).clicked() { + // Selected first: a paste lands above it, a duplicate takes the selection. + app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); + app.run(id, json!({"effect": eid.0})); + ui.close(); + } } }); } @@ -681,7 +693,9 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { ui.separator(); run(app, ui, tr("Cut layer(s)"), "layer.cut", json!({"layer": lid}), true); run(app, ui, tr("Copy layer(s)"), "layer.copy", json!({"layer": lid}), true); - run(app, ui, tr("Paste layer(s)"), "layer.paste", json!({}), app.session.clipboard.is_some()); + let (paste_layer, paste_effect) = (crate::menus::enabled(app, "layer.paste"), crate::menus::enabled(app, "effect.paste")); + run(app, ui, tr("Paste layer(s)"), "layer.paste", json!({}), paste_layer); + run(app, ui, tr("Paste effect"), "effect.paste", json!({}), paste_effect); let paste_instance = crate::menus::enabled(app, "layer.pasteInstance"); run(app, ui, tr("Paste as instance"), "layer.pasteInstance", json!({}), paste_instance); run(app, ui, tr("Duplicate layer(s)"), "layer.duplicate", json!({"layer": lid}), true); diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index ddfc00b4..a955af2b 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -187,6 +187,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast/Luminosity", "التباين / الإضاءة"), ("Converted maps", "الخرائط المحوّلة"), ("Copy RGB values", "نسخ قيم RGB"), + ("Copy effect", "نسخ التأثير"), ("Copy from", "نسخ من"), ("Copy layer(s)", "نسخ الطبقة (الطبقات)"), ("Copy the selected layer alone (its empty parts copy nothing)", "نسخ الطبقة المحددة وحدها (الأجزاء الفارغة لا تنسخ شيئاً)"), @@ -209,6 +210,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Cube", "مكعب"), ("Current layer", "الطبقة الحالية"), ("Curvature", "الانحناء"), + ("Cut effect", "قص التأثير"), ("Cut layer(s)", "قص الطبقة (الطبقات)"), ("Cyan / red", "سماوي / أحمر"), ("Cylinder", "أسطوانة"), @@ -582,6 +584,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Particles", "جسيمات"), ("Passthrough", "تمرير مباشر (Passthrough)"), ("Paste as instance", "لصق كنسخة مرتبطة (Instance)"), + ("Paste effect", "لصق التأثير"), ("Paste layer(s)", "لصق الطبقة (الطبقات)"), ("Path", "مسار"), ("Path trace on the processor instead of the graphics card (slower)", "تتبع المسار على المعالج بدلاً من بطاقة الرسوميات (أبطأ)"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 50ee85a0..a025fed2 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -199,6 +199,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast/Luminosity", "Kontrast/Luminanz"), ("Converted maps", "Konvertierte Maps"), ("Copy RGB values", "RGB-Werte kopieren"), + ("Copy effect", "Effekt kopieren"), ("Copy from", "Kopieren aus"), ("Copy layer(s)", "Ebene(n) kopieren"), ("Copy the selected layer alone (its empty parts copy nothing)", "Nur die ausgewählte Ebene kopieren (ihre leeren Bereiche kopieren nichts)"), @@ -221,6 +222,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Cube", "Würfel"), ("Current layer", "Aktuelle Ebene"), ("Curvature", "Krümmung"), + ("Cut effect", "Effekt ausschneiden"), ("Cut layer(s)", "Ebene(n) ausschneiden"), ("Cyan / red", "Cyan / Rot"), ("Cylinder", "Zylinder"), @@ -618,6 +620,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Particles", "Partikel"), ("Passthrough", "Hindurchwirken"), ("Paste as instance", "Als Instanz einfügen"), + ("Paste effect", "Effekt einfügen"), ("Paste layer(s)", "Ebene(n) einfügen"), ("Path", "Pfad"), ("Path trace on the processor instead of the graphics card (slower)", "Path Tracing auf dem Prozessor statt auf der Grafikkarte (langsamer)"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 360fabcb..db130c41 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -196,6 +196,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast/Luminosity", "Contraste/Luminosidad"), ("Converted maps", "Mapas convertidos"), ("Copy RGB values", "Copiar los valores RGB"), + ("Copy effect", "Copiar efecto"), ("Copy from", "Copiar de"), ("Copy layer(s)", "Copiar capa(s)"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copiar solo la capa seleccionada (sus partes vacías no copian nada)"), @@ -218,6 +219,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Cube", "Cubo"), ("Current layer", "Capa actual"), ("Curvature", "Curvatura"), + ("Cut effect", "Cortar efecto"), ("Cut layer(s)", "Cortar capa(s)"), ("Cyan / red", "Cian / rojo"), ("Cylinder", "Cilindro"), @@ -609,6 +611,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Particles", "Partículas"), ("Passthrough", "Paso directo"), ("Paste as instance", "Pegar como instancia"), + ("Paste effect", "Pegar efecto"), ("Paste layer(s)", "Pegar capa(s)"), ("Path", "Trazado"), ("Path trace on the processor instead of the graphics card (slower)", "Trazar trayectorias en el procesador en lugar de la tarjeta gráfica (más lento)"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 9b0134b5..49099db4 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -199,6 +199,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast/Luminosity", "Contraste/Luminosité"), ("Converted maps", "Cartes converties"), ("Copy RGB values", "Copier les valeurs RVB"), + ("Copy effect", "Copier l'effet"), ("Copy from", "Copier depuis"), ("Copy layer(s)", "Copier le(s) calque(s)"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copier uniquement le calque sélectionné (ses parties vides ne copient rien)"), @@ -221,6 +222,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Cube", "Cube"), ("Current layer", "Calque actuel"), ("Curvature", "Courbure"), + ("Cut effect", "Couper l'effet"), ("Cut layer(s)", "Couper le(s) calque(s)"), ("Cyan / red", "Cyan / rouge"), ("Cylinder", "Cylindre"), @@ -621,6 +623,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Particles", "Particules"), ("Passthrough", "Transfert"), ("Paste as instance", "Coller comme instance"), + ("Paste effect", "Coller l'effet"), ("Paste layer(s)", "Coller le(s) calque(s)"), ("Path", "Tracé"), ("Path trace on the processor instead of the graphics card (slower)", "Tracé de chemins sur le processeur au lieu de la carte graphique (plus lent)"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index e4caba91..98ffb78d 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -202,6 +202,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast/Luminosity", "Contrasto/Luminosità"), ("Converted maps", "Mappe convertite"), ("Copy RGB values", "Copia i valori RGB"), + ("Copy effect", "Copia effetto"), ("Copy from", "Copia da"), ("Copy layer(s)", "Copia livello/i"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copia solo il livello selezionato (le sue parti vuote non copiano nulla)"), @@ -224,6 +225,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Cube", "Cubo"), ("Current layer", "Livello corrente"), ("Curvature", "Curvatura"), + ("Cut effect", "Taglia effetto"), ("Cut layer(s)", "Taglia livello/i"), ("Cyan / red", "Ciano / rosso"), ("Cylinder", "Cilindro"), @@ -615,6 +617,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Particles", "Particelle"), ("Passthrough", "Pass-through"), ("Paste as instance", "Incolla come istanza"), + ("Paste effect", "Incolla effetto"), ("Paste layer(s)", "Incolla livello/i"), ("Path", "Tracciato"), ("Path trace on the processor instead of the graphics card (slower)", "Esegui il path tracing sul processore anziché sulla scheda grafica (più lento)"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 82a55e51..c7502ad5 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -199,6 +199,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast/Luminosity", "コントラスト/輝度"), ("Converted maps", "変換マップ"), ("Copy RGB values", "RGB 値をコピー"), + ("Copy effect", "エフェクトをコピー"), ("Copy from", "コピー元"), ("Copy layer(s)", "レイヤーをコピー"), ("Copy the selected layer alone (its empty parts copy nothing)", "選択中のレイヤーのみをコピー (空の部分は何もコピーしない)"), @@ -221,6 +222,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Cube", "立方体"), ("Current layer", "現在のレイヤー"), ("Curvature", "曲率"), + ("Cut effect", "エフェクトを切り取り"), ("Cut layer(s)", "レイヤーを切り取り"), ("Cyan / red", "シアン / レッド"), ("Cylinder", "円柱"), @@ -597,6 +599,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Particles", "パーティクル"), ("Passthrough", "通過"), ("Paste as instance", "インスタンスとして貼り付け"), + ("Paste effect", "エフェクトを貼り付け"), ("Paste layer(s)", "レイヤーを貼り付け"), ("Path", "パス"), ("Path trace on the processor instead of the graphics card (slower)", "グラフィックカードではなくプロセッサーでパストレース (低速)"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 43b14e48..4a61bc58 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -190,6 +190,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast/Luminosity", "대비/광도"), ("Converted maps", "변환된 맵"), ("Copy RGB values", "RGB 값 복사"), + ("Copy effect", "이펙트 복사"), ("Copy from", "복사 원본"), ("Copy layer(s)", "레이어 복사"), ("Copy the selected layer alone (its empty parts copy nothing)", "선택한 레이어만 복사합니다 (빈 부분은 복사되지 않음)"), @@ -212,6 +213,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Cube", "큐브"), ("Current layer", "현재 레이어"), ("Curvature", "곡률"), + ("Cut effect", "이펙트 잘라내기"), ("Cut layer(s)", "레이어 잘라내기"), ("Cyan / red", "녹청 / 빨강"), ("Cylinder", "실린더"), @@ -588,6 +590,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Particles", "파티클"), ("Passthrough", "통과"), ("Paste as instance", "인스턴스로 붙여넣기"), + ("Paste effect", "이펙트 붙여넣기"), ("Paste layer(s)", "레이어 붙여넣기"), ("Path", "패스"), ("Path trace on the processor instead of the graphics card (slower)", "그래픽 카드 대신 프로세서에서 패스 트레이싱합니다 (더 느림)"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 6860307c..1707b143 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -196,6 +196,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast/Luminosity", "Contraste/Luminosidade"), ("Converted maps", "Mapas convertidos"), ("Copy RGB values", "Copiar os valores RGB"), + ("Copy effect", "Copiar efeito"), ("Copy from", "Copiar de"), ("Copy layer(s)", "Copiar camada(s)"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copiar apenas a camada selecionada (suas partes vazias não copiam nada)"), @@ -218,6 +219,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Cube", "Cubo"), ("Current layer", "Camada atual"), ("Curvature", "Curvatura"), + ("Cut effect", "Recortar efeito"), ("Cut layer(s)", "Recortar camada(s)"), ("Cyan / red", "Ciano / vermelho"), ("Cylinder", "Cilindro"), @@ -606,6 +608,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Particles", "Partículas"), ("Passthrough", "Passagem"), ("Paste as instance", "Colar como instância"), + ("Paste effect", "Colar efeito"), ("Paste layer(s)", "Colar camada(s)"), ("Path", "Caminho"), ("Path trace on the processor instead of the graphics card (slower)", "Fazer path tracing no processador em vez da placa de vídeo (mais lento)"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index c1499b76..212e1123 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -169,6 +169,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Contrast/Luminosity", "对比度/亮度"), ("Converted maps", "转换贴图"), ("Copy RGB values", "复制 RGB 值"), + ("Copy effect", "复制效果"), ("Copy from", "复制自"), ("Copy layer(s)", "复制图层"), ("Copy the selected layer alone (its empty parts copy nothing)", "仅复制所选图层(其空白部分不复制任何内容)"), @@ -191,6 +192,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Cube", "立方体"), ("Current layer", "当前图层"), ("Curvature", "曲率"), + ("Cut effect", "剪切效果"), ("Cut layer(s)", "剪切图层"), ("Cyan / red", "青色 / 红色"), ("Cylinder", "圆柱体"), @@ -540,6 +542,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Particles", "粒子"), ("Passthrough", "穿透"), ("Paste as instance", "粘贴为实例"), + ("Paste effect", "粘贴效果"), ("Paste layer(s)", "粘贴图层"), ("Path", "路径"), ("Path trace on the processor instead of the graphics card (slower)", "在处理器而非显卡上进行路径追踪(较慢)"), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 3f83a1ad..04c76b0c 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -269,7 +269,19 @@ pub fn forwarded_shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context, event let event = clipboard_key(&event, held).unwrap_or(event); let egui::Event::Key { key, pressed: true, repeat: false, modifiers, .. } = event else { continue }; let Some((id, _)) = active.iter().find(|(_, sc)| sc.logical_key == key && modifiers.matches_logically(sc.modifiers)) else { continue }; - invoke(app, ctx, id); + invoke(app, ctx, clipboard_command(app, id)); + } +} + +/// The layer clipboard shortcuts copy and cut the selected effect instead of its layer, and +/// paste a copied effect onto the selection. +fn clipboard_command<'a>(app: &TextureCraftApp, id: &'a str) -> &'a str { + let effect = matches!(app.session.target, texturecraft_engine::StackTarget::Effect(_)); + match id { + "layer.copy" if effect => "effect.copy", + "layer.cut" if effect => "effect.cut", + "layer.paste" if enabled(app, "effect.paste") => "effect.paste", + _ => id, } } @@ -311,7 +323,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { // Ctrl+V reaches the app only while the system clipboard holds text or an image. ctx.copy_text(layer.name.clone()); } - invoke(app, ctx, id); + invoke(app, ctx, clipboard_command(app, id)); } } diff --git a/crates/ui-egui/tests/layer_clipboard.rs b/crates/ui-egui/tests/layer_clipboard.rs index 3db97ca2..22af038e 100644 --- a/crates/ui-egui/tests/layer_clipboard.rs +++ b/crates/ui-egui/tests/layer_clipboard.rs @@ -43,3 +43,20 @@ fn ctrl_c_then_ctrl_v_pastes_a_copy() { h.run_steps(3); assert!(count(&h) > before, "Ctrl+V pastes the layer"); } + +#[test] +fn ctrl_c_and_ctrl_v_copy_and_paste_a_selected_effect() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let id = |v: serde_json::Value, key: &str| LayerId(v[key].as_u64().unwrap()); + let layer = id(texturecraft_engine::execute(&mut session, "layer.add.fill", &serde_json::Value::Null).unwrap(), "layer"); + let p = serde_json::json!({"target": "content", "filter": "invert"}); + let effect = id(texturecraft_engine::execute(&mut session, "effect.add.filter", &p).unwrap(), "effect"); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + h.event(egui::Event::Copy); + h.run_steps(3); + assert_eq!(h.state().session.clipboard.as_ref().map(|(_, id)| *id), Some(effect), "Ctrl+C copies the selected effect"); + h.event(egui::Event::Paste("Fill".into())); + h.run_steps(3); + assert_eq!(h.state().session.doc.project.layers[&layer].content_effects.len(), 2, "Ctrl+V pastes it above"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b2c9d9b9..64f03908 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -16,7 +16,8 @@ painted tile count, so an agent can verify its work without a screenshot. `effect.histogram {effect, channel?, bins?}` counts the values an effect reads (a levels effect's input), so an agent can pick its input range from the data. `effect.move {effect, index}` reorders an effect within its stack (0 = bottom) and `effect.duplicate {effect}` copies -one just above itself. +one just above itself. `effect.copy {effect?}` and `effect.cut {effect?}` put an effect on the +layer clipboard, and `effect.paste {layer?, target?}` adds it to another layer's content or mask. ## Control channel (desktop app) diff --git a/docs/features.md b/docs/features.md index adca8f55..bace7359 100644 --- a/docs/features.md +++ b/docs/features.md @@ -43,7 +43,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA **mesh-map generators** (edge wear, dirt, thin areas, curvature, AO, position and direction gradients, all with world-space noise), filters, ID color selection and compare. Alt+click a mask to view it alone. Drag an effect to reorder its stack, or right-click it to duplicate it - (painted strokes included). + (painted strokes included) or copy it onto another layer or mask (Ctrl+C, Ctrl+V). - **Fill layers** take uniform values, **23 procedurals** (clouds, cells, grunge, scratches, wood grain, bricks, fabric weave, twill, leather grain, marble veins, Voronoi, paint chips…) or your own **images**, through UV, tri-planar, planar, spherical, cylindrical or decal projection. From fbceb95242734b50b90cc326a5667b69f3c6d1e4 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 12:19:21 +0700 Subject: [PATCH 60/60] Effects: Delete and Ctrl+D act on a selected effect With an effect selected, Delete removed its whole layer and Ctrl+D duplicated the layer. Both now act on the effect, like the clipboard shortcuts; effect commands default to the selected effect. --- crates/engine/src/effect_clipboard.rs | 10 +++----- crates/engine/src/mask_cmds.rs | 31 ++++++++++++++++++------- crates/ui-egui/src/menus.rs | 12 ++++++---- crates/ui-egui/tests/layer_clipboard.rs | 11 +++++++-- docs/features.md | 3 ++- 5 files changed, 43 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/effect_clipboard.rs b/crates/engine/src/effect_clipboard.rs index 748ecd7f..8132c9ca 100644 --- a/crates/engine/src/effect_clipboard.rs +++ b/crates/engine/src/effect_clipboard.rs @@ -4,9 +4,9 @@ use serde_json::{Value, json}; use texturecraft_core::{EffectKind, LayerId, Mask, MaskBackground, Source}; -use crate::commands::{CommandSpec, bad, has_layer, layer_param, strp, u64p}; +use crate::commands::{CommandSpec, bad, has_layer, layer_param, strp}; use crate::layer_ops::{empty_texel, fit}; -use crate::mask_cmds::{anchor_source, content_target}; +use crate::mask_cmds::{anchor_source, content_target, effect_id}; use crate::session::StackTarget; use crate::{EngineError, Result, Session, cmd}; @@ -41,11 +41,7 @@ fn can_paste(s: &Session) -> std::result::Result<(), String> { fn copy(s: &mut Session, p: &Value) -> Result { const CMD: &str = "effect.copy"; - let eid = match (u64p(p, "effect"), s.target) { - (Some(e), _) => LayerId(e), - (None, StackTarget::Effect(e)) => e, - (None, _) => return Err(bad(CMD, "`effect` is required (no effect is selected)")), - }; + let eid = effect_id(s, p, CMD)?; if s.doc.project.effect(eid).is_none() { return Err(bad(CMD, format!("no effect {}", eid.0))); } diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 5d7ecd2f..784755c2 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -98,8 +98,16 @@ pub fn specs() -> Vec { has_layer, set ), - cmd!("effect.remove", "Remove effect", [], None, "{effect}", has_layer, remove_effect), - cmd!("effect.duplicate", "Duplicate effect", [], None, "{effect} → {effect} (the copy, just above it, pixels included)", has_layer, duplicate_effect), + cmd!("effect.remove", "Remove effect", [], None, "{effect?: the selected effect}", has_layer, remove_effect), + cmd!( + "effect.duplicate", + "Duplicate effect", + [], + None, + "{effect?: the selected effect} → {effect} (the copy, just above it, pixels included)", + has_layer, + duplicate_effect + ), cmd!("effect.move", "Move effect", [], None, "{effect, index: position in its stack, 0 = bottom (applied first)}", has_layer, move_effect), cmd!( "effect.histogram", @@ -380,14 +388,19 @@ fn add_compare(s: &mut Session, p: &Value) -> Result { push_effect(s, p, kind, BlendMode::Normal) } -fn effect_id(p: &Value, cmd: &str) -> Result { - u64p(p, "effect").map(LayerId).ok_or_else(|| bad(cmd, "`effect` id is required")) +/// The `effect` param, or the selected effect. +pub(crate) fn effect_id(s: &Session, p: &Value, cmd: &str) -> Result { + match (u64p(p, "effect"), s.target) { + (Some(e), _) => Ok(LayerId(e)), + (None, StackTarget::Effect(e)) => Ok(e), + (None, _) => Err(bad(cmd, "`effect` is required (no effect is selected)")), + } } /// The distribution of the values entering an effect (what a levels effect remaps). fn histogram(s: &mut Session, p: &Value) -> Result { const CMD: &str = "effect.histogram"; - let eid = effect_id(p, CMD)?; + let eid = effect_id(s, p, CMD)?; let (owner, _) = s.doc.project.effect(eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?; let l = s.doc.project.layer(owner)?; let content = l.content_effects.iter().any(|e| e.id == eid); @@ -401,7 +414,7 @@ fn histogram(s: &mut Session, p: &Value) -> Result { } fn set(s: &mut Session, p: &Value) -> Result { - let eid = effect_id(p, "effect.set")?; + let eid = effect_id(s, p, "effect.set")?; let blend = blend_param("effect.set", p, "blend")?; // A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone // re-targets the current one. @@ -470,7 +483,7 @@ fn stack_of(project: &mut Project, eid: LayerId) -> Option<(&mut Vec, us fn duplicate_effect(s: &mut Session, p: &Value) -> Result { const CMD: &str = "effect.duplicate"; - let eid = effect_id(p, CMD)?; + let eid = effect_id(s, p, CMD)?; let new = s.edit("Duplicate effect", |s| { let new = s.doc.project.alloc_id(); let (list, i) = stack_of(&mut s.doc.project, eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?; @@ -498,7 +511,7 @@ fn duplicate_effect(s: &mut Session, p: &Value) -> Result { fn move_effect(s: &mut Session, p: &Value) -> Result { const CMD: &str = "effect.move"; - let eid = effect_id(p, CMD)?; + let eid = effect_id(s, p, CMD)?; let index = u64p(p, "index").ok_or_else(|| bad(CMD, "`index` is required"))?; s.edit("Move effect", |s| { let (list, i) = stack_of(&mut s.doc.project, eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?; @@ -511,7 +524,7 @@ fn move_effect(s: &mut Session, p: &Value) -> Result { } fn remove_effect(s: &mut Session, p: &Value) -> Result { - let eid = effect_id(p, "effect.remove")?; + let eid = effect_id(s, p, "effect.remove")?; s.edit("Remove effect", |s| { let content = match s.doc.project.effect(eid) { Some((owner, _)) => s.doc.project.layer(owner)?.content_effects.iter().any(|e| e.id == eid), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 04c76b0c..015566e8 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -269,17 +269,19 @@ pub fn forwarded_shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context, event let event = clipboard_key(&event, held).unwrap_or(event); let egui::Event::Key { key, pressed: true, repeat: false, modifiers, .. } = event else { continue }; let Some((id, _)) = active.iter().find(|(_, sc)| sc.logical_key == key && modifiers.matches_logically(sc.modifiers)) else { continue }; - invoke(app, ctx, clipboard_command(app, id)); + invoke(app, ctx, effect_command(app, id)); } } -/// The layer clipboard shortcuts copy and cut the selected effect instead of its layer, and -/// paste a copied effect onto the selection. -fn clipboard_command<'a>(app: &TextureCraftApp, id: &'a str) -> &'a str { +/// Layer shortcuts act on the selected effect instead of its layer (copy, cut, duplicate, +/// remove), and paste a copied effect onto the selection. +fn effect_command<'a>(app: &TextureCraftApp, id: &'a str) -> &'a str { let effect = matches!(app.session.target, texturecraft_engine::StackTarget::Effect(_)); match id { "layer.copy" if effect => "effect.copy", "layer.cut" if effect => "effect.cut", + "layer.duplicate" if effect => "effect.duplicate", + "layer.remove" if effect => "effect.remove", "layer.paste" if enabled(app, "effect.paste") => "effect.paste", _ => id, } @@ -323,7 +325,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { // Ctrl+V reaches the app only while the system clipboard holds text or an image. ctx.copy_text(layer.name.clone()); } - invoke(app, ctx, clipboard_command(app, id)); + invoke(app, ctx, effect_command(app, id)); } } diff --git a/crates/ui-egui/tests/layer_clipboard.rs b/crates/ui-egui/tests/layer_clipboard.rs index 22af038e..36c20ff9 100644 --- a/crates/ui-egui/tests/layer_clipboard.rs +++ b/crates/ui-egui/tests/layer_clipboard.rs @@ -45,7 +45,7 @@ fn ctrl_c_then_ctrl_v_pastes_a_copy() { } #[test] -fn ctrl_c_and_ctrl_v_copy_and_paste_a_selected_effect() { +fn layer_shortcuts_act_on_a_selected_effect() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let id = |v: serde_json::Value, key: &str| LayerId(v[key].as_u64().unwrap()); let layer = id(texturecraft_engine::execute(&mut session, "layer.add.fill", &serde_json::Value::Null).unwrap(), "layer"); @@ -53,10 +53,17 @@ fn ctrl_c_and_ctrl_v_copy_and_paste_a_selected_effect() { let effect = id(texturecraft_engine::execute(&mut session, "effect.add.filter", &p).unwrap(), "effect"); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); + let effects = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers.get(&layer).map(|l| l.content_effects.len()); h.event(egui::Event::Copy); h.run_steps(3); assert_eq!(h.state().session.clipboard.as_ref().map(|(_, id)| *id), Some(effect), "Ctrl+C copies the selected effect"); h.event(egui::Event::Paste("Fill".into())); h.run_steps(3); - assert_eq!(h.state().session.doc.project.layers[&layer].content_effects.len(), 2, "Ctrl+V pastes it above"); + assert_eq!(effects(&h), Some(2), "Ctrl+V pastes it above"); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::D); + h.run_steps(3); + assert_eq!(effects(&h), Some(3), "Ctrl+D duplicates the effect"); + h.key_press(egui::Key::Delete); + h.run_steps(3); + assert_eq!(effects(&h), Some(2), "Delete removes the effect, not its layer"); } diff --git a/docs/features.md b/docs/features.md index bace7359..f6afa05c 100644 --- a/docs/features.md +++ b/docs/features.md @@ -43,7 +43,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA **mesh-map generators** (edge wear, dirt, thin areas, curvature, AO, position and direction gradients, all with world-space noise), filters, ID color selection and compare. Alt+click a mask to view it alone. Drag an effect to reorder its stack, or right-click it to duplicate it - (painted strokes included) or copy it onto another layer or mask (Ctrl+C, Ctrl+V). + (painted strokes included) or copy it onto another layer or mask (Ctrl+C, Ctrl+V); with an + effect selected, Ctrl+D and Delete duplicate or remove it. - **Fill layers** take uniform values, **23 procedurals** (clouds, cells, grunge, scratches, wood grain, bricks, fabric weave, twill, leather grain, marble veins, Voronoi, paint chips…) or your own **images**, through UV, tri-planar, planar, spherical, cylindrical or decal projection.