/
webgl_thread.rs
3013 lines (2836 loc) · 116 KB
/
webgl_thread.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 https://mozilla.org/MPL/2.0/. */
use crate::webgl_limits::GLLimitsDetect;
use byteorder::{ByteOrder, NativeEndian, WriteBytesExt};
use canvas_traits::webgl;
use canvas_traits::webgl::ActiveAttribInfo;
use canvas_traits::webgl::ActiveUniformBlockInfo;
use canvas_traits::webgl::ActiveUniformInfo;
use canvas_traits::webgl::AlphaTreatment;
use canvas_traits::webgl::DOMToTextureCommand;
use canvas_traits::webgl::GLContextAttributes;
use canvas_traits::webgl::GLLimits;
use canvas_traits::webgl::GlType;
use canvas_traits::webgl::InternalFormatIntVec;
use canvas_traits::webgl::ProgramLinkInfo;
use canvas_traits::webgl::SwapChainId;
use canvas_traits::webgl::TexDataType;
use canvas_traits::webgl::TexFormat;
use canvas_traits::webgl::WebGLBufferId;
use canvas_traits::webgl::WebGLChan;
use canvas_traits::webgl::WebGLCommand;
use canvas_traits::webgl::WebGLCommandBacktrace;
use canvas_traits::webgl::WebGLContextId;
use canvas_traits::webgl::WebGLCreateContextResult;
use canvas_traits::webgl::WebGLFramebufferBindingRequest;
use canvas_traits::webgl::WebGLFramebufferId;
use canvas_traits::webgl::WebGLMsg;
use canvas_traits::webgl::WebGLMsgSender;
use canvas_traits::webgl::WebGLOpaqueFramebufferId;
use canvas_traits::webgl::WebGLProgramId;
use canvas_traits::webgl::WebGLQueryId;
use canvas_traits::webgl::WebGLReceiver;
use canvas_traits::webgl::WebGLRenderbufferId;
use canvas_traits::webgl::WebGLSLVersion;
use canvas_traits::webgl::WebGLSamplerId;
use canvas_traits::webgl::WebGLSender;
use canvas_traits::webgl::WebGLShaderId;
use canvas_traits::webgl::WebGLSyncId;
use canvas_traits::webgl::WebGLTextureId;
use canvas_traits::webgl::WebGLTransparentFramebufferId;
use canvas_traits::webgl::WebGLVersion;
use canvas_traits::webgl::WebGLVertexArrayId;
use canvas_traits::webgl::WebVRCommand;
use canvas_traits::webgl::WebVRRenderHandler;
use canvas_traits::webgl::YAxisTreatment;
use euclid::default::Size2D;
use fnv::FnvHashMap;
use half::f16;
use pixels::{self, PixelFormat};
use servo_config::opts;
use sparkle::gl;
use sparkle::gl::GLint;
use sparkle::gl::GLuint;
use sparkle::gl::Gl;
use std::borrow::Cow;
use std::collections::HashMap;
use std::rc::Rc;
use std::slice;
use std::sync::{Arc, Mutex};
use std::thread;
use surfman;
use surfman::platform::generic::universal::adapter::Adapter;
use surfman::platform::generic::universal::connection::Connection;
use surfman::platform::generic::universal::context::Context;
use surfman::platform::generic::universal::device::Device;
use surfman::ContextAttributeFlags;
use surfman::ContextAttributes;
use surfman::GLVersion;
use surfman::SurfaceAccess;
use surfman::SurfaceInfo;
use surfman::SurfaceType;
use surfman_chains::{SurfmanProvider, SwapChains};
use surfman_chains_api::SwapChainsAPI;
use webrender_traits::{WebrenderExternalImageRegistry, WebrenderImageHandlerType};
use webxr_api::SessionId;
use webxr_api::SwapChainId as WebXRSwapChainId;
#[cfg(feature = "xr-profile")]
fn to_ms(ns: u64) -> f64 {
ns as f64 / 1_000_000.
}
struct GLContextData {
ctx: Context,
gl: Rc<Gl>,
state: GLState,
attributes: GLContextAttributes,
}
pub struct GLState {
webgl_version: WebGLVersion,
gl_version: GLVersion,
clear_color: (f32, f32, f32, f32),
scissor_test_enabled: bool,
stencil_write_mask: (u32, u32),
stencil_clear_value: i32,
depth_write_mask: bool,
depth_clear_value: f64,
default_vao: gl::GLuint,
}
impl Default for GLState {
fn default() -> GLState {
GLState {
gl_version: GLVersion { major: 1, minor: 0 },
webgl_version: WebGLVersion::WebGL1,
clear_color: (0., 0., 0., 0.),
scissor_test_enabled: false,
stencil_write_mask: (0, 0),
stencil_clear_value: 0,
depth_write_mask: true,
depth_clear_value: 1.,
default_vao: 0,
}
}
}
/// A WebGLThread manages the life cycle and message multiplexing of
/// a set of WebGLContexts living in the same thread.
pub(crate) struct WebGLThread {
/// The GPU device.
device: Device,
/// Channel used to generate/update or delete `webrender_api::ImageKey`s.
webrender_api: webrender_api::RenderApi,
/// Map of live WebGLContexts.
contexts: FnvHashMap<WebGLContextId, GLContextData>,
/// Cached information for WebGLContexts.
cached_context_info: FnvHashMap<WebGLContextId, WebGLContextInfo>,
/// Current bound context.
bound_context_id: Option<WebGLContextId>,
/// Handler user to send WebVR commands.
// TODO: replace webvr implementation with one built on top of webxr
#[allow(dead_code)]
webvr_compositor: Option<Box<dyn WebVRRenderHandler>>,
/// Texture ids and sizes used in DOM to texture outputs.
dom_outputs: FnvHashMap<webrender_api::PipelineId, DOMToTextureData>,
/// List of registered webrender external images.
/// We use it to get an unique ID for new WebGLContexts.
external_images: Arc<Mutex<WebrenderExternalImageRegistry>>,
/// The receiver that will be used for processing WebGL messages.
receiver: crossbeam_channel::Receiver<WebGLMsg>,
/// The receiver that should be used to send WebGL messages for processing.
sender: WebGLSender<WebGLMsg>,
/// The swap chains used by webrender
webrender_swap_chains: SwapChains<WebGLContextId>,
/// The swap chains used by webxr
webxr_swap_chains: SwapChains<WebXRSwapChainId>,
/// The set of all surface providers corresponding to WebXR sessions.
webxr_surface_providers: SurfaceProviders,
/// A channel to allow arbitrary threads to execute tasks that run in the WebGL thread.
runnable_receiver: crossbeam_channel::Receiver<WebGlRunnable>,
/// Whether this context is a GL or GLES context.
api_type: gl::GlType,
}
pub type WebGlExecutor = crossbeam_channel::Sender<WebGlRunnable>;
pub type WebGlRunnable = Box<dyn FnOnce() + Send>;
pub type SurfaceProviders = Arc<Mutex<HashMap<SessionId, SurfaceProvider>>>;
pub type SurfaceProvider = Box<dyn surfman_chains::SurfaceProvider + Send>;
/// The data required to initialize an instance of the WebGLThread type.
pub(crate) struct WebGLThreadInit {
pub webxr_surface_providers: SurfaceProviders,
pub webrender_api_sender: webrender_api::RenderApiSender,
pub webvr_compositor: Option<Box<dyn WebVRRenderHandler>>,
pub external_images: Arc<Mutex<WebrenderExternalImageRegistry>>,
pub sender: WebGLSender<WebGLMsg>,
pub receiver: WebGLReceiver<WebGLMsg>,
pub webrender_swap_chains: SwapChains<WebGLContextId>,
pub webxr_swap_chains: SwapChains<WebXRSwapChainId>,
pub connection: Connection,
pub adapter: Adapter,
pub api_type: gl::GlType,
pub runnable_receiver: crossbeam_channel::Receiver<WebGlRunnable>,
}
// A size at which it should be safe to create GL contexts
const SAFE_VIEWPORT_DIMS: [u32; 2] = [1024, 1024];
impl WebGLThread {
/// Create a new instance of WebGLThread.
pub(crate) fn new(
WebGLThreadInit {
webrender_api_sender,
webvr_compositor,
external_images,
sender,
receiver,
webrender_swap_chains,
webxr_swap_chains,
webxr_surface_providers,
connection,
adapter,
api_type,
runnable_receiver,
}: WebGLThreadInit,
) -> Self {
WebGLThread {
device: Device::new(&connection, &adapter).expect("Couldn't open WebGL device!"),
webrender_api: webrender_api_sender.create_api(),
contexts: Default::default(),
cached_context_info: Default::default(),
bound_context_id: None,
webvr_compositor,
dom_outputs: Default::default(),
external_images,
sender,
receiver: receiver.into_inner(),
webrender_swap_chains,
webxr_swap_chains,
webxr_surface_providers,
runnable_receiver,
api_type,
}
}
/// Perform all initialization required to run an instance of WebGLThread
/// in parallel on its own dedicated thread.
pub(crate) fn run_on_own_thread(init: WebGLThreadInit) {
thread::Builder::new()
.name("WebGL thread".to_owned())
.spawn(move || {
let mut data = WebGLThread::new(init);
data.process();
})
.expect("Thread spawning failed");
}
fn process(&mut self) {
let webgl_chan = WebGLChan(self.sender.clone());
loop {
crossbeam_channel::select! {
recv(self.receiver) -> msg => {
match msg {
Ok(msg) => {
let exit = self.handle_msg(msg, &webgl_chan);
if exit {
return;
}
}
_ => break,
}
}
recv(self.runnable_receiver) -> msg => {
if let Ok(msg) = msg {
msg();
} else {
self.runnable_receiver = crossbeam_channel::never();
}
}
}
}
}
/// Handles a generic WebGLMsg message
fn handle_msg(&mut self, msg: WebGLMsg, webgl_chan: &WebGLChan) -> bool {
trace!("processing {:?}", msg);
match msg {
WebGLMsg::CreateContext(version, size, attributes, result_sender) => {
let result = self.create_webgl_context(version, size, attributes);
result_sender
.send(result.map(|(id, limits)| {
let image_key = self
.cached_context_info
.get_mut(&id)
.expect("Where's the cached context info?")
.image_key;
let data = Self::make_current_if_needed(
&self.device,
id,
&self.contexts,
&mut self.bound_context_id,
)
.expect("WebGLContext not found");
let glsl_version = Self::get_glsl_version(&*data.gl);
let api_type = match data.gl.get_type() {
gl::GlType::Gl => GlType::Gl,
gl::GlType::Gles => GlType::Gles,
};
// FIXME(nox): Should probably be done by surfman.
if api_type != GlType::Gles {
// Points sprites are enabled by default in OpenGL 3.2 core
// and in GLES. Rather than doing version detection, it does
// not hurt to enable them anyways.
data.gl.enable(gl::POINT_SPRITE);
let err = data.gl.get_error();
if err != 0 {
warn!("Error enabling GL point sprites: {}", err);
}
data.gl.enable(gl::PROGRAM_POINT_SIZE);
let err = data.gl.get_error();
if err != 0 {
warn!("Error enabling GL program point size: {}", err);
}
}
WebGLCreateContextResult {
sender: WebGLMsgSender::new(id, webgl_chan.clone()),
limits,
glsl_version,
api_type,
image_key,
}
}))
.unwrap();
},
WebGLMsg::ResizeContext(ctx_id, size, sender) => {
self.resize_webgl_context(ctx_id, size, sender);
},
WebGLMsg::RemoveContext(ctx_id) => {
self.remove_webgl_context(ctx_id);
},
WebGLMsg::WebGLCommand(ctx_id, command, backtrace) => {
self.handle_webgl_command(ctx_id, command, backtrace);
},
WebGLMsg::WebVRCommand(ctx_id, command) => {
self.handle_webvr_command(ctx_id, command);
},
WebGLMsg::CreateWebXRSwapChain(ctx_id, size, sender, id) => {
let _ = sender.send(self.create_webxr_swap_chain(ctx_id, size, id));
},
WebGLMsg::SwapBuffers(swap_ids, sender, sent_time) => {
self.handle_swap_buffers(swap_ids, sender, sent_time);
},
WebGLMsg::DOMToTextureCommand(command) => {
self.handle_dom_to_texture(command);
},
WebGLMsg::Exit => {
return true;
},
}
false
}
/// Handles a WebGLCommand for a specific WebGLContext
fn handle_webgl_command(
&mut self,
context_id: WebGLContextId,
command: WebGLCommand,
backtrace: WebGLCommandBacktrace,
) {
if self.cached_context_info.get_mut(&context_id).is_none() {
return;
}
let data = Self::make_current_if_needed_mut(
&self.device,
context_id,
&mut self.contexts,
&mut self.bound_context_id,
);
if let Some(data) = data {
match command {
// We have to handle framebuffer binding differently, because `apply`
// assumes that the currently attached surface is the right one for binding
// the framebuffer, and since it doesn't get passed the swap buffers
// it casn't do that itself. At some point we could refactor apply so
// it takes a self parameter, at which point that won't be necessary.
WebGLCommand::BindFramebuffer(_, request) => {
WebGLImpl::attach_surface(
context_id,
&self.webrender_swap_chains,
&self.webxr_swap_chains,
request,
&mut data.ctx,
&mut self.device,
);
},
// Similarly, dropping a WebGL framebuffer needs access to the swap chains,
// in order to delete the entry.
WebGLCommand::DeleteFramebuffer(WebGLFramebufferId::Opaque(
WebGLOpaqueFramebufferId::WebXR(id),
)) => {
let _ = self
.webxr_swap_chains
.destroy(id, &mut self.device, &mut data.ctx);
},
_ => {},
}
WebGLImpl::apply(
&self.device,
&data.ctx,
&*data.gl,
&mut data.state,
&data.attributes,
command,
backtrace,
);
}
}
/// Handles a WebVRCommand for a specific WebGLContext
fn handle_webvr_command(&mut self, _context_id: WebGLContextId, _command: WebVRCommand) {
// TODO(pcwalton): Reenable.
}
/// Creates a new WebGLContext
#[allow(unsafe_code)]
fn create_webgl_context(
&mut self,
webgl_version: WebGLVersion,
requested_size: Size2D<u32>,
attributes: GLContextAttributes,
) -> Result<(WebGLContextId, webgl::GLLimits), String> {
debug!("WebGLThread::create_webgl_context({:?})", requested_size);
// Creating a new GLContext may make the current bound context_id dirty.
// Clear it to ensure that make_current() is called in subsequent commands.
self.bound_context_id = None;
let context_attributes = &ContextAttributes {
version: webgl_version.to_surfman_version(),
flags: attributes.to_surfman_context_attribute_flags(webgl_version),
};
let context_descriptor = self
.device
.create_context_descriptor(&context_attributes)
.unwrap();
let safe_size = Size2D::new(
requested_size.width.min(SAFE_VIEWPORT_DIMS[0]).max(1),
requested_size.height.min(SAFE_VIEWPORT_DIMS[1]).max(1),
);
let surface_type = SurfaceType::Generic {
size: safe_size.to_i32(),
};
let surface_access = self.surface_access();
let surface_provider = Box::new(SurfmanProvider::new(surface_access));
let mut ctx = self
.device
.create_context(&context_descriptor)
.expect("Failed to create the GL context!");
let surface = self
.device
.create_surface(&ctx, surface_access, &surface_type)
.expect("Failed to create the initial surface!");
self.device
.bind_surface_to_context(&mut ctx, surface)
.unwrap();
// https://github.com/pcwalton/surfman/issues/7
self.device
.make_context_current(&ctx)
.expect("failed to make new context current");
let id = WebGLContextId(
self.external_images
.lock()
.unwrap()
.next_id(WebrenderImageHandlerType::WebGL)
.0,
);
self.webrender_swap_chains
.create_attached_swap_chain(id, &mut self.device, &mut ctx, surface_provider)
.expect("Failed to create the swap chain");
let swap_chain = self
.webrender_swap_chains
.get(id)
.expect("Failed to get the swap chain");
debug!(
"Created webgl context {:?}/{:?}",
id,
self.device.context_id(&ctx)
);
let gl = match self.api_type {
gl::GlType::Gl => Gl::gl_fns(gl::ffi_gl::Gl::load_with(|symbol_name| {
self.device.get_proc_address(&ctx, symbol_name)
})),
gl::GlType::Gles => Gl::gles_fns(gl::ffi_gles::Gles2::load_with(|symbol_name| {
self.device.get_proc_address(&ctx, symbol_name)
})),
};
let limits = GLLimits::detect(&*gl, webgl_version);
let size = clamp_viewport(&gl, requested_size);
if safe_size != size {
debug!("Resizing swap chain from {} to {}", safe_size, size);
swap_chain
.resize(&mut self.device, &mut ctx, size.to_i32())
.expect("Failed to resize swap chain");
}
self.device.make_context_current(&ctx).unwrap();
let framebuffer = self
.device
.context_surface_info(&ctx)
.unwrap()
.unwrap()
.framebuffer_object;
gl.bind_framebuffer(gl::FRAMEBUFFER, framebuffer);
gl.viewport(0, 0, size.width as i32, size.height as i32);
gl.scissor(0, 0, size.width as i32, size.height as i32);
gl.clear_color(0., 0., 0., 0.);
gl.clear_depth(1.);
gl.clear_stencil(0);
gl.clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT | gl::STENCIL_BUFFER_BIT);
debug_assert_eq!(gl.get_error(), gl::NO_ERROR);
let descriptor = self.device.context_descriptor(&ctx);
let descriptor_attributes = self.device.context_descriptor_attributes(&descriptor);
let gl_version = descriptor_attributes.version;
let has_alpha = descriptor_attributes
.flags
.contains(ContextAttributeFlags::ALPHA);
let texture_target = current_wr_texture_target(&self.device);
let use_apple_vertex_array = WebGLImpl::needs_apple_vertex_arrays(gl_version);
let default_vao = if let Some(vao) =
WebGLImpl::create_vertex_array(&gl, use_apple_vertex_array, webgl_version)
{
let vao = vao.get();
WebGLImpl::bind_vertex_array(&gl, vao, use_apple_vertex_array, webgl_version);
vao
} else {
0
};
let state = GLState {
gl_version,
webgl_version,
default_vao,
..Default::default()
};
self.contexts.insert(
id,
GLContextData {
ctx,
gl,
state,
attributes,
},
);
let image_key = Self::create_wr_external_image(
&self.webrender_api,
size.to_i32(),
has_alpha,
id,
texture_target,
);
self.cached_context_info
.insert(id, WebGLContextInfo { image_key });
Ok((id, limits))
}
/// Resizes a WebGLContext
fn resize_webgl_context(
&mut self,
context_id: WebGLContextId,
requested_size: Size2D<u32>,
sender: WebGLSender<Result<(), String>>,
) {
let data = Self::make_current_if_needed_mut(
&self.device,
context_id,
&mut self.contexts,
&mut self.bound_context_id,
)
.expect("Missing WebGL context!");
let size = clamp_viewport(&data.gl, requested_size);
// Check to see if any of the current framebuffer bindings are the surface we're about to
// throw out. If so, we'll have to reset them after destroying the surface.
let framebuffer_rebinding_info =
FramebufferRebindingInfo::detect(&self.device, &data.ctx, &*data.gl);
// Resize the swap chains
if let Some(swap_chain) = self.webrender_swap_chains.get(context_id) {
swap_chain
.resize(&mut self.device, &mut data.ctx, size.to_i32())
.expect("Failed to resize swap chain");
// temporary, till https://github.com/pcwalton/surfman/issues/35 is fixed
self.device
.make_context_current(&data.ctx)
.expect("Failed to make context current again");
swap_chain
.clear_surface(&mut self.device, &mut data.ctx, &*data.gl)
.expect("Failed to clear resized swap chain");
} else {
error!("Failed to find swap chain");
}
// Reset framebuffer bindings as appropriate.
framebuffer_rebinding_info.apply(&self.device, &data.ctx, &*data.gl);
// Update WR image if needed.
let info = self.cached_context_info.get_mut(&context_id).unwrap();
let context_descriptor = self.device.context_descriptor(&data.ctx);
let has_alpha = self
.device
.context_descriptor_attributes(&context_descriptor)
.flags
.contains(ContextAttributeFlags::ALPHA);
let texture_target = current_wr_texture_target(&self.device);
Self::update_wr_external_image(
&self.webrender_api,
size.to_i32(),
has_alpha,
context_id,
info.image_key,
texture_target,
);
debug_assert_eq!(data.gl.get_error(), gl::NO_ERROR);
sender.send(Ok(())).unwrap();
}
/// Removes a WebGLContext and releases attached resources.
fn remove_webgl_context(&mut self, context_id: WebGLContextId) {
// Release webrender image keys.
if let Some(info) = self.cached_context_info.remove(&context_id) {
let mut txn = webrender_api::Transaction::new();
txn.delete_image(info.image_key);
self.webrender_api.update_resources(txn.resource_updates)
}
// We need to make the context current so its resources can be disposed of.
Self::make_current_if_needed(
&self.device,
context_id,
&self.contexts,
&mut self.bound_context_id,
);
// Release GL context.
let mut data = match self.contexts.remove(&context_id) {
Some(data) => data,
None => return,
};
// Destroy the swap chains
self.webrender_swap_chains
.destroy(context_id, &mut self.device, &mut data.ctx)
.unwrap();
self.webxr_swap_chains
.destroy_all(&mut self.device, &mut data.ctx)
.unwrap();
// Destroy the context
self.device.destroy_context(&mut data.ctx).unwrap();
// Removing a GLContext may make the current bound context_id dirty.
self.bound_context_id = None;
}
fn handle_swap_buffers(
&mut self,
swap_ids: Vec<SwapChainId>,
completed_sender: WebGLSender<u64>,
_sent_time: u64,
) {
#[cfg(feature = "xr-profile")]
let start_swap = time::precise_time_ns();
#[cfg(feature = "xr-profile")]
println!(
"WEBXR PROFILING [swap request]:\t{}ms",
to_ms(start_swap - _sent_time)
);
debug!("handle_swap_buffers()");
for swap_id in swap_ids {
let context_id = swap_id.context_id();
let data = Self::make_current_if_needed_mut(
&self.device,
context_id,
&mut self.contexts,
&mut self.bound_context_id,
)
.expect("Where's the GL data?");
// Ensure there are no pending GL errors from other parts of the pipeline.
debug_assert_eq!(data.gl.get_error(), gl::NO_ERROR);
// Check to see if any of the current framebuffer bindings are the surface we're about
// to swap out. If so, we'll have to reset them after destroying the surface.
let framebuffer_rebinding_info =
FramebufferRebindingInfo::detect(&self.device, &data.ctx, &*data.gl);
debug_assert_eq!(data.gl.get_error(), gl::NO_ERROR);
debug!("Getting swap chain for {:?}", swap_id);
let swap_chain = match swap_id {
SwapChainId::Context(id) => self.webrender_swap_chains.get(id),
SwapChainId::Framebuffer(_, WebGLOpaqueFramebufferId::WebXR(id)) => {
self.webxr_swap_chains.get(id)
},
}
.expect("Where's the swap chain?");
debug!("Swapping {:?}", swap_id);
swap_chain
.swap_buffers(&mut self.device, &mut data.ctx)
.unwrap();
debug_assert_eq!(data.gl.get_error(), gl::NO_ERROR);
// TODO: if preserveDrawingBuffer is true, then blit the front buffer to the back buffer
// https://github.com/servo/servo/issues/24604
debug!("Clearing {:?}", swap_id);
swap_chain
.clear_surface(&mut self.device, &mut data.ctx, &*data.gl)
.unwrap();
debug_assert_eq!(data.gl.get_error(), gl::NO_ERROR);
// Rebind framebuffers as appropriate.
debug!("Rebinding {:?}", swap_id);
framebuffer_rebinding_info.apply(&self.device, &data.ctx, &*data.gl);
debug_assert_eq!(data.gl.get_error(), gl::NO_ERROR);
let SurfaceInfo {
framebuffer_object,
id,
..
} = self
.device
.context_surface_info(&data.ctx)
.unwrap()
.unwrap();
debug!(
"... rebound framebuffer {}, new back buffer surface is {:?}",
framebuffer_object, id
);
}
#[allow(unused)]
let mut end_swap = 0;
#[cfg(feature = "xr-profile")]
{
end_swap = time::precise_time_ns();
println!(
"WEBXR PROFILING [swap buffer]:\t{}ms",
to_ms(end_swap - start_swap)
);
}
completed_sender.send(end_swap).unwrap();
}
/// Creates a new WebXR swap chain
#[allow(unsafe_code)]
fn create_webxr_swap_chain(
&mut self,
context_id: WebGLContextId,
size: Size2D<i32>,
session_id: SessionId,
) -> Option<WebXRSwapChainId> {
debug!("WebGLThread::create_webxr_swap_chain()");
let id = WebXRSwapChainId::new();
let surface_access = self.surface_access();
let data = Self::make_current_if_needed_mut(
&self.device,
context_id,
&mut self.contexts,
&mut self.bound_context_id,
)?;
let surface_provider = self
.webxr_surface_providers
.lock()
.unwrap()
.remove(&session_id)
.unwrap_or_else(|| Box::new(SurfmanProvider::new(surface_access)));
self.webxr_swap_chains
.create_detached_swap_chain(id, size, &mut self.device, &mut data.ctx, surface_provider)
.ok()?;
debug!("Created swap chain {:?}", id);
Some(id)
}
/// Which access mode to use
fn surface_access(&self) -> SurfaceAccess {
SurfaceAccess::GPUOnly
}
fn handle_dom_to_texture(&mut self, command: DOMToTextureCommand) {
match command {
DOMToTextureCommand::Attach(context_id, texture_id, document_id, pipeline_id, size) => {
let data = Self::make_current_if_needed(
&self.device,
context_id,
&self.contexts,
&mut self.bound_context_id,
)
.expect("WebGLContext not found in a WebGL DOMToTextureCommand::Attach command");
// Initialize the texture that WR will use for frame outputs.
data.gl.tex_image_2d(
gl::TEXTURE_2D,
0,
gl::RGBA as gl::GLint,
size.width,
size.height,
0,
gl::RGBA,
gl::UNSIGNED_BYTE,
None,
);
self.dom_outputs.insert(
pipeline_id,
DOMToTextureData {
context_id,
texture_id,
document_id,
size,
},
);
let mut txn = webrender_api::Transaction::new();
txn.enable_frame_output(pipeline_id, true);
self.webrender_api.send_transaction(document_id, txn);
},
DOMToTextureCommand::Lock(pipeline_id, gl_sync, sender) => {
let result = self.handle_dom_to_texture_lock(pipeline_id, gl_sync);
// Send the texture id and size to WR.
sender.send(result).unwrap();
},
DOMToTextureCommand::Detach(texture_id) => {
if let Some((pipeline_id, document_id)) = self
.dom_outputs
.iter()
.find(|&(_, v)| v.texture_id == texture_id)
.map(|(k, v)| (*k, v.document_id))
{
let mut txn = webrender_api::Transaction::new();
txn.enable_frame_output(pipeline_id, false);
self.webrender_api.send_transaction(document_id, txn);
self.dom_outputs.remove(&pipeline_id);
}
},
}
}
pub(crate) fn handle_dom_to_texture_lock(
&mut self,
pipeline_id: webrender_api::PipelineId,
gl_sync: usize,
) -> Option<(u32, Size2D<i32>)> {
let device = &self.device;
let contexts = &self.contexts;
let bound_context_id = &mut self.bound_context_id;
self.dom_outputs.get(&pipeline_id).and_then(|dom_data| {
let data = Self::make_current_if_needed(
device,
dom_data.context_id,
contexts,
bound_context_id,
);
data.and_then(|data| {
// The next glWaitSync call is used to synchronize the two flows of
// OpenGL commands (WR and WebGL) in order to avoid using semi-ready WR textures.
// glWaitSync doesn't block WebGL CPU thread.
data.gl
.wait_sync(gl_sync as gl::GLsync, 0, gl::TIMEOUT_IGNORED);
Some((dom_data.texture_id.get(), dom_data.size))
})
})
}
/// Gets a reference to a Context for a given WebGLContextId and makes it current if required.
fn make_current_if_needed<'a>(
device: &Device,
context_id: WebGLContextId,
contexts: &'a FnvHashMap<WebGLContextId, GLContextData>,
bound_id: &mut Option<WebGLContextId>,
) -> Option<&'a GLContextData> {
let data = contexts.get(&context_id);
if let Some(data) = data {
if Some(context_id) != *bound_id {
device.make_context_current(&data.ctx).unwrap();
*bound_id = Some(context_id);
}
}
data
}
/// Gets a mutable reference to a GLContextWrapper for a WebGLContextId and makes it current if required.
fn make_current_if_needed_mut<'a>(
device: &Device,
context_id: WebGLContextId,
contexts: &'a mut FnvHashMap<WebGLContextId, GLContextData>,
bound_id: &mut Option<WebGLContextId>,
) -> Option<&'a mut GLContextData> {
let data = contexts.get_mut(&context_id);
if let Some(ref data) = data {
if Some(context_id) != *bound_id {
device.make_context_current(&data.ctx).unwrap();
*bound_id = Some(context_id);
}
}
data
}
/// Creates a `webrender_api::ImageKey` that uses shared textures.
fn create_wr_external_image(
webrender_api: &webrender_api::RenderApi,
size: Size2D<i32>,
alpha: bool,
context_id: WebGLContextId,
target: webrender_api::TextureTarget,
) -> webrender_api::ImageKey {
let descriptor = Self::image_descriptor(size, alpha);
let data = Self::external_image_data(context_id, target);
let image_key = webrender_api.generate_image_key();
let mut txn = webrender_api::Transaction::new();
txn.add_image(image_key, descriptor, data, None);
webrender_api.update_resources(txn.resource_updates);
image_key
}
/// Updates a `webrender_api::ImageKey` that uses shared textures.
fn update_wr_external_image(
webrender_api: &webrender_api::RenderApi,
size: Size2D<i32>,
alpha: bool,
context_id: WebGLContextId,
image_key: webrender_api::ImageKey,
target: webrender_api::TextureTarget,
) {
let descriptor = Self::image_descriptor(size, alpha);
let data = Self::external_image_data(context_id, target);
let mut txn = webrender_api::Transaction::new();
txn.update_image(image_key, descriptor, data, &webrender_api::DirtyRect::All);
webrender_api.update_resources(txn.resource_updates);
}
/// Helper function to create a `webrender_api::ImageDescriptor`.
fn image_descriptor(size: Size2D<i32>, alpha: bool) -> webrender_api::ImageDescriptor {
let mut flags = webrender_api::ImageDescriptorFlags::empty();
flags.set(webrender_api::ImageDescriptorFlags::IS_OPAQUE, !alpha);
webrender_api::ImageDescriptor {
size: webrender_api::units::DeviceIntSize::new(size.width, size.height),
stride: None,
format: webrender_api::ImageFormat::BGRA8,
offset: 0,
flags,
}
}
/// Helper function to create a `webrender_api::ImageData::External` instance.
fn external_image_data(
context_id: WebGLContextId,
target: webrender_api::TextureTarget,
) -> webrender_api::ImageData {
let data = webrender_api::ExternalImageData {
id: webrender_api::ExternalImageId(context_id.0 as u64),
channel_index: 0,
image_type: webrender_api::ExternalImageType::TextureHandle(target),
};
webrender_api::ImageData::External(data)
}
/// Gets the GLSL Version supported by a GLContext.
fn get_glsl_version(gl: &Gl) -> WebGLSLVersion {
let version = gl.get_string(gl::SHADING_LANGUAGE_VERSION);
// Fomat used by SHADING_LANGUAGE_VERSION query : major.minor[.release] [vendor info]
let mut values = version.split(&['.', ' '][..]);
let major = values
.next()
.and_then(|v| v.parse::<u32>().ok())
.unwrap_or(1);
let minor = values
.next()
.and_then(|v| v.parse::<u32>().ok())
.unwrap_or(20);
WebGLSLVersion { major, minor }
}
}
impl Drop for WebGLThread {
fn drop(&mut self) {
// Call remove_context functions in order to correctly delete WebRender image keys.
let context_ids: Vec<WebGLContextId> = self.contexts.keys().map(|id| *id).collect();
for id in context_ids {
self.remove_webgl_context(id);
}
}
}
/// Helper struct to store cached WebGLContext information.