Truly independent web browser
LibCompositing: Share a WorldTransforms table in replay and damage
Aliaksandr Kalenik267b3f428b52
diff --git a/Libraries/LibCompositing/Rust/src/display_list/damage.rs b/Libraries/LibCompositing/Rust/src/display_list/damage.rsindex 24b9f43efac..84feb47f00a 100644--- a/Libraries/LibCompositing/Rust/src/display_list/damage.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/damage.rs@@ -5,7 +5,7 @@*/use super::effect_clip_plan::EffectClipPlan;-use super::effect_geometry::{Extent, SpaceMatrices, changed_extent_through_filters, nearest_spreading_effects};+use super::effect_geometry::{Extent, changed_extent_through_filters, nearest_spreading_effects};use super::replay::{OwnSpaceClipExtent, own_space_clip_extent};use super::summary::{DisplayListSummary, LiveContent};use crate::display_list::builder::{@@ -23,8 +23,7 @@ use crate::fast_hash::FastMap;use crate::host::FfiAnimatedContentViewportEffect;use crate::visual_context::queries::TreeCullingScratch;use crate::visual_context::{- ClipNodeData, EffectNodeData, IncludeVisualViewportTransform, SpatialData, VisualContextTree,- device_offset_for_index,+ ClipNodeData, EffectNodeData, ScrollSnap, SpatialData, VisualContextTree, WorldTransforms, device_offset_for_index,};use libgfx_rust::{AffineTransform, FloatMatrix4x4, FloatPoint, FloatRect, IntRect, enclosing_int_rect};use std::cell::{Cell, OnceCell, RefCell};@@ -471,29 +470,11 @@ struct ContextPairVerdict {equal: bool,}-// How one tree's filters spread the commands drawn under them, worked out on first use.+// Where one tree draws its commands and how its filters spread them, worked out on first use.#[derive(Default)]-struct FilterSpreading {+struct LazySideGeometry {nearest_spreading_effects: OnceCell<Vec<EffectNodeIndex>>,- to_root_matrices: RefCell<Vec<Option<FloatMatrix4x4>>>,-}--struct TreeSpaces<'a> {- tree: &'a VisualContextTree,- scroll_offsets: &'a [FloatPoint],- to_root_matrices: &'a mut Vec<Option<FloatMatrix4x4>>,-}--impl SpaceMatrices for TreeSpaces<'_> {- fn to_root_matrix(&mut self, space: SpatialNodeIndex) -> FloatMatrix4x4 {- if self.to_root_matrices.is_empty() {- self.to_root_matrices.resize(self.tree.spatial_nodes.len(), None);- }- *self.to_root_matrices[space.0 as usize].get_or_insert_with(|| {- self.tree- .accumulated_matrix(space, self.scroll_offsets, IncludeVisualViewportTransform::Yes)- })- }+ world_transforms: OnceCell<WorldTransforms>,}// Where a command's inline clips in spaces of their own let it draw on one side of the comparison.@@ -504,22 +485,13 @@ fn own_space_clip_extent_on(command: &CommandReference<'_>, side: TreeSide<'_>){return None;}- let mut to_root_matrices = side.filter_spreading.to_root_matrices.borrow_mut();- let mut spaces = TreeSpaces {- tree: side.tree,- scroll_offsets: side.scroll_offsets,- to_root_matrices: &mut to_root_matrices,- };- let mut to_root = |space: SpatialNodeIndex| {- ((space.0 as usize) < side.tree.spatial_nodes.len()).then(|| spaces.to_root_matrix(space))- };- let command_to_root = to_root(command.context.spatial)?;+ let world = side.world();own_space_clip_extent(&command.header,command.payload,command.header.bounding_rect.to_float(),- command_to_root,- to_root,+ world.draw_matrix_if_known(command.context.spatial)?,+ |space| world.draw_matrix_if_known(space),)}@@ -530,7 +502,21 @@ struct TreeSide<'b> {scroll_offsets: &'b [FloatPoint],culling: &'b TreeCullingScratch,effect_clips: &'b EffectClipPlan,- filter_spreading: &'b FilterSpreading,+ lazy_geometry: &'b LazySideGeometry,+}++impl<'b> TreeSide<'b> {+ // Damage maps commands with the matrices replay draws them with.+ fn world(&self) -> &'b WorldTransforms {+ self.lazy_geometry.world_transforms.get_or_init(|| {+ WorldTransforms::new(+ self.tree,+ self.scroll_offsets,+ FloatMatrix4x4::identity(),+ ScrollSnap::Truncate,+ )+ })+ }}struct TreeChainComparison<'a> {@@ -555,8 +541,8 @@ struct TreeChainComparison<'a> {effect_chain_memo: RefCell<Vec<ChainMemoEntry>>,chain_walk_path: RefCell<Vec<(u32, u32)>>,mask_comparisons: RefCell<FastMap<(u32, u32), bool>>,- old_filter_spreading: FilterSpreading,- new_filter_spreading: FilterSpreading,+ old_lazy_geometry: LazySideGeometry,+ new_lazy_geometry: LazySideGeometry,}impl<'a> TreeChainComparison<'a> {@@ -566,7 +552,7 @@ impl<'a> TreeChainComparison<'a> {scroll_offsets: self.old_scroll_offsets,culling: &self.old_culling,effect_clips: &self.old_effect_clips,- filter_spreading: &self.old_filter_spreading,+ lazy_geometry: &self.old_lazy_geometry,}}@@ -576,7 +562,7 @@ impl<'a> TreeChainComparison<'a> {scroll_offsets: self.new_scroll_offsets,culling: &self.new_culling,effect_clips: &self.new_effect_clips,- filter_spreading: &self.new_filter_spreading,+ lazy_geometry: &self.new_lazy_geometry,}}@@ -793,12 +779,8 @@ impl<'a> TreeChainComparison<'a> {// The viewport bounds that the clips outside every filter on a context's effect chain put on the// filtered output, or None when no rect clip bounds it. Replay can widen an effect's output clip// for escaping descendants, so the complete display list's layer plan says which clips are outside.-fn filter_output_clip_bounds(- context: ContextRef,- tree: &VisualContextTree,- effect_clips: &EffectClipPlan,- scroll_offsets: &[FloatPoint],-) -> Option<FloatRect> {+fn filter_output_clip_bounds(context: ContextRef, side: TreeSide<'_>) -> Option<FloatRect> {+ let (tree, effect_clips) = (side.tree, side.effect_clips);let mut clip = context.clip;let mut effect = context.effect;while !effect.is_none() {@@ -816,13 +798,9 @@ fn filter_output_clip_bounds(if let ClipNodeData::Rect(data) = &node.data&& data.mode == ClipMode::Intersect{- let bounds = tree- .transform_rect_to_viewport(- node.spatial,- data.rect,- scroll_offsets,- IncludeVisualViewportTransform::Yes,- )+ let bounds = side+ .world()+ .map_rect_to_root(node.spatial, data.rect).inflated(1.0, 1.0);if bounds.x.is_finite() && bounds.y.is_finite() && bounds.width.is_finite() && bounds.height.is_finite() {output_bounds = Some(output_bounds.map_or(bounds, |output_bounds| output_bounds.intersected(bounds)));@@ -883,7 +861,7 @@ impl DamageAccumulator {// it spread the change.fn add_changed_content_damage(&mut self, rect: FloatRect, context: ContextRef, side: TreeSide<'_>) {let nearest_spreading_effects = side- .filter_spreading+ .lazy_geometry.nearest_spreading_effects.get_or_init(|| nearest_spreading_effects(side.tree));let spread_by_filters =@@ -894,26 +872,17 @@ impl DamageAccumulator {context.spatial,rect,context.effect,- &mut TreeSpaces {- tree: side.tree,- scroll_offsets: side.scroll_offsets,- to_root_matrices: &mut side.filter_spreading.to_root_matrices.borrow_mut(),- },+ side.world(),);// Spread content can reach far past the clips it was drawn in, but not past those outside// the filters.let output_clip_bounds = if spread_by_filters {- filter_output_clip_bounds(context, side.tree, side.effect_clips, side.scroll_offsets)+ filter_output_clip_bounds(context, side)} else {None};let mut transformed_rect = match (extent, output_clip_bounds) {- (Extent::Within(rect), _) => side.tree.transform_rect_to_viewport(- space,- rect,- side.scroll_offsets,- IncludeVisualViewportTransform::Yes,- ),+ (Extent::Within(rect), _) => side.world().map_rect_to_root(space, rect),(_, Some(output_clip_bounds)) => output_clip_bounds,_ => {self.changed_unbounded_command = true;@@ -1006,12 +975,7 @@ impl DamageAccumulator {let node = &tree.effect_nodes[effect.0 as usize];let backdrop = backdrop_of(effect).expect("only effects with a backdrop filter are collected");let region = backdrop.region.to_float();- let to_root_matrix = TreeSpaces {- tree,- scroll_offsets: side.scroll_offsets,- to_root_matrices: &mut side.filter_spreading.to_root_matrices.borrow_mut(),- }- .to_root_matrix(node.spatial);+ let to_root_matrix = side.world().draw_matrix(node.spatial);let reads_damage = (|| {if !to_root_matrix.is_2d_affine() {return None;@@ -1365,6 +1329,7 @@ pub fn animated_content_may_affect_viewport(};*flag = true;}+ let world = OnceCell::new();let mut may_affect_viewport = false;let tape = Tape {bytes: command_bytes,@@ -1426,13 +1391,14 @@ pub fn animated_content_may_affect_viewport(}let mut rect = header.bounding_rect.to_float();if has_inline_clip_in_its_own_space && header.has_bounding_rect {- let to_root = |space: SpatialNodeIndex| {- ((space.0 as usize) < tree.spatial_nodes.len())- .then(|| tree.accumulated_matrix(space, scroll_offsets, IncludeVisualViewportTransform::Yes))- };- if let Some(command_to_root) = to_root(run.context.spatial)+ let world = world.get_or_init(|| {+ WorldTransforms::new(tree, scroll_offsets, FloatMatrix4x4::identity(), ScrollSnap::Truncate)+ });+ if let Some(command_to_root) = world.draw_matrix_if_known(run.context.spatial)&& let Some(OwnSpaceClipExtent::Within(clipped_rect)) =- own_space_clip_extent(header, payload, rect, command_to_root, to_root)+ own_space_clip_extent(header, payload, rect, command_to_root, |space| {+ world.draw_matrix_if_known(space)+ }){if clipped_rect.is_empty() {return;@@ -1551,8 +1517,8 @@ pub fn compute_display_list_damage(]),chain_walk_path: RefCell::new(Vec::new()),mask_comparisons: RefCell::new(FastMap::default()),- old_filter_spreading: FilterSpreading::default(),- new_filter_spreading: FilterSpreading::default(),+ old_lazy_geometry: LazySideGeometry::default(),+ new_lazy_geometry: LazySideGeometry::default(),};let scroll_offsets_differ = old_scroll_offsets != new_scroll_offsets;// NB: An inline clip in a space of its own names its space by index, which a new tree can give to another node,@@ -2272,6 +2238,47 @@ mod tests {);}+ #[test]+ fn content_under_nested_fractional_scrolls_is_damaged_where_replay_draws_it() {+ let mut tree = identity_tree();+ let mut scroll_node = VISUAL_VIEWPORT_NODE_INDEX;+ for _ in 0..3 {+ scroll_node = tree.append_spatial(+ SpatialData::Scroll(ScrollData {+ state_slot: NO_SCROLL_STATE_SLOT,+ owner_paintable: NodeSlotId::INVALID,+ }),+ scroll_node,+ );+ }+ let mut scroll_offsets = vec![FloatPoint { x: 0.0, y: -0.9 }; 4];+ scroll_offsets[0] = FloatPoint::default();+ let rect = IntRect::new(10, 10, 20, 20);+ let new_commands = command_bytes(+ &FillRect {+ rect,+ color: RED,+ compositing_and_blending_operator: CompositingAndBlendingOperator::Normal,+ background_color_animation_effect: EffectNodeIndex::NONE,+ },+ Some(rect),+ context_in(scroll_node, ContextRef::default()),+ );+ // Replay truncates each of the three offsets to zero, so the rect is drawn where it was recorded.+ assert_eq!(+ damage_with_scroll_offsets(+ &TestDisplayList::default(),+ &tree,+ &scroll_offsets,+ &new_commands,+ &tree,+ &scroll_offsets,+ IntRect::new(0, 0, 100, 100),+ ),+ Some(IntRect::new(9, 9, 22, 22))+ );+ }+#[test]fn identical_display_lists_have_no_damage() {let tree = identity_tree();diff --git a/Libraries/LibCompositing/Rust/src/display_list/effect_geometry.rs b/Libraries/LibCompositing/Rust/src/display_list/effect_geometry.rsindex 0592ba79534..f100d71a53d 100644--- a/Libraries/LibCompositing/Rust/src/display_list/effect_geometry.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/effect_geometry.rs@@ -13,8 +13,8 @@use crate::display_list::commands::{DisplayListCommandRun, EffectNodeIndex, SpatialNodeIndex};use crate::filter_bytes;-use crate::visual_context::{EffectNode, EffectNodeData, VisualContextTree};-use libgfx_rust::{FloatMatrix4x4, FloatRect, multiply_affine};+use crate::visual_context::{EffectNode, EffectNodeData, VisualContextTree, WorldTransforms};+use libgfx_rust::FloatRect;#[derive(Clone, Copy, Debug, PartialEq)]pub enum Extent {@@ -34,44 +34,16 @@ impl Extent {}}- fn mapped_between_spaces(- self,- spaces: &mut impl SpaceMatrices,- from: SpatialNodeIndex,- to: SpatialNodeIndex,- ) -> Self {+ fn mapped_between_spaces(self, world: &WorldTransforms, from: SpatialNodeIndex, to: SpatialNodeIndex) -> Self {match self {- Self::Within(rect) => map_rect_between_spaces(spaces, rect, from, to).map_or(Self::Anywhere, Self::Within),+ Self::Within(rect) => world+ .map_rect_between_spaces(rect, from, to)+ .map_or(Self::Anywhere, Self::Within),extent => extent,}}}-pub trait SpaceMatrices {- /// The matrix that takes coordinates in `space` to the root's.- fn to_root_matrix(&mut self, space: SpatialNodeIndex) -> FloatMatrix4x4;-}--/// Maps `rect` from `from`'s space into `to`'s, or gives `None` when either space is not a-/// two-dimensional transform of the root or `to`'s cannot be inverted.-pub fn map_rect_between_spaces(- spaces: &mut impl SpaceMatrices,- rect: FloatRect,- from: SpatialNodeIndex,- to: SpatialNodeIndex,-) -> Option<FloatRect> {- if from == to {- return Some(rect);- }- let from_matrix = spaces.to_root_matrix(from);- let to_matrix = spaces.to_root_matrix(to);- if !from_matrix.is_2d_affine() || !to_matrix.is_2d_affine() {- return None;- }- let root_to_target = to_matrix.extract_2d_affine().inverse()?;- Some(multiply_affine(root_to_target, from_matrix.extract_2d_affine()).map_rect(rect))-}-/// Where an effect paints what it composites, given that content in the effect's space.pub fn effect_output_extent(node: &EffectNode, content: Extent) -> Extent {let Extent::Within(rect) = content else {@@ -131,7 +103,7 @@ pub fn changed_extent_through_filters(space: SpatialNodeIndex,rect: FloatRect,effect: EffectNodeIndex,- spaces: &mut impl SpaceMatrices,+ world: &WorldTransforms,) -> (SpatialNodeIndex, Extent) {let nearest_at_or_above = |effect: EffectNodeIndex| {if effect.is_none() {@@ -145,7 +117,7 @@ pub fn changed_extent_through_filters(let mut effect = nearest_at_or_above(effect);while !effect.is_none() && extent != Extent::Anywhere {let node = &tree.effect_nodes[effect.0 as usize];- extent = changed_output_extent(node, extent.mapped_between_spaces(spaces, space, node.spatial));+ extent = changed_output_extent(node, extent.mapped_between_spaces(world, space, node.spatial));space = node.spatial;effect = nearest_at_or_above(node.parent);}@@ -164,7 +136,7 @@ pub struct EffectGeometry {pub fn compute_effect_geometry(tree: &VisualContextTree,command_runs: &[DisplayListCommandRun],- spaces: &mut impl SpaceMatrices,+ world: &WorldTransforms,geometry: &mut Vec<EffectGeometry>,) {geometry.clear();@@ -179,9 +151,9 @@ pub fn compute_effect_geometry(// Neighboring runs mostly differ only in their clip, so their ink is united before it is// mapped into the effect's space.let mut pending: Option<(DisplayListCommandRun, FloatRect)> = None;- let mut add_ink = |geometry: &mut Vec<EffectGeometry>, run: &DisplayListCommandRun, ink: FloatRect| {+ let add_ink = |geometry: &mut Vec<EffectGeometry>, run: &DisplayListCommandRun, ink: FloatRect| {let node = &tree.effect_nodes[run.context.effect.0 as usize];- let landed = Extent::Within(ink).mapped_between_spaces(spaces, run.context.spatial, node.spatial);+ let landed = Extent::Within(ink).mapped_between_spaces(world, run.context.spatial, node.spatial);let content = &mut geometry[run.context.effect.0 as usize].content;*content = content.united(landed);};@@ -218,7 +190,7 @@ pub fn compute_effect_geometry(continue;}let parent_spatial = tree.effect_nodes[node.parent.0 as usize].spatial;- let landed = output.mapped_between_spaces(spaces, node.spatial, parent_spatial);+ let landed = output.mapped_between_spaces(world, node.spatial, parent_spatial);let parent_content = &mut geometry[node.parent.0 as usize].content;*parent_content = parent_content.united(landed);}@@ -228,25 +200,14 @@ pub fn compute_effect_geometry(mod tests {use super::*;use crate::display_list::commands::{ClipNodeIndex, ContextRef, EffectNodeIndex, VISUAL_VIEWPORT_NODE_INDEX};- use crate::visual_context::{- EffectsData, IncludeVisualViewportTransform, SpatialData, TransformData, TransformDataRole,- };+ use crate::visual_context::{EffectsData, ScrollSnap, SpatialData, TransformData, TransformDataRole};use libgfx_rust::filter::Filter;use libgfx_rust::{- Color, ColorFilterType, CompositingAndBlendingOperator, FloatPoint, IntRect, rotation_matrix, scale_matrix,- translation_matrix,+ Color, ColorFilterType, CompositingAndBlendingOperator, FloatMatrix4x4, FloatPoint, IntRect, rotation_matrix,+ scale_matrix, translation_matrix,};use std::sync::Arc;- struct TreeSpaces<'a>(&'a VisualContextTree);-- impl SpaceMatrices for TreeSpaces<'_> {- fn to_root_matrix(&mut self, space: SpatialNodeIndex) -> FloatMatrix4x4 {- self.0- .accumulated_matrix(space, &[], IncludeVisualViewportTransform::Yes)- }- }-fn transform(matrix: FloatMatrix4x4) -> TransformData {TransformData {matrix,@@ -300,7 +261,8 @@ mod tests {fn geometry_of(tree: &VisualContextTree, runs: &[DisplayListCommandRun]) -> Vec<EffectGeometry> {let mut geometry = Vec::new();- compute_effect_geometry(tree, runs, &mut TreeSpaces(tree), &mut geometry);+ let world = WorldTransforms::new(tree, &[], FloatMatrix4x4::identity(), ScrollSnap::None);+ compute_effect_geometry(tree, runs, &world, &mut geometry);geometry}@@ -414,12 +376,13 @@ mod tests {assert_eq!(nearest[opacity.0 as usize], blur);assert_eq!(nearest[plain.0 as usize], EffectNodeIndex::NONE);let content = FloatRect::new(10.0, 20.0, 30.0, 40.0);+ let world = WorldTransforms::new(&tree, &[], FloatMatrix4x4::identity(), ScrollSnap::None);assert_eq!(- changed_extent_through_filters(&tree, &nearest, scaled, content, shadow, &mut TreeSpaces(&tree)),+ changed_extent_through_filters(&tree, &nearest, scaled, content, shadow, &world),(VISUAL_VIEWPORT_NODE_INDEX, within(-10.0, 10.0, 120.0, 160.0)));assert_eq!(- changed_extent_through_filters(&tree, &nearest, scaled, content, plain, &mut TreeSpaces(&tree)),+ changed_extent_through_filters(&tree, &nearest, scaled, content, plain, &world),(scaled, Extent::Within(content)));}diff --git a/Libraries/LibCompositing/Rust/src/display_list/replay.rs b/Libraries/LibCompositing/Rust/src/display_list/replay.rsindex 2812b4068f0..69e77e9b22f 100644--- a/Libraries/LibCompositing/Rust/src/display_list/replay.rs+++ b/Libraries/LibCompositing/Rust/src/display_list/replay.rs@@ -13,15 +13,13 @@ use crate::display_list::commands::{};use crate::display_list::depth_sorted_plan::{DepthSortedReplayStepKind, build_depth_sorted_replay_plan};use crate::display_list::effect_clip_plan::EffectClipPlan;-use crate::display_list::effect_geometry::{- EffectGeometry, Extent, SpaceMatrices, compute_effect_geometry, map_rect_between_spaces,-};+use crate::display_list::effect_geometry::{EffectGeometry, Extent, compute_effect_geometry};use crate::display_list::ffi_bytes::FfiBytes;use crate::display_list::nested_records::span_bytes;use crate::visual_context::queries::TreeCullingScratch;use crate::visual_context::{- ClipNodeData, ContextRef, EffectNodeData, ScrollSnap, SpatialData, VisualContextTree, device_offset_for_index,- resolve_leaf_to_context_matrices, should_cull_back_face,+ ClipNodeData, ContextRef, EffectNodeData, ScrollSnap, SpatialData, VisualContextTree, WorldTransforms,+ device_offset_for_index, resolve_leaf_to_context_matrices,};use libgfx_rust::filter::Filter;use libgfx_rust::path::Path;@@ -192,27 +190,6 @@ pub fn replay_records<Painter: ReplayPainter + ?Sized>(});}-// Cumulative to-root matrices for every spatial node, resolved against the live scroll offsets-// and folded onto the canvas matrix at replay entry, so any node's space can be entered-// absolutely with a single set_matrix(). Spatial nodes therefore never touch the canvas save-// stack; only clips and effects do. A backface marker's entry carries the flattened matrix that-// feeds its cull test and its descendants, while content recorded directly under the marker-// belongs to its parent's plane, so draw_space redirects the marker to the parent's entry.-#[derive(Default)]-struct ReplayPaletteStorage {- to_root_matrices: Vec<FloatMatrix4x4>,- local_matrices: Vec<FloatMatrix4x4>,- draw_spaces: Vec<SpatialNodeIndex>,- backface_culled: Vec<bool>,- flattens_inherited_transform: Vec<bool>,-}--impl SpaceMatrices for &ReplayPaletteStorage {- fn to_root_matrix(&mut self, space: SpatialNodeIndex) -> FloatMatrix4x4 {- self.to_root_matrices[self.draw_spaces[space.0 as usize].0 as usize]- }-}-// Recorded bounds are whole device pixels around geometry that antialiasing and glyph rounding// can push past them by up to this much, and a layer's bounds clip what is drawn into it.const LAYER_CONTENT_MARGIN_IN_DEVICE_PIXELS: f32 = 2.0;@@ -226,10 +203,10 @@ enum Applied {// Steady-state replays reuse the previous frame's capacity. Taking the storage out of the slot// for the duration of a replay keeps re-entrant nested replays from clobbering the outer-// driver's buffers; the slot keeps whichever returned storage has the larger palette.+// driver's buffers; the slot keeps whichever returned storage has the larger table.#[derive(Default)]struct ReplayScratchStorage {- palette: ReplayPaletteStorage,+ world: WorldTransforms,culling: TreeCullingScratch,applied: Vec<Applied>,target: Vec<Applied>,@@ -245,21 +222,17 @@ fn take_replay_scratch_storage() -> ReplayScratchStorage {}fn return_replay_scratch_storage(mut storage: ReplayScratchStorage) {- storage.palette.to_root_matrices.clear();- storage.palette.local_matrices.clear();- storage.palette.draw_spaces.clear();- storage.palette.backface_culled.clear();- storage.palette.flattens_inherited_transform.clear();+ storage.world.clear();storage.culling.clear();storage.applied.clear();storage.target.clear();storage.effect_geometry.clear();WARM_REPLAY_SCRATCH_STORAGE.with(|slot| {let mut slot = slot.borrow_mut();- let slot_has_larger_palette = slot.as_ref().is_some_and(|kept| {- kept.palette.to_root_matrices.capacity() >= storage.palette.to_root_matrices.capacity()- });- if !slot_has_larger_palette {+ let slot_has_larger_table = slot+ .as_ref()+ .is_some_and(|kept| kept.world.to_root.capacity() >= storage.world.to_root.capacity());+ if !slot_has_larger_table {*slot = Some(storage);}});@@ -279,12 +252,14 @@ struct ReplayDriver<'a, Painter: ReplayPainter> {effect_clips: &'a EffectClipPlan,root_group_color: Color,painter: &'a mut Painter,- palette: ReplayPaletteStorage,+ // Spatial nodes never touch the canvas save stack: any node's space is entered absolutely with a single+ // set_matrix(), so only clips and effects do.+ world: WorldTransforms,culling: TreeCullingScratch,spatial_dependency_order: Vec<u32>,tree_has_sorting_contexts: bool,replay_base_matrix: FloatMatrix4x4,- // The palette entry the canvas matrix currently equals, if known; popping a clip or a layer+ // The draw space the canvas matrix currently equals, if known; popping a clip or a layer// resets the matrix to its save point, so unwinding invalidates it. Recorded streams contain// no matrix-mutating commands, so playing commands never invalidates the cache.current_ctm_space: Option<SpatialNodeIndex>,@@ -372,112 +347,19 @@ fn int_rect_enclosing(rect: FloatRect) -> Option<IntRect> {.then(|| enclosing_int_rect(rect))}-// The cull state of the element that establishes the 3D rendering context rooted at root: the cull state of the-// plane the context is flattened into.-fn backface_culled_outside_sorting_context(- tree: &VisualContextTree,- backface_culled: &[bool],- root: SpatialNodeIndex,-) -> bool {- let mut index = root;- loop {- if tree- .local_transform(index, &[], ScrollSnap::None)- .establishes_sorting_context- {- return backface_culled[index.0 as usize];- }- if index.0 == 0 {- return false;- }- index = tree.spatial_nodes[index.0 as usize].parent;- }-}--fn fill_replay_palette_in_dependency_order(- tree: &VisualContextTree,- spatial_dependency_order: &[u32],- scroll_offsets: &[FloatPoint],- replay_base_matrix: FloatMatrix4x4,- palette: &mut ReplayPaletteStorage,-) {- let node_count = tree.spatial_nodes.len();- palette.to_root_matrices.clear();- palette.to_root_matrices.resize(node_count, replay_base_matrix);- palette.local_matrices.clear();- palette.local_matrices.resize(node_count, FloatMatrix4x4::identity());- palette.draw_spaces.clear();- palette- .draw_spaces- .extend((0..node_count).map(|index| SpatialNodeIndex(index as u32)));- palette.backface_culled.clear();- palette.backface_culled.resize(node_count, false);- palette.flattens_inherited_transform.clear();- palette.flattens_inherited_transform.resize(node_count, false);- for &index in spatial_dependency_order {- let i = index as usize;- let parent = tree.spatial_nodes[i].parent.0 as usize;- // Whole device pixels, so scrolled content never lands on subpixel positions.- let local = tree.local_transform(SpatialNodeIndex(index), scroll_offsets, ScrollSnap::Truncate);- let parent_matrix = if i == 0 {- replay_base_matrix- } else {- palette.to_root_matrices[parent]- };- palette.to_root_matrices[i] = local.applied_to(parent_matrix);- palette.local_matrices[i] = local.matrix;- palette.flattens_inherited_transform[i] = local.flattens_inherited_transform;- let mut culled = i != 0 && palette.backface_culled[parent];- // https://drafts.csswg.org/css-transforms-2/#3d-rendering-contexts- // A participant in a 3D rendering context is its own plane, so the hidden backfaces of other planes in the- // context don't cull it. But a context is part of the content flattened into the plane its establishing- // element sits in, so whatever culls that plane culls the whole context: A participant starts from the cull- // state of the element that establishes its context. The spec doesn't yet say if a hidden backface culls the- // 3D rendering contexts nested in it:- // https://github.com/w3c/csswg-drafts/issues/918- if let Some(root) = local.sorting_context_root {- culled = backface_culled_outside_sorting_context(tree, &palette.backface_culled, root);- }- if let Some(plane_root) = local.backface_plane_root {- palette.draw_spaces[i] = palette.draw_spaces[parent];- if !culled {- let plane_root_matrix = palette.to_root_matrices[plane_root.0 as usize];- culled = should_cull_back_face(palette.to_root_matrices[i], plane_root_matrix);- }- }- palette.backface_culled[i] = culled;- }-}-impl<Painter: ReplayPainter> ReplayDriver<'_, Painter> {- fn build_transform_palette(&mut self, scroll_offsets: &[FloatPoint]) {- fill_replay_palette_in_dependency_order(- self.tree,- &self.spatial_dependency_order,- scroll_offsets,- self.replay_base_matrix,- &mut self.palette,- );- }-fn ensure_ctm_space(&mut self, spatial: SpatialNodeIndex) {- let space = self.palette.draw_spaces[spatial.0 as usize];+ let space = self.world.draw_space[spatial.0 as usize];if self.current_ctm_space == Some(space) {return;}- self.painter- .set_matrix(&self.palette.to_root_matrices[space.0 as usize]);+ self.painter.set_matrix(&self.world.to_root[space.0 as usize]);self.current_ctm_space = Some(space);}fn effect_geometry(&mut self, effect: EffectNodeIndex) -> EffectGeometry {if !self.effect_geometry_is_known {- compute_effect_geometry(- self.tree,- self.command_runs,- &mut &self.palette,- &mut self.effect_geometry,- );+ compute_effect_geometry(self.tree, self.command_runs, &self.world, &mut self.effect_geometry);self.effect_geometry_is_known = true;}self.effect_geometry[effect.0 as usize]@@ -488,7 +370,7 @@ impl<Painter: ReplayPainter> ReplayDriver<'_, Painter> {let Extent::Within(content) = self.effect_geometry(effect).content else {return None;};- let to_root_matrix = (&self.palette).to_root_matrix(space);+ let to_root_matrix = self.world.draw_matrix(space);if !to_root_matrix.is_2d_affine() {return None;}@@ -574,9 +456,10 @@ impl<Painter: ReplayPainter> ReplayDriver<'_, Painter> {ClipNodeData::Path(path) => Some(path.bounding_rect.to_float()),_ => None,};- if let Some(clip_rect) = clip_rect- .and_then(|rect| map_rect_between_spaces(&mut &self.palette, rect, clip_node.spatial, node.spatial))- {+ if let Some(clip_rect) = clip_rect.and_then(|rect| {+ self.world+ .map_rect_between_spaces(rect, clip_node.spatial, node.spatial)+ }) {edge = edge.intersected(clip_rect);}clip = clip_node.parent;@@ -798,7 +681,7 @@ impl<Painter: ReplayPainter> ReplayDriver<'_, Painter> {// context spares the pushes.fn execute_run(&mut self, run_index: usize) {let run = self.command_runs[run_index];- if self.palette.backface_culled[run.context.spatial.0 as usize] {+ if self.world.backface_culled[run.context.spatial.0 as usize] {return;}if self.culling.context_culls_everything(run.context) {@@ -815,11 +698,8 @@ impl<Painter: ReplayPainter> ReplayDriver<'_, Painter> {return;}let records = &self.tape[run.offset as usize..(run.offset + run.size) as usize];- let palette = &self.palette;- let clip_space_matrix = |space: SpatialNodeIndex| {- let draw_space = palette.draw_spaces.get(space.0 as usize)?;- palette.to_root_matrices.get(draw_space.0 as usize).copied()- };+ let world = &self.world;+ let clip_space_matrix = |space: SpatialNodeIndex| world.draw_matrix_if_known(space);self.painter.execute_run(run_index, records, self.scroll_offsets, &clip_space_matrix);}@@ -839,16 +719,16 @@ impl<Painter: ReplayPainter> ReplayDriver<'_, Painter> {&contexts,&self.spatial_dependency_order,&parent_by_node,- &self.palette.local_matrices,- &self.palette.flattens_inherited_transform,+ &self.world.local,+ &self.world.flattens_inherited_transform,);let plan = build_depth_sorted_replay_plan(self.command_runs,&contexts,- &self.palette.to_root_matrices,+ &self.world.to_root,&leaf_to_context_palette,- &self.palette.draw_spaces,- &self.palette.backface_culled,+ &self.world.draw_space,+ &self.world.backface_culled,&self.culling,);for step in &plan.steps {@@ -916,7 +796,7 @@ pub fn replay_display_list(effect_clips,root_group_color,painter,- palette: scratch.palette,+ world: scratch.world,culling: scratch.culling,spatial_dependency_order: tree.spatial_dependency_order(),tree_has_sorting_contexts: tree.spatial_nodes.iter().any(|node| {@@ -930,10 +810,17 @@ pub fn replay_display_list(effect_geometry: scratch.effect_geometry,effect_geometry_is_known: false,};- driver.build_transform_palette(scroll_offsets);+ // Whole device pixels, so scrolled content never lands on subpixel positions.+ driver.world.fill(+ tree,+ &driver.spatial_dependency_order,+ scroll_offsets,+ replay_base_matrix,+ ScrollSnap::Truncate,+ );driver.execute();return_replay_scratch_storage(ReplayScratchStorage {- palette: std::mem::take(&mut driver.palette),+ world: std::mem::take(&mut driver.world),culling: std::mem::take(&mut driver.culling),applied: std::mem::take(&mut driver.applied),target: std::mem::take(&mut driver.target),@@ -1007,22 +894,8 @@ mod tests {permuted.spatial_nodes[permuted_child.0 as usize].parent = permuted_parent;let base = scale_matrix(2.0, 2.0, 1.0);- let mut in_order_palette = ReplayPaletteStorage::default();- fill_replay_palette_in_dependency_order(- &in_order,- &in_order.spatial_dependency_order(),- &[],- base,- &mut in_order_palette,- );- let mut permuted_palette = ReplayPaletteStorage::default();- fill_replay_palette_in_dependency_order(- &permuted,- &permuted.spatial_dependency_order(),- &[],- base,- &mut permuted_palette,- );+ let in_order_palette = WorldTransforms::new(&in_order, &[], base, ScrollSnap::Truncate);+ let permuted_palette = WorldTransforms::new(&permuted, &[], base, ScrollSnap::Truncate);let pairs = [(VISUAL_VIEWPORT_NODE_INDEX, VISUAL_VIEWPORT_NODE_INDEX),(parent, permuted_parent),@@ -1033,16 +906,16 @@ mod tests {let map = |index: SpatialNodeIndex| pairs.iter().find(|(original, _)| *original == index).unwrap().1;for (original, mapped) in pairs {assert_eq!(- permuted_palette.to_root_matrices[mapped.0 as usize],- in_order_palette.to_root_matrices[original.0 as usize]+ permuted_palette.to_root[mapped.0 as usize],+ in_order_palette.to_root[original.0 as usize]);assert_eq!(- permuted_palette.local_matrices[mapped.0 as usize],- in_order_palette.local_matrices[original.0 as usize]+ permuted_palette.local[mapped.0 as usize],+ in_order_palette.local[original.0 as usize]);assert_eq!(- permuted_palette.draw_spaces[mapped.0 as usize],- map(in_order_palette.draw_spaces[original.0 as usize])+ permuted_palette.draw_space[mapped.0 as usize],+ map(in_order_palette.draw_space[original.0 as usize]));assert_eq!(permuted_palette.backface_culled[mapped.0 as usize],@@ -1054,7 +927,7 @@ mod tests {);}assert!(in_order_palette.backface_culled[marker.0 as usize]);- assert_eq!(in_order_palette.draw_spaces[marker.0 as usize], plane);+ assert_eq!(in_order_palette.draw_space[marker.0 as usize], plane);}#[derive(Debug, PartialEq)]diff --git a/Libraries/LibCompositing/Rust/src/visual_context/mod.rs b/Libraries/LibCompositing/Rust/src/visual_context/mod.rsindex b6411bde8bf..edd7c2334ec 100644--- a/Libraries/LibCompositing/Rust/src/visual_context/mod.rs+++ b/Libraries/LibCompositing/Rust/src/visual_context/mod.rs@@ -9,6 +9,7 @@ pub mod queries;pub mod scroll_state;pub mod serialize;pub mod visual_animations;+pub mod world_transforms;use std::collections::HashMap;@@ -24,6 +25,7 @@ pub use crate::display_list::commands::{ClipMode, ClipNodeIndex, ContextRef, EffectNodeIndex, SpatialNodeIndex, VISUAL_VIEWPORT_NODE_INDEX,};pub use queries::{ClipBehavior, should_cull_back_face};+pub use world_transforms::WorldTransforms;#[derive(Clone, Copy, Debug, PartialEq, Eq)]#[repr(u8)]diff --git a/Libraries/LibCompositing/Rust/src/visual_context/queries.rs b/Libraries/LibCompositing/Rust/src/visual_context/queries.rsindex f40f938ca23..6ee81b55c1d 100644--- a/Libraries/LibCompositing/Rust/src/visual_context/queries.rs+++ b/Libraries/LibCompositing/Rust/src/visual_context/queries.rs@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+use super::world_transforms::MINIMUM_PROJECTION_W;use super::{ClipData, ClipMode, ClipNode, ClipNodeData, ClipNodeIndex, ContextRef, EffectNodeData, EffectNodeIndex,IncludeVisualViewportTransform, LocalTransform, LocalTransformKind, ScrollSnap, SpatialData, SpatialNodeIndex,@@ -14,9 +15,6 @@ use libgfx_rust::{CompositingAndBlendingOperator, FloatMatrix4x4, FloatPoint, FloatRect, IntPoint, IntRect, map_rect_through_matrix,};-// Homogeneous coordinates this close to the eye plane have no meaningful projection.-const MINIMUM_PROJECTION_W: f32 = 0.0001;-#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum ClipBehavior {Respect,diff --git a/Libraries/LibCompositing/Rust/src/visual_context/world_transforms.rs b/Libraries/LibCompositing/Rust/src/visual_context/world_transforms.rsnew file mode 100644index 00000000000..a3e9d6b5b5e--- /dev/null+++ b/Libraries/LibCompositing/Rust/src/visual_context/world_transforms.rs@@ -0,0 +1,159 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use super::{ScrollSnap, SpatialNodeIndex, VisualContextTree, should_cull_back_face};+use libgfx_rust::{FloatMatrix4x4, FloatPoint, FloatRect, map_rect_through_matrix, multiply_affine};++// Homogeneous coordinates this close to the eye plane have no meaningful projection.+pub const MINIMUM_PROJECTION_W: f32 = 0.0001;++/// The to-root matrix of every spatial node under one set of scroll offsets, filled in dependency order so that any+/// node's space is entered with a single matrix. A backface marker's entry carries the flattened matrix that feeds its+/// cull test and its descendants, while content recorded directly under the marker belongs to its parent's plane, so+/// `draw_space` redirects the marker to the parent's entry.+#[derive(Default)]+pub struct WorldTransforms {+ pub local: Vec<FloatMatrix4x4>,+ pub to_root: Vec<FloatMatrix4x4>,+ pub flattens_inherited_transform: Vec<bool>,+ pub backface_culled: Vec<bool>,+ pub draw_space: Vec<SpatialNodeIndex>,+}++// The cull state of the element that establishes the 3D rendering context rooted at root: the cull state of the+// plane the context is flattened into.+fn backface_culled_outside_sorting_context(+ tree: &VisualContextTree,+ backface_culled: &[bool],+ root: SpatialNodeIndex,+) -> bool {+ let mut index = root;+ loop {+ if tree+ .local_transform(index, &[], ScrollSnap::None)+ .establishes_sorting_context+ {+ return backface_culled[index.0 as usize];+ }+ if index.0 == 0 {+ return false;+ }+ index = tree.spatial_nodes[index.0 as usize].parent;+ }+}++impl WorldTransforms {+ pub fn new(+ tree: &VisualContextTree,+ scroll_offsets: &[FloatPoint],+ root_parent_matrix: FloatMatrix4x4,+ scroll_snap: ScrollSnap,+ ) -> Self {+ let mut world = Self::default();+ world.fill(+ tree,+ &tree.spatial_dependency_order(),+ scroll_offsets,+ root_parent_matrix,+ scroll_snap,+ );+ world+ }++ pub fn clear(&mut self) {+ self.local.clear();+ self.to_root.clear();+ self.flattens_inherited_transform.clear();+ self.backface_culled.clear();+ self.draw_space.clear();+ }++ /// Fills the table, with `root_parent_matrix` as what the visual viewport node's transform applies on top of.+ pub fn fill(+ &mut self,+ tree: &VisualContextTree,+ spatial_dependency_order: &[u32],+ scroll_offsets: &[FloatPoint],+ root_parent_matrix: FloatMatrix4x4,+ scroll_snap: ScrollSnap,+ ) {+ let node_count = tree.spatial_nodes.len();+ self.clear();+ self.local.resize(node_count, FloatMatrix4x4::identity());+ self.to_root.resize(node_count, root_parent_matrix);+ self.flattens_inherited_transform.resize(node_count, false);+ self.backface_culled.resize(node_count, false);+ self.draw_space+ .extend((0..node_count).map(|index| SpatialNodeIndex(index as u32)));+ for &index in spatial_dependency_order {+ let i = index as usize;+ let parent = tree.spatial_nodes[i].parent.0 as usize;+ let local = tree.local_transform(SpatialNodeIndex(index), scroll_offsets, scroll_snap);+ let parent_matrix = if i == 0 {+ root_parent_matrix+ } else {+ self.to_root[parent]+ };+ self.to_root[i] = local.applied_to(parent_matrix);+ self.local[i] = local.matrix;+ self.flattens_inherited_transform[i] = local.flattens_inherited_transform;+ let mut culled = i != 0 && self.backface_culled[parent];+ // https://drafts.csswg.org/css-transforms-2/#3d-rendering-contexts+ // A participant in a 3D rendering context is its own plane, so the hidden backfaces of other planes in the+ // context don't cull it. But a context is part of the content flattened into the plane its establishing+ // element sits in, so whatever culls that plane culls the whole context: A participant starts from the+ // cull state of the element that establishes its context. The spec doesn't yet say if a hidden backface+ // culls the 3D rendering contexts nested in it:+ // https://github.com/w3c/csswg-drafts/issues/918+ if let Some(root) = local.sorting_context_root {+ culled = backface_culled_outside_sorting_context(tree, &self.backface_culled, root);+ }+ if let Some(plane_root) = local.backface_plane_root {+ self.draw_space[i] = self.draw_space[parent];+ culled = culled || should_cull_back_face(self.to_root[i], self.to_root[plane_root.0 as usize]);+ }+ self.backface_culled[i] = culled;+ }+ }++ /// The matrix that content recorded in `space` is drawn with.+ pub fn draw_matrix(&self, space: SpatialNodeIndex) -> FloatMatrix4x4 {+ self.to_root[self.draw_space[space.0 as usize].0 as usize]+ }++ pub fn draw_matrix_if_known(&self, space: SpatialNodeIndex) -> Option<FloatMatrix4x4> {+ ((space.0 as usize) < self.draw_space.len()).then(|| self.draw_matrix(space))+ }++ /// Where content drawn within `rect` in `space` lands in the root's space.+ pub fn map_rect_to_root(&self, space: SpatialNodeIndex, rect: FloatRect) -> FloatRect {+ let matrix = self.draw_matrix(space);+ if matrix.is_2d_affine() {+ return matrix.extract_2d_affine().map_rect(rect);+ }+ map_rect_through_matrix(matrix, rect, MINIMUM_PROJECTION_W)+ }++ /// Maps `rect` from `from`'s space into `to`'s, or gives `None` when either space is not a two-dimensional+ /// transform of the root or `to`'s cannot be inverted.+ pub fn map_rect_between_spaces(+ &self,+ rect: FloatRect,+ from: SpatialNodeIndex,+ to: SpatialNodeIndex,+ ) -> Option<FloatRect> {+ if from == to {+ return Some(rect);+ }+ let from_matrix = self.draw_matrix(from);+ let to_matrix = self.draw_matrix(to);+ if !from_matrix.is_2d_affine() || !to_matrix.is_2d_affine() {+ return None;+ }+ let root_to_target = to_matrix.extract_2d_affine().inverse()?;+ Some(multiply_affine(root_to_target, from_matrix.extract_2d_affine()).map_rect(rect))+ }+}