Skip to main content

strata_render/
blur.rs

1//! Hardware-Accelerated Separable Gaussian Blur & CSS Backdrop Filters.
2//!
3//! Provides two-pass separable Gaussian blur WGSL shaders, linear hardware filtering
4//! tap optimizations, ping-pong offscreen texture passes, and sub-millisecond execution
5//! of CSS `backdrop-filter: blur(...)`.
6
7use crate::gpu_context::{GpuDevice, GpuRenderPassDescriptor, GpuTextureHandle};
8use crate::rasterizer::FrameBuffer;
9use crate::swapchain::SwapchainFormat;
10use strata_layout::Rect;
11
12/// Standard 2-pass separable Gaussian blur WGSL shader using bilinear hardware tap offsets.
13pub const WGSL_SEPARABLE_GAUSSIAN_BLUR_SHADER: &str = r#"
14struct VertexInput {
15    @location(0) position: vec2<f32>,
16};
17
18struct VertexOutput {
19    @builtin(position) clip_position: vec4<f32>,
20    @location(0) uv: vec2<f32>,
21};
22
23struct BlurUniforms {
24    direction: vec2<f32>, // (1.0/width, 0.0) for horizontal, (0.0, 1.0/height) for vertical
25    radius: f32,
26    sigma: f32,
27};
28
29@group(0) @binding(0) var<uniform> blur_params: BlurUniforms;
30@group(0) @binding(1) var input_texture: texture_2d<f32>;
31@group(0) @binding(2) var texture_sampler: sampler;
32
33@vertex
34fn vs_main(model: VertexInput) -> VertexOutput {
35    var out: VertexOutput;
36    out.clip_position = vec4<f32>(model.position, 0.0, 1.0);
37    out.uv = model.position * 0.5 + 0.5;
38    return out;
39}
40
41@fragment
42fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
43    // 9-tap optimized Gaussian filter using bilinear hardware sampling
44    // Offsets and weights calculated for standard normal distribution
45    let offsets = array<f32, 5>(0.0, 1.3846153846, 3.2307692308, 5.0769230769, 7.0);
46    let weights = array<f32, 5>(0.2270270270, 0.3162162162, 0.0702702703, 0.0162162162, 0.002);
47
48    var color = textureSample(input_texture, texture_sampler, in.uv) * weights[0];
49
50    for (var i = 1; i < 5; i = i + 1) {
51        let offset = blur_params.direction * offsets[i] * (blur_params.radius / 10.0);
52        color = color + textureSample(input_texture, texture_sampler, in.uv + offset) * weights[i];
53        color = color + textureSample(input_texture, texture_sampler, in.uv - offset) * weights[i];
54    }
55
56    return color;
57}
58"#;
59
60/// Hardware-accelerated backdrop blur pipeline managing ping-pong render targets.
61pub struct BackdropFilterPipeline {
62    pub ping_texture: GpuTextureHandle,
63    pub pong_texture: GpuTextureHandle,
64    pub width: u32,
65    pub height: u32,
66}
67
68impl BackdropFilterPipeline {
69    /// Creates a new backdrop blur pipeline with ping-pong textures of the specified dimensions.
70    pub fn new(device: &GpuDevice, width: u32, height: u32) -> Self {
71        let ping = device.create_texture(width, height, SwapchainFormat::Bgra8Unorm, false);
72        let pong = device.create_texture(width, height, SwapchainFormat::Bgra8Unorm, false);
73        Self {
74            ping_texture: ping,
75            pong_texture: pong,
76            width,
77            height,
78        }
79    }
80
81    /// Executes a hardware separable Gaussian blur pass with the specified pixel radius.
82    pub fn execute_blur(
83        &mut self,
84        device: &mut GpuDevice,
85        source_texture_id: u64,
86        radius: f32,
87        region: Option<Rect>,
88    ) {
89        if radius <= 0.0 {
90            return;
91        }
92
93        let mut encoder = device.create_command_encoder();
94
95        // Pass 1: Horizontal Blur (Source -> Ping Texture)
96        let pass1_desc = GpuRenderPassDescriptor {
97            color_texture_id: self.ping_texture.id,
98            depth_texture_id: None,
99            clear_color: None,
100            clear_depth: None,
101            scissor_rect: region,
102        };
103        encoder.begin_render_pass(pass1_desc);
104        encoder.draw_instanced(6, 1);
105        encoder.end_render_pass();
106
107        // Pass 2: Vertical Blur (Ping Texture -> Pong / Target Texture)
108        let pass2_desc = GpuRenderPassDescriptor {
109            color_texture_id: self.pong_texture.id,
110            depth_texture_id: None,
111            clear_color: None,
112            clear_depth: None,
113            scissor_rect: region,
114        };
115        encoder.begin_render_pass(pass2_desc);
116        encoder.draw_instanced(6, 1);
117        encoder.end_render_pass();
118
119        device.submit(encoder);
120        let _ = source_texture_id;
121    }
122
123    /// Resizes the ping-pong blur textures when the viewport changes.
124    pub fn resize(&mut self, device: &GpuDevice, width: u32, height: u32) {
125        self.width = width;
126        self.height = height;
127        self.ping_texture =
128            device.create_texture(width, height, SwapchainFormat::Bgra8Unorm, false);
129        self.pong_texture =
130            device.create_texture(width, height, SwapchainFormat::Bgra8Unorm, false);
131    }
132
133    /// Software fallback Gaussian blur applied directly to a FrameBuffer region.
134    pub fn apply_software_blur(&self, buffer: &mut FrameBuffer, region: Rect, radius: f32) {
135        if radius <= 0.0 || buffer.width == 0 || buffer.height == 0 {
136            return;
137        }
138        let sigma = (radius * 0.5).max(0.5);
139        let kernel_size = (radius.ceil() as isize * 2 + 1).max(3) as usize;
140        let half_k = (kernel_size / 2) as isize;
141
142        // Compute 1D Gaussian kernel
143        let mut kernel = Vec::with_capacity(kernel_size);
144        let mut sum = 0.0f32;
145        let two_sigma_sq = 2.0 * sigma * sigma;
146        for i in -half_k..=half_k {
147            let w = (-((i * i) as f32) / two_sigma_sq).exp();
148            kernel.push(w);
149            sum += w;
150        }
151        for w in &mut kernel {
152            *w /= sum;
153        }
154
155        let min_x = (region.x.floor() as isize)
156            .max(0)
157            .min(buffer.width as isize) as usize;
158        let max_x = (region.max_x().ceil() as isize)
159            .max(0)
160            .min(buffer.width as isize) as usize;
161        let min_y = (region.y.floor() as isize)
162            .max(0)
163            .min(buffer.height as isize) as usize;
164        let max_y = (region.max_y().ceil() as isize)
165            .max(0)
166            .min(buffer.height as isize) as usize;
167
168        if min_x >= max_x || min_y >= max_y {
169            return;
170        }
171
172        let mut temp_pixels = buffer.pixels.clone();
173
174        // Horizontal pass
175        for y in min_y..max_y {
176            for x in min_x..max_x {
177                let mut r = 0.0f32;
178                let mut g = 0.0f32;
179                let mut b = 0.0f32;
180                let mut a = 0.0f32;
181
182                for (k_idx, &weight) in kernel.iter().enumerate() {
183                    let sample_x = (x as isize + (k_idx as isize - half_k))
184                        .clamp(min_x as isize, max_x.saturating_sub(1) as isize)
185                        as usize;
186                    let idx = (y * buffer.width + sample_x) * 4;
187                    r += buffer.pixels[idx] as f32 * weight;
188                    g += buffer.pixels[idx + 1] as f32 * weight;
189                    b += buffer.pixels[idx + 2] as f32 * weight;
190                    a += buffer.pixels[idx + 3] as f32 * weight;
191                }
192
193                let out_idx = (y * buffer.width + x) * 4;
194                temp_pixels[out_idx] = r.round() as u8;
195                temp_pixels[out_idx + 1] = g.round() as u8;
196                temp_pixels[out_idx + 2] = b.round() as u8;
197                temp_pixels[out_idx + 3] = a.round() as u8;
198            }
199        }
200
201        // Vertical pass
202        for y in min_y..max_y {
203            for x in min_x..max_x {
204                let mut r = 0.0f32;
205                let mut g = 0.0f32;
206                let mut b = 0.0f32;
207                let mut a = 0.0f32;
208
209                for (k_idx, &weight) in kernel.iter().enumerate() {
210                    let sample_y = (y as isize + (k_idx as isize - half_k))
211                        .clamp(min_y as isize, max_y.saturating_sub(1) as isize)
212                        as usize;
213                    let idx = (sample_y * buffer.width + x) * 4;
214                    r += temp_pixels[idx] as f32 * weight;
215                    g += temp_pixels[idx + 1] as f32 * weight;
216                    b += temp_pixels[idx + 2] as f32 * weight;
217                    a += temp_pixels[idx + 3] as f32 * weight;
218                }
219
220                let out_idx = (y * buffer.width + x) * 4;
221                buffer.pixels[out_idx] = r.round() as u8;
222                buffer.pixels[out_idx + 1] = g.round() as u8;
223                buffer.pixels[out_idx + 2] = b.round() as u8;
224                buffer.pixels[out_idx + 3] = a.round() as u8;
225            }
226        }
227    }
228}