Skip to main content

gpui_wgpu/
wgpu_context.rs

1// Modified for gpui-pre (snapshot of zed@125ca86): adapt device queues and sRGB detection to wgpu 30.0.1.
2#[cfg(not(target_family = "wasm"))]
3use crate::{WgpuRenderer, WgpuSurfaceConfig};
4#[cfg(not(target_family = "wasm"))]
5use anyhow::Context as _;
6#[cfg(not(target_family = "wasm"))]
7use gpui_util::ResultExt;
8use parking_lot::Mutex;
9use std::sync::Arc;
10use std::sync::atomic::{AtomicBool, Ordering};
11use wgpu::TextureFormat;
12
13#[derive(Clone)]
14pub struct WgpuContext {
15    pub instance: wgpu::Instance,
16    pub adapter: wgpu::Adapter,
17    pub device: Arc<wgpu::Device>,
18    pub queue: Arc<wgpu::Queue>,
19    backend: WgpuBackend,
20    dual_source_blending: bool,
21    color_texture_format: wgpu::TextureFormat,
22    errors: Arc<DeviceErrorState>,
23}
24
25/// Errors reported by wgpu's device-wide callbacks.
26///
27/// A device has exactly one lost callback and one uncaptured-error callback, so this
28/// state is installed once per device and shared by every renderer using it. Renderers
29/// keep their own handle so they can keep observing a loss after the context that
30/// produced it has been dropped for recovery.
31#[derive(Default)]
32pub struct DeviceErrorState {
33    lost: AtomicBool,
34    last_error: Mutex<(u64, Option<String>)>,
35}
36
37impl DeviceErrorState {
38    fn install(device: &wgpu::Device) -> Arc<Self> {
39        let errors = Arc::new(Self::default());
40        device.set_device_lost_callback({
41            let errors = Arc::clone(&errors);
42            move |reason, message| {
43                log::error!("wgpu device lost: reason={reason:?}, message={message}");
44                if reason != wgpu::DeviceLostReason::Destroyed {
45                    errors.lost.store(true, Ordering::Relaxed);
46                }
47            }
48        });
49        device.on_uncaptured_error(Arc::new({
50            let errors = Arc::clone(&errors);
51            move |error| errors.record(error.to_string())
52        }));
53        errors
54    }
55
56    /// Returns true if the GPU device was lost (e.g., due to driver crash, suspend/resume).
57    pub fn device_lost(&self) -> bool {
58        self.lost.load(Ordering::Relaxed)
59    }
60
61    fn record(&self, error: String) {
62        let mut last_error = self.last_error.lock();
63        last_error.0 = last_error.0.wrapping_add(1);
64        last_error.1 = Some(error);
65    }
66
67    /// Returns the latest error once per observer, without consuming shared state.
68    /// Start each observer at zero, including after switching devices, so errors
69    /// raised during construction are observed. Multiple errors between observations
70    /// coalesce into the latest error; this is not an error queue.
71    pub fn observe_error(&self, generation: &mut u64) -> Option<String> {
72        let last_error = self.last_error.lock();
73        if *generation == last_error.0 {
74            return None;
75        }
76        *generation = last_error.0;
77        last_error.1.clone()
78    }
79
80    /// The generation an observer should start from to see only errors raised after
81    /// this call, for a renderer joining a device other renderers already used.
82    pub fn current_generation(&self) -> u64 {
83        self.last_error.lock().0
84    }
85}
86
87#[derive(Clone, Copy, Debug, Eq, PartialEq)]
88pub enum WgpuBackend {
89    BrowserWebGpu,
90    Gl,
91    Native(wgpu::Backend),
92}
93
94#[cfg(target_family = "wasm")]
95#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
96pub enum WebBackendPreference {
97    #[default]
98    Auto,
99    WebGpu,
100    WebGl,
101}
102
103#[cfg(target_family = "wasm")]
104pub struct PreparedWebGraphics {
105    pub context: WgpuContext,
106    pub surface: wgpu::Surface<'static>,
107}
108
109/// wgpu-core refuses to create a surface when neither the instance nor the surface
110/// target carries a display handle, and `SurfaceTarget::Canvas` always passes `None`.
111/// The WebGL2 backend never reads the handle (WebGPU bypasses wgpu-core entirely), so
112/// a unit web display handle on the instance satisfies the check.
113#[cfg(target_family = "wasm")]
114#[derive(Debug)]
115struct WebDisplaySource;
116
117#[cfg(target_family = "wasm")]
118impl raw_window_handle::HasDisplayHandle for WebDisplaySource {
119    fn display_handle(
120        &self,
121    ) -> Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> {
122        Ok(raw_window_handle::DisplayHandle::web())
123    }
124}
125
126#[derive(Clone, Copy)]
127pub struct CompositorGpuHint {
128    pub vendor_id: u32,
129    pub device_id: u32,
130}
131
132impl WgpuContext {
133    #[cfg(not(target_family = "wasm"))]
134    pub fn new(
135        instance: wgpu::Instance,
136        surface: &wgpu::Surface<'_>,
137        config: &WgpuSurfaceConfig,
138        compositor_gpu: Option<CompositorGpuHint>,
139    ) -> anyhow::Result<Self> {
140        Self::new_with_options(instance, surface, config, compositor_gpu, false)
141    }
142
143    #[cfg(not(target_family = "wasm"))]
144    pub fn new_rejecting_software(
145        instance: wgpu::Instance,
146        surface: &wgpu::Surface<'_>,
147        config: &WgpuSurfaceConfig,
148        compositor_gpu: Option<CompositorGpuHint>,
149    ) -> anyhow::Result<Self> {
150        Self::new_with_options(instance, surface, config, compositor_gpu, true)
151    }
152
153    #[cfg(not(target_family = "wasm"))]
154    fn new_with_options(
155        instance: wgpu::Instance,
156        surface: &wgpu::Surface<'_>,
157        config: &WgpuSurfaceConfig,
158        compositor_gpu: Option<CompositorGpuHint>,
159        reject_software: bool,
160    ) -> anyhow::Result<Self> {
161        let device_id_filter = Self::device_id_filter();
162
163        // Select an adapter by actually testing surface configuration with the real device.
164        // This is the only reliable way to determine compatibility on hybrid GPU systems.
165        let (adapter, device, queue, dual_source_blending, color_texture_format) =
166            gpui::block_on(Self::select_adapter_and_device(
167                &instance,
168                device_id_filter,
169                surface,
170                config,
171                compositor_gpu.as_ref(),
172                reject_software,
173            ))?;
174
175        Ok(Self::from_native_adapter_and_device(
176            instance,
177            adapter,
178            device,
179            queue,
180            dual_source_blending,
181            color_texture_format,
182        ))
183    }
184
185    #[cfg(all(
186        not(target_family = "wasm"),
187        any(test, feature = "bench-support", feature = "test-support")
188    ))]
189    pub(crate) fn new_headless() -> anyhow::Result<(Self, wgpu::TextureFormat)> {
190        // Creating a device takes tens of milliseconds, and benchmarks create a headless
191        // renderer for every window they open, so the process shares one device until it
192        // is lost. A static rather than a thread-local: the cached device is never dropped,
193        // because wgpu's queue reads its own thread-locals on drop and would panic if
194        // dropped while a thread's thread-locals are being destroyed.
195        static HEADLESS: Mutex<Option<(WgpuContext, wgpu::TextureFormat)>> = Mutex::new(None);
196        let mut headless = HEADLESS.lock();
197        if let Some((context, format)) = headless.as_ref()
198            && !context.device_lost()
199        {
200            return Ok((context.clone(), *format));
201        }
202        let created = Self::create_headless()?;
203        *headless = Some(created.clone());
204        Ok(created)
205    }
206
207    #[cfg(all(
208        not(target_family = "wasm"),
209        any(test, feature = "bench-support", feature = "test-support")
210    ))]
211    fn create_headless() -> anyhow::Result<(Self, wgpu::TextureFormat)> {
212        let instance = Self::instance(None);
213        let device_id_filter = Self::device_id_filter();
214        let (adapter, device, queue, dual_source_blending, color_texture_format, target_format) =
215            gpui::block_on(async {
216                let mut adapters = instance.enumerate_adapters(wgpu::Backends::all()).await;
217                Self::sort_adapters(&mut adapters, device_id_filter, None);
218
219                for adapter in adapters {
220                    let adapter_info = adapter.get_info();
221                    let Some(target_format) = Self::headless_target_format(&adapter) else {
222                        log::warn!(
223                            "Adapter {:?} has no supported headless render target format",
224                            adapter_info.name
225                        );
226                        continue;
227                    };
228
229                    match Self::create_device(&adapter).await {
230                        Ok((device, queue, dual_source_blending, color_texture_format)) => {
231                            #[cfg(feature = "bench-support")]
232                            if adapter_info.device_type == wgpu::DeviceType::Cpu {
233                                log::error!(
234                                    "Headless renderer selected software adapter {:?}; \
235                                     benchmark results measure CPU software rendering, not hardware GPU rendering",
236                                    adapter_info.name
237                                );
238                            }
239                            return Ok((
240                                adapter,
241                                device,
242                                queue,
243                                dual_source_blending,
244                                color_texture_format,
245                                target_format,
246                            ));
247                        }
248                        Err(error) => {
249                            log::warn!(
250                                "Failed to create a headless device for adapter {:?}: {error:#}",
251                                adapter_info.name
252                            );
253                        }
254                    }
255                }
256
257                anyhow::bail!("No usable headless GPU adapter found")
258            })?;
259
260        Ok((
261            Self::from_native_adapter_and_device(
262                instance,
263                adapter,
264                device,
265                queue,
266                dual_source_blending,
267                color_texture_format,
268            ),
269            target_format,
270        ))
271    }
272
273    #[cfg(all(
274        not(target_family = "wasm"),
275        any(test, feature = "bench-support", feature = "test-support")
276    ))]
277    /// Both candidates are 8-bit RGBA-ordered or BGRA-ordered formats: headless readback
278    /// copies rows as 4 bytes per pixel and only swizzles, so no other formats may be added
279    /// here without updating it.
280    fn headless_target_format(adapter: &wgpu::Adapter) -> Option<wgpu::TextureFormat> {
281        let required_usages =
282            wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC;
283        [
284            wgpu::TextureFormat::Rgba8Unorm,
285            wgpu::TextureFormat::Bgra8Unorm,
286        ]
287        .into_iter()
288        .find(|format| {
289            adapter
290                .get_texture_format_features(*format)
291                .allowed_usages
292                .contains(required_usages)
293        })
294    }
295
296    #[cfg(not(target_family = "wasm"))]
297    fn from_native_adapter_and_device(
298        instance: wgpu::Instance,
299        adapter: wgpu::Adapter,
300        device: wgpu::Device,
301        queue: wgpu::Queue,
302        dual_source_blending: bool,
303        color_texture_format: TextureFormat,
304    ) -> Self {
305        let errors = DeviceErrorState::install(&device);
306
307        log::info!(
308            "Selected GPU adapter: {:?} ({:?})",
309            adapter.get_info().name,
310            adapter.get_info().backend
311        );
312        let backend = WgpuBackend::Native(adapter.get_info().backend);
313
314        Self {
315            instance,
316            adapter,
317            device: Arc::new(device),
318            queue: Arc::new(queue),
319            backend,
320            dual_source_blending,
321            color_texture_format,
322            errors,
323        }
324    }
325
326    #[cfg(not(target_family = "wasm"))]
327    fn device_id_filter() -> Option<u32> {
328        match std::env::var("ZED_DEVICE_ID") {
329            Ok(value) => parse_pci_id(&value)
330                .context("Failed to parse device ID from `ZED_DEVICE_ID` environment variable")
331                .log_err(),
332            Err(std::env::VarError::NotPresent) => None,
333            error => {
334                error
335                    .context("Failed to read value of `ZED_DEVICE_ID` environment variable")
336                    .log_err();
337                None
338            }
339        }
340    }
341
342    pub fn supports_transient_attachments(&self) -> bool {
343        #[cfg(target_family = "wasm")]
344        if self.backend == WgpuBackend::BrowserWebGpu {
345            // wgpu passes usage bits straight to the browser without knowing
346            // whether it recognizes this one.
347            return js_sys::Reflect::get(&js_sys::global(), &"GPUTextureUsage".into())
348                .and_then(|usage| js_sys::Reflect::has(&usage, &"TRANSIENT_ATTACHMENT".into()))
349                .unwrap_or(false);
350        }
351        true
352    }
353
354    #[cfg(target_family = "wasm")]
355    pub async fn new_web(
356        canvas: &web_sys::HtmlCanvasElement,
357        preference: WebBackendPreference,
358    ) -> anyhow::Result<PreparedWebGraphics> {
359        Self::new_web_with_backend(canvas, preference).await
360    }
361
362    #[cfg(target_family = "wasm")]
363    #[allow(clippy::arc_with_non_send_sync)]
364    async fn new_web_with_backend(
365        canvas: &web_sys::HtmlCanvasElement,
366        preference: WebBackendPreference,
367    ) -> anyhow::Result<PreparedWebGraphics> {
368        let backends = match preference {
369            WebBackendPreference::Auto => wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::GL,
370            WebBackendPreference::WebGpu => wgpu::Backends::BROWSER_WEBGPU,
371            WebBackendPreference::WebGl => wgpu::Backends::GL,
372        };
373        let descriptor = wgpu::InstanceDescriptor {
374            backends,
375            flags: wgpu::InstanceFlags::default(),
376            backend_options: wgpu::BackendOptions::default(),
377            memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
378            display: Some(Box::new(WebDisplaySource)),
379        };
380        let instance = if preference == WebBackendPreference::Auto {
381            wgpu::util::new_instance_with_webgpu_detection(descriptor).await
382        } else {
383            wgpu::Instance::new(descriptor)
384        };
385        let surface = instance
386            .create_surface(wgpu::SurfaceTarget::Canvas(canvas.clone()))
387            .map_err(|error| {
388                anyhow::anyhow!("Failed to create browser graphics surface: {error}")
389            })?;
390
391        let adapter = instance
392            .request_adapter(&wgpu::RequestAdapterOptions {
393                power_preference: wgpu::PowerPreference::HighPerformance,
394                compatible_surface: Some(&surface),
395                force_fallback_adapter: false,
396                apply_limit_buckets: false,
397            })
398            .await
399            .map_err(|error| {
400                anyhow::anyhow!(
401                    "Failed to request a {preference:?} adapter compatible with the canvas: {error}"
402                )
403            })?;
404        let adapter_info = adapter.get_info();
405        let backend = match adapter_info.backend {
406            wgpu::Backend::BrowserWebGpu => WgpuBackend::BrowserWebGpu,
407            wgpu::Backend::Gl => WgpuBackend::Gl,
408            backend => {
409                anyhow::bail!(
410                    "Browser graphics initialization selected unexpected backend {backend:?}"
411                )
412            }
413        };
414
415        let (device, queue, dual_source_blending, color_texture_format) =
416            Self::create_device(&adapter).await?;
417        let errors = DeviceErrorState::install(&device);
418        log::info!(
419            "Browser graphics initialized: requested={preference:?}, selected={backend:?}, \
420             adapter={:?}, limits={:?}, dual_source_blending={dual_source_blending}",
421            adapter_info.name,
422            device.limits(),
423        );
424
425        let context = Self {
426            instance,
427            adapter,
428            device: Arc::new(device),
429            queue: Arc::new(queue),
430            backend,
431            dual_source_blending,
432            color_texture_format,
433            errors,
434        };
435        Ok(PreparedWebGraphics { context, surface })
436    }
437
438    async fn create_device(
439        adapter: &wgpu::Adapter,
440    ) -> anyhow::Result<(wgpu::Device, wgpu::Queue, bool, TextureFormat)> {
441        let dual_source_blending = adapter
442            .features()
443            .contains(wgpu::Features::DUAL_SOURCE_BLENDING);
444
445        let mut required_features = wgpu::Features::empty();
446        if dual_source_blending {
447            required_features |= wgpu::Features::DUAL_SOURCE_BLENDING;
448        } else {
449            log::warn!(
450                "Dual-source blending not available on this GPU. \
451                Subpixel text antialiasing will be disabled."
452            );
453        }
454
455        let color_atlas_texture_format = Self::select_color_texture_format(adapter)?;
456        #[cfg(target_family = "wasm")]
457        let required_limits = if adapter.get_info().backend == wgpu::Backend::Gl {
458            wgpu::Limits::downlevel_webgl2_defaults()
459                .using_resolution(adapter.limits())
460                .using_alignment(adapter.limits())
461        } else {
462            wgpu::Limits::downlevel_defaults()
463                .using_resolution(adapter.limits())
464                .using_alignment(adapter.limits())
465        };
466        #[cfg(not(target_family = "wasm"))]
467        let required_limits = wgpu::Limits::downlevel_defaults()
468            .using_resolution(adapter.limits())
469            .using_alignment(adapter.limits());
470
471        let (device, queue) = adapter
472            .request_device(&wgpu::DeviceDescriptor {
473                label: Some("gpui_device"),
474                required_features,
475                required_limits,
476                memory_hints: wgpu::MemoryHints::MemoryUsage,
477                trace: wgpu::Trace::Off,
478                experimental_features: wgpu::ExperimentalFeatures::disabled(),
479            })
480            .await
481            .map_err(|e| anyhow::anyhow!("Failed to create wgpu device: {e}"))?;
482
483        Ok((
484            device,
485            queue,
486            dual_source_blending,
487            color_atlas_texture_format,
488        ))
489    }
490
491    #[cfg(not(target_family = "wasm"))]
492    pub fn instance(display: Option<Box<dyn wgpu::wgt::WgpuHasDisplayHandle>>) -> wgpu::Instance {
493        wgpu::Instance::new(wgpu::InstanceDescriptor {
494            backends: wgpu::Backends::VULKAN | wgpu::Backends::GL,
495            flags: wgpu::InstanceFlags::default(),
496            backend_options: wgpu::BackendOptions::default(),
497            memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
498            display,
499        })
500    }
501
502    pub fn check_compatible_with_surface(&self, surface: &wgpu::Surface<'_>) -> anyhow::Result<()> {
503        let caps = surface.get_capabilities(&self.adapter);
504        if caps.formats.is_empty() {
505            let info = self.adapter.get_info();
506            anyhow::bail!(
507                "Adapter {:?} (backend={:?}, device={:#06x}) is not compatible with the \
508                 display surface for this window.",
509                info.name,
510                info.backend,
511                info.device,
512            );
513        }
514        Ok(())
515    }
516
517    /// Select an adapter and create a device, testing that the surface can actually be configured.
518    /// This is the only reliable way to determine compatibility on hybrid GPU systems, where
519    /// adapters may report surface compatibility via get_capabilities() but fail when actually
520    /// configuring (e.g., NVIDIA reporting Vulkan Wayland support but failing because the
521    /// Wayland compositor runs on the Intel GPU).
522    #[cfg(not(target_family = "wasm"))]
523    async fn select_adapter_and_device(
524        instance: &wgpu::Instance,
525        device_id_filter: Option<u32>,
526        surface: &wgpu::Surface<'_>,
527        config: &WgpuSurfaceConfig,
528        compositor_gpu: Option<&CompositorGpuHint>,
529        reject_software: bool,
530    ) -> anyhow::Result<(
531        wgpu::Adapter,
532        wgpu::Device,
533        wgpu::Queue,
534        bool,
535        TextureFormat,
536    )> {
537        let mut adapters: Vec<_> = instance.enumerate_adapters(wgpu::Backends::all()).await;
538
539        if adapters.is_empty() {
540            anyhow::bail!("No GPU adapters found");
541        }
542
543        if let Some(device_id) = device_id_filter {
544            log::info!("ZED_DEVICE_ID filter: {:#06x}", device_id);
545        }
546
547        Self::sort_adapters(&mut adapters, device_id_filter, compositor_gpu);
548
549        // Log all available adapters (in sorted order)
550        log::info!("Found {} GPU adapter(s):", adapters.len());
551        for adapter in &adapters {
552            let info = adapter.get_info();
553            log::info!(
554                "  - {} (vendor={:#06x}, device={:#06x}, backend={:?}, type={:?})",
555                info.name,
556                info.vendor,
557                info.device,
558                info.backend,
559                info.device_type,
560            );
561        }
562
563        // Test each adapter by creating a device and configuring the surface
564        for adapter in adapters {
565            let info = adapter.get_info();
566
567            if reject_software && info.device_type == wgpu::DeviceType::Cpu {
568                log::info!(
569                    "Skipping software renderer: {} ({:?})",
570                    info.name,
571                    info.backend
572                );
573                continue;
574            }
575
576            log::info!("Testing adapter: {} ({:?})...", info.name, info.backend);
577
578            match Self::try_adapter_with_surface(&adapter, surface, config).await {
579                Ok((device, queue, dual_source_blending, color_atlas_texture_format)) => {
580                    log::info!(
581                        "Selected GPU (passed configuration test): {} ({:?})",
582                        info.name,
583                        info.backend
584                    );
585                    return Ok((
586                        adapter,
587                        device,
588                        queue,
589                        dual_source_blending,
590                        color_atlas_texture_format,
591                    ));
592                }
593                Err(e) => {
594                    log::info!(
595                        "  Adapter {} ({:?}) failed: {}, trying next...",
596                        info.name,
597                        info.backend,
598                        e
599                    );
600                }
601            }
602        }
603
604        anyhow::bail!("No GPU adapter found that can configure the display surface")
605    }
606
607    /// Sort adapters into a single priority order. Tiers (from highest to lowest):
608    ///
609    /// 1. ZED_DEVICE_ID match — explicit user override
610    /// 2. Compositor GPU match — the GPU the display server is rendering on
611    /// 3. Device type (Discrete > Integrated > Other > Virtual > Cpu).
612    ///    "Other" ranks above "Virtual" because OpenGL seems to count as "Other".
613    /// 4. Backend — prefer Vulkan/Metal/Dx12 over GL/etc.
614    #[cfg(not(target_family = "wasm"))]
615    fn sort_adapters(
616        adapters: &mut [wgpu::Adapter],
617        device_id_filter: Option<u32>,
618        compositor_gpu: Option<&CompositorGpuHint>,
619    ) {
620        adapters.sort_by_key(|adapter| {
621            let info = adapter.get_info();
622            // Backends like OpenGL report device=0 for all adapters, so
623            // device-based matching is only meaningful when non-zero.
624            let device_known = info.device != 0;
625            let user_override: u8 = match device_id_filter {
626                Some(id) if device_known && info.device == id => 0,
627                _ => 1,
628            };
629            let compositor_match: u8 = match compositor_gpu {
630                Some(hint)
631                    if device_known
632                        && info.vendor == hint.vendor_id
633                        && info.device == hint.device_id =>
634                {
635                    0
636                }
637                _ => 1,
638            };
639            let type_priority: u8 = match info.device_type {
640                wgpu::DeviceType::DiscreteGpu => 0,
641                wgpu::DeviceType::IntegratedGpu => 1,
642                wgpu::DeviceType::Other => 2,
643                wgpu::DeviceType::VirtualGpu => 3,
644                wgpu::DeviceType::Cpu => 4,
645            };
646            let backend_priority: u8 = match info.backend {
647                wgpu::Backend::Vulkan | wgpu::Backend::Metal | wgpu::Backend::Dx12 => 0,
648                _ => 1,
649            };
650
651            (
652                user_override,
653                compositor_match,
654                type_priority,
655                backend_priority,
656            )
657        });
658    }
659
660    /// Try to use an adapter with a surface by creating a device and testing configuration.
661    /// Returns the device and queue if successful, allowing them to be reused.
662    #[cfg(not(target_family = "wasm"))]
663    async fn try_adapter_with_surface(
664        adapter: &wgpu::Adapter,
665        surface: &wgpu::Surface<'_>,
666        config: &WgpuSurfaceConfig,
667    ) -> anyhow::Result<(wgpu::Device, wgpu::Queue, bool, TextureFormat)> {
668        let caps = surface.get_capabilities(adapter);
669        if caps.formats.is_empty() {
670            anyhow::bail!("no compatible surface formats");
671        }
672        if caps.alpha_modes.is_empty() {
673            anyhow::bail!("no compatible alpha modes");
674        }
675
676        let (device, queue, dual_source_blending, color_atlas_texture_format) =
677            Self::create_device(adapter).await?;
678        // Test with the configuration the renderer will use, so that it doesn't need to
679        // configure the surface a second time.
680        let (surface_config, _, _) =
681            WgpuRenderer::surface_configuration(surface, adapter, &device, config)?;
682        let error_scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
683
684        surface.configure(&device, &surface_config);
685
686        let error = error_scope.pop().await;
687        if let Some(e) = error {
688            anyhow::bail!("surface configuration failed: {e}");
689        }
690
691        Ok((
692            device,
693            queue,
694            dual_source_blending,
695            color_atlas_texture_format,
696        ))
697    }
698
699    fn select_color_texture_format(adapter: &wgpu::Adapter) -> anyhow::Result<wgpu::TextureFormat> {
700        let required_usages = wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST;
701        let bgra_features = adapter.get_texture_format_features(wgpu::TextureFormat::Bgra8Unorm);
702        let rgba_features = adapter.get_texture_format_features(wgpu::TextureFormat::Rgba8Unorm);
703        #[cfg(target_family = "wasm")]
704        if adapter.get_info().backend == wgpu::Backend::Gl
705            && rgba_features.allowed_usages.contains(required_usages)
706        {
707            return Ok(wgpu::TextureFormat::Rgba8Unorm);
708        }
709        if bgra_features.allowed_usages.contains(required_usages) {
710            return Ok(wgpu::TextureFormat::Bgra8Unorm);
711        }
712        if rgba_features.allowed_usages.contains(required_usages) {
713            let info = adapter.get_info();
714            log::warn!(
715                "Adapter {} ({:?}) does not support Bgra8Unorm atlas textures with usages {:?}; \
716                 falling back to Rgba8Unorm atlas textures.",
717                info.name,
718                info.backend,
719                required_usages,
720            );
721            return Ok(wgpu::TextureFormat::Rgba8Unorm);
722        }
723
724        let info = adapter.get_info();
725        Err(anyhow::anyhow!(
726            "Adapter {} ({:?}, device={:#06x}) does not support a usable color atlas texture \
727             format with usages {:?}. Bgra8Unorm allowed usages: {:?}; \
728             Rgba8Unorm allowed usages: {:?}.",
729            info.name,
730            info.backend,
731            info.device,
732            required_usages,
733            bgra_features.allowed_usages,
734            rgba_features.allowed_usages,
735        ))
736    }
737    pub fn backend(&self) -> WgpuBackend {
738        self.backend
739    }
740
741    pub fn uses_webgl_instance_data(&self) -> bool {
742        matches!(self.backend, WgpuBackend::Gl) && cfg!(target_family = "wasm")
743    }
744
745    pub fn supports_dual_source_blending(&self) -> bool {
746        self.dual_source_blending
747    }
748
749    pub fn color_texture_format(&self) -> wgpu::TextureFormat {
750        self.color_texture_format
751    }
752
753    /// Returns true if the GPU device was lost (e.g., due to driver crash, suspend/resume).
754    /// When this returns true, the context should be recreated.
755    pub fn device_lost(&self) -> bool {
756        self.errors.device_lost()
757    }
758
759    /// The device-wide error state, shared with renderers on this device.
760    pub fn errors(&self) -> &Arc<DeviceErrorState> {
761        &self.errors
762    }
763}
764
765#[cfg(not(target_family = "wasm"))]
766fn parse_pci_id(id: &str) -> anyhow::Result<u32> {
767    let mut id = id.trim();
768
769    if id.starts_with("0x") || id.starts_with("0X") {
770        id = &id[2..];
771    }
772    let is_hex_string = id.chars().all(|c| c.is_ascii_hexdigit());
773    let is_4_chars = id.len() == 4;
774    anyhow::ensure!(
775        is_4_chars && is_hex_string,
776        "Expected a 4 digit PCI ID in hexadecimal format"
777    );
778
779    u32::from_str_radix(id, 16).context("parsing PCI ID as hex")
780}
781
782#[cfg(test)]
783mod tests {
784    use super::{DeviceErrorState, parse_pci_id};
785
786    #[test]
787    fn device_errors_are_observed_independently() {
788        let errors = DeviceErrorState::default();
789        let mut first = 0;
790        let mut second = 0;
791        assert_eq!(errors.observe_error(&mut first), None);
792        errors.record("first".into());
793        assert_eq!(errors.observe_error(&mut first).as_deref(), Some("first"));
794        assert_eq!(errors.observe_error(&mut first), None);
795        assert_eq!(errors.observe_error(&mut second).as_deref(), Some("first"));
796        assert_eq!(errors.observe_error(&mut second), None);
797
798        errors.record("second".into());
799        assert_eq!(errors.observe_error(&mut second).as_deref(), Some("second"));
800        assert_eq!(errors.observe_error(&mut first).as_deref(), Some("second"));
801        assert_eq!(errors.observe_error(&mut first), None);
802        assert_eq!(errors.observe_error(&mut second), None);
803    }
804
805    #[test]
806    fn device_errors_coalesce_and_new_observers_see_latest() {
807        let errors = DeviceErrorState::default();
808        errors.record("older".into());
809        errors.record("latest".into());
810        let mut generation = 0;
811        assert_eq!(
812            errors.observe_error(&mut generation).as_deref(),
813            Some("latest")
814        );
815        assert_eq!(errors.observe_error(&mut generation), None);
816
817        let replacement = DeviceErrorState::default();
818        replacement.record("replacement".into());
819        generation = 0;
820        assert_eq!(
821            replacement.observe_error(&mut generation).as_deref(),
822            Some("replacement")
823        );
824        assert_eq!(replacement.observe_error(&mut generation), None);
825    }
826
827    #[test]
828    fn test_parse_device_id() {
829        assert!(parse_pci_id("0xABCD").is_ok());
830        assert!(parse_pci_id("ABCD").is_ok());
831        assert!(parse_pci_id("abcd").is_ok());
832        assert!(parse_pci_id("1234").is_ok());
833        assert!(parse_pci_id("123").is_err());
834        assert_eq!(
835            parse_pci_id(&format!("{:x}", 0x1234)).unwrap(),
836            parse_pci_id(&format!("{:X}", 0x1234)).unwrap(),
837        );
838
839        assert_eq!(
840            parse_pci_id(&format!("{:#x}", 0x1234)).unwrap(),
841            parse_pci_id(&format!("{:#X}", 0x1234)).unwrap(),
842        );
843    }
844}