Skip to main content

velox_engine/platform/
mod.rs

1//! 跨平台窗口、显示表面与事件循环抽象层。
2//!
3//! 统一内聚并适配多端平台后端,并为外部专有后端提供 [`Platform`]、[`PlatformSurface`]、[`AsyncPlatform`]、[`AsyncPlatformSurface`] 等通用特征抽象:
4//! - [`testing`](`#![no_std]`):提供确定性无头事件注入、虚拟时钟推进与像素断言平台;
5//! - [`wayland`](`std`):提供纯 Wayland 客户端平台 [`wayland::WaylandPlatform`](支持 `xdg_toplevel`、`zwlr_layer_shell_v1`、`zxdg_decoration_v1` 与 `wl_shm` 双缓冲脏区回溯同步,不依赖 `winit`);
6//! - [`winit`](`std`):提供跨桌面宿主窗口的事件驱动调试平台 [`winit::WinitPlatform`];
7//! - [`mobile`] / [`android`] / [`ios`] / [`harmony`]:提供移动端触控、安全区、IME 与原生窗口生命周期桥接;
8//! - [`web`]:提供 WebAssembly HTML5 Canvas 像素输出与脏区上报平台。
9
10use core::future::Future;
11use core::time::Duration;
12
13use crate::engine::VeloxEngine;
14
15pub mod clipboard;
16pub mod mobile;
17pub mod testing;
18pub mod web;
19
20pub use clipboard::{clipboard_has_text, clipboard_read_into, clipboard_write_text};
21pub use clipboard::clipboard_read_text;
22
23pub mod a11y_bridge;
24pub mod android;
25pub mod embed_ffi;
26pub mod harmony;
27pub mod ios;
28pub mod os_integration;
29pub mod shm_driver;
30pub mod wayland;
31pub mod winit;
32
33
34pub use crate::renderers::RepaintBufferType;
35
36/// 桌面与移动端平台默认及可选渲染后端类型。
37///
38/// - 桌面端([`winit::WinitPlatform`] / [`wayland::WaylandPlatform`])与移动端([`mobile::MobileEmbedApp`])默认采用自研轻量级 `wgpu` 2D SDF GPU 渲染器([`DesktopRenderBackend::Wgpu`],跨平台统一驱动 Windows D3D12、macOS/iOS Metal、Linux/Android/HarmonyOS Vulkan);
39/// - 轻量化与受限显示环境可使用内置零外部依赖 SDF 扫描线软件渲染器([`DesktopRenderBackend::Software`])。
40#[derive(Copy, Clone, PartialEq, Eq, Debug)]
41pub enum DesktopRenderBackend {
42    /// 自研轻量级 `wgpu` 2D SDF GPU 硬件加速后端(Windows D3D12 / macOS & iOS Metal / Linux & Android Vulkan)。
43    Wgpu,
44    /// 多线程按水平条带并行的 SDF 扫描线软件渲染后端。
45    Software,
46}
47
48impl DesktopRenderBackend {
49    /// 返回桌面与移动端平台的默认渲染后端:
50    /// - 若启用了 `gpu`(默认开启),选择 [`DesktopRenderBackend::Wgpu`];
51    /// - 否则回退至内置 [`DesktopRenderBackend::Software`]。
52    #[inline(always)]
53    pub const fn default_desktop() -> Self {
54        #[cfg(feature = "gpu")]
55        {
56            Self::Wgpu
57        }
58        #[cfg(not(feature = "gpu"))]
59        {
60            Self::Software
61        }
62    }
63
64    /// 判断当前后端是否为 GPU 硬件加速后端。
65    #[inline(always)]
66    pub const fn is_gpu(self) -> bool {
67        matches!(self, Self::Wgpu)
68    }
69}
70
71impl Default for DesktopRenderBackend {
72    #[inline(always)]
73    fn default() -> Self {
74        Self::default_desktop()
75    }
76}
77
78/// 平台事件循环控制流状态。
79#[derive(Copy, Clone, PartialEq, Eq, Debug)]
80pub enum PlatformControlFlow {
81    /// 存在进行中的过渡动画或待处理事件,下一帧继续立即轮询。
82    Poll,
83    /// 界面处于完全静止状态(`!engine.needs_redraw()`),平台可进入 `WFI` 中断休眠或阻塞等待输入,实现 0% CPU 占用。
84    Wait,
85    /// 退出平台事件循环。
86    Exit,
87}
88
89/// 单帧平台表面刷新统计报告。
90#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
91pub struct FlushReport {
92    /// 本帧合并提交的脏矩形数量(`0` 表示静止帧未触发重绘)。
93    pub dirty_regions: usize,
94    /// 本帧传输的条带数(MCU 模式)或提交的共享内存缓冲区数(Winit/Wayland/KMS/桌面模式)。
95    pub strips_or_buffers: usize,
96    /// 本帧实际光栅化并刷新的像素总数。
97    pub pixels_updated: usize,
98    /// 本帧瞬态内存池(`ScratchArena`)触及的峰值占用字节数。
99    pub arena_peak_bytes: usize,
100    /// 本帧 `ScratchArena` 发生静默字符串截断或临时切片空降级的次数(非 0 说明竞技场容量紧张)。
101    pub arena_truncations: u32,
102}
103
104impl FlushReport {
105    /// 编译期空刷新报告常量(供 `const fn` 平台构造器使用)。
106    #[inline(always)]
107    pub const fn const_empty() -> Self {
108        Self {
109            dirty_regions: 0,
110            strips_or_buffers: 0,
111            pixels_updated: 0,
112            arena_peak_bytes: 0,
113            arena_truncations: 0,
114        }
115    }
116
117    /// 构造并自动附加来自 [`VeloxEngine`] 的 `ScratchArena` 峰值水位与静默截断遥测。
118    #[inline(always)]
119    pub fn with_engine(
120        dirty_regions: usize,
121        strips_or_buffers: usize,
122        pixels_updated: usize,
123        engine: &VeloxEngine,
124    ) -> Self {
125        Self {
126            dirty_regions,
127            strips_or_buffers,
128            pixels_updated,
129            arena_peak_bytes: engine.last_arena_peak_bytes(),
130            arena_truncations: engine.last_arena_truncations(),
131        }
132    }
133
134    /// 本帧是否发生了实际像素重绘。
135    #[inline(always)]
136    pub const fn has_updates(&self) -> bool {
137        self.dirty_regions > 0
138    }
139}
140
141/// 平台显示表面抽象。
142///
143/// 负责将 [`VeloxEngine`] 求解出的脏矩形区域桥接至底层显示设备
144/// (如 Winit/Wayland 双缓冲表面、移动端图形表面、Web Canvas 或外部自定义显示驱动)。
145pub trait PlatformSurface {
146    /// 获取当前显示表面的逻辑宽高 `(width, height)`。
147    fn surface_size(&self) -> (i16, i16);
148
149    /// 按给定时间步长 `dt_ms`(毫秒)推进一帧 [`VeloxEngine`] 并刷新所有脏区到显示设备。
150    fn flush_frame_dt(&mut self, engine: &mut VeloxEngine, dt_ms: u16) -> FlushReport;
151
152    /// 以默认 60FPS(`16ms`)步长执行一帧刷新。
153    #[inline]
154    fn flush_frame(&mut self, engine: &mut VeloxEngine) -> FlushReport {
155        self.flush_frame_dt(engine, 16)
156    }
157}
158
159/// 核心平台抽象接口。
160///
161/// 负责提供单调时钟源、平台输入事件收集、显示表面刷屏以及主事件循环调度。
162pub trait Platform {
163    /// 返回自平台启动以来的单调递增时长(桌面端默认由 `Instant` 提供)。
164    fn duration_since_start(&self) -> Duration {
165        Duration::ZERO
166    }
167
168    /// 单步执行一次平台事件采集、状态更新与按需脏区刷屏,返回下一次循环的 [`PlatformControlFlow`] 调度策略。
169    fn step_platform(&mut self, engine: &mut VeloxEngine, dt_ms: u16) -> PlatformControlFlow;
170
171    /// 启动平台主事件循环,接管 [`VeloxEngine`] 直至收到 [`PlatformControlFlow::Exit`]。
172    fn run_event_loop(mut self, mut engine: VeloxEngine)
173    where
174        Self: Sized,
175    {
176        let mut last_tick = std::time::Instant::now();
177        loop {
178            let dt_ms = {
179                let now = std::time::Instant::now();
180                let elapsed = now.duration_since(last_tick).as_millis();
181                last_tick = now;
182                elapsed.clamp(1, 100) as u16
183            };
184
185            match self.step_platform(&mut engine, dt_ms) {
186                PlatformControlFlow::Poll => {
187                    {
188                        let frame_budget = Duration::from_millis(16);
189                        let spent = last_tick.elapsed();
190                        if spent < frame_budget {
191                            std::thread::sleep(frame_budget - spent);
192                        }
193                    }
194                }
195                PlatformControlFlow::Wait => {
196                    std::thread::sleep(Duration::from_millis(16));
197                }
198                PlatformControlFlow::Exit => break,
199            }
200        }
201    }
202}
203
204/// 面向异步运行时的平台显示表面抽象(非阻塞异步帧刷新)。
205pub trait AsyncPlatformSurface {
206    /// 获取当前显示表面的逻辑宽高 `(width, height)`。
207    fn surface_size(&self) -> (i16, i16);
208
209    /// 按给定时间步长 `dt_ms`(毫秒)异步推进一帧 [`VeloxEngine`] 并刷新所有脏区。
210    fn flush_frame_dt_async(
211        &mut self,
212        engine: &mut VeloxEngine,
213        dt_ms: u16,
214    ) -> impl Future<Output = FlushReport>;
215
216    /// 以默认 60FPS(`16ms`)步长异步执行一帧刷新。
217    fn flush_frame_async(&mut self, engine: &mut VeloxEngine) -> impl Future<Output = FlushReport> {
218        self.flush_frame_dt_async(engine, 16)
219    }
220}
221
222/// 面向异步执行器的核心平台抽象接口(零忙等阻塞,帧刷新与空闲等待全程 `.await` 让出执行权)。
223pub trait AsyncPlatform {
224    /// 返回自平台启动以来的单调递增时长。
225    fn duration_since_start(&self) -> Duration {
226        Duration::ZERO
227    }
228
229    /// 异步单步执行一次平台事件采集、状态更新与非阻塞 DMA 脏区刷屏,返回下一次循环的 [`PlatformControlFlow`]。
230    fn step_platform_async(
231        &mut self,
232        engine: &mut VeloxEngine,
233        dt_ms: u16,
234    ) -> impl Future<Output = PlatformControlFlow>;
235}