diff --git a/crates/editor/src/element.rs b/crates/editor/src/element.rs index 331291e6d0d..f9ce88a407f 100644 --- a/crates/editor/src/element.rs +++ b/crates/editor/src/element.rs @@ -5083,7 +5083,7 @@ impl EditorElement { } fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) { - window.paint_layer(layout.hitbox.bounds, |window| { + window.paint_layer(|window| { let scroll_top = layout.position_map.scroll_position.y; let gutter_bg = cx.theme().colors().editor_gutter_background; window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg)); @@ -5406,7 +5406,7 @@ impl EditorElement { } let line_height = layout.position_map.line_height; - window.paint_layer(layout.gutter_hitbox.bounds, |window| { + window.paint_layer(|window| { for (hunk, hitbox) in &layout.display_hunks { let hunk_to_paint = match hunk { DisplayDiffHunk::Folded { .. } => { @@ -5619,35 +5619,33 @@ impl EditorElement { window: &mut Window, cx: &mut App, ) { - window.paint_layer(layout.gutter_hitbox.bounds, |window| { - window.with_element_namespace("crease_toggles", |window| { - for crease_toggle in layout.crease_toggles.iter_mut().flatten() { - crease_toggle.paint(window, cx); - } - }); - - window.with_element_namespace("expand_toggles", |window| { - for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() { - expand_toggle.paint(window, cx); - } - }); - - for bookmark in layout.bookmarks.iter_mut() { - bookmark.paint(window, cx); - } - - for breakpoint in layout.breakpoints.iter_mut() { - breakpoint.paint(window, cx); - } - - for test_indicator in layout.test_indicators.iter_mut() { - test_indicator.paint(window, cx); - } - - if let Some(diff_review_button) = layout.diff_review_button.as_mut() { - diff_review_button.paint(window, cx); + window.with_element_namespace("crease_toggles", |window| { + for crease_toggle in layout.crease_toggles.iter_mut().flatten() { + crease_toggle.paint(window, cx); } }); + + window.with_element_namespace("expand_toggles", |window| { + for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() { + expand_toggle.paint(window, cx); + } + }); + + for bookmark in layout.bookmarks.iter_mut() { + bookmark.paint(window, cx); + } + + for breakpoint in layout.breakpoints.iter_mut() { + breakpoint.paint(window, cx); + } + + for test_indicator in layout.test_indicators.iter_mut() { + test_indicator.paint(window, cx); + } + + if let Some(diff_review_button) = layout.diff_review_button.as_mut() { + diff_review_button.paint(window, cx); + } } fn paint_gutter_highlights( @@ -5685,7 +5683,7 @@ impl EditorElement { let highlight_width = 0.275 * layout.position_map.line_height; let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height); - window.paint_layer(layout.gutter_hitbox.bounds, |window| { + window.paint_layer(|window| { for (range, color) in &layout.highlighted_gutter_ranges { let start_row = if range.start.row() < layout.visible_display_row_range.start { layout.visible_display_row_range.start - DisplayRow(1) @@ -5729,11 +5727,9 @@ impl EditorElement { return; }; - window.paint_layer(layout.gutter_hitbox.bounds, |window| { - for mut blame_element in blamed_display_rows.into_iter() { - blame_element.paint(window, cx); - } - }) + for mut blame_element in blamed_display_rows.into_iter() { + blame_element.paint(window, cx); + } } fn populate_point_diagnostics( @@ -5975,7 +5971,7 @@ impl EditorElement { window: &mut Window, cx: &mut App, ) -> SmallVec<[Range; 32]> { - window.paint_layer(layout.position_map.text_hitbox.bounds, |window| { + window.paint_layer(|window| { let mut invisible_display_ranges = SmallVec::<[Range; 32]>::new(); let line_end_overshoot = 0.15 * layout.position_map.line_height; for (range, color) in &layout.highlighted_ranges { @@ -6072,7 +6068,7 @@ impl EditorElement { // A softer than perfect black let redaction_color = gpui::rgb(0x0e1111); - window.paint_layer(layout.position_map.text_hitbox.bounds, |window| { + window.paint_layer(|window| { for range in layout.redacted_ranges.iter() { self.paint_highlighted_range( range.clone(), @@ -6173,7 +6169,7 @@ impl EditorElement { }, }; - window.paint_layer(hitbox.bounds, |window| { + window.paint_layer(|window| { window.paint_quad(quad( hitbox.bounds, Corners::default(), @@ -6676,9 +6672,7 @@ impl EditorElement { fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) { if let Some(mut blame_layout) = layout.inline_blame_layout.take() { - window.paint_layer(layout.position_map.text_hitbox.bounds, |window| { - blame_layout.element.paint(window, cx); - }) + blame_layout.element.paint(window, cx); } } @@ -6689,9 +6683,7 @@ impl EditorElement { cx: &mut App, ) { if let Some(mut inline_code_actions) = layout.inline_code_actions.take() { - window.paint_layer(layout.position_map.text_hitbox.bounds, |window| { - inline_code_actions.paint(window, cx); - }) + inline_code_actions.paint(window, cx); } } @@ -6711,54 +6703,48 @@ impl EditorElement { let minimap_hitbox = layout.thumb_layout.hitbox.clone(); let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap(); - window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| { - window.with_element_namespace("minimap", |window| { - layout.minimap.paint(window, cx); - if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds { - let minimap_thumb_color = match layout.thumb_layout.thumb_state { - ScrollbarThumbState::Idle => { - cx.theme().colors().minimap_thumb_background - } - ScrollbarThumbState::Hovered => { - cx.theme().colors().minimap_thumb_hover_background - } - ScrollbarThumbState::Dragging => { - cx.theme().colors().minimap_thumb_active_background - } - }; - let minimap_thumb_border = match layout.thumb_border_style { - MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH), - MinimapThumbBorder::LeftOnly => Edges { - left: ScrollbarLayout::BORDER_WIDTH, - ..Default::default() - }, - MinimapThumbBorder::LeftOpen => Edges { - right: ScrollbarLayout::BORDER_WIDTH, - top: ScrollbarLayout::BORDER_WIDTH, - bottom: ScrollbarLayout::BORDER_WIDTH, - ..Default::default() - }, - MinimapThumbBorder::RightOpen => Edges { - left: ScrollbarLayout::BORDER_WIDTH, - top: ScrollbarLayout::BORDER_WIDTH, - bottom: ScrollbarLayout::BORDER_WIDTH, - ..Default::default() - }, - MinimapThumbBorder::None => Default::default(), - }; + window.with_element_namespace("minimap", |window| { + layout.minimap.paint(window, cx); + if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds { + let minimap_thumb_color = match layout.thumb_layout.thumb_state { + ScrollbarThumbState::Idle => cx.theme().colors().minimap_thumb_background, + ScrollbarThumbState::Hovered => { + cx.theme().colors().minimap_thumb_hover_background + } + ScrollbarThumbState::Dragging => { + cx.theme().colors().minimap_thumb_active_background + } + }; + let minimap_thumb_border = match layout.thumb_border_style { + MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH), + MinimapThumbBorder::LeftOnly => Edges { + left: ScrollbarLayout::BORDER_WIDTH, + ..Default::default() + }, + MinimapThumbBorder::LeftOpen => Edges { + right: ScrollbarLayout::BORDER_WIDTH, + top: ScrollbarLayout::BORDER_WIDTH, + bottom: ScrollbarLayout::BORDER_WIDTH, + ..Default::default() + }, + MinimapThumbBorder::RightOpen => Edges { + left: ScrollbarLayout::BORDER_WIDTH, + top: ScrollbarLayout::BORDER_WIDTH, + bottom: ScrollbarLayout::BORDER_WIDTH, + ..Default::default() + }, + MinimapThumbBorder::None => Default::default(), + }; - window.paint_layer(minimap_hitbox.bounds, |window| { - window.paint_quad(quad( - thumb_bounds, - Corners::default(), - minimap_thumb_color, - minimap_thumb_border, - cx.theme().colors().minimap_thumb_border, - BorderStyle::Solid, - )); - }); - } - }); + window.paint_quad(quad( + thumb_bounds, + Corners::default(), + minimap_thumb_color, + minimap_thumb_border, + cx.theme().colors().minimap_thumb_border, + BorderStyle::Solid, + )); + } }); if dragging_minimap { diff --git a/crates/editor/src/element/header.rs b/crates/editor/src/element/header.rs index cb12d33f17d..5cd09185db3 100644 --- a/crates/editor/src/element/header.rs +++ b/crates/editor/src/element/header.rs @@ -432,42 +432,36 @@ impl StickyHeaders { let line_height = layout.position_map.line_height; for line in self.lines.iter_mut().rev() { - window.paint_layer( - Bounds::new( + window.paint_layer(|window| { + let gutter_bounds = Bounds::new( layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset), - size(line.hitbox.size.width, line_height), - ), - |window| { - let gutter_bounds = Bounds::new( - layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset), - size(layout.gutter_hitbox.size.width, line_height), - ); - window.paint_quad(fill(gutter_bounds, self.gutter_background)); + size(layout.gutter_hitbox.size.width, line_height), + ); + window.paint_quad(fill(gutter_bounds, self.gutter_background)); - let text_bounds = Bounds::new( - layout.position_map.text_hitbox.origin + point(Pixels::ZERO, line.offset), - size(line.available_text_width, line_height), - ); - window.paint_quad(fill(text_bounds, self.content_background)); + let text_bounds = Bounds::new( + layout.position_map.text_hitbox.origin + point(Pixels::ZERO, line.offset), + size(line.available_text_width, line_height), + ); + window.paint_quad(fill(text_bounds, self.content_background)); - if line.hitbox.is_hovered(window) { - let hover_overlay = cx.theme().colors().panel_overlay_hover; - window.paint_quad(fill(gutter_bounds, hover_overlay)); - window.paint_quad(fill(text_bounds, hover_overlay)); - } + if line.hitbox.is_hovered(window) { + let hover_overlay = cx.theme().colors().panel_overlay_hover; + window.paint_quad(fill(gutter_bounds, hover_overlay)); + window.paint_quad(fill(text_bounds, hover_overlay)); + } - line.paint( - layout, - self.gutter_right_padding, - line.available_text_width, - layout.content_origin, - line_height, - whitespace_setting, - window, - cx, - ); - }, - ); + line.paint( + layout, + self.gutter_right_padding, + line.available_text_width, + layout.content_origin, + line_height, + whitespace_setting, + window, + cx, + ); + }); window.set_cursor_style(CursorStyle::IBeam, &line.hitbox); } diff --git a/crates/git_ui/src/git_graph.rs b/crates/git_ui/src/git_graph.rs index a0950056c9d..5615de90d64 100644 --- a/crates/git_ui/src/git_graph.rs +++ b/crates/git_ui/src/git_graph.rs @@ -3631,7 +3631,7 @@ impl GitGraph { move |bounds: Bounds, _: (), window: &mut Window, cx: &mut App| { graph_canvas_bounds.set(Some(bounds)); - window.paint_layer(bounds, |window| { + window.paint_layer(|window| { let theme = cx.theme(); let accent_colors = theme.accents(); let background = theme.colors().editor_background; @@ -3670,6 +3670,48 @@ impl GitGraph { } } + // Commit nodes are painted before the lines, which are drawn + // over the nodes' halos to meet their rings. + for (row_idx, row) in rows.into_iter().enumerate() { + let absolute_row_idx = first_visible_row + row_idx; + let row_color = accent_colors.color_for_index(row.color_idx as u32); + let row_y_center = + bounds.origin.y + row_idx as f32 * row_height + row_height / 2.0 + - vertical_scroll_offset; + + let commit_x = lane_center_x(bounds, row.lane as f32); + + if paint_ref_connectors && !row.data.ref_names.is_empty() { + paint_dashed_connector( + bounds.origin.x, + commit_x - COMMIT_CIRCLE_RADIUS, + row_y_center, + row_color.opacity(0.5), + window, + ); + } + + // Match the node halo to the row's effective background so + // the ring blends seamlessly on hovered/selected rows. + let node_background = if selected_entry_idx == Some(absolute_row_idx) + || context_menu_target_index == Some(absolute_row_idx) + { + background.blend(selected_bg) + } else if hovered_entry_idx == Some(absolute_row_idx) { + background.blend(hover_bg) + } else { + background + }; + + draw_commit_circle( + commit_x, + row_y_center, + row_color, + node_background, + window, + ); + } + for line in commit_lines { let Some((start_segment_idx, start_column)) = line.get_first_visible_segment_idx(first_visible_row) @@ -3825,56 +3867,10 @@ impl GitGraph { for builder in builders { if let Ok(path) = builder.build() { - // we paint each color on it's own layer to stop overlapping lines - // of different colors changing the color of a line - window.paint_layer(bounds, |window| { - window.paint_path(path, line_color); - }); + window.paint_path(path, line_color); } } } - - // Commit nodes are painted last so they sit on top of the - // connector lines, keeping each commit a clear, distinct point. - for (row_idx, row) in rows.into_iter().enumerate() { - let absolute_row_idx = first_visible_row + row_idx; - let row_color = accent_colors.color_for_index(row.color_idx as u32); - let row_y_center = - bounds.origin.y + row_idx as f32 * row_height + row_height / 2.0 - - vertical_scroll_offset; - - let commit_x = lane_center_x(bounds, row.lane as f32); - - if paint_ref_connectors && !row.data.ref_names.is_empty() { - paint_dashed_connector( - bounds.origin.x, - commit_x - COMMIT_CIRCLE_RADIUS, - row_y_center, - row_color.opacity(0.5), - window, - ); - } - - // Match the node halo to the row's effective background so - // the ring blends seamlessly on hovered/selected rows. - let node_background = if selected_entry_idx == Some(absolute_row_idx) - || context_menu_target_index == Some(absolute_row_idx) - { - background.blend(selected_bg) - } else if hovered_entry_idx == Some(absolute_row_idx) { - background.blend(hover_bg) - } else { - background - }; - - draw_commit_circle( - commit_x, - row_y_center, - row_color, - node_background, - window, - ); - } }) }, ) diff --git a/crates/gpui/src/bounds_tree.rs b/crates/gpui/src/bounds_tree.rs index e95e32477b9..a4a0ade5499 100644 --- a/crates/gpui/src/bounds_tree.rs +++ b/crates/gpui/src/bounds_tree.rs @@ -1,4 +1,4 @@ -use crate::{Bounds, Half}; +use crate::{Bounds, Half, scene::PrimitiveKind}; use std::{ cmp, fmt::Debug, @@ -13,10 +13,12 @@ const MAX_CHILDREN: usize = 12; /// A spatial tree optimized for finding maximum ordering among intersecting bounds. /// /// This is an R-tree variant specifically designed for the use case of assigning -/// z-order to overlapping UI elements. Key optimizations: -/// - Tracks the leaf with global max ordering for O(1) fast-path queries +/// z-order to overlapping UI elements. Each bounds has an ordering and a kind; +/// bounds sharing an ordering are drawn in the order of their kinds. Key +/// optimizations: +/// - Tracks the leaf with global max key for O(1) fast-path queries /// - Uses higher branching factor (4) for lower tree height -/// - Aggressive pruning during search based on max_order metadata +/// - Aggressive pruning during search based on max_key metadata #[derive(Debug)] pub(crate) struct BoundsTree where @@ -26,7 +28,7 @@ where nodes: Vec>, /// Index of the root node, if any. root: Option, - /// Index of the leaf with the highest ordering (for fast-path lookups). + /// Index of the leaf with the highest key (for fast-path lookups). max_leaf: Option, /// Reusable stack for tree traversal during insertion. insert_path: Vec, @@ -42,19 +44,24 @@ where { /// Bounding box containing this node and all descendants. bounds: Bounds, - /// Maximum ordering value in this subtree. - max_order: u32, + /// Maximum key in this subtree. + max_key: Key, /// Node-specific data. kind: NodeKind, } +/// The ordering of a bounds, then its kind, which orders the bounds that share +/// an ordering. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +struct Key { + ordering: u32, + kind: PrimitiveKind, +} + #[derive(Debug, Clone)] enum NodeKind { /// Leaf node containing actual bounds data. - Leaf { - /// The ordering assigned to this bounds. - order: u32, - }, + Leaf { key: Key }, /// Internal node with children. Internal { /// Indices of child nodes (2 to MAX_CHILDREN). @@ -65,7 +72,7 @@ enum NodeKind { /// Fixed-size array for child indices, avoiding heap allocation. #[derive(Debug, Clone)] struct NodeChildren { - // Keeps an invariant where the max order child is always at the end + // Keeps an invariant where the max key child is always at the end indices: [usize; MAX_CHILDREN], len: u8, } @@ -113,39 +120,48 @@ where self.search_stack.clear(); } - /// Inserts bounds into the tree and returns its assigned ordering. + /// Inserts bounds of the given kind into the tree and returns its assigned + /// ordering. /// - /// The ordering is one greater than the maximum ordering of any - /// existing bounds that intersect with the new bounds. - pub fn insert(&mut self, new_bounds: Bounds) -> u32 { - // Find maximum ordering among intersecting bounds - let max_intersecting = self.find_max_ordering(&new_bounds); - let ordering = max_intersecting + 1; + /// The ordering is one greater than the maximum ordering of any existing + /// bounds that intersect with the new bounds. The new bounds share that + /// maximum ordering instead if every intersecting bounds there has a kind + /// of at most `max_shared_kind`, since those are drawn first. + pub fn insert( + &mut self, + new_bounds: Bounds, + kind: PrimitiveKind, + max_shared_kind: PrimitiveKind, + ) -> u32 { + let ordering = match self.find_max_key(&new_bounds) { + None => 1, + Some(max_key) if max_key.kind <= max_shared_kind => max_key.ordering, + Some(max_key) => max_key.ordering + 1, + }; + let key = Key { ordering, kind }; // Insert the new leaf - let new_leaf_idx = self.insert_leaf(new_bounds, ordering); + let new_leaf_idx = self.insert_leaf(new_bounds, key); // Update max_leaf tracking self.max_leaf = match self.max_leaf { None => Some(new_leaf_idx), - Some(old_idx) if self.nodes[old_idx].max_order < ordering => Some(new_leaf_idx), + Some(old_idx) if self.nodes[old_idx].max_key < key => Some(new_leaf_idx), some => some, }; ordering } - /// Finds the maximum ordering among all bounds that intersect with the query. - fn find_max_ordering(&mut self, query: &Bounds) -> u32 { - let Some(root_idx) = self.root else { - return 0; - }; + /// Finds the maximum key among all bounds that intersect with the query. + fn find_max_key(&mut self, query: &Bounds) -> Option { + let root_idx = self.root?; - // Fast path: check if the max-ordering leaf intersects + // Fast path: check if the max-key leaf intersects if let Some(max_idx) = self.max_leaf { let max_node = &self.nodes[max_idx]; if query.intersects(&max_node.bounds) { - return max_node.max_order; + return Some(max_node.max_key); } } @@ -153,7 +169,8 @@ where self.search_stack.clear(); self.search_stack.push(NonNull::from(&self.nodes[root_idx])); - let mut max_found = 0u32; + // `None` compares below every key. + let mut max_found = None; while let Some(node) = self.search_stack.pop() { // SAFETY: `node` is guaranteed to be valid as the `nodes` stack is unmodified in this function @@ -161,7 +178,7 @@ where let node = unsafe { node.as_ref() }; // Pruning: skip if this subtree can't improve our result - if node.max_order <= max_found { + if Some(node.max_key) <= max_found { continue; } @@ -171,18 +188,18 @@ where } match &node.kind { - NodeKind::Leaf { order } => { - max_found = cmp::max(max_found, *order); + NodeKind::Leaf { key } => { + max_found = cmp::max(max_found, Some(*key)); } NodeKind::Internal { children } => { - // Children are maintained with highest max_order at the end. + // Children are maintained with highest max_key at the end. // Push in forward order to highest (last) is popped first. self.search_stack.extend( children .as_slice() .iter() .map(|&child_idx| &self.nodes[child_idx]) - .filter(|node| node.max_order > max_found) + .filter(|node| Some(node.max_key) > max_found) .map(NonNull::from), ); } @@ -192,14 +209,14 @@ where max_found } - /// Inserts a leaf node with the given bounds and ordering. + /// Inserts a leaf node with the given bounds and key. /// Returns the index of the new leaf. - fn insert_leaf(&mut self, bounds: Bounds, order: u32) -> usize { + fn insert_leaf(&mut self, bounds: Bounds, key: Key) -> usize { let new_leaf_idx = self.nodes.len(); self.nodes.push(Node { bounds: bounds.clone(), - max_order: order, - kind: NodeKind::Leaf { order }, + max_key: key, + kind: NodeKind::Leaf { key }, }); let Some(root_idx) = self.root else { @@ -211,11 +228,11 @@ where // If root is a leaf, create internal node with both if matches!(self.nodes[root_idx].kind, NodeKind::Leaf { .. }) { let root_bounds = self.nodes[root_idx].bounds.clone(); - let root_order = self.nodes[root_idx].max_order; + let root_key = self.nodes[root_idx].max_key; let mut children = NodeChildren::new(); // Max end invariant - if order > root_order { + if key > root_key { children.push(root_idx); children.push(new_leaf_idx); } else { @@ -226,7 +243,7 @@ where let new_root_idx = self.nodes.len(); self.nodes.push(Node { bounds: root_bounds.union(&bounds), - max_order: cmp::max(root_order, order), + max_key: cmp::max(root_key, key), kind: NodeKind::Internal { children }, }); self.root = Some(new_root_idx); @@ -270,24 +287,24 @@ where if let NodeKind::Internal { children } = &mut node.kind { children.push(new_leaf_idx); - // Swap new leaf only if it has the highest max_order - if order <= node.max_order { + // Swap new leaf only if it has the highest max_key + if key <= node.max_key { let last = children.len() - 1; children.indices.swap(last - 1, last); } } node.bounds = node.bounds.union(&bounds); - node.max_order = cmp::max(node.max_order, order); + node.max_key = cmp::max(node.max_key, key); break; } else { // Node is full, create new internal with [best_leaf, new_leaf] let sibling_bounds = self.nodes[best_child_idx].bounds.clone(); - let sibling_order = self.nodes[best_child_idx].max_order; + let sibling_key = self.nodes[best_child_idx].max_key; let mut new_children = NodeChildren::new(); // Max end invariant - if order > sibling_order { + if key > sibling_key { new_children.push(best_child_idx); new_children.push(new_leaf_idx); } else { @@ -296,10 +313,10 @@ where } let new_internal_idx = self.nodes.len(); - let new_internal_max = cmp::max(sibling_order, order); + let new_internal_max_key = cmp::max(sibling_key, key); self.nodes.push(Node { bounds: sibling_bounds.union(&bounds), - max_order: new_internal_max, + max_key: new_internal_max_key, kind: NodeKind::Internal { children: new_children, }, @@ -312,9 +329,9 @@ where children.indices[best_child_pos] = new_internal_idx; - // If new internal has highest max_order, swap it to the end + // If new internal has highest max_key, swap it to the end // to maintain sorting invariant - if new_internal_max > parent.max_order { + if new_internal_max_key > parent.max_key { children.indices.swap(best_child_pos, children_len - 1); } } @@ -326,14 +343,14 @@ where } } - // Propagate bounds and max_order updates up the tree + // Propagate bounds and max_key updates up the tree let mut updated_child_idx = None; for &node_idx in self.insert_path.iter().rev() { let node = &mut self.nodes[node_idx]; node.bounds = node.bounds.union(&bounds); - if node.max_order < order { - node.max_order = order; + if node.max_key < key { + node.max_key = key; // Swap updated child to end (skip first iteration since the invariant is already handled by previous cases) if let Some(child_idx) = updated_child_idx { @@ -380,6 +397,7 @@ mod tests { #[test] fn test_insert() { let mut tree = BoundsTree::::default(); + let (quad, shadow) = (PrimitiveKind::Quad, PrimitiveKind::Shadow); let bounds1 = Bounds { origin: Point { x: 0.0, y: 0.0 }, size: Size { @@ -403,9 +421,9 @@ mod tests { }; // Insert the bounds into the tree and verify the order is correct - assert_eq!(tree.insert(bounds1), 1); - assert_eq!(tree.insert(bounds2), 2); - assert_eq!(tree.insert(bounds3), 3); + assert_eq!(tree.insert(bounds1, quad, shadow), 1); + assert_eq!(tree.insert(bounds2, quad, shadow), 2); + assert_eq!(tree.insert(bounds3, quad, shadow), 3); // Insert non-overlapping bounds and verify they can reuse orders let bounds4 = Bounds { @@ -429,19 +447,24 @@ mod tests { height: 10.0, }, }; - assert_eq!(tree.insert(bounds4), 1); // bounds4 does not overlap with bounds1, bounds2, or bounds3 - assert_eq!(tree.insert(bounds5), 1); // bounds5 does not overlap with any other bounds - assert_eq!(tree.insert(bounds6), 2); // bounds6 overlaps with bounds4, so it should have a different order + assert_eq!(tree.insert(bounds4, quad, shadow), 1); // bounds4 does not overlap with bounds1, bounds2, or bounds3 + assert_eq!(tree.insert(bounds5, quad, shadow), 1); // bounds5 does not overlap with any other bounds + assert_eq!(tree.insert(bounds6, quad, shadow), 2); // bounds6 overlaps with bounds4, so it should have a different order } #[test] fn test_random_iterations() { let max_bounds = 100; for seed in 1..=1000 { - // let seed = 44; let mut tree = BoundsTree::default(); let mut rng = rand::rngs::StdRng::seed_from_u64(seed as u64); - let mut expected_quads: Vec<(Bounds, u32)> = Vec::new(); + let mut expected_quads: Vec<(Bounds, u32, PrimitiveKind)> = Vec::new(); + let kinds = [ + PrimitiveKind::Shadow, + PrimitiveKind::Quad, + PrimitiveKind::Path, + PrimitiveKind::Underline, + ]; // Insert a random number of random AABBs into the tree. let num_bounds = rng.random_range(1..=max_bounds); @@ -454,17 +477,22 @@ mod tests { origin: Point { x: min_x, y: min_y }, size: Size { width, height }, }; + let kind = kinds[rng.random_range(0..kinds.len())]; + let max_shared_kind = kinds[rng.random_range(0..kinds.len())]; - let expected_ordering = expected_quads + let max_intersecting = expected_quads .iter() - .filter_map(|quad| quad.0.intersects(&bounds).then_some(quad.1)) - .max() - .unwrap_or(0) - + 1; - expected_quads.push((bounds, expected_ordering)); + .filter(|quad| quad.0.intersects(&bounds)) + .map(|quad| (quad.1, quad.2)) + .max(); + let expected_ordering = match max_intersecting { + None => 1, + Some((ordering, max_kind)) if max_kind <= max_shared_kind => ordering, + Some((ordering, _)) => ordering + 1, + }; + expected_quads.push((bounds, expected_ordering, kind)); - // Insert the AABB into the tree and collect intersections. - let actual_ordering = tree.insert(bounds); + let actual_ordering = tree.insert(bounds, kind, max_shared_kind); assert_eq!(actual_ordering, expected_ordering); } } diff --git a/crates/gpui/src/geometry.rs b/crates/gpui/src/geometry.rs index 234299825c9..899db1b31d2 100644 --- a/crates/gpui/src/geometry.rs +++ b/crates/gpui/src/geometry.rs @@ -1187,6 +1187,37 @@ impl + Sub + Clone + Debug + Defa let bottom_right = self.bottom_right().max(&other.bottom_right()); Bounds::from_corners(top_left, bottom_right) } + + /// Computes the smallest `Bounds` that covers the area of both `Bounds`. + /// + /// Unlike [`Bounds::union`], an empty `Bounds` covers nothing, so joining with it returns + /// the other `Bounds` unchanged. + /// + /// # Examples + /// + /// ``` + /// # use gpui::{Bounds, Point, Size}; + /// let bounds = Bounds { + /// origin: Point { x: 5, y: 5 }, + /// size: Size { width: 10, height: 10 }, + /// }; + /// let empty = Bounds { + /// origin: Point { x: 0, y: 0 }, + /// size: Size { width: 0, height: 10 }, + /// }; + /// + /// assert_eq!(bounds.join(&empty), bounds); + /// assert_eq!(empty.join(&bounds), bounds); + /// ``` + pub fn join(&self, other: &Self) -> Self { + if self.is_empty() { + other.clone() + } else if other.is_empty() { + self.clone() + } else { + self.union(other) + } + } } impl Bounds @@ -4052,6 +4083,37 @@ mod tests { } } + #[test] + fn test_bounds_join() { + let bounds = Bounds { + origin: Point { x: 5.0, y: 5.0 }, + size: Size { + width: 5.0, + height: 5.0, + }, + }; + let other = Bounds { + origin: Point { x: 20.0, y: 0.0 }, + size: Size { + width: 5.0, + height: 5.0, + }, + }; + assert_eq!(bounds.join(&other), bounds.union(&other)); + + let empty = Bounds { + origin: Point { x: 0.0, y: 0.0 }, + size: Size { + width: 0.0, + height: 10.0, + }, + }; + assert_eq!(bounds.join(&empty), bounds); + assert_eq!(empty.join(&bounds), bounds); + assert_eq!(Bounds::default().join(&bounds), bounds); + assert_ne!(bounds.union(&empty), bounds); + } + #[test] fn test_bounds_intersects() { let bounds1 = Bounds { diff --git a/crates/gpui/src/scene.rs b/crates/gpui/src/scene.rs index 458301fdcf5..4fe789e73ca 100644 --- a/crates/gpui/src/scene.rs +++ b/crates/gpui/src/scene.rs @@ -8,7 +8,8 @@ use crate::{ AtlasTextureId, AtlasTile, Background, Bounds, ContentMask, Corners, Edges, Hsla, Path, PathTiles, Pixels, Point, Radians, ScaledPixels, Size, bounds_tree::BoundsTree, }; -use std::{fmt::Debug, iter::Peekable, ops::Range, rc::Rc, slice}; +use smallvec::SmallVec; +use std::{collections::VecDeque, fmt::Debug, iter::Peekable, ops::Range, rc::Rc, slice}; #[expect(missing_docs)] pub type DrawOrder = u32; @@ -34,12 +35,20 @@ impl PaddedBool32 { } } +struct Layer { + primitives: SmallVec<[Range; 1]>, + bounds: Bounds, + max_kind: PrimitiveKind, + max_shared_kind: PrimitiveKind, +} + #[derive(Default)] #[expect(missing_docs)] pub struct Scene { pub(crate) paint_operations: Vec, primitive_bounds: BoundsTree, - layer_stack: Vec, + layer_stack: Vec, + layers: VecDeque, pub shadows: Vec, pub quads: Vec, pub paths: Vec, @@ -56,6 +65,7 @@ impl Scene { self.paint_operations.clear(); self.primitive_bounds.clear(); self.layer_stack.clear(); + self.layers.clear(); self.paths.clear(); self.shadows.clear(); self.quads.clear(); @@ -70,82 +80,110 @@ impl Scene { self.paint_operations.len() } - pub fn push_layer(&mut self, bounds: Bounds) { - let order = self.primitive_bounds.insert(bounds); - self.layer_stack.push(order); - self.paint_operations - .push(PaintOperation::StartLayer(bounds)); + pub fn push_layer(&mut self) { + self.layer_stack.push(self.layers.len()); + self.layers.push_back(Layer { + primitives: SmallVec::new(), + bounds: Bounds::default(), + max_kind: PrimitiveKind::Shadow, + max_shared_kind: PrimitiveKind::Surface, + }); + self.paint_operations.push(PaintOperation::StartLayer); } pub fn pop_layer(&mut self) { self.layer_stack.pop(); + if self.layer_stack.is_empty() { + while let Some(layer) = self.layers.pop_front() { + self.insert_layer(layer); + } + } self.paint_operations.push(PaintOperation::EndLayer); } - pub fn insert_primitive(&mut self, primitive: impl Into) { - let mut primitive = primitive.into(); - let clipped_bounds = primitive - .bounds() - .intersect(&primitive.content_mask().bounds); + fn insert_layer(&mut self, layer: Layer) { + if layer.primitives.is_empty() { + return; + } + let order = + self.primitive_bounds + .insert(layer.bounds, layer.max_kind, layer.max_shared_kind); + for index in layer.primitives.into_iter().flatten() { + if let PaintOperation::Primitive(primitive) = &self.paint_operations[index] { + let primitive = primitive.clone(); + self.push_primitive(primitive, order); + } + } + } + pub fn insert_primitive(&mut self, primitive: impl Into) { + let primitive = primitive.into(); + let clipped_bounds = primitive.clipped_bounds(); if clipped_bounds.is_empty() { return; } - let order = self - .layer_stack - .last() - .copied() - .unwrap_or_else(|| self.primitive_bounds.insert(clipped_bounds)); - match &mut primitive { - Primitive::Shadow(shadow) => { - shadow.order = order; - self.shadows.push(*shadow); - } - Primitive::Quad(quad) => { - quad.order = order; - self.quads.push(*quad); - } - Primitive::Path(path) => { - path.order = order; - self.paths.push(path.clone()); - } - Primitive::Underline(underline) => { - underline.order = order; - self.underlines.push(*underline); - } - Primitive::MonochromeSprite(sprite) => { - sprite.order = order; - self.monochrome_sprites.push(*sprite); - } - Primitive::SubpixelSprite(sprite) => { - sprite.order = order; - self.subpixel_sprites.push(*sprite); - } - Primitive::PolychromeSprite(sprite) => { - sprite.order = order; - self.polychrome_sprites.push(*sprite); - } - Primitive::Surface(surface) => { - surface.order = order; - self.surfaces.push(surface.clone()); + let kind = primitive.kind(); + if let Some(&layer) = self.layer_stack.last() + && let Some(layer) = self.layers.get_mut(layer) + { + layer.bounds = layer.bounds.join(&clipped_bounds); + layer.max_kind = layer.max_kind.max(kind); + layer.max_shared_kind = layer.max_shared_kind.min(kind.max_shared_kind()); + let index = self.paint_operations.len(); + match layer.primitives.last_mut() { + Some(range) if range.end == index => range.end += 1, + _ => layer.primitives.push(index..index + 1), } + } else { + let order = self + .primitive_bounds + .insert(clipped_bounds, kind, kind.max_shared_kind()); + self.push_primitive(primitive.clone(), order); } self.paint_operations .push(PaintOperation::Primitive(primitive)); } + fn push_primitive(&mut self, primitive: Primitive, order: DrawOrder) { + match primitive { + Primitive::Shadow(shadow) => self.shadows.push(Shadow { order, ..shadow }), + Primitive::Quad(quad) => self.quads.push(Quad { order, ..quad }), + Primitive::Path(mut path) => { + path.order = order; + self.paths.push(path); + } + Primitive::Underline(underline) => { + self.underlines.push(Underline { order, ..underline }) + } + Primitive::MonochromeSprite(sprite) => self + .monochrome_sprites + .push(MonochromeSprite { order, ..sprite }), + Primitive::SubpixelSprite(sprite) => self + .subpixel_sprites + .push(SubpixelSprite { order, ..sprite }), + Primitive::PolychromeSprite(sprite) => self + .polychrome_sprites + .push(PolychromeSprite { order, ..sprite }), + Primitive::Surface(mut surface) => { + surface.order = order; + self.surfaces.push(surface); + } + } + } + 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::StartLayer(bounds) => self.push_layer(*bounds), + PaintOperation::StartLayer => self.push_layer(), PaintOperation::EndLayer => self.pop_layer(), } } } 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); self.paths.sort_by_key(|path| path.order); @@ -208,9 +246,26 @@ pub(crate) enum PrimitiveKind { Surface, } +impl PrimitiveKind { + /// We guarantee that overlapping primitives are drawn in paint order. + /// But, to improve GPU draw batching, the renderer sorts primitives that + /// share a draw order by kind, then by atlas texture, and only then in + /// paint order. So, a primitive can only share the draw order of the + /// topmost primitive it overlaps if that primitive's kind is at most the + /// one returned here. Otherwise, it needs a new draw order. + fn max_shared_kind(self) -> Self { + match self { + Self::MonochromeSprite => Self::Underline, + Self::SubpixelSprite => Self::MonochromeSprite, + Self::PolychromeSprite => Self::SubpixelSprite, + kind => kind, + } + } +} + pub(crate) enum PaintOperation { Primitive(Primitive), - StartLayer(Bounds), + StartLayer, EndLayer, } @@ -229,6 +284,19 @@ pub enum Primitive { #[expect(missing_docs)] impl Primitive { + pub(crate) fn kind(&self) -> PrimitiveKind { + match self { + Primitive::Shadow(_) => PrimitiveKind::Shadow, + Primitive::Quad(_) => PrimitiveKind::Quad, + Primitive::Path(_) => PrimitiveKind::Path, + Primitive::Underline(_) => PrimitiveKind::Underline, + Primitive::MonochromeSprite(_) => PrimitiveKind::MonochromeSprite, + Primitive::SubpixelSprite(_) => PrimitiveKind::SubpixelSprite, + Primitive::PolychromeSprite(_) => PrimitiveKind::PolychromeSprite, + Primitive::Surface(_) => PrimitiveKind::Surface, + } + } + pub fn bounds(&self) -> &Bounds { match self { Primitive::Shadow(shadow) => &shadow.bounds, @@ -242,6 +310,20 @@ impl Primitive { } } + fn transformation(&self) -> TransformationMatrix { + match self { + Primitive::MonochromeSprite(sprite) => sprite.transformation, + Primitive::SubpixelSprite(sprite) => sprite.transformation, + _ => TransformationMatrix::unit(), + } + } + + fn clipped_bounds(&self) -> Bounds { + self.transformation() + .transform_bounds(*self.bounds()) + .intersect(&self.content_mask().bounds) + } + pub fn content_mask(&self) -> &ContentMask { match self { Primitive::Shadow(shadow) => &shadow.content_mask, @@ -578,10 +660,9 @@ pub struct Shadow { pub corner_radii: Corners, pub content_mask: ContentMask, pub color: Hsla, - pub element_bounds: Bounds, - pub element_corner_radii: Corners, - /// 0 = drop shadow (rendered outside the element), 1 = inset shadow (rendered inside). - pub inset: u32, + pub shape_bounds: Bounds, + pub shape_corner_radii: Corners, + pub inset: PaddedBool32, pub pad: u32, // align to 8 bytes } @@ -686,6 +767,31 @@ impl TransformationMatrix { } } + /// The smallest bounds that contain `bounds` once it is transformed. + pub(crate) fn transform_bounds(&self, bounds: Bounds) -> Bounds { + if *self == Self::unit() { + return bounds; + } + let [[xx, xy], [yx, yy]] = self.rotation_scale; + let [translate_x, translate_y] = self.translation; + let corners = [ + bounds.origin, + bounds.top_right(), + bounds.bottom_left(), + bounds.bottom_right(), + ] + .map(|corner| { + Point::new( + ScaledPixels(xx * corner.x.0 + xy * corner.y.0 + translate_x), + ScaledPixels(yx * corner.x.0 + yy * corner.y.0 + translate_y), + ) + }); + let [first, rest @ ..] = corners; + let top_left = rest.iter().fold(first, |min, corner| min.min(corner)); + let bottom_right = rest.iter().fold(first, |max, corner| max.max(corner)); + Bounds::from_corners(top_left, bottom_right) + } + /// Apply transformation to a point, mainly useful for debugging pub fn apply(&self, point: Point) -> Point { let input = [point.x.0, point.y.0]; @@ -881,3 +987,113 @@ impl From for Primitive { Primitive::Path(path) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{point, size}; + + fn square(x: f32) -> Bounds { + Bounds { + origin: point(ScaledPixels(x), ScaledPixels(0.)), + size: size(ScaledPixels(10.), ScaledPixels(10.)), + } + } + + fn quad(x: f32) -> Quad { + Quad { + bounds: square(x), + content_mask: ContentMask { bounds: square(x) }, + ..Default::default() + } + } + + fn underline(x: f32) -> Underline { + Underline { + order: 0, + pad: 0, + bounds: square(x), + content_mask: ContentMask { bounds: square(x) }, + color: Hsla::default(), + thickness: ScaledPixels(1.), + wavy: false.into(), + } + } + + fn batch_labels(scene: &mut Scene) -> Vec { + scene.finish(); + scene.batches().map(|batch| batch.label()).collect() + } + + #[test] + fn layers_are_drawn_in_paint_order() { + // A quad painted after a layer goes above it. + let mut scene = Scene::default(); + scene.insert_primitive(quad(0.)); + scene.push_layer(); + scene.insert_primitive(underline(0.)); + scene.insert_primitive(underline(5.)); + scene.pop_layer(); + scene.insert_primitive(quad(5.)); + assert_eq!( + batch_labels(&mut scene), + ["quads (1)", "underlines (2)", "quads (1)"] + ); + + // A layer goes above the layer painted before it. + let mut scene = Scene::default(); + scene.push_layer(); + scene.insert_primitive(underline(0.)); + scene.pop_layer(); + scene.push_layer(); + scene.insert_primitive(quad(5.)); + scene.pop_layer(); + assert_eq!(batch_labels(&mut scene), ["underlines (1)", "quads (1)"]); + } + + #[test] + fn nested_layers_are_drawn_above_their_parents() { + // A layer has one draw order, so what it paints after a nested layer + // still goes below that layer. + let mut scene = Scene::default(); + scene.push_layer(); + scene.insert_primitive(underline(0.)); + scene.push_layer(); + scene.insert_primitive(quad(5.)); + scene.pop_layer(); + scene.insert_primitive(underline(5.)); + scene.pop_layer(); + assert_eq!(batch_labels(&mut scene), ["underlines (2)", "quads (1)"]); + + // The same holds when the nested layer shares its parent's order. + let mut scene = Scene::default(); + scene.push_layer(); + scene.insert_primitive(quad(0.)); + scene.push_layer(); + scene.insert_primitive(quad(5.)); + scene.pop_layer(); + scene.insert_primitive(quad(8.)); + scene.pop_layer(); + assert_eq!(batch_labels(&mut scene), ["quads (3)"]); + assert_eq!( + scene + .quads + .iter() + .map(|quad| quad.bounds) + .collect::>(), + [square(0.), square(8.), square(5.)] + ); + + // A layer goes above the layers nested in the layer before it. + let mut scene = Scene::default(); + scene.push_layer(); + scene.push_layer(); + scene.insert_primitive(underline(0.)); + scene.pop_layer(); + scene.pop_layer(); + scene.push_layer(); + scene.insert_primitive(quad(5.)); + scene.pop_layer(); + assert_eq!(batch_labels(&mut scene), ["underlines (1)", "quads (1)"]); + } +} diff --git a/crates/gpui/src/text_system/line.rs b/crates/gpui/src/text_system/line.rs index bbaa8f9cd73..e0eb71f5918 100644 --- a/crates/gpui/src/text_system/line.rs +++ b/crates/gpui/src/text_system/line.rs @@ -545,15 +545,7 @@ fn paint_line( &mut Window, ), ) -> Result<()> { - let line_bounds = line_paint_bounds( - origin, - layout, - line_height, - align, - align_width, - wrap_boundaries, - ); - window.paint_layer(line_bounds, |window| { + window.paint_layer(|window| { let padding_top = (line_height - layout.ascent - layout.descent) / 2.; let baseline_offset = point(px(0.), padding_top + layout.ascent); let underline_y_offset = underline_y_offset(line_height, layout.ascent, layout.descent); @@ -816,15 +808,7 @@ fn paint_line_background( window: &mut Window, cx: &mut App, ) -> Result<()> { - let line_bounds = line_paint_bounds( - origin, - layout, - line_height, - align, - align_width, - wrap_boundaries, - ); - window.paint_layer(line_bounds, |window| { + window.paint_layer(|window| { let mut decoration_runs = decoration_runs.iter(); let mut wraps = wrap_boundaries.iter().peekable(); let mut run_end = 0; @@ -955,51 +939,6 @@ fn paint_line_background( }) } -fn line_paint_bounds( - origin: Point, - layout: &LineLayout, - line_height: Pixels, - align: TextAlign, - align_width: Option, - wrap_boundaries: &[WrapBoundary], -) -> Bounds { - let mut bounds = Bounds::new( - origin, - size( - layout.width, - line_height * (wrap_boundaries.len() as f32 + 1.), - ), - ); - if align == TextAlign::Left || layout.len == 0 { - return bounds; - } - - let align_width = align_width.unwrap_or(layout.width); - let mut row_start = Pixels::ZERO; - let row_ends = wrap_boundaries - .iter() - .map(|boundary| { - layout.runs[boundary.run_ix].glyphs[boundary.glyph_ix] - .position - .x - }) - .chain([layout.width]); - for (row, row_end) in row_ends.enumerate() { - let width = row_end - row_start; - let offset = match align { - TextAlign::Left => Pixels::ZERO, - TextAlign::Center => (align_width - width) / 2., - TextAlign::Right => align_width - width, - }; - bounds = bounds.union(&Bounds::new( - point(origin.x + offset, origin.y + line_height * row as f32), - size(width, line_height), - )); - row_start = row_end; - } - bounds -} - fn aligned_origin_x( origin: Point, align_width: Pixels, @@ -1067,68 +1006,6 @@ mod tests { } } - #[test] - fn test_aligned_line_paint_bounds() { - let line = make_shaped_line("abcd", &[(0, 0.), (1, 10.), (2, 20.), (3, 30.)], 40., &[]); - let origin = point(px(10.), px(20.)); - let line_height = px(16.); - for (wrapped, align_width, expected_edges) in [ - (false, None, [(10., 50.), (10., 50.), (10., 50.)]), - (true, None, [(10., 50.), (10., 50.), (10., 50.)]), - (false, Some(40.), [(10., 50.), (10., 50.), (10., 50.)]), - (true, Some(40.), [(10., 50.), (10., 50.), (10., 50.)]), - (false, Some(100.), [(10., 50.), (10., 80.), (10., 110.)]), - (true, Some(100.), [(10., 50.), (10., 70.), (10., 110.)]), - (false, Some(10.), [(10., 50.), (-5., 50.), (-20., 50.)]), - (true, Some(10.), [(10., 50.), (5., 50.), (0., 50.)]), - (false, Some(0.), [(10., 50.), (-10., 50.), (-30., 50.)]), - (true, Some(0.), [(10., 50.), (0., 50.), (-10., 50.)]), - ] { - let boundaries = if wrapped { - vec![WrapBoundary { - run_ix: 0, - glyph_ix: 2, - }] - } else { - Vec::new() - }; - for (align, (left, right)) in [TextAlign::Left, TextAlign::Center, TextAlign::Right] - .into_iter() - .zip(expected_edges) - { - assert_eq!( - line_paint_bounds( - origin, - &line.layout, - line_height, - align, - align_width.map(px), - &boundaries, - ), - Bounds::new( - point(px(left), origin.y), - size(px(right - left), px(if wrapped { 32. } else { 16. })), - ), - "wrapped={wrapped}, align={align:?}, align_width={align_width:?}", - ); - } - } - let empty = make_shaped_line("", &[], 0., &[]); - for align in [TextAlign::Left, TextAlign::Center, TextAlign::Right] { - assert_eq!( - line_paint_bounds( - origin, - &empty.layout, - line_height, - align, - Some(px(100.)), - &[] - ), - Bounds::new(origin, size(Pixels::ZERO, line_height)), - ); - } - } - #[gpui::test] fn test_underline_handler_matches_default_paint(cx: &mut TestAppContext) { test_underline_handler_at_scales(cx, |window, cx| { diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs index c6c2eab384d..7505acec3f0 100644 --- a/crates/gpui/src/window.rs +++ b/crates/gpui/src/window.rs @@ -4868,28 +4868,20 @@ impl Window { }); } - /// Creates a new painting layer for the specified bounds. A "layer" is a batch - /// of geometry that are non-overlapping and have the same draw order. This is typically used + /// Creates a new painting layer. A "layer" is a batch of geometry that are + /// non-overlapping and have the same draw order. This is typically used /// for performance reasons. /// + /// Layers painted inside `f` are drawn above this layer, including above + /// what `f` paints after them. + /// /// This method should only be called as part of the paint phase of element drawing. - pub fn paint_layer(&mut self, bounds: Bounds, f: impl FnOnce(&mut Self) -> R) -> R { + pub fn paint_layer(&mut self, f: impl FnOnce(&mut Self) -> R) -> R { self.invalidator.debug_assert_paint(); - let content_mask = self.content_mask(); - let clipped_bounds = bounds.intersect(&content_mask.bounds); - if !clipped_bounds.is_empty() { - self.next_frame - .scene - .push_layer(self.cover_bounds(clipped_bounds)); - } - + self.next_frame.scene.push_layer(); let result = f(self); - - if !clipped_bounds.is_empty() { - self.next_frame.scene.pop_layer(); - } - + self.next_frame.scene.pop_layer(); result } @@ -4909,23 +4901,27 @@ impl Window { let scale_factor = self.scale_factor(); let content_mask = self.snapped_content_mask(); let opacity = self.element_opacity(); - let element_bounds = self.cover_bounds(bounds); - let element_corner_radii = corner_radii.scale(scale_factor); for shadow in shadows { if shadow.inset { continue; } - let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius); + let shape_bounds = + self.cover_bounds((bounds + shadow.offset).dilate(shadow.spread_radius)); + if shape_bounds.is_empty() { + continue; + } + let blur_radius = shadow.blur_radius.scale(scale_factor); self.next_frame.scene.insert_primitive(Shadow { order: 0, - blur_radius: shadow.blur_radius.scale(scale_factor), - bounds: self.cover_bounds(shadow_bounds), + blur_radius, + // Leave room for the tail of the blur. + bounds: shape_bounds.dilate(blur_radius * 3.), content_mask, - corner_radii: corner_radii.scale(scale_factor), + corner_radii: Corners::default(), color: shadow.color.opacity(opacity), - element_bounds, - element_corner_radii, - inset: 0, + shape_bounds, + shape_corner_radii: corner_radii.scale(scale_factor), + inset: false.into(), pad: 0, }); } @@ -4964,13 +4960,13 @@ impl Window { self.next_frame.scene.insert_primitive(Shadow { order: 0, blur_radius: shadow.blur_radius.scale(scale_factor), - bounds: self.cover_bounds(hole), + bounds: element_bounds, content_mask, - corner_radii: hole_corner_radii.scale(scale_factor), + corner_radii: element_corner_radii, color: shadow.color.opacity(opacity), - element_bounds, - element_corner_radii, - inset: 1, + shape_bounds: self.cover_bounds(hole), + shape_corner_radii: hole_corner_radii.scale(scale_factor), + inset: true.into(), pad: 0, }); } diff --git a/crates/gpui_apple/src/shaders.metal b/crates/gpui_apple/src/shaders.metal index 5a5f2793bd2..38a49bc8409 100644 --- a/crates/gpui_apple/src/shaders.metal +++ b/crates/gpui_apple/src/shaders.metal @@ -443,21 +443,8 @@ vertex ShadowFragmentInput shadow_vertex( float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); Shadow shadow = shadows[shadow_id]; - Bounds_ScaledPixels bounds; - if (shadow.inset != 0u) { - bounds = shadow.element_bounds; - } else { - // Leave room for the gaussian tail outside the shadow rect. - float margin = 3. * shadow.blur_radius; - bounds = shadow.bounds; - bounds.origin.x -= margin; - bounds.origin.y -= margin; - bounds.size.width += 2. * margin; - bounds.size.height += 2. * margin; - } - ClippedVertex clipped = - clip_to_mask(unit_vertex, bounds, shadow.content_mask.bounds); + clip_to_mask(unit_vertex, shadow.bounds, shadow.content_mask.bounds); float4 device_position = to_device_position_impl(clipped.position, viewport_size); float4 color = hsla_to_rgba(shadow.color); @@ -473,29 +460,30 @@ fragment float4 shadow_fragment(ShadowFragmentInput input [[stage_in]], [[buffer(ShadowInputIndex_Shadows)]]) { Shadow shadow = shadows[input.shadow_id]; - float2 origin = float2(shadow.bounds.origin.x, shadow.bounds.origin.y); - float2 size = float2(shadow.bounds.size.width, shadow.bounds.size.height); + 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.corner_radii.top_left; + corner_radius = shadow.shape_corner_radii.top_left; } else { - corner_radius = shadow.corner_radii.bottom_left; + corner_radius = shadow.shape_corner_radii.bottom_left; } } else { if (point.y < 0.) { - corner_radius = shadow.corner_radii.top_right; + corner_radius = shadow.shape_corner_radii.top_right; } else { - corner_radius = shadow.corner_radii.bottom_right; + corner_radius = shadow.shape_corner_radii.bottom_right; } } float alpha; if (shadow.blur_radius == 0.) { - float distance = quad_sdf(input.position.xy, shadow.bounds, shadow.corner_radii); + 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 @@ -520,8 +508,8 @@ 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.element_bounds, - shadow.element_corner_radii); + float element_distance = + quad_sdf(input.position.xy, shadow.bounds, shadow.corner_radii); alpha *= saturate(0.5 - element_distance); } diff --git a/crates/gpui_platform/benches/primitives.rs b/crates/gpui_platform/benches/primitives.rs index 1f1e129210c..960f40d638c 100644 --- a/crates/gpui_platform/benches/primitives.rs +++ b/crates/gpui_platform/benches/primitives.rs @@ -314,13 +314,13 @@ fn build_scene(scene: &mut Scene, rectangles: &[Rectangle]) { Kind::Shadow => scene.insert_primitive(gpui::Shadow { order: 0, blur_radius: gpui::ScaledPixels(6.), - bounds, - corner_radii: Corners::all(gpui::ScaledPixels(4.)), + bounds: bounds.dilate(gpui::ScaledPixels(18.)), + corner_radii: Corners::default(), content_mask, color: rectangle.color, - element_bounds: bounds, - element_corner_radii: Corners::all(gpui::ScaledPixels(4.)), - inset: 0, + shape_bounds: bounds, + shape_corner_radii: Corners::all(gpui::ScaledPixels(4.)), + inset: false.into(), pad: 0, }), Kind::Underline => scene.insert_primitive(gpui::Underline { diff --git a/crates/gpui_wgpu/src/shaders.wgsl b/crates/gpui_wgpu/src/shaders.wgsl index f62cf8240eb..06213ff35a7 100644 --- a/crates/gpui_wgpu/src/shaders.wgsl +++ b/crates/gpui_wgpu/src/shaders.wgsl @@ -968,15 +968,16 @@ fn fmod(a: f32, b: f32) -> f32 { struct Shadow { order: u32, blur_radius: f32, - // The shadow rect for drop shadows; the "hole" rect for inset shadows. + // The area the shadow paints: the blurred extent of a drop shadow, or the element + // that an inset shadow is clipped to. bounds: Bounds, corner_radii: Corners, content_mask: Bounds, color: Hsla, - // Only consulted when `inset == 1u`: the element's own bounds, used as a rounded-rect - // clip so the shadow never escapes the element. - element_bounds: Bounds, - element_corner_radii: Corners, + // The shape that is blurred: the silhouette of a drop shadow, or the hole of an + // inset shadow. + shape_bounds: Bounds, + shape_corner_radii: Corners, // 0 = drop shadow, 1 = inset shadow. inset: u32, pad: u32, // align to 8 bytes @@ -993,19 +994,8 @@ fn vs_shadow(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) ins let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); var shadow = load_shadow(instance_id); - var geometry: Bounds; - if (shadow.inset != 0u) { - geometry = shadow.element_bounds; - } else { - // Leave room for the gaussian tail outside the shadow rect. - let margin = 3.0 * shadow.blur_radius; - geometry = shadow.bounds; - geometry.origin -= vec2(margin); - geometry.size += 2.0 * vec2(margin); - } - var out = ShadowVarying(); - let clipped = clip_to_mask(unit_vertex, geometry, shadow.content_mask); + let clipped = clip_to_mask(unit_vertex, shadow.bounds, shadow.content_mask); out.position = to_device_position_impl(clipped.position); out.color = hsla_to_rgba(shadow.color); out.shadow_id = instance_id; @@ -1015,15 +1005,15 @@ fn vs_shadow(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) ins @fragment fn fs_shadow(input: ShadowVarying) -> @location(0) vec4 { let shadow = load_shadow(input.shadow_id); - let half_size = shadow.bounds.size / 2.0; - let center = shadow.bounds.origin + half_size; + 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.corner_radii); + 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.bounds, shadow.corner_radii); + 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 @@ -1048,8 +1038,7 @@ fn fs_shadow(input: ShadowVarying) -> @location(0) vec4 { // 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; - let element_distance = quad_sdf(input.position.xy, shadow.element_bounds, - shadow.element_corner_radii); + let element_distance = quad_sdf(input.position.xy, shadow.bounds, shadow.corner_radii); alpha *= saturate(0.5 - element_distance); } diff --git a/crates/gpui_windows/src/shaders.hlsl b/crates/gpui_windows/src/shaders.hlsl index 90136902c55..47506c1a895 100644 --- a/crates/gpui_windows/src/shaders.hlsl +++ b/crates/gpui_windows/src/shaders.hlsl @@ -851,8 +851,8 @@ struct Shadow { Corners corner_radii; Bounds content_mask; Hsla color; - Bounds element_bounds; - Corners element_corner_radii; + Bounds shape_bounds; + Corners shape_corner_radii; uint inset; uint pad; // align to 8 bytes }; @@ -870,18 +870,7 @@ ShadowFragmentInput shadow_vertex(uint vertex_id: SV_VertexID, uint instance_id: uint shadow_id = batch_start_index + instance_id; Shadow shadow = shadows[shadow_id]; - Bounds bounds; - if (shadow.inset != 0u) { - bounds = shadow.element_bounds; - } else { - // Leave room for the gaussian tail outside the shadow rect. - float margin = 3.0 * shadow.blur_radius; - bounds = shadow.bounds; - bounds.origin -= margin; - bounds.size += 2.0 * margin; - } - - ClippedVertex vertex = clip_to_mask(unit_vertex, bounds, shadow.content_mask); + ClippedVertex vertex = clip_to_mask(unit_vertex, shadow.bounds, shadow.content_mask); float4 device_position = to_device_position_impl(vertex.position); float4 color = hsla_to_rgba(shadow.color); @@ -896,14 +885,14 @@ 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.bounds.size / 2.; - float2 center = shadow.bounds.origin + half_size; + 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.corner_radii); + 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.bounds, shadow.corner_radii); + 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 @@ -928,8 +917,7 @@ 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.element_bounds, - shadow.element_corner_radii); + float element_distance = quad_sdf(input.position.xy, shadow.bounds, shadow.corner_radii); alpha *= saturate(0.5 - element_distance); } diff --git a/crates/markdown/src/markdown.rs b/crates/markdown/src/markdown.rs index 7335744ddbd..466d5dab2c3 100644 --- a/crates/markdown/src/markdown.rs +++ b/crates/markdown/src/markdown.rs @@ -8189,37 +8189,43 @@ mod tests { }); cx.run_until_parked(); cx.update(|window, cx| { + // Quads are drawn in this order: by draw order, then in paint + // order. At an equal draw order, quads are drawn before underlines. let quads = window.painted_quads(); let selection_bounds = quads .iter() .find(|quad| quad.background == Background::from(gpui::red())) .expect("selection is painted") .bounds; - let order_for_color = |color| { - let orders = quads + // A quad can be painted as several pieces. + let positions_for_color = |color| { + let positions = quads .iter() - .filter(|quad| { + .enumerate() + .filter(|(_, quad)| { quad.background == Background::from(color) && quad.bounds.intersects(&selection_bounds) }) - .map(|quad| quad.order) + .map(|(position, _)| position) .collect::>(); - assert_eq!(orders.len(), 1); - orders[0] + let first = *positions.first().expect("quad is painted"); + let last = *positions.last().expect("quad is painted"); + first..=last }; - let chip_order = order_for_color(gpui::green()); - let search_order = order_for_color(cx.theme().colors().search_match_background); - let selection_order = order_for_color(gpui::red()); + let chip = positions_for_color(gpui::green()); + let search = positions_for_color(cx.theme().colors().search_match_background); + let selection = positions_for_color(gpui::red()); + let selection_order = quads[*selection.end()].order; let text_order = window .painted_underlines() .iter() .map(|underline| underline.order) .min() .expect("strikethrough is painted"); - assert!(chip_order < search_order); - assert!(search_order < selection_order); + assert!(chip.end() < search.start()); + assert!(search.end() < selection.start()); assert!( - selection_order < text_order, + selection_order <= text_order, "alignment={alignment}, text={text}, selection={selection_order}, glyphs={text_order}", ); }); @@ -8259,17 +8265,22 @@ mod tests { let highlight_color = cx.update(|_, cx| cx.theme().colors().search_match_background); cx.update(|window, _| { + // Quads are drawn in this order: by draw order, then in paint order. + // At an equal draw order, quads are drawn before underlines. let quads = window.painted_quads(); - let order_of_quad_with = |color: Hsla| { - quads - .iter() - .find(|quad| quad.background == color.into()) - .map(|quad| quad.order) - }; - let run_background_order = - order_of_quad_with(run_background_color).expect("link background should be painted"); - let highlight_order = - order_of_quad_with(highlight_color).expect("search highlight should be painted"); + let has_color = |color: Hsla| move |quad: &gpui::Quad| quad.background == color.into(); + let last_run_background = quads + .iter() + .rposition(has_color(run_background_color)) + .expect("link background should be painted"); + let first_highlight = quads + .iter() + .position(has_color(highlight_color)) + .expect("search highlight should be painted"); + let last_highlight = quads + .iter() + .rposition(has_color(highlight_color)) + .expect("search highlight should be painted"); // Strikethroughs are painted in the same layer as the glyphs let text_order = window .painted_underlines() @@ -8278,11 +8289,11 @@ mod tests { .min() .expect("strikethrough should be painted"); assert!( - run_background_order < highlight_order, + last_run_background < first_highlight, "text run backgrounds must not cover search highlights" ); assert!( - highlight_order < text_order, + quads[last_highlight].order <= text_order, "search highlight must be drawn below the text, otherwise opaque theme colors hide it" ); });