1#[cfg(not(target_family = "wasm"))]
2use anyhow::Context as _;
3#[cfg(not(target_family = "wasm"))]
4use gpui_util::ResultExt;
5use std::sync::Arc;
6use std::sync::atomic::{AtomicBool, Ordering};
7
8pub struct WgpuContext {
9 pub instance: wgpu::Instance,
10 pub adapter: wgpu::Adapter,
11 pub device: Arc<wgpu::Device>,
12 pub queue: Arc<wgpu::Queue>,
13 dual_source_blending: bool,
14 device_lost: Arc<AtomicBool>,
15}
16
17#[derive(Clone, Copy)]
18pub struct CompositorGpuHint {
19 pub vendor_id: u32,
20 pub device_id: u32,
21}
22
23impl WgpuContext {
24 #[cfg(not(target_family = "wasm"))]
25 pub fn new(
26 instance: wgpu::Instance,
27 surface: &wgpu::Surface<'_>,
28 compositor_gpu: Option<CompositorGpuHint>,
29 ) -> anyhow::Result<Self> {
30 let device_id_filter = match std::env::var("ZED_DEVICE_ID") {
31 Ok(val) => parse_pci_id(&val)
32 .context("Failed to parse device ID from `ZED_DEVICE_ID` environment variable")
33 .log_err(),
34 Err(std::env::VarError::NotPresent) => None,
35 err => {
36 err.context("Failed to read value of `ZED_DEVICE_ID` environment variable")
37 .log_err();
38 None
39 }
40 };
41
42 // Select an adapter by actually testing surface configuration with the real device.
43 // This is the only reliable way to determine compatibility on hybrid GPU systems.
44 let (adapter, device, queue, dual_source_blending) =
45 pollster::block_on(Self::select_adapter_and_device(
46 &instance,
47 device_id_filter,
48 surface,
49 compositor_gpu.as_ref(),
50 ))?;
51
52 let device_lost = Arc::new(AtomicBool::new(false));
53 device.set_device_lost_callback({
54 let device_lost = Arc::clone(&device_lost);
55 move |reason, message| {
56 log::error!("wgpu device lost: reason={reason:?}, message={message}");
57 if reason != wgpu::DeviceLostReason::Destroyed {
58 device_lost.store(true, Ordering::Relaxed);
59 }
60 }
61 });
62
63 log::info!(
64 "Selected GPU adapter: {:?} ({:?})",
65 adapter.get_info().name,
66 adapter.get_info().backend
67 );
68
69 Ok(Self {
70 instance,
71 adapter,
72 device: Arc::new(device),
73 queue: Arc::new(queue),
74 dual_source_blending,
75 device_lost,
76 })
77 }
78
79 #[cfg(target_family = "wasm")]
80 pub async fn new_web() -> anyhow::Result<Self> {
81 let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
82 backends: wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::GL,
83 flags: wgpu::InstanceFlags::default(),
84 backend_options: wgpu::BackendOptions::default(),
85 memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
86 display: None,
87 });
88
89 let adapter = instance
90 .request_adapter(&wgpu::RequestAdapterOptions {
91 power_preference: wgpu::PowerPreference::HighPerformance,
92 compatible_surface: None,
93 force_fallback_adapter: false,
94 })
95 .await
96 .map_err(|e| anyhow::anyhow!("Failed to request GPU adapter: {e}"))?;
97
98 log::info!(
99 "Selected GPU adapter: {:?} ({:?})",
100 adapter.get_info().name,
101 adapter.get_info().backend
102 );
103
104 let device_lost = Arc::new(AtomicBool::new(false));
105 let (device, queue, dual_source_blending) = Self::create_device(&adapter).await?;
106
107 Ok(Self {
108 instance,
109 adapter,
110 device: Arc::new(device),
111 queue: Arc::new(queue),
112 dual_source_blending,
113 device_lost,
114 })
115 }
116
117 async fn create_device(
118 adapter: &wgpu::Adapter,
119 ) -> anyhow::Result<(wgpu::Device, wgpu::Queue, bool)> {
120 let dual_source_blending = adapter
121 .features()
122 .contains(wgpu::Features::DUAL_SOURCE_BLENDING);
123
124 let mut required_features = wgpu::Features::empty();
125 if dual_source_blending {
126 required_features |= wgpu::Features::DUAL_SOURCE_BLENDING;
127 } else {
128 log::warn!(
129 "Dual-source blending not available on this GPU. \
130 Subpixel text antialiasing will be disabled."
131 );
132 }
133
134 let (device, queue) = adapter
135 .request_device(&wgpu::DeviceDescriptor {
136 label: Some("gpui_device"),
137 required_features,
138 required_limits: wgpu::Limits::downlevel_defaults()
139 .using_resolution(adapter.limits())
140 .using_alignment(adapter.limits()),
141 memory_hints: wgpu::MemoryHints::MemoryUsage,
142 trace: wgpu::Trace::Off,
143 experimental_features: wgpu::ExperimentalFeatures::disabled(),
144 })
145 .await
146 .map_err(|e| anyhow::anyhow!("Failed to create wgpu device: {e}"))?;
147
148 Ok((device, queue, dual_source_blending))
149 }
150
151 #[cfg(not(target_family = "wasm"))]
152 pub fn instance(display: Box<dyn wgpu::wgt::WgpuHasDisplayHandle>) -> wgpu::Instance {
153 wgpu::Instance::new(wgpu::InstanceDescriptor {
154 backends: wgpu::Backends::VULKAN | wgpu::Backends::GL,
155 flags: wgpu::InstanceFlags::default(),
156 backend_options: wgpu::BackendOptions::default(),
157 memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
158 display: Some(display),
159 })
160 }
161
162 pub fn check_compatible_with_surface(&self, surface: &wgpu::Surface<'_>) -> anyhow::Result<()> {
163 let caps = surface.get_capabilities(&self.adapter);
164 if caps.formats.is_empty() {
165 let info = self.adapter.get_info();
166 anyhow::bail!(
167 "Adapter {:?} (backend={:?}, device={:#06x}) is not compatible with the \
168 display surface for this window.",
169 info.name,
170 info.backend,
171 info.device,
172 );
173 }
174 Ok(())
175 }
176
177 /// Select an adapter and create a device, testing that the surface can actually be configured.
178 /// This is the only reliable way to determine compatibility on hybrid GPU systems, where
179 /// adapters may report surface compatibility via get_capabilities() but fail when actually
180 /// configuring (e.g., NVIDIA reporting Vulkan Wayland support but failing because the
181 /// Wayland compositor runs on the Intel GPU).
182 #[cfg(not(target_family = "wasm"))]
183 async fn select_adapter_and_device(
184 instance: &wgpu::Instance,
185 device_id_filter: Option<u32>,
186 surface: &wgpu::Surface<'_>,
187 compositor_gpu: Option<&CompositorGpuHint>,
188 ) -> anyhow::Result<(wgpu::Adapter, wgpu::Device, wgpu::Queue, bool)> {
189 let mut adapters: Vec<_> = instance.enumerate_adapters(wgpu::Backends::all()).await;
190
191 if adapters.is_empty() {
192 anyhow::bail!("No GPU adapters found");
193 }
194
195 if let Some(device_id) = device_id_filter {
196 log::info!("ZED_DEVICE_ID filter: {:#06x}", device_id);
197 }
198
199 // Sort adapters into a single priority order. Tiers (from highest to lowest):
200 //
201 // 1. ZED_DEVICE_ID match — explicit user override
202 // 2. Compositor GPU match — the GPU the display server is rendering on
203 // 3. Device type (Discrete > Integrated > Other > Virtual > Cpu).
204 // "Other" ranks above "Virtual" because OpenGL seems to count as "Other".
205 // 4. Backend — prefer Vulkan/Metal/Dx12 over GL/etc.
206 adapters.sort_by_key(|adapter| {
207 let info = adapter.get_info();
208
209 // Backends like OpenGL report device=0 for all adapters, so
210 // device-based matching is only meaningful when non-zero.
211 let device_known = info.device != 0;
212
213 let user_override: u8 = match device_id_filter {
214 Some(id) if device_known && info.device == id => 0,
215 _ => 1,
216 };
217
218 let compositor_match: u8 = match compositor_gpu {
219 Some(hint)
220 if device_known
221 && info.vendor == hint.vendor_id
222 && info.device == hint.device_id =>
223 {
224 0
225 }
226 _ => 1,
227 };
228
229 let type_priority: u8 = match info.device_type {
230 wgpu::DeviceType::DiscreteGpu => 0,
231 wgpu::DeviceType::IntegratedGpu => 1,
232 wgpu::DeviceType::Other => 2,
233 wgpu::DeviceType::VirtualGpu => 3,
234 wgpu::DeviceType::Cpu => 4,
235 };
236
237 let backend_priority: u8 = match info.backend {
238 wgpu::Backend::Vulkan => 0,
239 wgpu::Backend::Metal => 0,
240 wgpu::Backend::Dx12 => 0,
241 _ => 1,
242 };
243
244 (
245 user_override,
246 compositor_match,
247 type_priority,
248 backend_priority,
249 )
250 });
251
252 // Log all available adapters (in sorted order)
253 log::info!("Found {} GPU adapter(s):", adapters.len());
254 for adapter in &adapters {
255 let info = adapter.get_info();
256 log::info!(
257 " - {} (vendor={:#06x}, device={:#06x}, backend={:?}, type={:?})",
258 info.name,
259 info.vendor,
260 info.device,
261 info.backend,
262 info.device_type,
263 );
264 }
265
266 // Test each adapter by creating a device and configuring the surface
267 for adapter in adapters {
268 let info = adapter.get_info();
269 log::info!("Testing adapter: {} ({:?})...", info.name, info.backend);
270
271 match Self::try_adapter_with_surface(&adapter, surface).await {
272 Ok((device, queue, dual_source_blending)) => {
273 log::info!(
274 "Selected GPU (passed configuration test): {} ({:?})",
275 info.name,
276 info.backend
277 );
278 return Ok((adapter, device, queue, dual_source_blending));
279 }
280 Err(e) => {
281 log::info!(
282 " Adapter {} ({:?}) failed: {}, trying next...",
283 info.name,
284 info.backend,
285 e
286 );
287 }
288 }
289 }
290
291 anyhow::bail!("No GPU adapter found that can configure the display surface")
292 }
293
294 /// Try to use an adapter with a surface by creating a device and testing configuration.
295 /// Returns the device and queue if successful, allowing them to be reused.
296 #[cfg(not(target_family = "wasm"))]
297 async fn try_adapter_with_surface(
298 adapter: &wgpu::Adapter,
299 surface: &wgpu::Surface<'_>,
300 ) -> anyhow::Result<(wgpu::Device, wgpu::Queue, bool)> {
301 let caps = surface.get_capabilities(adapter);
302 if caps.formats.is_empty() {
303 anyhow::bail!("no compatible surface formats");
304 }
305 if caps.alpha_modes.is_empty() {
306 anyhow::bail!("no compatible alpha modes");
307 }
308
309 let (device, queue, dual_source_blending) = Self::create_device(adapter).await?;
310 let error_scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
311
312 let test_config = wgpu::SurfaceConfiguration {
313 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
314 format: caps.formats[0],
315 width: 64,
316 height: 64,
317 present_mode: wgpu::PresentMode::Fifo,
318 desired_maximum_frame_latency: 2,
319 alpha_mode: caps.alpha_modes[0],
320 view_formats: vec![],
321 };
322
323 surface.configure(&device, &test_config);
324
325 let error = error_scope.pop().await;
326 if let Some(e) = error {
327 anyhow::bail!("surface configuration failed: {e}");
328 }
329
330 Ok((device, queue, dual_source_blending))
331 }
332
333 pub fn supports_dual_source_blending(&self) -> bool {
334 self.dual_source_blending
335 }
336
337 /// Returns true if the GPU device was lost (e.g., due to driver crash, suspend/resume).
338 /// When this returns true, the context should be recreated.
339 pub fn device_lost(&self) -> bool {
340 self.device_lost.load(Ordering::Relaxed)
341 }
342
343 /// Returns a clone of the device_lost flag for sharing with renderers.
344 pub(crate) fn device_lost_flag(&self) -> Arc<AtomicBool> {
345 Arc::clone(&self.device_lost)
346 }
347}
348
349#[cfg(not(target_family = "wasm"))]
350fn parse_pci_id(id: &str) -> anyhow::Result<u32> {
351 let mut id = id.trim();
352
353 if id.starts_with("0x") || id.starts_with("0X") {
354 id = &id[2..];
355 }
356 let is_hex_string = id.chars().all(|c| c.is_ascii_hexdigit());
357 let is_4_chars = id.len() == 4;
358 anyhow::ensure!(
359 is_4_chars && is_hex_string,
360 "Expected a 4 digit PCI ID in hexadecimal format"
361 );
362
363 u32::from_str_radix(id, 16).context("parsing PCI ID as hex")
364}
365
366#[cfg(test)]
367mod tests {
368 use super::parse_pci_id;
369
370 #[test]
371 fn test_parse_device_id() {
372 assert!(parse_pci_id("0xABCD").is_ok());
373 assert!(parse_pci_id("ABCD").is_ok());
374 assert!(parse_pci_id("abcd").is_ok());
375 assert!(parse_pci_id("1234").is_ok());
376 assert!(parse_pci_id("123").is_err());
377 assert_eq!(
378 parse_pci_id(&format!("{:x}", 0x1234)).unwrap(),
379 parse_pci_id(&format!("{:X}", 0x1234)).unwrap(),
380 );
381
382 assert_eq!(
383 parse_pci_id(&format!("{:#x}", 0x1234)).unwrap(),
384 parse_pci_id(&format!("{:#X}", 0x1234)).unwrap(),
385 );
386 }
387}