From 73c0ce75d87f7537a48bfbaf5a2ee6ffc6ac1a53 Mon Sep 17 00:00:00 2001 From: Ivan Molodetskikh Date: Tue, 14 Apr 2026 07:35:11 +0000 Subject: [PATCH] Implement blur background effect --- niri-config/src/appearance.rs | 60 +++- niri-config/src/lib.rs | 11 + src/handlers/compositor.rs | 5 +- src/layer/mapped.rs | 7 + src/layout/mod.rs | 7 + src/layout/tile.rs | 2 + src/niri.rs | 4 + src/render_helpers/background_effect.rs | 45 ++- src/render_helpers/blur.rs | 355 ++++++++++++++++++++++ src/render_helpers/effect_buffer.rs | 104 ++++++- src/render_helpers/mod.rs | 1 + src/render_helpers/shaders/blur.vert | 11 + src/render_helpers/shaders/blur_down.frag | 21 ++ src/render_helpers/shaders/blur_up.frag | 29 ++ src/render_helpers/shaders/mod.rs | 9 + src/render_helpers/xray.rs | 10 +- src/window/mapped.rs | 11 +- 17 files changed, 674 insertions(+), 18 deletions(-) create mode 100644 src/render_helpers/blur.rs create mode 100644 src/render_helpers/shaders/blur.vert create mode 100644 src/render_helpers/shaders/blur_down.frag create mode 100644 src/render_helpers/shaders/blur_up.frag diff --git a/niri-config/src/appearance.rs b/niri-config/src/appearance.rs index 3ba9808b..824cc52a 100644 --- a/niri-config/src/appearance.rs +++ b/niri-config/src/appearance.rs @@ -1006,11 +1006,62 @@ where } } +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Blur { + pub off: bool, + pub passes: u8, + pub offset: f64, + pub noise: f64, + pub saturation: f64, +} + +impl Default for Blur { + fn default() -> Self { + Self { + off: false, + passes: 3, + offset: 3., + noise: 0.02, + saturation: 1.5, + } + } +} + +#[derive(knuffel::Decode, Debug, Default, Clone, Copy, PartialEq)] +pub struct BlurPart { + #[knuffel(child)] + pub off: bool, + #[knuffel(child)] + pub on: bool, + #[knuffel(child, unwrap(argument))] + pub passes: Option, + #[knuffel(child, unwrap(argument))] + pub offset: Option>, + #[knuffel(child, unwrap(argument))] + pub noise: Option>, + #[knuffel(child, unwrap(argument))] + pub saturation: Option>, +} + +impl MergeWith for Blur { + fn merge_with(&mut self, part: &BlurPart) { + self.off |= part.off; + if part.on { + self.off = false; + } + + merge_clone!((self, part), passes); + merge!((self, part), offset, noise, saturation); + } +} + #[derive(knuffel::Decode, Debug, Default, Clone, Copy, PartialEq)] pub struct BackgroundEffectRule { #[knuffel(child, unwrap(argument))] pub xray: Option, #[knuffel(child, unwrap(argument))] + pub blur: Option, + #[knuffel(child, unwrap(argument))] pub noise: Option>, #[knuffel(child, unwrap(argument))] pub saturation: Option>, @@ -1026,13 +1077,20 @@ pub struct BackgroundEffect { /// - `Some(true)`: xray even if no other background effect is active pub xray: Option, + /// Whether to blur the background. + /// + /// - `None`: no blur + /// - `Some(false)`: never blur + /// - `Some(true)`: always blur + pub blur: Option, + pub noise: Option, pub saturation: Option, } impl MergeWith for BackgroundEffect { fn merge_with(&mut self, part: &BackgroundEffectRule) { - merge_clone_opt!((self, part), xray); + merge_clone_opt!((self, part), xray, blur); if let Some(x) = part.noise { self.noise = Some(x.0); diff --git a/niri-config/src/lib.rs b/niri-config/src/lib.rs index ed073b09..a12c6be3 100644 --- a/niri-config/src/lib.rs +++ b/niri-config/src/lib.rs @@ -78,6 +78,7 @@ pub struct Config { pub hotkey_overlay: HotkeyOverlay, pub config_notification: ConfigNotification, pub animations: Animations, + pub blur: Blur, pub gestures: Gestures, pub overview: Overview, pub environment: Environment, @@ -194,6 +195,7 @@ where "hotkey-overlay" => m_merge!(hotkey_overlay), "config-notification" => m_merge!(config_notification), "animations" => m_merge!(animations), + "blur" => m_merge!(blur), "gestures" => m_merge!(gestures), "overview" => m_merge!(overview), "xwayland-satellite" => m_merge!(xwayland_satellite), @@ -1616,6 +1618,13 @@ mod tests { }, ), }, + blur: Blur { + off: false, + passes: 3, + offset: 3.0, + noise: 0.02, + saturation: 1.5, + }, gestures: Gestures { dnd_edge_view_scroll: DndEdgeViewScroll { trigger_width: 10.0, @@ -1847,6 +1856,7 @@ mod tests { tiled_state: None, background_effect: BackgroundEffectRule { xray: None, + blur: None, noise: None, saturation: None, }, @@ -1887,6 +1897,7 @@ mod tests { baba_is_float: None, background_effect: BackgroundEffectRule { xray: None, + blur: None, noise: None, saturation: None, }, diff --git a/src/handlers/compositor.rs b/src/handlers/compositor.rs index d70ed5f9..19a3c2c4 100644 --- a/src/handlers/compositor.rs +++ b/src/handlers/compositor.rs @@ -195,7 +195,10 @@ impl CompositorHandler for State { // The mapped pre-commit hook deals with dma-bufs on its own. self.remove_default_dmabuf_pre_commit_hook(surface); let hook = add_mapped_toplevel_pre_commit_hook(toplevel); - let mapped = Mapped::new(window, rules, hook); + let mapped = { + let config = self.niri.config.borrow(); + Mapped::new(window, rules, hook, &config) + }; let window = mapped.window.clone(); let target = if let Some(p) = &parent { diff --git a/src/layer/mapped.rs b/src/layer/mapped.rs index 667de501..6d2945f5 100644 --- a/src/layer/mapped.rs +++ b/src/layer/mapped.rs @@ -42,6 +42,9 @@ pub struct MappedLayer { /// The shadow around the surface. shadow: Shadow, + /// The blur config, passed for background effect rendering. + blur_config: niri_config::Blur, + /// The view size for the layer surface's output. view_size: Size, @@ -85,6 +88,7 @@ impl MappedLayer { view_size, scale, shadow: Shadow::new(shadow_config), + blur_config: config.blur, clock, } } @@ -95,6 +99,8 @@ impl MappedLayer { shadow_config.on = false; shadow_config.merge_with(&self.rules.shadow); self.shadow.update_config(shadow_config); + + self.blur_config = config.blur; } pub fn update_shaders(&mut self) { @@ -234,6 +240,7 @@ impl MappedLayer { self.scale, false, surface, + self.blur_config, radius, self.rules.background_effect, xray_pos, diff --git a/src/layout/mod.rs b/src/layout/mod.rs index 1d0aad1a..cd090e59 100644 --- a/src/layout/mod.rs +++ b/src/layout/mod.rs @@ -134,6 +134,11 @@ pub trait LayoutElement { /// Unique ID of this element. fn id(&self) -> &Self::Id; + /// Updates the config for the element. + fn update_config(&mut self, blur_config: niri_config::Blur) { + let _ = blur_config; + } + /// Visual size of the element. /// /// This is what the user would consider the size, i.e. excluding CSD shadows and whatnot. @@ -364,6 +369,7 @@ pub struct Options { pub animations: niri_config::Animations, pub gestures: niri_config::Gestures, pub overview: niri_config::Overview, + pub blur: niri_config::Blur, // Debug flags. pub disable_resize_throttling: bool, pub disable_transactions: bool, @@ -624,6 +630,7 @@ impl Options { animations: config.animations.clone(), gestures: config.gestures, overview: config.overview, + blur: config.blur, disable_resize_throttling: config.debug.disable_resize_throttling, disable_transactions: config.debug.disable_transactions, deactivate_unfocused_windows: config.debug.deactivate_unfocused_windows, diff --git a/src/layout/tile.rs b/src/layout/tile.rs index 158a90cf..fa337747 100644 --- a/src/layout/tile.rs +++ b/src/layout/tile.rs @@ -251,6 +251,8 @@ impl Tile { let shadow_config = self.options.layout.shadow.merged_with(&rules.shadow); self.shadow.update_config(shadow_config); + + self.window.update_config(self.options.blur); } pub fn update_shaders(&mut self) { diff --git a/src/niri.rs b/src/niri.rs index b46c4353..626f53b1 100644 --- a/src/niri.rs +++ b/src/niri.rs @@ -149,6 +149,7 @@ use crate::protocols::mutter_x11_interop::MutterX11InteropManagerState; use crate::protocols::output_management::OutputManagementManagerState; use crate::protocols::screencopy::{Screencopy, ScreencopyBuffer, ScreencopyManagerState}; use crate::protocols::virtual_pointer::VirtualPointerManagerState; +use crate::render_helpers::blur::BlurOptions; use crate::render_helpers::debug::push_opaque_regions; use crate::render_helpers::primary_gpu_texture::PrimaryGpuTextureRenderElement; use crate::render_helpers::renderer::NiriRenderer; @@ -4077,13 +4078,16 @@ impl Niri { state.xray.workspaces.push((geo, bg_color)); } state.xray.backdrop_color = state.backdrop_buffer.color(); + let blur_options = BlurOptions::from(self.config.borrow().blur); for buf in &state.xray.background { let mut buffer = buf.borrow_mut(); buffer.update_size(size, scale); + buffer.update_blur_options(blur_options); } for buf in &state.xray.backdrop { let mut buffer = buf.borrow_mut(); buffer.update_size(size, scale); + buffer.update_blur_options(blur_options); } let layer_map = layer_map_for_output(out); diff --git a/src/render_helpers/background_effect.rs b/src/render_helpers/background_effect.rs index ad225044..e9dd028e 100644 --- a/src/render_helpers/background_effect.rs +++ b/src/render_helpers/background_effect.rs @@ -20,11 +20,13 @@ pub struct BackgroundEffect { /// Stored here in addition to `RenderParams` to damage when it changes. // FIXME: would be good to remove this duplication of radius. corner_radius: CornerRadius, + blur_config: niri_config::Blur, options: Options, } #[derive(Debug, Clone, Copy, PartialEq, Default)] pub struct Options { + pub blur: bool, pub xray: bool, pub noise: Option, pub saturation: Option, @@ -32,7 +34,10 @@ pub struct Options { impl Options { fn is_visible(&self) -> bool { - self.xray || self.noise.is_some_and(|x| x > 0.) || self.saturation.is_some_and(|x| x != 1.) + self.xray + || self.blur + || self.noise.is_some_and(|x| x > 0.) + || self.saturation.is_some_and(|x| x != 1.) } } @@ -70,16 +75,27 @@ impl BackgroundEffect { Self { damage: ExtraDamage::new(), corner_radius: CornerRadius::default(), + blur_config: niri_config::Blur::default(), options: Options::default(), } } + pub fn update_config(&mut self, config: niri_config::Blur) { + if self.blur_config == config { + return; + } + + self.blur_config = config; + self.damage.damage_all(); + } + pub fn update_render_elements( &mut self, corner_radius: CornerRadius, effect: niri_config::BackgroundEffect, ) { let mut options = Options { + blur: effect.blur == Some(true), xray: effect.xray == Some(true), noise: effect.noise, saturation: effect.saturation, @@ -122,8 +138,17 @@ impl BackgroundEffect { let damage = self.damage.render(params.geometry); - let noise = self.options.noise.unwrap_or(0.) as f32; - let saturation = self.options.saturation.unwrap_or(1.) as f32; + // Use noise/saturation from options, falling back to blur defaults if blurred, and + // to no effect if not blurred. + let blur = self.options.blur && !self.blur_config.off; + let noise = if blur { self.blur_config.noise } else { 0. }; + let noise = self.options.noise.unwrap_or(noise) as f32; + let saturation = if blur { + self.blur_config.saturation + } else { + 1. + }; + let saturation = self.options.saturation.unwrap_or(saturation) as f32; if self.options.xray { let Some(xray) = ctx.xray else { @@ -131,9 +156,15 @@ impl BackgroundEffect { }; push(damage.into()); - xray.render(ctx, params, xray_pos, noise, saturation, &mut |elem| { - push(elem.into()) - }); + xray.render( + ctx, + params, + xray_pos, + blur, + noise, + saturation, + &mut |elem| push(elem.into()), + ); } else { // Render non-xray effect. } @@ -160,6 +191,7 @@ pub fn render_for_tile( scale: f64, clip_to_geometry: bool, surface: &WlSurface, + blur_config: niri_config::Blur, radius: CornerRadius, effect: niri_config::BackgroundEffect, xray_pos: XrayPos, @@ -169,6 +201,7 @@ pub fn render_for_tile( let background_effect = SurfaceBackgroundEffect::get(states); let mut background_effect = background_effect.0.lock().unwrap(); + background_effect.update_config(blur_config); background_effect.update_render_elements(radius, effect); if !background_effect.is_visible() { diff --git a/src/render_helpers/blur.rs b/src/render_helpers/blur.rs new file mode 100644 index 00000000..17041d08 --- /dev/null +++ b/src/render_helpers/blur.rs @@ -0,0 +1,355 @@ +use std::cmp::max; +use std::iter::{once, zip}; +use std::rc::Rc; + +use anyhow::{ensure, Context as _}; +use smithay::backend::allocator::Fourcc; +use smithay::backend::renderer::gles::{ + ffi, link_program, GlesError, GlesFrame, GlesRenderer, GlesTexture, +}; +use smithay::backend::renderer::{ContextId, Frame as _, Renderer as _, Texture as _}; +use smithay::gpu_span_location; +use smithay::utils::{Buffer, Size}; + +use crate::render_helpers::shaders::Shaders; + +#[derive(Debug)] +pub struct Blur { + program: BlurProgram, + /// Context ID of the renderer that created the program and the textures. + renderer_context_id: ContextId, + /// Output texture followed by intermediate textures, large to small. + /// + /// Created lazily and stored here to avoid recreating blur textures frequently. + textures: Vec, +} + +#[derive(Debug, Default, Clone, Copy, PartialEq)] +pub struct BlurOptions { + pub passes: u8, + pub offset: f64, +} + +impl From for BlurOptions { + fn from(config: niri_config::Blur) -> Self { + Self { + passes: config.passes, + offset: config.offset, + } + } +} + +#[derive(Debug, Clone)] +pub struct BlurProgram(Rc); + +#[derive(Debug)] +struct BlurProgramInner { + down: BlurProgramInternal, + up: BlurProgramInternal, +} + +#[derive(Debug)] +struct BlurProgramInternal { + program: ffi::types::GLuint, + uniform_tex: ffi::types::GLint, + uniform_half_pixel: ffi::types::GLint, + uniform_offset: ffi::types::GLint, + attrib_vert: ffi::types::GLint, +} + +unsafe fn compile_program(gl: &ffi::Gles2, src: &str) -> Result { + let program = unsafe { link_program(gl, include_str!("shaders/blur.vert"), src)? }; + + let vert = c"vert"; + let tex = c"tex"; + let half_pixel = c"half_pixel"; + let offset = c"offset"; + + Ok(BlurProgramInternal { + program, + uniform_tex: gl.GetUniformLocation(program, tex.as_ptr()), + uniform_half_pixel: gl.GetUniformLocation(program, half_pixel.as_ptr()), + uniform_offset: gl.GetUniformLocation(program, offset.as_ptr()), + attrib_vert: gl.GetAttribLocation(program, vert.as_ptr()), + }) +} + +impl BlurProgram { + pub fn compile(renderer: &mut GlesRenderer) -> anyhow::Result { + renderer + .with_context(move |gl| unsafe { + let down = compile_program(gl, include_str!("shaders/blur_down.frag")) + .context("error compiling blur_down shader")?; + let up = compile_program(gl, include_str!("shaders/blur_up.frag")) + .context("error compiling blur_up shader")?; + Ok(Self(Rc::new(BlurProgramInner { down, up }))) + }) + .context("error making GL context current")? + } + + pub fn destroy(self, renderer: &mut GlesRenderer) -> Result<(), GlesError> { + renderer.with_context(move |gl| unsafe { + gl.DeleteProgram(self.0.down.program); + gl.DeleteProgram(self.0.up.program); + }) + } +} + +impl Blur { + pub fn new(renderer: &mut GlesRenderer) -> Option { + let program = Shaders::get(renderer).blur.clone()?; + Some(Self { + program, + renderer_context_id: renderer.context_id(), + textures: Vec::new(), + }) + } + + pub fn context_id(&self) -> ContextId { + self.renderer_context_id.clone() + } + + pub fn prepare_textures( + &mut self, + mut create_texture: impl FnMut(Fourcc, Size) -> Result, + source: &GlesTexture, + options: BlurOptions, + ) -> anyhow::Result<()> { + let _span = tracy_client::span!("Blur::prepare_textures"); + + let passes = options.passes.clamp(1, 31) as usize; + let size = source.size(); + + if let Some(output) = self.textures.first_mut() { + let old_size = output.size(); + if old_size != size { + trace!( + "recreating textures: output size changed from {} × {} to {} × {}", + old_size.w, + old_size.h, + size.w, + size.h + ); + self.textures.clear(); + } else if !output.is_unique_reference() { + debug!("recreating textures: not unique",); + // We only need to recreate the output texture here, but this case shouldn't really + // happen anyway, and this is simpler. + self.textures.clear(); + } + } + + // Create any missing textures. + let mut w = size.w; + let mut h = size.h; + for i in 0..=passes { + let size = Size::new(w, h); + w = max(1, w / 2); + h = max(1, h / 2); + + if self.textures.len() > i { + // This texture already exists. + continue; + } + + // debug!("creating texture for step {i} sized {w} × {h}"); + + let texture: GlesTexture = + create_texture(Fourcc::Abgr8888, size).context("error creating texture")?; + self.textures.push(texture); + } + + // Drop any no longer needed textures. + self.textures.drain(passes + 1..); + + Ok(()) + } + + pub fn render( + &mut self, + frame: &mut GlesFrame, + source: &GlesTexture, + options: BlurOptions, + ) -> anyhow::Result { + let _span = tracy_client::span!("Blur::render"); + trace!("rendering blur"); + + ensure!( + frame.context_id() == self.renderer_context_id, + "wrong renderer" + ); + + let passes = options.passes.clamp(1, 31) as usize; + let size = source.size(); + + ensure!( + self.textures.len() == passes + 1, + "wrong textures len: expected {}, got {}", + passes + 1, + self.textures.len() + ); + + let output = &mut self.textures[0]; + ensure!( + output.size() == size, + "wrong output texture size: expected {size:?}, got {:?}", + output.size() + ); + + ensure!( + output.is_unique_reference(), + "output texture has a non-unique reference" + ); + + frame.with_profiled_context(gpu_span_location!("Blur::render"), |gl| unsafe { + while gl.GetError() != ffi::NO_ERROR {} + + let mut current_fbo = 0i32; + let mut viewport = [0i32; 4]; + gl.GetIntegerv(ffi::FRAMEBUFFER_BINDING, &mut current_fbo as *mut _); + gl.GetIntegerv(ffi::VIEWPORT, viewport.as_mut_ptr()); + + gl.Disable(ffi::BLEND); + gl.Disable(ffi::SCISSOR_TEST); + + gl.ActiveTexture(ffi::TEXTURE0); + + let mut fbos = [0; 2]; + gl.GenFramebuffers(fbos.len() as _, fbos.as_mut_ptr()); + gl.BindFramebuffer(ffi::DRAW_FRAMEBUFFER, fbos[0]); + + let program = &self.program.0.down; + gl.UseProgram(program.program); + gl.Uniform1i(program.uniform_tex, 0); + gl.Uniform1f(program.uniform_offset, options.offset as f32); + + let vertices: [f32; 12] = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0]; + gl.EnableVertexAttribArray(program.attrib_vert as u32); + gl.BindBuffer(ffi::ARRAY_BUFFER, 0); + gl.VertexAttribPointer( + program.attrib_vert as u32, + 2, + ffi::FLOAT, + ffi::FALSE, + 0, + vertices.as_ptr().cast(), + ); + + let src = once(source).chain(&self.textures[1..]); + let dst = &self.textures[1..]; + for (src, dst) in zip(src, dst) { + let dst_size = dst.size(); + let w = dst_size.w; + let h = dst_size.h; + gl.Viewport(0, 0, w, h); + + // During downsampling, half_pixel is half of the destination pixel. + gl.Uniform2f(program.uniform_half_pixel, 0.5 / w as f32, 0.5 / h as f32); + + let src = src.tex_id(); + let dst = dst.tex_id(); + + trace!("drawing down {src} to {dst}"); + gl.FramebufferTexture2D( + ffi::DRAW_FRAMEBUFFER, + ffi::COLOR_ATTACHMENT0, + ffi::TEXTURE_2D, + dst, + 0, + ); + + gl.BindTexture(ffi::TEXTURE_2D, src); + gl.TexParameteri(ffi::TEXTURE_2D, ffi::TEXTURE_MIN_FILTER, ffi::LINEAR as i32); + gl.TexParameteri(ffi::TEXTURE_2D, ffi::TEXTURE_MAG_FILTER, ffi::LINEAR as i32); + gl.TexParameteri( + ffi::TEXTURE_2D, + ffi::TEXTURE_WRAP_S, + ffi::CLAMP_TO_EDGE as i32, + ); + gl.TexParameteri( + ffi::TEXTURE_2D, + ffi::TEXTURE_WRAP_T, + ffi::CLAMP_TO_EDGE as i32, + ); + + gl.DrawArrays(ffi::TRIANGLES, 0, 6); + } + + gl.DisableVertexAttribArray(program.attrib_vert as u32); + + // Up + let program = &self.program.0.up; + gl.UseProgram(program.program); + gl.Uniform1i(program.uniform_tex, 0); + gl.Uniform1f(program.uniform_offset, options.offset as f32); + + let vertices: [f32; 12] = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0]; + gl.EnableVertexAttribArray(program.attrib_vert as u32); + gl.BindBuffer(ffi::ARRAY_BUFFER, 0); + gl.VertexAttribPointer( + program.attrib_vert as u32, + 2, + ffi::FLOAT, + ffi::FALSE, + 0, + vertices.as_ptr().cast(), + ); + + let src = self.textures.iter().rev(); + let dst = self.textures.iter().rev().skip(1); + for (src, dst) in zip(src, dst) { + let dst_size = dst.size(); + let w = dst_size.w; + let h = dst_size.h; + gl.Viewport(0, 0, w, h); + + // During upsampling, half_pixel is half of the source pixel. + let src_size = src.size(); + let src_w = src_size.w as f32; + let src_h = src_size.h as f32; + gl.Uniform2f(program.uniform_half_pixel, 0.5 / src_w, 0.5 / src_h); + + let src = src.tex_id(); + let dst = dst.tex_id(); + + trace!("drawing up {src} to {dst}"); + gl.FramebufferTexture2D( + ffi::DRAW_FRAMEBUFFER, + ffi::COLOR_ATTACHMENT0, + ffi::TEXTURE_2D, + dst, + 0, + ); + + gl.BindTexture(ffi::TEXTURE_2D, src); + gl.TexParameteri(ffi::TEXTURE_2D, ffi::TEXTURE_MIN_FILTER, ffi::LINEAR as i32); + gl.TexParameteri(ffi::TEXTURE_2D, ffi::TEXTURE_MAG_FILTER, ffi::LINEAR as i32); + gl.TexParameteri( + ffi::TEXTURE_2D, + ffi::TEXTURE_WRAP_S, + ffi::CLAMP_TO_EDGE as i32, + ); + gl.TexParameteri( + ffi::TEXTURE_2D, + ffi::TEXTURE_WRAP_T, + ffi::CLAMP_TO_EDGE as i32, + ); + + gl.DrawArrays(ffi::TRIANGLES, 0, 6); + } + + gl.DisableVertexAttribArray(program.attrib_vert as u32); + + gl.BindFramebuffer(ffi::FRAMEBUFFER, 0); + gl.DeleteFramebuffers(fbos.len() as _, fbos.as_ptr()); + + // Restore state set by GlesFrame that we just modified. + gl.Enable(ffi::BLEND); + gl.Enable(ffi::SCISSOR_TEST); + gl.BindFramebuffer(ffi::FRAMEBUFFER, current_fbo as u32); + gl.Viewport(viewport[0], viewport[1], viewport[2], viewport[3]); + })?; + + Ok(self.textures[0].clone()) + } +} diff --git a/src/render_helpers/effect_buffer.rs b/src/render_helpers/effect_buffer.rs index fa060fd2..00a1c9a6 100644 --- a/src/render_helpers/effect_buffer.rs +++ b/src/render_helpers/effect_buffer.rs @@ -1,10 +1,10 @@ use std::mem; -use anyhow::Context as _; +use anyhow::{ensure, Context as _}; use smithay::backend::allocator::Fourcc; use smithay::backend::renderer::damage::OutputDamageTracker; use smithay::backend::renderer::element::{Id, RenderElementStates}; -use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture}; +use smithay::backend::renderer::gles::{GlesFrame, GlesRenderer, GlesTexture}; use smithay::backend::renderer::utils::CommitCounter; use smithay::backend::renderer::{ Bind as _, Color32F, ContextId, Offscreen as _, Renderer as _, Texture, @@ -12,6 +12,7 @@ use smithay::backend::renderer::{ use smithay::utils::{Buffer, Logical, Physical, Scale, Size, Transform}; use crate::niri::OutputRenderElements; +use crate::render_helpers::blur::{Blur, BlurOptions}; #[derive(Debug)] pub struct EffectBuffer { @@ -22,13 +23,17 @@ pub struct EffectBuffer { size: Size, /// Scale of the effect buffer. scale: Scale, + /// Options for blurring. + blur_options: BlurOptions, /// Elements to be rendered on demand. elements: Elements, /// Offscreen buffer where elements get rendered. offscreen: Option, + /// Blurring program, if available. + blur: Option, - /// Commit counter for the offscreen texture. + /// Commit counter that takes into account both original and blurred texture changes. commit_counter: CommitCounter, } @@ -55,6 +60,10 @@ struct Offscreen { damage: OutputDamageTracker, /// Render element states from the last render into the offscreen. states: RenderElementStates, + /// Rendered blurred version of the texture. + /// + /// When texture needs to be reblurred, this field must be reset to `None`. + blurred: Option, } impl Default for Elements { @@ -69,8 +78,10 @@ impl EffectBuffer { id: Id::new(), size: Size::default(), scale: Scale::from(1.), + blur_options: BlurOptions::default(), elements: Elements::default(), offscreen: None, + blur: None, commit_counter: CommitCounter::default(), } } @@ -100,6 +111,21 @@ impl EffectBuffer { self.scale = scale; } + pub fn update_blur_options(&mut self, options: BlurOptions) { + if self.blur_options == options { + return; + } + + self.blur_options = options; + + if let Some(offscreen) = &mut self.offscreen { + if offscreen.blurred.is_some() { + offscreen.blurred = None; + self.commit_counter.increment(); + } + } + } + pub fn elements(&mut self) -> &mut Vec> { // Assume we're going to insert new elements, switch to New. match mem::take(&mut self.elements) { @@ -113,12 +139,19 @@ impl EffectBuffer { elements } - pub fn prepare(&mut self, renderer: &mut GlesRenderer) -> bool { + pub fn prepare(&mut self, renderer: &mut GlesRenderer, blur: bool) -> bool { if let Err(err) = self.prepare_offscreen(renderer) { warn!("error preparing offscreen: {err:?}"); return false; }; + if blur { + if let Err(err) = self.prepare_blur(renderer) { + warn!("error preparing blur: {err:?}"); + return false; + } + } + true } @@ -176,6 +209,7 @@ impl EffectBuffer { scale: self.scale, damage, states: RenderElementStates::default(), + blurred: None, }) }; @@ -189,6 +223,7 @@ impl EffectBuffer { offscreen.damage = OutputDamageTracker::new(buffer_size, self.scale, Transform::Normal); self.commit_counter.increment(); + offscreen.blurred = None; } // Render the elements if any. @@ -215,6 +250,9 @@ impl EffectBuffer { if res.damage.is_some() { self.commit_counter.increment(); + + // Original texture changed; reset the blurred texture. + offscreen.blurred = None; } // Clear and put the storage back. @@ -224,8 +262,62 @@ impl EffectBuffer { Ok(()) } - pub fn render(&mut self) -> anyhow::Result { + fn prepare_blur(&mut self, renderer: &mut GlesRenderer) -> anyhow::Result<()> { + let offscreen = self.offscreen.as_mut().context("missing offscreen")?; + if offscreen.blurred.is_some() { + // Already rendered. + return Ok(()); + } + + if let Some(blur) = &self.blur { + if blur.context_id() != renderer.context_id() { + debug!("recreating blur: renderer changed"); + self.blur = None; + } + } + + let blur = if let Some(blur) = &mut self.blur { + blur + } else { + let Some(blur) = Blur::new(renderer) else { + // Missing blur shader. + return Ok(()); + }; + self.blur.insert(blur) + }; + + ensure!( + offscreen.renderer_context_id == renderer.context_id(), + "wrong renderer context id" + ); + + blur.prepare_textures( + |fourcc, size| renderer.create_buffer(fourcc, size), + &offscreen.texture, + self.blur_options, + ) + .context("error preparing blur textures")?; + + Ok(()) + } + + pub fn render(&mut self, frame: &mut GlesFrame, blur: bool) -> anyhow::Result { let offscreen = self.offscreen.as_mut().context("offscreen is missing")?; - Ok(offscreen.texture.clone()) + + if !blur { + return Ok(offscreen.texture.clone()); + } + + let texture = if let Some(texture) = &offscreen.blurred { + texture.clone() + } else { + let blur = self.blur.as_mut().context("blur is missing")?; + let blurred = blur + .render(frame, &offscreen.texture, self.blur_options) + .context("error rendering blur")?; + offscreen.blurred.insert(blurred).clone() + }; + + Ok(texture) } } diff --git a/src/render_helpers/mod.rs b/src/render_helpers/mod.rs index 5f6ac806..64ea997f 100644 --- a/src/render_helpers/mod.rs +++ b/src/render_helpers/mod.rs @@ -25,6 +25,7 @@ use crate::render_helpers::renderer::AsGlesRenderer; use crate::render_helpers::xray::Xray; pub mod background_effect; +pub mod blur; pub mod border; pub mod clipped_surface; pub mod damage; diff --git a/src/render_helpers/shaders/blur.vert b/src/render_helpers/shaders/blur.vert new file mode 100644 index 00000000..c796897c --- /dev/null +++ b/src/render_helpers/shaders/blur.vert @@ -0,0 +1,11 @@ +#version 100 + +attribute vec2 vert; +varying vec2 v_coords; + +void main() { + v_coords = vert; + // vert goes from 0 to 1; position must be from -1 to 1. + vec2 position = vert * 2.0 - 1.0; + gl_Position = vec4(position, 1.0, 1.0); +} diff --git a/src/render_helpers/shaders/blur_down.frag b/src/render_helpers/shaders/blur_down.frag new file mode 100644 index 00000000..bc4c5fa2 --- /dev/null +++ b/src/render_helpers/shaders/blur_down.frag @@ -0,0 +1,21 @@ +#version 100 + +precision highp float; + +varying vec2 v_coords; + +uniform sampler2D tex; +uniform vec2 half_pixel; +uniform float offset; + +void main() { + vec2 o = half_pixel * offset; + + vec4 sum = texture2D(tex, v_coords) * 4.0; + sum += texture2D(tex, v_coords + vec2(-o.x, -o.y)); + sum += texture2D(tex, v_coords + vec2( o.x, -o.y)); + sum += texture2D(tex, v_coords + vec2(-o.x, o.y)); + sum += texture2D(tex, v_coords + vec2( o.x, o.y)); + + gl_FragColor = sum / 8.0; +} diff --git a/src/render_helpers/shaders/blur_up.frag b/src/render_helpers/shaders/blur_up.frag new file mode 100644 index 00000000..d5651582 --- /dev/null +++ b/src/render_helpers/shaders/blur_up.frag @@ -0,0 +1,29 @@ +#version 100 + +precision highp float; + +varying vec2 v_coords; + +uniform sampler2D tex; +uniform vec2 half_pixel; +uniform float offset; + +void main() { + vec2 o = half_pixel * offset; + + vec4 sum = vec4(0.0); + + // Four edge centers + sum += texture2D(tex, v_coords + vec2(-o.x * 2.0, 0.0)); + sum += texture2D(tex, v_coords + vec2( o.x * 2.0, 0.0)); + sum += texture2D(tex, v_coords + vec2(0.0, -o.y * 2.0)); + sum += texture2D(tex, v_coords + vec2(0.0, o.y * 2.0)); + + // Four diagonal corners + sum += texture2D(tex, v_coords + vec2(-o.x, o.y)) * 2.0; + sum += texture2D(tex, v_coords + vec2( o.x, o.y)) * 2.0; + sum += texture2D(tex, v_coords + vec2(-o.x, -o.y)) * 2.0; + sum += texture2D(tex, v_coords + vec2( o.x, -o.y)) * 2.0; + + gl_FragColor = sum / 12.0; +} diff --git a/src/render_helpers/shaders/mod.rs b/src/render_helpers/shaders/mod.rs index 4851cd7a..7be9b159 100644 --- a/src/render_helpers/shaders/mod.rs +++ b/src/render_helpers/shaders/mod.rs @@ -8,6 +8,7 @@ use smithay::backend::renderer::gles::{ use super::renderer::NiriRenderer; use super::shader_element::ShaderProgram; +use crate::render_helpers::blur::BlurProgram; pub struct Shaders { pub border: Option, @@ -16,6 +17,7 @@ pub struct Shaders { pub postprocess_and_clip: Option, pub resize: Option, pub gradient_fade: Option, + pub blur: Option, pub custom_resize: RefCell>, pub custom_close: RefCell>, pub custom_open: RefCell>, @@ -140,6 +142,12 @@ impl Shaders { }) .ok(); + let blur = BlurProgram::compile(renderer) + .map_err(|err| { + warn!("error compiling blur shaders: {err:?}"); + }) + .ok(); + Self { border, shadow, @@ -147,6 +155,7 @@ impl Shaders { postprocess_and_clip, resize, gradient_fade, + blur, custom_resize: RefCell::new(None), custom_close: RefCell::new(None), custom_open: RefCell::new(None), diff --git a/src/render_helpers/xray.rs b/src/render_helpers/xray.rs index 6ed4b179..36ddf63a 100644 --- a/src/render_helpers/xray.rs +++ b/src/render_helpers/xray.rs @@ -73,6 +73,7 @@ pub struct XrayElement { clip_geo_size: Vec2, corner_radius: CornerRadius, scale: f32, + blur: bool, noise: f32, saturation: f32, bg_color: Color32F, @@ -95,6 +96,7 @@ impl Xray { ctx: RenderCtx, params: RenderParams, xray_pos: XrayPos, + blur: bool, noise: f32, saturation: f32, push: &mut dyn FnMut(XrayElement), @@ -121,7 +123,7 @@ impl Xray { let mut background = self.background[ctx.target as usize].borrow_mut(); let prev = background.commit(); - if background.prepare(ctx.renderer) { + if background.prepare(ctx.renderer, blur) { if background.commit() != prev { trace!("background damaged"); } @@ -191,6 +193,7 @@ impl Xray { clip_geo_size, corner_radius, scale: params.scale as f32, + blur, noise, saturation, bg_color: *bg_color, @@ -206,7 +209,7 @@ impl Xray { } let prev = backdrop.commit(); - if backdrop.prepare(ctx.renderer) { + if backdrop.prepare(ctx.renderer, blur) { if backdrop.commit() != prev { trace!("backdrop damaged"); } @@ -239,6 +242,7 @@ impl Xray { clip_geo_size, corner_radius: corner_radius.scaled_by(zoom as f32), scale: params.scale as f32, + blur, noise, saturation, bg_color: self.backdrop_color, @@ -297,7 +301,7 @@ impl RenderElement for XrayElement { _opaque_regions: &[Rectangle], ) -> Result<(), GlesError> { let mut buffer = self.buffer.borrow_mut(); - let texture = match buffer.render() { + let texture = match buffer.render(frame, self.blur) { Ok(x) => x, Err(err) => { warn!("error rendering effect buffer: {err:?}"); diff --git a/src/window/mapped.rs b/src/window/mapped.rs index 831edc85..31e98db6 100644 --- a/src/window/mapped.rs +++ b/src/window/mapped.rs @@ -106,6 +106,9 @@ pub struct Mapped { /// Buffer to draw instead of the window when it should be blocked out. block_out_buffer: RefCell, + /// The blur config, passed for background effect rendering. + blur_config: niri_config::Blur, + /// Whether the next configure should be animated, if the configured state changed. animate_next_configure: bool, @@ -251,7 +254,7 @@ enum RequestSizeOnce { } impl Mapped { - pub fn new(window: Window, rules: ResolvedWindowRules, hook: HookId) -> Self { + pub fn new(window: Window, rules: ResolvedWindowRules, hook: HookId, config: &Config) -> Self { let surface = window.wl_surface().expect("no X11 support"); let credentials = get_credentials_for_surface(&surface); let mut rv = Self { @@ -271,6 +274,7 @@ impl Mapped { is_window_cast_target: false, ignore_opacity_window_rule: false, block_out_buffer: RefCell::new(SolidColorBuffer::new((0., 0.), [0., 0., 0., 1.])), + blur_config: config.blur, animate_next_configure: false, animate_serials: Vec::new(), animation_snapshot: None, @@ -604,6 +608,10 @@ impl LayoutElement for Mapped { &self.window } + fn update_config(&mut self, blur_config: niri_config::Blur) { + self.blur_config = blur_config; + } + fn size(&self) -> Size { self.window.geometry().size } @@ -691,6 +699,7 @@ impl LayoutElement for Mapped { scale, clip_to_geometry, self.toplevel().wl_surface(), + self.blur_config, radius, self.rules.background_effect, xray_pos,