Skip to main content

wgpu_hal/gles/
adapter.rs

1use alloc::{borrow::ToOwned as _, format, string::String, sync::Arc, vec, vec::Vec};
2
3use glow::HasContext;
4use wgpu_sync::{atomic::AtomicU8, Mutex};
5use wgt::AstcChannel;
6
7use crate::auxil::db;
8use crate::gles::ShaderClearProgram;
9
10// https://webgl2fundamentals.org/webgl/lessons/webgl-data-textures.html
11
12const GL_UNMASKED_VENDOR_WEBGL: u32 = 0x9245;
13const GL_UNMASKED_RENDERER_WEBGL: u32 = 0x9246;
14
15impl super::Adapter {
16    pub fn get_glsl_version(&self) -> naga::back::glsl::Version {
17        self.shared.shading_language_version
18    }
19
20    /// Note that this function is intentionally lenient in regards to parsing,
21    /// and will try to recover at least the first two version numbers without
22    /// resulting in an `Err`.
23    /// # Notes
24    /// `WebGL 2` version returned as `OpenGL ES 3.0`
25    fn parse_version(mut src: &str) -> Result<(u8, u8), crate::InstanceError> {
26        let webgl_sig = "WebGL ";
27        // According to the WebGL specification
28        // VERSION  WebGL<space>1.0<space><vendor-specific information>
29        // SHADING_LANGUAGE_VERSION WebGL<space>GLSL<space>ES<space>1.0<space><vendor-specific information>
30        let is_webgl = src.starts_with(webgl_sig);
31        if is_webgl {
32            let pos = src.rfind(webgl_sig).unwrap_or(0);
33            src = &src[pos + webgl_sig.len()..];
34        } else {
35            let es_sig = " ES ";
36            match src.rfind(es_sig) {
37                Some(pos) => {
38                    src = &src[pos + es_sig.len()..];
39                }
40                None => {
41                    return Err(crate::InstanceError::new(format!(
42                        "OpenGL version {src:?} does not contain 'ES'"
43                    )));
44                }
45            }
46        };
47
48        let glsl_es_sig = "GLSL ES ";
49        let is_glsl = match src.find(glsl_es_sig) {
50            Some(pos) => {
51                src = &src[pos + glsl_es_sig.len()..];
52                true
53            }
54            None => false,
55        };
56
57        Self::parse_full_version(src).map(|(major, minor)| {
58            (
59                // Return WebGL 2.0 version as OpenGL ES 3.0
60                if is_webgl && !is_glsl {
61                    major + 1
62                } else {
63                    major
64                },
65                minor,
66            )
67        })
68    }
69
70    /// According to the OpenGL specification, the version information is
71    /// expected to follow the following syntax:
72    ///
73    /// ~~~bnf
74    /// <major>       ::= <number>
75    /// <minor>       ::= <number>
76    /// <revision>    ::= <number>
77    /// <vendor-info> ::= <string>
78    /// <release>     ::= <major> "." <minor> ["." <release>]
79    /// <version>     ::= <release> [" " <vendor-info>]
80    /// ~~~
81    ///
82    /// Note that this function is intentionally lenient in regards to parsing,
83    /// and will try to recover at least the first two version numbers without
84    /// resulting in an `Err`.
85    pub(super) fn parse_full_version(src: &str) -> Result<(u8, u8), crate::InstanceError> {
86        let (version, _vendor_info) = match src.find(' ') {
87            Some(i) => (&src[..i], src[i + 1..].to_owned()),
88            None => (src, String::new()),
89        };
90
91        // TODO: make this even more lenient so that we can also accept
92        // `<major> "." <minor> [<???>]`
93        let mut it = version.split('.');
94        let major = it.next().and_then(|s| s.parse().ok());
95        let minor = it.next().and_then(|s| {
96            let trimmed = if s.starts_with('0') {
97                "0"
98            } else {
99                s.trim_end_matches('0')
100            };
101            trimmed.parse().ok()
102        });
103
104        match (major, minor) {
105            (Some(major), Some(minor)) => Ok((major, minor)),
106            _ => Err(crate::InstanceError::new(format!(
107                "unable to extract OpenGL version from {version:?}"
108            ))),
109        }
110    }
111
112    fn make_info(vendor_orig: String, renderer_orig: String, version: String) -> wgt::AdapterInfo {
113        let vendor = vendor_orig.to_lowercase();
114        let renderer = renderer_orig.to_lowercase();
115
116        // opengl has no way to discern device_type, so we can try to infer it from the renderer string
117        let strings_that_imply_integrated = [
118            " xpress", // space here is on purpose so we don't match express
119            "amd renoir",
120            "radeon hd 4200",
121            "radeon hd 4250",
122            "radeon hd 4290",
123            "radeon hd 4270",
124            "radeon hd 4225",
125            "radeon hd 3100",
126            "radeon hd 3200",
127            "radeon hd 3000",
128            "radeon hd 3300",
129            "radeon(tm) r4 graphics",
130            "radeon(tm) r5 graphics",
131            "radeon(tm) r6 graphics",
132            "radeon(tm) r7 graphics",
133            "radeon r7 graphics",
134            "nforce", // all nvidia nforce are integrated
135            "tegra",  // all nvidia tegra are integrated
136            "shield", // all nvidia shield are integrated
137            "igp",
138            "mali",
139            "intel",
140            "v3d",
141            "apple m", // all apple m are integrated
142        ];
143        let strings_that_imply_cpu = ["mesa offscreen", "swiftshader", "llvmpipe"];
144
145        //TODO: handle Intel Iris XE as discreet
146        let inferred_device_type = if vendor.contains("qualcomm")
147            || vendor.contains("intel")
148            || strings_that_imply_integrated
149                .iter()
150                .any(|&s| renderer.contains(s))
151        {
152            wgt::DeviceType::IntegratedGpu
153        } else if strings_that_imply_cpu.iter().any(|&s| renderer.contains(s)) {
154            wgt::DeviceType::Cpu
155        } else {
156            // At this point the Device type is Unknown.
157            // It's most likely DiscreteGpu, but we do not know for sure.
158            // Use "Other" to avoid possibly making incorrect assumptions.
159            // Note that if this same device is available under some other API (ex: Vulkan),
160            // It will mostly likely get a different device type (probably DiscreteGpu).
161            wgt::DeviceType::Other
162        };
163
164        // source: Sascha Willems at Vulkan
165        let vendor_id = if vendor.contains("amd") {
166            db::amd::VENDOR
167        } else if vendor.contains("imgtec") {
168            db::imgtec::VENDOR
169        } else if vendor.contains("nvidia") {
170            db::nvidia::VENDOR
171        } else if vendor.contains("arm") {
172            db::arm::VENDOR
173        } else if vendor.contains("qualcomm") {
174            db::qualcomm::VENDOR
175        } else if vendor.contains("intel") {
176            db::intel::VENDOR
177        } else if vendor.contains("broadcom") {
178            db::broadcom::VENDOR
179        } else if vendor.contains("mesa") {
180            db::mesa::VENDOR
181        } else if vendor.contains("apple") {
182            db::apple::VENDOR
183        } else {
184            0
185        };
186
187        wgt::AdapterInfo {
188            name: renderer_orig,
189            vendor: vendor_id,
190            driver_info: version,
191            ..wgt::AdapterInfo::new(inferred_device_type, wgt::Backend::Gl)
192        }
193    }
194
195    pub(super) unsafe fn expose(
196        context: super::AdapterContext,
197        backend_options: wgt::GlBackendOptions,
198    ) -> Option<crate::ExposedAdapter<super::Api>> {
199        let gl = context.lock();
200        let extensions = gl.supported_extensions();
201
202        let (vendor_const, renderer_const) = if extensions.contains("WEBGL_debug_renderer_info") {
203            // emscripten doesn't enable "WEBGL_debug_renderer_info" extension by default. so, we do it manually.
204            // See https://github.com/gfx-rs/wgpu/issues/3245 for context
205            #[cfg(Emscripten)]
206            if unsafe {
207                super::emscripten::enable_extension(c"WEBGL_debug_renderer_info".to_str().unwrap())
208            } {
209                (GL_UNMASKED_VENDOR_WEBGL, GL_UNMASKED_RENDERER_WEBGL)
210            } else {
211                (glow::VENDOR, glow::RENDERER)
212            }
213            // glow already enables WEBGL_debug_renderer_info on wasm32-unknown-unknown target by default.
214            #[cfg(not(Emscripten))]
215            (GL_UNMASKED_VENDOR_WEBGL, GL_UNMASKED_RENDERER_WEBGL)
216        } else {
217            (glow::VENDOR, glow::RENDERER)
218        };
219
220        let vendor = unsafe { gl.get_parameter_string(vendor_const) };
221        let renderer = unsafe { gl.get_parameter_string(renderer_const) };
222        let version = unsafe { gl.get_parameter_string(glow::VERSION) };
223        log::debug!("Vendor: {vendor}");
224        log::debug!("Renderer: {renderer}");
225        log::debug!("Version: {version}");
226
227        let full_ver = Self::parse_full_version(&version).ok();
228        let es_ver = full_ver.map_or_else(|| Self::parse_version(&version).ok(), |_| None);
229
230        if let Some(full_ver) = full_ver {
231            let core_profile = (full_ver >= (3, 2)).then(|| unsafe {
232                gl.get_parameter_i32(glow::CONTEXT_PROFILE_MASK)
233                    & glow::CONTEXT_CORE_PROFILE_BIT as i32
234                    != 0
235            });
236            log::trace!(
237                "Profile: {}",
238                core_profile
239                    .map(|core_profile| if core_profile {
240                        "Core"
241                    } else {
242                        "Compatibility"
243                    })
244                    .unwrap_or("Legacy")
245            );
246        }
247
248        if es_ver.is_none() && full_ver.is_none() {
249            log::warn!("Unable to parse OpenGL version");
250            return None;
251        }
252
253        if let Some(es_ver) = es_ver {
254            if es_ver < (3, 0) {
255                log::warn!(
256                    "Returned GLES context is {}.{}, when 3.0+ was requested",
257                    es_ver.0,
258                    es_ver.1
259                );
260                return None;
261            }
262        }
263
264        if let Some(full_ver) = full_ver {
265            if full_ver < (3, 3) {
266                log::warn!(
267                    "Returned GL context is {}.{}, when 3.3+ is needed",
268                    full_ver.0,
269                    full_ver.1
270                );
271                return None;
272            }
273        }
274
275        let shading_language_version = {
276            let sl_version = unsafe { gl.get_parameter_string(glow::SHADING_LANGUAGE_VERSION) };
277            log::debug!("SL version: {sl_version}");
278            if full_ver.is_some() {
279                let (sl_major, sl_minor) = Self::parse_full_version(&sl_version).ok()?;
280                let mut value = sl_major as u16 * 100 + sl_minor as u16 * 10;
281                // Naga doesn't think it supports GL 460+, so we cap it at 450
282                if value > 450 {
283                    value = 450;
284                }
285                naga::back::glsl::Version::Desktop(value)
286            } else {
287                let (sl_major, sl_minor) = Self::parse_version(&sl_version).ok()?;
288                let value = sl_major as u16 * 100 + sl_minor as u16 * 10;
289                naga::back::glsl::Version::Embedded {
290                    version: value,
291                    is_webgl: cfg!(any(webgl, Emscripten)),
292                }
293            }
294        };
295
296        log::debug!("Supported GL Extensions: {extensions:#?}");
297
298        let supported = |(req_es_major, req_es_minor), (req_full_major, req_full_minor)| {
299            let es_supported = es_ver
300                .map(|es_ver| es_ver >= (req_es_major, req_es_minor))
301                .unwrap_or_default();
302
303            let full_supported = full_ver
304                .map(|full_ver| full_ver >= (req_full_major, req_full_minor))
305                .unwrap_or_default();
306
307            es_supported || full_supported
308        };
309
310        let supports_storage =
311            supported((3, 1), (4, 3)) || extensions.contains("GL_ARB_shader_storage_buffer_object");
312        let supports_compute =
313            supported((3, 1), (4, 3)) || extensions.contains("GL_ARB_compute_shader");
314        let supports_work_group_params = supports_compute;
315
316        // ANGLE provides renderer strings like: "ANGLE (Apple, Apple M1 Pro, OpenGL 4.1)"
317        let is_angle = renderer.contains("ANGLE");
318
319        let vertex_shader_storage_blocks = if supports_storage {
320            let value =
321                (unsafe { gl.get_parameter_i32(glow::MAX_VERTEX_SHADER_STORAGE_BLOCKS) } as u32);
322
323            if value == 0 && extensions.contains("GL_ARB_shader_storage_buffer_object") {
324                // The driver for AMD Radeon HD 5870 returns zero here, so assume the value matches the compute shader storage block count.
325                // Windows doesn't recognize `GL_MAX_VERTEX_ATTRIB_STRIDE`.
326                let new = (unsafe { gl.get_parameter_i32(glow::MAX_COMPUTE_SHADER_STORAGE_BLOCKS) }
327                    as u32);
328                log::debug!("Max vertex shader storage blocks is zero, but GL_ARB_shader_storage_buffer_object is specified. Assuming the compute value {new}");
329                new
330            } else {
331                value
332            }
333        } else {
334            0
335        };
336        let fragment_shader_storage_blocks = if supports_storage {
337            (unsafe { gl.get_parameter_i32(glow::MAX_FRAGMENT_SHADER_STORAGE_BLOCKS) } as u32)
338        } else {
339            0
340        };
341        let vertex_shader_storage_textures = if supports_storage {
342            (unsafe { gl.get_parameter_i32(glow::MAX_VERTEX_IMAGE_UNIFORMS) } as u32)
343        } else {
344            0
345        };
346        let fragment_shader_storage_textures = if supports_storage {
347            (unsafe { gl.get_parameter_i32(glow::MAX_FRAGMENT_IMAGE_UNIFORMS) } as u32)
348        } else {
349            0
350        };
351        let max_storage_block_size = if supports_storage {
352            (unsafe { gl.get_parameter_i32(glow::MAX_SHADER_STORAGE_BLOCK_SIZE) } as u32)
353        } else {
354            0
355        };
356        let max_element_index = unsafe { gl.get_parameter_i32(glow::MAX_ELEMENT_INDEX) } as u32;
357
358        // WORKAROUND: In order to work around an issue with GL on RPI4 and similar, we ignore a
359        // zero vertex ssbo count if there are vertex sstos. (more info:
360        // https://github.com/gfx-rs/wgpu/pull/1607#issuecomment-874938961) The hardware does not
361        // want us to write to these SSBOs, but GLES cannot express that. We detect this case and
362        // disable writing to SSBOs.
363        let vertex_ssbo_false_zero =
364            vertex_shader_storage_blocks == 0 && vertex_shader_storage_textures != 0;
365        if vertex_ssbo_false_zero {
366            // We only care about fragment here as the 0 is a lie.
367            log::debug!("Max vertex shader SSBO == 0 and SSTO != 0. Interpreting as false zero.");
368        }
369
370        let max_storage_buffers_per_shader_stage = if vertex_shader_storage_blocks == 0 {
371            fragment_shader_storage_blocks
372        } else {
373            vertex_shader_storage_blocks.min(fragment_shader_storage_blocks)
374        };
375        let max_storage_textures_per_shader_stage = if vertex_shader_storage_textures == 0 {
376            fragment_shader_storage_textures
377        } else {
378            vertex_shader_storage_textures.min(fragment_shader_storage_textures)
379        };
380        // NOTE: GL_ARB_compute_shader adds support for indirect dispatch
381        let indirect_execution = supported((3, 1), (4, 3))
382            || (extensions.contains("GL_ARB_draw_indirect") && supports_compute);
383        let supports_cube_array = supported((3, 2), (4, 0))
384            || (supported((3, 1), (4, 0)) && extensions.contains("GL_EXT_texture_cube_map_array"));
385
386        let mut downlevel_flags = wgt::DownlevelFlags::empty()
387            | wgt::DownlevelFlags::COMPARISON_SAMPLERS
388            | wgt::DownlevelFlags::MSL2_1
389            | wgt::DownlevelFlags::NON_POWER_OF_TWO_MIPMAPPED_TEXTURES;
390        downlevel_flags.set(
391            wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES,
392            supports_cube_array,
393        );
394        downlevel_flags.set(wgt::DownlevelFlags::COMPUTE_SHADERS, supports_compute);
395        downlevel_flags.set(
396            wgt::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE,
397            max_storage_block_size != 0,
398        );
399        downlevel_flags.set(wgt::DownlevelFlags::INDIRECT_EXECUTION, indirect_execution);
400        downlevel_flags.set(wgt::DownlevelFlags::BASE_VERTEX, supported((3, 2), (3, 2)));
401        downlevel_flags.set(
402            wgt::DownlevelFlags::INDEPENDENT_BLEND,
403            supported((3, 2), (4, 0)) || extensions.contains("GL_EXT_draw_buffers_indexed"),
404        );
405        downlevel_flags.set(
406            wgt::DownlevelFlags::VERTEX_STORAGE,
407            max_storage_block_size != 0
408                && max_storage_buffers_per_shader_stage != 0
409                && (vertex_shader_storage_blocks != 0 || vertex_ssbo_false_zero),
410        );
411        downlevel_flags.set(wgt::DownlevelFlags::FRAGMENT_STORAGE, supports_storage);
412        if extensions.contains("EXT_texture_filter_anisotropic")
413            || extensions.contains("GL_EXT_texture_filter_anisotropic")
414        {
415            let max_aniso =
416                unsafe { gl.get_parameter_i32(glow::MAX_TEXTURE_MAX_ANISOTROPY_EXT) } as u32;
417            downlevel_flags.set(wgt::DownlevelFlags::ANISOTROPIC_FILTERING, max_aniso >= 16);
418        }
419        downlevel_flags.set(
420            wgt::DownlevelFlags::BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED,
421            !(cfg!(any(webgl, Emscripten)) || is_angle),
422        );
423        // see https://registry.khronos.org/webgl/specs/latest/2.0/#BUFFER_OBJECT_BINDING
424        downlevel_flags.set(
425            wgt::DownlevelFlags::UNRESTRICTED_INDEX_BUFFER,
426            !cfg!(any(webgl, Emscripten)),
427        );
428        downlevel_flags.set(
429            wgt::DownlevelFlags::UNRESTRICTED_EXTERNAL_TEXTURE_COPIES,
430            !cfg!(any(webgl, Emscripten)),
431        );
432        downlevel_flags.set(
433            wgt::DownlevelFlags::FULL_DRAW_INDEX_UINT32,
434            max_element_index == u32::MAX,
435        );
436        downlevel_flags.set(
437            wgt::DownlevelFlags::MULTISAMPLED_SHADING,
438            supported((3, 2), (4, 0)) || extensions.contains("OES_sample_variables"),
439        );
440        // GLSL ES has no `noperspective` qualifier, so `@interpolate(linear)` is only
441        // expressible on desktop GLSL (where we require at least 330, well past the 130
442        // that introduced `noperspective`).
443        downlevel_flags.set(
444            wgt::DownlevelFlags::LINEAR_INTERPOLATION,
445            !shading_language_version.is_es(),
446        );
447        let query_buffers = extensions.contains("GL_ARB_query_buffer_object")
448            || extensions.contains("GL_AMD_query_buffer_object");
449        if query_buffers {
450            downlevel_flags.set(wgt::DownlevelFlags::NONBLOCKING_QUERY_RESOLVE, true);
451        }
452
453        // Desktop GL: norm16 is core since GL 3.0/3.1; we minimum-version
454        // to GL 3.3, so always on. GLES/WebGL2: needs `EXT_texture_norm16`.
455        let supports_16bit_norm = if es_ver.is_some() {
456            extensions.contains("GL_EXT_texture_norm16")
457                || extensions.contains("EXT_texture_norm16")
458        } else {
459            true
460        };
461        // SNORM color-rendering is not spec-guaranteed on either path
462        // (GLES Table 8.13 marks it not-renderable; desktop GL exposes
463        // it as only "optionally renderable"), so gate it on
464        // `EXT_render_snorm` for both - matching how `COLOR_BUFFER_FLOAT`
465        // is probed above.
466        let supports_16bit_snorm_renderable = supports_16bit_norm
467            && (extensions.contains("GL_EXT_render_snorm")
468                || extensions.contains("EXT_render_snorm"));
469        // Storage on norm16. ARB_shader_image_load_store / GL 4.2 Table X.2 and
470        // NV_image_formats Table 8.27 both list `r16/rg16/rgba16` and the SNORM
471        // variants as image-unit formats, so one gate covers UNORM and SNORM.
472        // Paths:
473        //   * Desktop:  core in GL 4.2+; on 3.3..=4.1 via `GL_ARB_shader_image_load_store`.
474        //   * GLES/WebGL2: only via `GL_NV_image_formats` - the ES 3.1/3.2 core
475        //     Table 8.27 omits these formats, and `GL_EXT_texture_norm16` does not
476        //     extend Table 8.27 (NV_image_formats itself depends on EXT_texture_norm16
477        //     for the norm16 entries, so an ES driver exposing NV_image_formats
478        //     without EXT_texture_norm16 still wouldn't accept them - the
479        //     `supports_16bit_norm` prerequisite below catches that).
480        let supports_16bit_norm_storage = supports_16bit_norm
481            && if es_ver.is_some() {
482                extensions.contains("GL_NV_image_formats")
483            } else {
484                full_ver.is_some_and(|v| v >= (4, 2))
485                    || extensions.contains("GL_ARB_shader_image_load_store")
486            };
487
488        let mut features = wgt::Features::empty()
489            | wgt::Features::CLEAR_TEXTURE
490            | wgt::Features::DEPTH32FLOAT_STENCIL8
491            | wgt::Features::IMMEDIATES
492            | wgt::Features::PASSTHROUGH_SHADERS
493            | wgt::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES
494            | wgt::Features::UNRESTRICTED_BYTES_PER_ROW;
495        features.set(
496            wgt::Features::TEXTURE_FORMAT_16BIT_NORM,
497            supports_16bit_norm,
498        );
499        features.set(
500            wgt::Features::ADDRESS_MODE_CLAMP_TO_BORDER | wgt::Features::ADDRESS_MODE_CLAMP_TO_ZERO,
501            extensions.contains("GL_EXT_texture_border_clamp")
502                || extensions.contains("GL_ARB_texture_border_clamp"),
503        );
504        features.set(
505            wgt::Features::DEPTH_CLIP_CONTROL,
506            extensions.contains("GL_EXT_depth_clamp") || extensions.contains("GL_ARB_depth_clamp"),
507        );
508        features.set(
509            wgt::Features::VERTEX_WRITABLE_STORAGE,
510            downlevel_flags.contains(wgt::DownlevelFlags::VERTEX_STORAGE)
511                && vertex_shader_storage_textures != 0,
512        );
513        features.set(
514            wgt::Features::MULTIVIEW,
515            extensions.contains("OVR_multiview2") || extensions.contains("GL_OVR_multiview2"),
516        );
517        features.set(
518            wgt::Features::DUAL_SOURCE_BLENDING,
519            extensions.contains("GL_EXT_blend_func_extended")
520                || extensions.contains("GL_ARB_blend_func_extended"),
521        );
522        features.set(
523            wgt::Features::CLIP_DISTANCES,
524            full_ver.is_some() || extensions.contains("GL_EXT_clip_cull_distance"),
525        );
526        features.set(
527            wgt::Features::PRIMITIVE_INDEX,
528            supported((3, 2), (3, 2))
529                || extensions.contains("OES_geometry_shader")
530                || extensions.contains("GL_ARB_geometry_shader4"),
531        );
532        features.set(
533            wgt::Features::SHADER_EARLY_DEPTH_TEST,
534            supported((3, 1), (4, 2)) || extensions.contains("GL_ARB_shader_image_load_store"),
535        );
536        if extensions.contains("GL_ARB_timer_query") {
537            features.set(wgt::Features::TIMESTAMP_QUERY, true);
538            features.set(wgt::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS, true);
539            features.set(wgt::Features::TIMESTAMP_QUERY_INSIDE_PASSES, true);
540        }
541        let gl_bcn_exts = [
542            "GL_EXT_texture_compression_s3tc",
543            "GL_EXT_texture_compression_rgtc",
544            "GL_ARB_texture_compression_bptc",
545        ];
546        let gles_bcn_exts = [
547            "GL_EXT_texture_compression_s3tc_srgb",
548            "GL_EXT_texture_compression_rgtc",
549            "GL_EXT_texture_compression_bptc",
550        ];
551        let webgl_bcn_exts = [
552            "WEBGL_compressed_texture_s3tc",
553            "WEBGL_compressed_texture_s3tc_srgb",
554            "EXT_texture_compression_rgtc",
555            "EXT_texture_compression_bptc",
556        ];
557        let bcn_exts = if cfg!(any(webgl, Emscripten)) {
558            &webgl_bcn_exts[..]
559        } else if es_ver.is_some() {
560            &gles_bcn_exts[..]
561        } else {
562            &gl_bcn_exts[..]
563        };
564        features.set(
565            wgt::Features::TEXTURE_COMPRESSION_BC,
566            bcn_exts.iter().all(|&ext| extensions.contains(ext)),
567        );
568        features.set(
569            wgt::Features::TEXTURE_COMPRESSION_BC_SLICED_3D,
570            bcn_exts.iter().all(|&ext| extensions.contains(ext)), // BC guaranteed Sliced 3D
571        );
572        let has_etc = if cfg!(any(webgl, Emscripten)) {
573            extensions.contains("WEBGL_compressed_texture_etc")
574        } else {
575            es_ver.is_some() || extensions.contains("GL_ARB_ES3_compatibility")
576        };
577        features.set(wgt::Features::TEXTURE_COMPRESSION_ETC2, has_etc);
578
579        // `OES_texture_compression_astc` provides 2D + 3D, LDR + HDR support
580        if extensions.contains("WEBGL_compressed_texture_astc")
581            || extensions.contains("GL_OES_texture_compression_astc")
582        {
583            #[cfg(webgl)]
584            {
585                if context
586                    .glow_context
587                    .compressed_texture_astc_supports_ldr_profile()
588                {
589                    features.insert(wgt::Features::TEXTURE_COMPRESSION_ASTC);
590                    features.insert(wgt::Features::TEXTURE_COMPRESSION_ASTC_SLICED_3D);
591                }
592                if context
593                    .glow_context
594                    .compressed_texture_astc_supports_hdr_profile()
595                {
596                    features.insert(wgt::Features::TEXTURE_COMPRESSION_ASTC_HDR);
597                }
598            }
599
600            #[cfg(any(native, Emscripten))]
601            {
602                features.insert(wgt::Features::TEXTURE_COMPRESSION_ASTC);
603                features.insert(wgt::Features::TEXTURE_COMPRESSION_ASTC_SLICED_3D);
604                features.insert(wgt::Features::TEXTURE_COMPRESSION_ASTC_HDR);
605            }
606        } else {
607            features.set(
608                wgt::Features::TEXTURE_COMPRESSION_ASTC,
609                extensions.contains("GL_KHR_texture_compression_astc_ldr"),
610            );
611            features.set(
612                wgt::Features::TEXTURE_COMPRESSION_ASTC_SLICED_3D,
613                extensions.contains("GL_KHR_texture_compression_astc_ldr")
614                    && extensions.contains("GL_KHR_texture_compression_astc_sliced_3d"),
615            );
616            features.set(
617                wgt::Features::TEXTURE_COMPRESSION_ASTC_HDR,
618                extensions.contains("GL_KHR_texture_compression_astc_hdr"),
619            );
620        }
621
622        downlevel_flags.set(
623            wgt::DownlevelFlags::TEXTURE_COMPRESSION,
624            features.contains(wgt::Features::TEXTURE_COMPRESSION_BC)
625                || features.contains(
626                    wgt::Features::TEXTURE_COMPRESSION_ETC2
627                        | wgt::Features::TEXTURE_COMPRESSION_ASTC,
628                ),
629        );
630
631        features.set(
632            wgt::Features::FLOAT32_FILTERABLE,
633            extensions.contains("GL_ARB_color_buffer_float")
634                || extensions.contains("GL_EXT_color_buffer_float")
635                || extensions.contains("OES_texture_float_linear"),
636        );
637
638        if es_ver.is_none() {
639            features |= wgt::Features::POLYGON_MODE_LINE | wgt::Features::POLYGON_MODE_POINT;
640        }
641
642        // We *might* be able to emulate bgra8unorm-storage but currently don't attempt to.
643
644        let mut private_caps = super::PrivateCapabilities::empty();
645
646        #[cfg(all(unix, native))]
647        if let Some(egl) = context.egl_instance() {
648            if let Some(display) = context.raw_display() {
649                if let Ok(extensions) = egl.query_string(Some(*display), khronos_egl::EXTENSIONS) {
650                    for extension in extensions.to_string_lossy().split_ascii_whitespace() {
651                        match extension {
652                            "EGL_EXT_image_dma_buf_import" => {
653                                private_caps
654                                    .insert(super::PrivateCapabilities::EGL_IMAGE_DMA_BUF_IMPORT);
655                            }
656                            "EGL_EXT_image_dma_buf_import_modifiers" => {
657                                private_caps.insert(
658                                    super::PrivateCapabilities::EGL_IMAGE_DMA_BUF_IMPORT_MODIFIERS,
659                                );
660                            }
661                            _ => {}
662                        }
663                    }
664                }
665            }
666        }
667
668        private_caps.set(
669            super::PrivateCapabilities::BUFFER_ALLOCATION,
670            extensions.contains("GL_EXT_buffer_storage")
671                || extensions.contains("GL_ARB_buffer_storage"),
672        );
673        private_caps.set(
674            super::PrivateCapabilities::SHADER_BINDING_LAYOUT,
675            supports_compute,
676        );
677        private_caps.set(
678            super::PrivateCapabilities::SHADER_TEXTURE_SHADOW_LOD,
679            extensions.contains("GL_EXT_texture_shadow_lod"),
680        );
681        private_caps.set(
682            super::PrivateCapabilities::MEMORY_BARRIERS,
683            supported((3, 1), (4, 2)),
684        );
685        private_caps.set(
686            super::PrivateCapabilities::VERTEX_BUFFER_LAYOUT,
687            supported((3, 1), (4, 3)) || extensions.contains("GL_ARB_vertex_attrib_binding"),
688        );
689        private_caps.set(
690            super::PrivateCapabilities::INDEX_BUFFER_ROLE_CHANGE,
691            !cfg!(any(webgl, Emscripten)),
692        );
693        private_caps.set(
694            super::PrivateCapabilities::GET_BUFFER_SUB_DATA,
695            cfg!(any(webgl, Emscripten)) || full_ver.is_some(),
696        );
697        let color_buffer_float = extensions.contains("GL_EXT_color_buffer_float")
698            || extensions.contains("GL_ARB_color_buffer_float")
699            || extensions.contains("EXT_color_buffer_float");
700        let color_buffer_half_float = extensions.contains("GL_EXT_color_buffer_half_float")
701            || extensions.contains("GL_ARB_half_float_pixel");
702        private_caps.set(
703            super::PrivateCapabilities::COLOR_BUFFER_HALF_FLOAT,
704            color_buffer_half_float || color_buffer_float,
705        );
706        private_caps.set(
707            super::PrivateCapabilities::COLOR_BUFFER_FLOAT,
708            color_buffer_float,
709        );
710        private_caps.set(super::PrivateCapabilities::QUERY_BUFFERS, query_buffers);
711        private_caps.set(super::PrivateCapabilities::QUERY_64BIT, full_ver.is_some());
712        private_caps.set(
713            super::PrivateCapabilities::TEXTURE_STORAGE,
714            supported((3, 0), (4, 2)),
715        );
716        let is_mali = renderer.to_lowercase().contains("mali");
717        let debug_fns_enabled = match backend_options.debug_fns {
718            wgt::GlDebugFns::Auto => gl.supports_debug() && !is_mali,
719            wgt::GlDebugFns::ForceEnabled => gl.supports_debug(),
720            wgt::GlDebugFns::Disabled => false,
721        };
722        private_caps.set(super::PrivateCapabilities::DEBUG_FNS, debug_fns_enabled);
723        private_caps.set(
724            super::PrivateCapabilities::INVALIDATE_FRAMEBUFFER,
725            supported((3, 0), (4, 3)),
726        );
727        if let Some(full_ver) = full_ver {
728            let supported =
729                full_ver >= (4, 2) && extensions.contains("GL_ARB_shader_draw_parameters");
730            private_caps.set(
731                super::PrivateCapabilities::FULLY_FEATURED_INSTANCING,
732                supported,
733            );
734            // Desktop 4.2 and greater specify the first instance parameter.
735            //
736            // For all other versions, the behavior is undefined.
737            //
738            // We only support indirect first instance when we also have ARB_shader_draw_parameters as
739            // that's the only way to get gl_InstanceID to work correctly.
740            features.set(wgt::Features::INDIRECT_FIRST_INSTANCE, supported);
741        }
742        private_caps.set(
743            super::PrivateCapabilities::MULTISAMPLED_RENDER_TO_TEXTURE,
744            extensions.contains("GL_EXT_multisampled_render_to_texture"),
745        );
746        private_caps.set(
747            super::PrivateCapabilities::TEXTURE_FORMAT_NORM16,
748            supports_16bit_norm,
749        );
750        private_caps.set(
751            super::PrivateCapabilities::TEXTURE_FORMAT_SNORM16_RENDERABLE,
752            supports_16bit_snorm_renderable,
753        );
754        private_caps.set(
755            super::PrivateCapabilities::TEXTURE_FORMAT_NORM16_STORAGE,
756            supports_16bit_norm_storage,
757        );
758
759        // GLSL ES 3.10+ / GLSL 4.30+ natively support coherent/volatile qualifiers
760        // on storage buffers. These were introduced alongside storage buffer support.
761        if supports_storage {
762            features |= wgt::Features::MEMORY_DECORATION_COHERENT
763                | wgt::Features::MEMORY_DECORATION_VOLATILE;
764        }
765
766        let max_texture_size = unsafe { gl.get_parameter_i32(glow::MAX_TEXTURE_SIZE) } as u32;
767        let max_texture_3d_size = unsafe { gl.get_parameter_i32(glow::MAX_3D_TEXTURE_SIZE) } as u32;
768
769        let min_uniform_buffer_offset_alignment =
770            (unsafe { gl.get_parameter_i32(glow::UNIFORM_BUFFER_OFFSET_ALIGNMENT) } as u32);
771        let min_storage_buffer_offset_alignment = if supports_storage {
772            (unsafe { gl.get_parameter_i32(glow::SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT) } as u32)
773        } else {
774            256
775        };
776        let max_uniform_buffers_per_shader_stage =
777            unsafe { gl.get_parameter_i32(glow::MAX_VERTEX_UNIFORM_BLOCKS) }
778                .min(unsafe { gl.get_parameter_i32(glow::MAX_FRAGMENT_UNIFORM_BLOCKS) })
779                as u32;
780
781        let max_compute_workgroups_per_dimension = if supports_work_group_params {
782            unsafe { gl.get_parameter_indexed_i32(glow::MAX_COMPUTE_WORK_GROUP_COUNT, 0) }
783                .min(unsafe { gl.get_parameter_indexed_i32(glow::MAX_COMPUTE_WORK_GROUP_COUNT, 1) })
784                .min(unsafe { gl.get_parameter_indexed_i32(glow::MAX_COMPUTE_WORK_GROUP_COUNT, 2) })
785                as u32
786        } else {
787            0
788        };
789
790        let max_color_attachments = unsafe {
791            gl.get_parameter_i32(glow::MAX_COLOR_ATTACHMENTS)
792                .min(gl.get_parameter_i32(glow::MAX_DRAW_BUFFERS)) as u32
793        };
794
795        // 16 bytes per sample is the maximum size of a color attachment.
796        let max_color_attachment_bytes_per_sample =
797            max_color_attachments * wgt::TextureFormat::MAX_TARGET_PIXEL_BYTE_COST;
798
799        let limits = crate::auxil::adjust_raw_limits(wgt::Limits {
800            max_texture_dimension_1d: max_texture_size,
801            max_texture_dimension_2d: max_texture_size,
802            max_texture_dimension_3d: max_texture_3d_size,
803            max_texture_array_layers: unsafe {
804                gl.get_parameter_i32(glow::MAX_ARRAY_TEXTURE_LAYERS)
805            } as u32,
806            max_bind_groups: u32::MAX,
807            // No limit.
808            max_bind_groups_plus_vertex_buffers: u32::MAX,
809            // No limit.
810            max_bindings_per_bind_group: u32::MAX,
811            max_dynamic_uniform_buffers_per_pipeline_layout: max_uniform_buffers_per_shader_stage,
812            max_dynamic_storage_buffers_per_pipeline_layout: max_storage_buffers_per_shader_stage,
813            max_sampled_textures_per_shader_stage: super::MAX_TEXTURE_SLOTS as u32,
814            max_samplers_per_shader_stage: super::MAX_SAMPLERS as u32,
815            max_storage_buffers_per_shader_stage,
816            max_storage_buffers_in_vertex_stage: 0,
817            max_storage_buffers_in_fragment_stage: 0,
818            max_storage_textures_per_shader_stage,
819            max_storage_textures_in_vertex_stage: 0,
820            max_storage_textures_in_fragment_stage: 0,
821            max_uniform_buffers_per_shader_stage,
822            max_binding_array_elements_per_shader_stage: 0,
823            max_binding_array_sampler_elements_per_shader_stage: 0,
824            max_binding_array_acceleration_structure_elements_per_shader_stage: 0,
825            max_uniform_buffer_binding_size: unsafe {
826                gl.get_parameter_i32(glow::MAX_UNIFORM_BLOCK_SIZE)
827            } as u64,
828            max_storage_buffer_binding_size: if supports_storage {
829                unsafe { gl.get_parameter_i32(glow::MAX_SHADER_STORAGE_BLOCK_SIZE) }
830            } else {
831                0
832            } as u64,
833            max_vertex_buffers: if private_caps
834                .contains(super::PrivateCapabilities::VERTEX_BUFFER_LAYOUT)
835            {
836                (unsafe { gl.get_parameter_i32(glow::MAX_VERTEX_ATTRIB_BINDINGS) } as u32)
837            } else {
838                16 // should this be different?
839            },
840            max_vertex_attributes: (unsafe { gl.get_parameter_i32(glow::MAX_VERTEX_ATTRIBS) }
841                as u32)
842                .min(super::MAX_VERTEX_ATTRIBUTES as u32),
843            max_vertex_buffer_array_stride: if private_caps
844                .contains(super::PrivateCapabilities::VERTEX_BUFFER_LAYOUT)
845            {
846                if let Some(full_ver) = full_ver {
847                    if full_ver >= (4, 4) {
848                        // We can query `GL_MAX_VERTEX_ATTRIB_STRIDE` in OpenGL 4.4+
849                        let value =
850                            (unsafe { gl.get_parameter_i32(glow::MAX_VERTEX_ATTRIB_STRIDE) })
851                                as u32;
852
853                        if value == 0 {
854                            // This should be at least 2048, but the driver for AMD Radeon HD 5870 on
855                            // Windows doesn't recognize `GL_MAX_VERTEX_ATTRIB_STRIDE`.
856
857                            log::debug!("Max vertex attribute stride is 0. Assuming it is the OpenGL minimum spec 2048");
858                            2048
859                        } else {
860                            value
861                        }
862                    } else {
863                        log::debug!("Max vertex attribute stride unknown. Assuming it is the OpenGL minimum spec 2048");
864                        2048
865                    }
866                } else {
867                    (unsafe { gl.get_parameter_i32(glow::MAX_VERTEX_ATTRIB_STRIDE) }) as u32
868                }
869            } else {
870                !0
871            },
872            max_immediate_size: super::MAX_IMMEDIATES as u32 * 4,
873            min_uniform_buffer_offset_alignment,
874            min_storage_buffer_offset_alignment,
875            max_inter_stage_shader_variables: {
876                // MAX_VARYING_COMPONENTS may return 0, because it is deprecated since OpenGL 3.2 core,
877                // and an OpenGL Context with the core profile and with forward-compatibility=true,
878                // will make deprecated constants unavailable.
879                let max_varying_components =
880                    unsafe { gl.get_parameter_i32(glow::MAX_VARYING_COMPONENTS) } as u32;
881                if max_varying_components == 0 {
882                    // default value for max_inter_stage_shader_variables
883                    15
884                } else {
885                    max_varying_components / 4
886                }
887            },
888            max_color_attachments,
889            max_color_attachment_bytes_per_sample,
890            max_compute_workgroup_storage_size: if supports_work_group_params {
891                (unsafe { gl.get_parameter_i32(glow::MAX_COMPUTE_SHARED_MEMORY_SIZE) } as u32)
892            } else {
893                0
894            },
895            max_compute_invocations_per_workgroup: if supports_work_group_params {
896                (unsafe { gl.get_parameter_i32(glow::MAX_COMPUTE_WORK_GROUP_INVOCATIONS) } as u32)
897            } else {
898                0
899            },
900            max_compute_workgroup_size_x: if supports_work_group_params {
901                (unsafe { gl.get_parameter_indexed_i32(glow::MAX_COMPUTE_WORK_GROUP_SIZE, 0) }
902                    as u32)
903            } else {
904                0
905            },
906            max_compute_workgroup_size_y: if supports_work_group_params {
907                (unsafe { gl.get_parameter_indexed_i32(glow::MAX_COMPUTE_WORK_GROUP_SIZE, 1) }
908                    as u32)
909            } else {
910                0
911            },
912            max_compute_workgroup_size_z: if supports_work_group_params {
913                (unsafe { gl.get_parameter_indexed_i32(glow::MAX_COMPUTE_WORK_GROUP_SIZE, 2) }
914                    as u32)
915            } else {
916                0
917            },
918            max_compute_workgroups_per_dimension,
919            max_buffer_size: i32::MAX as u64,
920            max_non_sampler_bindings: u32::MAX,
921
922            max_task_workgroup_total_count: 0,
923            max_task_workgroups_per_dimension: 0,
924            max_mesh_workgroup_total_count: 0,
925            max_mesh_workgroups_per_dimension: 0,
926            max_task_invocations_per_workgroup: 0,
927            max_task_invocations_per_dimension: 0,
928            max_mesh_invocations_per_workgroup: 0,
929            max_mesh_invocations_per_dimension: 0,
930            max_task_payload_size: 0,
931            max_mesh_output_vertices: 0,
932            max_mesh_output_primitives: 0,
933            max_mesh_output_layers: 0,
934            max_mesh_multiview_view_count: 0,
935
936            max_blas_primitive_count: 0,
937            max_blas_geometry_count: 0,
938            max_tlas_instance_count: 0,
939            max_acceleration_structures_per_shader_stage: 0,
940            max_buffers_and_acceleration_structures_per_shader_stage: u32::MAX,
941
942            max_multiview_view_count: 0,
943
944            max_ray_dispatch_count: 0,
945            max_ray_recursion_depth: 0,
946        });
947
948        let mut workarounds = super::Workarounds::empty();
949
950        workarounds.set(
951            super::Workarounds::EMULATE_BUFFER_MAP,
952            cfg!(any(webgl, Emscripten)),
953        );
954
955        let r = renderer.to_lowercase();
956        // Check for Mesa sRGB clear bug. See
957        // [`super::PrivateCapabilities::MESA_I915_SRGB_SHADER_CLEAR`].
958        if context.is_owned()
959            && r.contains("mesa")
960            && r.contains("intel")
961            && r.split(&[' ', '(', ')'][..])
962                .any(|substr| substr.len() == 3 && substr.chars().nth(2) == Some('l'))
963        {
964            log::debug!(
965                "Detected skylake derivative running on mesa i915. Clears to srgb textures will \
966                use manual shader clears."
967            );
968            workarounds.set(super::Workarounds::MESA_I915_SRGB_SHADER_CLEAR, true);
969        }
970
971        let downlevel_defaults = wgt::DownlevelLimits {};
972        let max_samples = unsafe { gl.get_parameter_i32(glow::MAX_SAMPLES) };
973
974        // Drop the GL guard so we can move the context into AdapterShared
975        // ( on Wasm the gl handle is just a ref so we tell clippy to allow
976        // dropping the ref )
977        #[cfg_attr(target_family = "wasm", allow(dropping_references))]
978        drop(gl);
979
980        let downlevel = wgt::DownlevelCapabilities {
981            flags: downlevel_flags,
982            limits: downlevel_defaults,
983            shader_model: wgt::ShaderModel::Sm5,
984        };
985
986        features.set(
987            wgt::Features::CORE_FEATURES_AND_LIMITS,
988            crate::auxil::supports_core_features_and_limits(&limits, &downlevel),
989        );
990
991        Some(crate::ExposedAdapter {
992            adapter: super::Adapter {
993                shared: Arc::new(super::AdapterShared {
994                    context,
995                    private_caps,
996                    workarounds,
997                    features,
998                    limits: limits.clone(),
999                    options: backend_options,
1000                    shading_language_version,
1001                    next_shader_id: Default::default(),
1002                    program_cache: Default::default(),
1003                    es: es_ver.is_some(),
1004                    max_msaa_samples: max_samples,
1005                }),
1006            },
1007            info: Self::make_info(vendor, renderer, version),
1008            features,
1009            capabilities: crate::Capabilities {
1010                limits,
1011                downlevel,
1012                alignments: crate::Alignments {
1013                    buffer_copy_offset: wgt::BufferSize::new(4).unwrap(),
1014                    buffer_copy_pitch: wgt::BufferSize::new(4).unwrap(),
1015                    // #6151: `wgpu_hal::gles` doesn't ask Naga to inject bounds
1016                    // checks in GLSL, and it doesn't request extensions like
1017                    // `KHR_robust_buffer_access_behavior` that would provide
1018                    // them, so we can't really implement the checks promised by
1019                    // [`crate::BufferBinding`].
1020                    //
1021                    // Since this is a pre-existing condition, for the time
1022                    // being, provide 1 as the value here, to cause as little
1023                    // trouble as possible.
1024                    uniform_bounds_check_alignment: wgt::BufferSize::new(1).unwrap(),
1025                    raw_tlas_instance_size: 0,
1026                    ray_tracing_scratch_buffer_alignment: 0,
1027                    ray_tracing_pipeline_group_data_size: 0,
1028                    ray_tracing_pipeline_group_data_alignment: 0,
1029                    ray_tracing_pipeline_data_offset_alignment: 0,
1030                },
1031                cooperative_matrix_properties: Vec::new(),
1032                ray_tracing_invocation_reorder_mode: wgt::RayTracingInvocationReorderMode::None,
1033            },
1034        })
1035    }
1036
1037    unsafe fn compile_shader(
1038        source: &str,
1039        gl: &glow::Context,
1040        shader_type: u32,
1041        es: bool,
1042    ) -> Option<glow::Shader> {
1043        let source = if es {
1044            format!("#version 300 es\nprecision lowp float;\n{source}")
1045        } else {
1046            let version = gl.version();
1047            if version.major == 3 && version.minor == 0 {
1048                // OpenGL 3.0 only supports this format
1049                format!("#version 130\n{source}")
1050            } else {
1051                // OpenGL 3.1+ support this format
1052                format!("#version 140\n{source}")
1053            }
1054        };
1055        let shader = unsafe { gl.create_shader(shader_type) }.expect("Could not create shader");
1056        unsafe { gl.shader_source(shader, &source) };
1057        unsafe { gl.compile_shader(shader) };
1058
1059        if !unsafe { gl.get_shader_compile_status(shader) } {
1060            let msg = unsafe { gl.get_shader_info_log(shader) };
1061            if !msg.is_empty() {
1062                log::error!("\tShader compile error: {msg}");
1063            }
1064            unsafe { gl.delete_shader(shader) };
1065            None
1066        } else {
1067            Some(shader)
1068        }
1069    }
1070
1071    unsafe fn create_shader_clear_program(
1072        gl: &glow::Context,
1073        es: bool,
1074    ) -> Option<ShaderClearProgram> {
1075        let program = unsafe { gl.create_program() }.expect("Could not create shader program");
1076        let vertex = unsafe {
1077            Self::compile_shader(
1078                include_str!("./shaders/clear.vert"),
1079                gl,
1080                glow::VERTEX_SHADER,
1081                es,
1082            )?
1083        };
1084        let fragment = unsafe {
1085            Self::compile_shader(
1086                include_str!("./shaders/clear.frag"),
1087                gl,
1088                glow::FRAGMENT_SHADER,
1089                es,
1090            )?
1091        };
1092        unsafe { gl.attach_shader(program, vertex) };
1093        unsafe { gl.attach_shader(program, fragment) };
1094        unsafe { gl.link_program(program) };
1095
1096        let linked_ok = unsafe { gl.get_program_link_status(program) };
1097        let msg = unsafe { gl.get_program_info_log(program) };
1098        if !msg.is_empty() {
1099            log::error!("Shader link error: {msg}");
1100        }
1101        if !linked_ok {
1102            return None;
1103        }
1104
1105        let color_uniform_location = unsafe { gl.get_uniform_location(program, "color") }
1106            .expect("Could not find color uniform in shader clear shader");
1107        unsafe { gl.delete_shader(vertex) };
1108        unsafe { gl.delete_shader(fragment) };
1109
1110        Some(ShaderClearProgram {
1111            program,
1112            color_uniform_location,
1113        })
1114    }
1115}
1116
1117impl crate::Adapter for super::Adapter {
1118    type A = super::Api;
1119
1120    unsafe fn open(
1121        &self,
1122        features: wgt::Features,
1123        _limits: &wgt::Limits,
1124        _memory_hints: &wgt::MemoryHints,
1125    ) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> {
1126        let gl = &self.shared.context.lock();
1127        unsafe { gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1) };
1128        unsafe { gl.pixel_store_i32(glow::PACK_ALIGNMENT, 1) };
1129        let main_vao =
1130            unsafe { gl.create_vertex_array() }.map_err(|_| crate::DeviceError::OutOfMemory)?;
1131        unsafe { gl.bind_vertex_array(Some(main_vao)) };
1132
1133        // Desktop GL defaults to non-seamless cube sampling; ES 3.0+ and other backends are seamless by spec.
1134        if !self.shared.es {
1135            unsafe { gl.enable(glow::TEXTURE_CUBE_MAP_SEAMLESS) };
1136        }
1137
1138        let zero_buffer =
1139            unsafe { gl.create_buffer() }.map_err(|_| crate::DeviceError::OutOfMemory)?;
1140        unsafe { gl.bind_buffer(glow::COPY_READ_BUFFER, Some(zero_buffer)) };
1141        let zeroes = vec![0u8; super::ZERO_BUFFER_SIZE];
1142        unsafe { gl.buffer_data_u8_slice(glow::COPY_READ_BUFFER, &zeroes, glow::STATIC_DRAW) };
1143
1144        // Compile the shader program we use for doing manual clears to work around Mesa fastclear
1145        // bug.
1146
1147        let shader_clear_program = if self
1148            .shared
1149            .workarounds
1150            .contains(super::Workarounds::MESA_I915_SRGB_SHADER_CLEAR)
1151        {
1152            Some(unsafe {
1153                Self::create_shader_clear_program(gl, self.shared.es)
1154                    .ok_or(crate::DeviceError::Lost)?
1155            })
1156        } else {
1157            // If we don't need the workaround, don't waste time and resources compiling the clear program
1158            None
1159        };
1160
1161        Ok(crate::OpenDevice {
1162            device: super::Device {
1163                shared: Arc::clone(&self.shared),
1164                main_vao,
1165                #[cfg(all(native, feature = "renderdoc"))]
1166                render_doc: Default::default(),
1167                counters: Default::default(),
1168            },
1169            queue: super::Queue {
1170                shared: Arc::clone(&self.shared),
1171                features,
1172                draw_fbo: unsafe { gl.create_framebuffer() }
1173                    .map_err(|_| crate::DeviceError::OutOfMemory)?,
1174                copy_fbo: unsafe { gl.create_framebuffer() }
1175                    .map_err(|_| crate::DeviceError::OutOfMemory)?,
1176                shader_clear_program,
1177                zero_buffer,
1178                temp_query_results: Mutex::new(Vec::new()),
1179                draw_buffer_count: AtomicU8::new(1),
1180                current_index_buffer: Mutex::new(None),
1181            },
1182        })
1183    }
1184
1185    unsafe fn texture_format_capabilities(
1186        &self,
1187        format: wgt::TextureFormat,
1188    ) -> crate::TextureFormatCapabilities {
1189        use crate::TextureFormatCapabilities as Tfc;
1190        use wgt::TextureFormat as Tf;
1191
1192        let sample_count = {
1193            let max_samples = self.shared.max_msaa_samples;
1194            if max_samples >= 16 {
1195                Tfc::MULTISAMPLE_X2
1196                    | Tfc::MULTISAMPLE_X4
1197                    | Tfc::MULTISAMPLE_X8
1198                    | Tfc::MULTISAMPLE_X16
1199            } else if max_samples >= 8 {
1200                Tfc::MULTISAMPLE_X2 | Tfc::MULTISAMPLE_X4 | Tfc::MULTISAMPLE_X8
1201            } else {
1202                // The lowest supported level in GLE3.0/WebGL2 is 4X
1203                // (see GL_MAX_SAMPLES in https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml).
1204                // On some platforms, like iOS Safari, `get_parameter_i32(MAX_SAMPLES)` returns 0,
1205                // so we always fall back to supporting 4x here.
1206                Tfc::MULTISAMPLE_X2 | Tfc::MULTISAMPLE_X4
1207            }
1208        };
1209
1210        // Base types are pulled from the table in the OpenGLES 3.0 spec in section 3.8.
1211        //
1212        // The storage types are based on table 8.26, in section
1213        // "TEXTURE IMAGE LOADS AND STORES" of OpenGLES-3.2 spec.
1214        let empty = Tfc::empty();
1215        let base = Tfc::COPY_SRC | Tfc::COPY_DST;
1216        let unfilterable = base | Tfc::SAMPLED;
1217        let depth = base | Tfc::SAMPLED | sample_count | Tfc::DEPTH_STENCIL_ATTACHMENT;
1218        let filterable = unfilterable | Tfc::SAMPLED_LINEAR;
1219        let renderable =
1220            unfilterable | Tfc::COLOR_ATTACHMENT | sample_count | Tfc::MULTISAMPLE_RESOLVE;
1221        let filterable_renderable = filterable | renderable | Tfc::COLOR_ATTACHMENT_BLEND;
1222        let storage =
1223            base | Tfc::STORAGE_READ_WRITE | Tfc::STORAGE_READ_ONLY | Tfc::STORAGE_WRITE_ONLY;
1224
1225        let feature_fn = |f, caps| {
1226            if self.shared.features.contains(f) {
1227                caps
1228            } else {
1229                empty
1230            }
1231        };
1232
1233        let bcn_features = feature_fn(wgt::Features::TEXTURE_COMPRESSION_BC, filterable);
1234        let etc2_features = feature_fn(wgt::Features::TEXTURE_COMPRESSION_ETC2, filterable);
1235        let astc_features = feature_fn(wgt::Features::TEXTURE_COMPRESSION_ASTC, filterable);
1236        let astc_hdr_features = feature_fn(wgt::Features::TEXTURE_COMPRESSION_ASTC_HDR, filterable);
1237
1238        let private_caps_fn = |f, caps| {
1239            if self.shared.private_caps.contains(f) {
1240                caps
1241            } else {
1242                empty
1243            }
1244        };
1245
1246        let half_float_renderable = private_caps_fn(
1247            super::PrivateCapabilities::COLOR_BUFFER_HALF_FLOAT,
1248            Tfc::COLOR_ATTACHMENT
1249                | Tfc::COLOR_ATTACHMENT_BLEND
1250                | sample_count
1251                | Tfc::MULTISAMPLE_RESOLVE,
1252        );
1253
1254        let float_renderable = private_caps_fn(
1255            super::PrivateCapabilities::COLOR_BUFFER_FLOAT,
1256            Tfc::COLOR_ATTACHMENT
1257                | Tfc::COLOR_ATTACHMENT_BLEND
1258                | sample_count
1259                | Tfc::MULTISAMPLE_RESOLVE,
1260        );
1261
1262        let texture_float_linear = feature_fn(wgt::Features::FLOAT32_FILTERABLE, filterable);
1263
1264        let image_atomic = feature_fn(wgt::Features::TEXTURE_ATOMIC, Tfc::STORAGE_ATOMIC);
1265        let image_64_atomic = feature_fn(wgt::Features::TEXTURE_INT64_ATOMIC, Tfc::STORAGE_ATOMIC);
1266
1267        // UNORM gets full filterable+renderable; SNORM splits because
1268        // `EXT_texture_norm16` marks only UNORM as color-renderable.
1269        // Storage rides on a separate cap (desktop GL >= 4.2 core / pre-4.2
1270        // `GL_ARB_shader_image_load_store`, GLES `GL_NV_image_formats`).
1271        let norm16_unorm = private_caps_fn(
1272            super::PrivateCapabilities::TEXTURE_FORMAT_NORM16,
1273            filterable_renderable,
1274        );
1275        let norm16_snorm = if self
1276            .shared
1277            .private_caps
1278            .contains(super::PrivateCapabilities::TEXTURE_FORMAT_SNORM16_RENDERABLE)
1279        {
1280            norm16_unorm
1281        } else {
1282            private_caps_fn(
1283                super::PrivateCapabilities::TEXTURE_FORMAT_NORM16,
1284                filterable,
1285            )
1286        };
1287        let norm16_storage = private_caps_fn(
1288            super::PrivateCapabilities::TEXTURE_FORMAT_NORM16_STORAGE,
1289            storage,
1290        );
1291
1292        match format {
1293            Tf::R8Unorm => filterable_renderable,
1294            Tf::R8Snorm => filterable,
1295            Tf::R8Uint => renderable,
1296            Tf::R8Sint => renderable,
1297            Tf::R16Uint => renderable,
1298            Tf::R16Sint => renderable,
1299            Tf::R16Unorm => norm16_unorm | norm16_storage,
1300            Tf::R16Snorm => norm16_snorm | norm16_storage,
1301            Tf::R16Float => filterable | half_float_renderable,
1302            Tf::Rg8Unorm => filterable_renderable,
1303            Tf::Rg8Snorm => filterable,
1304            Tf::Rg8Uint => renderable,
1305            Tf::Rg8Sint => renderable,
1306            Tf::R32Uint => renderable | storage | image_atomic,
1307            Tf::R32Sint => renderable | storage | image_atomic,
1308            Tf::R32Float => unfilterable | storage | float_renderable | texture_float_linear,
1309            Tf::Rg16Uint => renderable,
1310            Tf::Rg16Sint => renderable,
1311            Tf::Rg16Unorm => norm16_unorm | norm16_storage,
1312            Tf::Rg16Snorm => norm16_snorm | norm16_storage,
1313            Tf::Rg16Float => filterable | half_float_renderable,
1314            Tf::Rgba8Unorm => filterable_renderable | storage,
1315            Tf::Rgba8UnormSrgb => filterable_renderable,
1316            Tf::Bgra8Unorm | Tf::Bgra8UnormSrgb => filterable_renderable,
1317            Tf::Rgba8Snorm => filterable | storage,
1318            Tf::Rgba8Uint => renderable | storage,
1319            Tf::Rgba8Sint => renderable | storage,
1320            Tf::Rgb10a2Uint => renderable,
1321            Tf::Rgb10a2Unorm => filterable_renderable,
1322            Tf::Rg11b10Ufloat => filterable | float_renderable,
1323            Tf::R64Uint => image_64_atomic,
1324            Tf::Rg32Uint => renderable,
1325            Tf::Rg32Sint => renderable,
1326            Tf::Rg32Float => unfilterable | float_renderable | texture_float_linear,
1327            Tf::Rgba16Uint => renderable | storage,
1328            Tf::Rgba16Sint => renderable | storage,
1329            Tf::Rgba16Unorm => norm16_unorm | norm16_storage,
1330            Tf::Rgba16Snorm => norm16_snorm | norm16_storage,
1331            Tf::Rgba16Float => filterable | storage | half_float_renderable,
1332            Tf::Rgba32Uint => renderable | storage,
1333            Tf::Rgba32Sint => renderable | storage,
1334            Tf::Rgba32Float => unfilterable | storage | float_renderable | texture_float_linear,
1335            Tf::Stencil8
1336            | Tf::Depth16Unorm
1337            | Tf::Depth32Float
1338            | Tf::Depth32FloatStencil8
1339            | Tf::Depth24Plus
1340            | Tf::Depth24PlusStencil8 => depth,
1341            Tf::NV12 => empty,
1342            Tf::P010 => empty,
1343            Tf::Rgb9e5Ufloat => filterable,
1344            Tf::Bc1RgbaUnorm
1345            | Tf::Bc1RgbaUnormSrgb
1346            | Tf::Bc2RgbaUnorm
1347            | Tf::Bc2RgbaUnormSrgb
1348            | Tf::Bc3RgbaUnorm
1349            | Tf::Bc3RgbaUnormSrgb
1350            | Tf::Bc4RUnorm
1351            | Tf::Bc4RSnorm
1352            | Tf::Bc5RgUnorm
1353            | Tf::Bc5RgSnorm
1354            | Tf::Bc6hRgbFloat
1355            | Tf::Bc6hRgbUfloat
1356            | Tf::Bc7RgbaUnorm
1357            | Tf::Bc7RgbaUnormSrgb => bcn_features,
1358            Tf::Etc2Rgb8Unorm
1359            | Tf::Etc2Rgb8UnormSrgb
1360            | Tf::Etc2Rgb8A1Unorm
1361            | Tf::Etc2Rgb8A1UnormSrgb
1362            | Tf::Etc2Rgba8Unorm
1363            | Tf::Etc2Rgba8UnormSrgb
1364            | Tf::EacR11Unorm
1365            | Tf::EacR11Snorm
1366            | Tf::EacRg11Unorm
1367            | Tf::EacRg11Snorm => etc2_features,
1368            Tf::Astc {
1369                block: _,
1370                channel: AstcChannel::Unorm | AstcChannel::UnormSrgb,
1371            } => astc_features,
1372            Tf::Astc {
1373                block: _,
1374                channel: AstcChannel::Hdr,
1375            } => astc_hdr_features,
1376        }
1377    }
1378
1379    unsafe fn surface_capabilities(
1380        &self,
1381        surface: &super::Surface,
1382    ) -> Option<crate::SurfaceCapabilities> {
1383        #[cfg(webgl)]
1384        if self.shared.context.webgl2_context != surface.webgl2_context {
1385            return None;
1386        }
1387
1388        if surface.presentable {
1389            // There is no extended-range or wide-gamut path in the GLES
1390            // backend; everything is presented as sRGB.
1391            let format_caps = |format: wgt::TextureFormat| wgt::SurfaceFormatCapabilities {
1392                format,
1393                color_spaces: wgt::SurfaceColorSpaces::SRGB,
1394            };
1395            let mut formats = vec![
1396                format_caps(wgt::TextureFormat::Rgba8Unorm),
1397                #[cfg(native)]
1398                format_caps(wgt::TextureFormat::Bgra8Unorm),
1399            ];
1400            if surface.supports_srgb() {
1401                formats.extend([
1402                    format_caps(wgt::TextureFormat::Rgba8UnormSrgb),
1403                    #[cfg(native)]
1404                    format_caps(wgt::TextureFormat::Bgra8UnormSrgb),
1405                ])
1406            }
1407            if self
1408                .shared
1409                .private_caps
1410                .contains(super::PrivateCapabilities::COLOR_BUFFER_HALF_FLOAT)
1411            {
1412                formats.push(format_caps(wgt::TextureFormat::Rgba16Float))
1413            }
1414
1415            Some(crate::SurfaceCapabilities {
1416                formats,
1417                present_modes: if cfg!(windows) {
1418                    vec![wgt::PresentMode::Fifo, wgt::PresentMode::Immediate]
1419                } else {
1420                    vec![wgt::PresentMode::Fifo] //TODO
1421                },
1422                composite_alpha_modes: vec![wgt::CompositeAlphaMode::Opaque], //TODO
1423                maximum_frame_latency: 2..=2, //TODO, unused currently
1424                current_extent: None,
1425                usage: wgt::TextureUses::COLOR_TARGET,
1426            })
1427        } else {
1428            None
1429        }
1430    }
1431
1432    unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp {
1433        wgt::PresentationTimestamp::INVALID_TIMESTAMP
1434    }
1435
1436    fn get_ordered_buffer_usages(&self) -> wgt::BufferUses {
1437        wgt::BufferUses::INCLUSIVE | wgt::BufferUses::MAP_WRITE
1438    }
1439
1440    // Don't put barriers between inclusive uses
1441    fn get_ordered_texture_usages(&self) -> wgt::TextureUses {
1442        wgt::TextureUses::INCLUSIVE
1443            | wgt::TextureUses::COLOR_TARGET
1444            | wgt::TextureUses::DEPTH_WRITE
1445            | wgt::TextureUses::STENCIL_WRITE
1446    }
1447}
1448
1449impl super::AdapterShared {
1450    pub(super) unsafe fn get_buffer_sub_data(
1451        &self,
1452        gl: &glow::Context,
1453        target: u32,
1454        offset: i32,
1455        dst_data: &mut [u8],
1456    ) {
1457        if self
1458            .private_caps
1459            .contains(super::PrivateCapabilities::GET_BUFFER_SUB_DATA)
1460        {
1461            unsafe { gl.get_buffer_sub_data(target, offset, dst_data) };
1462        } else {
1463            log::error!("Fake map");
1464            let length = dst_data.len();
1465            // glMapBufferRange throws an error if length is 0.
1466            if length != 0 {
1467                let buffer_mapping =
1468                    unsafe { gl.map_buffer_range(target, offset, length as _, glow::MAP_READ_BIT) };
1469
1470                unsafe {
1471                    core::ptr::copy_nonoverlapping(buffer_mapping, dst_data.as_mut_ptr(), length)
1472                };
1473
1474                unsafe { gl.unmap_buffer(target) };
1475            }
1476        }
1477    }
1478}
1479
1480#[cfg(send_sync)]
1481unsafe impl Sync for super::Adapter {}
1482#[cfg(send_sync)]
1483unsafe impl Send for super::Adapter {}
1484
1485#[cfg(test)]
1486mod tests {
1487    use super::super::Adapter;
1488
1489    #[test]
1490    fn test_version_parse() {
1491        Adapter::parse_version("1").unwrap_err();
1492        Adapter::parse_version("1.").unwrap_err();
1493        Adapter::parse_version("1 h3l1o. W0rld").unwrap_err();
1494        Adapter::parse_version("1. h3l1o. W0rld").unwrap_err();
1495        Adapter::parse_version("1.2.3").unwrap_err();
1496
1497        assert_eq!(Adapter::parse_version("OpenGL ES 3.1").unwrap(), (3, 1));
1498        assert_eq!(
1499            Adapter::parse_version("OpenGL ES 2.0 Google Nexus").unwrap(),
1500            (2, 0)
1501        );
1502        assert_eq!(Adapter::parse_version("GLSL ES 1.1").unwrap(), (1, 1));
1503        assert_eq!(
1504            Adapter::parse_version("OpenGL ES GLSL ES 3.20").unwrap(),
1505            (3, 2)
1506        );
1507        assert_eq!(
1508            // WebGL 2.0 should parse as OpenGL ES 3.0
1509            Adapter::parse_version("WebGL 2.0 (OpenGL ES 3.0 Chromium)").unwrap(),
1510            (3, 0)
1511        );
1512        assert_eq!(
1513            Adapter::parse_version("WebGL GLSL ES 3.00 (OpenGL ES GLSL ES 3.0 Chromium)").unwrap(),
1514            (3, 0)
1515        );
1516    }
1517}