Skip to main content

wgpu_hal/gles/
device.rs

1use alloc::{
2    borrow::{Cow, ToOwned},
3    format,
4    string::String,
5    string::ToString as _,
6    sync::Arc,
7    vec,
8    vec::Vec,
9};
10use core::{cmp::max, convert::TryInto, num::NonZeroU32, ptr, sync::atomic::Ordering};
11
12use arrayvec::ArrayVec;
13use glow::HasContext;
14use naga::FastHashMap;
15use wgpu_sync::Mutex;
16
17use super::{conv, PrivateCapabilities};
18use crate::auxil::map_naga_stage;
19use crate::TlasInstance;
20
21/// An error importing a texture into the GLES backend.
22#[cfg(all(unix, native))]
23#[derive(Debug, thiserror::Error)]
24pub enum ImportTextureError {
25    /// The device reported an error.
26    #[error(transparent)]
27    Device(#[from] crate::DeviceError),
28    /// The descriptor requests an unsupported texture configuration.
29    #[error("DMA-BUF GLES import supports only a single-layer, single-sampled 2D texture with one mip level")]
30    UnsupportedTextureDescriptor,
31    /// An import parameter cannot be represented as EGLint.
32    #[error("Import parameter {0} does not fit EGLint")]
33    ParameterOutOfRange(&'static str),
34    /// The device was not created from an EGL context.
35    #[error("GLES device was not created from an EGL context")]
36    MissingEglContext,
37    /// The device does not expose an EGL display.
38    #[error("GLES device does not expose an EGLDisplay")]
39    MissingEglDisplay,
40    /// A required EXT_IMAGE_DMA_BUF_IMPORT extension is not supported.
41    #[error("EXT_IMAGE_DMA_BUF_IMPORT is not supported")]
42    MissingImageDmaBufImportExtension,
43    /// A required EXT_IMAGE_DMA_BUF_IMPORT_MODIFIERS extension is not supported.
44    #[error("EXT_IMAGE_DMA_BUF_IMPORT_MODIFIERS is not supported")]
45    MissingImageDmaBufImportModifiersExtension,
46    /// A required GL or EGL function is unavailable.
47    #[error("GL or EGL entry point {0} is unavailable")]
48    MissingEntryPoint(&'static str),
49    /// EGL image creation failed.
50    #[error("eglCreateImageKHR failed: {0:?}")]
51    EglImageCreation(#[source] Option<khronos_egl::Error>),
52    /// EGL image destruction failed.
53    #[error("eglDestroyImageKHR failed: {0:?}")]
54    EglImageDestruction(#[source] Option<khronos_egl::Error>),
55    /// GL texture creation failed.
56    #[error("Failed to create GL texture: {0}")]
57    GlTextureCreation(String),
58    /// Failed to bind or configure the imported texture.
59    #[error("Failed to bind or configure the imported texture with error {gl_error:#x}")]
60    BindAndConfigure { gl_error: u32 },
61}
62
63type ShaderStage<'a> = (
64    naga::ShaderStage,
65    &'a crate::ProgrammableStage<'a, super::ShaderModule>,
66);
67type NameBindingMap = FastHashMap<String, (super::BindingRegister, u8)>;
68
69struct CompilationContext<'a> {
70    layout: &'a super::PipelineLayout,
71    sampler_map: &'a mut super::SamplerBindMap,
72    name_binding_map: &'a mut NameBindingMap,
73    immediates_items: &'a mut Vec<naga::back::glsl::ImmediateItem>,
74    multiview_mask: Option<NonZeroU32>,
75    clip_distance_count: &'a mut u32,
76}
77
78impl CompilationContext<'_> {
79    fn consume_reflection(
80        self,
81        gl: &glow::Context,
82        module: &naga::Module,
83        ep_info: &naga::valid::FunctionInfo,
84        reflection_info: naga::back::glsl::ReflectionInfo,
85        naga_stage: naga::ShaderStage,
86        program: glow::Program,
87    ) {
88        for (handle, var) in module.global_variables.iter() {
89            if ep_info[handle].is_empty() {
90                continue;
91            }
92            let register = match var.space {
93                naga::AddressSpace::Uniform => super::BindingRegister::UniformBuffers,
94                naga::AddressSpace::Storage { .. } => super::BindingRegister::StorageBuffers,
95                _ => continue,
96            };
97
98            let br = var.binding.as_ref().unwrap();
99            let slot = self.layout.get_slot(br);
100
101            let name = match reflection_info.uniforms.get(&handle) {
102                Some(name) => name.clone(),
103                None => continue,
104            };
105            log::trace!(
106                "Rebind buffer: {:?} -> {}, register={:?}, slot={}",
107                var.name.as_ref(),
108                name,
109                register,
110                slot
111            );
112            self.name_binding_map.insert(name, (register, slot));
113        }
114
115        for (name, mapping) in reflection_info.texture_mapping {
116            let var = &module.global_variables[mapping.texture];
117            let register = match module.types[var.ty].inner {
118                naga::TypeInner::Image {
119                    class: naga::ImageClass::Storage { .. },
120                    ..
121                } => super::BindingRegister::Images,
122                _ => super::BindingRegister::Textures,
123            };
124
125            let tex_br = var.binding.as_ref().unwrap();
126            let texture_linear_index = self.layout.get_slot(tex_br);
127
128            self.name_binding_map
129                .insert(name, (register, texture_linear_index));
130            if let Some(sampler_handle) = mapping.sampler {
131                let sam_br = module.global_variables[sampler_handle]
132                    .binding
133                    .as_ref()
134                    .unwrap();
135                let sampler_linear_index = self.layout.get_slot(sam_br);
136                self.sampler_map[texture_linear_index as usize] = Some(sampler_linear_index);
137            }
138        }
139
140        for (name, location) in reflection_info.varying {
141            match naga_stage {
142                naga::ShaderStage::Vertex => {
143                    assert_eq!(location.index, 0);
144                    unsafe { gl.bind_attrib_location(program, location.location, &name) }
145                }
146                naga::ShaderStage::Fragment => {
147                    assert_eq!(location.index, 0);
148                    unsafe { gl.bind_frag_data_location(program, location.location, &name) }
149                }
150                naga::ShaderStage::Compute => {}
151                naga::ShaderStage::Task
152                | naga::ShaderStage::Mesh
153                | naga::ShaderStage::RayGeneration
154                | naga::ShaderStage::AnyHit
155                | naga::ShaderStage::ClosestHit
156                | naga::ShaderStage::Miss => unreachable!(),
157            }
158        }
159
160        *self.immediates_items = reflection_info.immediates_items;
161
162        if naga_stage == naga::ShaderStage::Vertex {
163            *self.clip_distance_count = reflection_info.clip_distance_count;
164        }
165    }
166}
167
168impl super::Device {
169    /// # Safety
170    ///
171    /// - `name` must be created respecting `desc`
172    /// - `name` must be a texture
173    /// - If `drop_callback` is [`None`], wgpu-hal will take ownership of the texture. If
174    ///   `drop_callback` is [`Some`], the texture must be valid until the callback is called.
175    #[cfg(any(native, Emscripten))]
176    pub unsafe fn texture_from_raw(
177        &self,
178        name: NonZeroU32,
179        desc: &crate::TextureDescriptor,
180        drop_callback: Option<crate::DropCallback>,
181    ) -> super::Texture {
182        super::Texture {
183            inner: super::TextureInner::Texture {
184                raw: glow::NativeTexture(name),
185                target: super::Texture::get_info_from_desc(desc),
186            },
187            drop_guard: crate::DropGuard::from_option(drop_callback),
188            mip_level_count: desc.mip_level_count,
189            array_layer_count: desc.array_layer_count(),
190            format: desc.format,
191            format_desc: self.shared.describe_texture_format(desc.format),
192            copy_size: desc.copy_extent(),
193        }
194    }
195
196    /// # Safety
197    ///
198    /// - `name` must be created respecting `desc`
199    /// - `name` must be a renderbuffer
200    /// - If `drop_callback` is [`None`], wgpu-hal will take ownership of the renderbuffer. If
201    ///   `drop_callback` is [`Some`], the renderbuffer must be valid until the callback is called.
202    #[cfg(any(native, Emscripten))]
203    pub unsafe fn texture_from_raw_renderbuffer(
204        &self,
205        name: NonZeroU32,
206        desc: &crate::TextureDescriptor,
207        drop_callback: Option<crate::DropCallback>,
208    ) -> super::Texture {
209        super::Texture {
210            inner: super::TextureInner::Renderbuffer {
211                raw: glow::NativeRenderbuffer(name),
212            },
213            drop_guard: crate::DropGuard::from_option(drop_callback),
214            mip_level_count: desc.mip_level_count,
215            array_layer_count: desc.array_layer_count(),
216            format: desc.format,
217            format_desc: self.shared.describe_texture_format(desc.format),
218            copy_size: desc.copy_extent(),
219        }
220    }
221
222    /// Imports a single-plane DMA-BUF as a GLES `GL_TEXTURE_2D` without copying.
223    /// `None` for `drm_modifier` requests an implicit layout.
224    /// The supplied FD is closed on both success and failure. The EGL image is
225    /// destroyed after binding; the GL texture retains the imported storage.
226    ///
227    /// # Errors
228    ///
229    /// Returns [`ImportTextureError`] if the texture configuration is unsupported,
230    /// an import parameter does not fit EGLint, required EGL resources, extensions
231    /// or entry points are unavailable, or a GL or EGL operation fails.
232    ///
233    /// # Safety
234    ///
235    /// - `fd`, `drm_format`, `stride`, `offset` and `drm_modifier` must describe
236    ///   the same DMA-BUF allocation.
237    /// - `desc` must be valid (consider calling `wgpu_core::Device::validate_texture_descriptor`)
238    ///   and must accurately describe the texture being imported (including `drm_format`)
239    /// - Only one 2D plane, one array layer, one mip level and one sample are
240    ///   currently supported.
241    /// - Synchronization with the DMA-BUF producer must be handled separately.
242    #[cfg(all(unix, native))]
243    pub unsafe fn texture_from_dmabuf_fd(
244        &self,
245        fd: std::os::fd::OwnedFd,
246        desc: &crate::TextureDescriptor,
247        drm_format: u32,
248        drm_modifier: Option<u64>,
249        stride: u64,
250        offset: u64,
251    ) -> Result<super::Texture, ImportTextureError> {
252        use core::ffi::c_void;
253        use core::ptr;
254        use glow::HasContext as _;
255        use std::os::fd::AsRawFd as _;
256
257        const LINUX_DMA_BUF_EXT: khronos_egl::Enum = 0x3270;
258        const LINUX_DRM_FOURCC_EXT: khronos_egl::Int = 0x3271;
259        const DMA_BUF_PLANE0_FD_EXT: khronos_egl::Int = 0x3272;
260        const DMA_BUF_PLANE0_OFFSET_EXT: khronos_egl::Int = 0x3273;
261        const DMA_BUF_PLANE0_PITCH_EXT: khronos_egl::Int = 0x3274;
262        const DMA_BUF_PLANE0_MODIFIER_LO_EXT: khronos_egl::Int = 0x3443;
263        const DMA_BUF_PLANE0_MODIFIER_HI_EXT: khronos_egl::Int = 0x3444;
264
265        let context = self.context();
266        let raw_texture = {
267            // Release the context lock once the GL import operations are complete.
268            let gl = context.lock();
269            let error = unsafe { gl.get_error() };
270            if error != glow::NO_ERROR {
271                log::warn!("Pre-existing GL error blocks DMA-BUF texture import: {error:#x}");
272                return Err(ImportTextureError::Device(crate::DeviceError::Unexpected));
273            }
274
275            if desc.dimension != wgt::TextureDimension::D2
276                || desc.size.depth_or_array_layers != 1
277                || desc.mip_level_count != 1
278                || desc.sample_count != 1
279                || desc.format.is_multi_planar_format()
280            {
281                return Err(ImportTextureError::UnsupportedTextureDescriptor);
282            }
283
284            let width = i32::try_from(desc.size.width)
285                .map_err(|_| ImportTextureError::ParameterOutOfRange("width"))?;
286
287            let height = i32::try_from(desc.size.height)
288                .map_err(|_| ImportTextureError::ParameterOutOfRange("height"))?;
289
290            let stride = i32::try_from(stride)
291                .map_err(|_| ImportTextureError::ParameterOutOfRange("stride"))?;
292
293            let offset = i32::try_from(offset)
294                .map_err(|_| ImportTextureError::ParameterOutOfRange("offset"))?;
295
296            let drm_format = i32::try_from(drm_format)
297                .map_err(|_| ImportTextureError::ParameterOutOfRange("drm_format"))?;
298
299            let egl = context
300                .egl_instance()
301                .ok_or(ImportTextureError::MissingEglContext)?;
302
303            let display = *context
304                .raw_display()
305                .ok_or(ImportTextureError::MissingEglDisplay)?;
306
307            let caps = self.shared.private_caps;
308            if !caps.contains(PrivateCapabilities::EGL_IMAGE_DMA_BUF_IMPORT) {
309                return Err(ImportTextureError::MissingImageDmaBufImportExtension);
310            }
311
312            if drm_modifier.is_some()
313                && !caps.contains(PrivateCapabilities::EGL_IMAGE_DMA_BUF_IMPORT_MODIFIERS)
314            {
315                return Err(ImportTextureError::MissingImageDmaBufImportModifiersExtension);
316            }
317
318            let create_image: unsafe extern "system" fn(
319                display: *mut c_void,
320                context: *mut c_void,
321                target: u32,
322                buffer: *mut c_void,
323                attributes: *const i32,
324            ) -> *mut c_void = {
325                let address = egl
326                    .get_proc_address("eglCreateImageKHR")
327                    .ok_or(ImportTextureError::MissingEntryPoint("eglCreateImageKHR"))?;
328
329                unsafe { core::mem::transmute(address) }
330            };
331
332            let destroy_image: unsafe extern "system" fn(
333                display: *mut c_void,
334                image: *mut c_void,
335            ) -> u32 = {
336                let address = egl
337                    .get_proc_address("eglDestroyImageKHR")
338                    .ok_or(ImportTextureError::MissingEntryPoint("eglDestroyImageKHR"))?;
339
340                unsafe { core::mem::transmute(address) }
341            };
342
343            let image_target_texture: unsafe extern "system" fn(target: u32, image: *mut c_void) = {
344                let address = egl.get_proc_address("glEGLImageTargetTexture2DOES").ok_or(
345                    ImportTextureError::MissingEntryPoint("glEGLImageTargetTexture2DOES"),
346                )?;
347
348                unsafe { core::mem::transmute(address) }
349            };
350
351            let mut attributes = vec![
352                khronos_egl::WIDTH,
353                width,
354                khronos_egl::HEIGHT,
355                height,
356                LINUX_DRM_FOURCC_EXT,
357                drm_format,
358                DMA_BUF_PLANE0_FD_EXT,
359                fd.as_raw_fd(),
360                DMA_BUF_PLANE0_OFFSET_EXT,
361                offset,
362                DMA_BUF_PLANE0_PITCH_EXT,
363                stride,
364            ];
365
366            if let Some(modifier) = drm_modifier {
367                let modifier_low = modifier as u32;
368                let modifier_high = (modifier >> 32) as u32;
369
370                attributes.extend_from_slice(&[
371                    DMA_BUF_PLANE0_MODIFIER_LO_EXT,
372                    modifier_low as i32,
373                    DMA_BUF_PLANE0_MODIFIER_HI_EXT,
374                    modifier_high as i32,
375                ]);
376            }
377
378            attributes.push(khronos_egl::NONE);
379
380            let egl_image = unsafe {
381                create_image(
382                    display.as_ptr(),
383                    ptr::null_mut(),
384                    LINUX_DMA_BUF_EXT,
385                    ptr::null_mut(),
386                    attributes.as_ptr(),
387                )
388            };
389
390            if egl_image.is_null() {
391                /*
392                 * EGL never takes ownership of the fd. OwnedFd closes it
393                 * automatically when this function returns.
394                 */
395                return Err(ImportTextureError::EglImageCreation(egl.get_error()));
396            }
397
398            let raw_texture = match unsafe { gl.create_texture() } {
399                Ok(texture) => texture,
400                Err(error) => {
401                    if unsafe { destroy_image(display.as_ptr(), egl_image) } == 0 {
402                        log::error!(
403                            "eglDestroyImageKHR failed after GL texture creation failure: {:?}",
404                            egl.get_error()
405                        );
406                    }
407
408                    return Err(ImportTextureError::GlTextureCreation(error));
409                }
410            };
411
412            let gl_error = unsafe {
413                let mut error = gl.get_error();
414                if error == glow::NO_ERROR {
415                    gl.bind_texture(glow::TEXTURE_2D, Some(raw_texture));
416                    error = gl.get_error();
417                }
418
419                if error == glow::NO_ERROR {
420                    image_target_texture(glow::TEXTURE_2D, egl_image);
421                    error = gl.get_error();
422                }
423
424                if error == glow::NO_ERROR {
425                    gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_BASE_LEVEL, 0);
426                    error = gl.get_error();
427                }
428
429                if error == glow::NO_ERROR {
430                    gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MAX_LEVEL, 0);
431                    error = gl.get_error();
432                }
433
434                if error == glow::NO_ERROR {
435                    gl.bind_texture(glow::TEXTURE_2D, None);
436                    error = gl.get_error();
437                }
438
439                error
440            };
441
442            if gl_error != glow::NO_ERROR {
443                unsafe {
444                    gl.delete_texture(raw_texture);
445                }
446
447                if unsafe { destroy_image(display.as_ptr(), egl_image) } == 0 {
448                    log::error!(
449                        "eglDestroyImageKHR failed after GL texture import failure: {:?}",
450                        egl.get_error()
451                    );
452                }
453
454                return Err(ImportTextureError::BindAndConfigure { gl_error });
455            }
456
457            // The GL texture retains the image storage, so the EGLImage is no longer needed.
458            if unsafe { destroy_image(display.as_ptr(), egl_image) } == 0 {
459                let error = egl.get_error();
460                unsafe { gl.delete_texture(raw_texture) };
461                return Err(ImportTextureError::EglImageDestruction(error));
462            }
463
464            raw_texture
465        };
466
467        Ok(unsafe { self.texture_from_raw(raw_texture.0, desc, None) })
468    }
469
470    /// Wrap an existing `WebGlTexture` as a wgpu-hal texture, without copying.
471    ///
472    /// The handle is always externally owned: unlike `texture_from_raw` (the
473    /// native import), where a [`None`] callback transfers ownership of the raw GL name,
474    /// wgpu-hal never deletes a `WebGlTexture` — it is a GC-managed JS handle,
475    /// like the `GpuTexture`s the WebGPU backend wraps. If `drop_callback` is
476    /// [`Some`], it fires once wgpu-hal is done with the handle; deleting the
477    /// texture at that point, if desired, is the callback's job.
478    ///
479    /// `view_dimension` selects the texture's bind target (`D2` →
480    /// `TEXTURE_2D`, `D2Array` → `TEXTURE_2D_ARRAY`, `Cube` →
481    /// `TEXTURE_CUBE_MAP`, `D3` → `TEXTURE_3D`) and must match the type
482    /// `handle` was created as; it cannot be inferred from `desc`.
483    ///
484    /// `handle` must have been created by this device's
485    /// `WebGl2RenderingContext`, match `desc`, and stay valid until wgpu-hal
486    /// is done with it. Violations yield GL errors rather than memory
487    /// unsafety, which is why this method is not `unsafe`.
488    #[cfg(webgl)]
489    pub fn texture_from_webgl_handle(
490        &self,
491        handle: web_sys::WebGlTexture,
492        desc: &crate::TextureDescriptor,
493        view_dimension: wgt::TextureViewDimension,
494        drop_callback: Option<crate::DropCallback>,
495    ) -> super::Texture {
496        assert_eq!(
497            view_dimension.compatible_texture_dimension(),
498            desc.dimension,
499            "view_dimension {view_dimension:?} is incompatible with the descriptor's dimension",
500        );
501
502        // SAFETY: glow marks this `unsafe` as it does all GL entry points, but
503        // it only inserts the handle into glow's slotmap; every later use of
504        // the key goes through browser-validated WebGL calls.
505        let raw = unsafe { self.shared.context.lock().register_external_texture(handle) };
506
507        super::Texture {
508            inner: super::TextureInner::Texture {
509                raw,
510                target: super::Texture::target_for_view_dimension(view_dimension),
511            },
512            // Always a guard, even without a callback: its presence is what
513            // marks the handle as externally owned in `destroy_texture`.
514            drop_guard: Some(crate::DropGuard::external(drop_callback)),
515            mip_level_count: desc.mip_level_count,
516            array_layer_count: desc.array_layer_count(),
517            format: desc.format,
518            format_desc: self.shared.describe_texture_format(desc.format),
519            copy_size: desc.copy_extent(),
520        }
521    }
522
523    /// Borrow the underlying `WebGlTexture` for a wgpu-hal texture, if it is a
524    /// plain GL texture on the WebGL backend.
525    ///
526    /// Works for both normally-created textures and textures imported via
527    /// [`Self::texture_from_webgl_handle`]. Returns `None` for renderbuffers /
528    /// framebuffers or if the glow slot is dead.
529    #[cfg(webgl)]
530    pub fn webgl_texture_handle(&self, texture: &super::Texture) -> Option<web_sys::WebGlTexture> {
531        match texture.inner {
532            super::TextureInner::Texture { raw, .. } => {
533                self.shared.context.lock().as_web_gl_texture(raw)
534            }
535            _ => None,
536        }
537    }
538
539    /// # Safety
540    ///
541    /// - `name` must be a non-zero GL buffer name created respecting `desc`.
542    /// - The buffer's storage size must be at least `desc.size`.
543    /// - If `desc.usage` includes [`BufferUses::MAP_READ`](wgt::BufferUses::MAP_READ) or
544    ///   [`BufferUses::MAP_WRITE`](wgt::BufferUses::MAP_WRITE), the GL buffer must have
545    ///   been allocated with `glBufferStorage` (or equivalent) using flags compatible
546    ///   with persistent mapping (`GL_MAP_PERSISTENT_BIT` plus matching read/write/coherent
547    ///   bits). Buffers created with the legacy `glBufferData` family cannot be mapped
548    ///   through this path.
549    /// - If `drop_callback` is [`None`], wgpu-hal will take ownership of the buffer and
550    ///   call `glDeleteBuffers` on it. If `drop_callback` is [`Some`], the buffer must
551    ///   remain valid until the callback is invoked.
552    #[cfg(any(native, Emscripten))]
553    pub unsafe fn buffer_from_raw(
554        &self,
555        name: NonZeroU32,
556        desc: &crate::BufferDescriptor,
557        drop_callback: Option<crate::DropCallback>,
558    ) -> super::Buffer {
559        let target = if desc.usage.contains(wgt::BufferUses::INDEX) {
560            glow::ELEMENT_ARRAY_BUFFER
561        } else {
562            glow::ARRAY_BUFFER
563        };
564
565        let is_host_visible = desc
566            .usage
567            .intersects(wgt::BufferUses::MAP_READ | wgt::BufferUses::MAP_WRITE);
568        let is_coherent = desc
569            .memory_flags
570            .contains(crate::MemoryFlags::PREFER_COHERENT);
571
572        let mut map_flags = 0;
573        if desc.usage.contains(wgt::BufferUses::MAP_READ) {
574            map_flags |= glow::MAP_READ_BIT;
575        }
576        if desc.usage.contains(wgt::BufferUses::MAP_WRITE) {
577            map_flags |= glow::MAP_WRITE_BIT;
578        }
579        if is_host_visible {
580            map_flags |= glow::MAP_PERSISTENT_BIT;
581            if is_coherent {
582                map_flags |= glow::MAP_COHERENT_BIT;
583            }
584        }
585        if !is_coherent && desc.usage.contains(wgt::BufferUses::MAP_WRITE) {
586            map_flags |= glow::MAP_FLUSH_EXPLICIT_BIT;
587        }
588
589        self.counters.buffers.add(1);
590
591        super::Buffer {
592            raw: Some(glow::NativeBuffer(name)),
593            target,
594            map_flags,
595            map_state: Arc::new(Mutex::new(super::BufferMapState {
596                mapped: false,
597                data: None,
598                offset_of_current_mapping: 0,
599            })),
600            drop_guard: crate::DropGuard::from_option(drop_callback).map(Arc::new),
601        }
602    }
603
604    unsafe fn compile_shader(
605        gl: &glow::Context,
606        shader: &str,
607        naga_stage: naga::ShaderStage,
608        #[cfg_attr(target_family = "wasm", allow(unused))] label: Option<&str>,
609    ) -> Result<glow::Shader, crate::PipelineError> {
610        let target = match naga_stage {
611            naga::ShaderStage::Vertex => glow::VERTEX_SHADER,
612            naga::ShaderStage::Fragment => glow::FRAGMENT_SHADER,
613            naga::ShaderStage::Compute => glow::COMPUTE_SHADER,
614            naga::ShaderStage::Task
615            | naga::ShaderStage::Mesh
616            | naga::ShaderStage::RayGeneration
617            | naga::ShaderStage::AnyHit
618            | naga::ShaderStage::ClosestHit
619            | naga::ShaderStage::Miss => unreachable!(),
620        };
621
622        let raw = unsafe { gl.create_shader(target) }.unwrap();
623        #[cfg(native)]
624        if gl.supports_debug() {
625            let name = raw.0.get();
626            unsafe { gl.object_label(glow::SHADER, name, label) };
627        }
628
629        unsafe { gl.shader_source(raw, shader) };
630        unsafe { gl.compile_shader(raw) };
631
632        log::debug!("\tCompiled shader {raw:?}");
633
634        let compiled_ok = unsafe { gl.get_shader_compile_status(raw) };
635        let msg = unsafe { gl.get_shader_info_log(raw) };
636        if compiled_ok {
637            if !msg.is_empty() {
638                log::debug!("\tCompile message: {msg}");
639            }
640            Ok(raw)
641        } else {
642            log::error!("\tShader compilation failed: {msg}");
643            unsafe { gl.delete_shader(raw) };
644            Err(crate::PipelineError::Linkage(
645                map_naga_stage(naga_stage),
646                msg,
647            ))
648        }
649    }
650
651    fn create_shader(
652        gl: &glow::Context,
653        naga_stage: naga::ShaderStage,
654        stage: &crate::ProgrammableStage<super::ShaderModule>,
655        context: CompilationContext,
656        program: glow::Program,
657    ) -> Result<glow::Shader, crate::PipelineError> {
658        let source = 'outer: {
659            use naga::back::glsl;
660            let pipeline_options = glsl::PipelineOptions {
661                shader_stage: naga_stage,
662                entry_point: stage.entry_point.to_owned(),
663                multiview: context
664                    .multiview_mask
665                    .map(|a| NonZeroU32::new(a.get().count_ones()).unwrap()),
666            };
667
668            let naga = match stage.module.source {
669                super::ShaderModuleSource::Naga(ref naga) => naga,
670                super::ShaderModuleSource::Passthrough { ref source } => {
671                    break 'outer Cow::Borrowed(source);
672                }
673            };
674
675            let (module, info) = naga::back::pipeline_constants::process_overrides(
676                &naga.module,
677                &naga.info,
678                Some((naga_stage, stage.entry_point)),
679                stage.constants,
680            )
681            .map_err(|e| {
682                let msg = format!("{e}");
683                crate::PipelineError::PipelineConstants(map_naga_stage(naga_stage), msg)
684            })?;
685
686            let entry_point_index = module
687                .entry_points
688                .iter()
689                .position(|ep| ep.name.as_str() == stage.entry_point)
690                .ok_or(crate::PipelineError::EntryPoint(naga_stage))?;
691
692            use naga::proc::BoundsCheckPolicy;
693            // The image bounds checks require the TEXTURE_LEVELS feature available in GL core 4.3+.
694            let version = gl.version();
695            let image_check = if !version.is_embedded && (version.major, version.minor) >= (4, 3) {
696                BoundsCheckPolicy::ReadZeroSkipWrite
697            } else {
698                BoundsCheckPolicy::Unchecked
699            };
700
701            // Other bounds check are either provided by glsl or not implemented yet.
702            let policies = naga::proc::BoundsCheckPolicies {
703                index: BoundsCheckPolicy::Unchecked,
704                buffer: BoundsCheckPolicy::Unchecked,
705                image_load: image_check,
706                binding_array: BoundsCheckPolicy::Unchecked,
707            };
708
709            let mut output = String::new();
710            let needs_temp_options = stage.zero_initialize_workgroup_memory
711                != context.layout.naga_options.zero_initialize_workgroup_memory;
712            let mut temp_options;
713            let naga_options = if needs_temp_options {
714                // We use a conditional here, as cloning the naga_options could be expensive
715                // That is, we want to avoid doing that unless we cannot avoid it
716                temp_options = context.layout.naga_options.clone();
717                temp_options.zero_initialize_workgroup_memory =
718                    stage.zero_initialize_workgroup_memory;
719                &temp_options
720            } else {
721                &context.layout.naga_options
722            };
723            let mut writer = glsl::Writer::new(
724                &mut output,
725                &module,
726                &info,
727                naga_options,
728                &pipeline_options,
729                policies,
730            )
731            .map_err(|e| {
732                let msg = format!("{e}");
733                crate::PipelineError::Linkage(map_naga_stage(naga_stage), msg)
734            })?;
735
736            let reflection_info = writer.write().map_err(|e| {
737                let msg = format!("{e}");
738                crate::PipelineError::Linkage(map_naga_stage(naga_stage), msg)
739            })?;
740
741            log::debug!("Naga generated shader:\n{output}");
742
743            context.consume_reflection(
744                gl,
745                &module,
746                info.get_entry_point(entry_point_index),
747                reflection_info,
748                naga_stage,
749                program,
750            );
751            Cow::Owned(output)
752        };
753
754        unsafe { Self::compile_shader(gl, &source, naga_stage, stage.module.label.as_deref()) }
755    }
756
757    unsafe fn create_pipeline<'a>(
758        &self,
759        gl: &glow::Context,
760        shaders: ArrayVec<ShaderStage<'a>, { crate::MAX_CONCURRENT_SHADER_STAGES }>,
761        layout: &super::PipelineLayout,
762        #[cfg_attr(target_family = "wasm", allow(unused))] label: Option<&str>,
763        multiview_mask: Option<NonZeroU32>,
764    ) -> Result<Arc<super::PipelineInner>, crate::PipelineError> {
765        let mut program_stages = ArrayVec::new();
766        let group_to_binding_to_slot = layout
767            .group_infos
768            .iter()
769            .map(|group| group.as_ref().map(|group| group.binding_to_slot.clone()))
770            .collect::<Vec<_>>();
771        for &(naga_stage, stage) in &shaders {
772            program_stages.push(super::ProgramStage {
773                naga_stage: naga_stage.to_owned(),
774                shader_id: stage.module.id,
775                entry_point: stage.entry_point.to_owned(),
776                zero_initialize_workgroup_memory: stage.zero_initialize_workgroup_memory,
777                constant_hash: Self::create_constant_hash(stage),
778            });
779        }
780        let mut guard = self
781            .shared
782            .program_cache
783            .try_lock()
784            .expect("Couldn't acquire program_cache lock");
785        // This guard ensures that we can't accidentally destroy a program whilst we're about to reuse it
786        // The only place that destroys a pipeline is also locking on `program_cache`
787        let program = guard
788            .entry(super::ProgramCacheKey {
789                stages: program_stages,
790                group_to_binding_to_slot: group_to_binding_to_slot.into_boxed_slice(),
791            })
792            .or_insert_with(|| unsafe {
793                Self::create_program(
794                    gl,
795                    shaders,
796                    layout,
797                    label,
798                    multiview_mask,
799                    self.shared.shading_language_version,
800                    self.shared.private_caps,
801                )
802            })
803            .to_owned()?;
804        drop(guard);
805
806        Ok(program)
807    }
808
809    fn create_constant_hash(stage: &crate::ProgrammableStage<super::ShaderModule>) -> Vec<u8> {
810        let mut buf: Vec<u8> = Vec::new();
811
812        for (key, value) in stage.constants.iter() {
813            buf.extend_from_slice(key.as_bytes());
814            buf.extend_from_slice(&value.to_ne_bytes());
815        }
816
817        buf
818    }
819
820    unsafe fn create_program<'a>(
821        gl: &glow::Context,
822        shaders: ArrayVec<ShaderStage<'a>, { crate::MAX_CONCURRENT_SHADER_STAGES }>,
823        layout: &super::PipelineLayout,
824        #[cfg_attr(target_family = "wasm", allow(unused))] label: Option<&str>,
825        multiview_mask: Option<NonZeroU32>,
826        glsl_version: naga::back::glsl::Version,
827        private_caps: PrivateCapabilities,
828    ) -> Result<Arc<super::PipelineInner>, crate::PipelineError> {
829        let glsl_version = match glsl_version {
830            naga::back::glsl::Version::Embedded { version, .. } => format!("{version} es"),
831            naga::back::glsl::Version::Desktop(version) => format!("{version}"),
832        };
833        let program = unsafe { gl.create_program() }.unwrap();
834        #[cfg(native)]
835        if let Some(label) = label {
836            if private_caps.contains(PrivateCapabilities::DEBUG_FNS) {
837                let name = program.0.get();
838                unsafe { gl.object_label(glow::PROGRAM, name, Some(label)) };
839            }
840        }
841
842        let mut name_binding_map = NameBindingMap::default();
843        let mut immediates_items = ArrayVec::<_, { crate::MAX_CONCURRENT_SHADER_STAGES }>::new();
844        let mut sampler_map = [None; super::MAX_TEXTURE_SLOTS];
845        let mut has_stages = wgt::ShaderStages::empty();
846        let mut shaders_to_delete = ArrayVec::<_, { crate::MAX_CONCURRENT_SHADER_STAGES }>::new();
847        let mut clip_distance_count = 0;
848
849        for &(naga_stage, stage) in &shaders {
850            has_stages |= map_naga_stage(naga_stage);
851            let pc_item = {
852                immediates_items.push(Vec::new());
853                immediates_items.last_mut().unwrap()
854            };
855            let context = CompilationContext {
856                layout,
857                sampler_map: &mut sampler_map,
858                name_binding_map: &mut name_binding_map,
859                immediates_items: pc_item,
860                multiview_mask,
861                clip_distance_count: &mut clip_distance_count,
862            };
863
864            let shader = Self::create_shader(gl, naga_stage, stage, context, program)?;
865            shaders_to_delete.push(shader);
866        }
867
868        // Create empty fragment shader if only vertex shader is present
869        if has_stages == wgt::ShaderStages::VERTEX {
870            let shader_src = format!("#version {glsl_version}\n void main(void) {{}}",);
871            log::debug!("Only vertex shader is present. Creating an empty fragment shader",);
872            let shader = unsafe {
873                Self::compile_shader(
874                    gl,
875                    &shader_src,
876                    naga::ShaderStage::Fragment,
877                    Some("(wgpu internal) dummy fragment shader"),
878                )
879            }?;
880            shaders_to_delete.push(shader);
881        }
882
883        for &shader in shaders_to_delete.iter() {
884            unsafe { gl.attach_shader(program, shader) };
885        }
886        unsafe { gl.link_program(program) };
887
888        for shader in shaders_to_delete {
889            unsafe { gl.delete_shader(shader) };
890        }
891
892        log::debug!("\tLinked program {program:?}");
893
894        let linked_ok = unsafe { gl.get_program_link_status(program) };
895        let msg = unsafe { gl.get_program_info_log(program) };
896        if !linked_ok {
897            return Err(crate::PipelineError::Linkage(has_stages, msg));
898        }
899        if !msg.is_empty() {
900            log::debug!("\tLink message: {msg}");
901        }
902
903        if !private_caps.contains(PrivateCapabilities::SHADER_BINDING_LAYOUT) {
904            // This remapping is only needed if we aren't able to put the binding layout
905            // in the shader. We can't remap storage buffers this way.
906            unsafe { gl.use_program(Some(program)) };
907            for (ref name, (register, slot)) in name_binding_map {
908                log::trace!("Get binding {name:?} from program {program:?}");
909                match register {
910                    super::BindingRegister::UniformBuffers => {
911                        let index = unsafe { gl.get_uniform_block_index(program, name) }.unwrap();
912                        log::trace!("\tBinding slot {slot} to block index {index}");
913                        unsafe { gl.uniform_block_binding(program, index, slot as _) };
914                    }
915                    super::BindingRegister::StorageBuffers => {
916                        let index =
917                            unsafe { gl.get_shader_storage_block_index(program, name) }.unwrap();
918                        log::error!("Unable to re-map shader storage block {name} to {index}");
919                        return Err(crate::DeviceError::Lost.into());
920                    }
921                    super::BindingRegister::Textures | super::BindingRegister::Images => {
922                        let location = unsafe { gl.get_uniform_location(program, name) };
923                        unsafe { gl.uniform_1_i32(location.as_ref(), slot as _) };
924                    }
925                }
926            }
927        }
928
929        let mut uniforms = ArrayVec::new();
930
931        for stage_items in immediates_items {
932            for item in stage_items {
933                let location = unsafe { gl.get_uniform_location(program, &item.access_path) };
934
935                log::trace!(
936                    "immediate data item: name={}, ty={:?}, offset={}, location={:?}",
937                    item.access_path,
938                    item.ty,
939                    item.offset,
940                    location,
941                );
942
943                if let Some(location) = location {
944                    uniforms.push(super::ImmediateDesc {
945                        location,
946                        offset: item.offset,
947                        size_bytes: item.size_bytes,
948                        ty: item.ty,
949                    });
950                }
951            }
952        }
953
954        let first_instance_location = if has_stages.contains(wgt::ShaderStages::VERTEX) {
955            // If this returns none (the uniform isn't active), that's fine, we just won't set it.
956            unsafe { gl.get_uniform_location(program, naga::back::glsl::FIRST_INSTANCE_BINDING) }
957        } else {
958            None
959        };
960
961        Ok(Arc::new(super::PipelineInner {
962            program,
963            sampler_map,
964            first_instance_location,
965            immediates_descs: uniforms,
966            clip_distance_count,
967        }))
968    }
969}
970
971impl crate::Device for super::Device {
972    type A = super::Api;
973
974    unsafe fn create_buffer(
975        &self,
976        desc: &crate::BufferDescriptor,
977    ) -> Result<(super::Buffer, wgt::BufferAddress), crate::DeviceError> {
978        let target = if desc.usage.contains(wgt::BufferUses::INDEX) {
979            glow::ELEMENT_ARRAY_BUFFER
980        } else {
981            glow::ARRAY_BUFFER
982        };
983
984        let emulate_map = self
985            .shared
986            .workarounds
987            .contains(super::Workarounds::EMULATE_BUFFER_MAP)
988            || !self
989                .shared
990                .private_caps
991                .contains(PrivateCapabilities::BUFFER_ALLOCATION);
992
993        if emulate_map && desc.usage.intersects(wgt::BufferUses::MAP_WRITE) {
994            return Ok((
995                super::Buffer {
996                    raw: None,
997                    target,
998                    map_flags: 0,
999                    map_state: Arc::new(Mutex::new(super::BufferMapState {
1000                        mapped: false,
1001                        data: Some(vec![0; desc.size as usize]),
1002                        offset_of_current_mapping: 0,
1003                    })),
1004                    drop_guard: None,
1005                },
1006                desc.size,
1007            ));
1008        }
1009
1010        let gl = &self.shared.context.lock();
1011
1012        let target = if desc.usage.contains(wgt::BufferUses::INDEX) {
1013            glow::ELEMENT_ARRAY_BUFFER
1014        } else {
1015            glow::ARRAY_BUFFER
1016        };
1017
1018        let is_host_visible = desc
1019            .usage
1020            .intersects(wgt::BufferUses::MAP_READ | wgt::BufferUses::MAP_WRITE);
1021        let is_coherent = desc
1022            .memory_flags
1023            .contains(crate::MemoryFlags::PREFER_COHERENT);
1024
1025        let mut map_flags = 0;
1026        if desc.usage.contains(wgt::BufferUses::MAP_READ) {
1027            map_flags |= glow::MAP_READ_BIT;
1028        }
1029        if desc.usage.contains(wgt::BufferUses::MAP_WRITE) {
1030            map_flags |= glow::MAP_WRITE_BIT;
1031        }
1032
1033        let raw = Some(unsafe { gl.create_buffer() }.map_err(|_| crate::DeviceError::OutOfMemory)?);
1034        unsafe { gl.bind_buffer(target, raw) };
1035        let raw_size = desc
1036            .size
1037            .try_into()
1038            .map_err(|_| crate::DeviceError::OutOfMemory)?;
1039
1040        if self
1041            .shared
1042            .private_caps
1043            .contains(PrivateCapabilities::BUFFER_ALLOCATION)
1044        {
1045            if is_host_visible {
1046                map_flags |= glow::MAP_PERSISTENT_BIT;
1047                if is_coherent {
1048                    map_flags |= glow::MAP_COHERENT_BIT;
1049                }
1050            }
1051            // TODO: may also be required for other calls involving `buffer_sub_data_u8_slice` (e.g. copy buffer to buffer and clear buffer)
1052            if desc.usage.intersects(wgt::BufferUses::QUERY_RESOLVE) {
1053                map_flags |= glow::DYNAMIC_STORAGE_BIT;
1054            }
1055            unsafe { gl.buffer_storage(target, raw_size, None, map_flags) };
1056        } else {
1057            assert!(!is_coherent);
1058            let usage = if is_host_visible {
1059                if desc.usage.contains(wgt::BufferUses::MAP_READ) {
1060                    glow::STREAM_READ
1061                } else {
1062                    glow::DYNAMIC_DRAW
1063                }
1064            } else {
1065                // Even if the usage doesn't contain SRC_READ, we update it internally at least once
1066                // Some vendors take usage very literally and STATIC_DRAW will freeze us with an empty buffer
1067                // https://github.com/gfx-rs/wgpu/issues/3371
1068                glow::DYNAMIC_DRAW
1069            };
1070            unsafe { gl.buffer_data_size(target, raw_size, usage) };
1071        }
1072
1073        unsafe { gl.bind_buffer(target, None) };
1074
1075        if !is_coherent && desc.usage.contains(wgt::BufferUses::MAP_WRITE) {
1076            map_flags |= glow::MAP_FLUSH_EXPLICIT_BIT;
1077        }
1078        //TODO: do we need `glow::MAP_UNSYNCHRONIZED_BIT`?
1079
1080        #[cfg(native)]
1081        if let Some(label) = desc.label {
1082            if self
1083                .shared
1084                .private_caps
1085                .contains(PrivateCapabilities::DEBUG_FNS)
1086            {
1087                let name = raw.map_or(0, |buf| buf.0.get());
1088                unsafe { gl.object_label(glow::BUFFER, name, Some(label)) };
1089            }
1090        }
1091
1092        let data = if emulate_map && desc.usage.contains(wgt::BufferUses::MAP_READ) {
1093            Some(vec![0; desc.size as usize])
1094        } else {
1095            None
1096        };
1097
1098        self.counters.buffers.add(1);
1099
1100        Ok((
1101            super::Buffer {
1102                raw,
1103                target,
1104                map_flags,
1105                map_state: Arc::new(Mutex::new(super::BufferMapState {
1106                    mapped: false,
1107                    data,
1108                    offset_of_current_mapping: 0,
1109                })),
1110                drop_guard: None,
1111            },
1112            desc.size,
1113        ))
1114    }
1115
1116    unsafe fn destroy_buffer(&self, buffer: super::Buffer) {
1117        if buffer.drop_guard.is_none() {
1118            if let Some(raw) = buffer.raw {
1119                let gl = &self.shared.context.lock();
1120                unsafe { gl.delete_buffer(raw) };
1121            }
1122        }
1123
1124        // For clarity, we explicitly drop the drop guard. Although this has no real semantic effect as the
1125        // end of the scope will drop the drop guard since this function takes ownership of the buffer.
1126        drop(buffer.drop_guard);
1127
1128        self.counters.buffers.sub(1);
1129    }
1130
1131    unsafe fn add_raw_buffer(&self, _buffer: &super::Buffer) {
1132        self.counters.buffers.add(1);
1133    }
1134
1135    unsafe fn map_buffer(
1136        &self,
1137        buffer: &super::Buffer,
1138        range: crate::MemoryRange,
1139    ) -> Result<crate::BufferMapping, crate::DeviceError> {
1140        let is_coherent = buffer.map_flags & glow::MAP_COHERENT_BIT != 0;
1141        let ptr = match buffer.raw {
1142            None => {
1143                let mut map_state = buffer.map_state.lock();
1144                let vec = map_state.data.as_mut().unwrap();
1145                let slice = &mut vec.as_mut_slice()[range.start as usize..range.end as usize];
1146                slice.as_mut_ptr()
1147            }
1148            Some(raw) => {
1149                let gl = &self.shared.context.lock();
1150                unsafe { gl.bind_buffer(buffer.target, Some(raw)) };
1151                let mut map_state = buffer.map_state.lock();
1152                let ptr = if let Some(map_read_allocation) = map_state.data.as_mut() {
1153                    let slice = map_read_allocation.as_mut_slice();
1154                    unsafe { self.shared.get_buffer_sub_data(gl, buffer.target, 0, slice) };
1155                    slice.as_mut_ptr()
1156                } else {
1157                    map_state.offset_of_current_mapping = range.start;
1158                    // glMapBufferRange throws an error if length is 0.
1159                    // We want to allow mapping 0-sized buffer slices, so perform a workaround
1160                    // if the range length is 0. The resulting pointer must never be dereferenced.
1161                    let range_start: i32 = range
1162                        .start
1163                        .try_into()
1164                        .expect("Buffer range invalid for GLES");
1165                    let range_length: i32 = (range.end - range.start)
1166                        .try_into()
1167                        .expect("Buffer range invalid for GLES");
1168                    if range_length != 0 {
1169                        map_state.mapped = true;
1170                        unsafe {
1171                            gl.map_buffer_range(
1172                                buffer.target,
1173                                range_start,
1174                                range_length,
1175                                buffer.map_flags,
1176                            )
1177                        }
1178                    } else {
1179                        ptr::dangling_mut()
1180                    }
1181                };
1182                unsafe { gl.bind_buffer(buffer.target, None) };
1183                ptr
1184            }
1185        };
1186        Ok(crate::BufferMapping {
1187            ptr: ptr::NonNull::new(ptr).ok_or(crate::DeviceError::Lost)?,
1188            is_coherent,
1189        })
1190    }
1191    unsafe fn unmap_buffer(&self, buffer: &super::Buffer) {
1192        let gl = &self.shared.context.lock();
1193        let mut map_state = buffer.map_state.lock();
1194        if core::mem::replace(&mut map_state.mapped, false) {
1195            if let Some(raw) = buffer.raw {
1196                if map_state.data.is_none() {
1197                    unsafe { gl.bind_buffer(buffer.target, Some(raw)) };
1198                    unsafe { gl.unmap_buffer(buffer.target) };
1199                    unsafe { gl.bind_buffer(buffer.target, None) };
1200                    map_state.offset_of_current_mapping = 0;
1201                }
1202            }
1203        }
1204    }
1205    unsafe fn flush_mapped_ranges<I>(&self, buffer: &super::Buffer, ranges: I)
1206    where
1207        I: Iterator<Item = crate::MemoryRange>,
1208    {
1209        let gl = &self.shared.context.lock();
1210        let map_state = buffer.map_state.lock();
1211        if map_state.mapped {
1212            if let Some(raw) = buffer.raw {
1213                if map_state.data.is_none() {
1214                    unsafe { gl.bind_buffer(buffer.target, Some(raw)) };
1215                    for range in ranges {
1216                        let offset_of_current_mapping = map_state.offset_of_current_mapping;
1217                        unsafe {
1218                            gl.flush_mapped_buffer_range(
1219                                buffer.target,
1220                                (range.start - offset_of_current_mapping) as i32,
1221                                (range.end - range.start) as i32,
1222                            )
1223                        };
1224                    }
1225                }
1226            }
1227        }
1228    }
1229    unsafe fn invalidate_mapped_ranges<I>(&self, _buffer: &super::Buffer, _ranges: I) {
1230        //TODO: do we need to do anything?
1231    }
1232
1233    unsafe fn create_texture(
1234        &self,
1235        desc: &crate::TextureDescriptor,
1236    ) -> Result<super::Texture, crate::DeviceError> {
1237        let gl = &self.shared.context.lock();
1238
1239        let render_usage = wgt::TextureUses::COLOR_TARGET
1240            | wgt::TextureUses::DEPTH_WRITE
1241            | wgt::TextureUses::DEPTH_READ
1242            | wgt::TextureUses::STENCIL_WRITE
1243            | wgt::TextureUses::STENCIL_READ
1244            | wgt::TextureUses::TRANSIENT;
1245        let format_desc = self.shared.describe_texture_format(desc.format);
1246
1247        let inner = if render_usage.contains(desc.usage)
1248            && desc.dimension == wgt::TextureDimension::D2
1249            && desc.size.depth_or_array_layers == 1
1250        {
1251            let raw = unsafe { gl.create_renderbuffer().unwrap() };
1252            unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, Some(raw)) };
1253            if desc.sample_count > 1 {
1254                unsafe {
1255                    gl.renderbuffer_storage_multisample(
1256                        glow::RENDERBUFFER,
1257                        desc.sample_count as i32,
1258                        format_desc.internal,
1259                        desc.size.width as i32,
1260                        desc.size.height as i32,
1261                    )
1262                };
1263            } else {
1264                unsafe {
1265                    gl.renderbuffer_storage(
1266                        glow::RENDERBUFFER,
1267                        format_desc.internal,
1268                        desc.size.width as i32,
1269                        desc.size.height as i32,
1270                    )
1271                };
1272            }
1273
1274            #[cfg(native)]
1275            if let Some(label) = desc.label {
1276                if self
1277                    .shared
1278                    .private_caps
1279                    .contains(PrivateCapabilities::DEBUG_FNS)
1280                {
1281                    let name = raw.0.get();
1282                    unsafe { gl.object_label(glow::RENDERBUFFER, name, Some(label)) };
1283                }
1284            }
1285
1286            unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, None) };
1287            super::TextureInner::Renderbuffer { raw }
1288        } else {
1289            let raw = unsafe { gl.create_texture().unwrap() };
1290            let target = super::Texture::get_info_from_desc(desc);
1291
1292            unsafe { gl.bind_texture(target, Some(raw)) };
1293            //Note: this has to be done before defining the storage!
1294            match desc.format.sample_type(None, Some(self.shared.features)) {
1295                Some(
1296                    wgt::TextureSampleType::Float { filterable: false }
1297                    | wgt::TextureSampleType::Uint
1298                    | wgt::TextureSampleType::Sint,
1299                ) => {
1300                    // reset default filtering mode
1301                    unsafe {
1302                        gl.tex_parameter_i32(target, glow::TEXTURE_MIN_FILTER, glow::NEAREST as i32)
1303                    };
1304                    unsafe {
1305                        gl.tex_parameter_i32(target, glow::TEXTURE_MAG_FILTER, glow::NEAREST as i32)
1306                    };
1307                }
1308                _ => {}
1309            }
1310
1311            if conv::is_layered_target(target) {
1312                unsafe {
1313                    if self
1314                        .shared
1315                        .private_caps
1316                        .contains(PrivateCapabilities::TEXTURE_STORAGE)
1317                    {
1318                        gl.tex_storage_3d(
1319                            target,
1320                            desc.mip_level_count as i32,
1321                            format_desc.internal,
1322                            desc.size.width as i32,
1323                            desc.size.height as i32,
1324                            desc.size.depth_or_array_layers as i32,
1325                        )
1326                    } else if target == glow::TEXTURE_3D {
1327                        let mut width = desc.size.width;
1328                        let mut height = desc.size.height;
1329                        let mut depth = desc.size.depth_or_array_layers;
1330                        for i in 0..desc.mip_level_count {
1331                            gl.tex_image_3d(
1332                                target,
1333                                i as i32,
1334                                format_desc.internal as i32,
1335                                width as i32,
1336                                height as i32,
1337                                depth as i32,
1338                                0,
1339                                format_desc.external,
1340                                format_desc.data_type,
1341                                glow::PixelUnpackData::Slice(None),
1342                            );
1343                            width = max(1, width / 2);
1344                            height = max(1, height / 2);
1345                            depth = max(1, depth / 2);
1346                        }
1347                    } else {
1348                        let mut width = desc.size.width;
1349                        let mut height = desc.size.height;
1350                        for i in 0..desc.mip_level_count {
1351                            gl.tex_image_3d(
1352                                target,
1353                                i as i32,
1354                                format_desc.internal as i32,
1355                                width as i32,
1356                                height as i32,
1357                                desc.size.depth_or_array_layers as i32,
1358                                0,
1359                                format_desc.external,
1360                                format_desc.data_type,
1361                                glow::PixelUnpackData::Slice(None),
1362                            );
1363                            width = max(1, width / 2);
1364                            height = max(1, height / 2);
1365                        }
1366                    }
1367                };
1368            } else if desc.sample_count > 1 {
1369                unsafe {
1370                    gl.tex_storage_2d_multisample(
1371                        target,
1372                        desc.sample_count as i32,
1373                        format_desc.internal,
1374                        desc.size.width as i32,
1375                        desc.size.height as i32,
1376                        true,
1377                    )
1378                };
1379            } else {
1380                unsafe {
1381                    if self
1382                        .shared
1383                        .private_caps
1384                        .contains(PrivateCapabilities::TEXTURE_STORAGE)
1385                    {
1386                        gl.tex_storage_2d(
1387                            target,
1388                            desc.mip_level_count as i32,
1389                            format_desc.internal,
1390                            desc.size.width as i32,
1391                            desc.size.height as i32,
1392                        )
1393                    } else if target == glow::TEXTURE_CUBE_MAP {
1394                        let mut width = desc.size.width;
1395                        let mut height = desc.size.height;
1396                        for i in 0..desc.mip_level_count {
1397                            for face in [
1398                                glow::TEXTURE_CUBE_MAP_POSITIVE_X,
1399                                glow::TEXTURE_CUBE_MAP_NEGATIVE_X,
1400                                glow::TEXTURE_CUBE_MAP_POSITIVE_Y,
1401                                glow::TEXTURE_CUBE_MAP_NEGATIVE_Y,
1402                                glow::TEXTURE_CUBE_MAP_POSITIVE_Z,
1403                                glow::TEXTURE_CUBE_MAP_NEGATIVE_Z,
1404                            ] {
1405                                gl.tex_image_2d(
1406                                    face,
1407                                    i as i32,
1408                                    format_desc.internal as i32,
1409                                    width as i32,
1410                                    height as i32,
1411                                    0,
1412                                    format_desc.external,
1413                                    format_desc.data_type,
1414                                    glow::PixelUnpackData::Slice(None),
1415                                );
1416                            }
1417                            width = max(1, width / 2);
1418                            height = max(1, height / 2);
1419                        }
1420                    } else {
1421                        let mut width = desc.size.width;
1422                        let mut height = desc.size.height;
1423                        for i in 0..desc.mip_level_count {
1424                            gl.tex_image_2d(
1425                                target,
1426                                i as i32,
1427                                format_desc.internal as i32,
1428                                width as i32,
1429                                height as i32,
1430                                0,
1431                                format_desc.external,
1432                                format_desc.data_type,
1433                                glow::PixelUnpackData::Slice(None),
1434                            );
1435                            width = max(1, width / 2);
1436                            height = max(1, height / 2);
1437                        }
1438                    }
1439                };
1440            }
1441
1442            #[cfg(native)]
1443            if let Some(label) = desc.label {
1444                if self
1445                    .shared
1446                    .private_caps
1447                    .contains(PrivateCapabilities::DEBUG_FNS)
1448                {
1449                    let name = raw.0.get();
1450                    unsafe { gl.object_label(glow::TEXTURE, name, Some(label)) };
1451                }
1452            }
1453
1454            unsafe { gl.bind_texture(target, None) };
1455            super::TextureInner::Texture { raw, target }
1456        };
1457
1458        self.counters.textures.add(1);
1459
1460        Ok(super::Texture {
1461            inner,
1462            drop_guard: None,
1463            mip_level_count: desc.mip_level_count,
1464            array_layer_count: desc.array_layer_count(),
1465            format: desc.format,
1466            format_desc,
1467            copy_size: desc.copy_extent(),
1468        })
1469    }
1470
1471    unsafe fn destroy_texture(&self, texture: super::Texture) {
1472        if texture.drop_guard.is_none() {
1473            let gl = &self.shared.context.lock();
1474            match texture.inner {
1475                super::TextureInner::Renderbuffer { raw, .. } => {
1476                    unsafe { gl.delete_renderbuffer(raw) };
1477                }
1478                super::TextureInner::DefaultRenderbuffer => {}
1479                super::TextureInner::Texture { raw, .. } => {
1480                    unsafe { gl.delete_texture(raw) };
1481                }
1482                #[cfg(webgl)]
1483                super::TextureInner::ExternalFramebuffer { .. } => {}
1484                #[cfg(native)]
1485                super::TextureInner::ExternalNativeFramebuffer { .. } => {}
1486            }
1487        } else {
1488            // Externally owned: never delete the underlying GL object. On
1489            // WebGL an imported handle (from `texture_from_webgl_handle`)
1490            // additionally occupies a slot in glow's resource tracker;
1491            // reclaim it via `unregister_external_texture`, which does *not*
1492            // `gl.deleteTexture`, so the caller's handle survives.
1493            #[cfg(webgl)]
1494            if let super::TextureInner::Texture { raw, .. } = texture.inner {
1495                self.shared.context.lock().unregister_external_texture(raw);
1496            }
1497        }
1498
1499        // For clarity, we explicitly drop the drop guard. Although this has no real semantic effect as the
1500        // end of the scope will drop the drop guard since this function takes ownership of the texture.
1501        drop(texture.drop_guard);
1502
1503        self.counters.textures.sub(1);
1504    }
1505
1506    unsafe fn add_raw_texture(&self, _texture: &super::Texture) {
1507        self.counters.textures.add(1);
1508    }
1509
1510    unsafe fn create_texture_view(
1511        &self,
1512        texture: &super::Texture,
1513        desc: &crate::TextureViewDescriptor,
1514    ) -> Result<super::TextureView, crate::DeviceError> {
1515        self.counters.texture_views.add(1);
1516        Ok(super::TextureView {
1517            //TODO: use `super::Texture::target_for_view_dimension(desc.dimension)`?
1518            inner: texture.inner.clone(),
1519            aspects: crate::FormatAspects::new(texture.format, desc.range.aspect),
1520            mip_levels: desc.range.mip_range(texture.mip_level_count),
1521            array_layers: desc.range.layer_range(texture.array_layer_count),
1522            format: texture.format,
1523        })
1524    }
1525
1526    unsafe fn destroy_texture_view(&self, _view: super::TextureView) {
1527        self.counters.texture_views.sub(1);
1528    }
1529
1530    unsafe fn create_sampler(
1531        &self,
1532        desc: &crate::SamplerDescriptor,
1533    ) -> Result<super::Sampler, crate::DeviceError> {
1534        let gl = &self.shared.context.lock();
1535
1536        let raw = unsafe { gl.create_sampler().unwrap() };
1537
1538        let (min, mag) =
1539            conv::map_filter_modes(desc.min_filter, desc.mag_filter, desc.mipmap_filter);
1540
1541        unsafe { gl.sampler_parameter_i32(raw, glow::TEXTURE_MIN_FILTER, min as i32) };
1542        unsafe { gl.sampler_parameter_i32(raw, glow::TEXTURE_MAG_FILTER, mag as i32) };
1543
1544        unsafe {
1545            gl.sampler_parameter_i32(
1546                raw,
1547                glow::TEXTURE_WRAP_S,
1548                conv::map_address_mode(desc.address_modes[0]) as i32,
1549            )
1550        };
1551        unsafe {
1552            gl.sampler_parameter_i32(
1553                raw,
1554                glow::TEXTURE_WRAP_T,
1555                conv::map_address_mode(desc.address_modes[1]) as i32,
1556            )
1557        };
1558        unsafe {
1559            gl.sampler_parameter_i32(
1560                raw,
1561                glow::TEXTURE_WRAP_R,
1562                conv::map_address_mode(desc.address_modes[2]) as i32,
1563            )
1564        };
1565
1566        if let Some(border_color) = desc.border_color {
1567            let border = match border_color {
1568                wgt::SamplerBorderColor::TransparentBlack | wgt::SamplerBorderColor::Zero => {
1569                    [0.0; 4]
1570                }
1571                wgt::SamplerBorderColor::OpaqueBlack => [0.0, 0.0, 0.0, 1.0],
1572                wgt::SamplerBorderColor::OpaqueWhite => [1.0; 4],
1573            };
1574            unsafe { gl.sampler_parameter_f32_slice(raw, glow::TEXTURE_BORDER_COLOR, &border) };
1575        }
1576
1577        unsafe { gl.sampler_parameter_f32(raw, glow::TEXTURE_MIN_LOD, desc.lod_clamp.start) };
1578        unsafe { gl.sampler_parameter_f32(raw, glow::TEXTURE_MAX_LOD, desc.lod_clamp.end) };
1579
1580        // If clamp is not 1, we know anisotropy is supported up to 16x
1581        if desc.anisotropy_clamp != 1 {
1582            unsafe {
1583                gl.sampler_parameter_f32(
1584                    raw,
1585                    glow::TEXTURE_MAX_ANISOTROPY,
1586                    f32::from(desc.anisotropy_clamp),
1587                )
1588            };
1589        }
1590
1591        //set_param_float(glow::TEXTURE_LOD_BIAS, info.lod_bias.0);
1592
1593        if let Some(compare) = desc.compare {
1594            unsafe {
1595                gl.sampler_parameter_i32(
1596                    raw,
1597                    glow::TEXTURE_COMPARE_MODE,
1598                    glow::COMPARE_REF_TO_TEXTURE as i32,
1599                )
1600            };
1601            unsafe {
1602                gl.sampler_parameter_i32(
1603                    raw,
1604                    glow::TEXTURE_COMPARE_FUNC,
1605                    conv::map_compare_func(compare) as i32,
1606                )
1607            };
1608        }
1609
1610        #[cfg(native)]
1611        if let Some(label) = desc.label {
1612            if self
1613                .shared
1614                .private_caps
1615                .contains(PrivateCapabilities::DEBUG_FNS)
1616            {
1617                let name = raw.0.get();
1618                unsafe { gl.object_label(glow::SAMPLER, name, Some(label)) };
1619            }
1620        }
1621
1622        self.counters.samplers.add(1);
1623
1624        Ok(super::Sampler { raw })
1625    }
1626
1627    unsafe fn destroy_sampler(&self, sampler: super::Sampler) {
1628        let gl = &self.shared.context.lock();
1629        unsafe { gl.delete_sampler(sampler.raw) };
1630        self.counters.samplers.sub(1);
1631    }
1632
1633    unsafe fn create_command_encoder(
1634        &self,
1635        _desc: &crate::CommandEncoderDescriptor<super::Queue>,
1636    ) -> Result<super::CommandEncoder, crate::DeviceError> {
1637        self.counters.command_encoders.add(1);
1638
1639        Ok(super::CommandEncoder {
1640            cmd_buffer: super::CommandBuffer::default(),
1641            state: Default::default(),
1642            private_caps: self.shared.private_caps,
1643            counters: Arc::clone(&self.counters),
1644        })
1645    }
1646
1647    unsafe fn create_bind_group_layout(
1648        &self,
1649        desc: &crate::BindGroupLayoutDescriptor,
1650    ) -> Result<super::BindGroupLayout, crate::DeviceError> {
1651        self.counters.bind_group_layouts.add(1);
1652        Ok(super::BindGroupLayout {
1653            entries: Arc::from(desc.entries),
1654        })
1655    }
1656
1657    unsafe fn destroy_bind_group_layout(&self, _bg_layout: super::BindGroupLayout) {
1658        self.counters.bind_group_layouts.sub(1);
1659    }
1660
1661    unsafe fn create_pipeline_layout(
1662        &self,
1663        desc: &crate::PipelineLayoutDescriptor<super::BindGroupLayout>,
1664    ) -> Result<super::PipelineLayout, crate::DeviceError> {
1665        use naga::back::glsl;
1666
1667        let mut group_infos = Vec::with_capacity(desc.bind_group_layouts.len());
1668        let mut num_samplers = 0u8;
1669        let mut num_textures = 0u8;
1670        let mut num_images = 0u8;
1671        let mut num_uniform_buffers = 0u8;
1672        let mut num_storage_buffers = 0u8;
1673
1674        let mut writer_flags = glsl::WriterFlags::ADJUST_COORDINATE_SPACE;
1675        writer_flags.set(
1676            glsl::WriterFlags::TEXTURE_SHADOW_LOD,
1677            self.shared
1678                .private_caps
1679                .contains(PrivateCapabilities::SHADER_TEXTURE_SHADOW_LOD),
1680        );
1681        writer_flags.set(
1682            glsl::WriterFlags::DRAW_PARAMETERS,
1683            self.shared
1684                .private_caps
1685                .contains(PrivateCapabilities::FULLY_FEATURED_INSTANCING),
1686        );
1687        // We always force point size to be written and it will be ignored by the driver if it's not a point list primitive.
1688        // https://github.com/gfx-rs/wgpu/pull/3440/files#r1095726950
1689        writer_flags.set(glsl::WriterFlags::FORCE_POINT_SIZE, true);
1690        let mut binding_map = glsl::BindingMap::default();
1691
1692        for (group_index, bg_layout) in desc.bind_group_layouts.iter().enumerate() {
1693            let Some(bg_layout) = bg_layout else {
1694                group_infos.push(None);
1695                continue;
1696            };
1697
1698            // create a vector with the size enough to hold all the bindings, filled with `!0`
1699            let mut binding_to_slot = vec![
1700                !0;
1701                bg_layout
1702                    .entries
1703                    .iter()
1704                    .map(|b| b.binding)
1705                    .max()
1706                    .map_or(0, |idx| idx as usize + 1)
1707            ]
1708            .into_boxed_slice();
1709
1710            for entry in bg_layout.entries.iter() {
1711                let counter = match entry.ty {
1712                    wgt::BindingType::Sampler { .. } => &mut num_samplers,
1713                    wgt::BindingType::Texture { .. } => &mut num_textures,
1714                    wgt::BindingType::StorageTexture { .. } => &mut num_images,
1715                    wgt::BindingType::Buffer {
1716                        ty: wgt::BufferBindingType::Uniform,
1717                        ..
1718                    } => &mut num_uniform_buffers,
1719                    wgt::BindingType::Buffer {
1720                        ty: wgt::BufferBindingType::Storage { .. },
1721                        ..
1722                    } => &mut num_storage_buffers,
1723                    wgt::BindingType::AccelerationStructure { .. } => unimplemented!(),
1724                    wgt::BindingType::ExternalTexture => unimplemented!(),
1725                };
1726
1727                binding_to_slot[entry.binding as usize] = *counter;
1728                let br = naga::ResourceBinding {
1729                    group: group_index as u32,
1730                    binding: entry.binding,
1731                };
1732                binding_map.insert(br, *counter);
1733                *counter += entry.count.map_or(1, |c| c.get() as u8);
1734            }
1735
1736            group_infos.push(Some(super::BindGroupLayoutInfo {
1737                entries: Arc::clone(&bg_layout.entries),
1738                binding_to_slot,
1739            }));
1740        }
1741
1742        self.counters.pipeline_layouts.add(1);
1743
1744        Ok(super::PipelineLayout {
1745            group_infos: group_infos.into_boxed_slice(),
1746            naga_options: glsl::Options {
1747                version: self.shared.shading_language_version,
1748                writer_flags,
1749                binding_map,
1750                zero_initialize_workgroup_memory: true,
1751            },
1752        })
1753    }
1754
1755    unsafe fn destroy_pipeline_layout(&self, _pipeline_layout: super::PipelineLayout) {
1756        self.counters.pipeline_layouts.sub(1);
1757    }
1758
1759    unsafe fn create_bind_group(
1760        &self,
1761        desc: &crate::BindGroupDescriptor<
1762            super::BindGroupLayout,
1763            super::Buffer,
1764            super::Sampler,
1765            super::TextureView,
1766            super::AccelerationStructure,
1767        >,
1768    ) -> Result<super::BindGroup, crate::DeviceError> {
1769        let mut contents = Vec::new();
1770
1771        let layout_and_entry_iter = desc.entries.iter().map(|entry| {
1772            let layout = desc
1773                .layout
1774                .entries
1775                .iter()
1776                .find(|layout_entry| layout_entry.binding == entry.binding)
1777                .expect("internal error: no layout entry found with binding slot");
1778            (entry, layout)
1779        });
1780        for (entry, layout) in layout_and_entry_iter {
1781            let binding = match layout.ty {
1782                wgt::BindingType::Buffer { .. } => {
1783                    let bb = &desc.buffers[entry.resource_index as usize];
1784                    super::RawBinding::Buffer {
1785                        raw: bb.buffer.raw.unwrap(),
1786                        offset: bb.offset as i32,
1787                        size: bb.size.get() as i32,
1788                    }
1789                }
1790                wgt::BindingType::Sampler { .. } => {
1791                    let sampler = desc.samplers[entry.resource_index as usize];
1792                    super::RawBinding::Sampler(sampler.raw)
1793                }
1794                wgt::BindingType::Texture { view_dimension, .. } => {
1795                    let view = desc.textures[entry.resource_index as usize].view;
1796                    if view.array_layers.start != 0 {
1797                        log::error!("Unable to create a sampled texture binding for non-zero array layer.\n{}",
1798                            "This is an implementation problem of wgpu-hal/gles backend.")
1799                    }
1800                    let (raw, target) = view.inner.as_native();
1801
1802                    // GLES adapters should always have a valid binding view dimension specified,
1803                    // validated at the core layer.
1804                    debug_assert_eq!(
1805                        target,
1806                        super::Texture::target_for_view_dimension(view_dimension)
1807                    );
1808
1809                    super::RawBinding::Texture {
1810                        raw,
1811                        target,
1812                        aspects: view.aspects,
1813                        mip_levels: view.mip_levels.clone(),
1814                    }
1815                }
1816                wgt::BindingType::StorageTexture {
1817                    access,
1818                    format,
1819                    view_dimension,
1820                } => {
1821                    let view = desc.textures[entry.resource_index as usize].view;
1822                    let format_desc = self.shared.describe_texture_format(format);
1823                    let (raw, _target) = view.inner.as_native();
1824                    super::RawBinding::Image(super::ImageBinding {
1825                        raw,
1826                        mip_level: view.mip_levels.start,
1827                        array_layer: match view_dimension {
1828                            wgt::TextureViewDimension::D2Array
1829                            | wgt::TextureViewDimension::CubeArray => None,
1830                            _ => Some(view.array_layers.start),
1831                        },
1832                        access: conv::map_storage_access(access),
1833                        format: format_desc.internal,
1834                    })
1835                }
1836                wgt::BindingType::AccelerationStructure { .. } => unimplemented!(),
1837                wgt::BindingType::ExternalTexture => unimplemented!(),
1838            };
1839            contents.push(binding);
1840        }
1841
1842        self.counters.bind_groups.add(1);
1843
1844        Ok(super::BindGroup {
1845            contents: contents.into_boxed_slice(),
1846        })
1847    }
1848
1849    unsafe fn destroy_bind_group(&self, _group: super::BindGroup) {
1850        self.counters.bind_groups.sub(1);
1851    }
1852
1853    unsafe fn create_shader_module(
1854        &self,
1855        desc: &crate::ShaderModuleDescriptor,
1856        shader: crate::ShaderInput,
1857    ) -> Result<super::ShaderModule, crate::ShaderError> {
1858        self.counters.shader_modules.add(1);
1859
1860        Ok(super::ShaderModule {
1861            source: match shader {
1862                crate::ShaderInput::Naga(naga) => super::ShaderModuleSource::Naga(naga),
1863                // The backend doesn't yet expose this feature so it should be fine
1864                crate::ShaderInput::Glsl { shader, .. } => super::ShaderModuleSource::Passthrough {
1865                    source: shader.to_owned(),
1866                },
1867                crate::ShaderInput::SpirV(_)
1868                | crate::ShaderInput::MetalLib { .. }
1869                | crate::ShaderInput::Msl { .. }
1870                | crate::ShaderInput::Dxil { .. }
1871                | crate::ShaderInput::Hlsl { .. } => {
1872                    unreachable!()
1873                }
1874            },
1875            label: desc.label.map(|str| str.to_string()),
1876            id: self.shared.next_shader_id.fetch_add(1, Ordering::Relaxed),
1877        })
1878    }
1879
1880    unsafe fn destroy_shader_module(&self, _module: super::ShaderModule) {
1881        self.counters.shader_modules.sub(1);
1882    }
1883
1884    unsafe fn create_render_pipeline(
1885        &self,
1886        desc: &crate::RenderPipelineDescriptor<
1887            super::PipelineLayout,
1888            super::ShaderModule,
1889            super::PipelineCache,
1890        >,
1891    ) -> Result<super::RenderPipeline, crate::PipelineError> {
1892        let (vertex_stage, vertex_buffers) = match &desc.vertex_processor {
1893            crate::VertexProcessor::Standard {
1894                vertex_buffers,
1895                ref vertex_stage,
1896            } => (vertex_stage, vertex_buffers),
1897            crate::VertexProcessor::Mesh { .. } => unreachable!(),
1898        };
1899        let gl = &self.shared.context.lock();
1900        let mut shaders = ArrayVec::new();
1901        shaders.push((naga::ShaderStage::Vertex, vertex_stage));
1902        if let Some(ref fs) = desc.fragment_stage {
1903            shaders.push((naga::ShaderStage::Fragment, fs));
1904        }
1905        let inner = unsafe {
1906            self.create_pipeline(gl, shaders, desc.layout, desc.label, desc.multiview_mask)
1907        }?;
1908
1909        let (vertex_buffers, vertex_attributes) = {
1910            let mut buffers = Vec::new();
1911            let mut attributes = Vec::new();
1912            for (index, vb_layout) in vertex_buffers.iter().enumerate() {
1913                let vb_desc = if let Some(vb_layout) = vb_layout {
1914                    for vat in vb_layout.attributes.iter() {
1915                        let format_desc = conv::describe_vertex_format(vat.format);
1916                        attributes.push(super::AttributeDesc {
1917                            location: vat.shader_location,
1918                            offset: vat.offset as u32,
1919                            buffer_index: index as u32,
1920                            format_desc,
1921                        });
1922                    }
1923                    Some(super::VertexBufferDesc {
1924                        step: vb_layout.step_mode,
1925                        stride: vb_layout.array_stride as u32,
1926                    })
1927                } else {
1928                    None
1929                };
1930                buffers.push(vb_desc);
1931            }
1932            (buffers.into_boxed_slice(), attributes.into_boxed_slice())
1933        };
1934
1935        let color_targets = {
1936            let mut targets = Vec::new();
1937            for ct in desc.color_targets.iter().filter_map(|at| at.as_ref()) {
1938                targets.push(super::ColorTargetDesc {
1939                    mask: ct.write_mask,
1940                    blend: ct.blend.as_ref().map(conv::map_blend),
1941                });
1942            }
1943            //Note: if any of the states are different, and `INDEPENDENT_BLEND` flag
1944            // is not exposed, then this pipeline will not bind correctly.
1945            targets.into_boxed_slice()
1946        };
1947
1948        self.counters.render_pipelines.add(1);
1949
1950        Ok(super::RenderPipeline {
1951            inner,
1952            primitive: desc.primitive,
1953            vertex_buffers,
1954            vertex_attributes,
1955            color_targets,
1956            depth: desc.depth_stencil.as_ref().map(|ds| super::DepthState {
1957                function: conv::map_compare_func(ds.depth_compare.unwrap_or_default()),
1958                mask: ds.depth_write_enabled.unwrap_or_default(),
1959            }),
1960            depth_bias: desc
1961                .depth_stencil
1962                .as_ref()
1963                .map(|ds| ds.bias)
1964                .unwrap_or_default(),
1965            stencil: desc
1966                .depth_stencil
1967                .as_ref()
1968                .map(|ds| conv::map_stencil(&ds.stencil)),
1969            alpha_to_coverage_enabled: desc.multisample.alpha_to_coverage_enabled,
1970        })
1971    }
1972
1973    unsafe fn destroy_render_pipeline(&self, pipeline: super::RenderPipeline) {
1974        // If the pipeline only has 2 strong references remaining, they're `pipeline` and `program_cache`
1975        // This is safe to assume as long as:
1976        // - `RenderPipeline` can't be cloned
1977        // - The only place that we can get a new reference is during `program_cache.lock()`
1978        if Arc::strong_count(&pipeline.inner) == 2 {
1979            let gl = &self.shared.context.lock();
1980            let mut program_cache = self.shared.program_cache.lock();
1981            program_cache.retain(|_, v| match *v {
1982                Ok(ref p) => p.program != pipeline.inner.program,
1983                Err(_) => false,
1984            });
1985            unsafe { gl.delete_program(pipeline.inner.program) };
1986        }
1987
1988        self.counters.render_pipelines.sub(1);
1989    }
1990
1991    unsafe fn create_compute_pipeline(
1992        &self,
1993        desc: &crate::ComputePipelineDescriptor<
1994            super::PipelineLayout,
1995            super::ShaderModule,
1996            super::PipelineCache,
1997        >,
1998    ) -> Result<super::ComputePipeline, crate::PipelineError> {
1999        let gl = &self.shared.context.lock();
2000        let mut shaders = ArrayVec::new();
2001        shaders.push((naga::ShaderStage::Compute, &desc.stage));
2002        let inner = unsafe { self.create_pipeline(gl, shaders, desc.layout, desc.label, None) }?;
2003
2004        self.counters.compute_pipelines.add(1);
2005
2006        Ok(super::ComputePipeline { inner })
2007    }
2008
2009    unsafe fn destroy_compute_pipeline(&self, pipeline: super::ComputePipeline) {
2010        // If the pipeline only has 2 strong references remaining, they're `pipeline` and `program_cache``
2011        // This is safe to assume as long as:
2012        // - `ComputePipeline` can't be cloned
2013        // - The only place that we can get a new reference is during `program_cache.lock()`
2014        if Arc::strong_count(&pipeline.inner) == 2 {
2015            let gl = &self.shared.context.lock();
2016            let mut program_cache = self.shared.program_cache.lock();
2017            program_cache.retain(|_, v| match *v {
2018                Ok(ref p) => p.program != pipeline.inner.program,
2019                Err(_) => false,
2020            });
2021            unsafe { gl.delete_program(pipeline.inner.program) };
2022        }
2023
2024        self.counters.compute_pipelines.sub(1);
2025    }
2026
2027    unsafe fn create_ray_tracing_pipeline(
2028        &self,
2029        _desc: &crate::RayTracingPipelineDescriptor<
2030            super::PipelineLayout,
2031            super::ShaderModule,
2032            super::PipelineCache,
2033        >,
2034    ) -> Result<super::RayTracingPipeline, crate::PipelineError> {
2035        unimplemented!("Ray tracing is unsupported on GL")
2036    }
2037
2038    unsafe fn destroy_ray_tracing_pipeline(&self, _pipeline: super::RayTracingPipeline) {
2039        unimplemented!("Ray tracing is unsupported on GL")
2040    }
2041
2042    unsafe fn get_raytracing_pipeline_group_data(
2043        &self,
2044        _pipeline: &super::RayTracingPipeline,
2045        _groups: core::ops::Range<u32>,
2046    ) -> Result<Vec<u8>, crate::DeviceError> {
2047        unimplemented!("Ray tracing is unsupported on GL")
2048    }
2049
2050    unsafe fn create_pipeline_cache(
2051        &self,
2052        _: &crate::PipelineCacheDescriptor<'_>,
2053    ) -> Result<super::PipelineCache, crate::PipelineCacheError> {
2054        // Even though the cache doesn't do anything, we still return something here
2055        // as the least bad option
2056        Ok(super::PipelineCache)
2057    }
2058    unsafe fn destroy_pipeline_cache(&self, _: super::PipelineCache) {}
2059
2060    #[cfg_attr(target_family = "wasm", allow(unused))]
2061    unsafe fn create_query_set(
2062        &self,
2063        desc: &wgt::QuerySetDescriptor<crate::Label>,
2064    ) -> Result<super::QuerySet, crate::DeviceError> {
2065        let gl = &self.shared.context.lock();
2066
2067        let mut queries = Vec::with_capacity(desc.count as usize);
2068        for _ in 0..desc.count {
2069            let query =
2070                unsafe { gl.create_query() }.map_err(|_| crate::DeviceError::OutOfMemory)?;
2071
2072            // We aren't really able to, in general, label queries.
2073            //
2074            // We could take a timestamp here to "initialize" the query,
2075            // but that's a bit of a hack, and we don't want to insert
2076            // random timestamps into the command stream of we don't have to.
2077
2078            queries.push(query);
2079        }
2080
2081        self.counters.query_sets.add(1);
2082
2083        Ok(super::QuerySet {
2084            queries: queries.into_boxed_slice(),
2085            target: match desc.ty {
2086                wgt::QueryType::Occlusion => glow::ANY_SAMPLES_PASSED_CONSERVATIVE,
2087                wgt::QueryType::Timestamp => glow::TIMESTAMP,
2088                _ => unimplemented!(),
2089            },
2090        })
2091    }
2092
2093    unsafe fn destroy_query_set(&self, set: super::QuerySet) {
2094        let gl = &self.shared.context.lock();
2095        for &query in set.queries.iter() {
2096            unsafe { gl.delete_query(query) };
2097        }
2098        self.counters.query_sets.sub(1);
2099    }
2100
2101    unsafe fn create_fence(&self) -> Result<super::Fence, crate::DeviceError> {
2102        self.counters.fences.add(1);
2103        Ok(super::Fence::new(&self.shared.options))
2104    }
2105
2106    unsafe fn destroy_fence(&self, fence: super::Fence) {
2107        let gl = &self.shared.context.lock();
2108        fence.destroy(gl);
2109        self.counters.fences.sub(1);
2110    }
2111
2112    unsafe fn get_fence_value(
2113        &self,
2114        fence: &super::Fence,
2115    ) -> Result<crate::FenceValue, crate::DeviceError> {
2116        #[cfg_attr(target_family = "wasm", allow(clippy::needless_borrow))]
2117        Ok(fence.get_latest(&self.shared.context.lock()))
2118    }
2119    unsafe fn wait(
2120        &self,
2121        fence: &super::Fence,
2122        wait_value: crate::FenceValue,
2123        timeout: Option<core::time::Duration>,
2124    ) -> Result<bool, crate::DeviceError> {
2125        if fence.satisfied(wait_value) {
2126            return Ok(true);
2127        }
2128
2129        let gl = &self.shared.context.lock();
2130        // MAX_CLIENT_WAIT_TIMEOUT_WEBGL is:
2131        // - 1s in Gecko https://searchfox.org/mozilla-central/rev/754074e05178e017ef6c3d8e30428ffa8f1b794d/dom/canvas/WebGLTypes.h#1386
2132        // - 0 in WebKit https://github.com/WebKit/WebKit/blob/4ef90d4672ca50267c0971b85db403d9684508ea/Source/WebCore/html/canvas/WebGL2RenderingContext.cpp#L110
2133        // - 0 in Chromium https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc;l=112;drc=a3cb0ac4c71ec04abfeaed199e5d63230eca2551
2134        let timeout_ns = if cfg!(any(webgl, Emscripten)) {
2135            0
2136        } else {
2137            timeout
2138                .map(|t| t.as_nanos().min(u32::MAX as u128) as u32)
2139                .unwrap_or(u32::MAX)
2140        };
2141        fence.wait(gl, wait_value, timeout_ns)
2142    }
2143
2144    unsafe fn start_graphics_debugger_capture(&self) -> bool {
2145        #[cfg(all(native, feature = "renderdoc"))]
2146        return unsafe {
2147            self.render_doc
2148                .start_frame_capture(self.shared.context.raw_context(), ptr::null_mut())
2149        };
2150        #[allow(unreachable_code)]
2151        false
2152    }
2153    unsafe fn stop_graphics_debugger_capture(&self) {
2154        #[cfg(all(native, feature = "renderdoc"))]
2155        unsafe {
2156            self.render_doc
2157                .end_frame_capture(ptr::null_mut(), ptr::null_mut())
2158        }
2159    }
2160    unsafe fn create_acceleration_structure(
2161        &self,
2162        _desc: &crate::AccelerationStructureDescriptor,
2163    ) -> Result<super::AccelerationStructure, crate::DeviceError> {
2164        unimplemented!()
2165    }
2166    unsafe fn get_acceleration_structure_build_sizes<'a>(
2167        &self,
2168        _desc: &crate::GetAccelerationStructureBuildSizesDescriptor<'a, super::Buffer>,
2169    ) -> crate::AccelerationStructureBuildSizes {
2170        unimplemented!()
2171    }
2172    unsafe fn get_acceleration_structure_device_address(
2173        &self,
2174        _acceleration_structure: &super::AccelerationStructure,
2175    ) -> wgt::BufferAddress {
2176        unimplemented!()
2177    }
2178    unsafe fn destroy_acceleration_structure(
2179        &self,
2180        _acceleration_structure: super::AccelerationStructure,
2181    ) {
2182    }
2183
2184    fn tlas_instance_to_bytes(&self, _instance: TlasInstance, _to_extend: &mut Vec<u8>) {
2185        unimplemented!()
2186    }
2187
2188    fn get_internal_counters(&self) -> wgt::HalCounters {
2189        self.counters.as_ref().clone()
2190    }
2191
2192    fn check_if_oom(&self) -> Result<(), crate::DeviceError> {
2193        Ok(())
2194    }
2195}
2196
2197#[cfg(send_sync)]
2198unsafe impl Sync for super::Device {}
2199#[cfg(send_sync)]
2200unsafe impl Send for super::Device {}