gpui: Reduce overdraw using the depth buffer (#66811)

GPUI paints a frame by recording primitives (quads, shadows, paths,
underlines, glyph sprites, surfaces) into a `Scene`. The renderer then
draws the scene's primitives back to front, so that later primitives
paint over earlier ones. This means every pixel of every primitive is
shaded, even where a later primitive completely covers it. In heavily
nested UI, this adds up to a lot of overdraw.

Inspired by WebRender, we reduce overdraw with a depth buffer and two
passes:
- The opaque pass draws quads that we know cover their whole area with
an opaque color. They're drawn front to back, with depth testing and
depth writes enabled. In practice, we can only make this guarantee for
quads with a solid, fully opaque fill and no rounded corners.
- The blended pass draws everything else back to front, with depth
testing enabled but depth writes disabled. This is essentially the
existing render loop with a depth test added. Any fragment 'behind' an
opaque quad fails the depth test and is never shaded.

To get more of each frame into the opaque pass, `paint_quad` now splits
any quad with rounded corners into a rectangular interior and the four
edge strips around it. The interior is a plain rectangle, so if its fill
is solid and opaque, it's drawn in the opaque pass, and only the strips
need the border and corner shading.

Measured on an Intel HD 4600:

Scene | Before | After | Change | Pixel shader invocations |
|---|---|---|---|---|
| Editor | 3,941µs | 1,689µs | −57% | 3.71M → 1.65M (−55%) |
| Command palette | 7,658µs | 2,275µs | −70% | 5.33M → 1.80M (−66%) |
| Git Graph | 3,589µs | 1,889µs | −47% | 3.13M → 1.65M (−47%) |

Fixes https://github.com/zed-industries/zed/issues/8043

Release Notes:
- Reduced GPU usage
- [GPUI] Improved rendering performance by skipping pixels hidden behind
opaque quads
This commit is contained in:
John Tur
2026-11-12 08:19:31 +00:00
committed by GitHub
parent 1d8eda94bd
commit be07e43ea0
15 changed files with 900 additions and 127 deletions
Generated
+1
View File
@@ -7672,6 +7672,7 @@ dependencies = [
"gpui_util",
"image",
"itertools 0.14.0",
"js-sys",
"log",
"naga",
"parking_lot",
+13 -1
View File
@@ -3166,7 +3166,7 @@ impl From<usize> 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<f32> for ScaledPixels {
}
}
impl std::iter::Sum for ScaledPixels {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(Self::default(), |a, b| a + b)
}
}
impl<'a> std::iter::Sum<&'a ScaledPixels> for ScaledPixels {
fn sum<I: Iterator<Item = &'a Self>>(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.
+11
View File
@@ -226,6 +226,17 @@ impl Scene {
}
}
/// 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(
+89 -45
View File
@@ -4973,42 +4973,45 @@ impl Window {
}
fn largest_border_interior(quad: &Quad) -> Bounds<ScaledPixels> {
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 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;
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,
// 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<ScaledPixels>| {
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 +5039,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 +5123,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
});
}
}
+1
View File
@@ -56,6 +56,7 @@ objc2-metal = { version = "0.3.2", default-features = false, features = [
"MTLCommandBuffer",
"MTLCommandEncoder",
"MTLCommandQueue",
"MTLDepthStencil",
"MTLDevice",
"MTLDrawable",
"MTLLibrary",
+174 -27
View File
@@ -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<ProtocolObject<dyn MTLDevice>>,
layer: Option<Retained<CAMetalLayer>>,
#[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<ProtocolObject<dyn MTLRenderPipelineState>>,
shadows_pipeline_state: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
quads_pipeline_state: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
opaque_quads_pipeline_state: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
underlines_pipeline_state: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
monochrome_sprites_pipeline_state: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
polychrome_sprites_pipeline_state: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
surfaces_pipeline_state: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
depth_write_state: Retained<ProtocolObject<dyn MTLDepthStencilState>>,
depth_test_state: Retained<ProtocolObject<dyn MTLDepthStencilState>>,
depth_texture: Option<Retained<ProtocolObject<dyn MTLTexture>>>,
instance_buffer_pool: Arc<Mutex<InstanceBufferPool>>,
sprite_atlas: Arc<MetalAtlas>,
core_video_texture_cache: CFRetained<CVMetalTextureCache>,
@@ -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<dyn MTLTexture>,
) -> Result<Retained<ProtocolObject<dyn MTLTexture>>> {
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<dyn MTLRenderCommandEncoder>,
) {
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<usize>,
@@ -1164,6 +1287,7 @@ impl MetalRenderer {
fn new_command_encoder_for_texture(
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
texture: &ProtocolObject<dyn MTLTexture>,
depth_texture: &ProtocolObject<dyn MTLTexture>,
viewport_size: Size<DevicePixels>,
clear_color: MTLClearColor,
) -> Result<Retained<ProtocolObject<dyn MTLRenderCommandEncoder>>> {
@@ -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<Retained<ProtocolObject<dyn MTLRenderPipelineState>>> {
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<dyn MTLDevice>,
write_depth: bool,
) -> Result<Retained<ProtocolObject<dyn MTLDepthStencilState>>> {
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<ProtocolObject<dyn MTLBuffer>>,
@@ -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)]
+56 -2
View File
@@ -67,17 +67,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);
@@ -429,6 +450,39 @@ 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 ShadowFragmentInput {
float4 position [[position]];
float4 color [[flat]];
+1
View File
@@ -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"] }
+55 -1
View File
@@ -81,6 +81,9 @@ struct GlobalParams {
viewport_size: vec2<f32>,
path_paint_base: u32,
path_curve_base: u32,
depth_scale: f32,
quad_count: u32,
pad: vec2<u32>,
}
override PREMULTIPLIED_ALPHA: bool = false;
@@ -564,6 +567,20 @@ fn is_shaped(quad: Quad) -> bool {
return has_rounded_corners(quad.corner_radii) || has_border(quad.border_widths);
}
const CULLED_POSITION: vec4<f32> = vec4<f32>(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<f32>,
@location(0) @interpolate(flat) border_color: vec4<f32>,
@@ -576,12 +593,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>(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>(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;
@@ -963,6 +986,37 @@ fn fmod(a: f32, b: f32) -> f32 {
return a - b * trunc(a / b);
}
// --- opaque quads --- //
struct OpaqueQuadVarying {
@builtin(position) position: vec4<f32>,
@location(0) @interpolate(flat) color: vec4<f32>,
}
@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>(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<f32> {
return input.color;
}
// --- shadows --- //
struct Shadow {
+12
View File
@@ -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,
+144 -23
View File
@@ -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,16 @@ struct GlobalParams {
viewport_size: [f32; 2],
path_paint_base: u32,
path_curve_base: u32,
depth_scale: f32,
quad_count: u32,
pad: [u32; 2],
}
const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
struct DepthTexture {
texture: wgpu::Texture,
view: wgpu::TextureView,
}
#[repr(C)]
@@ -110,6 +120,7 @@ pub struct WgpuSurfaceConfig {
struct WgpuPipelines {
quads: wgpu::RenderPipeline,
opaque_quads: wgpu::RenderPipeline,
shadows: wgpu::RenderPipeline,
path_tiles: wgpu::RenderPipeline,
underlines: wgpu::RenderPipeline,
@@ -206,7 +217,9 @@ struct WgpuRendererCore {
rendering_params: RenderingParameters,
is_bgr: bool,
dual_source_blending: bool,
transient_attachments: bool,
adapter_info: wgpu::AdapterInfo,
depth_texture: Option<DepthTexture>,
/// Read by the headless renderer to create its render target.
#[cfg(all(
not(target_family = "wasm"),
@@ -780,7 +793,7 @@ impl WgpuRendererCore {
texture_layout: Option<&wgpu::BindGroupLayout>,
topology: wgpu::PrimitiveTopology,
color_targets: &[Option<wgpu::ColorTargetState>],
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));
@@ -814,12 +827,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 +849,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 +879,7 @@ impl WgpuRendererCore {
None,
wgpu::PrimitiveTopology::TriangleStrip,
&[Some(color_target.clone())],
1,
false,
&shader_module,
);
@@ -860,7 +892,7 @@ impl WgpuRendererCore {
None,
wgpu::PrimitiveTopology::TriangleStrip,
&[Some(color_target.clone())],
1,
false,
&shader_module,
);
@@ -873,7 +905,7 @@ impl WgpuRendererCore {
None,
wgpu::PrimitiveTopology::TriangleStrip,
&[Some(color_target.clone())],
1,
false,
&shader_module,
);
@@ -886,7 +918,7 @@ impl WgpuRendererCore {
Some(&layouts.texture),
wgpu::PrimitiveTopology::TriangleStrip,
&[Some(color_target.clone())],
1,
false,
&shader_module,
);
@@ -917,7 +949,7 @@ impl WgpuRendererCore {
blend: Some(subpixel_blend),
write_mask: wgpu::ColorWrites::COLOR,
})],
1,
false,
subpixel_module,
))
} else {
@@ -933,7 +965,7 @@ impl WgpuRendererCore {
Some(&layouts.texture),
wgpu::PrimitiveTopology::TriangleStrip,
&[Some(color_target.clone())],
1,
false,
&shader_module,
);
@@ -946,12 +978,13 @@ impl WgpuRendererCore {
None,
wgpu::PrimitiveTopology::TriangleStrip,
&[Some(color_target)],
1,
false,
&shader_module,
);
WgpuPipelines {
quads,
opaque_quads,
shadows,
path_tiles,
underlines,
@@ -1257,7 +1290,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 +1387,14 @@ 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,
pad: [0; 2],
};
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<DevicePixels>) {
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,
+1
View File
@@ -33,6 +33,7 @@ mod shader_compilation {
// Define all modules
let modules = [
"quad",
"opaque_quad",
"shadow",
"path_tile",
"underline",
+281 -21
View File
@@ -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<ID3D11DeviceContext1>,
dxgi_device: Option<IDXGIDevice>,
annotation: Option<ID3DUserDefinedAnnotation>,
}
@@ -71,6 +72,8 @@ struct DirectXResources {
swap_chain: IDXGISwapChain1,
render_target: Option<ID3D11Texture2D>,
render_target_view: Option<ID3D11RenderTargetView>,
depth_stencil_texture: ID3D11Texture2D,
depth_stencil_view: Option<ID3D11DepthStencilView>,
// Cached viewport
viewport: D3D11_VIEWPORT,
@@ -79,6 +82,7 @@ struct DirectXResources {
struct DirectXRenderPipelines {
shadow_pipeline: PipelineState<Shadow>,
quad_pipeline: PipelineState<Quad>,
opaque_quad_pipeline: OpaqueQuadPipeline,
path_tile_pipeline: PipelineState<PathTile>,
path_curves: StructuredBuffer<PathCurve>,
path_paints: StructuredBuffer<PathPaint>,
@@ -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<DevicePixels>) -> 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<T> {
fragment: ID3D11PixelShader,
instances: StructuredBuffer<T>,
blend_state: ID3D11BlendState,
depth_stencil_state: ID3D11DepthStencilState,
}
impl<T> PipelineState<T> {
@@ -1085,6 +1190,7 @@ impl<T> PipelineState<T> {
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<T> PipelineState<T> {
&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<T> PipelineState<T> {
&self.vertex,
&self.fragment,
&self.blend_state,
&self.depth_stencil_state,
);
unsafe {
device_context.PSSetSamplers(0, Some(sampler));
@@ -1158,6 +1266,63 @@ impl<T> PipelineState<T> {
}
}
/// 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<Self> {
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<Quad>,
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<ID3D11RenderTargetView>,
ID3D11Texture2D,
Option<ID3D11DepthStencilView>,
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<ID3D11DepthStencilView>)> {
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<ID3D11BlendState> {
}
}
#[inline]
fn create_opaque_blend_state(device: &ID3D11Device) -> Result<ID3D11BlendState> {
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<ID3D11DepthStencilState> {
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<ID3D11BlendState> {
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",
+60 -2
View File
@@ -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;
@@ -536,12 +543,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<Quad> 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 +571,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);
@@ -838,6 +861,41 @@ float4 quad_fragment(QuadFragmentInput input): SV_Target {
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
+1 -5
View File
@@ -16336,11 +16336,7 @@ fn window_corners(cx: &mut VisualTestContext) -> WindowCorners {
let quads = window.painted_quads();
let outline = quads
.iter()
.find(|quad| {
quad.bounds == frame
&& quad.border_widths.top.0 > 0.
&& !quad.border_color.is_transparent()
})
.find(|quad| quad.bounds == frame && !quad.border_color.is_transparent())
.expect("window frame border");
let probe_offset = 1.5 * scale_factor;
let corner = |x: ScaledPixels, y: ScaledPixels, direction_x: f32, direction_y: f32| {