-
Notifications
You must be signed in to change notification settings - Fork 54
/
render_backend.rs
1875 lines (1658 loc) · 72 KB
/
render_backend.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/. */
//! The high-level module responsible for managing the pipeline and preparing
//! commands to be issued by the `Renderer`.
//!
//! See the comment at the top of the `renderer` module for a description of
//! how these two pieces interact.
use api::{ApiMsg, BuiltDisplayList, ClearCache, DebugCommand, DebugFlags};
#[cfg(feature = "debugger")]
use api::{BuiltDisplayListIter, DisplayItem};
use api::{DocumentId, DocumentLayer, ExternalScrollId, FrameMsg, HitTestFlags, HitTestResult};
use api::{IdNamespace, MemoryReport, PipelineId, RenderNotifier, SceneMsg, ScrollClamping};
use api::{ScrollLocation, ScrollNodeState, TransactionMsg, ResourceUpdate, BlobImageKey};
use api::{NotificationRequest, Checkpoint};
use api::{ClipIntern, FilterDataIntern, PrimitiveKeyKind};
use api::units::*;
use api::channel::{MsgReceiver, MsgSender, Payload};
#[cfg(feature = "capture")]
use api::CaptureBits;
#[cfg(feature = "replay")]
use api::CapturedDocument;
use crate::clip_scroll_tree::{SpatialNodeIndex, ClipScrollTree};
#[cfg(feature = "debugger")]
use crate::debug_server;
use crate::frame_builder::{FrameBuilder, FrameBuilderConfig};
use crate::glyph_rasterizer::{FontInstance};
use crate::gpu_cache::GpuCache;
use crate::hit_test::{HitTest, HitTester};
use crate::intern::DataStore;
use crate::internal_types::{DebugOutput, FastHashMap, FastHashSet, RenderedDocument, ResultMsg};
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use crate::picture::RetainedTiles;
use crate::prim_store::{PrimitiveScratchBuffer, PrimitiveInstance};
use crate::prim_store::{PrimitiveInstanceKind, PrimTemplateCommonData};
use crate::prim_store::interned::*;
use crate::profiler::{BackendProfileCounters, IpcProfileCounters, ResourceProfileCounters};
use crate::record::ApiRecordingReceiver;
use crate::render_task::RenderTaskGraphCounters;
use crate::renderer::{AsyncPropertySampler, PipelineInfo};
use crate::resource_cache::ResourceCache;
#[cfg(feature = "replay")]
use crate::resource_cache::PlainCacheOwn;
#[cfg(any(feature = "capture", feature = "replay"))]
use crate::resource_cache::PlainResources;
use crate::scene::{Scene, SceneProperties};
use crate::scene_builder::*;
#[cfg(feature = "serialize")]
use serde::{Serialize, Deserialize};
#[cfg(feature = "debugger")]
use serde_json;
#[cfg(any(feature = "capture", feature = "replay"))]
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{channel, Sender, Receiver};
use std::time::{UNIX_EPOCH, SystemTime};
use std::u32;
#[cfg(feature = "replay")]
use crate::tiling::Frame;
use time::precise_time_ns;
use crate::util::{Recycler, VecHelper, drain_filter};
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
#[derive(Clone)]
pub struct DocumentView {
pub device_rect: DeviceIntRect,
pub layer: DocumentLayer,
pub pan: DeviceIntPoint,
pub device_pixel_ratio: f32,
pub page_zoom_factor: f32,
pub pinch_zoom_factor: f32,
}
impl DocumentView {
pub fn accumulated_scale_factor(&self) -> DevicePixelScale {
DevicePixelScale::new(
self.device_pixel_ratio *
self.page_zoom_factor *
self.pinch_zoom_factor
)
}
}
#[derive(Copy, Clone, Hash, MallocSizeOf, PartialEq, PartialOrd, Debug, Eq, Ord)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct FrameId(usize);
impl FrameId {
/// Returns a FrameId corresponding to the first frame.
///
/// Note that we use 0 as the internal id here because the current code
/// increments the frame id at the beginning of the frame, rather than
/// at the end, and we want the first frame to be 1. It would probably
/// be sensible to move the advance() call to after frame-building, and
/// then make this method return FrameId(1).
pub fn first() -> Self {
FrameId(0)
}
/// Returns the backing usize for this FrameId.
pub fn as_usize(&self) -> usize {
self.0
}
/// Advances this FrameId to the next frame.
pub fn advance(&mut self) {
self.0 += 1;
}
/// An invalid sentinel FrameId, which will always compare less than
/// any valid FrameId.
pub const INVALID: FrameId = FrameId(0);
}
impl ::std::ops::Add<usize> for FrameId {
type Output = Self;
fn add(self, other: usize) -> FrameId {
FrameId(self.0 + other)
}
}
impl ::std::ops::Sub<usize> for FrameId {
type Output = Self;
fn sub(self, other: usize) -> FrameId {
assert!(self.0 >= other, "Underflow subtracting FrameIds");
FrameId(self.0 - other)
}
}
/// Identifier to track a sequence of frames.
///
/// This is effectively a `FrameId` with a ridealong timestamp corresponding
/// to when advance() was called, which allows for more nuanced cache eviction
/// decisions. As such, we use the `FrameId` for equality and comparison, since
/// we should never have two `FrameStamps` with the same id but different
/// timestamps.
#[derive(Copy, Clone, Debug, MallocSizeOf)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub struct FrameStamp {
id: FrameId,
time: SystemTime,
document_id: DocumentId,
}
impl Eq for FrameStamp {}
impl PartialEq for FrameStamp {
fn eq(&self, other: &Self) -> bool {
// We should not be checking equality unless the documents are the same
debug_assert!(self.document_id == other.document_id);
self.id == other.id
}
}
impl PartialOrd for FrameStamp {
fn partial_cmp(&self, other: &Self) -> Option<::std::cmp::Ordering> {
self.id.partial_cmp(&other.id)
}
}
impl FrameStamp {
/// Gets the FrameId in this stamp.
pub fn frame_id(&self) -> FrameId {
self.id
}
/// Gets the time associated with this FrameStamp.
pub fn time(&self) -> SystemTime {
self.time
}
/// Gets the DocumentId in this stamp.
pub fn document_id(&self) -> DocumentId {
self.document_id
}
pub fn is_valid(&self) -> bool {
// If any fields are their default values, the whole struct should equal INVALID
debug_assert!((self.time != UNIX_EPOCH && self.id != FrameId(0) && self.document_id != DocumentId::INVALID) ||
*self == Self::INVALID);
self.document_id != DocumentId::INVALID
}
/// Returns a FrameStamp corresponding to the first frame.
pub fn first(document_id: DocumentId) -> Self {
FrameStamp {
id: FrameId::first(),
time: SystemTime::now(),
document_id: document_id,
}
}
/// Advances to a new frame.
pub fn advance(&mut self) {
self.id.advance();
self.time = SystemTime::now();
}
/// An invalid sentinel FrameStamp.
pub const INVALID: FrameStamp = FrameStamp {
id: FrameId(0),
time: UNIX_EPOCH,
document_id: DocumentId::INVALID,
};
}
macro_rules! declare_data_stores {
( $( $name:ident : $ty:ty, )+ ) => {
/// A collection of resources that are shared by clips, primitives
/// between display lists.
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
#[derive(Default)]
pub struct DataStores {
$(
pub $name: DataStore<$ty>,
)+
}
impl DataStores {
/// Reports CPU heap usage.
fn report_memory(&self, ops: &mut MallocSizeOfOps, r: &mut MemoryReport) {
$(
r.interning.data_stores.$name += self.$name.size_of(ops);
)+
}
fn apply_updates(
&mut self,
updates: InternerUpdates,
profile_counters: &mut BackendProfileCounters,
) {
$(
self.$name.apply_updates(
updates.$name,
&mut profile_counters.intern.$name,
);
)+
}
}
}
}
enumerate_interners!(declare_data_stores);
impl DataStores {
pub fn as_common_data(
&self,
prim_inst: &PrimitiveInstance
) -> &PrimTemplateCommonData {
match prim_inst.kind {
PrimitiveInstanceKind::Rectangle { data_handle, .. } |
PrimitiveInstanceKind::Clear { data_handle, .. } => {
let prim_data = &self.prim[data_handle];
&prim_data.common
}
PrimitiveInstanceKind::Image { data_handle, .. } => {
let prim_data = &self.image[data_handle];
&prim_data.common
}
PrimitiveInstanceKind::ImageBorder { data_handle, .. } => {
let prim_data = &self.image_border[data_handle];
&prim_data.common
}
PrimitiveInstanceKind::LineDecoration { data_handle, .. } => {
let prim_data = &self.line_decoration[data_handle];
&prim_data.common
}
PrimitiveInstanceKind::LinearGradient { data_handle, .. } => {
let prim_data = &self.linear_grad[data_handle];
&prim_data.common
}
PrimitiveInstanceKind::NormalBorder { data_handle, .. } => {
let prim_data = &self.normal_border[data_handle];
&prim_data.common
}
PrimitiveInstanceKind::Picture { data_handle, .. } => {
let prim_data = &self.picture[data_handle];
&prim_data.common
}
PrimitiveInstanceKind::RadialGradient { data_handle, .. } => {
let prim_data = &self.radial_grad[data_handle];
&prim_data.common
}
PrimitiveInstanceKind::TextRun { data_handle, .. } => {
let prim_data = &self.text_run[data_handle];
&prim_data.common
}
PrimitiveInstanceKind::YuvImage { data_handle, .. } => {
let prim_data = &self.yuv_image[data_handle];
&prim_data.common
}
}
}
}
struct Document {
// The id of this document
id: DocumentId,
// The latest built scene, usable to build frames.
// received from the scene builder thread.
scene: Scene,
// Temporary list of removed pipelines received from the scene builder
// thread and forwarded to the renderer.
removed_pipelines: Vec<(PipelineId, DocumentId)>,
view: DocumentView,
/// The ClipScrollTree for this document which tracks SpatialNodes, ClipNodes, and ClipChains.
/// This is stored here so that we are able to preserve scrolling positions between rendered
/// frames.
clip_scroll_tree: ClipScrollTree,
/// The id and time of the current frame.
stamp: FrameStamp,
// the `Option` here is only to deal with borrow checker
frame_builder: Option<FrameBuilder>,
// A set of pipelines that the caller has requested be
// made available as output textures.
output_pipelines: FastHashSet<PipelineId>,
/// A data structure to allow hit testing against rendered frames. This is updated
/// every time we produce a fully rendered frame.
hit_tester: Option<HitTester>,
/// Properties that are resolved during frame building and can be changed at any time
/// without requiring the scene to be re-built.
dynamic_properties: SceneProperties,
/// Track whether the last built frame is up to date or if it will need to be re-built
/// before rendering again.
frame_is_valid: bool,
hit_tester_is_valid: bool,
rendered_frame_is_valid: bool,
// We track this information to be able to display debugging information from the
// renderer.
has_built_scene: bool,
data_stores: DataStores,
/// Contains various vecs of data that is used only during frame building,
/// where we want to recycle the memory each new display list, to avoid constantly
/// re-allocating and moving memory around.
scratch: PrimitiveScratchBuffer,
/// Keep track of the size of render task graph to pre-allocate memory up-front
/// the next frame.
render_task_counters: RenderTaskGraphCounters,
}
impl Document {
pub fn new(
id: DocumentId,
size: DeviceIntSize,
layer: DocumentLayer,
default_device_pixel_ratio: f32,
) -> Self {
Document {
id,
scene: Scene::new(),
removed_pipelines: Vec::new(),
view: DocumentView {
device_rect: size.into(),
layer,
pan: DeviceIntPoint::zero(),
page_zoom_factor: 1.0,
pinch_zoom_factor: 1.0,
device_pixel_ratio: default_device_pixel_ratio,
},
clip_scroll_tree: ClipScrollTree::new(),
stamp: FrameStamp::first(id),
frame_builder: None,
output_pipelines: FastHashSet::default(),
hit_tester: None,
dynamic_properties: SceneProperties::new(),
frame_is_valid: false,
hit_tester_is_valid: false,
rendered_frame_is_valid: false,
has_built_scene: false,
data_stores: DataStores::default(),
scratch: PrimitiveScratchBuffer::new(),
render_task_counters: RenderTaskGraphCounters::new(),
}
}
fn can_render(&self) -> bool {
self.frame_builder.is_some() && self.scene.has_root_pipeline()
}
fn has_pixels(&self) -> bool {
!self.view.device_rect.size.is_empty_or_negative()
}
fn process_frame_msg(
&mut self,
message: FrameMsg,
) -> DocumentOps {
match message {
FrameMsg::UpdateEpoch(pipeline_id, epoch) => {
self.scene.update_epoch(pipeline_id, epoch);
}
FrameMsg::Scroll(delta, cursor) => {
profile_scope!("Scroll");
let node_index = match self.hit_tester {
Some(ref hit_tester) => {
// Ideally we would call self.scroll_nearest_scrolling_ancestor here, but
// we need have to avoid a double-borrow.
let test = HitTest::new(None, cursor, HitTestFlags::empty());
hit_tester.find_node_under_point(test)
}
None => {
None
}
};
if self.hit_tester.is_some() {
if self.scroll_nearest_scrolling_ancestor(delta, node_index) {
self.hit_tester_is_valid = false;
self.frame_is_valid = false;
}
}
return DocumentOps {
// TODO: Does it make sense to track this as a scrolling even if we
// ended up not scrolling anything?
scroll: true,
..DocumentOps::nop()
};
}
FrameMsg::HitTest(pipeline_id, point, flags, tx) => {
if !self.hit_tester_is_valid {
self.rebuild_hit_tester();
}
let result = match self.hit_tester {
Some(ref hit_tester) => {
hit_tester.hit_test(HitTest::new(pipeline_id, point, flags))
}
None => HitTestResult { items: Vec::new() },
};
tx.send(result).unwrap();
}
FrameMsg::SetPan(pan) => {
if self.view.pan != pan {
self.view.pan = pan;
self.hit_tester_is_valid = false;
self.frame_is_valid = false;
}
}
FrameMsg::ScrollNodeWithId(origin, id, clamp) => {
profile_scope!("ScrollNodeWithScrollId");
if self.scroll_node(origin, id, clamp) {
self.hit_tester_is_valid = false;
self.frame_is_valid = false;
}
return DocumentOps {
scroll: true,
..DocumentOps::nop()
};
}
FrameMsg::GetScrollNodeState(tx) => {
profile_scope!("GetScrollNodeState");
tx.send(self.get_scroll_node_state()).unwrap();
}
FrameMsg::UpdateDynamicProperties(property_bindings) => {
self.dynamic_properties.set_properties(property_bindings);
}
FrameMsg::AppendDynamicProperties(property_bindings) => {
self.dynamic_properties.add_properties(property_bindings);
}
FrameMsg::SetPinchZoom(factor) => {
if self.view.pinch_zoom_factor != factor.get() {
self.view.pinch_zoom_factor = factor.get();
self.frame_is_valid = false;
}
}
}
DocumentOps::nop()
}
fn build_frame(
&mut self,
resource_cache: &mut ResourceCache,
gpu_cache: &mut GpuCache,
resource_profile: &mut ResourceProfileCounters,
debug_flags: DebugFlags,
) -> RenderedDocument {
let accumulated_scale_factor = self.view.accumulated_scale_factor();
let pan = self.view.pan.to_f32() / accumulated_scale_factor;
// Advance to the next frame.
self.stamp.advance();
assert!(self.stamp.frame_id() != FrameId::INVALID,
"First frame increment must happen before build_frame()");
let frame = {
let frame_builder = self.frame_builder.as_mut().unwrap();
let frame = frame_builder.build(
resource_cache,
gpu_cache,
self.stamp,
&mut self.clip_scroll_tree,
&self.scene.pipelines,
accumulated_scale_factor,
self.view.layer,
self.view.device_rect.origin,
pan,
&mut resource_profile.texture_cache,
&mut resource_profile.gpu_cache,
&self.dynamic_properties,
&mut self.data_stores,
&mut self.scratch,
&mut self.render_task_counters,
debug_flags,
);
self.hit_tester = Some(frame_builder.create_hit_tester(
&self.clip_scroll_tree,
&self.data_stores.clip,
));
frame
};
self.frame_is_valid = true;
self.hit_tester_is_valid = true;
let is_new_scene = self.has_built_scene;
self.has_built_scene = false;
RenderedDocument {
frame,
is_new_scene,
}
}
fn rebuild_hit_tester(&mut self) {
if let Some(ref mut frame_builder) = self.frame_builder {
let accumulated_scale_factor = self.view.accumulated_scale_factor();
let pan = self.view.pan.to_f32() / accumulated_scale_factor;
self.clip_scroll_tree.update_tree(
pan,
&self.dynamic_properties,
);
self.hit_tester = Some(frame_builder.create_hit_tester(
&self.clip_scroll_tree,
&self.data_stores.clip,
));
self.hit_tester_is_valid = true;
}
}
pub fn updated_pipeline_info(&mut self) -> PipelineInfo {
let removed_pipelines = self.removed_pipelines.take_and_preallocate();
PipelineInfo {
epochs: self.scene.pipeline_epochs.iter()
.map(|(&pipeline_id, &epoch)| ((pipeline_id, self.id), epoch)).collect(),
removed_pipelines,
}
}
pub fn discard_frame_state_for_pipeline(&mut self, pipeline_id: PipelineId) {
self.clip_scroll_tree
.discard_frame_state_for_pipeline(pipeline_id);
}
/// Returns true if any nodes actually changed position or false otherwise.
pub fn scroll_nearest_scrolling_ancestor(
&mut self,
scroll_location: ScrollLocation,
scroll_node_index: Option<SpatialNodeIndex>,
) -> bool {
self.clip_scroll_tree.scroll_nearest_scrolling_ancestor(scroll_location, scroll_node_index)
}
/// Returns true if the node actually changed position or false otherwise.
pub fn scroll_node(
&mut self,
origin: LayoutPoint,
id: ExternalScrollId,
clamp: ScrollClamping
) -> bool {
self.clip_scroll_tree.scroll_node(origin, id, clamp)
}
pub fn get_scroll_node_state(&self) -> Vec<ScrollNodeState> {
self.clip_scroll_tree.get_scroll_node_state()
}
pub fn new_async_scene_ready(
&mut self,
mut built_scene: BuiltScene,
recycler: &mut Recycler,
) {
self.scene = built_scene.scene;
self.frame_is_valid = false;
self.hit_tester_is_valid = false;
// Give the old frame builder a chance to destroy any resources.
// Right now, all this does is build a hash map of any cached
// surface tiles, that can be provided to the next frame builder.
let mut retained_tiles = RetainedTiles::new();
if let Some(frame_builder) = self.frame_builder.take() {
let globals = frame_builder.destroy(
&mut retained_tiles,
&self.clip_scroll_tree,
);
// Provide any cached tiles from the previous frame builder to
// the newly built one.
built_scene.frame_builder.set_retained_resources(
retained_tiles,
globals,
);
}
self.frame_builder = Some(built_scene.frame_builder);
self.scratch.recycle(recycler);
let old_scrolling_states = self.clip_scroll_tree.drain();
self.clip_scroll_tree = built_scene.clip_scroll_tree;
self.clip_scroll_tree.finalize_and_apply_pending_scroll_offsets(old_scrolling_states);
}
}
struct DocumentOps {
scroll: bool,
}
impl DocumentOps {
fn nop() -> Self {
DocumentOps {
scroll: false,
}
}
}
/// The unique id for WR resource identification.
/// The namespace_id should start from 1.
static NEXT_NAMESPACE_ID: AtomicUsize = AtomicUsize::new(1);
#[cfg(any(feature = "capture", feature = "replay"))]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
struct PlainRenderBackend {
default_device_pixel_ratio: f32,
frame_config: FrameBuilderConfig,
documents: FastHashMap<DocumentId, DocumentView>,
resources: PlainResources,
}
/// The render backend is responsible for transforming high level display lists into
/// GPU-friendly work which is then submitted to the renderer in the form of a frame::Frame.
///
/// The render backend operates on its own thread.
pub struct RenderBackend {
api_rx: MsgReceiver<ApiMsg>,
payload_rx: Receiver<Payload>,
result_tx: Sender<ResultMsg>,
scene_tx: Sender<SceneBuilderRequest>,
low_priority_scene_tx: Sender<SceneBuilderRequest>,
scene_rx: Receiver<SceneBuilderResult>,
payload_buffer: Vec<Payload>,
default_device_pixel_ratio: f32,
gpu_cache: GpuCache,
resource_cache: ResourceCache,
frame_config: FrameBuilderConfig,
documents: FastHashMap<DocumentId, Document>,
notifier: Box<RenderNotifier>,
recorder: Option<Box<ApiRecordingReceiver>>,
sampler: Option<Box<AsyncPropertySampler + Send>>,
size_of_ops: Option<MallocSizeOfOps>,
debug_flags: DebugFlags,
namespace_alloc_by_client: bool,
recycler: Recycler,
}
impl RenderBackend {
pub fn new(
api_rx: MsgReceiver<ApiMsg>,
payload_rx: Receiver<Payload>,
result_tx: Sender<ResultMsg>,
scene_tx: Sender<SceneBuilderRequest>,
low_priority_scene_tx: Sender<SceneBuilderRequest>,
scene_rx: Receiver<SceneBuilderResult>,
default_device_pixel_ratio: f32,
resource_cache: ResourceCache,
notifier: Box<RenderNotifier>,
frame_config: FrameBuilderConfig,
recorder: Option<Box<ApiRecordingReceiver>>,
sampler: Option<Box<AsyncPropertySampler + Send>>,
size_of_ops: Option<MallocSizeOfOps>,
debug_flags: DebugFlags,
namespace_alloc_by_client: bool,
) -> RenderBackend {
RenderBackend {
api_rx,
payload_rx,
result_tx,
scene_tx,
low_priority_scene_tx,
scene_rx,
payload_buffer: Vec::new(),
default_device_pixel_ratio,
resource_cache,
gpu_cache: GpuCache::new(),
frame_config,
documents: FastHashMap::default(),
notifier,
recorder,
sampler,
size_of_ops,
debug_flags,
namespace_alloc_by_client,
recycler: Recycler::new(),
}
}
fn process_scene_msg(
&mut self,
document_id: DocumentId,
message: SceneMsg,
frame_counter: u32,
txn: &mut Transaction,
ipc_profile_counters: &mut IpcProfileCounters,
) {
let doc = self.documents.get_mut(&document_id).expect("No document?");
match message {
SceneMsg::UpdateEpoch(pipeline_id, epoch) => {
txn.epoch_updates.push((pipeline_id, epoch));
}
SceneMsg::SetPageZoom(factor) => {
doc.view.page_zoom_factor = factor.get();
}
SceneMsg::SetDocumentView {
device_rect,
device_pixel_ratio,
} => {
doc.view.device_rect = device_rect;
doc.view.device_pixel_ratio = device_pixel_ratio;
}
SceneMsg::SetDisplayList {
epoch,
pipeline_id,
background,
viewport_size,
content_size,
list_descriptor,
preserve_frame_state,
} => {
profile_scope!("SetDisplayList");
let data = if let Some(idx) = self.payload_buffer.iter().position(|data|
data.epoch == epoch && data.pipeline_id == pipeline_id
) {
self.payload_buffer.swap_remove(idx)
} else {
loop {
let data = self.payload_rx.recv().unwrap();
if data.epoch == epoch && data.pipeline_id == pipeline_id {
break data;
} else {
self.payload_buffer.push(data);
}
}
};
if let Some(ref mut r) = self.recorder {
r.write_payload(frame_counter, &data.to_data());
}
let built_display_list =
BuiltDisplayList::from_data(data.display_list_data, list_descriptor);
if !preserve_frame_state {
doc.discard_frame_state_for_pipeline(pipeline_id);
}
let display_list_len = built_display_list.data().len();
let (builder_start_time, builder_finish_time, send_start_time) =
built_display_list.times();
let display_list_received_time = precise_time_ns();
txn.display_list_updates.push(DisplayListUpdate {
built_display_list,
pipeline_id,
epoch,
background,
viewport_size,
content_size,
});
// Note: this isn't quite right as auxiliary values will be
// pulled out somewhere in the prim_store, but aux values are
// really simple and cheap to access, so it's not a big deal.
let display_list_consumed_time = precise_time_ns();
ipc_profile_counters.set(
builder_start_time,
builder_finish_time,
send_start_time,
display_list_received_time,
display_list_consumed_time,
display_list_len,
);
}
SceneMsg::SetRootPipeline(pipeline_id) => {
profile_scope!("SetRootPipeline");
txn.set_root_pipeline = Some(pipeline_id);
}
SceneMsg::RemovePipeline(pipeline_id) => {
profile_scope!("RemovePipeline");
txn.removed_pipelines.push((pipeline_id, document_id));
}
SceneMsg::EnableFrameOutput(pipeline_id, enable) => {
if enable {
doc.output_pipelines.insert(pipeline_id);
} else {
doc.output_pipelines.remove(&pipeline_id);
}
}
}
}
fn next_namespace_id(&self) -> IdNamespace {
IdNamespace(NEXT_NAMESPACE_ID.fetch_add(1, Ordering::Relaxed) as u32)
}
pub fn run(&mut self, mut profile_counters: BackendProfileCounters) {
let mut frame_counter: u32 = 0;
let mut keep_going = true;
if let Some(ref sampler) = self.sampler {
sampler.register();
}
while keep_going {
profile_scope!("handle_msg");
while let Ok(msg) = self.scene_rx.try_recv() {
match msg {
SceneBuilderResult::Transactions(mut txns, result_tx) => {
self.prepare_for_frames();
self.maybe_force_nop_documents(
&mut frame_counter,
&mut profile_counters,
|document_id| txns.iter().any(|txn| txn.document_id == document_id));
for mut txn in txns.drain(..) {
let has_built_scene = txn.built_scene.is_some();
if let Some(doc) = self.documents.get_mut(&txn.document_id) {
doc.removed_pipelines.append(&mut txn.removed_pipelines);
if let Some(built_scene) = txn.built_scene.take() {
doc.new_async_scene_ready(
built_scene,
&mut self.recycler,
);
}
if let Some(ref tx) = result_tx {
let (resume_tx, resume_rx) = channel();
tx.send(SceneSwapResult::Complete(resume_tx)).unwrap();
// Block until the post-swap hook has completed on
// the scene builder thread. We need to do this before
// we can sample from the sampler hook which might happen
// in the update_document call below.
resume_rx.recv().ok();
}
} else {
// The document was removed while we were building it, skip it.
// TODO: we might want to just ensure that removed documents are
// always forwarded to the scene builder thread to avoid this case.
if let Some(ref tx) = result_tx {
tx.send(SceneSwapResult::Aborted).unwrap();
}
continue;
}
self.resource_cache.add_rasterized_blob_images(
txn.rasterized_blobs.take()
);
if let Some((rasterizer, info)) = txn.blob_rasterizer.take() {
self.resource_cache.set_blob_rasterizer(rasterizer, info);
}
self.update_document(
txn.document_id,
txn.resource_updates.take(),
txn.interner_updates.take(),
txn.frame_ops.take(),
txn.notifications.take(),
txn.render_frame,
txn.invalidate_rendered_frame,
&mut frame_counter,
&mut profile_counters,
has_built_scene,
);
}
self.bookkeep_after_frames();
},
SceneBuilderResult::FlushComplete(tx) => {
tx.send(()).ok();
}
SceneBuilderResult::ExternalEvent(evt) => {
self.notifier.external_event(evt);
}
SceneBuilderResult::ClearNamespace(id) => {
self.resource_cache.clear_namespace(id);
self.documents.retain(|doc_id, _doc| doc_id.namespace_id != id);
}
SceneBuilderResult::Stopped => {
panic!("We haven't sent a Stop yet, how did we get a Stopped back?");
}
}
}
keep_going = match self.api_rx.recv() {
Ok(msg) => {
if let Some(ref mut r) = self.recorder {
r.write_msg(frame_counter, &msg);
}
self.process_api_msg(msg, &mut profile_counters, &mut frame_counter)
}
Err(..) => { false }
};
}
let _ = self.low_priority_scene_tx.send(SceneBuilderRequest::Stop);
// Ensure we read everything the scene builder is sending us from
// inflight messages, otherwise the scene builder might panic.
while let Ok(msg) = self.scene_rx.recv() {
match msg {
SceneBuilderResult::FlushComplete(tx) => {
// If somebody's blocked waiting for a flush, how did they
// trigger the RB thread to shut down? This shouldn't happen
// but handle it gracefully anyway.
debug_assert!(false);
tx.send(()).ok();
}
SceneBuilderResult::Stopped => break,
_ => continue,
}
}
self.notifier.shut_down();
if let Some(ref sampler) = self.sampler {
sampler.deregister();
}
}
fn process_api_msg(
&mut self,
msg: ApiMsg,
profile_counters: &mut BackendProfileCounters,
frame_counter: &mut u32,
) -> bool {
match msg {
ApiMsg::WakeUp => {}
ApiMsg::WakeSceneBuilder => {
self.scene_tx.send(SceneBuilderRequest::WakeUp).unwrap();
}
ApiMsg::FlushSceneBuilder(tx) => {
self.low_priority_scene_tx.send(SceneBuilderRequest::Flush(tx)).unwrap();
}
ApiMsg::UpdateResources(mut updates) => {
self.resource_cache.pre_scene_building_update(
&mut updates,
&mut profile_counters.resources
);
self.resource_cache.post_scene_building_update(
updates,
&mut profile_counters.resources
);
}