From 8678292cfeb55b56a22f17884eba028718dbcfa3 Mon Sep 17 00:00:00 2001 From: nolight132 Date: Thu, 26 Nov 2026 15:32:53 +0100 Subject: [PATCH 1/7] chore: vendor the gpui subset of zed@621a6adf30 --- crates/gpui/examples/svg_animation.rs | 222 ++++++++ crates/gpui/examples/system_notifications.rs | 2 +- crates/gpui/src/app.rs | 7 +- crates/gpui/src/app/headless_app_context.rs | 11 +- crates/gpui/src/app/test_context.rs | 29 +- crates/gpui/src/elements/animation.rs | 9 + crates/gpui/src/elements/svg.rs | 474 +++++++++++++++++- crates/gpui/src/geometry.rs | 16 +- crates/gpui/src/keymap.rs | 4 +- crates/gpui/src/platform.rs | 6 +- crates/gpui/src/platform/test/platform.rs | 13 +- crates/gpui/src/profiler.rs | 9 +- crates/gpui/src/profiler/journal.rs | 4 +- crates/gpui/src/scene.rs | 202 +++++++- crates/gpui/src/svg_renderer.rs | 379 +++++++++++++- crates/gpui/src/window.rs | 220 +++++--- crates/gpui_apple/Cargo.toml | 1 + crates/gpui_apple/src/metal_renderer.rs | 201 +++++++- crates/gpui_apple/src/shaders.metal | 221 +++++--- crates/gpui_linux/src/linux/platform.rs | 3 +- crates/gpui_linux/src/linux/x11/clipboard.rs | 2 +- crates/gpui_macos/src/platform.rs | 24 +- crates/gpui_macos/src/system_notifications.rs | 218 +++++--- crates/gpui_platform/benches/atlas_upload.rs | 2 +- crates/gpui_platform/benches/primitives.rs | 30 +- crates/gpui_wgpu/Cargo.toml | 1 + crates/gpui_wgpu/src/cosmic_text_system.rs | 3 +- crates/gpui_wgpu/src/shaders.wgsl | 192 +++++-- crates/gpui_wgpu/src/wgpu_context.rs | 12 + crates/gpui_wgpu/src/wgpu_renderer.rs | 179 +++++-- crates/gpui_windows/Cargo.toml | 3 +- crates/gpui_windows/build.rs | 1 + crates/gpui_windows/src/directx_renderer.rs | 302 ++++++++++- crates/gpui_windows/src/platform.rs | 3 +- crates/gpui_windows/src/shaders.hlsl | 186 +++++-- crates/zlog/src/filter.rs | 14 + crates/ztracing_macro/Cargo.toml | 3 + 37 files changed, 2720 insertions(+), 488 deletions(-) create mode 100644 crates/gpui/examples/svg_animation.rs diff --git a/crates/gpui/examples/svg_animation.rs b/crates/gpui/examples/svg_animation.rs new file mode 100644 index 00000000..db915065 --- /dev/null +++ b/crates/gpui/examples/svg_animation.rs @@ -0,0 +1,222 @@ +#![cfg_attr(target_family = "wasm", no_main)] + +//! Compares SVGs animated with [`Svg::with_timed_transformation`], which +//! moves them in the already painted scene, against the same SVGs animated by +//! re-rendering with `with_animation`. It shows spinners and pulsing rings. +//! +//! The header counts how many times the view has rendered. With the retained +//! scene the count stays put while the SVGs keep animating; when re-rendering +//! it climbs once per frame. Pass `--rerender` to start in that mode, and +//! `--max-fps ` to cap how often the retained scene is presented. + +#[path = "example_support/fonts.rs"] +mod example_support; + +use std::{cell::Cell, time::Duration}; + +use gpui::{ + Animation, AnimationExt as _, App, Bounds, Context, Easing, TimedTransformation, + Transformation, Window, WindowBounds, WindowOptions, div, ease_out_quint, percentage, + prelude::*, px, rgb, size, svg, +}; +use gpui_platform::application; + +const ARROW_CIRCLE_SVG: &str = concat!( + env!("CARGO_MANIFEST_DIR"), + "/examples/image/arrow_circle.svg" +); + +const RING_SVG: &[u8] = br#""#; + +const SPINNER_COUNT: usize = 100; +const PULSE_COUNT: usize = 100; +const SPIN_PERIOD: Duration = Duration::from_secs(2); +const PULSE_PERIOD: Duration = Duration::from_millis(1750); + +#[derive(Clone, Copy, PartialEq)] +enum Mode { + RetainedScene, + Rerender, +} + +struct SvgAnimationExample { + mode: Mode, + max_fps: Option, + render_count: Cell, +} + +impl SvgAnimationExample { + fn timed(&self, transformation: TimedTransformation) -> TimedTransformation { + match self.max_fps { + Some(max_fps) => transformation.with_max_fps(max_fps), + None => transformation, + } + } + + fn pulse(&self, index: usize) -> impl IntoElement { + let ring = svg().size_4().data(RING_SVG).text_color(rgb(0x16a34a)); + let ring = match self.mode { + Mode::RetainedScene => ring + .with_timed_transformation( + self.timed( + TimedTransformation::new(PULSE_PERIOD) + .from(Transformation::alpha(0.6)) + .to(Transformation::scale(size(1.5, 1.5)).with_alpha(0.)) + .with_scale_easing(Easing::EaseOutQuint), + ), + ) + .into_any_element(), + Mode::Rerender => ring + .with_animation( + ("pulse", index), + Animation::new(PULSE_PERIOD).repeat_synced(), + |svg, delta| { + let scale = 1. + 0.5 * ease_out_quint()(delta); + svg.with_transformation( + Transformation::scale(size(scale, scale)) + .with_alpha(0.6 * (1. - delta)), + ) + }, + ) + .into_any_element(), + }; + div() + .size_6() + .flex() + .items_center() + .justify_center() + .child(div().absolute().size_1p5().rounded_full().bg(rgb(0x16a34a))) + .child(ring) + } + + fn spinner(&self, index: usize) -> impl IntoElement { + let spinner = svg() + .size_6() + .external_path(ARROW_CIRCLE_SVG) + .text_color(rgb(0x3b82f6)); + match self.mode { + Mode::RetainedScene => spinner + .with_timed_transformation(self.timed(TimedTransformation::rotation( + SPIN_PERIOD, + Transformation::default(), + ))) + .into_any_element(), + Mode::Rerender => spinner + .with_animation( + ("spinner", index), + Animation::new(SPIN_PERIOD).repeat_synced(), + |svg, delta| svg.with_transformation(Transformation::rotate(percentage(delta))), + ) + .into_any_element(), + } + } +} + +impl Render for SvgAnimationExample { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + self.render_count.set(self.render_count.get() + 1); + let mode = self.mode; + let mode_label = match mode { + Mode::RetainedScene => "retained scene (with_timed_transformation)", + Mode::Rerender => "re-render (with_animation)", + }; + + div() + .flex() + .flex_col() + .size_full() + .bg(gpui::white()) + .text_color(gpui::black()) + .p_4() + .gap_3() + .child( + div() + .flex() + .flex_row() + .items_center() + .gap_4() + .child( + div() + .id("toggle-mode") + .px_3() + .py_1() + .rounded_md() + .bg(rgb(0xe5e7eb)) + .cursor_pointer() + .child(format!("Mode: {mode_label}")) + .on_click(cx.listener(|this, _, _, cx| { + this.mode = match this.mode { + Mode::RetainedScene => Mode::Rerender, + Mode::Rerender => Mode::RetainedScene, + }; + cx.notify(); + })), + ) + .child(format!("Renders: {}", self.render_count.get())), + ) + .child( + div() + .flex() + .flex_row() + .flex_wrap() + .gap_2() + .children((0..SPINNER_COUNT).map(|index| self.spinner(index))), + ) + .child( + div() + .flex() + .flex_row() + .flex_wrap() + .gap_2() + .children((0..PULSE_COUNT).map(|index| self.pulse(index))), + ) + } +} + +fn run_example() { + application().run(|cx: &mut App| { + if !example_support::load_fonts(cx) { + return; + } + let options = WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds::centered( + None, + size(px(720.), px(480.)), + cx, + ))), + ..Default::default() + }; + cx.open_window(options, |_, cx| { + cx.activate(false); + let mode = if std::env::args().any(|arg| arg == "--rerender") { + Mode::Rerender + } else { + Mode::RetainedScene + }; + let mut arguments = std::env::args(); + let max_fps = arguments + .by_ref() + .find(|argument| argument == "--max-fps") + .and_then(|_| arguments.next()) + .and_then(|max_fps| max_fps.parse().ok()); + cx.new(|_| SvgAnimationExample { + mode, + max_fps, + render_count: Cell::new(0), + }) + }) + .expect("failed to open window"); + }); +} + +#[cfg(not(target_family = "wasm"))] +fn main() { + run_example(); +} + +#[cfg(target_family = "wasm")] +#[wasm_bindgen::prelude::wasm_bindgen(start)] +pub fn start() { + gpui_platform::web_init(); + run_example(); +} diff --git a/crates/gpui/examples/system_notifications.rs b/crates/gpui/examples/system_notifications.rs index faf69191..0deff83d 100644 --- a/crates/gpui/examples/system_notifications.rs +++ b/crates/gpui/examples/system_notifications.rs @@ -63,7 +63,7 @@ impl Render for SystemNotificationExample { ))) .child( button("dismiss", "Dismiss").on_click(cx.listener(|this, _, _, cx| { - cx.dismiss_system_notification(NOTIFICATION_TAG); + cx.dismiss_system_notification(NOTIFICATION_TAG).detach(); this.status = "Dismissed the notification".into(); cx.notify(); })), diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rs index f102819a..64a79c79 100644 --- a/crates/gpui/src/app.rs +++ b/crates/gpui/src/app.rs @@ -2085,8 +2085,11 @@ impl App { /// /// Best-effort: some platforms cannot retract a notification once shown, /// in which case it ages out of the notification center on its own. - pub fn dismiss_system_notification(&self, tag: &str) { - self.platform.dismiss_system_notification(tag); + /// The task completes after the platform calls return, not after any + /// asynchronous work inside the operating system. Dropping it does not + /// cancel dismissal. + pub fn dismiss_system_notification(&self, tag: &str) -> Task<()> { + self.platform.dismiss_system_notification(tag) } /// Registers the handler invoked when the user activates a system diff --git a/crates/gpui/src/app/headless_app_context.rs b/crates/gpui/src/app/headless_app_context.rs index c7f7c913..3eb2ebee 100644 --- a/crates/gpui/src/app/headless_app_context.rs +++ b/crates/gpui/src/app/headless_app_context.rs @@ -13,7 +13,7 @@ use crate::{ Context, Entity, EntityId, ForegroundExecutor, Global, Pixels, PlatformHeadlessRenderer, PlatformTextSystem, Render, Reservation, Size, Task, TestDispatcher, TestPlatform, TextSystem, Window, WindowBounds, WindowHandle, WindowOptions, - app::{GpuiBorrow, GpuiMode}, + app::{GpuiBorrow, GpuiMode, test_context::test_window}, }; use anyhow::Result; use image::RgbaImage; @@ -130,6 +130,15 @@ impl HeadlessAppContext { self.dispatcher.run_until_parked(); } + /// Simulates the window moving to a display with a different scale factor. + pub fn simulate_window_scale_factor_change( + &mut self, + window: AnyWindowHandle, + scale_factor: f32, + ) { + test_window(&self.app, window).simulate_scale_factor_change(scale_factor); + } + /// Advances the simulated clock. pub fn advance_clock(&self, duration: Duration) { self.dispatcher.advance_clock(duration); diff --git a/crates/gpui/src/app/test_context.rs b/crates/gpui/src/app/test_context.rs index beff5ea7..df3cce6f 100644 --- a/crates/gpui/src/app/test_context.rs +++ b/crates/gpui/src/app/test_context.rs @@ -16,6 +16,19 @@ use std::{ cell::RefCell, future::Future, ops::Deref, path::PathBuf, rc::Rc, sync::Arc, time::Duration, }; +pub(crate) fn test_window(app: &AppCell, window: AnyWindowHandle) -> TestWindow { + app.borrow_mut() + .windows + .get_mut(window.id) + .expect("window not found") + .as_deref_mut() + .expect("window is being updated") + .platform_window + .as_test() + .expect("window is not a TestWindow") + .clone() +} + /// A TestAppContext is provided to tests created with `#[gpui::test]`, it provides /// an implementation of `Context` with additional methods that are useful in tests. #[derive(Clone)] @@ -670,17 +683,7 @@ impl TestAppContext { /// Returns the `TestWindow` backing the given handle. pub(crate) fn test_window(&self, window: AnyWindowHandle) -> TestWindow { - self.app - .borrow_mut() - .windows - .get_mut(window.id) - .unwrap() - .as_deref_mut() - .unwrap() - .platform_window - .as_test() - .unwrap() - .clone() + test_window(&self.app, window) } /// Returns a stream of notifications whenever the Entity is updated. @@ -1424,7 +1427,7 @@ mod tests { }] ); - cx.update(|cx| cx.dismiss_system_notification("thread-1")); + cx.update(|cx| cx.dismiss_system_notification("thread-1").detach()); assert!(cx.delivered_system_notifications().is_empty()); assert_eq!(cx.dismissed_system_notifications(), ["thread-1"]); } @@ -1499,7 +1502,7 @@ mod tests { actions: Vec::new(), }); cx.on_system_notification_response(|response, cx| { - cx.dismiss_system_notification(&response.tag); + cx.dismiss_system_notification(&response.tag).detach(); }); }); diff --git a/crates/gpui/src/elements/animation.rs b/crates/gpui/src/elements/animation.rs index 33f7bc19..ddb0b19e 100644 --- a/crates/gpui/src/elements/animation.rs +++ b/crates/gpui/src/elements/animation.rs @@ -511,6 +511,15 @@ mod easing { move |delta| 1.0 - (1.0 - delta).powi(5) } + /// A heartbeat: a strong beat, a weaker one, then a rest. Starts and ends at 0 and peaks at 1. + pub fn heartbeat(delta: f32) -> f32 { + let beat = |center: f32, width: f32, height: f32| { + let x = (delta - center) / width; + height * (-x * x).exp() + }; + beat(0.2, 0.06, 1.0) + beat(0.4, 0.05, 0.58) + } + /// Apply the given easing function, first in the forward direction and then in the reverse direction pub fn bounce(easing: impl Fn(f32) -> f32) -> impl Fn(f32) -> f32 { move |delta| { diff --git a/crates/gpui/src/elements/svg.rs b/crates/gpui/src/elements/svg.rs index e87f0da6..8183abe4 100644 --- a/crates/gpui/src/elements/svg.rs +++ b/crates/gpui/src/elements/svg.rs @@ -1,21 +1,24 @@ use std::{ + f32::consts::TAU, fs, hash::{Hash, Hasher}, path::Path, sync::Arc, + time::Duration, }; use crate::{ App, Asset, Bounds, Element, GlobalElementId, Hitbox, InspectorElementId, InteractiveElement, - Interactivity, LayoutId, Pixels, Point, Radians, SharedString, Size, StyleRefinement, Styled, - TransformationMatrix, Window, point, px, radians, size, + Interactivity, LayoutId, Pixels, Point, Radians, SharedString, Size, SpriteAnimation, + StyleRefinement, Styled, TransformationMatrix, Window, ease_in_out, ease_out_quint, heartbeat, + linear, point, px, quadratic, radians, size, }; use gpui_util::ResultExt; /// An SVG element. pub struct Svg { interactivity: Interactivity, - transformation: Option, + transformation: Option, path: Option, external_path: Option, data: Option>, @@ -64,6 +67,20 @@ impl Svg { /// Transform the SVG element with the given transformation. /// Note that this won't effect the hitbox or layout of the element, only the rendering. pub fn with_transformation(mut self, transformation: Transformation) -> Self { + self.transformation = Some(transformation.into()); + self + } + + /// Continuously animate the SVG between two transformations, phase-locked to the + /// app's shared animation clock like [`crate::Animation::repeat_synced`]. + /// + /// The SVG is painted once. On later frames the window moves it in the scene it + /// already has and presents that again, instead of re-rendering this view. + /// + /// This replaces [`Self::with_transformation`], and like it doesn't affect layout + /// or hit testing. The SVG is still clipped and ordered by the bounds of its + /// starting transformation, so keep its motion close to them. + pub fn with_timed_transformation(mut self, transformation: TimedTransformation) -> Self { self.transformation = Some(transformation); self } @@ -138,23 +155,35 @@ impl Element for Svg { window, cx, |style, window, cx| { - let transformation = self + let center = bounds.center(); + let scale_factor = window.scale_factor(); + let animation = self .transformation - .as_ref() - .map(|transformation| { - transformation.into_matrix(bounds.center(), window.scale_factor()) - }) + .filter(|timed| timed.is_animated() && !cx.reduce_motion()) + .map(|timed| SpriteAnimation::new(timed, center, scale_factor)); + // Without an animation, such as with reduced motion, the SVG is + // drawn at its starting transformation. + let pose = self.transformation.map(|timed| timed.from); + let transformation = pose + .map(|pose| pose.into_matrix(center, scale_factor)) .unwrap_or_default(); + // The scene applies an animated sprite's alpha before each present, + // on top of the color it is inserted with. + let alpha = match animation { + Some(_) => 1., + None => pose.map_or(1., |pose| pose.alpha_factor()), + }; if let Some((data, path)) = self.data.as_ref().zip(self.data_path.as_ref()) { if let Some(color) = style.text.color { window - .paint_svg( + .paint_animated_svg( bounds, path.clone(), Some(&**data), transformation, - color, + animation, + color.opacity(alpha), cx, ) .log_err(); @@ -170,18 +199,27 @@ impl Element for Svg { }; window - .paint_svg( + .paint_animated_svg( bounds, path.clone(), Some(&bytes), transformation, - color, + animation, + color.opacity(alpha), cx, ) .log_err(); } else if let Some((path, color)) = self.path.as_ref().zip(style.text.color) { window - .paint_svg(bounds, path.clone(), None, transformation, color, cx) + .paint_animated_svg( + bounds, + path.clone(), + None, + transformation, + animation, + color.opacity(alpha), + cx, + ) .log_err(); } }, @@ -207,6 +245,7 @@ pub struct Transformation { scale: Size, translate: Point, rotate: Radians, + alpha: f32, } impl Default for Transformation { @@ -215,6 +254,7 @@ impl Default for Transformation { scale: size(1.0, 1.0), translate: point(px(0.0), px(0.0)), rotate: radians(0.0), + alpha: 1.0, } } } @@ -224,17 +264,15 @@ impl Transformation { pub fn scale(scale: Size) -> Self { Self { scale, - translate: point(px(0.0), px(0.0)), - rotate: radians(0.0), + ..Self::default() } } /// Create a new Transformation with the specified translation. pub fn translate(translate: Point) -> Self { Self { - scale: size(1.0, 1.0), translate, - rotate: radians(0.0), + ..Self::default() } } @@ -242,12 +280,30 @@ impl Transformation { pub fn rotate(rotate: impl Into) -> Self { let rotate = rotate.into(); Self { - scale: size(1.0, 1.0), - translate: point(px(0.0), px(0.0)), rotate, + ..Self::default() + } + } + + /// Create a new Transformation that multiplies the SVG's alpha by `alpha`. + pub fn alpha(alpha: f32) -> Self { + Self { + alpha, + ..Self::default() } } + /// Update the alpha factor of this transformation. Unlike an element's + /// opacity, this only applies to the SVG itself. + pub fn with_alpha(mut self, alpha: f32) -> Self { + self.alpha = alpha; + self + } + + pub(crate) fn alpha_factor(&self) -> f32 { + self.alpha + } + /// Update the scaling factor of this transformation. pub fn with_scaling(mut self, scale: Size) -> Self { self.scale = scale; @@ -266,7 +322,11 @@ impl Transformation { self } - fn into_matrix(self, center: Point, scale_factor: f32) -> TransformationMatrix { + pub(crate) fn into_matrix( + self, + center: Point, + scale_factor: f32, + ) -> TransformationMatrix { //Note: if you read this as a sequence of matrix multiplications, start from the bottom TransformationMatrix::unit() .translate(center.scale(scale_factor) + self.translate.scale(scale_factor)) @@ -276,6 +336,201 @@ impl Transformation { } } +/// How a value's rate of change varies over one pass of a [`TimedTransformation`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Easing { + /// A constant rate. + #[default] + Linear, + /// Starts slowly and accelerates. + Quadratic, + /// Starts and ends slowly, and speeds up in the middle. + EaseInOut, + /// Starts quickly and decelerates to a stop. + EaseOutQuint, + /// Two quick beats, a strong one then a weaker one, followed by a rest. + /// Unlike the other easings it ends where it started, so the value + /// reaches `to` at the first beat and is back at `from` by the end. + Heartbeat, +} + +impl Easing { + fn apply(self, delta: f32) -> f32 { + match self { + Easing::Linear => linear(delta), + Easing::Quadratic => quadratic(delta), + Easing::EaseInOut => ease_in_out(delta), + Easing::EaseOutQuint => ease_out_quint()(delta), + Easing::Heartbeat => heartbeat(delta), + } + } +} + +/// A [`Transformation`] that repeatedly moves from one pose to another over a +/// period, for [`Svg::with_timed_transformation`]. +/// +/// Each value of the transformation has its own [`Easing`], so for example an +/// SVG can grow quickly at first while fading at a constant rate. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct TimedTransformation { + period: Duration, + from: Transformation, + to: Transformation, + scale_easing: Easing, + translation_easing: Easing, + rotation_easing: Easing, + alpha_easing: Easing, + alternate: bool, + min_frame_interval: Option, +} + +impl TimedTransformation { + /// Create a timed transformation that repeats every `period`. It animates + /// nothing until [`Self::from`] and [`Self::to`] differ. + pub fn new(period: Duration) -> Self { + Self { + period, + from: Transformation::default(), + to: Transformation::default(), + scale_easing: Easing::Linear, + translation_easing: Easing::Linear, + rotation_easing: Easing::Linear, + alpha_easing: Easing::Linear, + alternate: false, + min_frame_interval: None, + } + } + + /// Create a timed transformation that turns `from` clockwise, one full + /// turn per `period`. + pub fn rotation(period: Duration, from: Transformation) -> Self { + Self::new(period) + .from(from) + .to(from.with_rotation(radians(from.rotate.0 + TAU))) + } + + fn is_animated(&self) -> bool { + !self.period.is_zero() && self.from != self.to + } + + /// Set the transformation at the start of each period. + pub fn from(mut self, transformation: Transformation) -> Self { + self.from = transformation; + self + } + + /// Set the transformation reached at the end of each period. + pub fn to(mut self, transformation: Transformation) -> Self { + self.to = transformation; + self + } + + /// Set the easing of every value. + pub fn with_easing(mut self, easing: Easing) -> Self { + self.scale_easing = easing; + self.translation_easing = easing; + self.rotation_easing = easing; + self.alpha_easing = easing; + self + } + + /// Set the easing of the scale. + pub fn with_scale_easing(mut self, easing: Easing) -> Self { + self.scale_easing = easing; + self + } + + /// Set the easing of the translation. + pub fn with_translation_easing(mut self, easing: Easing) -> Self { + self.translation_easing = easing; + self + } + + /// Set the easing of the rotation. + pub fn with_rotation_easing(mut self, easing: Easing) -> Self { + self.rotation_easing = easing; + self + } + + /// Set the easing of the alpha. + pub fn with_alpha_easing(mut self, easing: Easing) -> Self { + self.alpha_easing = easing; + self + } + + /// Move from the start to the end and back again within each period, + /// instead of jumping back to the start. + pub fn alternate(mut self) -> Self { + self.alternate = true; + self + } + + /// Present at most `max_fps` frames per second while nothing but timed + /// transformations needs a frame. The least restrictive limit in a window + /// wins. Values that are not finite and positive are ignored. + pub fn with_max_fps(mut self, max_fps: f32) -> Self { + if max_fps.is_finite() && max_fps > 0.0 { + self.min_frame_interval = Some(Duration::from_secs_f64(1.0 / max_fps as f64)); + } + self + } + + pub(crate) fn min_frame_interval(&self) -> Option { + self.min_frame_interval + } + + /// The transformation `elapsed` time after the animation clock started. + pub(crate) fn at(&self, elapsed: Duration) -> Transformation { + let period_nanos = self.period.as_nanos(); + if period_nanos == 0 { + return self.from; + } + let mut delta = Duration::from_nanos((elapsed.as_nanos() % period_nanos) as u64) + .as_secs_f32() + / self.period.as_secs_f32(); + if self.alternate { + delta = 1.0 - (2.0 * delta - 1.0).abs(); + } + + let interpolate = + |from: f32, to: f32, easing: Easing| from + (to - from) * easing.apply(delta); + let (from, to) = (self.from, self.to); + Transformation { + scale: size( + interpolate(from.scale.width, to.scale.width, self.scale_easing), + interpolate(from.scale.height, to.scale.height, self.scale_easing), + ), + translate: point( + px(interpolate( + from.translate.x.0, + to.translate.x.0, + self.translation_easing, + )), + px(interpolate( + from.translate.y.0, + to.translate.y.0, + self.translation_easing, + )), + ), + rotate: radians(interpolate( + from.rotate.0, + to.rotate.0, + self.rotation_easing, + )), + alpha: interpolate(from.alpha, to.alpha, self.alpha_easing), + } + } +} + +impl From for TimedTransformation { + /// A timed transformation that stays at `transformation`. + fn from(transformation: Transformation) -> Self { + Self::new(Duration::ZERO) + .from(transformation) + .to(transformation) + } +} + enum SvgAsset {} impl Asset for SvgAsset { @@ -293,3 +548,182 @@ impl Asset for SvgAsset { } } } + +#[cfg(test)] +mod tests { + use std::{cell::Cell, f32::consts::FRAC_PI_2, rc::Rc, time::Duration}; + + use crate::{ + Context, Easing, IntoElement, Render, SpriteAnimationId, Styled, TestAppContext, + TimedTransformation, Transformation, VisualTestContext, Window, div, prelude::*, px, red, + size, svg, + }; + + const SQUARE_SVG: &[u8] = + br#""#; + + struct AnimatedSvgView { + transformation: TimedTransformation, + renders: Rc>, + } + + impl Render for AnimatedSvgView { + fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + self.renders.set(self.renders.get() + 1); + div().child( + svg() + .data(SQUARE_SVG) + .size(px(16.)) + .text_color(red()) + .with_timed_transformation(self.transformation), + ) + } + } + + struct Pose { + rotation_scale: [[f32; 2]; 2], + center_offset: [f32; 2], + alpha: f32, + } + + /// Opens a window showing `transformation` and returns a function that + /// delivers a frame `advance` later and reports the animated sprite's pose, + /// along with the number of times the view has rendered. + fn animate( + transformation: TimedTransformation, + cx: &mut TestAppContext, + ) -> (impl FnMut(Duration) -> Pose, Rc>) { + let renders = Rc::new(Cell::new(0)); + let (_, cx) = cx.add_window_view({ + let renders = renders.clone(); + move |_, _| AnimatedSvgView { + transformation, + renders, + } + }); + cx.run_until_parked(); + let cx: &mut VisualTestContext = cx; + let pose_after = move |advance: Duration| { + cx.executor().advance_clock(advance); + cx.update(|window, cx| { + window.simulate_next_frame(cx); + window.advance_scene_animations(cx); + let sprite = window + .rendered_frame + .scene + .monochrome_sprites + .iter() + .find(|sprite| sprite.animation != SpriteAnimationId::NONE) + .expect("the SVG should be painted as an animated sprite"); + let center = sprite.bounds.center(); + let [[a, b], [c, d]] = sprite.transformation.rotation_scale; + let [x, y] = sprite.transformation.translation; + Pose { + rotation_scale: sprite.transformation.rotation_scale, + center_offset: [ + a * center.x.0 + b * center.y.0 + x - center.x.0, + c * center.x.0 + d * center.y.0 + y - center.y.0, + ], + alpha: sprite.color.a, + } + }) + }; + (pose_after, renders) + } + + #[crate::test] + fn test_rotation_advances_without_rerendering(cx: &mut TestAppContext) { + let (mut pose_after, renders) = animate( + TimedTransformation::rotation(Duration::from_secs(1), Transformation::default()), + cx, + ); + let renders_before_frames = renders.get(); + + for quarter in 0..4 { + let pose = pose_after(if quarter == 0 { + Duration::ZERO + } else { + Duration::from_millis(250) + }); + let (sin, cos) = (quarter as f32 * FRAC_PI_2).sin_cos(); + let expected = [[cos, -sin], [sin, cos]]; + for (actual, expected) in pose + .rotation_scale + .as_flattened() + .iter() + .zip(expected.as_flattened()) + { + assert!((actual - expected).abs() < 1e-5, "quarter {quarter}"); + } + assert!(pose.center_offset.iter().all(|offset| offset.abs() < 1e-3)); + } + assert_eq!(renders.get(), renders_before_frames); + } + + #[crate::test] + fn test_timed_transformation_eases_each_value_separately(cx: &mut TestAppContext) { + let (mut pose_after, renders) = animate( + TimedTransformation::new(Duration::from_secs(1)) + .from(Transformation::alpha(0.4)) + .to(Transformation::scale(size(1.5, 1.5)).with_alpha(0.)) + .with_scale_easing(Easing::EaseOutQuint), + cx, + ); + let renders_before_frames = renders.get(); + + let pose = pose_after(Duration::ZERO); + assert!((pose.rotation_scale[0][0] - 1.).abs() < 1e-5); + assert!((pose.alpha - 0.4).abs() < 1e-5); + + // Halfway through, the scale has eased most of the way out while the + // alpha has faded exactly half. + let pose = pose_after(Duration::from_millis(500)); + assert!((pose.rotation_scale[0][0] - (1. + 0.5 * (1. - 0.5f32.powi(5)))).abs() < 1e-5); + assert!((pose.alpha - 0.2).abs() < 1e-5); + assert_eq!(renders.get(), renders_before_frames); + } + + #[crate::test] + fn test_heartbeat_returns_to_its_start(cx: &mut TestAppContext) { + let (mut pose_after, _) = animate( + TimedTransformation::new(Duration::from_secs(1)) + .to(Transformation::scale(size(1.12, 1.12))) + .with_scale_easing(Easing::Heartbeat), + cx, + ); + + assert!((pose_after(Duration::ZERO).rotation_scale[0][0] - 1.).abs() < 1e-3); + assert!((pose_after(Duration::from_millis(200)).rotation_scale[0][0] - 1.12).abs() < 1e-3); + // Each call advances the clock further, to 400ms and then 999ms. + let second_beat = pose_after(Duration::from_millis(200)).rotation_scale[0][0]; + assert!(second_beat > 1.05 && second_beat < 1.09); + assert!((pose_after(Duration::from_millis(599)).rotation_scale[0][0] - 1.).abs() < 1e-3); + } + + #[crate::test] + fn test_scene_presents_as_often_as_its_least_capped_animation(cx: &mut TestAppContext) { + let spin = TimedTransformation::rotation(Duration::from_secs(1), Transformation::default()); + let (_, cx) = cx.add_window_view(move |_, _| CappedView { spin }); + cx.run_until_parked(); + cx.update(|window, _| { + assert_eq!( + window.rendered_frame.scene.animation_frame_interval(), + Some(Duration::from_millis(50)) + ); + }); + } + + struct CappedView { + spin: TimedTransformation, + } + + impl Render for CappedView { + fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + let icon = || svg().data(SQUARE_SVG).size(px(16.)).text_color(red()); + div() + .child(icon().with_timed_transformation(self.spin.with_max_fps(10.))) + .child(icon().with_timed_transformation(self.spin.with_max_fps(20.))) + .child(icon().with_transformation(Transformation::alpha(0.5))) + } + } +} diff --git a/crates/gpui/src/geometry.rs b/crates/gpui/src/geometry.rs index 899db1b3..df59ce8c 100644 --- a/crates/gpui/src/geometry.rs +++ b/crates/gpui/src/geometry.rs @@ -3166,7 +3166,7 @@ impl From for DevicePixels { /// a single logical pixel may correspond to multiple physical pixels. By using `ScaledPixels`, /// dimensions and positions can be specified in a way that scales appropriately across different /// display resolutions. -#[derive(Clone, Copy, Default, Add, AddAssign, Sub, SubAssign, Div, DivAssign, PartialEq)] +#[derive(Clone, Copy, Default, Add, AddAssign, Sub, SubAssign, Neg, Div, DivAssign, PartialEq)] #[repr(transparent)] pub struct ScaledPixels(pub f32); @@ -3320,6 +3320,18 @@ impl MulAssign for ScaledPixels { } } +impl std::iter::Sum for ScaledPixels { + fn sum>(iter: I) -> Self { + iter.fold(Self::default(), |a, b| a + b) + } +} + +impl<'a> std::iter::Sum<&'a ScaledPixels> for ScaledPixels { + fn sum>(iter: I) -> Self { + iter.fold(Self::default(), |a, b| a + *b) + } +} + /// Represents a length in rems, a unit based on the font-size of the window, which can be assigned with [`Window::set_rem_size`][set_rem_size]. /// /// Rems are used for defining lengths that are scalable and consistent across different UI elements. @@ -3804,7 +3816,7 @@ pub const fn relative(fraction: f32) -> DefiniteLength { /// Returns the Golden Ratio, i.e. `~(1.0 + sqrt(5.0)) / 2.0`. pub const fn phi() -> DefiniteLength { - relative(1.618_034) + relative(std::f32::consts::GOLDEN_RATIO) } /// Constructs a `Rems` value representing a length in rems. diff --git a/crates/gpui/src/keymap.rs b/crates/gpui/src/keymap.rs index 6283fe6b..a7a32116 100644 --- a/crates/gpui/src/keymap.rs +++ b/crates/gpui/src/keymap.rs @@ -199,10 +199,10 @@ impl Keymap { let mut pending_bindings = SmallVec::<[(BindingIndex, &KeyBinding); 1]>::new(); for (ix, binding) in keymap_bindings { - let Some(depth) = self.binding_enabled(binding, context_stack) else { + let Some(pending) = binding.match_keystrokes(input) else { continue; }; - let Some(pending) = binding.match_keystrokes(input) else { + let Some(depth) = self.binding_enabled(binding, context_stack) else { continue; }; diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs index 1f344f2f..86520ab0 100644 --- a/crates/gpui/src/platform.rs +++ b/crates/gpui/src/platform.rs @@ -579,8 +579,12 @@ pub trait Platform: 'static { /// /// Best-effort: some platforms cannot retract a notification once shown, /// in which case it ages out of the notification center on its own. - fn dismiss_system_notification(&self, tag: &str) { + /// The task completes after the platform calls return, not after any + /// asynchronous work inside the operating system. Dropping it does not + /// cancel dismissal. + fn dismiss_system_notification(&self, tag: &str) -> Task<()> { _ = tag; + Task::ready(()) } /// Registers the callback invoked when the user activates a system diff --git a/crates/gpui/src/platform/test/platform.rs b/crates/gpui/src/platform/test/platform.rs index 9d112b30..04ebbe92 100644 --- a/crates/gpui/src/platform/test/platform.rs +++ b/crates/gpui/src/platform/test/platform.rs @@ -1,16 +1,14 @@ -#[cfg(any(test, feature = "test-support"))] -use crate::NoopTextSystem; -#[cfg(any(test, feature = "test-support"))] -use crate::PathPromptOptions; use crate::{ ActivityGuard, AnyWindowHandle, AppLifecyclePhase, BackgroundExecutor, ClipboardItem, - CursorStyle, DevicePixels, DisplayId, DummyKeyboardMapper, ForegroundExecutor, Keymap, - OwnedMenu, Platform, PlatformDisplay, PlatformHeadlessRenderer, PlatformKeyboardLayout, + CursorStyle, DevicePixels, DummyKeyboardMapper, ForegroundExecutor, Keymap, OwnedMenu, + Platform, PlatformDisplay, PlatformHeadlessRenderer, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem, PromptButton, ScreenCaptureFrame, ScreenCaptureSource, ScreenCaptureStream, SharedString, SourceMetadata, SystemNotification, SystemNotificationResponse, Task, TestDisplay, TestWindow, ThermalState, WindowAppearance, WindowParams, size, }; +#[cfg(any(test, feature = "test-support"))] +use crate::{DisplayId, NoopTextSystem, PathPromptOptions}; use anyhow::Result; #[cfg(any(test, feature = "test-support"))] use collections::VecDeque; @@ -735,7 +733,7 @@ impl Platform for TestPlatform { system_notifications.shown.push(notification); } - fn dismiss_system_notification(&self, tag: &str) { + fn dismiss_system_notification(&self, tag: &str) -> Task<()> { let mut system_notifications = self.system_notifications.borrow_mut(); system_notifications .delivered @@ -743,6 +741,7 @@ impl Platform for TestPlatform { system_notifications .dismissed .push(SharedString::from(tag.to_string())); + Task::ready(()) } fn on_system_notification_response( diff --git a/crates/gpui/src/profiler.rs b/crates/gpui/src/profiler.rs index d78ccb9d..18e639a3 100644 --- a/crates/gpui/src/profiler.rs +++ b/crates/gpui/src/profiler.rs @@ -741,7 +741,7 @@ pub(crate) struct TraceGuard; #[cfg(any(feature = "bench-support", all(test, feature = "profiler")))] pub(crate) fn trace_scope() -> TraceGuard { - let incremented = TRACE_STATE.fetch_update(Ordering::AcqRel, Ordering::Acquire, |state| { + let incremented = TRACE_STATE.try_update(Ordering::AcqRel, Ordering::Acquire, |state| { (state & TRACE_SCOPE_COUNT_MASK < TRACE_SCOPE_COUNT_MASK).then_some(state + 1) }); assert!(incremented.is_ok(), "too many active profiler trace scopes"); @@ -751,10 +751,9 @@ pub(crate) fn trace_scope() -> TraceGuard { #[cfg(any(feature = "bench-support", all(test, feature = "profiler")))] impl Drop for TraceGuard { fn drop(&mut self) { - let previous_state = - TRACE_STATE.fetch_update(Ordering::AcqRel, Ordering::Acquire, |state| { - (state & TRACE_SCOPE_COUNT_MASK > 0).then_some(state - 1) - }); + let previous_state = TRACE_STATE.try_update(Ordering::AcqRel, Ordering::Acquire, |state| { + (state & TRACE_SCOPE_COUNT_MASK > 0).then_some(state - 1) + }); match previous_state { Ok(1) => clear_trace_buffers(), Ok(_) => {} diff --git a/crates/gpui/src/profiler/journal.rs b/crates/gpui/src/profiler/journal.rs index 28c66b6e..4c810f86 100644 --- a/crates/gpui/src/profiler/journal.rs +++ b/crates/gpui/src/profiler/journal.rs @@ -167,6 +167,8 @@ pub enum FrameSkipReason { ThermalFrameRateLimit, /// Low power mode deferred drawing. LowPowerFrameRateLimit, + /// A scene animation's frame rate cap deferred presenting. + AnimationFrameRateLimit, } /// A completed frame request that returned without drawing a new frame. @@ -442,7 +444,7 @@ impl ForegroundRunnableCounter { fn finished(&self) { let _ = self .0 - .fetch_update(Ordering::AcqRel, Ordering::Acquire, |count| { + .try_update(Ordering::AcqRel, Ordering::Acquire, |count| { count.checked_sub(1) }); } diff --git a/crates/gpui/src/scene.rs b/crates/gpui/src/scene.rs index 4fe789e7..b2104e54 100644 --- a/crates/gpui/src/scene.rs +++ b/crates/gpui/src/scene.rs @@ -6,10 +6,13 @@ use serde::{Deserialize, Serialize}; use crate::{ AtlasTextureId, AtlasTile, Background, Bounds, ContentMask, Corners, Edges, Hsla, Path, - PathTiles, Pixels, Point, Radians, ScaledPixels, Size, bounds_tree::BoundsTree, + PathTiles, Pixels, Point, Radians, ScaledPixels, Size, TimedTransformation, + bounds_tree::BoundsTree, }; use smallvec::SmallVec; -use std::{collections::VecDeque, fmt::Debug, iter::Peekable, ops::Range, rc::Rc, slice}; +use std::{ + collections::VecDeque, fmt::Debug, iter::Peekable, ops::Range, rc::Rc, slice, time::Duration, +}; #[expect(missing_docs)] pub type DrawOrder = u32; @@ -57,6 +60,7 @@ pub struct Scene { pub subpixel_sprites: Vec, pub polychrome_sprites: Vec, pub surfaces: Vec, + animations: Vec, } #[expect(missing_docs)] @@ -74,6 +78,49 @@ impl Scene { self.subpixel_sprites.clear(); self.polychrome_sprites.clear(); self.surfaces.clear(); + self.animations.clear(); + } + + /// Inserts a sprite that [`Self::advance_animations`] keeps moving. The + /// sprite's color is taken as its color before the animation's alpha. + pub(crate) fn insert_animated_sprite( + &mut self, + mut sprite: MonochromeSprite, + mut animation: SpriteAnimation, + ) { + sprite.animation = SpriteAnimationId(self.animations.len() as u32); + animation.base_color = sprite.color; + if self.try_insert_primitive(sprite.into()) { + self.animations.push(animation); + } + } + + /// How long the window may wait between presents of this scene while only + /// its animations need a frame: `None` when nothing in it animates, and + /// zero when an animation wants every frame. + pub(crate) fn animation_frame_interval(&self) -> Option { + self.animations + .iter() + .map(|animation| { + animation + .transformation + .min_frame_interval() + .unwrap_or_default() + }) + .min() + } + + /// Moves every animated sprite to its pose at `elapsed` time on the app's + /// synced animation clock, without the scene being rebuilt. + pub(crate) fn advance_animations(&mut self, elapsed: Duration) { + for animation in &self.animations { + let Some(sprite) = self.monochrome_sprites.get_mut(animation.sprite_index) else { + continue; + }; + let pose = animation.transformation.at(elapsed); + sprite.transformation = pose.into_matrix(animation.center, animation.scale_factor); + sprite.color = animation.base_color.opacity(pose.alpha_factor()); + } } pub fn len(&self) -> usize { @@ -117,10 +164,14 @@ impl Scene { } pub fn insert_primitive(&mut self, primitive: impl Into) { - let primitive = primitive.into(); + self.try_insert_primitive(primitive.into()); + } + + /// Returns whether the primitive was kept, rather than clipped away. + fn try_insert_primitive(&mut self, primitive: Primitive) -> bool { let clipped_bounds = primitive.clipped_bounds(); if clipped_bounds.is_empty() { - return; + return false; } let kind = primitive.kind(); @@ -143,6 +194,7 @@ impl Scene { } self.paint_operations .push(PaintOperation::Primitive(primitive)); + true } fn push_primitive(&mut self, primitive: Primitive, order: DrawOrder) { @@ -175,7 +227,17 @@ impl Scene { pub fn replay(&mut self, range: Range, prev_scene: &Scene) { for operation in &prev_scene.paint_operations[range] { match operation { - PaintOperation::Primitive(primitive) => self.insert_primitive(primitive.clone()), + PaintOperation::Primitive(primitive) => { + // Animation ids index the scene they were inserted into. + if let Primitive::MonochromeSprite(sprite) = primitive + && let Some(animation) = + prev_scene.animations.get(sprite.animation.0 as usize) + { + self.insert_animated_sprite(*sprite, *animation); + } else { + self.insert_primitive(primitive.clone()); + } + } PaintOperation::StartLayer => self.push_layer(), PaintOperation::EndLayer => self.pop_layer(), } @@ -184,17 +246,30 @@ impl Scene { pub fn finish(&mut self) { debug_assert!(self.layer_stack.is_empty(), "unbalanced scene layers"); - self.shadows.sort_by_key(|shadow| shadow.order); - self.quads.sort_by_key(|quad| quad.order); + let keys = &mut Vec::new(); + sort_in_place(&mut self.shadows, keys, |shadow| (shadow.order, 0)); + sort_in_place(&mut self.quads, keys, |quad| (quad.order, 0)); self.paths.sort_by_key(|path| path.order); - self.underlines.sort_by_key(|underline| underline.order); - self.monochrome_sprites - .sort_by_key(|sprite| (sprite.order, sprite.tile.texture_id.index)); - self.subpixel_sprites - .sort_by_key(|sprite| (sprite.order, sprite.tile.texture_id.index)); - self.polychrome_sprites - .sort_by_key(|sprite| (sprite.order, sprite.tile.texture_id.index)); + sort_in_place(&mut self.underlines, keys, |underline| (underline.order, 0)); + sort_in_place(&mut self.monochrome_sprites, keys, |sprite| { + (sprite.order, sprite.tile.texture_id.index) + }); + sort_in_place(&mut self.subpixel_sprites, keys, |sprite| { + (sprite.order, sprite.tile.texture_id.index) + }); + sort_in_place(&mut self.polychrome_sprites, keys, |sprite| { + (sprite.order, sprite.tile.texture_id.index) + }); self.surfaces.sort_by_key(|surface| surface.order); + + // Sorting moved the sprites, so animations learn where theirs ended up. + if !self.animations.is_empty() { + for (index, sprite) in self.monochrome_sprites.iter().enumerate() { + if let Some(animation) = self.animations.get_mut(sprite.animation.0 as usize) { + animation.sprite_index = index; + } + } + } } #[cfg_attr( @@ -226,6 +301,57 @@ impl Scene { } } +/// Sorts small `(key, index)` pairs instead of the primitives themselves, then moves each +/// primitive into place once. Primitives are large, so a comparison sort that shuffles them +/// directly spends most of its time copying. Ties keep insertion order, as `sort_by_key` +/// does, because the index is part of what is sorted. +fn sort_in_place( + primitives: &mut [T], + keys: &mut Vec<(u64, u32)>, + key: impl Fn(&T) -> (u32, u32), +) { + if primitives.is_sorted_by_key(&key) { + return; + } + keys.clear(); + keys.extend(primitives.iter().enumerate().map(|(index, primitive)| { + let (major, minor) = key(primitive); + ((major as u64) << 32 | minor as u64, index as u32) + })); + keys.sort_unstable(); + + // `keys[target].1` is the source index for `target`. Follow each cycle of that + // permutation, marking visited slots by pointing them at themselves. + for start in 0..primitives.len() { + if keys[start].1 as usize == start { + continue; + } + let displaced = primitives[start]; + let mut target = start; + loop { + let source = keys[target].1 as usize; + keys[target].1 = target as u32; + if source == start { + primitives[target] = displaced; + break; + } + primitives[target] = primitives[source]; + target = source; + } + } +} + +/// The depth step between consecutive quads in a frame with `quad_count` quads. +pub fn quad_depth_scale(quad_count: usize) -> f32 { + let denominator = (quad_count.min((1 << 24) - 1) + 1).next_power_of_two(); + 1.0 / denominator as f32 +} + +/// Maps a quad's index in [`Scene::quads`] to depth, with greater values closer. +pub fn quad_depth(quad_id: u32, scale: f32) -> f32 { + ((quad_id + 1) as f32 * scale).min(1.0) +} + #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Default)] #[cfg_attr( all( @@ -816,7 +942,7 @@ impl Default for TransformationMatrix { #[expect(missing_docs)] pub struct MonochromeSprite { pub order: DrawOrder, - pub pad: u32, + pub animation: SpriteAnimationId, pub tile: AtlasTile, pub bounds: Bounds, pub content_mask: ContentMask, @@ -824,6 +950,52 @@ pub struct MonochromeSprite { pub transformation: TransformationMatrix, } +/// Refers to an animation of the scene a sprite is inserted into. +/// +/// A single `u32` so it fits the sprite's existing padding and leaves the +/// instance layout unchanged on every backend; renderers ignore it. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[repr(transparent)] +pub struct SpriteAnimationId(u32); + +impl SpriteAnimationId { + /// No animation. + pub const NONE: Self = Self(u32::MAX); +} + +impl Default for SpriteAnimationId { + fn default() -> Self { + Self::NONE + } +} + +/// A [`TimedTransformation`] the window applies to a sprite right before +/// every present, so the scene can be presented again without being redrawn. +#[derive(Copy, Clone, Debug)] +pub(crate) struct SpriteAnimation { + transformation: TimedTransformation, + center: Point, + scale_factor: f32, + base_color: Hsla, + sprite_index: usize, +} + +impl SpriteAnimation { + pub(crate) fn new( + transformation: TimedTransformation, + center: Point, + scale_factor: f32, + ) -> Self { + Self { + transformation, + center, + scale_factor, + base_color: Hsla::default(), + sprite_index: usize::MAX, + } + } +} + impl From for Primitive { fn from(sprite: MonochromeSprite) -> Self { Primitive::MonochromeSprite(sprite) diff --git a/crates/gpui/src/svg_renderer.rs b/crates/gpui/src/svg_renderer.rs index 49f77a17..ce0e2b07 100644 --- a/crates/gpui/src/svg_renderer.rs +++ b/crates/gpui/src/svg_renderer.rs @@ -2,11 +2,14 @@ use crate::{ AssetSource, DevicePixels, IsZero, RenderImage, Result, SharedString, Size, swap_rgba_pa_to_bgra, }; +use collections::HashMap; use image::Frame; +use parking_lot::Mutex; use resvg::tiny_skia::Pixmap; use smallvec::SmallVec; use std::{ hash::Hash, + path::Path, sync::{Arc, LazyLock, OnceLock}, }; @@ -102,6 +105,19 @@ pub struct SvgRenderer { /// scales should retain this value to avoid re-paying the parse cost. pub struct ParsedSvg(usvg::Tree); +/// The font of an SVG `` element, as the values of its presentation attributes. +#[derive(Clone, Copy, Debug)] +pub struct SvgTextFont<'a> { + /// The `font-family` list. + pub family: &'a str, + /// The `font-size`, in pixels. + pub size: f32, + /// The `font-weight`. + pub weight: &'a str, + /// The `font-style`. + pub style: &'a str, +} + /// The size in which to rasterize the SVG. #[derive(Clone, Copy)] pub enum SvgSize { @@ -132,45 +148,64 @@ impl SvgRenderer { // eagerly at construction time. This avoids the expensive deep-clone // of the system font database for code paths that never render SVGs // (e.g. tests). - let enriched_fontdb: Arc>> = Arc::new(OnceLock::new()); + let enriched_fontdb = Arc::new(OnceLock::>::new()); let default_font_resolver = usvg::FontResolver::default_font_selector(); let font_resolver = Box::new({ let asset_source = asset_source.clone(); + let enriched_fontdb = enriched_fontdb.clone(); move |font: &usvg::Font, db: &mut Arc| { + let fontdb = enriched_fontdb.get_or_init(|| { + let mut db = (**SYSTEM_FONT_DB).clone(); + load_bundled_fonts(&*asset_source, &mut db); + fix_generic_font_families(&mut db); + Mutex::new(FontDatabase { + database: Arc::new(db), + owned_faces: HashMap::default(), + remaining_owned_bytes: MAX_OWNED_FONT_BYTES, + fallback_faces: HashMap::default(), + }) + }); if db.is_empty() { - let fontdb = enriched_fontdb.get_or_init(|| { - let mut db = (**SYSTEM_FONT_DB).clone(); - load_bundled_fonts(&*asset_source, &mut db); - fix_generic_font_families(&mut db); - Arc::new(db) - }); - *db = fontdb.clone(); - } - if let Some(id) = default_font_resolver(font, db) { - return Some(id); + *db = fontdb.lock().database.clone(); } - // fontdb doesn't recognize CSS system font keywords like "system-ui" - // or "ui-sans-serif", so fall back to sans-serif before any face. - let sans_query = usvg::fontdb::Query { - families: &[usvg::fontdb::Family::SansSerif], - ..Default::default() - }; - db.query(&sans_query) - .or_else(|| db.faces().next().map(|f| f.id)) + let id = default_font_resolver(font, db).or_else(|| { + // fontdb doesn't recognize CSS system font keywords like "system-ui" + // or "ui-sans-serif", so fall back to sans-serif before any face. + let sans_query = usvg::fontdb::Query { + families: &[usvg::fontdb::Family::SansSerif], + ..Default::default() + }; + db.query(&sans_query) + .or_else(|| db.faces().next().map(|f| f.id)) + })?; + Some(fontdb.lock().owned_face(db, id)) } }); let default_fallback_selection = usvg::FontResolver::default_fallback_selector(); let fallback_selection = Box::new( move |ch: char, fonts: &[usvg::fontdb::ID], db: &mut Arc| { - if is_emoji_presentation(ch) { - if let Some(id) = select_emoji_font(ch, fonts, db.as_ref(), EMOJI_FONT_FAMILIES) - { - return Some(id); + let mut select = |fonts: &[usvg::fontdb::ID]| { + if is_emoji_presentation(ch) { + if let Some(id) = + select_emoji_font(ch, fonts, db.as_ref(), EMOJI_FONT_FAMILIES) + { + return Some(id); + } } - } - default_fallback_selection(ch, fonts, db) + default_fallback_selection(ch, fonts, db) + }; + let Some(fontdb) = enriched_fontdb.get() else { + return select(fonts); + }; + let face = cached_fallback_face(fontdb, ch, fonts, select)?; + let owned_face = fontdb.lock().owned_face(db, face); + Some(if fonts.contains(&owned_face) { + face + } else { + owned_face + }) }, ); let options = usvg::Options { @@ -191,6 +226,29 @@ impl SvgRenderer { usvg::Tree::from_data(bytes, &self.usvg_options).map(ParsedSvg) } + /// Returns the advance of `text` drawn by this renderer as a single line of SVG ``. + pub fn measure_text_width( + &self, + text: &str, + font: &SvgTextFont<'_>, + ) -> Result { + let mut svg = String::from( + r#""#)); + push_xml_escaped(&mut svg, text); + svg.push_str(""); + + let tree = usvg::Tree::from_str(&svg, &self.usvg_options)?; + Ok(underline_width(tree.root())) + } + /// Rasterizes a previously parsed SVG into an image buffer. pub fn render_parsed( &self, @@ -306,6 +364,139 @@ fn rasterize_tree(tree: &usvg::Tree, size: SvgSize) -> Result, + owned_faces: HashMap, + remaining_owned_bytes: u64, + fallback_faces: HashMap<(usvg::fontdb::ID, char), Option>, +} + +impl FontDatabase { + fn owned_face( + &mut self, + db: &mut Arc, + id: usvg::fontdb::ID, + ) -> usvg::fontdb::ID { + let Some(usvg::fontdb::Source::File(path)) = db.face(id).map(|face| face.source.clone()) + else { + return id; + }; + if !self.owned_faces.contains_key(&id) { + self.own_font_file(&path); + } + *db = self.database.clone(); + self.owned_faces.get(&id).copied().unwrap_or(id) + } + + fn own_font_file(&mut self, path: &Path) { + let file_faces = self + .database + .faces() + .filter(|face| { + matches!(&face.source, usvg::fontdb::Source::File(face_path) if face_path == path) + }) + .map(|face| (face.id, face.index)) + .collect::>(); + let remaining_owned_bytes = self.remaining_owned_bytes; + let data = std::fs::metadata(path).and_then(|metadata| { + (metadata.len() <= remaining_owned_bytes) + .then(|| std::fs::read(path)) + .transpose() + }); + let owned_ids = match data { + Ok(Some(data)) if data.len() as u64 <= remaining_owned_bytes => { + let size = data.len() as u64; + let owned_ids = Arc::make_mut(&mut self.database) + .load_font_source(usvg::fontdb::Source::Binary(Arc::new(data))); + if !owned_ids.is_empty() { + self.remaining_owned_bytes -= size; + } + owned_ids + } + Ok(_) => Default::default(), + Err(error) => { + log::warn!("Failed to read font {path:?}: {error}"); + Default::default() + } + }; + for (id, index) in file_faces { + let owned_id = owned_ids + .iter() + .copied() + .find(|owned_id| { + self.database + .face(*owned_id) + .is_some_and(|face| face.index == index) + }) + .unwrap_or(id); + self.owned_faces.insert(id, owned_id); + } + } +} + +const MAX_CACHED_FALLBACK_FACES: usize = 16 * 1024; + +fn cached_fallback_face( + fontdb: &Mutex, + ch: char, + fonts: &[usvg::fontdb::ID], + mut select: impl FnMut(&[usvg::fontdb::ID]) -> Option, +) -> Option { + let Some(base) = fonts.first() else { + return select(fonts); + }; + let key = (*base, ch); + let cached_face = fontdb.lock().fallback_faces.get(&key).copied(); + let face = match cached_face { + Some(face) => face, + None => { + let face = select(&fonts[..1]); + let fallback_faces = &mut fontdb.lock().fallback_faces; + if fallback_faces.len() < MAX_CACHED_FALLBACK_FACES { + fallback_faces.insert(key, face); + } + face + } + }; + match face { + Some(face) if fonts.contains(&face) => select(fonts), + face => face, + } +} + +fn underline_width(group: &usvg::Group) -> f32 { + group.children().iter().fold(0., |width, node| { + width + + match node { + usvg::Node::Text(text) => text + .layouted() + .iter() + .filter_map(|span| span.underline.as_ref()) + .fold(0., |width, underline| { + width + underline.data().bounds().width() + }), + usvg::Node::Group(group) => underline_width(group), + usvg::Node::Path(_) | usvg::Node::Image(_) => 0., + } + }) +} + +fn push_xml_escaped(xml: &mut String, text: &str) { + for character in text.chars() { + match character { + '&' => xml.push_str("&"), + '<' => xml.push_str("<"), + '>' => xml.push_str(">"), + '"' => xml.push_str("""), + '\t' | '\n' | '\r' => xml.push(character), + '\u{0}'..='\u{1f}' | '\u{fffe}' | '\u{ffff}' => {} + _ => xml.push(character), + } + } +} + fn load_bundled_fonts(asset_source: &dyn AssetSource, db: &mut usvg::fontdb::Database) { let font_paths = [ "fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf", @@ -356,6 +547,7 @@ fn fix_generic_font_families(db: &mut usvg::fontdb::Database) { #[cfg(test)] mod tests { use super::*; + use std::{borrow::Cow, cell::Cell}; use usvg::fontdb::{Database, Family, Query}; const IBM_PLEX_REGULAR: &[u8] = @@ -390,6 +582,103 @@ mod tests { Ok(()) } + #[test] + fn measured_text_width_matches_rasterized_advance() -> Result<()> { + let renderer = SvgRenderer::new(Arc::new(BundledFonts)); + let font = SvgTextFont { + family: "IBM Plex Sans", + size: 40., + weight: "normal", + style: "normal", + }; + let frame_width = rasterized_text_width(&renderer, "MM")?; + assert!(frame_width > 0.); + + for text in ["MMMM", " ", " ", "\u{a0}", "\u{200b}", "M\u{200b}"] { + let measured = renderer.measure_text_width(text, &font)?; + let rasterized = rasterized_text_width(&renderer, &format!("M{text}M"))? - frame_width; + assert!( + (measured - rasterized).abs() <= 1., + "{text:?} measured {measured}px, rasterized {rasterized}px" + ); + } + assert_eq!( + renderer.measure_text_width("M\u{200b}", &font)?, + renderer.measure_text_width("M", &font)? + ); + assert!(renderer.measure_text_width("<&\"\u{1}>", &font)? > 0.); + Ok(()) + } + + #[test] + fn owns_font_bytes_within_budget() -> Result<()> { + let font_path = |name| { + std::env::temp_dir().join(format!( + "gpui-svg-renderer-{}-{name}.ttf", + std::process::id() + )) + }; + let (plex_path, lilex_path) = (font_path("plex"), font_path("lilex")); + std::fs::write(&plex_path, IBM_PLEX_REGULAR)?; + std::fs::write(&lilex_path, LILEX_REGULAR)?; + let mut database = Database::new(); + database.load_font_file(&plex_path)?; + database.load_font_file(&lilex_path)?; + let mut fonts = FontDatabase { + database: Arc::new(database), + owned_faces: HashMap::default(), + remaining_owned_bytes: IBM_PLEX_REGULAR.len() as u64, + fallback_faces: HashMap::default(), + }; + let mut db = fonts.database.clone(); + let face_ids = db.faces().map(|face| face.id).collect::>(); + let (plex_id, lilex_id) = (face_ids[0], face_ids[1]); + + let owned_plex_id = fonts.owned_face(&mut db, plex_id); + let owned_lilex_id = fonts.owned_face(&mut db, lilex_id); + std::fs::write(&plex_path, b"changed")?; + let data_len = |id| db.with_face_data(id, |data, _| data.len()); + let data_lens = (data_len(plex_id), data_len(owned_plex_id)); + std::fs::remove_file(&plex_path)?; + std::fs::remove_file(&lilex_path)?; + + assert_eq!(data_lens, (Some(7), Some(IBM_PLEX_REGULAR.len()))); + assert_eq!(owned_lilex_id, lilex_id); + assert_eq!(fonts.remaining_owned_bytes, 0); + assert_eq!(fonts.owned_face(&mut db, plex_id), owned_plex_id); + Ok(()) + } + + #[test] + fn fallback_faces_are_remembered_until_excluded() { + let database = db_with_bundled_fonts(); + let face_ids = database.faces().map(|face| face.id).collect::>(); + let (base, fallback) = (face_ids[0], face_ids[1]); + let fontdb = Mutex::new(FontDatabase { + database: Arc::new(database), + owned_faces: HashMap::default(), + remaining_owned_bytes: 0, + fallback_faces: HashMap::default(), + }); + let selections = Cell::new(0); + let fallback_face = |ch, fonts: &[usvg::fontdb::ID]| { + cached_fallback_face(&fontdb, ch, fonts, |excluded| { + selections.set(selections.get() + 1); + (!excluded.contains(&fallback)).then_some(fallback) + }) + }; + + assert_eq!(fallback_face('x', &[base]), Some(fallback)); + assert_eq!(fallback_face('x', &[base]), Some(fallback)); + assert_eq!(selections.get(), 1); + assert_eq!(fallback_face('x', &[base, fallback]), None); + assert_eq!(selections.get(), 2); + assert_eq!(fallback_face('y', &[base, fallback]), None); + assert_eq!(selections.get(), 4); + assert_eq!(fallback_face('y', &[base]), Some(fallback)); + assert_eq!(selections.get(), 4); + } + fn db_with_bundled_fonts() -> Database { let mut db = Database::new(); db.load_font_data(IBM_PLEX_REGULAR.to_vec()); @@ -522,4 +811,44 @@ mod tests { face.families ); } + + struct BundledFonts; + + impl AssetSource for BundledFonts { + fn load(&self, path: &str) -> Result>> { + Ok(match path { + "fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf" => { + Some(Cow::Borrowed(IBM_PLEX_REGULAR)) + } + "fonts/lilex/Lilex-Regular.ttf" => Some(Cow::Borrowed(LILEX_REGULAR)), + _ => None, + }) + } + + fn list(&self, _path: &str) -> Result> { + Ok(Vec::new()) + } + } + + fn rasterized_text_width(renderer: &SvgRenderer, text: &str) -> Result { + let svg = format!( + r#"{text}"# + ); + let pixmap = renderer.render_pixmap(svg.as_bytes(), SvgSize::ScaleFactor(1.))?; + let width = pixmap.width() as usize; + let inked_columns = (0..width) + .filter(|column| { + pixmap + .pixels() + .iter() + .skip(*column) + .step_by(width) + .any(|pixel| pixel.alpha() > 0) + }) + .collect::>(); + Ok(match (inked_columns.first(), inked_columns.last()) { + (Some(first), Some(last)) => (last - first + 1) as f32, + _ => 0., + }) + } } diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs index 7505acec..9432b5db 100644 --- a/crates/gpui/src/window.rs +++ b/crates/gpui/src/window.rs @@ -19,12 +19,12 @@ use crate::{ Point, PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow, SharedString, Size, - StrikethroughStyle, Style, SubpixelSprite, Subscription, SystemWindowTab, - SystemWindowTabController, TabStopMap, Task, TextInputConfiguration, TextInputStateChange, - TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState, TransformationMatrix, - Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance, WindowBounds, - WindowControls, WindowDecorations, WindowInsets, WindowOptions, WindowParams, WindowTextSystem, - WindowVisibility, point, prelude::*, px, rems, size, transparent_black, + SpriteAnimation, SpriteAnimationId, StrikethroughStyle, Style, SubpixelSprite, Subscription, + SystemWindowTab, SystemWindowTabController, TabStopMap, Task, TextInputConfiguration, + TextInputStateChange, TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState, + TransformationMatrix, Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance, + WindowBounds, WindowControls, WindowDecorations, WindowInsets, WindowOptions, WindowParams, + WindowTextSystem, WindowVisibility, point, prelude::*, px, rems, size, transparent_black, }; use crate::gestures::{GestureTuning, RecognizedTouchGesture, TouchGestureRecognizer}; @@ -1287,6 +1287,9 @@ pub struct Window { SingleSubscriberSet bool>>, hovered: Rc>, pub(crate) needs_present: Rc>, + /// The rendered scene's [`Scene::animation_frame_interval`]. While it is + /// `Some`, the scene must keep being presented even when nothing is redrawn. + scene_animation_interval: Rc>>, /// Tracks recent input event timestamps to determine if input is arriving at a high rate. /// Used to selectively enable VRR optimization only when input rate exceeds 60fps. pub(crate) input_rate_tracker: Rc>, @@ -1736,6 +1739,7 @@ impl Window { profiler::journal::record_window_visibility(handle.window_id(), visibility); let hovered = Rc::new(Cell::new(platform_window.is_hovered())); let needs_present = Rc::new(Cell::new(false)); + let scene_animation_interval = Rc::new(Cell::new(None::)); let next_frame_callbacks: Rc>> = Default::default(); let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default())); @@ -1901,6 +1905,7 @@ impl Window { let invalidator = invalidator.clone(); let active = active.clone(); let needs_present = needs_present.clone(); + let scene_animation_interval = scene_animation_interval.clone(); let next_frame_callbacks = next_frame_callbacks.clone(); let input_rate_tracker = input_rate_tracker.clone(); let mut deferred_force_render = false; @@ -1960,12 +1965,14 @@ impl Window { // underclocking, but subject to the same power limits as redraws. let high_rate_input = input_rate_tracker.borrow_mut().is_high_rate(); let has_next_frame_callbacks = !next_frame_callbacks.borrow().is_empty(); - let has_frame_demand = invalidator.is_dirty() + let has_demand_besides_animation = invalidator.is_dirty() || force_render || has_next_frame_callbacks || request_frame_options.require_presentation || needs_present.get() || high_rate_input; + let has_frame_demand = + has_demand_besides_animation || scene_animation_interval.get().is_some(); let should_throttle = !request_frame_options.require_presentation; let inactive_without_high_rate_input = @@ -1981,6 +1988,10 @@ impl Window { thermal_state, power_mode, ); + let animation_frame_interval = scene_animation_interval + .get() + .filter(|interval| !has_demand_besides_animation && !interval.is_zero()); + let min_frame_interval = min_frame_interval.max(animation_frame_interval); let now = Instant::now(); // Idle display-link ticks must neither consume a frame slot nor @@ -2007,7 +2018,11 @@ impl Window { profiler::journal::record_frame_skipped( window_id, Instant::now(), - if inactive_without_high_rate_input + if animation_frame_interval.is_some() + && animation_frame_interval == min_frame_interval + { + profiler::journal::FrameSkipReason::AnimationFrameRateLimit + } else if inactive_without_high_rate_input && inactive_frame_interval == min_frame_interval { profiler::journal::FrameSkipReason::InactiveFrameRateLimit @@ -2042,6 +2057,7 @@ impl Window { let should_draw = invalidator.is_dirty() || force_render; let needs_present = request_frame_options.require_presentation || needs_present.get() + || scene_animation_interval.get().is_some() || high_rate_input; if should_draw { measure("frame duration", || { @@ -2057,6 +2073,7 @@ impl Window { window.refresh(); } let arena_clear_needed = window.draw(cx); + window.advance_scene_animations(cx); window.present(); arena_clear_needed.clear(cx); }) @@ -2070,7 +2087,10 @@ impl Window { }) } else if needs_present { handle - .update(&mut cx, |_, window, _| window.present()) + .update(&mut cx, |_, window, cx| { + window.advance_scene_animations(cx); + window.present(); + }) .with_context(|| { format!("presenting frame for window {:?}", handle.window_id()) }) @@ -2081,6 +2101,7 @@ impl Window { .update(&mut cx, |_, window, _| { if window.invalidator.is_dirty() || !window.next_frame_callbacks.borrow().is_empty() + || window.scene_animation_interval.get().is_some() { window.platform_window.schedule_frame(); } @@ -2098,7 +2119,10 @@ impl Window { // after this frame (the window was re-invalidated mid-draw, or // animations scheduled next-frame callbacks), re-arm the frame // source explicitly. - if invalidator.is_dirty() || !next_frame_callbacks.borrow().is_empty() { + if invalidator.is_dirty() + || !next_frame_callbacks.borrow().is_empty() + || scene_animation_interval.get().is_some() + { invalidator.wake_platform(); } #[cfg(feature = "profiler")] @@ -2417,6 +2441,7 @@ impl Window { visibility_observers: SingleSubscriberSet::new(), hovered, needs_present, + scene_animation_interval, input_rate_tracker, #[cfg(feature = "profiler")] window_profiler: profiler::WindowProfiler::new(handle.window_id())?, @@ -3029,6 +3054,11 @@ impl Window { self.on_next_frame(move |_, cx| cx.notify(entity)); } + pub(crate) fn advance_scene_animations(&mut self, cx: &App) { + let elapsed = cx.background_executor().now() - cx.synced_animation_epoch; + self.rendered_frame.scene.advance_animations(elapsed); + } + /// Runs all callbacks scheduled via [`Self::on_next_frame`], returning how many ran. /// /// Tests have no platform frame loop, so this simulates the delivery of the @@ -3841,6 +3871,8 @@ impl Window { let previous_focus_path = self.rendered_frame.focus_path(); let previous_window_active = self.rendered_frame.window_active; mem::swap(&mut self.rendered_frame, &mut self.next_frame); + self.scene_animation_interval + .set(self.rendered_frame.scene.animation_frame_interval()); self.next_frame.clear(); let current_focus_path = self.rendered_frame.focus_path(); let current_window_active = self.rendered_frame.window_active; @@ -4973,42 +5005,45 @@ impl Window { } fn largest_border_interior(quad: &Quad) -> Bounds { - let radii = &quad.corner_radii; - let widths = &quad.border_widths; - let edge_radii = Edges { - top: radii.top_left.max(radii.top_right), - right: radii.top_right.max(radii.bottom_right), - bottom: radii.bottom_left.max(radii.bottom_right), - left: radii.top_left.max(radii.bottom_left), - }; - - let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0)); - let inset_bounds = |top_left_inset, bottom_right_inset| { - Bounds::from_corners( - quad.bounds.origin + top_left_inset + antialias_inset, - quad.bounds.bottom_right() - bottom_right_inset - antialias_inset, + let size = quad.bounds.size; + let diagonal = (size.width.0 * size.width.0 + size.height.0 * size.height.0).sqrt(); + if diagonal == 0. { + return Bounds::default(); + } + // The interior's corners sit on the corner arcs. Taking the angle along + // the arc whose tangent is the quad's aspect ratio stays within 1% of + // the largest interior. + let cos = size.height.0 / diagonal; + let sin = size.width.0 / diagonal; + + // A corner's inner border edge is a quarter ellipse around the + // corner's center, with the border widths taken off its radius. + let corner_inset = |radius: ScaledPixels, width_x: ScaledPixels, width_y: ScaledPixels| { + point( + width_x.max(radius - (radius - width_x) * cos), + width_y.max(radius - (radius - width_y) * sin), ) }; - // Rounded corners need only be excluded on one axis. Either candidate - // is empty of border pixels, so use the larger interior. - let horizontal_band = inset_bounds( - point(widths.left, widths.top.max(edge_radii.top)), - point(widths.right, widths.bottom.max(edge_radii.bottom)), - ); - let vertical_band = inset_bounds( - point(widths.left.max(edge_radii.left), widths.top), - point(widths.right.max(edge_radii.right), widths.bottom), - ); + let radii = &quad.corner_radii; + let widths = &quad.border_widths; + let top_left = corner_inset(radii.top_left, widths.left, widths.top); + let top_right = corner_inset(radii.top_right, widths.right, widths.top); + let bottom_right = corner_inset(radii.bottom_right, widths.right, widths.bottom); + let bottom_left = corner_inset(radii.bottom_left, widths.left, widths.bottom); - let area = |bounds: &Bounds| { - bounds.size.width.0.max(0.) * bounds.size.height.0.max(0.) - }; - if area(&horizontal_band) >= area(&vertical_band) { - horizontal_band - } else { - vertical_band - } + let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0)); + Bounds::from_corners( + quad.bounds.origin + + point(top_left.x.max(bottom_left.x), top_left.y.max(top_right.y)) + + antialias_inset, + quad.bounds.bottom_right() + - point( + top_right.x.max(bottom_right.x), + bottom_left.y.max(bottom_right.y), + ) + - antialias_inset, + ) } /// Paint one or more quads into the scene for the next frame at the current stacking context. @@ -5036,22 +5071,66 @@ impl Window { border_widths: snapped_border_widths, border_style: quad.border_style, }; + self.insert_quad(quad); + } - if !quad.background.is_transparent() { + fn insert_quad(&mut self, quad: Quad) { + let has_background = !quad.background.is_transparent(); + let has_border = + quad.border_widths != Edges::default() && !quad.border_color.is_transparent(); + if !has_background && !has_border { + return; + } + + let is_rectangle = + quad.border_widths == Edges::default() && quad.corner_radii == Corners::default(); + if has_background && is_rectangle { self.next_frame.scene.insert_primitive(quad); return; } - // Splitting a border-only quad around its empty interior avoids shading - // every transparent pixel inside large outlines. + let plain_border = quad.corner_radii == Corners::default() + && quad.border_style == BorderStyle::Solid + && (!has_background || quad.border_color.is_opaque()); + + // Splitting off the interior leaves only the strips around it for the + // border and corner shading. let outer_bounds = quad.bounds; - let inner_bounds = Self::largest_border_interior(&quad); + let inner_bounds = if plain_border { + quad.bounds.extend(quad.border_widths.map(|width| -*width)) + } else { + Self::largest_border_interior(&quad) + }; + + // A plain border's strips can be plain rectangles of the border color. + // Otherwise, each strip is the whole quad masked to the strip, so the + // border, corners and gradients are still shaded relative to the full quad. + let strip_quad = if plain_border { + Quad { + background: quad.border_color.into(), + border_widths: Edges::default(), + ..quad + } + } else { + quad + }; if inner_bounds.is_empty() { - self.next_frame.scene.insert_primitive(quad); + self.next_frame.scene.insert_primitive(strip_quad); return; } + if has_background { + self.next_frame.scene.insert_primitive(Quad { + content_mask: ContentMask { + bounds: quad.content_mask.bounds.intersect(&inner_bounds), + }, + border_widths: Edges::default(), + corner_radii: Corners::default(), + ..quad + }); + } + let strips = [ // Top Bounds::from_corners( @@ -5076,15 +5155,12 @@ impl Window { ]; for strip in strips { - let content_mask_bounds = quad.content_mask.bounds.intersect(&strip); - if !content_mask_bounds.is_empty() { - self.next_frame.scene.insert_primitive(Quad { - content_mask: ContentMask { - bounds: content_mask_bounds, - }, - ..quad - }); - } + self.next_frame.scene.insert_primitive(Quad { + content_mask: ContentMask { + bounds: quad.content_mask.bounds.intersect(&strip), + }, + ..strip_quad + }); } } @@ -5224,7 +5300,7 @@ impl Window { } else { self.next_frame.scene.insert_primitive(MonochromeSprite { order: 0, - pad: 0, + animation: SpriteAnimationId::NONE, bounds, content_mask, color: color.opacity(element_opacity), @@ -5330,6 +5406,21 @@ impl Window { transformation: TransformationMatrix, color: Hsla, cx: &App, + ) -> Result<()> { + self.paint_animated_svg(bounds, path, data, transformation, None, color, cx) + } + + /// Like [`Self::paint_svg`], with an `animation` the window applies before every + /// present, so the view isn't re-rendered to advance it. + pub(crate) fn paint_animated_svg( + &mut self, + bounds: Bounds, + path: SharedString, + data: Option<&[u8]>, + transformation: TransformationMatrix, + animation: Option, + color: Hsla, + cx: &App, ) -> Result<()> { self.invalidator.debug_assert_paint(); @@ -5371,15 +5462,22 @@ impl Window { .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0))) .map_size(|size| size.ceil()); - self.next_frame.scene.insert_primitive(MonochromeSprite { + let sprite = MonochromeSprite { order: 0, - pad: 0, + animation: SpriteAnimationId::NONE, bounds: final_bounds, content_mask, color: color.opacity(element_opacity), tile, transformation, - }); + }; + match animation { + Some(animation) => self + .next_frame + .scene + .insert_animated_sprite(sprite, animation), + None => self.next_frame.scene.insert_primitive(sprite), + } Ok(()) } @@ -5521,7 +5619,7 @@ impl Window { frame_index, }; - self.sprite_atlas.remove(¶ms.clone().into()); + self.sprite_atlas.remove(¶ms.into()); } Ok(()) diff --git a/crates/gpui_apple/Cargo.toml b/crates/gpui_apple/Cargo.toml index 488d1dca..2503ed08 100644 --- a/crates/gpui_apple/Cargo.toml +++ b/crates/gpui_apple/Cargo.toml @@ -56,6 +56,7 @@ objc2-metal = { version = "0.3.2", default-features = false, features = [ "MTLCommandBuffer", "MTLCommandEncoder", "MTLCommandQueue", + "MTLDepthStencil", "MTLDevice", "MTLDrawable", "MTLLibrary", diff --git a/crates/gpui_apple/src/metal_renderer.rs b/crates/gpui_apple/src/metal_renderer.rs index 732fa31d..86eff3d4 100644 --- a/crates/gpui_apple/src/metal_renderer.rs +++ b/crates/gpui_apple/src/metal_renderer.rs @@ -3,7 +3,7 @@ use anyhow::{Context as _, Result}; use block2::RcBlock; use gpui::{ AtlasTextureId, Bounds, ContentMask, DevicePixels, PaintSurface, PaintedPath, PrimitiveBatch, - ScaledPixels, Scene, Size, size, + ScaledPixels, Scene, Size, quad_depth, quad_depth_scale, size, }; #[cfg(any(test, feature = "bench-support", feature = "test-support"))] use image::RgbaImage; @@ -20,16 +20,15 @@ use objc2_foundation::{NSRange, NSString}; use objc2_metal::MTLCopyAllDevices; use objc2_metal::{ MTLBlendFactor, MTLBlendOperation, MTLBuffer, MTLClearColor, MTLCommandBuffer, - MTLCommandEncoder, MTLCommandQueue, MTLCreateSystemDefaultDevice, MTLDevice, MTLDrawable, - MTLGPUFamily, MTLLibrary, MTLLoadAction, MTLPixelFormat, MTLPrimitiveType, - MTLRenderCommandEncoder, MTLRenderPassDescriptor, MTLRenderPipelineDescriptor, - MTLRenderPipelineState, MTLResourceOptions, MTLStoreAction, MTLTexture, MTLViewport, + MTLCommandEncoder, MTLCommandQueue, MTLCompareFunction, MTLCreateSystemDefaultDevice, + MTLDepthStencilDescriptor, MTLDepthStencilState, MTLDevice, MTLDrawable, MTLGPUFamily, + MTLLibrary, MTLLoadAction, MTLPixelFormat, MTLPrimitiveType, MTLRenderCommandEncoder, + MTLRenderPassDescriptor, MTLRenderPipelineDescriptor, MTLRenderPipelineState, + MTLResourceOptions, MTLStorageMode, MTLStoreAction, MTLTexture, MTLTextureDescriptor, + MTLTextureUsage, MTLViewport, }; #[cfg(any(test, feature = "bench-support", feature = "test-support"))] -use objc2_metal::{ - MTLBlitCommandEncoder, MTLOrigin, MTLRegion, MTLSize, MTLStorageMode, MTLTextureDescriptor, - MTLTextureUsage, -}; +use objc2_metal::{MTLBlitCommandEncoder, MTLOrigin, MTLRegion, MTLSize}; use objc2_quartz_core::{CAMetalDrawable, CAMetalLayer}; use parking_lot::Mutex; @@ -124,7 +123,6 @@ enum DisplayLinkMode { pub struct MetalRenderer { device: Retained>, layer: Option>, - #[cfg(any(test, feature = "bench-support", feature = "test-support"))] is_apple_gpu: bool, is_unified_memory: bool, presents_with_transaction: bool, @@ -135,10 +133,14 @@ pub struct MetalRenderer { path_tiles_pipeline_state: Retained>, shadows_pipeline_state: Retained>, quads_pipeline_state: Retained>, + opaque_quads_pipeline_state: Retained>, underlines_pipeline_state: Retained>, monochrome_sprites_pipeline_state: Retained>, polychrome_sprites_pipeline_state: Retained>, surfaces_pipeline_state: Retained>, + depth_write_state: Retained>, + depth_test_state: Retained>, + depth_texture: Option>>, instance_buffer_pool: Arc>, sprite_atlas: Arc, core_video_texture_cache: CFRetained, @@ -287,6 +289,7 @@ impl MetalRenderer { "path_tile_vertex", "path_tile_fragment", MTLPixelFormat::BGRA8Unorm, + true, )?; let shadows_pipeline_state = build_pipeline_state( &device, @@ -295,6 +298,7 @@ impl MetalRenderer { "shadow_vertex", "shadow_fragment", MTLPixelFormat::BGRA8Unorm, + true, )?; let quads_pipeline_state = build_pipeline_state( &device, @@ -303,6 +307,16 @@ impl MetalRenderer { "quad_vertex", "quad_fragment", MTLPixelFormat::BGRA8Unorm, + true, + )?; + let opaque_quads_pipeline_state = build_pipeline_state( + &device, + &library, + "opaque_quads", + "opaque_quad_vertex", + "opaque_quad_fragment", + MTLPixelFormat::BGRA8Unorm, + false, )?; let underlines_pipeline_state = build_pipeline_state( &device, @@ -311,6 +325,7 @@ impl MetalRenderer { "underline_vertex", "underline_fragment", MTLPixelFormat::BGRA8Unorm, + true, )?; let monochrome_sprites_pipeline_state = build_pipeline_state( &device, @@ -319,6 +334,7 @@ impl MetalRenderer { "monochrome_sprite_vertex", "monochrome_sprite_fragment", MTLPixelFormat::BGRA8Unorm, + true, )?; let polychrome_sprites_pipeline_state = build_pipeline_state( &device, @@ -327,6 +343,7 @@ impl MetalRenderer { "polychrome_sprite_vertex", "polychrome_sprite_fragment", MTLPixelFormat::BGRA8Unorm, + true, )?; let surfaces_pipeline_state = build_pipeline_state( &device, @@ -335,8 +352,12 @@ impl MetalRenderer { "surface_vertex", "surface_fragment", MTLPixelFormat::BGRA8Unorm, + true, )?; + let depth_write_state = build_depth_stencil_state(&device, true)?; + let depth_test_state = build_depth_stencil_state(&device, false)?; + let command_queue = device.newCommandQueue().context("creating command queue")?; let supports_shared_storage = cfg!(target_os = "ios") || is_apple_gpu; #[expect( @@ -362,7 +383,6 @@ impl MetalRenderer { layer, presents_with_transaction: false, display_link_mode: DisplayLinkMode::Detached, - #[cfg(any(test, feature = "bench-support", feature = "test-support"))] is_apple_gpu, is_unified_memory, opaque, @@ -370,10 +390,14 @@ impl MetalRenderer { path_tiles_pipeline_state, shadows_pipeline_state, quads_pipeline_state, + opaque_quads_pipeline_state, underlines_pipeline_state, monochrome_sprites_pipeline_state, polychrome_sprites_pipeline_state, surfaces_pipeline_state, + depth_write_state, + depth_test_state, + depth_texture: None, instance_buffer_pool, sprite_atlas, core_video_texture_cache, @@ -723,10 +747,12 @@ impl MetalRenderer { .commandBuffer() .context("creating command buffer")?; let alpha = if self.opaque { 1. } else { 0. }; + let depth_texture = self.depth_texture_matching(texture)?; let command_encoder = new_command_encoder_for_texture( &command_buffer, texture, + &depth_texture, viewport_size, MTLClearColor { red: 0., @@ -735,23 +761,51 @@ impl MetalRenderer { alpha, }, )?; - // SAFETY: Metal copies the viewport bytes, which match every vertex - // shader's `GlobalInputIndex_ViewportSize` argument. + let depth_scale = quad_depth_scale(scene.quads.len()); + // SAFETY: Metal copies both values, which match every vertex shader's + // `GlobalInputIndex_ViewportSize` and `GlobalInputIndex_DepthScale` arguments. unsafe { command_encoder.setVertexBytes_length_atIndex( ptr::NonNull::from(&viewport_size).cast(), mem::size_of_val(&viewport_size), GlobalInputIndex::ViewportSize as usize, ); + command_encoder.setVertexBytes_length_atIndex( + ptr::NonNull::from(&depth_scale).cast(), + mem::size_of_val(&depth_scale), + GlobalInputIndex::DepthScale as usize, + ); } + self.draw_opaque_quads(scene.quads.len(), instance_bindings, &command_encoder); + command_encoder.setDepthStencilState(Some(&self.depth_test_state)); + + let mut quad_cursor: u32 = 0; let mut path_tile_cursor = 0; for batch in scene.batches() { + // 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 matches!(&batch, PrimitiveBatch::Quads(_)) { + (0.0, 1.0) + } else { + let depth = quad_depth(quad_cursor, depth_scale) as f64; + (depth, depth) + }; + command_encoder.setViewport(MTLViewport { + originX: 0.0, + originY: 0.0, + width: i32::from(viewport_size.width) as f64, + height: i32::from(viewport_size.height) as f64, + znear, + zfar, + }); + match batch { PrimitiveBatch::Shadows(range) => { self.draw_shadows(range, instance_bindings, &command_encoder) } PrimitiveBatch::Quads(range) => { + quad_cursor += range.len() as u32; self.draw_quads(range, instance_bindings, &command_encoder) } PrimitiveBatch::Paths(range) => { @@ -804,6 +858,75 @@ impl MetalRenderer { Ok(command_buffer) } + fn depth_texture_matching( + &mut self, + target: &ProtocolObject, + ) -> Result>> { + if let Some(depth_texture) = &self.depth_texture + && depth_texture.width() == target.width() + && depth_texture.height() == target.height() + { + return Ok(depth_texture.clone()); + } + let descriptor = MTLTextureDescriptor::new(); + // SAFETY: The size is the size of an existing render target, which the device supports. + unsafe { + descriptor.setWidth(target.width()); + descriptor.setHeight(target.height()); + } + descriptor.setPixelFormat(MTLPixelFormat::Depth32Float); + descriptor.setUsage(MTLTextureUsage::RenderTarget); + // The depth buffer never leaves its render pass, so Apple GPUs can keep + // it in tile memory without allocating any backing store. + descriptor.setStorageMode(if self.is_apple_gpu { + MTLStorageMode::Memoryless + } else { + MTLStorageMode::Private + }); + let depth_texture = self + .device + .newTextureWithDescriptor(&descriptor) + .context("allocating depth texture")?; + self.depth_texture = Some(depth_texture.clone()); + Ok(depth_texture) + } + + fn draw_opaque_quads( + &self, + quad_count: usize, + instance_bindings: &InstanceBindings, + command_encoder: &ProtocolObject, + ) { + if quad_count == 0 { + return; + } + let quad_count_value = quad_count as u32; + + command_encoder.setRenderPipelineState(&self.opaque_quads_pipeline_state); + command_encoder.setDepthStencilState(Some(&self.depth_write_state)); + // SAFETY: The scene's quads and the copied count match the shader layouts and slots. + // Metal retains the buffer, and writer.finish publishes its writes. + unsafe { + command_encoder.setVertexBuffer_offset_atIndex( + Some(&instance_bindings.quads.buffer), + instance_bindings.quads.offset, + QuadInputIndex::Quads as usize, + ); + command_encoder.setVertexBytes_length_atIndex( + ptr::NonNull::from(&quad_count_value).cast(), + mem::size_of_val(&quad_count_value), + QuadInputIndex::QuadCount as usize, + ); + command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( + MTLPrimitiveType::TriangleStrip, + 0, + 4, + quad_count, + 0, + ); + } + } + fn draw_path_tiles( &self, tiles: Range, @@ -1164,6 +1287,7 @@ impl MetalRenderer { fn new_command_encoder_for_texture( command_buffer: &ProtocolObject, texture: &ProtocolObject, + depth_texture: &ProtocolObject, viewport_size: Size, clear_color: MTLClearColor, ) -> Result>> { @@ -1179,6 +1303,13 @@ fn new_command_encoder_for_texture( color_attachment.setLoadAction(MTLLoadAction::Clear); color_attachment.setClearColor(clear_color); + let depth_attachment = render_pass_descriptor.depthAttachment(); + depth_attachment.setTexture(Some(depth_texture)); + depth_attachment.setLoadAction(MTLLoadAction::Clear); + depth_attachment.setClearDepth(0.0); + // The depth buffer is only needed within this pass. + depth_attachment.setStoreAction(MTLStoreAction::DontCare); + let command_encoder = command_buffer .renderCommandEncoderWithDescriptor(&render_pass_descriptor) .context("creating render command encoder")?; @@ -1232,6 +1363,7 @@ fn build_pipeline_state( vertex_fn_name: &str, fragment_fn_name: &str, pixel_format: MTLPixelFormat, + blending: bool, ) -> Result>> { let vertex_fn = library .newFunctionWithName(&NSString::from_str(vertex_fn_name)) @@ -1247,19 +1379,32 @@ fn build_pipeline_state( // SAFETY: Index zero is within the pipeline's color attachment array. let color_attachment = unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) }; color_attachment.setPixelFormat(pixel_format); - color_attachment.setBlendingEnabled(true); + color_attachment.setBlendingEnabled(blending); color_attachment.setRgbBlendOperation(MTLBlendOperation::Add); color_attachment.setAlphaBlendOperation(MTLBlendOperation::Add); color_attachment.setSourceRGBBlendFactor(MTLBlendFactor::SourceAlpha); color_attachment.setSourceAlphaBlendFactor(MTLBlendFactor::One); color_attachment.setDestinationRGBBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); color_attachment.setDestinationAlphaBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); + descriptor.setDepthAttachmentPixelFormat(MTLPixelFormat::Depth32Float); device .newRenderPipelineStateWithDescriptor_error(&descriptor) .with_context(|| format!("creating {label} render pipeline")) } +fn build_depth_stencil_state( + device: &ProtocolObject, + write_depth: bool, +) -> Result>> { + let descriptor = MTLDepthStencilDescriptor::new(); + descriptor.setDepthCompareFunction(MTLCompareFunction::Greater); + descriptor.setDepthWriteEnabled(write_depth); + device + .newDepthStencilStateWithDescriptor(&descriptor) + .context("creating depth stencil state") +} + #[derive(Clone)] struct InstanceBinding { buffer: Retained>, @@ -1443,43 +1588,45 @@ impl InstanceBufferWriter { #[repr(C)] enum GlobalInputIndex { ViewportSize = 0, + DepthScale = 1, } #[repr(C)] enum ShadowInputIndex { - Shadows = 1, + Shadows = 2, } #[repr(C)] enum QuadInputIndex { - Quads = 1, + Quads = 2, + QuadCount = 3, } #[repr(C)] enum UnderlineInputIndex { - Underlines = 1, + Underlines = 2, } #[repr(C)] enum SpriteInputIndex { - Sprites = 1, - AtlasTextureSize = 2, - AtlasTexture = 3, + Sprites = 2, + AtlasTextureSize = 3, + AtlasTexture = 4, } #[repr(C)] enum SurfaceInputIndex { - Surfaces = 1, - TextureSize = 2, - YTexture = 3, - CbCrTexture = 4, + Surfaces = 2, + TextureSize = 3, + YTexture = 4, + CbCrTexture = 5, } #[repr(C)] enum PathTileInputIndex { - Tiles = 1, - Curves = 2, - Paints = 3, + Tiles = 2, + Curves = 3, + Paints = 4, } #[derive(Clone, Debug, Eq, PartialEq)] diff --git a/crates/gpui_apple/src/shaders.metal b/crates/gpui_apple/src/shaders.metal index 38a49bc8..680842f8 100644 --- a/crates/gpui_apple/src/shaders.metal +++ b/crates/gpui_apple/src/shaders.metal @@ -39,10 +39,6 @@ float pick_corner_radius(float2 center_to_point, Corners_ScaledPixels corner_rad float quad_sdf(float2 point, Bounds_ScaledPixels bounds, Corners_ScaledPixels corner_radii); float quad_sdf_impl(float2 center_to_point, float corner_radius); -float gaussian(float x, float sigma); -float2 erf(float2 x); -float blur_along_x(float x, float y, float sigma, float corner, - float2 half_size); float4 over(float4 below, float4 above); float radians(float degrees); @@ -67,17 +63,38 @@ struct QuadFragmentInput { PreparedBackground background; }; +constant float4 CULLED_POSITION = float4(0., 0., 0., 1.); + +float quad_depth(uint quad_id, float depth_scale) { + return saturate(float(quad_id + 1u) * depth_scale); +} + +// Opaque rectangles are drawn by the opaque pass instead of the quad pass. +bool is_opaque_rectangle(Quad quad) { + return quad.background.tag == 0u && quad.background.solid.a >= 1.0 && + !has_rounded_corners(quad.corner_radii) && + !has_border(quad.border_widths); +} + vertex QuadFragmentInput quad_vertex( uint vertex_id [[vertex_id]], uint quad_id [[instance_id]], constant Quad *quads [[buffer(QuadInputIndex_Quads)]], constant Size_DevicePixels *viewport_size - [[buffer(GlobalInputIndex_ViewportSize)]]) { - float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); + [[buffer(GlobalInputIndex_ViewportSize)]], + constant float *depth_scale [[buffer(GlobalInputIndex_DepthScale)]]) { Quad quad = quads[quad_id]; + if (is_opaque_rectangle(quad)) { + QuadFragmentInput culled = {}; + culled.position = CULLED_POSITION; + return culled; + } + + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); ClippedVertex clipped = clip_to_mask(unit_vertex, quad.bounds, quad.content_mask.bounds); float4 device_position = to_device_position_impl(clipped.position, viewport_size); + device_position.z = quad_depth(quad_id, *depth_scale); float4 border_color = hsla_to_rgba(quad.border_color); bool simple = !is_shaped(quad) && quad.background.tag == 0u; PreparedBackground background = prepare_background(quad.background); @@ -369,11 +386,8 @@ fragment float4 quad_fragment(QuadFragmentInput input [[stage_in]], } } - // Blend the border on top of the background and then linearly interpolate - // between the two as we slide inside the background. - float4 blended_border = over(background, border_color); - color = mix(background, blended_border, - saturate(antialias_threshold - inner_sdf)); + border_color.a *= saturate(antialias_threshold - inner_sdf); + color = over(background, border_color); } return color * float4(1.0, 1.0, 1.0, saturate(antialias_threshold - outer_sdf)); @@ -429,12 +443,114 @@ float quarter_ellipse_sdf(float2 point, float2 radii) { return unit_circle_sdf * (radii.x + radii.y) * -0.5; } +struct OpaqueQuadFragmentInput { + float4 position [[position]]; + float4 color [[flat]]; +}; + +vertex OpaqueQuadFragmentInput opaque_quad_vertex( + uint vertex_id [[vertex_id]], uint instance_id [[instance_id]], + constant Quad *quads [[buffer(QuadInputIndex_Quads)]], + constant uint *quad_count [[buffer(QuadInputIndex_QuadCount)]], + constant Size_DevicePixels *viewport_size + [[buffer(GlobalInputIndex_ViewportSize)]], + constant float *depth_scale [[buffer(GlobalInputIndex_DepthScale)]]) { + uint quad_id = *quad_count - 1u - instance_id; + Quad quad = quads[quad_id]; + if (!is_opaque_rectangle(quad)) { + return OpaqueQuadFragmentInput{CULLED_POSITION, float4(0.)}; + } + + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); + ClippedVertex clipped = + clip_to_mask(unit_vertex, quad.bounds, quad.content_mask.bounds); + float4 device_position = + to_device_position_impl(clipped.position, viewport_size); + device_position.z = quad_depth(quad_id, *depth_scale); + return OpaqueQuadFragmentInput{device_position, + hsla_to_rgba(quad.background.solid)}; +} + +fragment float4 opaque_quad_fragment(OpaqueQuadFragmentInput input + [[stage_in]]) { + return input.color; +} + +struct PreparedBlurredRoundedRect { + float4 shape; + float4 r1; + float4 exponent; + float4 scale; +}; + struct ShadowFragmentInput { float4 position [[position]]; float4 color [[flat]]; uint shadow_id [[flat]]; + float4 blur_shape [[flat]]; + float4 blur_r1 [[flat]]; + float4 blur_exponent [[flat]]; + float4 blur_scale [[flat]]; }; +float erf7(float x) { + x = clamp(x, -10., 10.) * (2. / sqrt(M_PI_F)); + float xx = x * x; + x = x + (0.24295 + (0.03395 + 0.0104 * xx) * xx) * (x * xx); + return x / sqrt(1. + x * x); +} + +// Raph Levien's blurred rounded rectangle approximation, whose blur s is sigma * sqrt(2): +// https://raphlinus.github.io/graphics/2020/04/21/blurred-rounded-rects.html +PreparedBlurredRoundedRect prepare_blurred_rounded_rect(float2 size, Corners_ScaledPixels corner_radii, float sigma) { + float s = max(sigma * sqrt(2.), 1e-6); + float s_inv = 1. / s; + float min_edge = min(size.x, size.y); + float r_max = 0.5 * min_edge; + float4 radii = float4(corner_radii.top_left, corner_radii.top_right, + corner_radii.bottom_right, corner_radii.bottom_left); + float4 r0 = min(sqrt(radii * radii + 1.15 * 1.15 * s * s), r_max); + float4 r1 = min(sqrt(radii * radii + 4. * s * s), r_max); + + float2 half_extent = 0.5 * s_inv * size; + float delta = 1.25 * s * (exp(-half_extent.x * half_extent.x) - exp(-half_extent.y * half_extent.y)); + float2 adjusted_size = float2(size.x + min(delta, 0.), size.y - max(delta, 0.)); + float4 peak = s_inv * 0.5 * (max(adjusted_size.x, adjusted_size.y) - 0.5 * radii); + + PreparedBlurredRoundedRect output; + output.shape = float4(0.5 * adjusted_size, s_inv, min_edge); + output.r1 = r1; + output.exponent = 2. * r1 / r0; + output.scale = 0.5 * float4(erf7(peak.x), erf7(peak.y), erf7(peak.z), erf7(peak.w)); + return output; +} + +float pick_corner(float2 center_to_point, float4 values) { + Corners_ScaledPixels corners = {values.x, values.y, values.z, values.w}; + return pick_corner_radius(center_to_point, corners); +} + +float blurred_rounded_rect(float2 center_to_point, PreparedBlurredRoundedRect prepared) { + float r1 = pick_corner(center_to_point, prepared.r1); + float exponent = pick_corner(center_to_point, prepared.exponent); + float scale = pick_corner(center_to_point, prepared.scale); + float s_inv = prepared.shape.z; + float min_edge = prepared.shape.w; + + float2 p0 = abs(center_to_point) - (prepared.shape.xy - r1); + float2 p1 = max(p0, 0.); + float d_pos; + if (p1.x > 0. && p1.y > 0.) { + d_pos = pow(pow(p1.x, exponent) + pow(p1.y, exponent), 1. / exponent); + } else { + d_pos = p1.x + p1.y; + } + + float d_neg = min(max(p0.x, p0.y), 0.); + float d = d_pos + d_neg - r1; + return scale * (erf7(s_inv * (min_edge + d)) - erf7(s_inv * d)); +} + vertex ShadowFragmentInput shadow_vertex( uint vertex_id [[vertex_id]], uint shadow_id [[instance_id]], constant Shadow *shadows [[buffer(ShadowInputIndex_Shadows)]], @@ -448,11 +564,18 @@ vertex ShadowFragmentInput shadow_vertex( float4 device_position = to_device_position_impl(clipped.position, viewport_size); float4 color = hsla_to_rgba(shadow.color); + PreparedBlurredRoundedRect blur = prepare_blurred_rounded_rect( + float2(shadow.shape_bounds.size.width, shadow.shape_bounds.size.height), + shadow.shape_corner_radii, shadow.blur_radius); return ShadowFragmentInput{ device_position, color, - shadow_id}; + shadow_id, + blur.shape, + blur.r1, + blur.exponent, + blur.scale}; } fragment float4 shadow_fragment(ShadowFragmentInput input [[stage_in]], @@ -460,48 +583,18 @@ fragment float4 shadow_fragment(ShadowFragmentInput input [[stage_in]], [[buffer(ShadowInputIndex_Shadows)]]) { Shadow shadow = shadows[input.shadow_id]; - float2 origin = float2(shadow.shape_bounds.origin.x, shadow.shape_bounds.origin.y); - float2 size = float2(shadow.shape_bounds.size.width, shadow.shape_bounds.size.height); - float2 half_size = size / 2.; - float2 center = origin + half_size; - float2 point = input.position.xy - center; - float corner_radius; - if (point.x < 0.) { - if (point.y < 0.) { - corner_radius = shadow.shape_corner_radii.top_left; - } else { - corner_radius = shadow.shape_corner_radii.bottom_left; - } - } else { - if (point.y < 0.) { - corner_radius = shadow.shape_corner_radii.top_right; - } else { - corner_radius = shadow.shape_corner_radii.bottom_right; - } - } - float alpha; if (shadow.blur_radius == 0.) { float distance = quad_sdf(input.position.xy, shadow.shape_bounds, shadow.shape_corner_radii); alpha = saturate(0.5 - distance); } else { - // The signal is only non-zero in a limited range, so don't waste samples - float low = point.y - half_size.y; - float high = point.y + half_size.y; - float start = clamp(-3. * shadow.blur_radius, low, high); - float end = clamp(3. * shadow.blur_radius, low, high); - - // Accumulate samples (we can get away with surprisingly few samples) - float step = (end - start) / 4.; - float y = start + step * 0.5; - alpha = 0.; - for (int i = 0; i < 4; i++) { - alpha += blur_along_x(point.x, point.y - y, shadow.blur_radius, - corner_radius, half_size) * - gaussian(y, shadow.blur_radius) * step; - y += step; - } + float2 origin = float2(shadow.shape_bounds.origin.x, shadow.shape_bounds.origin.y); + float2 size = float2(shadow.shape_bounds.size.width, shadow.shape_bounds.size.height); + float2 center = origin + size / 2.; + PreparedBlurredRoundedRect blur = {input.blur_shape, input.blur_r1, + input.blur_exponent, input.blur_scale}; + alpha = blurred_rounded_rect(input.position.xy - center, blur); } if (shadow.inset != 0u) { @@ -1070,30 +1163,6 @@ float quad_sdf_impl(float2 corner_center_to_point, float corner_radius) { } } -// A standard gaussian function, used for weighting samples -float gaussian(float x, float sigma) { - return exp(-(x * x) / (2. * sigma * sigma)) / (sqrt(2. * M_PI_F) * sigma); -} - -// This approximates the error function, needed for the gaussian integral -float2 erf(float2 x) { - float2 s = sign(x); - float2 a = abs(x); - float2 r1 = 1. + (0.278393 + (0.230389 + (0.000972 + 0.078108 * a) * a) * a) * a; - float2 r2 = r1 * r1; - return s - s / (r2 * r2); -} - -float blur_along_x(float x, float y, float sigma, float corner, - float2 half_size) { - float delta = min(half_size.y - corner - abs(y), 0.); - float curved = - half_size.x - corner + sqrt(max(0., corner * corner - delta * delta)); - float2 integral = - 0.5 + 0.5 * erf((x + float2(-curved, curved)) * (sqrt(0.5) / sigma)); - return integral.y - integral.x; -} - ClippedVertex clip_to_mask(float2 unit_vertex, Bounds_ScaledPixels bounds, Bounds_ScaledPixels mask) { float2 bounds_origin = float2(bounds.origin.x, bounds.origin.y); @@ -1128,12 +1197,10 @@ float4 distance_from_clip_rect_transformed(float2 unit_vertex, Bounds_ScaledPixe } float4 over(float4 below, float4 above) { - float4 result; float alpha = above.a + below.a * (1.0 - above.a); - result.rgb = - (above.rgb * above.a + below.rgb * below.a * (1.0 - above.a)) / alpha; - result.a = alpha; - return result; + float3 premultiplied = + above.rgb * above.a + below.rgb * below.a * (1.0 - above.a); + return float4(premultiplied / (alpha == 0.0 ? 1.0 : alpha), alpha); } PreparedBackground prepare_background(Background background) { diff --git a/crates/gpui_linux/src/linux/platform.rs b/crates/gpui_linux/src/linux/platform.rs index b24300bb..c9bbd2de 100644 --- a/crates/gpui_linux/src/linux/platform.rs +++ b/crates/gpui_linux/src/linux/platform.rs @@ -1005,8 +1005,9 @@ impl Platform for LinuxPlatform { }); } - fn dismiss_system_notification(&self, tag: &str) { + fn dismiss_system_notification(&self, tag: &str) -> Task<()> { self.with_common(|common| common.system_notifications.dismiss(tag)); + Task::ready(()) } fn on_system_notification_response( diff --git a/crates/gpui_linux/src/linux/x11/clipboard.rs b/crates/gpui_linux/src/linux/x11/clipboard.rs index 9835786e..ef6976e8 100644 --- a/crates/gpui_linux/src/linux/x11/clipboard.rs +++ b/crates/gpui_linux/src/linux/x11/clipboard.rs @@ -12,7 +12,7 @@ * The project to which this file belongs is licensed under either of * the Apache 2.0 or the MIT license at the licensee's choice. The terms * and conditions of the chosen license apply to this file. -*/ + */ // More info about using the clipboard on X11: // https://tronche.com/gui/x/icccm/sec-2.html#s-2.6 diff --git a/crates/gpui_macos/src/platform.rs b/crates/gpui_macos/src/platform.rs index d42ac63f..218b296d 100644 --- a/crates/gpui_macos/src/platform.rs +++ b/crates/gpui_macos/src/platform.rs @@ -2,6 +2,7 @@ use crate::{ AppleActivity, AppleDispatcher, BoolExt, MacDisplay, MacKeyboardLayout, MacKeyboardMapper, MacWindow, events::key_to_menu_equivalent, main_thread_marker, ns_string, pasteboard::Pasteboard, renderer, set_active_window_cursor_style, + system_notifications::NotificationCommand, }; use anyhow::{Context as _, anyhow}; use block2::RcBlock; @@ -1128,14 +1129,27 @@ impl Platform for MacPlatform { fn show_system_notification(&self, notification: gpui::SystemNotification) { let mut state = self.0.lock(); - let executor = state.foreground_executor.clone(); - state.system_notifications.show(&executor, notification); + let foreground_executor = state.foreground_executor.clone(); + let background_executor = state.background_executor.clone(); + state + .system_notifications + .send( + &foreground_executor, + &background_executor, + NotificationCommand::Show(notification), + ) + .detach(); } - fn dismiss_system_notification(&self, tag: &str) { + fn dismiss_system_notification(&self, tag: &str) -> Task<()> { let mut state = self.0.lock(); - let executor = state.foreground_executor.clone(); - state.system_notifications.dismiss(&executor, tag); + let foreground_executor = state.foreground_executor.clone(); + let background_executor = state.background_executor.clone(); + state.system_notifications.send( + &foreground_executor, + &background_executor, + NotificationCommand::Dismiss(gpui::SharedString::from(tag.to_owned())), + ) } fn on_system_notification_response( diff --git a/crates/gpui_macos/src/system_notifications.rs b/crates/gpui_macos/src/system_notifications.rs index 4bfd9522..8c1df527 100644 --- a/crates/gpui_macos/src/system_notifications.rs +++ b/crates/gpui_macos/src/system_notifications.rs @@ -4,19 +4,24 @@ //! so nothing can trigger the authorization prompt or the framework's //! not-in-a-bundle abort) until the application posts a notification or //! registers a response callback. +//! +//! Notification-center calls can synchronously wait for the macOS service. +//! A single worker owns the center so those waits never block the UI, while +//! preserving the order of posting and dismissing notifications. -use std::cell::{Cell, RefCell}; +use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; +use std::sync::mpsc::{Sender, channel}; use block2::RcBlock; use futures::StreamExt as _; -use futures::channel::mpsc; +use futures::channel::{mpsc, oneshot}; use gpui::{ - ForegroundExecutor, SharedString, SystemNotification, SystemNotificationAction, - SystemNotificationResponse, Task, + BackgroundExecutor, ForegroundExecutor, SharedString, SystemNotification, + SystemNotificationAction, SystemNotificationResponse, Task, }; -use objc2::rc::Retained; +use objc2::rc::{Retained, autoreleasepool}; use objc2::runtime::{Bool, ProtocolObject}; use objc2::{AnyThread, DefinedClass, define_class, msg_send}; use objc2_foundation::{NSArray, NSBundle, NSError, NSObject, NSObjectProtocol, NSSet, NSString}; @@ -30,10 +35,19 @@ use objc2_user_notifications::{ type ResponseCallback = Rc>>>; +#[cfg_attr(test, derive(Debug, PartialEq, Eq))] +pub(crate) enum NotificationCommand { + Show(SystemNotification), + Dismiss(SharedString), +} + pub(crate) struct SystemNotificationState { initialized: bool, - center: Option, + commands: Option)>>, callback: ResponseCallback, + /// The center's `delegate` property is weak; keeping the delegate retained + /// here keeps response handling alive for the app's lifetime. + _delegate: Option>, _response_task: Option>, } @@ -41,24 +55,35 @@ impl SystemNotificationState { pub(crate) fn new() -> Self { Self { initialized: false, - center: None, + commands: None, callback: Rc::new(RefCell::new(None)), + _delegate: None, _response_task: None, } } - pub(crate) fn show(&mut self, executor: &ForegroundExecutor, notification: SystemNotification) { - self.initialize(executor); - if let Some(center) = &self.center { - center.show(notification); - } - } - - pub(crate) fn dismiss(&mut self, executor: &ForegroundExecutor, tag: &str) { - self.initialize(executor); - if let Some(center) = &self.center { - center.dismiss(tag); + pub(crate) fn send( + &mut self, + foreground_executor: &ForegroundExecutor, + background_executor: &BackgroundExecutor, + command: NotificationCommand, + ) -> Task<()> { + self.initialize(foreground_executor); + let Some(commands) = &self.commands else { + return Task::ready(()); + }; + let (completed, completion) = oneshot::channel(); + if let Err(error) = commands.send((command, completed)) { + log::error!("system notification worker disconnected: {error}"); + return Task::ready(()); } + background_executor.spawn(async move { + if let Err(error) = completion.await { + log::error!( + "system notification worker stopped before completing a command: {error}" + ); + } + }) } pub(crate) fn on_response( @@ -76,11 +101,45 @@ impl SystemNotificationState { } self.initialized = true; + // UserNotifications aborts outside an app bundle. Checking the bundle + // does not contact the notification service. + if NSBundle::mainBundle().bundleIdentifier().is_none() { + log::info!("system notifications disabled: not running from an app bundle"); + return; + } + let (sender, mut receiver) = mpsc::unbounded(); - self.center = NotificationCenter::new(sender); - if self.center.is_none() { + // Install the delegate before returning so a response delivered right + // after registration (e.g. the click that launched the app) has + // somewhere to go. Setting the delegate doesn't wait on the + // notification service, unlike the calls handled by the worker. + let delegate = autoreleasepool(|_| { + let delegate = NotificationResponseDelegate::new(sender); + UNUserNotificationCenter::currentNotificationCenter() + .setDelegate(Some(ProtocolObject::from_ref(&*delegate))); + delegate + }); + self._delegate = Some(delegate); + + let (commands, pending_commands) = channel::<(NotificationCommand, oneshot::Sender<()>)>(); + let worker = std::thread::Builder::new() + .name("system-notifications".into()) + .spawn(move || { + let mut center = autoreleasepool(|_| NotificationCenter::new()); + for (command, completed) in pending_commands { + autoreleasepool(|_| match command { + NotificationCommand::Show(notification) => center.show(notification), + NotificationCommand::Dismiss(tag) => center.dismiss(&tag), + }); + // The caller may stop waiting without cancelling the operation. + _ = completed.send(()); + } + }); + if let Err(error) = worker { + log::error!("failed to start system notification worker: {error}"); return; } + self.commands = Some(commands); // Responses arrive from the delegate on an arbitrary thread; this task // hands them to the registered callback on the main thread. @@ -102,46 +161,28 @@ impl SystemNotificationState { struct NotificationCenter { center: Retained, - /// The center's `delegate` property is weak; keeping the delegate retained - /// here keeps response handling alive for the app's lifetime. - _delegate: Retained, /// The union of every action set registered so far. Categories are shared /// by notifications with identical actions because macOS replaces the /// entire registered set whenever a category is added. - categories: RefCell< + categories: HashMap, (SharedString, Retained)>, - >, - authorization_requested: Cell, + authorization_requested: bool, } impl NotificationCenter { - fn new(sender: mpsc::UnboundedSender) -> Option { - // `UNUserNotificationCenter` raises `NSInternalInconsistencyException` - // ("bundleProxyForCurrentProcess is nil"), aborting the process, when - // the binary isn't part of an app bundle — which is how dev builds run - // via `cargo run`. A bundle identifier is only present when launched - // from a real `.app`, so use it as the guard. - if NSBundle::mainBundle().bundleIdentifier().is_none() { - log::info!("system notifications disabled: not running from an app bundle"); - return None; + fn new() -> Self { + Self { + center: UNUserNotificationCenter::currentNotificationCenter(), + categories: HashMap::new(), + authorization_requested: false, } - - let center = UNUserNotificationCenter::currentNotificationCenter(); - let delegate = NotificationResponseDelegate::new(sender); - center.setDelegate(Some(ProtocolObject::from_ref(&*delegate))); - - Some(Self { - center, - _delegate: delegate, - categories: RefCell::new(HashMap::new()), - authorization_requested: Cell::new(false), - }) } - fn request_authorization(&self) { - if self.authorization_requested.replace(true) { + fn request_authorization(&mut self) { + if self.authorization_requested { return; } + self.authorization_requested = true; let completion = RcBlock::new(|granted: Bool, error: *mut NSError| { // SAFETY: when non-null, `error` is a valid `NSError` for the // duration of the callback. @@ -161,7 +202,7 @@ impl NotificationCenter { ); } - fn show(&self, notification: SystemNotification) { + fn show(&mut self, notification: SystemNotification) { self.request_authorization(); let content = UNMutableNotificationContent::new(); @@ -194,14 +235,15 @@ impl NotificationCenter { .addNotificationRequest_withCompletionHandler(&request, Some(&completion)); } - fn register_category(&self, actions: &[SystemNotificationAction]) -> SharedString { - let mut categories = self.categories.borrow_mut(); - if let Some((identifier, _category)) = categories.get(actions) { + fn register_category(&mut self, actions: &[SystemNotificationAction]) -> SharedString { + if let Some((identifier, _category)) = self.categories.get(actions) { return identifier.clone(); } - let identifier = - SharedString::from(format!("gpui-system-notification-{}", categories.len())); + let identifier = SharedString::from(format!( + "gpui-system-notification-{}", + self.categories.len() + )); let platform_actions: Vec> = actions .iter() .map(|action| { @@ -220,8 +262,10 @@ impl NotificationCenter { UNNotificationCategoryOptions::empty(), ); - categories.insert(actions.to_vec(), (identifier.clone(), category)); - let all: Vec> = categories + self.categories + .insert(actions.to_vec(), (identifier.clone(), category)); + let all: Vec> = self + .categories .values() .map(|(_identifier, category)| category.clone()) .collect(); @@ -307,3 +351,65 @@ impl NotificationResponseDelegate { unsafe { msg_send![super(this), init] } } } + +#[cfg(test)] +mod tests { + use super::*; + use futures::FutureExt as _; + + #[gpui::test] + async fn test_notification_commands_do_not_wait_for_the_service(cx: &mut gpui::TestAppContext) { + let (sender, receiver) = channel(); + let mut state = SystemNotificationState { + initialized: true, + commands: Some(sender), + ..SystemNotificationState::new() + }; + let notification = SystemNotification { + tag: "thread".into(), + title: "Finished".into(), + body: "Ready for input".into(), + actions: vec![], + }; + + // No service consumes commands until after every UI call has returned. + let mut tasks = [ + state.send( + &cx.foreground_executor, + &cx.background_executor, + NotificationCommand::Show(notification.clone()), + ), + state.send( + &cx.foreground_executor, + &cx.background_executor, + NotificationCommand::Dismiss("thread".into()), + ), + state.send( + &cx.foreground_executor, + &cx.background_executor, + NotificationCommand::Show(notification.clone()), + ), + ]; + for task in &mut tasks { + assert!(task.now_or_never().is_none()); + } + + let (commands, completions): (Vec<_>, Vec<_>) = receiver.try_iter().unzip(); + assert_eq!( + commands, + vec![ + NotificationCommand::Show(notification.clone()), + NotificationCommand::Dismiss("thread".into()), + NotificationCommand::Show(notification), + ] + ); + for completed in completions { + completed + .send(()) + .expect("caller is waiting for completion"); + } + for task in tasks { + task.await; + } + } +} diff --git a/crates/gpui_platform/benches/atlas_upload.rs b/crates/gpui_platform/benches/atlas_upload.rs index 8ede1a5b..9ad76e2b 100644 --- a/crates/gpui_platform/benches/atlas_upload.rs +++ b/crates/gpui_platform/benches/atlas_upload.rs @@ -224,7 +224,7 @@ fn tile_scene(tile: AtlasTile) -> Scene { match tile.texture_id.kind { AtlasTextureKind::Monochrome => scene.insert_primitive(MonochromeSprite { order: 0, - pad: 0, + animation: gpui::SpriteAnimationId::NONE, tile, bounds, content_mask, diff --git a/crates/gpui_platform/benches/primitives.rs b/crates/gpui_platform/benches/primitives.rs index 960f40d6..422dbd4b 100644 --- a/crates/gpui_platform/benches/primitives.rs +++ b/crates/gpui_platform/benches/primitives.rs @@ -296,6 +296,11 @@ fn scene_content_mask() -> ContentMask { } fn build_scene(scene: &mut Scene, rectangles: &[Rectangle]) { + insert_primitives(scene, rectangles); + scene.finish(); +} + +fn insert_primitives(scene: &mut Scene, rectangles: &[Rectangle]) { scene.clear(); let content_mask = scene_content_mask().scale(1.); for (index, rectangle) in rectangles.iter().enumerate() { @@ -340,7 +345,7 @@ fn build_scene(scene: &mut Scene, rectangles: &[Rectangle]) { + point(glyph_size * (glyph as f32 * 0.6), gpui::ScaledPixels(0.)); scene.insert_primitive(gpui::MonochromeSprite { order: 0, - pad: 0, + animation: gpui::SpriteAnimationId::NONE, tile: glyph_tile(index + glyph), bounds: Bounds::new(origin, size(glyph_size * 0.6, glyph_size)), content_mask, @@ -351,7 +356,26 @@ fn build_scene(scene: &mut Scene, rectangles: &[Rectangle]) { } } } - scene.finish(); +} + +fn scene_finish(criterion: &mut criterion::Criterion) { + let mut group = criterion.benchmark_group("Primitives/finish"); + for case in cases() { + let mut fixture = None; + group.bench_function(case.to_string(), |bencher| { + let rectangles = fixture.get_or_insert_with(|| rectangles(&case, 512.)); + bencher.iter_batched_ref( + || { + let mut scene = Scene::default(); + insert_primitives(&mut scene, rectangles); + scene + }, + |scene| scene.finish(), + criterion::BatchSize::LargeInput, + ); + }); + } + group.finish(); } fn scene_ordering(criterion: &mut criterion::Criterion) { @@ -414,6 +438,6 @@ gpui::bench_group!( .warm_up_time(Duration::from_millis(500)) .measurement_time(Duration::from_secs(1)) .sample_size(20); - targets = paint_rectangles, scene_ordering + targets = paint_rectangles, scene_ordering, scene_finish ); gpui::bench_main!(benches); diff --git a/crates/gpui_wgpu/Cargo.toml b/crates/gpui_wgpu/Cargo.toml index 600d0083..777b3e14 100644 --- a/crates/gpui_wgpu/Cargo.toml +++ b/crates/gpui_wgpu/Cargo.toml @@ -48,6 +48,7 @@ wgpu = { workspace = true, features = ["std", "metal", "gles", "vulkan", "wgsl", wgpu = { workspace = true, default-features = true } [target.'cfg(target_family = "wasm")'.dependencies] +js-sys.workspace = true web-sys = { workspace = true, features = ["HtmlCanvasElement"] } wgpu = { workspace = true, features = ["webgl"] } diff --git a/crates/gpui_wgpu/src/cosmic_text_system.rs b/crates/gpui_wgpu/src/cosmic_text_system.rs index 7d738aff..eafe9744 100644 --- a/crates/gpui_wgpu/src/cosmic_text_system.rs +++ b/crates/gpui_wgpu/src/cosmic_text_system.rs @@ -364,8 +364,7 @@ impl CosmicTextSystemState { cached.clone() } else { let loaded = self.load_family(fallback_name, features, None)?; - self.font_ids_by_family_cache - .insert(fb_key.clone(), loaded.clone()); + self.font_ids_by_family_cache.insert(fb_key, loaded.clone()); loaded }; let Some(&fb_id) = fb_ids.first() else { diff --git a/crates/gpui_wgpu/src/shaders.wgsl b/crates/gpui_wgpu/src/shaders.wgsl index 06213ff3..8dd2d022 100644 --- a/crates/gpui_wgpu/src/shaders.wgsl +++ b/crates/gpui_wgpu/src/shaders.wgsl @@ -81,10 +81,12 @@ struct GlobalParams { viewport_size: vec2, path_paint_base: u32, path_curve_base: u32, + depth_scale: f32, + quad_count: u32, + premultiplied_alpha: u32, + pad: u32, } -override PREMULTIPLIED_ALPHA: bool = false; - struct GammaParams { gamma_ratios: vec4, grayscale_enhanced_contrast: f32, @@ -328,29 +330,8 @@ fn oklab_to_linear_srgb(color: vec4) -> vec4 { fn over(below: vec4, above: vec4) -> vec4 { let alpha = above.a + below.a * (1.0 - above.a); - let color = (above.rgb * above.a + below.rgb * below.a * (1.0 - above.a)) / alpha; - return vec4(color, alpha); -} - -// A standard gaussian function, used for weighting samples -fn gaussian(x: f32, sigma: f32) -> f32{ - return exp(-(x * x) / (2.0 * sigma * sigma)) / (sqrt(2.0 * M_PI_F) * sigma); -} - -// This approximates the error function, needed for the gaussian integral -fn erf(v: vec2) -> vec2 { - let s = sign(v); - let a = abs(v); - let r1 = 1.0 + (0.278393 + (0.230389 + (0.000972 + 0.078108 * a) * a) * a) * a; - let r2 = r1 * r1; - return s - s / (r2 * r2); -} - -fn blur_along_x(x: f32, y: f32, sigma: f32, corner: f32, half_size: vec2) -> f32 { - let delta = min(half_size.y - corner - abs(y), 0.0); - let curved = half_size.x - corner + sqrt(max(0.0, corner * corner - delta * delta)); - let integral = 0.5 + 0.5 * erf((x + vec2(-curved, curved)) * (sqrt(0.5) / sigma)); - return integral.y - integral.x; + let premultiplied = above.rgb * above.a + below.rgb * below.a * (1.0 - above.a); + return vec4(premultiplied / select(alpha, 1.0, alpha == 0.0), alpha); } // Selects corner radius based on quadrant. @@ -406,7 +387,7 @@ fn quad_sdf_impl(corner_center_to_point: vec2, corner_radius: f32) -> f32 { // target alpha compositing mode. fn blend_color(color: vec4, alpha_factor: f32) -> vec4 { let alpha = color.a * alpha_factor; - let multiplier = select(1.0, alpha, PREMULTIPLIED_ALPHA); + let multiplier = select(1.0, alpha, globals.premultiplied_alpha != 0u); return vec4(color.rgb * multiplier, alpha); } @@ -564,6 +545,20 @@ fn is_shaped(quad: Quad) -> bool { return has_rounded_corners(quad.corner_radii) || has_border(quad.border_widths); } +const CULLED_POSITION: vec4 = vec4(0.0, 0.0, 0.0, 1.0); + +fn quad_depth(quad_id: u32) -> f32 { + return saturate(f32(quad_id + 1u) * globals.depth_scale); +} + +// Opaque rectangles are drawn by the opaque pass instead of the quad pass. +fn is_opaque_rectangle(quad: Quad) -> bool { + return quad.background.tag == 0u + && quad.background.solid.a >= 1.0 + && !has_rounded_corners(quad.corner_radii) + && !has_border(quad.border_widths); +} + struct QuadVarying { @builtin(position) position: vec4, @location(0) @interpolate(flat) border_color: vec4, @@ -576,12 +571,18 @@ struct QuadVarying { @vertex fn vs_quad(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> QuadVarying { - let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); let quad = load_quad(instance_id); var out = QuadVarying(); + if (is_opaque_rectangle(quad)) { + out.position = CULLED_POSITION; + return out; + } + + let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); let clipped = clip_to_mask(unit_vertex, quad.bounds, quad.content_mask); out.position = to_device_position_impl(clipped.position); + out.position.z = quad_depth(instance_id); out.border_color = hsla_to_rgba(quad.border_color); let simple = !is_shaped(quad) && quad.background.tag == 0u; @@ -900,11 +901,8 @@ fn fs_quad(input: QuadVarying) -> @location(0) vec4 { } } - // Blend the border on top of the background and then linearly interpolate - // between the two as we slide inside the background. - let blended_border = over(background, border_color); - color = mix(background, blended_border, - saturate(antialias_threshold - inner_sdf)); + border_color.a *= saturate(antialias_threshold - inner_sdf); + color = over(background, border_color); } return blend_color(color, saturate(antialias_threshold - outer_sdf)); @@ -963,6 +961,37 @@ fn fmod(a: f32, b: f32) -> f32 { return a - b * trunc(a / b); } +// --- opaque quads --- // + +struct OpaqueQuadVarying { + @builtin(position) position: vec4, + @location(0) @interpolate(flat) color: vec4, +} + +@vertex +fn vs_opaque_quad(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> OpaqueQuadVarying { + let quad_id = globals.quad_count - 1u - instance_id; + let quad = load_quad(quad_id); + + var out = OpaqueQuadVarying(); + if (!is_opaque_rectangle(quad)) { + out.position = CULLED_POSITION; + return out; + } + + let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); + let clipped = clip_to_mask(unit_vertex, quad.bounds, quad.content_mask); + out.position = to_device_position_impl(clipped.position); + out.position.z = quad_depth(quad_id); + out.color = blend_color(hsla_to_rgba(quad.background.solid), 1.0); + return out; +} + +@fragment +fn fs_opaque_quad(input: OpaqueQuadVarying) -> @location(0) vec4 { + return input.color; +} + // --- shadows --- // struct Shadow { @@ -987,6 +1016,74 @@ struct ShadowVarying { @builtin(position) position: vec4, @location(0) @interpolate(flat) color: vec4, @location(1) @interpolate(flat) shadow_id: u32, + @location(2) @interpolate(flat) blur_shape: vec4, + @location(3) @interpolate(flat) blur_r1: vec4, + @location(4) @interpolate(flat) blur_exponent: vec4, + @location(5) @interpolate(flat) blur_scale: vec4, +} + +struct PreparedBlurredRoundedRect { + shape: vec4, + r1: vec4, + exponent: vec4, + scale: vec4, +} + +fn erf7(input: f32) -> f32 { + let x = clamp(input, -10.0, 10.0) * (2.0 / sqrt(M_PI_F)); + let xx = x * x; + let y = x + (0.24295 + (0.03395 + 0.0104 * xx) * xx) * (x * xx); + return y / sqrt(1.0 + y * y); +} + +// Raph Levien's blurred rounded rectangle approximation, whose blur s is sigma * sqrt(2): +// https://raphlinus.github.io/graphics/2020/04/21/blurred-rounded-rects.html +fn prepare_blurred_rounded_rect(size: vec2, corner_radii: Corners, sigma: f32) -> PreparedBlurredRoundedRect { + let s = max(sigma * sqrt(2.0), 1e-6); + let s_inv = 1.0 / s; + let min_edge = min(size.x, size.y); + let r_max = 0.5 * min_edge; + let radii = vec4(corner_radii.top_left, corner_radii.top_right, + corner_radii.bottom_right, corner_radii.bottom_left); + let r0 = min(sqrt(radii * radii + 1.15 * 1.15 * s * s), vec4(r_max)); + let r1 = min(sqrt(radii * radii + 4.0 * s * s), vec4(r_max)); + + let half_extent = 0.5 * s_inv * size; + let delta = 1.25 * s * (exp(-half_extent.x * half_extent.x) - exp(-half_extent.y * half_extent.y)); + let adjusted_size = vec2(size.x + min(delta, 0.0), size.y - max(delta, 0.0)); + let peak = s_inv * 0.5 * (max(adjusted_size.x, adjusted_size.y) - 0.5 * radii); + + var output: PreparedBlurredRoundedRect; + output.shape = vec4(0.5 * adjusted_size, s_inv, min_edge); + output.r1 = r1; + output.exponent = 2.0 * r1 / r0; + output.scale = 0.5 * vec4(erf7(peak.x), erf7(peak.y), erf7(peak.z), erf7(peak.w)); + return output; +} + +fn pick_corner(center_to_point: vec2, values: vec4) -> f32 { + return pick_corner_radius(center_to_point, Corners(values.x, values.y, values.z, values.w)); +} + +fn blurred_rounded_rect(center_to_point: vec2, prepared: PreparedBlurredRoundedRect) -> f32 { + let r1 = pick_corner(center_to_point, prepared.r1); + let exponent = pick_corner(center_to_point, prepared.exponent); + let scale = pick_corner(center_to_point, prepared.scale); + let s_inv = prepared.shape.z; + let min_edge = prepared.shape.w; + + let p0 = abs(center_to_point) - (prepared.shape.xy - r1); + let p1 = max(p0, vec2(0.0)); + var d_pos: f32; + if (p1.x > 0.0 && p1.y > 0.0) { + d_pos = pow(pow(p1.x, exponent) + pow(p1.y, exponent), 1.0 / exponent); + } else { + d_pos = p1.x + p1.y; + } + + let d_neg = min(max(p0.x, p0.y), 0.0); + let d = d_pos + d_neg - r1; + return scale * (erf7(s_inv * (min_edge + d)) - erf7(s_inv * d)); } @vertex @@ -999,39 +1096,28 @@ fn vs_shadow(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) ins out.position = to_device_position_impl(clipped.position); out.color = hsla_to_rgba(shadow.color); out.shadow_id = instance_id; + let blur = prepare_blurred_rounded_rect(shadow.shape_bounds.size, shadow.shape_corner_radii, + shadow.blur_radius); + out.blur_shape = blur.shape; + out.blur_r1 = blur.r1; + out.blur_exponent = blur.exponent; + out.blur_scale = blur.scale; return out; } @fragment fn fs_shadow(input: ShadowVarying) -> @location(0) vec4 { let shadow = load_shadow(input.shadow_id); - let half_size = shadow.shape_bounds.size / 2.0; - let center = shadow.shape_bounds.origin + half_size; - let center_to_point = input.position.xy - center; - - let corner_radius = pick_corner_radius(center_to_point, shadow.shape_corner_radii); var alpha: f32; if (shadow.blur_radius == 0.0) { let distance = quad_sdf(input.position.xy, shadow.shape_bounds, shadow.shape_corner_radii); alpha = saturate(0.5 - distance); } else { - // The signal is only non-zero in a limited range, so don't waste samples - let low = center_to_point.y - half_size.y; - let high = center_to_point.y + half_size.y; - let start = clamp(-3.0 * shadow.blur_radius, low, high); - let end = clamp(3.0 * shadow.blur_radius, low, high); - - // Accumulate samples (we can get away with surprisingly few samples) - let step = (end - start) / 4.0; - var y = start + step * 0.5; - alpha = 0.0; - for (var i = 0; i < 4; i += 1) { - let blur = blur_along_x(center_to_point.x, center_to_point.y - y, - shadow.blur_radius, corner_radius, half_size); - alpha += blur * gaussian(y, shadow.blur_radius) * step; - y += step; - } + let center = shadow.shape_bounds.origin + shadow.shape_bounds.size / 2.0; + let blur = PreparedBlurredRoundedRect(input.blur_shape, input.blur_r1, + input.blur_exponent, input.blur_scale); + alpha = blurred_rounded_rect(input.position.xy - center, blur); } if (shadow.inset != 0u) { diff --git a/crates/gpui_wgpu/src/wgpu_context.rs b/crates/gpui_wgpu/src/wgpu_context.rs index 5563a761..37e9a0aa 100644 --- a/crates/gpui_wgpu/src/wgpu_context.rs +++ b/crates/gpui_wgpu/src/wgpu_context.rs @@ -338,6 +338,18 @@ impl WgpuContext { } } + pub fn supports_transient_attachments(&self) -> bool { + #[cfg(target_family = "wasm")] + if self.backend == WgpuBackend::BrowserWebGpu { + // wgpu passes usage bits straight to the browser without knowing + // whether it recognizes this one. + return js_sys::Reflect::get(&js_sys::global(), &"GPUTextureUsage".into()) + .and_then(|usage| js_sys::Reflect::has(&usage, &"TRANSIENT_ATTACHMENT".into())) + .unwrap_or(false); + } + true + } + #[cfg(target_family = "wasm")] pub async fn new_web( canvas: &web_sys::HtmlCanvasElement, diff --git a/crates/gpui_wgpu/src/wgpu_renderer.rs b/crates/gpui_wgpu/src/wgpu_renderer.rs index 73fa8e2a..53af304a 100644 --- a/crates/gpui_wgpu/src/wgpu_renderer.rs +++ b/crates/gpui_wgpu/src/wgpu_renderer.rs @@ -4,7 +4,7 @@ use bytemuck::{Pod, Zeroable}; use collections::FxHashMap; use gpui::{ AtlasTextureId, Bounds, DevicePixels, GpuSpecs, PaintedPath, PrimitiveBatch, ScaledPixels, - Scene, Size, get_gamma_correction_ratios, + Scene, Size, get_gamma_correction_ratios, quad_depth, quad_depth_scale, }; use log::warn; #[cfg(not(target_family = "wasm"))] @@ -61,6 +61,17 @@ struct GlobalParams { viewport_size: [f32; 2], path_paint_base: u32, path_curve_base: u32, + depth_scale: f32, + quad_count: u32, + premultiplied_alpha: u32, + pad: u32, +} + +const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float; + +struct DepthTexture { + texture: wgpu::Texture, + view: wgpu::TextureView, } #[repr(C)] @@ -110,6 +121,7 @@ pub struct WgpuSurfaceConfig { struct WgpuPipelines { quads: wgpu::RenderPipeline, + opaque_quads: wgpu::RenderPipeline, shadows: wgpu::RenderPipeline, path_tiles: wgpu::RenderPipeline, underlines: wgpu::RenderPipeline, @@ -118,6 +130,7 @@ struct WgpuPipelines { poly_sprites: wgpu::RenderPipeline, #[allow(dead_code)] surfaces: wgpu::RenderPipeline, + premultiplied_alpha: bool, } /// One frame allocation of instance data, ready to bind. @@ -206,7 +219,9 @@ struct WgpuRendererCore { rendering_params: RenderingParameters, is_bgr: bool, dual_source_blending: bool, + transient_attachments: bool, adapter_info: wgpu::AdapterInfo, + depth_texture: Option, /// Read by the headless renderer to create its render target. #[cfg(all( not(target_family = "wasm"), @@ -761,10 +776,6 @@ impl WgpuRendererCore { } else { wgpu::BlendState::ALPHA_BLENDING }; - let compilation_options = wgpu::PipelineCompilationOptions { - constants: &[("PREMULTIPLIED_ALPHA", f64::from(premultiplied_alpha as u8))], - ..Default::default() - }; let color_target = wgpu::ColorTargetState { format: surface_format, @@ -780,7 +791,7 @@ impl WgpuRendererCore { texture_layout: Option<&wgpu::BindGroupLayout>, topology: wgpu::PrimitiveTopology, color_targets: &[Option], - sample_count: u32, + depth_write_enabled: bool, module: &wgpu::ShaderModule| { let mut bind_group_layouts = vec![Some(globals_layout), Some(data_layout)]; bind_group_layouts.extend(texture_layout.map(Some)); @@ -797,13 +808,13 @@ impl WgpuRendererCore { module, entry_point: Some(vs_entry), buffers: &[], - compilation_options: compilation_options.clone(), + compilation_options: wgpu::PipelineCompilationOptions::default(), }, fragment: Some(wgpu::FragmentState { module, entry_point: Some(fs_entry), targets: color_targets, - compilation_options: compilation_options.clone(), + compilation_options: wgpu::PipelineCompilationOptions::default(), }), primitive: wgpu::PrimitiveState { topology, @@ -814,12 +825,14 @@ impl WgpuRendererCore { unclipped_depth: false, conservative: false, }, - depth_stencil: None, - multisample: wgpu::MultisampleState { - count: sample_count, - mask: !0, - alpha_to_coverage_enabled: false, - }, + depth_stencil: Some(wgpu::DepthStencilState { + format: DEPTH_FORMAT, + depth_write_enabled: Some(depth_write_enabled), + depth_compare: Some(wgpu::CompareFunction::Greater), + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), + multisample: wgpu::MultisampleState::default(), multiview_mask: None, cache: None, }) @@ -834,7 +847,24 @@ impl WgpuRendererCore { None, wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, + &shader_module, + ); + + let opaque_quads = create_pipeline( + "opaque_quads", + "vs_opaque_quad", + "fs_opaque_quad", + &layouts.globals, + &layouts.instances, + None, + wgpu::PrimitiveTopology::TriangleStrip, + &[Some(wgpu::ColorTargetState { + format: surface_format, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + true, &shader_module, ); @@ -847,7 +877,7 @@ impl WgpuRendererCore { None, wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, &shader_module, ); @@ -860,7 +890,7 @@ impl WgpuRendererCore { None, wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, &shader_module, ); @@ -873,7 +903,7 @@ impl WgpuRendererCore { None, wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, &shader_module, ); @@ -886,7 +916,7 @@ impl WgpuRendererCore { Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, &shader_module, ); @@ -917,7 +947,7 @@ impl WgpuRendererCore { blend: Some(subpixel_blend), write_mask: wgpu::ColorWrites::COLOR, })], - 1, + false, subpixel_module, )) } else { @@ -933,7 +963,7 @@ impl WgpuRendererCore { Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, &shader_module, ); @@ -946,12 +976,13 @@ impl WgpuRendererCore { None, wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target)], - 1, + false, &shader_module, ); WgpuPipelines { quads, + opaque_quads, shadows, path_tiles, underlines, @@ -959,6 +990,7 @@ impl WgpuRendererCore { subpixel_sprites, poly_sprites, surfaces, + premultiplied_alpha, } } } @@ -1257,7 +1289,9 @@ impl WgpuRendererCore { rendering_params, is_bgr: false, dual_source_blending, + transient_attachments: context.supports_transient_attachments(), adapter_info: context.adapter.get_info(), + depth_texture: None, #[cfg(all( not(target_family = "wasm"), any(test, feature = "bench-support", feature = "test-support") @@ -1352,10 +1386,15 @@ impl WgpuRendererCore { scene.polychrome_sprites.len(), ) })?; + let depth_scale = quad_depth_scale(scene.quads.len()); let globals = GlobalParams { viewport_size: [size.width.0 as f32, size.height.0 as f32], path_paint_base: instance_bindings.path_tiles.paint_base, path_curve_base: instance_bindings.path_tiles.curve_base, + depth_scale, + quad_count: scene.quads.len() as u32, + premultiplied_alpha: self.resources().pipelines.premultiplied_alpha as u32, + pad: 0, }; self.resources().queue.write_buffer( &self.resources().globals_buffer, @@ -1363,6 +1402,16 @@ impl WgpuRendererCore { bytemuck::bytes_of(&globals), ); self.prepare_texture_bind_groups(scene); + self.ensure_depth_texture(size); + let depth_view = &self + .depth_texture + .as_ref() + .context("depth texture missing")? + .view; + // Quads are written first, so their instance indices are their + // indices in `scene.quads` on both transports, which the quad depths + // rely on. + debug_assert_eq!(instance_bindings.quads.first_instance, 0); let mut encoder = self.resources() @@ -1383,20 +1432,57 @@ impl WgpuRendererCore { }, depth_slice: None, })], - depth_stencil_attachment: None, + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: depth_view, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(0.0), + store: wgpu::StoreOp::Discard, + }), + stencil_ops: None, + }), ..Default::default() }); pass.set_bind_group(0, &self.resources().globals_bind_group, &[]); + self.draw_instances( + &instance_bindings.quads, + &self.resources().pipelines.opaque_quads, + instance_range(0..scene.quads.len()), + &mut pass, + ); + + let viewport_width = size.width.0 as f32; + let viewport_height = size.height.0 as f32; + let mut quad_cursor: u32 = 0; let mut path_tile_cursor = 0; for batch in scene.batches() { + // 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 (minimum_depth, maximum_depth) = if matches!(&batch, PrimitiveBatch::Quads(_)) { + (0.0, 1.0) + } else { + let depth = quad_depth(quad_cursor, depth_scale); + (depth, depth) + }; + pass.set_viewport( + 0.0, + 0.0, + viewport_width, + viewport_height, + minimum_depth, + maximum_depth, + ); + match batch { - PrimitiveBatch::Quads(range) => self.draw_instances( - &instance_bindings.quads, - &self.resources().pipelines.quads, - instance_range(range), - &mut pass, - ), + PrimitiveBatch::Quads(range) => { + quad_cursor += range.len() as u32; + self.draw_instances( + &instance_bindings.quads, + &self.resources().pipelines.quads, + instance_range(range), + &mut pass, + ) + } PrimitiveBatch::Shadows(range) => self.draw_instances( &instance_bindings.shadows, &self.resources().pipelines.shadows, @@ -1468,6 +1554,41 @@ impl WgpuRendererCore { Ok(submission) } + fn ensure_depth_texture(&mut self, size: Size) { + let width = size.width.0 as u32; + let height = size.height.0 as u32; + if let Some(depth_texture) = &self.depth_texture + && depth_texture.texture.width() == width + && depth_texture.texture.height() == height + { + return; + } + let usage = if self.transient_attachments { + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TRANSIENT_ATTACHMENT + } else { + wgpu::TextureUsages::RENDER_ATTACHMENT + }; + let texture = self + .resources() + .device + .create_texture(&wgpu::TextureDescriptor { + label: Some("depth_texture"), + size: wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: DEPTH_FORMAT, + usage, + view_formats: &[], + }); + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + self.depth_texture = Some(DepthTexture { texture, view }); + } + fn write_instances( &mut self, scene: &Scene, diff --git a/crates/gpui_windows/Cargo.toml b/crates/gpui_windows/Cargo.toml index 37e4a2f7..83e2d2d0 100644 --- a/crates/gpui_windows/Cargo.toml +++ b/crates/gpui_windows/Cargo.toml @@ -17,8 +17,6 @@ default = ["gpui/default"] test-support = ["gpui/test-support"] screen-capture = ["gpui/screen-capture", "scap"] -[dependencies] -gpui.workspace = true [target.'cfg(target_os = "windows")'.dependencies] accesskit.workspace = true @@ -28,6 +26,7 @@ collections.workspace = true dunce.workspace = true etagere.workspace = true futures.workspace = true +gpui.workspace = true gpui_util.workspace = true image.workspace = true itertools.workspace = true diff --git a/crates/gpui_windows/build.rs b/crates/gpui_windows/build.rs index bbef5316..4b5c3d66 100644 --- a/crates/gpui_windows/build.rs +++ b/crates/gpui_windows/build.rs @@ -33,6 +33,7 @@ mod shader_compilation { // Define all modules let modules = [ "quad", + "opaque_quad", "shadow", "path_tile", "underline", diff --git a/crates/gpui_windows/src/directx_renderer.rs b/crates/gpui_windows/src/directx_renderer.rs index 2b364d49..8573fe40 100644 --- a/crates/gpui_windows/src/directx_renderer.rs +++ b/crates/gpui_windows/src/directx_renderer.rs @@ -62,6 +62,7 @@ pub(crate) struct DirectXRendererDevices { pub(crate) dxgi_factory: IDXGIFactory6, pub(crate) device: ID3D11Device, pub(crate) device_context: ID3D11DeviceContext, + device_context1: Option, dxgi_device: Option, annotation: Option, } @@ -71,6 +72,8 @@ struct DirectXResources { swap_chain: IDXGISwapChain1, render_target: Option, render_target_view: Option, + depth_stencil_texture: ID3D11Texture2D, + depth_stencil_view: Option, // Cached viewport viewport: D3D11_VIEWPORT, @@ -79,6 +82,7 @@ struct DirectXResources { struct DirectXRenderPipelines { shadow_pipeline: PipelineState, quad_pipeline: PipelineState, + opaque_quad_pipeline: OpaqueQuadPipeline, path_tile_pipeline: PipelineState, path_curves: StructuredBuffer, path_paints: StructuredBuffer, @@ -132,12 +136,14 @@ impl DirectXRendererDevices { Some(device.cast().context("Creating DXGI device")?) }; let annotation = device_context.cast().ok(); + let device_context1 = device_context.cast().ok(); Ok(Self { adapter: adapter.clone(), dxgi_factory: dxgi_factory.clone(), device: device.clone(), device_context: device_context.clone(), + device_context1, dxgi_device, annotation, }) @@ -195,7 +201,7 @@ impl DirectXRenderer { self.atlas.clone() } - fn pre_draw(&self, clear_color: &[f32; 4]) -> Result<()> { + fn pre_draw(&self, clear_color: &[f32; 4], depth_scale: f32) -> Result<()> { let resources = self.resources.as_ref().expect("resources missing"); let device_context = &self .devices @@ -211,7 +217,8 @@ impl DirectXRenderer { grayscale_enhanced_contrast: self.font_info.grayscale_enhanced_contrast, subpixel_enhanced_contrast: self.font_info.subpixel_enhanced_contrast, is_bgr: self.font_info.is_bgr as u32, - _pad: [0; 3], + depth_scale, + _pad: [0; 2], }], )?; unsafe { @@ -222,8 +229,19 @@ impl DirectXRenderer { .context("missing render target view")?, clear_color, ); - device_context - .OMSetRenderTargets(Some(slice::from_ref(&resources.render_target_view)), None); + device_context.ClearDepthStencilView( + resources + .depth_stencil_view + .as_ref() + .context("missing depth stencil view")?, + D3D11_CLEAR_DEPTH.0, + 0.0, + 0, + ); + device_context.OMSetRenderTargets( + Some(slice::from_ref(&resources.render_target_view)), + resources.depth_stencil_view.as_ref(), + ); device_context.RSSetViewports(Some(slice::from_ref(&resources.viewport))); device_context .VSSetConstantBuffers(0, Some(slice::from_ref(&self.globals.global_params_buffer))); @@ -235,6 +253,13 @@ impl DirectXRenderer { Ok(()) } + fn discard_depth_buffer(&self) -> Option<()> { + let context1 = self.devices.as_ref()?.device_context1.as_ref()?; + let depth_stencil_view = self.resources.as_ref()?.depth_stencil_view.as_ref()?; + unsafe { context1.DiscardView(depth_stencil_view) }; + Some(()) + } + #[inline] fn present(&mut self) -> Result<()> { let result = unsafe { @@ -308,9 +333,10 @@ impl DirectXRenderer { .handle_device_lost(&devices.device, &devices.device_context); unsafe { - devices - .device_context - .OMSetRenderTargets(Some(slice::from_ref(&resources.render_target_view)), None); + devices.device_context.OMSetRenderTargets( + Some(slice::from_ref(&resources.render_target_view)), + resources.depth_stencil_view.as_ref(), + ); } self.devices = Some(devices); self.resources = Some(resources); @@ -345,10 +371,14 @@ impl DirectXRenderer { scene: &Scene, background_appearance: WindowBackgroundAppearance, ) -> Result<()> { - self.pre_draw(&match background_appearance { - WindowBackgroundAppearance::Opaque => [1.0f32; 4], - _ => [0.0f32; 4], - })?; + let depth_scale = quad_depth_scale(scene.quads.len()); + self.pre_draw( + &match background_appearance { + WindowBackgroundAppearance::Opaque => [1.0f32; 4], + _ => [0.0f32; 4], + }, + depth_scale, + )?; self.upload_scene_buffers(scene)?; let annotation = self @@ -356,14 +386,39 @@ impl DirectXRenderer { .as_ref() .and_then(|devices| devices.annotation.clone()) .filter(|annotation| unsafe { annotation.GetStatus().as_bool() }); + + if !scene.quads.is_empty() { + let _annotation = annotation.as_ref().map(|annotation| { + Annotation::new( + annotation, + HSTRING::from(format!("opaque quads ({})", scene.quads.len())), + ) + }); + self.draw_opaque_quads(scene.quads.len())?; + } + + let mut quad_cursor: u32 = 0; let mut path_tile_cursor = 0; for batch in scene.batches() { let _annotation = annotation .as_ref() .map(|annotation| Annotation::new(annotation, HSTRING::from(batch.label()))); + + // Quad shaders assign each quad its own depth. + // In every other batch type, the depth is fixed to the position of the quad cursor. + if matches!(&batch, PrimitiveBatch::Quads(_)) { + self.set_viewport_depth_range(0.0, 1.0)?; + } else { + let depth = quad_depth(quad_cursor, depth_scale); + self.set_viewport_depth_range(depth, depth)?; + } + match batch { PrimitiveBatch::Shadows(range) => self.draw_shadows(range.start, range.len()), - PrimitiveBatch::Quads(range) => self.draw_quads(range.start, range.len()), + PrimitiveBatch::Quads(range) => { + quad_cursor += range.len() as u32; + self.draw_quads(range.start, range.len()) + } PrimitiveBatch::Paths(range) => { let tiles_start = path_tile_cursor; path_tile_cursor += scene.paths[range] @@ -399,6 +454,7 @@ impl DirectXRenderer { ) })?; } + self.discard_depth_buffer(); Ok(()) } @@ -480,6 +536,36 @@ impl DirectXRenderer { .context("Failed to build RgbaImage from staging readback") } + fn set_viewport_depth_range(&self, minimum_depth: f32, maximum_depth: f32) -> Result<()> { + let devices = self.devices.as_ref().context("devices missing")?; + let resources = self.resources.as_ref().context("resources missing")?; + // Equal endpoints collapse every shader depth to the same value. + let viewport = D3D11_VIEWPORT { + MinDepth: minimum_depth, + MaxDepth: maximum_depth, + ..resources.viewport + }; + unsafe { + devices + .device_context + .RSSetViewports(Some(slice::from_ref(&viewport))) + }; + Ok(()) + } + + fn draw_opaque_quads(&self, quad_count: usize) -> Result<()> { + let devices = self.devices.as_ref().context("devices missing")?; + self.pipelines.opaque_quad_pipeline.draw( + &devices.device_context, + &self.pipelines.quad_pipeline, + self.globals + .batch_params_buffer + .as_ref() + .context("batch params buffer missing")?, + quad_count as u32, + ) + } + pub(crate) fn resize(&mut self, new_size: Size) -> Result<()> { let width = new_size.width.0.max(1) as u32; let height = new_size.height.0.max(1) as u32; @@ -516,9 +602,10 @@ impl DirectXRenderer { resources.recreate_resources(devices, width, height)?; unsafe { - devices - .device_context - .OMSetRenderTargets(Some(slice::from_ref(&resources.render_target_view)), None); + devices.device_context.OMSetRenderTargets( + Some(slice::from_ref(&resources.render_target_view)), + resources.depth_stencil_view.as_ref(), + ); } Ok(()) @@ -829,14 +916,21 @@ impl DirectXResources { )? }; - let (render_target, render_target_view, viewport) = - create_resources(devices, &swap_chain, width, height)?; + let ( + render_target, + render_target_view, + depth_stencil_texture, + depth_stencil_view, + viewport, + ) = create_resources(devices, &swap_chain, width, height)?; set_rasterizer_state(&devices.device, &devices.device_context)?; Ok(Self { swap_chain, render_target: Some(render_target), render_target_view, + depth_stencil_texture, + depth_stencil_view, viewport, }) } @@ -848,10 +942,17 @@ impl DirectXResources { width: u32, height: u32, ) -> Result<()> { - let (render_target, render_target_view, viewport) = - create_resources(devices, &self.swap_chain, width, height)?; + let ( + render_target, + render_target_view, + depth_stencil_texture, + depth_stencil_view, + viewport, + ) = create_resources(devices, &self.swap_chain, width, height)?; self.render_target = Some(render_target); self.render_target_view = render_target_view; + self.depth_stencil_texture = depth_stencil_texture; + self.depth_stencil_view = depth_stencil_view; self.viewport = viewport; Ok(()) } @@ -910,10 +1011,12 @@ impl DirectXRenderPipelines { 16, create_blend_state(device)?, )?; + let opaque_quad_pipeline = OpaqueQuadPipeline::new(device)?; Ok(Self { shadow_pipeline, quad_pipeline, + opaque_quad_pipeline, path_tile_pipeline, path_curves, path_paints, @@ -987,7 +1090,8 @@ struct GlobalParams { grayscale_enhanced_contrast: f32, subpixel_enhanced_contrast: f32, is_bgr: u32, - _pad: [u32; 3], + depth_scale: f32, + _pad: [u32; 2], } #[derive(Clone, Copy, Debug, Default)] @@ -1061,6 +1165,7 @@ struct PipelineState { fragment: ID3D11PixelShader, instances: StructuredBuffer, blend_state: ID3D11BlendState, + depth_stencil_state: ID3D11DepthStencilState, } impl PipelineState { @@ -1085,6 +1190,7 @@ impl PipelineState { fragment, instances: StructuredBuffer::new(device, label, buffer_size)?, blend_state, + depth_stencil_state: create_depth_stencil_state(device, D3D11_DEPTH_WRITE_MASK_ZERO)?, }) } @@ -1113,6 +1219,7 @@ impl PipelineState { &self.vertex, &self.fragment, &self.blend_state, + &self.depth_stencil_state, ); unsafe { device_context.DrawInstanced(4, instance_count, 0, 0); @@ -1138,6 +1245,7 @@ impl PipelineState { &self.vertex, &self.fragment, &self.blend_state, + &self.depth_stencil_state, ); unsafe { device_context.PSSetSamplers(0, Some(sampler)); @@ -1158,6 +1266,63 @@ impl PipelineState { } } +/// Draws opaque rectangles ahead of everything else, writing depth so that +/// later passes skip the pixels they cover. +struct OpaqueQuadPipeline { + vertex: ID3D11VertexShader, + fragment: ID3D11PixelShader, + blend_state: ID3D11BlendState, + depth_stencil_state: ID3D11DepthStencilState, +} + +impl OpaqueQuadPipeline { + fn new(device: &ID3D11Device) -> Result { + let vertex = { + let raw_shader = RawShaderBytes::new(ShaderModule::OpaqueQuad, ShaderTarget::Vertex)?; + create_vertex_shader(device, raw_shader.as_bytes())? + }; + let fragment = { + let raw_shader = RawShaderBytes::new(ShaderModule::OpaqueQuad, ShaderTarget::Fragment)?; + create_fragment_shader(device, raw_shader.as_bytes())? + }; + Ok(OpaqueQuadPipeline { + vertex, + fragment, + blend_state: create_opaque_blend_state(device)?, + depth_stencil_state: create_depth_stencil_state(device, D3D11_DEPTH_WRITE_MASK_ALL)?, + }) + } + + /// Draws every quad, last first. The vertex shader drops all but opaque + /// rectangles. + fn draw( + &self, + device_context: &ID3D11DeviceContext, + quad_pipeline: &PipelineState, + batch_params_buffer: &ID3D11Buffer, + quad_count: u32, + ) -> Result<()> { + if quad_count == 0 { + return Ok(()); + } + quad_pipeline.ensure_range(0, quad_count)?; + // Drawing front to back lets the depth test skip pixels that a later + // quad already covers. + update_batch_start(device_context, batch_params_buffer, quad_count - 1)?; + set_pipeline_state( + device_context, + slice::from_ref(&quad_pipeline.instances.view), + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, + &self.vertex, + &self.fragment, + &self.blend_state, + &self.depth_stencil_state, + ); + unsafe { device_context.DrawInstanced(4, quad_count, 0, 0) }; + Ok(()) + } +} + impl Drop for DirectXRenderer { fn drop(&mut self) { #[cfg(debug_assertions)] @@ -1238,12 +1403,22 @@ fn create_resources( ) -> Result<( ID3D11Texture2D, Option, + ID3D11Texture2D, + Option, D3D11_VIEWPORT, )> { let (render_target, render_target_view) = create_render_target_and_its_view(swap_chain, &devices.device)?; + let (depth_stencil_texture, depth_stencil_view) = + create_depth_stencil_texture_and_view(&devices.device, width, height)?; let viewport = set_viewport(&devices.device_context, width as f32, height as f32); - Ok((render_target, render_target_view, viewport)) + Ok(( + render_target, + render_target_view, + depth_stencil_texture, + depth_stencil_view, + viewport, + )) } #[inline] @@ -1271,6 +1446,37 @@ fn set_viewport(device_context: &ID3D11DeviceContext, width: f32, height: f32) - viewport[0] } +#[inline] +fn create_depth_stencil_texture_and_view( + device: &ID3D11Device, + width: u32, + height: u32, +) -> Result<(ID3D11Texture2D, Option)> { + let texture = unsafe { + let mut output = None; + let desc = D3D11_TEXTURE2D_DESC { + Width: width, + Height: height, + MipLevels: 1, + ArraySize: 1, + Format: DXGI_FORMAT_D32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Usage: D3D11_USAGE_DEFAULT, + BindFlags: D3D11_BIND_DEPTH_STENCIL.0 as u32, + CPUAccessFlags: 0, + MiscFlags: 0, + }; + device.CreateTexture2D(&desc, None, Some(&mut output))?; + output.unwrap() + }; + let mut view = None; + unsafe { device.CreateDepthStencilView(&texture, None, Some(&mut view))? }; + Ok((texture, view)) +} + #[inline] fn set_rasterizer_state(device: &ID3D11Device, device_context: &ID3D11DeviceContext) -> Result<()> { let desc = D3D11_RASTERIZER_DESC { @@ -1313,6 +1519,52 @@ fn create_blend_state(device: &ID3D11Device) -> Result { } } +#[inline] +fn create_opaque_blend_state(device: &ID3D11Device) -> Result { + let mut desc = D3D11_BLEND_DESC::default(); + desc.RenderTarget[0].BlendEnable = false.into(); + desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; + desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; + desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; + desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; + desc.RenderTarget[0].DestBlend = D3D11_BLEND_ZERO; + desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; + desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8; + unsafe { + let mut state = None; + device.CreateBlendState(&desc, Some(&mut state))?; + Ok(state.unwrap()) + } +} + +#[inline] +fn create_depth_stencil_state( + device: &ID3D11Device, + write_mask: D3D11_DEPTH_WRITE_MASK, +) -> Result { + let stencil_op = D3D11_DEPTH_STENCILOP_DESC { + StencilFailOp: D3D11_STENCIL_OP_KEEP, + StencilDepthFailOp: D3D11_STENCIL_OP_KEEP, + StencilPassOp: D3D11_STENCIL_OP_KEEP, + StencilFunc: D3D11_COMPARISON_ALWAYS, + }; + let desc = D3D11_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: write_mask, + DepthFunc: D3D11_COMPARISON_GREATER, + StencilEnable: false.into(), + StencilReadMask: D3D11_DEFAULT_STENCIL_READ_MASK as u8, + StencilWriteMask: D3D11_DEFAULT_STENCIL_WRITE_MASK as u8, + FrontFace: stencil_op, + BackFace: stencil_op, + }; + unsafe { + let mut state = None; + device.CreateDepthStencilState(&desc, Some(&mut state))?; + Ok(state.unwrap()) + } +} + #[inline] fn create_blend_state_for_subpixel_rendering(device: &ID3D11Device) -> Result { let mut desc = D3D11_BLEND_DESC::default(); @@ -1441,6 +1693,7 @@ fn set_pipeline_state( vertex_shader: &ID3D11VertexShader, fragment_shader: &ID3D11PixelShader, blend_state: &ID3D11BlendState, + depth_stencil_state: &ID3D11DepthStencilState, ) { unsafe { device_context.VSSetShaderResources(1, Some(buffer_view)); @@ -1449,6 +1702,7 @@ fn set_pipeline_state( device_context.VSSetShader(vertex_shader, None); device_context.PSSetShader(fragment_shader, None); device_context.OMSetBlendState(blend_state, None, 0xFFFFFFFF); + device_context.OMSetDepthStencilState(depth_stencil_state, 0); } } @@ -1478,6 +1732,7 @@ pub(crate) mod shader_resources { #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub(crate) enum ShaderModule { Quad, + OpaqueQuad, Shadow, Underline, PathTile, @@ -1529,6 +1784,10 @@ pub(crate) mod shader_resources { ShaderTarget::Vertex => QUAD_VERTEX_BYTES, ShaderTarget::Fragment => QUAD_FRAGMENT_BYTES, }, + ShaderModule::OpaqueQuad => match target { + ShaderTarget::Vertex => OPAQUE_QUAD_VERTEX_BYTES, + ShaderTarget::Fragment => OPAQUE_QUAD_FRAGMENT_BYTES, + }, ShaderModule::Shadow => match target { ShaderTarget::Vertex => SHADOW_VERTEX_BYTES, ShaderTarget::Fragment => SHADOW_FRAGMENT_BYTES, @@ -1626,6 +1885,7 @@ pub(crate) mod shader_resources { pub fn as_str(self) -> &'static str { match self { ShaderModule::Quad => "quad", + ShaderModule::OpaqueQuad => "opaque_quad", ShaderModule::Shadow => "shadow", ShaderModule::Underline => "underline", ShaderModule::PathTile => "path_tile", diff --git a/crates/gpui_windows/src/platform.rs b/crates/gpui_windows/src/platform.rs index 4cf4b6be..a5f0d49e 100644 --- a/crates/gpui_windows/src/platform.rs +++ b/crates/gpui_windows/src/platform.rs @@ -927,8 +927,9 @@ impl Platform for WindowsPlatform { .log_err(); } - fn dismiss_system_notification(&self, tag: &str) { + fn dismiss_system_notification(&self, tag: &str) -> Task<()> { self.system_notifications.borrow_mut().dismiss(tag); + Task::ready(()) } fn on_system_notification_response( diff --git a/crates/gpui_windows/src/shaders.hlsl b/crates/gpui_windows/src/shaders.hlsl index 47506c1a..e849773b 100644 --- a/crates/gpui_windows/src/shaders.hlsl +++ b/crates/gpui_windows/src/shaders.hlsl @@ -6,7 +6,8 @@ cbuffer GlobalParams: register(b0) { float grayscale_enhanced_contrast; float subpixel_enhanced_contrast; uint is_bgr; - uint3 global_pad; + float depth_scale; + uint2 global_pad; }; cbuffer BatchParams: register(b1) { @@ -110,6 +111,12 @@ float4 to_device_position(float2 unit_vertex, Bounds bounds) { return to_device_position_impl(position); } +float quad_depth(uint quad_id) { + return saturate(float(quad_id + 1u) * depth_scale); +} + +static const float4 CULLED_POSITION = float4(0.0, 0.0, 0.0, 1.0); + float4 distance_from_clip_rect_impl(float2 position, Bounds clip_bounds) { float2 tl = position - clip_bounds.origin; float2 br = clip_bounds.origin + clip_bounds.size - position; @@ -240,33 +247,10 @@ float4 oklab_to_srgb(float4 color) { return float4(linear_to_srgb(linear_rgb), color.a); } -// This approximates the error function, needed for the gaussian integral -float2 erf(float2 x) { - float2 s = sign(x); - float2 a = abs(x); - x = 1. + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a; - x *= x; - return s - s / (x * x); -} - -float blur_along_x(float x, float y, float sigma, float corner, float2 half_size) { - float delta = min(half_size.y - corner - abs(y), 0.); - float curved = half_size.x - corner + sqrt(max(0., corner * corner - delta * delta)); - float2 integral = 0.5 + 0.5 * erf((x + float2(-curved, curved)) * (sqrt(0.5) / sigma)); - return integral.y - integral.x; -} - -// A standard gaussian function, used for weighting samples -float gaussian(float x, float sigma) { - return exp(-(x * x) / (2. * sigma * sigma)) / (sqrt(2. * M_PI_F) * sigma); -} - float4 over(float4 below, float4 above) { - float4 result; float alpha = above.a + below.a * (1.0 - above.a); - result.rgb = (above.rgb * above.a + below.rgb * below.a * (1.0 - above.a)) / alpha; - result.a = alpha; - return result; + float3 premultiplied = above.rgb * above.a + below.rgb * below.a * (1.0 - above.a); + return float4(premultiplied / (alpha == 0.0 ? 1.0 : alpha), alpha); } float2 to_tile_position(float2 unit_vertex, AtlasTile tile) { @@ -536,12 +520,27 @@ struct QuadFragmentInput { PreparedBackground background; }; +// Opaque rectangles are drawn by the opaque pass instead of the quad pass. +bool is_opaque_rectangle(Quad quad) { + return quad.background.tag == 0u + && quad.background.solid.a >= 1.0 + && !has_rounded_corners(quad.corner_radii) + && !has_border(quad.border_widths); +} + StructuredBuffer quads: register(t1); QuadFragmentInput quad_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { - float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); uint quad_id = batch_start_index + instance_id; Quad quad = quads[quad_id]; + + if (is_opaque_rectangle(quad)) { + QuadFragmentInput culled = (QuadFragmentInput)0; + culled.position = CULLED_POSITION; + return culled; + } + + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); ClippedVertex vertex = clip_to_mask(unit_vertex, quad.bounds, quad.content_mask); float4 device_position = to_device_position_impl(vertex.position); @@ -549,6 +548,7 @@ QuadFragmentInput quad_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_ QuadFragmentInput output; output.position = device_position; + output.position.z = quad_depth(quad_id); output.border_color = border_color; bool simple = !is_shaped(quad) && quad.background.tag == 0u; output.quad_id = quad_id | (simple ? SIMPLE_PRIMITIVE_FLAG : 0u); @@ -828,16 +828,48 @@ float4 quad_fragment(QuadFragmentInput input): SV_Target { } } - // Blend the border on top of the background and then linearly interpolate - // between the two as we slide inside the background. - float4 blended_border = over(background, border_color); - color = lerp(background, blended_border, - saturate(antialias_threshold - inner_sdf)); + border_color.a *= saturate(antialias_threshold - inner_sdf); + color = over(background, border_color); } return color * float4(1.0, 1.0, 1.0, saturate(antialias_threshold - outer_sdf)); } +/* +** +** Opaque quads +** +*/ + +struct OpaqueQuadFragmentInput { + float4 position: SV_Position; + nointerpolation float4 color: COLOR0; +}; + +OpaqueQuadFragmentInput opaque_quad_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { + uint quad_id = batch_start_index - instance_id; + Quad quad = quads[quad_id]; + + OpaqueQuadFragmentInput output; + if (!is_opaque_rectangle(quad)) { + output.position = CULLED_POSITION; + output.color = float4(0.0, 0.0, 0.0, 0.0); + return output; + } + + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); + ClippedVertex vertex = clip_to_mask(unit_vertex, quad.bounds, quad.content_mask); + + output.position = to_device_position_impl(vertex.position); + output.position.z = quad_depth(quad_id); + output.color = hsla_to_rgba(quad.background.solid); + return output; +} + +float4 opaque_quad_fragment(OpaqueQuadFragmentInput input): SV_Target { + return input.color; +} + /* ** ** Shadows @@ -857,14 +889,80 @@ struct Shadow { uint pad; // align to 8 bytes }; +struct PreparedBlurredRoundedRect { + nointerpolation float4 shape: TEXCOORD1; + nointerpolation float4 r1: TEXCOORD2; + nointerpolation float4 exponent: TEXCOORD3; + nointerpolation float4 scale: TEXCOORD4; +}; + struct ShadowFragmentInput { nointerpolation uint shadow_id: TEXCOORD0; float4 position: SV_Position; nointerpolation float4 color: COLOR; + PreparedBlurredRoundedRect blur; }; StructuredBuffer shadows: register(t1); +float erf7(float x) { + x = clamp(x, -10., 10.) * (2. / sqrt(M_PI_F)); + float xx = x * x; + x = x + (0.24295 + (0.03395 + 0.0104 * xx) * xx) * (x * xx); + return x / sqrt(1. + x * x); +} + +// Raph Levien's blurred rounded rectangle approximation, whose blur s is sigma * sqrt(2): +// https://raphlinus.github.io/graphics/2020/04/21/blurred-rounded-rects.html +PreparedBlurredRoundedRect prepare_blurred_rounded_rect(float2 size, Corners corner_radii, float sigma) { + float s = max(sigma * sqrt(2.), 1e-6); + float s_inv = 1. / s; + float min_edge = min(size.x, size.y); + float r_max = 0.5 * min_edge; + float4 radii = float4(corner_radii.top_left, corner_radii.top_right, + corner_radii.bottom_right, corner_radii.bottom_left); + float4 r0 = min(sqrt(radii * radii + 1.15 * 1.15 * s * s), r_max); + float4 r1 = min(sqrt(radii * radii + 4. * s * s), r_max); + + float2 half_extent = 0.5 * s_inv * size; + float delta = 1.25 * s * (exp(-half_extent.x * half_extent.x) - exp(-half_extent.y * half_extent.y)); + float2 adjusted_size = float2(size.x + min(delta, 0.), size.y - max(delta, 0.)); + float4 peak = s_inv * 0.5 * (max(adjusted_size.x, adjusted_size.y) - 0.5 * radii); + + PreparedBlurredRoundedRect output; + output.shape = float4(0.5 * adjusted_size, s_inv, min_edge); + output.r1 = r1; + output.exponent = 2. * r1 / r0; + output.scale = 0.5 * float4(erf7(peak.x), erf7(peak.y), erf7(peak.z), erf7(peak.w)); + return output; +} + +float pick_corner(float2 center_to_point, float4 values) { + Corners corners = { values.x, values.y, values.z, values.w }; + return pick_corner_radius(center_to_point, corners); +} + +float blurred_rounded_rect(float2 center_to_point, PreparedBlurredRoundedRect prepared) { + float r1 = pick_corner(center_to_point, prepared.r1); + float exponent = pick_corner(center_to_point, prepared.exponent); + float scale = pick_corner(center_to_point, prepared.scale); + float s_inv = prepared.shape.z; + float min_edge = prepared.shape.w; + + float2 p0 = abs(center_to_point) - (prepared.shape.xy - r1); + float2 p1 = max(p0, 0.); + float d_pos; + [branch] if (p1.x > 0. && p1.y > 0.) { + d_pos = pow(pow(p1.x, exponent) + pow(p1.y, exponent), 1. / exponent); + } else { + d_pos = p1.x + p1.y; + } + + float d_neg = min(max(p0.x, p0.y), 0.); + float d = d_pos + d_neg - r1; + return scale * (erf7(s_inv * (min_edge + d)) - erf7(s_inv * d)); +} + ShadowFragmentInput shadow_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); uint shadow_id = batch_start_index + instance_id; @@ -878,6 +976,7 @@ ShadowFragmentInput shadow_vertex(uint vertex_id: SV_VertexID, uint instance_id: output.position = device_position; output.color = color; output.shadow_id = shadow_id; + output.blur = prepare_blurred_rounded_rect(shadow.shape_bounds.size, shadow.shape_corner_radii, shadow.blur_radius); return output; } @@ -885,32 +984,13 @@ ShadowFragmentInput shadow_vertex(uint vertex_id: SV_VertexID, uint instance_id: float4 shadow_fragment(ShadowFragmentInput input): SV_TARGET { Shadow shadow = shadows[input.shadow_id]; - float2 half_size = shadow.shape_bounds.size / 2.; - float2 center = shadow.shape_bounds.origin + half_size; - float2 point0 = input.position.xy - center; - float corner_radius = pick_corner_radius(point0, shadow.shape_corner_radii); - float alpha; if (shadow.blur_radius == 0.) { float distance = quad_sdf(input.position.xy, shadow.shape_bounds, shadow.shape_corner_radii); alpha = saturate(0.5 - distance); } else { - // The signal is only non-zero in a limited range, so don't waste samples - float low = point0.y - half_size.y; - float high = point0.y + half_size.y; - float start = clamp(-3. * shadow.blur_radius, low, high); - float end = clamp(3. * shadow.blur_radius, low, high); - - // Accumulate samples (we can get away with surprisingly few samples) - float step = (end - start) / 4.; - float y = start + step * 0.5; - alpha = 0.; - for (int i = 0; i < 4; i++) { - alpha += blur_along_x(point0.x, point0.y - y, shadow.blur_radius, - corner_radius, half_size) * - gaussian(y, shadow.blur_radius) * step; - y += step; - } + float2 center = shadow.shape_bounds.origin + shadow.shape_bounds.size / 2.; + alpha = blurred_rounded_rect(input.position.xy - center, input.blur); } if (shadow.inset != 0u) { diff --git a/crates/zlog/src/filter.rs b/crates/zlog/src/filter.rs index afd1466d..2b0d227f 100644 --- a/crates/zlog/src/filter.rs +++ b/crates/zlog/src/filter.rs @@ -99,6 +99,9 @@ pub fn refresh_from_settings(settings: &HashMap) { level_enabled_max = level_enabled_max.max(level as u8); } } + for (_, level) in &map_new.modules { + level_enabled_max = level_enabled_max.max(*level as u8); + } LEVEL_ENABLED_MAX_CONFIG.store(level_enabled_max, Ordering::Release); { @@ -542,6 +545,17 @@ mod tests { ); } + #[test] + fn test_refresh_from_settings_with_module_filter() { + let settings = [("a::b".to_string(), "trace".to_string())] + .into_iter() + .collect(); + refresh_from_settings(&settings); + let is_enabled = is_scope_enabled(&scope_new(&[""]), Some("a::b"), log::Level::Trace); + refresh_from_settings(&HashMap::default()); + assert!(is_enabled); + } + #[test] fn test_is_enabled_module() { let mut map = scope_map_from_keys(&[("a", "trace")]); diff --git a/crates/ztracing_macro/Cargo.toml b/crates/ztracing_macro/Cargo.toml index 78feebb8..b85bbf2a 100644 --- a/crates/ztracing_macro/Cargo.toml +++ b/crates/ztracing_macro/Cargo.toml @@ -5,6 +5,9 @@ edition.workspace = true publish.workspace = true license = "Apache-2.0" +[lints] +workspace = true + [lib] proc-macro = true test = false From 22d9688d7ad8200b4e69f4ba8871cbc8dd530363 Mon Sep 17 00:00:00 2001 From: nolight132 Date: Thu, 26 Nov 2026 15:50:44 +0100 Subject: [PATCH 2/7] chore: merge the metal and directx renderers of zed@621a6adf30 behind the depth gate --- crates/gpui_apple/src/metal_renderer.rs | 1518 ++++++++++++++++- crates/gpui_apple/src/shaders.metal | 416 ++++- crates/gpui_windows/src/directx_renderer.rs | 1688 ++++++++++++++++++- crates/gpui_windows/src/shaders.hlsl | 453 ++++- 4 files changed, 3905 insertions(+), 170 deletions(-) diff --git a/crates/gpui_apple/src/metal_renderer.rs b/crates/gpui_apple/src/metal_renderer.rs index 86eff3d4..626eeffe 100644 --- a/crates/gpui_apple/src/metal_renderer.rs +++ b/crates/gpui_apple/src/metal_renderer.rs @@ -1,9 +1,11 @@ use crate::metal_atlas::MetalAtlas; use anyhow::{Context as _, Result}; use block2::RcBlock; +use collections::FxHashMap; use gpui::{ - AtlasTextureId, Bounds, ContentMask, DevicePixels, PaintSurface, PaintedPath, PrimitiveBatch, - ScaledPixels, Scene, Size, quad_depth, quad_depth_scale, size, + AtlasTextureId, BLUR_LEVELS, BlurPasses, Bounds, ContentMask, DEPTH_PREPASS, DevicePixels, + GAUSSIAN_REACH, LayerEffect, PaintSurface, PaintedPath, PrimitiveBatch, Pyramid, ScaledPixels, + Scene, ShaderId, Size, point, quad_depth, quad_depth_scale, size, }; #[cfg(any(test, feature = "bench-support", feature = "test-support"))] use image::RgbaImage; @@ -20,19 +22,27 @@ use objc2_foundation::{NSRange, NSString}; use objc2_metal::MTLCopyAllDevices; use objc2_metal::{ MTLBlendFactor, MTLBlendOperation, MTLBuffer, MTLClearColor, MTLCommandBuffer, - MTLCommandEncoder, MTLCommandQueue, MTLCompareFunction, MTLCreateSystemDefaultDevice, - MTLDepthStencilDescriptor, MTLDepthStencilState, MTLDevice, MTLDrawable, MTLGPUFamily, - MTLLibrary, MTLLoadAction, MTLPixelFormat, MTLPrimitiveType, MTLRenderCommandEncoder, - MTLRenderPassDescriptor, MTLRenderPipelineDescriptor, MTLRenderPipelineState, - MTLResourceOptions, MTLStorageMode, MTLStoreAction, MTLTexture, MTLTextureDescriptor, - MTLTextureUsage, MTLViewport, + MTLCommandEncoder, MTLCommandQueue, MTLCompareFunction, MTLCompileOptions, + MTLCreateSystemDefaultDevice, MTLDepthStencilDescriptor, MTLDepthStencilState, MTLDevice, + MTLDrawable, MTLGPUFamily, MTLLibrary, MTLLoadAction, MTLPixelFormat, MTLPrimitiveType, + MTLRenderCommandEncoder, MTLRenderPassDescriptor, MTLRenderPipelineDescriptor, + MTLRenderPipelineState, MTLResourceOptions, MTLScissorRect, MTLStorageMode, MTLStoreAction, + MTLTexture, MTLTextureDescriptor, MTLTextureType, MTLTextureUsage, MTLViewport, }; #[cfg(any(test, feature = "bench-support", feature = "test-support"))] use objc2_metal::{MTLBlitCommandEncoder, MTLOrigin, MTLRegion, MTLSize}; use objc2_quartz_core::{CAMetalDrawable, CAMetalLayer}; use parking_lot::Mutex; -use std::{cell::Cell, mem, mem::MaybeUninit, ops::Range, ptr, slice, sync::Arc}; +use std::{ + cell::Cell, + mem, + mem::MaybeUninit, + ops::Range, + ptr, slice, + sync::Arc, + time::{Duration, Instant}, +}; #[cfg(not(feature = "runtime_shaders"))] const SHADERS_METALLIB: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/shaders.metallib")); @@ -41,6 +51,20 @@ const SHADERS_SOURCE_FILE: &str = include_str!(concat!(env!("OUT_DIR"), "/stitch /// Metal requires the offset a buffer is bound at to be 256-byte aligned. const INSTANCE_BUFFER_ALIGNMENT: usize = 256; const MAX_INSTANCE_BUFFER_SIZE: usize = 256 * 1024 * 1024; +const INITIAL_INSTANCE_BUFFER_SIZE: usize = 2 * 1024 * 1024; +/// How long the instance buffer pool watches its peak use before deciding whether to shrink. +const INSTANCE_BUFFER_SETTLE: Duration = Duration::from_secs(5); +/// How long an offscreen target may go unused before its memory is given back. A frame with a +/// blur, layer or path on screen touches its targets every time, so only targets that nothing +/// on screen draws through are released. +const IDLE_RELEASE: Duration = Duration::from_secs(2); +/// How deeply filtered layers can nest before the innermost ones stop being filtered. Each depth +/// keeps one offscreen target, made the first time a frame nests that deep. +const LAYER_DEPTH: usize = 8; + +/// The widest and tallest the overscan may grow a frame drawn offscreen to, which every Metal GPU +/// can allocate. A window already larger keeps its size and gets no overscan. +const MAX_FRAME: i32 = 16384; pub type Context = Arc>; pub type Renderer = MetalRenderer; @@ -56,13 +80,18 @@ pub fn new_renderer( pub struct InstanceBufferPool { buffer_size: usize, buffers: Vec, + /// The most any frame has written since `window` began. + peak: usize, + window: Instant, } impl Default for InstanceBufferPool { fn default() -> Self { Self { - buffer_size: 2 * 1024 * 1024, + buffer_size: INITIAL_INSTANCE_BUFFER_SIZE, buffers: Vec::new(), + peak: 0, + window: Instant::now(), } } } @@ -111,6 +140,29 @@ impl InstanceBufferPool { self.buffers.push(buffer) } } + + /// Shrinks the buffers once every frame over the last `INSTANCE_BUFFER_SETTLE` has needed + /// under a quarter of one. `used` is what the frame just encoded wrote, and the new size keeps + /// twice the peak so the next busy frame does not grow it straight back. Buffers still in + /// flight are dropped when they come back, since their size no longer matches. + pub(crate) fn settle(&mut self, used: usize) { + self.peak = self.peak.max(used); + let now = Instant::now(); + if now.duration_since(self.window) < INSTANCE_BUFFER_SETTLE { + return; + } + let peak = mem::take(&mut self.peak); + self.window = now; + + let buffer_size = (peak * 2) + .next_power_of_two() + .clamp(INITIAL_INSTANCE_BUFFER_SIZE, MAX_INSTANCE_BUFFER_SIZE); + if peak * 4 > self.buffer_size || buffer_size >= self.buffer_size { + return; + } + log::info!("decreased instance buffer size to {buffer_size}"); + self.reset(buffer_size); + } } enum DisplayLinkMode { @@ -138,12 +190,29 @@ pub struct MetalRenderer { monochrome_sprites_pipeline_state: Retained>, polychrome_sprites_pipeline_state: Retained>, surfaces_pipeline_state: Retained>, + backdrops_pipeline_state: Retained>, + backdrop_punch_pipeline_state: Retained>, + gaussian_pipeline_state: Retained>, + pyramid_down_pipeline_state: Retained>, + pyramid_up_pipeline_state: Retained>, + blit_pipeline_state: Retained>, + /// Writes transparent black under a scissor, for wiping the part of a layer target in use. + clear_pipeline_state: Retained>, + composite_pipeline_state: Retained>, + masked_pipeline_state: Retained>, + /// A pipeline per custom shader, built from its MSL translation the first time a frame draws + /// it. A shader that failed to build is kept as `None`, so it is not built again every frame. + custom_pipeline_states: + FxHashMap>>>, depth_write_state: Retained>, depth_test_state: Retained>, depth_texture: Option>>, instance_buffer_pool: Arc>, sprite_atlas: Arc, core_video_texture_cache: CFRetained, + filter_targets: FilterTargets, + /// When the frame being encoded started, which stamps every offscreen target it touches. + frame_time: Instant, /// Offscreen render target reused across `render_scene` calls when /// rendering headlessly without reading pixels back. #[cfg(any(test, feature = "bench-support", feature = "test-support"))] @@ -355,6 +424,91 @@ impl MetalRenderer { true, )?; + // A backdrop mixes the blurred copy into what it covers rather than laying it over: + // the punch scales the destination by `1 - k`, the draw after it adds `blurred * k`. + // Laying it over cost a see-through window its transparency. + let backdrops_pipeline_state = build_filter_pipeline_state( + &device, + &library, + "backdrops", + "backdrop_vertex", + "backdrop_fragment", + MTLPixelFormat::BGRA8Unorm, + FilterBlend::Add, + )?; + let backdrop_punch_pipeline_state = build_filter_pipeline_state( + &device, + &library, + "backdrop_punch", + "backdrop_vertex", + "backdrop_punch_fragment", + MTLPixelFormat::BGRA8Unorm, + FilterBlend::Punch, + )?; + let gaussian_pipeline_state = build_filter_pipeline_state( + &device, + &library, + "gaussian", + "filter_vertex", + "gaussian_fragment", + MTLPixelFormat::BGRA8Unorm, + FilterBlend::Replace, + )?; + let pyramid_down_pipeline_state = build_filter_pipeline_state( + &device, + &library, + "pyramid_down", + "filter_vertex", + "pyramid_down_fragment", + MTLPixelFormat::BGRA8Unorm, + FilterBlend::Replace, + )?; + let pyramid_up_pipeline_state = build_filter_pipeline_state( + &device, + &library, + "pyramid_up", + "filter_vertex", + "pyramid_up_fragment", + MTLPixelFormat::BGRA8Unorm, + FilterBlend::Replace, + )?; + let blit_pipeline_state = build_filter_pipeline_state( + &device, + &library, + "blit", + "filter_vertex", + "blit_fragment", + MTLPixelFormat::BGRA8Unorm, + FilterBlend::Replace, + )?; + let clear_pipeline_state = build_filter_pipeline_state( + &device, + &library, + "clear", + "filter_vertex", + "clear_fragment", + MTLPixelFormat::BGRA8Unorm, + FilterBlend::Replace, + )?; + let composite_pipeline_state = build_filter_pipeline_state( + &device, + &library, + "composite", + "filter_vertex", + "mask_fragment", + MTLPixelFormat::BGRA8Unorm, + FilterBlend::Over, + )?; + let masked_pipeline_state = build_filter_pipeline_state( + &device, + &library, + "masked", + "filter_vertex", + "mask_fragment", + MTLPixelFormat::BGRA8Unorm, + FilterBlend::Over, + )?; + let depth_write_state = build_depth_stencil_state(&device, true)?; let depth_test_state = build_depth_stencil_state(&device, false)?; @@ -395,12 +549,24 @@ impl MetalRenderer { monochrome_sprites_pipeline_state, polychrome_sprites_pipeline_state, surfaces_pipeline_state, + backdrops_pipeline_state, + backdrop_punch_pipeline_state, + gaussian_pipeline_state, + pyramid_down_pipeline_state, + pyramid_up_pipeline_state, + blit_pipeline_state, + clear_pipeline_state, + composite_pipeline_state, + masked_pipeline_state, + custom_pipeline_states: FxHashMap::default(), depth_write_state, depth_test_state, depth_texture: None, instance_buffer_pool, sprite_atlas, core_video_texture_cache, + filter_targets: FilterTargets::default(), + frame_time: Instant::now(), #[cfg(any(test, feature = "bench-support", feature = "test-support"))] headless_render_target: None, }) @@ -480,6 +646,72 @@ impl MetalRenderer { if let Some(layer) = &self.layer { layer.setDrawableSize(CGSize::new(size.width.0 as f64, size.height.0 as f64)); } + // Targets made for the old size are freed now rather than held until the next frame + // that draws a filter rebuilds them. + if self.filter_targets.size != size { + self.filter_targets = FilterTargets::default(); + } + } + + /// One filter target for a drawable of `viewport_size`, created if no frame has drawn + /// through it at that size since it was last released. + fn filter_texture( + &mut self, + target: FilterTarget, + viewport_size: Size, + ) -> Result>> { + if self.filter_targets.size != viewport_size { + self.filter_targets = FilterTargets { + size: viewport_size, + ..FilterTargets::default() + }; + } + let shrink = target.shrink() as usize; + // A level rounds up, so it covers the whole frame and its last texel can hang past it. + let width = (i32::from(viewport_size.width).max(1) as usize).div_ceil(shrink); + let height = (i32::from(viewport_size.height).max(1) as usize).div_ceil(shrink); + let now = self.frame_time; + let device = &self.device; + let slot = self.filter_targets.slot(target); + let scratch = match slot { + Some(scratch) => scratch, + None => { + let descriptor = MTLTextureDescriptor::new(); + descriptor.setTextureType(MTLTextureType::Type2D); + descriptor.setPixelFormat(MTLPixelFormat::BGRA8Unorm); + // SAFETY: Both dimensions are at least one and this descriptor creates a 2D texture. + unsafe { + descriptor.setWidth(width); + descriptor.setHeight(height); + } + descriptor.setStorageMode(MTLStorageMode::Private); + descriptor.setUsage(MTLTextureUsage::RenderTarget | MTLTextureUsage::ShaderRead); + let texture = device + .newTextureWithDescriptor(&descriptor) + .context("allocating filter target")?; + slot.insert(Scratch { texture, used: now }) + } + }; + scratch.used = now; + Ok(scratch.texture.clone()) + } + + /// Frees offscreen targets that no frame has drawn through for `IDLE_RELEASE`. Every frame + /// checks this itself, so a caller only needs it for a window that has stopped drawing. + pub fn release_idle_targets(&mut self) { + self.release_targets_idle_at(Instant::now()); + } + + /// Drops every offscreen target that no frame has drawn through within `IDLE_RELEASE` of + /// `now`. A command buffer retains what it encodes, so a target an earlier frame still uses + /// on the GPU stays alive until that frame completes. + fn release_targets_idle_at(&mut self, now: Instant) { + let idle = |used: Instant| now.duration_since(used) >= IDLE_RELEASE; + for slot in self.filter_targets.slots() { + if slot.as_ref().is_some_and(|scratch| idle(scratch.used)) { + *slot = None; + } + } } pub fn update_transparency(&mut self, transparent: bool) { @@ -581,7 +813,9 @@ impl MetalRenderer { )?; let instance_buffer_pool = self.instance_buffer_pool.clone(); + let used = writer.offset; let frame_resources = Cell::new(Some((writer.finish(), surface_textures))); + instance_buffer_pool.lock().settle(used); let block = RcBlock::new( move |_: ptr::NonNull>| { if let Some((instance_buffer, _surface_textures)) = frame_resources.take() { @@ -742,24 +976,53 @@ impl MetalRenderer { viewport_size: Size, surface_textures: &mut Vec>, ) -> Result>> { + self.frame_time = Instant::now(); let command_queue = self.command_queue.clone(); let command_buffer = command_queue .commandBuffer() .context("creating command buffer")?; let alpha = if self.opaque { 1. } else { 0. }; - let depth_texture = self.depth_texture_matching(texture)?; + let filtered = + filters_enabled() && (!scene.effects.is_empty() || !scene.backdrops.is_empty()); + // Backdrops read what the frame has drawn so far, which a drawable cannot be sampled from, + // so a frame carrying them is drawn offscreen and blitted back at the end. A backdrop near + // the right or bottom edge reads what the scene drew past it too, so that frame is drawn + // larger by the overscan, and the blit leaves the overscan behind. + let overscan = match filters_enabled() { + true => scene.overscan, + false => Size::default(), + }; + let overscanned = overscan.width.0 > 0 || overscan.height.0 > 0; + let mirrored = (filtered && !scene.backdrops.is_empty()) || overscanned; + let grow = |side: DevicePixels, past: DevicePixels| { + DevicePixels(side.0 + past.0.clamp(0, (MAX_FRAME - side.0).max(0))) + }; + let viewport_size = match mirrored { + true => size( + grow(viewport_size.width, overscan.width), + grow(viewport_size.height, overscan.height), + ), + false => viewport_size, + }; + let main_texture = match mirrored { + true => self.filter_texture(FilterTarget::Frame, viewport_size)?, + false => texture.retain(), + }; + let depth_texture = DEPTH_PREPASS + .then(|| self.depth_texture_matching(&main_texture)) + .transpose()?; - let command_encoder = new_command_encoder_for_texture( + let mut command_encoder = new_command_encoder_for_texture( &command_buffer, - texture, - &depth_texture, + &main_texture, + depth_texture.as_deref(), viewport_size, - MTLClearColor { + Some(MTLClearColor { red: 0., green: 0., blue: 0., alpha, - }, + }), )?; let depth_scale = quad_depth_scale(scene.quads.len()); // SAFETY: Metal copies both values, which match every vertex shader's @@ -777,28 +1040,110 @@ impl MetalRenderer { ); } - self.draw_opaque_quads(scene.quads.len(), instance_bindings, &command_encoder); - command_encoder.setDepthStencilState(Some(&self.depth_test_state)); + if DEPTH_PREPASS { + self.draw_opaque_quads(scene.quads.len(), instance_bindings, &command_encoder); + command_encoder.setDepthStencilState(Some(&self.depth_test_state)); + } + + let mut stack: Vec = Vec::new(); + // What each open layer will be composited through: neighbours that ask for the same filter + // share one target, so a list of separately blurred rows costs one pass, not one per row. + let mut spans: Vec> = Vec::new(); + // The part of each open layer's target that was wiped when it opened. A neighbour may only + // share the target when everything it draws lands inside it. + let mut wiped: Vec> = Vec::new(); let mut quad_cursor: u32 = 0; let mut path_tile_cursor = 0; for batch in scene.batches() { + let wanted = filtered + .then(|| scene.filtered(scene.batch_order(&batch))) + .flatten() + .map(|index| scene.filter_chain(index)) + .unwrap_or_default(); + let shared = stack + .iter() + .zip(wanted.iter()) + .take_while(|(open, next)| open == next) + .count(); + + let mut merged = false; + while stack.len() > shared { + if stack.len() == shared + 1 + && wanted.len() == stack.len() + && let Some(open) = stack.last_mut() + && let Some(span) = spans.last_mut() + { + let next = scene.effects[wanted[shared]]; + let layer = scene.effects[*open]; + if layer.can_merge_with(&next) + && wiped + .last() + .is_some_and(|wiped| covers(*wiped, layer_wipe(next))) + { + *open = wanted[shared]; + *span = span.union(&next.destination_clip()); + merged = true; + break; + } + } + + let index = stack.pop().expect("the stack is not empty"); + let layer = scene.effects[index]; + let clip = spans.pop().unwrap_or_else(|| layer.destination_clip()); + wiped.pop(); + + command_encoder.endEncoding(); + command_encoder = self.close_layer( + &command_buffer, + layer, + clip, + stack.len(), + &main_texture, + viewport_size, + depth_scale, + )?; + } + + for index in wanted.iter().skip(shared + usize::from(merged)) { + if stack.len() >= LAYER_DEPTH { + break; + } + let layer = scene.effects[*index]; + let depth = stack.len(); + + command_encoder.endEncoding(); + let target = self.filter_texture(FilterTarget::Layer(depth), viewport_size)?; + // Clearing the whole target writes every tile of a window-sized texture, which + // on a tiled GPU costs more than most layers draw. Only the source area, and the + // margin a blur reads past it, is ever read back, so only that is wiped. + command_encoder = + new_discarding_command_encoder(&command_buffer, &target, viewport_size)?; + bind_viewport(&command_encoder, viewport_size, depth_scale); + self.clear_within(&command_encoder, layer_wipe(layer), viewport_size); + stack.push(*index); + spans.push(layer.destination_clip()); + wiped.push(layer_wipe(layer)); + } + // 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 matches!(&batch, PrimitiveBatch::Quads(_)) { - (0.0, 1.0) - } else { - let depth = quad_depth(quad_cursor, depth_scale) as f64; - (depth, depth) - }; - command_encoder.setViewport(MTLViewport { - originX: 0.0, - originY: 0.0, - width: i32::from(viewport_size.width) as f64, - height: i32::from(viewport_size.height) as f64, - znear, - zfar, - }); + if DEPTH_PREPASS { + let (znear, zfar) = if matches!(&batch, PrimitiveBatch::Quads(_)) { + (0.0, 1.0) + } else { + let depth = quad_depth(quad_cursor, depth_scale) as f64; + (depth, depth) + }; + command_encoder.setViewport(MTLViewport { + originX: 0.0, + originY: 0.0, + width: i32::from(viewport_size.width) as f64, + height: i32::from(viewport_size.height) as f64, + znear, + zfar, + }); + } match batch { PrimitiveBatch::Shadows(range) => { @@ -808,6 +1153,18 @@ impl MetalRenderer { quad_cursor += range.len() as u32; self.draw_quads(range, instance_bindings, &command_encoder) } + PrimitiveBatch::Shaders { shader, range } => { + if let Some(pipeline) = self.custom_pipeline_state(shader) { + self.draw_custom_shaders( + &pipeline, + range, + instance_bindings, + viewport_size, + depth_scale, + &command_encoder, + ); + } + } PrimitiveBatch::Paths(range) => { let tiles_start = path_tile_cursor; path_tile_cursor += scene.paths[range] @@ -837,6 +1194,60 @@ impl MetalRenderer { instance_bindings, &command_encoder, ), + PrimitiveBatch::Backdrops(range) => { + if !filtered { + continue; + } + let backdrops = &scene.backdrops[range.clone()]; + let sigma = backdrops + .iter() + .fold(0., |widest: f32, backdrop| widest.max(backdrop.blur)); + // A backdrop samples the blur only within its own bounds, so the passes + // are scissored to the union of the batch's, grown by the kernel inside + // `blur_source`, rather than run over the whole frame. + let clip = backdrops + .iter() + .map(|backdrop| backdrop.bounds) + .reduce(|union, bounds| union.union(&bounds)); + + command_encoder.endEncoding(); + let source = self.backdrop_source( + &command_buffer, + &main_texture, + &wiped, + viewport_size, + clip.map(|clip| clip.dilate(BlurPasses::for_sigma(sigma).source_margin())), + )?; + let blurred = self.blur_source( + &command_buffer, + &source, + false, + sigma, + clip, + viewport_size, + )?; + let target = match stack.len().checked_sub(1) { + Some(depth) => { + self.filter_texture(FilterTarget::Layer(depth), viewport_size)? + } + None => main_texture.clone(), + }; + command_encoder = new_command_encoder_for_texture( + &command_buffer, + &target, + None, + viewport_size, + None, + )?; + bind_viewport(&command_encoder, viewport_size, depth_scale); + self.draw_backdrops( + range, + instance_bindings, + &blurred, + viewport_size, + &command_encoder, + ); + } PrimitiveBatch::Surfaces(range) => { if let Err(error) = self.draw_surfaces( &scene.surfaces[range.clone()], @@ -853,11 +1264,559 @@ impl MetalRenderer { } } + while let Some(index) = stack.pop() { + let layer = scene.effects[index]; + let clip = spans.pop().unwrap_or_else(|| layer.destination_clip()); + wiped.pop(); + + command_encoder.endEncoding(); + command_encoder = self.close_layer( + &command_buffer, + layer, + clip, + stack.len(), + &main_texture, + viewport_size, + depth_scale, + )?; + } + command_encoder.endEncoding(); + if mirrored { + self.filter_pass( + &command_buffer, + &self.blit_pipeline_state, + &main_texture, + texture, + None, + None, + )?; + } + + self.release_targets_idle_at(self.frame_time); + Ok(command_buffer) } + /// Blurs a filtered layer that has just closed, when its filter asks for a blur, and + /// composites it as the first draw of a pass that resumes its parent. The caller carries on + /// drawing through the encoder it returns. `depth` is the closed layer's own nesting depth. + fn close_layer( + &mut self, + command_buffer: &ProtocolObject, + layer: LayerEffect, + clip: Bounds, + depth: usize, + main_texture: &ProtocolObject, + viewport_size: Size, + depth_scale: f32, + ) -> Result>> { + let source = self.filter_texture( + FilterTarget::Layer(depth.min(LAYER_DEPTH - 1)), + viewport_size, + )?; + let onto = match depth.checked_sub(1) { + Some(parent) => self.filter_texture( + FilterTarget::Layer(parent.min(LAYER_DEPTH - 1)), + viewport_size, + )?, + None => main_texture.retain(), + }; + let blurred = match layer.filter.blurs() { + true => self.blur_source( + command_buffer, + &source, + true, + layer.filter.blur, + Some(layer.blur_bounds(clip)), + viewport_size, + )?, + false => source, + }; + let encoder = + new_command_encoder_for_texture(command_buffer, &onto, None, viewport_size, None)?; + bind_viewport(&encoder, viewport_size, depth_scale); + self.composite_layer(&encoder, &blurred, layer, clip, viewport_size); + Ok(encoder) + } + + /// Writes transparent black over `bounds` of the encoder's target and lifts the scissor + /// again, so the draws after it see the whole target. + fn clear_within( + &self, + encoder: &ProtocolObject, + bounds: Bounds, + viewport_size: Size, + ) { + let Some(within) = Self::scissor(bounds, viewport_size, 1) else { + return; + }; + encoder.setRenderPipelineState(&self.clear_pipeline_state); + encoder.setScissorRect(within); + // SAFETY: `filter_vertex` builds the four strip vertices from their ids and reads no buffer. + unsafe { + encoder.drawPrimitives_vertexStart_vertexCount(MTLPrimitiveType::TriangleStrip, 0, 4); + } + encoder.setScissorRect(whole_scissor(viewport_size)); + } + + /// Clamps a region to the target it is drawn into, shrunk to the blur step it runs at. + fn scissor( + bounds: Bounds, + viewport_size: Size, + shrink: u32, + ) -> Option { + let shrink = shrink as f32; + let width = (i32::from(viewport_size.width) as f32 / shrink).ceil(); + let height = (i32::from(viewport_size.height) as f32 / shrink).ceil(); + let left = (bounds.origin.x.0 / shrink).floor().clamp(0., width); + let top = (bounds.origin.y.0 / shrink).floor().clamp(0., height); + let right = ((bounds.origin.x.0 + bounds.size.width.0) / shrink) + .ceil() + .clamp(left, width); + let bottom = ((bounds.origin.y.0 + bounds.size.height.0) / shrink) + .ceil() + .clamp(top, height); + if right <= left || bottom <= top { + return None; + } + + Some(MTLScissorRect { + x: left as usize, + y: top as usize, + width: (right - left) as usize, + height: (bottom - top) as usize, + }) + } + + /// Draws one full-screen pass of a filter from `source` into `target`. + fn filter_pass( + &self, + command_buffer: &ProtocolObject, + pipeline: &ProtocolObject, + source: &ProtocolObject, + target: &ProtocolObject, + params: Option<&BlurParams>, + within: Option, + ) -> Result<()> { + let size = size( + DevicePixels(target.width() as i32), + DevicePixels(target.height() as i32), + ); + // A scissored pass leaves the rest of its target alone, and the passes after it read only + // what the passes before them wrote. Clearing the whole target first is a full write of a + // window-sized texture, which on a tiled GPU costs more than a narrow blur itself. + let encoder = match within { + Some(_) => new_discarding_command_encoder(command_buffer, target, size)?, + None => new_command_encoder_for_texture( + command_buffer, + target, + None, + size, + Some(MTLClearColor { + red: 0., + green: 0., + blue: 0., + alpha: 0., + }), + )?, + }; + encoder.setRenderPipelineState(pipeline); + // SAFETY: The source texture and the copied parameters match the filter shader's slots. + // Metal retains the texture until the pass completes. + unsafe { + encoder.setFragmentTexture_atIndex(Some(source), FilterInputIndex::Source as usize); + if let Some(params) = params { + encoder.setFragmentBytes_length_atIndex( + ptr::NonNull::from(params).cast(), + mem::size_of::(), + FilterInputIndex::Params as usize, + ); + } + } + if let Some(within) = within { + encoder.setScissorRect(within); + } + // SAFETY: `filter_vertex` builds the four strip vertices from their ids and reads no buffer. + unsafe { + encoder.drawPrimitives_vertexStart_vertexCount(MTLPrimitiveType::TriangleStrip, 0, 4); + } + encoder.endEncoding(); + Ok(()) + } + + /// Blurs a source and returns the target holding the result, at full size. A `spare` source + /// is a layer nothing reads again, so the blur writes its result back into it rather than + /// into a full-size target of its own. + fn blur_source( + &mut self, + command_buffer: &ProtocolObject, + source: &ProtocolObject, + spare: bool, + sigma: f32, + clip: Option>, + viewport_size: Size, + ) -> Result>> { + match BlurPasses::for_sigma(sigma) { + BlurPasses::Gaussian(sigma) => { + self.gaussian_blur(command_buffer, source, spare, sigma, clip, viewport_size) + } + BlurPasses::Pyramid(pyramid) => { + self.pyramid_blur(command_buffer, source, spare, pyramid, clip, viewport_size) + } + } + } + + /// Blurs a source across into the scratch target and down into level zero, or back into a + /// `spare` source, both at full size. The pass across covers the clip grown by the kernel, + /// since the pass down reads that far above and below it. + fn gaussian_blur( + &mut self, + command_buffer: &ProtocolObject, + source: &ProtocolObject, + spare: bool, + sigma: f32, + clip: Option>, + viewport_size: Size, + ) -> Result>> { + let extent = [ + i32::from(viewport_size.width) as f32, + i32::from(viewport_size.height) as f32, + ]; + let across = BlurParams { + direction: [1., 0.], + extent, + radius: sigma, + pad: 0., + }; + let down = BlurParams { + direction: [0., 1.], + extent, + radius: sigma, + pad: 0., + }; + let scratch = self.filter_texture(FilterTarget::Scratch, viewport_size)?; + let settled = match spare { + true => source.retain(), + false => self.filter_texture(FilterTarget::Level(0), viewport_size)?, + }; + let within = |margin: f32| { + clip.and_then(|clip| Self::scissor(clip.dilate(ScaledPixels(margin)), viewport_size, 1)) + }; + let reach = (sigma * GAUSSIAN_REACH).ceil() + 1.; + + self.filter_pass( + command_buffer, + &self.gaussian_pipeline_state, + source, + &scratch, + Some(&across), + within(reach), + )?; + self.filter_pass( + command_buffer, + &self.gaussian_pipeline_state, + &scratch, + &settled, + Some(&down), + within(1.), + )?; + Ok(settled) + } + + /// Blurs a source with a [`Pyramid`]: down to the deepest level, a gaussian across and down + /// there, and back up to full size. Returns the target holding the result: level zero, or a + /// `spare` source. + fn pyramid_blur( + &mut self, + command_buffer: &ProtocolObject, + source: &ProtocolObject, + spare: bool, + pyramid: Pyramid, + clip: Option>, + viewport_size: Size, + ) -> Result>> { + let deepest = pyramid.levels; + let frame = ( + i32::from(viewport_size.width) as f32, + i32::from(viewport_size.height) as f32, + ); + // A pass reads a level of its own, so each gets its own parameters, which carry how + // much of that level holds the frame. + let params = |level: usize, direction: [f32; 2], radius: f32| { + let shrink = (1u32 << level) as f32; + BlurParams { + direction, + extent: [frame.0 / shrink, frame.1 / shrink], + radius, + pad: 0., + } + }; + let reads: Vec = (0..=deepest) + .map(|level| params(level, [0., 0.], 0.)) + .collect(); + let across = params(deepest, [1., 0.], pyramid.sigma); + let along = params(deepest, [0., 1.], pyramid.sigma); + let levels: Vec>> = (0..=deepest) + .map(|level| match (level, spare) { + (0, true) => Ok(source.retain()), + _ => self.filter_texture(FilterTarget::Level(level), viewport_size), + }) + .collect::>()?; + let spread = self.filter_texture(FilterTarget::Spread(deepest), viewport_size)?; + // A pass leaves what lies past its scissor undefined, so each writes the clip grown by + // everything the passes after it read. + let within = |level: usize, margin: f32| { + clip.and_then(|clip| { + Self::scissor(clip.dilate(ScaledPixels(margin)), viewport_size, 1 << level) + }) + }; + + for level in 1..=deepest { + let from: &ProtocolObject = match level { + 1 => source, + _ => &levels[level - 1], + }; + self.filter_pass( + command_buffer, + &self.pyramid_down_pipeline_state, + from, + &levels[level], + Some(&reads[level - 1]), + within(level, pyramid.down_margin(level)), + )?; + } + self.filter_pass( + command_buffer, + &self.gaussian_pipeline_state, + &levels[deepest], + &spread, + Some(&across), + within(deepest, pyramid.across_margin()), + )?; + self.filter_pass( + command_buffer, + &self.gaussian_pipeline_state, + &spread, + &levels[deepest], + Some(&along), + within(deepest, pyramid.along_margin()), + )?; + for level in (0..deepest).rev() { + self.filter_pass( + command_buffer, + &self.pyramid_up_pipeline_state, + &levels[level + 1], + &levels[level], + Some(&reads[level + 1]), + within(level, pyramid.up_margin(level)), + )?; + } + Ok(levels[0].clone()) + } + + /// Draws a filtered layer back into its parent through `encoder`, clipped to the layer's bounds, + /// and leaves the encoder open with the scissor lifted for the parent's own draws. + fn composite_layer( + &self, + encoder: &ProtocolObject, + source: &ProtocolObject, + layer: LayerEffect, + clip: Bounds, + viewport_size: Size, + ) { + let Some(within) = Self::scissor(layer.destination_scissor_bounds(clip), viewport_size, 1) + else { + return; + }; + let masked = layer.filter.fades(); + encoder.setRenderPipelineState(match masked { + true => &self.masked_pipeline_state, + false => &self.composite_pipeline_state, + }); + let params = mask_params(layer, clip); + // SAFETY: The layer texture and the copied viewport and mask parameters match the mask + // shader's slots. Metal retains the texture until the pass completes. + unsafe { + encoder.setFragmentTexture_atIndex(Some(source), FilterInputIndex::Source as usize); + encoder.setFragmentBytes_length_atIndex( + ptr::NonNull::from(&viewport_size).cast(), + mem::size_of_val(&viewport_size), + FilterInputIndex::ViewportSize as usize, + ); + encoder.setFragmentBytes_length_atIndex( + ptr::NonNull::from(¶ms).cast(), + mem::size_of::(), + FilterInputIndex::Params as usize, + ); + } + encoder.setScissorRect(within); + // SAFETY: `filter_vertex` builds the four strip vertices from their ids and reads no buffer. + unsafe { + encoder.drawPrimitives_vertexStart_vertexCount(MTLPrimitiveType::TriangleStrip, 0, 4); + } + encoder.setScissorRect(whole_scissor(viewport_size)); + } + + /// Flattens open layers in source coordinates without changing their eventual composites. + fn backdrop_source( + &mut self, + command_buffer: &ProtocolObject, + frame: &ProtocolObject, + wiped: &[Bounds], + viewport_size: Size, + clip: Option>, + ) -> Result>> { + let depth = wiped.len(); + if depth == 0 { + return Ok(frame.retain()); + } + let target = self.filter_texture(FilterTarget::Backdrop, viewport_size)?; + let bounds = Bounds::new( + point(ScaledPixels(0.), ScaledPixels(0.)), + size( + ScaledPixels(viewport_size.width.0 as f32), + ScaledPixels(viewport_size.height.0 as f32), + ), + ); + let params = MaskParams { + source_bounds: bounds, + fade_bounds: bounds, + scale: 1., + ..Default::default() + }; + // Each open layer is read only where it was wiped when it opened, since the rest of its + // target still holds whatever an earlier layer left there. + let mut sources = vec![(frame.retain(), clip)]; + sources.extend( + (0..depth) + .map(|level| { + let within = match clip { + Some(clip) => clip.intersect(&wiped[level]), + None => wiped[level], + }; + Ok(( + self.filter_texture(FilterTarget::Layer(level), viewport_size)?, + Some(within), + )) + }) + .collect::>>()?, + ); + let encoder = new_command_encoder_for_texture( + command_buffer, + &target, + None, + viewport_size, + Some(MTLClearColor { + red: 0., + green: 0., + blue: 0., + alpha: 0., + }), + )?; + encoder.setRenderPipelineState(&self.composite_pipeline_state); + // SAFETY: The viewport and mask parameters are copied from live values into the mask + // shader's slots. + unsafe { + encoder.setFragmentBytes_length_atIndex( + ptr::NonNull::from(&viewport_size).cast(), + mem::size_of_val(&viewport_size), + FilterInputIndex::ViewportSize as usize, + ); + encoder.setFragmentBytes_length_atIndex( + ptr::NonNull::from(¶ms).cast(), + mem::size_of_val(¶ms), + FilterInputIndex::Params as usize, + ); + } + for (source, within) in sources { + let scissor = match within { + Some(within) => match Self::scissor(within, viewport_size, 1) { + Some(scissor) => scissor, + None => continue, + }, + None => whole_scissor(viewport_size), + }; + encoder.setScissorRect(scissor); + // SAFETY: The source texture matches the mask shader's slot and Metal retains it until + // the pass completes. `filter_vertex` builds the four strip vertices from their ids. + unsafe { + encoder + .setFragmentTexture_atIndex(Some(&source), FilterInputIndex::Source as usize); + encoder.drawPrimitives_vertexStart_vertexCount( + MTLPrimitiveType::TriangleStrip, + 0, + 4, + ); + } + } + encoder.endEncoding(); + Ok(target) + } + + fn draw_backdrops( + &self, + backdrops: Range, + instance_bindings: &InstanceBindings, + source: &ProtocolObject, + viewport_size: Size, + command_encoder: &ProtocolObject, + ) { + if backdrops.is_empty() { + return; + } + + command_encoder.setRenderPipelineState(&self.backdrop_punch_pipeline_state); + // SAFETY: The scene's backdrop range matches the uploaded shader layouts and slots. Metal + // retains the buffers and texture, writer.finish publishes their writes, and viewport + // bytes are copied. + unsafe { + command_encoder.setVertexBuffer_offset_atIndex( + Some(&instance_bindings.backdrops.buffer), + instance_bindings.backdrops.offset, + FilterInputIndex::Backdrops as usize, + ); + command_encoder.setFragmentBuffer_offset_atIndex( + Some(&instance_bindings.backdrops.buffer), + instance_bindings.backdrops.offset, + FilterInputIndex::Backdrops as usize, + ); + command_encoder.setVertexBytes_length_atIndex( + ptr::NonNull::from(&viewport_size).cast(), + mem::size_of_val(&viewport_size), + FilterInputIndex::ViewportSize as usize, + ); + command_encoder.setFragmentBytes_length_atIndex( + ptr::NonNull::from(&viewport_size).cast(), + mem::size_of_val(&viewport_size), + FilterInputIndex::ViewportSize as usize, + ); + command_encoder + .setFragmentTexture_atIndex(Some(source), FilterInputIndex::Source as usize); + // The hole first, the blurred copy into it second: together they are + // `dst = mix(dst, blurred, k)`, which leaves a see-through window as clear as it was. + command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( + MTLPrimitiveType::TriangleStrip, + 0, + 4, + backdrops.len(), + backdrops.start, + ); + } + command_encoder.setRenderPipelineState(&self.backdrops_pipeline_state); + // SAFETY: The same bindings serve the second pipeline, which shares the backdrop shader's slots. + unsafe { + command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( + MTLPrimitiveType::TriangleStrip, + 0, + 4, + backdrops.len(), + backdrops.start, + ); + } + } + fn depth_texture_matching( &mut self, target: &ProtocolObject, @@ -1044,6 +2003,101 @@ impl MetalRenderer { } } + /// The pipeline of a custom shader, built the first time a frame draws it. `None` means it + /// failed to build, which is logged once and leaves its instances undrawn. + fn custom_pipeline_state( + &mut self, + shader: ShaderId, + ) -> Option>> { + if let Some(pipeline) = self.custom_pipeline_states.get(&shader) { + return pipeline.clone(); + } + let pipeline = + build_custom_pipeline_state(&self.device, shader, MTLPixelFormat::BGRA8Unorm) + .inspect_err(|error| log::error!("{error:#}")) + .ok(); + self.custom_pipeline_states.insert(shader, pipeline.clone()); + pipeline + } + + fn draw_custom_shaders( + &self, + pipeline: &ProtocolObject, + shaders: Range, + instance_bindings: &InstanceBindings, + viewport_size: Size, + depth_scale: f32, + command_encoder: &ProtocolObject, + ) { + if shaders.is_empty() { + return; + } + + // Quads blend straight alpha on Metal, so the prelude leaves its colour unpremultiplied. + let globals = CustomShaderGlobals { + viewport_size: [ + i32::from(viewport_size.width) as f32, + i32::from(viewport_size.height) as f32, + ], + premultiplied_alpha: 0, + pad: 0, + }; + let buffer = &instance_bindings.shaders; + // naga reads the length of the instance buffer from here, though nothing it emits for + // the prelude bounds checks against it. + let length = buffer.buffer.length().saturating_sub(buffer.offset) as u32; + + command_encoder.setRenderPipelineState(pipeline); + let globals_size = mem::size_of::(); + let globals_bytes = ptr::NonNull::from(&globals).cast(); + let length_size = mem::size_of::(); + let length_bytes = ptr::NonNull::from(&length).cast(); + // SAFETY: The globals and length are copied from live values, and the instance range lies + // within the scene's shader instances at an aligned offset, all in the slots naga's MSL + // reads. Metal retains the buffer, and writer.finish publishes its writes. + unsafe { + command_encoder.setVertexBytes_length_atIndex( + globals_bytes, + globals_size, + gpui::MslShader::GLOBALS_BUFFER as usize, + ); + command_encoder.setFragmentBytes_length_atIndex( + globals_bytes, + globals_size, + gpui::MslShader::GLOBALS_BUFFER as usize, + ); + command_encoder.setVertexBytes_length_atIndex( + length_bytes, + length_size, + gpui::MslShader::SIZES_BUFFER as usize, + ); + command_encoder.setFragmentBytes_length_atIndex( + length_bytes, + length_size, + gpui::MslShader::SIZES_BUFFER as usize, + ); + command_encoder.setVertexBuffer_offset_atIndex( + Some(&buffer.buffer), + buffer.offset, + gpui::MslShader::INSTANCES_BUFFER as usize, + ); + command_encoder.setFragmentBuffer_offset_atIndex( + Some(&buffer.buffer), + buffer.offset, + gpui::MslShader::INSTANCES_BUFFER as usize, + ); + command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( + MTLPrimitiveType::TriangleStrip, + 0, + 4, + shaders.len(), + shaders.start, + ); + } + // The globals and instances took the slots of the viewport and depth scale. + bind_viewport(command_encoder, viewport_size, depth_scale); + } + fn draw_underlines( &self, underlines: Range, @@ -1284,12 +2338,105 @@ impl MetalRenderer { } } +/// Layer filters can be switched off from the environment to tell a rendering problem from a +/// compositing one. +fn filters_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("GPUI_FILTERS").as_deref() != Ok("0")) +} + +/// Whether `outer` holds all of `inner`. +fn covers(outer: Bounds, inner: Bounds) -> bool { + outer.origin.x <= inner.origin.x + && outer.origin.y <= inner.origin.y + && outer.bottom_right().x >= inner.bottom_right().x + && outer.bottom_right().y >= inner.bottom_right().y +} + +/// The part of a layer's target that has to start transparent: its source area and, for a blurred +/// layer, as far again as the blur reads past it, plus a pixel for the rounding of the scissor. +fn layer_wipe(layer: LayerEffect) -> Bounds { + let margin = match layer.filter.blurs() { + true => BlurPasses::for_sigma(layer.filter.blur).source_margin(), + false => ScaledPixels(0.), + }; + layer.source_bounds.dilate(margin + ScaledPixels(1.)) +} + +/// Binds the viewport and quad depth scale the primitive shaders read at `GlobalInputIndex`. A +/// pass starts without them, and the custom shader globals and instances share their slots. +fn bind_viewport( + encoder: &ProtocolObject, + viewport_size: Size, + depth_scale: f32, +) { + // SAFETY: Metal copies both values, which match every vertex shader's + // `GlobalInputIndex_ViewportSize` and `GlobalInputIndex_DepthScale` arguments. + unsafe { + encoder.setVertexBytes_length_atIndex( + ptr::NonNull::from(&viewport_size).cast(), + mem::size_of_val(&viewport_size), + GlobalInputIndex::ViewportSize as usize, + ); + encoder.setVertexBytes_length_atIndex( + ptr::NonNull::from(&depth_scale).cast(), + mem::size_of_val(&depth_scale), + GlobalInputIndex::DepthScale as usize, + ); + } +} + +/// A scissor over the whole target, for lifting one that was set for a single draw. +fn whole_scissor(viewport_size: Size) -> MTLScissorRect { + MTLScissorRect { + x: 0, + y: 0, + width: i32::from(viewport_size.width).max(0) as usize, + height: i32::from(viewport_size.height).max(0) as usize, + } +} + +/// An encoder on `texture` that keeps nothing it held, for a pass that writes everything it later +/// reads. +fn new_discarding_command_encoder( + command_buffer: &ProtocolObject, + texture: &ProtocolObject, + viewport_size: Size, +) -> Result>> { + let render_pass_descriptor = MTLRenderPassDescriptor::new(); + // SAFETY: Index zero is within the render pass's color attachment array. + let color_attachment = unsafe { + render_pass_descriptor + .colorAttachments() + .objectAtIndexedSubscript(0) + }; + color_attachment.setTexture(Some(texture)); + color_attachment.setLoadAction(MTLLoadAction::DontCare); + color_attachment.setStoreAction(MTLStoreAction::Store); + + let command_encoder = command_buffer + .renderCommandEncoderWithDescriptor(&render_pass_descriptor) + .context("creating render command encoder")?; + command_encoder.setViewport(MTLViewport { + originX: 0.0, + originY: 0.0, + width: i32::from(viewport_size.width) as f64, + height: i32::from(viewport_size.height) as f64, + znear: 0.0, + zfar: 1.0, + }); + Ok(command_encoder) +} + +/// Starts a render pass into `texture`, with a depth attachment only when `depth_texture` is given. +/// The pass descriptor retains the textures, so they may be temporaries the caller drops before +/// the encoder ends. fn new_command_encoder_for_texture( command_buffer: &ProtocolObject, texture: &ProtocolObject, - depth_texture: &ProtocolObject, + depth_texture: Option<&ProtocolObject>, viewport_size: Size, - clear_color: MTLClearColor, + clear_color: Option, ) -> Result>> { let render_pass_descriptor = MTLRenderPassDescriptor::new(); // SAFETY: Index zero is within the render pass's color attachment array. @@ -1300,15 +2447,21 @@ 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); + if let Some(clear_color) = clear_color { + color_attachment.setLoadAction(MTLLoadAction::Clear); + color_attachment.setClearColor(clear_color); + } else { + color_attachment.setLoadAction(MTLLoadAction::Load); + } - let depth_attachment = render_pass_descriptor.depthAttachment(); - depth_attachment.setTexture(Some(depth_texture)); - depth_attachment.setLoadAction(MTLLoadAction::Clear); - depth_attachment.setClearDepth(0.0); - // The depth buffer is only needed within this pass. - depth_attachment.setStoreAction(MTLStoreAction::DontCare); + if let Some(depth_texture) = depth_texture { + let depth_attachment = render_pass_descriptor.depthAttachment(); + depth_attachment.setTexture(Some(depth_texture)); + depth_attachment.setLoadAction(MTLLoadAction::Clear); + depth_attachment.setClearDepth(0.0); + // The depth buffer is only needed within this pass. + depth_attachment.setStoreAction(MTLStoreAction::DontCare); + } let command_encoder = command_buffer .renderCommandEncoderWithDescriptor(&render_pass_descriptor) @@ -1356,6 +2509,208 @@ fn read_texture_to_image(texture: &ProtocolObject) -> Result>, + used: Instant, +} + +/// One of the offscreen targets filters draw through. +#[derive(Clone, Copy)] +enum FilterTarget { + /// The accumulated background of all open layers before a backdrop samples it. + Backdrop, + /// The frame itself, drawn offscreen so a backdrop can sample what lies under it. + Frame, + /// The target a filtered layer is drawn into, by nesting depth. + Layer(usize), + /// One blur level, the frame's size halved as many times as its index and rounded up, so the + /// last texel of a level can hang past the frame's edge. Level zero holds a finished blur. + Level(usize), + /// Where a gaussian keeps its pass across before the pass down. + Scratch, + /// Where the gaussian at the deepest level of a pyramid keeps its pass across, at that + /// level's size. + Spread(usize), +} + +impl FilterTarget { + /// How many times smaller than the frame the target is on each side. + fn shrink(self) -> u32 { + match self { + Self::Level(level) | Self::Spread(level) => 1 << level, + Self::Frame | Self::Layer(_) | Self::Scratch | Self::Backdrop => 1, + } + } +} + +/// Offscreen targets a frame needs to blur and mask what it has drawn, all made for one +/// drawable size. Each one is allocated the first time a frame draws through it, so a frame +/// with one shallow blur pays for the targets it touches rather than for every depth and level. +#[derive(Default)] +struct FilterTargets { + size: Size, + frame: Option, + backdrop: Option, + layers: [Option; LAYER_DEPTH], + levels: [Option; BLUR_LEVELS + 1], + spreads: [Option; BLUR_LEVELS + 1], + scratch: Option, +} + +impl FilterTargets { + fn slot(&mut self, target: FilterTarget) -> &mut Option { + match target { + FilterTarget::Backdrop => &mut self.backdrop, + FilterTarget::Frame => &mut self.frame, + FilterTarget::Layer(depth) => &mut self.layers[depth], + FilterTarget::Level(level) => &mut self.levels[level], + FilterTarget::Scratch => &mut self.scratch, + FilterTarget::Spread(level) => &mut self.spreads[level], + } + } + + fn slots(&mut self) -> impl Iterator> { + std::iter::once(&mut self.frame) + .chain(std::iter::once(&mut self.backdrop)) + .chain(self.layers.iter_mut()) + .chain(self.levels.iter_mut()) + .chain(self.spreads.iter_mut()) + .chain(std::iter::once(&mut self.scratch)) + } +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub struct BlurParams { + pub direction: [f32; 2], + /// How many texels of the texture the pass reads hold the frame. A blur level rounds its + /// size up, so its last texel can hang past the frame's edge. + pub extent: [f32; 2], + pub radius: f32, + pub pad: f32, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub struct MaskParams { + pub source_bounds: Bounds, + pub fade_bounds: Bounds, + pub transform_origin: [f32; 2], + pub translation: [f32; 2], + pub scale: f32, + pub fade_top: f32, + pub fade_bottom: f32, + pub fade_left: f32, + pub fade_right: f32, + pub pad: f32, +} + +const _: () = { + assert!(mem::size_of::() == 18 * mem::size_of::()); + assert!(mem::offset_of!(MaskParams, source_bounds) == 0); + assert!(mem::offset_of!(MaskParams, fade_bounds) == 16); + assert!(mem::offset_of!(MaskParams, transform_origin) == 32); + assert!(mem::offset_of!(MaskParams, translation) == 40); + assert!(mem::offset_of!(MaskParams, scale) == 48); + assert!(mem::offset_of!(MaskParams, fade_top) == 52); + assert!(mem::offset_of!(MaskParams, fade_bottom) == 56); + assert!(mem::offset_of!(MaskParams, fade_left) == 60); + assert!(mem::offset_of!(MaskParams, fade_right) == 64); + assert!(mem::offset_of!(MaskParams, pad) == 68); +}; + +#[repr(C)] +pub enum FilterInputIndex { + Backdrops = 2, + ViewportSize = 3, + Params = 4, + Source = 5, +} + +fn mask_params(layer: LayerEffect, destination_clip: Bounds) -> MaskParams { + MaskParams { + source_bounds: if layer.filter.transforms() { + layer.source_bounds + } else { + destination_clip + }, + // Preserve the existing Metal fade clip for unscaled layers. A scaled layer must apply + // the fade in source coordinates before the final transform. + fade_bounds: if layer.filter.transforms() { + layer.source_bounds + } else { + destination_clip + }, + transform_origin: [layer.transform_origin.x.0, layer.transform_origin.y.0], + translation: [layer.filter.translate.x.0, layer.filter.translate.y.0], + scale: layer.filter.scale, + fade_top: layer.filter.fade_top, + fade_bottom: layer.filter.fade_bottom, + fade_left: layer.filter.fade_left, + fade_right: layer.filter.fade_right, + pad: 0.0, + } +} + +/// How a filter pipeline lands on what it covers. +#[derive(Clone, Copy, PartialEq)] +enum FilterBlend { + /// Replaces the destination outright. + Replace, + /// Premultiplied source-over. + Over, + /// Adds itself to the destination, for the second half of a backdrop's mix. + Add, + /// Keeps `1 - src.a` of the destination and contributes nothing of its own, for the first + /// half of a backdrop's mix. + Punch, +} + +fn build_filter_pipeline_state( + device: &ProtocolObject, + library: &ProtocolObject, + label: &str, + vertex_fn_name: &str, + fragment_fn_name: &str, + pixel_format: MTLPixelFormat, + blend: FilterBlend, +) -> Result>> { + let vertex_fn = library + .newFunctionWithName(&NSString::from_str(vertex_fn_name)) + .with_context(|| format!("locating vertex function {vertex_fn_name}"))?; + let fragment_fn = library + .newFunctionWithName(&NSString::from_str(fragment_fn_name)) + .with_context(|| format!("locating fragment function {fragment_fn_name}"))?; + + let descriptor = MTLRenderPipelineDescriptor::new(); + descriptor.setLabel(Some(&NSString::from_str(label))); + descriptor.setVertexFunction(Some(vertex_fn.as_ref())); + descriptor.setFragmentFunction(Some(fragment_fn.as_ref())); + // SAFETY: Index zero is within the pipeline's color attachment array. + let color_attachment = unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) }; + color_attachment.setPixelFormat(pixel_format); + color_attachment.setBlendingEnabled(blend != FilterBlend::Replace); + if let Some((source, destination)) = match blend { + FilterBlend::Replace => None, + FilterBlend::Over => Some((MTLBlendFactor::One, MTLBlendFactor::OneMinusSourceAlpha)), + FilterBlend::Add => Some((MTLBlendFactor::One, MTLBlendFactor::One)), + FilterBlend::Punch => Some((MTLBlendFactor::Zero, MTLBlendFactor::OneMinusSourceAlpha)), + } { + color_attachment.setRgbBlendOperation(MTLBlendOperation::Add); + color_attachment.setAlphaBlendOperation(MTLBlendOperation::Add); + color_attachment.setSourceRGBBlendFactor(source); + color_attachment.setSourceAlphaBlendFactor(source); + color_attachment.setDestinationRGBBlendFactor(destination); + color_attachment.setDestinationAlphaBlendFactor(destination); + } + + device + .newRenderPipelineStateWithDescriptor_error(&descriptor) + .with_context(|| format!("creating {label} render pipeline")) +} + fn build_pipeline_state( device: &ProtocolObject, library: &ProtocolObject, @@ -1386,13 +2741,72 @@ fn build_pipeline_state( color_attachment.setSourceAlphaBlendFactor(MTLBlendFactor::One); color_attachment.setDestinationRGBBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); color_attachment.setDestinationAlphaBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); - descriptor.setDepthAttachmentPixelFormat(MTLPixelFormat::Depth32Float); + if DEPTH_PREPASS { + descriptor.setDepthAttachmentPixelFormat(MTLPixelFormat::Depth32Float); + } device .newRenderPipelineStateWithDescriptor_error(&descriptor) .with_context(|| format!("creating {label} render pipeline")) } +/// The globals the custom shader prelude reads, laid out as its `GpuiShaderGlobals`. +#[repr(C)] +struct CustomShaderGlobals { + viewport_size: [f32; 2], + premultiplied_alpha: u32, + pad: u32, +} + +/// Translates a custom shader to MSL, compiles it and builds a pipeline that blends it the way +/// quads are blended. +fn build_custom_pipeline_state( + device: &ProtocolObject, + shader: ShaderId, + pixel_format: MTLPixelFormat, +) -> Result>> { + let program = gpui::shader_program(shader) + .with_context(|| format!("custom shader {} was never registered", shader.0))?; + let msl = program.to_msl()?; + let library = device + .newLibraryWithSource_options_error( + &NSString::from_str(&msl.source), + Some(&MTLCompileOptions::new()), + ) + .map_err(|error| anyhow::anyhow!("custom shader `{}`: {error}", program.label))?; + let function = |name: &str| { + library + .newFunctionWithName(&NSString::from_str(name)) + .with_context(|| { + format!( + "custom shader `{}`: locating function {name}", + program.label + ) + }) + }; + let vertex_fn = function(&msl.vertex_entry)?; + let fragment_fn = function(&msl.fragment_entry)?; + + let descriptor = MTLRenderPipelineDescriptor::new(); + descriptor.setLabel(Some(&NSString::from_str(&program.label))); + descriptor.setVertexFunction(Some(vertex_fn.as_ref())); + descriptor.setFragmentFunction(Some(fragment_fn.as_ref())); + // SAFETY: Index zero is within the pipeline's color attachment array. + let color_attachment = unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) }; + color_attachment.setPixelFormat(pixel_format); + color_attachment.setBlendingEnabled(true); + color_attachment.setRgbBlendOperation(MTLBlendOperation::Add); + color_attachment.setAlphaBlendOperation(MTLBlendOperation::Add); + color_attachment.setSourceRGBBlendFactor(MTLBlendFactor::SourceAlpha); + color_attachment.setSourceAlphaBlendFactor(MTLBlendFactor::One); + color_attachment.setDestinationRGBBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); + color_attachment.setDestinationAlphaBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); + + device + .newRenderPipelineStateWithDescriptor_error(&descriptor) + .map_err(|error| anyhow::anyhow!("custom shader `{}`: {error}", program.label)) +} + fn build_depth_stencil_state( device: &ProtocolObject, write_depth: bool, @@ -1412,7 +2826,9 @@ struct InstanceBinding { } struct InstanceBindings { + backdrops: InstanceBinding, quads: InstanceBinding, + shaders: InstanceBinding, path_tiles: InstanceBinding, path_curves: InstanceBinding, path_paints: InstanceBinding, @@ -1431,7 +2847,9 @@ fn write_instances(scene: &Scene, writer: &mut InstanceBufferWriter) -> Result anyhow::Result<()> { + use gpui::PlatformHeadlessRenderer as _; + let mut renderer = MetalHeadlessRenderer::new()?; + render_fixture::run("", &[], |scene, size| { + renderer.render_scene_to_image(scene, size) + }) +} diff --git a/crates/gpui_apple/src/shaders.metal b/crates/gpui_apple/src/shaders.metal index 680842f8..a45001f7 100644 --- a/crates/gpui_apple/src/shaders.metal +++ b/crates/gpui_apple/src/shaders.metal @@ -37,8 +37,10 @@ float dash_alpha(float t, float period, float length, float dash_velocity, float quarter_ellipse_sdf(float2 point, float2 radii); float pick_corner_radius(float2 center_to_point, Corners_ScaledPixels corner_radii); float quad_sdf(float2 point, Bounds_ScaledPixels bounds, - Corners_ScaledPixels corner_radii); -float quad_sdf_impl(float2 center_to_point, float corner_radius); + Corners_ScaledPixels corner_radii, float corner_smoothing); +float2 corner_shape(float radius, float smoothing, float2 half_size); +float superellipse_sdf(float2 point, float radius, float exponent); +float quad_sdf_impl(float2 center_to_point, float corner_radius, float corner_exponent); float4 over(float4 below, float4 above); float radians(float degrees); @@ -63,17 +65,43 @@ struct QuadFragmentInput { PreparedBackground background; }; +// The device pixels `bounds` reach into: the bounds grown out to whole pixels, so an edge that +// falls between pixels still draws the pixel it partly covers. Bounds on the pixel grid stay as +// they are. +Bounds_ScaledPixels pixel_cover(Bounds_ScaledPixels bounds) { + float2 origin = floor(float2(bounds.origin.x, bounds.origin.y)); + float2 far_edge = ceil(float2(bounds.origin.x + bounds.size.width, + bounds.origin.y + bounds.size.height)); + Bounds_ScaledPixels cover = bounds; + cover.origin.x = origin.x; + cover.origin.y = origin.y; + cover.size.width = far_edge.x - origin.x; + cover.size.height = far_edge.y - origin.y; + return cover; +} + +// How much of the pixel centred on `position` the bounds cover: 1 inside them, and the share +// left where an edge falls through the pixel. +float pixel_coverage(float2 position, Bounds_ScaledPixels bounds) { + float2 origin = float2(bounds.origin.x, bounds.origin.y); + float2 near_edge = max(position - 0.5, origin); + float2 far_edge = + min(position + 0.5, origin + float2(bounds.size.width, bounds.size.height)); + float2 overlap = saturate(far_edge - near_edge); + return overlap.x * overlap.y; +} + constant float4 CULLED_POSITION = float4(0., 0., 0., 1.); float quad_depth(uint quad_id, float depth_scale) { return saturate(float(quad_id + 1u) * depth_scale); } -// Opaque rectangles are drawn by the opaque pass instead of the quad pass. +// Opaque rectangles are drawn by the opaque pass instead of the quad pass. The fork draws no +// opaque pass (`DEPTH_PREPASS` in scene.rs), so the quad pass keeps every quad. Upstream's test is +// a solid opaque background with neither rounded corners nor a border. bool is_opaque_rectangle(Quad quad) { - return quad.background.tag == 0u && quad.background.solid.a >= 1.0 && - !has_rounded_corners(quad.corner_radii) && - !has_border(quad.border_widths); + return false; } vertex QuadFragmentInput quad_vertex( @@ -90,13 +118,18 @@ vertex QuadFragmentInput quad_vertex( } float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); + Bounds_ScaledPixels cover = pixel_cover(quad.bounds); ClippedVertex clipped = - clip_to_mask(unit_vertex, quad.bounds, quad.content_mask.bounds); + clip_to_mask(unit_vertex, cover, quad.content_mask.bounds); float4 device_position = to_device_position_impl(clipped.position, viewport_size); device_position.z = quad_depth(quad_id, *depth_scale); float4 border_color = hsla_to_rgba(quad.border_color); - bool simple = !is_shaped(quad) && quad.background.tag == 0u; + // A quad off the pixel grid covers its edge pixels only in part, which the fragment weighs. + bool on_grid = all(float4(cover.origin.x, cover.origin.y, cover.size.width, cover.size.height) == + float4(quad.bounds.origin.x, quad.bounds.origin.y, quad.bounds.size.width, + quad.bounds.size.height)); + bool simple = !is_shaped(quad) && quad.background.tag == 0u && on_grid; PreparedBackground background = prepare_background(quad.background); return QuadFragmentInput{ @@ -118,6 +151,15 @@ fragment float4 quad_fragment(QuadFragmentInput input [[stage_in]], quad.bounds, input.position.xy); bool unrounded = !has_rounded_corners(quad.corner_radii); + // A quad off the pixel grid partly covers the pixels its edges fall through. On the grid + // this is 1 for every pixel drawn. + float coverage = pixel_coverage(input.position.xy, quad.bounds); + + // Fast path when the quad is not rounded and doesn't have any border + if (!is_shaped(quad)) { + return background * float4(1.0, 1.0, 1.0, coverage); + } + float2 size = float2(quad.bounds.size.width, quad.bounds.size.height); float2 half_size = size / 2.0; float2 point = input.position.xy - float2(quad.bounds.origin.x, quad.bounds.origin.y); @@ -127,8 +169,10 @@ fragment float4 quad_fragment(QuadFragmentInput input [[stage_in]], // minimum distance between the center of the pixel and the edge. const float antialias_threshold = 0.5; - // Radius of the nearest corner - float corner_radius = pick_corner_radius(center_to_point, quad.corner_radii); + // How far along the edges the nearest corner reaches, and the exponent of its curve + float2 corner = corner_shape(pick_corner_radius(center_to_point, quad.corner_radii), + quad.corner_smoothing, half_size); + float corner_radius = corner.x; // Width of the nearest borders float2 border = float2( @@ -175,11 +219,11 @@ fragment float4 quad_fragment(QuadFragmentInput input [[stage_in]], // Fast path for points that must be part of the background if (is_within_inner_straight_border && !is_near_rounded_corner) { - return background; + return background * float4(1.0, 1.0, 1.0, coverage); } // Signed distance of the point to the outside edge of the quad's border - float outer_sdf = quad_sdf_impl(corner_center_to_point, corner_radius); + float outer_sdf = quad_sdf_impl(corner_center_to_point, corner_radius, corner.y); // Approximate signed distance of the point to the inside edge of the quad's // border. It is negative outside this edge (within the border), and @@ -197,9 +241,10 @@ fragment float4 quad_fragment(QuadFragmentInput input [[stage_in]], } else if (is_beyond_inner_straight_border) { // Fast path for points that must be outside the inner edge inner_sdf = -1.0; - } else if (reduced_border.x == reduced_border.y) { - // Fast path for circular inner edge. - inner_sdf = -(outer_sdf + reduced_border.x); + } else if (reduced_border.x == reduced_border.y || corner.y != 2.0) { + // Fast path for circular inner edge. A smoothed corner offsets its outer edge by the + // wider border, since its inner edge has no exact form either way. + inner_sdf = -(outer_sdf + max(reduced_border.x, reduced_border.y)); } else { float2 ellipse_radii = max(float2(0.0), float2(corner_radius) - reduced_border); inner_sdf = quarter_ellipse_sdf(corner_center_to_point, ellipse_radii); @@ -390,7 +435,9 @@ fragment float4 quad_fragment(QuadFragmentInput input [[stage_in]], color = over(background, border_color); } - return color * float4(1.0, 1.0, 1.0, saturate(antialias_threshold - outer_sdf)); + // The distance field knows nothing of how much of the pixel the quad covers, so a quad + // thinner than a pixel would come out stronger than the share of the pixel it fills. + return color * float4(1.0, 1.0, 1.0, min(coverage, saturate(antialias_threshold - outer_sdf))); } // Returns the dash velocity of a corner given the dash velocity of the two @@ -586,7 +633,7 @@ fragment float4 shadow_fragment(ShadowFragmentInput input [[stage_in]], float alpha; if (shadow.blur_radius == 0.) { float distance = quad_sdf(input.position.xy, shadow.shape_bounds, - shadow.shape_corner_radii); + shadow.shape_corner_radii, 0.0); alpha = saturate(0.5 - distance); } else { float2 origin = float2(shadow.shape_bounds.origin.x, shadow.shape_bounds.origin.y); @@ -601,9 +648,15 @@ fragment float4 shadow_fragment(ShadowFragmentInput input [[stage_in]], // The inset shadow is the complement of the (blurred) hole rect, clipped to the element. // `saturate(0.5 - d)` gives a 1-pixel antialiased edge: d <= -0.5 -> 1, d >= 0.5 -> 0. alpha = 1. - alpha; - float element_distance = - quad_sdf(input.position.xy, shadow.bounds, shadow.corner_radii); + float element_distance = quad_sdf(input.position.xy, shadow.element_bounds, + shadow.element_corner_radii, shadow.element_corner_smoothing); alpha *= saturate(0.5 - element_distance); + } else { + // A drop shadow is clipped to outside the element, the way CSS draws one, so an + // element with a translucent fill never shows its own shadow through it. + float element_distance = quad_sdf(input.position.xy, shadow.element_bounds, + shadow.element_corner_radii, shadow.element_corner_smoothing); + alpha *= saturate(0.5 + element_distance); } return input.color * float4(1., 1., 1., alpha); @@ -761,7 +814,7 @@ fragment float4 polychrome_sprite_fragment( color.b = grayscale; } float distance = - quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii); + quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii, 0.0); color.a *= input.opacity * saturate(0.5 - distance); return color; } @@ -1135,31 +1188,62 @@ float pick_corner_radius(float2 center_to_point, Corners_ScaledPixels corner_rad // Signed distance of the point to the quad's border - positive outside the // border, and negative inside. float quad_sdf(float2 point, Bounds_ScaledPixels bounds, - Corners_ScaledPixels corner_radii) { + Corners_ScaledPixels corner_radii, float corner_smoothing) { float2 half_size = float2(bounds.size.width, bounds.size.height) / 2.0; float2 center = float2(bounds.origin.x, bounds.origin.y) + half_size; float2 center_to_point = point - center; - float corner_radius = pick_corner_radius(center_to_point, corner_radii); + float2 corner = corner_shape(pick_corner_radius(center_to_point, corner_radii), + corner_smoothing, half_size); float2 corner_to_point = fabs(center_to_point) - half_size; - float2 corner_center_to_point = corner_to_point + corner_radius; - return quad_sdf_impl(corner_center_to_point, corner_radius); + float2 corner_center_to_point = corner_to_point + corner.x; + return quad_sdf_impl(corner_center_to_point, corner.x, corner.y); +} + +// How much further along each edge a fully smoothed corner starts than a round one, as a share +// of its radius. The same as `SQUIRCLE_REACH` in gpui. +constant float SQUIRCLE_REACH = 0.528665; + +// The shape of a corner of `radius` smoothed by `smoothing`: how far along each edge it starts, +// and the exponent of the superellipse it follows, 2 for a circular arc. The exponent is picked +// so that the corner crosses its diagonal where a round corner of `radius` would, which keeps +// it the same size to the eye. A corner with no room to reach further stays round. +float2 corner_shape(float radius, float smoothing, float2 half_size) { + if (smoothing <= 0.0 || radius <= 0.0) { + return float2(radius, 2.0); + } + float room = min(half_size.x, half_size.y); + float extent = max(radius, min(radius * (1.0 + SQUIRCLE_REACH * smoothing), room)); + float inset = (1.0 - sqrt(0.5)) * radius / extent; + return float2(extent, -1.0 / log2(1.0 - inset)); +} + +// Signed distance from a point, measured from a corner's center, to a superellipse corner of +// `radius` and `exponent`. The superellipse's norm divided by the length of its gradient is a +// true distance near the curve, which is where antialiasing reads it. +float superellipse_sdf(float2 point, float radius, float exponent) { + float2 component = fabs(point); + float norm = powr(powr(component.x, exponent) + powr(component.y, exponent), 1.0 / exponent); + if (norm <= 0.0) { + return -radius; + } + float slope = length(powr(component / norm, float2(exponent - 1.0))); + return (norm - radius) / slope; } // Implementation of quad signed distance field -float quad_sdf_impl(float2 corner_center_to_point, float corner_radius) { +float quad_sdf_impl(float2 corner_center_to_point, float corner_radius, float corner_exponent) { if (corner_radius == 0.0) { // Fast path for unrounded corners return max(corner_center_to_point.x, corner_center_to_point.y); } else { - // Signed distance of the point from a quad that is inset by corner_radius - // It is negative inside this quad, and positive outside - float signed_distance_to_inset_quad = - // 0 inside the inset quad, and positive outside - length(max(float2(0.0), corner_center_to_point)) + - // 0 outside the inset quad, and negative inside - min(0.0, max(corner_center_to_point.x, corner_center_to_point.y)); - - return signed_distance_to_inset_quad - corner_radius; + // 0 inside the quad inset by corner_radius, and positive outside + float2 outside = max(float2(0.0), corner_center_to_point); + // 0 outside the inset quad, and negative inside + float inside = min(0.0, max(corner_center_to_point.x, corner_center_to_point.y)); + if (corner_exponent == 2.0) { + return length(outside) + inside - corner_radius; + } + return superellipse_sdf(outside, corner_radius, corner_exponent) + inside; } } @@ -1317,6 +1401,270 @@ float4 background_color(PreparedBackground prepared, Background background, return color; } +struct FilterVertexOutput { + float4 position [[position]]; + float2 uv; +}; + +struct FilterFragmentInput { + float4 position [[position]]; + float2 uv; +}; + +vertex FilterVertexOutput filter_vertex(uint unit_vertex_id [[vertex_id]]) { + float2 unit_vertex = float2(float(unit_vertex_id & 1u), + 0.5 * float(unit_vertex_id & 2u)); + return FilterVertexOutput{ + float4(unit_vertex.x * 2.0 - 1.0, 1.0 - unit_vertex.y * 2.0, 0.0, 1.0), + unit_vertex}; +} + +struct BackdropVertexOutput { + float4 position [[position]]; + uint backdrop_id [[flat]]; +}; + +struct BackdropFragmentInput { + float4 position [[position]]; + uint backdrop_id [[flat]]; +}; + +vertex BackdropVertexOutput backdrop_vertex( + uint vertex_id [[vertex_id]], uint backdrop_id [[instance_id]], + constant Backdrop *backdrops [[buffer(FilterInputIndex_Backdrops)]], + constant Size_DevicePixels *viewport_size + [[buffer(FilterInputIndex_ViewportSize)]]) { + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); + Backdrop backdrop = backdrops[backdrop_id]; + ClippedVertex clipped = + clip_to_mask(unit_vertex, backdrop.bounds, backdrop.content_mask.bounds); + float4 device_position = + to_device_position_impl(clipped.position, viewport_size); + return BackdropVertexOutput{device_position, backdrop_id}; +} + +// A backdrop replaces what it covers with the blurred copy of it rather than laying that copy +// over it: `dst = mix(dst, blurred, k)`, k being the coverage times the instance's opacity. +// Over an opaque frame the two are one picture, since a copy of alpha one hides whatever it +// covers; over a see-through window they are not, and laying it over left `a + a(1 - a)` +// where the window asked for `a`. The mix is two draws over one instance buffer: +// `backdrop_punch_fragment` for `dst *= (1 - k)`, then this one, added on top. +fragment float4 backdrop_fragment( + BackdropFragmentInput input [[stage_in]], + constant Backdrop *backdrops [[buffer(FilterInputIndex_Backdrops)]], + constant Size_DevicePixels *viewport_size + [[buffer(FilterInputIndex_ViewportSize)]], + texture2d source [[texture(FilterInputIndex_Source)]]) { + constexpr sampler source_sampler(mag_filter::linear, min_filter::linear, + address::clamp_to_edge); + Backdrop backdrop = backdrops[input.backdrop_id]; + float2 position = input.position.xy; + float2 extent = float2(float(viewport_size->width), float(viewport_size->height)); + float4 sampled = source.sample(source_sampler, position / extent); + float distance = quad_sdf(position, backdrop.bounds, backdrop.corner_radii, backdrop.corner_smoothing); + float coverage = saturate(0.5 - distance); + + return sampled * coverage * backdrop.opacity; +} + +// The hole the blurred copy lands in: alpha alone, blended so what it covers keeps `1 - k` of +// itself, colour and alpha together. +fragment float4 backdrop_punch_fragment( + BackdropFragmentInput input [[stage_in]], + constant Backdrop *backdrops [[buffer(FilterInputIndex_Backdrops)]], + constant Size_DevicePixels *viewport_size + [[buffer(FilterInputIndex_ViewportSize)]], + texture2d source [[texture(FilterInputIndex_Source)]]) { + Backdrop backdrop = backdrops[input.backdrop_id]; + float2 position = input.position.xy; + float distance = quad_sdf(position, backdrop.bounds, backdrop.corner_radii, backdrop.corner_smoothing); + float coverage = saturate(0.5 - distance); + + return float4(0.0, 0.0, 0.0, coverage * backdrop.opacity); +} + +// How much of a texel wide footprint centred at `at`, in texels, lies within `0..extent` on both +// axes. Nothing lies past the frame's edges, so every blur pass weighs its taps by this and +// divides by the weight it kept, with `extent` as how many texels of the texture it reads hold +// the frame. A blur against an edge then averages what is there instead of stretching the border +// row across the kernel, which made every row that scrolled out under the edge flash through the +// blur on its way. +float blur_inside(float2 at, float2 extent) { + float2 span = saturate(min(at + 0.5, extent) - max(at - 0.5, float2(0.0))); + return span.x * span.y; +} + +// How much of a texel wide span centred at `at`, in texels, lies within `0..limit` along one +// axis. A gaussian pass reads along one axis only, so a texel's coverage across it is the same +// for every tap and must not weigh the taps against the centre. +float blur_along(float at, float limit) { + return saturate(min(at + 0.5, limit) - max(at - 0.5, 0.0)); +} + +// A narrow blur runs `gaussian_fragment` across and then down at full resolution, with `radius` +// as its standard deviation, and a wide one runs it across and down the deepest level of a +// pyramid. It pairs neighbouring taps into one bilinear fetch placed between them by their +// weights, which halves the fetches, and relies on sampling a texture of the same size as the +// target, so every pair lands between two texel centres along the axis. Every tap, the centre +// too, counts by how much of it lies inside the frame along the axis, so a tap past the frame's +// edge drops out of the pair it belongs to. +fragment float4 gaussian_fragment( + FilterFragmentInput input [[stage_in]], + constant BlurParams *params [[buffer(FilterInputIndex_Params)]], + texture2d source [[texture(FilterInputIndex_Source)]]) { + constexpr sampler source_sampler(mag_filter::linear, min_filter::linear, + address::clamp_to_edge); + float2 size = float2(source.get_width(), source.get_height()); + float2 direction = float2(params->direction[0], params->direction[1]); + float2 extent = float2(params->extent[0], params->extent[1]); + float2 texel = direction / size; + float axis = dot(input.uv * size, direction); + float limit = dot(extent, direction); + float sigma = max(params->radius, 0.0001); + float reach = min(ceil(sigma * 3.0), 24.0); + float spread = 2.0 * sigma * sigma; + + float own = blur_along(axis, limit); + float4 total = own * source.sample(source_sampler, input.uv); + float weight = own; + for (float inner = 1.0; inner <= reach; inner += 2.0) { + float outer = inner + 1.0; + float inner_weight = exp(-inner * inner / spread); + float outer_weight = outer <= reach ? exp(-outer * outer / spread) : 0.0; + for (float side = -1.0; side <= 1.0; side += 2.0) { + float inner_tap = inner_weight * blur_along(axis + inner * side, limit); + float outer_tap = outer_weight * blur_along(axis + outer * side, limit); + float pair = inner_tap + outer_tap; + float2 at = texel * (side * (inner * inner_tap + outer * outer_tap) / max(pair, 0.0001)); + total += pair * source.sample(source_sampler, input.uv + at); + weight += pair; + } + } + + return total / max(weight, 0.0001); +} + +// Four bilinear taps at `centre` plus `offset` mirrored into each quadrant, in texels of +// `source`, each weighed by how much of it falls within `extent`. +float4 pyramid_taps(texture2d source, float2 centre, float2 offset, float2 extent) { + constexpr sampler source_sampler(mag_filter::linear, min_filter::linear, + address::clamp_to_edge); + float2 size = float2(source.get_width(), source.get_height()); + float4 total = float4(0.0); + float weight = 0.0; + for (int i = 0; i < 4; i++) { + float2 corner = float2((i & 1) ? 1.0 : -1.0, (i & 2) ? 1.0 : -1.0); + float2 at = centre + offset * corner; + float tap = blur_inside(at, extent); + total += tap * source.sample(source_sampler, at / size); + weight += tap; + } + return total / max(weight, 0.0001); +} + +// Halves the level it reads, the first passes of a pyramid. A target texel sits over the corner +// of four source texels, and a bilinear tap on each of the four corners around that one averages +// the four by four texels under it. +fragment float4 pyramid_down_fragment( + FilterFragmentInput input [[stage_in]], + constant BlurParams *params [[buffer(FilterInputIndex_Params)]], + texture2d source [[texture(FilterInputIndex_Source)]]) { + float2 extent = float2(params->extent[0], params->extent[1]); + return pyramid_taps(source, input.position.xy * 2.0, float2(1.0), extent); +} + +// Doubles the level it reads, back towards full size. Four bilinear taps half a texel out on +// each diagonal lay a box of one texel over the bilinear tent, which rounds off the corners a +// tent alone leaves at every texel of the level below and keeps its grid from showing. +fragment float4 pyramid_up_fragment( + FilterFragmentInput input [[stage_in]], + constant BlurParams *params [[buffer(FilterInputIndex_Params)]], + texture2d source [[texture(FilterInputIndex_Source)]]) { + float2 extent = float2(params->extent[0], params->extent[1]); + return pyramid_taps(source, input.position.xy * 0.5, float2(0.5), extent); +} + +// Wipes the scissored part of a layer target, so a layer only clears what it will be read from. +fragment float4 clear_fragment(FilterFragmentInput input [[stage_in]]) { + return float4(0.0); +} + +// Copies the frame into the drawable texel for texel. The frame can be larger than the drawable +// by the overscan past its right and bottom edges, which the copy leaves behind. +fragment float4 blit_fragment( + FilterFragmentInput input [[stage_in]], + texture2d source [[texture(FilterInputIndex_Source)]]) { + return source.read(uint2(input.position.xy)); +} + +fragment float4 mask_fragment( + FilterFragmentInput input [[stage_in]], + constant MaskParams *params [[buffer(FilterInputIndex_Params)]], + constant Size_DevicePixels *viewport_size + [[buffer(FilterInputIndex_ViewportSize)]], + texture2d source [[texture(FilterInputIndex_Source)]]) { + constexpr sampler source_sampler(mag_filter::linear, min_filter::linear, + address::clamp_to_edge); + float2 extent = float2(float(viewport_size->width), float(viewport_size->height)); + float2 destination_point = input.position.xy; + float2 origin = float2(params->transform_origin[0], params->transform_origin[1]); + float2 translation = float2(params->translation[0], params->translation[1]); + float2 source_point = origin + (destination_point - translation - origin) / params->scale; + // Only the part of the source inside the frame was drawn, so only that part covers pixels. + float2 bounds_origin = float2(params->source_bounds.origin.x, + params->source_bounds.origin.y); + float2 source_origin = max(bounds_origin, float2(0.0)); + float2 source_end = min(bounds_origin + float2(params->source_bounds.size.width, + params->source_bounds.size.height), + extent); + + // An untransformed layer keeps the frame's pixel grid, so a pixel is in or out. A transformed + // one covers each pixel as far as its transformed bounds overlap it, which smooths the edge + // the clamped sample below leaves hard. + float coverage = 1.0; + if (params->scale == 1.0 && all(translation == float2(0.0))) { + if (any(source_point < source_origin) || any(source_point >= source_end)) { + return float4(0.0); + } + } else { + float2 start = origin + (source_origin - origin) * params->scale + translation; + float2 end = origin + (source_end - origin) * params->scale + translation; + float2 overlap = + saturate(min(destination_point + 0.5, end) - max(destination_point - 0.5, start)); + coverage = overlap.x * overlap.y; + if (coverage <= 0.0) { + return float4(0.0); + } + } + + float top = source_point.y - params->fade_bounds.origin.y; + float bottom = params->fade_bounds.origin.y + params->fade_bounds.size.height - source_point.y; + + float fade = 1.0; + if (params->fade_top > 0.0) { + fade = min(fade, smoothstep(0.0, params->fade_top, top)); + } + if (params->fade_bottom > 0.0) { + fade = min(fade, smoothstep(0.0, params->fade_bottom, bottom)); + } + if (params->fade_left > 0.0) { + float left = source_point.x - params->fade_bounds.origin.x; + fade = min(fade, smoothstep(0.0, params->fade_left, left)); + } + if (params->fade_right > 0.0) { + float right = params->fade_bounds.origin.x + params->fade_bounds.size.width - source_point.x; + fade = min(fade, smoothstep(0.0, params->fade_right, right)); + } + + // The sample stays half a texel inside the texels the layer covers and inside the frame, so a + // stretched edge repeats the layer's last texels rather than blending them with whatever lies + // past it. A pixel centre of an untransformed layer is already inside and does not move. + float2 low = max(floor(source_origin), float2(0.0)) + 0.5; + float2 high = min(ceil(source_end), extent) - 0.5; + float2 texel = clamp(source_point, low, max(low, high)); + return source.sample(source_sampler, texel / extent) * coverage * fade; +} + bool has_rounded_corners(Corners_ScaledPixels corner_radii) { return corner_radii.top_left != 0.0 || corner_radii.top_right != 0.0 || corner_radii.bottom_right != 0.0 || corner_radii.bottom_left != 0.0; diff --git a/crates/gpui_windows/src/directx_renderer.rs b/crates/gpui_windows/src/directx_renderer.rs index 8573fe40..1c2c026e 100644 --- a/crates/gpui_windows/src/directx_renderer.rs +++ b/crates/gpui_windows/src/directx_renderer.rs @@ -2,13 +2,15 @@ use std::{ ops::Range, slice, sync::{Arc, OnceLock}, + time::{Duration, Instant}, }; use anyhow::{Context, Result}; +use collections::FxHashMap; use gpui_util::ResultExt; use windows::{ Win32::{ - Foundation::HWND, + Foundation::{HWND, RECT}, Graphics::{ Direct3D::*, Direct3D11::*, @@ -26,6 +28,13 @@ use gpui::*; pub(crate) const DISABLE_DIRECT_COMPOSITION: &str = "GPUI_DISABLE_DIRECT_COMPOSITION"; const RENDER_TARGET_FORMAT: DXGI_FORMAT = DXGI_FORMAT_B8G8R8A8_UNORM; +/// How deeply filtered layers can nest before the innermost ones stop being filtered. Each depth +/// keeps one offscreen target, made the first time a frame nests that deep. +const LAYER_DEPTH: usize = 8; +/// How long an offscreen target may go unused before its memory is given back. A frame with a +/// blur or layer on screen touches its targets every time, so only targets that nothing on +/// screen draws through are released. +const IDLE_RELEASE: Duration = Duration::from_secs(2); const MAX_INSTANCE_BUFFER_SIZE: usize = 256 * 1024 * 1024; pub(crate) struct FontInfo { @@ -53,6 +62,9 @@ pub(crate) struct DirectXRenderer { /// In that case we want to discard the first frame that we draw as we got reset in the middle of a frame /// meaning we lost all the allocated gpu textures and scene resources. skip_draws: bool, + + /// When the frame being drawn started, which stamps every offscreen target it touches. + frame_time: Instant, } /// Direct3D objects @@ -72,14 +84,207 @@ struct DirectXResources { swap_chain: IDXGISwapChain1, render_target: Option, render_target_view: Option, - depth_stencil_texture: ID3D11Texture2D, + depth_stencil_texture: Option, depth_stencil_view: Option, + // Offscreen targets the frame blurs and masks through + filters: FilterTargets, + // Cached viewport viewport: D3D11_VIEWPORT, } +/// A texture the renderer can both draw into and sample from. +#[derive(Clone)] +struct RenderTexture { + _texture: ID3D11Texture2D, + view: Option, + source: Option, +} + +/// An offscreen target created the first time a frame needs it and released once it has gone +/// `IDLE_RELEASE` without use. +struct Scratch { + texture: RenderTexture, + used: Instant, +} + +/// One of the offscreen targets filters draw through. +#[derive(Clone, Copy)] +enum FilterTarget { + /// The accumulated background of all open layers before a backdrop samples it. + Backdrop, + /// The frame itself, drawn offscreen so a backdrop can sample what lies under it. + Frame, + /// The target a filtered layer is drawn into, by nesting depth. + Layer(usize), + /// One blur level, the frame's size halved as many times as its index and rounded up, so the + /// last texel of a level can hang past the frame's edge. Level zero holds a finished blur. + Level(usize), + /// Where a gaussian keeps its pass across before the pass down. + Scratch, + /// Where the gaussian at the deepest level of a pyramid keeps its pass across, at that + /// level's size. + Spread(usize), +} + +impl FilterTarget { + /// How many times smaller than the frame the target is on each side. + fn shrink(self) -> u32 { + match self { + Self::Level(level) | Self::Spread(level) => 1 << level, + Self::Frame | Self::Layer(_) | Self::Scratch | Self::Backdrop => 1, + } + } +} + +/// Offscreen targets a frame needs to blur and mask what it has drawn, all made for one swap +/// chain size. Each one is allocated the first time a frame draws through it, so a frame with +/// one shallow blur pays for the targets it touches rather than for every depth and level. +struct FilterTargets { + width: u32, + height: u32, + frame: Option, + backdrop: Option, + layers: [Option; LAYER_DEPTH], + levels: [Option; BLUR_LEVELS + 1], + spreads: [Option; BLUR_LEVELS + 1], + scratch: Option, +} + +impl FilterTargets { + fn new(width: u32, height: u32) -> Self { + Self { + width, + height, + frame: None, + backdrop: None, + layers: std::array::from_fn(|_| None), + levels: std::array::from_fn(|_| None), + spreads: std::array::from_fn(|_| None), + scratch: None, + } + } + + fn slot(&mut self, target: FilterTarget) -> &mut Option { + match target { + FilterTarget::Backdrop => &mut self.backdrop, + FilterTarget::Frame => &mut self.frame, + FilterTarget::Layer(depth) => &mut self.layers[depth.min(LAYER_DEPTH - 1)], + FilterTarget::Level(level) => &mut self.levels[level], + FilterTarget::Scratch => &mut self.scratch, + FilterTarget::Spread(level) => &mut self.spreads[level], + } + } + + /// A target this frame has already drawn through, which every target but the one being + /// opened is by the time it is read. + fn get(&self, target: FilterTarget) -> Result<&RenderTexture> { + let slot = match target { + FilterTarget::Backdrop => &self.backdrop, + FilterTarget::Frame => &self.frame, + FilterTarget::Layer(depth) => &self.layers[depth.min(LAYER_DEPTH - 1)], + FilterTarget::Level(level) => &self.levels[level], + FilterTarget::Scratch => &self.scratch, + FilterTarget::Spread(level) => &self.spreads[level], + }; + slot.as_ref() + .map(|scratch| &scratch.texture) + .context("missing filter target") + } + + /// The target, created at the swap chain's size (shrunk for a blur level) if no frame has + /// drawn through it since it was last released, and marked as used by the frame at `now`. + fn touch( + &mut self, + device: &ID3D11Device, + target: FilterTarget, + now: Instant, + ) -> Result { + let shrink = target.shrink(); + let (width, height) = (self.width.div_ceil(shrink), self.height.div_ceil(shrink)); + let slot = self.slot(target); + if slot.is_none() { + *slot = Some(Scratch { + texture: create_render_texture(device, width, height)?, + used: now, + }); + } + let scratch = slot.as_mut().context("missing filter target")?; + scratch.used = now; + Ok(scratch.texture.clone()) + } + + /// Drops every target no frame has drawn through within `IDLE_RELEASE` of `now`. + fn release_idle(&mut self, now: Instant) { + let slots = std::iter::once(&mut self.frame) + .chain(std::iter::once(&mut self.backdrop)) + .chain(self.layers.iter_mut()) + .chain(self.levels.iter_mut()) + .chain(self.spreads.iter_mut()) + .chain(std::iter::once(&mut self.scratch)); + for slot in slots { + if slot + .as_ref() + .is_some_and(|scratch| now.duration_since(scratch.used) >= IDLE_RELEASE) + { + *slot = None; + } + } + } +} + +#[derive(Clone, Copy, Default)] +#[repr(C)] +struct FilterParams { + source_bounds: Bounds, + fade_bounds: Bounds, + direction: [f32; 2], + transform_origin: [f32; 2], + radius: f32, + scale: f32, + fade_top: f32, + fade_bottom: f32, + fade_left: f32, + fade_right: f32, + translation: [f32; 2], + /// How many texels of the texture a blur pass reads hold the frame. A blur level rounds its + /// size up, so its last texel can hang past the frame's edge. + extent: [f32; 2], +} + +const _: () = { + assert!(std::mem::size_of::() == 22 * std::mem::size_of::()); + assert!(std::mem::offset_of!(FilterParams, source_bounds) == 0); + assert!(std::mem::offset_of!(FilterParams, fade_bounds) == 16); + assert!(std::mem::offset_of!(FilterParams, direction) == 32); + assert!(std::mem::offset_of!(FilterParams, transform_origin) == 40); + assert!(std::mem::offset_of!(FilterParams, radius) == 48); + assert!(std::mem::offset_of!(FilterParams, scale) == 52); + assert!(std::mem::offset_of!(FilterParams, fade_top) == 56); + assert!(std::mem::offset_of!(FilterParams, fade_bottom) == 60); + assert!(std::mem::offset_of!(FilterParams, fade_left) == 64); + assert!(std::mem::offset_of!(FilterParams, fade_right) == 68); + assert!(std::mem::offset_of!(FilterParams, translation) == 72); + assert!(std::mem::offset_of!(FilterParams, extent) == 80); +}; + +#[derive(Clone, Copy)] +enum Pass { + Gaussian, + PyramidDown, + PyramidUp, +} + struct DirectXRenderPipelines { + backdrop_pipeline: PipelineState, + backdrop_punch: Shading, + gaussian_pipeline: PipelineState, + pyramid_down_pipeline: PipelineState, + pyramid_up_pipeline: PipelineState, + blit_pipeline: PipelineState, + composite_pipeline: PipelineState, + mask_pipeline: PipelineState, shadow_pipeline: PipelineState, quad_pipeline: PipelineState, opaque_quad_pipeline: OpaqueQuadPipeline, @@ -89,13 +294,19 @@ struct DirectXRenderPipelines { underline_pipeline: PipelineState, mono_sprites: PipelineState, subpixel_sprites: PipelineState, + subpixel_sprites_layered: Shading, poly_sprites: PipelineState, + custom_shaders: CustomShaders, } struct DirectXGlobalElements { global_params_buffer: Option, batch_params_buffer: Option, sampler: Option, + /// Clamps to the edge, for filter and compositing passes. A blur tap past the bottom of a + /// target would otherwise wrap to its top, and the transparent rows it reads there show the + /// desktop through an edge the blurred element touches. + filter_sampler: Option, } struct Annotation<'a>(&'a ID3DUserDefinedAnnotation); @@ -194,6 +405,7 @@ impl DirectXRenderer { width: 1, height: 1, skip_draws: false, + frame_time: Instant::now(), }) } @@ -229,15 +441,17 @@ impl DirectXRenderer { .context("missing render target view")?, clear_color, ); - device_context.ClearDepthStencilView( - resources - .depth_stencil_view - .as_ref() - .context("missing depth stencil view")?, - D3D11_CLEAR_DEPTH.0, - 0.0, - 0, - ); + if DEPTH_PREPASS { + device_context.ClearDepthStencilView( + resources + .depth_stencil_view + .as_ref() + .context("missing depth stencil view")?, + D3D11_CLEAR_DEPTH.0, + 0.0, + 0, + ); + } device_context.OMSetRenderTargets( Some(slice::from_ref(&resources.render_target_view)), resources.depth_stencil_view.as_ref(), @@ -250,6 +464,9 @@ impl DirectXRenderer { device_context .PSSetConstantBuffers(0, Some(slice::from_ref(&self.globals.global_params_buffer))); } + // The rasterizer clips to the scissor rect, which starts every frame empty. + self.reset_scissor()?; + Ok(()) } @@ -261,6 +478,563 @@ impl DirectXRenderer { } #[inline] + /// The handles a filter pass needs, cloned so the pipelines can be borrowed alongside them. + fn pipeline_handles( + &self, + ) -> Result<( + ID3D11Device, + ID3D11DeviceContext, + ID3D11SamplerState, + ID3D11Buffer, + )> { + let devices = self.devices.as_ref().context("devices missing")?; + + Ok(( + devices.device.clone(), + devices.device_context.clone(), + self.globals + .filter_sampler + .as_ref() + .context("missing filter sampler")? + .clone(), + self.globals + .batch_params_buffer + .as_ref() + .context("missing batch params")? + .clone(), + )) + } + + /// Points the pipeline at one of the offscreen targets, or at the frame when `depth` is none. + fn open_target(&self, depth: Option) -> Result<()> { + let resources = self.resources.as_ref().context("resources missing")?; + let devices = self.devices.as_ref().context("devices missing")?; + let view = match depth { + Some(depth) => &resources.filters.get(FilterTarget::Layer(depth))?.view, + None => &resources.filters.get(FilterTarget::Frame)?.view, + }; + unsafe { + devices + .device_context + .OMSetRenderTargets(Some(slice::from_ref(view)), None); + devices + .device_context + .RSSetViewports(Some(slice::from_ref(&resources.viewport))); + } + self.reset_scissor()?; + + Ok(()) + } + + /// Points the pipeline back at what the batch in hand is drawing into: the innermost open + /// layer, or the frame when none is open. Anything that binds a target of its own has to come + /// back through here, or the primitives after it land in the window while the rest of the + /// frame is still being assembled somewhere else. + fn resume_target(&self, stack: &[usize], mirrored: bool) -> Result<()> { + match stack.len().checked_sub(1) { + Some(depth) => self.open_target(Some(depth)), + None => self.restore_frame(mirrored), + } + } + + /// Clears one of the offscreen layer targets, creating it if it was released, and points the + /// pipeline at it. + fn open_layer(&mut self, depth: usize) -> Result<()> { + let target = self.filter_target(FilterTarget::Layer(depth))?; + let devices = self.devices.as_ref().context("devices missing")?; + let view = target.view.as_ref().context("missing layer target")?; + unsafe { + devices + .device_context + .ClearRenderTargetView(view, &[0.0f32; 4]); + } + + self.open_target(Some(depth)) + } + + /// Draws a filtered layer back into its parent, clipped to the layer's bounds. + fn close_layer( + &mut self, + stack: &[usize], + layer: LayerEffect, + clip: Bounds, + mirrored: bool, + ) -> Result<()> { + let depth = stack.len(); + let source = { + let resources = self.resources.as_ref().context("resources missing")?; + resources + .filters + .get(FilterTarget::Layer(depth))? + .source + .clone() + }; + let blurred = match layer.filter.blurs() { + true => self.blur_source( + source, + Some(depth), + layer.filter.blur, + Some(layer.blur_bounds(clip)), + )?, + false => source, + }; + + match depth.checked_sub(1) { + Some(onto) => self.open_target(Some(onto))?, + None => self.restore_frame(mirrored)?, + } + let Some(within) = self.scissor(layer.destination_scissor_bounds(clip), 1)? else { + return Ok(()); + }; + + let (device, device_context, sampler, batch_params) = self.pipeline_handles()?; + let params = [FilterParams { + source_bounds: if layer.filter.transforms() { + layer.source_bounds + } else { + clip + }, + // Preserve the existing DirectX fade clip for unscaled layers. A scaled layer applies + // the fade in source coordinates before the final transform. + fade_bounds: if layer.filter.transforms() { + layer.source_bounds + } else { + clip + }, + transform_origin: [layer.transform_origin.x.0, layer.transform_origin.y.0], + translation: [layer.filter.translate.x.0, layer.filter.translate.y.0], + scale: layer.filter.scale, + fade_top: layer.filter.fade_top, + fade_bottom: layer.filter.fade_bottom, + fade_left: layer.filter.fade_left, + fade_right: layer.filter.fade_right, + ..Default::default() + }]; + + self.set_scissor(within); + let pipeline = match layer.filter.fades() { + true => &mut self.pipelines.mask_pipeline, + false => &mut self.pipelines.composite_pipeline, + }; + pipeline.update_buffer(&device, &device_context, ¶ms)?; + pipeline.draw_range_with_texture( + &device_context, + None, + slice::from_ref(&blurred), + &batch_params, + slice::from_ref(&Some(sampler)), + 0, + 1, + )?; + self.reset_scissor()?; + + Ok(()) + } + + /// Blurs a source and returns the target holding the result, at full size. A source that is + /// the layer at depth `spare` is read by nothing else, so the blur writes its result back + /// into it rather than into a full-size target of its own. + fn blur_source( + &mut self, + source: Option, + spare: Option, + sigma: f32, + clip: Option>, + ) -> Result> { + match BlurPasses::for_sigma(sigma) { + BlurPasses::Gaussian(sigma) => self.gaussian_blur(source, spare, sigma, clip), + BlurPasses::Pyramid(pyramid) => self.pyramid_blur(source, spare, pyramid, clip), + } + } + + /// Blurs a source across into the scratch target and down into level zero, or back into the + /// `spare` layer it came from, both at full size. The pass across covers the clip grown by + /// the kernel, since the pass down reads that far above and below it. + fn gaussian_blur( + &mut self, + source: Option, + spare: Option, + sigma: f32, + clip: Option>, + ) -> Result> { + let extent = { + let resources = self.resources.as_ref().context("resources missing")?; + [resources.viewport.Width, resources.viewport.Height] + }; + let across = FilterParams { + direction: [1., 0.], + radius: sigma, + extent, + ..Default::default() + }; + let down = FilterParams { + direction: [0., 1.], + radius: sigma, + extent, + ..Default::default() + }; + let region = |renderer: &Self, margin: f32| match clip { + Some(clip) => renderer.scissor(clip.dilate(ScaledPixels(margin)), 1), + None => Ok(None), + }; + let reach = (sigma * GAUSSIAN_REACH).ceil() + 1.; + + let within = region(self, reach)?; + let scratch = self.filter_pass( + Pass::Gaussian, + source, + FilterTarget::Scratch, + Some(across), + within, + )?; + let within = region(self, 1.)?; + self.filter_pass( + Pass::Gaussian, + scratch, + spare.map_or(FilterTarget::Level(0), FilterTarget::Layer), + Some(down), + within, + ) + } + + /// Blurs a source with a [`Pyramid`]: down to the deepest level, a gaussian across and down + /// there, and back up to full size. Returns what the last pass wrote: level zero, or the + /// `spare` layer it came from. + fn pyramid_blur( + &mut self, + source: Option, + spare: Option, + pyramid: Pyramid, + clip: Option>, + ) -> Result> { + let deepest = pyramid.levels; + let frame = { + let resources = self.resources.as_ref().context("resources missing")?; + (resources.viewport.Width, resources.viewport.Height) + }; + // A pass reads a level of its own, so each gets its own parameters, which carry how + // much of that level holds the frame. + let params = |level: usize, direction: [f32; 2], radius: f32| { + let shrink = (1u32 << level) as f32; + FilterParams { + direction, + radius, + extent: [frame.0 / shrink, frame.1 / shrink], + ..Default::default() + } + }; + // The targets are never cleared, so a pass reads stale texels past what the one before + // it wrote. Each pass writes the clip grown by everything the passes after it read, which + // keeps those stale texels out of the clip. + let region = |renderer: &Self, level: usize, margin: f32| match clip { + Some(clip) => renderer.scissor(clip.dilate(ScaledPixels(margin)), 1 << level), + None => Ok(None), + }; + + let mut from = source; + for level in 1..=deepest { + let within = region(self, level, pyramid.down_margin(level))?; + from = self.filter_pass( + Pass::PyramidDown, + from, + FilterTarget::Level(level), + Some(params(level - 1, [0., 0.], 0.)), + within, + )?; + } + let within = region(self, deepest, pyramid.across_margin())?; + from = self.filter_pass( + Pass::Gaussian, + from, + FilterTarget::Spread(deepest), + Some(params(deepest, [1., 0.], pyramid.sigma)), + within, + )?; + let within = region(self, deepest, pyramid.along_margin())?; + from = self.filter_pass( + Pass::Gaussian, + from, + FilterTarget::Level(deepest), + Some(params(deepest, [0., 1.], pyramid.sigma)), + within, + )?; + for level in (0..deepest).rev() { + let within = region(self, level, pyramid.up_margin(level))?; + let target = match (level, spare) { + (0, Some(depth)) => FilterTarget::Layer(depth), + _ => FilterTarget::Level(level), + }; + from = self.filter_pass( + Pass::PyramidUp, + from, + target, + Some(params(level + 1, [0., 0.], 0.)), + within, + )?; + } + Ok(from) + } + + /// Draws one full-screen pass of a filter into a blur target, returning what it wrote. The + /// target is not cleared first, since the pass writes every texel it covers. + fn filter_pass( + &mut self, + pass: Pass, + source: Option, + target: FilterTarget, + params: Option, + within: Option<[u32; 4]>, + ) -> Result> { + let shrink = target.shrink(); + let target = self.filter_target(target)?; + let (view, held, viewport) = { + let resources = self.resources.as_ref().context("resources missing")?; + let (width, height) = level_size(&resources.viewport, shrink); + ( + target.view, + target.source, + D3D11_VIEWPORT { + TopLeftX: 0., + TopLeftY: 0., + Width: width as f32, + Height: height as f32, + MinDepth: 0., + MaxDepth: 1., + }, + ) + }; + let (device, device_context, sampler, batch_params) = self.pipeline_handles()?; + + unsafe { + device_context.OMSetRenderTargets(Some(slice::from_ref(&view)), None); + device_context.RSSetViewports(Some(slice::from_ref(&viewport))); + } + match within { + Some(within) => self.set_scissor(within), + None => self.set_scissor([0, 0, viewport.Width as u32, viewport.Height as u32]), + } + + let pipeline = match pass { + Pass::Gaussian => &mut self.pipelines.gaussian_pipeline, + Pass::PyramidDown => &mut self.pipelines.pyramid_down_pipeline, + Pass::PyramidUp => &mut self.pipelines.pyramid_up_pipeline, + }; + pipeline.update_buffer(&device, &device_context, &[params.unwrap_or_default()])?; + pipeline.draw_range_with_texture( + &device_context, + None, + slice::from_ref(&source), + &batch_params, + slice::from_ref(&Some(sampler)), + 0, + 1, + )?; + + Ok(held) + } + + /// Flattens open layers in source coordinates without changing their eventual composites. + fn backdrop_source( + &mut self, + depth: usize, + clip: Option>, + ) -> Result> { + let frame = self.filter_target(FilterTarget::Frame)?; + if depth == 0 { + return Ok(frame.source); + } + let target = self.filter_target(FilterTarget::Backdrop)?; + let mut sources = vec![frame.source]; + for level in 0..depth { + sources.push(self.filter_target(FilterTarget::Layer(level))?.source); + } + let (device, context, sampler, batch_params) = self.pipeline_handles()?; + let viewport = self + .resources + .as_ref() + .context("resources missing")? + .viewport; + let bounds = Bounds::new( + point(ScaledPixels(0.), ScaledPixels(0.)), + size(ScaledPixels(viewport.Width), ScaledPixels(viewport.Height)), + ); + let params = [FilterParams { + source_bounds: bounds, + fade_bounds: bounds, + scale: 1., + ..Default::default() + }]; + unsafe { + context.OMSetRenderTargets(Some(slice::from_ref(&target.view)), None); + context.ClearRenderTargetView( + target.view.as_ref().context("missing backdrop target")?, + &[0.; 4], + ); + context.RSSetViewports(Some(slice::from_ref(&viewport))); + } + match clip + .map(|clip| self.scissor(clip, 1)) + .transpose()? + .flatten() + { + Some(within) => self.set_scissor(within), + None => self.reset_scissor()?, + } + self.pipelines + .composite_pipeline + .update_buffer(&device, &context, ¶ms)?; + for source in sources { + self.pipelines.composite_pipeline.draw_range_with_texture( + &context, + None, + slice::from_ref(&source), + &batch_params, + slice::from_ref(&Some(sampler.clone())), + 0, + 1, + )?; + } + Ok(target.source) + } + + /// Blurs the frame within `clip`, the union of the batch's backdrops grown by the kernel + /// inside `blur_source`, and draws the batch over it. A backdrop samples only within its + /// own bounds, so nothing outside the union is worth blurring. + fn draw_backdrops( + &mut self, + first: usize, + count: usize, + sigma: f32, + clip: Option>, + mirrored: bool, + stack: &[usize], + ) -> Result<()> { + let frame = self.backdrop_source( + stack.len(), + clip.map(|clip| clip.dilate(BlurPasses::for_sigma(sigma).source_margin())), + )?; + let blurred = self.blur_source(frame, None, sigma, clip)?; + self.resume_target(stack, mirrored)?; + + let (_, device_context, sampler, batch_params) = self.pipeline_handles()?; + + // The hole first, the blurred copy into it second: together they are + // `dst = mix(dst, blurred, k)`, which leaves a see-through window as clear as it was. + self.pipelines.backdrop_pipeline.draw_range_with_texture( + &device_context, + Some(&self.pipelines.backdrop_punch), + slice::from_ref(&blurred), + &batch_params, + slice::from_ref(&Some(sampler.clone())), + first as u32, + count as u32, + )?; + self.pipelines.backdrop_pipeline.draw_range_with_texture( + &device_context, + None, + slice::from_ref(&blurred), + &batch_params, + slice::from_ref(&Some(sampler)), + first as u32, + count as u32, + ) + } + + /// Points the pipeline back at what the frame is drawn into, offscreen or not. + fn restore_frame(&self, mirrored: bool) -> Result<()> { + if mirrored { + return self.open_target(None); + } + + let resources = self.resources.as_ref().context("resources missing")?; + let devices = self.devices.as_ref().context("devices missing")?; + unsafe { + devices + .device_context + .OMSetRenderTargets(Some(slice::from_ref(&resources.render_target_view)), None); + devices + .device_context + .RSSetViewports(Some(slice::from_ref(&resources.viewport))); + } + self.reset_scissor()?; + + Ok(()) + } + + /// Copies the offscreen frame onto the swap chain. + fn blit_frame(&mut self) -> Result<()> { + let source = { + let resources = self.resources.as_ref().context("resources missing")?; + resources.filters.get(FilterTarget::Frame)?.source.clone() + }; + self.restore_frame(false)?; + + let (device, device_context, sampler, batch_params) = self.pipeline_handles()?; + + self.pipelines.blit_pipeline.update_buffer( + &device, + &device_context, + &[FilterParams::default()], + )?; + self.pipelines.blit_pipeline.draw_range_with_texture( + &device_context, + None, + slice::from_ref(&source), + &batch_params, + slice::from_ref(&Some(sampler)), + 0, + 1, + ) + } + + /// Clamps a region to the target it is drawn into, shrunk to the blur step it runs at. Every + /// texel the region touches is covered, so a blur level is written out to the frame's edge + /// even where the region starts part way into a texel. + fn scissor(&self, bounds: Bounds, shrink: u32) -> Result> { + let resources = self.resources.as_ref().context("resources missing")?; + let (width, height) = level_size(&resources.viewport, shrink); + let shrink = shrink as f32; + let edge = |at: f32, round: fn(f32) -> f32, limit: u32| { + (round(at / shrink).max(0.) as u32).min(limit) + }; + let left = edge(bounds.origin.x.0, f32::floor, width); + let top = edge(bounds.origin.y.0, f32::floor, height); + let right = edge(bounds.origin.x.0 + bounds.size.width.0, f32::ceil, width); + let bottom = edge(bounds.origin.y.0 + bounds.size.height.0, f32::ceil, height); + if right <= left || bottom <= top { + return Ok(None); + } + + Ok(Some([left, top, right - left, bottom - top])) + } + + fn set_scissor(&self, within: [u32; 4]) { + let Some(devices) = self.devices.as_ref() else { + return; + }; + let [left, top, width, height] = within; + unsafe { + devices.device_context.RSSetScissorRects(Some(&[RECT { + left: left as i32, + top: top as i32, + right: (left + width) as i32, + bottom: (top + height) as i32, + }])); + } + } + + fn reset_scissor(&self) -> Result<()> { + let resources = self.resources.as_ref().context("resources missing")?; + self.set_scissor([ + 0, + 0, + resources.viewport.Width as u32, + resources.viewport.Height as u32, + ]); + + Ok(()) + } + fn present(&mut self) -> Result<()> { let result = unsafe { self.resources @@ -358,7 +1132,9 @@ impl DirectXRenderer { return Ok(()); } self.render(scene, background_appearance)?; - self.present() + let presented = self.present(); + self.release_targets_idle_at(self.frame_time); + presented } /// Clear the render target for `background_appearance` and encode every @@ -371,6 +1147,7 @@ impl DirectXRenderer { scene: &Scene, background_appearance: WindowBackgroundAppearance, ) -> Result<()> { + self.frame_time = Instant::now(); let depth_scale = quad_depth_scale(scene.quads.len()); self.pre_draw( &match background_appearance { @@ -381,13 +1158,34 @@ impl DirectXRenderer { )?; self.upload_scene_buffers(scene)?; + // Backdrops read what the frame has drawn so far, which the swap chain cannot be sampled + // from, so a frame carrying them is drawn offscreen and blitted back at the end. + let mirrored = !scene.backdrops.is_empty(); + if mirrored { + let cleared = self.filter_target(FilterTarget::Frame)?.view; + let devices = self.devices.as_ref().context("devices missing")?; + if let Some(cleared) = cleared.as_ref() { + unsafe { + devices + .device_context + .ClearRenderTargetView(cleared, &[0.0f32; 4]) + }; + } + self.open_target(None)?; + } + + let mut stack: Vec = Vec::new(); + // What each open layer will be composited through: neighbours that ask for the same filter + // share one target, so a list of separately blurred rows costs one pass, not one per row. + let mut spans: Vec> = Vec::new(); + let annotation = self .devices .as_ref() .and_then(|devices| devices.annotation.clone()) .filter(|annotation| unsafe { annotation.GetStatus().as_bool() }); - if !scene.quads.is_empty() { + if DEPTH_PREPASS && !scene.quads.is_empty() { let _annotation = annotation.as_ref().map(|annotation| { Annotation::new( annotation, @@ -404,13 +1202,58 @@ impl DirectXRenderer { .as_ref() .map(|annotation| Annotation::new(annotation, HSTRING::from(batch.label()))); + let wanted = scene + .filtered(scene.batch_order(&batch)) + .map(|index| scene.filter_chain(index)) + .unwrap_or_default(); + let shared = stack + .iter() + .zip(wanted.iter()) + .take_while(|(open, next)| open == next) + .count(); + + let mut merged = false; + while stack.len() > shared { + if stack.len() == shared + 1 + && wanted.len() == stack.len() + && let Some(open) = stack.last_mut() + && let Some(span) = spans.last_mut() + { + let next = scene.effects[wanted[shared]]; + let layer = scene.effects[*open]; + if layer.can_merge_with(&next) { + *open = wanted[shared]; + *span = span.union(&next.destination_clip()); + merged = true; + break; + } + } + + let index = stack.pop().expect("the stack is not empty"); + let layer = scene.effects[index]; + let clip = spans.pop().unwrap_or_else(|| layer.destination_clip()); + self.close_layer(&stack, layer, clip, mirrored)?; + } + + for index in wanted.iter().skip(shared + usize::from(merged)) { + if stack.len() >= LAYER_DEPTH { + break; + } + let layer = scene.effects[*index]; + self.open_layer(stack.len())?; + stack.push(*index); + spans.push(layer.destination_clip()); + } + // Quad shaders assign each quad its own depth. // In every other batch type, the depth is fixed to the position of the quad cursor. - if matches!(&batch, PrimitiveBatch::Quads(_)) { - self.set_viewport_depth_range(0.0, 1.0)?; - } else { - let depth = quad_depth(quad_cursor, depth_scale); - self.set_viewport_depth_range(depth, depth)?; + if DEPTH_PREPASS { + if matches!(&batch, PrimitiveBatch::Quads(_)) { + self.set_viewport_depth_range(0.0, 1.0)?; + } else { + let depth = quad_depth(quad_cursor, depth_scale); + self.set_viewport_depth_range(depth, depth)?; + } } match batch { @@ -419,6 +1262,9 @@ impl DirectXRenderer { quad_cursor += range.len() as u32; self.draw_quads(range.start, range.len()) } + PrimitiveBatch::Shaders { shader, range } => { + self.draw_custom_shaders(shader, range.start, range.len()) + } PrimitiveBatch::Paths(range) => { let tiles_start = path_tile_cursor; path_tile_cursor += scene.paths[range] @@ -432,11 +1278,26 @@ impl DirectXRenderer { self.draw_monochrome_sprites(texture_id, range.start, range.len()) } PrimitiveBatch::SubpixelSprites { texture_id, range } => { - self.draw_subpixel_sprites(texture_id, range.start, range.len()) + let into_layer = !stack.is_empty(); + self.draw_subpixel_sprites(texture_id, range.start, range.len(), into_layer) } PrimitiveBatch::PolychromeSprites { texture_id, range } => { self.draw_polychrome_sprites(texture_id, range.start, range.len()) } + PrimitiveBatch::Backdrops(range) => { + { + let backdrops = &scene.backdrops[range.clone()]; + let sigma = backdrops + .iter() + .fold(0., |widest: f32, backdrop| widest.max(backdrop.blur)); + let clip = backdrops + .iter() + .map(|backdrop| backdrop.bounds) + .reduce(|union, bounds| union.union(&bounds)); + self.draw_backdrops(range.start, range.len(), sigma, clip, mirrored, &stack)?; + } + Ok(()) + } PrimitiveBatch::Surfaces(range) => self.draw_surfaces(&scene.surfaces[range]), } .with_context(|| { @@ -454,16 +1315,54 @@ impl DirectXRenderer { ) })?; } + + while let Some(index) = stack.pop() { + let layer = scene.effects[index]; + let clip = spans.pop().unwrap_or_else(|| layer.destination_clip()); + self.close_layer(&stack, layer, clip, mirrored)?; + } + + if mirrored { + self.blit_frame()?; + } + self.discard_depth_buffer(); Ok(()) } + /// Frees offscreen targets that no frame has drawn through for `IDLE_RELEASE`. Every frame + /// checks this itself, so a caller only needs it for a window that has stopped drawing. + pub(crate) fn release_idle_targets(&mut self) { + self.release_targets_idle_at(Instant::now()); + } + + /// Drops every offscreen target that no frame has drawn through within `IDLE_RELEASE` of + /// `now`. The device context keeps a texture alive until the work that uses it is done, so + /// this is safe while earlier frames are still in flight. + fn release_targets_idle_at(&mut self, now: Instant) { + let Some(resources) = self.resources.as_mut() else { + return; + }; + resources.filters.release_idle(now); + } + + /// One filter target, created if no frame has drawn through it since it was last released. + fn filter_target(&mut self, target: FilterTarget) -> Result { + let now = self.frame_time; + let device = &self.devices.as_ref().context("devices missing")?.device; + self.resources + .as_mut() + .context("resources missing")? + .filters + .touch(device, target, now) + } + /// Render `scene` to an offscreen CPU image **without presenting** so /// the window need never be shown or visible (the macOS headless path /// goes through MetalRenderer; this is the Windows analogue). Draws into /// the existing render target, copies it into a `D3D11_USAGE_STAGING` /// texture, maps it, and converts BGRA to RGBA. - #[cfg(feature = "test-support")] + #[cfg(any(test, feature = "test-support"))] pub(crate) fn render_to_image( &mut self, scene: &Scene, @@ -622,6 +1521,14 @@ impl DirectXRenderer { )?; } + if !scene.backdrops.is_empty() { + self.pipelines.backdrop_pipeline.update_buffer( + &devices.device, + &devices.device_context, + &scene.backdrops, + )?; + } + if !scene.quads.is_empty() { self.pipelines.quad_pipeline.update_buffer( &devices.device, @@ -630,6 +1537,14 @@ impl DirectXRenderer { )?; } + if !scene.shaders.is_empty() { + self.pipelines.custom_shaders.update_buffer( + &devices.device, + &devices.device_context, + &scene.shaders, + )?; + } + if !scene.paths.is_empty() { let mut paints = Vec::with_capacity(scene.paths.len()); let mut curves = Vec::new(); @@ -649,18 +1564,6 @@ impl DirectXRenderer { self.pipelines .path_paints .write(&devices.device, &devices.device_context, &paints)?; - let buffers = [ - self.pipelines.path_curves.view.clone(), - self.pipelines.path_paints.view.clone(), - ]; - unsafe { - devices - .device_context - .VSSetShaderResources(2, Some(&buffers)); - devices - .device_context - .PSSetShaderResources(2, Some(&buffers)); - } } if !scene.underlines.is_empty() { @@ -730,11 +1633,46 @@ impl DirectXRenderer { ) } + fn draw_custom_shaders(&mut self, shader: ShaderId, start: usize, len: usize) -> Result<()> { + if len == 0 { + return Ok(()); + } + let devices = self.devices.as_ref().context("devices missing")?; + let viewport = self + .resources + .as_ref() + .context("resources missing")? + .viewport; + self.pipelines.custom_shaders.draw( + &devices.device, + &devices.device_context, + shader, + [viewport.Width, viewport.Height], + start as u32, + len as u32, + ) + } + + /// Draws a range of the frame's path tiles. The curves and paints are bound here for every + /// draw rather than once per frame, since a custom shader takes register `t2` for its + /// instances. fn draw_paths(&mut self, tile_range: Range) -> Result<()> { if tile_range.is_empty() { return Ok(()); } let devices = self.devices.as_ref().context("devices missing")?; + let buffers = [ + self.pipelines.path_curves.view.clone(), + self.pipelines.path_paints.view.clone(), + ]; + unsafe { + devices + .device_context + .VSSetShaderResources(2, Some(&buffers)); + devices + .device_context + .PSSetShaderResources(2, Some(&buffers)); + } self.pipelines.path_tile_pipeline.draw_range( &devices.device_context, self.globals @@ -777,6 +1715,7 @@ impl DirectXRenderer { }; self.pipelines.mono_sprites.draw_range_with_texture( &devices.device_context, + None, &texture_view, self.globals .batch_params_buffer @@ -793,6 +1732,7 @@ impl DirectXRenderer { texture_id: AtlasTextureId, start: usize, len: usize, + into_layer: bool, ) -> Result<()> { if len == 0 { return Ok(()); @@ -801,13 +1741,21 @@ impl DirectXRenderer { let Some(texture_view) = self.atlas.get_texture_view(texture_id) else { return Ok(()); }; + let batch_params = self + .globals + .batch_params_buffer + .as_ref() + .context("batch params buffer missing")?; + // See `subpixel_sprite_layered_fragment` for why a layer needs a different blend. + let shading = match into_layer { + true => Some(&self.pipelines.subpixel_sprites_layered), + false => None, + }; self.pipelines.subpixel_sprites.draw_range_with_texture( &devices.device_context, + shading, &texture_view, - self.globals - .batch_params_buffer - .as_ref() - .context("batch params buffer missing")?, + batch_params, slice::from_ref(&self.globals.sampler), start as u32, len as u32, @@ -829,6 +1777,7 @@ impl DirectXRenderer { }; self.pipelines.poly_sprites.draw_range_with_texture( &devices.device_context, + None, &texture_view, self.globals .batch_params_buffer @@ -923,10 +1872,12 @@ impl DirectXResources { depth_stencil_view, viewport, ) = create_resources(devices, &swap_chain, width, height)?; + let filters = FilterTargets::new(width, height); set_rasterizer_state(&devices.device, &devices.device_context)?; Ok(Self { swap_chain, + filters, render_target: Some(render_target), render_target_view, depth_stencil_texture, @@ -949,6 +1900,8 @@ impl DirectXResources { depth_stencil_view, viewport, ) = create_resources(devices, &self.swap_chain, width, height)?; + // The offscreen targets are rebuilt at the new size by the first frame that needs them. + self.filters = FilterTargets::new(width, height); self.render_target = Some(render_target); self.render_target_view = render_target_view; self.depth_stencil_texture = depth_stencil_texture; @@ -960,6 +1913,63 @@ impl DirectXResources { impl DirectXRenderPipelines { pub fn new(device: &ID3D11Device) -> Result { + // A backdrop mixes the blurred copy into what it covers instead of laying it over: + // the punch scales the destination by `1 - k`, the additive draw after it adds + // `blurred * k`. Laying it over cost a see-through window its transparency. + let backdrop_pipeline = PipelineState::new( + device, + "backdrop_pipeline", + ShaderModule::Backdrop, + 16, + create_blend_state_additive(device)?, + )?; + let backdrop_punch = Shading::new( + device, + ShaderModule::BackdropPunch, + create_blend_state_punch(device)?, + )?; + let gaussian_pipeline = PipelineState::new( + device, + "gaussian_pipeline", + ShaderModule::Gaussian, + 1, + create_blend_state_opaque(device)?, + )?; + let pyramid_down_pipeline = PipelineState::new( + device, + "pyramid_down_pipeline", + ShaderModule::PyramidDown, + 1, + create_blend_state_opaque(device)?, + )?; + let pyramid_up_pipeline = PipelineState::new( + device, + "pyramid_up_pipeline", + ShaderModule::PyramidUp, + 1, + create_blend_state_opaque(device)?, + )?; + let blit_pipeline = PipelineState::new( + device, + "blit_pipeline", + ShaderModule::Blit, + 1, + create_blend_state_opaque(device)?, + )?; + let composite_pipeline = PipelineState::new( + device, + "composite_pipeline", + ShaderModule::Mask, + 1, + create_blend_state_premultiplied(device)?, + )?; + let mask_pipeline = PipelineState::new( + device, + "mask_pipeline", + ShaderModule::Mask, + 1, + create_blend_state_premultiplied(device)?, + )?; let shadow_pipeline = PipelineState::new( device, "shadow_pipeline", @@ -1004,6 +2014,13 @@ impl DirectXRenderPipelines { 512, create_blend_state_for_subpixel_rendering(device)?, )?; + // The same glyphs, for when they land in an offscreen layer instead of the frame; + // see `subpixel_sprite_layered_fragment`. + let subpixel_sprites_layered = Shading::new( + device, + ShaderModule::SubpixelSpriteLayered, + create_blend_state_premultiplied(device)?, + )?; let poly_sprites = PipelineState::new( device, "polychrome_sprite_pipeline", @@ -1014,6 +2031,14 @@ impl DirectXRenderPipelines { let opaque_quad_pipeline = OpaqueQuadPipeline::new(device)?; Ok(Self { + backdrop_pipeline, + backdrop_punch, + gaussian_pipeline, + pyramid_down_pipeline, + pyramid_up_pipeline, + blit_pipeline, + composite_pipeline, + mask_pipeline, shadow_pipeline, quad_pipeline, opaque_quad_pipeline, @@ -1023,7 +2048,9 @@ impl DirectXRenderPipelines { underline_pipeline, mono_sprites, subpixel_sprites, + subpixel_sprites_layered, poly_sprites, + custom_shaders: CustomShaders::new(device)?, }) } } @@ -1056,28 +2083,14 @@ impl DirectXGlobalElements { let global_params_buffer = create_constant_buffer::(device)?; let batch_params_buffer = create_constant_buffer::(device)?; - let sampler = unsafe { - let desc = D3D11_SAMPLER_DESC { - Filter: D3D11_FILTER_MIN_MAG_MIP_LINEAR, - AddressU: D3D11_TEXTURE_ADDRESS_WRAP, - AddressV: D3D11_TEXTURE_ADDRESS_WRAP, - AddressW: D3D11_TEXTURE_ADDRESS_WRAP, - MipLODBias: 0.0, - MaxAnisotropy: 1, - ComparisonFunc: D3D11_COMPARISON_ALWAYS, - BorderColor: [0.0; 4], - MinLOD: 0.0, - MaxLOD: D3D11_FLOAT32_MAX, - }; - let mut output = None; - device.CreateSamplerState(&desc, Some(&mut output))?; - output - }; + let sampler = create_sampler(device, D3D11_TEXTURE_ADDRESS_WRAP)?; + let filter_sampler = create_sampler(device, D3D11_TEXTURE_ADDRESS_CLAMP)?; Ok(Self { global_params_buffer, batch_params_buffer, sampler, + filter_sampler, }) } } @@ -1109,6 +2122,30 @@ struct StructuredBuffer { _marker: std::marker::PhantomData, } +/// A second way to shade a pipeline's instances: its own fragment stage and blend over the +/// vertex stage and the instance buffer of the pipeline it is handed to. +struct Shading { + fragment: ID3D11PixelShader, + blend_state: ID3D11BlendState, +} + +impl Shading { + /// Takes the fragment stage of `shader_module`. The module needs no vertex entry point of + /// its own, since the draw keeps the pipeline's. + fn new( + device: &ID3D11Device, + shader_module: ShaderModule, + blend_state: ID3D11BlendState, + ) -> Result { + let raw_shader = RawShaderBytes::new(shader_module, ShaderTarget::Fragment)?; + let fragment = create_fragment_shader(device, raw_shader.as_bytes())?; + Ok(Shading { + fragment, + blend_state, + }) + } +} + impl StructuredBuffer { fn new(device: &ID3D11Device, label: &'static str, capacity: usize) -> Result { let buffer = create_buffer(device, std::mem::size_of::(), capacity)?; @@ -1227,9 +2264,13 @@ impl PipelineState { Ok(()) } + /// Draws a range of this pipeline's instances. `shading` replaces the fragment stage and + /// the blend for this draw alone, which is how one batch of instances is drawn two ways + /// without a second copy of it on the GPU. fn draw_range_with_texture( &self, device_context: &ID3D11DeviceContext, + shading: Option<&Shading>, texture: &[Option], batch_params_buffer: &ID3D11Buffer, sampler: &[Option], @@ -1237,14 +2278,18 @@ impl PipelineState { instance_count: u32, ) -> Result<()> { self.ensure_range(first_instance, instance_count)?; + let (fragment, blend_state) = match shading { + Some(shading) => (&shading.fragment, &shading.blend_state), + None => (&self.fragment, &self.blend_state), + }; update_batch_start(device_context, batch_params_buffer, first_instance)?; set_pipeline_state( device_context, slice::from_ref(&self.instances.view), D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, &self.vertex, - &self.fragment, - &self.blend_state, + fragment, + blend_state, &self.depth_stencil_state, ); unsafe { @@ -1266,6 +2311,166 @@ impl PipelineState { } } +/// The globals the custom shader prelude reads, laid out as its `GpuiShaderGlobals`. +#[derive(Clone, Copy)] +#[repr(C)] +struct CustomShaderGlobals { + viewport_size: [f32; 2], + premultiplied_alpha: u32, + pad: u32, +} + +/// The constants naga adds to `SV_VertexID` and `SV_InstanceID`, which Direct3D 11 counts from +/// zero in every draw, so the shader indexes the instances of its batch. +#[derive(Clone, Copy)] +#[repr(C)] +struct NagaConstants { + first_vertex: i32, + first_instance: i32, + other: u32, + pad: u32, +} + +/// The stages of one custom shader, compiled from its HLSL translation. +struct CustomPipeline { + vertex: ID3D11VertexShader, + fragment: ID3D11PixelShader, +} + +/// Everything custom shaders draw with: a raw buffer of the frame's instances, since naga reads +/// storage buffers as `ByteAddressBuffer`, the two constant buffers the prelude reads, and a +/// pipeline per shader, compiled the first time a frame draws it. +struct CustomShaders { + buffer: Option, + view: Option, + /// How many instances the buffer holds. + capacity: usize, + globals: Option, + constants: Option, + blend_state: ID3D11BlendState, + /// A shader that failed to compile is kept as `None`, so it is not compiled again every + /// frame. + pipelines: FxHashMap>, +} + +impl CustomShaders { + fn new(device: &ID3D11Device) -> Result { + Ok(Self { + buffer: None, + view: None, + capacity: 0, + globals: create_constant_buffer::(device)?, + constants: create_constant_buffer::(device)?, + blend_state: create_blend_state(device)?, + pipelines: FxHashMap::default(), + }) + } + + fn update_buffer( + &mut self, + device: &ID3D11Device, + device_context: &ID3D11DeviceContext, + data: &[ShaderQuad], + ) -> Result<()> { + if self.capacity < data.len() || self.buffer.is_none() { + let element_size = std::mem::size_of::(); + let required_size = std::mem::size_of_val(data); + anyhow::ensure!( + required_size <= MAX_INSTANCE_BUFFER_SIZE, + "custom shader buffer needs {required_size} bytes, above the maximum of {MAX_INSTANCE_BUFFER_SIZE}" + ); + let capacity = data + .len() + .next_power_of_two() + .max(16) + .min(MAX_INSTANCE_BUFFER_SIZE / element_size); + let buffer = create_raw_buffer(device, element_size * capacity)?; + self.view = create_raw_buffer_view(device, &buffer, element_size * capacity)?; + self.buffer = Some(buffer); + self.capacity = capacity; + } + let buffer = self + .buffer + .as_ref() + .context("custom shader buffer missing")?; + update_buffer(device_context, buffer, data) + } + + /// Draws `count` instances of `shader` from `first` on, or nothing when the shader does not + /// compile on this device. + fn draw( + &mut self, + device: &ID3D11Device, + device_context: &ID3D11DeviceContext, + shader: ShaderId, + viewport_size: [f32; 2], + first: u32, + count: u32, + ) -> Result<()> { + anyhow::ensure!( + (first + count) as usize <= self.capacity, + "DirectX instance range exceeds the custom shader buffer" + ); + let pipeline = self.pipelines.entry(shader).or_insert_with(|| { + compile_custom_pipeline(device, shader) + .inspect_err(|error| log::error!("{error:#}")) + .ok() + }); + let Some(pipeline) = pipeline else { + return Ok(()); + }; + + // Quads blend straight alpha here, so the prelude leaves its colour unpremultiplied. + let globals = self + .globals + .as_ref() + .context("custom shader globals missing")?; + update_buffer( + device_context, + globals, + &[CustomShaderGlobals { + viewport_size, + premultiplied_alpha: 0, + pad: 0, + }], + )?; + let constants = self + .constants + .as_ref() + .context("custom shader constants missing")?; + update_buffer( + device_context, + constants, + &[NagaConstants { + first_vertex: 0, + first_instance: first as i32, + other: 0, + pad: 0, + }], + )?; + + let globals_slot = gpui::HlslShader::GLOBALS_REGISTER; + let constants_slot = gpui::HlslShader::CONSTANTS_REGISTER; + let instances_slot = gpui::HlslShader::INSTANCES_REGISTER; + unsafe { + device_context.VSSetConstantBuffers(globals_slot, Some(slice::from_ref(&self.globals))); + device_context.PSSetConstantBuffers(globals_slot, Some(slice::from_ref(&self.globals))); + device_context + .VSSetConstantBuffers(constants_slot, Some(slice::from_ref(&self.constants))); + device_context + .PSSetConstantBuffers(constants_slot, Some(slice::from_ref(&self.constants))); + device_context.VSSetShaderResources(instances_slot, Some(slice::from_ref(&self.view))); + device_context.PSSetShaderResources(instances_slot, Some(slice::from_ref(&self.view))); + device_context.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); + device_context.VSSetShader(&pipeline.vertex, None); + device_context.PSSetShader(&pipeline.fragment, None); + device_context.OMSetBlendState(&self.blend_state, None, 0xFFFFFFFF); + device_context.DrawInstanced(4, count, 0, 0); + } + Ok(()) + } +} + /// Draws opaque rectangles ahead of everything else, writing depth so that /// later passes skip the pixels they cover. struct OpaqueQuadPipeline { @@ -1323,6 +2528,72 @@ impl OpaqueQuadPipeline { } } +/// Translates a custom shader to HLSL and compiles both of its stages for shader model 5.0, +/// which needs a device of feature level 11 or above. +fn compile_custom_pipeline(device: &ID3D11Device, shader: ShaderId) -> Result { + let program = gpui::shader_program(shader) + .with_context(|| format!("custom shader {} was never registered", shader.0))?; + anyhow::ensure!( + unsafe { device.GetFeatureLevel() }.0 >= D3D_FEATURE_LEVEL_11_0.0, + "custom shader `{}` needs Direct3D feature level 11", + program.label + ); + let hlsl = program.to_hlsl()?; + let vertex = compile_hlsl(&hlsl.source, &hlsl.vertex_entry, "vs_5_0", &program.label)?; + let fragment = compile_hlsl(&hlsl.source, &hlsl.fragment_entry, "ps_5_0", &program.label)?; + Ok(CustomPipeline { + vertex: create_vertex_shader(device, blob_bytes(&vertex))?, + fragment: create_fragment_shader(device, blob_bytes(&fragment))?, + }) +} + +/// Compiles one entry point of HLSL source with the system's `d3dcompiler_47.dll`. +fn compile_hlsl( + source: &str, + entry: &str, + target: &str, + label: &str, +) -> Result { + use windows::Win32::Graphics::Direct3D::{ + Fxc::{D3DCOMPILE_OPTIMIZATION_LEVEL3, D3DCompile}, + ID3DInclude, + }; + use windows::core::PCSTR; + + let entry = std::ffi::CString::new(entry)?; + let target = std::ffi::CString::new(target)?; + let name = std::ffi::CString::new(label)?; + let mut code = None; + let mut errors = None; + let result = unsafe { + D3DCompile( + source.as_ptr().cast(), + source.len(), + PCSTR::from_raw(name.as_ptr().cast()), + None, + None::<&ID3DInclude>, + PCSTR::from_raw(entry.as_ptr().cast()), + PCSTR::from_raw(target.as_ptr().cast()), + D3DCOMPILE_OPTIMIZATION_LEVEL3, + 0, + &mut code, + Some(&mut errors), + ) + }; + if let Err(error) = result { + let message = errors + .as_ref() + .map(|errors| String::from_utf8_lossy(blob_bytes(errors)).into_owned()) + .unwrap_or_else(|| error.to_string()); + anyhow::bail!("custom shader `{label}` failed to compile: {message}"); + } + code.context("the shader compiler returned no bytecode") +} + +fn blob_bytes(blob: &windows::Win32::Graphics::Direct3D::ID3DBlob) -> &[u8] { + unsafe { slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()) } +} + impl Drop for DirectXRenderer { fn drop(&mut self) { #[cfg(debug_assertions)] @@ -1403,14 +2674,20 @@ fn create_resources( ) -> Result<( ID3D11Texture2D, Option, - ID3D11Texture2D, + Option, Option, D3D11_VIEWPORT, )> { let (render_target, render_target_view) = create_render_target_and_its_view(swap_chain, &devices.device)?; - let (depth_stencil_texture, depth_stencil_view) = - create_depth_stencil_texture_and_view(&devices.device, width, height)?; + let (depth_stencil_texture, depth_stencil_view) = match DEPTH_PREPASS { + true => { + let (texture, view) = + create_depth_stencil_texture_and_view(&devices.device, width, height)?; + (Some(texture), view) + } + false => (None, None), + }; let viewport = set_viewport(&devices.device_context, width as f32, height as f32); Ok(( render_target, @@ -1487,7 +2764,7 @@ fn set_rasterizer_state(device: &ID3D11Device, device_context: &ID3D11DeviceCont DepthBiasClamp: 0.0, SlopeScaledDepthBias: 0.0, DepthClipEnable: true.into(), - ScissorEnable: false.into(), + ScissorEnable: true.into(), MultisampleEnable: true.into(), AntialiasedLineEnable: false.into(), }; @@ -1519,6 +2796,120 @@ fn create_blend_state(device: &ID3D11Device) -> Result { } } +/// Layers arrive already multiplied by their own alpha, so their colour must not be scaled again. +#[inline] +fn create_blend_state_premultiplied(device: &ID3D11Device) -> Result { + let mut desc = D3D11_BLEND_DESC::default(); + desc.RenderTarget[0].BlendEnable = true.into(); + desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; + desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; + desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; + desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; + desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; + desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA; + desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8; + unsafe { + let mut state = None; + device.CreateBlendState(&desc, Some(&mut state))?; + Ok(state.unwrap()) + } +} + +/// The first half of a backdrop's mix: the source contributes nothing of its own and the +/// destination keeps `1 - src.a` of itself, colour and alpha together, so the blurred copy +/// drawn after it lands in a hole rather than on top of what it replaces. +#[inline] +fn create_blend_state_punch(device: &ID3D11Device) -> Result { + let mut desc = D3D11_BLEND_DESC::default(); + desc.RenderTarget[0].BlendEnable = true.into(); + desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; + desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; + desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ZERO; + desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO; + desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; + desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA; + desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8; + unsafe { + let mut state = None; + device.CreateBlendState(&desc, Some(&mut state))?; + Ok(state.unwrap()) + } +} + +/// The second half: the blurred copy is added into the hole the punch left. +#[inline] +fn create_blend_state_additive(device: &ID3D11Device) -> Result { + let mut desc = D3D11_BLEND_DESC::default(); + desc.RenderTarget[0].BlendEnable = true.into(); + desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; + desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; + desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; + desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; + desc.RenderTarget[0].DestBlend = D3D11_BLEND_ONE; + desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE; + desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8; + unsafe { + let mut state = None; + device.CreateBlendState(&desc, Some(&mut state))?; + Ok(state.unwrap()) + } +} + +/// Blur and blit passes own every pixel they touch. +#[inline] +fn create_blend_state_opaque(device: &ID3D11Device) -> Result { + let mut desc = D3D11_BLEND_DESC::default(); + desc.RenderTarget[0].BlendEnable = false.into(); + desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; + desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; + desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; + desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; + desc.RenderTarget[0].DestBlend = D3D11_BLEND_ZERO; + desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; + desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8; + unsafe { + let mut state = None; + device.CreateBlendState(&desc, Some(&mut state))?; + Ok(state.unwrap()) + } +} + +#[inline] +fn create_render_texture(device: &ID3D11Device, width: u32, height: u32) -> Result { + let texture = unsafe { + let mut output = None; + let desc = D3D11_TEXTURE2D_DESC { + Width: width.max(1), + Height: height.max(1), + MipLevels: 1, + ArraySize: 1, + Format: RENDER_TARGET_FORMAT, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Usage: D3D11_USAGE_DEFAULT, + BindFlags: (D3D11_BIND_RENDER_TARGET.0 | D3D11_BIND_SHADER_RESOURCE.0) as u32, + CPUAccessFlags: 0, + MiscFlags: 0, + }; + device.CreateTexture2D(&desc, None, Some(&mut output))?; + output.unwrap() + }; + let mut view = None; + let mut source = None; + unsafe { + device.CreateRenderTargetView(&texture, None, Some(&mut view))?; + device.CreateShaderResourceView(&texture, None, Some(&mut source))?; + } + + Ok(RenderTexture { + _texture: texture, + view, + source, + }) +} + #[inline] fn create_opaque_blend_state(device: &ID3D11Device) -> Result { let mut desc = D3D11_BLEND_DESC::default(); @@ -1549,7 +2940,7 @@ fn create_depth_stencil_state( StencilFunc: D3D11_COMPARISON_ALWAYS, }; let desc = D3D11_DEPTH_STENCIL_DESC { - DepthEnable: true.into(), + DepthEnable: DEPTH_PREPASS.into(), DepthWriteMask: write_mask, DepthFunc: D3D11_COMPARISON_GREATER, StencilEnable: false.into(), @@ -1644,6 +3035,42 @@ fn create_buffer( Ok(buffer.unwrap()) } +/// A buffer shaders read as a `ByteAddressBuffer`, written from the CPU every frame. +fn create_raw_buffer(device: &ID3D11Device, size: usize) -> Result { + let desc = D3D11_BUFFER_DESC { + ByteWidth: size as u32, + Usage: D3D11_USAGE_DYNAMIC, + BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32, + CPUAccessFlags: D3D11_CPU_ACCESS_WRITE.0 as u32, + MiscFlags: D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS.0 as u32, + StructureByteStride: 0, + }; + let mut buffer = None; + unsafe { device.CreateBuffer(&desc, None, Some(&mut buffer)) }?; + buffer.context("the device returned no buffer") +} + +fn create_raw_buffer_view( + device: &ID3D11Device, + buffer: &ID3D11Buffer, + size: usize, +) -> Result> { + let desc = D3D11_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D11_SRV_DIMENSION_BUFFEREX, + Anonymous: D3D11_SHADER_RESOURCE_VIEW_DESC_0 { + BufferEx: D3D11_BUFFEREX_SRV { + FirstElement: 0, + NumElements: (size / 4) as u32, + Flags: D3D11_BUFFEREX_SRV_FLAG_RAW.0 as u32, + }, + }, + }; + let mut view = None; + unsafe { device.CreateShaderResourceView(buffer, Some(&desc), Some(&mut view)) }?; + Ok(view) +} + #[inline] fn create_buffer_view( device: &ID3D11Device, @@ -1731,6 +3158,15 @@ pub(crate) mod shader_resources { #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub(crate) enum ShaderModule { + Backdrop, + /// Fragment only. `vertex_source` sends it to `Backdrop` for a vertex stage. + BackdropPunch, + Gaussian, + PyramidDown, + /// Fragment only. `vertex_source` sends it to `PyramidDown` for a vertex stage. + PyramidUp, + Blit, + Mask, Quad, OpaqueQuad, Shadow, @@ -1738,6 +3174,8 @@ pub(crate) mod shader_resources { PathTile, MonochromeSprite, SubpixelSprite, + /// Fragment only. `vertex_source` sends it to `SubpixelSprite` for a vertex stage. + SubpixelSpriteLayered, PolychromeSprite, } @@ -1754,8 +3192,25 @@ pub(crate) mod shader_resources { _blob: ID3DBlob, } + impl ShaderModule { + /// Where the vertex stage of this module comes from. A fragment-only module borrows + /// another's, so asking it for a vertex shader answers with that one. + fn vertex_source(self) -> ShaderModule { + match self { + ShaderModule::BackdropPunch => ShaderModule::Backdrop, + ShaderModule::PyramidUp => ShaderModule::PyramidDown, + ShaderModule::SubpixelSpriteLayered => ShaderModule::SubpixelSprite, + module => module, + } + } + } + impl<'t> RawShaderBytes<'t> { pub(crate) fn new(module: ShaderModule, target: ShaderTarget) -> Result { + let module = match target { + ShaderTarget::Vertex => module.vertex_source(), + ShaderTarget::Fragment => module, + }; #[cfg(not(debug_assertions))] { Ok(Self::from_bytes(module, target)) @@ -1780,6 +3235,34 @@ pub(crate) mod shader_resources { #[cfg(not(debug_assertions))] fn from_bytes(module: ShaderModule, target: ShaderTarget) -> Self { let bytes = match module { + ShaderModule::Backdrop => match target { + ShaderTarget::Vertex => BACKDROP_VERTEX_BYTES, + ShaderTarget::Fragment => BACKDROP_FRAGMENT_BYTES, + }, + ShaderModule::BackdropPunch => match target { + ShaderTarget::Vertex => BACKDROP_VERTEX_BYTES, + ShaderTarget::Fragment => BACKDROP_PUNCH_FRAGMENT_BYTES, + }, + ShaderModule::Gaussian => match target { + ShaderTarget::Vertex => GAUSSIAN_VERTEX_BYTES, + ShaderTarget::Fragment => GAUSSIAN_FRAGMENT_BYTES, + }, + ShaderModule::PyramidDown => match target { + ShaderTarget::Vertex => PYRAMID_DOWN_VERTEX_BYTES, + ShaderTarget::Fragment => PYRAMID_DOWN_FRAGMENT_BYTES, + }, + ShaderModule::PyramidUp => match target { + ShaderTarget::Vertex => PYRAMID_DOWN_VERTEX_BYTES, + ShaderTarget::Fragment => PYRAMID_UP_FRAGMENT_BYTES, + }, + ShaderModule::Blit => match target { + ShaderTarget::Vertex => BLIT_VERTEX_BYTES, + ShaderTarget::Fragment => BLIT_FRAGMENT_BYTES, + }, + ShaderModule::Mask => match target { + ShaderTarget::Vertex => MASK_VERTEX_BYTES, + ShaderTarget::Fragment => MASK_FRAGMENT_BYTES, + }, ShaderModule::Quad => match target { ShaderTarget::Vertex => QUAD_VERTEX_BYTES, ShaderTarget::Fragment => QUAD_FRAGMENT_BYTES, @@ -1808,6 +3291,10 @@ pub(crate) mod shader_resources { ShaderTarget::Vertex => SUBPIXEL_SPRITE_VERTEX_BYTES, ShaderTarget::Fragment => SUBPIXEL_SPRITE_FRAGMENT_BYTES, }, + ShaderModule::SubpixelSpriteLayered => match target { + ShaderTarget::Vertex => SUBPIXEL_SPRITE_VERTEX_BYTES, + ShaderTarget::Fragment => SUBPIXEL_SPRITE_LAYERED_FRAGMENT_BYTES, + }, ShaderModule::PolychromeSprite => match target { ShaderTarget::Vertex => POLYCHROME_SPRITE_VERTEX_BYTES, ShaderTarget::Fragment => POLYCHROME_SPRITE_FRAGMENT_BYTES, @@ -1884,6 +3371,13 @@ pub(crate) mod shader_resources { impl ShaderModule { pub fn as_str(self) -> &'static str { match self { + ShaderModule::Backdrop => "backdrop", + ShaderModule::BackdropPunch => "backdrop_punch", + ShaderModule::Gaussian => "gaussian", + ShaderModule::PyramidDown => "pyramid_down", + ShaderModule::PyramidUp => "pyramid_up", + ShaderModule::Blit => "blit", + ShaderModule::Mask => "mask", ShaderModule::Quad => "quad", ShaderModule::OpaqueQuad => "opaque_quad", ShaderModule::Shadow => "shadow", @@ -1891,6 +3385,7 @@ pub(crate) mod shader_resources { ShaderModule::PathTile => "path_tile", ShaderModule::MonochromeSprite => "monochrome_sprite", ShaderModule::SubpixelSprite => "subpixel_sprite", + ShaderModule::SubpixelSpriteLayered => "subpixel_sprite_layered", ShaderModule::PolychromeSprite => "polychrome_sprite", } } @@ -2079,3 +3574,76 @@ mod dxgi { )) } } + +/// A linear sampler that treats coordinates outside a texture with `address`. +fn create_sampler( + device: &ID3D11Device, + address: D3D11_TEXTURE_ADDRESS_MODE, +) -> Result> { + let desc = D3D11_SAMPLER_DESC { + Filter: D3D11_FILTER_MIN_MAG_MIP_LINEAR, + AddressU: address, + AddressV: address, + AddressW: address, + MipLODBias: 0.0, + MaxAnisotropy: 1, + ComparisonFunc: D3D11_COMPARISON_ALWAYS, + BorderColor: [0.0; 4], + MinLOD: 0.0, + MaxLOD: D3D11_FLOAT32_MAX, + }; + let mut output = None; + unsafe { device.CreateSamplerState(&desc, Some(&mut output))? }; + Ok(output) +} + +/// The size in texels of a target `shrink` times smaller than the frame, rounded up so the level +/// covers the whole frame. Blur levels are made at exactly this size, so every pass draws over +/// the whole texture and no row or column is left unwritten at the frame's edge. +fn level_size(viewport: &D3D11_VIEWPORT, shrink: u32) -> (u32, u32) { + ( + (viewport.Width as u32).div_ceil(shrink), + (viewport.Height as u32).div_ceil(shrink), + ) +} + +#[cfg(test)] +#[path = "../../gpui/src/backdrop_test_fixture.rs"] +mod render_fixture; + +#[cfg(test)] +#[::core::prelude::v1::test] +fn render_fixture_cases() -> anyhow::Result<()> { + use windows::Win32::UI::WindowsAndMessaging::*; + use windows::core::w; + let hwnd = unsafe { + CreateWindowExW( + WINDOW_EX_STYLE::default(), + w!("STATIC"), + w!("render fixture"), + WS_POPUP, + 0, + 0, + 64, + 64, + None, + None, + None, + None, + )? + }; + let result = (|| { + let devices = DirectXDevices::new()?; + let mut renderer = DirectXRenderer::new(hwnd, &devices, true)?; + // The DirectX renderer ignores `Scene::overscan`, so a backdrop at the right or bottom + // edge blurs only what lies inside the window. + render_fixture::run("", &["overscan"], |scene, size| { + renderer.resize(size)?; + renderer.render_to_image(scene, WindowBackgroundAppearance::Opaque) + }) + })(); + unsafe { + DestroyWindow(hwnd)?; + } + result +} diff --git a/crates/gpui_windows/src/shaders.hlsl b/crates/gpui_windows/src/shaders.hlsl index e849773b..d6004b7b 100644 --- a/crates/gpui_windows/src/shaders.hlsl +++ b/crates/gpui_windows/src/shaders.hlsl @@ -97,6 +97,9 @@ struct TransformationMatrix { }; static const float M_PI_F = 3.141592653f; +// How much further along each edge a fully smoothed corner starts than a round one, as a share +// of its radius. The same as `SQUIRCLE_REACH` in gpui. +static const float SQUIRCLE_REACH = 0.528665f; static const float3 GRAYSCALE_FACTORS = float3(0.2126f, 0.7152f, 0.0722f); static const uint SIMPLE_PRIMITIVE_FLAG = 1u << 31; @@ -123,6 +126,25 @@ float4 distance_from_clip_rect_impl(float2 position, Bounds clip_bounds) { return float4(tl.x, br.x, tl.y, br.y); } +// The device pixels `bounds` reach into: the bounds grown out to whole pixels, so an edge that +// falls between pixels still draws the pixel it partly covers. Bounds on the pixel grid stay as +// they are. +Bounds pixel_cover(Bounds bounds) { + Bounds cover; + cover.origin = floor(bounds.origin); + cover.size = ceil(bounds.origin + bounds.size) - cover.origin; + return cover; +} + +// How much of the pixel centred on `position` the bounds cover: 1 inside them, and the share +// left where an edge falls through the pixel. +float pixel_coverage(float2 position, Bounds bounds) { + float2 near_edge = max(position - 0.5, bounds.origin); + float2 far_edge = min(position + 0.5, bounds.origin + bounds.size); + float2 overlap = saturate(far_edge - near_edge); + return overlap.x * overlap.y; +} + float4 distance_from_clip_rect_transformed(float2 unit_vertex, Bounds bounds, Bounds clip_bounds, TransformationMatrix transformation) { float2 position = unit_vertex * bounds.size + bounds.origin; float2 transformed = mul(position, transformation.rotation_scale) + transformation.translation; @@ -284,32 +306,59 @@ float4 to_device_position_transformed(float2 unit_vertex, Bounds bounds, return float4(device_position, 0.0, 1.0); } +// The shape of a corner of `radius` smoothed by `smoothing`: how far along each edge it starts, +// and the exponent of the superellipse it follows, 2 for a circular arc. The exponent is picked +// so that the corner crosses its diagonal where a round corner of `radius` would, which keeps +// it the same size to the eye. A corner with no room to reach further stays round. +float2 corner_shape(float radius, float smoothing, float2 half_size) { + if (smoothing <= 0.0 || radius <= 0.0) { + return float2(radius, 2.0); + } + float room = min(half_size.x, half_size.y); + float extent = max(radius, min(radius * (1.0 + SQUIRCLE_REACH * smoothing), room)); + float inset = (1.0 - sqrt(0.5)) * radius / extent; + return float2(extent, -1.0 / log2(1.0 - inset)); +} + +// Signed distance from a point, measured from a corner's center, to a superellipse corner of +// `radius` and `exponent`. The superellipse's norm divided by the length of its gradient is a +// true distance near the curve, which is where antialiasing reads it. +float superellipse_sdf(float2 pt, float radius, float exponent) { + float2 component = abs(pt); + float norm = pow(pow(component.x, exponent) + pow(component.y, exponent), 1.0 / exponent); + if (norm <= 0.0) { + return -radius; + } + float slope = length(pow(component / norm, float2(exponent - 1.0, exponent - 1.0))); + return (norm - radius) / slope; +} + // Implementation of quad signed distance field -float quad_sdf_impl(float2 corner_center_to_point, float corner_radius) { +float quad_sdf_impl(float2 corner_center_to_point, float corner_radius, float corner_exponent) { if (corner_radius == 0.0) { // Fast path for unrounded corners return max(corner_center_to_point.x, corner_center_to_point.y); } else { - // Signed distance of the point from a quad that is inset by corner_radius - // It is negative inside this quad, and positive outside - float signed_distance_to_inset_quad = - // 0 inside the inset quad, and positive outside - length(max(float2(0.0, 0.0), corner_center_to_point)) + - // 0 outside the inset quad, and negative inside - min(0.0, max(corner_center_to_point.x, corner_center_to_point.y)); - - return signed_distance_to_inset_quad - corner_radius; + // 0 inside the quad inset by corner_radius, and positive outside + float2 outside = max(float2(0.0, 0.0), corner_center_to_point); + // 0 outside the inset quad, and negative inside + float inside = min(0.0, max(corner_center_to_point.x, corner_center_to_point.y)); + if (corner_exponent == 2.0) { + return length(outside) + inside - corner_radius; + } + return superellipse_sdf(outside, corner_radius, corner_exponent) + inside; } } -float quad_sdf(float2 pt, Bounds bounds, Corners corner_radii) { +float quad_sdf(float2 pt, Bounds bounds, Corners corner_radii, float corner_smoothing) { float2 half_size = bounds.size / 2.; float2 center = bounds.origin + half_size; float2 center_to_point = pt - center; - float corner_radius = pick_corner_radius(center_to_point, corner_radii); + float2 corner = corner_shape(pick_corner_radius(center_to_point, corner_radii), + corner_smoothing, half_size); float2 corner_to_point = abs(center_to_point) - half_size; - float2 corner_center_to_point = corner_to_point + corner_radius; - return quad_sdf_impl(corner_center_to_point, corner_radius); + float2 corner_center_to_point = corner_to_point + corner.x; + return quad_sdf_impl(corner_center_to_point, corner.x, corner.y); } PreparedBackground prepare_background(Background background) { @@ -493,6 +542,8 @@ struct Quad { Hsla border_color; Corners corner_radii; Edges border_widths; + float corner_smoothing; + uint pad; }; bool has_rounded_corners(Corners corner_radii) { @@ -520,12 +571,11 @@ struct QuadFragmentInput { PreparedBackground background; }; -// Opaque rectangles are drawn by the opaque pass instead of the quad pass. +// Opaque rectangles are drawn by the opaque pass instead of the quad pass. The fork draws no +// opaque pass (`DEPTH_PREPASS` in scene.rs), so the quad pass keeps every quad. Upstream's test is +// a solid opaque background with neither rounded corners nor a border. bool is_opaque_rectangle(Quad quad) { - return quad.background.tag == 0u - && quad.background.solid.a >= 1.0 - && !has_rounded_corners(quad.corner_radii) - && !has_border(quad.border_widths); + return false; } StructuredBuffer quads: register(t1); @@ -541,7 +591,8 @@ QuadFragmentInput quad_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_ } float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); - ClippedVertex vertex = clip_to_mask(unit_vertex, quad.bounds, quad.content_mask); + Bounds cover = pixel_cover(quad.bounds); + ClippedVertex vertex = clip_to_mask(unit_vertex, cover, quad.content_mask); float4 device_position = to_device_position_impl(vertex.position); float4 border_color = hsla_to_rgba(quad.border_color); @@ -550,7 +601,10 @@ QuadFragmentInput quad_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_ output.position = device_position; output.position.z = quad_depth(quad_id); output.border_color = border_color; - bool simple = !is_shaped(quad) && quad.background.tag == 0u; + // A quad off the pixel grid partly covers the pixels its edges fall through, so only one on + // the grid fills every pixel it draws. + bool on_grid = all(cover.origin == quad.bounds.origin) && all(cover.size == quad.bounds.size); + bool simple = !is_shaped(quad) && quad.background.tag == 0u && on_grid; output.quad_id = quad_id | (simple ? SIMPLE_PRIMITIVE_FLAG : 0u); output.background = prepare_background(quad.background); return output; @@ -566,6 +620,15 @@ float4 quad_fragment(QuadFragmentInput input): SV_Target { background_color(input.background, quad.background, quad.bounds, input.position.xy); bool unrounded = !has_rounded_corners(quad.corner_radii); + // A quad off the pixel grid partly covers the pixels its edges fall through. On the grid + // this is 1 for every pixel drawn. + float coverage = pixel_coverage(input.position.xy, quad.bounds); + + // Fast path when the quad is not rounded and doesn't have any border + if (!is_shaped(quad)) { + return background * float4(1.0, 1.0, 1.0, coverage); + } + float2 size = quad.bounds.size; float2 half_size = size / 2.; float2 the_point = input.position.xy - quad.bounds.origin; @@ -575,8 +638,10 @@ float4 quad_fragment(QuadFragmentInput input): SV_Target { // minimum distance between the center of the pixel and the edge. const float antialias_threshold = 0.5; - // Radius of the nearest corner - float corner_radius = pick_corner_radius(center_to_point, quad.corner_radii); + // How far along the edges the nearest corner reaches, and the exponent of its curve + float2 corner = corner_shape(pick_corner_radius(center_to_point, quad.corner_radii), + quad.corner_smoothing, half_size); + float corner_radius = corner.x; float2 border = float2( center_to_point.x < 0.0 ? quad.border_widths.left : quad.border_widths.right, @@ -622,11 +687,11 @@ float4 quad_fragment(QuadFragmentInput input): SV_Target { // Fast path for points that must be part of the background if (is_within_inner_straight_border && !is_near_rounded_corner) { - return background; + return background * float4(1.0, 1.0, 1.0, coverage); } // Signed distance of the point to the outside edge of the quad's border - float outer_sdf = quad_sdf_impl(corner_center_to_point, corner_radius); + float outer_sdf = quad_sdf_impl(corner_center_to_point, corner_radius, corner.y); // Approximate signed distance of the point to the inside edge of the quad's // border. It is negative outside this edge (within the border), and @@ -644,9 +709,10 @@ float4 quad_fragment(QuadFragmentInput input): SV_Target { } else if (is_beyond_inner_straight_border) { // Fast path for points that must be outside the inner edge inner_sdf = -1.0; - } else if (reduced_border.x == reduced_border.y) { - // Fast path for circular inner edge. - inner_sdf = -(outer_sdf + reduced_border.x); + } else if (reduced_border.x == reduced_border.y || corner.y != 2.0) { + // Fast path for circular inner edge. A smoothed corner offsets its outer edge by the + // wider border, since its inner edge has no exact form either way. + inner_sdf = -(outer_sdf + max(reduced_border.x, reduced_border.y)); } else { float2 ellipse_radii = max(float2(0.0, 0.0), float2(corner_radius, corner_radius) - reduced_border); inner_sdf = quarter_ellipse_sdf(corner_center_to_point, ellipse_radii); @@ -832,7 +898,9 @@ float4 quad_fragment(QuadFragmentInput input): SV_Target { color = over(background, border_color); } - return color * float4(1.0, 1.0, 1.0, saturate(antialias_threshold - outer_sdf)); + // The distance field knows nothing of how much of the pixel the quad covers, so a quad + // thinner than a pixel would come out stronger than the share of the pixel it fills. + return color * float4(1.0, 1.0, 1.0, min(coverage, saturate(antialias_threshold - outer_sdf))); } /* @@ -879,14 +947,23 @@ float4 opaque_quad_fragment(OpaqueQuadFragmentInput input): SV_Target { struct Shadow { uint order; float blur_radius; + // The area the shadow paints: the blurred extent of a drop shadow, or the element + // that an inset shadow is clipped to. Bounds bounds; Corners corner_radii; Bounds content_mask; Hsla color; + // The shape that is blurred: the silhouette of a drop shadow, or the hole of an + // inset shadow. Bounds shape_bounds; Corners shape_corner_radii; + // 0 = drop shadow, 1 = inset shadow. uint inset; - uint pad; // align to 8 bytes + float element_corner_smoothing; + // The element that clips the shadow: a drop shadow is drawn only outside it, an inset one + // only inside it. + Bounds element_bounds; + Corners element_corner_radii; }; struct PreparedBlurredRoundedRect { @@ -986,7 +1063,7 @@ float4 shadow_fragment(ShadowFragmentInput input): SV_TARGET { float alpha; if (shadow.blur_radius == 0.) { - float distance = quad_sdf(input.position.xy, shadow.shape_bounds, shadow.shape_corner_radii); + float distance = quad_sdf(input.position.xy, shadow.shape_bounds, shadow.shape_corner_radii, 0.0); alpha = saturate(0.5 - distance); } else { float2 center = shadow.shape_bounds.origin + shadow.shape_bounds.size / 2.; @@ -997,8 +1074,15 @@ float4 shadow_fragment(ShadowFragmentInput input): SV_TARGET { // The inset shadow is the complement of the (blurred) hole rect, clipped to the element. // `saturate(0.5 - d)` gives a 1-pixel antialiased edge: d <= -0.5 -> 1, d >= 0.5 -> 0. alpha = 1.0 - alpha; - float element_distance = quad_sdf(input.position.xy, shadow.bounds, shadow.corner_radii); + float element_distance = quad_sdf(input.position.xy, shadow.element_bounds, + shadow.element_corner_radii, shadow.element_corner_smoothing); alpha *= saturate(0.5 - element_distance); + } else { + // A drop shadow is clipped to outside the element, the way CSS draws one, so an + // element with a translucent fill never shows its own shadow through it. + float element_distance = quad_sdf(input.position.xy, shadow.element_bounds, + shadow.element_corner_radii, shadow.element_corner_smoothing); + alpha *= saturate(0.5 + element_distance); } return input.color * float4(1., 1., 1., alpha); @@ -1313,6 +1397,25 @@ SubpixelSpriteFragmentOutput subpixel_sprite_fragment(MonochromeSpriteFragmentIn return output; } +// Drawn from `subpixel_sprite_vertex`, so this half has no vertex entry point of its own. +// +// `subpixel_sprite_fragment`'s dual-source blend always writes alpha = 1, which is +// fine on the opaque frame but wrong in an offscreen filter layer: those start +// transparent, and get composited onto their parent by that alpha afterward, so an +// antialiased glyph pixel would overwrite the parent instead of blending into it. +// This collapses ClearType's three channels into one coverage value and writes a +// normal premultiplied color instead, trading subpixel fringing for a correct blend. +float4 subpixel_sprite_layered_fragment(MonochromeSpriteFragmentInput input): SV_Target { + float3 sample = t_sprite.Sample(s_sprite, input.tile_position).rgb; + if (is_bgr) { + sample = sample.bgr; + } + float3 alpha_corrected = apply_contrast_and_gamma_correction3(sample, input.color.rgb, subpixel_enhanced_contrast, gamma_ratios); + float average_coverage = (alpha_corrected.r + alpha_corrected.g + alpha_corrected.b) / 3.0f; + float coverage = input.color.a * average_coverage; + return float4(input.color.rgb * coverage, coverage); +} + /* ** ** Polychrome sprites @@ -1366,7 +1469,291 @@ float4 polychrome_sprite_fragment(PolychromeSpriteFragmentInput input): SV_Targe if (sprite.grayscale != 0u) { color.rgb = dot(color.rgb, GRAYSCALE_FACTORS); } - float distance = quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii); + float distance = quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii, 0.0); color.a *= input.opacity * saturate(0.5 - distance); return color; } + +/* +** +** Backdrops +** +*/ + +struct Backdrop { + uint order; + float corner_smoothing; + float blur; + float opacity; + Bounds bounds; + Bounds content_mask; + Corners corner_radii; +}; + +struct BackdropFragmentInput { + float4 position: SV_Position; + nointerpolation uint backdrop_id: TEXCOORD0; +}; + +StructuredBuffer backdrops: register(t1); + +BackdropFragmentInput backdrop_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); + uint backdrop_id = batch_start_index + instance_id; + Backdrop backdrop = backdrops[backdrop_id]; + ClippedVertex vertex = clip_to_mask(unit_vertex, backdrop.bounds, backdrop.content_mask); + + BackdropFragmentInput output; + output.position = to_device_position_impl(vertex.position); + output.backdrop_id = backdrop_id; + return output; +} + +// A backdrop replaces what it covers with the blurred copy of it rather than laying that copy +// over it: `dst = mix(dst, blurred, k)`, k being the coverage times the instance's opacity. +// Over an opaque frame the two are one picture, since a copy of alpha one hides what it +// covers; over a see-through window laying it over left `a + a(1 - a)` where the window asked +// for `a`. The mix is two draws over one instance buffer: `backdrop_punch_fragment` for +// `dst *= (1 - k)`, then this one, added on top. +float4 backdrop_fragment(BackdropFragmentInput input): SV_Target { + Backdrop backdrop = backdrops[input.backdrop_id]; + float2 position = input.position.xy; + float4 sampled = t_sprite.Sample(s_sprite, position / global_viewport_size); + float distance = quad_sdf(position, backdrop.bounds, backdrop.corner_radii, backdrop.corner_smoothing); + float coverage = saturate(0.5 - distance); + + return sampled * coverage * backdrop.opacity; +} + +// The hole the blurred copy lands in: alpha alone, blended so what it covers keeps `1 - k` of +// itself, colour and alpha together. +float4 backdrop_punch_fragment(BackdropFragmentInput input): SV_Target { + Backdrop backdrop = backdrops[input.backdrop_id]; + float2 position = input.position.xy; + float distance = quad_sdf(position, backdrop.bounds, backdrop.corner_radii, backdrop.corner_smoothing); + float coverage = saturate(0.5 - distance); + + return float4(0.0, 0.0, 0.0, coverage * backdrop.opacity); +} + +/* +** +** Layer filters +** +*/ + +struct FilterParams { + Bounds source_bounds; + Bounds fade_bounds; + float2 direction; + float2 transform_origin; + float radius; + float scale; + float fade_top; + float fade_bottom; + float fade_left; + float fade_right; + float2 translation; + // How many texels of the texture a blur pass reads hold the frame. + float2 extent; +}; + +struct FilterVertexOutput { + float4 position: SV_Position; + float2 uv: TEXCOORD0; +}; + +struct FilterFragmentInput { + float4 position: SV_Position; + float2 uv: TEXCOORD0; +}; + +StructuredBuffer filter_params: register(t1); + +FilterVertexOutput filter_vertex_impl(uint vertex_id) { + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); + + FilterVertexOutput output; + output.position = float4(unit_vertex.x * 2.0 - 1.0, 1.0 - unit_vertex.y * 2.0, 0.0, 1.0); + output.uv = unit_vertex; + return output; +} + +FilterVertexOutput gaussian_vertex(uint vertex_id: SV_VertexID) { + return filter_vertex_impl(vertex_id); +} + +FilterVertexOutput pyramid_down_vertex(uint vertex_id: SV_VertexID) { + return filter_vertex_impl(vertex_id); +} + +FilterVertexOutput blit_vertex(uint vertex_id: SV_VertexID) { + return filter_vertex_impl(vertex_id); +} + +FilterVertexOutput mask_vertex(uint vertex_id: SV_VertexID) { + return filter_vertex_impl(vertex_id); +} + +// How much of a texel wide footprint centred at `at`, in texels, lies within `0..extent` on both +// axes. Nothing lies past the frame's edges, so every blur pass weighs its taps by this and +// divides by the weight it kept, with `extent` as how many texels of the texture it reads hold +// the frame. A blur against an edge then averages what is there instead of stretching the border +// row across the kernel, which made every row that scrolled out under the edge flash through the +// blur on its way. +float blur_inside(float2 at, float2 extent) { + float2 span = saturate(min(at + 0.5, extent) - max(at - 0.5, float2(0.0, 0.0))); + return span.x * span.y; +} + +// How much of a texel wide span centred at `at`, in texels, lies within `0..limit` along one +// axis. A gaussian pass reads along one axis only, so a texel's coverage across it is the same +// for every tap and must not weigh the taps against the centre. +float blur_along(float at, float limit) { + return saturate(min(at + 0.5, limit) - max(at - 0.5, 0.0)); +} + +// A narrow blur runs `gaussian_fragment` across and then down at full resolution, with `radius` +// as its standard deviation, and a wide one runs it across and down the deepest level of a +// pyramid. It pairs neighbouring taps into one bilinear fetch placed between them by their +// weights, which halves the fetches, and relies on sampling a texture of the same size as the +// target, so every pair lands between two texel centres along the axis. Every tap, the centre +// too, counts by how much of it lies inside the frame along the axis, so a tap past the frame's +// edge drops out of the pair it belongs to. +float4 gaussian_fragment(FilterFragmentInput input): SV_Target { + FilterParams params = filter_params[batch_start_index]; + float width; + float height; + t_sprite.GetDimensions(width, height); + float2 size = float2(width, height); + float2 texel = params.direction / size; + float axis = dot(input.uv * size, params.direction); + float limit = dot(params.extent, params.direction); + float sigma = max(params.radius, 0.0001); + float reach = min(ceil(sigma * 3.0), 24.0); + float spread = 2.0 * sigma * sigma; + + float own = blur_along(axis, limit); + float4 total = own * t_sprite.Sample(s_sprite, input.uv); + float weight = own; + for (float inner = 1.0; inner <= reach; inner += 2.0) { + float outer = inner + 1.0; + float inner_weight = exp(-inner * inner / spread); + float outer_weight = outer <= reach ? exp(-outer * outer / spread) : 0.0; + [unroll] + for (int i = 0; i < 2; i++) { + float side = i == 0 ? -1.0 : 1.0; + float inner_tap = inner_weight * blur_along(axis + inner * side, limit); + float outer_tap = outer_weight * blur_along(axis + outer * side, limit); + float pair = inner_tap + outer_tap; + float2 at = texel * (side * (inner * inner_tap + outer * outer_tap) / max(pair, 0.0001)); + total += pair * t_sprite.Sample(s_sprite, input.uv + at); + weight += pair; + } + } + + return total / max(weight, 0.0001); +} + +// Four bilinear taps at `centre` plus `offset` mirrored into each quadrant, in texels of the +// texture read, each weighed by how much of it falls within `extent`. +float4 pyramid_taps(float2 centre, float2 offset, float2 extent) { + float width; + float height; + t_sprite.GetDimensions(width, height); + float2 size = float2(width, height); + float4 total = float4(0.0, 0.0, 0.0, 0.0); + float weight = 0.0; + [unroll] + for (int i = 0; i < 4; i++) { + float2 corner = float2((i & 1) ? 1.0 : -1.0, (i & 2) ? 1.0 : -1.0); + float2 at = centre + offset * corner; + float tap = blur_inside(at, extent); + total += tap * t_sprite.Sample(s_sprite, at / size); + weight += tap; + } + return total / max(weight, 0.0001); +} + +// Halves the level it reads, the first passes of a pyramid. A target texel sits over the corner +// of four source texels, and a bilinear tap on each of the four corners around that one averages +// the four by four texels under it. +float4 pyramid_down_fragment(FilterFragmentInput input): SV_Target { + FilterParams params = filter_params[batch_start_index]; + return pyramid_taps(input.position.xy * 2.0, float2(1.0, 1.0), params.extent); +} + +// Doubles the level it reads, back towards full size. Four bilinear taps half a texel out on +// each diagonal lay a box of one texel over the bilinear tent, which rounds off the corners a +// tent alone leaves at every texel of the level below and keeps its grid from showing. +float4 pyramid_up_fragment(FilterFragmentInput input): SV_Target { + FilterParams params = filter_params[batch_start_index]; + return pyramid_taps(input.position.xy * 0.5, float2(0.5, 0.5), params.extent); +} + + +float4 blit_fragment(FilterFragmentInput input): SV_Target { + return t_sprite.Sample(s_sprite, input.uv); +} + +// Where a point of a layer's source lands in the frame, applying the layer's transform. +float2 mask_destination(FilterParams params, float2 source_point) { + return params.transform_origin + (source_point - params.transform_origin) * params.scale + + params.translation; +} + +float4 mask_fragment(FilterFragmentInput input): SV_Target { + FilterParams params = filter_params[batch_start_index]; + float2 destination_point = input.position.xy; + float2 source_point = params.transform_origin + + (destination_point - params.translation - params.transform_origin) / params.scale; + // Only the part of the source inside the frame was drawn, so only that part covers pixels. + float2 source_start = max(params.source_bounds.origin, float2(0.0, 0.0)); + float2 source_end = min(params.source_bounds.origin + params.source_bounds.size, + global_viewport_size); + + // An untransformed layer keeps the frame's pixel grid, so a pixel is in or out. A + // transformed one covers each pixel as far as its transformed bounds overlap it, which + // smooths the edge the clamped sample below leaves hard. + float coverage = 1.0; + if (params.scale == 1.0 && all(params.translation == float2(0.0, 0.0))) { + if (any(source_point < source_start) || any(source_point >= source_end)) { + return float4(0.0, 0.0, 0.0, 0.0); + } + } else { + float2 start = mask_destination(params, source_start); + float2 end = mask_destination(params, source_end); + float2 overlap = saturate(min(destination_point + 0.5, end) - max(destination_point - 0.5, start)); + coverage = overlap.x * overlap.y; + if (coverage <= 0.0) { + return float4(0.0, 0.0, 0.0, 0.0); + } + } + + float top = source_point.y - params.fade_bounds.origin.y; + float bottom = params.fade_bounds.origin.y + params.fade_bounds.size.y - source_point.y; + + float fade = 1.0; + if (params.fade_top > 0.0) { + fade = min(fade, smoothstep(0.0, params.fade_top, top)); + } + if (params.fade_bottom > 0.0) { + fade = min(fade, smoothstep(0.0, params.fade_bottom, bottom)); + } + if (params.fade_left > 0.0) { + float left = source_point.x - params.fade_bounds.origin.x; + fade = min(fade, smoothstep(0.0, params.fade_left, left)); + } + if (params.fade_right > 0.0) { + float right = params.fade_bounds.origin.x + params.fade_bounds.size.x - source_point.x; + fade = min(fade, smoothstep(0.0, params.fade_right, right)); + } + + // The sample stays half a texel inside the texels the layer covers and inside the frame, so + // a stretched edge repeats the layer's last texels rather than blending them with whatever + // lies past it. A pixel centre of an untransformed layer is already inside and does not move. + float2 low = max(floor(source_start), float2(0.0, 0.0)) + 0.5; + float2 high = min(ceil(source_end), global_viewport_size) - 0.5; + float2 texel = clamp(source_point, low, max(low, high)); + return t_sprite.Sample(s_sprite, texel / global_viewport_size) * coverage * fade; +} From 49c91c7e9f35e6e724e371a4e1d94fac3e1b3685 Mon Sep 17 00:00:00 2001 From: nolight132 Date: Thu, 26 Nov 2026 16:39:21 +0100 Subject: [PATCH 3/7] chore(gpui): refresh Cargo.lock for async-task patch --- Cargo.lock | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 58eac663..85051bd1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -453,7 +453,7 @@ dependencies = [ [[package]] name = "async-task" version = "4.7.1" -source = "git+https://github.com/zed-industries/async-task.git?rev=015845a19fc31752c02367567d3b8900a406f9da#015845a19fc31752c02367567d3b8900a406f9da" +source = "git+https://github.com/smol-rs/async-task?rev=41fd3359c75e221bd8b187a8ee361aa309c1714c#41fd3359c75e221bd8b187a8ee361aa309c1714c" [[package]] name = "async-trait" @@ -2388,6 +2388,7 @@ dependencies = [ "gpui_util", "image", "itertools 0.14.0", + "js-sys", "log", "naga", "parking_lot", From 3c1c4983d1ed3b9ef981e8f0031f128a2307079a Mon Sep 17 00:00:00 2001 From: nolight132 Date: Thu, 26 Nov 2026 17:00:24 +0100 Subject: [PATCH 4/7] perf(gpui): inline keep_primitive and skip animation lookup when empty --- crates/gpui/src/scene.rs | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/crates/gpui/src/scene.rs b/crates/gpui/src/scene.rs index 0b4285f7..e25d4610 100644 --- a/crates/gpui/src/scene.rs +++ b/crates/gpui/src/scene.rs @@ -557,6 +557,7 @@ impl Scene { /// Inserts a primitive replayed from a scene whose history matched this one's where the /// replay began, with the order it was drawn at there. + #[inline] fn keep_primitive(&mut self, primitive: Primitive) { let index = self.paint_operations.len(); if let Some(layer) = self @@ -664,6 +665,7 @@ impl Scene { .iter() .map(|(index, _)| *index) .peekable(); + let has_animations = !prev_scene.animations.is_empty(); for (index, operation) in (range.start..).zip(&prev_scene.paint_operations[range]) { // A cached view nested in this range may be replayed alone next frame, so the // marks inside it move along with what they mark. @@ -672,15 +674,18 @@ impl Scene { } match operation { PaintOperation::Primitive(primitive) => { - match (keep, prev_scene.animated_sprite(primitive)) { - (true, Some((sprite, animation))) => { - self.keep_animated_sprite(sprite, animation) + if has_animations + && let Some((sprite, animation)) = prev_scene.animated_sprite(primitive) + { + match keep { + true => self.keep_animated_sprite(sprite, animation), + false => self.insert_animated_sprite(sprite, animation), } - (false, Some((sprite, animation))) => { - self.insert_animated_sprite(sprite, animation) + } else { + match keep { + true => self.keep_primitive(primitive.clone()), + false => self.insert_primitive(primitive.clone()), } - (true, None) => self.keep_primitive(primitive.clone()), - (false, None) => self.insert_primitive(primitive.clone()), } } PaintOperation::StartLayer(key) => match layers_kept { From f2803e14d6e0cc74b49a20538b71a2e581d13ae9 Mon Sep 17 00:00:00 2001 From: nolight132 Date: Thu, 26 Nov 2026 17:30:38 +0100 Subject: [PATCH 5/7] fix(gpui): clear unequal smoothed border widths in largest_border_interior --- crates/gpui/src/window.rs | 61 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 57 insertions(+), 4 deletions(-) diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs index 46d4738f..3e3ae39c 100644 --- a/crates/gpui/src/window.rs +++ b/crates/gpui/src/window.rs @@ -5617,11 +5617,24 @@ impl Window { // A corner's inner border edge is a quarter ellipse around the // corner's center, with the border widths taken off its radius. + // Smoothed corners offset their outer curve by the wider border on + // both axes in the shader, so use that width for both coordinates + // inside a rounded corner. + let smoothed = quad.corner_smoothing > 0.0; let corner_inset = |radius: ScaledPixels, width_x: ScaledPixels, width_y: ScaledPixels| { - point( - width_x.max(radius - (radius - width_x) * cos), - width_y.max(radius - (radius - width_y) * sin), - ) + if smoothed && radius > ScaledPixels(0.0) { + let w = width_x.max(width_y); + let inner = (radius - w).max(ScaledPixels(0.0)); + point( + width_x.max(radius - inner * cos), + width_y.max(radius - inner * sin), + ) + } else { + point( + width_x.max(radius - (radius - width_x) * cos), + width_y.max(radius - (radius - width_y) * sin), + ) + } }; // A smoothed corner starts further along each edge than its radius and bulges past the @@ -12224,4 +12237,44 @@ mod inspector_tests { }) .expect("closed inspector has no bookkeeping and no style overrides"); } + + #[test] + fn largest_border_interior_clears_unequal_smoothed_borders() { + let mut quad = Quad { + order: 0, + border_style: BorderStyle::Solid, + bounds: Bounds::new( + point(ScaledPixels(0.0), ScaledPixels(0.0)), + size(ScaledPixels(200.0), ScaledPixels(200.0)), + ), + content_mask: ContentMask { + bounds: Bounds::new( + point(ScaledPixels(0.0), ScaledPixels(0.0)), + size(ScaledPixels(200.0), ScaledPixels(200.0)), + ), + }, + background: crate::Background::default(), + border_color: crate::black(), + corner_radii: Corners::all(ScaledPixels(60.0)), + border_widths: Edges { + top: ScaledPixels(1.0), + right: ScaledPixels(50.0), + bottom: ScaledPixels(1.0), + left: ScaledPixels(50.0), + }, + corner_smoothing: 1.0, + pad: 0, + }; + let interior = Window::largest_border_interior(&quad); + assert!( + !interior.contains(&point(ScaledPixels(64.5), ScaledPixels(29.5))), + "interior cutout {interior:?} must not clip a smoothed corner offset by the wider border" + ); + assert!(interior.origin.y > ScaledPixels(63.0)); + + quad.corner_radii = Corners::all(ScaledPixels(0.0)); + let square_interior = Window::largest_border_interior(&quad); + assert_eq!(square_interior.origin.y, ScaledPixels(2.0)); + assert_eq!(square_interior.origin.x, ScaledPixels(51.0)); + } } From 8f95176bd4461f628b4467ba9ebc65cc60602556 Mon Sep 17 00:00:00 2001 From: nolight132 Date: Thu, 26 Nov 2026 17:30:38 +0100 Subject: [PATCH 6/7] fix(gpui): guard collapsed shadow shape bounds against 0/0 blur exponent --- crates/gpui_apple/src/shaders.metal | 10 ++++- crates/gpui_wgpu/src/shaders.wgsl | 14 ++++++- crates/gpui_wgpu/src/wgpu_renderer.rs | 57 +++++++++++++++++++++++++++ crates/gpui_windows/src/shaders.hlsl | 14 ++++++- 4 files changed, 89 insertions(+), 6 deletions(-) diff --git a/crates/gpui_apple/src/shaders.metal b/crates/gpui_apple/src/shaders.metal index a45001f7..71bfe59e 100644 --- a/crates/gpui_apple/src/shaders.metal +++ b/crates/gpui_apple/src/shaders.metal @@ -550,9 +550,13 @@ float erf7(float x) { // Raph Levien's blurred rounded rectangle approximation, whose blur s is sigma * sqrt(2): // https://raphlinus.github.io/graphics/2020/04/21/blurred-rounded-rects.html PreparedBlurredRoundedRect prepare_blurred_rounded_rect(float2 size, Corners_ScaledPixels corner_radii, float sigma) { + float min_edge = min(size.x, size.y); + if (min_edge <= 0.) { + return PreparedBlurredRoundedRect{ + float4(0.), float4(0.), float4(2.), float4(0.)}; + } float s = max(sigma * sqrt(2.), 1e-6); float s_inv = 1. / s; - float min_edge = min(size.x, size.y); float r_max = 0.5 * min_edge; float4 radii = float4(corner_radii.top_left, corner_radii.top_right, corner_radii.bottom_right, corner_radii.bottom_left); @@ -631,7 +635,9 @@ fragment float4 shadow_fragment(ShadowFragmentInput input [[stage_in]], Shadow shadow = shadows[input.shadow_id]; float alpha; - if (shadow.blur_radius == 0.) { + if (shadow.shape_bounds.size.width <= 0. || shadow.shape_bounds.size.height <= 0.) { + alpha = 0.; + } else if (shadow.blur_radius == 0.) { float distance = quad_sdf(input.position.xy, shadow.shape_bounds, shadow.shape_corner_radii, 0.0); alpha = saturate(0.5 - distance); diff --git a/crates/gpui_wgpu/src/shaders.wgsl b/crates/gpui_wgpu/src/shaders.wgsl index 1537b629..577b8a30 100644 --- a/crates/gpui_wgpu/src/shaders.wgsl +++ b/crates/gpui_wgpu/src/shaders.wgsl @@ -1108,9 +1108,17 @@ fn erf7(input: f32) -> f32 { // Raph Levien's blurred rounded rectangle approximation, whose blur s is sigma * sqrt(2): // https://raphlinus.github.io/graphics/2020/04/21/blurred-rounded-rects.html fn prepare_blurred_rounded_rect(size: vec2, corner_radii: Corners, sigma: f32) -> PreparedBlurredRoundedRect { + let min_edge = min(size.x, size.y); + if (min_edge <= 0.0) { + var empty: PreparedBlurredRoundedRect; + empty.shape = vec4(0.0); + empty.r1 = vec4(0.0); + empty.exponent = vec4(2.0); + empty.scale = vec4(0.0); + return empty; + } let s = max(sigma * sqrt(2.0), 1e-6); let s_inv = 1.0 / s; - let min_edge = min(size.x, size.y); let r_max = 0.5 * min_edge; let radii = vec4(corner_radii.top_left, corner_radii.top_right, corner_radii.bottom_right, corner_radii.bottom_left); @@ -1179,7 +1187,9 @@ fn fs_shadow(input: ShadowVarying) -> @location(0) vec4 { let shadow = load_shadow(input.shadow_id); var alpha: f32; - if (shadow.blur_radius == 0.0) { + if (shadow.shape_bounds.size.x <= 0.0 || shadow.shape_bounds.size.y <= 0.0) { + alpha = 0.0; + } else if (shadow.blur_radius == 0.0) { let distance = quad_sdf(input.position.xy, shadow.shape_bounds, shadow.shape_corner_radii, 0.0); alpha = saturate(0.5 - distance); diff --git a/crates/gpui_wgpu/src/wgpu_renderer.rs b/crates/gpui_wgpu/src/wgpu_renderer.rs index 1991bbfb..c7679ac7 100644 --- a/crates/gpui_wgpu/src/wgpu_renderer.rs +++ b/crates/gpui_wgpu/src/wgpu_renderer.rs @@ -4530,3 +4530,60 @@ fn render_fixture_cases() -> anyhow::Result<()> { renderer.render_scene_to_image(scene, size) }) } + +#[cfg(all(test, target_os = "linux"))] +#[test] +fn collapsed_inset_shadow_hole_fills_element() -> anyhow::Result<()> { + use gpui::{ + Bounds, ContentMask, Corners, DevicePixels, Hsla, PlatformHeadlessRenderer as _, + ScaledPixels, Scene, Shadow, Size, point, size, + }; + + let mut renderer = crate::WgpuHeadlessRenderer::new()?; + let viewport = Size::new(DevicePixels(64), DevicePixels(64)); + let full = Bounds::new( + point(ScaledPixels(0.0), ScaledPixels(0.0)), + size(ScaledPixels(64.0), ScaledPixels(64.0)), + ); + let element = Bounds::new( + point(ScaledPixels(8.0), ScaledPixels(8.0)), + size(ScaledPixels(48.0), ScaledPixels(48.0)), + ); + let collapsed_hole = Bounds::new( + point(ScaledPixels(32.0), ScaledPixels(32.0)), + size(ScaledPixels(0.0), ScaledPixels(0.0)), + ); + for blur_radius in [8.0, 0.0] { + let mut scene = Scene::default(); + scene.insert_primitive(Shadow { + order: 0, + blur_radius: ScaledPixels(blur_radius), + bounds: element, + content_mask: ContentMask { bounds: full }, + corner_radii: Corners::default(), + color: Hsla { + h: 0.0, + s: 1.0, + l: 0.5, + a: 1.0, + }, + shape_bounds: collapsed_hole, + shape_corner_radii: Corners::default(), + inset: true.into(), + element_corner_smoothing: 0.0, + element_bounds: element, + element_corner_radii: Corners::default(), + }); + scene.finish(); + let image = renderer.render_scene_to_image(&scene, viewport)?; + for (x, y) in [(32, 32), (20, 20), (44, 44)] { + let pixel = image.get_pixel(x, y).0; + assert_eq!( + pixel, + [255, 0, 0, 255], + "collapsed inset shadow (blur={blur_radius}) at ({x},{y}) must fill element" + ); + } + } + Ok(()) +} diff --git a/crates/gpui_windows/src/shaders.hlsl b/crates/gpui_windows/src/shaders.hlsl index d6004b7b..26c90ad1 100644 --- a/crates/gpui_windows/src/shaders.hlsl +++ b/crates/gpui_windows/src/shaders.hlsl @@ -992,9 +992,17 @@ float erf7(float x) { // Raph Levien's blurred rounded rectangle approximation, whose blur s is sigma * sqrt(2): // https://raphlinus.github.io/graphics/2020/04/21/blurred-rounded-rects.html PreparedBlurredRoundedRect prepare_blurred_rounded_rect(float2 size, Corners corner_radii, float sigma) { + float min_edge = min(size.x, size.y); + if (min_edge <= 0.) { + PreparedBlurredRoundedRect empty; + empty.shape = float4(0., 0., 0., 0.); + empty.r1 = float4(0., 0., 0., 0.); + empty.exponent = float4(2., 2., 2., 2.); + empty.scale = float4(0., 0., 0., 0.); + return empty; + } float s = max(sigma * sqrt(2.), 1e-6); float s_inv = 1. / s; - float min_edge = min(size.x, size.y); float r_max = 0.5 * min_edge; float4 radii = float4(corner_radii.top_left, corner_radii.top_right, corner_radii.bottom_right, corner_radii.bottom_left); @@ -1062,7 +1070,9 @@ float4 shadow_fragment(ShadowFragmentInput input): SV_TARGET { Shadow shadow = shadows[input.shadow_id]; float alpha; - if (shadow.blur_radius == 0.) { + if (shadow.shape_bounds.size.width <= 0. || shadow.shape_bounds.size.height <= 0.) { + alpha = 0.; + } else if (shadow.blur_radius == 0.) { float distance = quad_sdf(input.position.xy, shadow.shape_bounds, shadow.shape_corner_radii, 0.0); alpha = saturate(0.5 - distance); } else { From 5c312806ffd22864c5eb40c683c9bc224bb5d6f9 Mon Sep 17 00:00:00 2001 From: nolight132 Date: Thu, 26 Nov 2026 17:36:23 +0100 Subject: [PATCH 7/7] fix(gpui): keep collapsed inset holes empty and fix hlsl size fields --- crates/gpui/src/window.rs | 49 ++++++++++++++++++++++++++- crates/gpui_wgpu/src/wgpu_renderer.rs | 2 +- crates/gpui_windows/src/shaders.hlsl | 2 +- 3 files changed, 50 insertions(+), 3 deletions(-) diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs index 3e3ae39c..07034b1e 100644 --- a/crates/gpui/src/window.rs +++ b/crates/gpui/src/window.rs @@ -5577,6 +5577,13 @@ impl Window { continue; } let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius); + // Keep an empty hole empty rather than letting cover_bounds expand a fractional + // collapsed rect into a 1px hole. + let shape_bounds = if hole.is_empty() { + Bounds::default() + } else { + self.cover_bounds(hole) + }; // Clamp at zero so a large spread can't produce negative radii, which would // break the SDF in the shader. let zero = Pixels::ZERO; @@ -5593,7 +5600,7 @@ impl Window { content_mask, corner_radii: element_corner_radii, color: shadow.color.opacity(opacity), - shape_bounds: self.cover_bounds(hole), + shape_bounds, shape_corner_radii: hole_corner_radii.scale(scale_factor), inset: true.into(), element_corner_smoothing: corner_smoothing, @@ -12277,4 +12284,44 @@ mod inspector_tests { assert_eq!(square_interior.origin.y, ScaledPixels(2.0)); assert_eq!(square_interior.origin.x, ScaledPixels(51.0)); } + + #[gpui::test] + fn test_collapsed_inset_shadow_hole_stays_empty_at_fractional_origin(cx: &mut TestAppContext) { + struct BlankView; + impl Render for BlankView { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + } + } + let window = cx.add_window(|_, _| BlankView); + cx.update_window(window.into(), |_, window, cx| { + window.draw(cx).clear(cx); + window.invalidator.set_phase(DrawPhase::Paint); + let bounds = Bounds::new(point(px(10.5), px(10.5)), size(px(20.0), px(20.0))); + window.paint_inset_shadows( + bounds, + Corners::default(), + 0.0, + &[BoxShadow { + color: crate::black(), + offset: point(px(0.0), px(0.0)), + blur_radius: px(4.0), + spread_radius: px(10.0), + inset: true, + }], + ); + let shadow = window + .next_frame + .scene + .shadows + .last() + .expect("collapsed inset shadow inserted"); + assert!( + shadow.shape_bounds.is_empty(), + "collapsed inset hole at fractional origin must stay empty, got {:?}", + shadow.shape_bounds + ); + }) + .unwrap(); + } } diff --git a/crates/gpui_wgpu/src/wgpu_renderer.rs b/crates/gpui_wgpu/src/wgpu_renderer.rs index c7679ac7..0b279fa9 100644 --- a/crates/gpui_wgpu/src/wgpu_renderer.rs +++ b/crates/gpui_wgpu/src/wgpu_renderer.rs @@ -4550,7 +4550,7 @@ fn collapsed_inset_shadow_hole_fills_element() -> anyhow::Result<()> { size(ScaledPixels(48.0), ScaledPixels(48.0)), ); let collapsed_hole = Bounds::new( - point(ScaledPixels(32.0), ScaledPixels(32.0)), + point(ScaledPixels(32.5), ScaledPixels(32.5)), size(ScaledPixels(0.0), ScaledPixels(0.0)), ); for blur_radius in [8.0, 0.0] { diff --git a/crates/gpui_windows/src/shaders.hlsl b/crates/gpui_windows/src/shaders.hlsl index 26c90ad1..3beaaab8 100644 --- a/crates/gpui_windows/src/shaders.hlsl +++ b/crates/gpui_windows/src/shaders.hlsl @@ -1070,7 +1070,7 @@ float4 shadow_fragment(ShadowFragmentInput input): SV_TARGET { Shadow shadow = shadows[input.shadow_id]; float alpha; - if (shadow.shape_bounds.size.width <= 0. || shadow.shape_bounds.size.height <= 0.) { + if (shadow.shape_bounds.size.x <= 0. || shadow.shape_bounds.size.y <= 0.) { alpha = 0.; } else if (shadow.blur_radius == 0.) { float distance = quad_sdf(input.position.xy, shadow.shape_bounds, shadow.shape_corner_radii, 0.0);