-
Notifications
You must be signed in to change notification settings - Fork 920
/
egl.rs
1100 lines (1000 loc) · 39.2 KB
/
egl.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
use glow::HasContext;
use parking_lot::{Mutex, MutexGuard};
use raw_window_handle::{HasRawWindowHandle, RawWindowHandle};
use std::{ffi::CStr, os::raw, ptr, sync::Arc, time::Duration};
/// The amount of time to wait while trying to obtain a lock to the adapter context
const CONTEXT_LOCK_TIMEOUT_SECS: u64 = 1;
const EGL_CONTEXT_FLAGS_KHR: i32 = 0x30FC;
const EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR: i32 = 0x0001;
const EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT: i32 = 0x30BF;
const EGL_PLATFORM_WAYLAND_KHR: u32 = 0x31D8;
const EGL_PLATFORM_X11_KHR: u32 = 0x31D5;
const EGL_PLATFORM_ANGLE_ANGLE: u32 = 0x3202;
const EGL_PLATFORM_ANGLE_NATIVE_PLATFORM_TYPE_ANGLE: u32 = 0x348F;
const EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED: u32 = 0x3451;
const EGL_GL_COLORSPACE_KHR: u32 = 0x309D;
const EGL_GL_COLORSPACE_SRGB_KHR: u32 = 0x3089;
type XOpenDisplayFun =
unsafe extern "system" fn(display_name: *const raw::c_char) -> *mut raw::c_void;
type WlDisplayConnectFun =
unsafe extern "system" fn(display_name: *const raw::c_char) -> *mut raw::c_void;
type WlDisplayDisconnectFun = unsafe extern "system" fn(display: *const raw::c_void);
type WlEglWindowCreateFun = unsafe extern "system" fn(
surface: *const raw::c_void,
width: raw::c_int,
height: raw::c_int,
) -> *mut raw::c_void;
type WlEglWindowResizeFun = unsafe extern "system" fn(
window: *const raw::c_void,
width: raw::c_int,
height: raw::c_int,
dx: raw::c_int,
dy: raw::c_int,
);
type WlEglWindowDestroyFun = unsafe extern "system" fn(window: *const raw::c_void);
#[cfg(target_os = "android")]
extern "C" {
pub fn ANativeWindow_setBuffersGeometry(
window: *mut raw::c_void,
width: i32,
height: i32,
format: i32,
) -> i32;
}
type EglLabel = *const raw::c_void;
#[allow(clippy::upper_case_acronyms)]
type EGLDEBUGPROCKHR = Option<
unsafe extern "system" fn(
error: egl::Enum,
command: *const raw::c_char,
message_type: u32,
thread_label: EglLabel,
object_label: EglLabel,
message: *const raw::c_char,
),
>;
const EGL_DEBUG_MSG_CRITICAL_KHR: u32 = 0x33B9;
const EGL_DEBUG_MSG_ERROR_KHR: u32 = 0x33BA;
const EGL_DEBUG_MSG_WARN_KHR: u32 = 0x33BB;
const EGL_DEBUG_MSG_INFO_KHR: u32 = 0x33BC;
type EglDebugMessageControlFun =
unsafe extern "system" fn(proc: EGLDEBUGPROCKHR, attrib_list: *const egl::Attrib) -> raw::c_int;
unsafe extern "system" fn egl_debug_proc(
error: egl::Enum,
command_raw: *const raw::c_char,
message_type: u32,
_thread_label: EglLabel,
_object_label: EglLabel,
message_raw: *const raw::c_char,
) {
let log_severity = match message_type {
EGL_DEBUG_MSG_CRITICAL_KHR | EGL_DEBUG_MSG_ERROR_KHR => log::Level::Error,
EGL_DEBUG_MSG_WARN_KHR => log::Level::Warn,
EGL_DEBUG_MSG_INFO_KHR => log::Level::Info,
_ => log::Level::Debug,
};
let command = CStr::from_ptr(command_raw).to_string_lossy();
let message = if message_raw.is_null() {
"".into()
} else {
CStr::from_ptr(message_raw).to_string_lossy()
};
log::log!(
log_severity,
"EGL '{}' code 0x{:x}: {}",
command,
error,
message,
);
}
fn open_x_display() -> Option<(ptr::NonNull<raw::c_void>, libloading::Library)> {
log::info!("Loading X11 library to get the current display");
unsafe {
let library = libloading::Library::new("libX11.so").ok()?;
let func: libloading::Symbol<XOpenDisplayFun> = library.get(b"XOpenDisplay").unwrap();
let result = func(ptr::null());
ptr::NonNull::new(result).map(|ptr| (ptr, library))
}
}
fn test_wayland_display() -> Option<libloading::Library> {
/* We try to connect and disconnect here to simply ensure there
* is an active wayland display available.
*/
log::info!("Loading Wayland library to get the current display");
let library = unsafe {
let client_library = libloading::Library::new("libwayland-client.so").ok()?;
let wl_display_connect: libloading::Symbol<WlDisplayConnectFun> =
client_library.get(b"wl_display_connect").unwrap();
let wl_display_disconnect: libloading::Symbol<WlDisplayDisconnectFun> =
client_library.get(b"wl_display_disconnect").unwrap();
let display = ptr::NonNull::new(wl_display_connect(ptr::null()))?;
wl_display_disconnect(display.as_ptr());
libloading::Library::new("libwayland-egl.so").ok()?
};
Some(library)
}
#[derive(Clone, Copy, Debug)]
enum SrgbFrameBufferKind {
/// No support for SRGB surface
None,
/// Using EGL 1.5's support for colorspaces
Core,
/// Using EGL_KHR_gl_colorspace
Khr,
}
/// Choose GLES framebuffer configuration.
fn choose_config(
egl: &egl::DynamicInstance<egl::EGL1_4>,
display: egl::Display,
srgb_kind: SrgbFrameBufferKind,
) -> Result<(egl::Config, bool), crate::InstanceError> {
//TODO: EGL_SLOW_CONFIG
let tiers = [
(
"off-screen",
&[egl::RENDERABLE_TYPE, egl::OPENGL_ES2_BIT][..],
),
("presentation", &[egl::SURFACE_TYPE, egl::WINDOW_BIT]),
#[cfg(not(target_os = "android"))]
("native-render", &[egl::NATIVE_RENDERABLE, egl::TRUE as _]),
];
let mut attributes = Vec::with_capacity(9);
for tier_max in (0..tiers.len()).rev() {
let name = tiers[tier_max].0;
log::info!("\tTrying {}", name);
attributes.clear();
for &(_, tier_attr) in tiers[..=tier_max].iter() {
attributes.extend_from_slice(tier_attr);
}
// make sure the Alpha is enough to support sRGB
match srgb_kind {
SrgbFrameBufferKind::None => {}
_ => {
attributes.push(egl::ALPHA_SIZE);
attributes.push(8);
}
}
attributes.push(egl::NONE);
match egl.choose_first_config(display, &attributes) {
Ok(Some(config)) => {
if tier_max == 1 {
//Note: this has been confirmed to malfunction on Intel+NV laptops,
// but also on Angle.
log::warn!("EGL says it can present to the window but not natively",);
}
// Android emulator can't natively present either.
let tier_threshold = if cfg!(target_os = "android") || cfg!(windows) {
1
} else {
2
};
return Ok((config, tier_max >= tier_threshold));
}
Ok(None) => {
log::warn!("No config found!");
}
Err(e) => {
log::error!("error in choose_first_config: {:?}", e);
}
}
}
Err(crate::InstanceError)
}
fn gl_debug_message_callback(source: u32, gltype: u32, id: u32, severity: u32, message: &str) {
let source_str = match source {
glow::DEBUG_SOURCE_API => "API",
glow::DEBUG_SOURCE_WINDOW_SYSTEM => "Window System",
glow::DEBUG_SOURCE_SHADER_COMPILER => "ShaderCompiler",
glow::DEBUG_SOURCE_THIRD_PARTY => "Third Party",
glow::DEBUG_SOURCE_APPLICATION => "Application",
glow::DEBUG_SOURCE_OTHER => "Other",
_ => unreachable!(),
};
let log_severity = match severity {
glow::DEBUG_SEVERITY_HIGH => log::Level::Error,
glow::DEBUG_SEVERITY_MEDIUM => log::Level::Warn,
glow::DEBUG_SEVERITY_LOW => log::Level::Info,
glow::DEBUG_SEVERITY_NOTIFICATION => log::Level::Trace,
_ => unreachable!(),
};
let type_str = match gltype {
glow::DEBUG_TYPE_DEPRECATED_BEHAVIOR => "Deprecated Behavior",
glow::DEBUG_TYPE_ERROR => "Error",
glow::DEBUG_TYPE_MARKER => "Marker",
glow::DEBUG_TYPE_OTHER => "Other",
glow::DEBUG_TYPE_PERFORMANCE => "Performance",
glow::DEBUG_TYPE_POP_GROUP => "Pop Group",
glow::DEBUG_TYPE_PORTABILITY => "Portability",
glow::DEBUG_TYPE_PUSH_GROUP => "Push Group",
glow::DEBUG_TYPE_UNDEFINED_BEHAVIOR => "Undefined Behavior",
_ => unreachable!(),
};
log::log!(
log_severity,
"GLES: [{}/{}] ID {} : {}",
source_str,
type_str,
id,
message
);
if cfg!(debug_assertions) && log_severity == log::Level::Error {
std::process::exit(1);
}
}
/// A wrapper around a [`glow::Context`] and the required EGL context that uses locking to guarantee
/// exclusive access when shared with multiple threads.
pub struct AdapterContext {
glow_context: Mutex<glow::Context>,
egl: Arc<egl::DynamicInstance<egl::EGL1_4>>,
egl_display: egl::Display,
pub(super) egl_context: egl::Context,
egl_pbuffer: Option<egl::Surface>,
}
unsafe impl Sync for AdapterContext {}
unsafe impl Send for AdapterContext {}
/// A guard containing a lock to an [`AdapterContext`]
pub struct AdapterContextLock<'a> {
glow_context: MutexGuard<'a, glow::Context>,
egl: &'a Arc<egl::DynamicInstance<egl::EGL1_4>>,
egl_display: egl::Display,
}
impl<'a> std::ops::Deref for AdapterContextLock<'a> {
type Target = glow::Context;
fn deref(&self) -> &Self::Target {
&self.glow_context
}
}
impl<'a> Drop for AdapterContextLock<'a> {
fn drop(&mut self) {
// Make the EGL context *not* current on this thread
self.egl
.make_current(self.egl_display, None, None, None)
.expect("Cannot make EGL context not current");
}
}
impl AdapterContext {
/// Get's the [`glow::Context`] without waiting for a lock
///
/// # Safety
///
/// This should only be called when you have manually made sure that the current thread has made
/// the EGL context current and that no other thread also has the EGL context current.
/// Additionally, you must manually make the EGL context **not** current after you are done with
/// it, so that future calls to `lock()` will not fail.
///
/// > **Note:** Calling this function **will** still lock the [`glow::Context`] which adds an
/// > extra safe-guard against accidental concurrent access to the context.
pub unsafe fn get_without_egl_lock(&self) -> MutexGuard<glow::Context> {
self.glow_context
.try_lock_for(Duration::from_secs(CONTEXT_LOCK_TIMEOUT_SECS))
.expect("Could not lock adapter context. This is most-likely a deadlcok.")
}
/// Obtain a lock to the EGL context and get handle to the [`glow::Context`] that can be used to
/// do rendering.
#[track_caller]
pub fn lock<'a>(&'a self) -> AdapterContextLock<'a> {
let glow_context = self
.glow_context
// Don't lock forever. If it takes longer than 1 second to get the lock we've got a
// deadlock and should panic to show where we got stuck
.try_lock_for(Duration::from_secs(CONTEXT_LOCK_TIMEOUT_SECS))
.expect("Could not lock adapter context. This is most-likely a deadlcok.");
// Make the EGL context current on this thread
self.egl
.make_current(
self.egl_display,
self.egl_pbuffer,
self.egl_pbuffer,
Some(self.egl_context),
)
.expect("Cannot make EGL context current");
AdapterContextLock {
glow_context,
egl: &self.egl,
egl_display: self.egl_display,
}
}
}
#[derive(Debug)]
struct Inner {
egl: Arc<egl::DynamicInstance<egl::EGL1_4>>,
#[allow(unused)]
version: (i32, i32),
supports_native_window: bool,
display: egl::Display,
config: egl::Config,
context: egl::Context,
/// Dummy pbuffer (1x1).
/// Required for `eglMakeCurrent` on platforms that doesn't supports `EGL_KHR_surfaceless_context`.
pbuffer: Option<egl::Surface>,
wl_display: Option<*mut raw::c_void>,
/// Method by which the framebuffer should support srgb
srgb_kind: SrgbFrameBufferKind,
}
impl Inner {
fn create(
flags: crate::InstanceFlags,
egl: Arc<egl::DynamicInstance<egl::EGL1_4>>,
display: egl::Display,
) -> Result<Self, crate::InstanceError> {
let version = egl.initialize(display).map_err(|_| crate::InstanceError)?;
let vendor = egl.query_string(Some(display), egl::VENDOR).unwrap();
let display_extensions = egl
.query_string(Some(display), egl::EXTENSIONS)
.unwrap()
.to_string_lossy();
log::info!("Display vendor {:?}, version {:?}", vendor, version,);
log::debug!(
"Display extensions: {:#?}",
display_extensions.split_whitespace().collect::<Vec<_>>()
);
let srgb_kind = if version >= (1, 5) {
log::info!("\tEGL surface: +srgb");
SrgbFrameBufferKind::Core
} else if display_extensions.contains("EGL_KHR_gl_colorspace") {
log::info!("\tEGL surface: +srgb khr");
SrgbFrameBufferKind::Khr
} else {
log::warn!("\tEGL surface: -srgb");
SrgbFrameBufferKind::None
};
if log::max_level() >= log::LevelFilter::Trace {
log::trace!("Configurations:");
let config_count = egl.get_config_count(display).unwrap();
let mut configurations = Vec::with_capacity(config_count);
egl.get_configs(display, &mut configurations).unwrap();
for &config in configurations.iter() {
log::trace!("\tCONFORMANT=0x{:X}, RENDERABLE=0x{:X}, NATIVE_RENDERABLE=0x{:X}, SURFACE_TYPE=0x{:X}, ALPHA_SIZE={}",
egl.get_config_attrib(display, config, egl::CONFORMANT).unwrap(),
egl.get_config_attrib(display, config, egl::RENDERABLE_TYPE).unwrap(),
egl.get_config_attrib(display, config, egl::NATIVE_RENDERABLE).unwrap(),
egl.get_config_attrib(display, config, egl::SURFACE_TYPE).unwrap(),
egl.get_config_attrib(display, config, egl::ALPHA_SIZE).unwrap(),
);
}
}
let (config, supports_native_window) = choose_config(&egl, display, srgb_kind)?;
egl.bind_api(egl::OPENGL_ES_API).unwrap();
let needs_robustness = true;
let mut khr_context_flags = 0;
let supports_khr_context = display_extensions.contains("EGL_KHR_create_context");
//TODO: make it so `Device` == EGL Context
let mut context_attributes = vec![
egl::CONTEXT_CLIENT_VERSION,
3, // Request GLES 3.0 or higher
];
if flags.contains(crate::InstanceFlags::DEBUG) {
if version >= (1, 5) {
log::info!("\tEGL context: +debug");
context_attributes.push(egl::CONTEXT_OPENGL_DEBUG);
context_attributes.push(egl::TRUE as _);
} else if supports_khr_context {
log::info!("\tEGL context: +debug KHR");
khr_context_flags |= EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR;
} else {
log::info!("\tEGL context: -debug");
}
}
if needs_robustness {
//Note: the core version can fail if robustness is not supported
// (regardless of whether the extension is supported!).
// In fact, Angle does precisely that awful behavior, so we don't try it there.
if version >= (1, 5) && !display_extensions.contains("EGL_ANGLE_") {
log::info!("\tEGL context: +robust access");
context_attributes.push(egl::CONTEXT_OPENGL_ROBUST_ACCESS);
context_attributes.push(egl::TRUE as _);
} else if display_extensions.contains("EGL_EXT_create_context_robustness") {
log::info!("\tEGL context: +robust access EXT");
context_attributes.push(EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT);
context_attributes.push(egl::TRUE as _);
} else {
//Note: we aren't trying `EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR`
// because it's for desktop GL only, not GLES.
log::warn!("\tEGL context: -robust access");
}
//TODO do we need `egl::CONTEXT_OPENGL_NOTIFICATION_STRATEGY_EXT`?
}
if khr_context_flags != 0 {
context_attributes.push(EGL_CONTEXT_FLAGS_KHR);
context_attributes.push(khr_context_flags);
}
context_attributes.push(egl::NONE);
let context = match egl.create_context(display, config, None, &context_attributes) {
Ok(context) => context,
Err(e) => {
log::warn!("unable to create GLES 3.x context: {:?}", e);
return Err(crate::InstanceError);
}
};
// Testing if context can be binded without surface
// and creating dummy pbuffer surface if not.
let pbuffer =
if version >= (1, 5) || display_extensions.contains("EGL_KHR_surfaceless_context") {
log::info!("\tEGL context: +surfaceless");
None
} else {
let attributes = [egl::WIDTH, 1, egl::HEIGHT, 1, egl::NONE];
egl.create_pbuffer_surface(display, config, &attributes)
.map(Some)
.map_err(|e| {
log::warn!("Error in create_pbuffer_surface: {:?}", e);
crate::InstanceError
})?
};
Ok(Self {
egl,
display,
version,
supports_native_window,
config,
context,
pbuffer,
wl_display: None,
srgb_kind,
})
}
}
impl Drop for Inner {
fn drop(&mut self) {
if let Err(e) = self.egl.destroy_context(self.display, self.context) {
log::warn!("Error in destroy_context: {:?}", e);
}
if let Err(e) = self.egl.terminate(self.display) {
log::warn!("Error in terminate: {:?}", e);
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum WindowKind {
Wayland,
X11,
AngleX11,
Unknown,
}
#[derive(Clone, Debug)]
struct WindowSystemInterface {
library: Option<Arc<libloading::Library>>,
kind: WindowKind,
}
pub struct Instance {
wsi: WindowSystemInterface,
flags: crate::InstanceFlags,
inner: Mutex<Inner>,
}
unsafe impl Send for Instance {}
unsafe impl Sync for Instance {}
impl crate::Instance<super::Api> for Instance {
unsafe fn init(desc: &crate::InstanceDescriptor) -> Result<Self, crate::InstanceError> {
let egl_result = if cfg!(windows) {
egl::DynamicInstance::<egl::EGL1_4>::load_required_from_filename("libEGL.dll")
} else if cfg!(any(target_os = "macos", target_os = "ios")) {
egl::DynamicInstance::<egl::EGL1_4>::load_required_from_filename("libEGL.dylib")
} else {
egl::DynamicInstance::<egl::EGL1_4>::load_required()
};
let egl = match egl_result {
Ok(egl) => Arc::new(egl),
Err(e) => {
log::info!("Unable to open libEGL: {:?}", e);
return Err(crate::InstanceError);
}
};
let client_extensions = egl.query_string(None, egl::EXTENSIONS);
let client_ext_str = match client_extensions {
Ok(ext) => ext.to_string_lossy().into_owned(),
Err(_) => String::new(),
};
log::debug!(
"Client extensions: {:#?}",
client_ext_str.split_whitespace().collect::<Vec<_>>()
);
let wayland_library = if client_ext_str.contains(&"EGL_EXT_platform_wayland") {
test_wayland_display()
} else {
None
};
let x11_display_library = if client_ext_str.contains(&"EGL_EXT_platform_x11") {
open_x_display()
} else {
None
};
let angle_x11_display_library = if client_ext_str.contains(&"EGL_ANGLE_platform_angle") {
open_x_display()
} else {
None
};
let (display, wsi_library, wsi_kind) = if let (Some(library), Some(egl)) =
(wayland_library, egl.upcast::<egl::EGL1_5>())
{
log::info!("Using Wayland platform");
let display_attributes = [egl::ATTRIB_NONE];
let display = egl
.get_platform_display(
EGL_PLATFORM_WAYLAND_KHR,
egl::DEFAULT_DISPLAY,
&display_attributes,
)
.unwrap();
(display, Some(Arc::new(library)), WindowKind::Wayland)
} else if let (Some((display, library)), Some(egl)) =
(x11_display_library, egl.upcast::<egl::EGL1_5>())
{
log::info!("Using X11 platform");
let display_attributes = [egl::ATTRIB_NONE];
let display = egl
.get_platform_display(EGL_PLATFORM_X11_KHR, display.as_ptr(), &display_attributes)
.unwrap();
(display, Some(Arc::new(library)), WindowKind::X11)
} else if let (Some((display, library)), Some(egl)) =
(angle_x11_display_library, egl.upcast::<egl::EGL1_5>())
{
log::info!("Using Angle platform with X11");
let display_attributes = [
EGL_PLATFORM_ANGLE_NATIVE_PLATFORM_TYPE_ANGLE as egl::Attrib,
EGL_PLATFORM_X11_KHR as egl::Attrib,
EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED as egl::Attrib,
if desc.flags.contains(crate::InstanceFlags::VALIDATION) {
1
} else {
0
},
egl::ATTRIB_NONE,
];
let display = egl
.get_platform_display(
EGL_PLATFORM_ANGLE_ANGLE,
display.as_ptr(),
&display_attributes,
)
.unwrap();
(display, Some(Arc::new(library)), WindowKind::AngleX11)
} else {
log::info!("Using default platform");
let display = egl.get_display(egl::DEFAULT_DISPLAY).unwrap();
(display, None, WindowKind::Unknown)
};
if desc.flags.contains(crate::InstanceFlags::VALIDATION)
&& client_ext_str.contains(&"EGL_KHR_debug")
{
log::info!("Enabling EGL debug output");
let function: EglDebugMessageControlFun =
std::mem::transmute(egl.get_proc_address("eglDebugMessageControlKHR").unwrap());
let attributes = [
EGL_DEBUG_MSG_CRITICAL_KHR as egl::Attrib,
1,
EGL_DEBUG_MSG_ERROR_KHR as egl::Attrib,
1,
EGL_DEBUG_MSG_WARN_KHR as egl::Attrib,
1,
EGL_DEBUG_MSG_INFO_KHR as egl::Attrib,
1,
egl::ATTRIB_NONE,
];
(function)(Some(egl_debug_proc), attributes.as_ptr());
}
let inner = Inner::create(desc.flags, egl, display)?;
Ok(Instance {
wsi: WindowSystemInterface {
library: wsi_library,
kind: wsi_kind,
},
flags: desc.flags,
inner: Mutex::new(inner),
})
}
#[cfg_attr(target_os = "macos", allow(unused, unused_mut, unreachable_code))]
unsafe fn create_surface(
&self,
has_handle: &impl HasRawWindowHandle,
) -> Result<Surface, crate::InstanceError> {
use raw_window_handle::RawWindowHandle as Rwh;
let raw_window_handle = has_handle.raw_window_handle();
#[cfg_attr(target_os = "android", allow(unused_mut))]
let mut inner = self.inner.lock();
match raw_window_handle {
Rwh::Xlib(_) => {}
Rwh::Xcb(_) => {}
Rwh::Win32(_) => {}
Rwh::AppKit(_) => {}
#[cfg(target_os = "android")]
Rwh::AndroidNdk(handle) => {
let format = inner
.egl
.get_config_attrib(inner.display, inner.config, egl::NATIVE_VISUAL_ID)
.unwrap();
let ret = ANativeWindow_setBuffersGeometry(handle.a_native_window, 0, 0, format);
if ret != 0 {
log::error!("Error returned from ANativeWindow_setBuffersGeometry");
return Err(crate::InstanceError);
}
}
Rwh::Wayland(handle) => {
/* Wayland displays are not sharable between surfaces so if the
* surface we receive from this handle is from a different
* display, we must re-initialize the context.
*
* See gfx-rs/gfx#3545
*/
log::warn!("Re-initializing Gles context due to Wayland window");
if inner
.wl_display
.map(|ptr| ptr != handle.display)
.unwrap_or(true)
{
use std::ops::DerefMut;
let display_attributes = [egl::ATTRIB_NONE];
let display = inner
.egl
.upcast::<egl::EGL1_5>()
.unwrap()
.get_platform_display(
EGL_PLATFORM_WAYLAND_KHR,
handle.display,
&display_attributes,
)
.unwrap();
let new_inner = Inner::create(self.flags, inner.egl.clone(), display)
.map_err(|_| crate::InstanceError)?;
let old_inner = std::mem::replace(inner.deref_mut(), new_inner);
inner.wl_display = Some(handle.display);
drop(old_inner);
}
}
other => {
log::error!("Unsupported window: {:?}", other);
return Err(crate::InstanceError);
}
};
inner
.egl
.make_current(inner.display, None, None, None)
.unwrap();
Ok(Surface {
egl: Arc::clone(&inner.egl),
wsi: self.wsi.clone(),
config: inner.config,
display: inner.display,
context: inner.context,
presentable: inner.supports_native_window,
pbuffer: inner.pbuffer,
raw_window_handle,
swapchain: None,
srgb_kind: inner.srgb_kind,
})
}
unsafe fn destroy_surface(&self, _surface: Surface) {}
unsafe fn enumerate_adapters(&self) -> Vec<crate::ExposedAdapter<super::Api>> {
let inner = self.inner.lock();
inner
.egl
.make_current(
inner.display,
inner.pbuffer,
inner.pbuffer,
Some(inner.context),
)
.unwrap();
let gl = glow::Context::from_loader_function(|name| {
inner
.egl
.get_proc_address(name)
.map_or(ptr::null(), |p| p as *const _)
});
if self.flags.contains(crate::InstanceFlags::DEBUG) && gl.supports_debug() {
log::info!(
"Max label length: {}",
gl.get_parameter_i32(glow::MAX_LABEL_LENGTH)
);
}
if self.flags.contains(crate::InstanceFlags::VALIDATION) && gl.supports_debug() {
log::info!("Enabling GLES debug output");
gl.enable(glow::DEBUG_OUTPUT);
gl.debug_message_callback(gl_debug_message_callback);
}
inner
.egl
.make_current(inner.display, None, None, None)
.unwrap();
super::Adapter::expose(AdapterContext {
glow_context: Mutex::new(gl),
egl: inner.egl.clone(),
egl_display: inner.display,
egl_context: inner.context,
egl_pbuffer: inner.pbuffer,
})
.into_iter()
.collect()
}
}
#[derive(Debug)]
pub struct Swapchain {
surface: egl::Surface,
wl_window: Option<*mut raw::c_void>,
framebuffer: glow::Framebuffer,
renderbuffer: glow::Renderbuffer,
/// Extent because the window lies
extent: wgt::Extent3d,
format: wgt::TextureFormat,
format_desc: super::TextureFormatDesc,
#[allow(unused)]
sample_type: wgt::TextureSampleType,
}
#[derive(Debug)]
pub struct Surface {
egl: Arc<egl::DynamicInstance<egl::EGL1_4>>,
wsi: WindowSystemInterface,
config: egl::Config,
display: egl::Display,
context: egl::Context,
#[allow(unused)]
pbuffer: Option<egl::Surface>,
pub(super) presentable: bool,
raw_window_handle: RawWindowHandle,
swapchain: Option<Swapchain>,
srgb_kind: SrgbFrameBufferKind,
}
unsafe impl Send for Surface {}
unsafe impl Sync for Surface {}
impl Surface {
pub(super) unsafe fn present(
&mut self,
_suf_texture: super::Texture,
gl: &glow::Context,
) -> Result<(), crate::SurfaceError> {
let sc = self.swapchain.as_ref().unwrap();
self.egl
.make_current(
self.display,
Some(sc.surface),
Some(sc.surface),
Some(self.context),
)
.map_err(|e| {
log::error!("make_current(surface) failed: {}", e);
crate::SurfaceError::Lost
})?;
gl.disable(glow::SCISSOR_TEST);
gl.color_mask(true, true, true, true);
gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, None);
gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(sc.framebuffer));
// Note the Y-flipping here. GL's presentation is not flipped,
// but main rendering is. Therefore, we Y-flip the output positions
// in the shader, and also this blit.
gl.blit_framebuffer(
0,
sc.extent.height as i32,
sc.extent.width as i32,
0,
0,
0,
sc.extent.width as i32,
sc.extent.height as i32,
glow::COLOR_BUFFER_BIT,
glow::NEAREST,
);
gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None);
self.egl
.swap_buffers(self.display, sc.surface)
.map_err(|e| {
log::error!("swap_buffers failed: {}", e);
crate::SurfaceError::Lost
})?;
self.egl
.make_current(self.display, None, None, None)
.map_err(|e| {
log::error!("make_current(null) failed: {}", e);
crate::SurfaceError::Lost
})?;
Ok(())
}
unsafe fn unconfigure_impl(
&mut self,
device: &super::Device,
) -> Option<(egl::Surface, Option<*mut raw::c_void>)> {
let gl = &device.shared.context.lock();
match self.swapchain.take() {
Some(sc) => {
gl.delete_renderbuffer(sc.renderbuffer);
gl.delete_framebuffer(sc.framebuffer);
Some((sc.surface, sc.wl_window))
}
None => None,
}
}
pub fn supports_srgb(&self) -> bool {
match self.srgb_kind {
SrgbFrameBufferKind::None => false,
_ => true,
}
}
}
impl crate::Surface<super::Api> for Surface {
unsafe fn configure(
&mut self,
device: &super::Device,
config: &crate::SurfaceConfiguration,
) -> Result<(), crate::SurfaceError> {
use raw_window_handle::RawWindowHandle as Rwh;
let (surface, wl_window) = match self.unconfigure_impl(device) {
Some(pair) => pair,
None => {
let mut wl_window = None;
let (mut temp_xlib_handle, mut temp_xcb_handle);
#[allow(trivial_casts)]
let native_window_ptr = match (self.wsi.kind, self.raw_window_handle) {
(WindowKind::Unknown | WindowKind::X11, Rwh::Xlib(handle)) => {
temp_xlib_handle = handle.window;
&mut temp_xlib_handle as *mut _ as *mut std::ffi::c_void
}
(WindowKind::AngleX11, Rwh::Xlib(handle)) => {
handle.window as *mut std::ffi::c_void
}
(WindowKind::Unknown | WindowKind::X11, Rwh::Xcb(handle)) => {
temp_xcb_handle = handle.window;
&mut temp_xcb_handle as *mut _ as *mut std::ffi::c_void
}
(WindowKind::AngleX11, Rwh::Xcb(handle)) => {
handle.window as *mut std::ffi::c_void
}
(WindowKind::Unknown, Rwh::AndroidNdk(handle)) => handle.a_native_window,
(WindowKind::Wayland, Rwh::Wayland(handle)) => {
let library = self.wsi.library.as_ref().unwrap();
let wl_egl_window_create: libloading::Symbol<WlEglWindowCreateFun> =
library.get(b"wl_egl_window_create").unwrap();
let window = wl_egl_window_create(handle.surface, 640, 480) as *mut _
as *mut std::ffi::c_void;
wl_window = Some(window);
window
}
(WindowKind::Unknown, Rwh::Win32(handle)) => handle.hwnd,
(WindowKind::Unknown, Rwh::AppKit(handle)) => handle.ns_view,
_ => {
log::warn!(
"Initialized platform {:?} doesn't work with window {:?}",
self.wsi.kind,
self.raw_window_handle
);
return Err(crate::SurfaceError::Other("incompatible window kind"));
}
};
let mut attributes = vec![
egl::RENDER_BUFFER,
// We don't want any of the buffering done by the driver, because we
// manage a swapchain on our side.
// Some drivers just fail on surface creation seeing `EGL_SINGLE_BUFFER`.
if cfg!(target_os = "android")
|| cfg!(windows)
|| self.wsi.kind == WindowKind::AngleX11
{
egl::BACK_BUFFER
} else {
egl::SINGLE_BUFFER
},
];
match self.srgb_kind {
SrgbFrameBufferKind::None => {}
SrgbFrameBufferKind::Core => {
attributes.push(egl::GL_COLORSPACE);
attributes.push(egl::GL_COLORSPACE_SRGB);
}
SrgbFrameBufferKind::Khr => {
attributes.push(EGL_GL_COLORSPACE_KHR as i32);
attributes.push(EGL_GL_COLORSPACE_SRGB_KHR as i32);
}
}
attributes.push(egl::ATTRIB_NONE as i32);
// Careful, we can still be in 1.4 version even if `upcast` succeeds
let raw_result = match self.egl.upcast::<egl::EGL1_5>() {
Some(egl) if self.wsi.kind != WindowKind::Unknown => {
let attributes_usize = attributes
.into_iter()
.map(|v| v as usize)
.collect::<Vec<_>>();
egl.create_platform_window_surface(
self.display,
self.config,
native_window_ptr,
&attributes_usize,
)
}
_ => self.egl.create_window_surface(
self.display,
self.config,
native_window_ptr,
Some(&attributes),
),
};