-
Notifications
You must be signed in to change notification settings - Fork 54
/
picture.rs
6852 lines (6150 loc) · 290 KB
/
picture.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/. */
//! A picture represents a dynamically rendered image.
//!
//! # Overview
//!
//! Pictures consists of:
//!
//! - A number of primitives that are drawn onto the picture.
//! - A composite operation describing how to composite this
//! picture into its parent.
//! - A configuration describing how to draw the primitives on
//! this picture (e.g. in screen space or local space).
//!
//! The tree of pictures are generated during scene building.
//!
//! Depending on their composite operations pictures can be rendered into
//! intermediate targets or folded into their parent picture.
//!
//! ## Picture caching
//!
//! Pictures can be cached to reduce the amount of rasterization happening per
//! frame.
//!
//! When picture caching is enabled, the scene is cut into a small number of slices,
//! typically:
//!
//! - content slice
//! - UI slice
//! - background UI slice which is hidden by the other two slices most of the time.
//!
//! Each of these slice is made up of fixed-size large tiles of 2048x512 pixels
//! (or 128x128 for the UI slice).
//!
//! Tiles can be either cached rasterized content into a texture or "clear tiles"
//! that contain only a solid color rectangle rendered directly during the composite
//! pass.
//!
//! ## Invalidation
//!
//! Each tile keeps track of the elements that affect it, which can be:
//!
//! - primitives
//! - clips
//! - image keys
//! - opacity bindings
//! - transforms
//!
//! These dependency lists are built each frame and compared to the previous frame to
//! see if the tile changed.
//!
//! The tile's primitive dependency information is organized in a quadtree, each node
//! storing an index buffer of tile primitive dependencies.
//!
//! The union of the invalidated leaves of each quadtree produces a per-tile dirty rect
//! which defines the scissor rect used when replaying the tile's drawing commands and
//! can be used for partial present.
//!
//! ## Display List shape
//!
//! WR will first look for an iframe item in the root stacking context to apply
//! picture caching to. If that's not found, it will apply to the entire root
//! stacking context of the display list. Apart from that, the format of the
//! display list is not important to picture caching. Each time a new scroll root
//! is encountered, a new picture cache slice will be created. If the display
//! list contains more than some arbitrary number of slices (currently 8), the
//! content will all be squashed into a single slice, in order to save GPU memory
//! and compositing performance.
//!
//! ## Compositor Surfaces
//!
//! Sometimes, a primitive would prefer to exist as a native compositor surface.
//! This allows a large and/or regularly changing primitive (such as a video, or
//! webgl canvas) to be updated each frame without invalidating the content of
//! tiles, and can provide a significant performance win and battery saving.
//!
//! Since drawing a primitive as a compositor surface alters the ordering of
//! primitives in a tile, we use 'overlay tiles' to ensure correctness. If a
//! tile has a compositor surface, _and_ that tile has primitives that overlap
//! the compositor surface rect, the tile switches to be drawn in alpha mode.
//!
//! We rely on only promoting compositor surfaces that are opaque primitives.
//! With this assumption, the tile(s) that intersect the compositor surface get
//! a 'cutout' in the rectangle where the compositor surface exists (not the
//! entire tile), allowing that tile to be drawn as an alpha tile after the
//! compositor surface.
//!
//! Tiles are only drawn in overlay mode if there is content that exists on top
//! of the compositor surface. Otherwise, we can draw the tiles in the normal fast
//! path before the compositor surface is drawn. Use of the per-tile valid and
//! dirty rects ensure that we do a minimal amount of per-pixel work here to
//! blend the overlay tile (this is not always optimal right now, but will be
//! improved as a follow up).
use api::{MixBlendMode, PipelineId, PremultipliedColorF, FilterPrimitiveKind};
use api::{PropertyBinding, PropertyBindingId, FilterPrimitive, FontRenderMode};
use api::{DebugFlags, RasterSpace, ImageKey, ColorF, ColorU, PrimitiveFlags};
use api::units::*;
use crate::box_shadow::BLUR_SAMPLE_SCALE;
use crate::clip::{ClipStore, ClipChainInstance, ClipDataHandle, ClipChainId};
use crate::spatial_tree::{ROOT_SPATIAL_NODE_INDEX,
SpatialTree, CoordinateSpaceMapping, SpatialNodeIndex, VisibleFace
};
use crate::composite::{CompositorKind, CompositeState, NativeSurfaceId, NativeTileId};
use crate::composite::{ExternalSurfaceDescriptor};
use crate::debug_colors;
use euclid::{vec2, vec3, Point2D, Scale, Size2D, Vector2D, Rect, Transform3D, SideOffsets2D};
use euclid::approxeq::ApproxEq;
use crate::filterdata::SFilterData;
use crate::frame_builder::{FrameBuilderConfig, FrameVisibilityContext, FrameVisibilityState};
use crate::intern::ItemUid;
use crate::internal_types::{FastHashMap, FastHashSet, PlaneSplitter, Filter, PlaneSplitAnchor, TextureSource};
use crate::frame_builder::{FrameBuildingContext, FrameBuildingState, PictureState, PictureContext};
use crate::gpu_cache::{GpuCache, GpuCacheAddress, GpuCacheHandle};
use crate::gpu_types::{UvRectKind, ZBufferId};
use plane_split::{Clipper, Polygon, Splitter};
use crate::prim_store::{SpaceMapper, PrimitiveVisibilityMask, PointKey, PrimitiveTemplateKind};
use crate::prim_store::{SpaceSnapper, PictureIndex, PrimitiveInstance, PrimitiveInstanceKind};
use crate::prim_store::{get_raster_rects, PrimitiveScratchBuffer, RectangleKey};
use crate::prim_store::{OpacityBindingStorage, ImageInstanceStorage, OpacityBindingIndex};
use crate::prim_store::{ColorBindingStorage, ColorBindingIndex, PrimitiveVisibilityFlags};
use crate::print_tree::{PrintTree, PrintTreePrinter};
use crate::render_backend::DataStores;
use crate::render_task_graph::RenderTaskId;
use crate::render_target::RenderTargetKind;
use crate::render_task::{RenderTask, RenderTaskLocation, BlurTaskCache, ClearMode};
use crate::resource_cache::{ResourceCache, ImageGeneration};
use crate::scene::SceneProperties;
use crate::spatial_tree::CoordinateSystemId;
use smallvec::SmallVec;
use std::{mem, u8, marker, u32};
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::texture_cache::TextureCacheHandle;
use crate::util::{MaxRect, VecHelper, RectHelpers, MatrixHelpers};
use crate::filterdata::{FilterDataHandle};
#[cfg(any(feature = "capture", feature = "replay"))]
use ron;
#[cfg(feature = "capture")]
use crate::scene_builder_thread::InternerUpdates;
#[cfg(any(feature = "capture", feature = "replay"))]
use crate::intern::{Internable, UpdateList};
#[cfg(any(feature = "capture", feature = "replay"))]
use api::{ClipIntern, FilterDataIntern, PrimitiveKeyKind};
#[cfg(any(feature = "capture", feature = "replay"))]
use crate::prim_store::backdrop::Backdrop;
#[cfg(any(feature = "capture", feature = "replay"))]
use crate::prim_store::borders::{ImageBorder, NormalBorderPrim};
#[cfg(any(feature = "capture", feature = "replay"))]
use crate::prim_store::gradient::{LinearGradient, RadialGradient, ConicGradient};
#[cfg(any(feature = "capture", feature = "replay"))]
use crate::prim_store::image::{Image, YuvImage};
#[cfg(any(feature = "capture", feature = "replay"))]
use crate::prim_store::line_dec::LineDecoration;
#[cfg(any(feature = "capture", feature = "replay"))]
use crate::prim_store::picture::Picture;
#[cfg(any(feature = "capture", feature = "replay"))]
use crate::prim_store::text_run::TextRun;
#[cfg(feature = "capture")]
use std::fs::File;
#[cfg(feature = "capture")]
use std::io::prelude::*;
#[cfg(feature = "capture")]
use std::path::PathBuf;
use crate::scene_building::{SliceFlags};
#[cfg(feature = "replay")]
// used by tileview so don't use an internal_types FastHashMap
use std::collections::HashMap;
// Maximum blur radius for blur filter (different than box-shadow blur).
// Taken from FilterNodeSoftware.cpp in Gecko.
pub const MAX_BLUR_RADIUS: f32 = 100.;
/// Specify whether a surface allows subpixel AA text rendering.
#[derive(Debug, Clone, PartialEq)]
pub enum SubpixelMode {
/// This surface allows subpixel AA text
Allow,
/// Subpixel AA text cannot be drawn on this surface
Deny,
/// Subpixel AA can be drawn on this surface, if not intersecting
/// with the excluded regions
Conditional {
excluded_rects: Vec<PictureRect>,
},
}
/// A comparable transform matrix, that compares with epsilon checks.
#[derive(Debug, Clone)]
struct MatrixKey {
m: [f32; 16],
}
impl PartialEq for MatrixKey {
fn eq(&self, other: &Self) -> bool {
const EPSILON: f32 = 0.001;
// TODO(gw): It's possible that we may need to adjust the epsilon
// to be tighter on most of the matrix, except the
// translation parts?
for (i, j) in self.m.iter().zip(other.m.iter()) {
if !i.approx_eq_eps(j, &EPSILON) {
return false;
}
}
true
}
}
/// A comparable / hashable version of a coordinate space mapping. Used to determine
/// if a transform dependency for a tile has changed.
#[derive(Debug, PartialEq, Clone)]
enum TransformKey {
Local,
ScaleOffset {
scale_x: f32,
scale_y: f32,
offset_x: f32,
offset_y: f32,
},
Transform {
m: MatrixKey,
}
}
impl<Src, Dst> From<CoordinateSpaceMapping<Src, Dst>> for TransformKey {
fn from(transform: CoordinateSpaceMapping<Src, Dst>) -> TransformKey {
match transform {
CoordinateSpaceMapping::Local => {
TransformKey::Local
}
CoordinateSpaceMapping::ScaleOffset(ref scale_offset) => {
TransformKey::ScaleOffset {
scale_x: scale_offset.scale.x,
scale_y: scale_offset.scale.y,
offset_x: scale_offset.offset.x,
offset_y: scale_offset.offset.y,
}
}
CoordinateSpaceMapping::Transform(ref m) => {
TransformKey::Transform {
m: MatrixKey {
m: m.to_row_major_array(),
},
}
}
}
}
}
/// Information about a picture that is pushed / popped on the
/// PictureUpdateState during picture traversal pass.
struct PictureInfo {
/// The spatial node for this picture.
_spatial_node_index: SpatialNodeIndex,
}
/// Picture-caching state to keep between scenes.
pub struct PictureCacheState {
/// The tiles retained by this picture cache.
pub tiles: FastHashMap<TileOffset, Box<Tile>>,
/// State of the spatial nodes from previous frame
spatial_nodes: FastHashMap<SpatialNodeIndex, SpatialNodeDependency>,
/// State of opacity bindings from previous frame
opacity_bindings: FastHashMap<PropertyBindingId, OpacityBindingInfo>,
/// State of color bindings from previous frame
color_bindings: FastHashMap<PropertyBindingId, ColorBindingInfo>,
/// The current transform of the picture cache root spatial node
root_transform: TransformKey,
/// The current tile size in device pixels
current_tile_size: DeviceIntSize,
/// Various allocations we want to avoid re-doing.
allocations: PictureCacheRecycledAllocations,
/// Currently allocated native compositor surface for this picture cache.
pub native_surface: Option<NativeSurface>,
/// A cache of compositor surfaces that are retained between display lists
pub external_native_surface_cache: FastHashMap<ExternalNativeSurfaceKey, ExternalNativeSurface>,
/// The retained virtual offset for this slice between display lists.
virtual_offset: DeviceIntPoint,
}
pub struct PictureCacheRecycledAllocations {
old_opacity_bindings: FastHashMap<PropertyBindingId, OpacityBindingInfo>,
old_color_bindings: FastHashMap<PropertyBindingId, ColorBindingInfo>,
compare_cache: FastHashMap<PrimitiveComparisonKey, PrimitiveCompareResult>,
}
/// Stores a list of cached picture tiles that are retained
/// between new scenes.
#[cfg_attr(feature = "capture", derive(Serialize))]
pub struct RetainedTiles {
/// The tiles retained between display lists.
#[cfg_attr(feature = "capture", serde(skip))] //TODO
pub caches: FastHashMap<usize, PictureCacheState>,
}
impl RetainedTiles {
pub fn new() -> Self {
RetainedTiles {
caches: FastHashMap::default(),
}
}
/// Merge items from one retained tiles into another.
pub fn merge(&mut self, other: RetainedTiles) {
assert!(self.caches.is_empty() || other.caches.is_empty());
if self.caches.is_empty() {
self.caches = other.caches;
}
}
}
/// Unit for tile coordinates.
#[derive(Hash, Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct TileCoordinate;
// Geometry types for tile coordinates.
pub type TileOffset = Point2D<i32, TileCoordinate>;
pub type TileSize = Size2D<i32, TileCoordinate>;
pub type TileRect = Rect<i32, TileCoordinate>;
/// The maximum number of compositor surfaces that are allowed per picture cache. This
/// is an arbitrary number that should be enough for common cases, but low enough to
/// prevent performance and memory usage drastically degrading in pathological cases.
const MAX_COMPOSITOR_SURFACES: usize = 4;
/// The size in device pixels of a normal cached tile.
pub const TILE_SIZE_DEFAULT: DeviceIntSize = DeviceIntSize {
width: 1024,
height: 512,
_unit: marker::PhantomData,
};
/// The size in device pixels of a tile for horizontal scroll bars
pub const TILE_SIZE_SCROLLBAR_HORIZONTAL: DeviceIntSize = DeviceIntSize {
width: 512,
height: 16,
_unit: marker::PhantomData,
};
/// The size in device pixels of a tile for vertical scroll bars
pub const TILE_SIZE_SCROLLBAR_VERTICAL: DeviceIntSize = DeviceIntSize {
width: 16,
height: 512,
_unit: marker::PhantomData,
};
const TILE_SIZE_FOR_TESTS: [DeviceIntSize; 6] = [
DeviceIntSize {
width: 128,
height: 128,
_unit: marker::PhantomData,
},
DeviceIntSize {
width: 256,
height: 256,
_unit: marker::PhantomData,
},
DeviceIntSize {
width: 512,
height: 512,
_unit: marker::PhantomData,
},
TILE_SIZE_DEFAULT,
TILE_SIZE_SCROLLBAR_VERTICAL,
TILE_SIZE_SCROLLBAR_HORIZONTAL,
];
// Return the list of tile sizes for the renderer to allocate texture arrays for.
pub fn tile_cache_sizes(testing: bool) -> &'static [DeviceIntSize] {
if testing {
&TILE_SIZE_FOR_TESTS
} else {
&[
TILE_SIZE_DEFAULT,
TILE_SIZE_SCROLLBAR_HORIZONTAL,
TILE_SIZE_SCROLLBAR_VERTICAL,
]
}
}
/// The maximum size per axis of a surface,
/// in WorldPixel coordinates.
const MAX_SURFACE_SIZE: f32 = 4096.0;
/// The maximum number of sub-dependencies (e.g. clips, transforms) we can handle
/// per-primitive. If a primitive has more than this, it will invalidate every frame.
const MAX_PRIM_SUB_DEPS: usize = u8::MAX as usize;
/// Used to get unique tile IDs, even when the tile cache is
/// destroyed between display lists / scenes.
static NEXT_TILE_ID: AtomicUsize = AtomicUsize::new(0);
fn clamp(value: i32, low: i32, high: i32) -> i32 {
value.max(low).min(high)
}
fn clampf(value: f32, low: f32, high: f32) -> f32 {
value.max(low).min(high)
}
/// Clamps the blur radius depending on scale factors.
fn clamp_blur_radius(blur_radius: f32, scale_factors: (f32, f32)) -> f32 {
// Clamping must occur after scale factors are applied, but scale factors are not applied
// until later on. To clamp the blur radius, we first apply the scale factors and then clamp
// and finally revert the scale factors.
// TODO: the clamping should be done on a per-axis basis, but WR currently only supports
// having a single value for both x and y blur.
let largest_scale_factor = f32::max(scale_factors.0, scale_factors.1);
let adjusted_blur_radius = blur_radius * largest_scale_factor;
let clamped_blur_radius = f32::min(adjusted_blur_radius, MAX_BLUR_RADIUS);
clamped_blur_radius / largest_scale_factor
}
/// An index into the prims array in a TileDescriptor.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct PrimitiveDependencyIndex(pub u32);
/// Information about the state of a binding.
#[derive(Debug)]
pub struct BindingInfo<T> {
/// The current value retrieved from dynamic scene properties.
value: T,
/// True if it was changed (or is new) since the last frame build.
changed: bool,
}
/// Information stored in a tile descriptor for a binding.
#[derive(Debug, PartialEq, Clone, Copy)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum Binding<T> {
Value(T),
Binding(PropertyBindingId),
}
impl<T> From<PropertyBinding<T>> for Binding<T> {
fn from(binding: PropertyBinding<T>) -> Binding<T> {
match binding {
PropertyBinding::Binding(key, _) => Binding::Binding(key.id),
PropertyBinding::Value(value) => Binding::Value(value),
}
}
}
pub type OpacityBinding = Binding<f32>;
pub type OpacityBindingInfo = BindingInfo<f32>;
pub type ColorBinding = Binding<ColorU>;
pub type ColorBindingInfo = BindingInfo<ColorU>;
/// Information about the state of a spatial node value
#[derive(Debug)]
pub struct SpatialNodeDependency {
/// The current value retrieved from the spatial tree.
value: TransformKey,
/// True if it was changed (or is new) since the last frame build.
changed: bool,
}
// Immutable context passed to picture cache tiles during pre_update
struct TilePreUpdateContext {
/// Maps from picture cache coords -> world space coords.
pic_to_world_mapper: SpaceMapper<PicturePixel, WorldPixel>,
/// The fractional position of the picture cache, which may
/// require invalidation of all tiles.
fract_offset: PictureVector2D,
/// The optional background color of the picture cache instance
background_color: Option<ColorF>,
/// The visible part of the screen in world coords.
global_screen_world_rect: WorldRect,
/// Current size of tiles in picture units.
tile_size: PictureSize,
}
// Immutable context passed to picture cache tiles during post_update
struct TilePostUpdateContext<'a> {
/// Maps from picture cache coords -> world space coords.
pic_to_world_mapper: SpaceMapper<PicturePixel, WorldPixel>,
/// Global scale factor from world -> device pixels.
global_device_pixel_scale: DevicePixelScale,
/// The local clip rect (in picture space) of the entire picture cache
local_clip_rect: PictureRect,
/// The calculated backdrop information for this cache instance.
backdrop: BackdropInfo,
/// Information about transform node differences from last frame.
spatial_nodes: &'a FastHashMap<SpatialNodeIndex, SpatialNodeDependency>,
/// Information about opacity bindings from the picture cache.
opacity_bindings: &'a FastHashMap<PropertyBindingId, OpacityBindingInfo>,
/// Information about color bindings from the picture cache.
color_bindings: &'a FastHashMap<PropertyBindingId, ColorBindingInfo>,
/// Current size in device pixels of tiles for this cache
current_tile_size: DeviceIntSize,
/// The local rect of the overall picture cache
local_rect: PictureRect,
/// A list of the external surfaces that are present on this slice
external_surfaces: &'a [ExternalSurfaceDescriptor],
/// Pre-allocated z-id to assign to opaque tiles during post_update. We
/// use a different z-id for opaque/alpha tiles, so that compositor
/// surfaces (such as videos) can have a z-id between these values,
/// which allows compositor surfaces to occlude opaque tiles, but not
/// alpha tiles.
z_id_opaque: ZBufferId,
/// Pre-allocated z-id to assign to alpha tiles during post_update
z_id_alpha: ZBufferId,
}
// Mutable state passed to picture cache tiles during post_update
struct TilePostUpdateState<'a> {
/// Allow access to the texture cache for requesting tiles
resource_cache: &'a mut ResourceCache,
/// Current configuration and setup for compositing all the picture cache tiles in renderer.
composite_state: &'a mut CompositeState,
/// A cache of comparison results to avoid re-computation during invalidation.
compare_cache: &'a mut FastHashMap<PrimitiveComparisonKey, PrimitiveCompareResult>,
}
/// Information about the dependencies of a single primitive instance.
struct PrimitiveDependencyInfo {
/// If true, we should clip the prim rect to the tile boundaries.
clip_by_tile: bool,
/// Unique content identifier of the primitive.
prim_uid: ItemUid,
/// The picture space origin of this primitive.
prim_origin: PicturePoint,
/// The (conservative) clipped area in picture space this primitive occupies.
prim_clip_rect: PictureRect,
/// Image keys this primitive depends on.
images: SmallVec<[ImageDependency; 8]>,
/// Opacity bindings this primitive depends on.
opacity_bindings: SmallVec<[OpacityBinding; 4]>,
/// Color binding this primitive depends on.
color_binding: Option<ColorBinding>,
/// Clips that this primitive depends on.
clips: SmallVec<[ItemUid; 8]>,
/// Spatial nodes references by the clip dependencies of this primitive.
spatial_nodes: SmallVec<[SpatialNodeIndex; 4]>,
/// If true, this primitive has been promoted to be a compositor surface.
is_compositor_surface: bool,
}
impl PrimitiveDependencyInfo {
/// Construct dependency info for a new primitive.
fn new(
prim_uid: ItemUid,
prim_origin: PicturePoint,
prim_clip_rect: PictureRect,
) -> Self {
PrimitiveDependencyInfo {
prim_uid,
prim_origin,
images: SmallVec::new(),
opacity_bindings: SmallVec::new(),
color_binding: None,
clip_by_tile: false,
prim_clip_rect,
clips: SmallVec::new(),
spatial_nodes: SmallVec::new(),
is_compositor_surface: false,
}
}
}
/// A stable ID for a given tile, to help debugging. These are also used
/// as unique identifiers for tile surfaces when using a native compositor.
#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct TileId(pub usize);
/// A descriptor for the kind of texture that a picture cache tile will
/// be drawn into.
#[derive(Debug)]
pub enum SurfaceTextureDescriptor {
/// When using the WR compositor, the tile is drawn into an entry
/// in the WR texture cache.
TextureCache {
handle: TextureCacheHandle
},
/// When using an OS compositor, the tile is drawn into a native
/// surface identified by arbitrary id.
Native {
/// The arbitrary id of this tile.
id: Option<NativeTileId>,
},
}
/// This is the same as a `SurfaceTextureDescriptor` but has been resolved
/// into a texture cache handle (if appropriate) that can be used by the
/// batching and compositing code in the renderer.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum ResolvedSurfaceTexture {
TextureCache {
/// The texture ID to draw to.
texture: TextureSource,
/// Slice index in the texture array to draw to.
layer: i32,
},
Native {
/// The arbitrary id of this tile.
id: NativeTileId,
/// The size of the tile in device pixels.
size: DeviceIntSize,
}
}
impl SurfaceTextureDescriptor {
/// Create a resolved surface texture for this descriptor
pub fn resolve(
&self,
resource_cache: &ResourceCache,
size: DeviceIntSize,
) -> ResolvedSurfaceTexture {
match self {
SurfaceTextureDescriptor::TextureCache { handle } => {
let cache_item = resource_cache.texture_cache.get(handle);
ResolvedSurfaceTexture::TextureCache {
texture: cache_item.texture_id,
layer: cache_item.texture_layer,
}
}
SurfaceTextureDescriptor::Native { id } => {
ResolvedSurfaceTexture::Native {
id: id.expect("bug: native surface not allocated"),
size,
}
}
}
}
}
/// The backing surface for this tile.
#[derive(Debug)]
pub enum TileSurface {
Texture {
/// Descriptor for the surface that this tile draws into.
descriptor: SurfaceTextureDescriptor,
/// Bitfield specifying the dirty region(s) that are relevant to this tile.
visibility_mask: PrimitiveVisibilityMask,
},
Color {
color: ColorF,
},
Clear,
}
impl TileSurface {
fn kind(&self) -> &'static str {
match *self {
TileSurface::Color { .. } => "Color",
TileSurface::Texture { .. } => "Texture",
TileSurface::Clear => "Clear",
}
}
}
/// Optional extra information returned by is_same when
/// logging is enabled.
#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum CompareHelperResult<T> {
/// Primitives match
Equal,
/// Counts differ
Count {
prev_count: u8,
curr_count: u8,
},
/// Sentinel
Sentinel,
/// Two items are not equal
NotEqual {
prev: T,
curr: T,
},
/// User callback returned true on item
PredicateTrue {
curr: T
},
}
/// The result of a primitive dependency comparison. Size is a u8
/// since this is a hot path in the code, and keeping the data small
/// is a performance win.
#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
#[repr(u8)]
pub enum PrimitiveCompareResult {
/// Primitives match
Equal,
/// Something in the PrimitiveDescriptor was different
Descriptor,
/// The clip node content or spatial node changed
Clip,
/// The value of the transform changed
Transform,
/// An image dependency was dirty
Image,
/// The value of an opacity binding changed
OpacityBinding,
/// The value of a color binding changed
ColorBinding,
}
/// A more detailed version of PrimitiveCompareResult used when
/// debug logging is enabled.
#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum PrimitiveCompareResultDetail {
/// Primitives match
Equal,
/// Something in the PrimitiveDescriptor was different
Descriptor {
old: PrimitiveDescriptor,
new: PrimitiveDescriptor,
},
/// The clip node content or spatial node changed
Clip {
detail: CompareHelperResult<ItemUid>,
},
/// The value of the transform changed
Transform {
detail: CompareHelperResult<SpatialNodeIndex>,
},
/// An image dependency was dirty
Image {
detail: CompareHelperResult<ImageDependency>,
},
/// The value of an opacity binding changed
OpacityBinding {
detail: CompareHelperResult<OpacityBinding>,
},
/// The value of a color binding changed
ColorBinding {
detail: CompareHelperResult<ColorBinding>,
},
}
/// Debugging information about why a tile was invalidated
#[derive(Debug,Clone)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum InvalidationReason {
/// The fractional offset changed
FractionalOffset {
old: PictureVector2D,
new: PictureVector2D,
},
/// The background color changed
BackgroundColor {
old: Option<ColorF>,
new: Option<ColorF>,
},
/// The opaque state of the backing native surface changed
SurfaceOpacityChanged{
became_opaque: bool
},
/// There was no backing texture (evicted or never rendered)
NoTexture,
/// There was no backing native surface (never rendered, or recreated)
NoSurface,
/// The primitive count in the dependency list was different
PrimCount {
old: Option<Vec<ItemUid>>,
new: Option<Vec<ItemUid>>,
},
/// The content of one of the primitives was different
Content {
/// What changed in the primitive that was different
prim_compare_result: PrimitiveCompareResult,
prim_compare_result_detail: Option<PrimitiveCompareResultDetail>,
},
// The compositor type changed
CompositorKindChanged,
// The valid region of the tile changed
ValidRectChanged,
}
/// A minimal subset of Tile for debug capturing
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct TileSerializer {
pub rect: PictureRect,
pub current_descriptor: TileDescriptor,
pub fract_offset: PictureVector2D,
pub id: TileId,
pub root: TileNode,
pub background_color: Option<ColorF>,
pub invalidation_reason: Option<InvalidationReason>
}
/// A minimal subset of TileCacheInstance for debug capturing
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct TileCacheInstanceSerializer {
pub slice: usize,
pub tiles: FastHashMap<TileOffset, TileSerializer>,
pub background_color: Option<ColorF>,
pub fract_offset: PictureVector2D,
}
/// Information about a cached tile.
pub struct Tile {
/// The grid position of this tile within the picture cache
pub tile_offset: TileOffset,
/// The current world rect of this tile.
pub world_tile_rect: WorldRect,
/// The current local rect of this tile.
pub local_tile_rect: PictureRect,
/// The picture space dirty rect for this tile.
local_dirty_rect: PictureRect,
/// The device space dirty rect for this tile.
/// TODO(gw): We have multiple dirty rects available due to the quadtree above. In future,
/// expose these as multiple dirty rects, which will help in some cases.
pub device_dirty_rect: DeviceRect,
/// Device space rect that contains valid pixels region of this tile.
pub device_valid_rect: DeviceRect,
/// Uniquely describes the content of this tile, in a way that can be
/// (reasonably) efficiently hashed and compared.
pub current_descriptor: TileDescriptor,
/// The content descriptor for this tile from the previous frame.
pub prev_descriptor: TileDescriptor,
/// Handle to the backing surface for this tile.
pub surface: Option<TileSurface>,
/// If true, this tile is marked valid, and the existing texture
/// cache handle can be used. Tiles are invalidated during the
/// build_dirty_regions method.
pub is_valid: bool,
/// If true, this tile intersects with the currently visible screen
/// rect, and will be drawn.
pub is_visible: bool,
/// The current fractional offset of the cache transform root. If this changes,
/// all tiles need to be invalidated and redrawn, since snapping differences are
/// likely to occur.
fract_offset: PictureVector2D,
/// The tile id is stable between display lists and / or frames,
/// if the tile is retained. Useful for debugging tile evictions.
pub id: TileId,
/// If true, the tile was determined to be opaque, which means blending
/// can be disabled when drawing it.
pub is_opaque: bool,
/// Root node of the quadtree dirty rect tracker.
root: TileNode,
/// The last rendered background color on this tile.
background_color: Option<ColorF>,
/// The first reason the tile was invalidated this frame.
invalidation_reason: Option<InvalidationReason>,
/// If true, this tile has one or more compositor surfaces affecting it.
pub has_compositor_surface: bool,
/// The local space valid rect for any primitives found prior to the first compositor
/// surface that affects this tile.
bg_local_valid_rect: PictureRect,
/// The local space valid rect for any primitives found after the first compositor
/// surface that affects this tile.
fg_local_valid_rect: PictureRect,
/// z-buffer id for this tile, which is one of z_id_opaque or z_id_alpha, depending on tile opacity
pub z_id: ZBufferId,
}
impl Tile {
/// Construct a new, invalid tile.
fn new(tile_offset: TileOffset) -> Self {
let id = TileId(NEXT_TILE_ID.fetch_add(1, Ordering::Relaxed));
Tile {
tile_offset,
local_tile_rect: PictureRect::zero(),
world_tile_rect: WorldRect::zero(),
device_valid_rect: DeviceRect::zero(),
local_dirty_rect: PictureRect::zero(),
device_dirty_rect: DeviceRect::zero(),
surface: None,
current_descriptor: TileDescriptor::new(),
prev_descriptor: TileDescriptor::new(),
is_valid: false,
is_visible: false,
fract_offset: PictureVector2D::zero(),
id,
is_opaque: false,
root: TileNode::new_leaf(Vec::new()),
background_color: None,
invalidation_reason: None,
has_compositor_surface: false,
bg_local_valid_rect: PictureRect::zero(),
fg_local_valid_rect: PictureRect::zero(),
z_id: ZBufferId::invalid(),
}
}
/// Print debug information about this tile to a tree printer.
fn print(&self, pt: &mut dyn PrintTreePrinter) {
pt.new_level(format!("Tile {:?}", self.id));
pt.add_item(format!("local_tile_rect: {}", self.local_tile_rect));
pt.add_item(format!("fract_offset: {:?}", self.fract_offset));
pt.add_item(format!("background_color: {:?}", self.background_color));
pt.add_item(format!("invalidation_reason: {:?}", self.invalidation_reason));
self.current_descriptor.print(pt);
pt.end_level();
}
/// Check if the content of the previous and current tile descriptors match
fn update_dirty_rects(
&mut self,
ctx: &TilePostUpdateContext,
state: &mut TilePostUpdateState,
invalidation_reason: &mut Option<InvalidationReason>,
frame_context: &FrameVisibilityContext,
) -> PictureRect {
let mut prim_comparer = PrimitiveComparer::new(
&self.prev_descriptor,
&self.current_descriptor,
state.resource_cache,
ctx.spatial_nodes,
ctx.opacity_bindings,
ctx.color_bindings,
);
let mut dirty_rect = PictureRect::zero();
self.root.update_dirty_rects(
&self.prev_descriptor.prims,
&self.current_descriptor.prims,
&mut prim_comparer,
&mut dirty_rect,
state.compare_cache,
invalidation_reason,
frame_context,
);
dirty_rect
}
/// Invalidate a tile based on change in content. This
/// must be called even if the tile is not currently
/// visible on screen. We might be able to improve this
/// later by changing how ComparableVec is used.
fn update_content_validity(
&mut self,
ctx: &TilePostUpdateContext,
state: &mut TilePostUpdateState,
frame_context: &FrameVisibilityContext,
) {
// Check if the contents of the primitives, clips, and
// other dependencies are the same.
state.compare_cache.clear();
let mut invalidation_reason = None;
let dirty_rect = self.update_dirty_rects(
ctx,
state,
&mut invalidation_reason,
frame_context,
);
if !dirty_rect.is_empty() {
self.invalidate(
Some(dirty_rect),
invalidation_reason.expect("bug: no invalidation_reason"),
);
}
// TODO(gw): We can avoid invalidating the whole tile in some cases here,
// but it should be a fairly rare invalidation case.
if self.current_descriptor.local_valid_rect != self.prev_descriptor.local_valid_rect {
self.invalidate(None, InvalidationReason::ValidRectChanged);