Files
zed/crates/gpui/examples/paths_bench.rs
T
John Tur ffe0fa29e4 gpui: Improve path rendering (#66809)
GPUI currently implements paths in two ways:

- A remnant of a Loop-Blinn shader (which doesn't quite work because the
winding accumulation is missing).
- Tessellating paths on the CPU with `lyon` and uploading the triangles
to the GPU.

Tessellated triangles have no curve coordinates, so Loop-Blinn's
analytic antialiasing doesn't help them. To antialias them, we used 4x
MSAA instead. This was particularly problematic:

- MSAA has an enormous bandwidth and memory cost relative to the quality
of the result (5 coverage levels).
- Many lower-end GPUs can't afford MSAA on the main render target. So,
paths rendered into a separate MSAA target, which was resolved into an
intermediate texture and then drawn onto the main target. These textures
cost extra memory.
- The MSAA draw and resolve happened per path batch. We didn't use a
single path atlas, because in principle its memory use is unbounded.
This dramatically magnifies the bandwidth cost of path rendering,
especially on tile-based GPUs, since every batch switches render passes
mid-frame.

We present a new path renderer that computes analytic coverage per pixel
from the winding number. Coverage is computed as in Eric Lengyel's Slug:
we cast rays leftward and upward from the pixel and count crossings with
the path's curves. Crossings within the pixel contribute partial
winding.

GPUI paths can be larger and more complex than glyphs. But since they're
built at a fixed scale in screen space, we can do some of the spatial
work on the CPU:

- `PathBuilder` turns each contour into closed chains of monotone
quadratic curves.
- The curves are binned into square cells, where each cell lists only
the curves near it. Cell size is picked per path to balance binning cost
against shading cost.
- For each cell, the CPU computes a *backdrop* value that encodes the
winding contribution of all the curves it doesn't list.
- Neighboring cells with the same curve list and backdrop merge into
rectangular tiles. A large rectangle becomes nine tiles: four corners,
four edges, and a solid interior with no listed curves.
- Each tile is one GPU instance, and the shader loops only over that
tile's curves.

Tiles are drawn in the main render pass alongside every other primitive.
There's no MSAA, no intermediate textures, no extra render passes or
resolves, and no tessellation.

---

Binning has a different cost profile from tessellation:

- The tessellator's work happened almost entirely in
`PathBuilder::build()`. Binning depends on the display scale, so it
happens in `paint_path`. Code that caches and reuses `Path`s pays
binning cost on every paint. However, this doesn't seem to be a common
pattern, so mitigations are deferred.
- In general, fills are about as fast as before or slightly faster,
while strokes are 2–8× slower. `lyon` has a dedicated stroke tessellator
that emits triangles directly along the stroke. We convert the stroke to
an outline with `tiny-skia`, then bin it like any other fill. Long,
sprawling strokes are the worst case (a 1,000-point scribble takes about
1.5ms now vs 0.2ms before).


GPU time is, generally, reduced dramatically. Measured on an Intel HD
4600:

| Scene | Before | After | Change | Pixel shader invocations |
|---|---|---|---|---|
| `painting` example | 9,257µs | 1,928µs | −79% | 1.81M → 1.50M (−17%) |
| Git Graph | 19,669µs | 3,828µs | −81% | 3.21M → 3.13M (−2%) |

---

Some breaking changes were made to the API:

- `Path` is no longer generic and can only be built with `PathBuilder`.
Use `PathBuilder`'s equivalents of `Path`'s builder methods.
- `PathBuilder` can still be populated from `lyon` path builders, but
the places where `lyon`'s tessellator leaked into the API were removed.
`StrokeOptions` and `FillOptions` are now GPUI types with fewer options,
and `PathBuilder::build_path` is gone.
- Since paths now render with analytic antialiasing, you may see
conflation artifacts where MSAA didn't have any.

Release Notes:
- Reduced GPU usage
- [GPUI] Improved path rendering performance. `Path` is no longer
generic and must be built with `PathBuilder`

---------

Co-authored-by: Anthony Eid <hello@anthonyeid.me>
2026-11-12 08:19:30 +00:00

114 lines
3.4 KiB
Rust

#![cfg_attr(target_family = "wasm", no_main)]
#[path = "example_support/fonts.rs"]
mod example_support;
use gpui::{
Background, Bounds, ColorSpace, Context, Path, PathBuilder, Pixels, Render, TitlebarOptions,
Window, WindowBounds, WindowOptions, canvas, div, linear_color_stop, linear_gradient, point,
prelude::*, px, rgb, size,
};
use gpui_platform::application;
const DEFAULT_WINDOW_WIDTH: Pixels = px(1024.0);
const DEFAULT_WINDOW_HEIGHT: Pixels = px(768.0);
struct PaintingViewer {
default_lines: Vec<(Path, Background)>,
_painting: bool,
}
impl PaintingViewer {
fn new(_window: &mut Window, _cx: &mut Context<Self>) -> Self {
let mut lines = vec![];
// draw a lightening bolt ⚡
for _ in 0..2000 {
// draw a ⭐
let mut builder = PathBuilder::fill();
builder.move_to(point(px(350.), px(100.)));
builder.line_to(point(px(370.), px(160.)));
builder.line_to(point(px(430.), px(160.)));
builder.line_to(point(px(380.), px(200.)));
builder.line_to(point(px(400.), px(260.)));
builder.line_to(point(px(350.), px(220.)));
builder.line_to(point(px(300.), px(260.)));
builder.line_to(point(px(320.), px(200.)));
builder.line_to(point(px(270.), px(160.)));
builder.line_to(point(px(330.), px(160.)));
builder.line_to(point(px(350.), px(100.)));
let path = builder.build().unwrap();
lines.push((
path,
linear_gradient(
180.,
linear_color_stop(rgb(0xFACC15), 0.7),
linear_color_stop(rgb(0xD56D0C), 1.),
)
.color_space(ColorSpace::Oklab),
));
}
Self {
default_lines: lines,
_painting: false,
}
}
}
impl Render for PaintingViewer {
fn render(&mut self, window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
window.request_animation_frame();
let lines = self.default_lines.clone();
div().size_full().child(
canvas(
move |_, _, _| {},
move |_, _, window, _| {
for (path, color) in lines {
window.paint_path(path, color);
}
},
)
.size_full(),
)
}
}
fn run_example() {
application().run(|cx| {
if !example_support::load_fonts(cx) {
return;
}
cx.open_window(
WindowOptions {
titlebar: Some(TitlebarOptions {
title: Some("Vulkan".into()),
..Default::default()
}),
focus: true,
window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
None,
size(DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT),
cx,
))),
..Default::default()
},
|window, cx| cx.new(|cx| PaintingViewer::new(window, cx)),
)
.unwrap();
cx.activate(true);
});
}
#[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();
}