-
Notifications
You must be signed in to change notification settings - Fork 265
/
renderer.rs
2166 lines (1915 loc) · 91.8 KB
/
renderer.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 webrender API.
//!
//! The `webrender::renderer` module provides the interface to webrender, which
//! is accessible through [`Renderer`][renderer]
//!
//! [renderer]: struct.Renderer.html
use debug_colors;
use debug_render::DebugRenderer;
use device::{DepthFunction, Device, FrameId, ProgramId, TextureId, VertexFormat, GpuMarker, GpuProfiler};
use device::{GpuSample, TextureFilter, VAOId, VertexUsageHint, FileWatcherHandler, TextureTarget, ShaderError};
use euclid::Matrix4D;
use fnv::FnvHasher;
use frame_builder::FrameBuilderConfig;
use gleam::gl;
use gpu_store::{GpuStore, GpuStoreLayout};
use internal_types::{CacheTextureId, RendererFrame, ResultMsg, TextureUpdateOp};
use internal_types::{TextureUpdateList, PackedVertex, RenderTargetMode};
use internal_types::{ORTHO_NEAR_PLANE, ORTHO_FAR_PLANE, SourceTexture};
use internal_types::{BatchTextures, TextureSampler};
use prim_store::GradientData;
use profiler::{Profiler, BackendProfileCounters};
use profiler::{GpuProfileTag, RendererProfileTimers, RendererProfileCounters};
use record::ApiRecordingReceiver;
use render_backend::RenderBackend;
use render_task::RenderTaskData;
use std;
use std::cmp;
use std::collections::{HashMap, VecDeque};
use std::f32;
use std::hash::BuildHasherDefault;
use std::marker::PhantomData;
use std::mem;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::thread;
use texture_cache::TextureCache;
use threadpool::ThreadPool;
use tiling::{AlphaBatchKind, BlurCommand, Frame, PrimitiveBatch, RenderTarget};
use tiling::{AlphaRenderTarget, CacheClipInstance, PrimitiveInstance, ColorRenderTarget, RenderTargetKind};
use time::precise_time_ns;
use thread_profiler::{register_thread_with_profiler, write_profile};
use util::TransformedRectKind;
use webgl_types::GLContextHandleWrapper;
use webrender_traits::{ColorF, Epoch, PipelineId, RenderNotifier, RenderDispatcher};
use webrender_traits::{ExternalImageId, ExternalImageType, ImageData, ImageFormat, RenderApiSender};
use webrender_traits::{DeviceIntRect, DevicePoint, DeviceIntPoint, DeviceIntSize, DeviceUintSize};
use webrender_traits::{ImageDescriptor, BlobImageRenderer};
use webrender_traits::channel;
use webrender_traits::VRCompositorHandler;
use webrender_traits::{YuvColorSpace, YuvFormat};
use webrender_traits::{YUV_COLOR_SPACES, YUV_FORMATS};
pub const GPU_DATA_TEXTURE_POOL: usize = 5;
pub const MAX_VERTEX_TEXTURE_WIDTH: usize = 1024;
const GPU_TAG_CACHE_BOX_SHADOW: GpuProfileTag = GpuProfileTag { label: "C_BoxShadow", color: debug_colors::BLACK };
const GPU_TAG_CACHE_CLIP: GpuProfileTag = GpuProfileTag { label: "C_Clip", color: debug_colors::PURPLE };
const GPU_TAG_CACHE_TEXT_RUN: GpuProfileTag = GpuProfileTag { label: "C_TextRun", color: debug_colors::MISTYROSE };
const GPU_TAG_INIT: GpuProfileTag = GpuProfileTag { label: "Init", color: debug_colors::WHITE };
const GPU_TAG_SETUP_TARGET: GpuProfileTag = GpuProfileTag { label: "Target", color: debug_colors::SLATEGREY };
const GPU_TAG_PRIM_RECT: GpuProfileTag = GpuProfileTag { label: "Rect", color: debug_colors::RED };
const GPU_TAG_PRIM_IMAGE: GpuProfileTag = GpuProfileTag { label: "Image", color: debug_colors::GREEN };
const GPU_TAG_PRIM_YUV_IMAGE: GpuProfileTag = GpuProfileTag { label: "YuvImage", color: debug_colors::DARKGREEN };
const GPU_TAG_PRIM_BLEND: GpuProfileTag = GpuProfileTag { label: "Blend", color: debug_colors::LIGHTBLUE };
const GPU_TAG_PRIM_HW_COMPOSITE: GpuProfileTag = GpuProfileTag { label: "HwComposite", color: debug_colors::DODGERBLUE };
const GPU_TAG_PRIM_COMPOSITE: GpuProfileTag = GpuProfileTag { label: "Composite", color: debug_colors::MAGENTA };
const GPU_TAG_PRIM_TEXT_RUN: GpuProfileTag = GpuProfileTag { label: "TextRun", color: debug_colors::BLUE };
const GPU_TAG_PRIM_GRADIENT: GpuProfileTag = GpuProfileTag { label: "Gradient", color: debug_colors::YELLOW };
const GPU_TAG_PRIM_ANGLE_GRADIENT: GpuProfileTag = GpuProfileTag { label: "AngleGradient", color: debug_colors::POWDERBLUE };
const GPU_TAG_PRIM_RADIAL_GRADIENT: GpuProfileTag = GpuProfileTag { label: "RadialGradient", color: debug_colors::LIGHTPINK };
const GPU_TAG_PRIM_BOX_SHADOW: GpuProfileTag = GpuProfileTag { label: "BoxShadow", color: debug_colors::CYAN };
const GPU_TAG_PRIM_BORDER: GpuProfileTag = GpuProfileTag { label: "Border", color: debug_colors::ORANGE };
const GPU_TAG_PRIM_BORDER_CORNER: GpuProfileTag = GpuProfileTag { label: "BorderCorner", color: debug_colors::DARKSLATEGREY };
const GPU_TAG_PRIM_BORDER_EDGE: GpuProfileTag = GpuProfileTag { label: "BorderEdge", color: debug_colors::LAVENDER };
const GPU_TAG_PRIM_CACHE_IMAGE: GpuProfileTag = GpuProfileTag { label: "CacheImage", color: debug_colors::SILVER };
const GPU_TAG_BLUR: GpuProfileTag = GpuProfileTag { label: "Blur", color: debug_colors::VIOLET };
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum ImageBufferKind {
Texture2D = 0,
TextureRect = 1,
TextureExternal = 2,
}
pub const IMAGE_BUFFER_KINDS: [ImageBufferKind; 3] = [
ImageBufferKind::Texture2D,
ImageBufferKind::TextureRect,
ImageBufferKind::TextureExternal
];
impl ImageBufferKind {
pub fn get_feature_string(&self) -> &'static str {
match *self {
ImageBufferKind::Texture2D => "",
ImageBufferKind::TextureRect => "TEXTURE_RECT",
ImageBufferKind::TextureExternal => "TEXTURE_EXTERNAL",
}
}
pub fn has_platform_support(&self, gl_type: &gl::GlType) -> bool {
match *gl_type {
gl::GlType::Gles => {
match *self {
ImageBufferKind::Texture2D => true,
ImageBufferKind::TextureRect => true,
ImageBufferKind::TextureExternal => true,
}
}
gl::GlType::Gl => {
match *self {
ImageBufferKind::Texture2D => true,
ImageBufferKind::TextureRect => true,
ImageBufferKind::TextureExternal => false,
}
}
}
}
}
#[derive(Debug, Copy, Clone)]
pub enum RendererKind {
Native,
OSMesa,
}
#[derive(Debug)]
pub struct GpuProfile {
pub frame_id: FrameId,
pub paint_time_ns: u64,
}
impl GpuProfile {
fn new<T>(frame_id: FrameId, samples: &[GpuSample<T>]) -> GpuProfile {
let mut paint_time_ns = 0;
for sample in samples {
paint_time_ns += sample.time_ns;
}
GpuProfile {
frame_id: frame_id,
paint_time_ns: paint_time_ns,
}
}
}
#[derive(Debug)]
pub struct CpuProfile {
pub frame_id: FrameId,
pub composite_time_ns: u64,
pub draw_calls: usize,
}
impl CpuProfile {
fn new(frame_id: FrameId,
composite_time_ns: u64,
draw_calls: usize) -> CpuProfile {
CpuProfile {
frame_id: frame_id,
composite_time_ns: composite_time_ns,
draw_calls: draw_calls,
}
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum BlendMode {
None,
Alpha,
PremultipliedAlpha,
// Use the color of the text itself as a constant color blend factor.
Subpixel(ColorF),
}
struct GpuDataTexture<L> {
id: TextureId,
layout: PhantomData<L>,
}
impl<L: GpuStoreLayout> GpuDataTexture<L> {
fn new(device: &mut Device) -> GpuDataTexture<L> {
let id = device.create_texture_ids(1, TextureTarget::Default)[0];
GpuDataTexture {
id: id,
layout: PhantomData,
}
}
fn init<T: Default>(&mut self,
device: &mut Device,
data: &mut Vec<T>) {
if data.is_empty() {
return;
}
let items_per_row = L::items_per_row::<T>();
let rows_per_item = L::rows_per_item::<T>();
// Extend the data array to be a multiple of the row size.
// This ensures memory safety when the array is passed to
// OpenGL to upload to the GPU.
if items_per_row != 0 {
while data.len() % items_per_row != 0 {
data.push(T::default());
}
}
let height = if items_per_row != 0 {
data.len() / items_per_row
} else {
data.len() * rows_per_item
};
device.init_texture(self.id,
L::texture_width::<T>() as u32,
height as u32,
L::image_format(),
L::texture_filter(),
RenderTargetMode::None,
Some(unsafe { mem::transmute(data.as_slice()) } ));
}
}
pub struct VertexDataTextureLayout {}
impl GpuStoreLayout for VertexDataTextureLayout {
fn image_format() -> ImageFormat {
ImageFormat::RGBAF32
}
fn texture_width<T>() -> usize {
MAX_VERTEX_TEXTURE_WIDTH - (MAX_VERTEX_TEXTURE_WIDTH % Self::texels_per_item::<T>())
}
fn texture_filter() -> TextureFilter {
TextureFilter::Nearest
}
}
type VertexDataTexture = GpuDataTexture<VertexDataTextureLayout>;
pub type VertexDataStore<T> = GpuStore<T, VertexDataTextureLayout>;
pub struct GradientDataTextureLayout {}
impl GpuStoreLayout for GradientDataTextureLayout {
fn image_format() -> ImageFormat {
ImageFormat::RGBA8
}
fn texture_width<T>() -> usize {
mem::size_of::<GradientData>() / Self::texel_size() / 2
}
fn texture_filter() -> TextureFilter {
TextureFilter::Linear
}
}
type GradientDataTexture = GpuDataTexture<GradientDataTextureLayout>;
pub type GradientDataStore = GpuStore<GradientData, GradientDataTextureLayout>;
const TRANSFORM_FEATURE: &'static str = "TRANSFORM";
const SUBPIXEL_AA_FEATURE: &'static str = "SUBPIXEL_AA";
const CLIP_FEATURE: &'static str = "CLIP";
enum ShaderKind {
Primitive,
Cache(VertexFormat),
ClipCache,
}
struct LazilyCompiledShader {
id: Option<ProgramId>,
name: &'static str,
kind: ShaderKind,
features: Vec<&'static str>,
}
impl LazilyCompiledShader {
fn new(kind: ShaderKind,
name: &'static str,
features: &[&'static str],
device: &mut Device,
precache: bool) -> Result<LazilyCompiledShader, ShaderError> {
let mut shader = LazilyCompiledShader {
id: None,
name: name,
kind: kind,
features: features.to_vec(),
};
if precache {
try!{ shader.get(device) };
}
Ok(shader)
}
fn get(&mut self, device: &mut Device) -> Result<ProgramId, ShaderError> {
if self.id.is_none() {
let id = try!{
match self.kind {
ShaderKind::Primitive => {
create_prim_shader(self.name,
device,
&self.features,
VertexFormat::Triangles)
}
ShaderKind::Cache(format) => {
create_prim_shader(self.name,
device,
&self.features,
format)
}
ShaderKind::ClipCache => {
create_clip_shader(self.name, device)
}
}
};
self.id = Some(id);
}
Ok(self.id.unwrap())
}
}
struct PrimitiveShader {
simple: LazilyCompiledShader,
transform: LazilyCompiledShader,
}
struct FileWatcher {
notifier: Arc<Mutex<Option<Box<RenderNotifier>>>>,
result_tx: Sender<ResultMsg>,
}
impl FileWatcherHandler for FileWatcher {
fn file_changed(&self, path: PathBuf) {
self.result_tx.send(ResultMsg::RefreshShader(path)).ok();
let mut notifier = self.notifier.lock();
notifier.as_mut().unwrap().as_mut().unwrap().new_frame_ready();
}
}
fn _get_ubo_max_len<T>(max_ubo_size: usize) -> usize {
let item_size = mem::size_of::<T>();
let max_items = max_ubo_size / item_size;
// TODO(gw): Clamping to 1024 since some shader compilers
// seem to go very slow when you have high
// constants for array lengths. Investigate
// whether this clamping actually hurts performance!
cmp::min(max_items, 1024)
}
impl PrimitiveShader {
fn new(name: &'static str,
device: &mut Device,
features: &[&'static str],
precache: bool) -> Result<PrimitiveShader, ShaderError> {
let simple = try!{
LazilyCompiledShader::new(ShaderKind::Primitive,
name,
features,
device,
precache)
};
let mut transform_features = features.to_vec();
transform_features.push(TRANSFORM_FEATURE);
let transform = try!{
LazilyCompiledShader::new(ShaderKind::Primitive,
name,
&transform_features,
device,
precache)
};
Ok(PrimitiveShader {
simple: simple,
transform: transform,
})
}
fn get(&mut self,
device: &mut Device,
transform_kind: TransformedRectKind) -> Result<ProgramId, ShaderError> {
match transform_kind {
TransformedRectKind::AxisAligned => self.simple.get(device),
TransformedRectKind::Complex => self.transform.get(device),
}
}
}
fn create_prim_shader(name: &'static str,
device: &mut Device,
features: &[&'static str],
vertex_format: VertexFormat) -> Result<ProgramId, ShaderError> {
let mut prefix = format!("#define WR_MAX_VERTEX_TEXTURE_WIDTH {}\n",
MAX_VERTEX_TEXTURE_WIDTH);
for feature in features {
prefix.push_str(&format!("#define WR_FEATURE_{}\n", feature));
}
debug!("PrimShader {}", name);
let includes = &["prim_shared"];
device.create_program_with_prefix(name, includes, Some(prefix), vertex_format)
}
fn create_clip_shader(name: &'static str, device: &mut Device) -> Result<ProgramId, ShaderError> {
let prefix = format!("#define WR_MAX_VERTEX_TEXTURE_WIDTH {}\n
#define WR_FEATURE_TRANSFORM",
MAX_VERTEX_TEXTURE_WIDTH);
debug!("ClipShader {}", name);
let includes = &["prim_shared", "clip_shared"];
device.create_program_with_prefix(name, includes, Some(prefix), VertexFormat::Clip)
}
struct GpuDataTextures {
layer_texture: VertexDataTexture,
render_task_texture: VertexDataTexture,
prim_geom_texture: VertexDataTexture,
data16_texture: VertexDataTexture,
data32_texture: VertexDataTexture,
data64_texture: VertexDataTexture,
data128_texture: VertexDataTexture,
resource_rects_texture: VertexDataTexture,
gradient_data_texture: GradientDataTexture,
}
impl GpuDataTextures {
fn new(device: &mut Device) -> GpuDataTextures {
GpuDataTextures {
layer_texture: VertexDataTexture::new(device),
render_task_texture: VertexDataTexture::new(device),
prim_geom_texture: VertexDataTexture::new(device),
data16_texture: VertexDataTexture::new(device),
data32_texture: VertexDataTexture::new(device),
data64_texture: VertexDataTexture::new(device),
data128_texture: VertexDataTexture::new(device),
resource_rects_texture: VertexDataTexture::new(device),
gradient_data_texture: GradientDataTexture::new(device),
}
}
fn init_frame(&mut self, device: &mut Device, frame: &mut Frame) {
self.data16_texture.init(device, &mut frame.gpu_data16);
self.data32_texture.init(device, &mut frame.gpu_data32);
self.data64_texture.init(device, &mut frame.gpu_data64);
self.data128_texture.init(device, &mut frame.gpu_data128);
self.prim_geom_texture.init(device, &mut frame.gpu_geometry);
self.resource_rects_texture.init(device, &mut frame.gpu_resource_rects);
self.layer_texture.init(device, &mut frame.layer_texture_data);
self.render_task_texture.init(device, &mut frame.render_task_data);
self.gradient_data_texture.init(device, &mut frame.gpu_gradient_data);
device.bind_texture(TextureSampler::Layers, self.layer_texture.id);
device.bind_texture(TextureSampler::RenderTasks, self.render_task_texture.id);
device.bind_texture(TextureSampler::Geometry, self.prim_geom_texture.id);
device.bind_texture(TextureSampler::Data16, self.data16_texture.id);
device.bind_texture(TextureSampler::Data32, self.data32_texture.id);
device.bind_texture(TextureSampler::Data64, self.data64_texture.id);
device.bind_texture(TextureSampler::Data128, self.data128_texture.id);
device.bind_texture(TextureSampler::ResourceRects, self.resource_rects_texture.id);
device.bind_texture(TextureSampler::Gradients, self.gradient_data_texture.id);
}
}
/// The renderer is responsible for submitting to the GPU the work prepared by the
/// RenderBackend.
pub struct Renderer {
result_rx: Receiver<ResultMsg>,
device: Device,
pending_texture_updates: Vec<TextureUpdateList>,
pending_shader_updates: Vec<PathBuf>,
current_frame: Option<RendererFrame>,
// These are "cache shaders". These shaders are used to
// draw intermediate results to cache targets. The results
// of these shaders are then used by the primitive shaders.
cs_box_shadow: LazilyCompiledShader,
cs_text_run: LazilyCompiledShader,
cs_blur: LazilyCompiledShader,
/// These are "cache clip shaders". These shaders are used to
/// draw clip instances into the cached clip mask. The results
/// of these shaders are also used by the primitive shaders.
cs_clip_rectangle: LazilyCompiledShader,
cs_clip_image: LazilyCompiledShader,
// The are "primitive shaders". These shaders draw and blend
// final results on screen. They are aware of tile boundaries.
// Most draw directly to the framebuffer, but some use inputs
// from the cache shaders to draw. Specifically, the box
// shadow primitive shader stretches the box shadow cache
// output, and the cache_image shader blits the results of
// a cache shader (e.g. blur) to the screen.
ps_rectangle: PrimitiveShader,
ps_rectangle_clip: PrimitiveShader,
ps_text_run: PrimitiveShader,
ps_text_run_subpixel: PrimitiveShader,
ps_image: Vec<Option<PrimitiveShader>>,
ps_yuv_image: Vec<Option<PrimitiveShader>>,
ps_border: PrimitiveShader,
ps_border_corner: PrimitiveShader,
ps_border_edge: PrimitiveShader,
ps_gradient: PrimitiveShader,
ps_angle_gradient: PrimitiveShader,
ps_radial_gradient: PrimitiveShader,
ps_box_shadow: PrimitiveShader,
ps_cache_image: PrimitiveShader,
ps_blend: LazilyCompiledShader,
ps_hw_composite: LazilyCompiledShader,
ps_composite: LazilyCompiledShader,
notifier: Arc<Mutex<Option<Box<RenderNotifier>>>>,
enable_profiler: bool,
max_recorded_profiles: usize,
clear_framebuffer: bool,
clear_color: ColorF,
debug: DebugRenderer,
render_target_debug: bool,
enable_batcher: bool,
backend_profile_counters: BackendProfileCounters,
profile_counters: RendererProfileCounters,
profiler: Profiler,
last_time: u64,
color_render_targets: Vec<TextureId>,
alpha_render_targets: Vec<TextureId>,
gpu_profile: GpuProfiler<GpuProfileTag>,
prim_vao_id: VAOId,
blur_vao_id: VAOId,
clip_vao_id: VAOId,
gdt_index: usize,
gpu_data_textures: [GpuDataTextures; GPU_DATA_TEXTURE_POOL],
pipeline_epoch_map: HashMap<PipelineId, Epoch, BuildHasherDefault<FnvHasher>>,
/// Used to dispatch functions to the main thread's event loop.
/// Required to allow GLContext sharing in some implementations like WGL.
main_thread_dispatcher: Arc<Mutex<Option<Box<RenderDispatcher>>>>,
/// A vector for fast resolves of texture cache IDs to
/// native texture IDs. This maps to a free-list managed
/// by the backend thread / texture cache. We free the
/// texture memory associated with a TextureId when its
/// texture cache ID is freed by the texture cache, but
/// reuse the TextureId when the texture caches's free
/// list reuses the texture cache ID. This saves having to
/// use a hashmap, and allows a flat vector for performance.
cache_texture_id_map: Vec<TextureId>,
/// A special 1x1 dummy cache texture used for shaders that expect to work
/// with the cache but are actually running in the first pass
/// when no target is yet provided as a cache texture input.
dummy_cache_texture_id: TextureId,
dither_matrix_texture_id: Option<TextureId>,
/// Optional trait object that allows the client
/// application to provide external buffers for image data.
external_image_handler: Option<Box<ExternalImageHandler>>,
/// Map of external image IDs to native textures.
external_images: HashMap<(ExternalImageId, u8), TextureId, BuildHasherDefault<FnvHasher>>,
// Optional trait object that handles WebVR commands.
// Some WebVR commands such as SubmitFrame must be synced with the WebGL render thread.
vr_compositor_handler: Arc<Mutex<Option<Box<VRCompositorHandler>>>>,
/// List of profile results from previous frames. Can be retrieved
/// via get_frame_profiles().
cpu_profiles: VecDeque<CpuProfile>,
gpu_profiles: VecDeque<GpuProfile>,
}
#[derive(Debug)]
pub enum InitError {
Shader(ShaderError),
Thread(std::io::Error),
}
impl From<ShaderError> for InitError {
fn from(err: ShaderError) -> Self { InitError::Shader(err) }
}
impl From<std::io::Error> for InitError {
fn from(err: std::io::Error) -> Self { InitError::Thread(err) }
}
impl Renderer {
/// Initializes webrender and creates a `Renderer` and `RenderApiSender`.
///
/// # Examples
/// Initializes a `Renderer` with some reasonable values. For more information see
/// [`RendererOptions`][rendereroptions].
///
/// ```rust,ignore
/// # use webrender::renderer::Renderer;
/// # use std::path::PathBuf;
/// let opts = webrender::RendererOptions {
/// device_pixel_ratio: 1.0,
/// resource_override_path: None,
/// enable_aa: false,
/// enable_profiler: false,
/// };
/// let (renderer, sender) = Renderer::new(opts);
/// ```
/// [rendereroptions]: struct.RendererOptions.html
pub fn new(gl: Rc<gl::Gl>,
mut options: RendererOptions,
initial_window_size: DeviceUintSize) -> Result<(Renderer, RenderApiSender), InitError> {
let (api_tx, api_rx) = try!{ channel::msg_channel() };
let (payload_tx, payload_rx) = try!{ channel::payload_channel() };
let (result_tx, result_rx) = channel();
let gl_type = gl.get_type();
register_thread_with_profiler("Compositor".to_owned());
let notifier = Arc::new(Mutex::new(None));
let file_watch_handler = FileWatcher {
result_tx: result_tx.clone(),
notifier: Arc::clone(¬ifier),
};
let mut device = Device::new(gl,
options.resource_override_path.clone(),
Box::new(file_watch_handler));
// device-pixel ratio doesn't matter here - we are just creating resources.
device.begin_frame(1.0);
let cs_box_shadow = try!{
LazilyCompiledShader::new(ShaderKind::Cache(VertexFormat::Triangles),
"cs_box_shadow",
&[],
&mut device,
options.precache_shaders)
};
let cs_text_run = try!{
LazilyCompiledShader::new(ShaderKind::Cache(VertexFormat::Triangles),
"cs_text_run",
&[],
&mut device,
options.precache_shaders)
};
let cs_blur = try!{
LazilyCompiledShader::new(ShaderKind::Cache(VertexFormat::Blur),
"cs_blur",
&[],
&mut device,
options.precache_shaders)
};
let cs_clip_rectangle = try!{
LazilyCompiledShader::new(ShaderKind::ClipCache,
"cs_clip_rectangle",
&[],
&mut device,
options.precache_shaders)
};
let cs_clip_image = try!{
LazilyCompiledShader::new(ShaderKind::ClipCache,
"cs_clip_image",
&[],
&mut device,
options.precache_shaders)
};
let ps_rectangle = try!{
PrimitiveShader::new("ps_rectangle",
&mut device,
&[],
options.precache_shaders)
};
let ps_rectangle_clip = try!{
PrimitiveShader::new("ps_rectangle",
&mut device,
&[ CLIP_FEATURE ],
options.precache_shaders)
};
let ps_text_run = try!{
PrimitiveShader::new("ps_text_run",
&mut device,
&[],
options.precache_shaders)
};
let ps_text_run_subpixel = try!{
PrimitiveShader::new("ps_text_run",
&mut device,
&[ SUBPIXEL_AA_FEATURE ],
options.precache_shaders)
};
// All image configuration.
let mut image_features = Vec::new();
let mut ps_image: Vec<Option<PrimitiveShader>> = Vec::new();
// PrimitiveShader is not clonable. Use push() to initialize the vec.
for _ in 0..IMAGE_BUFFER_KINDS.len() {
ps_image.push(None);
}
for buffer_kind in 0..IMAGE_BUFFER_KINDS.len() {
if IMAGE_BUFFER_KINDS[buffer_kind].has_platform_support(&gl_type) {
let feature_string = IMAGE_BUFFER_KINDS[buffer_kind].get_feature_string();
if feature_string != "" {
image_features.push(feature_string);
}
let shader = try!{
PrimitiveShader::new("ps_image",
&mut device,
&image_features,
options.precache_shaders)
};
ps_image[buffer_kind] = Some(shader);
}
image_features.clear();
}
// All yuv_image configuration.
let mut yuv_features = Vec::new();
let yuv_shader_num = IMAGE_BUFFER_KINDS.len() *
YUV_FORMATS.len() *
YUV_COLOR_SPACES.len();
let mut ps_yuv_image: Vec<Option<PrimitiveShader>> = Vec::new();
// PrimitiveShader is not clonable. Use push() to initialize the vec.
for _ in 0..yuv_shader_num {
ps_yuv_image.push(None);
}
for buffer_kind in 0..IMAGE_BUFFER_KINDS.len() {
if IMAGE_BUFFER_KINDS[buffer_kind].has_platform_support(&gl_type) {
for format_kind in 0..YUV_FORMATS.len() {
for color_space_kind in 0..YUV_COLOR_SPACES.len() {
let feature_string = IMAGE_BUFFER_KINDS[buffer_kind].get_feature_string();
if feature_string != "" {
yuv_features.push(feature_string);
}
let feature_string = YUV_FORMATS[format_kind].get_feature_string();
if feature_string != "" {
yuv_features.push(feature_string);
}
let feature_string = YUV_COLOR_SPACES[color_space_kind].get_feature_string();
if feature_string != "" {
yuv_features.push(feature_string);
}
let shader = try!{
PrimitiveShader::new("ps_yuv_image",
&mut device,
&yuv_features,
options.precache_shaders)
};
let index = Renderer::get_yuv_shader_index(IMAGE_BUFFER_KINDS[buffer_kind],
YUV_FORMATS[format_kind],
YUV_COLOR_SPACES[color_space_kind]);
ps_yuv_image[index] = Some(shader);
yuv_features.clear();
}
}
}
}
let ps_border = try!{
PrimitiveShader::new("ps_border",
&mut device,
&[],
options.precache_shaders)
};
let ps_border_corner = try!{
PrimitiveShader::new("ps_border_corner",
&mut device,
&[],
options.precache_shaders)
};
let ps_border_edge = try!{
PrimitiveShader::new("ps_border_edge",
&mut device,
&[],
options.precache_shaders)
};
let ps_box_shadow = try!{
PrimitiveShader::new("ps_box_shadow",
&mut device,
&[],
options.precache_shaders)
};
let dithering_feature = ["DITHERING"];
let ps_gradient = try!{
PrimitiveShader::new("ps_gradient",
&mut device,
if options.enable_dithering {
&dithering_feature
} else {
&[]
},
options.precache_shaders)
};
let ps_angle_gradient = try!{
PrimitiveShader::new("ps_angle_gradient",
&mut device,
if options.enable_dithering {
&dithering_feature
} else {
&[]
},
options.precache_shaders)
};
let ps_radial_gradient = try!{
PrimitiveShader::new("ps_radial_gradient",
&mut device,
if options.enable_dithering {
&dithering_feature
} else {
&[]
},
options.precache_shaders)
};
let ps_cache_image = try!{
PrimitiveShader::new("ps_cache_image",
&mut device,
&[],
options.precache_shaders)
};
let ps_blend = try!{
LazilyCompiledShader::new(ShaderKind::Primitive,
"ps_blend",
&[],
&mut device,
options.precache_shaders)
};
let ps_composite = try!{
LazilyCompiledShader::new(ShaderKind::Primitive,
"ps_composite",
&[],
&mut device,
options.precache_shaders)
};
let ps_hw_composite = try!{
LazilyCompiledShader::new(ShaderKind::Primitive,
"ps_hardware_composite",
&[],
&mut device,
options.precache_shaders)
};
let device_max_size = device.max_texture_size();
let max_texture_size = cmp::min(device_max_size, options.max_texture_size.unwrap_or(device_max_size));
let mut texture_cache = TextureCache::new(max_texture_size);
let mut backend_profile_counters = BackendProfileCounters::new();
let white_pixels: Vec<u8> = vec![
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
];
let mask_pixels: Vec<u8> = vec![
0xff, 0xff,
0xff, 0xff,
];
// TODO: Ensure that the white texture can never get evicted when the cache supports LRU eviction!
let white_image_id = texture_cache.new_item_id();
texture_cache.insert(white_image_id,
ImageDescriptor::new(2, 2, ImageFormat::RGBA8, false),
TextureFilter::Linear,
ImageData::Raw(Arc::new(white_pixels)),
&mut backend_profile_counters.resources.texture_cache);
let dummy_mask_image_id = texture_cache.new_item_id();
texture_cache.insert(dummy_mask_image_id,
ImageDescriptor::new(2, 2, ImageFormat::A8, false),
TextureFilter::Linear,
ImageData::Raw(Arc::new(mask_pixels)),
&mut backend_profile_counters.resources.texture_cache);
let dummy_cache_texture_id = device.create_texture_ids(1, TextureTarget::Array)[0];
device.init_texture(dummy_cache_texture_id,
1,
1,
ImageFormat::RGBA8,
TextureFilter::Linear,
RenderTargetMode::LayerRenderTarget(1),
None);
let dither_matrix_texture_id = if options.enable_dithering {
let dither_matrix: [u8; 64] = [
00, 48, 12, 60, 03, 51, 15, 63,
32, 16, 44, 28, 35, 19, 47, 31,
08, 56, 04, 52, 11, 59, 07, 55,
40, 24, 36, 20, 43, 27, 39, 23,
02, 50, 14, 62, 01, 49, 13, 61,
34, 18, 46, 30, 33, 17, 45, 29,
10, 58, 06, 54, 09, 57, 05, 53,
42, 26, 38, 22, 41, 25, 37, 21
];
let id = device.create_texture_ids(1, TextureTarget::Default)[0];
device.init_texture(id,
8,
8,
ImageFormat::A8,
TextureFilter::Nearest,
RenderTargetMode::None,
Some(&dither_matrix));
Some(id)
} else {
None
};
let debug_renderer = DebugRenderer::new(&mut device);
let gpu_data_textures = [
GpuDataTextures::new(&mut device),
GpuDataTextures::new(&mut device),
GpuDataTextures::new(&mut device),
GpuDataTextures::new(&mut device),
GpuDataTextures::new(&mut device),
];
let x0 = 0.0;
let y0 = 0.0;
let x1 = 1.0;
let y1 = 1.0;
let quad_indices: [u16; 6] = [ 0, 1, 2, 2, 1, 3 ];
let quad_vertices = [
PackedVertex {
pos: [x0, y0],
},
PackedVertex {
pos: [x1, y0],
},
PackedVertex {
pos: [x0, y1],
},
PackedVertex {
pos: [x1, y1],
},
];
let prim_vao_id = device.create_vao(VertexFormat::Triangles, mem::size_of::<PrimitiveInstance>() as i32);
device.bind_vao(prim_vao_id);
device.update_vao_indices(prim_vao_id, &quad_indices, VertexUsageHint::Static);
device.update_vao_main_vertices(prim_vao_id, &quad_vertices, VertexUsageHint::Static);
let blur_vao_id = device.create_vao_with_new_instances(VertexFormat::Blur, mem::size_of::<BlurCommand>() as i32, prim_vao_id);
let clip_vao_id = device.create_vao_with_new_instances(VertexFormat::Clip, mem::size_of::<CacheClipInstance>() as i32, prim_vao_id);
device.end_frame();
let main_thread_dispatcher = Arc::new(Mutex::new(None));
let backend_notifier = Arc::clone(¬ifier);
let backend_main_thread_dispatcher = Arc::clone(&main_thread_dispatcher);
let vr_compositor = Arc::new(Mutex::new(None));
let backend_vr_compositor = Arc::clone(&vr_compositor);
// We need a reference to the webrender context from the render backend in order to share
// texture ids
let context_handle = match options.renderer_kind {
RendererKind::Native => GLContextHandleWrapper::current_native_handle(),
RendererKind::OSMesa => GLContextHandleWrapper::current_osmesa_handle(),
};
let config = FrameBuilderConfig::new(options.enable_scrollbars,
options.enable_subpixel_aa,
options.debug);