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