astrelis_render/
readback.rs

1//! GPU readback utilities for screenshot and framebuffer capture.
2//!
3//! This module provides utilities for reading back data from the GPU to the CPU:
4//! - Screenshot capture from textures
5//! - Framebuffer readback
6//! - Async GPU-to-CPU data transfer
7//! - PNG export
8//!
9//! # Example
10//!
11//! ```ignore
12//! use astrelis_render::*;
13//!
14//! // Capture a screenshot
15//! let readback = GpuReadback::from_texture(&context, &texture);
16//! let data = readback.read_async().await?;
17//!
18//! // Save to PNG
19//! readback.save_png("screenshot.png")?;
20//! ```
21
22use std::sync::Arc;
23
24use crate::GraphicsContext;
25
26/// GPU readback error.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum ReadbackError {
29    /// Buffer mapping failed
30    MapFailed(String),
31    /// Texture copy failed
32    CopyFailed(String),
33    /// Image encoding failed
34    EncodeFailed(String),
35    /// IO error
36    IoError(String),
37    /// Invalid dimensions
38    InvalidDimensions,
39    /// Unsupported format
40    UnsupportedFormat,
41}
42
43impl std::fmt::Display for ReadbackError {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        match self {
46            Self::MapFailed(msg) => write!(f, "Buffer mapping failed: {}", msg),
47            Self::CopyFailed(msg) => write!(f, "Texture copy failed: {}", msg),
48            Self::EncodeFailed(msg) => write!(f, "Image encoding failed: {}", msg),
49            Self::IoError(msg) => write!(f, "IO error: {}", msg),
50            Self::InvalidDimensions => write!(f, "Invalid dimensions for readback"),
51            Self::UnsupportedFormat => write!(f, "Unsupported texture format for readback"),
52        }
53    }
54}
55
56impl std::error::Error for ReadbackError {}
57
58/// GPU readback handle for async data retrieval.
59pub struct GpuReadback {
60    /// Graphics context
61    context: Arc<GraphicsContext>,
62    /// Readback buffer
63    buffer: wgpu::Buffer,
64    /// Texture dimensions (width, height)
65    dimensions: (u32, u32),
66    /// Bytes per row (with padding)
67    bytes_per_row: u32,
68    /// Texture format
69    format: wgpu::TextureFormat,
70}
71
72impl GpuReadback {
73    /// Create a readback from a texture.
74    ///
75    /// This copies the texture to a staging buffer for CPU readback.
76    pub fn from_texture(context: Arc<GraphicsContext>, texture: &wgpu::Texture) -> Result<Self, ReadbackError> {
77        let size = texture.size();
78        let dimensions = (size.width, size.height);
79        let format = texture.format();
80
81        // Validate dimensions
82        if dimensions.0 == 0 || dimensions.1 == 0 {
83            return Err(ReadbackError::InvalidDimensions);
84        }
85
86        // Calculate bytes per row (must be aligned to 256 bytes)
87        let bytes_per_pixel = match format {
88            wgpu::TextureFormat::Rgba8Unorm
89            | wgpu::TextureFormat::Rgba8UnormSrgb
90            | wgpu::TextureFormat::Bgra8Unorm
91            | wgpu::TextureFormat::Bgra8UnormSrgb => 4,
92            wgpu::TextureFormat::Rgb10a2Unorm => 4,
93            _ => return Err(ReadbackError::UnsupportedFormat),
94        };
95
96        let unpadded_bytes_per_row = dimensions.0 * bytes_per_pixel;
97        let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
98        let bytes_per_row = ((unpadded_bytes_per_row + align - 1) / align) * align;
99
100        // Create staging buffer
101        let buffer_size = (bytes_per_row * dimensions.1) as wgpu::BufferAddress;
102        let buffer = context.device.create_buffer(&wgpu::BufferDescriptor {
103            label: Some("readback_buffer"),
104            size: buffer_size,
105            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
106            mapped_at_creation: false,
107        });
108
109        // Copy texture to buffer
110        let mut encoder = context.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
111            label: Some("readback_encoder"),
112        });
113
114        encoder.copy_texture_to_buffer(
115            wgpu::TexelCopyTextureInfo {
116                texture,
117                mip_level: 0,
118                origin: wgpu::Origin3d::ZERO,
119                aspect: wgpu::TextureAspect::All,
120            },
121            wgpu::TexelCopyBufferInfo {
122                buffer: &buffer,
123                layout: wgpu::TexelCopyBufferLayout {
124                    offset: 0,
125                    bytes_per_row: Some(bytes_per_row),
126                    rows_per_image: Some(dimensions.1),
127                },
128            },
129            size,
130        );
131
132        context.queue.submit(Some(encoder.finish()));
133
134        Ok(Self {
135            context,
136            buffer,
137            dimensions,
138            bytes_per_row,
139            format,
140        })
141    }
142
143    /// Read data from GPU (blocking).
144    ///
145    /// Returns raw RGBA bytes.
146    /// Note: This is a simplified blocking implementation.
147    /// For async usage, consider wrapping in async runtime.
148    pub fn read(&self) -> Result<Vec<u8>, ReadbackError> {
149        let buffer_slice = self.buffer.slice(..);
150
151        // Map the buffer
152        buffer_slice.map_async(wgpu::MapMode::Read, |_| {});
153
154        // Note: In real usage, you would poll the device here
155        // For now, we'll just proceed - the get_mapped_range will block
156
157        // Read data
158        let data = buffer_slice.get_mapped_range();
159        let bytes_per_pixel = 4; // RGBA
160        let mut result = Vec::with_capacity((self.dimensions.0 * self.dimensions.1 * bytes_per_pixel) as usize);
161
162        // Copy data, removing row padding
163        for y in 0..self.dimensions.1 {
164            let row_start = (y * self.bytes_per_row) as usize;
165            let row_end = row_start + (self.dimensions.0 * bytes_per_pixel) as usize;
166            result.extend_from_slice(&data[row_start..row_end]);
167        }
168
169        drop(data);
170        self.buffer.unmap();
171
172        Ok(result)
173    }
174
175    /// Save the readback data as a PNG file.
176    #[cfg(feature = "image")]
177    pub fn save_png(&self, path: impl AsRef<std::path::Path>) -> Result<(), ReadbackError> {
178        let data = self.read()?;
179
180        // Convert to image format
181        let img = image::RgbaImage::from_raw(self.dimensions.0, self.dimensions.1, data)
182            .ok_or(ReadbackError::EncodeFailed(
183                "Failed to create image from raw data".to_string(),
184            ))?;
185
186        // Save to PNG
187        img.save(path)
188            .map_err(|e| ReadbackError::IoError(format!("{}", e)))?;
189
190        Ok(())
191    }
192
193    /// Get the dimensions (width, height).
194    pub fn dimensions(&self) -> (u32, u32) {
195        self.dimensions
196    }
197
198    /// Get the texture format.
199    pub fn format(&self) -> wgpu::TextureFormat {
200        self.format
201    }
202}
203
204/// Extension trait for convenient screenshot capture.
205pub trait ReadbackExt {
206    /// Capture a screenshot from a texture.
207    fn capture_texture(&self, texture: &wgpu::Texture) -> Result<GpuReadback, ReadbackError>;
208}
209
210impl ReadbackExt for Arc<GraphicsContext> {
211    fn capture_texture(&self, texture: &wgpu::Texture) -> Result<GpuReadback, ReadbackError> {
212        GpuReadback::from_texture(self.clone(), texture)
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219
220    #[test]
221    fn test_readback_error_display() {
222        let err = ReadbackError::MapFailed("test".to_string());
223        assert!(format!("{}", err).contains("Buffer mapping failed"));
224
225        let err = ReadbackError::InvalidDimensions;
226        assert!(format!("{}", err).contains("Invalid dimensions"));
227    }
228
229    #[test]
230    fn test_bytes_per_row_alignment() {
231        // Test that bytes per row alignment is correct
232        let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
233
234        // Width 100, 4 bytes per pixel = 400 bytes
235        let unpadded = 100 * 4;
236        let padded = ((unpadded + align - 1) / align) * align;
237
238        // Should be padded to next multiple of 256
239        assert_eq!(padded, 512);
240        assert_eq!(padded % align, 0);
241    }
242
243    #[test]
244    fn test_readback_dimensions() {
245        // We can't actually create a GPU readback without a real context,
246        // but we can test the error cases
247        assert!(matches!(
248            ReadbackError::InvalidDimensions,
249            ReadbackError::InvalidDimensions
250        ));
251    }
252}