Skip to main content

velox_engine/platform/
web.rs

1//! WebAssembly (`wasm32-unknown-unknown`) 与 HTML5 `<canvas>` 平台后端。
2//!
3//! 设计特点:
4//! - **零外部 JS 框架/DOM 树同步开销**:在 WebAssembly 线性内存中直接维护 `Rgba8888` 像素帧缓冲与脏矩形列表;
5//! - **增量脏矩形 `putImageData` 提交**:浏览器 `requestAnimationFrame` 仅在 `dirty_rects_count > 0` 时调用
6//!   `ctx.putImageData(imageData, 0, 0, rect.x, rect.y, rect.w, rect.h)` 局部刷新变化区域;
7//! - **完整支持桌面与移动 Web 浏览器交互**:统一桥接 `PointerEvent`、触摸滚动、`WheelEvent`、键盘导航、
8//!   浏览器历史后退 (`popstate` -> `InputEvent::NavigateBack`) 与 `env(safe-area-inset-*)`。
9
10use std::vec;
11use std::vec::Vec;
12
13use crate::arena::SmallVec;
14use crate::display::Rgba8888;
15use crate::engine::VeloxEngine;
16use crate::platform::mobile::CDirtyRect;
17use crate::platform::testing::TestingPlatform;
18use crate::solver::Region;
19
20/// `#![no_std]` 固定分辨率 WebAssembly `<canvas>` 平台宿主(默认 `320x240`,动态或高分辨率建议使用 [`WebCanvasApp`])。
21///
22/// 统一复用泛型 [`TestingPlatform<W, H, Rgba8888>`]。
23pub type WebPlatform<const W: usize = 320, const H: usize = 240> =
24    TestingPlatform<W, H, Rgba8888>;
25
26/// 面向自适应网页窗口的动态分辨率 WebAssembly `<canvas>` 应用实例。
27pub struct WebCanvasApp {
28    pub engine: VeloxEngine,
29    width: i16,
30    height: i16,
31    dpi_scale: i16,
32    framebuffer: Vec<Rgba8888>,
33    dirty_rects: Vec<CDirtyRect>,
34}
35
36impl WebCanvasApp {
37    /// 创建指定初始画布宽高 `(width, height)` 的 WebAssembly 应用宿主。
38    pub fn new(width: i16, height: i16) -> Self {
39        let w = width.max(1);
40        let h = height.max(1);
41        Self {
42            engine: VeloxEngine::new(w, h),
43            width: w,
44            height: h,
45            dpi_scale: 1,
46            framebuffer: vec![Rgba8888(0); (w as usize) * (h as usize)],
47            dirty_rects: Vec::with_capacity(8),
48        }
49    }
50
51    /// 设置物理像素 HiDPI 缩放倍率(如 Retina `2x` / `3x`),布局与点击事件保持逻辑坐标 `(width, height)`。
52    pub fn set_dpi_scale(&mut self, scale: i16) {
53        let s = scale.clamp(1, 4);
54        if s != self.dpi_scale {
55            self.dpi_scale = s;
56            self.engine.set_dpi_scale(s);
57            let pw = (self.width as usize) * (s as usize);
58            let ph = (self.height as usize) * (s as usize);
59            self.framebuffer.resize(pw * ph, Rgba8888(0));
60            self.engine.resize(self.width, self.height);
61        }
62    }
63
64    /// 获取当前 HiDPI 缩放倍率。
65    #[inline(always)]
66    pub const fn dpi_scale(&self) -> i16 {
67        self.dpi_scale
68    }
69
70    /// 响应浏览器 `ResizeObserver` 或 `window.onresize` 动态调整画布分辨率。
71    pub fn resize(&mut self, width: i16, height: i16) {
72        let w = width.max(1);
73        let h = height.max(1);
74        if w != self.width || h != self.height {
75            self.width = w;
76            self.height = h;
77            let pw = (w as usize) * (self.dpi_scale as usize);
78            let ph = (h as usize) * (self.dpi_scale as usize);
79            self.framebuffer.resize(pw * ph, Rgba8888(0));
80            self.engine.resize(w, h);
81        }
82    }
83
84    /// 同步浏览器 `env(safe-area-inset-*)` 安全区边距。
85    pub fn set_safe_area(&mut self, top: i16, right: i16, bottom: i16, left: i16) {
86        self.engine
87            .set_safe_area(crate::pod::SafeAreaInsets::new(top, right, bottom, left));
88    }
89
90    /// 注入 Web 宿主唤醒回调(例如 `queueMicrotask` / `requestAnimationFrame` 触发器)。
91    pub fn set_async_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
92        self.engine.set_async_waker(waker);
93    }
94
95    /// 排空浏览器主线程中所有已就绪的前景异步协程与 `defer` 回调。
96    #[inline]
97    pub fn poll_async_tasks(&mut self) -> bool {
98        self.engine.poll_async_tasks()
99    }
100
101    /// 是否存在待重绘脏视图、动画或已就绪异步任务(用于决定浏览器是否按需暂停 `requestAnimationFrame`)。
102    #[inline]
103    pub fn needs_redraw(&self) -> bool {
104        self.engine.needs_redraw()
105    }
106
107    /// 推进一帧渲染并光栅化所有脏矩形,返回本帧脏矩形个数。
108    pub fn step_frame(&mut self, dt_ms: u16) -> usize {
109        self.dirty_rects.clear();
110        let s = self.dpi_scale.max(1);
111        let mut regions: SmallVec<Region, 8> = SmallVec::new();
112        for &r in self.engine.step_frame_dt(dt_ms) {
113            regions.push(r);
114        }
115        for &reg in regions.as_slice() {
116            self.engine
117                .rasterize_region(reg, self.framebuffer.as_mut_slice());
118            self.dirty_rects.push(CDirtyRect {
119                x: reg.x.saturating_mul(s),
120                y: reg.y.saturating_mul(s),
121                w: reg.w.saturating_mul(s),
122                h: reg.h.saturating_mul(s),
123            });
124        }
125        self.dirty_rects.len()
126    }
127
128    /// 获取供浏览器 `ImageData` 零拷贝读取的 `RGBA8888` 字节切片。
129    #[inline(always)]
130    pub fn rgba_bytes(&self) -> &[u8] {
131        unsafe {
132            core::slice::from_raw_parts(
133                self.framebuffer.as_ptr() as *const u8,
134                self.framebuffer.len() * 4,
135            )
136        }
137    }
138
139    /// 获取本帧脏矩形切片。
140    #[inline(always)]
141    pub fn dirty_rects(&self) -> &[CDirtyRect] {
142        self.dirty_rects.as_slice()
143    }
144
145    /// 获取当前指针下方组件要求的鼠标光标形状(供 `<canvas>` 实时同步 `canvas.style.cursor`)。
146    #[inline]
147    pub fn cursor_shape(&self) -> crate::pod::CursorShape {
148        self.engine.cursor_shape()
149    }
150
151    /// 获取当前鼠标光标对应的标准 CSS `cursor` 字符串。
152    #[inline]
153    pub fn cursor_css(&self) -> &'static str {
154        self.engine.cursor_shape().as_css_str()
155    }
156}
157
158/// 生成可直接由浏览器加载的 HTML5 `<canvas>` 宿主页面代码。
159pub fn generate_web_index_html(wasm_url: &str, width: u16, height: u16) -> std::string::String {
160    std::format!(
161        r#"<!DOCTYPE html>
162<html lang="zh-CN">
163<head>
164  <meta charset="utf-8" />
165  <meta name="viewport" content="width=device-width,initial-scale=1" />
166  <link rel="icon" href="data:," />
167  <title>Velox WebAssembly Application</title>
168  <style>
169    html, body {{ margin: 0; padding: 0; background: #0b0f17; display: flex; justify-content: center; align-items: center; height: 100vh; font-family: system-ui, sans-serif; }}
170    canvas {{ width: {width}px; height: {height}px; border-radius: 12px; box-shadow: 0 16px 40px rgba(0,0,0,0.5); touch-action: none; }}
171  </style>
172</head>
173<body>
174  <canvas id="velox-canvas" width="{width}" height="{height}"></canvas>
175  <script type="module">
176{WEB_CANVAS_BOOTSTRAP_JS}
177    mountVeloxCanvas("{wasm_url}", document.getElementById("velox-canvas"), "velox_wasm_app_init");
178  </script>
179</body>
180</html>"#
181    )
182}
183
184/// 为指定业务视图类型一键导出完整的 WebAssembly `<canvas>` C ABI (`velox_wasm_app_init` / `velox_web_app_*`) 符号。
185#[macro_export]
186macro_rules! export_web_app {
187    ($app_ty:ty) => {
188        #[unsafe(no_mangle)]
189        pub extern "C" fn velox_wasm_app_init(
190            width: i16,
191            height: i16,
192        ) -> *mut $crate::platform::web::WebCanvasApp {
193            let mut app = $crate::platform::web::WebCanvasApp::new(width, height);
194            let _ = app.engine.mount_root(<$app_ty as Default>::default());
195            std::boxed::Box::into_raw(std::boxed::Box::new(app))
196        }
197
198        #[unsafe(no_mangle)]
199        pub unsafe extern "C" fn velox_web_app_destroy(
200            app: *mut $crate::platform::web::WebCanvasApp,
201        ) {
202            if !app.is_null() {
203                unsafe {
204                    drop(std::boxed::Box::from_raw(app));
205                }
206            }
207        }
208
209        #[unsafe(no_mangle)]
210        pub unsafe extern "C" fn velox_web_app_resize(
211            app: *mut $crate::platform::web::WebCanvasApp,
212            width: i16,
213            height: i16,
214        ) {
215            if let Some(app_ref) = unsafe { app.as_mut() } {
216                app_ref.resize(width, height);
217            }
218        }
219
220        #[unsafe(no_mangle)]
221        pub unsafe extern "C" fn velox_web_app_set_dpi_scale(
222            app: *mut $crate::platform::web::WebCanvasApp,
223            scale: i16,
224        ) {
225            if let Some(app_ref) = unsafe { app.as_mut() } {
226                app_ref.set_dpi_scale(scale);
227            }
228        }
229
230        #[unsafe(no_mangle)]
231        pub unsafe extern "C" fn velox_web_app_set_safe_area(
232            app: *mut $crate::platform::web::WebCanvasApp,
233            top: i16,
234            right: i16,
235            bottom: i16,
236            left: i16,
237        ) {
238            if let Some(app_ref) = unsafe { app.as_mut() } {
239                app_ref.set_safe_area(top, right, bottom, left);
240            }
241        }
242
243        #[unsafe(no_mangle)]
244        pub unsafe extern "C" fn velox_web_app_pointer_kind(
245            app: *mut $crate::platform::web::WebCanvasApp,
246            pointer_kind: u8,
247        ) {
248            if let Some(app_ref) = unsafe { app.as_mut() } {
249                let kind = match pointer_kind {
250                    0 => $crate::pod::PointerKind::Touch,
251                    2 => $crate::pod::PointerKind::Pen,
252                    _ => $crate::pod::PointerKind::Mouse,
253                };
254                app_ref.engine.set_pointer_kind(kind);
255            }
256        }
257
258        #[unsafe(no_mangle)]
259        pub unsafe extern "C" fn velox_web_app_pointer_event(
260            app: *mut $crate::platform::web::WebCanvasApp,
261            kind: u8,
262            x: i16,
263            y: i16,
264        ) {
265            if let Some(app_ref) = unsafe { app.as_mut() } {
266                let ev = match kind {
267                    0 => $crate::pod::InputEvent::PointerDown { x, y },
268                    1 => $crate::pod::InputEvent::PointerMove { x, y },
269                    2 => $crate::pod::InputEvent::PointerUp { x, y },
270                    _ => $crate::pod::InputEvent::PointerCancel,
271                };
272                app_ref.engine.dispatch_event(ev);
273            }
274        }
275
276        #[unsafe(no_mangle)]
277        pub unsafe extern "C" fn velox_web_app_wheel_event(
278            app: *mut $crate::platform::web::WebCanvasApp,
279            x: i16,
280            y: i16,
281            delta_y: i16,
282        ) {
283            if let Some(app_ref) = unsafe { app.as_mut() } {
284                app_ref
285                    .engine
286                    .dispatch_event($crate::pod::InputEvent::Scroll { x, y, delta_y });
287            }
288        }
289
290        #[unsafe(no_mangle)]
291        pub unsafe extern "C" fn velox_web_app_popstate_back(
292            app: *mut $crate::platform::web::WebCanvasApp,
293        ) -> bool {
294            if let Some(app_ref) = unsafe { app.as_mut() } {
295                app_ref.engine.dispatch_navigate_back()
296            } else {
297                false
298            }
299        }
300
301        #[unsafe(no_mangle)]
302        pub unsafe extern "C" fn velox_web_app_step_frame(
303            app: *mut $crate::platform::web::WebCanvasApp,
304            dt_ms: u16,
305        ) -> usize {
306            if let Some(app_ref) = unsafe { app.as_mut() } {
307                app_ref.step_frame(dt_ms)
308            } else {
309                0
310            }
311        }
312
313        #[unsafe(no_mangle)]
314        pub unsafe extern "C" fn velox_web_app_rgba_ptr(
315            app: *const $crate::platform::web::WebCanvasApp,
316        ) -> *const u8 {
317            if let Some(app_ref) = unsafe { app.as_ref() } {
318                app_ref.rgba_bytes().as_ptr()
319            } else {
320                core::ptr::null()
321            }
322        }
323
324        #[unsafe(no_mangle)]
325        pub unsafe extern "C" fn velox_web_app_rgba_byte_len(
326            app: *const $crate::platform::web::WebCanvasApp,
327        ) -> usize {
328            if let Some(app_ref) = unsafe { app.as_ref() } {
329                app_ref.rgba_bytes().len()
330            } else {
331                0
332            }
333        }
334
335        #[unsafe(no_mangle)]
336        pub unsafe extern "C" fn velox_web_app_dirty_rects_ptr(
337            app: *const $crate::platform::web::WebCanvasApp,
338        ) -> *const $crate::platform::mobile::CDirtyRect {
339            if let Some(app_ref) = unsafe { app.as_ref() } {
340                app_ref.dirty_rects().as_ptr()
341            } else {
342                core::ptr::null()
343            }
344        }
345
346        #[unsafe(no_mangle)]
347        pub unsafe extern "C" fn velox_web_app_dirty_rects_count(
348            app: *const $crate::platform::web::WebCanvasApp,
349        ) -> usize {
350            if let Some(app_ref) = unsafe { app.as_ref() } {
351                app_ref.dirty_rects().len()
352            } else {
353                0
354            }
355        }
356    };
357}
358
359/// 浏览器端加载 `.wasm` 并绑定 `<canvas>` 增量脏矩形渲染与指针事件的最小 JS 引导脚本。
360pub const WEB_CANVAS_BOOTSTRAP_JS: &str = r#"
361function unwrapCoreWasm(u8) {
362  if (u8[4] === 1) return u8;
363  let pos = 8;
364  while (pos < u8.length) {
365    const secId = u8[pos++];
366    let len = 0, shift = 0;
367    while (pos < u8.length) {
368      const b = u8[pos++];
369      len |= (b & 0x7f) << shift;
370      if ((b & 0x80) === 0) break;
371      shift += 7;
372    }
373    if (secId === 1 && u8[pos] === 0x00 && u8[pos + 1] === 0x61 && u8[pos + 2] === 0x73 && u8[pos + 3] === 0x6d && u8[pos + 4] === 0x01) {
374      return u8.subarray(pos, pos + len);
375    }
376    pos += len;
377  }
378  return u8;
379}
380
381export async function mountVeloxCanvas(wasmUrl, canvas, createAppExport = "velox_wasm_app_init") {
382  const wasiStub = new Proxy({}, { get: () => new Proxy({}, { get: () => () => 0 }) });
383  const sep = wasmUrl.includes("?") ? "&" : "?";
384  const resp = await fetch(`${wasmUrl}${sep}_t=${Date.now()}`, { cache: "no-store" });
385  const rawBytes = new Uint8Array(await resp.arrayBuffer());
386  const coreBytes = unwrapCoreWasm(rawBytes);
387  const { instance } = await WebAssembly.instantiate(coreBytes, wasiStub);
388  const exports = instance.exports;
389  const rect = canvas.getBoundingClientRect();
390  const logicalW = (rect.width | 0) || canvas.width;
391  const logicalH = (rect.height | 0) || canvas.height;
392  const dpr = Math.min(3, Math.max(1, Math.round(window.devicePixelRatio || 1)));
393  canvas.width = logicalW * dpr;
394  canvas.height = logicalH * dpr;
395  const app = exports[createAppExport](logicalW, logicalH);
396  if (typeof exports.velox_web_app_set_dpi_scale === "function" && dpr > 1) {
397    exports.velox_web_app_set_dpi_scale(app, dpr);
398  }
399  const ctx = canvas.getContext("2d");
400
401  canvas.addEventListener("pointerdown", e => {
402    if (typeof exports.velox_web_app_pointer_kind === "function") {
403      const pk = e.pointerType === "touch" ? 0 : (e.pointerType === "pen" ? 2 : 1);
404      exports.velox_web_app_pointer_kind(app, pk);
405    }
406    exports.velox_web_app_pointer_event(app, 0, e.offsetX | 0, e.offsetY | 0);
407  });
408  canvas.addEventListener("pointermove", e => exports.velox_web_app_pointer_event(app, 1, e.offsetX | 0, e.offsetY | 0));
409  canvas.addEventListener("pointerup", e => exports.velox_web_app_pointer_event(app, 2, e.offsetX | 0, e.offsetY | 0));
410  canvas.addEventListener("pointercancel", e => exports.velox_web_app_pointer_event(app, 3, 0, 0));
411  canvas.addEventListener("wheel", e => {
412    e.preventDefault();
413    exports.velox_web_app_wheel_event(app, e.offsetX | 0, e.offsetY | 0, (-e.deltaY * 0.5) | 0);
414  }, { passive: false });
415  window.addEventListener("popstate", () => exports.velox_web_app_popstate_back(app));
416
417  let lastTs = performance.now();
418  function tick(now) {
419    const dt = Math.min(100, Math.max(1, (now - lastTs) | 0));
420    lastTs = now;
421    const dirtyCount = exports.velox_web_app_step_frame(app, dt);
422    if (dirtyCount > 0) {
423      const w = canvas.width, h = canvas.height;
424      const rgbaPtr = exports.velox_web_app_rgba_ptr(app);
425      const rgbaLen = exports.velox_web_app_rgba_byte_len(app);
426      const img = new ImageData(new Uint8ClampedArray(exports.memory.buffer, rgbaPtr, rgbaLen), w, h);
427      const dirtyPtr = exports.velox_web_app_dirty_rects_ptr(app);
428      const rects = new Int16Array(exports.memory.buffer, dirtyPtr, dirtyCount * 4);
429      for (let i = 0; i < dirtyCount; i++) {
430        const x = rects[i * 4], y = rects[i * 4 + 1], rw = rects[i * 4 + 2], rh = rects[i * 4 + 3];
431        ctx.putImageData(img, 0, 0, x, y, rw, rh);
432      }
433    }
434    requestAnimationFrame(tick);
435  }
436  requestAnimationFrame(tick);
437  return { app, exports };
438}
439"#;
440
441/// WebAssembly 浏览器硬件渲染后端偏好(WebGPU 优先,自动回退 WebGL2 或 Canvas 2D 软光栅)。
442#[repr(u8)]
443#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
444pub enum WebGpuBackendPreference {
445    #[default]
446    WebGpuFirst = 0,
447    WebGl2Only = 1,
448    Software2dFallback = 2,
449}
450
451/// 面向浏览器 WebGPU / WebGL2 硬件直出的 `<canvas>` 宿主控制器(与软件 [`WebCanvasApp`] 并行)。
452pub struct WebGpuCanvasHost {
453    pub engine: VeloxEngine,
454    logical_width: i16,
455    logical_height: i16,
456    device_pixel_ratio: f32,
457    preference: WebGpuBackendPreference,
458    gpu_active: bool,
459}
460
461impl WebGpuCanvasHost {
462    pub fn new(
463        logical_width: i16,
464        logical_height: i16,
465        device_pixel_ratio: f32,
466        preference: WebGpuBackendPreference,
467    ) -> Self {
468        let w = logical_width.max(1);
469        let h = logical_height.max(1);
470        let dpr = device_pixel_ratio.clamp(0.5, 4.0);
471        let mut engine = VeloxEngine::new(w, h);
472        engine.set_scale_factor(dpr);
473        Self {
474            engine,
475            logical_width: w,
476            logical_height: h,
477            device_pixel_ratio: dpr,
478            preference,
479            gpu_active: preference != WebGpuBackendPreference::Software2dFallback,
480        }
481    }
482
483    #[inline]
484    pub const fn physical_size(&self) -> (u32, u32) {
485        let pw = ((self.logical_width as f32) * self.device_pixel_ratio) as u32;
486        let ph = ((self.logical_height as f32) * self.device_pixel_ratio) as u32;
487        (if pw < 1 { 1 } else { pw }, if ph < 1 { 1 } else { ph })
488    }
489
490    #[inline]
491    pub const fn preference(&self) -> WebGpuBackendPreference {
492        self.preference
493    }
494
495    #[inline]
496    pub const fn is_gpu_active(&self) -> bool {
497        self.gpu_active
498    }
499
500    pub fn resize(&mut self, logical_width: i16, logical_height: i16, device_pixel_ratio: f32) {
501        self.logical_width = logical_width.max(1);
502        self.logical_height = logical_height.max(1);
503        self.device_pixel_ratio = device_pixel_ratio.clamp(0.5, 4.0);
504        self.engine.set_scale_factor(self.device_pixel_ratio);
505        self.engine.resize(self.logical_width, self.logical_height);
506    }
507
508    /// 步进一帧逻辑并返回是否存在脏区需要驱动 WebGPU/WebGL2 `WgpuRenderer::render_to_view`。
509    pub fn step_needs_present(&mut self, dt_ms: u16) -> bool {
510        !self.engine.step_frame_dt(dt_ms).is_empty()
511    }
512}
513
514/// WebGPU / WebGL2 硬件直出前端桥接脚本模板(探测 `navigator.gpu` 并在无 WebGPU 环境优雅降级)。
515pub const WEBGPU_HOST_JS_BRIDGE: &str = r#"// Velox WebGPU / WebGL2 Hardware Surface Bridge
516export async function mountVeloxWebGpu(canvas, wasmUrl) {
517  const hasWebGpu = typeof navigator !== "undefined" && "gpu" in navigator;
518  const dpr = Math.min(4, Math.max(1, window.devicePixelRatio || 1));
519  canvas.width = Math.max(1, Math.round(canvas.clientWidth * dpr));
520  canvas.height = Math.max(1, Math.round(canvas.clientHeight * dpr));
521  const { instance } = await WebAssembly.instantiateStreaming(fetch(wasmUrl), {});
522  const exports = instance.exports;
523  const app = exports.velox_webgpu_app_new(canvas.clientWidth | 0, canvas.clientHeight | 0, dpr, hasWebGpu ? 0 : 1);
524  return { app, exports, backend: hasWebGpu ? "webgpu" : "webgl2" };
525}
526"#;