diff --git a/crates/gpu/src/select.rs b/crates/gpu/src/select.rs index 388f189c3..7a2fcb596 100644 --- a/crates/gpu/src/select.rs +++ b/crates/gpu/src/select.rs @@ -139,7 +139,7 @@ pub fn native_backends() -> wgpu::Backends { } } -pub(crate) fn tier_of(t: wgpu::DeviceType) -> Tier { +pub fn tier_of(t: wgpu::DeviceType) -> Tier { match t { wgpu::DeviceType::Cpu => Tier::Software, wgpu::DeviceType::DiscreteGpu | wgpu::DeviceType::IntegratedGpu | wgpu::DeviceType::VirtualGpu | wgpu::DeviceType::Other => Tier::Hardware, diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rs index d11819683..8536ed6f7 100644 --- a/crates/gpu/src/view.rs +++ b/crates/gpu/src/view.rs @@ -3290,7 +3290,7 @@ fn can_reuse(ss_ready: bool, cached: Option, key: u64) -> bool { /// section, images, analysis, accessibility map, ambient occlusion and the theme's hover and /// selection tints. The same key draws the same picture (pipelines and shaders are fixed for the /// renderer). -fn frame_key(cb: &Frame) -> u64 { +pub fn frame_key(cb: &Frame) -> u64 { use std::hash::Hash as _; let mut h = std::collections::hash_map::DefaultHasher::new(); cb.product.hash(&mut h); diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index fd264d006..389a20148 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -106,24 +106,22 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { app.agent_chat.dock_space = Some(Rect::from_x_y_ranges(screen.x_range(), available.y_range())); let t = Tokens::get(); let left = app.preferences.agent_chat_side == "left"; - let side = |id: Id| Container::new(ui.ctx(), Surface::Panel).edge(id, if left { Edge::Left } else { Edge::Right }); + let host = Container::new(ui.ctx(), Surface::Panel); + let side = |id: Id| host.edge(id, if left { Edge::Left } else { Edge::Right }); if app.preferences.agent_chat_minimized { - let r = side(Id::new("sc_agent_chat_strip")) - .exact_size(STRIP) - .resizable(false) - .frame(Container::new(ui.ctx(), Surface::Panel).edge_frame(t.panel)) - .show(ui, |ui| strip(app, ui)); + let r = host + .show_edge(ui, side(Id::new("sc_agent_chat_strip")).exact_size(STRIP).resizable(false), host.edge_frame(t.panel), |ui| strip(app, ui)); app.agent_chat.drop_rect = Some(r.response.rect); show_drop_hint(app, &ctx); return; } let width = app.preferences.agent_chat_width.clamp(MIN_WIDTH, MAX_WIDTH); - let r = side(panel_id(left)) - .default_size(width) - .size_range(MIN_WIDTH..=MAX_WIDTH) - .resizable(true) - .frame(Container::new(ui.ctx(), Surface::Panel).edge_frame(t.dialog_body)) - .show(ui, |ui| ui_kit::scope(ui, |ui| body(app, ui, left))); + let r = host.show_edge( + ui, + side(panel_id(left)).default_size(width).size_range(MIN_WIDTH..=MAX_WIDTH).resizable(true), + host.edge_frame(t.dialog_body), + |ui| ui_kit::scope(ui, |ui| body(app, ui, left)), + ); crate::scenario::publish_rect("agent_chat:panel", r.response.rect); app.agent_chat.panel_rect = Some(r.response.rect); #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/blur.rs b/crates/ui-egui/src/blur.rs new file mode 100644 index 000000000..e2b68c0e7 --- /dev/null +++ b/crates/ui-egui/src/blur.rs @@ -0,0 +1,118 @@ +//! Optional viewport-only blur. Plain frames do not record markers or own effect resources. +use egui::{Color32, Frame, Painter, Rect, Shape}; +use serde::Serialize; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub enum Capability { + Available, + Unavailable(&'static str), +} + +#[derive(Clone, Copy, Debug, Default, Serialize)] +pub struct Counters { + pub textures_created: u64, + pub buffers_created: u64, + pub bind_groups_created: u64, + pub pipelines_created: u64, + pub source_passes: u64, + pub blur_passes: u64, + pub composition_passes: u64, + pub present_passes: u64, + pub markers_emitted: u64, + pub markers_drawn: u64, + pub cache_hits: u64, + pub live_bytes: u64, + pub live_textures: u64, + pub live_buffers: u64, + pub live_bind_groups: u64, + pub live_pipelines: u64, +} + +impl Counters { + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn clear_live(&mut self) { + self.live_bytes = 0; + self.live_textures = 0; + self.live_buffers = 0; + self.live_bind_groups = 0; + self.live_pipelines = 0; + } +} + +pub fn validate_radius(radius: f32) -> Result { + if radius.is_finite() && (0.0..=40.0).contains(&radius) { + Ok(radius) + } else { + Err("blur radius must be finite and between 0 and 40 physical pixels") + } +} + +/// Original Kawase schedule. Offsets are in input texels; the first level is half sized. +pub fn schedule(radius: f32) -> Option<(usize, f32)> { + if validate_radius(radius).ok()? == 0.0 { + return None; + } + let steps = if radius <= 8.0 { + 2 + } else if radius <= 18.0 { + 3 + } else if radius <= 30.0 { + 4 + } else { + 5 + }; + // Per-axis tap variance: down 1/2, up 4/3, scaled by input texel size. + // Target tap sigma = radius / 2. Resampling adds its own measurable footprint. + let variance = (35.0 / 18.0) * (4.0_f32.powi(steps as i32) - 1.0); + Some((steps, radius / (2.0 * variance.sqrt()))) +} + +#[cfg(not(target_arch = "wasm32"))] +#[path = "blur_native.rs"] +mod implementation; +#[cfg(not(target_arch = "wasm32"))] +pub use implementation::*; + +#[cfg(target_arch = "wasm32")] +mod implementation { + use super::*; + #[derive(Default)] + pub struct State { + radius: f32, + } + impl State { + pub fn install(&mut self, _: &egui_wgpu::RenderState, _: bool) {} + pub fn set_radius(&mut self, radius: f32) -> Result<(), &'static str> { + self.radius = validate_radius(radius)?; + Ok(()) + } + pub fn radius(&self) -> f32 { + self.radius + } + pub fn capability(&self) -> Capability { + Capability::Unavailable("web compositor integration unavailable") + } + pub fn capability_for(&self, _: egui::ViewportId) -> Capability { + self.capability() + } + pub fn counters(&self) -> Counters { + Counters::default() + } + pub fn begin(&mut self, _: &egui::Context, _: bool) {} + pub fn set_surface_alpha(&mut self, _: Option) {} + } + pub fn enabled() -> bool { + false + } + pub fn panel_fill(fill: Color32) -> Color32 { + fill + } + pub fn decorate(_: &Painter, _: Frame, _: Rect, shape: Shape) -> Shape { + shape + } + pub fn viewport(painter: &Painter, rect: Rect, cb: crate::gpu::ViewportCallback, _: Rect, _: [Color32; 2]) { + painter.add(egui_wgpu::Callback::new_paint_callback(rect, cb)); + } +} +#[cfg(target_arch = "wasm32")] +pub use implementation::*; diff --git a/crates/ui-egui/src/blur.wgsl b/crates/ui-egui/src/blur.wgsl new file mode 100644 index 000000000..033f4ffd6 --- /dev/null +++ b/crates/ui-egui/src/blur.wgsl @@ -0,0 +1,70 @@ +// Original SolidCraft viewport-only dual-Kawase and rounded panel composition. +struct Params { a: vec4, rect: vec4, corners: vec4, top: vec4, bottom: vec4, outside: vec4 } +@group(0) @binding(0) var image: texture_2d; +@group(0) @binding(1) var filtering: sampler; +@group(0) @binding(2) var p: Params; +struct Vertex { @builtin(position) position: vec4, @location(0) uv: vec2 } +@vertex fn vertex(@builtin(vertex_index) i: u32) -> Vertex { + let uv = vec2(f32((i << 1u) & 2u), f32(i & 2u)); + return Vertex(vec4(uv * vec2(2.0, -2.0) + vec2(-1.0, 1.0), 0.0, 1.0), uv); +} +fn linear(c: vec3) -> vec3 { + return select(c / 12.92, pow((c + vec3(0.055)) / 1.055, vec3(2.4)), c > vec3(0.04045)); +} +fn gamma(c: vec3) -> vec3 { + return select(c * 12.92, 1.055 * pow(max(c, vec3(0.0)), vec3(1.0 / 2.4)) - vec3(0.055), c > vec3(0.0031308)); +} +fn load_linear(at: vec2) -> vec4 { + let c = textureLoad(image, clamp(at, vec2(0), vec2(textureDimensions(image)) - vec2(1)), 0); + // Only the source is gamma encoded on unorm targets. It is opaque, so decoding + // each texel BEFORE bilinear interpolation avoids filtering encoded colors. + return vec4(linear(c.rgb), c.a); +} +fn sample_at(uv: vec2) -> vec4 { + if p.a.y < 0.5 { return textureSampleLevel(image, filtering, uv, 0.0); } + let q = uv * vec2(textureDimensions(image)) - vec2(0.5); + let lo = vec2(floor(q)); let f = fract(q); + return mix(mix(load_linear(lo), load_linear(lo + vec2(1, 0)), f.x), + mix(load_linear(lo + vec2(0, 1)), load_linear(lo + vec2(1, 1)), f.x), f.y); +} +@fragment fn down(v: Vertex) -> @location(0) vec4 { + let d = vec2(p.a.x) / vec2(textureDimensions(image)); + return (4.0 * sample_at(v.uv) + sample_at(v.uv + d) + sample_at(v.uv - d) + + sample_at(v.uv + d * vec2(1.0, -1.0)) + sample_at(v.uv + d * vec2(-1.0, 1.0))) / 8.0; +} +@fragment fn up(v: Vertex) -> @location(0) vec4 { + let d = vec2(p.a.x) / vec2(textureDimensions(image)); + return (sample_at(v.uv + vec2(-2.0*d.x, 0.0)) + sample_at(v.uv + vec2(2.0*d.x, 0.0)) + + sample_at(v.uv + vec2(0.0, -2.0*d.y)) + sample_at(v.uv + vec2(0.0, 2.0*d.y)) + + 2.0 * (sample_at(v.uv + d) + sample_at(v.uv - d) + + sample_at(v.uv + d * vec2(1.0, -1.0)) + sample_at(v.uv + d * vec2(-1.0, 1.0)))) / 12.0; +} +@fragment fn background(v: Vertex) -> @location(0) vec4 { + let q = v.position.xy; + var c = p.outside; + if all(q >= p.rect.xy) && all(q < p.rect.zw) && all(q >= p.corners.xy) && all(q < p.corners.zw) { + c = mix(p.top, p.bottom, clamp((q.y - p.rect.y) / max(1.0, p.rect.w - p.rect.y), 0.0, 1.0)); + } + if p.a.z > 0.5 { return vec4(linear(c.rgb), 1.0); } + return vec4(c.rgb, 1.0); +} +@fragment fn panel(v: Vertex) -> @location(0) vec4 { + let center = (p.rect.xy + p.rect.zw) * 0.5; + let half_size = (p.rect.zw - p.rect.xy) * 0.5; + let relative = v.position.xy - center; + let upper = relative.y < 0.0; + let radius = select(select(p.corners.w, p.corners.z, relative.x < 0.0), select(p.corners.y, p.corners.x, relative.x < 0.0), upper); + let r = min(radius, min(half_size.x, half_size.y)); + let d = abs(relative) - half_size + vec2(r); + let distance = min(max(d.x, d.y), 0.0) + length(max(d, vec2(0.0))) - r; + let alpha = clamp(0.5 - distance, 0.0, 1.0) * p.a.w; + let c = textureSample(image, filtering, v.position.xy / vec2(textureDimensions(image))); + // Match egui: coverage/opacity multiply gamma-premultiplied RGB BEFORE the + // framebuffer conversion. B itself remains linear, opaque viewport color. + let premultiplied_gamma = gamma(c.rgb) * alpha; + let rgb = select(premultiplied_gamma, linear(premultiplied_gamma), p.a.z > 0.5); + return vec4(rgb, alpha); +} +@fragment fn present(v: Vertex) -> @location(0) vec4 { + return textureSample(image, filtering, v.uv); +} diff --git a/crates/ui-egui/src/blur_native.rs b/crates/ui-egui/src/blur_native.rs new file mode 100644 index 000000000..84169d057 --- /dev/null +++ b/crates/ui-egui/src/blur_native.rs @@ -0,0 +1,1047 @@ +use super::*; +use crate::gpu::{Renderer as ViewRenderer, ViewportCallback}; +use egui_wgpu::{CallbackResources, CallbackTrait, FrameCompositor, ScreenDescriptor, wgpu}; +use std::cell::RefCell; +use std::hash::{Hash, Hasher}; +use std::sync::{Arc, Mutex}; + +thread_local! { static CURRENT: RefCell>> = const { RefCell::new(None) }; } +thread_local! { static SURFACE_ALPHA: std::cell::Cell> = const { std::cell::Cell::new(None) }; } +const BUDGET: u64 = 256 * 1024 * 1024; +const MAX_MARKERS: usize = 256; +type Params = [f32; 24]; + +fn capability(adapter: &wgpu::Adapter, format: wgpu::TextureFormat, split: bool, msaa: u32) -> Capability { + if solidcraft_gpu::select::tier_of(adapter.get_info().device_type) == solidcraft_gpu::select::Tier::Software { + return Capability::Unavailable("software adapter (gpu-software)"); + } + rendering_capability(adapter, format, split, msaa) +} + +fn rendering_capability(adapter: &wgpu::Adapter, format: wgpu::TextureFormat, split: bool, msaa: u32) -> Capability { + let allowed = wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC; + if !split || msaa != 1 { + Capability::Unavailable("requires a native split scene and 1x UI without depth") + } else if !matches!( + format, + wgpu::TextureFormat::Rgba8Unorm | wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Rgba8UnormSrgb | wgpu::TextureFormat::Bgra8UnormSrgb + ) || [format, wgpu::TextureFormat::Rgba16Float].iter().any(|f| { + let features = adapter.get_texture_format_features(*f); + !features.allowed_usages.contains(allowed) || !features.flags.contains(wgpu::TextureFormatFeatureFlags::FILTERABLE) + }) { + Capability::Unavailable("required renderable filterable formats unavailable") + } else { + Capability::Available + } +} + +#[derive(Clone)] +struct Host { + adapter: wgpu::Adapter, + device: wgpu::Device, + queue: wgpu::Queue, + renderer: std::sync::Weak>, + lost: egui_wgpu::DeviceLost, + format: wgpu::TextureFormat, + capability: std::sync::OnceLock, + split: bool, + msaa: u32, +} +impl Host { + fn capability(&self) -> Capability { + *self.capability.get_or_init(|| capability(&self.adapter, self.format, self.split, self.msaa)) + } +} + +pub struct State { + radius: f32, + host: Option, + active: Option>, + retired: Counters, + source_supported: bool, + failure: Option<&'static str>, + surface_alpha: Option, + last_size: Option<[u32; 2]>, + last_background: Option<[Color32; 3]>, +} + +impl Default for State { + fn default() -> Self { + Self { + radius: 0.0, + host: None, + active: None, + retired: Counters::default(), + source_supported: true, + failure: None, + surface_alpha: None, + last_size: None, + last_background: None, + } + } +} + +impl State { + pub fn install(&mut self, rs: &egui_wgpu::RenderState, split: bool) { + self.retire(); + self.failure = None; + self.host = Some(Host { + adapter: rs.adapter.clone(), + device: rs.device.clone(), + queue: rs.queue.clone(), + renderer: Arc::downgrade(&rs.renderer), + lost: rs.device_lost.clone(), + format: rs.target_format, + capability: std::sync::OnceLock::new(), + split, + msaa: rs.msaa_samples, + }); + } + + fn retire(&mut self) { + if let Some(shared) = self.active.take() { + if let Ok(mut inner) = shared.inner.lock() { + self.retired = inner.counts; + self.retired.clear_live(); + self.failure = inner.failure.or(self.failure); + inner.gpu = None; + } + if let Some(renderer) = self.host.as_ref().and_then(|h| h.renderer.upgrade()) { + renderer.write().frame_compositor = None; + } + } + } + + pub fn set_radius(&mut self, radius: f32) -> Result<(), &'static str> { + let radius = validate_radius(radius)?; + if radius != self.radius { + self.retire(); + self.radius = radius; + self.failure = None; + } + Ok(()) + } + pub fn radius(&self) -> f32 { + self.radius + } + pub fn capability(&self) -> Capability { + let base = self.base_capability(); + if base == Capability::Available && self.active.as_ref().is_some_and(|s| s.inner.lock().is_ok_and(|i| i.missing_source)) { + return Capability::Unavailable("no viewport source in the last painted frame"); + } + base + } + pub fn capability_for(&self, viewport: egui::ViewportId) -> Capability { + if viewport != egui::ViewportId::ROOT { + return Capability::Unavailable("native pop-out source integration unavailable"); + } + self.capability() + } + fn base_capability(&self) -> Capability { + let Some(host) = &self.host else { return Capability::Unavailable("no GPU host") }; + if host.lost.is_lost() { + return Capability::Unavailable("device lost"); + } + let available = host.capability(); + if available != Capability::Available { + return available; + } + if !self.source_supported { + return Capability::Unavailable("workspace has no viewport source recipe"); + } + if let Some(reason) = self.failure { + return Capability::Unavailable(reason); + } + if let Some(shared) = &self.active { + return match shared.inner.lock() { + Ok(inner) => inner.failure.map_or(Capability::Available, Capability::Unavailable), + Err(_) => Capability::Unavailable("blur state unavailable"), + }; + } + Capability::Available + } + pub fn counters(&self) -> Counters { + self.active.as_ref().and_then(|s| s.inner.lock().ok().map(|i| i.counts)).unwrap_or(self.retired) + } + #[cfg(test)] + pub(crate) fn source_texture(&self) -> Option { + let inner = self.active.as_ref()?.inner.lock().ok()?; + Some(inner.gpu.as_ref()?.source._texture.clone()) + } + #[cfg(test)] + pub(crate) fn source_geometry(&self) -> Option<[Rect; 3]> { + self.active.as_ref()?.inner.lock().ok()?.geometry + } + /// Internal capture tint only; deliberately not a user preference. + pub fn set_surface_alpha(&mut self, alpha: Option) { + self.surface_alpha = alpha; + } + + pub fn begin(&mut self, ctx: &egui::Context, source_supported: bool) -> Scope { + let previous = CURRENT.with(|c| c.replace(None)); + let alpha = SURFACE_ALPHA.with(|a| a.replace(self.surface_alpha)); + if ctx.viewport_id() != egui::ViewportId::ROOT { + return Scope { previous, alpha }; + } + self.source_supported = source_supported; + if self.radius == 0.0 { + self.retire(); + return Scope { previous, alpha }; + } + let colors = crate::theme::Tokens::get(); + let background = [colors.viewport_top, colors.viewport_bottom, colors.app_bar]; + if self.last_background != Some(background) { + let failed = self.failure.is_some() || self.active.as_ref().is_some_and(|s| s.inner.lock().is_ok_and(|i| i.failure.is_some())); + if failed { + self.retire(); + self.failure = None; + } + self.last_background = Some(background); + } + let size = ctx.content_rect().size() * ctx.pixels_per_point(); + if size.is_finite() && size.x > 0.0 && size.y > 0.0 { + let size_key = [size.x.round() as u32, size.y.round() as u32]; + if self.last_size != Some(size_key) { + self.retire(); + self.failure = None; + self.last_size = Some(size_key); + } + } + if self.base_capability() != Capability::Available || !size.is_finite() || size.x <= 0.0 || size.y <= 0.0 { + self.retire(); + return Scope { previous, alpha }; + } + let Some(host) = &self.host else { return Scope { previous, alpha } }; + let shared = self.active.get_or_insert_with(|| { + Arc::new(Shared { + host: host.clone(), + radius: self.radius, + painting_owner: std::sync::atomic::AtomicBool::new(true), + inner: Mutex::new(Inner { counts: self.retired, ..Inner::default() }), + }) + }); + if let Ok(mut inner) = shared.inner.lock() { + inner.markers.clear(); + inner.serial = inner.serial.wrapping_add(1); + inner.source_seen = false; + inner.source_count = 0; + } + if let Some(renderer) = host.renderer.upgrade() { + renderer.write().frame_compositor = Some(shared.clone()); + } + CURRENT.with(|c| *c.borrow_mut() = Some(shared.clone())); + Scope { previous, alpha } + } +} + +/// Select production policy or bypass only its software rejection for rendering fixtures. +#[cfg(test)] +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum FixturePolicy { + Production, + Rendering, +} + +#[cfg(test)] +pub(crate) fn fixture_state( + adapter: &wgpu::Adapter, + device: &wgpu::Device, + queue: &wgpu::Queue, + renderer: &Arc>, + format: wgpu::TextureFormat, + policy: FixturePolicy, +) -> State { + State { + radius: 0.0, + host: Some(Host { + adapter: adapter.clone(), + device: device.clone(), + queue: queue.clone(), + renderer: Arc::downgrade(renderer), + lost: egui_wgpu::DeviceLost::watch(device), + format, + capability: match policy { + FixturePolicy::Production => std::sync::OnceLock::new(), + FixturePolicy::Rendering => std::sync::OnceLock::from(rendering_capability(adapter, format, true, 1)), + }, + split: true, + msaa: 1, + }), + active: None, + retired: Counters::default(), + source_supported: true, + failure: None, + surface_alpha: None, + last_size: None, + last_background: None, + } +} + +#[cfg(test)] +pub(crate) fn fixture_budget(size: [u32; 2], steps: usize) -> Option { + target_bytes(size, steps, 16384) +} +impl Drop for State { + fn drop(&mut self) { + self.retire(); + } +} + +/// Restores the previous context even on early UI returns. No heap allocation. +pub struct Scope { + previous: Option>, + alpha: Option, +} +impl Drop for Scope { + fn drop(&mut self) { + CURRENT.with(|c| *c.borrow_mut() = self.previous.take()); + SURFACE_ALPHA.with(|a| a.set(self.alpha)); + } +} + +pub fn enabled() -> bool { + CURRENT.with(|c| c.borrow().is_some()) +} +pub fn panel_fill(fill: Color32) -> Color32 { + if fill.a() == 0 { + return fill; + } + SURFACE_ALPHA.with(|a| { + a.get().map_or(fill, |alpha| { + let [r, g, b, _] = fill.to_srgba_unmultiplied(); + Color32::from_rgba_unmultiplied(r, g, b, alpha) + }) + }) +} + +struct Shared { + host: Host, + radius: f32, + inner: Mutex, + painting_owner: std::sync::atomic::AtomicBool, +} +#[derive(Default)] +struct Inner { + gpu: Option, + markers: Vec, + counts: Counters, + failure: Option<&'static str>, + serial: u64, + source_seen: bool, + screen: Option<([u32; 2], f32)>, + missing_source: bool, + source_count: u16, + #[cfg(test)] + geometry: Option<[Rect; 3]>, +} +#[derive(Clone, Copy)] +struct Marker { + rect: Rect, + corners: egui::CornerRadius, + opacity: f32, + snap: bool, +} + +pub fn decorate(painter: &Painter, frame: Frame, content: Rect, ordinary: Shape) -> Shape { + if frame.fill.a() == 255 || frame.fill.a() == 0 || !painter.is_visible() { + return ordinary; + } + CURRENT.with(|c| { + let kept = c.borrow(); + let Some(shared) = kept.as_ref() else { return ordinary }; + if painter.ctx().viewport_id() != egui::ViewportId::ROOT { + return ordinary; + } + let rect = frame.widget_rect(content); + if !rect.is_finite() || !rect.is_positive() { + return ordinary; + } + let index = if let Ok(mut inner) = shared.inner.lock() { + if inner.markers.len() >= MAX_MARKERS { + inner.failure = Some("blur panel limit exceeded"); + inner.gpu = None; + inner.counts.clear_live(); + return ordinary; + } + let index = inner.markers.len(); + inner.markers.push(Marker { + rect, + corners: frame.corner_radius, + opacity: painter.opacity(), + snap: painter.ctx().tessellation_options(|o| o.round_rects_to_pixels), + }); + inner.counts.markers_emitted += 1; + index + } else { + return ordinary; + }; + let callback = egui_wgpu::Callback::new_paint_callback(rect, PanelMarker { shared: shared.clone(), index }); + Shape::Vec(vec![Shape::Callback(callback), ordinary]) + }) +} + +pub fn viewport(painter: &Painter, rect: Rect, cb: ViewportCallback, background: Rect, colors: [Color32; 2]) { + CURRENT.with(|c| { + if let Some(shared) = c.borrow().as_ref() { + if let Ok(mut inner) = shared.inner.lock() { + inner.source_count = inner.source_count.saturating_add(1); + } + let outside = crate::theme::Tokens::get().app_bar; + painter.add(egui_wgpu::Callback::new_paint_callback( + rect, + Source { + cb, + rect, + clip: painter.clip_rect(), + background, + colors, + outside, + context: painter.ctx().clone(), + layer: painter.layer_id(), + shared: shared.clone(), + }, + )); + } else { + painter.add(egui_wgpu::Callback::new_paint_callback(rect, cb)); + } + }); +} + +struct Source { + cb: ViewportCallback, + rect: Rect, + clip: Rect, + background: Rect, + colors: [Color32; 2], + outside: Color32, + context: egui::Context, + layer: egui::LayerId, + shared: Arc, +} +impl CallbackTrait for Source { + fn prepare( + &self, + device: &wgpu::Device, + queue: &wgpu::Queue, + screen: &ScreenDescriptor, + encoder: &mut wgpu::CommandEncoder, + resources: &mut CallbackResources, + ) -> Vec { + self.cb.prepare(device, queue, screen, encoder, resources) + } + fn finish_prepare( + &self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + resources: &mut CallbackResources, + ) -> Vec { + let Some(view) = resources.get::() else { return Vec::new() }; + if !self.shared.painting_owner.load(std::sync::atomic::Ordering::Relaxed) { + return Vec::new(); + } + // Physical surface clamping is supplied by the pass owner, not inferred from DPI. + let Ok(mut inner) = self.shared.inner.lock() else { return Vec::new() }; + let Some((size, scale)) = inner.screen else { return Vec::new() }; + let screen = ScreenDescriptor { size_in_pixels: size, pixels_per_point: scale }; + if self.shared.host.lost.is_lost() || inner.failure.is_some() { + return Vec::new(); + } + // Read once after UI emission/output processing; transforms can be set after + // this callback was emitted. The callback shape itself stays in local space. + let Some([rect, clip, background]) = self.effective_geometry() else { + inner.failure = Some("invalid viewport source geometry"); + inner.gpu = None; + inner.counts.clear_live(); + return Vec::new(); + }; + #[cfg(test)] + { + inner.geometry = Some([rect, clip, background]); + } + if self.colors.iter().any(|color| color.a() != 255) || self.outside.a() != 255 { + inner.failure = Some("translucent viewport/background source unsupported"); + inner.gpu = None; + inner.counts.clear_live(); + return Vec::new(); + } + if screen.size_in_pixels.contains(&0) || !screen.pixels_per_point.is_finite() || screen.pixels_per_point <= 0.0 { + inner.gpu = None; + inner.counts.clear_live(); + return Vec::new(); + } + if inner.source_seen || inner.source_count != 1 { + inner.failure = Some("multiple viewport sources in one frame"); + inner.gpu = None; + inner.counts.clear_live(); + return Vec::new(); + } + inner.source_seen = true; + let Some((steps, offset)) = schedule(self.shared.radius) else { return Vec::new() }; + let Some(bytes) = target_bytes(screen.size_in_pixels, steps, self.shared.host.device.limits().max_texture_dimension_2d) else { + inner.failure = Some("blur target is empty, exceeds device limits or memory budget"); + inner.gpu = None; + inner.counts.clear_live(); + return Vec::new(); + }; + let replace = inner.gpu.as_ref().is_none_or(|g| g.size != screen.size_in_pixels || g.steps != steps); + if replace { + inner.gpu = None; + inner.counts.clear_live(); + let (gpu, failure) = egui_wgpu::capture_errors(device, || { + Gpu::new(device, self.shared.host.format, screen.size_in_pixels, steps, offset, &mut inner.counts) + }); + if let Some(error) = failure { + log::warn!("blur resources refused: {error}"); + inner.failure = Some("GPU refused blur resources"); + inner.counts.clear_live(); + return Vec::new(); + } + inner.gpu = Some(gpu); + inner.counts.live_bytes += bytes; + } + let key = self.key(&screen, [rect, clip, background]); + let serial = inner.serial; + let marker_count = inner.markers.len(); + let Inner { gpu, counts, .. } = &mut *inner; + let Some(gpu) = gpu else { return Vec::new() }; + gpu.ready_serial = serial; + let (_, failed) = egui_wgpu::capture_errors(device, || gpu.grow_markers(device, marker_count, counts)); + if let Some(error) = failed { + log::warn!("blur marker resources refused: {error}"); + inner.failure = Some("GPU refused blur marker resources"); + inner.gpu = None; + inner.counts.clear_live(); + return Vec::new(); + } + if gpu.valid == Some(key) { + counts.cache_hits += 1; + return Vec::new(); + } + let params = background_params(background, clip, self.colors, self.outside, screen.pixels_per_point, self.shared.host.format.is_srgb()); + if params.iter().any(|value| !value.is_finite()) { + inner.failure = Some("invalid physical viewport source geometry"); + inner.gpu = None; + inner.counts.clear_live(); + return Vec::new(); + } + queue.write_buffer(&gpu.background.uniform, 0, &bytes_of(¶ms)); + { + let mut pass = pass(encoder, "blur_source", &gpu.source.view, wgpu::Color::BLACK); + pass.set_pipeline(&gpu.background_pipeline); + pass.set_bind_group(0, &gpu.background.group, &[]); + pass.draw(0..3, 0..1); + let viewport = pixel_rect(rect, screen.pixels_per_point, screen.size_in_pixels); + let clipped = pixel_rect(rect.intersect(clip), screen.pixels_per_point, screen.size_in_pixels); + if let (Some([x, y, w, h]), Some([cx, cy, cw, ch])) = (viewport, clipped) { + pass.set_scissor_rect(cx, cy, cw, ch); + view.paint(&self.cb.0, &mut pass, [x as f32, y as f32, w as f32, h as f32]); + } + } + counts.source_passes += 1; + for step in &gpu.chain { + let mut pass = pass(encoder, "blur_kawase", &step.target.view, wgpu::Color::TRANSPARENT); + pass.set_pipeline(if step.down { &gpu.down } else { &gpu.up }); + pass.set_bind_group(0, &step.binding.group, &[]); + pass.draw(0..3, 0..1); + counts.blur_passes += 1; + } + gpu.pending = Some(key); + Vec::new() + } + fn paint(&self, info: egui::PaintCallbackInfo, pass: &mut wgpu::RenderPass<'static>, resources: &CallbackResources) { + self.cb.paint(info, pass, resources); + } +} + +impl Source { + fn effective_geometry(&self) -> Option<[Rect; 3]> { + let transform = self.context.layer_transform_to_global(self.layer).unwrap_or(egui::emath::TSTransform::IDENTITY); + if !transform.translation.is_finite() || !transform.scaling.is_finite() || transform.scaling <= 0.0 { + return None; + } + let geometry = [self.rect, self.clip, self.background].map(|r| transform.mul_rect(r)); + (geometry.iter().all(|r| r.is_finite()) && geometry[0].is_positive()).then_some(geometry) + } + + fn key(&self, screen: &ScreenDescriptor, geometry: [Rect; 3]) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + solidcraft_gpu::view::frame_key(&self.cb.0).hash(&mut h); + for r in geometry { + [r.min.x, r.min.y, r.max.x, r.max.y].map(f32::to_bits).hash(&mut h); + } + self.colors.hash(&mut h); + self.outside.hash(&mut h); + screen.size_in_pixels.hash(&mut h); + screen.pixels_per_point.to_bits().hash(&mut h); + self.shared.radius.to_bits().hash(&mut h); + self.shared.host.format.hash(&mut h); + h.finish() + } +} + +struct PanelMarker { + shared: Arc, + index: usize, +} +impl CallbackTrait for PanelMarker { + fn paint(&self, info: egui::PaintCallbackInfo, pass: &mut wgpu::RenderPass<'static>, _: &CallbackResources) { + let Ok(mut inner) = self.shared.inner.lock() else { return }; + if !self.shared.painting_owner.load(std::sync::atomic::Ordering::Relaxed) { + return; + } + if inner.failure.is_some() || self.shared.host.lost.is_lost() { + return; + } + let Some(marker) = inner.markers.get(self.index).copied() else { return }; + let Some(gpu) = inner.gpu.as_ref() else { return }; + if gpu.ready_serial != inner.serial || !inner.source_seen { + return; + } + let Some(binding) = gpu.markers.get(self.index) else { return }; + let mut p = [0.0; 24]; + p[2] = u8::from(self.shared.host.format.is_srgb()) as f32; + p[3] = marker.opacity; + let r = info.viewport; + if !r.is_finite() || !r.is_positive() { + return; + } + p[4..8].copy_from_slice(&[ + r.min.x * info.pixels_per_point, + r.min.y * info.pixels_per_point, + r.max.x * info.pixels_per_point, + r.max.y * info.pixels_per_point, + ]); + if marker.snap { + for value in &mut p[4..8] { + *value = value.round(); + } + } + let scale = info.pixels_per_point * r.width() / marker.rect.width(); + if !scale.is_finite() || p[4..8].iter().any(|v| !v.is_finite()) { + return; + } + p[8..12].copy_from_slice(&[marker.corners.nw, marker.corners.ne, marker.corners.sw, marker.corners.se].map(|v| f32::from(v) * scale)); + if p.iter().any(|value| !value.is_finite()) { + return; + } + // A distinct retained uniform per marker: queue writes never alias another marker's draw. + self.shared.host.queue.write_buffer(&binding.uniform, 0, &bytes_of(&p)); + pass.set_viewport(0.0, 0.0, gpu.size[0] as f32, gpu.size[1] as f32, 0.0, 1.0); + pass.set_pipeline(&gpu.panel); + pass.set_bind_group(0, &binding.group, &[]); + pass.draw(0..3, 0..1); + inner.counts.markers_drawn += 1; + } +} + +impl FrameCompositor for Shared { + fn begin_viewport(&self, viewport: u64) { + self.painting_owner.store(viewport == egui::ViewportId::ROOT.0.value(), std::sync::atomic::Ordering::Relaxed); + } + fn screen(&self, screen: &ScreenDescriptor, _: &mut CallbackResources) { + if !self.painting_owner.load(std::sync::atomic::Ordering::Relaxed) { + return; + } + if let Ok(mut inner) = self.inner.lock() { + inner.screen = Some((screen.size_in_pixels, screen.pixels_per_point)); + } + } + fn suspend(&self) { + if !self.host.lost.is_lost() && !self.painting_owner.load(std::sync::atomic::Ordering::Relaxed) { + return; + } + if let Ok(mut inner) = self.inner.lock() { + inner.gpu = None; + inner.counts.clear_live(); + inner.source_seen = false; + } + } + fn render( + &self, + renderer: &egui_wgpu::Renderer, + encoder: &mut wgpu::CommandEncoder, + target: &wgpu::TextureView, + jobs: &[egui::ClippedPrimitive], + screen: &ScreenDescriptor, + clear: [f32; 4], + ) -> bool { + if self.host.lost.is_lost() { + return false; + } + if !self.painting_owner.load(std::sync::atomic::Ordering::Relaxed) { + return false; + } + let (composition, pipeline, binding) = { + let Ok(mut inner) = self.inner.lock() else { return false }; + if !inner.source_seen { + inner.missing_source = true; + inner.gpu = None; + inner.counts.clear_live(); + return false; + } + inner.missing_source = false; + if inner.failure.is_some() { + return false; + } + let Some(gpu) = inner.gpu.as_ref() else { return false }; + if gpu.ready_serial != inner.serial || gpu.size != screen.size_in_pixels { + return false; + } + let data = (gpu.composition.view.clone(), gpu.present.clone(), gpu.presentation.group.clone()); + inner.counts.composition_passes += 1; + data + }; + { + let color = wgpu::Color { r: clear[0] as f64, g: clear[1] as f64, b: clear[2] as f64, a: clear[3] as f64 }; + let mut ui = pass(encoder, "blur_ui_composition", &composition, color); + renderer.render(&mut ui, jobs, screen); + } + { + let mut present = pass(encoder, "blur_present", target, wgpu::Color::TRANSPARENT); + present.set_pipeline(&pipeline); + present.set_bind_group(0, &binding, &[]); + present.draw(0..3, 0..1); + } + if let Ok(mut inner) = self.inner.lock() { + inner.counts.present_passes += 1; + } + true + } + fn submitted(&self) { + if !self.painting_owner.load(std::sync::atomic::Ordering::Relaxed) { + return; + } + if let Ok(mut inner) = self.inner.lock() { + if self.host.lost.is_lost() { + inner.gpu = None; + inner.counts.clear_live(); + inner.failure = Some("device lost"); + } else if let Some(gpu) = inner.gpu.as_mut() + && let Some(key) = gpu.pending.take() + { + gpu.valid = Some(key); + } + } + } +} + +struct Target { + _texture: wgpu::Texture, + view: wgpu::TextureView, +} +struct Binding { + uniform: wgpu::Buffer, + group: wgpu::BindGroup, +} +struct Step { + target: Target, + binding: Binding, + down: bool, +} +struct Gpu { + size: [u32; 2], + steps: usize, + source: Target, + composition: Target, + chain: Vec, + background: Binding, + presentation: Binding, + markers: Vec, + background_pipeline: wgpu::RenderPipeline, + down: wgpu::RenderPipeline, + up: wgpu::RenderPipeline, + panel: wgpu::RenderPipeline, + present: wgpu::RenderPipeline, + layout: wgpu::BindGroupLayout, + sampler: wgpu::Sampler, + valid: Option, + pending: Option, + ready_serial: u64, +} + +fn bytes_of(params: &Params) -> [u8; 96] { + let mut bytes = [0; 96]; + for (out, value) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(params) { + out.copy_from_slice(&value.to_le_bytes()); + } + bytes +} + +fn target_bytes(size: [u32; 2], steps: usize, max: u32) -> Option { + let [w, h] = size; + if w == 0 || h == 0 || w > max || h > max || !(2..=5).contains(&steps) { + return None; + } + // S/C are four-byte UI textures; every down/up target is linear RGBA16F. + let mut total = u64::from(w).checked_mul(u64::from(h))?.checked_mul(8)?; + let mut dims = size; + for _ in 0..steps { + dims = dims.map(|d| d.div_ceil(2)); + total = total.checked_add(u64::from(dims[0]).checked_mul(u64::from(dims[1]))?.checked_mul(8)?)?; + } + dims = size; + for _ in 0..steps { + total = total.checked_add(u64::from(dims[0]).checked_mul(u64::from(dims[1]))?.checked_mul(8)?)?; + dims = dims.map(|d| d.div_ceil(2)); + } + (total <= BUDGET).then_some(total) +} + +fn pixel_rect(rect: Rect, scale: f32, size: [u32; 2]) -> Option<[u32; 4]> { + if !rect.is_finite() || !rect.is_positive() || !scale.is_finite() || scale <= 0.0 { + return None; + } + let x = (rect.min.x * scale).round().clamp(0.0, size[0] as f32) as u32; + let y = (rect.min.y * scale).round().clamp(0.0, size[1] as f32) as u32; + let right = (rect.max.x * scale).round().clamp(x as f32, size[0] as f32) as u32; + let bottom = (rect.max.y * scale).round().clamp(y as f32, size[1] as f32) as u32; + (right > x && bottom > y).then_some([x, y, right - x, bottom - y]) +} + +fn background_params(rect: Rect, clip: Rect, colors: [Color32; 2], outside: Color32, scale: f32, srgb: bool) -> Params { + let mut p = [0.0; 24]; + p[2] = u8::from(srgb) as f32; + p[4..8].copy_from_slice(&[rect.min.x * scale, rect.min.y * scale, rect.max.x * scale, rect.max.y * scale]); + p[8..12].copy_from_slice(&[clip.min.x * scale, clip.min.y * scale, clip.max.x * scale, clip.max.y * scale]); + for (out, color) in p[12..24].as_chunks_mut::<4>().0.iter_mut().zip(colors.into_iter().chain([outside])) { + out.copy_from_slice(&color.to_normalized_gamma_f32()); + } + p +} + +fn pass(encoder: &mut wgpu::CommandEncoder, label: &'static str, view: &wgpu::TextureView, clear: wgpu::Color) -> wgpu::RenderPass<'static> { + encoder + .begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some(label), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(clear), store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }) + .forget_lifetime() +} + +impl Gpu { + fn new(device: &wgpu::Device, format: wgpu::TextureFormat, size: [u32; 2], steps: usize, offset: f32, counts: &mut Counters) -> Self { + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("blur bindings"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: std::num::NonZeroU64::new(96), + }, + count: None, + }, + ], + }); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("blur clamp"), + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("SolidCraft blur"), + source: wgpu::ShaderSource::Wgsl(include_str!("blur.wgsl").into()), + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("blur pipeline layout"), + bind_group_layouts: &[Some(&layout)], + immediate_size: 0, + }); + let background_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("blur background uniform only"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: std::num::NonZeroU64::new(96), + }, + count: None, + }], + }); + let background_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("blur source cannot sample composition"), + bind_group_layouts: &[Some(&background_layout)], + immediate_size: 0, + }); + let pipeline = |entry: &str, target, blend, layout: &wgpu::PipelineLayout| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(entry), + layout: Some(layout), + vertex: wgpu::VertexState { module: &module, entry_point: Some("vertex"), buffers: &[], compilation_options: Default::default() }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some(entry), + targets: &[Some(wgpu::ColorTargetState { format: target, blend, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }) + }; + let down = pipeline("down", wgpu::TextureFormat::Rgba16Float, None, &pipeline_layout); + let up = pipeline("up", wgpu::TextureFormat::Rgba16Float, None, &pipeline_layout); + let panel = pipeline("panel", format, Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), &pipeline_layout); + let present = pipeline("present", format, None, &pipeline_layout); + let background_pipeline = pipeline("background", format, None, &background_pipeline_layout); + counts.pipelines_created += 5; + counts.live_pipelines += 5; + let source = Target::new(device, size, format, counts); + let composition = Target::new(device, size, format, counts); + let background = Binding::background(device, &background_layout, counts); + let presentation = Binding::new(device, &layout, &sampler, &composition.view, [0.0; 24], counts); + let mut chain: Vec = Vec::new(); + let mut dimensions = Vec::with_capacity(steps + 1); + dimensions.push(size); + for _ in 0..steps { + let last = dimensions.last().copied().unwrap_or(size); + dimensions.push(last.map(|d| d.div_ceil(2))); + } + for (index, dims) in dimensions.iter().skip(1).enumerate() { + let input = chain.last().map_or(&source.view, |s| &s.target.view); + let mut p = [0.0; 24]; + p[0] = offset; + p[1] = u8::from(index == 0 && !format.is_srgb()) as f32; + let binding = Binding::new(device, &layout, &sampler, input, p, counts); + let target = Target::new(device, *dims, wgpu::TextureFormat::Rgba16Float, counts); + chain.push(Step { target, binding, down: true }); + } + for dims in dimensions.iter().take(steps).rev() { + let input = chain.last().map_or(&source.view, |s| &s.target.view); + let mut p = [0.0; 24]; + p[0] = offset; + let binding = Binding::new(device, &layout, &sampler, input, p, counts); + let target = Target::new(device, *dims, wgpu::TextureFormat::Rgba16Float, counts); + chain.push(Step { target, binding, down: false }); + } + Self { + size, + steps, + source, + composition, + chain, + background, + presentation, + markers: Vec::new(), + background_pipeline, + down, + up, + panel, + present, + layout, + sampler, + valid: None, + pending: None, + ready_serial: 0, + } + } + fn grow_markers(&mut self, device: &wgpu::Device, count: usize, counts: &mut Counters) { + let Some(last) = self.chain.last() else { return }; + while self.markers.len() < count { + self.markers.push(Binding::new(device, &self.layout, &self.sampler, &last.target.view, [0.0; 24], counts)); + } + } +} + +impl Target { + fn new(device: &wgpu::Device, size: [u32; 2], format: wgpu::TextureFormat, counts: &mut Counters) -> Self { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("blur target"), + size: wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + counts.textures_created += 1; + counts.live_textures += 1; + let view = texture.create_view(&Default::default()); + Self { _texture: texture, view } + } +} +impl Binding { + fn background(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, counts: &mut Counters) -> Self { + let uniform = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("blur background parameters"), + size: 96, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + counts.buffers_created += 1; + counts.live_buffers += 1; + counts.live_bytes += 96; + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("blur background has no input texture"), + layout, + entries: &[wgpu::BindGroupEntry { binding: 2, resource: uniform.as_entire_binding() }], + }); + counts.bind_groups_created += 1; + counts.live_bind_groups += 1; + Self { uniform, group } + } + fn new( + device: &wgpu::Device, + layout: &wgpu::BindGroupLayout, + sampler: &wgpu::Sampler, + view: &wgpu::TextureView, + params: Params, + counts: &mut Counters, + ) -> Self { + use wgpu::util::DeviceExt as _; + let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("blur parameters"), + contents: &bytes_of(¶ms), + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + }); + counts.buffers_created += 1; + counts.live_buffers += 1; + counts.live_bytes += 96; + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("blur sample"), + layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(view) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(sampler) }, + wgpu::BindGroupEntry { binding: 2, resource: uniform.as_entire_binding() }, + ], + }); + counts.bind_groups_created += 1; + counts.live_bind_groups += 1; + Self { uniform, group } + } +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index b775aebb5..d2e9994ba 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -555,6 +555,43 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> let f = |k: &str| p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()); let b = |k: &str| p.get(k).and_then(Value::as_bool).unwrap_or(false); match method { + "ui.blur" => { + // Internal rendering harness; deliberately no saved preference or product UI. + let radius = if let Some(radius) = p.get("radius_px") { + let Some(radius) = radius.as_f64().filter(|v| v.is_finite() && (0.0..=40.0).contains(v)) else { + return err("radius_px must be finite and between 0 and 40"); + }; + Some(radius as f32) + } else { + None + }; + let alpha = if let Some(alpha) = p.get("surface_alpha") { + let alpha = if alpha.is_null() { + None + } else { + let Some(alpha) = alpha.as_f64().filter(|v| v.is_finite() && (0.0..=1.0).contains(v)) else { + return err("surface_alpha must be null or between 0 and 1"); + }; + Some((alpha * 255.0).round() as u8) + }; + Some(alpha) + } else { + None + }; + if let Some(radius) = radius { + if let Err(error) = app.blur.set_radius(radius) { + return err(error); + } + ctx.request_repaint(); + } + if let Some(alpha) = alpha { + app.blur.set_surface_alpha(alpha); + ctx.request_repaint(); + } + ok( + json!({"radius_px":app.blur.radius(), "max_radius_px":40, "capability":app.blur.capability_for(ctx.viewport_id()), "counters":app.blur.counters()}), + ) + } "ui.status_fixture" => wrap(crate::viewport_status_fixture::control(app, p)), "ui.workspace" => { if let Some(workspace) = s("workspace") { @@ -1370,6 +1407,27 @@ pub(crate) fn write_screenshot(image: &egui::ColorImage, path: &str) -> Result<( #[cfg(test)] mod tests { + #[test] + fn blur_control_validates_before_mutation_and_reports_no_gpu() { + let mut h = crate::scenario::Harness::new(); + for invalid in [json!(-1), json!(41), json!("18"), json!(null)] { + let reply = h.call("ui.blur", json!({"radius_px":invalid})); + assert_eq!(reply["ok"], false, "{reply}"); + assert_eq!(h.app.blur.radius(), 0.0); + } + let reply = h.call("ui.blur", json!({"radius_px":18,"surface_alpha":2})); + assert_eq!(reply["ok"], false); + assert_eq!(h.app.blur.radius(), 0.0); + let reply = h.call("ui.blur", json!({"radius_px":18,"surface_alpha":0.7})); + assert_eq!(reply["ok"], true); + assert!(matches!(h.app.blur.capability(), crate::blur::Capability::Unavailable(_))); + h.frames(2); + assert_eq!(h.app.blur.counters().textures_created, 0); + assert_eq!(h.app.blur.counters().markers_emitted, 0); + h.call("ui.blur", json!({"radius_px":0,"surface_alpha":null})); + assert_eq!(h.app.blur.radius(), 0.0); + } + use serde_json::json; use solidcraft_engine::{Sel, Session}; diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index d9cd92072..a85469404 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -646,6 +646,451 @@ impl OffscreenFrames { #[cfg(test)] mod tests { + #[test] + fn blur_radius_schedule_and_hostile_values() { + use crate::blur::{schedule, validate_radius}; + for radius in [f32::NAN, f32::INFINITY, -1.0, 40.01] { + assert!(validate_radius(radius).is_err()); + assert!(schedule(radius).is_none()); + } + assert!(schedule(0.0).is_none()); + for (radius, steps) in [(1.0, 2), (8.0, 2), (9.0, 3), (18.0, 3), (19.0, 4), (30.0, 4), (31.0, 5), (40.0, 5)] { + let (actual, offset) = schedule(radius).unwrap(); + assert_eq!(actual, steps); + assert!(offset.is_finite() && offset > 0.0); + let variance = (35.0 / 18.0) * (4.0_f32.powi(steps as i32) - 1.0); + assert!((offset * variance.sqrt() - radius / 2.0).abs() < 0.0001); + } + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn blur_target_budget_rejects_empty_and_excessive_sizes() { + for size in [[0, 1], [1, 0], [u32::MAX, 2], [16384, 16384]] { + assert!(crate::blur::fixture_budget(size, 5).is_none()); + } + for steps in 2..=5 { + assert!(crate::blur::fixture_budget([1, 1], steps).is_some()); + assert!(crate::blur::fixture_budget([800, 600], steps).is_some()); + } + } + + /// Full egui GPU harness: actual app UI, callbacks, fonts, marker slots and pass owner. + /// This is intentionally distinct from model-only `ui.render`/OffscreenFrames. + #[cfg(not(target_arch = "wasm32"))] + struct BlurFixture { + app: crate::SolveApp, + ctx: egui::Context, + renderer: std::sync::Arc>, + adapter: egui_wgpu::wgpu::Adapter, + device: egui_wgpu::wgpu::Device, + queue: egui_wgpu::wgpu::Queue, + output: egui_wgpu::wgpu::Texture, + size: [u32; 2], + jobs: usize, + root_transform: egui::emath::TSTransform, + root_layer: Option, + } + + #[cfg(not(target_arch = "wasm32"))] + impl BlurFixture { + fn new(srgb: bool, policy: crate::blur::FixturePolicy) -> Option { + use super::*; + let Some((adapter, device, queue)) = offscreen_device() else { + assert!(std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "GPU adapter required for blur fixture"); + eprintln!("skipped blur fixture: no admitted adapter/device"); + return None; + }; + let format = if srgb { wgpu::TextureFormat::Rgba8UnormSrgb } else { wgpu::TextureFormat::Rgba8Unorm }; + let renderer = Arc::new(egui::epaint::mutex::RwLock::new(egui_wgpu::Renderer::new(&device, format, Default::default()))); + let mut app = crate::test_support::app_with_script(serde_json::json!({"commands":[ + {"command":"solid.box", "params":{"length":40,"width":30,"height":25}} + ]})); + app.home.open = false; + app.preferences.ambient_occlusion = false; + app.cpu_meshing = true; + app.cam.distance = 110.0; + app.cam.target = solidcraft_engine::geom::Vec3::new(20.0, 15.0, 12.5); + let window = GpuTarget { format, depth: None, samples: 1, tess: false, oit: false }; + let scene = GpuTarget { depth: Some(solidcraft_gpu::depth_format(&device, true)), ..window }; + let view = Renderer::with_window_target(&device, scene, window, None); + app.viewport.gpu = Some(view.target()); + app.viewport.draw_stats = Some(view.stats()); + renderer.write().callback_resources.insert(view); + app.blur = crate::blur::fixture_state(&adapter, &device, &queue, &renderer, format, policy); + if policy == crate::blur::FixturePolicy::Rendering { + assert_eq!(app.blur.capability(), crate::blur::Capability::Available, "blur fixture requires real rendering capabilities"); + } + let size = [800, 600]; + let output = device.create_texture(&wgpu::TextureDescriptor { + label: Some("full egui fixture"), + size: wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let ctx = crate::fonts::test_context(); + Some(Self { + app, + ctx, + renderer, + adapter, + device, + queue, + output, + size, + jobs: 0, + root_transform: egui::emath::TSTransform::IDENTITY, + root_layer: None, + }) + } + + fn frame(&mut self) -> f64 { + use super::*; + let started = std::time::Instant::now(); + // Keep local layout/input stationary, then transform only after emission. + if let Some(layer) = self.root_layer { + self.ctx.set_transform_layer(layer, egui::emath::TSTransform::IDENTITY); + } + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(self.size[0] as f32, self.size[1] as f32))), + time: Some(1.0), + focused: true, + ..Default::default() + }; + let app = &mut self.app; + let transform = self.root_transform; + let mut root_layer = None; + let mut out = self.ctx.run_ui(raw, |ui| { + root_layer = Some(ui.layer_id()); + app.logic(ui.ctx()); + app.ui(ui); + ui.ctx().set_transform_layer(ui.layer_id(), transform); + }); + self.root_layer = root_layer; + let jobs = self.ctx.tessellate(out.shapes, out.pixels_per_point); + self.jobs = jobs.len(); + let screen = egui_wgpu::ScreenDescriptor { size_in_pixels: self.size, pixels_per_point: out.pixels_per_point }; + let mut encoder = self.device.create_command_encoder(&Default::default()); + let mut renderer = self.renderer.write(); + for (id, deltas) in out.textures_delta.set.drain() { + for delta in deltas { + renderer.update_texture(&self.device, &self.queue, id, &delta); + } + } + if let Some(effect) = &renderer.frame_compositor { + effect.begin_viewport(egui::ViewportId::ROOT.0.value()); + } + let extra = renderer.update_buffers(&self.device, &self.queue, &mut encoder, &jobs, &screen); + let target = self.output.create_view(&Default::default()); + let composed = renderer + .frame_compositor + .as_ref() + .is_some_and(|effect| effect.render(&renderer, &mut encoder, &target, &jobs, &screen, [0.0, 0.0, 0.0, 1.0])); + if !composed { + let mut pass = encoder + .begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("fixture ordinary UI"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &target, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }) + .forget_lifetime(); + renderer.render(&mut pass, &jobs, &screen); + } + self.queue.submit(extra.into_iter().chain([encoder.finish()])); + if let Some(effect) = &renderer.frame_compositor { + effect.submitted(); + } + for id in out.textures_delta.free.drain() { + renderer.free_texture(&id); + } + drop(renderer); + self.device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + started.elapsed().as_secs_f64() * 1000.0 + } + + fn pixels(&self, source: bool) -> Vec { + use super::*; + let texture = if source { self.app.blur.source_texture().unwrap() } else { self.output.clone() }; + let size = texture.size(); + let stride = (size.width * 4).div_ceil(256) * 256; + let read = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("full egui readback"), + size: u64::from(stride) * u64::from(size.height), + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut encoder = self.device.create_command_encoder(&Default::default()); + encoder.copy_texture_to_buffer( + texture.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &read, + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(stride), rows_per_image: Some(size.height) }, + }, + size, + ); + self.queue.submit([encoder.finish()]); + let slice = read.slice(..); + slice.map_async(wgpu::MapMode::Read, |_| {}); + self.device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let bytes = slice.get_mapped_range().unwrap(); + bytes.chunks_exact(stride as usize).flat_map(|row| row[..size.width as usize * 4].iter().copied()).collect() + } + + fn evidence(&self, name: &str) { + let directory = std::env::var_os("SOLIDCRAFT_BLUR_EVIDENCE"); + let goldens = std::env::var_os("SOLIDCRAFT_BLUR_GOLDENS"); + if directory.is_none() && goldens.is_none() { + return; + } + let image = image::RgbaImage::from_raw(self.size[0], self.size[1], self.pixels(false)).unwrap(); + if let Some(dir) = directory { + let path = std::path::PathBuf::from(dir); + std::fs::create_dir_all(&path).unwrap(); + image.save(path.join(format!("{name}.png"))).unwrap(); + std::fs::write(path.join(format!("{name}-counters.json")), serde_json::to_vec_pretty(&self.app.blur.counters()).unwrap()).unwrap(); + } + if let Some(goldens) = goldens { + let expected = image::open(std::path::PathBuf::from(goldens).join(format!("{name}.png"))).unwrap().to_rgba8(); + assert_eq!(image.as_raw(), expected.as_raw(), "golden {name}"); + } + } + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn blur_production_policy_rejects_software_adapter() { + use crate::blur::{Capability, FixturePolicy}; + let Some(mut f) = BlurFixture::new(false, FixturePolicy::Production) else { return }; + if solidcraft_gpu::select::tier_of(f.adapter.get_info().device_type) != solidcraft_gpu::select::Tier::Software { + eprintln!("skipped software policy assertion: selected adapter is not software"); + return; + } + let unavailable = Capability::Unavailable("software adapter (gpu-software)"); + assert_eq!(f.app.blur.capability(), unavailable); + f.app.blur.set_radius(18.0).unwrap(); + for _ in 0..6 { + f.frame(); + } + assert_eq!(f.app.blur.capability(), unavailable); + let counts = f.app.blur.counters(); + assert_eq!((counts.textures_created, counts.buffers_created, counts.bind_groups_created, counts.pipelines_created), (0, 0, 0, 0)); + assert_eq!((counts.markers_emitted, counts.markers_drawn), (0, 0)); + assert_eq!(counts.live_bytes, 0); + assert!(f.app.blur.source_texture().is_none()); + assert!(f.renderer.read().frame_compositor.is_none()); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn blur_full_egui_composition() { + for srgb in [false, true] { + let Some(mut f) = BlurFixture::new(srgb, crate::blur::FixturePolicy::Rendering) else { return }; + for _ in 0..6 { + f.frame(); + } + assert_eq!(f.app.blur.capability(), crate::blur::Capability::Available); + let plain = f.pixels(false); + let plain_jobs = f.jobs; + let original_camera = f.app.cam; + let original_background = f.app.preferences.viewport_background; + let original_theme = f.app.preferences.theme.clone(); + let original_dark = f.app.ui.dark; + assert_eq!(f.app.blur.counters().textures_created, 0); + for dark in [false, true] { + f.app.preferences.theme = if dark { "dark" } else { "light" }.into(); + f.app.ui.dark = dark; + f.app.blur.set_surface_alpha(Some(180)); + f.app.cam = original_camera; + f.app.preferences.viewport_background = original_background; + f.app.blur.set_radius(0.0).unwrap(); + for _ in 0..3 { + f.frame(); + } + // The zero reference uses the same camera, view settings and panel alpha. + let zero_reference = f.pixels(false); + f.frame(); + assert_eq!(zero_reference, f.pixels(false), "stable zero reference"); + f.evidence(&format!("blur-{}-0-{}", if dark { "dark" } else { "light" }, if srgb { "srgb" } else { "unorm" })); + for radius in [8.0, 18.0, 40.0] { + f.app.cam = original_camera; + f.app.preferences.viewport_background = original_background; + f.app.blur.set_radius(radius).unwrap(); + for _ in 0..3 { + f.frame(); + } + let before = f.app.blur.counters(); + let source = f.pixels(true); + f.frame(); + let after = f.app.blur.counters(); + assert_eq!(before.source_passes, after.source_passes, "resting source"); + assert_eq!(before.blur_passes, after.blur_passes, "resting chain"); + assert!(after.cache_hits > before.cache_hits); + assert!(after.markers_drawn > before.markers_drawn); + assert_eq!(f.pixels(true), source); + // Change panels only: the immutable source must be byte-identical. + f.app.blur.set_surface_alpha(Some(120)); + f.frame(); + assert_eq!(f.pixels(true), source); + assert_eq!(f.app.blur.counters().source_passes, after.source_passes); + f.app.blur.set_surface_alpha(Some(180)); + f.frame(); + let positive = f.pixels(false); + let changed_pixels = zero_reference + .as_chunks::<4>() + .0 + .iter() + .zip(positive.as_chunks::<4>().0.iter()) + .filter(|(zero, blurred)| (0..3).any(|channel| zero[channel].abs_diff(blurred[channel]) > 1)) + .count(); + assert!(changed_pixels > 0, "radius {radius} must change RGB pixels with the same camera, alpha and theme"); + let name = format!("blur-{}-{}-{}", if dark { "dark" } else { "light" }, radius as u32, if srgb { "srgb" } else { "unorm" }); + f.evidence(&name); + let before = f.app.blur.counters(); + f.app.cam.yaw += 0.2; + f.frame(); + let after = f.app.blur.counters(); + assert_eq!(after.source_passes, before.source_passes + 1); + assert_eq!(after.blur_passes - before.blur_passes, 2 * crate::blur::schedule(radius).unwrap().0 as u64); + f.app.cam = original_camera; + f.frame(); + f.app.preferences.viewport_background = Some([3, 37, 93]); + let before = f.app.blur.counters(); + f.frame(); + let after = f.app.blur.counters(); + assert_eq!(after.source_passes, before.source_passes + 1, "background invalidation"); + assert_eq!(after.textures_created, before.textures_created, "background changes reuse storage"); + f.app.preferences.viewport_background = original_background; + f.frame(); + } + f.app.blur.set_radius(0.0).unwrap(); + for _ in 0..2 { + f.frame(); + } + assert_eq!(zero_reference, f.pixels(false), "on -> off preserves the fixed scene and tint"); + } + f.app.blur.set_surface_alpha(None); + f.app.cam = original_camera; + f.app.preferences.theme = original_theme; + f.app.ui.dark = original_dark; + // Compare two stable zero frames after resources are dropped. + for _ in 0..3 { + f.frame(); + } + let zero = f.pixels(false); + let before = f.app.blur.counters(); + for _ in 0..3 { + f.frame(); + } + assert_eq!(zero, f.pixels(false)); + assert_eq!(plain, zero, "on -> off restores the original decoded pixels"); + assert_eq!(plain_jobs, f.jobs, "plain primitive count is restored"); + assert_eq!(before.textures_created, f.app.blur.counters().textures_created); + assert_eq!(before.markers_emitted, f.app.blur.counters().markers_emitted); + assert_eq!(before.source_passes, f.app.blur.counters().source_passes); + assert_eq!(f.app.blur.counters().live_bytes, 0); + assert!(f.renderer.read().frame_compositor.is_none()); + assert!(plain.iter().any(|v| *v != 0)); + assert!(plain_jobs > 0); + } + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn blur_steady_frame_benchmark() { + let Some(mut f) = BlurFixture::new(false, crate::blur::FixturePolicy::Rendering) else { return }; + f.app.blur.set_surface_alpha(Some(180)); + let mut rows = Vec::new(); + for radius in [0.0, 18.0, 0.0] { + f.app.blur.set_radius(radius).unwrap(); + for _ in 0..6 { + f.frame(); + } + let before = f.app.blur.counters(); + let mut times: Vec = (0..30).map(|_| f.frame()).collect(); + times.sort_by(f64::total_cmp); + let after = f.app.blur.counters(); + assert_eq!(after.source_passes, before.source_passes); + assert_eq!(after.blur_passes, before.blur_passes); + rows.push(serde_json::json!({"radius_px":radius, "samples":times.len(), "min_ms":times[0], + "median_ms":(times[14] + times[15]) / 2.0, "max_ms":times[29], "before":before, "after":after})); + } + if let Some(dir) = std::env::var_os("SOLIDCRAFT_BLUR_EVIDENCE") { + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(std::path::PathBuf::from(dir).join("fixture-frame-timings.json"), serde_json::to_vec_pretty(&rows).unwrap()).unwrap(); + } + eprintln!("full egui UI/encode/GPU-completion milliseconds: {rows:?}"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn blur_suspend_releases_targets() { + let Some(mut f) = BlurFixture::new(false, crate::blur::FixturePolicy::Rendering) else { return }; + f.app.blur.set_surface_alpha(Some(180)); + f.app.blur.set_radius(18.0).unwrap(); + for _ in 0..3 { + f.frame(); + } + assert!(f.app.blur.counters().live_textures > 0); + f.renderer.read().frame_compositor.as_ref().unwrap().suspend(); + assert_eq!(f.app.blur.counters().live_bytes, 0); + f.frame(); + assert!(f.app.blur.counters().live_textures > 0); + f.app.blur.set_radius(0.0).unwrap(); + assert_eq!(f.app.blur.counters().live_textures, 0); + assert_eq!(f.app.blur.counters().live_bind_groups, 0); + assert_eq!(f.app.blur.counters().live_pipelines, 0); + assert_eq!(f.app.blur.counters().live_buffers, 0); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn blur_late_layer_transform_moves_source_and_invalidates_cache() { + let Some(mut f) = BlurFixture::new(false, crate::blur::FixturePolicy::Rendering) else { return }; + f.app.blur.set_radius(18.0).unwrap(); + f.app.blur.set_surface_alpha(Some(180)); + for _ in 0..6 { + f.frame(); + } + let local = f.app.blur.source_geometry().unwrap(); + let before = f.app.blur.counters(); + let original = f.pixels(true); + let x = (local[2].right() - 4.0).clamp(0.0, (f.size[0] - 1) as f32) as usize; + let y = local[2].center().y.clamp(0.0, (f.size[1] - 1) as f32) as usize; + let offset = (y * f.size[0] as usize + x) * 4; + let outside = crate::theme::Tokens::get().app_bar.to_array(); + assert_ne!(&original[offset..offset + 4], &outside, "probe starts in the viewport background"); + // Same local geometry/camera; applied after app.ui has emitted the callback. + let transform = egui::emath::TSTransform { translation: egui::vec2(-23.0, 17.0), scaling: 0.75 }; + f.root_transform = transform; + f.frame(); + assert_eq!(f.app.blur.source_geometry().unwrap(), local.map(|r| transform.mul_rect(r)), "viewport, clip and background all transform once"); + let after = f.app.blur.counters(); + assert_eq!(after.source_passes, before.source_passes + 1); + assert_eq!(after.blur_passes, before.blur_passes + 6); + assert_eq!(after.textures_created, before.textures_created, "placement changes reuse storage"); + assert_eq!(&f.pixels(true)[offset..offset + 4], &outside, "old location is outside the transformed clip"); + f.frame(); + assert_eq!(f.app.blur.counters().source_passes, after.source_passes, "unchanged transformed placement is cached"); + assert_eq!(f.app.blur.counters().blur_passes, after.blur_passes); + // A forced miss must still paint at the transformed location, not merely hash it. + f.app.cam.yaw += 0.1; + f.frame(); + assert_eq!(f.app.blur.counters().source_passes, after.source_passes + 1); + assert_eq!(&f.pixels(true)[offset..offset + 4], &outside); + } + /// Bodies are drawn from their plans on the GPU from the frame the evaluation shader has /// compiled, and built on the CPU until then (#4860). #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 51d3218b3..d640fd097 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -14,6 +14,7 @@ pub mod agent_chat; pub mod agent_cursor; pub mod ai_connect; pub mod bidi; +pub mod blur; pub mod bom_panel; pub mod browser; pub mod browser_canvas; @@ -505,6 +506,7 @@ pub(crate) enum EscapeOwner { } pub struct SolveApp { + pub blur: blur::State, pub(crate) viewport_status: ui_kit::StatusPresentation, pub(crate) viewport_status_fixture: viewport_status_fixture::Fixture, /// Compact browser embed: retain model panels and joint controls without application chrome. @@ -776,6 +778,7 @@ impl SolveApp { solidcraft_engine::slicer_files::clean_old(); let mut app = SolveApp { viewport_status: Default::default(), + blur: Default::default(), viewport_status_fixture: Default::default(), session, ui: UiState::default(), @@ -950,6 +953,7 @@ impl SolveApp { } fn set_wgpu_targets(&mut self, rs: &egui_wgpu::RenderState, scene: crate::gpu::GpuTarget, window: crate::gpu::GpuTarget) { + self.blur.install(rs, scene.depth.is_some() && window.depth.is_none() && window.samples == 1); #[allow(unused_mut)] // Only native hosts can wait for the startup readback. let (mut installed, stats, tess_ready) = gpu::install(rs, scene, window, !self.cpu_meshing); #[cfg(not(target_arch = "wasm32"))] @@ -2863,6 +2867,8 @@ impl SolveApp { /// Lay out the whole window. pub fn ui(&mut self, ui: &mut egui::Ui) { + let blur_source = !self.home.open && !render_workspace::result_active(self); + let _blur_scope = self.blur.begin(ui.ctx(), blur_source); value_step::set_enabled(ui.ctx(), self.preferences.step_values); canvas::set_boxes_shown(ui.ctx(), self.preferences.value_boxes_in_view); recent_colors::share(ui.ctx(), &mut self.ui.recent_colors); diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rs index c6ffcbeb7..8c2c7aae3 100644 --- a/crates/ui-egui/src/render_workspace.rs +++ b/crates/ui-egui/src/render_workspace.rs @@ -2019,7 +2019,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { } else { app.viewport.hover = None; } - crate::gpu::paint_background(ui.painter(), viewport, &preview_background(app)); + let background = preview_background(app); + crate::gpu::paint_background(ui.painter(), viewport, &background); let result = (|| -> Result<(), String> { if app.viewport.gpu.is_none() { return Err(crate::i18n::tr("render.error_gpu_preview").into()); @@ -2124,7 +2125,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { [f32::from(c.r()) / 255.0, f32::from(c.g()) / 255.0, f32::from(c.b()) / 255.0] }, }); - ui.painter().add(egui_wgpu::Callback::new_paint_callback(rect, callback)); + crate::blur::viewport(ui.painter(), rect, callback, viewport, [background.viewport_top, background.viewport_bottom]); Ok(()) })(); if let Err(error) = result { diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs index 29d1a7128..407bdf80f 100644 --- a/crates/ui-egui/src/timeline.rs +++ b/crates/ui-egui/src/timeline.rs @@ -668,18 +668,19 @@ pub fn timeline(app: &mut SolveApp, ui: &mut egui::Ui) { app.shell.history = Some(rect); crate::scenario::publish_rect("history:card", rect); let mut child = ui.new_child(UiBuilder::new().id_salt("sc_timeline").max_rect(rect)); - Container::paint_frame(ui.painter(), Container::new(ui.ctx(), Surface::Panel).frame(ui.ctx(), t.timeline, crate::frame::Side::Left), rect); + Container::paint_panel_frame( + ui.painter(), + Container::new(ui.ctx(), Surface::Panel).frame(ui.ctx(), t.timeline, crate::frame::Side::Left), + rect, + ); child.set_clip_rect(rect); timeline_contents(app, &mut child, true); } else { - let response = Container::new(ui.ctx(), Surface::Panel) - .edge("sc_timeline", Edge::Bottom) - .exact_size(40.0) - .frame(Container::new(ui.ctx(), Surface::Panel).edge_frame(t.timeline)) - .show(ui, |ui| { - timeline_contents(app, ui, false); - }); - let frame = Container::new(ui.ctx(), Surface::Panel).edge_frame(t.timeline); + let host = Container::new(ui.ctx(), Surface::Panel); + let response = host.show_edge(ui, host.edge("sc_timeline", Edge::Bottom).exact_size(40.0), host.edge_frame(t.timeline), |ui| { + timeline_contents(app, ui, false); + }); + let frame = host.edge_frame(t.timeline); Container::paint_inset(ui.painter(), response.response.rect - frame.outer_margin, frame); app.shell.history = Some(response.response.rect); crate::scenario::publish_rect("history:strip", response.response.rect); diff --git a/crates/ui-egui/src/timeline_left.rs b/crates/ui-egui/src/timeline_left.rs index dbcbcdcee..d7a9ec220 100644 --- a/crates/ui-egui/src/timeline_left.rs +++ b/crates/ui-egui/src/timeline_left.rs @@ -268,16 +268,17 @@ pub fn left_panel(app: &mut SolveApp, ui: &mut egui::Ui) { return; } // Held by a dialog, the docked panel stays allocated but empty, so the view keeps its size. - let response = Container::new(ui.ctx(), Surface::Panel) - .edge("sc_timeline_left", Edge::Left) - .exact_size(width) - .resizable(false) - .frame(Container::new(ui.ctx(), Surface::Panel).edge_frame(t.panel).inner_margin(t.space_4)) - .show(ui, |ui| { + let host = Container::new(ui.ctx(), Surface::Panel); + let response = host.show_edge( + ui, + host.edge("sc_timeline_left", Edge::Left).exact_size(width).resizable(false), + host.edge_frame(t.panel).inner_margin(t.space_4), + |ui| { if !held { left_timeline(app, ui); } - }); + }, + ); app.shell.history = Some(response.response.rect); if !held { crate::scenario::publish_rect("history:vertical", response.response.rect); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 5808ed588..5f437829d 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -1362,7 +1362,7 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { let host = Container::for_layout(layout, Surface::Chrome); let ribbon = host.edge("sc_toolbar", Edge::Top); let frame = host.edge_frame(fill); - let chrome = ribbon.exact_size(height).show_separator_line(false).frame(frame).show(ui, |ui| { + let chrome = host.show_edge(ui, ribbon.exact_size(height).show_separator_line(false), frame, |ui| { let r = if floating { Rect::from_min_max(cards.workspace.min, cards.ribbon.max) } else { frame.outer_rect(ui.max_rect()) }; let ws = if floating { cards.workspace } else { Rect::from_min_size(r.left_top(), vec2(WORKSPACE_WIDTH, ribbon_height - 1.0)) }; let ribbon_left = if floating { cards.ribbon.left() } else { ws.right() }; @@ -1371,7 +1371,7 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { let fill = if crate::render_workspace::active(app) && card == ws { crate::theme::TabAccent::current(ui.ctx()).soft } else { t.toolbar }; let frame = host.frame(ui.ctx(), fill, crate::frame::Side::Left); - ui.painter().add(frame.paint(card)); + host.paint_background(ui.painter(), frame, card); // Blank card space owns clicks as well as its buttons. ui.interact(card, ui.id().with(("shell_card", card.left().to_bits())), Sense::click_and_drag()); } diff --git a/crates/ui-egui/src/ui_kit/container.rs b/crates/ui-egui/src/ui_kit/container.rs index 1eabfa834..46947dd4b 100644 --- a/crates/ui-egui/src/ui_kit/container.rs +++ b/crates/ui-egui/src/ui_kit/container.rs @@ -5,6 +5,70 @@ use crate::frame::Side; use crate::{shell::LayoutMode, theme::Tokens}; use egui::{Color32, Context, Frame, Id, Stroke, WidgetText}; +pub(super) type Background = fn(&egui::Painter, Frame, egui::Rect, egui::Shape) -> egui::Shape; + +/// The feature sheet's deliberately restricted stock Window (no title, scrolling or fades). +/// Keep its builder private: the marker's layer and host clip are owned here. +pub(crate) struct FeatureWindow<'a> { + window: egui::Window<'a>, + id: Id, + frame: Frame, +} + +impl<'a> FeatureWindow<'a> { + pub(super) fn new(window: egui::Window<'a>, id: Id, frame: Frame) -> Self { + Self { window, id, frame } + } + + pub(crate) fn fixed_size(mut self, size: egui::Vec2) -> Self { + self.window = self.window.fixed_size(size); + self + } + + /// Borrow a caller's open flag only for this showing, retaining stock close handling. + pub(crate) fn open<'open>(self, open: &'open mut bool) -> FeatureWindow<'open> + where + 'a: 'open, + { + let window: egui::Window<'open> = self.window; + FeatureWindow { window: window.open(open), id: self.id, frame: self.frame } + } + + pub(crate) fn show(self, ctx: &Context, body: impl FnOnce(&mut egui::Ui) -> R) -> Option>> { + let background = Container::floating_card(Surface::Feature).background(ctx, self.frame); + self.show_background(ctx, background, body) + } + + pub(super) fn show_background( + self, + ctx: &Context, + background: Option, + body: impl FnOnce(&mut egui::Ui) -> R, + ) -> Option>> { + let Some(background) = background else { return self.window.show(ctx, body) }; + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Middle, self.id)); + let slot = painter.add(egui::Shape::Noop); + let mut host_painter = None; + let shown = self.window.show(ctx, |ui| { + // Resize's content clip omits the frame border/padding. This bounded Window + // uses Area's default viewport clip, with no fades or native title bar. + let mut painter = ui.painter().clone(); + painter.set_clip_rect(ctx.content_rect()); + host_painter = Some(painter); + body(ui) + }); + if let (Some(shown), Some(painter)) = (&shown, host_painter) { + // Window relocates inner_margin into an internal content Frame. Its final + // Area response still includes all margins and the original stroke width. + let content = shown.response.rect - self.frame.total_margin(); + if painter.is_visible() && painter.clip_rect().intersects(self.frame.widget_rect(content)) { + painter.set(slot, background(&painter, self.frame, content, egui::Shape::Noop)); + } + } + shown + } +} + /// Persistent panels adapt to the layout; transient UI retains its anchoring and modality. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Surface { @@ -187,6 +251,7 @@ impl Container { /// Tokenised outer chrome. Callers may supply content padding, not another card surface. pub fn frame(self, ctx: &Context, fill: Color32, side: crate::frame::Side) -> Frame { + let fill = if self.adaptive() { crate::blur::panel_fill(fill) } else { fill }; let t = Tokens::get(); let flat = Frame::NONE.fill(fill); match self.surface { @@ -220,6 +285,7 @@ impl Container { /// Surface of an allocated dock or internal pinned band. Floating card decoration is /// supplied by `frame`; edge-hosted panes must not acquire outer shadows or card gaps. pub fn edge_frame(self, fill: Color32) -> Frame { + let fill = if self.adaptive() { crate::blur::panel_fill(fill) } else { fill }; if self.adaptive() && !self.floating() { Self::compact_frame(fill, Tokens::get().primary_border(Tokens::get().border), self.joined.unwrap_or(DockEdges::ALL)) } else { @@ -261,6 +327,28 @@ impl Container { bounds: egui::Rect, body: impl FnOnce(&mut egui::Ui) -> R, ) -> egui::InnerResponse { + let background = self.background(ui.ctx(), frame); + self.show_frame_background(ui, frame, bounds, background, body) + } + + fn background(self, ctx: &Context, frame: Frame) -> Option { + // Keep the off path to boundary checks only: no painter, shape slot or allocation. + if self.adaptive() && crate::blur::enabled() && ctx.viewport_id() == egui::ViewportId::ROOT && (1..255).contains(&frame.fill.a()) { + Some(crate::blur::decorate) + } else { + None + } + } + + pub(super) fn show_frame_background( + self, + ui: &mut egui::Ui, + frame: Frame, + bounds: egui::Rect, + background: Option, + body: impl FnOnce(&mut egui::Ui) -> R, + ) -> egui::InnerResponse { + let slot = background.map(|_| ui.painter().add(egui::Shape::Noop)); let mut prepared = frame.begin(ui); let inner = body(&mut prepared.content_ui); if self.adaptive() && !self.floating() { @@ -273,6 +361,12 @@ impl Container { prepared.frame.corner_radius = Self::compact_rounding(edges); } let frame = prepared.frame; + if let (Some(background), Some(slot)) = (background, slot) + && ui.is_rect_visible(frame.widget_rect(prepared.content_ui.min_rect())) + { + let painter = ui.painter(); + painter.set(slot, background(painter, frame, prepared.content_ui.min_rect(), egui::Shape::Noop)); + } let response = prepared.end(ui); Self::paint_inset(ui.painter(), response.rect - frame.outer_margin, frame); egui::InnerResponse { inner, response } @@ -315,6 +409,17 @@ impl Container { Self::paint_inset(painter, frame.widget_rect(content), frame); } + /// Semantic manually painted workspace surface; HUDs keep `paint_frame`. + pub(crate) fn paint_background(self, painter: &egui::Painter, frame: Frame, content: egui::Rect) { + let shape = frame.paint(content); + painter.add(if self.adaptive() && crate::blur::enabled() { crate::blur::decorate(painter, frame, content, shape) } else { shape }); + } + + pub(crate) fn paint_panel_frame(painter: &egui::Painter, frame: Frame, content: egui::Rect) { + Self::floating_card(Surface::Panel).paint_background(painter, frame, content); + Self::paint_inset(painter, frame.widget_rect(content), frame); + } + /// Decorate the content-hugging frame of a popup or feature sheet after its contents. pub(crate) fn finish_content(ui: &egui::Ui, frame: Frame) { Self::paint_inset(ui.painter(), frame.widget_rect(ui.min_rect()), frame); @@ -340,6 +445,47 @@ impl Container { if self.adaptive() && !self.floating() { panel.show_separator_line(false) } else { panel } } + /// Stock Panel owns layout, persistence, interaction and its unmodified semantic Frame. + /// Only ordinary `show` is exposed; animated hosts need their own clip contract. + pub(crate) fn show_edge( + self, + ui: &mut egui::Ui, + panel: egui::Panel, + frame: Frame, + body: impl FnOnce(&mut egui::Ui) -> R, + ) -> egui::InnerResponse { + let background = self.background(ui.ctx(), frame); + Self::show_edge_background(ui, panel, frame, background, body) + } + + pub(super) fn show_edge_background( + ui: &mut egui::Ui, + panel: egui::Panel, + frame: Frame, + background: Option, + body: impl FnOnce(&mut egui::Ui) -> R, + ) -> egui::InnerResponse { + let Some(background) = background else { return panel.frame(frame).show(ui, body) }; + let slot = ui.painter().add(egui::Shape::Noop); + let mut host = None; + let shown = panel.frame(frame).show(ui, |ui| { + // Capture before the body can narrow the clip or change opacity. Frame adds + // no content clip, so this is the host/slide clip including its padding. + let painter = ui.painter().clone(); + let inner = body(ui); + host = Some((painter, ui.min_rect())); + inner + }); + if let Some((painter, content)) = host + && painter.is_visible() + && painter.clip_rect().intersects(frame.widget_rect(content)) + { + // min_rect is the actual Frame content, even if Panel clamps its response. + painter.set(slot, background(&painter, frame, content, egui::Shape::Noop)); + } + shown + } + pub(super) fn window<'a>(self, title: impl Into) -> egui::Window<'a> { egui::Window::new(title).enabled(self.input_enabled()) } diff --git a/crates/ui-egui/src/ui_kit/panel.rs b/crates/ui-egui/src/ui_kit/panel.rs index a9d3c0914..a686c4122 100644 --- a/crates/ui-egui/src/ui_kit/panel.rs +++ b/crates/ui-egui/src/ui_kit/panel.rs @@ -670,18 +670,18 @@ impl<'a> Panel<'a> { self.joined.map_or(container, |edges| container.joined(edges)).tool_frame(self.frame, right >= self.viewport.right() - 0.5) } - pub(crate) fn window(&self, ctx: &egui::Context) -> egui::Window<'a> { + pub(crate) fn window(&self, ctx: &egui::Context) -> super::container::FeatureWindow<'a> { self.window_placed(ctx, None) } /// The same window for contents the caller holds to `size` (egui's `fixed_size`); the card /// is that plus its frame. - pub(crate) fn fixed_window(&self, ctx: &egui::Context, size: egui::Vec2) -> egui::Window<'a> { + pub(crate) fn fixed_window(&self, ctx: &egui::Context, size: egui::Vec2) -> super::container::FeatureWindow<'a> { let outer = size.x + self.positioned_frame(ctx).total_margin().sum().x; self.window_placed(ctx, Some(outer)).fixed_size(size) } - fn window_placed(&self, ctx: &egui::Context, outer_width: Option) -> egui::Window<'a> { + fn window_placed(&self, ctx: &egui::Context, outer_width: Option) -> super::container::FeatureWindow<'a> { let gap = super::Container::new(ctx, super::Surface::Feature).gap(); let viewport = self.viewport; let anchor = self.bounded_anchor(ctx); @@ -701,7 +701,7 @@ impl<'a> Panel<'a> { }; // Keep drawing safe when even the header/footer cannot fit. egui clips the contents to // the remaining viewport; the normal small-height case still keeps both actions visible. - super::Container::new(ctx, super::Surface::Feature) + let window = super::Container::new(ctx, super::Surface::Feature) .window(self.title) .id(self.id) .title_bar(false) @@ -720,7 +720,8 @@ impl<'a> Panel<'a> { .default_height(0.0) .fade_in(false) .fade_out(false) - .order(egui::Order::Middle) + .order(egui::Order::Middle); + super::container::FeatureWindow::new(window, self.id, frame) } /// Feature header, scrolling padded body, pinned actions, drag target and compute status. diff --git a/crates/ui-egui/src/ui_kit/panel_tests.rs b/crates/ui-egui/src/ui_kit/panel_tests.rs index ea676ffd2..e0bf02cd4 100644 --- a/crates/ui-egui/src/ui_kit/panel_tests.rs +++ b/crates/ui-egui/src/ui_kit/panel_tests.rs @@ -4,6 +4,328 @@ use crate::ui_kit::*; use crate::{scenario, theme::Tokens}; use egui::Ui; +#[derive(Clone, Copy, Debug)] +enum BlurHost { + Frame, + Edge(Edge), + Window, +} + +const BLUR_HOSTS: [BlurHost; 6] = [ + BlurHost::Frame, + BlurHost::Edge(Edge::Left), + BlurHost::Edge(Edge::Right), + BlurHost::Edge(Edge::Top), + BlurHost::Edge(Edge::Bottom), + BlurHost::Window, +]; + +struct HostMarker { + frame: egui::Frame, + opacity: f32, +} + +fn host_marker(painter: &egui::Painter, frame: egui::Frame, content: egui::Rect, ordinary: egui::Shape) -> egui::Shape { + egui::Shape::Vec(vec![ + egui::Shape::Callback(egui::PaintCallback { + rect: frame.widget_rect(content), + callback: std::sync::Arc::new(HostMarker { frame, opacity: painter.opacity() }), + }), + ordinary, + ]) +} + +/// Compare the actual stock hosts against the app helpers without requiring a GPU. +/// mode: 0 = stock, 1 = production zero path, 2 = injected positive marker. +fn blur_host_fixture(host: BlurHost, mode: u8, position: egui::Pos2, transform: egui::emath::TSTransform) -> (egui::FullOutput, String) { + let ctx = crate::fonts::test_context(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0)); + let container = Container::for_layout(crate::shell::LayoutMode::Floating, Surface::Feature); + let frame = container + .frame(&ctx, egui::Color32::from_rgba_unmultiplied(40, 80, 100, 180), crate::frame::Side::Left) + .stroke(egui::Stroke::new(2.5, egui::Color32::WHITE)) + .inner_margin(egui::Margin { left: 9, right: 13, top: 7, bottom: 11 }) + .outer_margin(egui::Margin { left: -2, right: 3, top: -1, bottom: 4 }) + .corner_radius(egui::CornerRadius { nw: 3, ne: 7, sw: 11, se: 15 }); + let id = egui::Id::new("stock host fixture"); + let mut output = egui::FullOutput::default(); + let mut observation = String::new(); + for _ in 0..3 { + output = crate::test_support::frame(&ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + ui.multiply_opacity(0.75); + let mut body = |ui: &mut egui::Ui| { + let stack: Vec<_> = ui.stack().iter().map(|node| (node.id, node.kind(), *node.frame())).collect(); + let semantic = format!("{:?}", (ui.id(), ui.max_rect(), ui.clip_rect(), ui.stack().bg_color(), stack)); + ui.allocate_space(egui::vec2(83.0, 47.0)); + let response = ui.button("Content stays above its frame"); + // A child changing its content clip must not cut the host's padding/border. + ui.set_clip_rect(ui.clip_rect().shrink(6.0)); + observation = format!("{semantic} {:?}", (response.id, response.rect, ui.min_rect())); + }; + let background: Option = (mode == 2).then_some(host_marker); + let response = match host { + BlurHost::Frame => { + if mode == 0 { + let shown = frame.show(ui, &mut body); + Container::paint_inset(ui.painter(), shown.response.rect - frame.outer_margin, frame); + shown.response + } else if mode == 1 { + container.show_frame(ui, frame, screen, &mut body).response + } else { + container.show_frame_background(ui, frame, screen, background, &mut body).response + } + } + BlurHost::Edge(edge) => { + let panel = container.edge(id, edge).exact_size(170.0).resizable(false); + if mode == 0 { + panel.frame(frame).show(ui, &mut body).response + } else if mode == 1 { + container.show_edge(ui, panel, frame, &mut body).response + } else { + Container::show_edge_background(ui, panel, frame, background, &mut body).response + } + } + BlurHost::Window => { + let window = container + .window("Stock host fixture") + .id(id) + .title_bar(false) + .collapsible(false) + .resizable(false) + .scroll(false) + .fade_in(false) + .fade_out(false) + .constrain(false) + .fixed_pos(position) + .frame(frame); + if mode == 0 { + window.show(&ctx, &mut body).unwrap().response + } else { + let window = container::FeatureWindow::new(window, id, frame); + if mode == 1 { window.show(&ctx, &mut body) } else { window.show_background(&ctx, background, &mut body) }.unwrap().response + } + } + }; + observation.push_str(&format!(" {:?}", (response.id, response.rect))); + let layer = if matches!(host, BlurHost::Window) { egui::LayerId::new(egui::Order::Middle, id) } else { ui.layer_id() }; + ctx.set_transform_layer(layer, transform); + }); + } + (output, observation) +} + +fn blur_host_shapes(output: &egui::FullOutput, omit_markers: bool) -> Vec { + let mut shapes = Vec::new(); + for clipped in &output.shapes { + crate::test_support::each_shape(&clipped.shape, &mut |shape| { + if omit_markers && (matches!(shape, egui::Shape::Noop) || matches!(shape, egui::Shape::Callback(cb) if cb.callback.is::())) { + return; + } + shapes.push(format!("{:?} {shape:?}", clipped.clip_rect)); + }); + } + shapes +} + +#[test] +fn blur_stock_hosts_zero_has_identical_shapes_noops_geometry_and_ids() { + for host in BLUR_HOSTS { + let (stock, semantics) = blur_host_fixture(host, 0, egui::pos2(30.0, 35.0), egui::emath::TSTransform::IDENTITY); + let (off, off_semantics) = blur_host_fixture(host, 1, egui::pos2(30.0, 35.0), egui::emath::TSTransform::IDENTITY); + assert_eq!(semantics, off_semantics, "{host:?}"); + assert_eq!(blur_host_shapes(&stock, false), blur_host_shapes(&off, false), "no extra shapes, including Noop slots: {host:?}"); + } +} + +#[test] +fn blur_stock_window_open_flag_preserves_closed_close_and_reopen_behavior() { + fn record(mode: u8, omit_markers: bool) -> Vec<(Vec, String)> { + let ctx = crate::fonts::test_context(); + let container = Container::for_layout(crate::shell::LayoutMode::Floating, Surface::Feature); + let frame = container.frame(&ctx, Tokens::get().dialog_body, crate::frame::Side::Left); + let id = egui::Id::new("open flag fixture"); + let mut recorded = Vec::new(); + for (index, mut keep) in [false, false, true, true, true, false, false, false, true, true, true].into_iter().enumerate() { + let mut observation = String::new(); + let mut called = false; + let output = crate::test_support::frame(&ctx, egui::RawInput { time: Some(index as f64), ..Default::default() }, |_| { + let window = container + .window("Open flag fixture") + .id(id) + .title_bar(false) + .collapsible(false) + .resizable(false) + .scroll(false) + .fade_in(false) + .fade_out(false) + .frame(frame); + let mut body = |ui: &mut egui::Ui| { + called = true; + ui.label("Window body"); + if index == 4 { + // Window contains a closable Collapsible even with title/collapse + // controls disabled. Target the Window, not that nearer ancestor. + ui.close_kind(egui::UiKind::Window); + } + }; + let shown = if mode == 0 { + window.open(&mut keep).show(&ctx, &mut body) + } else { + // A long-lived builder must accept this frame-local mutable borrow. + let window: container::FeatureWindow<'static> = container::FeatureWindow::new(window, id, frame); + let window = window.open(&mut keep); + if mode == 1 { window.show(&ctx, &mut body) } else { window.show_background(&ctx, Some(host_marker), &mut body) } + }; + if index == 0 || index == 7 { + assert!(shown.is_none(), "initially closed and settled closed windows stay hidden"); + } + if index == 4 { + assert!(shown.as_ref().is_some_and(|shown| shown.response.should_close()), "the Window response carries the close request"); + } + observation = format!("{:?}", (keep, shown.map(|shown| (shown.response.id, shown.response.rect, shown.inner)))); + }); + if index == 0 || index == 7 { + assert!(!called); + } + if index == 4 { + assert!(!keep, "stock close requests update the caller's flag"); + } + if index == 10 { + assert!(called && keep, "the same persistent window can reopen"); + } + let mut markers = 0; + for clipped in &output.shapes { + crate::test_support::each_shape(&clipped.shape, &mut |shape| { + if matches!(shape, egui::Shape::Callback(cb) if cb.callback.is::()) { + markers += 1; + } + }); + } + if !called { + assert_eq!(markers, 0, "hidden windows emit no marker"); + } + if mode == 2 && index == 10 { + assert_eq!(markers, 1, "reopened windows regain their marker"); + } + recorded.push((blur_host_shapes(&output, omit_markers), observation)); + } + recorded + } + assert_eq!(record(0, false), record(1, false), "zero keeps stock shapes, including Noop counts and hidden windows"); + assert_eq!(record(0, true), record(2, true), "positive markers preserve stock visibility, close handling, geometry and IDs"); +} + +#[test] +fn blur_stock_hosts_marker_precedes_original_chrome_with_semantics_and_clip_intact() { + for host in BLUR_HOSTS { + let position = egui::pos2(30.0, 35.0); + let (stock, semantics) = blur_host_fixture(host, 0, position, egui::emath::TSTransform::IDENTITY); + let (marked, marked_semantics) = blur_host_fixture(host, 2, position, egui::emath::TSTransform::IDENTITY); + assert_eq!(semantics, marked_semantics, "bg_color, frame metadata, geometry and persistent IDs: {host:?}"); + assert_eq!(blur_host_shapes(&stock, true), blur_host_shapes(&marked, true), "original shadow/fill/stroke/content: {host:?}"); + let mut marker = None; + let mut fills = 0; + let mut callbacks = 0; + let mut shadows = 0; + for clipped in &marked.shapes { + crate::test_support::each_shape(&clipped.shape, &mut |shape| match shape { + egui::Shape::Callback(cb) if cb.callback.is::() => { + let info = cb.callback.downcast_ref::().unwrap(); + assert_eq!(info.frame.stroke.width, 2.5); + assert_eq!(info.opacity, if matches!(host, BlurHost::Window) { 1.0 } else { 0.75 }); + marker = Some((cb.rect, clipped.clip_rect, info.frame.corner_radius)); + callbacks += 1; + } + egui::Shape::Rect(rect) if rect.blur_width > 0.0 => { + assert!(marker.is_some(), "the marker must also precede the original shadow: {host:?}"); + shadows += 1; + } + egui::Shape::Rect(rect) if marker.is_some_and(|(r, _, _)| r == rect.rect) => { + let (_, clip, corners) = marker.unwrap(); + assert_eq!(rect.corner_radius, corners); + assert_eq!(clip, clipped.clip_rect, "use the outer host clip, including padding/border"); + assert!(clip.contains(rect.rect.center())); + fills += 1; + } + _ => {} + }); + } + assert_eq!(callbacks, 1, "{host:?}"); + assert_eq!(shadows, 1, "{host:?}"); + assert_eq!(fills, 1, "marker before the matching original fill: {host:?}"); + } +} + +#[test] +fn blur_stock_hosts_late_scaled_layers_and_moved_windows_keep_final_geometry() { + let transform = egui::emath::TSTransform { translation: egui::vec2(19.0, -7.0), scaling: 0.75 }; + for host in BLUR_HOSTS { + for position in [egui::pos2(30.0, 35.0), egui::pos2(-8.0, 135.0)] { + let (local, _) = blur_host_fixture(host, 2, position, egui::emath::TSTransform::IDENTITY); + let (moved, _) = blur_host_fixture(host, 2, position, transform); + let marker = |output: &egui::FullOutput| { + let mut result = None; + for clipped in &output.shapes { + crate::test_support::each_shape(&clipped.shape, &mut |shape| { + if let egui::Shape::Callback(cb) = shape + && cb.callback.is::() + { + result = Some((cb.rect, clipped.clip_rect)); + } + }); + } + result.unwrap() + }; + let (rect, clip) = marker(&local); + let (moved_rect, moved_clip) = marker(&moved); + assert_eq!(moved_rect, transform.mul_rect(rect), "{host:?}"); + assert_eq!(moved_clip, transform.mul_rect(clip), "host clipping transforms once: {host:?}"); + } + } +} + +#[test] +fn blur_stock_frame_marker_uses_final_joined_corner_radii() { + let ctx = crate::fonts::test_context(); + let output = crate::test_support::frame(&ctx, egui::RawInput::default(), |ui| { + let host = Container::for_layout(crate::shell::LayoutMode::Docked, Surface::Feature).joined(DockEdges::default()); + let frame = host.frame(ui.ctx(), Tokens::get().dialog_body, crate::frame::Side::Left); + let bounds = ui.available_rect_before_wrap(); + host.show_frame_background(ui, frame, bounds, Some(host_marker), |ui| { + ui.allocate_space(egui::vec2(90.0, 40.0)); + }); + }); + let mut matched = false; + for clipped in &output.shapes { + crate::test_support::each_shape(&clipped.shape, &mut |shape| { + if let egui::Shape::Callback(cb) = shape + && let Some(marker) = cb.callback.downcast_ref::() + { + assert_eq!(marker.frame.corner_radius, egui::CornerRadius { nw: 0, ne: 0, sw: 0, se: Tokens::get().radius_lg }); + matched = true; + } + }); + } + assert!(matched); +} + +#[test] +fn blur_zero_has_no_marker_or_tint_override() { + let mut state = crate::blur::State::default(); + state.set_radius(0.0).unwrap(); + let ctx = crate::fonts::test_context(); + let _scope = state.begin(&ctx, true); + assert!(!crate::blur::enabled()); + let fill = egui::Color32::from_rgba_unmultiplied(40, 80, 100, 180); + assert_eq!(crate::blur::panel_fill(fill), fill); + let original = egui::Shape::rect_filled(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(80.0, 40.0)), 9, fill); + let painter = ctx.layer_painter(egui::LayerId::background()); + let unchanged = crate::blur::decorate(&painter, egui::Frame::NONE.fill(fill), egui::Rect::NOTHING, original.clone()); + assert_eq!(format!("{original:?}"), format!("{unchanged:?}")); + assert_eq!(state.counters().markers_emitted, 0); + assert_eq!(state.counters().textures_created, 0); +} + #[test] fn checkbox_grid_and_close_header_are_clickable() { let ctx = crate::fonts::test_context(); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 49c5b33ac..57abd7ecf 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -4447,7 +4447,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { }, sky: sky_uniform(app.preferences.dark_parts_shading, proj.cam.up), }); - painter.add(egui_wgpu::Callback::new_paint_callback(rect, cb)); + crate::blur::viewport(&painter, rect, cb, rect, [t.viewport_top, t.viewport_bottom]); // The graphics card had no memory for the view's frame (#7296): say once why it looks // coarser. if !app.viewport.lowered_noted && app.viewport.draw_stats.as_ref().is_some_and(|s| s.lock().is_ok_and(|s| s.lowered)) { diff --git a/docs/blur-behind.md b/docs/blur-behind.md new file mode 100644 index 000000000..b92cbdc35 --- /dev/null +++ b/docs/blur-behind.md @@ -0,0 +1,341 @@ +# Blur behind panels (#9809) + +Implementation note for PR 5 of the #8876 series. Native implementation and +manager-run harnesses are present. No preference, product UI or default changes +are introduced. No build, test, GPU run, screenshot, benchmark or pixel comparison +has been run by this worker. Direct rustfmt is the only executable formatting work. + +## Accepted CPU budget + +The human decision is: **"Allow measured CPU checks; keep the change small."** +This replaces the spike's proposed static policy propagation and its unresolved +single-check requirement. The implementation has cheap per-host checks, a root +UI scope, and outer GPU preparation/composition/submission checks. It does **not** +claim one check per frame, two total dispatches, or measured zero CPU overhead. +There are no blur branches in `egui_wgpu::Renderer::render`'s primitive loop. +The initial source integration is for the root native viewport. The pass owner +supplies its viewport id before preparation; other native viewports use plain +painting and `capability_for` reports their missing source integration. They +cannot sample the root window's source or retain its pending submission key. + +At radius zero, `Container` uses the original frame shape/painting path; no +marker, Arc/Box for a blur callback, metadata vector, blur pipeline, texture, +uniform, binding or extra pass is created. The plain Window/Panel hook delegates +to the original `Frame::show` path, including its existing content boxing. A +previously enabled effect is detached and its CPU/GPU storage dropped on zero; +wgpu retains any in-flight references until their submitted work completes. +Existing viewport/MSAA/AO/OIT resources are baseline resources, not blur resources. +An explicit harness tint override intentionally changes ordinary panel fills even +at zero; leave `surface_alpha` null for comparisons against main. + +## Actual frame path and insertion points + +The pinned dependencies are egui/egui-wgpu/eframe 0.36.2 and wgpu 30.0.1. +eframe and egui remain registry dependencies; only egui-wgpu has local compositor +changes for blur. The egui dependency is the published 0.36.2 crate. + +| Stage | Actual path | +| --- | --- | +| Build UI | Native `eframe::App::ui` calls `SolveApp::ui` (`crates/ui-egui/src/lib.rs`). `blur::State::begin` installs a stack-scoped thread-local host policy. `cad_ui` draws the workspace under floating cards, or in the remaining central rectangle for docked layout. | +| View background | `viewport.rs::show` emits an egui gradient mesh before the viewport callback. `render_workspace.rs::show` emits its effective preview background, shared with the blur source. Neither is contained in the GPU renderer's scene texture. | +| Prepare scene | `gpu.rs::ViewportCallback::prepare` calls `solidcraft_gpu::view::Renderer::prepare`. Native `set_wgpu_split` already draws scene depth/MSAA/OIT offscreen. The UI target has one sample and no depth. The resolved scene is transparent outside geometry. | +| Acquire/order | `vendor/egui-wgpu/src/winit.rs::Painter::paint_and_update_textures` acquires/probes the drawable before preparing callbacks. `Renderer::update_buffers` uploads meshes, runs all callback `prepare`s, then all `finish_prepare`s. The enabled frame hook supplies actual physical target extent and the effective scale, including surface clamping. | +| Build source/blur | The enabled `blur_native.rs::Source` replaces the viewport callback. Its `prepare` delegates unchanged to the original callback. Its `finish_prepare` draws the independent background/prepared viewport into S, then the blur chain, all on the same encoder. A cache hit encodes neither source nor blur passes. | +| UI composition | The native pass owner selects an installed `FrameCompositor` before beginning the UI pass. It renders the unchanged egui primitive stream into C. At semantic markers, `PanelMarker::paint` samples B; ordinary panel fill/content follow in their original order. | +| Present/capture | A final triangle presents C into the normal drawable or existing capture texture. Existing screenshot copying, queue guard, texture frees and presentation remain after that. `submitted` commits a pending source key only after queue submission. | + +`CallbackTrait::paint` receives an already active pass, not its encoder or target; +it cannot redirect the UI or start blur passes. Callback command buffers execute +before the main encoder. Source production and its dependent blur therefore use +the same encoder and return no additional callback command buffers. + +## Independent source and color contract + +S, B and C are separate textures with separate jobs: + +- **S** is full-target, single-sample viewport/background color. Its construction + takes the explicit background rectangle/colors, inherited clip and prepared + `ViewportCallback::Frame`. The background pipeline has a uniform-only bind + group: it cannot sample C or a panel texture. The source viewport paint uses + the same prepared renderer, with its actual screen placement/scissor. +- **B** is the final full-target linear RGBA16F Kawase result, shared by every + eligible panel in that native viewport. Intermediate down/up targets are also + RGBA16F and are distinct read/write textures on every pass. +- **C** has the UI target's format and contains the normal sharp viewport plus + egui UI/markers. Only the final presentation samples C. C never feeds S or B. + +No prefix of the UI paint list is blurred. A docked panel or window can precede +the viewport in that list; this does not affect source construction. Panels, +menus, HUDs, toasts, dimension editors, cursors and input shields are excluded. +The source does include model/sketch/highlight/preview geometry, section caps, +reference images and point clouds drawn by the GPU viewport. A panel outside +the model rectangle sees the deterministic source background, not invented +geometry behind a dock. Extending the projection under docks is a separate change. + +Render preview uses its original product `Frame`, lighting, resolution reduction +and effective preview background, including authored-scene precedence and the +animated tab gradient. It does not call a model snapshot renderer or +replace the Render scene settings. Home/result-image contexts are unavailable; +a missing source callback in a painted frame drops target storage and reports +unavailable instead of sampling a previous workspace's pixels. + +Source color is opaque viewport/background color. Translucent custom viewport +or outside backgrounds report unavailable before effect GPU allocation; their +composition with a transparent native window is not silently approximated. +For an unorm UI target, the +first down pass decodes each source texel before bilinear interpolation; for an +sRGB target, texture sampling performs the decode. All subsequent filtering is +linear. Marker output follows egui's gamma-premultiplied convention: convert B +to gamma, multiply RGB/alpha by rounded coverage and host opacity, and for an +sRGB attachment decode that premultiplied RGB before framebuffer conversion. +This matches egui's existing shader ordering rather than treating its output as +straight-alpha linear color. Presentation samples C in its own format; it does +not apply a second manual gamma transform. The harness exercises both unorm and +sRGB formats. The worker has not yet verified those images on hardware. + +## Semantic hosts, clipping and rounding + +Eligible surfaces are `Panel`, `Feature`, `Palette` and `Chrome`, with nonzero, +translucent outer fill. `Container` owns eligibility; alpha alone does not select +arbitrary UI. Opaque fills have no marker. Viewport, native application bar, +Canvas, InputShield, HUDs, Toast, Window and Popup are outside the initial policy. + +The app uses stock egui 0.36.2 public APIs. In the positive eligible path, +`Container::show_frame`, `show_edge` and the bounded `FeatureWindow::show` +reserve an early painter slot before invoking the original host. Once geometry +is known they populate that slot with a marker; the original shadow, fill, +stroke and contents remain in their original slots. The zero path reserves +nothing and calls the existing `Prepared::end`, `Panel::show` or `Window::show`. +No host becomes transparent, and child `UiStack` frame/background metadata, +styles, margins, stroke widths, IDs and interactions remain stock. + +`show_frame` owns `Frame::begin` and uses the final content rectangle and +joined-edge corner rounding. `show_edge` captures the panel painter before the +body can narrow its clip or change opacity, then measures the actual frame +content (the response may be clamped on overflow). Its marker uses the original +host clip, including padding/borders and any host clipping. Current adaptive +edge callers use ordinary `show`; the helper deliberately exposes no animated +panel entry point. + +Only `Panel::window_placed` creates an adaptive stock Window. Its small +`FeatureWindow` wrapper keeps the existing builder private and forwards only +`fixed_size`, `open` and `show`. The open flag is forwarded with a shortened borrow +lifetime; stock Window owns visibility and close-request handling. These sheets +explicitly disable native title bars, collapse, resize, scrolling and fades, +and use an explicit persistent ID and +Middle layer. The early slot is on that exact layer. The final Area response +includes the outer margins; subtracting the original total margins reconstructs +the content rectangle for marker geometry even though stock Window relocates +`inner_margin` into an internal Frame. The marker inherits the host painter's +visibility/opacity and Area's viewport clip, rather than Resize's content-only +clip. System windows (`Surface::Window`) remain outside blur eligibility. + +Manual workspace ribbon cards and History retain semantic background painting; +manual HUD painting remains plain. No private storage access, extra outer +visual container, duplicate frame or search for matching colors/rectangles is +used. The tests inject a marker function into these same helpers without a GPU +to compare stock and decorated output, geometry, IDs and semantic metadata. + +A marker precedes the ordinary shadow, fill, border and content on the same +layer. It retains all four final corner radii and painter +opacity. At paint it uses the final transformed callback rectangle and actual +physical scale, matching egui rectangle snapping when enabled. It changes the +GPU viewport to the full target, retains the renderer's inherited scissor, and +uses an antialiased rounded distance mask at the original unclipped rectangle. +Thus clipping an edge does not invent a new rounded corner. UVs come from screen +position, so a moved panel samples the corresponding source pixels. Distinct +retained marker uniforms prevent one panel's queue write from changing another's +draw. Marker count is bounded to 256. Nested/overlapping panels sample the same B, +never each other's fill or content. + +## Radius, cache, allocation and recovery + +Radius is finite physical pixels in 0..40; invalid requests are refused before +mutation. Zero selects plain rendering. Positive tiers have N down and N up passes: + +| Radius | N | First down target | +| --- | --- | --- | +| >0..8 | 2 | ceil-half resolution | +| >8..18 | 3 | ceil-half resolution | +| >18..30 | 4 | ceil-half resolution | +| >30..40 | 5 | ceil-half resolution | + +Every subsequent dimension is ceil-halved with a minimum of one pixel. Upsampling +ends at full resolution B. The original kernel has a center-plus-four-corners +down filter (weights 4,1,1,1,1) and an eight-tap up filter (axis weight 1, +diagonal weight 2). The offset, in input texels, is +`radius / (2 * sqrt((35/18) * (4^N - 1)))`. This normalizes the filters' tap sigma +across tier changes; resampling contributes an additional footprint. This is a +documented radius mapping, not a measured Gaussian-radius equivalence. Physical +spread and tier-boundary appearance still require the manager's impulse/golden review. + +`view::frame_key` is exposed without changing its existing behavior. The blur +signature includes that exact scene signature (including camera, lighting, +selection/hover, preview, images/clouds, analysis, section, AO and supersampling), +source/background rectangles and clip after the source layer's final global +transform, background colors, physical target extent, +effective scale, target encoding and radius. It is per device/host; installation +on a replacement device retires the old state. A pending key becomes valid only +after submission. A resting repaint reuses B with zero source/blur passes; normal +UI composition/presentation still occurs. Panel-only tint/layout changes reuse +the full-target source unless they change projection, source placement or extent. +No repaint timer is added to keep blur alive. + +The source captures its Context/layer only in the enabled branch. `finish_prepare` +queries `layer_transform_to_global` after UI emission, including a transform set +after the callback shape was emitted. One validated snapshot transforms viewport, +background and inherited clip for both the cache key and source painting. The +callback shape stays local so egui applies its own transformation exactly once. + +All effect GPU allocation is lazy and bounded. The target budget is 256 MiB, +computed with checked arithmetic before allocation, using four-byte S/C and +eight-byte down/up targets. Uniform bytes are also reported. The budget does not +claim to account for opaque driver pipeline/binding memory. Actual device limits +and format capabilities are queried. Resource creation/marker growth use error +scopes and return unavailable on refusal; failures latch until radius/host/size +changes, avoiding an allocation retry storm. Positive radius changes currently +retire/recreate effect storage, including pipelines; this is deliberately simple +but cold activation cost must be measured before PR 6 adds an interactive slider. + +Native zero physical window size suspends the effect before callback preparation, +including when the surface was clamped to 1x1. Geometry/scale is checked before +casts or allocation. Device loss suspends storage before further effect work; +existing device probing and acquired-frame lifetime handling are retained. +Replacement size/device rebuilds from a fresh signature. No explicit destruction +of in-flight textures, new unsafe block, unwrap/expect/panic path, synchronous +readback, or GPU completion wait was added to production painting. + +## Capability and other integrations + +`blur::Capability` is `Available` or `Unavailable(reason)`. `State::capability` +distinguishes missing GPU/native split integration, software adapter, unsupported +filterable/renderable formats, unsupported source context, missing source frame, +resource/size refusal and lost device. The actual window adapter is classified +with the same `gpu::select::tier_of` as headless captures; no renderer-name guessing. +Software adapters and web paths allocate no effect resources or markers. + +Web still uses eframe's unvendored `src/web/web_painter_wgpu.rs`, not the native +pass owner. Both WebGPU and WebGL2 report unavailable until that owner is wired +with equivalent acquire/zero-size/error ordering. This is an integration limit, +not a claim that WebGPU fragment blur is impossible. No eframe/epaint patch is used. + +`ui.render`, CLI snapshots and scenario `shot` remain model-only captures, through +`engine::capture`/`gpu::capture::Capturer` or the existing CPU fallback. They do not +paint egui panels and cannot prove blur correctness. Their code paths are unchanged. +The full GPU fixture in existing `gpu.rs::tests` renders actual app egui output, +font textures, viewport callbacks and compositor into a readback target. Tests +remain in the existing area modules; no per-issue test module was added. + +PR 6 must consume the capability/reason and finite 0..40 contract, leave saved +user intent intact on fallback, and request a frame on changes. It must not create +resources by opening Preferences. There is no persistent blur preference in PR 5. + +## Internal activation and manager-only validation + +The control hook is `ui.blur {radius_px?, surface_alpha?}`. `surface_alpha` is an +internal capture-only override in 0..1; null restores ordinary fills. Transparent +host frames remain transparent. The hook returns requested radius, maximum, +capability and cumulative counters. Activation is control-only and session-only; +default construction is zero and performs no environment lookup or GPU probe. +The adapter capability probe is cached lazily on activation or an explicit query. + +Counters increment at actual `create_texture`, buffer/bind-group/pipeline creation, +source/chain/UI/present encoding and marker emission/drawing. They include cache +hits and live texture/buffer/group/pipeline counts and texture/uniform bytes. +They are effect counters, not a fabricated whole-frame allocator or driver trace. +At zero, test deltas must remain zero and all live effect counts must be zero. +CPU allocations must additionally be measured with an external allocator/profiler; +no unsafe counting allocator was added. Timing alone cannot prove zero allocations. + +No commands below were run by this worker. Manager's minimal focused checks: + +```powershell +cargo test --locked --profile ci -p solidcraft-ui-egui --lib blur_stock_ -- --nocapture +cargo test --locked --profile ci -p solidcraft-ui-egui --lib blur_ -- --nocapture +cargo build --locked --profile ci -p solidcraft +``` + +The five `blur_stock_` tests compare stock and app-owned hosts without a GPU: +zero output includes identical Noop counts; positive output preserves chrome, +semantic fill/frame information and persistent IDs; asymmetric margins, stroke +width, host clipping, final joined corners and late layer transforms are covered. +They replace the old test of the vendored Window hook. They are authored only, +not executed by this worker. Open-flag forwarding also covers initially hidden, +closed and reopened windows, including stock close-request propagation via +`ui.close_kind(egui::UiKind::Window)`. Plain `ui.close()` targets Window's nearer +internal Collapsible, even when native title/collapse controls are disabled. +The other blur tests remain; the broader `blur_` filter selects fourteen tests. + +Cargo.lock was restored as text to the egui 0.36.2 registry source and checksum +from the matching local crates.io index entry; dependency versions are unchanged. +The full vendored egui copy and its path patch were removed; the egui-wgpu patch +and licences remain. No cargo execution was used. Set `SOLIDCRAFT_REQUIRE_GPU=1` to require an adapter +(hardware or software); a missing adapter/device fails every blur fixture consumer. +The explicit `cfg(test)` rendering fixture runs all positive compositor, cache, +pixel and suspension assertions on CI software adapters independently of production +software policy, retaining real adapter identity and format/device requirements. +A separate production-policy test asserts that actual software adapters report +`Unavailable("software adapter (gpu-software)")`, allocate no blur resources and +emit no markers. Production software blur remains unavailable. + +To export fixed-scene 8/18/40 and zero light/dark images, counters, and warmed +UI/encode/GPU-completion benchmark samples: + +```powershell +$env:SOLIDCRAFT_REQUIRE_GPU = '1' +$env:SOLIDCRAFT_BLUR_EVIDENCE = Join-Path $env:TEMP 'solidcraft-9809-blur-review' +cargo test --locked --profile ci -p solidcraft-ui-egui --lib blur_ -- --nocapture +``` + +`SOLIDCRAFT_BLUR_GOLDENS` can name a separate reviewed PNG directory for decoded +RGBA equality. No expected pixels were invented or automatically blessed here. +The fixed fixture tests both target encodings, source independence from panel +tint, rest/cache hits, camera invalidation, exact tier pass counts, on/off pixel +restoration, hostile sizes/radii, suspension/resource release, host-slot ordering, +and late layer translation/scaling. The latter checks transformed viewport, +background/clip placement, cache invalidation/reuse, and pixels outside the moved +clip even on a forced miss. Further device-loss, resize/DPI, clipping/overlap and +calibrated radius review remain manager validation work, not claimed test results. + +For actual window evidence after the manager builds, start the branch app with +the same sample, dimensions, camera/theme and graphics settings as the baseline. +Use the manager's isolated TEMP settings/control-blur launch environment and its +written token file (`$blurTokenPath` below). Port 38876 is the user review app and +must not be contacted or relaunched; blur validation uses explicit port 38877: + +```powershell +.\target\ci\solidcraft.exe --sample --control 38877 +# In a second shell; always choose a NEW output directory: +.\scripts\blur-evidence.ps1 -Port 38877 -TokenPath $blurTokenPath -OutputDirectory "$env:TEMP\solidcraft-9809-window-review" +``` + +The collector saves ordinary zero UI/model captures before applying a tint, +light/dark 0/18 UI screenshots, feature counters, and warmed CPU `frame_ms` plus +screenshot-roundtrip timing samples. Roundtrip timing includes PNG readback/I/O +and is explicitly not GPU frame timing. The full fixture benchmark separately +waits for GPU completion, only in test code. For before/after zero CPU timing, +connect the collector to the manager's separately running main baseline with +`-Baseline -Port -OutputDirectory `. +It never launches/builds the baseline or overwrites existing evidence. Baseline +artifacts under TEMP/solidcraft-8876-evidence and its checkout were not modified. +Compare decoded images, not PNG file bytes. If ffmpeg is available, its RGBA +framemd5 output provides pixel hashes and dimensions without Pillow: + +```powershell +$mainPng = "$env:TEMP\solidcraft-8876-evidence\blur-main-zero-ui.png" +$branchPng = "$env:TEMP\solidcraft-9809-window-review\zero-ui.png" +$mainDecoded = (& ffmpeg -v error -i $mainPng -frames:v 1 -pix_fmt rgba -f framemd5 -) -join "`n" +if ($LASTEXITCODE -ne 0) { throw 'Baseline decode failed' } +$branchDecoded = (& ffmpeg -v error -i $branchPng -frames:v 1 -pix_fmt rgba -f framemd5 -) -join "`n" +if ($LASTEXITCODE -ne 0) { throw 'Branch decode failed' } +if ($mainDecoded -cne $branchDecoded) { throw 'Decoded RGBA/dimensions differ' } +``` + +Report timing medians/ranges, machine, adapter/backend/driver, size/DPI and power +settings from alternating warmed baseline/branch runs. Use PIX/RenderDoc or an +allocator profiler for complete GPU/CPU allocation/pass accounting. The manager +measured the exact prerequisite base `f1c2fc880`; comparisons require identical +restored UI/model settings. Current validation records belong in the PR body; +the new fixture is not a substitute for that comparison. Later manager gates are +wasm, layers, licences, lists, containers/clippy, then full CI before commit/merge. +Worker execution counts: tests/builds/checks/cargo/xtask/UI runs/screenshots = 0. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 036a97a70..316d863d4 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -28,6 +28,15 @@ The control channel is **on by default**. SolidCraft listens on `127.0.0.1` only so agents can drive the app without a launch flag. Every connection still needs this launch's token (below); nothing else on the machine, and nothing off it, can send a command. +Internal rendering harness: `ui.blur {radius_px?, surface_alpha?}` queries or sets +session-only panel blur. Radius is finite physical pixels in 0..40; the optional +capture tint is 0..1 (`null` restores ordinary fills). This is not a saved +preference. The reply contains requested radius, capability/reason and cumulative +actual effect counters, including live resources and encoded passes. Unsupported +software/web/source contexts stay on ordinary painting. Use `ui.screenshot` for +panel evidence; `ui.render` remains a model-only capture. Activation, full egui GPU +fixture and manager-run evidence commands are in [blur-behind.md](blur-behind.md). + | Launch | What listens | |---|---| | `solidcraft --control PORT`, or `SOLIDCRAFT_CONTROL_PORT=PORT` | exactly `127.0.0.1:PORT` (the flag wins over the variable), whatever the setting | diff --git a/scripts/blur-evidence.ps1 b/scripts/blur-evidence.ps1 new file mode 100644 index 000000000..e4c1d95ed --- /dev/null +++ b/scripts/blur-evidence.ps1 @@ -0,0 +1,77 @@ +# Manager-run local evidence collector. Does not launch/build anything or modify baseline files. +param( + [Parameter(Mandatory = $true)][int]$Port, + [Parameter(Mandatory = $true)][string]$OutputDirectory, + [string]$TokenPath, + [switch]$Baseline, + [ValidateRange(1, 1000)][int]$Frames = 30 +) +$ErrorActionPreference = 'Stop' +if (-not $TokenPath) { $TokenPath = Join-Path $env:LOCALAPPDATA "SolidCraft/control/$Port.token" } +$blurToken = (Get-Content -LiteralPath $TokenPath -Raw).Trim() +$blurOutput = [IO.Path]::GetFullPath($OutputDirectory) +if (Test-Path -LiteralPath $blurOutput) { throw 'Use a new output directory; existing evidence is never overwritten.' } +New-Item -ItemType Directory -Path $blurOutput | Out-Null +$blurClient = [Net.Sockets.TcpClient]::new('127.0.0.1', $Port) +$blurClient.ReceiveTimeout = 60000 +$blurClient.SendTimeout = 60000 +$blurStream = $blurClient.GetStream() +$blurReader = [IO.StreamReader]::new($blurStream) +$blurWriter = [IO.StreamWriter]::new($blurStream, [Text.UTF8Encoding]::new($false)) +$blurWriter.AutoFlush = $true +$script:blurRequestId = 0 +function Invoke-BlurControl([string]$Method, $Parameters = @{}) { + $script:blurRequestId++ + $blurWriter.WriteLine((@{ id = $script:blurRequestId; token = $blurToken; method = $Method; params = $Parameters } | ConvertTo-Json -Compress -Depth 30)) + $blurLine = $blurReader.ReadLine() + if (-not $blurLine) { throw 'Control connection closed.' } + $blurReply = $blurLine | ConvertFrom-Json + if (-not $blurReply.ok) { throw "$Method failed: $($blurReply.error)" } + return $blurReply.result +} +function Save-BlurShot([string]$Name) { + Invoke-BlurControl 'ui.screenshot' @{ path = (Join-Path $blurOutput "$Name.png"); allow_paths = @($blurOutput) } | Out-Null +} +try { + $blurInitial = Invoke-BlurControl 'ui.inspect' + $blurPrefs = Invoke-BlurControl 'ui.prefs' + $blurInitial | ConvertTo-Json -Depth 30 | Set-Content -LiteralPath (Join-Path $blurOutput 'initial-inspect.json') + if (-not $Baseline) { Invoke-BlurControl 'ui.blur' @{ radius_px = 0; surface_alpha = $null } | Out-Null } + # Leave the current scene/theme/size untouched for the main/branch zero comparison. + $blurTimings = @() + for ($blurIndex = 0; $blurIndex -lt ($Frames + 5); $blurIndex++) { + $blurClock = [Diagnostics.Stopwatch]::StartNew() + # A screenshot forces a presented frame. Reuse only this collector's scratch file. + Save-BlurShot 'timing-scratch' + $blurClock.Stop() + $blurInspect = Invoke-BlurControl 'ui.inspect' + if ($blurIndex -ge 5) { + $blurTimings += @{ ui_cpu_ms = $blurInspect.frame_ms; screenshot_roundtrip_ms = $blurClock.Elapsed.TotalMilliseconds } + } + } + $blurReport = @{ machine = $env:COMPUTERNAME; mode = $(if ($Baseline) { 'baseline' } else { 'branch-zero' }); samples = $blurTimings; inspect = $blurInitial } + if (-not $Baseline) { $blurReport.counters = Invoke-BlurControl 'ui.blur' } + $blurReport | ConvertTo-Json -Depth 30 | Set-Content -LiteralPath (Join-Path $blurOutput 'zero-timing.json') + Save-BlurShot 'zero-ui' + Invoke-BlurControl 'ui.render' @{ path = (Join-Path $blurOutput 'zero-model.png'); allow_paths = @($blurOutput) } | Out-Null + if (-not $Baseline) { + foreach ($blurTheme in @('light', 'dark')) { + Invoke-BlurControl 'ui.prefs' @{ theme = $blurTheme } | Out-Null + foreach ($blurRadius in @(0, 18)) { + Invoke-BlurControl 'ui.blur' @{ radius_px = $blurRadius; surface_alpha = 0.7 } | Out-Null + Save-BlurShot "$blurTheme-$blurRadius" + $blurState = Invoke-BlurControl 'ui.blur' + $blurState | ConvertTo-Json -Depth 12 | Set-Content -LiteralPath (Join-Path $blurOutput "$blurTheme-$blurRadius-counters.json") + if ($blurRadius -gt 0 -and $blurState.capability -ne 'Available') { throw "Blur unavailable: $($blurState.capability | ConvertTo-Json -Compress)" } + } + } + } +} finally { + try { + if (-not $Baseline) { Invoke-BlurControl 'ui.blur' @{ radius_px = 0; surface_alpha = $null } | Out-Null } + if (-not $Baseline -and $blurPrefs -and $blurPrefs.theme) { Invoke-BlurControl 'ui.prefs' @{ theme = $blurPrefs.theme } | Out-Null } + if (-not $Baseline -and $blurInitial -and $null -ne $blurInitial.ui.dark) { Invoke-BlurControl 'ui.set' @{ dark = $blurInitial.ui.dark } | Out-Null } + } finally { + $blurWriter.Dispose(); $blurReader.Dispose(); $blurClient.Dispose() + } +} diff --git a/vendor/egui-wgpu/src/renderer.rs b/vendor/egui-wgpu/src/renderer.rs index 05b29b8f6..e28a2579f 100644 --- a/vendor/egui-wgpu/src/renderer.rs +++ b/vendor/egui-wgpu/src/renderer.rs @@ -129,6 +129,29 @@ pub struct ScreenDescriptor { pub pixels_per_point: f32, } +/// SolidCraft: optional ownership of a complete frame, outside the primitive loop. +/// Returning false keeps the ordinary pass. No effect resources exist by default. +pub trait FrameCompositor: Send + Sync { + /// SolidCraft: select the native viewport before any effect preparation/painting. + fn begin_viewport(&self, _viewport: u64) {} + /// SolidCraft: actual acquired target geometry, before callback preparation. + fn screen(&self, _screen: &ScreenDescriptor, _resources: &mut CallbackResources) {} + /// SolidCraft: release target-dependent state on zero size or a lost device. + fn suspend(&self) {} + fn render( + &self, + renderer: &Renderer, + encoder: &mut wgpu::CommandEncoder, + target: &wgpu::TextureView, + jobs: &[epaint::ClippedPrimitive], + screen: &ScreenDescriptor, + clear: [f32; 4], + ) -> bool; + + /// Called only after the commands producing cached pixels have been submitted. + fn submitted(&self) {} +} + impl ScreenDescriptor { /// size in "logical" points fn screen_size_in_points(&self) -> [f32; 2] { @@ -263,6 +286,8 @@ pub struct Renderer { /// /// See also [`CallbackTrait`]. pub callback_resources: CallbackResources, + /// SolidCraft: installed lazily by an enabled effect; the ordinary loop is unchanged. + pub frame_compositor: Option>, } impl Renderer { @@ -469,6 +494,7 @@ impl Renderer { samplers: HashMap::default(), options, callback_resources: CallbackResources::default(), + frame_compositor: None, } } @@ -933,6 +959,9 @@ impl Renderer { profiling::function_scope!(); self.skip_frame = false; + if let Some(effect) = &self.frame_compositor { + effect.screen(screen_descriptor, &mut self.callback_resources); + } let screen_size_in_points = screen_descriptor.screen_size_in_points(); let uniform_buffer_content = UniformBuffer { diff --git a/vendor/egui-wgpu/src/winit.rs b/vendor/egui-wgpu/src/winit.rs index bacb3f8a9..0784fefc1 100644 --- a/vendor/egui-wgpu/src/winit.rs +++ b/vendor/egui-wgpu/src/winit.rs @@ -663,6 +663,11 @@ impl Painter { .as_ref() .is_some_and(|rs| rs.device_lost.is_lost()) { + if let Some(rs) = &self.render_state + && let Some(effect) = &rs.renderer.read().frame_compositor + { + effect.suspend(); + } // The app's frame (not this paint) acts on it: keep its frames coming. self.context .request_repaint_after_for(std::time::Duration::from_millis(250), viewport_id); @@ -702,11 +707,22 @@ impl Painter { let Some(render_state) = self.render_state.as_mut() else { return vsync_sec; }; + if let Some(effect) = &render_state.renderer.read().frame_compositor { + effect.begin_viewport(viewport_id.0.value()); + } let mut render_queue_guard = RendererQueueGuard { queue: &render_state.queue, commands_submitted: false, }; + // SolidCraft: a minimized native window may retain a clamped 1x1 surface. + if let Some(effect) = &render_state.renderer.read().frame_compositor { + let extent = window.inner_size(); + if extent.width == 0 || extent.height == 0 { + effect.suspend(); + return vsync_sec; + } + } let Some(surface_state) = self.surfaces.get_mut(&viewport_id) else { return vsync_sec; @@ -794,6 +810,9 @@ impl Painter { // is still there. The first queue write to meet a lost device panics inside wgpu (#4172); // the submission meets it instead, marks it lost, and the frame is dropped unpresented. if render_state.device_lost.probe(&render_state.queue) { + if let Some(effect) = &render_state.renderer.read().frame_compositor { + effect.suspend(); + } render_queue_guard.commands_submitted = true; log::error!( "The graphics device was lost: {}", @@ -867,62 +886,79 @@ impl Painter { (texture_view, Some(&target_view)) }); - let render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("egui_render"), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view, - resolve_target, - ops: wgpu::Operations { - load: wgpu::LoadOp::Clear(wgpu::Color { - r: clear_color[0] as f64, - g: clear_color[1] as f64, - b: clear_color[2] as f64, - a: clear_color[3] as f64, - }), - store: wgpu::StoreOp::Store, - }, - depth_slice: None, - })], - depth_stencil_attachment: self.depth_texture_view.get(&viewport_id).map(|view| { - wgpu::RenderPassDepthStencilAttachment { + // SolidCraft: the pass owner selects offscreen composition once, never in render's loop. + let composed = self.options.msaa_samples == 1 + && self.options.depth_stencil_format.is_none() + && renderer.frame_compositor.as_ref().is_some_and(|effect| { + effect.render( + &renderer, + &mut encoder, + &target_view, + clipped_primitives, + &screen_descriptor, + clear_color, + ) + }); + if !composed { + let render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("egui_render"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, - depth_ops: self - .options - .depth_stencil_format - .is_some_and(|depth_stencil_format| { - depth_stencil_format.has_depth_aspect() - }) - .then_some(wgpu::Operations { - load: wgpu::LoadOp::Clear(1.0), - // It is very unlikely that the depth buffer is needed after egui finished rendering - // so no need to store it. (this can improve performance on tiling GPUs like mobile chips or Apple Silicon) - store: wgpu::StoreOp::Discard, + resolve_target, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { + r: clear_color[0] as f64, + g: clear_color[1] as f64, + b: clear_color[2] as f64, + a: clear_color[3] as f64, }), - stencil_ops: self - .options - .depth_stencil_format - .is_some_and(|depth_stencil_format| { - depth_stencil_format.has_stencil_aspect() - }) - .then_some(wgpu::Operations { - load: wgpu::LoadOp::Clear(0), - store: wgpu::StoreOp::Discard, - }), - } - }), - timestamp_writes: None, - occlusion_query_set: None, - multiview_mask: None, - }); + store: wgpu::StoreOp::Store, + }, + depth_slice: None, + })], + depth_stencil_attachment: self.depth_texture_view.get(&viewport_id).map( + |view| { + wgpu::RenderPassDepthStencilAttachment { + view, + depth_ops: self + .options + .depth_stencil_format + .is_some_and(|depth_stencil_format| { + depth_stencil_format.has_depth_aspect() + }) + .then_some(wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + // It is very unlikely that the depth buffer is needed after egui finished rendering + // so no need to store it. (this can improve performance on tiling GPUs like mobile chips or Apple Silicon) + store: wgpu::StoreOp::Discard, + }), + stencil_ops: self + .options + .depth_stencil_format + .is_some_and(|depth_stencil_format| { + depth_stencil_format.has_stencil_aspect() + }) + .then_some(wgpu::Operations { + load: wgpu::LoadOp::Clear(0), + store: wgpu::StoreOp::Discard, + }), + } + }, + ), + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); - // Forgetting the pass' lifetime means that we are no longer compile-time protected from - // runtime errors caused by accessing the parent encoder before the render pass is dropped. - // Since we don't pass it on to the renderer, we should be perfectly safe against this mistake here! - renderer.render( - &mut render_pass.forget_lifetime(), - clipped_primitives, - &screen_descriptor, - ); + // Forgetting the pass' lifetime means that we are no longer compile-time protected from + // runtime errors caused by accessing the parent encoder before the render pass is dropped. + // Since we don't pass it on to the renderer, we should be perfectly safe against this mistake here! + renderer.render( + &mut render_pass.forget_lifetime(), + clipped_primitives, + &screen_descriptor, + ); + } if capture && let Some(capture_state) = &mut self.screen_capture_state { capture_buffer = Some(capture_state.copy_textures( @@ -951,6 +987,10 @@ impl Painter { // Ensure that the queue guard does not do unnecessary work when dropped render_queue_guard.commands_submitted = true; + // SolidCraft: caches become valid only after the producer encoder was submitted. + if let Some(effect) = &render_state.renderer.read().frame_compositor { + effect.submitted(); + } // Free textures marked for destruction **after** queue submit since they might still be used in the current frame. // Calling `wgpu::Texture::destroy` on a texture that is still in use would invalidate the command buffer(s) it is used in. @@ -1015,4 +1055,3 @@ impl Painter { // TODO(emilk): something here? } } -