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/46] 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/46] 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/46] 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/46] 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/46] 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 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 06/46] 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 aef225f3a6d59c7f63e2c7b12711d18c5ed2cd69 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:14:41 -0500 Subject: [PATCH 07/46] feat(bake): Auto-rebake keeps one mesh map up to date A map chosen with `bake.autoRebake {map}` (or the new Auto-rebake checkbox in the bake mode's per-map panel) bakes itself again, alone, whenever what it was baked from changes: the texture set's bake settings (except which maps are ticked), the low poly, the high polys or the cage. The apps poll `Session::auto_rebake_due` each frame and bake the due sets in the background; `bake.autoRebake.run` does the same once, blocking, for agents and scripts. A set only takes part once it has the map baked at its current output size, so Auto-rebake keeps a bake current without starting one or leaving a set's maps at two sizes. A manual bake of the map also marks the set up to date, and a change made while a bake runs triggers another. The choice isn't saved in the project. The other maps of the set are left as they were. Strings translated in all nine languages (native-speaker review welcome, as for the rest). Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 2 +- crates/engine/src/auto_rebake.rs | 168 +++++++++++++++++++++++++++++ crates/engine/src/bake_cmds.rs | 6 +- crates/engine/src/commands.rs | 1 + crates/engine/src/lib.rs | 1 + crates/engine/src/session.rs | 3 + crates/engine/tests/auto_rebake.rs | 92 ++++++++++++++++ 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 | 2 + crates/ui-egui/src/lib.rs | 23 +++- crates/ui-egui/src/windows.rs | 12 ++- 17 files changed, 339 insertions(+), 6 deletions(-) create mode 100644 crates/engine/src/auto_rebake.rs create mode 100644 crates/engine/tests/auto_rebake.rs diff --git a/ROADMAP.md b/ROADMAP.md index 007c96bd..9b9e1a17 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -16,7 +16,7 @@ end to end today (engine + UI + automation + tests), not what is planned. | 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 | -| 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 | — | +| 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; **Auto-rebake** (`bake.autoRebake`: one map bakes itself again in the background when its bake settings, the low poly or the high polys change); 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) | diff --git a/crates/engine/src/auto_rebake.rs b/crates/engine/src/auto_rebake.rs new file mode 100644 index 00000000..039a3878 --- /dev/null +++ b/crates/engine/src/auto_rebake.rs @@ -0,0 +1,168 @@ +//! Auto-rebake: one mesh map that bakes itself again when what it was baked from changes. +//! +//! The map is chosen with `bake.autoRebake`. From then on, [`Session::auto_rebake_due`] names the +//! texture sets whose bake inputs (the set's bake settings except the list of maps, the low poly, +//! the high polys and the cage) differ from those of their last bake of that map. +//! The apps poll it each frame and bake the due sets in the background; `bake.autoRebake.run` +//! does the same thing once, blocking, for agents and scripts. +//! +//! A set only takes part once it has the map baked at its current output size: Auto-rebake +//! keeps a bake up to date, it doesn't start one, and it never leaves a set's maps at two sizes. +//! The choice isn't part of the project. + +use std::collections::BTreeMap; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +use serde_json::{Value, json}; +use texturecraft_bake::Progress; +use texturecraft_core::BakedMap; + +use crate::bake_cmds::BakeTask; +use crate::commands::{CommandSpec, always, bad, boolp, strp}; +use crate::{Result, Session, cmd}; + +/// Which map rebakes itself, and what each texture set was last baked from. +#[derive(Clone, Debug, Default)] +pub struct AutoRebake { + pub map: Option, + /// Fingerprint of each set's bake inputs when it last baked [`AutoRebake::map`]. + seen: BTreeMap, + /// Fingerprint taken when a set's bake started, kept when that bake finishes. + pending: BTreeMap, +} + +pub fn specs() -> Vec { + vec![ + cmd!( + "bake.autoRebake", + "Auto-rebake", + [], + None, + "{map?: map id (e.g. \"normal_base\", \"height\") to keep up to date, or null / off: true to turn it off; no params: just report} → {map, due: [texture sets that need a rebake]}", + always, + auto_rebake + ), + cmd!( + "bake.autoRebake.run", + "Run Auto-rebake", + [], + None, + "{cpu?: true (skip the GPU)} → {rebaked: [texture sets]}: bakes the Auto-rebake map of every set whose bake inputs changed since it was last baked, now", + always, + auto_rebake_run + ), + ] +} + +impl Session { + /// A fingerprint of everything a bake of texture set `ts` is made from, except which maps it + /// makes. + pub fn bake_inputs_key(&self, ts: usize) -> Option { + let set = self.doc.project.texture_sets.get(ts)?; + let mut settings = set.bake.clone(); + settings.maps.clear(); + settings.enabled = true; + let mut h = DefaultHasher::new(); + serde_json::to_string(&settings).ok()?.hash(&mut h); + (Arc::as_ptr(&self.mesh) as usize).hash(&mut h); + for m in &self.bake_meshes.high { + (Arc::as_ptr(&m.mesh) as usize).hash(&mut h); + } + self.bake_meshes.cage.as_ref().map(|c| Arc::as_ptr(&c.mesh) as usize).hash(&mut h); + Some(h.finish()) + } + + /// Texture sets whose Auto-rebake map is out of date. A set seen for the first time (a project + /// just opened, a bake from before Auto-rebake was on) is taken as up to date. + pub fn auto_rebake_due(&mut self) -> Vec { + let Some(map) = self.auto_rebake.map else { return Vec::new() }; + let mut due = Vec::new(); + for ts in 0..self.doc.project.texture_sets.len() { + let Some(set) = self.doc.project.texture_sets.get(ts).filter(|t| t.bake.enabled) else { continue }; + let columns = set.tile_grid().map_or(1, |g| g.cols); + let baked = self.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map) && b.resolution == set.bake.resolution.saturating_mul(columns)); + let Some(key) = self.bake_inputs_key(ts).filter(|_| baked) else { continue }; + match self.auto_rebake.seen.get(&ts) { + None => { + self.auto_rebake.seen.insert(ts, key); + } + Some(seen) if *seen != key => due.push(ts), + Some(_) => {} + } + } + due + } + + /// Call right before building the bake task of `ts`: remembers what it is baked from, so a + /// finished bake of the Auto-rebake map marks the set up to date (and a change made while it + /// ran still triggers another). + pub fn begin_bake(&mut self, ts: usize) { + if let Some(key) = self.bake_inputs_key(ts) { + self.auto_rebake.pending.insert(ts, key); + } + } + + /// The bake task of `ts` restricted to one map (Auto-rebake's: the other maps stay as they are). + pub fn bake_task_for(&self, ts: usize, only: Option) -> Result { + let mut task = self.bake_task(ts)?; + if let Some(m) = only { + task.settings.maps = std::iter::once(m).collect(); + } + Ok(task) + } + + /// Records a finished bake: when it made the Auto-rebake map, the set is up to date. + pub(crate) fn note_baked(&mut self, ts: usize, made: impl Iterator) { + let key = self.auto_rebake.pending.remove(&ts); + if let (Some(key), Some(map)) = (key, self.auto_rebake.map) + && made.into_iter().any(|m| m == map) + { + self.auto_rebake.seen.insert(ts, key); + } + } + + /// Bakes every due set's Auto-rebake map now (blocking); returns the sets. + pub fn auto_rebake_now(&mut self, cpu: bool) -> Result> { + let due = self.auto_rebake_due(); + let map = self.auto_rebake.map; + for &ts in &due { + self.begin_bake(ts); + let mut task = self.bake_task_for(ts, map)?; + if cpu { + task.tracer = None; + } + let out = task.run(&Progress::new())?; + self.apply_bake(ts, out)?; + } + Ok(due) + } +} + +fn state(s: &mut Session) -> Value { + json!({ "map": s.auto_rebake.map.map(BakedMap::id), "due": s.auto_rebake_due() }) +} + +fn auto_rebake(s: &mut Session, p: &Value) -> Result { + if boolp(p, "off") == Some(true) || p.get("map").is_some_and(Value::is_null) { + s.auto_rebake = AutoRebake::default(); + } else if let Some(id) = p.get("map") { + let map = id.as_str().and_then(BakedMap::parse).ok_or_else(|| bad("bake.autoRebake", format!("unknown mesh map {id}")))?; + if s.auto_rebake.map != Some(map) { + s.auto_rebake = AutoRebake { map: Some(map), ..AutoRebake::default() }; + } + } else if strp(p, "map").is_some() { + return Err(bad("bake.autoRebake", "`map` must be a map id or null")); + } + Ok(state(s)) +} + +fn auto_rebake_run(s: &mut Session, p: &Value) -> Result { + if s.auto_rebake.map.is_none() { + return Err(bad("bake.autoRebake.run", "no Auto-rebake map is set; run bake.autoRebake {map} first")); + } + let rebaked = s.auto_rebake_now(boolp(p, "cpu") == Some(true))?; + s.update(); + Ok(json!({ "rebaked": rebaked })) +} diff --git a/crates/engine/src/bake_cmds.rs b/crates/engine/src/bake_cmds.rs index d6387636..57cdbc25 100644 --- a/crates/engine/src/bake_cmds.rs +++ b/crates/engine/src/bake_cmds.rs @@ -177,6 +177,7 @@ impl Session { /// Store a finished bake (one undo step). pub fn apply_bake(&mut self, ts: usize, out: BakeOutput) -> Result<()> { self.log.push(format!("Baked texture set {ts} ({})", out.tracer)); + let made: Vec = out.maps.keys().copied().collect(); self.edit("Bake mesh maps", |s| { let maps: BTreeSet = out.maps.keys().copied().collect(); let entry = s.doc.baked.entry(ts).or_default(); @@ -186,11 +187,14 @@ impl Session { } s.doc.project.texture_set_mut(ts)?.baked.extend(maps); Ok(()) - }) + })?; + self.note_baked(ts, made.into_iter()); + Ok(()) } /// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran. pub fn bake_now(&mut self, ts: usize, cpu: bool) -> Result { + self.begin_bake(ts); let mut task = self.bake_task(ts)?; if cpu { task.tracer = None; diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 1d6b0cb8..cc946813 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -66,6 +66,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); v.extend(crate::bake_cmds::specs()); + v.extend(crate::auto_rebake::specs()); v.extend(crate::file_cmds::specs()); v.extend(crate::preset_cmds::specs()); v.extend(crate::resource_cmds::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2afa239..26e18949 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -8,6 +8,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod auto_rebake; pub mod bake_cmds; pub mod camera_cmds; pub mod commands; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index fa239848..2ef66011 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -320,6 +320,8 @@ pub struct Session { pub mesh_source: Option<(String, Vec)>, /// High-definition meshes and cage for baking (saved inside the project). pub bake_meshes: crate::BakeMeshes, + /// The map that bakes itself again when its inputs change (not saved). + pub auto_rebake: crate::auto_rebake::AutoRebake, pub caches: Vec, pub(crate) undo: Vec<(String, Document)>, pub(crate) redo: Vec<(String, Document)>, @@ -375,6 +377,7 @@ impl Session { bvh: Arc::new(bvh), mesh_source, bake_meshes: Default::default(), + auto_rebake: Default::default(), caches, undo: Vec::new(), redo: Vec::new(), diff --git a/crates/engine/tests/auto_rebake.rs b/crates/engine/tests/auto_rebake.rs new file mode 100644 index 00000000..c4fe8644 --- /dev/null +++ b/crates/engine/tests/auto_rebake.rs @@ -0,0 +1,92 @@ +//! Auto-rebake: one mesh map bakes itself again when its bake inputs change. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// A plane with a high poly just above it, baked once with height and opacity. +fn baked_session() -> (Session, std::path::PathBuf) { + let mesh = primitives::builtin("plane").unwrap(); + let mut obj = String::from("o Part_high\n"); + for p in &mesh.positions { + obj += &format!("v {} {} {}\n", p.x, p.y + 0.002, p.z); + } + for t in mesh.indices.chunks_exact(3) { + obj += &format!("f {} {} {}\n", t[0] + 1, t[1] + 1, t[2] + 1); + } + let dir = std::env::temp_dir().join(format!("tc_auto_rebake_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("hp.obj"); + std::fs::write(&path, obj).unwrap(); + let mut s = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap(); + execute(&mut s, "bake.highPoly.add", &json!({ "path": path.display().to_string() })).unwrap(); + execute(&mut s, "bake.settings", &json!({ "resolution": 128, "dilation": 0, "maps": ["height", "opacity"] })).unwrap(); + execute(&mut s, "bake.run", &json!({ "cpu": true })).unwrap(); + (s, dir) +} + +fn due(s: &mut Session) -> Vec { + execute(s, "bake.autoRebake", &Value::Null).unwrap()["due"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect() +} + +fn image(s: &Session, map: BakedMap) -> Arc> { + s.doc.baked[&0].maps[&map].clone() +} + +#[test] +fn a_changed_bake_input_rebakes_only_the_chosen_map() { + let (mut s, dir) = baked_session(); + // Off by default; nothing is due and the run command says what to do first. + assert_eq!(execute(&mut s, "bake.autoRebake", &Value::Null).unwrap()["map"], Value::Null); + assert!(execute(&mut s, "bake.autoRebake.run", &Value::Null).is_err()); + let r = execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap(); + assert_eq!(r["map"], "height"); + assert!(due(&mut s).is_empty(), "turning it on takes the current bake as up to date"); + + // Which maps are ticked is not a bake input; a setting is. + execute(&mut s, "bake.settings", &json!({ "maps": ["height", "opacity", "ambient_occlusion"] })).unwrap(); + assert!(due(&mut s).is_empty()); + execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.2, "maps": ["height", "opacity"] })).unwrap(); + assert_eq!(due(&mut s), [0]); + + let (height, opacity) = (image(&s, BakedMap::Height), image(&s, BakedMap::Opacity)); + let r = execute(&mut s, "bake.autoRebake.run", &json!({ "cpu": true })).unwrap(); + assert_eq!(r["rebaked"], json!([0])); + assert!(!Arc::ptr_eq(&height, &image(&s, BakedMap::Height)), "the Auto-rebake map was baked again"); + assert!(Arc::ptr_eq(&opacity, &image(&s, BakedMap::Opacity)), "the other maps were left alone"); + assert!(due(&mut s).is_empty(), "and the set is up to date"); + assert_eq!(execute(&mut s, "bake.autoRebake.run", &Value::Null).unwrap()["rebaked"], json!([])); + + // A manual bake of the map also counts; a changed high poly list is a change again. + execute(&mut s, "bake.settings", &json!({ "antialiasing": 2 })).unwrap(); + assert_eq!(due(&mut s), [0]); + s.begin_bake(0); + let out = s.bake_task_for(0, None).unwrap().run(&texturecraft_engine::bake::Progress::new()).unwrap(); + s.apply_bake(0, out).unwrap(); + assert!(due(&mut s).is_empty(), "a manual bake of the map marks it up to date"); + execute(&mut s, "bake.highPoly.remove", &json!({ "all": true })).unwrap(); + assert_eq!(due(&mut s), [0]); + + // A different output size is left to a manual bake: the maps would end up at two sizes. + execute(&mut s, "bake.settings", &json!({ "resolution": 256 })).unwrap(); + assert!(due(&mut s).is_empty()); + + // Hostile input, and turning it off. + for bad in [json!({ "map": "nonsense" }), json!({ "map": 3 })] { + assert!(execute(&mut s, "bake.autoRebake", &bad).is_err(), "{bad}"); + } + assert_eq!(execute(&mut s, "bake.autoRebake", &json!({ "map": null })).unwrap()["map"], Value::Null); + assert!(due(&mut s).is_empty()); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_set_without_the_map_baked_is_left_alone() { + let mut s = Session::new_project("t", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); + execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap(); + execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.3 })).unwrap(); + assert!(due(&mut s).is_empty(), "Auto-rebake keeps a bake up to date, it doesn't start one"); +} diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ce534a6f..728fab62 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -689,6 +689,11 @@ 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"), + ("Auto-rebake", "Automatisch neu backen"), + ( + "Bake this map again by itself when its bake settings, the low poly or the high polys change", + "Diese Map automatisch neu backen, wenn sich ihre Bake-Einstellungen, das Low-Poly- oder die High-Poly-Meshes ändern", + ), ("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 2b57afd8..22d221f4 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -680,6 +680,11 @@ 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"), + ("Auto-rebake", "Rehornear automáticamente"), + ( + "Bake this map again by itself when its bake settings, the low poly or the high polys change", + "Vuelve a hornear este mapa automáticamente cuando cambian sus ajustes de horneado, la malla low poly o las high poly", + ), ("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 0e72b031..f1ef103a 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -689,6 +689,11 @@ 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"), + ("Auto-rebake", "Précalcul automatique"), + ( + "Bake this map again by itself when its bake settings, the low poly or the high polys change", + "Précalcule à nouveau cette carte automatiquement quand ses réglages de précalcul, le maillage low poly ou les maillages high poly changent", + ), ("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 9260b188..dd5f04b4 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -689,6 +689,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "Ridimensionamento"), ("Restore every default shortcut", "Ripristina tutte le scorciatoie predefinite"), ("Return to painting mode", "Torna alla modalità pittura"), + ("Auto-rebake", "Bake automatico"), + ( + "Bake this map again by itself when its bake settings, the low poly or the high polys change", + "Esegue di nuovo il bake di questa mappa quando cambiano le sue impostazioni di bake, la mesh low poly o le mesh high poly", + ), ("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 2e333ab9..f670e670 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -668,6 +668,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "サイズ変更中"), ("Restore every default shortcut", "すべてのショートカットをデフォルトに戻す"), ("Return to painting mode", "ペイントモードに戻る"), + ("Auto-rebake", "自動再ベイク"), + ( + "Bake this map again by itself when its bake settings, the low poly or the high polys change", + "ベイク設定、ローポリ、またはハイポリが変わると、このマップを自動的にベイクし直します", + ), ("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 3945c9a9..e18daf69 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -659,6 +659,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "크기 조정 중"), ("Restore every default shortcut", "모든 기본 단축키를 복원합니다"), ("Return to painting mode", "페인팅 모드로 돌아가기"), + ("Auto-rebake", "자동 다시 베이크"), + ( + "Bake this map again by itself when its bake settings, the low poly or the high polys change", + "베이크 설정, 로우 폴리 또는 하이 폴리가 바뀌면 이 맵을 자동으로 다시 베이크합니다", + ), ("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 788df7f9..ffa080e8 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -677,6 +677,11 @@ 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"), + ("Auto-rebake", "Refazer bake automaticamente"), + ( + "Bake this map again by itself when its bake settings, the low poly or the high polys change", + "Refaz o bake deste mapa automaticamente quando as configurações de bake, a malha low poly ou as high poly mudam", + ), ("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 3de5246c..e6c1b6b4 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -608,6 +608,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "正在调整大小"), ("Restore every default shortcut", "恢复所有默认快捷键"), ("Return to painting mode", "返回绘画模式"), + ("Auto-rebake", "自动重新烘焙"), + ("Bake this map again by itself when its bake settings, the low poly or the high polys change", "当烘焙设置、低模或高模发生变化时,自动重新烘焙此贴图"), ("Right-click a layer > Create smart material", "右键单击图层 > 创建智能材质"), ("Rotation", "旋转"), ("Rotation (degrees)", "旋转(度)"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bd53bd98..e7261b22 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -51,6 +51,8 @@ pub struct BakeJob { pub queue: Vec, pub current: Option<(usize, Arc, std::sync::mpsc::Receiver>)>, pub total: usize, + /// Bake only this map (an Auto-rebake); None bakes every ticked map. + pub only: Option, } /// The browser build's notice when WebGPU is unavailable and wgpu fell back to WebGL2. @@ -176,7 +178,7 @@ impl TextureCraftApp { return; } let total = sets.len(); - self.bake = Some(BakeJob { queue: sets, current: None, total }); + self.bake = Some(BakeJob { queue: sets, current: None, total, only: None }); } fn poll_bake(&mut self, ctx: &egui::Context) { @@ -213,8 +215,9 @@ impl TextureCraftApp { self.toast(i18n::tr("Mesh maps baked"), false); return; } - let ts = job.queue.remove(0); - match self.session.bake_task(ts) { + let (ts, only) = (job.queue.remove(0), job.only); + self.session.begin_bake(ts); + match self.session.bake_task_for(ts, only) { Ok(task) => { let progress = Arc::new(Progress::new()); let p = progress.clone(); @@ -228,6 +231,19 @@ impl TextureCraftApp { } } + /// Auto-rebake: when the chosen map's bake inputs changed, bake it again in the background + /// (one set after another, only that map), unless a bake or a stroke is running. + fn drive_auto_rebake(&mut self) { + if self.bake.is_some() || self.session.stroke_active() || self.session.auto_rebake.map.is_none() { + return; + } + let due = self.session.auto_rebake_due(); + if !due.is_empty() { + let total = due.len(); + self.bake = Some(BakeJob { queue: due, current: None, total, only: self.session.auto_rebake.map }); + } + } + pub fn cancel_bake(&mut self) { if let Some(job) = self.bake.take() && let Some((_, p, _)) = job.current @@ -369,6 +385,7 @@ impl eframe::App for TextureCraftApp { web_files::dropped(self, ctx, f); } self.poll_bake(ctx); + self.drive_auto_rebake(); self.poll_resize(ctx); let scale = self.ui.prefs.ui_scale.clamp(0.5, 3.0); if (ctx.zoom_factor() - scale).abs() > 1e-3 { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 2ecafdd6..13bc3dc4 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -578,7 +578,17 @@ fn bake_panel(app: &mut TextureCraftApp, ui: &mut Ui) { ui.separator(); match selected { None => common_params(app, ui, &mut b), - Some(m) => map_params(ui, m, &mut b), + Some(m) => { + let mut auto = app.session.auto_rebake.map == Some(m); + if ui + .checkbox(&mut auto, tr("Auto-rebake")) + .on_hover_text(tr("Bake this map again by itself when its bake settings, the low poly or the high polys change")) + .changed() + { + app.run("bake.autoRebake", if auto { json!({ "map": m.id() }) } else { json!({ "off": true }) }); + } + map_params(ui, m, &mut b) + } } if b.direction == [0.0; 3] { b.direction = before.direction; From 5e21cb47c52f2b8605df4c5649598968930bd752 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:19:17 -0500 Subject: [PATCH 08/46] i18n: Arabic strings for Auto-rebake Arabic landed after this branch was cut, and the translation test requires every string in every language. Co-Authored-By: Claude Sonnet 5.5 --- 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..79b889b4 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -650,6 +650,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "تغيير الحجم"), ("Restore every default shortcut", "استعادة كل الاختصارات الافتراضية"), ("Return to painting mode", "العودة إلى نمط الرسم"), + ("Auto-rebake", "إعادة الخبز تلقائيًا"), + ( + "Bake this map again by itself when its bake settings, the low poly or the high polys change", + "يعيد خبز هذه الخريطة تلقائيًا عند تغيّر إعدادات الخبز أو المجسّم منخفض الدقة أو المجسّمات عالية الدقة", + ), ("Right-click a layer > Create smart material", "انقر بزر الفأرة الأيمن على طبقة > إنشاء مادة ذكية"), ("Rotation", "التدوير"), ("Rotation (degrees)", "التدوير (بالدرجات)"), 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 09/46] 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 10/46] 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 ffd311f5167dd5df48e54c03a825f3d143b7ad05 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:50:09 -0500 Subject: [PATCH 11/46] feat(import): MaterialX (.mtlx) material import as a fill layer file.importMaterialX {path, material?, name?} reads an open_pbr_surface, standard_surface or gltf_pbr material and adds one fill layer: image inputs (directly, through a nodegraph output or normalmap/convert/constant nodes, with fileprefix and the first UDIM tile) become image resources and sources, literal values become uniform sources (sRGB-tagged colours converted to linear, colours on scalar channels averaged), the displacement shader becomes height, and the first image's uvtiling becomes the UV projection scale. Emission follows the specifications' defaults (off unless emission_luminance / emission is above 0). Images are read only from the document's folder and below: a document is untrusted. Channels the texture set lacks, unreadable images and unsupported nodes are reported in `warnings`; nothing to import is an error. The whole import is one undo step. Written from the ASWF MaterialX 1.39 and OpenPBR Surface specifications; the reader caps size, depth and element count and has mutation tests. The inverse of the MaterialX export in #50. Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 2 +- crates/engine/src/commands.rs | 1 + crates/engine/src/lib.rs | 1 + crates/engine/src/materialx_cmds.rs | 148 +++++++ crates/engine/src/resource_cmds.rs | 2 +- crates/engine/tests/materialx_import.rs | 124 ++++++ crates/formats/src/lib.rs | 1 + crates/formats/src/materialx_read.rs | 542 ++++++++++++++++++++++++ 8 files changed, 819 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/materialx_cmds.rs create mode 100644 crates/engine/tests/materialx_import.rs create mode 100644 crates/formats/src/materialx_read.rs diff --git a/ROADMAP.md b/ROADMAP.md index 8563db44..9e5116a5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -11,7 +11,7 @@ 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, recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, **MaterialX import** (`file.importMaterialX`: a `.mtlx` material with `open_pbr_surface`, `standard_surface` or `gltf_pbr` becomes one fill layer with its textures and values), 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) | diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index b8938a19..dbd5c868 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -66,6 +66,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); v.extend(crate::bake_cmds::specs()); + v.extend(crate::materialx_cmds::specs()); v.extend(crate::file_cmds::specs()); v.extend(crate::preset_cmds::specs()); v.extend(crate::resource_cmds::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2f2e6920..352d8002 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -21,6 +21,7 @@ pub mod layer_ops; pub mod mask_cmds; pub mod material_lib; pub mod materials; +pub mod materialx_cmds; pub mod painting; pub mod path_tool; // Mesh reimport reads files: native only. diff --git a/crates/engine/src/materialx_cmds.rs b/crates/engine/src/materialx_cmds.rs new file mode 100644 index 00000000..8a212dd7 --- /dev/null +++ b/crates/engine/src/materialx_cmds.rs @@ -0,0 +1,148 @@ +//! `file.importMaterialX`: a MaterialX (`.mtlx`) material becomes one fill layer. +//! +//! The document is read by [`texturecraft_formats::materialx_read`]; here its image files are +//! loaded (only from the document's own folder and below: a document is untrusted, and its +//! `file` values must not reach other files), added to the project as resources and set as the +//! fill's sources, with constants as uniform sources. The whole import is one undo step. Channels +//! the texture set doesn't have, images that can't be read and anything the reader skipped are +//! reported in `warnings`; the import goes ahead with the rest. + +use std::collections::BTreeMap; +use std::sync::Arc; + +use serde_json::{Value, json}; +use texturecraft_core::{Channel, Fill, Layer, LayerKind, Projection, Source}; +use texturecraft_formats::materialx_read::{Material, Value as Mtlx}; + +use crate::commands::{CommandSpec, always, bad, strp}; +use crate::{EngineError, Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![cmd!( + "file.importMaterialX", + "Import MaterialX material...", + ["File"], + None, + "{path: a .mtlx file, material?: the surfacematerial to read (default: the first), name?: layer name} → {layer, material, channels, resources, warnings}: one fill layer with the material's textures (read from the file's folder) and values; open_pbr_surface, standard_surface and gltf_pbr are read", + always, + import + )] +} + +/// Loads an image file named in the document (relative to it): its bytes, or why not. +pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result, String>; + +impl Session { + /// Add `material` as a fill layer on the active texture set, loading its images with `load`. + /// Returns the reply of `file.importMaterialX`. + pub fn import_material(&mut self, material: Material, name: Option<&str>, load: Loader) -> Result { + let mut warnings = material.warnings.clone(); + let ts = self.ts(); + let available = self.doc.project.texture_set(ts).map(|t| t.channel_list()).unwrap_or_default(); + let mut fill = Fill { projection: Projection::Uv { scale: material.uv_tiling, rotation: 0.0, offset: [0.0, 0.0] }, ..Fill::default() }; + // Resources to add (name and encoded bytes), and their decoded images for the session. + let mut added: Vec<(String, Arc>)> = Vec::new(); + let mut decoded = Vec::new(); + let mut names: BTreeMap = BTreeMap::new(); + let mut channels: Vec = Vec::new(); + for (channel, value) in &material.channels { + if !available.contains(channel) { + warnings.push(format!("{} was skipped: this texture set has no such channel", channel.id())); + continue; + } + let source = match value { + Mtlx::Constant(c) => Source::Uniform(*c), + Mtlx::Image(file) => { + let resource = match names.get(file) { + Some(n) => n.clone(), + None => { + let loaded = + load(file).and_then(|bytes| texturecraft_formats::decode_image(&bytes).map(|image| (bytes, image)).map_err(|e| e.to_string())); + let (bytes, image) = match loaded { + Ok(v) => v, + Err(e) => { + warnings.push(format!("{} was skipped: {file}: {e}", channel.id())); + continue; + } + }; + let leaf = file.rsplit(['/', '\\']).next().unwrap_or(file); + let base = texturecraft_formats::sanitize_resource_name(leaf); + let (mut unique, mut n) = (base.clone(), 2); + while self.doc.resources.contains_key(&unique) || added.iter().any(|(a, _)| *a == unique) { + unique = format!("{n}_{base}"); + n += 1; + } + added.push((unique.clone(), Arc::new(bytes))); + decoded.push((unique.clone(), crate::resource_cmds::decoded(image))); + names.insert(file.clone(), unique.clone()); + unique + } + }; + Source::Image { name: resource } + } + }; + fill.sources.insert(*channel, source); + channels.push(*channel); + } + if channels.is_empty() { + let why = if warnings.is_empty() { String::new() } else { format!(" ({})", warnings.join("; ")) }; + return Err(EngineError::Other(format!("file.importMaterialX: nothing to import from {:?}{why}", material.name))); + } + let layer_name = name.map(str::to_string).unwrap_or_else(|| self.doc.project.next_layer_name(ts, &material.name)); + let resource_names: Vec = added.iter().map(|(n, _)| n.clone()).collect(); + let id = self.edit("Import MaterialX material", |s| { + for (n, bytes) in &added { + s.doc.resources.insert(n.clone(), bytes.clone()); + } + let id = s.doc.project.alloc_id(); + crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name, LayerKind::Fill(fill), &channels)) + })?; + self.images.extend(decoded); + Ok(json!({ + "layer": id.0, + "material": material.name, + "channels": channels.iter().map(|c| c.id()).collect::>(), + "resources": resource_names, + "warnings": warnings, + })) + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn import(s: &mut Session, p: &Value) -> Result { + use std::path::{Component, Path}; + let cmd = "file.importMaterialX"; + let path = strp(p, "path").filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, "`path` is required"))?; + let meta = std::fs::metadata(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?; + if !meta.is_file() || meta.len() > texturecraft_formats::materialx_read::MAX_BYTES as u64 { + return Err(bad(cmd, format!("{path} is not a MaterialX file of a readable size"))); + } + let bytes = std::fs::read(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?; + let material = texturecraft_formats::materialx_read::read_materialx(&bytes, strp(p, "material")).map_err(|e| bad(cmd, format!("{path}: {e}")))?; + let folder = Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); + let dir = folder.canonicalize().map_err(|e| bad(cmd, format!("cannot read the folder of {path}: {e}")))?; + let load = |file: &str| -> std::result::Result, String> { + // `` stands for a tile number; the first tile is read. + let file = file.replace("", "1001"); + let rel = Path::new(&file); + let outside = "the file is outside the material's folder"; + if rel.is_absolute() || rel.components().any(|c| matches!(c, Component::ParentDir | Component::Prefix(_) | Component::RootDir)) { + return Err(outside.into()); + } + let full = dir.join(rel).canonicalize().map_err(|e| e.to_string())?; + if !full.starts_with(&dir) { + return Err(outside.into()); + } + let len = std::fs::metadata(&full).map_err(|e| e.to_string())?.len(); + if len > 512 << 20 { + return Err("the file is over 512 MiB".into()); + } + std::fs::read(&full).map_err(|e| e.to_string()) + }; + s.import_material(material, strp(p, "name"), &load) +} + +#[cfg(target_arch = "wasm32")] +fn import(_: &mut Session, _: &Value) -> Result { + Err(EngineError::Other("file paths are not available in the browser".into())) +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 95736cbd..9bdf3949 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -31,7 +31,7 @@ pub fn specs() -> Vec { /// Largest accepted resource file. const MAX_BYTES: usize = 512 << 20; -fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { +pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { Arc::new(ImageRes { width: d.width, height: d.height, rgba: d.rgba, srgb: d.srgb }) } diff --git a/crates/engine/tests/materialx_import.rs b/crates/engine/tests/materialx_import.rs new file mode 100644 index 00000000..aa51746f --- /dev/null +++ b/crates/engine/tests/materialx_import.rs @@ -0,0 +1,124 @@ +//! `file.importMaterialX`: a .mtlx material becomes one fill layer with its textures. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, LayerKind, Source}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + Session::new_project("t", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap() +} + +fn png(path: &Path, rgb: [u8; 3]) { + image::RgbImage::from_pixel(4, 4, image::Rgb(rgb)).save(path).unwrap(); +} + +fn folder(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("tc_mtlx_import_{tag}_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("tex")).unwrap(); + dir +} + +const MATERIAL: &str = r#" + + + + + + + + + + + + + + + + + + + + + +"#; + +fn fill_of(s: &Session, layer: u64) -> texturecraft_engine::core::Fill { + let l = s.doc.project.layer(texturecraft_engine::core::LayerId(layer)).unwrap(); + match &l.kind { + LayerKind::Fill(f) => f.clone(), + other => panic!("not a fill: {other:?}"), + } +} + +#[test] +fn a_material_becomes_one_fill_layer_in_one_undo_step() { + let dir = folder("ok"); + png(&dir.join("tex/base.png"), [200, 40, 40]); + // A file next to the folder that a hostile document tries to reach. + png(&dir.parent().unwrap().join("escape.png"), [1, 2, 3]); + let mtlx = dir.join("brick.mtlx"); + std::fs::write(&mtlx, MATERIAL).unwrap(); + + let mut s = session(); + let before = s.doc.resources.len(); + let r = execute(&mut s, "file.importMaterialX", &json!({ "path": mtlx.display().to_string() })).unwrap(); + assert_eq!(r["material"], "Brick"); + let fill = fill_of(&s, r["layer"].as_u64().unwrap()); + // The one image used twice is one resource; the constant is uniform. + assert_eq!(r["resources"].as_array().unwrap().len(), 1, "{r}"); + let name = r["resources"][0].as_str().unwrap().to_string(); + assert!(matches!(fill.sources.get(&Channel::BaseColor), Some(Source::Image { name: n }) if *n == name)); + assert!(matches!(fill.sources.get(&Channel::Roughness), Some(Source::Image { name: n }) if *n == name)); + assert_eq!(fill.sources.get(&Channel::Metallic), Some(&Source::Uniform([1.0; 3]))); + assert!(matches!(fill.projection, texturecraft_engine::core::Projection::Uv { scale, .. } if scale == [3.0, 3.0]), "{:?}", fill.projection); + assert_eq!(s.doc.resources.len(), before + 1); + assert!(s.images.contains_key(&name), "the image is decoded for the viewport"); + + // The traversal and the missing file were skipped with a warning, not read. + let warnings = r["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect::>(); + assert!(fill.sources.get(&Channel::Normal).is_none() && fill.sources.get(&Channel::Height).is_none(), "{fill:?}"); + assert!(warnings.iter().any(|w| w.contains("outside")), "{warnings:?}"); + assert!(warnings.iter().any(|w| w.contains("missing.png")), "{warnings:?}"); + // A channel the texture set doesn't have is reported, not invented. + let has_coat = s.doc.project.texture_set(s.ts()).unwrap().channel_list().contains(&Channel::CoatWeight); + assert_eq!(fill.sources.contains_key(&Channel::CoatWeight), has_coat); + assert_eq!(warnings.iter().any(|w| w.contains("no such channel")), !has_coat, "{warnings:?}"); + assert!(!s.doc.resources.keys().any(|k| k.contains("escape")), "nothing outside the folder was imported"); + + // One undo removes the layer and its images together. + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.doc.resources.len(), before); + assert!(s.doc.project.layer(texturecraft_engine::core::LayerId(r["layer"].as_u64().unwrap())).is_err()); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_file(dir.parent().unwrap().join("escape.png")); +} + +#[test] +fn bad_documents_and_paths_are_errors_that_change_nothing() { + let dir = folder("bad"); + let mut s = session(); + let layers = |s: &Session| s.doc.project.texture_sets[0].stack.len(); + let (n, res) = (layers(&s), s.doc.resources.len()); + let run = |s: &mut Session, p: Value| execute(s, "file.importMaterialX", &p); + assert!(run(&mut s, json!({})).is_err()); + assert!(run(&mut s, json!({ "path": dir.join("nope.mtlx").display().to_string() })).is_err()); + for (i, text) in ["", "garbage", "", ""].iter().enumerate() { + let f = dir.join(format!("bad{i}.mtlx")); + std::fs::write(&f, text).unwrap(); + assert!(run(&mut s, json!({ "path": f.display().to_string() })).is_err(), "{text:?}"); + } + // Only images that can't be read: nothing to import is an error, not an empty layer. + let only_missing = MATERIAL.replace("base.png", "none.png"); + let f = dir.join("missing.mtlx"); + std::fs::write(&f, only_missing.replace("", "")).unwrap(); + assert!(run(&mut s, json!({ "path": f.display().to_string() })).is_err()); + // A material that isn't in the document. + std::fs::write(dir.join("m.mtlx"), MATERIAL).unwrap(); + assert!(run(&mut s, json!({ "path": dir.join("m.mtlx").display().to_string(), "material": "Nope" })).is_err()); + assert_eq!((layers(&s), s.doc.resources.len()), (n, res), "refused imports leave the project alone"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 3af93ab2..5bd6059e 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -26,6 +26,7 @@ pub mod export; #[cfg(not(target_arch = "wasm32"))] pub mod fonts; pub mod image_res; +pub mod materialx_read; pub mod mesh_export; pub mod mesh_import; pub mod presets; diff --git a/crates/formats/src/materialx_read.rs b/crates/formats/src/materialx_read.rs new file mode 100644 index 00000000..eecd2d71 --- /dev/null +++ b/crates/formats/src/materialx_read.rs @@ -0,0 +1,542 @@ +//! Reading a MaterialX (`.mtlx`) material into TextureCraft's channels, written from the ASWF +//! MaterialX specification (1.39) and the OpenPBR Surface and glTF PBR node definitions. Pure +//! Rust: no MaterialX library is linked. +//! +//! [`read_materialx`] finds a `surfacematerial`, follows its `surfaceshader` to an +//! `open_pbr_surface`, `standard_surface` or `gltf_pbr` node, and turns each input TextureCraft +//! has a channel for into a literal value or an image file: +//! +//! - a literal `value` becomes a constant (`color3` values tagged `srgb_texture` are converted +//! to linear; a colour given for a scalar channel is averaged); +//! - an input wired to a `tiledimage` or `image` node (directly or through a `nodegraph` +//! output) becomes that node's `file` (with `fileprefix` applied); `normalmap`, `convert` and +//! `constant` nodes in between are passed through; +//! - the material's `displacementshader` becomes the height channel; +//! - `uvtiling` of the first tiled image is returned as the UV tiling. +//! +//! Anything else (maths nodes, procedural patterns, other shaders) is skipped with a warning +//! rather than guessed at. Emission follows the specifications' defaults: OpenPBR emits nothing +//! unless `emission_luminance` is above 0, and `standard_surface` unless `emission` is. +//! +//! The reader takes untrusted bytes: the document size, nesting and element count are capped, a +//! wiring loop stops at a depth limit, and every failure is an error, never a panic. + +use std::collections::HashMap; + +use quick_xml::events::{BytesStart, Event}; +use texturecraft_core::Channel; +use texturecraft_texel::srgb_to_linear; + +use crate::{FormatError, Result, malformed}; + +const KIND: &str = "MaterialX document"; +/// Largest document read, in bytes. +pub const MAX_BYTES: usize = 16 << 20; +const MAX_DEPTH: usize = 64; +const MAX_ELEMENTS: usize = 200_000; +/// Longest chain of nodes followed from one shader input. +const MAX_HOPS: usize = 16; + +/// What one channel is set from. +#[derive(Clone, Debug, PartialEq)] +pub enum Value { + /// A constant: linear RGB for colours, `[v, v, v]` for scalars. + Constant([f32; 3]), + /// An image file, as written in the document (`fileprefix` applied), relative to it. + Image(String), +} + +/// A material read from a document. +#[derive(Clone, Debug, PartialEq)] +pub struct Material { + pub name: String, + /// The channels the material sets, in a fixed order. + pub channels: Vec<(Channel, Value)>, + /// The first image's `uvtiling` (1, 1 when none). + pub uv_tiling: [f32; 2], + /// What was skipped and why. + pub warnings: Vec, +} + +// --------------------------------------------------------------------------------------------- +// XML. + +#[derive(Default)] +struct El { + name: String, + attrs: Vec<(String, String)>, + children: Vec, +} + +impl El { + fn attr(&self, k: &str) -> Option<&str> { + self.attrs.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()) + } + + /// The child element named `name` (the `name` attribute: inputs and nodes are looked up by it). + fn input(&self, name: &str) -> Option<&El> { + self.children.iter().find(|c| c.attr("name") == Some(name)) + } +} + +fn element(e: &BytesStart) -> El { + let text = |b: &[u8]| String::from_utf8_lossy(b).into_owned(); + let attrs = e + .attributes() + .with_checks(false) + .flatten() + .map(|a| { + (text(a.key.local_name().as_ref()), a.normalized_value(quick_xml::XmlVersion::Implicit1_0).map_or_else(|_| text(&a.value), |v| v.into_owned())) + }) + .collect(); + El { name: text(e.local_name().as_ref()), attrs, children: Vec::new() } +} + +fn parse_xml(bytes: &[u8]) -> Result { + let mut reader = quick_xml::Reader::from_reader(bytes); + let mut stack = vec![El::default()]; + let mut count = 0usize; + loop { + let event = reader.read_event().map_err(|e| malformed(KIND, e))?; + if matches!(event, Event::Start(_) | Event::Empty(_)) { + count += 1; + if count > MAX_ELEMENTS || stack.len() > MAX_DEPTH { + return Err(FormatError::TooLarge(format!( + "the MaterialX document has more than {MAX_ELEMENTS} elements or is nested deeper than {MAX_DEPTH}" + ))); + } + } + match event { + Event::Start(e) => stack.push(element(&e)), + Event::Empty(e) => { + if let Some(parent) = stack.last_mut() { + parent.children.push(element(&e)); + } + } + Event::End(_) => { + let el = stack.pop().filter(|_| !stack.is_empty()).ok_or_else(|| malformed(KIND, "unbalanced end tag"))?; + if let Some(parent) = stack.last_mut() { + parent.children.push(el); + } + } + Event::Eof => break, + _ => {} + } + } + match (stack.pop(), stack.is_empty()) { + (Some(root), true) => Ok(root), + _ => Err(malformed(KIND, "unclosed elements at the end of the document")), + } +} + +// --------------------------------------------------------------------------------------------- +// Shader input tables: (shader input, channel). `kind` says how to read the value. + +#[derive(Clone, Copy, PartialEq)] +enum Shader { + OpenPbr, + Standard, + Gltf, +} + +const OPEN_PBR: &[(&str, Channel)] = &[ + ("base_color", Channel::BaseColor), + ("base_metalness", Channel::Metallic), + ("specular_roughness", Channel::Roughness), + ("geometry_normal", Channel::Normal), + ("geometry_opacity", Channel::Opacity), + ("emission_color", Channel::Emissive), + ("coat_weight", Channel::CoatWeight), + ("coat_roughness", Channel::CoatRoughness), + ("geometry_coat_normal", Channel::CoatNormal), + ("fuzz_weight", Channel::SheenWeight), + ("fuzz_color", Channel::SheenColor), + ("fuzz_roughness", Channel::SheenRoughness), + ("specular_roughness_anisotropy", Channel::AnisotropyLevel), + ("transmission_weight", Channel::Transmission), + ("subsurface_weight", Channel::ScatterWeight), +]; + +const STANDARD: &[(&str, Channel)] = &[ + ("base_color", Channel::BaseColor), + ("metalness", Channel::Metallic), + ("specular_roughness", Channel::Roughness), + ("normal", Channel::Normal), + ("opacity", Channel::Opacity), + ("emission_color", Channel::Emissive), + ("coat", Channel::CoatWeight), + ("coat_roughness", Channel::CoatRoughness), + ("coat_normal", Channel::CoatNormal), + ("sheen", Channel::SheenWeight), + ("sheen_color", Channel::SheenColor), + ("sheen_roughness", Channel::SheenRoughness), + ("specular_anisotropy", Channel::AnisotropyLevel), + ("transmission", Channel::Transmission), + ("subsurface", Channel::ScatterWeight), +]; + +const GLTF: &[(&str, Channel)] = &[ + ("base_color", Channel::BaseColor), + ("metallic", Channel::Metallic), + ("roughness", Channel::Roughness), + ("normal", Channel::Normal), + ("alpha", Channel::Opacity), + ("emission", Channel::Emissive), + ("occlusion", Channel::AmbientOcclusion), + ("clearcoat", Channel::CoatWeight), + ("clearcoat_roughness", Channel::CoatRoughness), + ("clearcoat_normal", Channel::CoatNormal), + ("sheen_color", Channel::SheenColor), + ("sheen_roughness", Channel::SheenRoughness), + ("transmission", Channel::Transmission), +]; + +// --------------------------------------------------------------------------------------------- +// Resolving what feeds an input. + +struct Doc<'a> { + root: &'a El, + /// Every node by name: the document's own, and each nodegraph's (qualified `graph/node`). + nodes: HashMap, + /// Each nodegraph's outputs: `graph/output` to the node name inside (qualified). + outputs: HashMap, + tiling: Option<[f32; 2]>, + warnings: Vec, +} + +enum Found { + Constant(Vec), + Image(String), + None, +} + +fn numbers(text: &str) -> Option> { + let v: Option> = text.split(',').map(|p| p.trim().parse::().ok().filter(|f| f.is_finite())).collect(); + v.filter(|v| !v.is_empty() && v.len() <= 4) +} + +impl<'a> Doc<'a> { + fn new(root: &'a El) -> Doc<'a> { + let mut nodes = HashMap::new(); + let mut outputs = HashMap::new(); + for c in &root.children { + match (c.name.as_str(), c.attr("name")) { + ("nodegraph", Some(g)) => { + for n in &c.children { + let Some(name) = n.attr("name") else { continue }; + if n.name == "output" { + if let Some(from) = n.attr("nodename") { + outputs.insert(format!("{g}/{name}"), format!("{g}/{from}")); + } + } else { + nodes.insert(format!("{g}/{name}"), n); + } + } + } + (_, Some(name)) => { + nodes.insert(name.to_owned(), c); + } + _ => {} + } + } + Doc { root, nodes, outputs, tiling: None, warnings: Vec::new() } + } + + /// What `input` (an `` element of a node) resolves to; `scope` is the nodegraph the + /// node lives in, if any. + fn resolve(&mut self, input: &El, scope: Option<&str>, hops: usize) -> Found { + if hops > MAX_HOPS { + self.warnings.push("a node chain is longer than 16 nodes (or loops); skipped".into()); + return Found::None; + } + if let Some(v) = input.attr("value") { + return numbers(v).map_or(Found::None, |n| Found::Constant(self.tag(input, n))); + } + let target = match (input.attr("nodegraph"), input.attr("output"), input.attr("nodename")) { + (Some(g), out, _) => { + let out = out.map(str::to_owned).or_else(|| self.outputs.keys().find_map(|k| k.strip_prefix(&format!("{g}/")).map(str::to_owned))); + out.and_then(|o| self.outputs.get(&format!("{g}/{o}")).cloned()) + } + (None, _, Some(n)) => { + Some(scope.map_or_else(|| n.to_owned(), |g| format!("{g}/{n}"))).filter(|q| self.nodes.contains_key(q)).or_else(|| Some(n.to_owned())) + } + _ => None, + }; + let Some(node) = target.as_deref().and_then(|t| self.nodes.get(t).copied()) else { return Found::None }; + let scope = target.as_deref().and_then(|t| t.split_once('/')).map(|(g, _)| g.to_owned()); + let scope = scope.as_deref(); + match node.name.as_str() { + "tiledimage" | "image" => { + let Some(file) = node.input("file").and_then(|f| f.attr("value")) else { + self.warnings.push(format!("image node {:?} has no file", node.attr("name").unwrap_or(""))); + return Found::None; + }; + let prefix = + [node.input("file").and_then(|f| f.attr("fileprefix")), node.attr("fileprefix"), self.root.attr("fileprefix")].into_iter().flatten().next(); + if self.tiling.is_none() + && let Some(t) = + node.input("uvtiling").and_then(|t| t.attr("value")).and_then(numbers).filter(|t| t.len() == 2 && t.iter().all(|v| *v > 0.0)) + { + self.tiling = Some([t[0], t[1]]); + } + Found::Image(format!("{}{file}", prefix.unwrap_or(""))) + } + "normalmap" | "convert" => match node.input("in") { + Some(i) => self.resolve(i, scope, hops + 1), + None => Found::None, + }, + "constant" => match node.input("value") { + Some(v) => self.resolve(v, scope, hops + 1), + None => Found::None, + }, + other => { + self.warnings.push(format!("a {other} node ({:?}) is not supported; its input was skipped", node.attr("name").unwrap_or(""))); + Found::None + } + } + } + + /// Literal values tagged with an sRGB colour space are converted to linear. + fn tag(&self, input: &El, mut n: Vec) -> Vec { + let space = input.attr("colorspace").or_else(|| self.root.attr("colorspace")).unwrap_or(""); + if input.attr("colorspace").is_some() && (space.starts_with("srgb") || space.starts_with("g22") || space.starts_with("g18")) && n.len() >= 3 { + n.iter_mut().take(3).for_each(|c| *c = srgb_to_linear(*c)); + } + n + } +} + +fn to_constant(channel: Channel, n: &[f32]) -> [f32; 3] { + match (channel.kind(), n) { + (_, [a]) => [*a; 3], + (texturecraft_core::ChannelKind::Color, [r, g, b, ..]) => [*r, *g, *b], + (_, [r, g, b, ..]) => { + let mean = (r + g + b) / 3.0; + [mean; 3] + } + _ => Channel::default_value(channel), + } +} + +/// The literal number of `input`, if it is one. +fn literal(shader: &El, name: &str) -> Option { + shader.input(name).and_then(|i| i.attr("value")).and_then(numbers).and_then(|n| n.first().copied()) +} + +/// Read the material called `material` (default: the first) from a `.mtlx` document. +pub fn read_materialx(bytes: &[u8], material: Option<&str>) -> Result { + crate::guard(KIND, || read_inner(bytes, material)) +} + +fn read_inner(bytes: &[u8], material: Option<&str>) -> Result { + if bytes.len() > MAX_BYTES { + return Err(FormatError::TooLarge(format!("the MaterialX document is over {} MiB", MAX_BYTES >> 20))); + } + let top = parse_xml(bytes)?; + let root = top.children.iter().find(|c| c.name == "materialx").ok_or_else(|| malformed(KIND, "no element"))?; + let mut doc = Doc::new(root); + let materials: Vec<&El> = root.children.iter().filter(|c| c.name == "surfacematerial").collect(); + let mat = match material { + Some(name) => materials + .iter() + .copied() + .find(|m| m.attr("name") == Some(name)) + .ok_or_else(|| FormatError::Invalid(format!("no material named {name:?} (found: {})", names(&materials))))?, + None => materials.first().copied().ok_or_else(|| FormatError::Unsupported("the document has no surfacematerial".into()))?, + }; + let mut out = Material { name: mat.attr("name").unwrap_or("Material").to_owned(), channels: Vec::new(), uv_tiling: [1.0, 1.0], warnings: Vec::new() }; + let shader = mat + .input("surfaceshader") + .and_then(|i| i.attr("nodename")) + .and_then(|n| doc.nodes.get(n).copied()) + .ok_or_else(|| malformed(KIND, "the material has no surface shader"))?; + let (kind, table) = match shader.name.as_str() { + "open_pbr_surface" => (Shader::OpenPbr, OPEN_PBR), + "standard_surface" => (Shader::Standard, STANDARD), + "gltf_pbr" => (Shader::Gltf, GLTF), + other => return Err(FormatError::Unsupported(format!("the surface shader is a {other}; open_pbr_surface, standard_surface and gltf_pbr are read"))), + }; + // Emission is off by default in OpenPBR and standard_surface. + let emits = match kind { + Shader::OpenPbr => { + shader.input("emission_luminance").is_some_and(|i| i.attr("value").is_none() || literal(shader, "emission_luminance").is_some_and(|v| v > 0.0)) + } + Shader::Standard => shader.input("emission").is_some_and(|i| i.attr("value").is_none() || literal(shader, "emission").is_some_and(|v| v > 0.0)), + Shader::Gltf => true, + }; + let weight = match kind { + Shader::OpenPbr => literal(shader, "base_weight"), + Shader::Standard => literal(shader, "base"), + Shader::Gltf => None, + }; + if weight.is_some_and(|w| (w - 1.0).abs() > 1e-6) { + doc.warnings.push("the base weight isn't 1; it was ignored".into()); + } + for &(input, channel) in table { + let Some(el) = shader.input(input) else { continue }; + if channel == Channel::Emissive && !emits && kind != Shader::Gltf { + doc.warnings.push(format!("{input} was skipped: the shader's emission is 0")); + continue; + } + match doc.resolve(el, None, 0) { + Found::Constant(n) => out.channels.push((channel, Value::Constant(to_constant(channel, &n)))), + Found::Image(f) => out.channels.push((channel, Value::Image(f))), + Found::None => {} + } + } + // The displacement shader's `displacement` input is the height. + if let Some(d) = mat.input("displacementshader").and_then(|i| i.attr("nodename")).and_then(|n| doc.nodes.get(n).copied()) + && let Some(i) = d.input("displacement") + { + match doc.resolve(i, None, 0) { + Found::Constant(n) => out.channels.push((Channel::Height, Value::Constant(to_constant(Channel::Height, &n)))), + Found::Image(f) => out.channels.push((Channel::Height, Value::Image(f))), + Found::None => {} + } + } + out.uv_tiling = doc.tiling.unwrap_or([1.0, 1.0]); + out.warnings = doc.warnings; + Ok(out) +} + +fn names(materials: &[&El]) -> String { + let n: Vec<&str> = materials.iter().filter_map(|m| m.attr("name")).collect(); + if n.is_empty() { "none".into() } else { n.join(", ") } +} + +#[cfg(test)] +mod tests { + use super::*; + + const OPENPBR: &str = r#" + + + + + + + + + + + + + + + + + + + + + + + +"#; + + fn get(m: &Material, c: Channel) -> Option<&Value> { + m.channels.iter().find(|(ch, _)| *ch == c).map(|(_, v)| v) + } + + #[test] + fn open_pbr_inputs_become_channels() { + let m = read_materialx(OPENPBR.as_bytes(), None).unwrap(); + assert_eq!(m.name, "Stone"); + assert_eq!(get(&m, Channel::BaseColor), Some(&Value::Image("stone_base.png".into()))); + assert_eq!(get(&m, Channel::Roughness), Some(&Value::Image("stone_r.png".into()))); + assert_eq!(get(&m, Channel::Normal), Some(&Value::Image("stone_n.png".into())), "through the normalmap node"); + assert_eq!(get(&m, Channel::Height), Some(&Value::Image("stone_h.png".into())), "from the displacement shader"); + assert_eq!(get(&m, Channel::Metallic), Some(&Value::Constant([1.0; 3]))); + assert_eq!(get(&m, Channel::CoatWeight), Some(&Value::Constant([0.25; 3]))); + assert_eq!(get(&m, Channel::Emissive), Some(&Value::Constant([1.0, 0.5, 0.0]))); + assert_eq!(m.uv_tiling, [4.0, 2.0]); + assert!(m.warnings.is_empty(), "{:?}", m.warnings); + } + + #[test] + fn emission_is_off_unless_the_shader_emits() { + let x = OPENPBR.replace(r#""#, ""); + let m = read_materialx(x.as_bytes(), None).unwrap(); + assert!(get(&m, Channel::Emissive).is_none()); + assert!(m.warnings.iter().any(|w| w.contains("emission")), "{:?}", m.warnings); + let zero = OPENPBR.replace(r#"value="2" />"#, r#"value="0" />"#); + assert!(get(&read_materialx(zero.as_bytes(), None).unwrap(), Channel::Emissive).is_none()); + } + + #[test] + fn standard_surface_nodegraphs_prefixes_and_colour_spaces() { + let x = r#" + + + + + + + + + + + + + +"#; + let m = read_materialx(x.as_bytes(), Some("M2")).unwrap(); + assert_eq!(m.name, "M2"); + assert_eq!(get(&m, Channel::BaseColor), Some(&Value::Image("tex/a.png".into())), "through the nodegraph, with the prefix"); + assert_eq!(get(&m, Channel::Roughness), Some(&Value::Constant([0.4; 3]))); + assert_eq!(get(&m, Channel::Opacity), Some(&Value::Constant([0.5; 3])), "a colour on a scalar channel is averaged"); + let Some(Value::Constant(c)) = get(&m, Channel::SheenColor) else { panic!("sheen colour") }; + assert!((c[0] - 0.214).abs() < 1e-3, "sRGB 0.5 is linear 0.214: {c:?}"); + assert!(m.warnings.iter().any(|w| w.contains("base weight")), "{:?}", m.warnings); + assert!(read_materialx(x.as_bytes(), Some("nope")).is_err()); + } + + #[test] + fn unsupported_nodes_and_shaders_are_reported() { + let x = OPENPBR.replace(r#""#; + assert!(matches!(read_materialx(other.as_bytes(), None), Err(FormatError::Unsupported(_)))); + } + + #[test] + fn hostile_documents_are_errors() { + for bad in ["", "not xml", "", "", "", ""] { + assert!(read_materialx(bad.as_bytes(), None).is_err(), "{bad:?}"); + } + // A wiring loop and a deep tree stop instead of running forever or overflowing. + let loop_doc = r#" + + "#; + let m = read_materialx(loop_doc.as_bytes(), None).unwrap(); + assert!(m.channels.is_empty() && m.warnings.iter().any(|w| w.contains("loops")), "{:?}", m.warnings); + let deep = format!("{}{}", "".repeat(200), "".repeat(200)); + assert!(matches!(read_materialx(deep.as_bytes(), None), Err(FormatError::TooLarge(_)))); + // Numbers: NaN, inf and over-long lists are not values. + let nan = OPENPBR.replace(r#"value="0.25""#, r#"value="NaN""#); + assert!(get(&read_materialx(nan.as_bytes(), None).unwrap(), Channel::CoatWeight).is_none()); + } + + #[test] + fn xml_entities_in_file_names_are_decoded() { + let x = OPENPBR.replace("stone_base.png", "a&b <1>.png"); + let m = read_materialx(x.as_bytes(), None).unwrap(); + assert_eq!(get(&m, Channel::BaseColor), Some(&Value::Image("a&b <1>.png".into()))); + } + + #[test] + fn mutated_documents_never_panic() { + // Truncations and byte flips of a real document: errors or materials, never a panic. + let bytes = OPENPBR.as_bytes(); + for cut in (0..bytes.len()).step_by(7) { + let _ = read_materialx(&bytes[..cut], None); + } + for i in (0..bytes.len()).step_by(5) { + let mut b = bytes.to_vec(); + b[i] ^= 0x5a; + let _ = read_materialx(&b, None); + } + } +} From 2385524b005c45aa67b9c054d739839f9ffb0654 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:53:56 -0500 Subject: [PATCH 12/46] test: use contains_key in the MaterialX import test Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/tests/materialx_import.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/materialx_import.rs b/crates/engine/tests/materialx_import.rs index aa51746f..cdd77fbf 100644 --- a/crates/engine/tests/materialx_import.rs +++ b/crates/engine/tests/materialx_import.rs @@ -80,7 +80,7 @@ fn a_material_becomes_one_fill_layer_in_one_undo_step() { // The traversal and the missing file were skipped with a warning, not read. let warnings = r["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect::>(); - assert!(fill.sources.get(&Channel::Normal).is_none() && fill.sources.get(&Channel::Height).is_none(), "{fill:?}"); + assert!(!fill.sources.contains_key(&Channel::Normal) && !fill.sources.contains_key(&Channel::Height), "{fill:?}"); assert!(warnings.iter().any(|w| w.contains("outside")), "{warnings:?}"); assert!(warnings.iter().any(|w| w.contains("missing.png")), "{warnings:?}"); // A channel the texture set doesn't have is reported, not invented. 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 13/46] 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 14/46] 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 4917eda4a818b71483cfb9677beec203ee631eb4 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:56:46 -0500 Subject: [PATCH 15/46] feat(ui): File > Import MaterialX material... with a file picker The menu item opens a .mtlx picker and runs file.importMaterialX; the new layer's name is toasted, the reader's warnings go to the Log, and the Layers panel is focused. The menu label and the picker's filter name are translated in all ten languages; menu parity is 54 of 54. Co-Authored-By: Claude Sonnet 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 | 2 ++ crates/ui-egui/src/i18n/it.rs | 2 ++ crates/ui-egui/src/i18n/ja.rs | 2 ++ crates/ui-egui/src/i18n/ko.rs | 2 ++ crates/ui-egui/src/i18n/pt_br.rs | 2 ++ crates/ui-egui/src/i18n/zh_hans.rs | 2 ++ crates/ui-egui/src/menus.rs | 1 + crates/ui-egui/src/windows.rs | 13 +++++++++++++ docs/parity.md | 3 ++- 12 files changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 495f1d59..76759b6e 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -399,6 +399,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import an image (File > Import resources) to project it onto the mesh.", "استورد صورة (ملف > استيراد الموارد) لإسقاطها على المجسم."), ("Import images to use them in fills and masks", "استورد الصور لاستخدامها في التعبئة والأقنعة"), ("Import resources...", "استيراد الموارد..."), + ("Import MaterialX material...", "استيراد مادة MaterialX..."), + ("MaterialX materials", "مواد MaterialX"), ("Import...", "استيراد..."), ("Imported template \"{name}\"", "تم استيراد القالب \"{name}\""), ("Imported {name}", "تم استيراد {name}"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index b20b228f..3da95541 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -423,6 +423,8 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Import images to use them in fills and masks", "Bilder importieren, um sie in Füllungen und Masken zu verwenden"), ("Import resources...", "Ressourcen importieren..."), + ("Import MaterialX material...", "MaterialX-Material importieren..."), + ("MaterialX materials", "MaterialX-Materialien"), ("Import...", "Importieren..."), ("Imported template \"{name}\"", "Vorlage „{name}“ importiert"), ("Imported {name}", "{name} importiert"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 829a54aa..8775e290 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -417,6 +417,8 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Import images to use them in fills and masks", "Importar imágenes para usarlas en rellenos y máscaras"), ("Import resources...", "Importar recursos..."), + ("Import MaterialX material...", "Importar material MaterialX..."), + ("MaterialX materials", "Materiales MaterialX"), ("Import...", "Importar..."), ("Imported template \"{name}\"", "Plantilla \"{name}\" importada"), ("Imported {name}", "{name} importado"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index eb9744c7..dd2c1521 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -423,6 +423,8 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Import images to use them in fills and masks", "Importez des images pour les utiliser dans les remplissages et les masques"), ("Import resources...", "Importer des ressources..."), + ("Import MaterialX material...", "Importer un matériau MaterialX..."), + ("MaterialX materials", "Matériaux MaterialX"), ("Import...", "Importer..."), ("Imported template \"{name}\"", "Modèle « {name} » importé"), ("Imported {name}", "{name} importé"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 664a3732..975a7554 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -420,6 +420,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import an image (File > Import resources) to project it onto the mesh.", "Importa un'immagine (File > Importa risorse) per proiettarla sulla mesh."), ("Import images to use them in fills and masks", "Importa immagini per usarle in riempimenti e maschere"), ("Import resources...", "Importa risorse..."), + ("Import MaterialX material...", "Importa materiale MaterialX..."), + ("MaterialX materials", "Materiali MaterialX"), ("Import...", "Importa..."), ("Imported template \"{name}\"", "Modello \"{name}\" importato"), ("Imported {name}", "{name} importato"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 3e79b658..ba49e580 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -408,6 +408,8 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Import images to use them in fills and masks", "画像をインポートして塗りつぶしやマスクで使用"), ("Import resources...", "リソースをインポート..."), + ("Import MaterialX material...", "MaterialX マテリアルをインポート..."), + ("MaterialX materials", "MaterialX マテリアル"), ("Import...", "インポート..."), ("Imported template \"{name}\"", "テンプレート「{name}」をインポートしました"), ("Imported {name}", "{name} をインポートしました"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 47d765cf..9f42b255 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -402,6 +402,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import an image (File > Import resources) to project it onto the mesh.", "메시에 투영할 이미지를 가져오세요 (파일 > 리소스 가져오기)."), ("Import images to use them in fills and masks", "채우기와 마스크에 사용할 이미지를 가져옵니다"), ("Import resources...", "리소스 가져오기..."), + ("Import MaterialX material...", "MaterialX 머티리얼 가져오기..."), + ("MaterialX materials", "MaterialX 머티리얼"), ("Import...", "가져오기..."), ("Imported template \"{name}\"", "템플릿 \"{name}\" 가져옴"), ("Imported {name}", "가져옴: {name}"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index ee434a60..9135d140 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -414,6 +414,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import an image (File > Import resources) to project it onto the mesh.", "Importe uma imagem (Arquivo > Importar recursos) para projetá-la na malha."), ("Import images to use them in fills and masks", "Importe imagens para usá-las em preenchimentos e máscaras"), ("Import resources...", "Importar recursos..."), + ("Import MaterialX material...", "Importar material MaterialX..."), + ("MaterialX materials", "Materiais MaterialX"), ("Import...", "Importar..."), ("Imported template \"{name}\"", "Modelo \"{name}\" importado"), ("Imported {name}", "{name} importado"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 41bd7998..82917b0a 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -360,6 +360,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import an image (File > Import resources) to project it onto the mesh.", "导入图像(文件 > 导入资源)以将其投影到网格上。"), ("Import images to use them in fills and masks", "导入图像以在填充和遮罩中使用"), ("Import resources...", "导入资源..."), + ("Import MaterialX material...", "导入 MaterialX 材质..."), + ("MaterialX materials", "MaterialX 材质"), ("Import...", "导入..."), ("Imported template \"{name}\"", "已导入模板“{name}”"), ("Imported {name}", "已导入 {name}"), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index bad5be7a..8a5b0069 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -45,6 +45,7 @@ pub const CATALOG: &[Item] = &[ it("File", "Remove unused resources...", "file.removeUnused", None), sep("File"), it("File", "Import resources...", "resource.import", None), + it("File", "Import MaterialX material...", "file.importMaterialX", None), it("File", "Export Textures...", "ui.export", Some("Ctrl+Shift+E")), it("File", "Export Mesh...", "file.exportMesh", None), sep("File"), diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index eab0046e..e9ac6353 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -963,6 +963,19 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> app.ui.dock.focus(crate::docking::Panel::Assets); true } + "file.importMaterialX" => { + if let Some(p) = rfd::FileDialog::new().add_filter(tr("MaterialX materials"), &["mtlx"]).pick_file() + && let Some(r) = app.run("file.importMaterialX", json!({"path": p.display().to_string()})) + { + let name = r.get("material").and_then(|n| n.as_str()).unwrap_or_default().to_string(); + for w in r.get("warnings").and_then(|w| w.as_array()).into_iter().flatten().filter_map(|w| w.as_str()) { + app.session.log.push(format!("MaterialX {name}: {w}")); + } + app.toast(trf("Imported {name}", &[("name", &name)]), false); + app.ui.dock.focus(crate::docking::Panel::Layers); + } + true + } "file.exportMesh" => { let name = format!("{}.obj", texturecraft_engine::formats::export::sanitize_file_stem(&app.session.doc.project.name)); if let Some(p) = rfd::FileDialog::new() diff --git a/docs/parity.md b/docs/parity.md index 86866434..2fc63bf5 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -2,7 +2,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Each row is a menu item of the target menu layout with TextureCraft's command id; **live** means the id is implemented. Feature parity beyond menus is tracked in [`ROADMAP.md`](../ROADMAP.md). -**53 of 53 menu items live (100%).** +**54 of 54 menu items live (100%).** ## File @@ -17,6 +17,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | Save a copy... | `file.saveCopy` | | live | | Remove unused resources... | `file.removeUnused` | | live | | Import resources... | `resource.import` | | live | +| Import MaterialX material... | `file.importMaterialX` | | live | | Export Textures... | `ui.export` | Ctrl+Shift+E | live | | Export Mesh... | `file.exportMesh` | | live | | Quit | `ui.quit` | Ctrl+Q | live | 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 16/46] 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 17/46] 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 18/46] 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 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 19/46] 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 20/46] 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 21/46] 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 22/46] 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 23/46] 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 24/46] 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 25/46] 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 26/46] 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 27/46] 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 28/46] 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 29/46] 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 30/46] 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 31/46] 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 32/46] 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 33/46] 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 34/46] 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 35/46] 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 36/46] 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 37/46] 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 9d1a989efabe9b3ca88b3f10b28f36b7115b5ca3 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:26:02 +0700 Subject: [PATCH 38/46] MaterialX import: clamp uvtiling like a fill's UV scale, reuse the resource size limit uvtiling is clamped to 0.001..=1000, the range layer.fill.projection accepts. Image files are capped by resource_cmds::MAX_BYTES instead of a second copy of the number. --- crates/engine/src/materialx_cmds.rs | 4 ++-- crates/engine/src/resource_cmds.rs | 2 +- crates/formats/src/materialx_read.rs | 5 ++++- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/materialx_cmds.rs b/crates/engine/src/materialx_cmds.rs index 8a212dd7..4dc1168f 100644 --- a/crates/engine/src/materialx_cmds.rs +++ b/crates/engine/src/materialx_cmds.rs @@ -134,8 +134,8 @@ fn import(s: &mut Session, p: &Value) -> Result { return Err(outside.into()); } let len = std::fs::metadata(&full).map_err(|e| e.to_string())?.len(); - if len > 512 << 20 { - return Err("the file is over 512 MiB".into()); + if len > crate::resource_cmds::MAX_BYTES as u64 { + return Err(format!("the file is over {} MB", crate::resource_cmds::MAX_BYTES >> 20)); } std::fs::read(&full).map_err(|e| e.to_string()) }; diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 9bdf3949..3f1d098a 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -29,7 +29,7 @@ pub fn specs() -> Vec { } /// Largest accepted resource file. -const MAX_BYTES: usize = 512 << 20; +pub(crate) const MAX_BYTES: usize = 512 << 20; pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { Arc::new(ImageRes { width: d.width, height: d.height, rgba: d.rgba, srgb: d.srgb }) diff --git a/crates/formats/src/materialx_read.rs b/crates/formats/src/materialx_read.rs index eecd2d71..c8cd8b39 100644 --- a/crates/formats/src/materialx_read.rs +++ b/crates/formats/src/materialx_read.rs @@ -277,7 +277,8 @@ impl<'a> Doc<'a> { && let Some(t) = node.input("uvtiling").and_then(|t| t.attr("value")).and_then(numbers).filter(|t| t.len() == 2 && t.iter().all(|v| *v > 0.0)) { - self.tiling = Some([t[0], t[1]]); + // The range a fill's UV scale accepts (`layer.fill.projection`). + self.tiling = Some([t[0].clamp(0.001, 1000.0), t[1].clamp(0.001, 1000.0)]); } Found::Image(format!("{}{file}", prefix.unwrap_or(""))) } @@ -451,6 +452,8 @@ mod tests { assert_eq!(get(&m, Channel::Emissive), Some(&Value::Constant([1.0, 0.5, 0.0]))); assert_eq!(m.uv_tiling, [4.0, 2.0]); assert!(m.warnings.is_empty(), "{:?}", m.warnings); + let extreme = OPENPBR.replace(r#"value="4, 2""#, r#"value="1e9, 1e-9""#); + assert_eq!(read_materialx(extreme.as_bytes(), None).unwrap().uv_tiling, [1000.0, 0.001], "clamped like a fill's UV scale"); } #[test] From f6bd07e4d6d6d8e2b72ec413e660aa21ecc4333e Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:32:20 +0700 Subject: [PATCH 39/46] 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 b7543a49bc7a76bbc5b92b21ebdc95dfb67f15a8 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:34:16 +0700 Subject: [PATCH 40/46] Auto-rebake: a cancelled or failed bake waits for the next input change After Cancel or a bake error the app re-queued the same Auto-rebake on the next frame, forever, because a set only counted as up to date after a successful bake. Session::bake_abandoned records the set being baked and the queued ones as seen; cancel_bake and the bake error paths call it. Also drops a useless into_iter() and an unreachable branch in bake.autoRebake. --- crates/engine/src/auto_rebake.rs | 18 +++++++++++----- crates/engine/tests/auto_rebake.rs | 33 +++++++++++++++++++++++++++--- crates/ui-egui/src/lib.rs | 19 ++++++++++------- 3 files changed, 55 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/auto_rebake.rs b/crates/engine/src/auto_rebake.rs index 039a3878..800eb514 100644 --- a/crates/engine/src/auto_rebake.rs +++ b/crates/engine/src/auto_rebake.rs @@ -20,7 +20,7 @@ use texturecraft_bake::Progress; use texturecraft_core::BakedMap; use crate::bake_cmds::BakeTask; -use crate::commands::{CommandSpec, always, bad, boolp, strp}; +use crate::commands::{CommandSpec, always, bad, boolp}; use crate::{Result, Session, cmd}; /// Which map rebakes itself, and what each texture set was last baked from. @@ -114,15 +114,25 @@ impl Session { } /// Records a finished bake: when it made the Auto-rebake map, the set is up to date. - pub(crate) fn note_baked(&mut self, ts: usize, made: impl Iterator) { + pub(crate) fn note_baked(&mut self, ts: usize, mut made: impl Iterator) { let key = self.auto_rebake.pending.remove(&ts); if let (Some(key), Some(map)) = (key, self.auto_rebake.map) - && made.into_iter().any(|m| m == map) + && made.any(|m| m == map) { self.auto_rebake.seen.insert(ts, key); } } + /// Records bakes of `sets` that were cancelled, failed or never started: Auto-rebake leaves + /// those sets alone until their bake inputs change again, instead of retrying every frame. + pub fn bake_abandoned(&mut self, sets: impl IntoIterator) { + for ts in sets { + if let Some(key) = self.auto_rebake.pending.remove(&ts).or_else(|| self.bake_inputs_key(ts)) { + self.auto_rebake.seen.insert(ts, key); + } + } + } + /// Bakes every due set's Auto-rebake map now (blocking); returns the sets. pub fn auto_rebake_now(&mut self, cpu: bool) -> Result> { let due = self.auto_rebake_due(); @@ -152,8 +162,6 @@ fn auto_rebake(s: &mut Session, p: &Value) -> Result { if s.auto_rebake.map != Some(map) { s.auto_rebake = AutoRebake { map: Some(map), ..AutoRebake::default() }; } - } else if strp(p, "map").is_some() { - return Err(bad("bake.autoRebake", "`map` must be a map id or null")); } Ok(state(s)) } diff --git a/crates/engine/tests/auto_rebake.rs b/crates/engine/tests/auto_rebake.rs index c4fe8644..9775c19c 100644 --- a/crates/engine/tests/auto_rebake.rs +++ b/crates/engine/tests/auto_rebake.rs @@ -8,7 +8,7 @@ use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute}; /// A plane with a high poly just above it, baked once with height and opacity. -fn baked_session() -> (Session, std::path::PathBuf) { +fn baked_session(tag: &str) -> (Session, std::path::PathBuf) { let mesh = primitives::builtin("plane").unwrap(); let mut obj = String::from("o Part_high\n"); for p in &mesh.positions { @@ -17,7 +17,7 @@ fn baked_session() -> (Session, std::path::PathBuf) { for t in mesh.indices.chunks_exact(3) { obj += &format!("f {} {} {}\n", t[0] + 1, t[1] + 1, t[2] + 1); } - let dir = std::env::temp_dir().join(format!("tc_auto_rebake_{}", std::process::id())); + let dir = std::env::temp_dir().join(format!("tc_auto_rebake_{tag}_{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("hp.obj"); std::fs::write(&path, obj).unwrap(); @@ -38,7 +38,7 @@ fn image(s: &Session, map: BakedMap) -> Arc> { #[test] fn a_changed_bake_input_rebakes_only_the_chosen_map() { - let (mut s, dir) = baked_session(); + let (mut s, dir) = baked_session("rebake"); // Off by default; nothing is due and the run command says what to do first. assert_eq!(execute(&mut s, "bake.autoRebake", &Value::Null).unwrap()["map"], Value::Null); assert!(execute(&mut s, "bake.autoRebake.run", &Value::Null).is_err()); @@ -83,6 +83,33 @@ fn a_changed_bake_input_rebakes_only_the_chosen_map() { let _ = std::fs::remove_dir_all(dir); } +#[test] +fn a_cancelled_or_failed_bake_is_not_queued_again_until_the_inputs_change() { + let (mut s, dir) = baked_session("cancel"); + execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap(); + assert!(due(&mut s).is_empty()); + execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.2 })).unwrap(); + assert_eq!(due(&mut s), [0]); + + // What the app does: start the bake, cancel it, record the abandoned bake. + s.begin_bake(0); + let mut task = s.bake_task_for(0, Some(BakedMap::Height)).unwrap(); + task.tracer = None; + let progress = texturecraft_engine::bake::Progress::new(); + progress.cancel(); + assert!(task.run(&progress).is_err(), "a cancelled bake fails"); + s.bake_abandoned([0]); + assert!(due(&mut s).is_empty(), "not queued again on the next frame"); + + // The next change makes it due again; a bake that never started (queued behind a failed + // one) is recorded the same way. + execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.3 })).unwrap(); + assert_eq!(due(&mut s), [0]); + s.bake_abandoned([0]); + assert!(due(&mut s).is_empty()); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn a_set_without_the_map_baked_is_left_alone() { let mut s = Session::new_project("t", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e7261b22..588986d3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -190,19 +190,19 @@ impl TextureCraftApp { let ts = *ts; job.current = None; if let Err(e) = self.session.apply_bake(ts, out) { + self.session.bake_abandoned([ts]); self.toast(e.to_string(), true); } } Ok(Err(e)) => { - job.current = None; let msg = e.to_string(); - self.bake = None; + self.cancel_bake(); self.toast(msg, true); return; } Err(std::sync::mpsc::TryRecvError::Empty) => return, Err(std::sync::mpsc::TryRecvError::Disconnected) => { - self.bake = None; + self.cancel_bake(); self.toast(i18n::tr("The bake worker stopped"), true); return; } @@ -226,7 +226,10 @@ impl TextureCraftApp { job.current = Some((ts, progress, rx)); } } - Err(e) => self.toast(e.to_string(), true), + Err(e) => { + self.session.bake_abandoned([ts]); + self.toast(e.to_string(), true); + } } } } @@ -244,12 +247,14 @@ impl TextureCraftApp { } } + /// Stops the bake job (also after an error). The set being baked and the queued ones wait for + /// their next bake input change before Auto-rebake tries them again. pub fn cancel_bake(&mut self) { - if let Some(job) = self.bake.take() - && let Some((_, p, _)) = job.current - { + let Some(job) = self.bake.take() else { return }; + if let Some((_, p, _)) = &job.current { p.cancel.store(true, Ordering::Relaxed); } + self.session.bake_abandoned(job.current.map(|(ts, ..)| ts).into_iter().chain(job.queue)); } /// Resize texture set `ts` to `resolution` on a worker thread (the document changes when From d71cdfa3ca9f400f476c85a334bf5153b7861ecd Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:35:32 +0700 Subject: [PATCH 41/46] 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 60428ef1c014100021100b548b85332b5cd3511f Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:39:07 +0700 Subject: [PATCH 42/46] Auto-rebake: register its commands before the bake commands Keeps the line clear of the one MaterialX import adds after the bake commands, so the two pull requests merge without a conflict. --- crates/engine/src/commands.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 3692cf6d..bca289cb 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -66,8 +66,8 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::uv_tile_cmds::specs()); v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); - v.extend(crate::bake_cmds::specs()); v.extend(crate::auto_rebake::specs()); + v.extend(crate::bake_cmds::specs()); v.extend(crate::file_cmds::specs()); v.extend(crate::preset_cmds::specs()); v.extend(crate::resource_cmds::specs()); From 410cf3a14f8a4d17f01a1c703ac98a3642023dcd Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:48:32 +0700 Subject: [PATCH 43/46] 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 44/46] 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 45/46] 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 46/46] 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.