Skip to main content

velox_engine/async_rt/
scheduler.rs

1//! 通用异步调度器抽象与异步事件循环驱动器。
2//!
3//! 本模块作为 Velox 框架与各类异步调度器之间的隔离层:
4//! 可由 `StdAsyncDriver`、[`ManualScheduler`](super::ManualScheduler) 或 `Tokio` / `smol` 适配器无缝接入 [`run_async_event_loop`]。
5
6use core::future::Future;
7use core::pin::Pin;
8use core::task::{Context, Poll};
9use core::time::Duration;
10
11use crate::engine::VeloxEngine;
12use crate::platform::{AsyncPlatform, PlatformControlFlow};
13
14/// 调度器能力描述符(用于诊断与运行时策略探测)。
15#[derive(Copy, Clone, PartialEq, Eq, Debug)]
16pub struct SchedulerCapabilities {
17    /// 调度器名称(如 `"velox-native-std"`、`"velox-manual"`、`"tokio"`、`"smol"`)。
18    pub name: &'static str,
19    /// 是否支持独立后台工作线程卸载(单线程 / WASM 为 `false`,桌面多线程为 `true`)。
20    pub supports_background_threads: bool,
21    /// 是否支持在事件回调中动态派生异步协程。
22    pub supports_dynamic_spawn: bool,
23    /// 是否采用可控确定性虚拟时钟(用于单元测试与时间快进)。
24    pub deterministic_clock: bool,
25}
26
27/// 主动向当前异步执行器让出一次调度片的 [`Future`]。
28///
29/// 在单线程协作式调度器(如 `LocalSet`)中,可防止连续动画渲染饿死同线程其他异步任务。
30#[derive(Default)]
31pub struct YieldNow {
32    yielded: bool,
33}
34
35impl YieldNow {
36    /// 创建一个单次让出调度片的 [`YieldNow`] Future。
37    #[inline(always)]
38    pub const fn new() -> Self {
39        Self { yielded: false }
40    }
41}
42
43impl Unpin for YieldNow {}
44
45impl Future for YieldNow {
46    type Output = ();
47
48    #[inline]
49    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
50        if self.yielded {
51            Poll::Ready(())
52        } else {
53            self.yielded = true;
54            cx.waker().wake_by_ref();
55            Poll::Pending
56        }
57    }
58}
59
60/// 单调时钟与非阻塞睡眠抽象。
61///
62/// 隔离框架核心与底层时钟源:
63/// - 在桌面/移动端由默认原生调度器或第三方运行时(如 Tokio / smol)提供;
64/// - 在单元测试中由确定性虚拟时钟提供 0ms 瞬时快进能力。
65pub trait SchedulerClock {
66    /// 返回单调递增的当前时间戳(毫秒)。
67    fn now_ms(&self) -> u64;
68
69    /// 非阻塞异步等待指定时长 `duration`。
70    fn sleep(&self, duration: Duration) -> impl Future<Output = ()>;
71}
72
73/// 异步主循环调度器抽象(面向 Tokio / smol / Std / 自定义测试宿主)。
74///
75/// 将 [`AsyncPlatform`] 与具体执行器彻底解耦:
76/// - 活跃渲染期间:按 [`AsyncLoopConfig::frame_interval`] 节流,并在渲染超时时调用 [`Self::yield_now`] 让出调度片;
77/// - 画面静止期间([`PlatformControlFlow::Wait`]):挂起在 [`Self::wait_for_event`] 上,实现 0% CPU 占用。
78pub trait AsyncDriver: SchedulerClock {
79    /// 返回当前调度器的能力元信息。
80    fn capabilities(&self) -> SchedulerCapabilities;
81
82    /// 当画面静止(`PlatformControlFlow::Wait`)时挂起等待外部事件(输入事件、后台异步完成等)唤醒。
83    ///
84    /// 实现方应保证黏性(latched)唤醒语义(例如 `UiWakeSignal`),避免在进入 `wait_for_event` 前夕触发的唤醒丢失。
85    fn wait_for_event(&self) -> impl Future<Output = ()>;
86
87    /// 主动向当前异步执行器让出一次调度片。
88    #[inline]
89    fn yield_now(&self) -> impl Future<Output = ()> {
90        YieldNow::new()
91    }
92}
93
94/// 通用异步事件循环配置参数。
95#[derive(Copy, Clone, PartialEq, Eq, Debug)]
96pub struct AsyncLoopConfig {
97    /// 活跃帧期间的目标刷新间隔(默认 `16ms` 对应 60Hz;`Duration::ZERO` 表示每帧仅 `yield_now`)。
98    pub frame_interval: Duration,
99    /// 可选最大步进帧数上限(`None` 表示持续运行至 `PlatformControlFlow::Exit`)。
100    pub max_steps: Option<u32>,
101    /// 当画面首次进入 `PlatformControlFlow::Wait` 空闲态时是否直接退出循环(默认 `false`:挂起等待唤醒)。
102    pub exit_on_idle: bool,
103}
104
105impl Default for AsyncLoopConfig {
106    #[inline(always)]
107    fn default() -> Self {
108        Self {
109            frame_interval: Duration::from_millis(16),
110            max_steps: None,
111            exit_on_idle: false,
112        }
113    }
114}
115
116impl AsyncLoopConfig {
117    /// 以指定目标帧间隔创建持续运行的异步事件循环配置。
118    #[inline(always)]
119    pub const fn new(frame_interval: Duration) -> Self {
120        Self {
121            frame_interval,
122            max_steps: None,
123            exit_on_idle: false,
124        }
125    }
126
127    /// 设置最大步进帧数上限(常用于测试与确定性演练)。
128    #[inline(always)]
129    pub const fn with_max_steps(mut self, max_steps: u32) -> Self {
130        self.max_steps = Some(max_steps);
131        self
132    }
133
134    /// 设置是否在首次静止(`PlatformControlFlow::Wait`)时立即退出循环。
135    #[inline(always)]
136    pub const fn with_exit_on_idle(mut self, exit_on_idle: bool) -> Self {
137        self.exit_on_idle = exit_on_idle;
138        self
139    }
140}
141
142/// [`run_async_event_loop`] 退出时返回的运行统计报告。
143#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
144pub struct AsyncLoopReport {
145    /// 累计执行的 `step_platform_async` 步数。
146    pub steps: u32,
147    /// 累计进入 `PlatformControlFlow::Wait` 空闲休眠(或空闲退出)的次数。
148    pub idle_waits: u32,
149    /// 循环退出前最后一次返回的控制流状态。
150    pub last_control_flow: Option<PlatformControlFlow>,
151}
152
153/// 跨调度器、全平台通用的异步主循环驱动函数。
154///
155/// 统一协调 [`AsyncPlatform`]、[`VeloxEngine`] 与可插拔 [`AsyncDriver`]:
156/// 1. 使用 [`SchedulerClock::now_ms`] 自动计算真实增量 `dt_ms`(钳位至 `1..=100` ms);
157/// 2. 异步调用 `platform.step_platform_async(engine, dt_ms).await`;
158/// 3. 返回 `Poll` 时按剩余帧预算 `driver.sleep(...).await` 或 `driver.yield_now().await`;
159/// 4. 返回 `Wait` 且无新增脏状态时,挂起在 `driver.wait_for_event().await` 进入 0% CPU 休眠;
160/// 5. 返回 `Exit` 或达到 `config.max_steps` 时干净退出并返回 [`AsyncLoopReport`]。
161pub async fn run_async_event_loop<P, D>(
162    platform: &mut P,
163    engine: &mut VeloxEngine,
164    driver: &D,
165    config: AsyncLoopConfig,
166) -> AsyncLoopReport
167where
168    P: AsyncPlatform,
169    D: AsyncDriver,
170{
171    let mut report = AsyncLoopReport::default();
172    let mut last_ms = driver.now_ms();
173    let frame_ms = config.frame_interval.as_millis().min(u64::MAX as u128) as u64;
174
175    loop {
176        if let Some(limit) = config.max_steps {
177            if report.steps >= limit {
178                break;
179            }
180        }
181
182        let step_start_ms = driver.now_ms();
183        let dt_ms = step_start_ms.saturating_sub(last_ms).clamp(1, 100) as u16;
184        last_ms = step_start_ms;
185
186        let flow = platform.step_platform_async(engine, dt_ms).await;
187        report.steps = report.steps.saturating_add(1);
188        report.last_control_flow = Some(flow);
189
190        match flow {
191            PlatformControlFlow::Exit => break,
192            PlatformControlFlow::Wait => {
193                // 若在步进末尾恰有异步事件或外设中断标脏,立即让出一次并继续下一帧,零延迟响应
194                if engine.needs_redraw() {
195                    driver.yield_now().await;
196                    continue;
197                }
198                report.idle_waits = report.idle_waits.saturating_add(1);
199                if config.exit_on_idle {
200                    break;
201                }
202                driver.wait_for_event().await;
203                last_ms = driver.now_ms();
204            }
205            PlatformControlFlow::Poll => {
206                let elapsed_ms = driver.now_ms().saturating_sub(step_start_ms);
207                if frame_ms > 0 && elapsed_ms < frame_ms {
208                    driver
209                        .sleep(Duration::from_millis(frame_ms - elapsed_ms))
210                        .await;
211                } else {
212                    driver.yield_now().await;
213                }
214            }
215        }
216    }
217
218    report
219}