Skip to main content

teksilo_render/
test_support.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4use std::sync::{OnceLock, mpsc};
5
6use crate::Renderer;
7
8/// Why an offscreen readback could not produce pixels.
9///
10/// Every variant means the same thing to a caller — no image this time — but
11/// they are kept apart because they point at different causes: a lost device
12/// is a driver / compositor event, a failed map is usually memory pressure.
13#[derive(Debug, thiserror::Error)]
14pub enum ReadbackError {
15    /// `map_async`'s callback was dropped without firing — the device was lost
16    /// before the mapping completed.
17    #[error("readback failed: the GPU device was lost while mapping")]
18    DeviceLost,
19    /// The buffer mapping itself failed.
20    #[error("readback failed: buffer mapping was refused ({0})")]
21    MapFailed(String),
22    /// `poll` reported a failure before the mapping could be observed.
23    #[error("readback failed: polling the device failed ({0})")]
24    PollFailed(String),
25}
26
27/// The process-wide GPU device every offscreen renderer shares.
28///
29/// One device per process, not one per caller. Two D3D12 **WARP** devices
30/// rasterizing at the same time fault inside `d3d10warp.dll` — Microsoft's
31/// software rasterizer, which is exactly what a GPU-less Windows host and the
32/// CI runners use — so a device per caller turned any two concurrent offscreen
33/// renders into a crash the faulting-module log pins on WARP itself, not on
34/// wgpu or on us. It is not something we can fix downstream; the only remedy is
35/// to stop creating the second device.
36///
37/// Sharing is also simply right: a GPU device is a process-level resource, and
38/// nothing here ever wanted a private one. Callers still get their **own**
39/// [`Renderer`] — that is where the glyph and path atlases live, so no caller
40/// can see another's cached glyphs.
41///
42/// `None` means this host can open no usable device at all; it is cached too,
43/// so a GPU-less machine pays the failed search once rather than per call.
44static SHARED_DEVICE: OnceLock<Option<(wgpu::Device, wgpu::Queue)>> = OnceLock::new();
45
46/// Open the one device, searching for an adapter that actually yields one.
47///
48/// Adapter selection is a *search*, not a single request. A host can enumerate
49/// an adapter it cannot actually open — a VM's OpenGL driver is the common
50/// case — while a perfectly good software device sits behind
51/// `force_fallback_adapter`. Treating the first `request_device` failure as
52/// fatal reports "no GPU" on a machine that has one, which is what made
53/// screenshots unavailable on GPU-less Windows hosts and CI runners (where
54/// DX12 WARP is present and works). So: try the preferred adapter, then an
55/// explicit software fallback, and only give up when neither yields a device.
56async fn open_shared_device(label: &'static str) -> Option<(wgpu::Device, wgpu::Queue)> {
57    #[cfg(test)]
58    DEVICE_OPENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
59    let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
60
61    for force_fallback_adapter in [false, true] {
62        let Ok(adapter) = instance
63            .request_adapter(&wgpu::RequestAdapterOptions {
64                power_preference: wgpu::PowerPreference::LowPower,
65                compatible_surface: None,
66                force_fallback_adapter,
67                ..Default::default()
68            })
69            .await
70        else {
71            continue;
72        };
73
74        // `downlevel_defaults` caps `max_texture_dimension_2d` at 2048, but the
75        // path atlas grows to 4096 — so a path-heavy frame would fail offscreen
76        // while rendering fine in a live window (which uses `Limits::default`).
77        // `using_resolution` lifts exactly the resolution limits to whatever
78        // this adapter really supports, keeping every other downlevel bound.
79        let limits = wgpu::Limits::downlevel_defaults().using_resolution(adapter.limits());
80
81        if let Ok((device, queue)) = adapter
82            .request_device(&wgpu::DeviceDescriptor {
83                label: Some(label),
84                required_features: wgpu::Features::empty(),
85                required_limits: limits,
86                ..Default::default()
87            })
88            .await
89        {
90            return Some((device, queue));
91        }
92    }
93    None
94}
95
96/// Build an offscreen renderer on the shared device, or `None` if this host can
97/// open no usable GPU device at all.
98///
99/// The [`Renderer`] is fresh per call; the device and queue behind it are
100/// shared process-wide, which is load-bearing rather than an optimisation: two
101/// D3D12 **WARP** devices rasterizing at once fault inside Microsoft's software
102/// rasterizer — exactly what a GPU-less Windows host and the CI runners use —
103/// so a device per caller turns any two concurrent offscreen renders into a
104/// crash. Atlases still live on the per-call `Renderer`, so no caller can see
105/// another's cached glyphs.
106///
107/// `label` names the device, so it only takes effect on the call that actually
108/// opens it; later callers join a device someone else already named.
109pub async fn create_test_renderer(
110    label: &'static str,
111) -> Option<(Renderer, wgpu::Device, wgpu::Queue)> {
112    let (device, queue) = shared_device(label)?;
113    let renderer = Renderer::new(
114        device.clone(),
115        queue.clone(),
116        wgpu::TextureFormat::Rgba8UnormSrgb,
117    );
118    Some((renderer, device.clone(), queue.clone()))
119}
120
121/// The shared device, opening it on the first call.
122///
123/// Synchronous on purpose. `OnceLock::get_or_init` gives "exactly one caller
124/// runs the initialiser, the rest wait" for free, and opening a GPU device is
125/// blocking work whichever way it is spelled — every caller already reaches
126/// this through `pollster::block_on`. The alternative, holding a lock across
127/// the `await` inside an async fn, is the shape `clippy::await_holding_lock`
128/// warns about, and it would deadlock the first caller that ever drove this
129/// from a single-threaded executor.
130fn shared_device(label: &'static str) -> Option<&'static (wgpu::Device, wgpu::Queue)> {
131    SHARED_DEVICE
132        .get_or_init(|| pollster::block_on(open_shared_device(label)))
133        .as_ref()
134}
135
136/// Read a texture back as tightly-packed RGBA, panicking on GPU failure.
137///
138/// Kept for tests, where a lost device is a test failure and a panic is the
139/// clearest report. Anything user-facing — a screenshot tool that must survive
140/// a driver restart — should call [`try_read_texture_rgba`] instead.
141pub fn read_texture_rgba(
142    device: &wgpu::Device,
143    queue: &wgpu::Queue,
144    texture: &wgpu::Texture,
145    width: u32,
146    height: u32,
147) -> Vec<u8> {
148    try_read_texture_rgba(device, queue, texture, width, height).expect("texture readback failed")
149}
150
151/// Read a texture back as tightly-packed RGBA.
152///
153/// The GPU copy needs each row aligned to
154/// [`wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`]; the padding is added for the copy
155/// and stripped back out here, so the returned buffer is exactly
156/// `width * height * 4` bytes with no stride.
157pub fn try_read_texture_rgba(
158    device: &wgpu::Device,
159    queue: &wgpu::Queue,
160    texture: &wgpu::Texture,
161    width: u32,
162    height: u32,
163) -> Result<Vec<u8>, ReadbackError> {
164    let bytes_per_pixel = 4u32;
165    let unpadded_bytes_per_row = width * bytes_per_pixel;
166    let padded_bytes_per_row = unpadded_bytes_per_row.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)
167        * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
168    let buffer_size = padded_bytes_per_row as u64 * height as u64;
169
170    let buffer = device.create_buffer(&wgpu::BufferDescriptor {
171        label: Some("teksilo_render_test_readback"),
172        size: buffer_size,
173        usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
174        mapped_at_creation: false,
175    });
176
177    let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
178        label: Some("teksilo_render_test_copy"),
179    });
180    encoder.copy_texture_to_buffer(
181        wgpu::TexelCopyTextureInfo {
182            texture,
183            mip_level: 0,
184            origin: wgpu::Origin3d::ZERO,
185            aspect: wgpu::TextureAspect::All,
186        },
187        wgpu::TexelCopyBufferInfo {
188            buffer: &buffer,
189            layout: wgpu::TexelCopyBufferLayout {
190                offset: 0,
191                bytes_per_row: Some(padded_bytes_per_row),
192                rows_per_image: Some(height),
193            },
194        },
195        wgpu::Extent3d {
196            width,
197            height,
198            depth_or_array_layers: 1,
199        },
200    );
201    queue.submit(std::iter::once(encoder.finish()));
202
203    let slice = buffer.slice(..);
204    let (tx, rx) = mpsc::channel();
205    slice.map_async(wgpu::MapMode::Read, move |result| {
206        let _ = tx.send(result);
207    });
208    device
209        .poll(wgpu::PollType::Wait {
210            submission_index: None,
211            timeout: None,
212        })
213        .map_err(|e| ReadbackError::PollFailed(e.to_string()))?;
214    rx.recv()
215        .map_err(|_| ReadbackError::DeviceLost)?
216        .map_err(|e| ReadbackError::MapFailed(e.to_string()))?;
217
218    let mapped = slice
219        .get_mapped_range()
220        .map_err(|e| ReadbackError::MapFailed(e.to_string()))?;
221    let mut pixels = vec![0u8; (width * height * bytes_per_pixel) as usize];
222    for row in 0..height as usize {
223        let src_offset = row * padded_bytes_per_row as usize;
224        let dst_offset = row * unpadded_bytes_per_row as usize;
225        pixels[dst_offset..dst_offset + unpadded_bytes_per_row as usize]
226            .copy_from_slice(&mapped[src_offset..src_offset + unpadded_bytes_per_row as usize]);
227    }
228    drop(mapped);
229    buffer.unmap();
230    Ok(pixels)
231}
232
233/// How many times a GPU device has actually been opened in this process.
234///
235/// Exists only so [`exactly_one_device_is_opened_per_process`] can assert the
236/// invariant the WARP crash depends on.
237#[cfg(test)]
238static DEVICE_OPENS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
239
240#[cfg(test)]
241mod shared_device_tests {
242    use super::*;
243
244    /// Every caller must land on the SAME device, even under contention.
245    ///
246    /// This is the invariant that keeps the offscreen renderer alive on a
247    /// GPU-less Windows host. Two D3D12 WARP devices rasterizing concurrently
248    /// fault inside `d3d10warp.dll`, which no amount of care on our side can
249    /// catch — it is a wild access violation in Microsoft's software
250    /// rasterizer, so the process dies mid-test. The only defence is to never
251    /// open the second device, and that is what this pins.
252    ///
253    /// Asserted through a counter rather than by comparing handles because
254    /// `wgpu::Device` exposes no identity: cloning is the supported way to
255    /// share one, so two clones are indistinguishable from two devices at the
256    /// type level — exactly the confusion that let a second device appear.
257    #[test]
258    fn exactly_one_device_is_opened_per_process() {
259        use std::sync::atomic::Ordering;
260
261        // Race several threads at the initialiser; `OnceLock` plus the init
262        // lock must let exactly one of them reach `open_shared_device`.
263        let barrier = std::sync::Arc::new(std::sync::Barrier::new(4));
264        let handles: Vec<_> = (0..4)
265            .map(|_| {
266                let b = barrier.clone();
267                std::thread::spawn(move || {
268                    b.wait();
269                    pollster::block_on(create_test_renderer("shared-device-test")).is_some()
270                })
271            })
272            .collect();
273        let got: Vec<bool> = handles.into_iter().map(|h| h.join().unwrap()).collect();
274
275        // Either this host has a device and every caller got one, or it has
276        // none and nobody did — never a mix.
277        assert!(
278            got.iter().all(|g| *g) || got.iter().all(|g| !*g),
279            "callers disagreed about whether a GPU exists: {got:?}"
280        );
281
282        let opens = DEVICE_OPENS.load(Ordering::Relaxed);
283        assert_eq!(
284            opens, 1,
285            "the device must be opened exactly once per process, not {opens} times - a second \
286             concurrent WARP device is an access violation inside d3d10warp.dll, not a slowdown"
287        );
288    }
289}