PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Intel Iris Xe on DX12: no more red blocks in brush previews and tool icons (#6790)
Higgs325847b32097e2a9e
diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rsindex c0f93bd31..a866eedf4 100644--- a/apps/photocraft/src/main.rs+++ b/apps/photocraft/src/main.rs@@ -544,6 +544,9 @@ fn main() -> eframe::Result {info.canvas = "cpu".into();if let Some(rs) = cc.wgpu_render_state.clone() {app.perf.gpu_info.set_adapter(&rs.adapter.get_info());+ // Every egui texture uploads through this adapter, whichever canvas draws:+ // Iris Xe on DX12 shows stale memory in all-zero texels (texel_guard.rs).+ photocraft_ui_egui::texel_guard::install(&cc.egui_ctx, &rs.adapter.get_info());let software_window = rs.adapter.get_info().device_type == eframe::wgpu::DeviceType::Cpu;if software_window && mode != photocraft_engine::prefs::RenderingMode::Cpu {app.perf.gpu_info.fallback = Some("No compatible hardware graphics adapter; using software graphics.".into());diff --git a/crates/gpu/examples/zero_block_probe.rs b/crates/gpu/examples/zero_block_probe.rsnew file mode 100644index 000000000..873a929f8--- /dev/null+++ b/crates/gpu/examples/zero_block_probe.rs@@ -0,0 +1,182 @@+//! Probe: do textures uploaded like egui-wgpu's (TEXTURE_BINDING | COPY_DST, one full+//! `write_texture`) read back exactly what was written? Uploads mostly-transparent images with a+//! few opaque texels, samples every texel in a render pass, reads the target back and counts+//! texels that differ. Between uploads it frees render targets cleared to red, so stale memory is+//! red if the driver hands it back without honouring the copy.+//!+//! cargo run --release -p photocraft-gpu --example zero_block_probe -- [dx12|vulkan|gl] [rounds] [guard]++use wgpu::util::DeviceExt;++const SHADER: &str = r"+@group(0) @binding(0) var t: texture_2d<f32>;+@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {+ let p = array(vec2(-1.0, -3.0), vec2(-1.0, 1.0), vec2(3.0, 1.0));+ return vec4(p[i], 0.0, 1.0);+}+@fragment fn fs(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> {+ return textureLoad(t, vec2<i32>(p.xy), 0);+}+";++fn main() {+ let args: Vec<String> = std::env::args().collect();+ let backends = match args.get(1).map(String::as_str) {+ Some("vulkan") => wgpu::Backends::VULKAN,+ Some("gl") => wgpu::Backends::GL,+ _ => wgpu::Backends::DX12,+ };+ let rounds: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(300);+ // `guard`: transparent texels are uploaded as (0, 0, 0, 1), as `photocraft_ui_egui::texel_guard` does.+ let guard = args.get(3).is_some_and(|a| a == "guard");+ let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { backends, ..wgpu::InstanceDescriptor::new_without_display_handle() });+ let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).expect("adapter");+ let info = adapter.get_info();+ println!("adapter: {} ({:?}) driver {} {}", info.name, info.backend, info.driver, info.driver_info);+ let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).expect("device");++ let fmt = wgpu::TextureFormat::Rgba8Unorm;+ let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(SHADER.into()) });+ let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: None,+ layout: None,+ vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] },+ fragment: Some(wgpu::FragmentState {+ module: &module,+ entry_point: Some("fs"),+ compilation_options: Default::default(),+ targets: &[Some(wgpu::ColorTargetState { format: fmt, blend: None, write_mask: wgpu::ColorWrites::ALL })],+ }),+ primitive: Default::default(),+ depth_stencil: None,+ multisample: Default::default(),+ multiview_mask: None,+ cache: None,+ });++ let mut bad_textures = 0;+ let mut bad_texels = 0usize;+ for round in 0..rounds {+ // Vary the size like the brush previews and icons do.+ let (w, h) = (16 + (round as u32 * 37) % 300, 16 + (round as u32 * 13) % 60);+ // Free some red render targets first: their memory is what a not-zeroed heap hands back.+ for _ in 0..2 {+ let rt = device.create_texture(&wgpu::TextureDescriptor {+ label: Some("red-rt"),+ size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: fmt,+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,+ view_formats: &[],+ });+ let view = rt.create_view(&Default::default());+ let mut enc = device.create_command_encoder(&Default::default());+ enc.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: None,+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {+ view: &view,+ depth_slice: None,+ resolve_target: None,+ ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: 1.0, g: 0.03, b: 0.03, a: 1.0 }), store: wgpu::StoreOp::Store },+ })],+ ..Default::default()+ });+ queue.submit([enc.finish()]);+ }+ // The upload: transparent except a diagonal band of opaque grey, like a stroke strip.+ let mut px = if guard { [0u8, 0, 0, 1].repeat((w * h) as usize) } else { vec![0u8; (w * h * 4) as usize] };+ for y in 0..h {+ for x in 0..w {+ if (x as i64 * h as i64 / w as i64 - y as i64).abs() < 3 {+ let i = ((y * w + x) * 4) as usize;+ px[i..i + 4].copy_from_slice(&[200, 200, 200, 255]);+ }+ }+ }+ let tex = device.create_texture_with_data(+ &queue,+ &wgpu::TextureDescriptor {+ label: Some("egui-like"),+ size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: fmt,+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,+ view_formats: &[],+ },+ wgpu::util::TextureDataOrder::LayerMajor,+ &px,+ );+ let target = device.create_texture(&wgpu::TextureDescriptor {+ label: Some("target"),+ size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: fmt,+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,+ view_formats: &[],+ });+ let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: None,+ layout: &pipeline.get_bind_group_layout(0),+ entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&tex.create_view(&Default::default())) }],+ });+ let tview = target.create_view(&Default::default());+ let row = (w * 4).div_ceil(256) * 256;+ let buf = device.create_buffer(&wgpu::BufferDescriptor {+ label: None,+ size: u64::from(row * h),+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,+ mapped_at_creation: false,+ });+ let mut enc = device.create_command_encoder(&Default::default());+ {+ let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: None,+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {+ view: &tview,+ depth_slice: None,+ resolve_target: None,+ ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLUE), store: wgpu::StoreOp::Store },+ })],+ ..Default::default()+ });+ pass.set_pipeline(&pipeline);+ pass.set_bind_group(0, &bind, &[]);+ pass.draw(0..3, 0..1);+ }+ enc.copy_texture_to_buffer(+ wgpu::TexelCopyTextureInfo { texture: &target, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },+ wgpu::TexelCopyBufferInfo { buffer: &buf, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: None } },+ wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },+ );+ queue.submit([enc.finish()]);+ buf.slice(..).map_async(wgpu::MapMode::Read, |_| {});+ device.poll(wgpu::PollType::wait_indefinitely()).expect("poll");+ let data = buf.slice(..).get_mapped_range().expect("mapped");+ let mut bad = 0;+ let mut first = None;+ for y in 0..h {+ for x in 0..w {+ let got = &data[(y * row + x * 4) as usize..(y * row + x * 4 + 4) as usize];+ let want = &px[((y * w + x) * 4) as usize..((y * w + x) * 4 + 4) as usize];+ if got != want {+ bad += 1;+ first.get_or_insert((x, y, got.to_vec()));+ }+ }+ }+ if bad > 0 {+ bad_textures += 1;+ bad_texels += bad;+ if bad_textures <= 10 {+ println!("round {round}: {w}x{h} texture has {bad} wrong texels, first {first:?}");+ }+ }+ }+ println!("{bad_textures}/{rounds} textures read back wrong ({bad_texels} texels)");+}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex bde51ff27..e9eb4b0a7 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -204,6 +204,7 @@ pub mod swatches_ui;pub mod symmetry_ui;mod tab_strip;pub mod targa_options_ui;+pub mod texel_guard;pub mod text_field_menu;pub mod theme;pub mod tiff_options_ui;diff --git a/crates/ui-egui/src/texel_guard.rs b/crates/ui-egui/src/texel_guard.rsnew file mode 100644index 000000000..28bca7c55--- /dev/null+++ b/crates/ui-egui/src/texel_guard.rs@@ -0,0 +1,185 @@+//! Intel Iris Xe on DirectX 12: no egui texture upload carries an all-zero texel, because the+//! driver shows stale memory where it does (the red blocks in Brush Preset picker strokes and+//! around tool icons).+//!+//! wgpu creates every texture on Iris Xe as a committed resource (its workaround for+//! gfx-rs/wgpu#3552, where suballocated textures had the same symptom) and, since wgpu added it,+//! with `D3D12_HEAP_FLAG_CREATE_NOT_ZEROED`. egui-wgpu fills each new texture with one full copy,+//! so wgpu never clears it first. On this driver the copy leaves 4×4 blocks whose texels are all+//! (0, 0, 0, 0) showing whatever the memory last held, typically a freed texture's pixels. Blocks+//! with any other value upload correctly, which is why the garbage sits only in the empty corners+//! of a thumbnail, never next to what is drawn. It shows up after textures have been freed and+//! made again: scrolling the picker (stroke previews come and go), switching brush tools (the+//! options bar and toolbar icons are rasterized again).+//!+//! [`TexelGuard`] rewrites fully transparent texels in every upload as premultiplied+//! (0, 0, 0, 1) before eframe hands the upload to the renderer: alpha 1/255 black, which darkens+//! what is underneath by less than one 8-bit level. It is installed only on the affected adapter+//! ([`affected`]); `PHOTOCRAFT_TEXEL_GUARD=1` forces it on (to check it on any GPU) and `=0` off.++use std::sync::Arc;++use eframe::wgpu;+use egui::{Color32, FullOutput, ImageData, TexturesDelta};++/// What a fully transparent texel is uploaded as.+pub const NEAR_CLEAR: Color32 = Color32::from_rgba_premultiplied(0, 0, 0, 1);++/// Whether texture uploads on this adapter need the guard (`env`: `PHOTOCRAFT_TEXEL_GUARD`).+pub fn affected(info: &wgpu::AdapterInfo, env: Option<&str>) -> bool {+ match env {+ Some("1") => true,+ Some("0") => false,+ // The same adapter test wgpu uses for its #3552 workaround.+ _ => info.backend == wgpu::Backend::Dx12 && info.name.contains("Iris(R) Xe"),+ }+}++/// Rewrite the fully transparent texels of every upload in `delta` as [`NEAR_CLEAR`]; returns+/// how many changed. Images without one are not copied.+pub fn guard(delta: &mut TexturesDelta) -> usize {+ let mut changed = 0;+ for d in delta.set.values_mut().flatten() {+ let ImageData::Color(image) = &mut d.image;+ if !image.pixels.contains(&Color32::TRANSPARENT) {+ continue;+ }+ for p in &mut Arc::make_mut(image).pixels {+ if *p == Color32::TRANSPARENT {+ *p = NEAR_CLEAR;+ changed += 1;+ }+ }+ }+ changed+}++/// The egui plugin that runs [`guard`] on each frame's texture uploads.+pub struct TexelGuard;++impl egui::Plugin for TexelGuard {+ fn debug_name(&self) -> &'static str {+ "TexelGuard"+ }++ fn output_hook(&mut self, _ctx: &egui::Context, output: &mut FullOutput) {+ guard(&mut output.textures_delta);+ }+}++/// Install [`TexelGuard`] on `ctx` when the window's adapter needs it; returns whether it did.+/// Call once, with the adapter eframe renders the window with.+pub fn install(ctx: &egui::Context, info: &wgpu::AdapterInfo) -> bool {+ let on = affected(info, std::env::var("PHOTOCRAFT_TEXEL_GUARD").ok().as_deref());+ if on && ctx.plugin_opt::<TexelGuard>().is_none() {+ ctx.add_plugin(TexelGuard);+ log::info!("texture uploads: transparent texels written as alpha 1/255 ({}, {:?}; gfx-rs/wgpu#3552)", info.name, info.backend);+ }+ on+}++#[cfg(test)]+mod tests {+ use super::*;+ use egui::epaint::ImageDelta;+ use egui::{ColorImage, TextureId, TextureOptions};++ fn adapter(name: &str, backend: wgpu::Backend) -> wgpu::AdapterInfo {+ wgpu::AdapterInfo { name: name.into(), ..wgpu::AdapterInfo::new(wgpu::DeviceType::IntegratedGpu, backend) }+ }++ #[test]+ fn only_iris_xe_on_dx12_is_affected_unless_forced() {+ assert!(affected(&adapter("Intel(R) Iris(R) Xe Graphics", wgpu::Backend::Dx12), None));+ assert!(!affected(&adapter("Intel(R) Iris(R) Xe Graphics", wgpu::Backend::Vulkan), None));+ assert!(!affected(&adapter("Intel(R) UHD Graphics 620", wgpu::Backend::Dx12), None));+ assert!(!affected(&adapter("NVIDIA GeForce RTX 4070", wgpu::Backend::Dx12), None));+ assert!(affected(&adapter("NVIDIA GeForce RTX 4070", wgpu::Backend::Dx12), Some("1")));+ assert!(!affected(&adapter("Intel(R) Iris(R) Xe Graphics", wgpu::Backend::Dx12), Some("0")));+ assert!(affected(&adapter("Intel(R) Iris(R) Xe Graphics", wgpu::Backend::Dx12), Some("nonsense")));+ }++ #[test]+ fn transparent_texels_upload_as_near_clear_and_nothing_else_changes() {+ // A stroke-strip-like image: mostly transparent, a grey texel and a faint one.+ let grey = Color32::from_gray(200);+ let faint = Color32::from_rgba_premultiplied(1, 1, 1, 2);+ let mut px = vec![Color32::TRANSPARENT; 16];+ px[5] = grey;+ px[6] = faint;+ let strip = Arc::new(ColorImage::new([4, 4], px));+ let opaque = Arc::new(ColorImage::filled([2, 2], grey));+ let mut delta = TexturesDelta::default();+ delta.set.insert(TextureId::Managed(1), [ImageDelta::full(ImageData::Color(strip.clone()), TextureOptions::LINEAR)].into_iter().collect());+ delta.set.insert(TextureId::Managed(2), [ImageDelta::full(ImageData::Color(opaque.clone()), TextureOptions::LINEAR)].into_iter().collect());+ // A partial update (the font atlas grows this way) is guarded too.+ let patch = Arc::new(ColorImage::new([2, 1], vec![Color32::TRANSPARENT, grey]));+ delta.set.insert(TextureId::Managed(0), [ImageDelta::partial([3, 4], ImageData::Color(patch), TextureOptions::LINEAR)].into_iter().collect());++ assert_eq!(guard(&mut delta), 14 + 1);+ let image = |id| {+ let ImageData::Color(i) = &delta.set[&TextureId::Managed(id)][0].image;+ i.clone()+ };+ let s = image(1);+ assert!(!s.pixels.contains(&Color32::TRANSPARENT));+ assert_eq!((s.pixels[5], s.pixels[6], s.pixels[0]), (grey, faint, NEAR_CLEAR));+ // The caller's image is untouched (copy on write), and an image with nothing to change is+ // not copied at all.+ assert!(strip.pixels.contains(&Color32::TRANSPARENT));+ assert!(Arc::ptr_eq(&image(2), &opaque));+ assert_eq!(image(0).pixels, vec![NEAR_CLEAR, grey]);+ // Idempotent: a second pass finds nothing.+ assert_eq!(guard(&mut delta), 0);+ delta.clear();+ }++ #[test]+ fn near_clear_is_premultiplied_and_invisible_over_any_background() {+ // Premultiplied blend: out = src + dst × (1 − a). Over every 8-bit level the result moves+ // by at most one level.+ let a = f32::from(NEAR_CLEAR.a()) / 255.0;+ assert!(NEAR_CLEAR.r() <= NEAR_CLEAR.a() && NEAR_CLEAR.g() <= NEAR_CLEAR.a() && NEAR_CLEAR.b() <= NEAR_CLEAR.a());+ for dst in 0..=255u8 {+ let out = (f32::from(NEAR_CLEAR.r()) + f32::from(dst) * (1.0 - a)).round();+ assert!((f32::from(dst) - out).abs() <= 1.0, "{dst} -> {out}");+ }+ }++ #[test]+ fn the_plugin_guards_a_frames_uploads() {+ let ctx = egui::Context::default();+ ctx.add_plugin(TexelGuard);+ let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {+ let img = ColorImage::new([8, 8], vec![Color32::TRANSPARENT; 64]);+ let tex = ui.ctx().load_texture("texel-guard-test", img, TextureOptions::LINEAR);+ ui.image((tex.id(), egui::vec2(8.0, 8.0)));+ });+ let uploaded: Vec<_> = out+ .textures_delta+ .set+ .values()+ .flatten()+ .filter_map(|d| {+ let ImageData::Color(i) = &d.image;+ (i.size == [8, 8]).then(|| i.clone())+ })+ .collect();+ assert_eq!(uploaded.len(), 1);+ assert!(uploaded[0].pixels.iter().all(|p| *p == NEAR_CLEAR));+ out.textures_delta.clear();+ }++ #[test]+ fn install_adds_the_plugin_once_and_only_where_needed() {+ if std::env::var_os("PHOTOCRAFT_TEXEL_GUARD").is_some() {+ return;+ }+ let ctx = egui::Context::default();+ assert!(!install(&ctx, &adapter("Apple M2", wgpu::Backend::Metal)));+ assert!(ctx.plugin_opt::<TexelGuard>().is_none());+ let iris = adapter("Intel(R) Iris(R) Xe Graphics", wgpu::Backend::Dx12);+ assert!(install(&ctx, &iris) && install(&ctx, &iris));+ assert!(ctx.plugin_opt::<TexelGuard>().is_some());+ }+}diff --git a/docs/development.md b/docs/development.mdindex 67f688b6b..0c7303760 100644--- a/docs/development.md+++ b/docs/development.md@@ -119,6 +119,7 @@ By default PhotoCraft's own crates log at `info` and everything else at `warn`.| `WGPU_BACKEND=dx12` | Pick the wgpu backend(s) (`vulkan`, `dx12`, `metal`, `gl`); overrides `performance.gpuBackend` and the startup fallback || `WGPU_DX12_COMPILER=fxc` | DX12 shader compiler (`fxc`, `dxc`, `auto`); `dxc` and `auto` look `dxcompiler.dll` up through the DLL search path || `PHOTOCRAFT_GPU_TILE=2048` | Force GPU canvas tiling (tests tile seams) |+| `PHOTOCRAFT_TEXEL_GUARD=1` (or `=0`) | Force on (off) uploading egui's fully transparent texels as alpha 1/255. On by default only for Intel Iris Xe on DX12, whose driver shows stale memory in all-zero texture blocks: red squares in brush previews and tool icons (`ui-egui/src/texel_guard.rs`; check a GPU with `cargo run --release -p photocraft-gpu --example zero_block_probe -- dx12 400`) || `PHOTOCRAFT_FX_NOCACHE=1` | Bypass the CPU layer-effect map cache (`compose::effect_maps`) || `PHOTOCRAFT_CPU_COMPOSE=1` | Keep the wgpu canvas but composite on the CPU (compare GPU vs CPU renders, e.g. with the snapshot example) || `PHOTOCRAFT_LOCALE` | Override Auto's native UI language for this launch; unsupported tags use English. See [system language detection](localization.md#first-launch-and-system-language). |