Skip to main content

strata_render/
swapchain.rs

1//! Hardware Swapchain Presentation Pipeline, Surface Presenter Trait, and Damage Scissoring.
2
3use crate::compositor::{DamageTracker, DisplayList};
4use crate::rasterizer::FrameBuffer;
5use std::time::{Duration, Instant};
6use strata_layout::Rect;
7
8/// Color format for pixel data stored in the swapchain surface.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
10pub enum SwapchainFormat {
11    /// 32-bit BGRA unsigned normalized (standard Windows DXGI and macOS Metal format).
12    #[default]
13    Bgra8Unorm,
14    /// 32-bit RGBA unsigned normalized (standard Wayland / Vulkan format).
15    Rgba8Unorm,
16    /// 64-bit HDR half-precision floating point.
17    Rgba16Float,
18    /// 32-bit floating-point depth buffer format.
19    Depth32Float,
20}
21
22impl SwapchainFormat {
23    /// Bytes per pixel for this format.
24    pub const fn bytes_per_pixel(&self) -> usize {
25        match self {
26            Self::Bgra8Unorm | Self::Rgba8Unorm | Self::Depth32Float => 4,
27            Self::Rgba16Float => 8,
28        }
29    }
30
31    /// Whether this format represents a depth or depth-stencil attachment.
32    pub const fn is_depth(&self) -> bool {
33        matches!(self, Self::Depth32Float)
34    }
35}
36
37/// Potential presentation and swapchain errors.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub enum PresentError {
40    SurfaceLost,
41    Outdated,
42    Timeout,
43    BufferTooSmall,
44    Custom(String),
45}
46
47/// Abstract hardware presentation surface capable of receiving rendered frames.
48pub trait SurfacePresenter {
49    /// Presents the contents of the given framebuffer to the display surface, optionally clipped to damage.
50    fn present(&mut self, buffer: &FrameBuffer, damage: Option<Rect>) -> Result<(), PresentError>;
51
52    /// Notifies the presentation surface of a dimension resize.
53    fn resize(&mut self, width: u32, height: u32) -> Result<(), PresentError>;
54
55    /// Returns physical surface dimensions as (width, height).
56    fn surface_size(&self) -> (u32, u32);
57}
58
59/// Zero-dependency software presentation surface holding a target backing pixel store.
60#[derive(Debug, Clone)]
61pub struct SoftwareSurfacePresenter {
62    pub width: u32,
63    pub height: u32,
64    pub format: SwapchainFormat,
65    pub backing_buffer: Vec<u8>,
66    pub presented_frames: u64,
67    pub damage_clipped_frames: u64,
68}
69
70impl SoftwareSurfacePresenter {
71    /// Creates a new software presentation surface initialized with the specified size and format.
72    pub fn new(width: u32, height: u32, format: SwapchainFormat) -> Self {
73        let byte_size = (width as usize) * (height as usize) * format.bytes_per_pixel();
74        Self {
75            width,
76            height,
77            format,
78            backing_buffer: vec![0; byte_size],
79            presented_frames: 0,
80            damage_clipped_frames: 0,
81        }
82    }
83}
84
85impl SurfacePresenter for SoftwareSurfacePresenter {
86    fn present(&mut self, buffer: &FrameBuffer, damage: Option<Rect>) -> Result<(), PresentError> {
87        let expected_size =
88            (self.width as usize) * (self.height as usize) * self.format.bytes_per_pixel();
89        if self.backing_buffer.len() < expected_size {
90            return Err(PresentError::BufferTooSmall);
91        }
92
93        if let Some(damage_rect) = damage {
94            self.damage_clipped_frames += 1;
95            let min_x = (damage_rect.x.floor() as isize)
96                .max(0)
97                .min(self.width as isize) as usize;
98            let max_x = (damage_rect.max_x().ceil() as isize)
99                .max(0)
100                .min(self.width as isize) as usize;
101            let min_y = (damage_rect.y.floor() as isize)
102                .max(0)
103                .min(self.height as isize) as usize;
104            let max_y = (damage_rect.max_y().ceil() as isize)
105                .max(0)
106                .min(self.height as isize) as usize;
107
108            let bpp = self.format.bytes_per_pixel();
109            let src_stride = buffer.width * 4;
110            let dst_stride = self.width as usize * bpp;
111
112            for y in min_y..max_y {
113                let src_row = y * src_stride;
114                let dst_row = y * dst_stride;
115
116                for x in min_x..max_x {
117                    let src_idx = src_row + x * 4;
118                    let dst_idx = dst_row + x * bpp;
119
120                    if src_idx + 3 < buffer.pixels.len() && dst_idx + 3 < self.backing_buffer.len()
121                    {
122                        let r = buffer.pixels[src_idx];
123                        let g = buffer.pixels[src_idx + 1];
124                        let b = buffer.pixels[src_idx + 2];
125                        let a = buffer.pixels[src_idx + 3];
126
127                        match self.format {
128                            SwapchainFormat::Bgra8Unorm => {
129                                self.backing_buffer[dst_idx] = b;
130                                self.backing_buffer[dst_idx + 1] = g;
131                                self.backing_buffer[dst_idx + 2] = r;
132                                self.backing_buffer[dst_idx + 3] = a;
133                            }
134                            SwapchainFormat::Rgba8Unorm => {
135                                self.backing_buffer[dst_idx] = r;
136                                self.backing_buffer[dst_idx + 1] = g;
137                                self.backing_buffer[dst_idx + 2] = b;
138                                self.backing_buffer[dst_idx + 3] = a;
139                            }
140                            SwapchainFormat::Rgba16Float => {
141                                // Simple 8-bit to half-float mapping for fallback
142                                self.backing_buffer[dst_idx] = r;
143                                self.backing_buffer[dst_idx + 1] = g;
144                                self.backing_buffer[dst_idx + 2] = b;
145                                self.backing_buffer[dst_idx + 3] = a;
146                            }
147                            SwapchainFormat::Depth32Float => {
148                                let lum = (r as f32 * 0.299 + g as f32 * 0.587 + b as f32 * 0.114)
149                                    / 255.0;
150                                let bytes = lum.to_ne_bytes();
151                                self.backing_buffer[dst_idx..dst_idx + 4].copy_from_slice(&bytes);
152                            }
153                        }
154                    }
155                }
156            }
157        } else {
158            // Full screen copy
159            if self.format == SwapchainFormat::Rgba8Unorm {
160                let copy_len = self.backing_buffer.len().min(buffer.pixels.len());
161                self.backing_buffer[..copy_len].copy_from_slice(&buffer.pixels[..copy_len]);
162            } else if self.format == SwapchainFormat::Bgra8Unorm {
163                for (dst, src) in self
164                    .backing_buffer
165                    .chunks_exact_mut(4)
166                    .zip(buffer.pixels.chunks_exact(4))
167                {
168                    dst[0] = src[2]; // B
169                    dst[1] = src[1]; // G
170                    dst[2] = src[0]; // R
171                    dst[3] = src[3]; // A
172                }
173            }
174        }
175
176        self.presented_frames += 1;
177        Ok(())
178    }
179
180    fn resize(&mut self, width: u32, height: u32) -> Result<(), PresentError> {
181        self.width = width;
182        self.height = height;
183        let byte_size = (width as usize) * (height as usize) * self.format.bytes_per_pixel();
184        self.backing_buffer.resize(byte_size, 0);
185        Ok(())
186    }
187
188    fn surface_size(&self) -> (u32, u32) {
189        (self.width, self.height)
190    }
191}
192
193/// Orchestrates display list compilation, damage scissoring, and swapchain presentation.
194#[derive(Debug)]
195pub struct SwapchainCompositor {
196    pub width: u32,
197    pub height: u32,
198    pub scale_factor: f32,
199    pub framebuffer: FrameBuffer,
200    pub damage_tracker: DamageTracker,
201    pub frame_count: u64,
202    pub total_render_duration: Duration,
203}
204
205impl SwapchainCompositor {
206    /// Creates a swapchain compositor with backing framebuffer sized to physical pixels.
207    pub fn new(width: u32, height: u32, scale_factor: f32) -> Self {
208        let pw = ((width as f32 * scale_factor) + 0.5) as usize;
209        let ph = ((height as f32 * scale_factor) + 0.5) as usize;
210        let mut damage_tracker = DamageTracker::new();
211        damage_tracker.add_damage(Rect::new(0.0, 0.0, width as f32, height as f32));
212
213        Self {
214            width,
215            height,
216            scale_factor,
217            framebuffer: FrameBuffer::new(pw.max(1), ph.max(1)),
218            damage_tracker,
219            frame_count: 0,
220            total_render_duration: Duration::ZERO,
221        }
222    }
223
224    /// Resizes swapchain dimensions, updating internal framebuffer and registering full dirty damage.
225    pub fn resize(&mut self, width: u32, height: u32, scale_factor: f32) {
226        self.width = width;
227        self.height = height;
228        self.scale_factor = scale_factor;
229        let pw = ((width as f32 * scale_factor) + 0.5) as usize;
230        let ph = ((height as f32 * scale_factor) + 0.5) as usize;
231        self.framebuffer = FrameBuffer::new(pw.max(1), ph.max(1));
232        self.damage_tracker
233            .add_damage(Rect::new(0.0, 0.0, width as f32, height as f32));
234    }
235
236    /// Renders display list and presents to target surface. Skips frame if clean and force_redraw is false.
237    pub fn render_and_present<P: SurfacePresenter>(
238        &mut self,
239        display_list: &DisplayList,
240        presenter: &mut P,
241        force_redraw: bool,
242    ) -> Result<bool, PresentError> {
243        let damage = if force_redraw {
244            Some(Rect::new(0.0, 0.0, self.width as f32, self.height as f32))
245        } else {
246            self.damage_tracker.bounding_damage()
247        };
248
249        if damage.is_none() && !force_redraw {
250            // Clean frame: 0 CPU/GPU wasted!
251            return Ok(false);
252        }
253
254        let start = Instant::now();
255        if let Some(damage_rect) = damage {
256            if force_redraw {
257                self.framebuffer.execute_display_list(display_list);
258            } else {
259                self.framebuffer
260                    .execute_display_list_damaged(display_list, damage_rect);
261            }
262        } else {
263            self.framebuffer.execute_display_list(display_list);
264        }
265        presenter.present(&self.framebuffer, damage)?;
266
267        self.damage_tracker.reset();
268        self.frame_count += 1;
269        self.total_render_duration += start.elapsed();
270
271        Ok(true)
272    }
273}
274
275/// Native hardware graphics API backend for presentation.
276#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
277pub enum HardwareBackend {
278    #[default]
279    Vulkan,
280    Metal,
281    Direct3D12,
282}
283
284/// Presentation mode configuring vertical synchronization and frame queuing.
285#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
286pub enum PresentMode {
287    /// FIFO presentation synchronized to display VSync (tearing-free, double/triple buffered).
288    #[default]
289    Fifo,
290    /// Mailbox presentation (triple-buffered lowest latency without tearing).
291    Mailbox,
292    /// Immediate presentation without vertical blank wait (lowest latency, tearing possible).
293    Immediate,
294}
295
296/// Multi-buffered hardware presentation surface with GPU fences and damage scissoring.
297#[derive(Debug, Clone)]
298pub struct HardwareSwapchainPresenter {
299    pub backend: HardwareBackend,
300    pub present_mode: PresentMode,
301    pub width: u32,
302    pub height: u32,
303    pub format: SwapchainFormat,
304    pub buffer_count: usize,
305    pub current_image_index: usize,
306    pub buffers: Vec<Vec<u8>>,
307    pub frame_fences: Vec<u64>,
308    pub current_fence: u64,
309    pub presented_frames: u64,
310    pub damage_clipped_frames: u64,
311}
312
313impl HardwareSwapchainPresenter {
314    /// Creates a multi-buffered hardware swapchain presenter.
315    pub fn new(
316        backend: HardwareBackend,
317        present_mode: PresentMode,
318        width: u32,
319        height: u32,
320        format: SwapchainFormat,
321        buffer_count: usize,
322    ) -> Self {
323        let count = buffer_count.clamp(2, 4);
324        let byte_size = (width as usize) * (height as usize) * format.bytes_per_pixel();
325        let buffers = vec![vec![0u8; byte_size]; count];
326        let frame_fences = vec![0u64; count];
327
328        Self {
329            backend,
330            present_mode,
331            width,
332            height,
333            format,
334            buffer_count: count,
335            current_image_index: 0,
336            buffers,
337            frame_fences,
338            current_fence: 0,
339            presented_frames: 0,
340            damage_clipped_frames: 0,
341        }
342    }
343
344    /// Acquires the next available swapchain buffer image index, advancing synchronization fences.
345    pub fn acquire_next_image(&mut self) -> Result<usize, PresentError> {
346        let next_idx = match self.present_mode {
347            PresentMode::Immediate => self.current_image_index,
348            PresentMode::Fifo | PresentMode::Mailbox => {
349                (self.current_image_index + 1) % self.buffer_count
350            }
351        };
352        self.current_image_index = next_idx;
353        Ok(next_idx)
354    }
355
356    /// Waits for a specific hardware fence value to complete with a specified timeout.
357    pub fn wait_for_fence(&self, fence: u64, _timeout: Duration) -> Result<(), PresentError> {
358        if self.current_fence >= fence {
359            Ok(())
360        } else {
361            Err(PresentError::Timeout)
362        }
363    }
364
365    /// Returns the last submitted hardware fence counter.
366    pub fn last_submitted_fence(&self) -> u64 {
367        self.current_fence
368    }
369}
370
371impl SurfacePresenter for HardwareSwapchainPresenter {
372    fn present(&mut self, buffer: &FrameBuffer, damage: Option<Rect>) -> Result<(), PresentError> {
373        let expected_size =
374            (self.width as usize) * (self.height as usize) * self.format.bytes_per_pixel();
375        let idx = self.acquire_next_image()?;
376        let target_buffer = &mut self.buffers[idx];
377
378        if target_buffer.len() < expected_size {
379            return Err(PresentError::BufferTooSmall);
380        }
381
382        if let Some(damage_rect) = damage {
383            self.damage_clipped_frames += 1;
384            let min_x = (damage_rect.x.floor() as isize)
385                .max(0)
386                .min(self.width as isize) as usize;
387            let max_x = (damage_rect.max_x().ceil() as isize)
388                .max(0)
389                .min(self.width as isize) as usize;
390            let min_y = (damage_rect.y.floor() as isize)
391                .max(0)
392                .min(self.height as isize) as usize;
393            let max_y = (damage_rect.max_y().ceil() as isize)
394                .max(0)
395                .min(self.height as isize) as usize;
396
397            let bpp = self.format.bytes_per_pixel();
398            let src_stride = buffer.width * 4;
399            let dst_stride = self.width as usize * bpp;
400
401            for y in min_y..max_y {
402                let src_row = y * src_stride;
403                let dst_row = y * dst_stride;
404
405                for x in min_x..max_x {
406                    let src_idx = src_row + x * 4;
407                    let dst_idx = dst_row + x * bpp;
408
409                    if src_idx + 3 < buffer.pixels.len() && dst_idx + 3 < target_buffer.len() {
410                        let r = buffer.pixels[src_idx];
411                        let g = buffer.pixels[src_idx + 1];
412                        let b = buffer.pixels[src_idx + 2];
413                        let a = buffer.pixels[src_idx + 3];
414
415                        match self.format {
416                            SwapchainFormat::Bgra8Unorm => {
417                                target_buffer[dst_idx] = b;
418                                target_buffer[dst_idx + 1] = g;
419                                target_buffer[dst_idx + 2] = r;
420                                target_buffer[dst_idx + 3] = a;
421                            }
422                            SwapchainFormat::Rgba8Unorm => {
423                                target_buffer[dst_idx] = r;
424                                target_buffer[dst_idx + 1] = g;
425                                target_buffer[dst_idx + 2] = b;
426                                target_buffer[dst_idx + 3] = a;
427                            }
428                            SwapchainFormat::Rgba16Float => {
429                                target_buffer[dst_idx] = r;
430                                target_buffer[dst_idx + 1] = g;
431                                target_buffer[dst_idx + 2] = b;
432                                target_buffer[dst_idx + 3] = a;
433                            }
434                            SwapchainFormat::Depth32Float => {
435                                let lum = (r as f32 * 0.299 + g as f32 * 0.587 + b as f32 * 0.114)
436                                    / 255.0;
437                                let bytes = lum.to_ne_bytes();
438                                target_buffer[dst_idx..dst_idx + 4].copy_from_slice(&bytes);
439                            }
440                        }
441                    }
442                }
443            }
444        } else {
445            if self.format == SwapchainFormat::Rgba8Unorm {
446                let copy_len = target_buffer.len().min(buffer.pixels.len());
447                target_buffer[..copy_len].copy_from_slice(&buffer.pixels[..copy_len]);
448            } else if self.format == SwapchainFormat::Bgra8Unorm {
449                for (dst, src) in target_buffer
450                    .chunks_exact_mut(4)
451                    .zip(buffer.pixels.chunks_exact(4))
452                {
453                    dst[0] = src[2];
454                    dst[1] = src[1];
455                    dst[2] = src[0];
456                    dst[3] = src[3];
457                }
458            }
459        }
460
461        self.current_fence += 1;
462        self.frame_fences[idx] = self.current_fence;
463        self.presented_frames += 1;
464        Ok(())
465    }
466
467    fn resize(&mut self, width: u32, height: u32) -> Result<(), PresentError> {
468        self.width = width;
469        self.height = height;
470        let byte_size = (width as usize) * (height as usize) * self.format.bytes_per_pixel();
471        for buf in &mut self.buffers {
472            buf.resize(byte_size, 0);
473        }
474        Ok(())
475    }
476
477    fn surface_size(&self) -> (u32, u32) {
478        (self.width, self.height)
479    }
480}