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 past that — so a path-heavy frame would fail here
76        // while rendering fine anywhere the cap is lifted. `using_resolution`
77        // lifts exactly the resolution limits to whatever this adapter really
78        // supports, keeping every other downlevel bound. The live window path
79        // asks for the same set, so a frame that renders in a test renders in
80        // a window too.
81        let limits = wgpu::Limits::downlevel_defaults().using_resolution(adapter.limits());
82
83        if let Ok((device, queue)) = adapter
84            .request_device(&wgpu::DeviceDescriptor {
85                label: Some(label),
86                required_features: wgpu::Features::empty(),
87                required_limits: limits,
88                ..Default::default()
89            })
90            .await
91        {
92            return Some((device, queue));
93        }
94    }
95    None
96}
97
98/// Build an offscreen renderer on the shared device, or `None` if this host can
99/// open no usable GPU device at all.
100///
101/// The [`Renderer`] is fresh per call; the device and queue behind it are
102/// shared process-wide, which is load-bearing rather than an optimisation: two
103/// D3D12 **WARP** devices rasterizing at once fault inside Microsoft's software
104/// rasterizer — exactly what a GPU-less Windows host and the CI runners use —
105/// so a device per caller turns any two concurrent offscreen renders into a
106/// crash. Atlases still live on the per-call `Renderer`, so no caller can see
107/// another's cached glyphs.
108///
109/// `label` names the device, so it only takes effect on the call that actually
110/// opens it; later callers join a device someone else already named.
111pub async fn create_test_renderer(
112    label: &'static str,
113) -> Option<(Renderer, wgpu::Device, wgpu::Queue)> {
114    let (device, queue) = shared_device(label)?;
115    let renderer = Renderer::new(
116        device.clone(),
117        queue.clone(),
118        wgpu::TextureFormat::Rgba8UnormSrgb,
119    );
120    Some((renderer, device.clone(), queue.clone()))
121}
122
123/// The shared device, opening it on the first call.
124///
125/// Synchronous on purpose. `OnceLock::get_or_init` gives "exactly one caller
126/// runs the initialiser, the rest wait" for free, and opening a GPU device is
127/// blocking work whichever way it is spelled — every caller already reaches
128/// this through `pollster::block_on`. The alternative, holding a lock across
129/// the `await` inside an async fn, is the shape `clippy::await_holding_lock`
130/// warns about, and it would deadlock the first caller that ever drove this
131/// from a single-threaded executor.
132fn shared_device(label: &'static str) -> Option<&'static (wgpu::Device, wgpu::Queue)> {
133    SHARED_DEVICE
134        .get_or_init(|| pollster::block_on(open_shared_device(label)))
135        .as_ref()
136}
137
138/// Read a texture back as tightly-packed RGBA, panicking on GPU failure.
139///
140/// Kept for tests, where a lost device is a test failure and a panic is the
141/// clearest report. Anything user-facing — a screenshot tool that must survive
142/// a driver restart — should call [`try_read_texture_rgba`] instead.
143pub fn read_texture_rgba(
144    device: &wgpu::Device,
145    queue: &wgpu::Queue,
146    texture: &wgpu::Texture,
147    width: u32,
148    height: u32,
149) -> Vec<u8> {
150    try_read_texture_rgba(device, queue, texture, width, height).expect("texture readback failed")
151}
152
153/// Read a texture back as tightly-packed RGBA.
154///
155/// The GPU copy needs each row aligned to
156/// [`wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`]; the padding is added for the copy
157/// and stripped back out here, so the returned buffer is exactly
158/// `width * height * 4` bytes with no stride.
159pub fn try_read_texture_rgba(
160    device: &wgpu::Device,
161    queue: &wgpu::Queue,
162    texture: &wgpu::Texture,
163    width: u32,
164    height: u32,
165) -> Result<Vec<u8>, ReadbackError> {
166    let bytes_per_pixel = 4u32;
167    let unpadded_bytes_per_row = width * bytes_per_pixel;
168    let padded_bytes_per_row = unpadded_bytes_per_row.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)
169        * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
170    let buffer_size = padded_bytes_per_row as u64 * height as u64;
171
172    let buffer = device.create_buffer(&wgpu::BufferDescriptor {
173        label: Some("teksilo_render_test_readback"),
174        size: buffer_size,
175        usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
176        mapped_at_creation: false,
177    });
178
179    let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
180        label: Some("teksilo_render_test_copy"),
181    });
182    encoder.copy_texture_to_buffer(
183        wgpu::TexelCopyTextureInfo {
184            texture,
185            mip_level: 0,
186            origin: wgpu::Origin3d::ZERO,
187            aspect: wgpu::TextureAspect::All,
188        },
189        wgpu::TexelCopyBufferInfo {
190            buffer: &buffer,
191            layout: wgpu::TexelCopyBufferLayout {
192                offset: 0,
193                bytes_per_row: Some(padded_bytes_per_row),
194                rows_per_image: Some(height),
195            },
196        },
197        wgpu::Extent3d {
198            width,
199            height,
200            depth_or_array_layers: 1,
201        },
202    );
203    queue.submit(std::iter::once(encoder.finish()));
204
205    let slice = buffer.slice(..);
206    let (tx, rx) = mpsc::channel();
207    slice.map_async(wgpu::MapMode::Read, move |result| {
208        let _ = tx.send(result);
209    });
210    device
211        .poll(wgpu::PollType::Wait {
212            submission_index: None,
213            timeout: None,
214        })
215        .map_err(|e| ReadbackError::PollFailed(e.to_string()))?;
216    rx.recv()
217        .map_err(|_| ReadbackError::DeviceLost)?
218        .map_err(|e| ReadbackError::MapFailed(e.to_string()))?;
219
220    let mapped = slice
221        .get_mapped_range()
222        .map_err(|e| ReadbackError::MapFailed(e.to_string()))?;
223    let mut pixels = vec![0u8; (width * height * bytes_per_pixel) as usize];
224    for row in 0..height as usize {
225        let src_offset = row * padded_bytes_per_row as usize;
226        let dst_offset = row * unpadded_bytes_per_row as usize;
227        pixels[dst_offset..dst_offset + unpadded_bytes_per_row as usize]
228            .copy_from_slice(&mapped[src_offset..src_offset + unpadded_bytes_per_row as usize]);
229    }
230    drop(mapped);
231    buffer.unmap();
232    Ok(pixels)
233}
234
235/// How many times a GPU device has actually been opened in this process.
236///
237/// Exists only so [`exactly_one_device_is_opened_per_process`] can assert the
238/// invariant the WARP crash depends on.
239#[cfg(test)]
240static DEVICE_OPENS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
241
242#[cfg(test)]
243mod shared_device_tests {
244    use super::*;
245
246    /// Every caller must land on the SAME device, even under contention.
247    ///
248    /// This is the invariant that keeps the offscreen renderer alive on a
249    /// GPU-less Windows host. Two D3D12 WARP devices rasterizing concurrently
250    /// fault inside `d3d10warp.dll`, which no amount of care on our side can
251    /// catch — it is a wild access violation in Microsoft's software
252    /// rasterizer, so the process dies mid-test. The only defence is to never
253    /// open the second device, and that is what this pins.
254    ///
255    /// Asserted through a counter rather than by comparing handles because
256    /// `wgpu::Device` exposes no identity: cloning is the supported way to
257    /// share one, so two clones are indistinguishable from two devices at the
258    /// type level — exactly the confusion that let a second device appear.
259    #[test]
260    fn exactly_one_device_is_opened_per_process() {
261        use std::sync::atomic::Ordering;
262
263        // Race several threads at the initialiser; `OnceLock` plus the init
264        // lock must let exactly one of them reach `open_shared_device`.
265        let barrier = std::sync::Arc::new(std::sync::Barrier::new(4));
266        let handles: Vec<_> = (0..4)
267            .map(|_| {
268                let b = barrier.clone();
269                std::thread::spawn(move || {
270                    b.wait();
271                    pollster::block_on(create_test_renderer("shared-device-test")).is_some()
272                })
273            })
274            .collect();
275        let got: Vec<bool> = handles.into_iter().map(|h| h.join().unwrap()).collect();
276
277        // Either this host has a device and every caller got one, or it has
278        // none and nobody did — never a mix.
279        assert!(
280            got.iter().all(|g| *g) || got.iter().all(|g| !*g),
281            "callers disagreed about whether a GPU exists: {got:?}"
282        );
283
284        let opens = DEVICE_OPENS.load(Ordering::Relaxed);
285        assert_eq!(
286            opens, 1,
287            "the device must be opened exactly once per process, not {opens} times - a second \
288             concurrent WARP device is an access violation inside d3d10warp.dll, not a slowdown"
289        );
290    }
291}