Skip to content

Visual Studio Code, rebuilt in Rust

Rust

feat(gpui_apple): blur backdrops as Chromium's backdrop-filter

rokartur3ed57f248a0c
diff --git a/native/crates/app/src/corner_lab.rs b/native/crates/app/src/corner_lab.rs
index 22f33180619..80e3e1b0c00 100644
--- a/native/crates/app/src/corner_lab.rs
+++ b/native/crates/app/src/corner_lab.rs
@@ -64,13 +64,12 @@ fn lab_box(index: usize, case: &Value) -> Div {
}]);
}
// frostedGlass.css's `::before`, as Workbench::frosted_glass paints it.
- if backdrop.is_some() {
+ if let Some(blur) = backdrop {
let fill = color(&case["bg"]);
let radii = gpui::Corners::all(px(radii[0] - borders[0]));
element = element.child(
gpui::canvas(|_, _, _| (), move |bounds, _, window, _| {
- // shortcut: gpui-fast has no backdrop blur yet, the tint alone; the backdrop cases fail until it is ported.
- window.paint_quad(gpui::fill(bounds, fill).corner_radii(radii));
+ window.paint_backdrop_blur(bounds, radii, px(blur), fill);
})
.absolute()
.inset_0(),
diff --git a/native/crates/app/src/workbench/quick_input_view.rs b/native/crates/app/src/workbench/quick_input_view.rs
index 14af4309b8b..3c26e1f65d0 100644
--- a/native/crates/app/src/workbench/quick_input_view.rs
+++ b/native/crates/app/src/workbench/quick_input_view.rs
@@ -434,7 +434,8 @@ impl Workbench {
/// is behind it, inside a 1px border with `radius` corners. Without glass the solid surface color.
pub(super) fn frosted_glass(&self, surface: &str, radius: f32) -> impl IntoElement {
let mut color = self.color(surface);
- if self.frosted_glass_enabled() {
+ let glass = self.frosted_glass_enabled();
+ if glass {
color.a *= self.frosted_glass_opacity();
}
canvas(
@@ -442,9 +443,10 @@ impl Workbench {
move |bounds, _, window, _| {
// Inside the 1px border, so the corners follow the padding box.
let radii = gpui::Corners::all(px(radius - 1.));
- // shortcut: gpui-fast has no backdrop blur (Wu's `paint_backdrop_blur`), so the glass tint paints over an
- // unblurred backdrop; port the blur to restore it (port/notes.md "GPUI on gpui-fast").
- window.paint_quad(gpui::fill(bounds, color).corner_radii(radii));
+ match glass {
+ true => window.paint_backdrop_blur(bounds, radii, px(12.), color),
+ false => window.paint_quad(gpui::fill(bounds, color).corner_radii(radii)),
+ }
},
)
.absolute()
diff --git a/native/vendor/gpui-fast/crates/gpui/src/fast/backdrop.rs b/native/vendor/gpui-fast/crates/gpui/src/fast/backdrop.rs
new file mode 100644
index 00000000000..acafe8a8dd7
--- /dev/null
+++ b/native/vendor/gpui-fast/crates/gpui/src/fast/backdrop.rs
@@ -0,0 +1,110 @@
+//! Backdrop blur (CSS `backdrop-filter: blur()`), handed to the renderer as a
+//! polychrome sprite whose texture index no atlas allocates, as layer tiles
+//! and rounded clips are: the scene orders, replays and clips it like any
+//! sprite. The tile carries the blur instead of a texture region: `tile_id`
+//! the blur radius in device pixels as `f32` bits, `bounds` the tint's
+//! `h, s, l, a` as `f32` bits (the Metal shader reads them back).
+
+use crate::{
+ AtlasTextureId, AtlasTextureKind, AtlasTile, Bounds, ContentMask, Corners, DevicePixels, Hsla,
+ PolychromeSprite, ScaledPixels, TileId, point, size,
+};
+
+/// The texture index of a backdrop blur sprite, above every layer tile and
+/// rounded clip index.
+pub const BACKDROP_TEXTURE_INDEX: u32 = u32::MAX;
+
+pub(crate) fn sprite(
+ bounds: Bounds<ScaledPixels>,
+ content_mask: ContentMask<ScaledPixels>,
+ corner_radii: Corners<ScaledPixels>,
+ blur_radius: ScaledPixels,
+ tint: Hsla,
+) -> PolychromeSprite {
+ let bits = |value: f32| DevicePixels(value.to_bits() as i32);
+ PolychromeSprite {
+ order: 0,
+ pad: 0,
+ grayscale: false.into(),
+ opacity: 1.,
+ bounds,
+ content_mask,
+ corner_radii,
+ tile: AtlasTile {
+ texture_id: AtlasTextureId {
+ index: BACKDROP_TEXTURE_INDEX,
+ kind: AtlasTextureKind::Polychrome,
+ },
+ tile_id: TileId(blur_radius.0.to_bits()),
+ padding: 0,
+ bounds: Bounds {
+ origin: point(bits(tint.h), bits(tint.s)),
+ size: size(bits(tint.l), bits(tint.a)),
+ },
+ },
+ }
+}
+
+/// The blur radius in device pixels of a backdrop blur sprite, `None` for
+/// any other sprite.
+pub fn backdrop_blur_radius(sprite: &PolychromeSprite) -> Option<f32> {
+ (sprite.tile.texture_id.index == BACKDROP_TEXTURE_INDEX)
+ .then(|| f32::from_bits(sprite.tile.tile_id.0))
+}
+
+/// The tint painted over a backdrop blur sprite's blurred backdrop.
+pub fn backdrop_tint(sprite: &PolychromeSprite) -> Hsla {
+ let value = |pixels: DevicePixels| f32::from_bits(pixels.0 as u32);
+ let bounds = sprite.tile.bounds;
+ Hsla {
+ h: value(bounds.origin.x),
+ s: value(bounds.origin.y),
+ l: value(bounds.size.width),
+ a: value(bounds.size.height),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{hsla, px};
+
+ #[test]
+ fn a_backdrop_sprite_carries_its_blur_radius_and_tint() {
+ let bounds = Bounds::new(point(px(1.), px(2.)), size(px(30.), px(40.))).scale(2.);
+ let tint = hsla(0.6, 0.5, 0.25, 0.75);
+ let sprite = sprite(bounds, ContentMask { bounds }, Corners::all(px(8.)).scale(2.), ScaledPixels(24.), tint);
+ assert_eq!(backdrop_blur_radius(&sprite), Some(24.));
+ assert_eq!(backdrop_tint(&sprite), tint);
+ }
+
+ #[crate::test]
+ fn inside_a_layer_a_backdrop_blur_is_its_tint_quad(cx: &mut crate::TestAppContext) {
+ use crate::{IntoElement, Styled, Window, canvas};
+ struct Layered;
+ impl crate::Render for Layered {
+ fn render(&mut self, _: &mut Window, _: &mut crate::Context<Self>) -> impl IntoElement {
+ canvas(
+ |_, _, _| {},
+ |bounds, _, window, _| {
+ let glass = Bounds::new(bounds.origin, size(px(40.), px(30.)));
+ window.paint_backdrop_blur(glass, Corners::all(px(4.)), px(12.), hsla(0.6, 0.5, 0.5, 0.5));
+ window.paint_layer(bounds, |window| {
+ window.paint_backdrop_blur(glass, Corners::all(px(4.)), px(12.), hsla(0.3, 0.5, 0.5, 0.5));
+ });
+ },
+ )
+ .size_full()
+ }
+ }
+ let (_, cx) = cx.add_window_view(|_, _| Layered);
+ cx.run_until_parked();
+ cx.update(|window, _| {
+ let scene = &window.rendered_frame.scene;
+ let sprites: Vec<_> = scene.polychrome_sprites.iter().map(backdrop_tint).collect();
+ assert_eq!(sprites, [hsla(0.6, 0.5, 0.5, 0.5)]);
+ let quads: Vec<_> = scene.quads.iter().map(|quad| quad.background.solid).collect();
+ assert!(!quads.is_empty() && quads.iter().all(|color| *color == hsla(0.3, 0.5, 0.5, 0.5)), "{quads:?}");
+ });
+ }
+}
diff --git a/native/vendor/gpui-fast/crates/gpui/src/fast/mod.rs b/native/vendor/gpui-fast/crates/gpui/src/fast/mod.rs
index 8e1fb1abd92..e6ce544e7ab 100644
--- a/native/vendor/gpui-fast/crates/gpui/src/fast/mod.rs
+++ b/native/vendor/gpui-fast/crates/gpui/src/fast/mod.rs
@@ -16,6 +16,7 @@
pub(crate) mod a11y;
pub(crate) mod app_borrow;
+pub(crate) mod backdrop;
pub(crate) mod bidi_wrap;
pub(crate) mod clock;
pub(crate) mod composition;
diff --git a/native/vendor/gpui-fast/crates/gpui/src/gpui.rs b/native/vendor/gpui-fast/crates/gpui/src/gpui.rs
index 8b24282827c..2ed07bc7c79 100644
--- a/native/vendor/gpui-fast/crates/gpui/src/gpui.rs
+++ b/native/vendor/gpui-fast/crates/gpui/src/gpui.rs
@@ -128,6 +128,7 @@ pub use elements::*;
pub use executor::*;
#[doc(hidden)]
pub use fast::app_borrow::app_is_borrowed;
+pub use fast::backdrop::{BACKDROP_TEXTURE_INDEX, backdrop_blur_radius, backdrop_tint};
pub use fast::composition::{
ComposedScene, ComposedSceneLayer, CompositionSurfaceId, CompositionSurfaceKind,
PlatformCompositionSurface, PlatformCompositionSurfaceContent, PlatformSurfaceAttachment,
diff --git a/native/vendor/gpui-fast/crates/gpui/src/window.rs b/native/vendor/gpui-fast/crates/gpui/src/window.rs
index 1406d4305e2..c710e8af93a 100644
--- a/native/vendor/gpui-fast/crates/gpui/src/window.rs
+++ b/native/vendor/gpui-fast/crates/gpui/src/window.rs
@@ -5187,6 +5187,32 @@ impl Window {
)
}
+ /// Blur everything already painted beneath `bounds`, then paint `tint` over it; both take the rounded clip together.
+ /// Content painted afterwards stays sharp. Only Metal reads the backdrop: elsewhere, and inside a layer, whose
+ /// tiles do not hold what is under it, the tint is painted as a plain quad.
+ pub fn paint_backdrop_blur(
+ &mut self,
+ bounds: Bounds<Pixels>,
+ corner_radii: Corners<Pixels>,
+ blur_radius: Pixels,
+ tint: impl Into<Hsla>,
+ ) {
+ self.invalidator.debug_assert_paint();
+ if !cfg!(target_os = "macos") || !self.next_frame.scene.fast_top_level() {
+ self.paint_quad(fill(bounds, tint.into()).corner_radii(corner_radii));
+ return;
+ }
+ let scale_factor = self.scale_factor();
+ let sprite = crate::fast::backdrop::sprite(
+ bounds.scale(scale_factor),
+ self.content_mask().scale(scale_factor),
+ corner_radii.scale(scale_factor),
+ blur_radius.scale(scale_factor),
+ tint.into(),
+ );
+ self.next_frame.scene.insert_primitive(sprite);
+ }
+
/// Paint one or more quads into the scene for the next frame at the current stacking context.
/// Quads are colored rectangular regions with an optional background, border, and corner radius.
/// see [`fill`], [`outline`], and [`quad`] to construct this type.
diff --git a/native/vendor/gpui-fast/crates/gpui_apple/src/fast/backdrop.rs b/native/vendor/gpui-fast/crates/gpui_apple/src/fast/backdrop.rs
new file mode 100644
index 00000000000..899a1c5f05d
--- /dev/null
+++ b/native/vendor/gpui-fast/crates/gpui_apple/src/fast/backdrop.rs
@@ -0,0 +1,473 @@
+//! Backdrop blur (CSS `backdrop-filter: blur()`), ported from Wu's Metal
+//! renderer: the drawable so far is cropped to the element, mirrored past it
+//! and downscaled as Skia does, blurred with `MPSImageGaussianBlur`, then
+//! drawn back clipped to the element's rounded rect under its tint.
+//!
+//! Reading the drawable ends the render pass, which loses a memoryless depth
+//! buffer, so a scene with a backdrop blur is drawn in paint order without
+//! the opaque quad pre-pass (see `frame.rs`).
+
+use std::{mem, ptr::NonNull};
+
+use anyhow::{Context as _, Result};
+use gpui::{DevicePixels, PolychromeSprite, Scene, Size, backdrop_blur_radius, size};
+use objc2::{
+ class, msg_send,
+ rc::{Allocated, Retained},
+ runtime::{AnyObject, ProtocolObject},
+};
+use objc2_foundation::NSString;
+use objc2_metal::{
+ MTLCommandBuffer, MTLCommandEncoder, MTLDevice, MTLLibrary, MTLLoadAction, MTLPixelFormat,
+ MTLPrimitiveType, MTLRenderCommandEncoder, MTLRenderPassDescriptor,
+ MTLRenderPipelineDescriptor, MTLRenderPipelineState, MTLStorageMode, MTLStoreAction,
+ MTLTexture, MTLTextureDescriptor, MTLTextureUsage, MTLViewport,
+};
+
+use crate::fast::rounded_clip::{self, Clip};
+use crate::metal_renderer::{
+ GlobalInputIndex, InstanceBindings, MetalRenderer, SpriteInputIndex, build_pipeline_state,
+};
+
+#[link(name = "MetalPerformanceShaders", kind = "framework")]
+unsafe extern "C" {}
+
+const SCRATCH_RELEASE_AFTER_IDLE_FRAMES: u32 = 30;
+const MAX_TEXTURE_PAIRS: usize = 4;
+const MAX_TEXTURE_BYTES: usize = 32 * 1024 * 1024;
+const TEXTURE_SIZE_QUANTUM: usize = 64;
+const MAX_KERNELS: usize = 4;
+const MPS_IMAGE_EDGE_MODE_CLAMP: usize = 1;
+const SOURCE_RECT_INDEX: usize = 5;
+
+/// Skia blurs with a sigma of at most 4 (SkImageFilterTypes.cpp `FilterResult::Builder::blur`). A larger blur halves
+/// the backdrop `levels` times about its center, rounds the last level out to whole pixels, blurs that and scales back
+/// up bilinearly.
+const MAX_SKIA_SIGMA: f32 = 4.0;
+const MAX_DOWNSCALE_LEVELS: usize = 5;
+
+/// The render pass a scene is encoded into; a backdrop blur ends it and starts the next on the same target.
+pub(crate) struct Pass<'a> {
+ pub(crate) encoder: Retained<ProtocolObject<dyn MTLRenderCommandEncoder>>,
+ pub(crate) command_buffer: &'a ProtocolObject<dyn MTLCommandBuffer>,
+ pub(crate) texture: &'a ProtocolObject<dyn MTLTexture>,
+ pub(crate) depth_texture: Retained<ProtocolObject<dyn MTLTexture>>,
+}
+
+pub(crate) struct Backdrop {
+ blur_pipeline: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
+ downscale_pipeline: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
+ /// Scratch and blurred textures of one size, least recently used first.
+ textures: Vec<[Retained<ProtocolObject<dyn MTLTexture>>; 2]>,
+ /// `MPSImageGaussianBlur` kernels by sigma, least recently used first.
+ kernels: Vec<(f32, Retained<AnyObject>)>,
+ idle_frames: u32,
+}
+
+impl Backdrop {
+ pub(crate) fn new(
+ device: &ProtocolObject<dyn MTLDevice>,
+ library: &ProtocolObject<dyn MTLLibrary>,
+ ) -> Result<Self> {
+ let blur_pipeline = build_pipeline_state(
+ device,
+ library,
+ "backdrop_blur",
+ "polychrome_sprite_vertex",
+ "backdrop_blur_fragment",
+ MTLPixelFormat::BGRA8Unorm,
+ true,
+ )?;
+ let descriptor = MTLRenderPipelineDescriptor::new();
+ descriptor.setLabel(Some(&NSString::from_str("backdrop_downscale")));
+ let function = |name: &str| {
+ library
+ .newFunctionWithName(&NSString::from_str(name))
+ .with_context(|| format!("locating function {name}"))
+ };
+ descriptor.setVertexFunction(Some(&*function("backdrop_downscale_vertex")?));
+ descriptor.setFragmentFunction(Some(&*function("backdrop_downscale_fragment")?));
+ // SAFETY: Index zero is within the pipeline's color attachment array.
+ unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) }
+ .setPixelFormat(MTLPixelFormat::BGRA8Unorm);
+ let downscale_pipeline = device
+ .newRenderPipelineStateWithDescriptor_error(&descriptor)
+ .context("creating backdrop_downscale render pipeline")?;
+ Ok(Self {
+ blur_pipeline,
+ downscale_pipeline,
+ textures: Vec::new(),
+ kernels: Vec::new(),
+ idle_frames: 0,
+ })
+ }
+
+ /// Frees the scratch textures and kernels once frames stop blurring.
+ pub(crate) fn end_frame(&mut self, blurred: bool) {
+ if blurred {
+ self.idle_frames = 0;
+ return;
+ }
+ self.idle_frames = self.idle_frames.saturating_add(1);
+ if self.idle_frames >= SCRATCH_RELEASE_AFTER_IDLE_FRAMES {
+ self.textures.clear();
+ self.kernels.clear();
+ }
+ }
+
+ fn textures(
+ &mut self,
+ device: &ProtocolObject<dyn MTLDevice>,
+ needed_width: usize,
+ needed_height: usize,
+ drawable: &ProtocolObject<dyn MTLTexture>,
+ ) -> Result<[Retained<ProtocolObject<dyn MTLTexture>>; 2]> {
+ let width = needed_width.div_ceil(TEXTURE_SIZE_QUANTUM) * TEXTURE_SIZE_QUANTUM;
+ let height = needed_height.div_ceil(TEXTURE_SIZE_QUANTUM) * TEXTURE_SIZE_QUANTUM;
+ let bytes = |pair: &[Retained<ProtocolObject<dyn MTLTexture>>; 2]| pair[0].width() * pair[0].height() * 8;
+ if let Some(index) = self
+ .textures
+ .iter()
+ .position(|pair| pair[0].width() == width && pair[0].height() == height)
+ {
+ let pair = self.textures.remove(index);
+ self.textures.push(pair.clone());
+ return Ok(pair);
+ }
+ let needed_bytes = width * height * 8;
+ let budget = (drawable.width() * drawable.height() * 16)
+ .min(MAX_TEXTURE_BYTES)
+ .max(needed_bytes);
+ while !self.textures.is_empty()
+ && (self.textures.len() >= MAX_TEXTURE_PAIRS
+ || self.textures.iter().map(bytes).sum::<usize>() + needed_bytes > budget)
+ {
+ self.textures.remove(0);
+ }
+ let descriptor = MTLTextureDescriptor::new();
+ // SAFETY: The size is at most a quantum past a crop of an existing render target.
+ unsafe {
+ descriptor.setWidth(width);
+ descriptor.setHeight(height);
+ }
+ descriptor.setPixelFormat(MTLPixelFormat::BGRA8Unorm);
+ descriptor.setStorageMode(MTLStorageMode::Private);
+ descriptor.setUsage(MTLTextureUsage::ShaderRead | MTLTextureUsage::RenderTarget);
+ let scratch = device
+ .newTextureWithDescriptor(&descriptor)
+ .context("allocating backdrop scratch texture")?;
+ descriptor.setUsage(MTLTextureUsage::ShaderRead | MTLTextureUsage::ShaderWrite);
+ let blurred = device
+ .newTextureWithDescriptor(&descriptor)
+ .context("allocating backdrop blur texture")?;
+ let pair = [scratch, blurred];
+ self.textures.push(pair.clone());
+ Ok(pair)
+ }
+
+ fn kernel(&mut self, device: &ProtocolObject<dyn MTLDevice>, sigma: f32) -> Result<Retained<AnyObject>> {
+ if let Some(index) = self.kernels.iter().position(|(cached, _)| (cached - sigma).abs() < 0.01) {
+ let entry = self.kernels.remove(index);
+ let kernel = entry.1.clone();
+ self.kernels.push(entry);
+ return Ok(kernel);
+ }
+ // SAFETY: MPSImageGaussianBlur's designated initializer takes a device and a float sigma.
+ let kernel: Option<Retained<AnyObject>> = unsafe {
+ let allocated: Allocated<AnyObject> = msg_send![class!(MPSImageGaussianBlur), alloc];
+ msg_send![allocated, initWithDevice: device, sigma: sigma]
+ };
+ let kernel = kernel.with_context(|| format!("creating a gaussian blur kernel with sigma {sigma}"))?;
+ // The default zero edge mode bleeds transparent black in from the scratch border.
+ // SAFETY: `edgeMode` is an NSUInteger property of every MPSKernel.
+ let _: () = unsafe { msg_send![&*kernel, setEdgeMode: MPS_IMAGE_EDGE_MODE_CLAMP] };
+ if self.kernels.len() >= MAX_KERNELS {
+ self.kernels.remove(0);
+ }
+ self.kernels.push((sigma, kernel.clone()));
+ Ok(kernel)
+ }
+}
+
+/// Whether `scene` or a scene nested in it paints a backdrop blur.
+pub(crate) fn has_backdrop_blur(scene: &Scene) -> bool {
+ scene
+ .polychrome_sprites
+ .iter()
+ .any(|sprite| backdrop_blur_radius(sprite).is_some())
+ || scene
+ .layers
+ .frames
+ .iter()
+ .filter_map(|frame| frame.content.scene())
+ .any(has_backdrop_blur)
+}
+
+/// Blurs what `pass` drew so far beneath each sprite of `range`, all backdrop blurs, and draws it back.
+pub(crate) fn draw(
+ renderer: &mut MetalRenderer,
+ sprites: &[PolychromeSprite],
+ range: std::ops::Range<usize>,
+ instance_bindings: &InstanceBindings,
+ pass: &mut Pass,
+ state: &EncoderState,
+) -> Result<()> {
+ // CAMetalLayer can still vend a pooled framebuffer-only drawable after the flag is cleared.
+ if pass.texture.isFramebufferOnly() {
+ return Ok(());
+ }
+ for index in range {
+ let sprite = &sprites[index];
+ let blur_radius = backdrop_blur_radius(sprite).context("a backdrop blur sprite")?;
+ let (width, height) = (pass.texture.width() as i64, pass.texture.height() as i64);
+ let bounds = sprite.bounds;
+ let region = [
+ (bounds.origin.x.0.round() as i64).max(0),
+ (bounds.origin.y.0.round() as i64).max(0),
+ ((bounds.origin.x.0 + bounds.size.width.0).round() as i64).min(width),
+ ((bounds.origin.y.0 + bounds.size.height.0).round() as i64).min(height),
+ ];
+ let [left, top, right, bottom] = region;
+ if right <= left || bottom <= top {
+ continue;
+ }
+ let downscale = Downscale::new(blur_radius.max(1.0), region);
+ // The gaussian reaches about 3 sigma: the scratch holds the image and that much mirrored around it.
+ let padding = (downscale.sigma * 3.0).ceil() as i64 + 2;
+ let device = renderer.device.clone();
+ let kernel = renderer.backdrop.kernel(&device, downscale.sigma)?;
+ let [scratch, blurred] = renderer.backdrop.textures(
+ &device,
+ (downscale.image[2] - downscale.image[0] + 2 * padding) as usize,
+ (downscale.image[3] - downscale.image[1] + 2 * padding) as usize,
+ pass.texture,
+ )?;
+ pass.encoder.endEncoding();
+
+ // The whole scratch is written, so the blur never samples stale texels.
+ let image = downscale.image.map(|value| value as i32);
+ let origin = [image[0] - padding as i32, image[1] - padding as i32];
+ let levels = downscale.levels as i32;
+ let mirror = scratch_encoder(pass.command_buffer, &scratch)?;
+ mirror.setRenderPipelineState(&renderer.backdrop.downscale_pipeline);
+ // SAFETY: Metal copies each live value, which matches backdrop_downscale_fragment's arguments.
+ unsafe {
+ mirror.setFragmentBytes_length_atIndex(NonNull::from(&image).cast(), mem::size_of_val(&image), 0);
+ mirror.setFragmentBytes_length_atIndex(NonNull::from(&origin).cast(), mem::size_of_val(&origin), 1);
+ mirror.setFragmentBytes_length_atIndex(NonNull::from(&levels).cast(), mem::size_of_val(&levels), 2);
+ mirror.setFragmentBytes_length_atIndex(
+ NonNull::from(&downscale.steps).cast(),
+ mem::size_of_val(&downscale.steps),
+ 3,
+ );
+ mirror.setFragmentTexture_atIndex(Some(pass.texture), 0);
+ mirror.drawPrimitives_vertexStart_vertexCount(MTLPrimitiveType::Triangle, 0, 3);
+ }
+ mirror.endEncoding();
+ // SAFETY: MPSUnaryImageKernel's encode method takes a command buffer and two textures of one size and format.
+ let _: () = unsafe {
+ msg_send![
+ &*kernel,
+ encodeToCommandBuffer: pass.command_buffer,
+ sourceTexture: &*scratch,
+ destinationTexture: &*blurred
+ ]
+ };
+
+ pass.encoder = crate::metal_renderer::new_command_encoder_for_texture(
+ pass.command_buffer,
+ pass.texture,
+ &pass.depth_texture,
+ state.viewport_size,
+ None,
+ )?;
+ state.restore(renderer, &pass.encoder)?;
+ // The blurred image's pixels are `downscale.scale` drawable pixels each, its image pixels start at the crop.
+ let source_rect = [
+ left as f32 - padding as f32 * downscale.scale[0],
+ top as f32 - padding as f32 * downscale.scale[1],
+ blurred.width() as f32 * downscale.scale[0],
+ blurred.height() as f32 * downscale.scale[1],
+ ];
+ let unit_size: Size<DevicePixels> = size(DevicePixels(1), DevicePixels(1));
+ let encoder = &pass.encoder;
+ encoder.setRenderPipelineState(&renderer.backdrop.blur_pipeline);
+ let sprites_binding = &instance_bindings.polychrome_sprites;
+ // SAFETY: The sprite instances and copied values match polychrome_sprite_vertex's and
+ // backdrop_blur_fragment's layouts and slots; Metal retains the buffer and texture.
+ unsafe {
+ encoder.setVertexBuffer_offset_atIndex(
+ Some(&sprites_binding.buffer),
+ sprites_binding.offset,
+ SpriteInputIndex::Sprites as usize,
+ );
+ encoder.setVertexBytes_length_atIndex(
+ NonNull::from(&unit_size).cast(),
+ mem::size_of_val(&unit_size),
+ SpriteInputIndex::AtlasTextureSize as usize,
+ );
+ encoder.setFragmentBuffer_offset_atIndex(
+ Some(&sprites_binding.buffer),
+ sprites_binding.offset,
+ SpriteInputIndex::Sprites as usize,
+ );
+ encoder.setFragmentBytes_length_atIndex(
+ NonNull::from(&source_rect).cast(),
+ mem::size_of_val(&source_rect),
+ SOURCE_RECT_INDEX,
+ );
+ encoder.setFragmentTexture_atIndex(Some(&blurred), SpriteInputIndex::AtlasTexture as usize);
+ encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance(
+ MTLPrimitiveType::TriangleStrip,
+ 0,
+ 4,
+ 1,
+ index,
+ );
+ }
+ }
+ Ok(())
+}
+
+/// What a pass's encoder is set up with between batches, set again on the encoder that resumes it.
+pub(crate) struct EncoderState<'a> {
+ pub(crate) viewport_size: Size<DevicePixels>,
+ pub(crate) depth_scale: f32,
+ pub(crate) depth: f64,
+ pub(crate) clips: &'a [Clip],
+}
+
+impl EncoderState<'_> {
+ fn restore(
+ &self,
+ renderer: &MetalRenderer,
+ encoder: &ProtocolObject<dyn MTLRenderCommandEncoder>,
+ ) -> Result<()> {
+ // SAFETY: Metal copies both values, which match every vertex shader's
+ // `GlobalInputIndex_ViewportSize` and `GlobalInputIndex_DepthScale` arguments.
+ unsafe {
+ encoder.setVertexBytes_length_atIndex(
+ NonNull::from(&self.viewport_size).cast(),
+ mem::size_of_val(&self.viewport_size),
+ GlobalInputIndex::ViewportSize as usize,
+ );
+ encoder.setVertexBytes_length_atIndex(
+ NonNull::from(&self.depth_scale).cast(),
+ mem::size_of_val(&self.depth_scale),
+ GlobalInputIndex::DepthScale as usize,
+ );
+ }
+ encoder.setDepthStencilState(Some(&renderer.depth_test_state));
+ encoder.setViewport(MTLViewport {
+ originX: 0.0,
+ originY: 0.0,
+ width: i32::from(self.viewport_size.width) as f64,
+ height: i32::from(self.viewport_size.height) as f64,
+ znear: self.depth,
+ zfar: self.depth,
+ });
+ rounded_clip::default_mask(encoder);
+ rounded_clip::bind(encoder, self.clips, &renderer.device)
+ }
+}
+
+fn scratch_encoder(
+ command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
+ scratch: &ProtocolObject<dyn MTLTexture>,
+) -> Result<Retained<ProtocolObject<dyn MTLRenderCommandEncoder>>> {
+ let descriptor = MTLRenderPassDescriptor::new();
+ // SAFETY: Index zero is within the render pass's color attachment array.
+ let attachment = unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) };
+ attachment.setTexture(Some(scratch));
+ attachment.setLoadAction(MTLLoadAction::DontCare);
+ attachment.setStoreAction(MTLStoreAction::Store);
+ command_buffer
+ .renderCommandEncoderWithDescriptor(&descriptor)
+ .context("creating backdrop scratch encoder")
+}
+
+struct Downscale {
+ levels: usize,
+ /// Per level and axis: the (scale, offset, lowest texel, highest texel) mapping its texel centers onto the level above.
+ steps: [[f32; 4]; 2 * MAX_DOWNSCALE_LEVELS],
+ /// The crop in the pixels the blur reads: the drawable's at level 0, else the smallest level's.
+ image: [i64; 4],
+ /// Drawable pixels per pixel of the blurred image.
+ scale: [f32; 2],
+ sigma: f32,
+}
+
+impl Downscale {
+ fn new(sigma: f32, region: [i64; 4]) -> Self {
+ let levels = downscale_levels(MAX_SKIA_SIGMA / sigma).min(MAX_DOWNSCALE_LEVELS);
+ let mut downscale = Downscale {
+ levels,
+ steps: [[0.0; 4]; 2 * MAX_DOWNSCALE_LEVELS],
+ image: region,
+ scale: [1.0, 1.0],
+ sigma,
+ };
+ if levels == 0 {
+ return downscale;
+ }
+ for axis in 0..2 {
+ let (low, high) = (region[axis] as f32, region[axis + 2] as f32);
+ let (mut left, mut right) = (low, high);
+ let (mut texel_left, mut clamp) = (0.0, [low, high - 1.0]);
+ for level in 1..=levels {
+ // `scale_about_center` leaves every level after the first centered on 0.
+ let center = (left + right) / 2.0;
+ let (mut next_left, mut next_right) = ((left - center) * 0.5, (right - center) * 0.5);
+ if level == levels {
+ (next_left, next_right) = (next_left.floor(), next_right.ceil());
+ }
+ let scale = (right - left) / (next_right - next_left);
+ let next_texel_left = next_left.floor();
+ let offset = (next_texel_left - next_left) * scale + left - texel_left - 0.5;
+ downscale.steps[(level - 1) * 2 + axis] = [scale, offset, clamp[0], clamp[1]];
+ (left, right, texel_left) = (next_left, next_right, next_texel_left);
+ clamp = [0.0, next_right.ceil() - next_texel_left - 1.0];
+ }
+ downscale.image[axis] = 0;
+ downscale.image[axis + 2] = (right - left) as i64;
+ downscale.scale[axis] = (high - low) / (right - left);
+ }
+ downscale.sigma = (sigma / downscale.scale[0]).min(MAX_SKIA_SIGMA);
+ downscale
+ }
+}
+
+/// SkImageFilterTypes.cpp `downscale_step_count`: halvings until the scale is reached, the last one dropped when it
+/// would barely scale.
+fn downscale_levels(scale: f32) -> usize {
+ if scale >= 1.0 {
+ return 0;
+ }
+ let mut steps = (1.0 / scale).ceil().log2().ceil() as i32;
+ let final_step_scale = scale * (1 << (steps - 1)) as f32;
+ let limit = if steps == 1 { 1.0 - 1e-3 } else { 0.9 };
+ if final_step_scale >= limit {
+ steps -= 1;
+ }
+ steps as usize
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_blur_above_sigma_4_runs_on_a_backdrop_halved_until_it_is_at_most_4() {
+ let frosted = Downscale::new(24.0, [100, 50, 302, 150]);
+ assert_eq!(frosted.levels, 3);
+ // 202 / 8 about the center is -12.625..12.625, rounded out to 26 pixels; 100 / 8 to 14.
+ assert_eq!(frosted.image, [0, 0, 26, 14]);
+ assert_eq!(frosted.scale, [202.0 / 26.0, 100.0 / 14.0]);
+ assert_eq!(frosted.sigma, 24.0 * 26.0 / 202.0);
+ // -50.5..50.5 starts the first level mid-pixel: its texel 0 centers on the crop's left edge, between 99 and 100.
+ assert_eq!(frosted.steps[0], [2.0, 98.5, 100.0, 301.0]);
+ assert_eq!(frosted.steps[2], [2.0, -1.5, 0.0, 101.0]);
+ assert_eq!(Downscale::new(4.0, [0, 0, 10, 10]).levels, 0);
+ assert_eq!(downscale_levels(4.0 / 8.4), 1, "a last halving that barely scales is dropped");
+ }
+}
diff --git a/native/vendor/gpui-fast/crates/gpui_apple/src/fast/frame.rs b/native/vendor/gpui-fast/crates/gpui_apple/src/fast/frame.rs
index 1447ef967d2..a2992957476 100644
--- a/native/vendor/gpui-fast/crates/gpui_apple/src/fast/frame.rs
+++ b/native/vendor/gpui-fast/crates/gpui_apple/src/fast/frame.rs
@@ -6,7 +6,9 @@ use super::{
ProtocolObject, Result, Retained, Scene, Size, mem, new_command_encoder_for_texture, ptr,
quad_depth, quad_depth_scale,
};
+use crate::fast::backdrop::{EncoderState, Pass, has_backdrop_blur};
use anyhow::Context as _;
+use gpui::BACKDROP_TEXTURE_INDEX;
impl MetalRenderer {
pub(super) fn fast_frame(
@@ -18,7 +20,9 @@ impl MetalRenderer {
viewport_size: Size<DevicePixels>,
surface_textures: &mut Vec<CFRetained<CVMetalTexture>>,
) -> Result<Retained<ProtocolObject<dyn MTLCommandBuffer>>> {
- if scene.layers.frames.is_empty() {
+ let blurs = has_backdrop_blur(scene);
+ self.backdrop.end_frame(blurs);
+ if scene.layers.frames.is_empty() && !blurs {
return self.draw_primitives_to_texture(
scene,
instance_bindings,
@@ -69,20 +73,28 @@ impl MetalRenderer {
texture,
&depth_texture,
viewport_size,
- clear,
+ Some(clear),
)?;
crate::fast::rounded_clip::default_mask(&encoder);
+ let mut pass = Pass {
+ encoder,
+ command_buffer,
+ texture,
+ depth_texture,
+ };
+ // Without depth writes everything at depth 1 draws in paint order, which survives the pass a blur ends.
+ let depth = has_backdrop_blur(scene).then_some(1.0);
let result = self.encode_fast_batches(
scene,
instance_bindings,
writer,
viewport_size,
- &encoder,
+ &mut pass,
&mut Vec::new(),
surface_textures,
- None,
+ depth,
);
- encoder.endEncoding();
+ pass.encoder.endEncoding();
result
}
@@ -93,7 +105,7 @@ impl MetalRenderer {
instance_bindings: &InstanceBindings,
writer: &mut InstanceBufferWriter,
viewport_size: Size<DevicePixels>,
- command_encoder: &ProtocolObject<dyn MTLRenderCommandEncoder>,
+ pass: &mut Pass,
clips: &mut Vec<crate::fast::rounded_clip::Clip>,
surface_textures: &mut Vec<CFRetained<CVMetalTexture>>,
parent_depth: Option<f64>,
@@ -104,6 +116,7 @@ impl MetalRenderer {
} else {
quad_depth_scale(scene.quads.len())
};
+ let command_encoder = &*pass.encoder;
// SAFETY: Metal copies both values, which match every vertex shader's
// `GlobalInputIndex_ViewportSize` and `GlobalInputIndex_DepthScale` arguments.
unsafe {
@@ -127,6 +140,7 @@ impl MetalRenderer {
let mut quad_cursor: u32 = 0;
let mut path_tile_cursor = 0;
for batch in scene.batches() {
+ let command_encoder = &*pass.encoder;
// Quad shaders assign each quad its own depth.
// In every other batch type, the depth is fixed to the position of the quad cursor.
let (znear, zfar) = if let Some(depth) = parent_depth {
@@ -171,6 +185,24 @@ impl MetalRenderer {
}
PrimitiveBatch::MonochromeSprites { texture_id, range } => self
.draw_monochrome_sprites(texture_id, range, instance_bindings, command_encoder),
+ PrimitiveBatch::PolychromeSprites { texture_id, range }
+ if texture_id.index == BACKDROP_TEXTURE_INDEX =>
+ {
+ let state = EncoderState {
+ viewport_size,
+ depth_scale,
+ depth: znear,
+ clips,
+ };
+ crate::fast::backdrop::draw(
+ self,
+ &scene.polychrome_sprites,
+ range,
+ instance_bindings,
+ pass,
+ &state,
+ )?;
+ }
PrimitiveBatch::PolychromeSprites { texture_id, range } => {
if crate::fast::rounded_clip::draw_group(
self,
@@ -179,14 +211,14 @@ impl MetalRenderer {
range.clone(),
writer,
viewport_size,
- command_encoder,
+ pass,
clips,
surface_textures,
znear,
)? {
// The nested scene used its own depth constants and tile runs.
unsafe {
- command_encoder.setVertexBytes_length_atIndex(
+ pass.encoder.setVertexBytes_length_atIndex(
ptr::NonNull::from(&depth_scale).cast(),
mem::size_of_val(&depth_scale),
GlobalInputIndex::DepthScale as usize,
@@ -198,7 +230,7 @@ impl MetalRenderer {
texture_id,
range,
instance_bindings,
- command_encoder,
+ &pass.encoder,
);
}
}
diff --git a/native/vendor/gpui-fast/crates/gpui_apple/src/fast/mod.rs b/native/vendor/gpui-fast/crates/gpui_apple/src/fast/mod.rs
index 60c28f09048..39da23890c4 100644
--- a/native/vendor/gpui-fast/crates/gpui_apple/src/fast/mod.rs
+++ b/native/vendor/gpui-fast/crates/gpui_apple/src/fast/mod.rs
@@ -12,6 +12,7 @@
mod bidi_wrap_tests;
#[cfg(feature = "font-kit")]
pub(crate) mod color_bitmap_fonts;
+pub(crate) mod backdrop;
pub(crate) mod composition;
pub(crate) mod dynamic_textures;
#[cfg(feature = "font-kit")]
diff --git a/native/vendor/gpui-fast/crates/gpui_apple/src/fast/rounded_clip.rs b/native/vendor/gpui-fast/crates/gpui_apple/src/fast/rounded_clip.rs
index 304165be11d..d090351790d 100644
--- a/native/vendor/gpui-fast/crates/gpui_apple/src/fast/rounded_clip.rs
+++ b/native/vendor/gpui-fast/crates/gpui_apple/src/fast/rounded_clip.rs
@@ -14,6 +14,7 @@ use objc2_metal::{
MTLResourceOptions,
};
+use crate::fast::backdrop::Pass;
use crate::metal_renderer::{InstanceBufferWriter, MetalRenderer, write_instances};
const CLIP_TEXTURE_BASE: u32 = 0xF100_0000;
@@ -62,7 +63,7 @@ pub(crate) fn default_mask(encoder: &ProtocolObject<dyn MTLRenderCommandEncoder>
}
}
-fn bind(
+pub(crate) fn bind(
encoder: &ProtocolObject<dyn MTLRenderCommandEncoder>,
clips: &[Clip],
device: &ProtocolObject<dyn MTLDevice>,
@@ -118,7 +119,7 @@ pub(crate) fn draw_group(
range: Range<usize>,
writer: &mut InstanceBufferWriter,
viewport: Size<DevicePixels>,
- encoder: &ProtocolObject<dyn MTLRenderCommandEncoder>,
+ pass: &mut Pass,
clips: &mut Vec<Clip>,
surface_textures: &mut Vec<CFRetained<CVMetalTexture>>,
parent_depth: f64,
@@ -148,13 +149,13 @@ pub(crate) fn draw_group(
],
vertical: [radii.r, radii.g, radii.b, radii.a],
});
- bind(encoder, clips, &renderer.device)?;
+ bind(&pass.encoder, clips, &renderer.device)?;
let drawn = renderer.encode_fast_batches(
child,
&child_bindings,
writer,
viewport,
- encoder,
+ pass,
clips,
surface_textures,
Some(parent_depth),
@@ -162,6 +163,6 @@ pub(crate) fn draw_group(
clips.pop();
drawn?;
}
- bind(encoder, clips, &renderer.device)?;
+ bind(&pass.encoder, clips, &renderer.device)?;
Ok(true)
}
diff --git a/native/vendor/gpui-fast/crates/gpui_apple/src/fast/rounded_clip_shader.rs b/native/vendor/gpui-fast/crates/gpui_apple/src/fast/rounded_clip_shader.rs
index 7251d4da672..0bc04d46b0c 100644
--- a/native/vendor/gpui-fast/crates/gpui_apple/src/fast/rounded_clip_shader.rs
+++ b/native/vendor/gpui-fast/crates/gpui_apple/src/fast/rounded_clip_shader.rs
@@ -12,6 +12,7 @@ pub fn source(source: &str) -> String {
"path_tile_fragment",
"surface_fragment",
"native_view_fragment",
+ "backdrop_blur_fragment",
] {
let start = source
.find(&format!("fragment float4 {name}("))
diff --git a/native/vendor/gpui-fast/crates/gpui_apple/src/metal_renderer.rs b/native/vendor/gpui-fast/crates/gpui_apple/src/metal_renderer.rs
index 160d60c8d1f..079c0efa51e 100644
--- a/native/vendor/gpui-fast/crates/gpui_apple/src/metal_renderer.rs
+++ b/native/vendor/gpui-fast/crates/gpui_apple/src/metal_renderer.rs
@@ -130,6 +130,7 @@ pub struct MetalRenderer {
/// Whether the last scene drawn to the layer let native views show through it.
shows_native_views: bool,
pub(crate) fast_layers: crate::fast::layers::TileCache,
+ pub(crate) backdrop: crate::fast::backdrop::Backdrop,
pub(crate) command_queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
path_tiles_pipeline_state: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
shadows_pipeline_state: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
@@ -143,7 +144,7 @@ pub struct MetalRenderer {
surfaces_pipeline_state: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
native_views_pipeline_state: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
depth_write_state: Retained<ProtocolObject<dyn MTLDepthStencilState>>,
- depth_test_state: Retained<ProtocolObject<dyn MTLDepthStencilState>>,
+ pub(crate) depth_test_state: Retained<ProtocolObject<dyn MTLDepthStencilState>>,
depth_texture: Option<Retained<ProtocolObject<dyn MTLTexture>>>,
pub(crate) instance_buffer_pool: Arc<Mutex<InstanceBufferPool>>,
pub(crate) sprite_atlas: Arc<MetalAtlas>,
@@ -367,6 +368,8 @@ impl MetalRenderer {
true, // fast rounded clips blend partially covered native-view holes.
)?;
+ let backdrop = crate::fast::backdrop::Backdrop::new(&device, &library)?;
+
let depth_write_state = build_depth_stencil_state(&device, true)?;
let depth_test_state = build_depth_stencil_state(&device, false)?;
@@ -400,6 +403,7 @@ impl MetalRenderer {
opaque,
shows_native_views: false,
fast_layers: Default::default(),
+ backdrop,
command_queue,
path_tiles_pipeline_state,
shadows_pipeline_state,
@@ -482,6 +486,10 @@ impl MetalRenderer {
self.shows_native_views = shows_native_views;
layer.setOpaque(self.opaque && !shows_native_views);
}
+ // A backdrop blur reads the drawable, which a framebuffer-only drawable forbids.
+ if layer.framebufferOnly() && crate::fast::backdrop::has_backdrop_blur(scene) {
+ layer.setFramebufferOnly(false);
+ }
let Some(drawable) = layer.nextDrawable() else {
log::error!(
"failed to retrieve next drawable, drawable size: {:?}",
@@ -725,12 +733,12 @@ impl MetalRenderer {
texture,
&depth_texture,
viewport_size,
- MTLClearColor {
+ Some(MTLClearColor {
red: 0.,
green: 0.,
blue: 0.,
alpha,
- },
+ }),
)?;
crate::fast::rounded_clip::default_mask(&command_encoder);
let depth_scale = quad_depth_scale(scene.quads.len());
@@ -1301,12 +1309,12 @@ impl MetalRenderer {
}
}
-fn new_command_encoder_for_texture(
+pub(crate) fn new_command_encoder_for_texture(
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
texture: &ProtocolObject<dyn MTLTexture>,
depth_texture: &ProtocolObject<dyn MTLTexture>,
viewport_size: Size<DevicePixels>,
- clear_color: MTLClearColor,
+ clear_color: Option<MTLClearColor>,
) -> Result<Retained<ProtocolObject<dyn MTLRenderCommandEncoder>>> {
let render_pass_descriptor = MTLRenderPassDescriptor::new();
// SAFETY: Index zero is within the render pass's color attachment array.
@@ -1317,8 +1325,13 @@ fn new_command_encoder_for_texture(
};
color_attachment.setTexture(Some(texture));
color_attachment.setStoreAction(MTLStoreAction::Store);
- color_attachment.setLoadAction(MTLLoadAction::Clear);
- color_attachment.setClearColor(clear_color);
+ match clear_color {
+ Some(clear_color) => {
+ color_attachment.setLoadAction(MTLLoadAction::Clear);
+ color_attachment.setClearColor(clear_color);
+ }
+ None => color_attachment.setLoadAction(MTLLoadAction::Load),
+ }
let depth_attachment = render_pass_descriptor.depthAttachment();
depth_attachment.setTexture(Some(depth_texture));
@@ -1373,7 +1386,7 @@ fn read_texture_to_image(texture: &ProtocolObject<dyn MTLTexture>) -> Result<Rgb
RgbaImage::from_raw(width, height, pixels).context("creating RGBA image from pixel data")
}
-fn build_pipeline_state(
+pub(crate) fn build_pipeline_state(
device: &ProtocolObject<dyn MTLDevice>,
library: &ProtocolObject<dyn MTLLibrary>,
label: &str,
@@ -1615,7 +1628,7 @@ impl InstanceBufferWriter {
/// Vertex buffer slots bound once per render pass and shared by every
/// pipeline. Each primitive's own slots start after these.
#[repr(C)]
-enum GlobalInputIndex {
+pub(crate) enum GlobalInputIndex {
ViewportSize = 0,
DepthScale = 1,
}
diff --git a/native/vendor/gpui-fast/crates/gpui_apple/src/shaders.metal b/native/vendor/gpui-fast/crates/gpui_apple/src/shaders.metal
index 890d156d30b..32b9b81128a 100644
--- a/native/vendor/gpui-fast/crates/gpui_apple/src/shaders.metal
+++ b/native/vendor/gpui-fast/crates/gpui_apple/src/shaders.metal
@@ -1479,3 +1479,95 @@ bool has_border(Edges_ScaledPixels border_widths) {
bool is_shaped(Quad quad) {
return has_rounded_corners(quad.corner_radii) || has_border(quad.border_widths);
}
+
+// Chromium blurs a backdrop-filter's input cropped to the element's bounds and mirrored past them (SkTileMode::kMirror),
+// so content outside the element never bleeds in. `region` is that crop in the pixels of the image the blur reads (the
+// drawable, or its downscale when `levels` > 0), `origin` the scratch texture's top left in those pixels.
+vertex float4 backdrop_downscale_vertex(uint vertex_id [[vertex_id]]) {
+ float2 corner = float2((vertex_id << 1) & 2, vertex_id & 2);
+ return float4(corner * float2(2., -2.) + float2(-1., 1.), 0., 1.);
+}
+
+int mirror_into(int x, int low, int high) {
+ int period = 2 * (high - low);
+ int t = ((x - low) % period + period) % period;
+ return low + (t < high - low ? t : period - 1 - t);
+}
+
+// One axis of Skia's progressive downscale (SkImageFilterTypes.cpp `FilterResult::rescale`): each level samples the one
+// above it bilinearly, clamped to its pixels. `steps[(level - 1) * 2 + axis]` maps a level's texel centers onto the
+// level above as (scale, offset, lowest texel, highest texel). Returns the drawable texels behind `texel` and weights.
+int downscale_taps(int texel, int levels, constant float4 *steps, int axis, thread int *index, thread float *weight) {
+ index[0] = texel;
+ weight[0] = 1.;
+ int count = 1;
+ for (int level = levels; level > 0; level--) {
+ float4 step = steps[(level - 1) * 2 + axis];
+ for (int tap = count - 1; tap >= 0; tap--) {
+ float u = clamp((float(index[tap]) + 0.5) * step.x + step.y, step.z, step.w);
+ float base = floor(u);
+ float w = weight[tap];
+ index[2 * tap] = int(base);
+ index[2 * tap + 1] = int(min(base + 1., step.w));
+ weight[2 * tap] = w * (1. - (u - base));
+ weight[2 * tap + 1] = w * (u - base);
+ }
+ count *= 2;
+ }
+ return count;
+}
+
+fragment float4 backdrop_downscale_fragment(float4 position [[position]],
+ constant int4 &region [[buffer(0)]],
+ constant int2 &origin [[buffer(1)]],
+ constant int &levels [[buffer(2)]],
+ constant float4 *steps [[buffer(3)]],
+ texture2d<float> source [[texture(0)]]) {
+ int2 pixel = int2(floor(position.xy)) + origin;
+ int2 texel = int2(mirror_into(pixel.x, region.x, region.z), mirror_into(pixel.y, region.y, region.w));
+ if (levels == 0) {
+ return source.read(uint2(texel));
+ }
+ int x_index[32];
+ float x_weight[32];
+ int y_index[32];
+ float y_weight[32];
+ int x_count = downscale_taps(texel.x, levels, steps, 0, x_index, x_weight);
+ int y_count = downscale_taps(texel.y, levels, steps, 1, y_index, y_weight);
+ float4 sum = float4(0.);
+ for (int y = 0; y < y_count; y++) {
+ for (int x = 0; x < x_count; x++) {
+ sum += source.read(uint2(x_index[x], y_index[y])) * (x_weight[x] * y_weight[y]);
+ }
+ }
+ return sum;
+}
+
+// A backdrop blur is a polychrome sprite (gpui `fast::backdrop`) whose tile carries the tint as float bits.
+fragment float4 backdrop_blur_fragment(
+ PolychromeSpriteFragmentInput input [[stage_in]],
+ constant PolychromeSprite *sprites [[buffer(SpriteInputIndex_Sprites)]],
+ constant float4 &source_rect [[buffer(5)]],
+ texture2d<float> source_texture [[texture(SpriteInputIndex_AtlasTexture)]]) {
+ constexpr sampler source_sampler(coord::normalized, address::clamp_to_edge, filter::linear);
+ PolychromeSprite sprite = sprites[input.sprite_id & ~SIMPLE_PRIMITIVE_FLAG];
+
+ // Chromium clips the blurred backdrop to the element's rounded rect with antialiasing, as it covers a fill.
+ float coverage = rrect_coverage(input.position.xy, sprite.bounds, sprite.corner_radii);
+ if (coverage <= 0.) {
+ discard_fragment();
+ }
+
+ // The blurred image covers only source_rect of the drawable, not the viewport.
+ float2 uv = (input.position.xy - source_rect.xy) / source_rect.zw;
+ float4 color = float4(source_texture.sample(source_sampler, uv).rgb, 1.0);
+ Bounds_DevicePixels tint_bits = sprite.tile.bounds;
+ Hsla tint_hsla = {as_type<float>(tint_bits.origin.x), as_type<float>(tint_bits.origin.y),
+ as_type<float>(tint_bits.size.width), as_type<float>(tint_bits.size.height)};
+ float4 tint = hsla_to_rgba(tint_hsla);
+ if (tint.a > 0.0) {
+ // The fill is rasterized into the element's 8-bit premultiplied layer first.
+ color = over(color, tint.a < 1.0 ? premultiplied_8bit(tint) : tint);
+ }
+ return float4(color.rgb, coverage);
+}