-
Notifications
You must be signed in to change notification settings - Fork 54
/
scene_building.rs
4223 lines (3798 loc) · 158 KB
/
scene_building.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use api::{AlphaType, BorderDetails, BorderDisplayItem, BuiltDisplayListIter, PrimitiveFlags};
use api::{ClipId, ColorF, CommonItemProperties, ComplexClipRegion, ComponentTransferFuncType, RasterSpace};
use api::{DisplayItem, DisplayItemRef, ExtendMode, ExternalScrollId, FilterData};
use api::{FilterOp, FilterPrimitive, FontInstanceKey, GlyphInstance, GlyphOptions, GradientStop};
use api::{IframeDisplayItem, ImageKey, ImageRendering, ItemRange, ColorDepth, QualitySettings};
use api::{LineOrientation, LineStyle, NinePatchBorderSource, PipelineId, MixBlendMode};
use api::{PropertyBinding, ReferenceFrame, ReferenceFrameKind, ScrollFrameDisplayItem, ScrollSensitivity};
use api::{Shadow, SpaceAndClipInfo, SpatialId, StackingContext, StickyFrameDisplayItem};
use api::{ClipMode, PrimitiveKeyKind, TransformStyle, YuvColorSpace, ColorRange, YuvData, TempFilterData};
use api::units::*;
use crate::clip::{ClipChainId, ClipRegion, ClipItemKey, ClipStore, ClipItemKeyKind};
use crate::clip::{ClipInternData, ClipDataHandle, ClipNodeKind};
use crate::spatial_tree::{ROOT_SPATIAL_NODE_INDEX, SpatialTree, SpatialNodeIndex};
use crate::frame_builder::{ChasePrimitive, FrameBuilderConfig};
use crate::glyph_rasterizer::FontInstance;
use crate::hit_test::{HitTestingItem, HitTestingScene};
use crate::image::simplify_repeated_primitive;
use crate::intern::Interner;
use crate::internal_types::{FastHashMap, FastHashSet, LayoutPrimitiveInfo, Filter};
use crate::picture::{Picture3DContext, PictureCompositeMode, PicturePrimitive, PictureOptions};
use crate::picture::{BlitReason, OrderedPictureChild, PrimitiveList, TileCacheInstance, ClusterFlags};
use crate::prim_store::{PrimitiveInstance, PrimitiveSceneData};
use crate::prim_store::{PrimitiveInstanceKind, NinePatchDescriptor, PrimitiveStore};
use crate::prim_store::{ScrollNodeAndClipChain, PictureIndex};
use crate::prim_store::{InternablePrimitive, SegmentInstanceIndex};
use crate::prim_store::{register_prim_chase_id, get_line_decoration_size};
use crate::prim_store::{SpaceSnapper};
use crate::prim_store::backdrop::Backdrop;
use crate::prim_store::borders::{ImageBorder, NormalBorderPrim};
use crate::prim_store::gradient::{GradientStopKey, LinearGradient, RadialGradient, RadialGradientParams, ConicGradient, ConicGradientParams};
use crate::prim_store::image::{Image, YuvImage};
use crate::prim_store::line_dec::{LineDecoration, LineDecorationCacheKey};
use crate::prim_store::picture::{Picture, PictureCompositeKey, PictureKey};
use crate::prim_store::text_run::TextRun;
use crate::render_backend::{DocumentView};
use crate::resource_cache::{FontInstanceMap, ImageRequest};
use crate::scene::{Scene, BuiltScene, SceneStats, StackingContextHelpers};
use crate::scene_builder_thread::Interners;
use crate::spatial_node::{StickyFrameInfo, ScrollFrameKind};
use euclid::approxeq::ApproxEq;
use std::{f32, mem, usize, ops};
use std::collections::vec_deque::VecDeque;
use std::sync::Arc;
use crate::util::{MaxRect, VecHelper};
use crate::filterdata::{SFilterDataComponent, SFilterData, SFilterDataKey};
#[derive(Debug, Copy, Clone)]
struct ClipNode {
id: ClipChainId,
count: usize,
}
impl ClipNode {
fn new(id: ClipChainId, count: usize) -> Self {
ClipNode {
id,
count,
}
}
}
/// The offset stack for a given reference frame.
struct ReferenceFrameState {
/// A stack of current offsets from the current reference frame scope.
offsets: Vec<LayoutVector2D>,
}
/// Maps from stacking context layout coordinates into reference frame
/// relative coordinates.
struct ReferenceFrameMapper {
/// A stack of reference frame scopes.
frames: Vec<ReferenceFrameState>,
}
impl ReferenceFrameMapper {
fn new() -> Self {
ReferenceFrameMapper {
frames: vec![
ReferenceFrameState {
offsets: vec![
LayoutVector2D::zero(),
],
}
],
}
}
/// Push a new scope. This resets the current offset to zero, and is
/// used when a new reference frame or iframe is pushed.
fn push_scope(&mut self) {
self.frames.push(ReferenceFrameState {
offsets: vec![
LayoutVector2D::zero(),
],
});
}
/// Pop a reference frame scope off the stack.
fn pop_scope(&mut self) {
self.frames.pop().unwrap();
}
/// Push a new offset for the current scope. This is used when
/// a new stacking context is pushed.
fn push_offset(&mut self, offset: LayoutVector2D) {
let frame = self.frames.last_mut().unwrap();
let current_offset = *frame.offsets.last().unwrap();
frame.offsets.push(current_offset + offset);
}
/// Pop a local stacking context offset from the current scope.
fn pop_offset(&mut self) {
let frame = self.frames.last_mut().unwrap();
frame.offsets.pop().unwrap();
}
/// Retrieve the current offset to allow converting a stacking context
/// relative coordinate to be relative to the owing reference frame.
/// TODO(gw): We could perhaps have separate coordinate spaces for this,
/// however that's going to either mean a lot of changes to
/// public API code, or a lot of changes to internal code.
/// Before doing that, we should revisit how Gecko would
/// prefer to provide coordinates.
/// TODO(gw): For now, this includes only the reference frame relative
/// offset. Soon, we will expand this to include the initial
/// scroll offsets that are now available on scroll nodes. This
/// will allow normalizing the coordinates even between display
/// lists where APZ has scrolled the content.
fn current_offset(&self) -> LayoutVector2D {
*self.frames.last().unwrap().offsets.last().unwrap()
}
}
/// Offsets primitives (and clips) by the external scroll offset
/// supplied to scroll nodes.
pub struct ScrollOffsetMapper {
pub current_spatial_node: SpatialNodeIndex,
pub current_offset: LayoutVector2D,
}
impl ScrollOffsetMapper {
fn new() -> Self {
ScrollOffsetMapper {
current_spatial_node: SpatialNodeIndex::INVALID,
current_offset: LayoutVector2D::zero(),
}
}
/// Return the accumulated external scroll offset for a spatial
/// node. This caches the last result, which is the common case,
/// or defers to the spatial tree to build the value.
fn external_scroll_offset(
&mut self,
spatial_node_index: SpatialNodeIndex,
spatial_tree: &SpatialTree,
) -> LayoutVector2D {
if spatial_node_index != self.current_spatial_node {
self.current_spatial_node = spatial_node_index;
self.current_offset = spatial_tree.external_scroll_offset(spatial_node_index);
}
self.current_offset
}
}
/// A data structure that keeps track of mapping between API Ids for clips/spatials and the indices
/// used internally in the SpatialTree to avoid having to do HashMap lookups. NodeIdToIndexMapper
/// is responsible for mapping both ClipId to ClipChainIndex and SpatialId to SpatialNodeIndex.
#[derive(Default)]
pub struct NodeIdToIndexMapper {
clip_node_map: FastHashMap<ClipId, ClipNode>,
spatial_node_map: FastHashMap<SpatialId, SpatialNodeIndex>,
}
impl NodeIdToIndexMapper {
pub fn add_clip_chain(
&mut self,
id: ClipId,
index: ClipChainId,
count: usize,
) {
let _old_value = self.clip_node_map.insert(id, ClipNode::new(index, count));
debug_assert!(_old_value.is_none());
}
pub fn map_spatial_node(&mut self, id: SpatialId, index: SpatialNodeIndex) {
let _old_value = self.spatial_node_map.insert(id, index);
debug_assert!(_old_value.is_none());
}
fn get_clip_node(&self, id: &ClipId) -> ClipNode {
self.clip_node_map[id]
}
pub fn get_clip_chain_id(&self, id: ClipId) -> ClipChainId {
self.clip_node_map[&id].id
}
pub fn get_spatial_node_index(&self, id: SpatialId) -> SpatialNodeIndex {
self.spatial_node_map[&id]
}
}
#[derive(Debug, Clone, Default)]
pub struct CompositeOps {
// Requires only a single texture as input (e.g. most filters)
pub filters: Vec<Filter>,
pub filter_datas: Vec<FilterData>,
pub filter_primitives: Vec<FilterPrimitive>,
// Requires two source textures (e.g. mix-blend-mode)
pub mix_blend_mode: Option<MixBlendMode>,
}
impl CompositeOps {
pub fn new(
filters: Vec<Filter>,
filter_datas: Vec<FilterData>,
filter_primitives: Vec<FilterPrimitive>,
mix_blend_mode: Option<MixBlendMode>
) -> Self {
CompositeOps {
filters,
filter_datas,
filter_primitives,
mix_blend_mode,
}
}
pub fn is_empty(&self) -> bool {
self.filters.is_empty() &&
self.filter_primitives.is_empty() &&
self.mix_blend_mode.is_none()
}
}
/// Information about unpaired Push/Pop clip chain instances that need to be fixed up.
struct ClipChainPairInfo {
spatial_node_index: SpatialNodeIndex,
clip_chain_id: ClipChainId,
}
bitflags! {
/// Slice flags
pub struct SliceFlags : u8 {
/// Slice created by a cluster that has ClusterFlags::SCROLLBAR_CONTAINER
const IS_SCROLLBAR = 1;
}
}
/// Information about a set of primitive clusters that will form a picture cache slice.
struct Slice {
/// The spatial node root of the picture cache. If this is None, the slice
/// will not be cached and instead drawn directly to the parent surface. This
/// is a temporary measure until we enable caching all slices.
cache_scroll_root: Option<SpatialNodeIndex>,
/// List of primitive clusters that make up this slice
prim_list: PrimitiveList,
/// A list of clips that are shared by all primitives in the slice. These can be
/// filtered out and applied when the tile cache is composited rather than per-item.
shared_clips: Option<Vec<ClipDataHandle>>,
/// Various flags describing properties of this slice
pub flags: SliceFlags,
}
impl Slice {
// Open clip chain instances at the start of a slice
fn push_clip_instances(
&mut self,
stack: &[ClipChainPairInfo],
) {
for clip_chain_instance in stack.iter().rev() {
self.prim_list.add_prim_to_start(
create_clip_prim_instance(
clip_chain_instance.clip_chain_id,
PrimitiveInstanceKind::PushClipChain,
),
LayoutSize::zero(),
clip_chain_instance.spatial_node_index,
PrimitiveFlags::IS_BACKFACE_VISIBLE,
);
}
}
// Close clip chain instances at the end of a slice
fn pop_clip_instances(
&mut self,
stack: &[ClipChainPairInfo],
) {
for clip_chain_instance in stack {
self.prim_list.add_prim(
create_clip_prim_instance(
clip_chain_instance.clip_chain_id,
PrimitiveInstanceKind::PopClipChain,
),
LayoutSize::zero(),
clip_chain_instance.spatial_node_index,
PrimitiveFlags::IS_BACKFACE_VISIBLE,
);
}
}
}
/// A structure that converts a serialized display list into a form that WebRender
/// can use to later build a frame. This structure produces a BuiltScene. Public
/// members are typically those that are destructured into the BuiltScene.
pub struct SceneBuilder<'a> {
/// The scene that we are currently building.
scene: &'a Scene,
/// The map of all font instances.
font_instances: FontInstanceMap,
/// A set of pipelines that the caller has requested be made available as
/// output textures.
output_pipelines: &'a FastHashSet<PipelineId>,
/// The data structure that converts between ClipId/SpatialId and the various
/// index types that the SpatialTree uses.
id_to_index_mapper: NodeIdToIndexMapper,
/// A stack of stacking context properties.
sc_stack: Vec<FlattenedStackingContext>,
/// Maintains state for any currently active shadows
pending_shadow_items: VecDeque<ShadowItem>,
/// The stack keeping track of the root clip chains associated with pipelines.
pipeline_clip_chain_stack: Vec<ClipChainId>,
/// The SpatialTree that we are currently building during building.
pub spatial_tree: SpatialTree,
/// The store of primitives.
pub prim_store: PrimitiveStore,
/// Information about all primitives involved in hit testing.
pub hit_testing_scene: HitTestingScene,
/// The store which holds all complex clipping information.
pub clip_store: ClipStore,
/// The configuration to use for the FrameBuilder. We consult this in
/// order to determine the default font.
pub config: FrameBuilderConfig,
/// Reference to the set of data that is interned across display lists.
interners: &'a mut Interners,
/// The root picture index for this builder. This is the picture
/// to start the culling phase from.
pub root_pic_index: PictureIndex,
/// Helper struct to map stacking context coords <-> reference frame coords.
rf_mapper: ReferenceFrameMapper,
/// Helper struct to map spatial nodes to external scroll offsets.
external_scroll_mapper: ScrollOffsetMapper,
/// If true, picture caching setup has already been completed.
picture_caching_initialized: bool,
/// The current recursion depth of iframes encountered. Used to restrict picture
/// caching slices to only the top-level content frame.
iframe_depth: usize,
/// The number of picture cache slices that were created for content.
content_slice_count: usize,
/// A set of any spatial nodes that are attached to either a picture cache
/// root, or a clip node on the picture cache primitive. These are used
/// to detect cases where picture caching must be disabled. This is mostly
/// a temporary workaround for some existing wrench tests. I don't think
/// Gecko ever produces picture cache slices with complex transforms, so
/// in future we should prevent this in the public API and remove this hack.
picture_cache_spatial_nodes: FastHashSet<SpatialNodeIndex>,
/// The current quality / performance settings for this scene.
quality_settings: QualitySettings,
}
impl<'a> SceneBuilder<'a> {
pub fn build(
scene: &Scene,
font_instances: FontInstanceMap,
view: &DocumentView,
output_pipelines: &FastHashSet<PipelineId>,
frame_builder_config: &FrameBuilderConfig,
interners: &mut Interners,
stats: &SceneStats,
) -> BuiltScene {
// We checked that the root pipeline is available on the render backend.
let root_pipeline_id = scene.root_pipeline_id.unwrap();
let root_pipeline = scene.pipelines.get(&root_pipeline_id).unwrap();
let background_color = root_pipeline
.background_color
.and_then(|color| if color.a > 0.0 { Some(color) } else { None });
let mut builder = SceneBuilder {
scene,
spatial_tree: SpatialTree::new(),
font_instances,
config: *frame_builder_config,
output_pipelines,
id_to_index_mapper: NodeIdToIndexMapper::default(),
hit_testing_scene: HitTestingScene::new(&stats.hit_test_stats),
pending_shadow_items: VecDeque::new(),
sc_stack: Vec::new(),
pipeline_clip_chain_stack: vec![ClipChainId::NONE],
prim_store: PrimitiveStore::new(&stats.prim_store_stats),
clip_store: ClipStore::new(),
interners,
root_pic_index: PictureIndex(0),
rf_mapper: ReferenceFrameMapper::new(),
external_scroll_mapper: ScrollOffsetMapper::new(),
picture_caching_initialized: false,
iframe_depth: 0,
content_slice_count: 0,
picture_cache_spatial_nodes: FastHashSet::default(),
quality_settings: view.quality_settings,
};
let device_pixel_scale = view.accumulated_scale_factor_for_snapping();
builder.push_root(
root_pipeline_id,
&root_pipeline.viewport_size,
&root_pipeline.content_size,
device_pixel_scale,
);
// In order to ensure we have a single root stacking context for the
// entire display list, we push one here. Gecko _almost_ wraps its
// entire display list within a single stacking context, but sometimes
// appends a few extra items in AddWindowOverlayWebRenderCommands. We
// could fix it there, but it's easier and more robust for WebRender
// to just ensure there's a context on the stack whenever we append
// primitives (since otherwise we'd panic).
//
// Note that we don't do this for iframes, even if they're pipeline
// roots, because they should be entirely contained within a stacking
// context, and we probably wouldn't crash if they weren't.
builder.push_stacking_context(
root_pipeline.pipeline_id,
CompositeOps::default(),
TransformStyle::Flat,
/* prim_flags = */ PrimitiveFlags::IS_BACKFACE_VISIBLE,
/* create_tile_cache = */ false,
ROOT_SPATIAL_NODE_INDEX,
ClipChainId::NONE,
RasterSpace::Screen,
/* is_backdrop_root = */ true,
device_pixel_scale,
);
builder.build_items(
&mut root_pipeline.display_list.iter(),
root_pipeline.pipeline_id,
true,
);
builder.pop_stacking_context();
debug_assert!(builder.sc_stack.is_empty());
BuiltScene {
has_root_pipeline: scene.has_root_pipeline(),
pipeline_epochs: scene.pipeline_epochs.clone(),
output_rect: view.device_rect.size.into(),
background_color,
hit_testing_scene: Arc::new(builder.hit_testing_scene),
spatial_tree: builder.spatial_tree,
prim_store: builder.prim_store,
clip_store: builder.clip_store,
root_pic_index: builder.root_pic_index,
config: builder.config,
content_slice_count: builder.content_slice_count,
picture_cache_spatial_nodes: builder.picture_cache_spatial_nodes,
}
}
/// Retrieve the current offset to allow converting a stacking context
/// relative coordinate to be relative to the owing reference frame,
/// also considering any external scroll offset on the provided
/// spatial node.
fn current_offset(
&mut self,
spatial_node_index: SpatialNodeIndex,
) -> LayoutVector2D {
// Get the current offset from stacking context <-> reference frame space.
let rf_offset = self.rf_mapper.current_offset();
// Get the external scroll offset, if applicable.
let scroll_offset = self
.external_scroll_mapper
.external_scroll_offset(
spatial_node_index,
&self.spatial_tree,
);
rf_offset + scroll_offset
}
/// Figure out the shape of the display list, and wrap various primitive clusters
/// into tile cache primitive instances.
fn setup_picture_caching(
&mut self,
main_prim_list: &mut PrimitiveList,
) {
if !self.config.global_enable_picture_caching {
return;
}
// Ensure that setup_picture_caching has executed
debug_assert!(self.picture_caching_initialized);
// Unconditionally insert a marker to create a picture cache slice on the
// first cluster. This handles implicit picture caches, and also the common
// case, by allowing the root / background primitives to be cached in a slice.
if let Some(cluster) = main_prim_list.clusters.first_mut() {
cluster.flags.insert(ClusterFlags::CREATE_PICTURE_CACHE_PRE);
}
// List of slices that have been found
let mut slices: Vec<Slice> = Vec::new();
// Current stack of open clip chain instances that need to be fixed up
let mut clip_chain_instance_stack = Vec::new();
// Tracker for whether a new slice should be created
let mut create_slice = true;
// The clips found the last time we traversed a set of clip chains. Stored and cleared
// here to avoid constant allocations.
let mut prim_clips = Vec::new();
// If true, the cache is out of date and needs to be rebuilt.
let mut update_shared_clips = true;
// The last prim clip chain we build prim_clips for.
let mut last_prim_clip_chain_id = ClipChainId::NONE;
// Walk the supplied top level of clusters, slicing into slices as appropriate
for cluster in main_prim_list.clusters.drain(..) {
// Check if this cluster requires a new slice
create_slice |= cluster.flags.intersects(
ClusterFlags::CREATE_PICTURE_CACHE_PRE | ClusterFlags::IS_CLEAR_PRIMITIVE
);
if create_slice {
// When creating a slice, close off any open clip chains on prev slice.
if let Some(prev_slice) = slices.last_mut() {
prev_slice.pop_clip_instances(&clip_chain_instance_stack);
}
let slice_flags = if cluster.flags.contains(ClusterFlags::SCROLLBAR_CONTAINER) {
SliceFlags::IS_SCROLLBAR
} else {
SliceFlags::empty()
};
let mut slice = Slice {
cache_scroll_root: cluster.cache_scroll_root,
prim_list: PrimitiveList::empty(),
shared_clips: None,
flags: slice_flags
};
// Open up clip chains on the stack on the new slice
slice.push_clip_instances(&clip_chain_instance_stack);
slices.push(slice);
create_slice = false;
}
// Step through each prim instance, in order to collect shared clips for the slice.
for instance in &cluster.prim_instances {
// If a Push/Pop clip chain, record that in the clip stack stack.
match instance.kind {
PrimitiveInstanceKind::PushClipChain => {
clip_chain_instance_stack.push(ClipChainPairInfo {
spatial_node_index: cluster.spatial_node_index,
clip_chain_id: instance.clip_chain_id,
});
// Invalidate the prim_clips cache - a clip chain was removed.
update_shared_clips = true;
continue;
}
PrimitiveInstanceKind::PopClipChain => {
let clip_chain_instance = clip_chain_instance_stack.pop().unwrap();
debug_assert_eq!(
clip_chain_instance.clip_chain_id,
instance.clip_chain_id,
);
debug_assert_eq!(
clip_chain_instance.spatial_node_index,
cluster.spatial_node_index,
);
// Invalidate the prim_clips cache - a clip chain was removed.
update_shared_clips = true;
continue;
}
_ => {}
}
// If the primitive clip chain is different, then we need to rebuild prim_clips.
update_shared_clips |= last_prim_clip_chain_id != instance.clip_chain_id;
last_prim_clip_chain_id = instance.clip_chain_id;
if update_shared_clips {
prim_clips.clear();
// Update the list of clips that apply to this primitive instance
for clip_instance in &clip_chain_instance_stack {
add_clips(
clip_instance.clip_chain_id,
&mut prim_clips,
&self.clip_store,
&self.interners,
);
}
add_clips(
instance.clip_chain_id,
&mut prim_clips,
&self.clip_store,
&self.interners,
);
}
// If there are no shared clips set for this slice, the shared clips are just
// the current clips set. Otherwise, the shared clips are those that are
// in both the current shared list and the clips list for this primitive.
match slices.last_mut().unwrap().shared_clips {
Some(ref mut shared_clips) => {
if update_shared_clips {
shared_clips.retain(|h1: &ClipDataHandle| {
let uid = h1.uid();
prim_clips.iter().any(|h2| {
uid == h2.uid()
})
});
}
}
ref mut shared_clips @ None => {
*shared_clips = Some(prim_clips.clone());
}
}
update_shared_clips = false;
}
// If this cluster creates a slice after, then note that for next cluster
create_slice |= cluster.flags.intersects(
ClusterFlags::CREATE_PICTURE_CACHE_POST | ClusterFlags::IS_CLEAR_PRIMITIVE
);
// Finally, add this cluster to the current slice
slices.last_mut().unwrap().prim_list.add_cluster(cluster);
}
// Close off any open clip chains on prev slice.
if let Some(prev_slice) = slices.last_mut() {
prev_slice.pop_clip_instances(&clip_chain_instance_stack);
}
// Step through the slices, creating picture cache wrapper instances.
for (slice_index, slice) in slices.drain(..).enumerate() {
let background_color = if slice_index == 0 {
self.config.background_color
} else {
None
};
// If the cluster specifies a scroll root, use it. Otherwise,
// just cache assuming no scrolling takes place. Even if that's
// not true, we still get caching benefits for any changes that
// occur while not scrolling (such as animation, video etc);
let scroll_root = slice.cache_scroll_root.unwrap_or(ROOT_SPATIAL_NODE_INDEX);
let instance = create_tile_cache(
slice_index,
slice.flags,
scroll_root,
slice.prim_list,
background_color,
slice.shared_clips.unwrap_or_else(Vec::new),
&mut self.interners,
&mut self.prim_store,
&mut self.clip_store,
&mut self.picture_cache_spatial_nodes,
&self.config,
);
main_prim_list.add_prim(
instance,
LayoutSize::zero(),
scroll_root,
PrimitiveFlags::IS_BACKFACE_VISIBLE,
);
}
}
fn build_items(
&mut self,
traversal: &mut BuiltDisplayListIter<'a>,
pipeline_id: PipelineId,
apply_pipeline_clip: bool,
) {
loop {
let item = match traversal.next() {
Some(item) => item,
None => break,
};
let subtraversal = match item.item() {
DisplayItem::PushStackingContext(ref info) => {
let space = self.get_space(&info.spatial_id);
let mut subtraversal = item.sub_iter();
self.build_stacking_context(
&mut subtraversal,
pipeline_id,
&info.stacking_context,
space,
info.origin,
item.filters(),
&item.filter_datas(),
item.filter_primitives(),
info.prim_flags,
apply_pipeline_clip,
);
Some(subtraversal)
}
DisplayItem::PushReferenceFrame(ref info) => {
let parent_space = self.get_space(&info.parent_spatial_id);
let mut subtraversal = item.sub_iter();
self.build_reference_frame(
&mut subtraversal,
pipeline_id,
parent_space,
info.origin,
&info.reference_frame,
apply_pipeline_clip,
);
Some(subtraversal)
}
DisplayItem::PopReferenceFrame |
DisplayItem::PopStackingContext => return,
_ => None,
};
// If build_item created a sub-traversal, we need `traversal` to have the
// same state as the completed subtraversal, so we reinitialize it here.
if let Some(mut subtraversal) = subtraversal {
subtraversal.merge_debug_stats_from(traversal);
*traversal = subtraversal;
} else {
self.build_item(item, pipeline_id, apply_pipeline_clip);
}
}
// TODO: factor this out to be part of capture
if cfg!(feature = "display_list_stats") {
let stats = traversal.debug_stats();
let total_bytes: usize = stats.iter().map(|(_, stats)| stats.num_bytes).sum();
println!("item, total count, total bytes, % of DL bytes, bytes per item");
for (label, stats) in stats {
println!("{}, {}, {}kb, {}%, {}",
label,
stats.total_count,
stats.num_bytes / 1000,
((stats.num_bytes as f32 / total_bytes.max(1) as f32) * 100.0) as usize,
stats.num_bytes / stats.total_count.max(1));
}
println!();
}
}
fn build_sticky_frame(
&mut self,
info: &StickyFrameDisplayItem,
parent_node_index: SpatialNodeIndex,
) {
let current_offset = self.current_offset(parent_node_index);
let frame_rect = info.bounds.translate(current_offset);
let sticky_frame_info = StickyFrameInfo::new(
frame_rect,
info.margins,
info.vertical_offset_bounds,
info.horizontal_offset_bounds,
info.previously_applied_offset,
);
let index = self.spatial_tree.add_sticky_frame(
parent_node_index,
sticky_frame_info,
info.id.pipeline_id(),
);
self.id_to_index_mapper.map_spatial_node(info.id, index);
}
fn build_scroll_frame(
&mut self,
item: &DisplayItemRef,
info: &ScrollFrameDisplayItem,
parent_node_index: SpatialNodeIndex,
pipeline_id: PipelineId,
) {
let current_offset = self.current_offset(parent_node_index);
let clip_region = ClipRegion::create_for_clip_node(
info.clip_rect,
item.complex_clip().iter(),
info.image_mask,
¤t_offset,
);
// Just use clip rectangle as the frame rect for this scroll frame.
// This is useful when calculating scroll extents for the
// SpatialNode::scroll(..) API as well as for properly setting sticky
// positioning offsets.
let frame_rect = clip_region.main;
let content_size = info.content_rect.size;
self.add_clip_node(info.clip_id, &info.parent_space_and_clip, clip_region);
self.add_scroll_frame(
info.scroll_frame_id,
parent_node_index,
info.external_id,
pipeline_id,
&frame_rect,
&content_size,
info.scroll_sensitivity,
ScrollFrameKind::Explicit,
info.external_scroll_offset,
);
}
fn build_reference_frame(
&mut self,
traversal: &mut BuiltDisplayListIter<'a>,
pipeline_id: PipelineId,
parent_spatial_node: SpatialNodeIndex,
origin: LayoutPoint,
reference_frame: &ReferenceFrame,
apply_pipeline_clip: bool,
) {
let current_offset = self.current_offset(parent_spatial_node);
self.push_reference_frame(
reference_frame.id,
Some(parent_spatial_node),
pipeline_id,
reference_frame.transform_style,
reference_frame.transform,
reference_frame.kind,
current_offset + origin.to_vector(),
);
self.rf_mapper.push_scope();
self.build_items(
traversal,
pipeline_id,
apply_pipeline_clip,
);
self.rf_mapper.pop_scope();
}
fn build_stacking_context(
&mut self,
traversal: &mut BuiltDisplayListIter<'a>,
pipeline_id: PipelineId,
stacking_context: &StackingContext,
spatial_node_index: SpatialNodeIndex,
origin: LayoutPoint,
filters: ItemRange<FilterOp>,
filter_datas: &[TempFilterData],
filter_primitives: ItemRange<FilterPrimitive>,
prim_flags: PrimitiveFlags,
apply_pipeline_clip: bool,
) {
// Avoid doing unnecessary work for empty stacking contexts.
if traversal.current_stacking_context_empty() {
traversal.skip_current_stacking_context();
return;
}
let composition_operations = {
CompositeOps::new(
filter_ops_for_compositing(filters),
filter_datas_for_compositing(filter_datas),
filter_primitives_for_compositing(filter_primitives),
stacking_context.mix_blend_mode_for_compositing(),
)
};
let clip_chain_id = match stacking_context.clip_id {
Some(clip_id) => self.id_to_index_mapper.get_clip_chain_id(clip_id),
None => ClipChainId::NONE,
};
self.push_stacking_context(
pipeline_id,
composition_operations,
stacking_context.transform_style,
prim_flags,
stacking_context.cache_tiles,
spatial_node_index,
clip_chain_id,
stacking_context.raster_space,
stacking_context.is_backdrop_root,
self.sc_stack.last().unwrap().snap_to_device.device_pixel_scale,
);
if cfg!(debug_assertions) && apply_pipeline_clip && clip_chain_id != ClipChainId::NONE {
// This is the rootmost stacking context in this pipeline that has
// a clip set. Check that the clip chain includes the pipeline clip
// as well, because this where we recurse with `apply_pipeline_clip`
// set to false and stop explicitly adding the pipeline clip to
// individual items.
let pipeline_clip = self.pipeline_clip_chain_stack.last().unwrap();
let mut found_root = *pipeline_clip == ClipChainId::NONE;
let mut cur_clip = clip_chain_id.clone();
while cur_clip != ClipChainId::NONE {
if cur_clip == *pipeline_clip {
found_root = true;
break;
}
cur_clip = self.clip_store.get_clip_chain(cur_clip).parent_clip_chain_id;
}
debug_assert!(found_root);
}
self.rf_mapper.push_offset(origin.to_vector());
self.build_items(
traversal,
pipeline_id,
apply_pipeline_clip && clip_chain_id == ClipChainId::NONE,
);
self.rf_mapper.pop_offset();
self.pop_stacking_context();
}
fn build_iframe(
&mut self,
info: &IframeDisplayItem,
spatial_node_index: SpatialNodeIndex,
) {
let iframe_pipeline_id = info.pipeline_id;
let pipeline = match self.scene.pipelines.get(&iframe_pipeline_id) {
Some(pipeline) => pipeline,
None => {
debug_assert!(info.ignore_missing_pipeline);
return
},
};
let current_offset = self.current_offset(spatial_node_index);
let clip_chain_index = self.add_clip_node(
ClipId::root(iframe_pipeline_id),
&info.space_and_clip,
ClipRegion::create_for_clip_node_with_local_clip(
&info.clip_rect,
¤t_offset,
),
);
self.pipeline_clip_chain_stack.push(clip_chain_index);
let snap_to_device = &mut self.sc_stack.last_mut().unwrap().snap_to_device;
snap_to_device.set_target_spatial_node(
spatial_node_index,
&self.spatial_tree,
);
let bounds = snap_to_device.snap_rect(
&info.bounds.translate(current_offset),
);
let content_size = snap_to_device.snap_size(&pipeline.content_size);
let spatial_node_index = self.push_reference_frame(
SpatialId::root_reference_frame(iframe_pipeline_id),
Some(spatial_node_index),
iframe_pipeline_id,
TransformStyle::Flat,
PropertyBinding::Value(LayoutTransform::identity()),
ReferenceFrameKind::Transform,
bounds.origin.to_vector(),
);
let iframe_rect = LayoutRect::new(LayoutPoint::zero(), bounds.size);
self.add_scroll_frame(
SpatialId::root_scroll_node(iframe_pipeline_id),
spatial_node_index,
Some(ExternalScrollId(0, iframe_pipeline_id)),
iframe_pipeline_id,
&iframe_rect,
&content_size,
ScrollSensitivity::ScriptAndInputEvents,
ScrollFrameKind::PipelineRoot,
LayoutVector2D::zero(),
);