-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
webgl_thread.rs
3332 lines (3128 loc) · 127 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 std::borrow::Cow;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::{slice, thread};
use bitflags::bitflags;
use byteorder::{ByteOrder, NativeEndian, WriteBytesExt};
use canvas_traits::webgl;
use canvas_traits::webgl::{
webgl_channel, ActiveAttribInfo, ActiveUniformBlockInfo, ActiveUniformInfo, AlphaTreatment,
GLContextAttributes, GLLimits, GlType, InternalFormatIntVec, ProgramLinkInfo, TexDataType,
TexFormat, WebGLBufferId, WebGLChan, WebGLCommand, WebGLCommandBacktrace, WebGLContextId,
WebGLCreateContextResult, WebGLFramebufferBindingRequest, WebGLFramebufferId, WebGLMsg,
WebGLMsgSender, WebGLProgramId, WebGLQueryId, WebGLReceiver, WebGLRenderbufferId,
WebGLSLVersion, WebGLSamplerId, WebGLSender, WebGLShaderId, WebGLSyncId, WebGLTextureId,
WebGLVersion, WebGLVertexArrayId, WebXRCommand, WebXRLayerManagerId, YAxisTreatment,
};
use euclid::default::Size2D;
use fnv::FnvHashMap;
use half::f16;
use log::{debug, error, trace, warn};
use pixels::{self, PixelFormat};
use sparkle::gl;
use sparkle::gl::{GLint, GLuint, Gl};
use surfman::chains::{PreserveBuffer, SwapChains, SwapChainsAPI};
use surfman::{
self, Adapter, Connection, Context, ContextAttributeFlags, ContextAttributes, Device,
GLVersion, SurfaceAccess, SurfaceInfo, SurfaceType,
};
use webrender::{RenderApi, RenderApiSender, Transaction};
use webrender_api::units::DeviceIntSize;
use webrender_api::{
DirtyRect, DocumentId, ExternalImageData, ExternalImageId, ExternalImageType, ImageBufferKind,
ImageData, ImageDescriptor, ImageDescriptorFlags, ImageFormat, ImageKey,
};
use webrender_traits::{WebrenderExternalImageRegistry, WebrenderImageHandlerType};
use webxr::SurfmanGL as WebXRSurfman;
use webxr_api::{
ContextId as WebXRContextId, Error as WebXRError, GLContexts as WebXRContexts,
GLTypes as WebXRTypes, LayerGrandManager as WebXRLayerGrandManager,
LayerGrandManagerAPI as WebXRLayerGrandManagerAPI, LayerId as WebXRLayerId,
LayerInit as WebXRLayerInit, LayerManager as WebXRLayerManager,
LayerManagerAPI as WebXRLayerManagerAPI, LayerManagerFactory as WebXRLayerManagerFactory,
SubImages as WebXRSubImages,
};
use crate::webgl_limits::GLLimitsDetect;
#[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,
}
#[derive(Debug)]
pub struct GLState {
webgl_version: WebGLVersion,
gl_version: GLVersion,
requested_flags: ContextAttributeFlags,
// This is the WebGL view of the color mask
// The GL view may be different: if the GL context supports alpha
// but the WebGL context doesn't, then color_write_mask.3 might be true
// but the GL color write mask is false.
color_write_mask: [bool; 4],
clear_color: (f32, f32, f32, f32),
scissor_test_enabled: bool,
// The WebGL view of the stencil write mask (see comment re `color_write_mask`)
stencil_write_mask: (u32, u32),
stencil_test_enabled: bool,
stencil_clear_value: i32,
// The WebGL view of the depth write mask (see comment re `color_write_mask`)
depth_write_mask: bool,
depth_test_enabled: bool,
depth_clear_value: f64,
// True when the default framebuffer is bound to DRAW_FRAMEBUFFER
drawing_to_default_framebuffer: bool,
default_vao: gl::GLuint,
}
impl GLState {
// Are we faking having no alpha / depth / stencil?
fn fake_no_alpha(&self) -> bool {
self.drawing_to_default_framebuffer &
!self.requested_flags.contains(ContextAttributeFlags::ALPHA)
}
fn fake_no_depth(&self) -> bool {
self.drawing_to_default_framebuffer &
!self.requested_flags.contains(ContextAttributeFlags::DEPTH)
}
fn fake_no_stencil(&self) -> bool {
self.drawing_to_default_framebuffer &
!self
.requested_flags
.contains(ContextAttributeFlags::STENCIL)
}
// We maintain invariants between the GLState object and the GL state.
fn restore_invariant(&self, gl: &Gl) {
self.restore_clear_color_invariant(gl);
self.restore_scissor_invariant(gl);
self.restore_alpha_invariant(gl);
self.restore_depth_invariant(gl);
self.restore_stencil_invariant(gl);
}
fn restore_clear_color_invariant(&self, gl: &Gl) {
let (r, g, b, a) = self.clear_color;
gl.clear_color(r, g, b, a);
}
fn restore_scissor_invariant(&self, gl: &Gl) {
if self.scissor_test_enabled {
gl.enable(gl::SCISSOR_TEST);
} else {
gl.disable(gl::SCISSOR_TEST);
}
}
fn restore_alpha_invariant(&self, gl: &Gl) {
let [r, g, b, a] = self.color_write_mask;
if self.fake_no_alpha() {
gl.color_mask(r, g, b, false);
} else {
gl.color_mask(r, g, b, a);
}
}
fn restore_depth_invariant(&self, gl: &Gl) {
if self.fake_no_depth() {
gl.depth_mask(false);
gl.disable(gl::DEPTH_TEST);
} else {
gl.depth_mask(self.depth_write_mask);
if self.depth_test_enabled {
gl.enable(gl::DEPTH_TEST);
} else {
gl.disable(gl::DEPTH_TEST);
}
}
}
fn restore_stencil_invariant(&self, gl: &Gl) {
if self.fake_no_stencil() {
gl.stencil_mask(0);
gl.disable(gl::STENCIL_TEST);
} else {
let (f, b) = self.stencil_write_mask;
gl.stencil_mask_separate(gl::FRONT, f);
gl.stencil_mask_separate(gl::BACK, b);
if self.stencil_test_enabled {
gl.enable(gl::STENCIL_TEST);
} else {
gl.disable(gl::STENCIL_TEST);
}
}
}
}
impl Default for GLState {
fn default() -> GLState {
GLState {
gl_version: GLVersion { major: 1, minor: 0 },
webgl_version: WebGLVersion::WebGL1,
requested_flags: ContextAttributeFlags::empty(),
color_write_mask: [true, true, true, true],
clear_color: (0., 0., 0., 0.),
scissor_test_enabled: false,
// Should these be 0xFFFF_FFFF?
stencil_write_mask: (0, 0),
stencil_test_enabled: false,
stencil_clear_value: 0,
depth_write_mask: true,
depth_test_enabled: false,
depth_clear_value: 1.,
default_vao: 0,
drawing_to_default_framebuffer: true,
}
}
}
/// 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 `ImageKey`s.
webrender_api: RenderApi,
webrender_doc: DocumentId,
/// 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>,
/// 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, Device>,
/// Whether this context is a GL or GLES context.
api_type: gl::GlType,
/// The bridge to WebXR
pub webxr_bridge: WebXRBridge,
}
/// The data required to initialize an instance of the WebGLThread type.
pub(crate) struct WebGLThreadInit {
pub webrender_api_sender: RenderApiSender,
pub webrender_doc: DocumentId,
pub external_images: Arc<Mutex<WebrenderExternalImageRegistry>>,
pub sender: WebGLSender<WebGLMsg>,
pub receiver: WebGLReceiver<WebGLMsg>,
pub webrender_swap_chains: SwapChains<WebGLContextId, Device>,
pub connection: Connection,
pub adapter: Adapter,
pub api_type: gl::GlType,
pub webxr_init: WebXRBridgeInit,
}
// 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,
webrender_doc,
external_images,
sender,
receiver,
webrender_swap_chains,
connection,
adapter,
api_type,
webxr_init,
}: WebGLThreadInit,
) -> Self {
WebGLThread {
device: connection
.create_device(&adapter)
.expect("Couldn't open WebGL device!"),
webrender_api: webrender_api_sender.create_api(),
webrender_doc,
contexts: Default::default(),
cached_context_info: Default::default(),
bound_context_id: None,
external_images,
sender,
receiver: receiver.into_inner(),
webrender_swap_chains,
api_type,
webxr_bridge: WebXRBridge::new(webxr_init),
}
}
/// 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".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());
while let Ok(msg) = self.receiver.recv() {
let exit = self.handle_msg(msg, &webgl_chan);
if exit {
// 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);
}
// Block on shutting-down WebRender.
self.webrender_api.shut_down(true);
return;
}
}
}
/// 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) => {
let _ = sender.send(self.resize_webgl_context(ctx_id, size));
},
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::WebXRCommand(command) => {
self.handle_webxr_command(command);
},
WebGLMsg::SwapBuffers(swap_ids, sender, sent_time) => {
self.handle_swap_buffers(swap_ids, sender, sent_time);
},
WebGLMsg::Exit => {
return true;
},
}
false
}
/// Handles a WebXR message
fn handle_webxr_command(&mut self, command: WebXRCommand) {
trace!("processing {:?}", command);
let mut contexts = WebXRBridgeContexts {
contexts: &mut self.contexts,
bound_context_id: &mut self.bound_context_id,
};
match command {
WebXRCommand::CreateLayerManager(sender) => {
let result = self
.webxr_bridge
.create_layer_manager(&mut self.device, &mut contexts);
let _ = sender.send(result);
},
WebXRCommand::DestroyLayerManager(manager_id) => {
self.webxr_bridge.destroy_layer_manager(manager_id);
},
WebXRCommand::CreateLayer(manager_id, context_id, layer_init, sender) => {
let result = self.webxr_bridge.create_layer(
manager_id,
&mut self.device,
&mut contexts,
context_id,
layer_init,
);
let _ = sender.send(result);
},
WebXRCommand::DestroyLayer(manager_id, context_id, layer_id) => {
self.webxr_bridge.destroy_layer(
manager_id,
&mut self.device,
&mut contexts,
context_id,
layer_id,
);
},
WebXRCommand::BeginFrame(manager_id, layers, sender) => {
let result = self.webxr_bridge.begin_frame(
manager_id,
&mut self.device,
&mut contexts,
&layers[..],
);
let _ = sender.send(result);
},
WebXRCommand::EndFrame(manager_id, layers, sender) => {
let result = self.webxr_bridge.end_frame(
manager_id,
&mut self.device,
&mut contexts,
&layers[..],
);
let _ = sender.send(result);
},
}
}
/// 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 {
WebGLImpl::apply(
&self.device,
&data.ctx,
&*data.gl,
&mut data.state,
&data.attributes,
command,
backtrace,
);
}
}
/// 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({:?}, {:?}, {:?})",
webgl_version, requested_size, attributes
);
// 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 requested_flags =
attributes.to_surfman_context_attribute_flags(webgl_version, self.api_type);
// Some GL implementations seem to only allow famebuffers
// to have alpha, depth and stencil if their creating context does.
// WebGL requires all contexts to be able to create framebuffers with
// alpha, depth and stencil. So we always create a context with them,
// and fake not having them if requested.
let flags = requested_flags |
ContextAttributeFlags::ALPHA |
ContextAttributeFlags::DEPTH |
ContextAttributeFlags::STENCIL;
let context_attributes = &ContextAttributes {
version: webgl_version.to_surfman_version(self.api_type),
flags: flags,
};
let context_descriptor = self
.device
.create_context_descriptor(&context_attributes)
.map_err(|err| format!("Failed to create context descriptor: {:?}", err))?;
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 mut ctx = self
.device
.create_context(&context_descriptor, None)
.map_err(|err| format!("Failed to create the GL context: {:?}", err))?;
let surface = self
.device
.create_surface(&ctx, surface_access, surface_type)
.map_err(|err| format!("Failed to create the initial surface: {:?}", err))?;
self.device
.bind_surface_to_context(&mut ctx, surface)
.map_err(|err| format!("Failed to bind initial surface: {:?}", err))?;
// https://github.com/pcwalton/surfman/issues/7
self.device
.make_context_current(&ctx)
.map_err(|err| format!("Failed to make new context current: {:?}", err))?;
let id = WebGLContextId(
self.external_images
.lock()
.expect("Lock poisoned?")
.next_id(WebrenderImageHandlerType::WebGL)
.0,
);
self.webrender_swap_chains
.create_attached_swap_chain(id, &mut self.device, &mut ctx, surface_access)
.map_err(|err| format!("Failed to create swap chain: {:?}", err))?;
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())
.map_err(|err| format!("Failed to resize swap chain: {:?}", err))?;
}
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 = requested_flags.contains(ContextAttributeFlags::ALPHA);
let image_buffer_kind = current_wr_image_buffer_kind(&self.device);
self.device.make_context_current(&ctx).unwrap();
let framebuffer = self
.device
.context_surface_info(&ctx)
.map_err(|err| format!("Failed to get context surface info: {:?}", err))?
.ok_or_else(|| format!("Failed to get context surface info"))?
.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., !has_alpha as u32 as f32);
gl.clear_depth(1.);
gl.clear_stencil(0);
gl.clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT | gl::STENCIL_BUFFER_BIT);
gl.clear_color(0., 0., 0., 0.);
debug_assert_eq!(gl.get_error(), gl::NO_ERROR);
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,
requested_flags,
default_vao,
..Default::default()
};
debug!("Created state {:?}", state);
state.restore_invariant(&*gl);
debug_assert_eq!(gl.get_error(), gl::NO_ERROR);
self.contexts.insert(
id,
GLContextData {
ctx,
gl,
state,
attributes,
},
);
let image_key = Self::create_wr_external_image(
&mut self.webrender_api,
self.webrender_doc,
size.to_i32(),
has_alpha,
id,
image_buffer_kind,
);
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>,
) -> 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) {
let alpha = data
.state
.requested_flags
.contains(ContextAttributeFlags::ALPHA);
let clear_color = [0.0, 0.0, 0.0, !alpha as i32 as f32];
swap_chain
.resize(&mut self.device, &mut data.ctx, size.to_i32())
.map_err(|err| format!("Failed to resize swap chain: {:?}", err))?;
swap_chain
.clear_surface(&mut self.device, &mut data.ctx, &*data.gl, clear_color)
.map_err(|err| format!("Failed to clear resized swap chain: {:?}", err))?;
} else {
error!("Failed to find swap chain");
}
// Reset framebuffer bindings as appropriate.
framebuffer_rebinding_info.apply(&self.device, &data.ctx, &*data.gl);
debug_assert_eq!(data.gl.get_error(), gl::NO_ERROR);
let has_alpha = data
.state
.requested_flags
.contains(ContextAttributeFlags::ALPHA);
self.update_wr_image_for_context(context_id, size.to_i32(), has_alpha);
Ok(())
}
/// 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 = Transaction::new();
txn.delete_image(info.image_key);
self.webrender_api.send_transaction(self.webrender_doc, txn)
}
// 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,
);
// Destroy WebXR layers associated with this context
let webxr_context_id = WebXRContextId::from(context_id);
let mut webxr_contexts = WebXRBridgeContexts {
contexts: &mut self.contexts,
bound_context_id: &mut self.bound_context_id,
};
self.webxr_bridge.destroy_all_layers(
&mut self.device,
&mut webxr_contexts,
webxr_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();
// 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,
context_ids: Vec<WebGLContextId>,
completed_sender: WebGLSender<u64>,
_sent_time: u64,
) {
debug!("handle_swap_buffers()");
for context_id in context_ids {
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 {:?}", context_id);
let swap_chain = self
.webrender_swap_chains
.get(context_id)
.expect("Where's the swap chain?");
debug!("Swapping {:?}", context_id);
swap_chain
.swap_buffers(
&mut self.device,
&mut data.ctx,
if data.attributes.preserve_drawing_buffer {
PreserveBuffer::Yes(&*data.gl)
} else {
PreserveBuffer::No
},
)
.unwrap();
debug_assert_eq!(data.gl.get_error(), gl::NO_ERROR);
if !data.attributes.preserve_drawing_buffer {
debug!("Clearing {:?}", context_id);
let alpha = data
.state
.requested_flags
.contains(ContextAttributeFlags::ALPHA);
let clear_color = [0.0, 0.0, 0.0, !alpha as i32 as f32];
swap_chain
.clear_surface(&mut self.device, &mut data.ctx, &*data.gl, clear_color)
.unwrap();
debug_assert_eq!(data.gl.get_error(), gl::NO_ERROR);
}
// Rebind framebuffers as appropriate.
debug!("Rebinding {:?}", context_id);
framebuffer_rebinding_info.apply(&self.device, &data.ctx, &*data.gl);
debug_assert_eq!(data.gl.get_error(), gl::NO_ERROR);
let SurfaceInfo {
size,
framebuffer_object,
id,
..
} = self
.device
.context_surface_info(&data.ctx)
.unwrap()
.unwrap();
debug!(
"... rebound framebuffer {}, new back buffer surface is {:?}",
framebuffer_object, id
);
let has_alpha = data
.state
.requested_flags
.contains(ContextAttributeFlags::ALPHA);
self.update_wr_image_for_context(context_id, size, has_alpha);
}
#[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();
}
/// Which access mode to use
fn surface_access(&self) -> SurfaceAccess {
SurfaceAccess::GPUOnly
}
/// 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: &mut RenderApi,
webrender_doc: DocumentId,
size: Size2D<i32>,
alpha: bool,
context_id: WebGLContextId,
image_buffer_kind: ImageBufferKind,
) -> ImageKey {
let descriptor = Self::image_descriptor(size, alpha);
let data = Self::external_image_data(context_id, image_buffer_kind);
let image_key = webrender_api.generate_image_key();
let mut txn = Transaction::new();
txn.add_image(image_key, descriptor, data, None);
webrender_api.send_transaction(webrender_doc, txn);
image_key
}
/// Tell WebRender to invalidate any cached tiles for a given `WebGLContextId`
/// when the underlying surface has changed e.g due to resize or buffer swap
fn update_wr_image_for_context(
&mut self,
context_id: WebGLContextId,
size: Size2D<i32>,
has_alpha: bool,
) {
let info = self.cached_context_info.get(&context_id).unwrap();
let image_buffer_kind = current_wr_image_buffer_kind(&self.device);
let descriptor = Self::image_descriptor(size, has_alpha);
let image_data = Self::external_image_data(context_id, image_buffer_kind);
let mut txn = Transaction::new();
txn.update_image(info.image_key, descriptor, image_data, &DirtyRect::All);
self.webrender_api.send_transaction(self.webrender_doc, txn);
}
/// Helper function to create a `ImageDescriptor`.
fn image_descriptor(size: Size2D<i32>, alpha: bool) -> ImageDescriptor {
let mut flags = ImageDescriptorFlags::empty();
flags.set(ImageDescriptorFlags::IS_OPAQUE, !alpha);
ImageDescriptor {
size: DeviceIntSize::new(size.width, size.height),
stride: None,
format: ImageFormat::BGRA8,
offset: 0,
flags,
}
}
/// Helper function to create a `ImageData::External` instance.
fn external_image_data(
context_id: WebGLContextId,
image_buffer_kind: ImageBufferKind,
) -> ImageData {
let data = ExternalImageData {
id: ExternalImageId(context_id.0 as u64),
channel_index: 0,
image_type: ExternalImageType::TextureHandle(image_buffer_kind),
};
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 }
}
}
/// Helper struct to store cached WebGLContext information.
struct WebGLContextInfo {
/// Currently used WebRender image key.
image_key: ImageKey,
}
// TODO(pcwalton): Add `GL_TEXTURE_EXTERNAL_OES`?
fn current_wr_image_buffer_kind(device: &Device) -> ImageBufferKind {
match device.surface_gl_texture_target() {
gl::TEXTURE_RECTANGLE => ImageBufferKind::TextureRect,
_ => ImageBufferKind::Texture2D,
}
}
/// WebGL Commands Implementation
pub struct WebGLImpl;
impl WebGLImpl {
#[allow(unsafe_code)]
pub fn apply(
device: &Device,
ctx: &Context,
gl: &Gl,
state: &mut GLState,
attributes: &GLContextAttributes,
command: WebGLCommand,
_backtrace: WebGLCommandBacktrace,
) {
debug!("WebGLImpl::apply({:?})", command);
// Ensure there are no pending GL errors from other parts of the pipeline.
debug_assert_eq!(gl.get_error(), gl::NO_ERROR);