Skip to main content

velox_engine/platform/
shm_driver.rs

1//! 跨平台通用双缓冲共享内存表面驱动器(`ShmSurfaceDriver`)与平台工具函数。
2//!
3//! 负责统一管理:
4//! - 双缓冲槽位 [`ShmSlot`] 与 Buffer Age = 2 历史脏矩形合并回溯;
5//! - 根据激活的 [`DesktopRenderBackend`](`Wgpu`、`Software`)
6//!   单路径执行真实像素渲染并写回前台缓冲区(消除 GPU 后端与软件光栅的双重执行冗余);
7//! - 通用 Linux `evdev` 键码解码 [`decode_linux_keycode`] 与无损 PNG 导出 [`write_uncompressed_png`]。
8
9use std::vec;
10use std::vec::Vec;
11
12use crate::display::{PixelFormat, Xrgb8888};
13use crate::engine::VeloxEngine;
14use crate::pod::{KeyCode, KeyModifiers};
15use crate::solver::Region;
16
17use super::DesktopRenderBackend;
18
19/// 共享内存帧缓冲句柄(兼容 Wayland `wl_buffer` ID)。
20#[derive(Copy, Clone, PartialEq, Eq, Debug)]
21pub struct WlBuffer {
22    pub id: u32,
23}
24
25/// 表面提交状态(跟踪附加的缓冲区 ID、`damage_buffer` 脏矩形列表与累计提交帧数)。
26#[derive(Clone, Debug, Default)]
27pub struct WlSurface {
28    /// 最近一次通过 `attach` 挂载的缓冲区 ID。
29    pub attached_buffer_id: Option<u32>,
30    /// 最近一次 `commit` 时提交的局部脏区域列表。
31    pub committed_damage: Vec<Region>,
32    /// 累计提交帧的次数。
33    pub commit_count: usize,
34}
35
36impl WlSurface {
37    pub fn new() -> Self {
38        Self::default()
39    }
40
41    /// 绑定后备缓冲区并清空本帧待提交脏区记录。
42    pub fn attach(&mut self, buffer: Option<&WlBuffer>, _x: i32, _y: i32) {
43        self.attached_buffer_id = buffer.map(|b| b.id);
44        self.committed_damage.clear();
45    }
46
47    /// 记录局部缓冲区脏矩形。
48    pub fn damage_buffer(&mut self, x: i32, y: i32, w: i32, h: i32) {
49        self.committed_damage
50            .push(Region::new(x as i16, y as i16, w as i16, h as i16));
51    }
52
53    /// 完成本帧表面状态原子提交。
54    pub fn commit(&mut self) {
55        self.commit_count += 1;
56    }
57}
58
59/// 双缓冲像素槽位(维护 Buffer Age 帧年龄)。
60pub struct ShmSlot {
61    pub wl_buffer: WlBuffer,
62    pub pixels: Vec<Xrgb8888>,
63    /// 合成器/宿主当前是否正在读取该 Buffer。
64    pub in_use: bool,
65    /// 距离上一次在该 Buffer 上绘制过去了多少帧(`0` 表示未初始化)。
66    pub age: u8,
67}
68
69impl ShmSlot {
70    pub fn new(id: u32, _width: usize, _height: usize) -> Self {
71        Self {
72            wl_buffer: WlBuffer { id },
73            pixels: Vec::new(),
74            in_use: false,
75            age: 0,
76        }
77    }
78}
79
80/// 跨平台双缓冲表面驱动器(支持 Buffer Age = 2 历史脏区回溯同步与多渲染后端真实像素输出)。
81pub struct WaylandSurfaceDriver {
82    pub slots: [ShmSlot; 2],
83    pub damage_history: [Vec<Region>; 2],
84    /// 最近一帧实际光栅化至活动槽位的脏矩形列表(包含 Buffer Age = 2 合并的历史脏矩形)。
85    pub last_raster_regions: Vec<Region>,
86    pub(crate) active_slot_idx: usize,
87    width: usize,
88    height: usize,
89    backend: DesktopRenderBackend,
90    #[cfg(feature = "gpu")]
91    gpu_scene: Option<crate::renderers::wgpu::WgpuScene>,
92}
93
94/// 通用双缓冲表面驱动器别名。
95pub type ShmSurfaceDriver = WaylandSurfaceDriver;
96/// 软件表面驱动器兼容别名。
97pub type SoftwareSurfaceDriver = WaylandSurfaceDriver;
98
99impl WaylandSurfaceDriver {
100    /// 创建指定像素尺寸的双缓冲驱动器(默认使用 [`DesktopRenderBackend::default_desktop`])。
101    pub fn new(width: usize, height: usize) -> Self {
102        let w = width.max(1);
103        let h = height.max(1);
104        Self {
105            slots: [ShmSlot::new(1, w, h), ShmSlot::new(2, w, h)],
106            damage_history: [Vec::new(), Vec::new()],
107            last_raster_regions: Vec::new(),
108            active_slot_idx: 0,
109            width: w,
110            height: h,
111            backend: DesktopRenderBackend::default_desktop(),
112            #[cfg(feature = "gpu")]
113            gpu_scene: None,
114        }
115    }
116
117    /// 配置渲染后端类型(`Wgpu` 或 `Software`)。
118    #[inline]
119    pub fn with_backend(mut self, backend: DesktopRenderBackend) -> Self {
120        self.backend = backend;
121        self
122    }
123
124    /// 动态切换渲染后端类型。
125    #[inline]
126    pub fn set_backend(&mut self, backend: DesktopRenderBackend) {
127        self.backend = backend;
128    }
129
130    /// 返回当前激活的渲染后端类型。
131    #[inline]
132    pub const fn backend(&self) -> DesktopRenderBackend {
133        self.backend
134    }
135
136    /// 获取最近一帧编译生成的轻量级 2D SDF GPU 场景图元统计引用。
137    #[cfg(feature = "gpu")]
138    #[inline]
139    pub fn gpu_scene(&self) -> Option<&crate::renderers::wgpu::WgpuScene> {
140        self.gpu_scene.as_ref()
141    }
142
143    /// 释放指定槽位以供下一帧复用。
144    pub fn release_buffer(&mut self, buffer_id: u32) {
145        for slot in &mut self.slots {
146            if slot.wl_buffer.id == buffer_id {
147                slot.in_use = false;
148            }
149        }
150    }
151
152    /// 获取最近一次提交到前台的 `Xrgb8888` 像素切片。
153    pub fn front_pixels(&self) -> &[Xrgb8888] {
154        &self.slots[self.active_slot_idx].pixels
155    }
156
157    /// 获取当前双缓冲表面分配的物理像素宽度(行步长 stride)。
158    #[inline(always)]
159    pub const fn width(&self) -> usize {
160        self.width
161    }
162
163    /// 获取当前双缓冲表面分配的物理像素高度。
164    #[inline(always)]
165    pub const fn height(&self) -> usize {
166        self.height
167    }
168
169    /// 动态调整双缓冲池尺寸。
170    pub fn resize(&mut self, width: usize, height: usize) {
171        let w = width.max(1);
172        let h = height.max(1);
173        self.width = w;
174        self.height = h;
175        self.slots = [ShmSlot::new(1, w, h), ShmSlot::new(2, w, h)];
176        self.damage_history = [Vec::new(), Vec::new()];
177        self.last_raster_regions.clear();
178        self.active_slot_idx = 0;
179    }
180
181    /// 以默认 60FPS (`16ms`) 步长执行一帧检查、Buffer Age 历史脏矩形合并、渲染与提交。
182    pub fn flush_frame(&mut self, core: &mut VeloxEngine, wl_surface: &mut WlSurface) -> bool {
183        self.flush_frame_dt(core, wl_surface, 16)
184    }
185
186    /// 按给定时间步长 `dt_ms` 执行一帧刷新与提交(真正由所选 `backend` 单路径产出像素,不再重复执行软件光栅)。
187    pub fn flush_frame_dt(
188        &mut self,
189        core: &mut VeloxEngine,
190        wl_surface: &mut WlSurface,
191        dt_ms: u16,
192    ) -> bool {
193        let curr_damage: Vec<Region> = core.step_frame_dt(dt_ms).to_vec();
194        if curr_damage.is_empty() {
195            return false;
196        }
197
198        let slot_idx = self
199            .slots
200            .iter()
201            .position(|s| !s.in_use)
202            .unwrap_or((self.active_slot_idx + 1) & 1);
203        let slot_age = self.slots[slot_idx].age;
204        let required_len = self.width.saturating_mul(self.height);
205        if self.slots[slot_idx].pixels.len() != required_len {
206            self.slots[slot_idx]
207                .pixels
208                .resize(required_len, Xrgb8888(0xFF00_0000));
209        }
210
211        let mut raster_regions = curr_damage.clone();
212        if slot_age == 0 || slot_age > 2 {
213            raster_regions = vec![core.viewport_region()];
214        } else if slot_age == 2 {
215            raster_regions.extend_from_slice(&self.damage_history[0]);
216        }
217
218        #[cfg(feature = "gpu")]
219        let s = core.dpi_scale().max(1);
220        let sf = core.scale_factor();
221        let dst_stride = self.width;
222
223        match self.backend {
224            DesktopRenderBackend::Wgpu => {
225                #[cfg(feature = "gpu")]
226                {
227                    let scene = self
228                        .gpu_scene
229                        .get_or_insert_with(crate::renderers::wgpu::WgpuScene::new);
230                    let _ = scene.record_draw_ops(core.cached_draw_ops(), s, &raster_regions);
231                }
232                let pixels = &mut self.slots[slot_idx].pixels;
233                for reg in &raster_regions {
234                    clear_transparent_region(pixels, dst_stride, self.height, sf, *reg);
235                    core.rasterize_strip(*reg, 0, 0, dst_stride, pixels);
236                }
237            }
238            DesktopRenderBackend::Software => {
239                let pixels = &mut self.slots[slot_idx].pixels;
240                for reg in &raster_regions {
241                    clear_transparent_region(pixels, dst_stride, self.height, sf, *reg);
242                    core.rasterize_strip(*reg, 0, 0, dst_stride, pixels);
243                }
244            }
245        }
246
247        let wl_buf = self.slots[slot_idx].wl_buffer;
248        wl_surface.attach(Some(&wl_buf), 0, 0);
249        for reg in &curr_damage {
250            wl_surface.damage_buffer(reg.x as i32, reg.y as i32, reg.w as i32, reg.h as i32);
251        }
252        wl_surface.commit();
253
254        self.slots[slot_idx].in_use = true;
255        self.slots[slot_idx].age = 1;
256        for (idx, other) in self.slots.iter_mut().enumerate() {
257            if idx != slot_idx && other.age > 0 {
258                other.age = other.age.saturating_add(1);
259            }
260        }
261        self.damage_history.rotate_right(1);
262        self.damage_history[0] = curr_damage;
263        self.last_raster_regions = raster_regions;
264        self.active_slot_idx = slot_idx;
265
266        true
267    }
268}
269
270/// 在光栅化脏区前将目标区域清零为全透明像素(避免透明悬浮层如 Dock 缩放/重排时残留上一帧边框与图标)。
271#[inline]
272fn clear_transparent_region(
273    pixels: &mut [Xrgb8888],
274    stride: usize,
275    height: usize,
276    scale_factor: f32,
277    reg: Region,
278) {
279    let sf = scale_factor.clamp(0.5, 4.0);
280    let x0 = (((reg.x.max(0) as f32) * sf).floor() as usize).min(stride);
281    let y0 = (((reg.y.max(0) as f32) * sf).floor() as usize).min(height);
282    let x1 = (((reg.right().max(0) as f32) * sf).ceil() as usize).min(stride);
283    let y1 = (((reg.bottom().max(0) as f32) * sf).ceil() as usize).min(height);
284    if x0 >= x1 || y0 >= y1 {
285        return;
286    }
287    for y in y0..y1 {
288        let row = y * stride;
289        if row + x1 <= pixels.len() {
290            pixels[row + x0..row + x1].fill(Xrgb8888(0));
291        }
292    }
293}
294
295/// 将 Linux `evdev` 键码(`<linux/input-event-codes.h>`)解码为 `Velox` [`KeyCode`]。
296///
297/// 供 `wayland` 及外部 Linux 输入后端统一共享(消除重复键码表)。
298pub fn decode_linux_keycode(code: u16) -> Option<KeyCode> {
299    match code {
300        1 => Some(KeyCode::Escape),
301        2 => Some(KeyCode::Char('1')),
302        3 => Some(KeyCode::Char('2')),
303        4 => Some(KeyCode::Char('3')),
304        5 => Some(KeyCode::Char('4')),
305        6 => Some(KeyCode::Char('5')),
306        7 => Some(KeyCode::Char('6')),
307        8 => Some(KeyCode::Char('7')),
308        9 => Some(KeyCode::Char('8')),
309        10 => Some(KeyCode::Char('9')),
310        11 => Some(KeyCode::Char('0')),
311        12 => Some(KeyCode::Char('-')),
312        13 => Some(KeyCode::Char('=')),
313        14 => Some(KeyCode::Backspace),
314        15 => Some(KeyCode::Tab),
315        16 => Some(KeyCode::Char('q')),
316        17 => Some(KeyCode::Char('w')),
317        18 => Some(KeyCode::Char('e')),
318        19 => Some(KeyCode::Char('r')),
319        20 => Some(KeyCode::Char('t')),
320        21 => Some(KeyCode::Char('y')),
321        22 => Some(KeyCode::Char('u')),
322        23 => Some(KeyCode::Char('i')),
323        24 => Some(KeyCode::Char('o')),
324        25 => Some(KeyCode::Char('p')),
325        28 | 96 => Some(KeyCode::Enter),
326        30 => Some(KeyCode::Char('a')),
327        31 => Some(KeyCode::Char('s')),
328        32 => Some(KeyCode::Char('d')),
329        33 => Some(KeyCode::Char('f')),
330        34 => Some(KeyCode::Char('g')),
331        35 => Some(KeyCode::Char('h')),
332        36 => Some(KeyCode::Char('j')),
333        37 => Some(KeyCode::Char('k')),
334        38 => Some(KeyCode::Char('l')),
335        44 => Some(KeyCode::Char('z')),
336        45 => Some(KeyCode::Char('x')),
337        46 => Some(KeyCode::Char('c')),
338        47 => Some(KeyCode::Char('v')),
339        48 => Some(KeyCode::Char('b')),
340        49 => Some(KeyCode::Char('n')),
341        50 => Some(KeyCode::Char('m')),
342        51 => Some(KeyCode::Char(',')),
343        52 => Some(KeyCode::Char('.')),
344        53 => Some(KeyCode::Char('/')),
345        57 => Some(KeyCode::Space),
346        102 => Some(KeyCode::Home),
347        103 => Some(KeyCode::Up),
348        104 => Some(KeyCode::PageUp),
349        105 => Some(KeyCode::Left),
350        106 => Some(KeyCode::Right),
351        107 => Some(KeyCode::End),
352        108 => Some(KeyCode::Down),
353        109 => Some(KeyCode::PageDown),
354        111 => Some(KeyCode::Delete),
355        _ => None,
356    }
357}
358
359/// 将 Linux `evdev` 修饰键码解码为 [`KeyModifiers`] 位标志。
360pub fn decode_linux_modifier(code: u16) -> Option<KeyModifiers> {
361    match code {
362        42 | 54 => Some(KeyModifiers::SHIFT),
363        29 | 97 => Some(KeyModifiers::CTRL),
364        56 | 100 => Some(KeyModifiers::ALT),
365        125 | 126 => Some(KeyModifiers::LOGO),
366        _ => None,
367    }
368}
369
370/// 将 `Xrgb8888` 像素切片导出为标准无损 PNG 文件。
371pub fn write_uncompressed_png(
372    path: &str,
373    width: usize,
374    height: usize,
375    pixels: &[Xrgb8888],
376) -> std::io::Result<()> {
377    fn crc32(data: &[u8]) -> u32 {
378        let mut crc = 0xFFFF_FFFFu32;
379        for &b in data {
380            crc ^= b as u32;
381            for _ in 0..8 {
382                if (crc & 1) != 0 {
383                    crc = (crc >> 1) ^ 0xEDB8_8320;
384                } else {
385                    crc >>= 1;
386                }
387            }
388        }
389        !crc
390    }
391
392    fn write_chunk(out: &mut Vec<u8>, tag: &[u8; 4], data: &[u8]) {
393        out.extend_from_slice(&(data.len() as u32).to_be_bytes());
394        let start = out.len();
395        out.extend_from_slice(tag);
396        out.extend_from_slice(data);
397        let c = crc32(&out[start..]);
398        out.extend_from_slice(&c.to_be_bytes());
399    }
400
401    let mut raw_scanlines = Vec::with_capacity(height * (1 + width * 3));
402    for y in 0..height {
403        raw_scanlines.push(0u8);
404        for x in 0..width {
405            let c = pixels[y * width + x].to_color();
406            raw_scanlines.push(c.r());
407            raw_scanlines.push(c.g());
408            raw_scanlines.push(c.b());
409        }
410    }
411
412    let mut zlib_stream = Vec::with_capacity(raw_scanlines.len() + 64);
413    zlib_stream.push(0x78);
414    zlib_stream.push(0x01);
415
416    let mut s1: u32 = 1;
417    let mut s2: u32 = 0;
418    for &b in &raw_scanlines {
419        s1 = (s1 + b as u32) % 65521;
420        s2 = (s2 + s1) % 65521;
421    }
422    let adler = (s2 << 16) | s1;
423
424    let total_len = raw_scanlines.len();
425    let mut offset = 0usize;
426    while offset < total_len {
427        let rem = total_len - offset;
428        let block_len = rem.min(65535);
429        let is_final = u8::from(offset + block_len >= total_len);
430        zlib_stream.push(is_final);
431        let len_u16 = block_len as u16;
432        let nlen_u16 = !len_u16;
433        zlib_stream.extend_from_slice(&len_u16.to_le_bytes());
434        zlib_stream.extend_from_slice(&nlen_u16.to_le_bytes());
435        zlib_stream.extend_from_slice(&raw_scanlines[offset..offset + block_len]);
436        offset += block_len;
437    }
438    zlib_stream.extend_from_slice(&adler.to_be_bytes());
439
440    let mut png = Vec::with_capacity(zlib_stream.len() + 128);
441    png.extend_from_slice(&[137, 80, 78, 71, 13, 10, 26, 10]);
442
443    let mut ihdr = Vec::with_capacity(13);
444    ihdr.extend_from_slice(&(width as u32).to_be_bytes());
445    ihdr.extend_from_slice(&(height as u32).to_be_bytes());
446    ihdr.extend_from_slice(&[8, 2, 0, 0, 0]);
447    write_chunk(&mut png, b"IHDR", &ihdr);
448    write_chunk(&mut png, b"IDAT", &zlib_stream);
449    write_chunk(&mut png, b"IEND", &[]);
450
451    std::fs::write(path, png)
452}