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 1/5] 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 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 2/5] 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 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 3/5] 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 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 4/5] 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 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 5/5] 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.