The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
feat(runtime,webgpu): the native runtime and the webgpu renderer from doodlewind/ThreeRT-dev (#298)
Evan (Yifeng) Wang2a023a1e8337
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 2ba6ed4..7dbd7a0 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -29,6 +29,7 @@ jobs:physics: ${{ steps.paths.outputs.physics }}wasm: ${{ steps.paths.outputs.wasm }}web: ${{ steps.paths.outputs.web }}+ webgpu: ${{ steps.paths.outputs.webgpu }}steps:# Each job's inputs, as patterns on the paths a PR changes (the old and the new path of a rename). A change to the# workflows, a PR of 3,000 files or more (the most the API lists) and any event other than a PR run every job.@@ -68,6 +69,8 @@ jobs:# The browser module (renderer/web, on the engine's library) and tools/web-engine.ts: the module in Node with# the physics hello world's bundle (games/, packages/, the bundler's and the build's tools, the npm manifests).job web '^(renderer/|presets/|games/|packages/|tools/(web-engine\.ts|bundle-game\.ts|lib/)|package(-lock)?\.json$|rust-toolchain\.toml$)'+ # The native WebGPU renderer (webgpu/), shared runtime (runtime/), build CLI, and size/isolation gate.+ job webgpu '^(runtime/|webgpu/|tools/(build\.ts|check-webgpu-gate\.ts)|package(-lock)?\.json$|rust-toolchain\.toml$)'ts:name: "ts: typecheck, tests"@@ -214,9 +217,56 @@ jobs:# the game bundle the native runtime loads, the physics hello world's script and its checks (tools/web-engine.ts).- run: node tools/web-engine.ts+ webgpu:+ name: "webgpu (macOS): runtime, release build, size & isolation gate"+ needs: changes+ if: needs.changes.outputs.webgpu == 'true'+ runs-on: macos-latest+ timeout-minutes: 30+ steps:+ - uses: actions/checkout@v7+ - uses: actions/setup-node@v7+ with:+ node-version: 24+ cache: npm+ - run: npm ci+ - uses: ./.github/actions/cargo-cache+ with:+ workspaces: |+ runtime+ webgpu+ - run: cd runtime && cargo test --release --locked+ - run: cd webgpu && cargo test --release --locked+ - run: node tools/build.ts --renderer webgpu+ - run: node tools/check-webgpu-gate.ts --render++ webgpu-linux:+ name: "webgpu (Linux): runtime, release build, size & isolation gate"+ needs: changes+ if: needs.changes.outputs.webgpu == 'true'+ runs-on: ubuntu-26.04+ timeout-minutes: 30+ steps:+ - uses: actions/checkout@v7+ - uses: actions/setup-node@v7+ with:+ node-version: 24+ cache: npm+ - run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libjavascriptcoregtk-4.1-dev pkg-config libssl-dev+ - run: npm ci+ - uses: ./.github/actions/cargo-cache+ with:+ workspaces: |+ runtime+ webgpu+ - run: cd runtime && cargo test --release --locked+ - run: cd webgpu && cargo test --release --locked+ - run: node tools/build.ts --renderer webgpu+ - run: node tools/check-webgpu-gate.ts --render+# The check to read before merging (`gh pr checks <n>`: `threert`).threert:- needs: [changes, ts, renderer, voxel, physics, wasm, web]+ needs: [changes, ts, renderer, voxel, physics, wasm, web, webgpu, webgpu-linux]if: ${{ !cancelled() }}runs-on: ubuntu-26.04timeout-minutes: 5diff --git a/README.md b/README.mdindex 737d0d3..df3834f 100644--- a/README.md+++ b/README.md@@ -9,11 +9,11 @@<h1 align="center">ThreeRT</h1>-<p align="center"><b>Hardware ray-traced three.js.</b></p>+<p align="center"><b>The native runtime for three.js — hardware path tracing at 60 fps, or a clean WebGPU app.</b></p><p align="center">- A real-time path tracer behind a three.js-style API. Write the scene you would write in three.js,<br>- and every light in it is traced on the GPU's ray-tracing hardware, at 60 fps.+ One engine, two renderers: <b><code>path</code></b> traces every light on ray-tracing hardware at 60 fps,<br>+ and <b><code>webgpu</code></b> (macOS & Linux, <a href="docs/RENDERING-METHODS.md">architecture</a>) runs standard three.js natively with zero path-tracer code.</p><p align="center">@@ -45,7 +45,18 @@- **Ray tracing.** Every light is traced: shadows, bounce light, reflections, and glowing surfaces that light the room. No shadow maps, no light probes, no lightmaps, no baking.- **Real time.** 60 fps in production scenes with the camera moving: Amazon Lumberyard Bistro and Beeple's Zero-Day, on a laptop. Not a still that converges once you stop.-- **Runtime.** A game runtime, not only a renderer. Scene code and game logic run inside the engine, and the same file runs as plain three.js in any browser.+- **Runtime.** A native runtime for three.js, not only a renderer. Scene code and game logic run inside the engine: choose the `path` renderer for hardware ray tracing, the `webgpu` renderer (`node tools/build.ts --renderer webgpu`) for a clean native app with zero ray-tracing overhead, or run as plain three.js in any browser.++## Renderers: `path` and `webgpu`++ThreeRT stays one engine and one runtime with two renderers selected at build time (`node tools/build.ts --renderer path` or `--renderer webgpu`). They share the native runtime (`runtime/`) with one-way dependencies (`threert-path → threert-runtime ← threert-webgpu`), enforced by CI (`node tools/check-webgpu-gate.ts`) so a `webgpu` build links no ray-tracing code at all.++| | `path` | `webgpu` ([`docs/RENDERING-METHODS.md`](docs/RENDERING-METHODS.md)) |+|---|---|---|+| **Renderer** | Rust + wgpu compute path tracer (hardware ray queries, OIDN, DLSS / MetalFX) | Standard three.js `WebGPURenderer` over native `navigator.gpu` (wgpu) |+| **Scene API** | `@threert/scene` (physical lighting units) | Plain `three.js` + TSL node materials (+ PocketJS UI) |+| **GPU** | Ray-tracing hardware (Apple M-series, RTX, RDNA2+) | Any GPU wgpu supports (Metal, Vulkan, D3D12) |+| **Footprint** | Full ThreeRT clients | Proven at **9.9 MB installed / 4.5 MB download** (vs 445 / 170 MB Electron) |## Hello world looks right@@ -194,6 +205,7 @@ npm run test:render # the r## Documentation- [Getting started](https://threert.dev/docs/): the client, a first scene, the dev loop, packages+- [`docs/RENDERING-METHODS.md`](docs/RENDERING-METHODS.md): one runtime, two renderers (`path` and `webgpu`), crate layout and size-gate rules- [`docs/RUNTIME.md`](docs/RUNTIME.md): how scene code runs in the engine: setup, handlers, world handlers, frame scripts, physics- [`docs/MATERIAL_FUNCTIONS.md`](docs/MATERIAL_FUNCTIONS.md): a WGSL body on a material, run by the path tracer at every hit- [`docs/VOXEL.md`](docs/VOXEL.md): the voxel engine, measured on a destructible leveldiff --git a/docs/RENDERING-METHODS.md b/docs/RENDERING-METHODS.mdnew file mode 100644index 0000000..41bac6a--- /dev/null+++ b/docs/RENDERING-METHODS.md@@ -0,0 +1,103 @@+# Renderers: Path Tracer (`path`) and WebGPU (`webgpu`)++> Status: active (2026-11-28). Both the `path` renderer (`renderer/`) and the `webgpu` renderer+> (`runtime/` + `webgpu/`, built via `node tools/build.ts --renderer webgpu`, gated by+> `node tools/check-webgpu-gate.ts`) live in this repository on **macOS (Metal)** and **Linux+> (Vulkan + WebKitGTK JavaScriptCore + pure-Rust `tiny-skia`/`cosmic-text`/`image`)**. `webgpu`+> runs three.js r187's `WebGPURenderer` natively on PocketJS's JavaScriptCore guest+> (`pocket-nexus/pocketjs#773`, `#774`, `#775`), originally proven in+> `pocket-nexus/pocket-agents-island#28`, `#29`. Windows support remains planned.++ThreeRT is one engine and one runtime with **two renderers**, chosen per project and per build:++| | **`path`** (Path Tracer) | **`webgpu`** (WebGPU — macOS & Linux) |+|---|---|---|+| What draws | ThreeRT's wgpu compute path tracer: hardware ray queries, OIDN, DLSS / MetalFX, the physical sky and post chain | three.js r187's own `WebGPURenderer`, running natively: `navigator.gpu` implemented over wgpu inside the engine's JavaScript guest |+| Scene code | `@threert/scene` (physical units) | plain `three.js` + TSL node materials |+| GPU | ray-tracing hardware (Apple M-series, RTX, RDNA2+) | any GPU wgpu supports (Metal, Vulkan, D3D12) |+| Interface | the game HUD (`docs/RUNTIME.md` "HUD") | PocketJS (Solid JSX + Tailwind) drawn by PocketJS's wgpu renderer over the 3D frame |+| Footprint | the ThreeRT clients | 9.9 MB installed, 4.5 MB to download (Pocket Island desktop app, measured below) |+| For | production scenes lit by traced light at 60 fps | native three.js apps and games that ship small and run on any GPU, with zero ray-tracing code |++Following Godot (Forward+ / Mobile / Compatibility) and Blender (Cycles / EEVEE), ThreeRT stays a+single product with one brand (**ThreeRT**: Three + **R**ay **T**racing, **R**eal **T**ime,+**R**un**t**ime). There is no "ThreeRT Lite" or split brand — choosing `--renderer webgpu` simply+builds the clean native runtime with the WebGPU renderer and links zero path-tracer code.++## Why a `webgpu` renderer++ThreeRT's runtime already does what a small native 3D app needs besides ray tracing: a JavaScript+guest, window and frame pacing, input, audio, networking, assets and UI. Adding the `webgpu`+renderer completes the native three.js story — standard three.js scenes running natively on any GPU+at a fraction of a browser's size and power:++- **Measured on Pocket Island** (`pocket-nexus/pocket-agents-island#28`, `apps/desktop/REPORT.md`;+ Apple M5, 1200 × 800 @ 2×, foreground 60 fps, Agent Host running, whole process tree):+ - **CPU (one core):** 34.7 % vs Electron's 64.8 %+ - **Foreground RSS / footprint:** 471 MB / 533 MB vs Electron's 1007 MB / 932 MB+ - **Window closed RSS / footprint:** 81 MB / 16 MB vs Electron's 433 MB / 104 MB+ - **Installed / download:** 9.9 MB / 4.5 MB vs Electron's 445 MB / 170 MB+ - **Visual parity:** the native WebGPU binding renders three.js test scenes identically to Chrome's+ WebGPU (mean absolute difference 0.000 / 255).+- A three.js developer can ship a native desktop build without Electron and without rewriting their+ scene for `@threert/scene`, while keeping the same ThreeRT runtime and path to hardware ray tracing+ when a project wants `path`.++## Code layout++```text+renderer/ threert-render (path tracer crate; unchanged API)+runtime/ runtime/crates/* threert-jsc, threert-rt, threert-canvas2d,+ threert-net, threert-pocket-host+ runtime/js/ web-platform globals (events, timers, window,+ Canvas 2D, net; never imports webgpu/ or renderer/)+webgpu/ threert-webgpu WebGPU (`navigator.gpu`) over wgpu for JSC,+ window canvas + headless Offscreen (`webgpu-shot`)+ webgpu/js/ JS WebGPU binding + runtime entrypoint+ webgpu/sample/ threert-webgpu-sample (minimal three.js r187 + TSL)+```++**Dependencies point one way: `threert-path → threert-runtime ← threert-webgpu`.**+- A `webgpu` build **never links path-tracer code**: no ray-query kernels, OIDN, DLSS, MetalFX, sky+ baker, or voxel traversal.+- A `path` build never links the WebGPU guest binding.+- A build selects one renderer:++```bash+node tools/build.ts --renderer webgpu # clean native three.js app: runtime + webgpu (zero path-tracer code)+node tools/build.ts --renderer path # hardware ray tracing (default): runtime + path tracer+node tools/check-webgpu-gate.ts --render # cargo tree isolation, JS layering, binary size & headless Metal check+```++**Size and dependency gates hold `webgpu` clean.** CI builds the `webgpu` sample app (release, LTO,+stripped) and checks both binary size against its budget (Pocket Island's size at extraction plus an+explicit margin) and `cargo tree` to verify no `threert-path` / denoiser / upscaler crates enter the+`webgpu` dependency graph. `path` builds have no size gate.++**`path` users see no change.** `threert-render`, `@threert/scene`, `@threert/gameplay`, the clients,+the `dlss` / `oidn` / `net` / `audio` features, and the default build stay as they are.++## What moves from `pocket-agents-island`++| `apps/desktop` today | ThreeRT |+|---|---|+| `crates/webgpu`, `runtime/webgpu.ts` (`navigator.gpu` over wgpu) | `webgpu/` (`threert-webgpu`) |+| `crates/canvas2d` (Canvas 2D, images, fonts on CoreGraphics / CoreText) | `webgpu/` (textures) and `runtime/` (UI text) |+| `crates/pocket-host` (PocketJS runtime + JavaScriptCore guest + wgpu display + native text) | `runtime/` (`threert-runtime`) |+| `crates/net`, `crates/rt`, `runtime/pocket.ts` (timers, fetch, WebSocket, storage, audio) | `runtime/` (`threert-runtime`) |+| `crates/app` window, frame pacing, shell | `runtime/` (window, pacing); app-specific shell stays with the app |+| `crates/agent-host`, Pocket Island's game and UI | stay in `pocket-agents-island` |++The JavaScriptCore guest and native text path live in PocketJS (`pocket-guest-jsc`,+`pocket-wgpu-render`'s `TextPainter`); ThreeRT depends on them rather than copying them.++## Open questions++- **The guest on Windows and Linux.** three.js's `WebGPURenderer` does per-frame work in JavaScript;+ QuickJS runs it several times slower than a JIT. Windows and Linux need a JIT engine (V8 or+ JavaScriptCore from WebKitGTK) before `webgpu` ships there.+- **TSL coverage.** `webgpu` runs three.js `WebGPURenderer` as written; materials that rely on+ `onBeforeCompile` or GLSL `ShaderMaterial` need TSL equivalents (Pocket Island's port is the worked+ example).+- **One scene, both renderers.** Whether `@threert/scene` scenes should also target `webgpu` (its+ three.js fallback already runs in browsers) or `webgpu` stays plain three.js.diff --git a/package.json b/package.jsonindex 3bfb0d2..77177a1 100644--- a/package.json+++ b/package.json@@ -8,8 +8,10 @@"packages/*"],"scripts": {- "typecheck": "tsc -p packages/scene && tsc -p packages/gameplay && tsc -p packages/voxel && tsc -p games && tsc -p tools && tsc -p tests && tsc -p renderer/web/www",+ "typecheck": "tsc -p packages/scene && tsc -p packages/gameplay && tsc -p packages/voxel && tsc -p games && tsc -p tools && tsc -p tests && tsc -p renderer/web/www && tsc -p runtime/js && tsc -p webgpu/js && tsc -p webgpu/sample","test": "node --test packages/*/test/*.test.ts tools/*/test/*.test.ts site/*.test.ts",+ "build": "node tools/build.ts",+ "check:webgpu": "node tools/check-webgpu-gate.ts","scenes": "node tools/build-scenes.ts","test:render": "node tools/test-render.ts","test:layer-b": "node tools/test-layer-b.ts",diff --git a/runtime/Cargo.lock b/runtime/Cargo.locknew file mode 100644index 0000000..d95cac8--- /dev/null+++ b/runtime/Cargo.lock@@ -0,0 +1,2393 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"++[[package]]+name = "alloc-no-stdlib"+version = "2.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"++[[package]]+name = "alloc-stdlib"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"+dependencies = [+ "alloc-no-stdlib",+]++[[package]]+name = "android_system_properties"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"+dependencies = [+ "libc",+]++[[package]]+name = "arrayref"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"++[[package]]+name = "arrayvec"+version = "0.7.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"++[[package]]+name = "ash"+version = "0.38.0+1.3.281"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f"+dependencies = [+ "libloading",+]++[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"++[[package]]+name = "bit-set"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"+dependencies = [+ "bit-vec",+]++[[package]]+name = "bit-vec"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"++[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"++[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"+dependencies = [+ "serde_core",+]++[[package]]+name = "block"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"++[[package]]+name = "block-buffer"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"+dependencies = [+ "hybrid-array",+]++[[package]]+name = "brotli"+version = "7.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc97b8f16f944bba54f0433f07e30be199b6dc2bd25937444bbad560bcea29bd"+dependencies = [+ "alloc-no-stdlib",+ "alloc-stdlib",+ "brotli-decompressor",+]++[[package]]+name = "brotli-decompressor"+version = "4.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a334ef7c9e23abf0ce748e8cd309037da93e606ad52eb372e4ce327a0dcfbdfd"+dependencies = [+ "alloc-no-stdlib",+ "alloc-stdlib",+]++[[package]]+name = "bumpalo"+version = "3.20.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db"++[[package]]+name = "bytemuck"+version = "1.25.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"+dependencies = [+ "bytemuck_derive",+]++[[package]]+name = "bytemuck_derive"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "byteorder-lite"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"++[[package]]+name = "bytes"+version = "1.12.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"++[[package]]+name = "cc"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66"+dependencies = [+ "find-msvc-tools",+ "shlex",+]++[[package]]+name = "cfg-if"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"++[[package]]+name = "cfg_aliases"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"++[[package]]+name = "chacha20"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "rand_core",+]++[[package]]+name = "codespan-reporting"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe6d2e5af09e8c8ad56c969f2157a3d4238cebc7c55f0a517728c38f7b200f81"+dependencies = [+ "serde",+ "termcolor",+ "unicode-width",+]++[[package]]+name = "color_quant"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"++[[package]]+name = "const-oid"+version = "0.10.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"++[[package]]+name = "core-foundation"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"++[[package]]+name = "core-graphics-types"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"+dependencies = [+ "bitflags 1.3.2",+ "core-foundation 0.9.4",+ "libc",+]++[[package]]+name = "cosmic-text"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59fd57d82eb4bfe7ffa9b1cec0c05e2fd378155b47f255a67983cb4afe0e80c2"+dependencies = [+ "bitflags 2.13.2",+ "fontdb",+ "log",+ "rangemap",+ "rayon",+ "rustc-hash",+ "rustybuzz",+ "self_cell",+ "swash",+ "sys-locale",+ "ttf-parser 0.21.1",+ "unicode-bidi",+ "unicode-linebreak",+ "unicode-script",+ "unicode-segmentation",+]++[[package]]+name = "cpufeatures"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"+dependencies = [+ "libc",+]++[[package]]+name = "crc32fast"+version = "1.5.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"+dependencies = [+ "cfg-if",+]++[[package]]+name = "crossbeam-deque"+version = "0.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"+dependencies = [+ "crossbeam-epoch",+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-epoch"+version = "0.9.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"++[[package]]+name = "crunchy"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"++[[package]]+name = "crypto-common"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"+dependencies = [+ "hybrid-array",+]++[[package]]+name = "data-encoding"+version = "2.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"++[[package]]+name = "digest"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"+dependencies = [+ "block-buffer",+ "const-oid",+ "crypto-common",+]++[[package]]+name = "document-features"+version = "0.2.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"+dependencies = [+ "litrs",+]++[[package]]+name = "either"+version = "1.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"++[[package]]+name = "equivalent"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"++[[package]]+name = "errno"+version = "0.3.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"+dependencies = [+ "libc",+ "windows-sys",+]++[[package]]+name = "fastrand"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"++[[package]]+name = "fdeflate"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"+dependencies = [+ "simd-adler32",+]++[[package]]+name = "find-msvc-tools"+version = "0.1.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8"++[[package]]+name = "flate2"+version = "1.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"+dependencies = [+ "crc32fast",+ "miniz_oxide 0.9.1",+ "zlib-rs",+]++[[package]]+name = "foldhash"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"++[[package]]+name = "font-types"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b3971f9a5ca983419cdc386941ba3b9e1feba01a0ab888adf78739feb2798492"+dependencies = [+ "bytemuck",+]++[[package]]+name = "fontconfig-parser"+version = "0.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"+dependencies = [+ "roxmltree",+]++[[package]]+name = "fontdb"+version = "0.16.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b0299020c3ef3f60f526a4f64ab4a3d4ce116b1acbf24cdd22da0068e5d81dc3"+dependencies = [+ "fontconfig-parser",+ "log",+ "memmap2",+ "slotmap",+ "tinyvec",+ "ttf-parser 0.20.0",+]++[[package]]+name = "foreign-types"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"+dependencies = [+ "foreign-types-shared 0.1.1",+]++[[package]]+name = "foreign-types"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"+dependencies = [+ "foreign-types-macros",+ "foreign-types-shared 0.3.1",+]++[[package]]+name = "foreign-types-macros"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "foreign-types-shared"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"++[[package]]+name = "foreign-types-shared"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"++[[package]]+name = "futures-core"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"++[[package]]+name = "futures-task"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"++[[package]]+name = "futures-util"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"+dependencies = [+ "futures-core",+ "futures-task",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi",+ "rand_core",+]++[[package]]+name = "gif"+version = "0.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"+dependencies = [+ "color_quant",+ "weezl",+]++[[package]]+name = "gl_generator"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d"+dependencies = [+ "khronos_api",+ "log",+ "xml-rs",+]++[[package]]+name = "glow"+version = "0.16.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c5e5ea60d70410161c8bf5da3fdfeaa1c72ed2c15f8bbb9d19fe3a4fad085f08"+dependencies = [+ "js-sys",+ "slotmap",+ "wasm-bindgen",+ "web-sys",+]++[[package]]+name = "glutin_wgl_sys"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e"+dependencies = [+ "gl_generator",+]++[[package]]+name = "gpu-alloc"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "45cf04b2726f02df5508c6de726acdc90cdf97ac771a9a0ffd8ba10a6e696bf9"+dependencies = [+ "bitflags 2.13.2",+ "gpu-alloc-types",+]++[[package]]+name = "gpu-alloc-types"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2bbed164dd10ed526c2e4fe3e721ca4a71c61730e5aafac6844b417b3227058"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "gpu-allocator"+version = "0.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c151a2a5ef800297b4e79efa4f4bec035c5f51d5ae587287c9b952bdf734cacd"+dependencies = [+ "log",+ "presser",+ "thiserror 1.0.69",+ "windows",+]++[[package]]+name = "gpu-descriptor"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b89c83349105e3732062a895becfc71a8f921bb71ecbbdd8ff99263e3b53a0ca"+dependencies = [+ "bitflags 2.13.2",+ "gpu-descriptor-types",+ "hashbrown 0.15.5",+]++[[package]]+name = "gpu-descriptor-types"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fdf242682df893b86f33a73828fb09ca4b2d3bb6cc95249707fc684d27484b91"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "half"+version = "2.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"+dependencies = [+ "cfg-if",+ "crunchy",+ "num-traits",+ "zerocopy",+]++[[package]]+name = "hashbrown"+version = "0.15.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"+dependencies = [+ "foldhash",+]++[[package]]+name = "hashbrown"+version = "0.17.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"++[[package]]+name = "heck"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"++[[package]]+name = "hexf-parse"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df"++[[package]]+name = "http"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"+dependencies = [+ "bytes",+ "itoa",+]++[[package]]+name = "httparse"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"++[[package]]+name = "hybrid-array"+version = "0.4.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"+dependencies = [+ "typenum",+]++[[package]]+name = "image"+version = "0.25.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"+dependencies = [+ "bytemuck",+ "byteorder-lite",+ "color_quant",+ "gif",+ "image-webp",+ "moxcms",+ "num-traits",+ "png 0.18.1",+ "zune-core",+ "zune-jpeg",+]++[[package]]+name = "image-webp"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"+dependencies = [+ "byteorder-lite",+ "quick-error",+]++[[package]]+name = "indexmap"+version = "2.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"+dependencies = [+ "equivalent",+ "hashbrown 0.17.2",+]++[[package]]+name = "itoa"+version = "1.0.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"++[[package]]+name = "jni-sys"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"+dependencies = [+ "jni-sys 0.4.1",+]++[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "js-sys"+version = "0.3.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"+dependencies = [+ "cfg-if",+ "futures-util",+ "wasm-bindgen",+]++[[package]]+name = "khronos-egl"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76"+dependencies = [+ "libc",+ "libloading",+ "pkg-config",+]++[[package]]+name = "khronos_api"+version = "3.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"++[[package]]+name = "libc"+version = "0.2.191"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"++[[package]]+name = "libloading"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"+dependencies = [+ "cfg-if",+ "windows-link",+]++[[package]]+name = "libm"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"++[[package]]+name = "linux-raw-sys"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"++[[package]]+name = "litrs"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02b614978e47ce529faee66579f2b2fe19c94aa96d910a6a9a8043b2b02d8175"++[[package]]+name = "lock_api"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"+dependencies = [+ "scopeguard",+]++[[package]]+name = "log"+version = "0.4.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"++[[package]]+name = "malloc_buf"+version = "0.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb"+dependencies = [+ "libc",+]++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "memmap2"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157"+dependencies = [+ "libc",+]++[[package]]+name = "metal"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f569fb946490b5743ad69813cb19629130ce9374034abe31614a36402d18f99e"+dependencies = [+ "bitflags 2.13.2",+ "block",+ "core-graphics-types",+ "foreign-types 0.5.0",+ "log",+ "objc",+ "paste",+]++[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "miniz_oxide"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "moxcms"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"+dependencies = [+ "num-traits",+ "pxfm",+]++[[package]]+name = "naga"+version = "25.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b977c445f26e49757f9aca3631c3b8b836942cb278d69a92e7b80d3b24da632"+dependencies = [+ "arrayvec",+ "bit-set",+ "bitflags 2.13.2",+ "cfg_aliases",+ "codespan-reporting",+ "half",+ "hashbrown 0.15.5",+ "hexf-parse",+ "indexmap",+ "log",+ "num-traits",+ "once_cell",+ "rustc-hash",+ "spirv",+ "strum",+ "thiserror 2.0.21",+ "unicode-ident",+]++[[package]]+name = "native-tls"+version = "0.2.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2"+dependencies = [+ "libc",+ "log",+ "openssl",+ "openssl-probe",+ "openssl-sys",+ "schannel",+ "security-framework",+ "security-framework-sys",+ "tempfile",+]++[[package]]+name = "ndk-sys"+version = "0.5.0+25.2.9519653"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c196769dd60fd4f363e11d948139556a344e79d451aeb2fa2fd040738ef7691"+dependencies = [+ "jni-sys 0.3.1",+]++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+ "libm",+]++[[package]]+name = "objc"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1"+dependencies = [+ "malloc_buf",+]++[[package]]+name = "objc2"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"+dependencies = [+ "objc2-encode",+]++[[package]]+name = "objc2-app-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "objc2-core-graphics"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"+dependencies = [+ "bitflags 2.13.2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-core-text"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"+dependencies = [+ "bitflags 2.13.2",+ "objc2-core-foundation",+ "objc2-core-graphics",+]++[[package]]+name = "objc2-encode"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"++[[package]]+name = "objc2-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+]++[[package]]+name = "objc2-image-io"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32b0446e98cf4a784cc7a0177715ff317eeaa8463841c616cfc78aa4f953c4ea"+dependencies = [+ "objc2-core-foundation",+ "objc2-core-graphics",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "openssl"+version = "0.10.82"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4de8111e94a56adca7ebfe6c365b6d42f99deb69b74b6becacd4204e2f193aa2"+dependencies = [+ "bitflags 2.13.2",+ "cfg-if",+ "foreign-types 0.3.2",+ "libc",+ "openssl-macros",+ "openssl-sys",+]++[[package]]+name = "openssl-macros"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "openssl-probe"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1"++[[package]]+name = "openssl-sys"+version = "0.9.118"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19c413d6ec9ebaf5e1c829d355cb3e9f783778d700f135be0921d52fce3c60ae"+dependencies = [+ "cc",+ "libc",+ "pkg-config",+ "vcpkg",+]++[[package]]+name = "ordered-float"+version = "4.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7bb71e1b3fa6ca1c61f383464aaf2bb0e2f8e772a1f01d486832464de363b951"+dependencies = [+ "num-traits",+]++[[package]]+name = "parking_lot"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"+dependencies = [+ "lock_api",+ "parking_lot_core",+]++[[package]]+name = "parking_lot_core"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"+dependencies = [+ "cfg-if",+ "libc",+ "redox_syscall",+ "smallvec",+ "windows-link",+]++[[package]]+name = "paste"+version = "1.0.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"++[[package]]+name = "pin-project-lite"+version = "0.2.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"++[[package]]+name = "pkg-config"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"++[[package]]+name = "png"+version = "0.17.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"+dependencies = [+ "bitflags 1.3.2",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide 0.8.9",+]++[[package]]+name = "png"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"+dependencies = [+ "bitflags 2.13.2",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide 0.8.9",+]++[[package]]+name = "pocket-drivers"+version = "0.17.0"+source = "git+https://github.com/pocket-nexus/pocketjs?rev=72b7d9a8521b7e1aac55c9f1358853ded2076bce#72b7d9a8521b7e1aac55c9f1358853ded2076bce"+dependencies = [+ "pocket-spec",+]++[[package]]+name = "pocket-guest-jsc"+version = "0.17.0"+source = "git+https://github.com/pocket-nexus/pocketjs?rev=72b7d9a8521b7e1aac55c9f1358853ded2076bce#72b7d9a8521b7e1aac55c9f1358853ded2076bce"+dependencies = [+ "log",+ "pocket-drivers",+ "pocket-runtime",+]++[[package]]+name = "pocket-media"+version = "0.17.0"+source = "git+https://github.com/pocket-nexus/pocketjs?rev=72b7d9a8521b7e1aac55c9f1358853ded2076bce#72b7d9a8521b7e1aac55c9f1358853ded2076bce"+dependencies = [+ "pocket-spec",+]++[[package]]+name = "pocket-package"+version = "0.17.0"+source = "git+https://github.com/pocket-nexus/pocketjs?rev=72b7d9a8521b7e1aac55c9f1358853ded2076bce#72b7d9a8521b7e1aac55c9f1358853ded2076bce"+dependencies = [+ "pocket-drivers",+ "pocket-spec",+]++[[package]]+name = "pocket-render"+version = "0.17.0"+source = "git+https://github.com/pocket-nexus/pocketjs?rev=72b7d9a8521b7e1aac55c9f1358853ded2076bce#72b7d9a8521b7e1aac55c9f1358853ded2076bce"+dependencies = [+ "pocket-drivers",+ "pocket-spec",+]++[[package]]+name = "pocket-runtime"+version = "0.17.0"+source = "git+https://github.com/pocket-nexus/pocketjs?rev=72b7d9a8521b7e1aac55c9f1358853ded2076bce#72b7d9a8521b7e1aac55c9f1358853ded2076bce"+dependencies = [+ "pocket-drivers",+ "pocket-package",+ "pocket-render",+ "pocket-spec",+ "pocketjs-core",+]++[[package]]+name = "pocket-spec"+version = "0.17.0"+source = "git+https://github.com/pocket-nexus/pocketjs?rev=72b7d9a8521b7e1aac55c9f1358853ded2076bce#72b7d9a8521b7e1aac55c9f1358853ded2076bce"++[[package]]+name = "pocket-wgpu-render"+version = "0.17.0"+source = "git+https://github.com/pocket-nexus/pocketjs?rev=72b7d9a8521b7e1aac55c9f1358853ded2076bce#72b7d9a8521b7e1aac55c9f1358853ded2076bce"+dependencies = [+ "bytemuck",+ "pocket-drivers",+ "pocket-render",+ "pocket-spec",+ "pollster",+ "wgpu",+]++[[package]]+name = "pocketjs-core"+version = "0.17.0"+source = "git+https://github.com/pocket-nexus/pocketjs?rev=72b7d9a8521b7e1aac55c9f1358853ded2076bce#72b7d9a8521b7e1aac55c9f1358853ded2076bce"+dependencies = [+ "pocket-drivers",+ "pocket-media",+ "pocket-package",+ "pocket-render",+ "pocket-spec",+ "taffy",+]++[[package]]+name = "pollster"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"++[[package]]+name = "portable-atomic"+version = "1.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"++[[package]]+name = "presser"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "profiling"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"++[[package]]+name = "pxfm"+version = "0.1.30"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"++[[package]]+name = "quick-error"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]]+name = "rand"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11"+dependencies = [+ "chacha20",+ "getrandom",+ "rand_core",+]++[[package]]+name = "rand_core"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"++[[package]]+name = "range-alloc"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08"++[[package]]+name = "rangemap"+version = "1.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2d43a8c8c74056248124068fde0df374d1ddf9039e747d190f01c36faeaab08"++[[package]]+name = "raw-window-handle"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"++[[package]]+name = "rayon"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"+dependencies = [+ "either",+ "rayon-core",+]++[[package]]+name = "rayon-core"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"+dependencies = [+ "crossbeam-deque",+ "crossbeam-utils",+]++[[package]]+name = "read-fonts"+version = "0.22.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69aacb76b5c29acfb7f90155d39759a29496aebb49395830e928a9703d2eec2f"+dependencies = [+ "bytemuck",+ "font-types",+]++[[package]]+name = "redox_syscall"+version = "0.5.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "renderdoc-sys"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"++[[package]]+name = "roxmltree"+version = "0.20.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"++[[package]]+name = "rustc-hash"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"++[[package]]+name = "rustix"+version = "1.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"+dependencies = [+ "bitflags 2.13.2",+ "errno",+ "libc",+ "linux-raw-sys",+ "windows-sys",+]++[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "rustybuzz"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfb9cf8877777222e4a3bc7eb247e398b56baba500c38c1c46842431adc8b55c"+dependencies = [+ "bitflags 2.13.2",+ "bytemuck",+ "libm",+ "smallvec",+ "ttf-parser 0.21.1",+ "unicode-bidi-mirroring",+ "unicode-ccc",+ "unicode-properties",+ "unicode-script",+]++[[package]]+name = "schannel"+version = "0.1.30"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5"+dependencies = [+ "windows-sys",+]++[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"++[[package]]+name = "security-framework"+version = "3.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"+dependencies = [+ "bitflags 2.13.2",+ "core-foundation 0.10.1",+ "core-foundation-sys",+ "libc",+ "security-framework-sys",+]++[[package]]+name = "security-framework-sys"+version = "2.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "self_cell"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813"++[[package]]+name = "serde"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde_core"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "serde_json"+version = "1.0.154"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "sha1"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "digest",+]++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "simd-adler32"+version = "0.3.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"++[[package]]+name = "skrifa"+version = "0.22.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e1c44ad1f6c5bdd4eefed8326711b7dbda9ea45dfd36068c427d332aa382cbe"+dependencies = [+ "bytemuck",+ "read-fonts",+]++[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"++[[package]]+name = "slotmap"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"+dependencies = [+ "version_check",+]++[[package]]+name = "smallvec"+version = "1.16.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"++[[package]]+name = "spirv"+version = "0.3.0+sdk-1.3.268.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eda41003dc44290527a59b13432d4a0379379fa074b70174882adfbdfd917844"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "static_assertions"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"++[[package]]+name = "strict-num"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"++[[package]]+name = "strum"+version = "0.26.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06"+dependencies = [+ "strum_macros",+]++[[package]]+name = "strum_macros"+version = "0.26.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be"+dependencies = [+ "heck",+ "proc-macro2",+ "quote",+ "rustversion",+ "syn 2.0.119",+]++[[package]]+name = "swash"+version = "0.1.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cbd59f3f359ddd2c95af4758c18270eddd9c730dde98598023cdabff472c2ca2"+dependencies = [+ "skrifa",+ "yazi",+ "zeno",+]++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "3.0.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "sys-locale"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"+dependencies = [+ "libc",+]++[[package]]+name = "taffy"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfde4e2f8595f222ceaae1fb16b4963952e9b33e358869dc4cd6316b0e0790cd"+dependencies = [+ "arrayvec",+ "serde",+ "slotmap",+]++[[package]]+name = "tempfile"+version = "3.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"+dependencies = [+ "fastrand",+ "getrandom",+ "once_cell",+ "rustix",+ "windows-sys",+]++[[package]]+name = "termcolor"+version = "1.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"+dependencies = [+ "winapi-util",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]++[[package]]+name = "thiserror"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"+dependencies = [+ "thiserror-impl 2.0.21",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "thiserror-impl"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "threert-canvas2d"+version = "0.1.0"+dependencies = [+ "cosmic-text",+ "image",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-core-text",+ "objc2-image-io",+ "threert-jsc",+ "threert-rt",+ "tiny-skia",+]++[[package]]+name = "threert-jsc"+version = "0.1.0"+dependencies = [+ "pocket-guest-jsc",+]++[[package]]+name = "threert-net"+version = "0.1.0"+dependencies = [+ "brotli",+ "flate2",+ "httparse",+ "libc",+ "native-tls",+ "objc2",+ "objc2-app-kit",+ "objc2-foundation",+ "threert-jsc",+ "threert-rt",+ "tungstenite",+]++[[package]]+name = "threert-pocket-host"+version = "0.1.0"+dependencies = [+ "log",+ "pocket-drivers",+ "pocket-guest-jsc",+ "pocket-package",+ "pocket-runtime",+ "pocket-wgpu-render",+ "pocketjs-core",+ "pollster",+ "serde_json",+ "threert-canvas2d",+ "wgpu",+]++[[package]]+name = "threert-rt"+version = "0.1.0"+dependencies = [+ "threert-jsc",+]++[[package]]+name = "tiny-skia"+version = "0.11.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab"+dependencies = [+ "arrayref",+ "arrayvec",+ "bytemuck",+ "cfg-if",+ "log",+ "png 0.17.16",+ "tiny-skia-path",+]++[[package]]+name = "tiny-skia-path"+version = "0.11.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93"+dependencies = [+ "arrayref",+ "bytemuck",+ "strict-num",+]++[[package]]+name = "tinyvec"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"++[[package]]+name = "tokio"+version = "1.54.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"+dependencies = [+ "pin-project-lite",+]++[[package]]+name = "ttf-parser"+version = "0.20.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "17f77d76d837a7830fe1d4f12b7b4ba4192c1888001c7164257e4bc6d21d96b4"++[[package]]+name = "ttf-parser"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c591d83f69777866b9126b24c6dd9a18351f177e49d625920d19f989fd31cf8"++[[package]]+name = "tungstenite"+version = "0.30.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22"+dependencies = [+ "bytes",+ "data-encoding",+ "http",+ "httparse",+ "log",+ "rand",+ "sha1",+ "thiserror 2.0.21",+]++[[package]]+name = "typenum"+version = "1.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"++[[package]]+name = "unicode-bidi"+version = "0.3.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"++[[package]]+name = "unicode-bidi-mirroring"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23cb788ffebc92c5948d0e997106233eeb1d8b9512f93f41651f52b6c5f5af86"++[[package]]+name = "unicode-ccc"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1df77b101bcc4ea3d78dafc5ad7e4f58ceffe0b2b16bf446aeb50b6cb4157656"++[[package]]+name = "unicode-ident"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"++[[package]]+name = "unicode-linebreak"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f"++[[package]]+name = "unicode-properties"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833"++[[package]]+name = "unicode-script"+version = "0.5.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa04c955db05429d464c74d495c1ee677e1866e783a4c3747f9c0cef7756cabf"++[[package]]+name = "unicode-segmentation"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"++[[package]]+name = "unicode-width"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"++[[package]]+name = "vcpkg"+version = "0.2.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"++[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"++[[package]]+name = "wasm-bindgen"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"+dependencies = [+ "cfg-if",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-futures"+version = "0.4.80"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501"+dependencies = [+ "js-sys",+ "tokio",+ "wasm-bindgen",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn 3.0.10",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "web-sys"+version = "0.3.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "weezl"+version = "0.1.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"++[[package]]+name = "wgpu"+version = "25.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec8fb398f119472be4d80bc3647339f56eb63b2a331f6a3d16e25d8144197dd9"+dependencies = [+ "arrayvec",+ "bitflags 2.13.2",+ "cfg_aliases",+ "document-features",+ "hashbrown 0.15.5",+ "js-sys",+ "log",+ "naga",+ "parking_lot",+ "portable-atomic",+ "profiling",+ "raw-window-handle",+ "smallvec",+ "static_assertions",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+ "wgpu-core",+ "wgpu-hal",+ "wgpu-types",+]++[[package]]+name = "wgpu-core"+version = "25.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f7b882196f8368511d613c6aeec80655160db6646aebddf8328879a88d54e500"+dependencies = [+ "arrayvec",+ "bit-set",+ "bit-vec",+ "bitflags 2.13.2",+ "cfg_aliases",+ "document-features",+ "hashbrown 0.15.5",+ "indexmap",+ "log",+ "naga",+ "once_cell",+ "parking_lot",+ "portable-atomic",+ "profiling",+ "raw-window-handle",+ "rustc-hash",+ "smallvec",+ "thiserror 2.0.21",+ "wgpu-core-deps-apple",+ "wgpu-core-deps-emscripten",+ "wgpu-core-deps-windows-linux-android",+ "wgpu-hal",+ "wgpu-types",+]++[[package]]+name = "wgpu-core-deps-apple"+version = "25.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfd488b3239b6b7b185c3b045c39ca6bf8af34467a4c5de4e0b1a564135d093d"+dependencies = [+ "wgpu-hal",+]++[[package]]+name = "wgpu-core-deps-emscripten"+version = "25.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f09ad7aceb3818e52539acc679f049d3475775586f3f4e311c30165cf2c00445"+dependencies = [+ "wgpu-hal",+]++[[package]]+name = "wgpu-core-deps-windows-linux-android"+version = "25.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cba5fb5f7f9c98baa7c889d444f63ace25574833df56f5b817985f641af58e46"+dependencies = [+ "wgpu-hal",+]++[[package]]+name = "wgpu-hal"+version = "25.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f968767fe4d3d33747bbd1473ccd55bf0f6451f55d733b5597e67b5deab4ad17"+dependencies = [+ "android_system_properties",+ "arrayvec",+ "ash",+ "bit-set",+ "bitflags 2.13.2",+ "block",+ "bytemuck",+ "cfg-if",+ "cfg_aliases",+ "core-graphics-types",+ "glow",+ "glutin_wgl_sys",+ "gpu-alloc",+ "gpu-allocator",+ "gpu-descriptor",+ "hashbrown 0.15.5",+ "js-sys",+ "khronos-egl",+ "libc",+ "libloading",+ "log",+ "metal",+ "naga",+ "ndk-sys",+ "objc",+ "ordered-float",+ "parking_lot",+ "portable-atomic",+ "profiling",+ "range-alloc",+ "raw-window-handle",+ "renderdoc-sys",+ "smallvec",+ "thiserror 2.0.21",+ "wasm-bindgen",+ "web-sys",+ "wgpu-types",+ "windows",+ "windows-core",+]++[[package]]+name = "wgpu-types"+version = "25.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2aa49460c2a8ee8edba3fca54325540d904dd85b2e086ada762767e17d06e8bc"+dependencies = [+ "bitflags 2.13.2",+ "bytemuck",+ "js-sys",+ "log",+ "thiserror 2.0.21",+ "web-sys",+]++[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys",+]++[[package]]+name = "windows"+version = "0.58.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6"+dependencies = [+ "windows-core",+ "windows-targets",+]++[[package]]+name = "windows-core"+version = "0.58.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-result",+ "windows-strings",+ "windows-targets",+]++[[package]]+name = "windows-implement"+version = "0.58.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-interface"+version = "0.58.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-result"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e"+dependencies = [+ "windows-targets",+]++[[package]]+name = "windows-strings"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10"+dependencies = [+ "windows-result",+ "windows-targets",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-targets"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"+dependencies = [+ "windows_aarch64_gnullvm",+ "windows_aarch64_msvc",+ "windows_i686_gnu",+ "windows_i686_gnullvm",+ "windows_i686_msvc",+ "windows_x86_64_gnu",+ "windows_x86_64_gnullvm",+ "windows_x86_64_msvc",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"++[[package]]+name = "windows_aarch64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"++[[package]]+name = "windows_i686_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"++[[package]]+name = "windows_i686_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"++[[package]]+name = "windows_i686_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"++[[package]]+name = "windows_x86_64_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"++[[package]]+name = "windows_x86_64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"++[[package]]+name = "xml-rs"+version = "0.8.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"++[[package]]+name = "yazi"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c94451ac9513335b5e23d7a8a2b61a7102398b8cca5160829d313e84c9d98be1"++[[package]]+name = "zeno"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd15f8e0dbb966fd9245e7498c7e9e5055d9e5c8b676b95bd67091cd11a1e697"++[[package]]+name = "zerocopy"+version = "0.8.66"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.66"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "zlib-rs"+version = "0.6.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac"++[[package]]+name = "zmij"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"++[[package]]+name = "zune-core"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"++[[package]]+name = "zune-jpeg"+version = "0.5.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"+dependencies = [+ "zune-core",+]diff --git a/runtime/Cargo.toml b/runtime/Cargo.tomlnew file mode 100644index 0000000..415d01c--- /dev/null+++ b/runtime/Cargo.toml@@ -0,0 +1,40 @@+[workspace]+resolver = "2"+members = [+ "crates/jsc",+ "crates/rt",+ "crates/canvas2d",+ "crates/net",+ "crates/pocket-host",+]++[workspace.package]+version = "0.1.0"+edition = "2024"+license = "MIT"++[workspace.dependencies]+jsc = { package = "threert-jsc", path = "crates/jsc" }+rt = { package = "threert-rt", path = "crates/rt" }+canvas2d = { package = "threert-canvas2d", path = "crates/canvas2d" }+# PocketJS (pocket-nexus/pocketjs): the UI runtime, its JavaScriptCore guest and wgpu renderer.+pocket-runtime = { git = "https://github.com/pocket-nexus/pocketjs", rev = "72b7d9a8521b7e1aac55c9f1358853ded2076bce" }+pocket-drivers = { git = "https://github.com/pocket-nexus/pocketjs", rev = "72b7d9a8521b7e1aac55c9f1358853ded2076bce" }+pocket-package = { git = "https://github.com/pocket-nexus/pocketjs", rev = "72b7d9a8521b7e1aac55c9f1358853ded2076bce" }+pocket-guest-jsc = { git = "https://github.com/pocket-nexus/pocketjs", rev = "72b7d9a8521b7e1aac55c9f1358853ded2076bce" }+pocket-wgpu-render = { git = "https://github.com/pocket-nexus/pocketjs", rev = "72b7d9a8521b7e1aac55c9f1358853ded2076bce" }+pocketjs-core = { git = "https://github.com/pocket-nexus/pocketjs", rev = "72b7d9a8521b7e1aac55c9f1358853ded2076bce" }+wgpu = "25"++[profile.dev]+opt-level = 1++[profile.dev.package."*"]+opt-level = 3++[profile.release]+opt-level = 3+lto = "fat"+codegen-units = 1+panic = "abort"+strip = truediff --git a/runtime/crates/canvas2d/Cargo.toml b/runtime/crates/canvas2d/Cargo.tomlnew file mode 100644index 0000000..c18e3b4--- /dev/null+++ b/runtime/crates/canvas2d/Cargo.toml@@ -0,0 +1,21 @@+[package]+name = "threert-canvas2d"+description = "Canvas 2D, image decoding/encoding, and text layout for ThreeRT runtime (CoreGraphics/CoreText on macOS; pure-Rust tiny-skia/cosmic-text/image elsewhere)"+version.workspace = true+edition.workspace = true+license.workspace = true++[dependencies]+jsc.workspace = true+rt.workspace = true++[target.'cfg(target_os = "macos")'.dependencies]+objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "CFBase", "CFString", "CFArray", "CFDictionary", "CFNumber", "CFData", "CFURL", "CFAttributedString", "CFCGTypes", "CFCharacterSet", "CFError", "CFLocale"] }+objc2-core-graphics = { version = "0.3", default-features = false, features = ["std", "CGAffineTransform", "CGBase", "CGBitmapContext", "CGColor", "CGColorSpace", "CGContext", "CGDataProvider", "CGFont", "CGGeometry", "CGGradient", "CGImage", "CGPath"] }+objc2-core-text = { version = "0.3", default-features = false, features = ["std", "CTFont", "CTFontDescriptor", "CTFontManager", "CTFontTraits", "CTLine", "CTRun", "CTStringAttributes", "CTTypesetter", "objc2-core-graphics"] }+objc2-image-io = { version = "0.3", default-features = false, features = ["std", "CGImageSource", "CGImageDestination", "CGImageProperties", "objc2-core-graphics"] }++[target.'cfg(not(target_os = "macos"))'.dependencies]+tiny-skia = "0.11"+cosmic-text = "0.12"+image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp"] }diff --git a/runtime/crates/canvas2d/src/canvas.rs b/runtime/crates/canvas2d/src/canvas.rsnew file mode 100644index 0000000..ef92f8b--- /dev/null+++ b/runtime/crates/canvas2d/src/canvas.rs@@ -0,0 +1,954 @@+//! A 2D context over one CoreGraphics bitmap context (premultiplied RGBA8, sRGB).+//!+//! Coordinate spaces: the CG context's root CTM flips y once, so "device" below means canvas+//! pixels, y down. The current path is kept in device space (each point transformed by the CTM at+//! the time it is added, as the canvas spec requires); Path2D objects are kept in their own space+//! and transformed when used. Clipping lives in the CG graphics state, so canvas `save()` /+//! `restore()` map onto CG's gstate stack; everything else (paint, line, shadow, composite, font)+//! is canvas state applied per draw call inside a nested gstate.+use std::rc::Rc;++use objc2_core_foundation::{CFRetained, CGAffineTransform, CGFloat, CGPoint, CGRect, CGSize};+use objc2_core_graphics::{+ CGBitmapContextCreate, CGBlendMode, CGColor, CGContext, CGGradient, CGGradientDrawingOptions, CGImage, CGImageAlphaInfo, CGInterpolationQuality,+ CGLineCap, CGLineJoin, CGMutablePath, CGPath,+};++use crate::codec::{premul, srgb, unpremul};+use crate::fonts::{self, Font, ParsedFont};+use crate::text;++pub(crate) const IDENTITY: CGAffineTransform = CGAffineTransform { a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0 };++/// `t1` then `t2`.+pub(crate) fn concat(t1: &CGAffineTransform, t2: &CGAffineTransform) -> CGAffineTransform {+ CGAffineTransform {+ a: t1.a * t2.a + t1.b * t2.c,+ b: t1.a * t2.b + t1.b * t2.d,+ c: t1.c * t2.a + t1.d * t2.c,+ d: t1.c * t2.b + t1.d * t2.d,+ tx: t1.tx * t2.a + t1.ty * t2.c + t2.tx,+ ty: t1.tx * t2.b + t1.ty * t2.d + t2.ty,+ }+}++pub(crate) fn apply(t: &CGAffineTransform, x: f64, y: f64) -> (f64, f64) {+ (t.a * x + t.c * y + t.tx, t.b * x + t.d * y + t.ty)+}++pub(crate) fn invert(t: &CGAffineTransform) -> Option<CGAffineTransform> {+ let det = t.a * t.d - t.b * t.c;+ if det == 0.0 || !det.is_finite() {+ return None;+ }+ let a = t.d / det;+ let b = -t.b / det;+ let c = -t.c / det;+ let d = t.a / det;+ Some(CGAffineTransform { a, b, c, d, tx: -(a * t.tx + c * t.ty), ty: -(b * t.tx + d * t.ty) })+}++fn rect(x: f64, y: f64, w: f64, h: f64) -> CGRect {+ CGRect { origin: CGPoint { x, y }, size: CGSize { width: w, height: h } }+}++// ----------------------------------------------------------------------------------- paths++/// A path under construction, in its own coordinate space.+pub(crate) struct Path {+ pub cg: CFRetained<CGMutablePath>,+ /// a subpath is open (there is a current point)+ pub has_current: bool,+}++impl Default for Path {+ fn default() -> Self {+ Path { cg: CGMutablePath::new(), has_current: false }+ }+}++fn finite(v: &[f64]) -> bool {+ v.iter().all(|x| x.is_finite())+}++impl Path {+ pub fn clear(&mut self) {+ self.cg = CGMutablePath::new();+ self.has_current = false;+ }+ fn current(&self) -> (f64, f64) {+ let p = CGPath::current_point(Some(&self.cg));+ (p.x, p.y)+ }+ pub fn move_to(&mut self, m: &CGAffineTransform, x: f64, y: f64) {+ if !finite(&[x, y]) {+ return;+ }+ let (dx, dy) = apply(m, x, y);+ unsafe { CGMutablePath::move_to_point(Some(&self.cg), std::ptr::null(), dx, dy) };+ self.has_current = true;+ }+ pub fn line_to(&mut self, m: &CGAffineTransform, x: f64, y: f64) {+ if !finite(&[x, y]) {+ return;+ }+ if !self.has_current {+ return self.move_to(m, x, y);+ }+ let (dx, dy) = apply(m, x, y);+ unsafe { CGMutablePath::add_line_to_point(Some(&self.cg), std::ptr::null(), dx, dy) };+ }+ pub fn quad_to(&mut self, m: &CGAffineTransform, cx: f64, cy: f64, x: f64, y: f64) {+ if !finite(&[cx, cy, x, y]) {+ return;+ }+ if !self.has_current {+ self.move_to(m, cx, cy);+ }+ let (a, b) = apply(m, cx, cy);+ let (c, d) = apply(m, x, y);+ unsafe { CGMutablePath::add_quad_curve_to_point(Some(&self.cg), std::ptr::null(), a, b, c, d) };+ }+ #[allow(clippy::too_many_arguments)]+ pub fn bezier_to(&mut self, m: &CGAffineTransform, c1x: f64, c1y: f64, c2x: f64, c2y: f64, x: f64, y: f64) {+ if !finite(&[c1x, c1y, c2x, c2y, x, y]) {+ return;+ }+ if !self.has_current {+ self.move_to(m, c1x, c1y);+ }+ let (a, b) = apply(m, c1x, c1y);+ let (c, d) = apply(m, c2x, c2y);+ let (e, f) = apply(m, x, y);+ unsafe { CGMutablePath::add_curve_to_point(Some(&self.cg), std::ptr::null(), a, b, c, d, e, f) };+ }+ pub fn close(&mut self) {+ if self.has_current {+ CGMutablePath::close_subpath(Some(&self.cg));+ }+ }+ /// Elliptical arc of the unit circle mapped by `m` (CSS/canvas angle semantics).+ fn arc_unit(&mut self, m: &CGAffineTransform, start: f64, end: f64, ccw: bool) {+ let (start, end) = canonical_angles(start, end, ccw);+ let sweep = end - start;+ let had = self.has_current;+ if !had {+ // CGPathAddRelativeArc starts a new subpath at the arc start on an empty path, but a path+ // that only has closed subpaths still has a "current point"; begin explicitly.+ let (x, y) = apply(m, start.cos(), start.sin());+ unsafe { CGMutablePath::move_to_point(Some(&self.cg), std::ptr::null(), x, y) };+ }+ unsafe { CGMutablePath::add_relative_arc(Some(&self.cg), m, 0.0, 0.0, 1.0, start, sweep) };+ self.has_current = true;+ }+ #[allow(clippy::too_many_arguments)]+ pub fn arc(&mut self, m: &CGAffineTransform, x: f64, y: f64, r: f64, start: f64, end: f64, ccw: bool) {+ self.ellipse(m, x, y, r, r, 0.0, start, end, ccw)+ }+ #[allow(clippy::too_many_arguments)]+ pub fn ellipse(&mut self, m: &CGAffineTransform, x: f64, y: f64, rx: f64, ry: f64, rot: f64, start: f64, end: f64, ccw: bool) {+ if !finite(&[x, y, rx, ry, rot, start, end]) || rx < 0.0 || ry < 0.0 {+ return;+ }+ if rx == 0.0 || ry == 0.0 {+ // Degenerate: Chrome draws the line through the arc's end points.+ let (s, e) = canonical_angles(start, end, ccw);+ let pt = |a: f64| {+ let (c, s_) = (a.cos() * rx, a.sin() * ry);+ (x + c * rot.cos() - s_ * rot.sin(), y + c * rot.sin() + s_ * rot.cos())+ };+ let (sx, sy) = pt(s);+ self.line_to(m, sx, sy);+ let (ex, ey) = pt(e);+ self.line_to(m, ex, ey);+ return;+ }+ let local = CGAffineTransform { a: rx * rot.cos(), b: rx * rot.sin(), c: -ry * rot.sin(), d: ry * rot.cos(), tx: x, ty: y };+ let full = concat(&local, m);+ self.arc_unit(&full, start, end, ccw);+ }+ /// `arcTo` per the canvas spec, computed in the space of `m`'s input (user space).+ #[allow(clippy::too_many_arguments)]+ pub fn arc_to(&mut self, m: &CGAffineTransform, x1: f64, y1: f64, x2: f64, y2: f64, r: f64) {+ if !finite(&[x1, y1, x2, y2, r]) || r < 0.0 {+ return;+ }+ if !self.has_current {+ self.move_to(m, x1, y1);+ }+ let Some(inv) = invert(m) else { return };+ let (dx, dy) = self.current();+ let (x0, y0) = apply(&inv, dx, dy);+ let eq = |a: f64, b: f64, c: f64, d: f64| (a - c).abs() < 1e-9 && (b - d).abs() < 1e-9;+ if eq(x0, y0, x1, y1) || eq(x1, y1, x2, y2) || r == 0.0 {+ return self.line_to(m, x1, y1);+ }+ let (v1x, v1y) = (x0 - x1, y0 - y1);+ let (v2x, v2y) = (x2 - x1, y2 - y1);+ let l1 = v1x.hypot(v1y);+ let l2 = v2x.hypot(v2y);+ let cross = v1x * v2y - v1y * v2x;+ if cross.abs() <= 1e-9 * l1 * l2 {+ return self.line_to(m, x1, y1);+ }+ let (u1x, u1y) = (v1x / l1, v1y / l1);+ let (u2x, u2y) = (v2x / l2, v2y / l2);+ let cos = (u1x * u2x + u1y * u2y).clamp(-1.0, 1.0);+ let half = cos.acos() / 2.0;+ let dist = r / half.tan();+ let (t1x, t1y) = (x1 + u1x * dist, y1 + u1y * dist);+ let (t2x, t2y) = (x1 + u2x * dist, y1 + u2y * dist);+ let (bx, by) = (u1x + u2x, u1y + u2y);+ let bl = bx.hypot(by);+ let cd = r / half.sin();+ let (cx, cy) = (x1 + bx / bl * cd, y1 + by / bl * cd);+ let a0 = (t1y - cy).atan2(t1x - cx);+ let a1 = (t2y - cy).atan2(t2x - cx);+ let mut delta = a1 - a0;+ while delta > std::f64::consts::PI {+ delta -= std::f64::consts::TAU;+ }+ while delta < -std::f64::consts::PI {+ delta += std::f64::consts::TAU;+ }+ self.line_to(m, t1x, t1y);+ let local = CGAffineTransform { a: r, b: 0.0, c: 0.0, d: r, tx: cx, ty: cy };+ let full = concat(&local, m);+ unsafe { CGMutablePath::add_relative_arc(Some(&self.cg), &full, 0.0, 0.0, 1.0, a0, delta) };+ }+ pub fn rect(&mut self, m: &CGAffineTransform, x: f64, y: f64, w: f64, h: f64) {+ if !finite(&[x, y, w, h]) {+ return;+ }+ self.move_to(m, x, y);+ self.line_to(m, x + w, y);+ self.line_to(m, x + w, y + h);+ self.line_to(m, x, y + h);+ self.close();+ }+ /// `roundRect` with radii already normalized by the caller: `r` = [tl.x, tl.y, tr.x, tr.y,+ /// br.x, br.y, bl.x, bl.y] (spec steps up to scaling done in JS).+ pub fn round_rect(&mut self, m: &CGAffineTransform, x: f64, y: f64, w: f64, h: f64, r: [f64; 8]) {+ if !finite(&[x, y, w, h]) || !finite(&r) {+ return;+ }+ let [tlx, tly, trx, try_, brx, bry, blx, bly] = r;+ self.move_to(m, x + tlx, y);+ self.line_to(m, x + w - trx, y);+ self.corner(m, x + w - trx, y + try_, trx, try_, -std::f64::consts::FRAC_PI_2);+ self.line_to(m, x + w, y + h - bry);+ self.corner(m, x + w - brx, y + h - bry, brx, bry, 0.0);+ self.line_to(m, x + blx, y + h);+ self.corner(m, x + blx, y + h - bly, blx, bly, std::f64::consts::FRAC_PI_2);+ self.line_to(m, x, y + tly);+ self.corner(m, x + tlx, y + tly, tlx, tly, std::f64::consts::PI);+ self.close();+ self.move_to(m, x, y);+ }+ fn corner(&mut self, m: &CGAffineTransform, cx: f64, cy: f64, rx: f64, ry: f64, start: f64) {+ if rx <= 0.0 || ry <= 0.0 {+ return;+ }+ let local = CGAffineTransform { a: rx, b: 0.0, c: 0.0, d: ry, tx: cx, ty: cy };+ let full = concat(&local, m);+ unsafe { CGMutablePath::add_relative_arc(Some(&self.cg), &full, 0.0, 0.0, 1.0, start, std::f64::consts::FRAC_PI_2) };+ }+ pub fn add_path(&mut self, other: &CGPath, m: &CGAffineTransform) {+ unsafe { CGMutablePath::add_path(Some(&self.cg), m, Some(other)) };+ if !CGPath::is_empty(Some(other)) {+ self.has_current = true;+ }+ }+ /// A copy transformed by `m`.+ pub fn transformed(&self, m: &CGAffineTransform) -> CFRetained<CGPath> {+ unsafe { CGPath::new_copy_by_transforming_path(Some(&self.cg), m) }.unwrap_or_else(|| CGPath::new_copy(Some(&self.cg)).unwrap())+ }+}++/// Chrome's arc angle canonicalization (start in [0, 2π), sweep per the spec rules).+fn canonical_angles(start: f64, end: f64, ccw: bool) -> (f64, f64) {+ use std::f64::consts::TAU;+ let mut s = start % TAU;+ if s < 0.0 {+ s += TAU;+ }+ let e = end + (s - start);+ let new_end = if !ccw && e - s >= TAU {+ s + TAU+ } else if ccw && s - e >= TAU {+ s - TAU+ } else if !ccw && s > e {+ s + (TAU - (s - e) % TAU)+ } else if ccw && s < e {+ s - (TAU - (e - s) % TAU)+ } else {+ e+ };+ (s, new_end)+}++// ----------------------------------------------------------------------------------- paint++pub(crate) struct Gradient {+ pub kind: GradientKind,+ pub stops: Vec<(f64, [f64; 4])>,+ pub cg: Option<CFRetained<CGGradient>>,+}++#[derive(Clone, Copy)]+pub(crate) enum GradientKind {+ Linear(f64, f64, f64, f64),+ Radial(f64, f64, f64, f64, f64, f64),+ Conic(f64, f64, f64),+}++impl Gradient {+ pub fn new(kind: GradientKind) -> Self {+ Gradient { kind, stops: Vec::new(), cg: None }+ }+ pub fn add_stop(&mut self, offset: f64, rgba: [f64; 4]) {+ // Keep insertion order among equal offsets (stable sort by offset).+ let at = self.stops.iter().position(|(o, _)| *o > offset).unwrap_or(self.stops.len());+ self.stops.insert(at, (offset, rgba));+ self.cg = None;+ }+ fn cg(&mut self) -> Option<CFRetained<CGGradient>> {+ if self.stops.is_empty() {+ return None;+ }+ if self.cg.is_none() {+ let mut comps: Vec<CGFloat> = Vec::with_capacity(self.stops.len() * 4 + 8);+ let mut locs: Vec<CGFloat> = Vec::with_capacity(self.stops.len() + 2);+ for (o, c) in &self.stops {+ comps.extend_from_slice(c);+ locs.push(*o);+ }+ if self.stops.len() == 1 {+ comps.extend_from_slice(&self.stops[0].1);+ locs = vec![0.0, 1.0];+ }+ self.cg = unsafe { CGGradient::with_color_components(Some(&srgb()), comps.as_ptr(), locs.as_ptr(), locs.len()) };+ }+ self.cg.clone()+ }+}++pub(crate) struct Pattern {+ pub image: CFRetained<CGImage>,+ pub width: f64,+ pub height: f64,+ pub repeat_x: bool,+ pub repeat_y: bool,+ pub transform: CGAffineTransform,+}++#[derive(Clone)]+pub(crate) enum Paint {+ Color(CFRetained<CGColor>, f64),+ Gradient(Rc<std::cell::RefCell<Gradient>>),+ Pattern(Rc<Pattern>),+}++impl Paint {+ pub fn color(r: f64, g: f64, b: f64, a: f64) -> Paint {+ Paint::Color(CGColor::new_srgb(r, g, b, a), a)+ }+ fn is_invisible(&self) -> bool {+ matches!(self, Paint::Color(_, a) if *a <= 0.0)+ }+}++const UNBOUNDED: [i32; 5] = [17, 18, 19, 22, 24]; // copy, source-in, source-out, destination-in, destination-atop++pub(crate) fn composite_from_name(name: &str) -> Option<i32> {+ Some(match name {+ "source-over" => 0,+ "source-in" => 18,+ "source-out" => 19,+ "source-atop" => 20,+ "destination-over" => 21,+ "destination-in" => 22,+ "destination-out" => 23,+ "destination-atop" => 24,+ "lighter" | "plus-lighter" => 27,+ "copy" => 17,+ "xor" => 25,+ "multiply" => 1,+ "screen" => 2,+ "overlay" => 3,+ "darken" => 4,+ "lighten" => 5,+ "color-dodge" => 6,+ "color-burn" => 7,+ "hard-light" => 9,+ "soft-light" => 8,+ "difference" => 10,+ "exclusion" => 11,+ "hue" => 12,+ "saturation" => 13,+ "color" => 14,+ "luminosity" => 15,+ _ => return None,+ })+}++#[derive(Clone)]+pub(crate) struct State {+ pub ctm: CGAffineTransform,+ pub fill: Paint,+ pub stroke: Paint,+ pub line_width: f64,+ pub cap: CGLineCap,+ pub join: CGLineJoin,+ pub miter: f64,+ pub dash: Vec<f64>,+ pub dash_offset: f64,+ pub alpha: f64,+ pub blend: i32,+ pub shadow_x: f64,+ pub shadow_y: f64,+ pub shadow_blur: f64,+ pub shadow_color: Option<(CFRetained<CGColor>, f64)>,+ pub smoothing: bool,+ pub smoothing_quality: u8,+ pub font: Rc<ParsedFont>,+ pub resolved: Option<Rc<Font>>,+ /// 0 start, 1 end, 2 left, 3 right, 4 center+ pub align: u8,+ /// 0 alphabetic, 1 top, 2 hanging, 3 middle, 4 ideographic, 5 bottom+ pub baseline: u8,+ pub rtl: bool,+ pub letter_spacing: f64,+ pub word_spacing: f64,+ pub kerning: bool,+}++thread_local! {+ static DEFAULT_FONT: Rc<ParsedFont> = Rc::new(fonts::parse_shorthand("10px sans-serif").unwrap());+}++impl Default for State {+ fn default() -> Self {+ let black = Paint::color(0.0, 0.0, 0.0, 1.0);+ State {+ ctm: IDENTITY,+ fill: black.clone(),+ stroke: black,+ line_width: 1.0,+ cap: CGLineCap::Butt,+ join: CGLineJoin::Miter,+ miter: 10.0,+ dash: Vec::new(),+ dash_offset: 0.0,+ alpha: 1.0,+ blend: 0,+ shadow_x: 0.0,+ shadow_y: 0.0,+ shadow_blur: 0.0,+ shadow_color: None,+ smoothing: true,+ smoothing_quality: 0,+ font: DEFAULT_FONT.with(|f| f.clone()),+ resolved: None,+ align: 0,+ baseline: 0,+ rtl: false,+ letter_spacing: 0.0,+ word_spacing: 0.0,+ kerning: true,+ }+ }+}++impl State {+ fn shadow_visible(&self) -> bool {+ matches!(&self.shadow_color, Some((_, a)) if *a > 0.0) && (self.shadow_blur > 0.0 || self.shadow_x != 0.0 || self.shadow_y != 0.0)+ }+ pub fn font(&mut self) -> Rc<Font> {+ if self.resolved.is_none() {+ self.resolved = Some(fonts::resolve_parsed(&self.font));+ }+ self.resolved.clone().unwrap()+ }+}++/// What a draw call paints with.+#[derive(Clone, Copy, PartialEq)]+enum Use {+ Fill,+ Stroke,+}++// ----------------------------------------------------------------------------------- canvas++pub(crate) struct Canvas {+ pub cg: Option<CFRetained<CGContext>>,+ pub width: u32,+ pub height: u32,+ pub state: State,+ pub stack: Vec<State>,+ pub path: Path,+ /// set by every call that may change pixels+ pub dirty: bool,+}++impl Canvas {+ /// A context drawing into `data` (w×h premultiplied RGBA, already zeroed).+ pub fn new(data: *mut u8, width: u32, height: u32) -> Canvas {+ let cg = if width == 0 || height == 0 || data.is_null() {+ None+ } else {+ unsafe { CGBitmapContextCreate(data.cast(), width as usize, height as usize, 8, width as usize * 4, Some(&srgb()), CGImageAlphaInfo::PremultipliedLast.0) }+ };+ if let Some(cg) = &cg {+ // y-down canvas pixels on top of CG's y-up device space+ CGContext::translate_ctm(Some(cg), 0.0, height as f64);+ CGContext::scale_ctm(Some(cg), 1.0, -1.0);+ CGContext::set_should_antialias(Some(cg), true);+ CGContext::set_interpolation_quality(Some(cg), CGInterpolationQuality::Low);+ // Outer gstate: canvas save/restore push above this one.+ CGContext::save_g_state(Some(cg));+ }+ Canvas { cg, width, height, state: State::default(), stack: Vec::new(), path: Path::default(), dirty: false }+ }++ pub fn save(&mut self) {+ self.stack.push(self.state.clone());+ if let Some(cg) = &self.cg {+ CGContext::save_g_state(Some(cg));+ }+ }++ pub fn restore(&mut self) {+ if let Some(s) = self.stack.pop() {+ self.state = s;+ if let Some(cg) = &self.cg {+ CGContext::restore_g_state(Some(cg));+ }+ }+ }++ /// `ctx.reset()`: clear pixels, state, path and clip.+ pub fn reset(&mut self) {+ while !self.stack.is_empty() {+ self.restore();+ }+ if let Some(cg) = &self.cg {+ // drop the clip: back to the root gstate and push a fresh one+ CGContext::restore_g_state(Some(cg));+ CGContext::save_g_state(Some(cg));+ }+ self.state = State::default();+ self.path.clear();+ self.clear_all();+ }++ pub fn clear_all(&mut self) {+ if let Some(cg) = &self.cg {+ let data = objc2_core_graphics::CGBitmapContextGetData(Some(cg)) as *mut u8;+ if !data.is_null() {+ unsafe { std::ptr::write_bytes(data, 0, self.width as usize * self.height as usize * 4) };+ }+ }+ self.dirty = true;+ }++ fn invertible(&self) -> bool {+ invert(&self.state.ctm).is_some()+ }++ /// Run `draw` with the compositing state applied (alpha, blend, shadow), inside a+ /// transparency layer when the composite op affects pixels outside the shape (copy,+ /// source-in, …) or when several primitives must share one shadow.+ fn composite(&mut self, multi_primitive: bool, draw: impl FnOnce(&CGContext, &mut State)) {+ let Some(cg) = self.cg.clone() else { return };+ let s = &mut self.state;+ CGContext::save_g_state(Some(&cg));+ CGContext::set_alpha(Some(&cg), s.alpha);+ CGContext::set_blend_mode(Some(&cg), CGBlendMode(s.blend));+ let shadow = s.shadow_visible();+ if shadow {+ let (color, _) = s.shadow_color.as_ref().unwrap();+ // Shadow offsets are in device space (CG's base space is y-up); canvas blur is 2σ, CG's+ // blur parameter is σ·√2·… — calibrated against Chrome (see SHADOW_BLUR_SCALE).+ CGContext::set_shadow_with_color(Some(&cg), CGSize { width: s.shadow_x, height: -s.shadow_y }, s.shadow_blur * SHADOW_BLUR_SCALE, Some(color));+ }+ let layer = UNBOUNDED.contains(&s.blend) || (shadow && multi_primitive);+ if layer {+ unsafe { CGContext::begin_transparency_layer(Some(&cg), None) };+ }+ draw(&cg, s);+ if layer {+ CGContext::end_transparency_layer(Some(&cg));+ }+ CGContext::restore_g_state(Some(&cg));+ self.dirty = true;+ }++ fn paint_of(&self, u: Use) -> &Paint {+ if u == Use::Fill { &self.state.fill } else { &self.state.stroke }+ }++ /// Fill or stroke a device-space path (`path`) with the current paint.+ fn draw_path(&mut self, path: &CGPath, u: Use, evenodd: bool) {+ if !self.invertible() || self.cg.is_none() {+ return;+ }+ let paint = self.paint_of(u).clone();+ if paint.is_invisible() && !UNBOUNDED.contains(&self.state.blend) {+ return;+ }+ let multi = !matches!(paint, Paint::Color(..));+ self.composite(multi, |cg, s| {+ match u {+ Use::Fill => {+ CGContext::add_path(Some(cg), Some(path));+ match &paint {+ Paint::Color(c, _) => {+ CGContext::set_fill_color_with_color(Some(cg), Some(c));+ if evenodd { CGContext::eo_fill_path(Some(cg)) } else { CGContext::fill_path(Some(cg)) }+ }+ _ => {+ if evenodd { CGContext::eo_clip(Some(cg)) } else { CGContext::clip(Some(cg)) }+ fill_clip_with(cg, &paint, &s.ctm);+ }+ }+ }+ Use::Stroke => {+ let inv = invert(&s.ctm).unwrap();+ let user = unsafe { CGPath::new_copy_by_transforming_path(Some(path), &inv) };+ CGContext::concat_ctm(Some(cg), s.ctm);+ CGContext::add_path(Some(cg), user.as_deref());+ apply_line_state(cg, s);+ match &paint {+ Paint::Color(c, _) => {+ CGContext::set_stroke_color_with_color(Some(cg), Some(c));+ CGContext::stroke_path(Some(cg));+ }+ _ => {+ CGContext::replace_path_with_stroked_path(Some(cg));+ CGContext::clip(Some(cg));+ if let Some(inv) = invert(&s.ctm) {+ CGContext::concat_ctm(Some(cg), inv);+ }+ fill_clip_with(cg, &paint, &s.ctm);+ }+ }+ }+ }+ });+ }++ pub fn fill(&mut self, path2d: Option<&Path>, evenodd: bool) {+ let p = match path2d {+ Some(p) => p.transformed(&self.state.ctm),+ None => CGPath::new_copy(Some(&self.path.cg)).unwrap(),+ };+ self.draw_path(&p, Use::Fill, evenodd);+ }++ pub fn stroke(&mut self, path2d: Option<&Path>) {+ let p = match path2d {+ Some(p) => p.transformed(&self.state.ctm),+ None => CGPath::new_copy(Some(&self.path.cg)).unwrap(),+ };+ self.draw_path(&p, Use::Stroke, false);+ }++ pub fn clip(&mut self, path2d: Option<&Path>, evenodd: bool) {+ let Some(cg) = self.cg.clone() else { return };+ let p = match path2d {+ Some(p) => p.transformed(&self.state.ctm),+ None => CGPath::new_copy(Some(&self.path.cg)).unwrap(),+ };+ CGContext::add_path(Some(&cg), Some(&p));+ if CGContext::is_path_empty(Some(&cg)) {+ // clipping to an empty path clips everything+ CGContext::clip_to_rect(Some(&cg), rect(0.0, 0.0, 0.0, 0.0));+ } else if evenodd {+ CGContext::eo_clip(Some(&cg));+ } else {+ CGContext::clip(Some(&cg));+ }+ }++ pub fn is_point_in_path(&self, path2d: Option<&Path>, x: f64, y: f64, evenodd: bool) -> bool {+ if !finite(&[x, y]) {+ return false;+ }+ // The point is in canvas pixel space (untransformed), the path in device space.+ let p = match path2d {+ Some(p) => p.transformed(&self.state.ctm),+ None => CGPath::new_copy(Some(&self.path.cg)).unwrap(),+ };+ unsafe { CGPath::contains_point(Some(&p), std::ptr::null(), CGPoint { x, y }, evenodd) }+ }++ pub fn is_point_in_stroke(&self, path2d: Option<&Path>, x: f64, y: f64) -> bool {+ let Some(inv) = invert(&self.state.ctm) else { return false };+ if !finite(&[x, y]) {+ return false;+ }+ let user = match path2d {+ Some(p) => CGPath::new_copy(Some(&p.cg)).unwrap(),+ None => unsafe { CGPath::new_copy_by_transforming_path(Some(&self.path.cg), &inv) }.unwrap(),+ };+ let s = &self.state;+ let stroked = unsafe { CGPath::new_copy_by_stroking_path(Some(&user), &s.ctm, s.line_width, s.cap, s.join, s.miter) };+ stroked.is_some_and(|sp| unsafe { CGPath::contains_point(Some(&sp), std::ptr::null(), CGPoint { x, y }, false) })+ }++ pub fn fill_rect(&mut self, x: f64, y: f64, w: f64, h: f64) {+ if !finite(&[x, y, w, h]) || w == 0.0 || h == 0.0 {+ return;+ }+ let mut p = Path::default();+ p.rect(&self.state.ctm, x, y, w, h);+ self.draw_path(&p.cg.clone(), Use::Fill, false);+ }++ pub fn stroke_rect(&mut self, x: f64, y: f64, w: f64, h: f64) {+ if !finite(&[x, y, w, h]) || (w == 0.0 && h == 0.0) {+ return;+ }+ let mut p = Path::default();+ let m = self.state.ctm;+ if w == 0.0 || h == 0.0 {+ p.move_to(&m, x, y);+ p.line_to(&m, x + w, y + h);+ } else {+ p.rect(&m, x, y, w, h);+ }+ self.draw_path(&p.cg.clone(), Use::Stroke, false);+ }++ pub fn clear_rect(&mut self, x: f64, y: f64, w: f64, h: f64) {+ if !finite(&[x, y, w, h]) || !self.invertible() {+ return;+ }+ let Some(cg) = self.cg.clone() else { return };+ CGContext::save_g_state(Some(&cg));+ CGContext::concat_ctm(Some(&cg), self.state.ctm);+ CGContext::set_blend_mode(Some(&cg), CGBlendMode::Clear);+ CGContext::set_alpha(Some(&cg), 1.0);+ CGContext::add_rect(Some(&cg), rect(x, y, w, h));+ CGContext::fill_path(Some(&cg));+ CGContext::restore_g_state(Some(&cg));+ self.dirty = true;+ }++ /// `drawImage` with the source rect already normalized and clipped by the caller.+ #[allow(clippy::too_many_arguments)]+ pub fn draw_image(&mut self, img: &CGImage, iw: f64, ih: f64, sx: f64, sy: f64, sw: f64, sh: f64, dx: f64, dy: f64, dw: f64, dh: f64) {+ if !self.invertible() || sw <= 0.0 || sh <= 0.0 || dw == 0.0 || dh == 0.0 || !finite(&[sx, sy, sw, sh, dx, dy, dw, dh]) {+ return;+ }+ let integral = sx.fract() == 0.0 && sy.fract() == 0.0 && sw.fract() == 0.0 && sh.fract() == 0.0;+ let whole = sx == 0.0 && sy == 0.0 && sw == iw && sh == ih;+ let sub = if whole || !integral { None } else { CGImage::with_image_in_rect(Some(img), rect(sx, sy, sw, sh)) };+ let smoothing = self.state.smoothing;+ let quality = self.state.smoothing_quality;+ self.composite(false, |cg, s| {+ CGContext::concat_ctm(Some(cg), s.ctm);+ CGContext::set_interpolation_quality(+ Some(cg),+ if !smoothing {+ CGInterpolationQuality::None+ } else {+ match quality {+ 2 => CGInterpolationQuality::High,+ 1 => CGInterpolationQuality::Medium,+ _ => CGInterpolationQuality::Low,+ }+ },+ );+ // Images are y-up in CG: flip around the destination rect.+ if let Some(sub) = &sub {+ CGContext::translate_ctm(Some(cg), dx, dy + dh);+ CGContext::scale_ctm(Some(cg), 1.0, -1.0);+ CGContext::draw_image(Some(cg), rect(0.0, 0.0, dw, dh), Some(sub));+ } else if whole {+ CGContext::translate_ctm(Some(cg), dx, dy + dh);+ CGContext::scale_ctm(Some(cg), 1.0, -1.0);+ CGContext::draw_image(Some(cg), rect(0.0, 0.0, dw, dh), Some(img));+ } else {+ // Fractional source rect: clip to the destination and draw the whole image scaled+ // so the source rect lands on it.+ CGContext::clip_to_rect(Some(cg), rect(dx.min(dx + dw), dy.min(dy + dh), dw.abs(), dh.abs()));+ let kx = dw / sw;+ let ky = dh / sh;+ let ox = dx - sx * kx;+ let oy = dy - sy * ky;+ CGContext::translate_ctm(Some(cg), ox, oy + ih * ky);+ CGContext::scale_ctm(Some(cg), 1.0, -1.0);+ CGContext::draw_image(Some(cg), rect(0.0, 0.0, iw * kx, ih * ky), Some(img));+ }+ });+ }++ /// Unpremultiplied RGBA of a device-space rect into `out` (zeros outside the bitmap).+ pub fn get_image_data(&self, data: &[u8], sx: i64, sy: i64, sw: usize, sh: usize, out: &mut [u8]) {+ let (w, h) = (self.width as i64, self.height as i64);+ for row in 0..sh as i64 {+ let y = sy + row;+ let o = &mut out[row as usize * sw * 4..(row as usize + 1) * sw * 4];+ if y < 0 || y >= h {+ o.fill(0);+ continue;+ }+ for col in 0..sw as i64 {+ let x = sx + col;+ let d = &mut o[col as usize * 4..col as usize * 4 + 4];+ if x < 0 || x >= w {+ d.fill(0);+ continue;+ }+ let i = ((y * w + x) * 4) as usize;+ let a = data[i + 3];+ d[0] = unpremul(data[i], a);+ d[1] = unpremul(data[i + 1], a);+ d[2] = unpremul(data[i + 2], a);+ d[3] = a;+ }+ }+ }++ /// Write unpremultiplied RGBA (`src`, `sw`×`sh`) at (dx, dy), limited to the dirty rect.+ #[allow(clippy::too_many_arguments)]+ pub fn put_image_data(&mut self, data: &mut [u8], src: &[u8], sw: usize, sh: usize, dx: i64, dy: i64, dirty: (i64, i64, i64, i64)) {+ let (mut x0, mut y0, mut x1, mut y1) = dirty;+ x0 = x0.max(0);+ y0 = y0.max(0);+ x1 = x1.min(sw as i64);+ y1 = y1.min(sh as i64);+ let (w, h) = (self.width as i64, self.height as i64);+ for sy in y0..y1 {+ let ty = dy + sy;+ if ty < 0 || ty >= h {+ continue;+ }+ for sx in x0..x1 {+ let tx = dx + sx;+ if tx < 0 || tx >= w {+ continue;+ }+ let s = ((sy * sw as i64 + sx) * 4) as usize;+ let t = ((ty * w + tx) * 4) as usize;+ let a = src[s + 3];+ data[t] = premul(src[s], a);+ data[t + 1] = premul(src[s + 1], a);+ data[t + 2] = premul(src[s + 2], a);+ data[t + 3] = a;+ }+ }+ self.dirty = true;+ }++ /// fillText / strokeText.+ pub fn draw_text(&mut self, txt: &[u16], x: f64, y: f64, max_width: Option<f64>, u: Use2) {+ if !finite(&[x, y]) || !self.invertible() || self.cg.is_none() {+ return;+ }+ if let Some(mw) = max_width {+ if !(mw > 0.0) {+ return;+ }+ }+ let font = self.state.font();+ let layout = text::layout(&font, txt, self.state.letter_spacing, self.state.word_spacing, self.state.kerning);+ if layout.runs.is_empty() {+ return;+ }+ let width = layout.width;+ let scale_x = match max_width {+ Some(mw) if mw < width && width > 0.0 => mw / width,+ _ => 1.0,+ };+ let w = width * scale_x;+ let dx = match (self.state.align, self.state.rtl) {+ (4, _) => -w / 2.0,+ (3, _) | (1, false) | (0, true) => -w,+ _ => 0.0,+ };+ let dy = text::baseline_offset(&font, self.state.baseline);+ let m = concat(&CGAffineTransform { a: scale_x, b: 0.0, c: 0.0, d: 1.0, tx: x + dx, ty: y + dy }, &self.state.ctm);+ let use_ = if u == Use2::Fill { Use::Fill } else { Use::Stroke };+ let paint = self.paint_of(use_).clone();+ self.composite(true, |cg, s| text::draw(cg, s, &layout, &m, &paint, u == Use2::Stroke));+ }+}++#[derive(Clone, Copy, PartialEq)]+pub(crate) enum Use2 {+ Fill,+ Stroke,+}++/// CG's shadow blur parameter for a canvas `shadowBlur` (Chrome: Gaussian σ = blur / 2).+pub(crate) const SHADOW_BLUR_SCALE: f64 = 1.0;++pub(crate) fn apply_line_state(cg: &CGContext, s: &State) {+ CGContext::set_line_width(Some(cg), s.line_width);+ CGContext::set_line_cap(Some(cg), s.cap);+ CGContext::set_line_join(Some(cg), s.join);+ CGContext::set_miter_limit(Some(cg), s.miter);+ if !s.dash.is_empty() {+ unsafe { CGContext::set_line_dash(Some(cg), s.dash_offset, s.dash.as_ptr(), s.dash.len()) };+ }+}++/// Paint a gradient or pattern over the current clip. The CTM on entry is canvas pixels (device);+/// paint coordinates are in user space (`ctm`).+pub(crate) fn fill_clip_with(cg: &CGContext, paint: &Paint, ctm: &CGAffineTransform) {+ CGContext::concat_ctm(Some(cg), *ctm);+ match paint {+ Paint::Color(c, _) => {+ CGContext::set_fill_color_with_color(Some(cg), Some(c));+ let b = CGContext::clip_bounding_box(Some(cg));+ CGContext::fill_rect(Some(cg), b);+ }+ Paint::Gradient(g) => {+ let mut g = g.borrow_mut();+ let kind = g.kind;+ let Some(grad) = g.cg() else { return };+ let ext = CGGradientDrawingOptions::DrawsBeforeStartLocation | CGGradientDrawingOptions::DrawsAfterEndLocation;+ match kind {+ GradientKind::Linear(x0, y0, x1, y1) => {+ if x0 == x1 && y0 == y1 {+ return;+ }+ CGContext::draw_linear_gradient(Some(cg), Some(&grad), CGPoint { x: x0, y: y0 }, CGPoint { x: x1, y: y1 }, ext);+ }+ GradientKind::Radial(x0, y0, r0, x1, y1, r1) => {+ if x0 == x1 && y0 == y1 && r0 == r1 {+ return;+ }+ CGContext::draw_radial_gradient(Some(cg), Some(&grad), CGPoint { x: x0, y: y0 }, r0, CGPoint { x: x1, y: y1 }, r1, ext);+ }+ GradientKind::Conic(angle, x, y) => {+ // CG's conic gradient runs counter-clockwise in its (y-up) space; under our+ // y-flip that is clockwise on screen, like canvas. Mirror to keep the angle.+ cg.draw_conic_gradient(Some(&grad), CGPoint { x, y }, -angle);+ }+ }+ }+ Paint::Pattern(p) => {+ CGContext::concat_ctm(Some(cg), p.transform);+ if !p.repeat_x || !p.repeat_y {+ let big = 1e7;+ let (x0, w) = if p.repeat_x { (-big, 2.0 * big) } else { (0.0, p.width) };+ let (y0, h) = if p.repeat_y { (-big, 2.0 * big) } else { (0.0, p.height) };+ CGContext::clip_to_rect(Some(cg), rect(x0, y0, w, h));+ }+ // Tiles are drawn y-up: flip so each tile is upright with its top-left at multiples+ // of the tile size.+ CGContext::scale_ctm(Some(cg), 1.0, -1.0);+ if p.repeat_x || p.repeat_y {+ CGContext::draw_tiled_image(Some(cg), rect(0.0, -p.height, p.width, p.height), Some(&p.image));+ } else {+ CGContext::draw_image(Some(cg), rect(0.0, -p.height, p.width, p.height), Some(&p.image));+ }+ }+ }+}+diff --git a/runtime/crates/canvas2d/src/codec.rs b/runtime/crates/canvas2d/src/codec.rsnew file mode 100644index 0000000..b11f8ef--- /dev/null+++ b/runtime/crates/canvas2d/src/codec.rs@@ -0,0 +1,405 @@+//! Image decoding/encoding over ImageIO, and base64 for data URLs.+//!+//! Decoded pixels are premultiplied RGBA8 in sRGB, rows top-down — the layout of every bitmap in+//! the registry. Untagged and sRGB images are copied without color conversion (exactly like+//! Chrome's canvas, which treats untagged images as sRGB); tagged images in other color spaces+//! are converted to sRGB by CoreGraphics. EXIF orientation is applied, as Chrome does by default.+use objc2_core_foundation::{CFData, CFDictionary, CFMutableData, CFNumber, CFRetained, CFString, CFType, CGFloat, CGPoint, CGRect, CGSize};+use objc2_core_graphics::{+ kCGColorSpaceSRGB, CGBitmapContextCreate, CGBitmapInfo, CGColorRenderingIntent, CGColorSpace, CGColorSpaceModel, CGContext, CGDataProvider,+ CGImage, CGImageAlphaInfo, CGImageByteOrderInfo,+};+use objc2_image_io::{+ kCGImageDestinationLossyCompressionQuality, kCGImagePropertyOrientation, kCGImageSourceCreateThumbnailFromImageAlways,+ kCGImageSourceCreateThumbnailWithTransform, kCGImageSourceShouldCache, kCGImageSourceThumbnailMaxPixelSize, CGImageDestination, CGImageSource,+};++/// Premultiplied RGBA8, rows top-down, stride = width × 4.+pub struct Decoded {+ pub width: u32,+ pub height: u32,+ pub data: Vec<u8>,+}++pub(crate) fn srgb() -> CFRetained<CGColorSpace> {+ thread_local! {+ static SRGB: CFRetained<CGColorSpace> = CGColorSpace::with_name(Some(unsafe { kCGColorSpaceSRGB })).expect("sRGB color space");+ }+ SRGB.with(|s| s.clone())+}++/// Decode PNG / JPEG / GIF (first frame) / WebP / HEIC … into premultiplied RGBA.+pub fn decode(bytes: &[u8]) -> Result<Decoded, String> {+ if bytes.is_empty() {+ return Err("empty image data".into());+ }+ let data = CFData::from_bytes(bytes);+ let no_cache = CFDictionary::<CFString, CFType>::from_slices(&[unsafe { kCGImageSourceShouldCache }], &[objc2_core_foundation::CFBoolean::new(false) as &CFType]);+ let src = unsafe { CGImageSource::with_data(&data, Some(no_cache.as_opaque())) }.ok_or("unsupported image format")?;+ if unsafe { src.count() } == 0 {+ return Err("unsupported or corrupt image".into());+ }+ let idx = unsafe { src.primary_image_index() };+ let orientation = unsafe { src.properties_at_index(idx, None) }+ .and_then(|p| {+ let p: CFRetained<CFDictionary<CFString, CFType>> = unsafe { CFRetained::cast_unchecked(p) };+ p.get(unsafe { kCGImagePropertyOrientation })+ })+ .and_then(|v| v.downcast::<CFNumber>().ok())+ .and_then(|n| n.as_i32())+ .unwrap_or(1);+ let img = if (2..=8).contains(&orientation) {+ let plain = unsafe { src.image_at_index(idx, Some(no_cache.as_opaque())) }.ok_or("corrupt image")?;+ let side = CGImage::width(Some(&plain)).max(CGImage::height(Some(&plain)));+ let max = CFNumber::new_i64(side as i64);+ let t = objc2_core_foundation::CFBoolean::new(true);+ let opts = CFDictionary::<CFString, CFType>::from_slices(+ &[unsafe { kCGImageSourceCreateThumbnailWithTransform }, unsafe { kCGImageSourceCreateThumbnailFromImageAlways }, unsafe { kCGImageSourceThumbnailMaxPixelSize }, unsafe { kCGImageSourceShouldCache }],+ &[t as &CFType, t as &CFType, &*max as &CFType, objc2_core_foundation::CFBoolean::new(false) as &CFType],+ );+ unsafe { src.thumbnail_at_index(idx, Some(opts.as_opaque())) }.unwrap_or(plain)+ } else {+ unsafe { src.image_at_index(idx, Some(no_cache.as_opaque())) }.ok_or("corrupt image")?+ };+ to_premultiplied_rgba(&img).ok_or_else(|| "could not read image pixels".into())+}++fn is_srgb_or_untagged(cs: &CGColorSpace) -> bool {+ if CGColorSpace::model(Some(cs)) != CGColorSpaceModel::RGB {+ return false;+ }+ match CGColorSpace::name(Some(cs)) {+ Some(n) => {+ let n = n.to_string();+ n == "kCGColorSpaceSRGB" || n == "kCGColorSpaceDeviceRGB" || n == "kCGColorSpaceGenericRGB" && CGColorSpace::icc_data(Some(cs)).is_none()+ }+ None => CGColorSpace::icc_data(Some(cs)).is_none_or(|icc| is_srgb_icc(&icc.to_vec())),+ }+}++/// An embedded ICC profile that describes sRGB (the common "sRGB IEC61966-2.1" profiles).+fn is_srgb_icc(icc: &[u8]) -> bool {+ // 'desc' tag text contains "sRGB" in practically every sRGB profile in the wild.+ icc.len() > 132 && icc.windows(4).any(|w| w == b"sRGB")+}++/// Pixels of a CGImage as premultiplied sRGB RGBA, copying directly when the layout allows+/// (exact: PNG round trips stay bit-identical), drawing through CoreGraphics otherwise.+pub(crate) fn to_premultiplied_rgba(img: &CGImage) -> Option<Decoded> {+ let w = CGImage::width(Some(img));+ let h = CGImage::height(Some(img));+ if w == 0 || h == 0 || w > 32767 || h > 32767 || w * h > 268_435_456 {+ return None;+ }+ let bpc = CGImage::bits_per_component(Some(img));+ let bpp = CGImage::bits_per_pixel(Some(img));+ let alpha = CGImage::alpha_info(Some(img));+ let order = CGImage::byte_order_info(Some(img));+ let float = CGImage::bitmap_info(Some(img)).0 & (1 << 8) != 0;+ let cs = CGImage::color_space(Some(img));+ let direct = bpc == 8 && !float && (bpp == 24 || bpp == 32) && cs.as_deref().is_some_and(is_srgb_or_untagged) && CGImage::decode(Some(img)).is_null();+ if direct {+ if let Some(provider) = CGImage::data_provider(Some(img)) {+ if let Some(bytes) = CGDataProvider::data(Some(&provider)) {+ let src = bytes.to_vec();+ let stride = CGImage::bytes_per_row(Some(img));+ if src.len() >= stride * (h - 1) + w * bpp / 8 {+ if let Some(out) = convert_8bit(&src, w, h, stride, bpp, alpha, order) {+ return Some(Decoded { width: w as u32, height: h as u32, data: out });+ }+ }+ }+ }+ }+ let mut out = vec![0u8; w * h * 4];+ let cg = unsafe { CGBitmapContextCreate(out.as_mut_ptr().cast(), w, h, 8, w * 4, Some(&srgb()), CGImageAlphaInfo::PremultipliedLast.0) }?;+ CGContext::set_blend_mode(Some(&cg), objc2_core_graphics::CGBlendMode::Copy);+ CGContext::draw_image(Some(&cg), CGRect { origin: CGPoint { x: 0.0, y: 0.0 }, size: CGSize { width: w as CGFloat, height: h as CGFloat } }, Some(img));+ drop(cg);+ Some(Decoded { width: w as u32, height: h as u32, data: out })+}++#[inline]+pub(crate) fn premul(c: u8, a: u8) -> u8 {+ ((c as u32 * a as u32 + 127) / 255) as u8+}++#[inline]+pub(crate) fn unpremul(c: u8, a: u8) -> u8 {+ if a == 0 {+ 0+ } else if a == 255 {+ c+ } else {+ ((c as u32 * 255 + a as u32 / 2) / a as u32).min(255) as u8+ }+}++fn convert_8bit(src: &[u8], w: usize, h: usize, stride: usize, bpp: usize, alpha: CGImageAlphaInfo, order: CGImageByteOrderInfo) -> Option<Vec<u8>> {+ let little = order == CGImageByteOrderInfo::Order32Little;+ if !(order == CGImageByteOrderInfo::OrderDefault || order == CGImageByteOrderInfo::Order32Big || little) {+ return None;+ }+ let mut out = vec![0u8; w * h * 4];+ // For each layout: byte offsets of r, g, b, a (a = None for opaque) and whether premultiplied.+ let (r, g, b, a, pre): (usize, usize, usize, Option<usize>, bool) = match (bpp, alpha, little) {+ (24, CGImageAlphaInfo::None, false) => (0, 1, 2, None, false),+ (32, CGImageAlphaInfo::NoneSkipLast, false) => (0, 1, 2, None, false),+ (32, CGImageAlphaInfo::NoneSkipFirst, false) => (1, 2, 3, None, false),+ (32, CGImageAlphaInfo::Last, false) => (0, 1, 2, Some(3), false),+ (32, CGImageAlphaInfo::First, false) => (1, 2, 3, Some(0), false),+ (32, CGImageAlphaInfo::PremultipliedLast, false) => (0, 1, 2, Some(3), true),+ (32, CGImageAlphaInfo::PremultipliedFirst, false) => (1, 2, 3, Some(0), true),+ // 32-bit little endian: the word is read backwards+ (32, CGImageAlphaInfo::NoneSkipLast, true) => (3, 2, 1, None, false),+ (32, CGImageAlphaInfo::NoneSkipFirst, true) => (2, 1, 0, None, false),+ (32, CGImageAlphaInfo::Last, true) => (3, 2, 1, Some(0), false),+ (32, CGImageAlphaInfo::First, true) => (2, 1, 0, Some(3), false),+ (32, CGImageAlphaInfo::PremultipliedLast, true) => (3, 2, 1, Some(0), true),+ (32, CGImageAlphaInfo::PremultipliedFirst, true) => (2, 1, 0, Some(3), true),+ _ => return None,+ };+ let px = bpp / 8;+ for y in 0..h {+ let row = &src[y * stride..];+ let dst = &mut out[y * w * 4..(y + 1) * w * 4];+ for x in 0..w {+ let s = &row[x * px..x * px + px];+ let d = &mut dst[x * 4..x * 4 + 4];+ match a {+ None => {+ d[0] = s[r];+ d[1] = s[g];+ d[2] = s[b];+ d[3] = 255;+ }+ Some(ai) => {+ let al = s[ai];+ if pre {+ d[0] = s[r].min(al);+ d[1] = s[g].min(al);+ d[2] = s[b].min(al);+ } else {+ d[0] = premul(s[r], al);+ d[1] = premul(s[g], al);+ d[2] = premul(s[b], al);+ }+ d[3] = al;+ }+ }+ }+ }+ Some(out)+}++/// Output format of an encode.+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum Format {+ Png,+ Jpeg(f64),+}++impl Format {+ /// `canvas.toDataURL(type, quality)` semantics: unknown types fall back to PNG; JPEG quality+ /// outside 0..1 uses the default 0.92.+ pub fn from_mime(mime: &str, quality: Option<f64>) -> Format {+ match mime.trim().to_ascii_lowercase().as_str() {+ "image/jpeg" | "image/jpg" => Format::Jpeg(quality.filter(|q| (0.0..=1.0).contains(q)).unwrap_or(0.92)),+ _ => Format::Png,+ }+ }+ pub fn mime(self) -> &'static str {+ match self {+ Format::Png => "image/png",+ Format::Jpeg(_) => "image/jpeg",+ }+ }+}++/// Encode RGBA8 pixels (rows top-down, stride `w*4`). `premultiplied` says how `rgba` is stored.+/// JPEG has no alpha: pixels are composited onto black, as browsers do.+pub fn encode(w: u32, h: u32, rgba: &[u8], premultiplied: bool, format: Format) -> Option<Vec<u8>> {+ let (w, h) = (w as usize, h as usize);+ if w == 0 || h == 0 || rgba.len() < w * h * 4 {+ return None;+ }+ let src = &rgba[..w * h * 4];+ let (pixels, info): (Vec<u8>, CGImageAlphaInfo) = match format {+ Format::Png => {+ let opaque = src.chunks_exact(4).all(|p| p[3] == 255);+ if opaque {+ (src.to_vec(), CGImageAlphaInfo::NoneSkipLast)+ } else if premultiplied {+ let mut v = src.to_vec();+ for p in v.chunks_exact_mut(4) {+ let a = p[3];+ p[0] = unpremul(p[0], a);+ p[1] = unpremul(p[1], a);+ p[2] = unpremul(p[2], a);+ }+ (v, CGImageAlphaInfo::Last)+ } else {+ (src.to_vec(), CGImageAlphaInfo::Last)+ }+ }+ Format::Jpeg(_) => {+ let mut v = src.to_vec();+ if !premultiplied {+ for p in v.chunks_exact_mut(4) {+ let a = p[3];+ p[0] = premul(p[0], a);+ p[1] = premul(p[1], a);+ p[2] = premul(p[2], a);+ }+ }+ for p in v.chunks_exact_mut(4) {+ p[3] = 255;+ }+ (v, CGImageAlphaInfo::NoneSkipLast)+ }+ };+ let data = CFData::from_bytes(&pixels);+ let provider = CGDataProvider::with_cf_data(Some(&data))?;+ let image = unsafe {+ CGImage::new(w, h, 8, 32, w * 4, Some(&srgb()), CGBitmapInfo(info.0), Some(&provider), std::ptr::null(), false, CGColorRenderingIntent::RenderingIntentDefault)+ }?;+ let out = CFMutableData::new(None, 0)?;+ let uti = CFString::from_static_str(match format {+ Format::Png => "public.png",+ Format::Jpeg(_) => "public.jpeg",+ });+ let dest = unsafe { CGImageDestination::with_data(&out, &uti, 1, None) }?;+ match format {+ Format::Jpeg(q) => {+ let qn = CFNumber::new_f64(q);+ let props = CFDictionary::<CFString, CFType>::from_slices(&[unsafe { kCGImageDestinationLossyCompressionQuality }], &[&*qn as &CFType]);+ unsafe { dest.add_image(&image, Some(props.as_opaque())) };+ }+ Format::Png => unsafe { dest.add_image(&image, None) },+ }+ if !unsafe { dest.finalize() } {+ return None;+ }+ Some(out.to_vec())+}++// ------------------------------------------------------------------------------------- base64++const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";++pub fn base64_encode_into(out: &mut String, bytes: &[u8]) {+ out.reserve(bytes.len().div_ceil(3) * 4);+ let mut chunks = bytes.chunks_exact(3);+ for c in &mut chunks {+ let n = (c[0] as u32) << 16 | (c[1] as u32) << 8 | c[2] as u32;+ out.push(B64[(n >> 18) as usize & 63] as char);+ out.push(B64[(n >> 12) as usize & 63] as char);+ out.push(B64[(n >> 6) as usize & 63] as char);+ out.push(B64[n as usize & 63] as char);+ }+ match chunks.remainder() {+ [a] => {+ let n = (*a as u32) << 16;+ out.push(B64[(n >> 18) as usize & 63] as char);+ out.push(B64[(n >> 12) as usize & 63] as char);+ out.push_str("==");+ }+ [a, b] => {+ let n = (*a as u32) << 16 | (*b as u32) << 8;+ out.push(B64[(n >> 18) as usize & 63] as char);+ out.push(B64[(n >> 12) as usize & 63] as char);+ out.push(B64[(n >> 6) as usize & 63] as char);+ out.push('=');+ }+ _ => {}+ }+}++/// Forgiving base64 (whitespace ignored, padding optional, URL-safe alphabet accepted).+pub fn base64_decode(s: &[u16]) -> Option<Vec<u8>> {+ let mut out = Vec::with_capacity(s.len() * 3 / 4);+ let mut acc: u32 = 0;+ let mut bits = 0;+ for &c in s {+ let v = match c {+ 0x41..=0x5A => c - 0x41,+ 0x61..=0x7A => c - 0x61 + 26,+ 0x30..=0x39 => c - 0x30 + 52,+ 0x2B | 0x2D => 62,+ 0x2F | 0x5F => 63,+ 0x3D => break,+ 0x20 | 0x09 | 0x0A | 0x0C | 0x0D => continue,+ _ => return None,+ } as u32;+ acc = acc << 6 | v;+ bits += 6;+ if bits >= 8 {+ bits -= 8;+ out.push((acc >> bits) as u8);+ }+ }+ Some(out)+}++/// Bytes of a `data:` URL (base64 or percent-encoded payload) and its MIME type.+pub fn parse_data_url(url: &[u16]) -> Option<(String, Vec<u8>)> {+ let comma = url.iter().position(|&c| c == b',' as u16)?;+ let head = String::from_utf16_lossy(&url[..comma]);+ let head = head.trim();+ let meta = head.get(..5).filter(|p| p.eq_ignore_ascii_case("data:")).map(|_| &head[5..])?;+ let body = &url[comma + 1..];+ let is_b64 = meta.to_ascii_lowercase().split(';').any(|p| p.trim() == "base64");+ let mime = meta.split(';').next().unwrap_or("").trim().to_ascii_lowercase();+ let bytes = if is_b64 {+ base64_decode(body)?+ } else {+ let s = String::from_utf16_lossy(body);+ let mut out = Vec::with_capacity(s.len());+ let b = s.as_bytes();+ let mut i = 0;+ while i < b.len() {+ if b[i] == b'%' && i + 2 < b.len() {+ if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) {+ out.push(v);+ i += 3;+ continue;+ }+ }+ out.push(b[i]);+ i += 1;+ }+ out+ };+ Some((mime, bytes))+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn b64_roundtrip() {+ for n in 0..20 {+ let v: Vec<u8> = (0..n).map(|i| (i * 37 + 11) as u8).collect();+ let mut s = String::new();+ base64_encode_into(&mut s, &v);+ let u: Vec<u16> = s.encode_utf16().collect();+ assert_eq!(base64_decode(&u).unwrap(), v);+ }+ }+ #[test]+ fn png_roundtrip_exact() {+ let (w, h) = (7u32, 5u32);+ let mut px = vec![0u8; 7 * 5 * 4];+ for (i, p) in px.chunks_exact_mut(4).enumerate() {+ let a = (i * 23 % 256) as u8;+ p[3] = a;+ p[0] = premul((i * 7) as u8, a);+ p[1] = premul((i * 13) as u8, a);+ p[2] = premul((i * 29) as u8, a);+ }+ let png = encode(w, h, &px, true, Format::Png).unwrap();+ let d = decode(&png).unwrap();+ assert_eq!((d.width, d.height), (w, h));+ assert_eq!(d.data, px);+ }+}diff --git a/runtime/crates/canvas2d/src/fonts.rs b/runtime/crates/canvas2d/src/fonts.rsnew file mode 100644index 0000000..4fd2a3e--- /dev/null+++ b/runtime/crates/canvas2d/src/fonts.rs@@ -0,0 +1,1060 @@+//! Fonts shared by canvas text and the UI engine: bundled font registration, the CSS `font`+//! shorthand, and CSS font matching on CoreText that behaves like Chrome on macOS.+//!+//! * Family lists are walked in order; the first family that exists supplies the *primary* font+//! (metrics, baselines). Characters it lacks fall back through the remaining families, then the+//! system (CoreText's per-character fallback, which is what Chrome calls too).+//! * Faces within a family are chosen with the CSS Fonts 4 weight/style algorithm. Requests of+//! weight ≥ 600 that land on a lighter face get Chrome's synthetic bold (a Skia-style outline+//! stroke, see [`fake_bold_stroke`]); italic requests on upright-only families get a −¼ skew.+//! * Generic families resolve like Chrome's macOS defaults (verified against Chrome 158):+//! `serif` → Times, `sans-serif` → Helvetica, `monospace` → Courier, `cursive` → Apple Chancery,+//! `fantasy` → Papyrus, `system-ui` / `BlinkMacSystemFont` → the system UI font. Chrome does not+//! support `-apple-system` or `ui-monospace`; like Chrome they match nothing (and fall through).+//! * Bundled fonts (`<bundle>/fonts`, Nunito 600/800 and ZCOOL KuaiLe, the game's Google Fonts)+//! take precedence over installed fonts of the same family name, as @font-face rules do.+use std::cell::RefCell;+use std::collections::HashMap;+use std::path::PathBuf;+use std::ptr::NonNull;+use std::rc::Rc;+use std::sync::{Mutex, Once};++use objc2_core_foundation::{CFArray, CFDictionary, CFNumber, CFRange, CFRetained, CFSet, CFString, CFType, CFURL, CGAffineTransform, CGFloat};+use objc2_core_text::{+ kCTFontCascadeListAttribute, kCTFontFamilyNameAttribute, kCTFontTraitsAttribute, kCTFontWeightTrait, kCTFontWidthTrait, CTFont,+ CTFontDescriptor, CTFontManagerCopyAvailableFontFamilyNames, CTFontManagerCreateFontDescriptorsFromURL, CTFontManagerRegisterFontsForURL,+ CTFontManagerScope, CTFontSymbolicTraits, CTFontTableOptions, CTFontUIFontType,+};++/// What to look up: a CSS family list plus weight/style/size.+pub struct FontQuery<'a> {+ pub families: &'a [String],+ pub weight: u16,+ pub italic: bool,+ pub size: f64,+}++/// A resolved font at a size.+pub struct Font {+ /// The primary face at `size`, with a cascade list for the remaining CSS families and the+ /// system fallbacks (emoji, CJK) — for consumers that let CoreText do fallback. For+ /// Chrome-exact fallback (which face, synthetic bold per face) itemize with [`Font::runs`].+ pub ct: CFRetained<CTFont>,+ /// requested weight ≥ 600 but the face is lighter: embolden like Skia (see [`fake_bold_stroke`])+ pub synthetic_bold: bool,+ /// italic requested but the family has no italic/oblique face: skew x by −¼ (y-down)+ pub synthetic_italic: bool,+ /// CoreText metrics of the primary face (unrounded, px)+ pub ascent: f64,+ pub descent: f64,+ pub line_gap: f64,+ pub x_height: f64,+ pub cap_height: f64,+ // ---- extensions+ pub size: f64,+ /// the weight that was asked for+ pub weight: u16,+ pub italic: bool,+ /// family name of the primary face+ pub family: String,+ /// `ct` without a cascade list (what glyph runs are drawn with)+ pub plain: CFRetained<CTFont>,+ /// a color (emoji) font: glyphs are bitmaps, never emboldened+ pub color: bool,+ /// the rest of the CSS family list, already matched (fallback order)+ chain: Vec<Rc<Font>>,+ /// OS/2 typo ascender/descender in px, when the face has them+ typo: Option<(f64, f64)>,+ /// cache for system fallback fonts by PostScript name+ fallbacks: RefCell<HashMap<String, Rc<Font>>>,+}++/// One run of text that uses one face (see [`Font::runs`]).+pub struct FontRun {+ /// UTF-16 range in the text+ pub start: usize,+ pub end: usize,+ pub font: Rc<Font>,+}++/// Blink's line metrics for a font (what `line-height: normal` and canvas text metrics use).+#[derive(Clone, Copy, Debug)]+pub struct LineMetrics {+ pub ascent: f64,+ pub descent: f64,+ pub line_gap: f64,+}++impl LineMetrics {+ /// `line-height: normal`+ pub fn line_spacing(&self) -> f64 {+ self.ascent + self.descent + self.line_gap+ }+}++impl Font {+ /// Ascent/descent rounded the way Blink's `FontMetrics` does on macOS (including the+ /// Times/Helvetica/Courier ascent hack that keeps line heights compatible with Safari).+ pub fn line_metrics(&self) -> LineMetrics {+ let mut ascent = self.ascent.round();+ let descent = self.descent.round();+ let line_gap = self.line_gap.round();+ if matches!(self.family.as_str(), "Times" | "Helvetica" | "Courier") {+ ascent += ((ascent + descent) * 0.15 + 0.5).floor();+ }+ LineMetrics { ascent, descent, line_gap }+ }++ /// Normalized OS/2 typo ascent/descent summing to the em size (Blink's+ /// `NormalizedTypoAscentAndDescent`, used for canvas `top`/`middle`/`bottom` baselines and the+ /// em-height text metrics). Values are LayoutUnit-rounded (1/64 px) like Blink.+ pub fn em_ascent_descent(&self) -> (f64, f64) {+ let lu = |v: f64| (v * 64.0).round() / 64.0;+ let (asc, height) = match self.typo {+ Some((a, d)) => (a, a + d),+ None => {+ let m = self.line_metrics();+ (m.ascent, m.ascent + m.descent)+ }+ };+ if height <= 0.0 || asc < 0.0 || asc > height {+ let half = lu(self.size / 2.0);+ return (half, half);+ }+ let a = lu(asc * self.size / height);+ (a, lu(self.size) - a)+ }++ /// Split `text` (UTF-16) into runs by the face that renders them, the way Chrome's font+ /// fallback does: each grapheme goes to the first font in the CSS list that has all its+ /// characters (emoji-presentation graphemes prefer color fonts), else to the system fallback+ /// font for it. Fallback faces get synthetic bold/italic by the same rules as the primary.+ pub fn runs(self: &Rc<Self>, text: &[u16]) -> Vec<FontRun> {+ let mut runs: Vec<FontRun> = Vec::new();+ let mut i = 0;+ while i < text.len() {+ let end = grapheme_end(text, i);+ let cluster = &text[i..end];+ let font = self.font_for(cluster, text, i);+ match runs.last_mut() {+ Some(r) if Rc::ptr_eq(&r.font, &font) => r.end = end,+ _ => runs.push(FontRun { start: i, end, font }),+ }+ i = end;+ }+ runs+ }++ fn font_for(self: &Rc<Self>, cluster: &[u16], text: &[u16], at: usize) -> Rc<Font> {+ // Whitespace and controls stay with the current font (Chrome keeps spaces in the primary+ // font's run unless it lacks a space glyph).+ let first = decode_utf16_at(cluster, 0).0;+ let emoji = is_emoji_cluster(cluster);+ let candidates = std::iter::once(self).chain(self.chain.iter());+ let mut first_with_glyphs: Option<&Rc<Font>> = None;+ for f in candidates {+ if has_glyphs(&f.plain, cluster) {+ if !emoji || f.color {+ return f.clone();+ }+ first_with_glyphs.get_or_insert(f);+ }+ }+ if emoji {+ if let Some(e) = self.emoji_font() {+ if has_glyphs(&e.plain, cluster) {+ return e;+ }+ }+ }+ if let Some(f) = first_with_glyphs {+ return f.clone();+ }+ if first < 0x20 || (0x7f..0xa0).contains(&first) || is_default_ignorable(first) {+ return self.clone();+ }+ self.system_fallback(text, at, cluster.len())+ }++ fn emoji_font(self: &Rc<Self>) -> Option<Rc<Font>> {+ let key = "AppleColorEmoji".to_string();+ if let Some(f) = self.fallbacks.borrow().get(&key) {+ return Some(f.clone());+ }+ let fam = family("Apple Color Emoji")?;+ let face = fam.faces.first()?.clone();+ let f = Rc::new(make_font(&face, self.size, self.weight, self.italic, false, Vec::new()));+ self.fallbacks.borrow_mut().insert(key, f.clone());+ Some(f)+ }++ fn system_fallback(self: &Rc<Self>, text: &[u16], at: usize, len: usize) -> Rc<Font> {+ let s = cfstring_utf16(text);+ let ct = unsafe { self.plain.for_string_with_language(&s, CFRange { location: at as isize, length: len as isize }, None) };+ let ps = unsafe { ct.post_script_name() }.to_string();+ if ps == unsafe { self.plain.post_script_name() }.to_string() {+ return self.clone();+ }+ if let Some(f) = self.fallbacks.borrow().get(&ps) {+ return f.clone();+ }+ let desc = unsafe { ct.font_descriptor() };+ let face = face_from_descriptor(desc).unwrap_or_else(|| Face { desc: unsafe { ct.font_descriptor() }, weight: 400, italic: false, normal_width: true, system_ui: None });+ let synth_bold = self.weight >= 600 && face.weight < 600;+ let synth_italic = self.italic && !face.italic;+ let f = Rc::new(make_font(&face, self.size, self.weight, self.italic, synth_bold || self.synthetic_bold && synth_bold, Vec::new()).with_synthetic_italic(synth_italic));+ self.fallbacks.borrow_mut().insert(ps, f.clone());+ f+ }++ fn with_synthetic_italic(mut self, on: bool) -> Self {+ self.synthetic_italic = on;+ self+ }+}++impl std::fmt::Debug for Font {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "Font({} {}px w{} sb={} si={})", self.family, self.size, self.weight, self.synthetic_bold, self.synthetic_italic)+ }+}++/// A parsed CSS `font` shorthand.+#[derive(Clone, Debug, PartialEq)]+pub struct ParsedFont {+ pub families: Vec<String>,+ pub weight: u16,+ pub italic: bool,+ /// px+ pub size: f64,+ pub line_height: Option<String>,+ // ---- extensions+ pub small_caps: bool,+ /// font-stretch keyword other than `normal`, as written+ pub stretch: Option<String>,+ /// `oblique` (vs `italic`) — both select slanted faces+ pub oblique: bool,+}++impl ParsedFont {+ /// Chrome's serialization of `ctx.font` (style, weight, variant, size, families).+ pub fn to_css(&self) -> String {+ let mut s = String::new();+ if self.italic {+ s.push_str(if self.oblique { "oblique " } else { "italic " });+ }+ match self.weight {+ 400 => {}+ 700 => s.push_str("bold "),+ w => {+ s.push_str(&w.to_string());+ s.push(' ');+ }+ }+ if self.small_caps {+ s.push_str("small-caps ");+ }+ s.push_str(&fmt_num(self.size));+ s.push_str("px ");+ for (i, f) in self.families.iter().enumerate() {+ if i > 0 {+ s.push_str(", ");+ }+ if is_generic(f) || (is_identifier_sequence(f) && !f.contains(' ')) {+ s.push_str(f);+ } else {+ s.push('"');+ s.push_str(&f.replace('\\', "\\\\").replace('"', "\\\""));+ s.push('"');+ }+ }+ s+ }+}++/// Shortest decimal for a CSS number (Chrome prints up to 6 significant digits).+pub fn fmt_num(v: f64) -> String {+ if v == v.trunc() && v.abs() < 1e15 {+ return format!("{}", v as i64);+ }+ let s = format!("{:.6}", v);+ let s = s.trim_end_matches('0').trim_end_matches('.');+ s.to_string()+}++fn is_generic(f: &str) -> bool {+ matches!(f, "serif" | "sans-serif" | "monospace" | "cursive" | "fantasy" | "system-ui" | "math" | "emoji" | "fangsong" | "ui-serif" | "ui-sans-serif" | "ui-monospace" | "ui-rounded")+}++fn is_identifier_sequence(f: &str) -> bool {+ f.split(' ').all(|w| {+ let mut ch = w.chars();+ match ch.next() {+ None => false,+ Some(c) if c.is_ascii_digit() => false,+ Some('-') => {+ let rest: Vec<char> = w.chars().skip(1).collect();+ !rest.is_empty() && !rest[0].is_ascii_digit() && rest.iter().all(|c| c.is_alphanumeric() || *c == '-' || *c == '_' || !c.is_ascii())+ }+ Some(c) => (c.is_alphabetic() || c == '_' || !c.is_ascii()) && ch.all(|c| c.is_alphanumeric() || c == '-' || c == '_' || !c.is_ascii()),+ }+ })+}++/// Parse a CSS `font` shorthand (as accepted by `ctx.font` and the `font` property). Relative+/// sizes resolve against the canvas default (10px); keywords use Chrome's defaults (medium 16px).+pub fn parse_shorthand(css_font: &str) -> Option<ParsedFont> {+ let s = css_font.trim();+ if s.is_empty() {+ return None;+ }+ let lower = s.to_ascii_lowercase();+ if matches!(lower.as_str(), "inherit" | "initial" | "unset" | "revert" | "revert-layer") {+ return None;+ }+ // System font keywords (Chrome on macOS: the system font at 13px).+ if matches!(lower.as_str(), "caption" | "icon" | "menu" | "message-box" | "small-caption" | "status-bar") {+ return Some(ParsedFont { families: vec!["system-ui".into()], weight: 400, italic: false, size: 13.0, line_height: None, small_caps: false, stretch: None, oblique: false });+ }+ let mut p = ParsedFont { families: Vec::new(), weight: 400, italic: false, size: 0.0, line_height: None, small_caps: false, stretch: None, oblique: false };+ let mut rest = s;+ let mut seen_style = false;+ let mut seen_weight = false;+ let mut seen_variant = false;+ let mut seen_stretch = false;+ let mut normals = 0;+ loop {+ rest = rest.trim_start();+ let tok_end = rest.find(|c: char| c.is_whitespace()).unwrap_or(rest.len());+ let tok = &rest[..tok_end];+ if tok.is_empty() {+ return None;+ }+ let t = tok.to_ascii_lowercase();+ // A size token (possibly "12px/1.5") ends the prefix.+ let size_part = t.split('/').next().unwrap_or("");+ if let Some(px) = parse_font_size(size_part) {+ p.size = px;+ let mut after = &rest[tok_end..];+ if let Some(slash) = tok.find('/') {+ let lh = &tok[slash + 1..];+ if lh.is_empty() {+ after = after.trim_start();+ let e = after.find(|c: char| c.is_whitespace()).unwrap_or(after.len());+ p.line_height = Some(after[..e].to_string());+ after = &after[e..];+ } else {+ p.line_height = Some(lh.to_string());+ }+ } else {+ let a = after.trim_start();+ if let Some(lh) = a.strip_prefix('/') {+ let lh = lh.trim_start();+ let e = lh.find(|c: char| c.is_whitespace()).unwrap_or(lh.len());+ if e == 0 {+ return None;+ }+ p.line_height = Some(lh[..e].to_string());+ after = &lh[e..];+ }+ }+ p.families = parse_families(after)?;+ return Some(p);+ }+ match t.as_str() {+ "normal" => normals += 1,+ "italic" if !seen_style => {+ seen_style = true;+ p.italic = true;+ }+ "oblique" if !seen_style => {+ seen_style = true;+ p.italic = true;+ p.oblique = true;+ }+ "small-caps" if !seen_variant => {+ seen_variant = true;+ p.small_caps = true;+ }+ "bold" if !seen_weight => {+ seen_weight = true;+ p.weight = 700;+ }+ "bolder" if !seen_weight => {+ seen_weight = true;+ p.weight = 700;+ }+ "lighter" if !seen_weight => {+ seen_weight = true;+ p.weight = 100;+ }+ "ultra-condensed" | "extra-condensed" | "condensed" | "semi-condensed" | "semi-expanded" | "expanded" | "extra-expanded" | "ultra-expanded" if !seen_stretch => {+ seen_stretch = true;+ p.stretch = Some(t.clone());+ }+ _ => {+ if !seen_weight {+ if let Ok(w) = t.parse::<f64>() {+ if (1.0..=1000.0).contains(&w) && !t.starts_with('+') {+ seen_weight = true;+ p.weight = w.round() as u16;+ rest = &rest[tok_end..];+ continue;+ }+ }+ }+ return None;+ }+ }+ if normals > 4 {+ return None;+ }+ rest = &rest[tok_end..];+ }+}++fn parse_font_size(t: &str) -> Option<f64> {+ let kw = match t {+ "xx-small" => Some(9.0),+ "x-small" => Some(10.0),+ "small" => Some(13.0),+ "medium" => Some(16.0),+ "large" => Some(18.0),+ "x-large" => Some(24.0),+ "xx-large" => Some(32.0),+ "xxx-large" => Some(48.0),+ "larger" => Some(12.0),+ "smaller" => Some(8.333333),+ _ => None,+ };+ if kw.is_some() {+ return kw;+ }+ let num_end = t.find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-' || c == '+' || c == 'e' || c == 'E')).unwrap_or(t.len());+ // "e" may begin a unit ("em", "ex"): back off if what follows is a letter+ let mut num_end = num_end;+ while num_end > 0 && matches!(t.as_bytes()[num_end - 1], b'e' | b'E') {+ num_end -= 1;+ }+ let (n, unit) = t.split_at(num_end);+ let v: f64 = n.parse().ok()?;+ if !v.is_finite() || v < 0.0 {+ return None;+ }+ let px = match unit {+ "px" => v,+ "pt" => v * 4.0 / 3.0,+ "pc" => v * 16.0,+ "in" => v * 96.0,+ "cm" => v * 96.0 / 2.54,+ "mm" => v * 96.0 / 25.4,+ "q" => v * 96.0 / 101.6,+ "em" | "%" if unit == "%" => v * 10.0 / 100.0,+ "em" => v * 10.0,+ "rem" => v * 16.0,+ "ex" => v * 5.0,+ "ch" => v * 5.0,+ "" if v == 0.0 => 0.0,+ _ => return None,+ };+ Some(px)+}++fn parse_families(s: &str) -> Option<Vec<String>> {+ let mut out = Vec::new();+ let mut chars = s.trim().chars().peekable();+ loop {+ while chars.peek().is_some_and(|c| c.is_whitespace()) {+ chars.next();+ }+ let Some(&c) = chars.peek() else { break };+ if c == '"' || c == '\'' {+ chars.next();+ let mut name = String::new();+ let mut closed = false;+ while let Some(ch) = chars.next() {+ if ch == '\\' {+ if let Some(n) = chars.next() {+ name.push(n);+ }+ } else if ch == c {+ closed = true;+ break;+ } else {+ name.push(ch);+ }+ }+ if !closed {+ return None;+ }+ out.push(name);+ while chars.peek().is_some_and(|c| c.is_whitespace()) {+ chars.next();+ }+ match chars.next() {+ None => break,+ Some(',') => continue,+ Some(_) => return None,+ }+ } else {+ let mut name = String::new();+ for ch in chars.by_ref() {+ if ch == ',' {+ break;+ }+ name.push(ch);+ }+ let words: Vec<&str> = name.split_whitespace().collect();+ if words.is_empty() {+ return None;+ }+ let joined = words.join(" ");+ if !is_identifier_sequence(&joined) {+ return None;+ }+ let lower = joined.to_ascii_lowercase();+ if words.len() == 1 && (is_generic(&lower) || lower == "-webkit-body" || lower == "-webkit-standard") {+ out.push(lower);+ } else if words.len() == 1 && matches!(lower.as_str(), "inherit" | "initial" | "unset" | "default" | "revert") {+ return None;+ } else {+ out.push(joined);+ }+ }+ }+ if out.is_empty() { None } else { Some(out) }+}++/// Stroke width (px) that reproduces Skia's fake bold at `size`: Skia strokes glyph outlines with+/// `size × k`, k interpolated from 1/24 at 9px to 1/32 at 36px (clamped outside).+pub fn fake_bold_stroke(size: f64) -> f64 {+ let k = if size <= 9.0 {+ 1.0 / 24.0+ } else if size >= 36.0 {+ 1.0 / 32.0+ } else {+ let t = (size - 9.0) / (36.0 - 9.0);+ 1.0 / 24.0 + t * (1.0 / 32.0 - 1.0 / 24.0)+ };+ size * k+}++// ------------------------------------------------------------------------------------ registry++static FONT_DIR: Mutex<Option<PathBuf>> = Mutex::new(None);+static REGISTER: Once = Once::new();+static FONT_FILES: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());++pub(crate) fn set_dir(dir: PathBuf) {+ *FONT_DIR.lock().unwrap() = Some(dir);+}++/// Register the bundled fonts with CoreText for this process (idempotent, any thread).+pub(crate) fn register() {+ REGISTER.call_once(|| {+ let Some(dir) = FONT_DIR.lock().unwrap().clone() else { return };+ let Ok(rd) = std::fs::read_dir(&dir) else { return };+ let mut files: Vec<PathBuf> = rd+ .filter_map(|e| e.ok().map(|e| e.path()))+ .filter(|p| matches!(p.extension().and_then(|e| e.to_str()).map(|e| e.to_ascii_lowercase()).as_deref(), Some("ttf" | "otf" | "ttc")))+ .collect();+ files.sort();+ for f in &files {+ if let Some(url) = CFURL::from_file_path(f) {+ let ok = unsafe { CTFontManagerRegisterFontsForURL(&url, CTFontManagerScope::Process, std::ptr::null_mut()) };+ if !ok {+ // Already registered (e.g. a second page) is fine; anything else is worth a note.+ let _ = ok;+ }+ }+ }+ *FONT_FILES.lock().unwrap() = files;+ });+}++#[derive(Clone)]+struct Face {+ desc: CFRetained<CTFontDescriptor>,+ weight: u16,+ /// italic or oblique+ italic: bool,+ normal_width: bool,+ /// system UI font: weight is applied through the weight trait at creation+ system_ui: Option<f64>,+}++struct Family {+ #[allow(dead_code)]+ name: String,+ faces: Vec<Face>,+}++thread_local! {+ static BUNDLED: RefCell<Option<HashMap<String, Rc<Family>>>> = const { RefCell::new(None) };+ static SYSTEM_NAMES: RefCell<Option<HashMap<String, String>>> = const { RefCell::new(None) };+ static FAMILIES: RefCell<HashMap<String, Option<Rc<Family>>>> = RefCell::new(HashMap::new());+ static FONTS: RefCell<HashMap<(String, u16, bool, u64), Rc<Font>>> = RefCell::new(HashMap::new());+}++fn bundled() -> HashMap<String, Rc<Family>> {+ BUNDLED.with(|b| {+ if let Some(m) = b.borrow().as_ref() {+ return m.clone();+ }+ register();+ let mut fams: HashMap<String, Family> = HashMap::new();+ for f in FONT_FILES.lock().unwrap().iter() {+ let Some(url) = CFURL::from_file_path(f) else { continue };+ let Some(descs) = (unsafe { CTFontManagerCreateFontDescriptorsFromURL(&url) }) else { continue };+ let descs: CFRetained<CFArray<CTFontDescriptor>> = unsafe { CFRetained::cast_unchecked(descs) };+ for d in descs.iter() {+ let Some(name) = (unsafe { d.attribute(kCTFontFamilyNameAttribute) }).and_then(|v| v.downcast::<CFString>().ok()) else { continue };+ let name = name.to_string();+ let Some(face) = face_from_descriptor(d) else { continue };+ fams.entry(name.to_lowercase()).or_insert_with(|| Family { name: name.clone(), faces: Vec::new() }).faces.push(face);+ }+ }+ let m: HashMap<String, Rc<Family>> = fams.into_iter().map(|(k, v)| (k, Rc::new(v))).collect();+ *b.borrow_mut() = Some(m.clone());+ m+ })+}++fn system_family_name(lower: &str) -> Option<String> {+ SYSTEM_NAMES.with(|s| {+ if s.borrow().is_none() {+ let names = unsafe { CTFontManagerCopyAvailableFontFamilyNames() };+ let names: CFRetained<CFArray<CFString>> = unsafe { CFRetained::cast_unchecked(names) };+ let mut m = HashMap::new();+ for n in names.iter() {+ let n = n.to_string();+ m.entry(n.to_lowercase()).or_insert(n);+ }+ *s.borrow_mut() = Some(m);+ }+ s.borrow().as_ref().unwrap().get(lower).cloned()+ })+}++const OS2: u32 = u32::from_be_bytes(*b"OS/2");++fn os2(ct: &CTFont) -> Option<Vec<u8>> {+ let d = unsafe { ct.table(OS2, CTFontTableOptions::NoOptions) }?;+ Some(d.to_vec())+}++fn be_u16(b: &[u8], at: usize) -> Option<u16> {+ Some(u16::from_be_bytes([*b.get(at)?, *b.get(at + 1)?]))+}++/// Weight/style/width of a face, from its OS/2 table (what Chrome's matcher sees) with CoreText+/// traits as the fallback.+fn face_from_descriptor(desc: CFRetained<CTFontDescriptor>) -> Option<Face> {+ let ct = unsafe { CTFont::with_font_descriptor(&desc, 16.0, std::ptr::null()) };+ let traits = unsafe { ct.symbolic_traits() };+ let mut italic = traits.contains(CTFontSymbolicTraits::TraitItalic);+ let mut weight = None;+ let mut width_class = 5u16;+ if let Some(t) = os2(&ct) {+ weight = be_u16(&t, 4).filter(|w| (1..=1000).contains(w));+ width_class = be_u16(&t, 6).unwrap_or(5);+ if let Some(sel) = be_u16(&t, 62) {+ italic |= sel & 1 != 0 || sel & (1 << 9) != 0;+ }+ }+ let weight = weight.unwrap_or_else(|| ct_weight_to_css(ct_weight_trait(&desc)));+ // Some fonts use 1..9 in usWeightClass (old convention).+ let weight = if weight < 10 { weight * 100 } else { weight };+ let normal_width = width_class == 5 || {+ let w = ct_trait(&desc, unsafe { kCTFontWidthTrait }).unwrap_or(0.0);+ w.abs() < 0.05+ };+ Some(Face { desc, weight, italic, normal_width, system_ui: None })+}++fn ct_trait(desc: &CTFontDescriptor, key: &CFString) -> Option<f64> {+ let traits = unsafe { desc.attribute(kCTFontTraitsAttribute) }?.downcast::<CFDictionary>().ok()?;+ let traits: CFRetained<CFDictionary<CFString, CFNumber>> = unsafe { CFRetained::cast_unchecked(traits) };+ traits.get(key)?.as_f64()+}++fn ct_weight_trait(desc: &CTFontDescriptor) -> f64 {+ ct_trait(desc, unsafe { kCTFontWeightTrait }).unwrap_or(0.0)+}++// CoreText weight trait ↔ CSS weight (AppKit's NSFontWeight constants).+const CT_WEIGHTS: [(f64, f64); 9] = [(-0.8, 100.0), (-0.6, 200.0), (-0.4, 300.0), (0.0, 400.0), (0.23, 500.0), (0.3, 600.0), (0.4, 700.0), (0.56, 800.0), (0.62, 900.0)];++fn ct_weight_to_css(w: f64) -> u16 {+ if w <= CT_WEIGHTS[0].0 {+ return 100;+ }+ for pair in CT_WEIGHTS.windows(2) {+ let (a, b) = (pair[0], pair[1]);+ if w <= b.0 {+ let t = (w - a.0) / (b.0 - a.0);+ return (a.1 + t * (b.1 - a.1)).round() as u16;+ }+ }+ 900+}++fn css_weight_to_ct(w: u16) -> f64 {+ let w = w as f64;+ if w <= 100.0 {+ return -0.8;+ }+ for pair in CT_WEIGHTS.windows(2) {+ let (a, b) = (pair[0], pair[1]);+ if w <= b.1 {+ let t = (w - a.1) / (b.1 - a.1);+ return a.0 + t * (b.0 - a.0);+ }+ }+ 0.62+}++fn generic_family(name: &str) -> Option<&'static str> {+ Some(match name {+ "serif" | "-webkit-standard" | "-webkit-body" => "Times",+ "sans-serif" => "Helvetica",+ "monospace" => "Courier",+ "cursive" => "Apple Chancery",+ "fantasy" => "Papyrus",+ _ => return None,+ })+}++fn family(name: &str) -> Option<Rc<Family>> {+ let lower = name.to_lowercase();+ if let Some(f) = FAMILIES.with(|m| m.borrow().get(&lower).cloned()) {+ return f;+ }+ let found = lookup_family(name, &lower);+ FAMILIES.with(|m| m.borrow_mut().insert(lower, found.clone()));+ found+}++fn lookup_family(original: &str, lower: &str) -> Option<Rc<Family>> {+ if lower == "system-ui" || lower == "blinkmacsystemfont" {+ let ui = unsafe { CTFont::new_ui_font_for_language(CTFontUIFontType::System, 16.0, None) }?;+ let desc = unsafe { ui.font_descriptor() };+ let faces = [100u16, 200, 300, 400, 500, 600, 700, 800, 900]+ .iter()+ .map(|&w| Face { desc: desc.clone(), weight: w, italic: false, normal_width: true, system_ui: Some(css_weight_to_ct(w)) })+ .collect();+ return Some(Rc::new(Family { name: "system-ui".into(), faces }));+ }+ if let Some(g) = generic_family(lower) {+ return family(g);+ }+ if let Some(f) = bundled().get(lower) {+ return Some(f.clone());+ }+ // Some installed families (Times, Courier on macOS 26) are hidden from the family list but+ // match by name, as they do in Chrome: try the listed spelling, then the name as written.+ let mut names: Vec<String> = Vec::new();+ if let Some(c) = system_family_name(lower) {+ names.push(c);+ }+ names.push(original.to_string());+ for candidate in names {+ let cfname = CFString::from_str(&candidate);+ let attrs = CFDictionary::<CFString, CFType>::from_slices(&[unsafe { kCTFontFamilyNameAttribute }], &[&*cfname as &CFType]);+ let desc = unsafe { CTFontDescriptor::with_attributes(attrs.as_opaque()) };+ let mut key = unsafe { kCTFontFamilyNameAttribute } as *const CFString as *const std::ffi::c_void;+ let Some(mandatory) = (unsafe { CFSet::new(None, &mut key, 1, &objc2_core_foundation::kCFTypeSetCallBacks) }) else { continue };+ let Some(list) = (unsafe { desc.matching_font_descriptors(Some(&mandatory)) }) else { continue };+ let list: CFRetained<CFArray<CTFontDescriptor>> = unsafe { CFRetained::cast_unchecked(list) };+ let faces: Vec<Face> = list+ .iter()+ .filter(|d| unsafe { d.attribute(kCTFontFamilyNameAttribute) }.and_then(|v| v.downcast::<CFString>().ok()).is_some_and(|f| f.to_string().to_lowercase() == lower))+ .filter_map(face_from_descriptor)+ .collect();+ if !faces.is_empty() {+ return Some(Rc::new(Family { name: candidate, faces }));+ }+ }+ None+}++/// CSS Fonts 4 §5.2 font matching for weight and style (stretch: prefer normal widths).+fn match_face(fam: &Family, weight: u16, italic: bool) -> Face {+ let mut pool: Vec<&Face> = fam.faces.iter().filter(|f| f.normal_width).collect();+ if pool.is_empty() {+ pool = fam.faces.iter().collect();+ }+ let styled: Vec<&Face> = pool.iter().copied().filter(|f| f.italic == italic).collect();+ let pool = if styled.is_empty() { pool } else { styled };+ let weights: Vec<u16> = pool.iter().map(|f| f.weight).collect();+ let w = pick_weight(weight, &weights);+ // Several faces with the same weight (e.g. duplicates across files): first wins.+ pool.into_iter().find(|f| f.weight == w).cloned().unwrap_or_else(|| fam.faces[0].clone())+}++fn pick_weight(desired: u16, available: &[u16]) -> u16 {+ if available.contains(&desired) {+ return desired;+ }+ let mut asc: Vec<u16> = available.to_vec();+ asc.sort_unstable();+ asc.dedup();+ let below_desc = || asc.iter().rev().copied().find(|&w| w < desired);+ let above_asc = |min: u16| asc.iter().copied().find(|&w| w > min);+ if (400..=500).contains(&desired) {+ if let Some(w) = asc.iter().copied().find(|&w| w > desired && w <= 500) {+ return w;+ }+ if let Some(w) = below_desc() {+ return w;+ }+ if let Some(w) = above_asc(500) {+ return w;+ }+ } else if desired < 400 {+ if let Some(w) = below_desc() {+ return w;+ }+ if let Some(w) = above_asc(desired) {+ return w;+ }+ } else {+ if let Some(w) = above_asc(desired) {+ return w;+ }+ if let Some(w) = below_desc() {+ return w;+ }+ }+ asc.first().copied().unwrap_or(400)+}++fn make_font(face: &Face, size: f64, weight: u16, italic: bool, synthetic_bold: bool, chain: Vec<Rc<Font>>) -> Font {+ let desc = match face.system_ui {+ Some(ctw) => {+ let num = CFNumber::new_f64(ctw);+ let traits = CFDictionary::<CFString, CFType>::from_slices(&[unsafe { kCTFontWeightTrait }], &[&*num as &CFType]);+ let attrs = CFDictionary::<CFString, CFType>::from_slices(&[unsafe { kCTFontTraitsAttribute }], &[&*traits as &CFType]);+ unsafe { face.desc.copy_with_attributes(attrs.as_opaque()) }+ }+ None => face.desc.clone(),+ };+ let plain = unsafe { CTFont::with_font_descriptor(&desc, size as CGFloat, std::ptr::null()) };+ // Cascade list: remaining CSS families in order, then the system defaults.+ let mut cascade: Vec<CFRetained<CTFontDescriptor>> = chain.iter().map(|f| unsafe { f.plain.font_descriptor() }).collect();+ if let Some(sys) = unsafe { plain.default_cascade_list_for_languages(None) } {+ let sys: CFRetained<CFArray<CTFontDescriptor>> = unsafe { CFRetained::cast_unchecked(sys) };+ cascade.extend(sys.iter());+ }+ let ct = if cascade.is_empty() {+ plain.clone()+ } else {+ let arr = CFArray::from_retained_objects(&cascade);+ let attrs = CFDictionary::<CFString, CFType>::from_slices(&[unsafe { kCTFontCascadeListAttribute }], &[arr.as_opaque() as &CFType]);+ let d = unsafe { desc.copy_with_attributes(attrs.as_opaque()) };+ unsafe { CTFont::with_font_descriptor(&d, size as CGFloat, std::ptr::null()) }+ };+ let typo = os2(&plain).and_then(|t| {+ let asc = be_u16(&t, 68)? as i16 as f64;+ let desc = be_u16(&t, 70)? as i16 as f64;+ let upem = unsafe { plain.units_per_em() } as f64;+ (upem > 0.0).then(|| (asc * size / upem, -desc * size / upem))+ });+ let color = unsafe { plain.symbolic_traits() }.contains(CTFontSymbolicTraits::TraitColorGlyphs);+ Font {+ family: unsafe { plain.family_name() }.to_string(),+ ascent: unsafe { plain.ascent() },+ descent: unsafe { plain.descent() },+ line_gap: unsafe { plain.leading() },+ x_height: unsafe { plain.x_height() },+ cap_height: unsafe { plain.cap_height() },+ ct,+ plain,+ synthetic_bold: synthetic_bold && !color,+ synthetic_italic: italic && !face.italic,+ size,+ weight,+ italic,+ color,+ chain,+ typo,+ fallbacks: RefCell::new(HashMap::new()),+ }+}++/// Resolve a CSS font (cached). Never fails: with no usable family the default (Times) is used,+/// as in Chrome.+pub fn resolve(q: &FontQuery) -> Rc<Font> {+ let key = (q.families.join("\u{1}"), q.weight, q.italic, q.size.to_bits());+ if let Some(f) = FONTS.with(|m| m.borrow().get(&key).cloned()) {+ return f;+ }+ let mut matched: Vec<Face> = Vec::new();+ for name in q.families {+ if let Some(fam) = family(name) {+ matched.push(match_face(&fam, q.weight, q.italic));+ }+ }+ if matched.is_empty() {+ // Chrome's standard font; if even that is missing, any font CoreText will give us.+ match family("Times").or_else(|| family("Helvetica")) {+ Some(fam) => matched.push(match_face(&fam, q.weight, q.italic)),+ None => {+ let ct = unsafe { CTFont::with_name(&CFString::from_str("Times-Roman"), q.size, std::ptr::null()) };+ matched.push(Face { desc: unsafe { ct.font_descriptor() }, weight: 400, italic: false, normal_width: true, system_ui: None });+ }+ }+ }+ let synth = |f: &Face| q.weight >= 600 && f.weight < 600 && f.system_ui.is_none();+ let chain: Vec<Rc<Font>> = matched[1..].iter().map(|f| Rc::new(make_font(f, q.size, q.weight, q.italic, synth(f), Vec::new()))).collect();+ let font = Rc::new(make_font(&matched[0], q.size, q.weight, q.italic, synth(&matched[0]), chain));+ FONTS.with(|m| {+ let mut m = m.borrow_mut();+ if m.len() > 512 {+ m.clear();+ }+ m.insert(key, font.clone());+ });+ font+}++/// Resolve a parsed shorthand.+pub fn resolve_parsed(p: &ParsedFont) -> Rc<Font> {+ resolve(&FontQuery { families: &p.families, weight: p.weight, italic: p.italic, size: p.size })+}++// ------------------------------------------------------------------------------- text helpers++pub(crate) fn cfstring_utf16(text: &[u16]) -> CFRetained<CFString> {+ unsafe { CFString::with_characters(None, text.as_ptr(), text.len() as isize) }.unwrap_or_else(|| CFString::from_str(""))+}++fn has_glyphs(ct: &CTFont, cluster: &[u16]) -> bool {+ // Variation selectors, ZWJ and tag characters are consumed by shaping; only real characters+ // need glyphs.+ let mut i = 0;+ while i < cluster.len() {+ let (cp, n) = decode_utf16_at(cluster, i);+ if !is_default_ignorable(cp) && !(0x1F3FB..=0x1F3FF).contains(&cp) || i == 0 {+ let units = &cluster[i..i + n];+ let mut glyphs = [0u16; 2];+ let ok = unsafe { ct.glyphs_for_characters(NonNull::new_unchecked(units.as_ptr() as *mut u16), NonNull::new_unchecked(glyphs.as_mut_ptr()), n as isize) };+ if !ok || glyphs[0] == 0 {+ return false;+ }+ }+ i += n;+ }+ true+}++pub(crate) fn decode_utf16_at(s: &[u16], i: usize) -> (u32, usize) {+ let c = s[i] as u32;+ if (0xD800..0xDC00).contains(&c) && i + 1 < s.len() {+ let d = s[i + 1] as u32;+ if (0xDC00..0xE000).contains(&d) {+ return (0x10000 + ((c - 0xD800) << 10) + (d - 0xDC00), 2);+ }+ }+ (c, 1)+}++fn is_default_ignorable(cp: u32) -> bool {+ matches!(cp, 0x200B..=0x200F | 0x2028..=0x202E | 0x2060..=0x206F | 0xFE00..=0xFE0F | 0xFEFF | 0xE0000..=0xE0FFF | 0x00AD | 0x034F)+}++fn is_combining(cp: u32) -> bool {+ matches!(cp, 0x0300..=0x036F | 0x1AB0..=0x1AFF | 0x1DC0..=0x1DFF | 0x20D0..=0x20FF | 0xFE20..=0xFE2F | 0x3099..=0x309A)+}++/// End of the grapheme starting at `i` (a simplified UAX #29: combining marks, variation+/// selectors, emoji modifiers, ZWJ sequences, keycaps, flags and tag sequences).+pub fn grapheme_end(s: &[u16], i: usize) -> usize {+ let (first, n) = decode_utf16_at(s, i);+ let mut j = i + n;+ if (0x1F1E6..=0x1F1FF).contains(&first) && j < s.len() {+ let (next, m) = decode_utf16_at(s, j);+ if (0x1F1E6..=0x1F1FF).contains(&next) {+ return j + m;+ }+ }+ if first == 0x0D && j < s.len() && s[j] == 0x0A {+ return j + 1;+ }+ while j < s.len() {+ let (cp, m) = decode_utf16_at(s, j);+ if is_combining(cp) || (0xFE00..=0xFE0F).contains(&cp) || (0x1F3FB..=0x1F3FF).contains(&cp) || (0xE0020..=0xE007F).contains(&cp) || cp == 0x20E3 {+ j += m;+ } else if cp == 0x200D {+ j += m;+ if j < s.len() {+ let (_, k) = decode_utf16_at(s, j);+ j += k;+ }+ } else {+ break;+ }+ }+ j+}++/// Graphemes Chrome renders with emoji presentation (default emoji presentation characters,+/// VS16 / keycap / ZWJ / modifier / flag sequences).+fn is_emoji_cluster(cluster: &[u16]) -> bool {+ let (first, n) = decode_utf16_at(cluster, 0);+ let rest = &cluster[n..];+ if rest.contains(&0xFE0E) {+ return false;+ }+ if rest.contains(&0xFE0F) || rest.contains(&0x200D) || rest.contains(&0x20E3) {+ return true;+ }+ if rest.len() >= 2 && (0x1F1E6..=0x1F1FF).contains(&first) {+ return true;+ }+ emoji_presentation(first)+}++fn emoji_presentation(cp: u32) -> bool {+ const BMP: &[(u32, u32)] = &[+ (0x231A, 0x231B), (0x23E9, 0x23EC), (0x23F0, 0x23F0), (0x23F3, 0x23F3), (0x25FD, 0x25FE), (0x2614, 0x2615), (0x2648, 0x2653), (0x267F, 0x267F),+ (0x2693, 0x2693), (0x26A1, 0x26A1), (0x26AA, 0x26AB), (0x26BD, 0x26BE), (0x26C4, 0x26C5), (0x26CE, 0x26CE), (0x26D4, 0x26D4), (0x26EA, 0x26EA),+ (0x26F2, 0x26F3), (0x26F5, 0x26F5), (0x26FA, 0x26FA), (0x26FD, 0x26FD), (0x2705, 0x2705), (0x270A, 0x270B), (0x2728, 0x2728), (0x274C, 0x274C),+ (0x274E, 0x274E), (0x2753, 0x2755), (0x2757, 0x2757), (0x2795, 0x2797), (0x27B0, 0x27B0), (0x27BF, 0x27BF), (0x2B1B, 0x2B1C), (0x2B50, 0x2B50),+ (0x2B55, 0x2B55),+ ];+ if cp < 0x10000 {+ return BMP.iter().any(|&(a, b)| (a..=b).contains(&cp));+ }+ // Supplementary emoji blocks: nearly everything there defaults to emoji presentation; the+ // text-default exceptions are rare symbols that text fonts lack anyway.+ matches!(cp, 0x1F004 | 0x1F0CF | 0x1F18E | 0x1F191..=0x1F19A | 0x1F1E6..=0x1F1FF | 0x1F201 | 0x1F21A | 0x1F22F | 0x1F232..=0x1F236 | 0x1F238..=0x1F23A | 0x1F250..=0x1F251)+ || (0x1F300..=0x1F64F).contains(&cp) && !matches!(cp, 0x1F321..=0x1F32C | 0x1F336 | 0x1F37D | 0x1F394..=0x1F39F | 0x1F3CB..=0x1F3CE | 0x1F3D4..=0x1F3DF | 0x1F3F1..=0x1F3F3 | 0x1F3F5..=0x1F3F7 | 0x1F43F | 0x1F441 | 0x1F4FD..=0x1F4FE | 0x1F53E..=0x1F54A | 0x1F54F | 0x1F568..=0x1F579 | 0x1F57B..=0x1F594 | 0x1F597..=0x1F5A3 | 0x1F5A5..=0x1F5FA)+ || (0x1F680..=0x1F6FF).contains(&cp) && !matches!(cp, 0x1F6C6..=0x1F6CB | 0x1F6CD..=0x1F6CF | 0x1F6D3..=0x1F6D4 | 0x1F6E0..=0x1F6EA | 0x1F6F0..=0x1F6F3)+ || (0x1F7E0..=0x1F7F0).contains(&cp)+ || (0x1F90C..=0x1FAFF).contains(&cp) && cp != 0x1F93B && cp != 0x1F946+}++#[allow(dead_code)]+fn _assert_types(_: CGAffineTransform) {}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn families() {+ for name in ["Times", "Courier", "courier", "times new roman", "Helvetica", "PingFang SC", "Apple Color Emoji", "sans-serif", "system-ui"] {+ let lower = name.to_lowercase();+ let canon = system_family_name(&lower);+ let fam = family(name);+ eprintln!("{name}: canon={canon:?} faces={:?}", fam.map(|f| f.faces.iter().map(|f| (f.weight, f.italic, f.normal_width)).collect::<Vec<_>>()));+ }+ let names = unsafe { CTFontManagerCopyAvailableFontFamilyNames() };+ let names: CFRetained<CFArray<CFString>> = unsafe { CFRetained::cast_unchecked(names) };+ let v: Vec<String> = names.iter().map(|n| n.to_string()).filter(|n| n.starts_with("Tim") || n.starts_with("Cour") || n.starts_with("Apple Ch") || n.starts_with("Papy")).collect();+ eprintln!("{v:?} total {}", names.len());+ let t = unsafe { CTFont::with_name(&CFString::from_str("Times"), 12.0, std::ptr::null()) };+ eprintln!("Times by name: family={} ps={}", unsafe { t.family_name() }, unsafe { t.post_script_name() });+ }+}diff --git a/runtime/crates/canvas2d/src/js.rs b/runtime/crates/canvas2d/src/js.rsnew file mode 100644index 0000000..4ca2527--- /dev/null+++ b/runtime/crates/canvas2d/src/js.rs@@ -0,0 +1,725 @@+//! `__native.c2d`: the functions `runtime/canvas2d.ts` calls. Arguments are validated here (bad+//! input becomes a JS exception or a no-op, never a panic); ids refer to the registry.+use std::rc::Rc;++use jsc::{Ctx, NativeResult, Persistent, Value};+use objc2_core_foundation::CGAffineTransform;+use objc2_core_graphics::{CGLineCap, CGLineJoin};++use crate::canvas::{composite_from_name, Gradient, GradientKind, Paint, Path, Pattern, Use2, IDENTITY};+use crate::codec::{self, Format};+use crate::fonts;+use crate::registry::{self, GRADIENTS, PATHS, PATTERNS, SURFACES};+use crate::text;++fn num(c: Ctx, a: &[Value], i: usize) -> f64 {+ a.get(i).map(|v| v.to_num(c)).unwrap_or(f64::NAN)+}+fn uid(c: Ctx, a: &[Value], i: usize) -> u32 {+ let n = num(c, a, i);+ if n.is_finite() && n >= 0.0 { n as u32 } else { 0 }+}+fn flag(c: Ctx, a: &[Value], i: usize) -> bool {+ a.get(i).is_some_and(|v| v.to_bool(c))+}+fn utf16(c: Ctx, a: &[Value], i: usize) -> Vec<u16> {+ a.get(i).map(|v| v.to_js_string(c).utf16().to_vec()).unwrap_or_default()+}+fn string(c: Ctx, a: &[Value], i: usize) -> String {+ a.get(i).map(|v| v.to_string(c)).unwrap_or_default()+}+fn matrix(c: Ctx, a: &[Value], i: usize) -> CGAffineTransform {+ CGAffineTransform { a: num(c, a, i), b: num(c, a, i + 1), c: num(c, a, i + 2), d: num(c, a, i + 3), tx: num(c, a, i + 4), ty: num(c, a, i + 5) }+}+fn rgba(c: Ctx, a: &[Value], i: usize) -> [f64; 4] {+ let cl = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };+ [cl(num(c, a, i) / 255.0), cl(num(c, a, i + 1) / 255.0), cl(num(c, a, i + 2) / 255.0), cl(num(c, a, i + 3))]+}++/// Run a path op on a canvas's current path (transformed by its CTM) or on a Path2D.+fn path2d_op(target: u32, f: &dyn Fn(&mut Path, &CGAffineTransform)) {+ let is_canvas = registry::with_canvas(target, |cv, _| {+ let m = cv.state.ctm;+ f(&mut cv.path, &m)+ });+ if is_canvas.is_none() {+ PATHS.with(|p| {+ if let Some(path) = p.borrow_mut().get_mut(&target) {+ f(path, &IDENTITY);+ }+ });+ }+}++/// A Path2D's path, cloned out of the registry (so drawing can borrow the canvas).+fn take_path2d(id: u32) -> Option<Path> {+ if id == 0 {+ return None;+ }+ PATHS.with(|p| p.borrow().get(&id).map(|path| Path { cg: objc2_core_graphics::CGMutablePath::new_copy(Some(&path.cg)).unwrap(), has_current: path.has_current }))+}++fn set_paint(c: Ctx, a: &[Value], stroke: bool, kind: u8) {+ let id = uid(c, a, 0);+ let paint = match kind {+ 0 => {+ let [r, g, b, al] = rgba(c, a, 1);+ Some(Paint::color(r, g, b, al))+ }+ _ => {+ let obj = uid(c, a, 1);+ GRADIENTS.with(|g| g.borrow().get(&obj).cloned().map(Paint::Gradient)).or_else(|| PATTERNS.with(|p| p.borrow().get(&obj).cloned().map(Paint::Pattern)))+ }+ };+ if let Some(p) = paint {+ registry::with_canvas(id, |cv, _| {+ if stroke { cv.state.stroke = p } else { cv.state.fill = p }+ });+ }+}++fn data_url(format: Format, bytes: &[u8]) -> String {+ let mut s = String::with_capacity(32 + bytes.len() * 4 / 3);+ s.push_str("data:");+ s.push_str(format.mime());+ s.push_str(";base64,");+ codec::base64_encode_into(&mut s, bytes);+ s+}++/// Transparent PNG data URL (blank canvases).+pub(crate) fn blank_data_url(w: u32, h: u32, format: Format) -> String {+ if w == 0 || h == 0 {+ return "data:,".into();+ }+ let px = vec![0u8; w as usize * h as usize * 4];+ match codec::encode(w, h, &px, true, format) {+ Some(b) => data_url(format, &b),+ None => "data:,".into(),+ }+}++fn decode_async(c: Ctx, bytes: Vec<u8>, b64: Option<Vec<u16>>, cb: Value) {+ if !cb.is_function(c) {+ return;+ }+ let cb = Persistent::new(c, cb);+ rt::spawn(+ move || {+ let bytes = match b64 {+ Some(url) => match codec::parse_data_url(&url) {+ Some((_, b)) => b,+ None => return Err("malformed data: URL".to_string()),+ },+ None => bytes,+ };+ codec::decode(&bytes)+ },+ move |c, res| {+ let args = match res {+ Ok(d) => {+ let (w, h) = (d.width, d.height);+ let id = registry::insert_image(w, h, d.data);+ [c.num(id as f64), c.num(w as f64), c.num(h as f64), c.undefined()]+ }+ Err(e) => [c.num(0.0), c.num(0.0), c.num(0.0), c.str(&e)],+ };+ if let Err(e) = c.call(cb.get(), None, &args) {+ rt::report("image load callback", &e);+ }+ },+ );+}++pub(crate) fn install(c: Ctx, native: Value) {+ let o = c.object();+ native.set(c, "c2d", o);+ let def = |name: &str, f: Box<dyn Fn(Ctx, &[Value]) -> NativeResult>| {+ o.set(c, name, c.function(move |c, _this, a| f(c, a)));+ };+ macro_rules! f {+ ($body:expr) => {+ Box::new($body)+ };+ }++ // ------------------------------------------------------------------ canvases+ def("create", f!(|c, a| Ok(c.num(registry::create_canvas(uid(c, a, 0), uid(c, a, 1)) as f64))));+ def("resize", f!(|c, a| {+ registry::resize_canvas(uid(c, a, 0), uid(c, a, 1), uid(c, a, 2));+ Ok(c.undefined())+ }));+ def("release", f!(|c, a| {+ registry::release(uid(c, a, 0));+ Ok(c.undefined())+ }));+ def("reset", f!(|c, a| {+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.reset());+ Ok(c.undefined())+ }));+ def("size", f!(|c, a| match registry::surface_size(uid(c, a, 0)) {+ Some((w, h)) => Ok(c.array(&[c.num(w as f64), c.num(h as f64)])),+ None => Ok(c.null()),+ }));+ def("version", f!(|c, a| Ok(c.num(SURFACES.with(|s| s.borrow().get(&uid(c, a, 0)).map(|s| s.version as f64).unwrap_or(0.0))))));++ // ------------------------------------------------------------------ state+ def("save", f!(|c, a| {+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.save());+ Ok(c.undefined())+ }));+ def("restore", f!(|c, a| {+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.restore());+ Ok(c.undefined())+ }));+ def("setTransform", f!(|c, a| {+ let m = matrix(c, a, 1);+ if [m.a, m.b, m.c, m.d, m.tx, m.ty].iter().all(|v| v.is_finite()) {+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.state.ctm = m);+ }+ Ok(c.undefined())+ }));+ def("setFillColor", f!(|c, a| {+ set_paint(c, a, false, 0);+ Ok(c.undefined())+ }));+ def("setStrokeColor", f!(|c, a| {+ set_paint(c, a, true, 0);+ Ok(c.undefined())+ }));+ def("setFillPaint", f!(|c, a| {+ set_paint(c, a, false, 1);+ Ok(c.undefined())+ }));+ def("setStrokePaint", f!(|c, a| {+ set_paint(c, a, true, 1);+ Ok(c.undefined())+ }));+ def("setLine", f!(|c, a| {+ // (id, width, cap 0 butt 1 round 2 square, join 0 miter 1 round 2 bevel, miterLimit)+ let (w, cap, join, miter) = (num(c, a, 1), uid(c, a, 2), uid(c, a, 3), num(c, a, 4));+ registry::with_canvas(uid(c, a, 0), |cv, _| {+ let s = &mut cv.state;+ if w.is_finite() && w > 0.0 {+ s.line_width = w;+ }+ s.cap = match cap {+ 1 => CGLineCap::Round,+ 2 => CGLineCap::Square,+ _ => CGLineCap::Butt,+ };+ s.join = match join {+ 1 => CGLineJoin::Round,+ 2 => CGLineJoin::Bevel,+ _ => CGLineJoin::Miter,+ };+ if miter.is_finite() && miter > 0.0 {+ s.miter = miter;+ }+ });+ Ok(c.undefined())+ }));+ def("setLineDash", f!(|c, a| {+ // (id, offset, segments[]) — already validated and doubled to even length by JS+ let offset = num(c, a, 1);+ let mut dash = Vec::new();+ if let Some(arr) = a.get(2).filter(|v| v.is_object(c)) {+ for i in 0..arr.len(c) {+ dash.push(arr.at(c, i).to_num(c));+ }+ }+ if dash.iter().any(|v| !v.is_finite() || *v < 0.0) {+ return Ok(c.undefined());+ }+ if dash.iter().all(|v| *v == 0.0) {+ dash.clear();+ }+ registry::with_canvas(uid(c, a, 0), |cv, _| {+ cv.state.dash = dash;+ if offset.is_finite() {+ cv.state.dash_offset = offset;+ }+ });+ Ok(c.undefined())+ }));+ def("setAlpha", f!(|c, a| {+ let v = num(c, a, 1);+ if v.is_finite() && (0.0..=1.0).contains(&v) {+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.state.alpha = v);+ }+ Ok(c.undefined())+ }));+ def("setComposite", f!(|c, a| {+ let ok = composite_from_name(&string(c, a, 1));+ if let Some(mode) = ok {+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.state.blend = mode);+ }+ Ok(c.bool(ok.is_some()))+ }));+ def("setShadow", f!(|c, a| {+ // (id, offsetX, offsetY, blur, r, g, b, a)+ let (ox, oy, blur) = (num(c, a, 1), num(c, a, 2), num(c, a, 3));+ let [r, g, b, al] = rgba(c, a, 4);+ registry::with_canvas(uid(c, a, 0), |cv, _| {+ let s = &mut cv.state;+ if ox.is_finite() {+ s.shadow_x = ox;+ }+ if oy.is_finite() {+ s.shadow_y = oy;+ }+ if blur.is_finite() && blur >= 0.0 {+ s.shadow_blur = blur;+ }+ s.shadow_color = Some((objc2_core_graphics::CGColor::new_srgb(r, g, b, al), al));+ });+ Ok(c.undefined())+ }));+ def("setSmoothing", f!(|c, a| {+ let (on, q) = (flag(c, a, 1), uid(c, a, 2));+ registry::with_canvas(uid(c, a, 0), |cv, _| {+ cv.state.smoothing = on;+ cv.state.smoothing_quality = q.min(2) as u8;+ });+ Ok(c.undefined())+ }));+ def("setFont", f!(|c, a| {+ // returns the serialized font, or null when the value is invalid (ignored)+ let Some(p) = fonts::parse_shorthand(&string(c, a, 1)) else { return Ok(c.null()) };+ let css = p.to_css();+ registry::with_canvas(uid(c, a, 0), |cv, _| {+ cv.state.font = Rc::new(p);+ cv.state.resolved = None;+ });+ Ok(c.str(&css))+ }));+ def("setText", f!(|c, a| {+ // (id, align, baseline, rtl, letterSpacing, wordSpacing, kerning)+ let (al, bl, rtl, ls, ws, k) = (uid(c, a, 1), uid(c, a, 2), flag(c, a, 3), num(c, a, 4), num(c, a, 5), flag(c, a, 6));+ registry::with_canvas(uid(c, a, 0), |cv, _| {+ let s = &mut cv.state;+ s.align = al.min(4) as u8;+ s.baseline = bl.min(5) as u8;+ s.rtl = rtl;+ s.letter_spacing = if ls.is_finite() { ls } else { 0.0 };+ s.word_spacing = if ws.is_finite() { ws } else { 0.0 };+ s.kerning = k;+ });+ Ok(c.undefined())+ }));++ // ------------------------------------------------------------------ paths+ def("newPath", f!(|c, _a| {+ let id = registry::next_id();+ PATHS.with(|p| p.borrow_mut().insert(id, Path::default()));+ Ok(c.num(id as f64))+ }));+ def("copyPath", f!(|c, a| {+ let src = uid(c, a, 0);+ let id = registry::next_id();+ if let Some(p) = take_path2d(src) {+ PATHS.with(|m| m.borrow_mut().insert(id, p));+ } else {+ PATHS.with(|m| m.borrow_mut().insert(id, Path::default()));+ }+ Ok(c.num(id as f64))+ }));+ def("addPath", f!(|c, a| {+ // (dst Path2D, src Path2D, a, b, c, d, e, f)+ let (dst, src) = (uid(c, a, 0), uid(c, a, 1));+ let mut m = matrix(c, a, 2);+ if ![m.a, m.b, m.c, m.d, m.tx, m.ty].iter().all(|v| v.is_finite()) {+ m = IDENTITY;+ }+ if let Some(sp) = take_path2d(src) {+ PATHS.with(|p| {+ if let Some(d) = p.borrow_mut().get_mut(&dst) {+ d.add_path(&sp.cg, &m);+ }+ });+ }+ Ok(c.undefined())+ }));+ def("beginPath", f!(|c, a| {+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.path.clear());+ Ok(c.undefined())+ }));+ def("moveTo", f!(|c, a| {+ let (x, y) = (num(c, a, 1), num(c, a, 2));+ path2d_op(uid(c, a, 0), &|p, m| p.move_to(m, x, y));+ Ok(c.undefined())+ }));+ def("lineTo", f!(|c, a| {+ let (x, y) = (num(c, a, 1), num(c, a, 2));+ path2d_op(uid(c, a, 0), &|p, m| p.line_to(m, x, y));+ Ok(c.undefined())+ }));+ def("quadTo", f!(|c, a| {+ let v: Vec<f64> = (1..5).map(|i| num(c, a, i)).collect();+ path2d_op(uid(c, a, 0), &|p, m| p.quad_to(m, v[0], v[1], v[2], v[3]));+ Ok(c.undefined())+ }));+ def("bezierTo", f!(|c, a| {+ let v: Vec<f64> = (1..7).map(|i| num(c, a, i)).collect();+ path2d_op(uid(c, a, 0), &|p, m| p.bezier_to(m, v[0], v[1], v[2], v[3], v[4], v[5]));+ Ok(c.undefined())+ }));+ def("arcTo", f!(|c, a| {+ let v: Vec<f64> = (1..6).map(|i| num(c, a, i)).collect();+ path2d_op(uid(c, a, 0), &|p, m| p.arc_to(m, v[0], v[1], v[2], v[3], v[4]));+ Ok(c.undefined())+ }));+ def("arc", f!(|c, a| {+ let v: Vec<f64> = (1..6).map(|i| num(c, a, i)).collect();+ let ccw = flag(c, a, 6);+ path2d_op(uid(c, a, 0), &|p, m| p.arc(m, v[0], v[1], v[2], v[3], v[4], ccw));+ Ok(c.undefined())+ }));+ def("ellipse", f!(|c, a| {+ let v: Vec<f64> = (1..8).map(|i| num(c, a, i)).collect();+ let ccw = flag(c, a, 8);+ path2d_op(uid(c, a, 0), &|p, m| p.ellipse(m, v[0], v[1], v[2], v[3], v[4], v[5], v[6], ccw));+ Ok(c.undefined())+ }));+ def("rect", f!(|c, a| {+ let v: Vec<f64> = (1..5).map(|i| num(c, a, i)).collect();+ path2d_op(uid(c, a, 0), &|p, m| p.rect(m, v[0], v[1], v[2], v[3]));+ Ok(c.undefined())+ }));+ def("roundRect", f!(|c, a| {+ let v: Vec<f64> = (1..13).map(|i| num(c, a, i)).collect();+ let r = [v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11]];+ path2d_op(uid(c, a, 0), &|p, m| p.round_rect(m, v[0], v[1], v[2], v[3], r));+ Ok(c.undefined())+ }));+ def("closePath", f!(|c, a| {+ path2d_op(uid(c, a, 0), &|p, _| p.close());+ Ok(c.undefined())+ }));++ // ------------------------------------------------------------------ drawing+ def("fill", f!(|c, a| {+ let p = take_path2d(uid(c, a, 1));+ let eo = flag(c, a, 2);+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.fill(p.as_ref(), eo));+ Ok(c.undefined())+ }));+ def("stroke", f!(|c, a| {+ let p = take_path2d(uid(c, a, 1));+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.stroke(p.as_ref()));+ Ok(c.undefined())+ }));+ def("clip", f!(|c, a| {+ let p = take_path2d(uid(c, a, 1));+ let eo = flag(c, a, 2);+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.clip(p.as_ref(), eo));+ Ok(c.undefined())+ }));+ def("isPointInPath", f!(|c, a| {+ let p = take_path2d(uid(c, a, 1));+ let (x, y, eo) = (num(c, a, 2), num(c, a, 3), flag(c, a, 4));+ Ok(c.bool(registry::with_canvas(uid(c, a, 0), |cv, _| cv.is_point_in_path(p.as_ref(), x, y, eo)).unwrap_or(false)))+ }));+ def("isPointInStroke", f!(|c, a| {+ let p = take_path2d(uid(c, a, 1));+ let (x, y) = (num(c, a, 2), num(c, a, 3));+ Ok(c.bool(registry::with_canvas(uid(c, a, 0), |cv, _| cv.is_point_in_stroke(p.as_ref(), x, y)).unwrap_or(false)))+ }));+ def("fillRect", f!(|c, a| {+ let v: Vec<f64> = (1..5).map(|i| num(c, a, i)).collect();+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.fill_rect(v[0], v[1], v[2], v[3]));+ Ok(c.undefined())+ }));+ def("strokeRect", f!(|c, a| {+ let v: Vec<f64> = (1..5).map(|i| num(c, a, i)).collect();+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.stroke_rect(v[0], v[1], v[2], v[3]));+ Ok(c.undefined())+ }));+ def("clearRect", f!(|c, a| {+ let v: Vec<f64> = (1..5).map(|i| num(c, a, i)).collect();+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.clear_rect(v[0], v[1], v[2], v[3]));+ Ok(c.undefined())+ }));+ for (name, use_) in [("fillText", Use2::Fill), ("strokeText", Use2::Stroke)] {+ def(name, Box::new(move |c, a| {+ let t = utf16(c, a, 1);+ let (x, y, mw) = (num(c, a, 2), num(c, a, 3), num(c, a, 4));+ let max_width = if a.get(4).is_some_and(|v| !v.is_undefined(c)) { Some(mw) } else { None };+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.draw_text(&t, x, y, max_width, use_));+ Ok(c.undefined())+ }));+ }+ def("measureText", f!(|c, a| {+ let t = utf16(c, a, 1);+ let r = registry::with_canvas(uid(c, a, 0), |cv, _| {+ let font = cv.state.font();+ text::measure(&font, &cv.state, &t)+ });+ match r {+ Some(v) => Ok(c.array(&v.iter().map(|x| c.num(*x)).collect::<Vec<_>>())),+ None => Ok(c.null()),+ }+ }));+ def("drawImage", f!(|c, a| {+ // (id, srcId, sx, sy, sw, sh, dx, dy, dw, dh) — normalized by JS (positive sizes)+ let (dst, src) = (uid(c, a, 0), uid(c, a, 1));+ let v: Vec<f64> = (2..10).map(|i| num(c, a, i)).collect();+ let Some((img, iw, ih)) = registry::snapshot(src) else { return Ok(c.undefined()) };+ let (iw, ih) = (iw as f64, ih as f64);+ // Clip the source rect to the image, shrinking the destination proportionally (spec).+ let (mut sx, mut sy, mut sw, mut sh) = (v[0], v[1], v[2], v[3]);+ let (mut dx, mut dy, mut dw, mut dh) = (v[4], v[5], v[6], v[7]);+ if sw == 0.0 || sh == 0.0 {+ return Ok(c.undefined());+ }+ let (kx, ky) = (dw / sw, dh / sh);+ if sx < 0.0 {+ dx -= sx * kx;+ dw += sx * kx;+ sw += sx;+ sx = 0.0;+ }+ if sy < 0.0 {+ dy -= sy * ky;+ dh += sy * ky;+ sh += sy;+ sy = 0.0;+ }+ if sx + sw > iw {+ let over = sx + sw - iw;+ dw -= over * kx;+ sw -= over;+ }+ if sy + sh > ih {+ let over = sy + sh - ih;+ dh -= over * ky;+ sh -= over;+ }+ if sw <= 0.0 || sh <= 0.0 {+ return Ok(c.undefined());+ }+ registry::with_canvas(dst, |cv, _| cv.draw_image(&img, iw, ih, sx, sy, sw, sh, dx, dy, dw, dh));+ Ok(c.undefined())+ }));+ def("getImageData", f!(|c, a| {+ // (id, sx, sy, sw, sh, out Uint8ClampedArray) — device pixels+ let (sx, sy) = (num(c, a, 1).floor() as i64, num(c, a, 2).floor() as i64);+ let (sw, sh) = (uid(c, a, 3) as usize, uid(c, a, 4) as usize);+ let id = uid(c, a, 0);+ let Some(out) = a.get(5).and_then(|v| v.bytes(c)) else { return Err("getImageData: no buffer".into()) };+ if out.len() < sw * sh * 4 {+ return Err("getImageData: buffer too small".into());+ }+ SURFACES.with(|s| {+ let s = s.borrow();+ match s.get(&id) {+ Some(surf) if !surf.data.is_empty() => match &surf.canvas {+ Some(cv) => cv.get_image_data(&surf.data, sx, sy, sw, sh, out),+ None => out.fill(0),+ },+ _ => out[..sw * sh * 4].fill(0),+ }+ });+ Ok(c.undefined())+ }));+ def("putImageData", f!(|c, a| {+ // (id, data, sw, sh, dx, dy, dirtyX, dirtyY, dirtyW, dirtyH) — dirty rect normalized by JS+ let id = uid(c, a, 0);+ let (sw, sh) = (uid(c, a, 2) as usize, uid(c, a, 3) as usize);+ let (dx, dy) = (num(c, a, 4) as i64, num(c, a, 5) as i64);+ let dirty = (num(c, a, 6) as i64, num(c, a, 7) as i64, (num(c, a, 6) + num(c, a, 8)) as i64, (num(c, a, 7) + num(c, a, 9)) as i64);+ let Some(src) = a.get(1).and_then(|v| v.bytes(c)) else { return Err("putImageData: no data".into()) };+ if src.len() < sw * sh * 4 {+ return Err("putImageData: data too small".into());+ }+ let src = src.to_vec();+ registry::with_canvas(id, |cv, data| {+ if !data.is_empty() {+ cv.put_image_data(data, &src, sw, sh, dx, dy, dirty);+ }+ });+ Ok(c.undefined())+ }));++ // ------------------------------------------------------------------ gradients / patterns+ def("linearGradient", f!(|c, a| {+ let v: Vec<f64> = (0..4).map(|i| num(c, a, i)).collect();+ let id = registry::next_id();+ GRADIENTS.with(|g| g.borrow_mut().insert(id, Rc::new(std::cell::RefCell::new(Gradient::new(GradientKind::Linear(v[0], v[1], v[2], v[3]))))));+ Ok(c.num(id as f64))+ }));+ def("radialGradient", f!(|c, a| {+ let v: Vec<f64> = (0..6).map(|i| num(c, a, i)).collect();+ let id = registry::next_id();+ GRADIENTS.with(|g| g.borrow_mut().insert(id, Rc::new(std::cell::RefCell::new(Gradient::new(GradientKind::Radial(v[0], v[1], v[2], v[3], v[4], v[5]))))));+ Ok(c.num(id as f64))+ }));+ def("conicGradient", f!(|c, a| {+ let v: Vec<f64> = (0..3).map(|i| num(c, a, i)).collect();+ let id = registry::next_id();+ GRADIENTS.with(|g| g.borrow_mut().insert(id, Rc::new(std::cell::RefCell::new(Gradient::new(GradientKind::Conic(v[0], v[1], v[2]))))));+ Ok(c.num(id as f64))+ }));+ def("addColorStop", f!(|c, a| {+ let (id, off) = (uid(c, a, 0), num(c, a, 1));+ let col = rgba(c, a, 2);+ GRADIENTS.with(|g| {+ if let Some(g) = g.borrow().get(&id) {+ g.borrow_mut().add_stop(off, col);+ }+ });+ Ok(c.undefined())+ }));+ def("pattern", f!(|c, a| {+ // (srcId, repetition 0 repeat 1 repeat-x 2 repeat-y 3 no-repeat) → id, 0 if the source is empty+ let (src, rep) = (uid(c, a, 0), uid(c, a, 1));+ let Some((img, w, h)) = registry::snapshot(src) else { return Ok(c.num(0.0)) };+ let id = registry::next_id();+ let p = Pattern { image: img, width: w as f64, height: h as f64, repeat_x: rep == 0 || rep == 1, repeat_y: rep == 0 || rep == 2, transform: IDENTITY };+ PATTERNS.with(|m| m.borrow_mut().insert(id, Rc::new(p)));+ Ok(c.num(id as f64))+ }));+ def("patternTransform", f!(|c, a| {+ let id = uid(c, a, 0);+ let m = matrix(c, a, 1);+ if [m.a, m.b, m.c, m.d, m.tx, m.ty].iter().all(|v| v.is_finite()) {+ PATTERNS.with(|p| {+ let mut p = p.borrow_mut();+ if let Some(old) = p.get(&id).cloned() {+ let new = Pattern { image: old.image.clone(), width: old.width, height: old.height, repeat_x: old.repeat_x, repeat_y: old.repeat_y, transform: m };+ p.insert(id, Rc::new(new));+ }+ });+ }+ Ok(c.undefined())+ }));++ // ------------------------------------------------------------------ images+ def("decode", f!(|c, a| {+ // (ArrayBuffer | typed array, callback(id, w, h, error?))+ let bytes = a.first().and_then(|v| v.bytes(c)).map(|b| b.to_vec()).unwrap_or_default();+ decode_async(c, bytes, None, a.get(1).copied().unwrap_or(c.undefined()));+ Ok(c.undefined())+ }));+ def("decodeDataURL", f!(|c, a| {+ let url = utf16(c, a, 0);+ decode_async(c, Vec::new(), Some(url), a.get(1).copied().unwrap_or(c.undefined()));+ Ok(c.undefined())+ }));+ def("imageFromPixels", f!(|c, a| {+ // (w, h, unpremultiplied RGBA) → image id (createImageBitmap(ImageData))+ let (w, h) = (uid(c, a, 0), uid(c, a, 1));+ let Some(src) = a.get(2).and_then(|v| v.bytes(c)) else { return Ok(c.num(0.0)) };+ let n = w as usize * h as usize * 4;+ if n == 0 || src.len() < n {+ return Ok(c.num(0.0));+ }+ let mut data = src[..n].to_vec();+ for p in data.chunks_exact_mut(4) {+ let al = p[3];+ p[0] = codec::premul(p[0], al);+ p[1] = codec::premul(p[1], al);+ p[2] = codec::premul(p[2], al);+ }+ Ok(c.num(registry::insert_image(w, h, data) as f64))+ }));+ def("copySurface", f!(|c, a| {+ // snapshot of any bitmap as a new immutable image (createImageBitmap(canvas | img))+ let src = uid(c, a, 0);+ let copy = SURFACES.with(|s| s.borrow().get(&src).map(|s| (s.width, s.height, s.data.clone())));+ match copy {+ Some((w, h, data)) if !data.is_empty() => Ok(c.num(registry::insert_image(w, h, data) as f64)),+ _ => Ok(c.num(0.0)),+ }+ }));++ // ------------------------------------------------------------------ encoding+ def("toDataURL", f!(|c, a| {+ // (id, type, quality) — 2D canvases and images+ let id = uid(c, a, 0);+ let q = num(c, a, 2);+ let format = Format::from_mime(&string(c, a, 1), q.is_finite().then_some(q));+ let url = SURFACES.with(|s| {+ let s = s.borrow();+ let surf = s.get(&id)?;+ if surf.width == 0 || surf.height == 0 {+ return Some("data:,".to_string());+ }+ if surf.data.is_empty() {+ return Some(blank_data_url(surf.width, surf.height, format));+ }+ codec::encode(surf.width, surf.height, &surf.data, true, format).map(|b| data_url(format, &b))+ });+ Ok(c.str(&url.unwrap_or_else(|| "data:,".into())))+ }));+ def("encodeRGBA", f!(|c, a| {+ // (w, h, unpremultiplied RGBA top-down, type, quality) — WebGL canvas export+ let (w, h) = (uid(c, a, 0), uid(c, a, 1));+ let q = num(c, a, 4);+ let format = Format::from_mime(&string(c, a, 3), q.is_finite().then_some(q));+ if w == 0 || h == 0 {+ return Ok(c.str("data:,"));+ }+ let Some(px) = a.get(2).and_then(|v| v.bytes(c)) else { return Ok(c.str(&blank_data_url(w, h, format))) };+ let px = px.to_vec();+ match codec::encode(w, h, &px, false, format) {+ Some(b) => Ok(c.str(&data_url(format, &b))),+ None => Ok(c.str("data:,")),+ }+ }));+ def("blankDataURL", f!(|c, a| {+ let q = num(c, a, 3);+ let format = Format::from_mime(&string(c, a, 2), q.is_finite().then_some(q));+ Ok(c.str(&blank_data_url(uid(c, a, 0), uid(c, a, 1), format)))+ }));++ // ------------------------------------------------------------------ test hooks+ if std::env::var_os("THREERT_C2D_TEST").is_some() || std::env::var_os("POCKET_C2D_TEST").is_some() {+ def("_writeFile", f!(|c, a| {+ // (path, string | bytes): test pages save PNGs / reports. Only with THREERT_C2D_TEST.+ let path = string(c, a, 0);+ let ok = match a.get(1) {+ Some(v) if v.typed_kind(c) != jsc::TypedArrayType::None => std::fs::write(&path, v.bytes(c).unwrap_or_default()).is_ok(),+ Some(v) => {+ let s = v.to_string(c);+ if let Some(b64) = s.strip_prefix("data:image/png;base64,") {+ let u: Vec<u16> = b64.encode_utf16().collect();+ std::fs::write(&path, codec::base64_decode(&u).unwrap_or_default()).is_ok()+ } else {+ std::fs::write(&path, s).is_ok()+ }+ }+ None => false,+ };+ Ok(c.bool(ok))+ }));+ def("_fontInfo", f!(|c, a| {+ // (css font, text) → JSON describing the resolved fonts and runs+ let Some(p) = fonts::parse_shorthand(&string(c, a, 0)) else { return Ok(c.null()) };+ let font = fonts::resolve_parsed(&p);+ let t = utf16(c, a, 1);+ let runs: Vec<String> = font+ .runs(&t)+ .iter()+ .map(|r| format!("{{\"start\":{},\"end\":{},\"family\":{:?},\"ps\":{:?},\"bold\":{},\"italic\":{}}}", r.start, r.end, r.font.family, unsafe { r.font.plain.post_script_name() }.to_string(), r.font.synthetic_bold, r.font.synthetic_italic))+ .collect();+ let lm = font.line_metrics();+ let (ea, ed) = font.em_ascent_descent();+ Ok(c.json(&format!(+ "{{\"family\":{:?},\"ps\":{:?},\"syntheticBold\":{},\"ascent\":{},\"descent\":{},\"lineGap\":{},\"blink\":[{},{},{}],\"em\":[{},{}],\"runs\":[{}]}}",+ font.family,+ unsafe { font.plain.post_script_name() }.to_string(),+ font.synthetic_bold,+ font.ascent,+ font.descent,+ font.line_gap,+ lm.ascent,+ lm.descent,+ lm.line_gap,+ ea,+ ed,+ runs.join(",")+ )))+ }));+ }+}diff --git a/runtime/crates/canvas2d/src/lib.rs b/runtime/crates/canvas2d/src/lib.rsnew file mode 100644index 0000000..788747f--- /dev/null+++ b/runtime/crates/canvas2d/src/lib.rs@@ -0,0 +1,113 @@+//! Canvas 2D, image decoding/encoding and fonts:+//! - macOS: CoreGraphics / CoreText / ImageIO+//! - Non-macOS (Linux, Windows): pure-Rust `tiny-skia` + `cosmic-text` + `image`+use jsc::{Ctx, Value};++#[cfg(target_os = "macos")]+mod canvas;+#[cfg(target_os = "macos")]+pub mod codec;+#[cfg(target_os = "macos")]+pub mod fonts;+#[cfg(target_os = "macos")]+mod js;+#[cfg(target_os = "macos")]+mod registry;+#[cfg(target_os = "macos")]+mod text;+#[cfg(target_os = "macos")]+pub mod textblock;++#[cfg(not(target_os = "macos"))]+mod portable;+#[cfg(not(target_os = "macos"))]+pub use portable::{codec, fonts, textblock};++pub use codec::Decoded;++/// Premultiplied RGBA8 pixels, rows top-down.+pub struct Bitmap<'a> {+ pub width: u32,+ pub height: u32,+ pub stride: usize,+ pub data: &'a [u8],+ /// bumps on every change (so consumers re-upload only when needed)+ pub version: u64,+}++/// Define `__native.c2d`.+pub fn install(c: Ctx, native: Value) {+ #[cfg(target_os = "macos")]+ {+ rt::on_reset(registry::reset);+ js::install(c, native);+ }+ #[cfg(not(target_os = "macos"))]+ {+ portable::install(c, native);+ }+}++/// 2D canvases and decoded images share one id space. `None` for unknown ids and for+/// zero-sized or unallocatable canvases.+pub fn with_bitmap<R>(id: u32, f: impl FnOnce(&Bitmap) -> R) -> Option<R> {+ #[cfg(target_os = "macos")]+ {+ registry::SURFACES.with(|s| {+ let s = s.borrow();+ let surf = s.get(&id)?;+ if surf.data.is_empty() {+ return None;+ }+ Some(f(&Bitmap { width: surf.width, height: surf.height, stride: surf.width as usize * 4, data: &surf.data, version: surf.version }))+ })+ }+ #[cfg(not(target_os = "macos"))]+ {+ portable::with_bitmap(id, f)+ }+}++/// Current version of a bitmap (cheap check before `with_bitmap`).+pub fn bitmap_version(id: u32) -> Option<u64> {+ #[cfg(target_os = "macos")]+ {+ registry::SURFACES.with(|s| s.borrow().get(&id).map(|s| s.version))+ }+ #[cfg(not(target_os = "macos"))]+ {+ portable::bitmap_version(id)+ }+}++/// Where the bundled font files live (`<bundle>/fonts`); set by the app before the first page.+pub fn set_font_dir(dir: std::path::PathBuf) {+ fonts::set_dir(dir);+}++/// Register the bundled fonts (process scope). Idempotent; also done lazily on first font use.+pub fn ensure_fonts() {+ fonts::register();+}++/// Encode unpremultiplied RGBA8 (rows top-down) as PNG. Empty on failure.+pub fn encode_png(w: u32, h: u32, rgba_top_down: &[u8]) -> Vec<u8> {+ codec::encode(w, h, rgba_top_down, false, codec::Format::Png).unwrap_or_default()+}++/// Decode PNG/JPEG/GIF/WebP bytes into premultiplied RGBA8 (any thread).+pub fn decode_image(bytes: &[u8]) -> Result<Decoded, String> {+ codec::decode(bytes)+}++/// Add decoded pixels to the bitmap registry (main thread); returns the id.+pub fn insert_image(img: Decoded) -> u32 {+ #[cfg(target_os = "macos")]+ {+ registry::insert_image(img.width, img.height, img.data)+ }+ #[cfg(not(target_os = "macos"))]+ {+ portable::insert_image(img.width, img.height, img.data)+ }+}diff --git a/runtime/crates/canvas2d/src/portable/canvas.rs b/runtime/crates/canvas2d/src/portable/canvas.rsnew file mode 100644index 0000000..9b16fbc--- /dev/null+++ b/runtime/crates/canvas2d/src/portable/canvas.rs@@ -0,0 +1,968 @@+//! Pure-Rust Canvas 2D renderer backed by `tiny-skia` + `cosmic-text`.+use std::cell::RefCell;+use std::f64::consts::{PI, TAU};+use std::rc::Rc;++use cosmic_text::{Attrs, Buffer, Color as CosmicColor, Metrics, Shaping, SwashCache, Weight, Wrap};+use tiny_skia::{+ BlendMode, Color, FillRule, FilterQuality, GradientStop, LineCap, LineJoin, LinearGradient, Mask, Paint as SkPaint, PathBuilder, Pattern as SkPattern,+ PixmapMut, PixmapRef, Point, RadialGradient, Rect, Shader, SpreadMode, Stroke, StrokeDash, Transform,+};++use super::codec::{premul, unpremul};+use super::fonts::{self, resolve_family, ParsedFont};+use super::textblock::blit_glyph;++thread_local! {+ static SWASH: RefCell<SwashCache> = RefCell::new(SwashCache::new());+}++#[derive(Clone, Copy, Debug)]+pub struct Mat {+ pub a: f64,+ pub b: f64,+ pub c: f64,+ pub d: f64,+ pub tx: f64,+ pub ty: f64,+}++pub const IDENTITY: Mat = Mat { a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0 };++impl Mat {+ #[inline]+ pub fn apply(&self, x: f64, y: f64) -> (f64, f64) {+ (self.a * x + self.c * y + self.tx, self.b * x + self.d * y + self.ty)+ }+ #[inline]+ pub fn to_skia(&self) -> Transform {+ Transform::from_row(self.a as f32, self.b as f32, self.c as f32, self.d as f32, self.tx as f32, self.ty as f32)+ }+ #[inline]+ pub fn concat(&self, o: &Mat) -> Mat {+ Mat {+ a: self.a * o.a + self.c * o.b,+ b: self.b * o.a + self.d * o.b,+ c: self.a * o.c + self.c * o.d,+ d: self.b * o.c + self.d * o.d,+ tx: self.a * o.tx + self.c * o.ty + self.tx,+ ty: self.b * o.tx + self.d * o.ty + self.ty,+ }+ }+ #[inline]+ pub fn invert(&self) -> Option<Mat> {+ let det = self.a * self.d - self.b * self.c;+ if !det.is_finite() || det.abs() <= 1e-12 {+ return None;+ }+ let inv = 1.0 / det;+ Some(Mat {+ a: self.d * inv,+ b: -self.b * inv,+ c: -self.c * inv,+ d: self.a * inv,+ tx: (self.c * self.ty - self.d * self.tx) * inv,+ ty: (self.b * self.tx - self.a * self.ty) * inv,+ })+ }+}++#[derive(Clone, Copy)]+pub enum Use2 {+ Fill,+ Stroke,+}++#[derive(Clone, Debug)]+pub enum GradientKind {+ Linear(f64, f64, f64, f64),+ Radial(f64, f64, f64, f64, f64, f64),+ Conic,+}++#[derive(Clone, Debug)]+pub struct Gradient {+ pub kind: GradientKind,+ pub stops: Vec<(f64, [f64; 4])>,+}++impl Gradient {+ pub fn new(kind: GradientKind) -> Self {+ Self { kind, stops: Vec::new() }+ }+ pub fn add_stop(&mut self, offset: f64, rgba: [f64; 4]) {+ if offset.is_finite() && (0.0..=1.0).contains(&offset) {+ self.stops.push((offset, rgba));+ }+ }+}++#[derive(Clone)]+pub struct Pattern {+ pub data: Vec<u8>,+ pub width: u32,+ pub height: u32,+ pub repeat_x: bool,+ pub repeat_y: bool,+ pub transform: Mat,+}++#[derive(Clone)]+pub enum Paint {+ Color([f64; 4]),+ Gradient(Rc<RefCell<Gradient>>),+ Pattern(Rc<Pattern>),+}++impl Paint {+ pub fn color(r: f64, g: f64, b: f64, a: f64) -> Self {+ Paint::Color([r, g, b, a])+ }+}++pub fn composite_from_name(name: &str) -> Option<BlendMode> {+ Some(match name {+ "source-over" => BlendMode::SourceOver,+ "source-in" => BlendMode::SourceIn,+ "source-out" => BlendMode::SourceOut,+ "source-atop" => BlendMode::SourceAtop,+ "destination-over" => BlendMode::DestinationOver,+ "destination-in" => BlendMode::DestinationIn,+ "destination-out" => BlendMode::DestinationOut,+ "destination-atop" => BlendMode::DestinationAtop,+ "lighter" => BlendMode::Plus,+ "copy" => BlendMode::Source,+ "xor" => BlendMode::Xor,+ "multiply" => BlendMode::Multiply,+ "screen" => BlendMode::Screen,+ "overlay" => BlendMode::Overlay,+ "darken" => BlendMode::Darken,+ "lighten" => BlendMode::Lighten,+ "color-dodge" => BlendMode::ColorDodge,+ "color-burn" => BlendMode::ColorBurn,+ "hard-light" => BlendMode::HardLight,+ "soft-light" => BlendMode::SoftLight,+ "difference" => BlendMode::Difference,+ "exclusion" => BlendMode::Exclusion,+ "hue" => BlendMode::Hue,+ "saturation" => BlendMode::Saturation,+ "color" => BlendMode::Color,+ "luminosity" => BlendMode::Luminosity,+ _ => return None,+ })+}++#[derive(Clone, Copy, Debug)]+enum Seg {+ Move(f64, f64),+ Line(f64, f64),+ Quad(f64, f64, f64, f64),+ Cubic(f64, f64, f64, f64, f64, f64),+ Close,+}++#[derive(Clone, Default)]+pub struct Path {+ segs: Vec<Seg>,+ current: Option<(f64, f64)>,+ sub_start: Option<(f64, f64)>,+}++impl Path {+ pub fn clear(&mut self) {+ self.segs.clear();+ self.current = None;+ self.sub_start = None;+ }++ pub fn add_path(&mut self, other: &Path, m: &Mat) {+ for &seg in &other.segs {+ match seg {+ Seg::Move(x, y) => {+ let (nx, ny) = m.apply(x, y);+ self.segs.push(Seg::Move(nx, ny));+ self.current = Some((nx, ny));+ self.sub_start = Some((nx, ny));+ }+ Seg::Line(x, y) => {+ let (nx, ny) = m.apply(x, y);+ self.segs.push(Seg::Line(nx, ny));+ self.current = Some((nx, ny));+ }+ Seg::Quad(cx, cy, x, y) => {+ let (ncx, ncy) = m.apply(cx, cy);+ let (nx, ny) = m.apply(x, y);+ self.segs.push(Seg::Quad(ncx, ncy, nx, ny));+ self.current = Some((nx, ny));+ }+ Seg::Cubic(c1x, c1y, c2x, c2y, x, y) => {+ let (a, b) = m.apply(c1x, c1y);+ let (c, d) = m.apply(c2x, c2y);+ let (nx, ny) = m.apply(x, y);+ self.segs.push(Seg::Cubic(a, b, c, d, nx, ny));+ self.current = Some((nx, ny));+ }+ Seg::Close => {+ self.segs.push(Seg::Close);+ self.current = self.sub_start;+ }+ }+ }+ }++ pub fn move_to(&mut self, m: &Mat, x: f64, y: f64) {+ if !x.is_finite() || !y.is_finite() {+ return;+ }+ let (tx, ty) = m.apply(x, y);+ self.segs.push(Seg::Move(tx, ty));+ self.current = Some((tx, ty));+ self.sub_start = Some((tx, ty));+ }++ pub fn line_to(&mut self, m: &Mat, x: f64, y: f64) {+ if !x.is_finite() || !y.is_finite() {+ return;+ }+ let (tx, ty) = m.apply(x, y);+ if self.current.is_none() {+ self.segs.push(Seg::Move(tx, ty));+ self.sub_start = Some((tx, ty));+ } else {+ self.segs.push(Seg::Line(tx, ty));+ }+ self.current = Some((tx, ty));+ }++ pub fn quad_to(&mut self, m: &Mat, cx: f64, cy: f64, x: f64, y: f64) {+ if ![cx, cy, x, y].iter().all(|v| v.is_finite()) {+ return;+ }+ let (tcx, tcy) = m.apply(cx, cy);+ let (tx, ty) = m.apply(x, y);+ if self.current.is_none() {+ self.segs.push(Seg::Move(tcx, tcy));+ self.sub_start = Some((tcx, tcy));+ }+ self.segs.push(Seg::Quad(tcx, tcy, tx, ty));+ self.current = Some((tx, ty));+ }++ pub fn bezier_to(&mut self, m: &Mat, c1x: f64, c1y: f64, c2x: f64, c2y: f64, x: f64, y: f64) {+ if ![c1x, c1y, c2x, c2y, x, y].iter().all(|v| v.is_finite()) {+ return;+ }+ let (a, b) = m.apply(c1x, c1y);+ let (c, d) = m.apply(c2x, c2y);+ let (tx, ty) = m.apply(x, y);+ if self.current.is_none() {+ self.segs.push(Seg::Move(a, b));+ self.sub_start = Some((a, b));+ }+ self.segs.push(Seg::Cubic(a, b, c, d, tx, ty));+ self.current = Some((tx, ty));+ }++ pub fn arc_to(&mut self, m: &Mat, x1: f64, y1: f64, x2: f64, y2: f64, r: f64) {+ if ![x1, y1, x2, y2, r].iter().all(|v| v.is_finite()) || r < 0.0 {+ return;+ }+ let Some((px, py)) = self.current else {+ self.move_to(m, x1, y1);+ return;+ };+ let Some(inv) = m.invert() else { return };+ let (x0, y0) = inv.apply(px, py);+ if ((x0 - x1).abs() < 1e-9 && (y0 - y1).abs() < 1e-9) || ((x1 - x2).abs() < 1e-9 && (y1 - y2).abs() < 1e-9) || r == 0.0 {+ self.line_to(m, x1, y1);+ return;+ }+ let (dx0, dy0) = (x0 - x1, y0 - y1);+ let (dx2, dy2) = (x2 - x1, y2 - y1);+ let l0 = dx0.hypot(dy0);+ let l2 = dx2.hypot(dy2);+ let (ux0, uy0) = (dx0 / l0, dy0 / l0);+ let (ux2, uy2) = (dx2 / l2, dy2 / l2);+ let cross = ux0 * uy2 - uy0 * ux2;+ if cross.abs() < 1e-9 {+ self.line_to(m, x1, y1);+ return;+ }+ let dot = (ux0 * ux2 + uy0 * uy2).clamp(-1.0, 1.0);+ let half = dot.acos() * 0.5;+ let dist = r / half.tan();+ let (t1x, t1y) = (x1 + ux0 * dist, y1 + uy0 * dist);+ let (t2x, t2y) = (x1 + ux2 * dist, y1 + uy2 * dist);+ let sign = if cross > 0.0 { 1.0 } else { -1.0 };+ let (cx, cy) = (t1x - uy0 * r * sign, t1y + ux0 * r * sign);+ let a0 = (t1y - cy).atan2(t1x - cx);+ let a1 = (t2y - cy).atan2(t2x - cx);+ self.line_to(m, t1x, t1y);+ self.arc(m, cx, cy, r, a0, a1, cross > 0.0);+ }++ pub fn arc(&mut self, m: &Mat, cx: f64, cy: f64, r: f64, start: f64, end: f64, ccw: bool) {+ self.ellipse(m, cx, cy, r, r, 0.0, start, end, ccw);+ }++ #[allow(clippy::too_many_arguments)]+ pub fn ellipse(&mut self, m: &Mat, cx: f64, cy: f64, rx: f64, ry: f64, rot: f64, start: f64, end: f64, ccw: bool) {+ if ![cx, cy, rx, ry, rot, start, end].iter().all(|v| v.is_finite()) || rx < 0.0 || ry < 0.0 {+ return;+ }+ let mut sweep = end - start;+ if !ccw {+ if sweep >= TAU {+ sweep = TAU;+ } else {+ sweep = sweep.rem_euclid(TAU);+ if sweep == 0.0 && end != start {+ sweep = TAU;+ }+ }+ } else if sweep <= -TAU {+ sweep = -TAU;+ } else {+ sweep = -((-sweep).rem_euclid(TAU));+ if sweep == 0.0 && end != start {+ sweep = -TAU;+ }+ }+ let steps = ((sweep.abs() / (PI / 2.0)).ceil() as usize).max(1);+ let da = sweep / steps as f64;+ let k = (4.0 / 3.0) * (da / 4.0).tan();+ let (cr, sr) = (rot.cos(), rot.sin());+ let pt = |a: f64| -> (f64, f64) {+ let lx = rx * a.cos();+ let ly = ry * a.sin();+ (cx + lx * cr - ly * sr, cy + lx * sr + ly * cr)+ };+ let deriv = |a: f64| -> (f64, f64) {+ let lx = -rx * a.sin();+ let ly = ry * a.cos();+ (lx * cr - ly * sr, lx * sr + ly * cr)+ };+ let (sx, sy) = pt(start);+ if self.current.is_none() {+ self.move_to(m, sx, sy);+ } else {+ self.line_to(m, sx, sy);+ }+ for i in 0..steps {+ let a0 = start + da * i as f64;+ let a1 = start + da * (i + 1) as f64;+ let (p0x, p0y) = pt(a0);+ let (p1x, p1y) = pt(a1);+ let (d0x, d0y) = deriv(a0);+ let (d1x, d1y) = deriv(a1);+ self.bezier_to(m, p0x + k * d0x, p0y + k * d0y, p1x - k * d1x, p1y - k * d1y, p1x, p1y);+ }+ }++ pub fn rect(&mut self, m: &Mat, x: f64, y: f64, w: f64, h: f64) {+ if ![x, y, w, h].iter().all(|v| v.is_finite()) {+ return;+ }+ self.move_to(m, x, y);+ self.line_to(m, x + w, y);+ self.line_to(m, x + w, y + h);+ self.line_to(m, x, y + h);+ self.close();+ }++ pub fn round_rect(&mut self, m: &Mat, mut x: f64, mut y: f64, mut w: f64, mut h: f64, r: [f64; 8]) {+ if ![x, y, w, h].iter().all(|v| v.is_finite()) || r.iter().any(|v| !v.is_finite()) {+ return;+ }+ if w < 0.0 {+ x += w;+ w = -w;+ }+ if h < 0.0 {+ y += h;+ h = -h;+ }+ let mut r = [r[0].max(0.0), r[1].max(0.0), r[2].max(0.0), r[3].max(0.0), r[4].max(0.0), r[5].max(0.0), r[6].max(0.0), r[7].max(0.0)];+ let mut scale = 1.0f64;+ for (sum, lim) in [(r[0] + r[2], w), (r[6] + r[4], w), (r[1] + r[7], h), (r[3] + r[5], h)] {+ if sum > lim && sum > 0.0 {+ scale = scale.min(lim / sum);+ }+ }+ for v in &mut r {+ *v *= scale;+ }+ self.move_to(m, x + r[0], y);+ self.line_to(m, x + w - r[2], y);+ if r[2] > 0.0 && r[3] > 0.0 {+ self.ellipse(m, x + w - r[2], y + r[3], r[2], r[3], 0.0, -PI / 2.0, 0.0, false);+ }+ self.line_to(m, x + w, y + h - r[5]);+ if r[4] > 0.0 && r[5] > 0.0 {+ self.ellipse(m, x + w - r[4], y + h - r[5], r[4], r[5], 0.0, 0.0, PI / 2.0, false);+ }+ self.line_to(m, x + r[6], y + h);+ if r[6] > 0.0 && r[7] > 0.0 {+ self.ellipse(m, x + r[6], y + h - r[7], r[6], r[7], 0.0, PI / 2.0, PI, false);+ }+ self.line_to(m, x, y + r[1]);+ if r[0] > 0.0 && r[1] > 0.0 {+ self.ellipse(m, x + r[0], y + r[1], r[0], r[1], 0.0, PI, 1.5 * PI, false);+ }+ self.close();+ }++ pub fn close(&mut self) {+ if self.current.is_some() {+ self.segs.push(Seg::Close);+ self.current = self.sub_start;+ }+ }++ fn to_skia(&self, extra_transform: Option<&Mat>) -> Option<tiny_skia::Path> {+ let mut pb = PathBuilder::new();+ let tr = |x: f64, y: f64| -> (f32, f32) {+ match extra_transform {+ Some(m) => {+ let (nx, ny) = m.apply(x, y);+ (nx as f32, ny as f32)+ }+ None => (x as f32, y as f32),+ }+ };+ for &seg in &self.segs {+ match seg {+ Seg::Move(x, y) => {+ let (x, y) = tr(x, y);+ pb.move_to(x, y);+ }+ Seg::Line(x, y) => {+ let (x, y) = tr(x, y);+ pb.line_to(x, y);+ }+ Seg::Quad(cx, cy, x, y) => {+ let (cx, cy) = tr(cx, cy);+ let (x, y) = tr(x, y);+ pb.quad_to(cx, cy, x, y);+ }+ Seg::Cubic(c1x, c1y, c2x, c2y, x, y) => {+ let (a, b) = tr(c1x, c1y);+ let (c, d) = tr(c2x, c2y);+ let (x, y) = tr(x, y);+ pb.cubic_to(a, b, c, d, x, y);+ }+ Seg::Close => pb.close(),+ }+ }+ pb.finish()+ }+}++#[derive(Clone)]+pub struct State {+ pub ctm: Mat,+ pub fill: Paint,+ pub stroke: Paint,+ pub line_width: f64,+ pub cap: LineCap,+ pub join: LineJoin,+ pub miter: f64,+ pub dash: Vec<f64>,+ pub dash_offset: f64,+ pub alpha: f64,+ pub blend: BlendMode,+ pub shadow_x: f64,+ pub shadow_y: f64,+ pub shadow_blur: f64,+ pub shadow_color: Option<[f64; 4]>,+ pub smoothing: bool,+ pub smoothing_quality: u8,+ pub font: Rc<ParsedFont>,+ pub align: u8,+ pub baseline: u8,+ pub rtl: bool,+ pub letter_spacing: f64,+ pub word_spacing: f64,+ pub kerning: bool,+ pub clip: Option<Mask>,+}++impl Default for State {+ fn default() -> Self {+ Self {+ ctm: IDENTITY,+ fill: Paint::color(0.0, 0.0, 0.0, 1.0),+ stroke: Paint::color(0.0, 0.0, 0.0, 1.0),+ line_width: 1.0,+ cap: LineCap::Butt,+ join: LineJoin::Miter,+ miter: 10.0,+ dash: Vec::new(),+ dash_offset: 0.0,+ alpha: 1.0,+ blend: BlendMode::SourceOver,+ shadow_x: 0.0,+ shadow_y: 0.0,+ shadow_blur: 0.0,+ shadow_color: None,+ smoothing: true,+ smoothing_quality: 0,+ font: Rc::new(ParsedFont::default()),+ align: 0,+ baseline: 0,+ rtl: false,+ letter_spacing: 0.0,+ word_spacing: 0.0,+ kerning: true,+ clip: None,+ }+ }+}++pub struct Canvas {+ pub width: u32,+ pub height: u32,+ pub state: State,+ pub stack: Vec<State>,+ pub path: Path,+ pub dirty: bool,+}++fn color_from_rgba(rgba: [f64; 4], alpha_mul: f64) -> Color {+ let a = (rgba[3] * alpha_mul).clamp(0.0, 1.0) as f32;+ Color::from_rgba(rgba[0].clamp(0.0, 1.0) as f32, rgba[1].clamp(0.0, 1.0) as f32, rgba[2].clamp(0.0, 1.0) as f32, a).unwrap_or(Color::TRANSPARENT)+}++impl Canvas {+ pub fn new(width: u32, height: u32) -> Self {+ Self { width, height, state: State::default(), stack: Vec::new(), path: Path::default(), dirty: false }+ }++ pub fn reset(&mut self, pixels: &mut [u8]) {+ pixels.fill(0);+ self.state = State::default();+ self.stack.clear();+ self.path.clear();+ self.dirty = true;+ }++ pub fn save(&mut self) {+ self.stack.push(self.state.clone());+ }++ pub fn restore(&mut self) {+ if let Some(prev) = self.stack.pop() {+ self.state = prev;+ }+ }++ fn make_paint<'a>(&self, paint: &'a Paint, alpha_mul: f64) -> Option<SkPaint<'a>> {+ let mut sp = SkPaint { anti_alias: true, blend_mode: self.state.blend, ..Default::default() };+ match paint {+ Paint::Color(rgba) => {+ sp.set_color(color_from_rgba(*rgba, alpha_mul));+ }+ Paint::Gradient(g) => {+ let g = g.borrow();+ if g.stops.is_empty() {+ return None;+ }+ let mut sorted = g.stops.clone();+ sorted.sort_by(|a, b| a.0.total_cmp(&b.0));+ let stops: Vec<GradientStop> = sorted+ .iter()+ .map(|(off, c)| GradientStop::new(*off as f32, color_from_rgba(*c, alpha_mul)))+ .collect();+ let tr = self.state.ctm.to_skia();+ sp.shader = match g.kind {+ GradientKind::Linear(x0, y0, x1, y1) => {+ LinearGradient::new(Point::from_xy(x0 as f32, y0 as f32), Point::from_xy(x1 as f32, y1 as f32), stops, SpreadMode::Pad, tr)?+ }+ GradientKind::Radial(x0, y0, _r0, x1, y1, r1) => {+ RadialGradient::new(Point::from_xy(x0 as f32, y0 as f32), Point::from_xy(x1 as f32, y1 as f32), r1.max(0.001) as f32, stops, SpreadMode::Pad, tr)?+ }+ GradientKind::Conic => {+ // Fallback to first stop color when conic is requested.+ Shader::SolidColor(color_from_rgba(sorted[0].1, alpha_mul))+ }+ };+ }+ Paint::Pattern(pat) => {+ let p_ref = PixmapRef::from_bytes(&pat.data, pat.width, pat.height)?;+ let spread = if pat.repeat_x || pat.repeat_y { SpreadMode::Repeat } else { SpreadMode::Pad };+ let filter = if self.state.smoothing { FilterQuality::Bilinear } else { FilterQuality::Nearest };+ let tr = self.state.ctm.concat(&pat.transform).to_skia();+ sp.shader = SkPattern::new(p_ref, spread, filter, alpha_mul.clamp(0.0, 1.0) as f32, tr);+ }+ }+ Some(sp)+ }++ fn make_stroke(&self) -> Stroke {+ let mut s = Stroke {+ width: self.state.line_width as f32,+ miter_limit: self.state.miter as f32,+ line_cap: self.state.cap,+ line_join: self.state.join,+ dash: None,+ };+ if !self.state.dash.is_empty() {+ let intervals: Vec<f32> = self.state.dash.iter().map(|&v| v as f32).collect();+ s.dash = StrokeDash::new(intervals, self.state.dash_offset as f32);+ }+ s+ }++ pub fn fill(&mut self, pixels: &mut [u8], path2d: Option<&Path>, even_odd: bool) {+ let Some(mut pm) = PixmapMut::from_bytes(pixels, self.width, self.height) else { return };+ let path = match path2d {+ Some(p) => p.to_skia(Some(&self.state.ctm)),+ None => self.path.to_skia(None),+ };+ let Some(path) = path else { return };+ let rule = if even_odd { FillRule::EvenOdd } else { FillRule::Winding };+ if let Some(sp) = self.make_paint(&self.state.fill, self.state.alpha) {+ pm.fill_path(&path, &sp, rule, Transform::identity(), self.state.clip.as_ref());+ self.dirty = true;+ }+ }++ pub fn stroke(&mut self, pixels: &mut [u8], path2d: Option<&Path>) {+ let Some(mut pm) = PixmapMut::from_bytes(pixels, self.width, self.height) else { return };+ let path = match path2d {+ Some(p) => p.to_skia(Some(&self.state.ctm)),+ None => self.path.to_skia(None),+ };+ let Some(path) = path else { return };+ let mut stroke = self.make_stroke();+ // Scale stroke width by average CTM scale since paths are pre-transformed in device space.+ let sx = self.state.ctm.a.hypot(self.state.ctm.b);+ let sy = self.state.ctm.c.hypot(self.state.ctm.d);+ let scale = ((sx + sy) * 0.5) as f32;+ if scale.is_finite() && scale > 0.0 {+ stroke.width *= scale;+ }+ if let Some(sp) = self.make_paint(&self.state.stroke, self.state.alpha) {+ pm.stroke_path(&path, &sp, &stroke, Transform::identity(), self.state.clip.as_ref());+ self.dirty = true;+ }+ }++ pub fn clip(&mut self, path2d: Option<&Path>, even_odd: bool) {+ if self.width == 0 || self.height == 0 {+ return;+ }+ let path = match path2d {+ Some(p) => p.to_skia(Some(&self.state.ctm)),+ None => self.path.to_skia(None),+ };+ let Some(path) = path else { return };+ let rule = if even_odd { FillRule::EvenOdd } else { FillRule::Winding };+ if let Some(mask) = self.state.clip.as_mut() {+ mask.intersect_path(&path, rule, true, Transform::identity());+ } else if let Some(mut mask) = Mask::new(self.width, self.height) {+ mask.fill_path(&path, rule, true, Transform::identity());+ self.state.clip = Some(mask);+ }+ }++ pub fn is_point_in_path(&self, path2d: Option<&Path>, x: f64, y: f64, _even_odd: bool) -> bool {+ if !x.is_finite() || !y.is_finite() {+ return false;+ }+ let path = match path2d {+ Some(p) => p.to_skia(Some(&self.state.ctm)),+ None => self.path.to_skia(None),+ };+ let Some(path) = path else { return false };+ let b = path.bounds();+ let (px, py) = (x as f32, y as f32);+ px >= b.left() && px <= b.right() && py >= b.top() && py <= b.bottom()+ }++ pub fn is_point_in_stroke(&self, path2d: Option<&Path>, x: f64, y: f64) -> bool {+ self.is_point_in_path(path2d, x, y, false)+ }++ pub fn fill_rect(&mut self, pixels: &mut [u8], x: f64, y: f64, w: f64, h: f64) {+ if ![x, y, w, h].iter().all(|v| v.is_finite()) || w == 0.0 || h == 0.0 {+ return;+ }+ let mut p = Path::default();+ p.rect(&self.state.ctm, x, y, w, h);+ let Some(sk) = p.to_skia(None) else { return };+ let Some(mut pm) = PixmapMut::from_bytes(pixels, self.width, self.height) else { return };+ if let Some(sp) = self.make_paint(&self.state.fill, self.state.alpha) {+ pm.fill_path(&sk, &sp, FillRule::Winding, Transform::identity(), self.state.clip.as_ref());+ self.dirty = true;+ }+ }++ pub fn stroke_rect(&mut self, pixels: &mut [u8], x: f64, y: f64, w: f64, h: f64) {+ if ![x, y, w, h].iter().all(|v| v.is_finite()) || (w == 0.0 && h == 0.0) {+ return;+ }+ let mut p = Path::default();+ p.rect(&self.state.ctm, x, y, w, h);+ let Some(sk) = p.to_skia(None) else { return };+ let Some(mut pm) = PixmapMut::from_bytes(pixels, self.width, self.height) else { return };+ let mut stroke = self.make_stroke();+ let scale = ((self.state.ctm.a.hypot(self.state.ctm.b) + self.state.ctm.c.hypot(self.state.ctm.d)) * 0.5) as f32;+ if scale.is_finite() && scale > 0.0 {+ stroke.width *= scale;+ }+ if let Some(sp) = self.make_paint(&self.state.stroke, self.state.alpha) {+ pm.stroke_path(&sk, &sp, &stroke, Transform::identity(), self.state.clip.as_ref());+ self.dirty = true;+ }+ }++ pub fn clear_rect(&mut self, pixels: &mut [u8], x: f64, y: f64, w: f64, h: f64) {+ if ![x, y, w, h].iter().all(|v| v.is_finite()) || w == 0.0 || h == 0.0 {+ return;+ }+ let mut p = Path::default();+ p.rect(&self.state.ctm, x, y, w, h);+ let Some(sk) = p.to_skia(None) else { return };+ let Some(mut pm) = PixmapMut::from_bytes(pixels, self.width, self.height) else { return };+ let mut sp = SkPaint { anti_alias: false, blend_mode: BlendMode::Clear, ..Default::default() };+ sp.set_color(Color::TRANSPARENT);+ pm.fill_path(&sk, &sp, FillRule::Winding, Transform::identity(), self.state.clip.as_ref());+ self.dirty = true;+ }++ pub fn measure_text(&self, text_u16: &[u16]) -> [f64; 12] {+ let s = String::from_utf16_lossy(text_u16);+ let size = self.state.font.size.max(1.0);+ let lh = size * 1.25;+ let width = if s.is_empty() {+ 0.0+ } else {+ fonts::with_font_system(|fs| {+ let fam = resolve_family(fs, &self.state.font.families);+ let attrs = Attrs::new().family(fam).weight(Weight(self.state.font.weight.clamp(100, 900))).style(self.state.font.cosmic_style());+ let mut buf = Buffer::new(fs, Metrics::new(size as f32, lh as f32));+ buf.set_wrap(fs, Wrap::None);+ buf.set_text(fs, &s, attrs, Shaping::Advanced);+ buf.shape_until_scroll(fs, false);+ buf.layout_runs().map(|r| r.line_w as f64).fold(0.0, f64::max)+ })+ };+ let ascent = size * 0.85;+ let descent = size * 0.25;+ let dx = text_align_offset(self.state.align, self.state.rtl, width);+ let left = -dx;+ let right = width + dx;+ // [width, actualLeft, actualRight, fontAscent, fontDescent, actualAscent, actualDescent, emAscent, emDescent, hanging, alphabetic, ideographic]+ [width, left, right, ascent, descent, ascent, descent, ascent, descent, ascent * 0.8, 0.0, -descent]+ }++ pub fn draw_text(&mut self, pixels: &mut [u8], text_u16: &[u16], x: f64, y: f64, _max_width: Option<f64>, use_: Use2) {+ if !x.is_finite() || !y.is_finite() || text_u16.is_empty() || self.width == 0 || self.height == 0 {+ return;+ }+ let s = String::from_utf16_lossy(text_u16);+ let paint = match use_ {+ Use2::Fill => &self.state.fill,+ Use2::Stroke => &self.state.stroke,+ };+ let color = match paint {+ Paint::Color(c) => [+ (c[0].clamp(0.0, 1.0) * 255.0).round() as u8,+ (c[1].clamp(0.0, 1.0) * 255.0).round() as u8,+ (c[2].clamp(0.0, 1.0) * 255.0).round() as u8,+ ((c[3] * self.state.alpha).clamp(0.0, 1.0) * 255.0).round() as u8,+ ],+ _ => [0, 0, 0, (self.state.alpha.clamp(0.0, 1.0) * 255.0).round() as u8],+ };+ if color[3] == 0 {+ return;+ }+ let metrics = self.measure_text(text_u16);+ let width_px = metrics[0];+ let dx = text_align_offset(self.state.align, self.state.rtl, width_px);+ let ascent = metrics[3];+ let descent = metrics[4];+ let dy = match self.state.baseline {+ 1 => ascent, // top+ 2 => ascent * 0.8, // hanging+ 3 => (ascent - descent) * 0.5, // middle+ 4 | 5 => -descent, // ideographic / bottom+ _ => 0.0, // alphabetic+ };+ let scale = ((self.state.ctm.a.hypot(self.state.ctm.b) + self.state.ctm.c.hypot(self.state.ctm.d)) * 0.5).max(0.1);+ let (gx0, gy0) = self.state.ctm.apply(x + dx, y + dy);+ let font_size = (self.state.font.size * scale).max(1.0) as f32;+ let line_h = font_size * 1.25;++ fonts::with_font_system(|fs| {+ let fam = resolve_family(fs, &self.state.font.families);+ let attrs = Attrs::new()+ .family(fam)+ .weight(Weight(self.state.font.weight.clamp(100, 900)))+ .style(self.state.font.cosmic_style())+ .color(CosmicColor::rgba(color[0], color[1], color[2], color[3]));+ let mut buf = Buffer::new(fs, Metrics::new(font_size, line_h));+ buf.set_wrap(fs, Wrap::None);+ buf.set_text(fs, &s, attrs, Shaping::Advanced);+ buf.shape_until_scroll(fs, false);+ SWASH.with(|sc| {+ let mut swash = sc.borrow_mut();+ for run in buf.layout_runs() {+ for glyph in run.glyphs.iter() {+ let physical = glyph.physical((gx0 as f32, gy0 as f32), 1.0);+ let Some(img) = swash.get_image_uncached(fs, physical.cache_key) else { continue };+ let px = physical.x + img.placement.left;+ let py = physical.y - img.placement.top;+ blit_glyph(pixels, self.width, self.height, px, py, &img, color);+ }+ }+ });+ });+ self.dirty = true;+ }++ #[allow(clippy::too_many_arguments)]+ pub fn draw_image(&mut self, pixels: &mut [u8], src_data: &[u8], iw: u32, ih: u32, sx: f64, sy: f64, sw: f64, sh: f64, dx: f64, dy: f64, dw: f64, dh: f64) {+ let Some(mut pm) = PixmapMut::from_bytes(pixels, self.width, self.height) else { return };+ let Some(src_pm) = PixmapRef::from_bytes(src_data, iw, ih) else { return };+ if sw <= 0.0 || sh <= 0.0 || dw == 0.0 || dh == 0.0 {+ return;+ }+ let scale_x = dw / sw;+ let scale_y = dh / sh;+ let pat_tr = self.state.ctm.concat(&Mat {+ a: scale_x,+ b: 0.0,+ c: 0.0,+ d: scale_y,+ tx: dx - sx * scale_x,+ ty: dy - sy * scale_y,+ });+ let filter = if self.state.smoothing { FilterQuality::Bilinear } else { FilterQuality::Nearest };+ let paint = SkPaint {+ shader: SkPattern::new(src_pm, SpreadMode::Pad, filter, self.state.alpha.clamp(0.0, 1.0) as f32, pat_tr.to_skia()),+ blend_mode: self.state.blend,+ anti_alias: true,+ ..Default::default()+ };+ let (rx, rw) = if dw >= 0.0 { (dx, dw) } else { (dx + dw, -dw) };+ let (ry, rh) = if dh >= 0.0 { (dy, dh) } else { (dy + dh, -dh) };+ let Some(rect) = Rect::from_xywh(rx as f32, ry as f32, rw as f32, rh as f32) else { return };+ pm.fill_rect(rect, &paint, self.state.ctm.to_skia(), self.state.clip.as_ref());+ self.dirty = true;+ }++ pub fn get_image_data(&self, data: &[u8], sx: i64, sy: i64, sw: usize, sh: usize, out: &mut [u8]) {+ out[..sw * sh * 4].fill(0);+ let (w, h) = (self.width as i64, self.height as i64);+ for row in 0..sh {+ let y = sy + row as i64;+ if y < 0 || y >= h {+ continue;+ }+ for col in 0..sw {+ let x = sx + col as i64;+ if x < 0 || x >= w {+ continue;+ }+ let si = ((y as usize) * (self.width as usize) + (x as usize)) * 4;+ let di = (row * sw + col) * 4;+ let a = data[si + 3];+ out[di] = unpremul(data[si], a);+ out[di + 1] = unpremul(data[si + 1], a);+ out[di + 2] = unpremul(data[si + 2], a);+ out[di + 3] = a;+ }+ }+ }++ #[allow(clippy::too_many_arguments)]+ pub fn put_image_data(&mut self, data: &mut [u8], src: &[u8], sw: usize, sh: usize, dx: i64, dy: i64, dirty: (i64, i64, i64, i64)) {+ let (w, h) = (self.width as i64, self.height as i64);+ let x0 = dirty.0.max(0);+ let y0 = dirty.1.max(0);+ let x1 = dirty.2.min(sw as i64);+ let y1 = dirty.3.min(sh as i64);+ for sy in y0..y1 {+ let ty = dy + sy;+ if ty < 0 || ty >= h {+ continue;+ }+ for sx in x0..x1 {+ let tx = dx + sx;+ if tx < 0 || tx >= w {+ continue;+ }+ let si = (sy as usize * sw + sx as usize) * 4;+ let di = (ty as usize * self.width as usize + tx as usize) * 4;+ let a = src[si + 3];+ data[di] = premul(src[si], a);+ data[di + 1] = premul(src[si + 1], a);+ data[di + 2] = premul(src[si + 2], a);+ data[di + 3] = a;+ }+ }+ self.dirty = true;+ }+}++/// Horizontal offset for Canvas 2D `textAlign`, matching JS `ALIGN = ["start", "end", "left", "right", "center"]`.+fn text_align_offset(align: u8, rtl: bool, width: f64) -> f64 {+ match (align, rtl) {+ (4, _) => -width * 0.5, // center+ (3, _) | (1, false) | (0, true) => -width, // right / end (LTR) / start (RTL)+ _ => 0.0, // left / start (LTR) / end (RTL)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn text_align_matches_js_enum() {+ // JS ALIGN = ["start", "end", "left", "right", "center"]+ assert_eq!(text_align_offset(0, false, 100.0), 0.0); // start (LTR)+ assert_eq!(text_align_offset(0, true, 100.0), -100.0); // start (RTL)+ assert_eq!(text_align_offset(1, false, 100.0), -100.0); // end (LTR)+ assert_eq!(text_align_offset(1, true, 100.0), 0.0); // end (RTL)+ assert_eq!(text_align_offset(2, false, 100.0), 0.0); // left+ assert_eq!(text_align_offset(2, true, 100.0), 0.0); // left+ assert_eq!(text_align_offset(3, false, 100.0), -100.0); // right+ assert_eq!(text_align_offset(3, true, 100.0), -100.0); // right+ assert_eq!(text_align_offset(4, false, 100.0), -50.0); // center+ assert_eq!(text_align_offset(4, true, 100.0), -50.0); // center+ }++ #[test]+ fn draw_text_center_align_centers_pixels() {+ let (w, h) = (128u32, 128u32);+ let mut pixels = vec![0u8; (w * h * 4) as usize];+ let mut cv = Canvas::new(w, h);+ cv.state.font = Rc::new(fonts::parse_shorthand("32px sans-serif").unwrap());+ cv.state.fill = Paint::color(1.0, 1.0, 1.0, 1.0);+ cv.state.align = 4; // center+ cv.state.baseline = 3; // middle+ let txt: Vec<u16> = "HH".encode_utf16().collect();+ let m = cv.measure_text(&txt);+ assert!(m[0] > 0.0);+ assert!((m[1] - m[0] * 0.5).abs() < 1e-6, "actualLeft should be half width for center align");+ assert!((m[2] - m[0] * 0.5).abs() < 1e-6, "actualRight should be half width for center align");++ cv.draw_text(&mut pixels, &txt, 64.0, 64.0, None, Use2::Fill);+ let mut min_x = w;+ let mut max_x = 0u32;+ for y in 0..h {+ for x in 0..w {+ if pixels[((y * w + x) * 4 + 3) as usize] > 0 {+ min_x = min_x.min(x);+ max_x = max_x.max(x);+ }+ }+ }+ assert!(min_x < max_x, "expected rendered glyph pixels");+ let mid = (min_x + max_x) as f64 * 0.5;+ assert!((mid - 64.0).abs() <= 3.0, "expected centered glyph near x=64, got bounds {min_x}..={max_x} (mid={mid})");+ }+}diff --git a/runtime/crates/canvas2d/src/portable/codec.rs b/runtime/crates/canvas2d/src/portable/codec.rsnew file mode 100644index 0000000..453fdb6--- /dev/null+++ b/runtime/crates/canvas2d/src/portable/codec.rs@@ -0,0 +1,235 @@+//! Pure-Rust image decoding/encoding (`image` crate) and base64 for data URLs.+use std::io::Cursor;++use image::codecs::jpeg::JpegEncoder;+use image::codecs::png::PngEncoder;+use image::{ColorType, ImageEncoder};++/// Premultiplied RGBA8, rows top-down, stride = width × 4.+pub struct Decoded {+ pub width: u32,+ pub height: u32,+ pub data: Vec<u8>,+}++#[derive(Clone, Copy, Debug)]+pub enum Format {+ Png,+ Jpeg(f64),+}++impl Format {+ pub fn from_mime(mime: &str, quality: Option<f64>) -> Self {+ if mime.eq_ignore_ascii_case("image/jpeg") {+ let q = quality.filter(|q| q.is_finite() && (0.0..=1.0).contains(q)).unwrap_or(0.92);+ Format::Jpeg(q)+ } else {+ Format::Png+ }+ }+ pub fn mime(self) -> &'static str {+ match self {+ Format::Png => "image/png",+ Format::Jpeg(_) => "image/jpeg",+ }+ }+}++#[inline]+pub fn premul(c: u8, a: u8) -> u8 {+ ((c as u16 * a as u16 + 127) / 255) as u8+}++#[inline]+pub fn unpremul(c: u8, a: u8) -> u8 {+ if a == 0 {+ 0+ } else if a == 255 {+ c+ } else {+ ((c as u32 * 255 + a as u32 / 2) / a as u32).min(255) as u8+ }+}++/// Decode PNG / JPEG / GIF / WebP into premultiplied RGBA8, top-down.+pub fn decode(bytes: &[u8]) -> Result<Decoded, String> {+ if bytes.is_empty() {+ return Err("empty image data".into());+ }+ let img = image::load_from_memory(bytes).map_err(|e| format!("decode image: {e}"))?;+ let rgba = img.to_rgba8();+ let (w, h) = rgba.dimensions();+ if w == 0 || h == 0 || w > 32767 || h > 32767 || (w as u64) * (h as u64) > 268_435_456 {+ return Err("image dimensions out of range".into());+ }+ let mut data = rgba.into_raw();+ for px in data.chunks_exact_mut(4) {+ let a = px[3];+ if a != 255 {+ px[0] = premul(px[0], a);+ px[1] = premul(px[1], a);+ px[2] = premul(px[2], a);+ }+ }+ Ok(Decoded { width: w, height: h, data })+}++/// Encode RGBA8 (top-down) into PNG or JPEG.+pub fn encode(w: u32, h: u32, src: &[u8], premultiplied: bool, format: Format) -> Option<Vec<u8>> {+ let need = (w as usize).checked_mul(h as usize)?.checked_mul(4)?;+ if w == 0 || h == 0 || src.len() < need {+ return None;+ }+ let src = &src[..need];+ let mut out = Vec::new();+ match format {+ Format::Png => {+ let mut pixels = src.to_vec();+ if premultiplied {+ for p in pixels.chunks_exact_mut(4) {+ let a = p[3];+ p[0] = unpremul(p[0], a);+ p[1] = unpremul(p[1], a);+ p[2] = unpremul(p[2], a);+ }+ }+ let enc = PngEncoder::new(&mut out);+ enc.write_image(&pixels, w, h, ColorType::Rgba8.into()).ok()?;+ }+ Format::Jpeg(q) => {+ let mut rgb = Vec::with_capacity((w as usize) * (h as usize) * 3);+ for p in src.chunks_exact(4) {+ if premultiplied {+ rgb.extend_from_slice(&[p[0], p[1], p[2]]);+ } else {+ let a = p[3];+ rgb.extend_from_slice(&[premul(p[0], a), premul(p[1], a), premul(p[2], a)]);+ }+ }+ let quality = (q * 100.0).round().clamp(1.0, 100.0) as u8;+ let mut cursor = Cursor::new(&mut out);+ let enc = JpegEncoder::new_with_quality(&mut cursor, quality);+ enc.write_image(&rgb, w, h, ColorType::Rgb8.into()).ok()?;+ }+ }+ Some(out)+}++// ------------------------------------------------------------------------------------- base64++const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";++pub fn base64_encode_into(out: &mut String, bytes: &[u8]) {+ out.reserve(bytes.len().div_ceil(3) * 4);+ let mut chunks = bytes.chunks_exact(3);+ for c in &mut chunks {+ let n = (c[0] as u32) << 16 | (c[1] as u32) << 8 | c[2] as u32;+ out.push(B64[(n >> 18) as usize & 63] as char);+ out.push(B64[(n >> 12) as usize & 63] as char);+ out.push(B64[(n >> 6) as usize & 63] as char);+ out.push(B64[n as usize & 63] as char);+ }+ match chunks.remainder() {+ [a] => {+ let n = (*a as u32) << 16;+ out.push(B64[(n >> 18) as usize & 63] as char);+ out.push(B64[(n >> 12) as usize & 63] as char);+ out.push_str("==");+ }+ [a, b] => {+ let n = (*a as u32) << 16 | (*b as u32) << 8;+ out.push(B64[(n >> 18) as usize & 63] as char);+ out.push(B64[(n >> 12) as usize & 63] as char);+ out.push(B64[(n >> 6) as usize & 63] as char);+ out.push('=');+ }+ _ => {}+ }+}++pub fn base64_decode(s: &[u16]) -> Option<Vec<u8>> {+ let mut out = Vec::with_capacity(s.len() * 3 / 4);+ let mut acc: u32 = 0;+ let mut bits = 0;+ for &c in s {+ let v = match c {+ 0x41..=0x5A => c - 0x41,+ 0x61..=0x7A => c - 0x61 + 26,+ 0x30..=0x39 => c - 0x30 + 52,+ 0x2B | 0x2D => 62,+ 0x2F | 0x5F => 63,+ 0x3D => break,+ 0x20 | 0x09 | 0x0A | 0x0C | 0x0D => continue,+ _ => return None,+ } as u32;+ acc = acc << 6 | v;+ bits += 6;+ if bits >= 8 {+ bits -= 8;+ out.push((acc >> bits) as u8);+ }+ }+ Some(out)+}++pub fn parse_data_url(url: &[u16]) -> Option<(String, Vec<u8>)> {+ let comma = url.iter().position(|&c| c == b',' as u16)?;+ let head = String::from_utf16_lossy(&url[..comma]);+ let head = head.trim();+ let meta = head.get(..5).filter(|p| p.eq_ignore_ascii_case("data:")).map(|_| &head[5..])?;+ let body = &url[comma + 1..];+ let is_b64 = meta.to_ascii_lowercase().split(';').any(|p| p.trim() == "base64");+ let mime = meta.split(';').next().unwrap_or("").trim().to_ascii_lowercase();+ let bytes = if is_b64 {+ base64_decode(body)?+ } else {+ let s = String::from_utf16_lossy(body);+ let mut out = Vec::with_capacity(s.len());+ let b = s.as_bytes();+ let mut i = 0;+ while i < b.len() {+ if b[i] == b'%' && i + 2 < b.len() {+ if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) {+ out.push(v);+ i += 3;+ continue;+ }+ }+ out.push(b[i]);+ i += 1;+ }+ out+ };+ Some((mime, bytes))+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn b64_roundtrip() {+ for n in 0..20 {+ let v: Vec<u8> = (0..n).map(|i| (i * 37 + 11) as u8).collect();+ let mut s = String::new();+ base64_encode_into(&mut s, &v);+ let u: Vec<u16> = s.encode_utf16().collect();+ assert_eq!(base64_decode(&u).unwrap(), v);+ }+ }+ #[test]+ fn png_roundtrip_exact() {+ let (w, h) = (7u32, 5u32);+ let mut px = vec![0u8; 7 * 5 * 4];+ for (i, p) in px.chunks_exact_mut(4).enumerate() {+ let a = (i * 23 % 256) as u8;+ p[3] = a;+ p[0] = premul((i * 7) as u8, a);+ p[1] = premul((i * 13) as u8, a);+ p[2] = premul((i * 29) as u8, a);+ }+ let png = encode(w, h, &px, true, Format::Png).unwrap();+ let d = decode(&png).unwrap();+ assert_eq!((d.width, d.height), (w, h));+ assert_eq!(d.data, px);+ }+}diff --git a/runtime/crates/canvas2d/src/portable/fonts.rs b/runtime/crates/canvas2d/src/portable/fonts.rsnew file mode 100644index 0000000..7c71b49--- /dev/null+++ b/runtime/crates/canvas2d/src/portable/fonts.rs@@ -0,0 +1,239 @@+//! Pure-Rust font management and CSS `font` shorthand parsing over `cosmic-text` (`fontdb`).+use std::path::PathBuf;+use std::sync::{Mutex, OnceLock};++use cosmic_text::{Family, FontSystem, Style, Weight};++static FONT_DIR: Mutex<Option<PathBuf>> = Mutex::new(None);+static FONT_SYSTEM: OnceLock<Mutex<FontSystem>> = OnceLock::new();+static LOADED_DIR: Mutex<Option<PathBuf>> = Mutex::new(None);++/// Directory of bundled `.ttf`/`.otf`/`.ttc` faces (`<bundle>/fonts`).+pub fn set_dir(dir: PathBuf) {+ *FONT_DIR.lock().unwrap_or_else(|e| e.into_inner()) = Some(dir);+ register();+}++/// Ensure bundled fonts (if configured) are loaded into the shared `FontSystem`.+pub fn register() {+ let dir = FONT_DIR.lock().unwrap_or_else(|e| e.into_inner()).clone();+ let Some(dir) = dir else { return };+ let mut loaded = LOADED_DIR.lock().unwrap_or_else(|e| e.into_inner());+ if loaded.as_ref() == Some(&dir) {+ return;+ }+ with_font_system(|fs| {+ if dir.is_dir() {+ fs.db_mut().load_fonts_dir(&dir);+ }+ });+ *loaded = Some(dir);+}++pub(crate) fn with_font_system<R>(f: impl FnOnce(&mut FontSystem) -> R) -> R {+ let lock = FONT_SYSTEM.get_or_init(|| Mutex::new(FontSystem::new()));+ let mut fs = lock.lock().unwrap_or_else(|e| e.into_inner());+ f(&mut fs)+}++#[derive(Clone, Debug)]+pub struct ParsedFont {+ pub families: Vec<String>,+ pub weight: u16,+ pub italic: bool,+ pub size: f64,+ pub line_height: Option<f64>,+ pub small_caps: bool,+ pub stretch: Option<String>,+ pub oblique: bool,+}++impl Default for ParsedFont {+ fn default() -> Self {+ Self {+ families: vec!["sans-serif".into()],+ weight: 400,+ italic: false,+ size: 10.0,+ line_height: None,+ small_caps: false,+ stretch: None,+ oblique: false,+ }+ }+}++impl ParsedFont {+ pub fn to_css(&self) -> String {+ let mut out = String::new();+ if self.italic {+ out.push_str("italic ");+ } else if self.oblique {+ out.push_str("oblique ");+ }+ if self.small_caps {+ out.push_str("small-caps ");+ }+ if self.weight != 400 {+ out.push_str(&format!("{} ", self.weight));+ }+ out.push_str(&format!("{}px ", self.size));+ for (i, fam) in self.families.iter().enumerate() {+ if i > 0 {+ out.push_str(", ");+ }+ if fam.contains(' ') {+ out.push('"');+ out.push_str(fam);+ out.push('"');+ } else {+ out.push_str(fam);+ }+ }+ out+ }++ pub fn cosmic_weight(&self) -> Weight {+ Weight(self.weight.clamp(100, 900))+ }++ pub fn cosmic_style(&self) -> Style {+ if self.italic {+ Style::Italic+ } else if self.oblique {+ Style::Oblique+ } else {+ Style::Normal+ }+ }+}++/// Pick the first CSS family present in `fontdb`, falling back to generic `SansSerif` / `Serif` / `Monospace`.+pub(crate) fn resolve_family<'a>(fs: &FontSystem, families: &'a [String]) -> Family<'a> {+ let db = fs.db();+ for raw in families {+ let name = raw.trim().trim_matches('"').trim_matches('\'');+ if name.is_empty() {+ continue;+ }+ match name.to_ascii_lowercase().as_str() {+ "sans-serif" | "system-ui" | "-apple-system" | "blinkmacsystemfont" | "ui-sans-serif" => return Family::SansSerif,+ "serif" | "ui-serif" => return Family::Serif,+ "monospace" | "ui-monospace" => return Family::Monospace,+ "cursive" => return Family::Cursive,+ "fantasy" => return Family::Fantasy,+ _ => {+ if db.faces().any(|f| f.families.iter().any(|(fam, _)| fam.eq_ignore_ascii_case(name))) {+ return Family::Name(name);+ }+ }+ }+ }+ Family::SansSerif+}++fn parse_size(tok: &str) -> Option<(f64, Option<f64>)> {+ let (sz_s, lh_s) = match tok.split_once('/') {+ Some((a, b)) => (a, Some(b)),+ None => (tok, None),+ };+ let lower = sz_s.to_ascii_lowercase();+ let px = if let Some(v) = lower.strip_suffix("px") {+ v.parse::<f64>().ok()?+ } else if let Some(v) = lower.strip_suffix("pt") {+ v.parse::<f64>().ok()? * (4.0 / 3.0)+ } else if let Some(v) = lower.strip_suffix("em").or_else(|| lower.strip_suffix("rem")) {+ v.parse::<f64>().ok()? * 16.0+ } else if let Some(v) = lower.strip_suffix('%') {+ v.parse::<f64>().ok()? * 0.16+ } else {+ return None;+ };+ if !px.is_finite() || px <= 0.0 {+ return None;+ }+ let lh = lh_s.and_then(|s| {+ let l = s.to_ascii_lowercase();+ if let Some(v) = l.strip_suffix("px") {+ v.parse::<f64>().ok()+ } else {+ l.parse::<f64>().ok().map(|m| m * px)+ }+ });+ Some((px, lh))+}++/// Parse a CSS `font` shorthand (`[style] [variant] [weight] <size>[/<line-height>] <family-list>`).+pub fn parse_shorthand(css: &str) -> Option<ParsedFont> {+ let s = css.trim();+ if s.is_empty() {+ return None;+ }+ let mut weight = 400u16;+ let mut italic = false;+ let mut oblique = false;+ let mut small_caps = false;++ let mut rest = s;+ let (size, line_height) = loop {+ let trimmed = rest.trim_start();+ if trimmed.is_empty() {+ return None;+ }+ let end = trimmed.find(|c: char| c.is_ascii_whitespace()).unwrap_or(trimmed.len());+ let tok = &trimmed[..end];+ rest = &trimmed[end..];+ if let Some(sz) = parse_size(tok) {+ break sz;+ }+ match tok.to_ascii_lowercase().as_str() {+ "italic" => italic = true,+ "oblique" => oblique = true,+ "normal" => {}+ "small-caps" => small_caps = true,+ "bold" | "bolder" => weight = 700,+ "lighter" => weight = 300,+ other => {+ if let Ok(w) = other.parse::<u16>() {+ if (1..=1000).contains(&w) {+ weight = w;+ continue;+ }+ }+ return None;+ }+ }+ };++ let fam_str = rest.trim();+ if fam_str.is_empty() {+ return None;+ }+ let families: Vec<String> = fam_str+ .split(',')+ .map(|f| f.trim().trim_matches('"').trim_matches('\'').to_string())+ .filter(|f| !f.is_empty())+ .collect();+ if families.is_empty() {+ return None;+ }+ Some(ParsedFont { families, weight, italic, size, line_height, small_caps, stretch: None, oblique })+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn families() {+ let p = parse_shorthand("700 16px \"Nunito\", sans-serif").unwrap();+ assert_eq!(p.weight, 700);+ assert_eq!(p.size, 16.0);+ assert_eq!(p.families, vec!["Nunito", "sans-serif"]);+ assert!(parse_shorthand("not a font").is_none());+ }+ #[test]+ fn set_dir_does_not_deadlock() {+ set_dir(std::env::temp_dir());+ register();+ }+}diff --git a/runtime/crates/canvas2d/src/portable/js.rs b/runtime/crates/canvas2d/src/portable/js.rsnew file mode 100644index 0000000..ce16e64--- /dev/null+++ b/runtime/crates/canvas2d/src/portable/js.rs@@ -0,0 +1,664 @@+//! `__native.c2d` JS bindings for the pure-Rust Canvas 2D backend.+use std::cell::RefCell;+use std::rc::Rc;++use jsc::{Ctx, NativeResult, Persistent, Value};+use tiny_skia::{LineCap, LineJoin};++use super::canvas::{composite_from_name, Gradient, GradientKind, Mat, Paint, Path, Pattern, Use2, IDENTITY};+use super::codec::{self, Format};+use super::fonts;+use super::{self as registry, GRADIENTS, PATHS, PATTERNS, SURFACES};++fn num(c: Ctx, a: &[Value], i: usize) -> f64 {+ a.get(i).map(|v| v.to_num(c)).unwrap_or(f64::NAN)+}+fn uid(c: Ctx, a: &[Value], i: usize) -> u32 {+ let n = num(c, a, i);+ if n.is_finite() && n >= 0.0 { n as u32 } else { 0 }+}+fn flag(c: Ctx, a: &[Value], i: usize) -> bool {+ a.get(i).is_some_and(|v| v.to_bool(c))+}+fn utf16(c: Ctx, a: &[Value], i: usize) -> Vec<u16> {+ a.get(i).map(|v| v.to_js_string(c).utf16().to_vec()).unwrap_or_default()+}+fn string(c: Ctx, a: &[Value], i: usize) -> String {+ a.get(i).map(|v| v.to_string(c)).unwrap_or_default()+}+fn matrix(c: Ctx, a: &[Value], i: usize) -> Mat {+ Mat { a: num(c, a, i), b: num(c, a, i + 1), c: num(c, a, i + 2), d: num(c, a, i + 3), tx: num(c, a, i + 4), ty: num(c, a, i + 5) }+}+fn rgba(c: Ctx, a: &[Value], i: usize) -> [f64; 4] {+ let cl = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };+ [cl(num(c, a, i) / 255.0), cl(num(c, a, i + 1) / 255.0), cl(num(c, a, i + 2) / 255.0), cl(num(c, a, i + 3))]+}++fn path2d_op(target: u32, f: &dyn Fn(&mut Path, &Mat)) {+ let is_canvas = registry::with_canvas(target, |cv, _| {+ let m = cv.state.ctm;+ f(&mut cv.path, &m)+ });+ if is_canvas.is_none() {+ PATHS.with(|p| {+ if let Some(path) = p.borrow_mut().get_mut(&target) {+ f(path, &IDENTITY);+ }+ });+ }+}++fn take_path2d(id: u32) -> Option<Path> {+ if id == 0 {+ return None;+ }+ PATHS.with(|p| p.borrow().get(&id).cloned())+}++fn set_paint(c: Ctx, a: &[Value], stroke: bool, kind: u8) {+ let id = uid(c, a, 0);+ let paint = match kind {+ 0 => {+ let [r, g, b, al] = rgba(c, a, 1);+ Some(Paint::color(r, g, b, al))+ }+ _ => {+ let obj = uid(c, a, 1);+ GRADIENTS.with(|g| g.borrow().get(&obj).cloned().map(Paint::Gradient)).or_else(|| PATTERNS.with(|p| p.borrow().get(&obj).cloned().map(Paint::Pattern)))+ }+ };+ if let Some(p) = paint {+ registry::with_canvas(id, |cv, _| {+ if stroke { cv.state.stroke = p } else { cv.state.fill = p }+ });+ }+}++fn data_url(format: Format, bytes: &[u8]) -> String {+ let mut s = String::with_capacity(32 + bytes.len() * 4 / 3);+ s.push_str("data:");+ s.push_str(format.mime());+ s.push_str(";base64,");+ codec::base64_encode_into(&mut s, bytes);+ s+}++fn blank_data_url(w: u32, h: u32, format: Format) -> String {+ if w == 0 || h == 0 {+ return "data:,".into();+ }+ let px = vec![0u8; w as usize * h as usize * 4];+ match codec::encode(w, h, &px, true, format) {+ Some(b) => data_url(format, &b),+ None => "data:,".into(),+ }+}++fn decode_async(c: Ctx, bytes: Vec<u8>, b64: Option<Vec<u16>>, cb: Value) {+ if !cb.is_function(c) {+ return;+ }+ let cb = Persistent::new(c, cb);+ rt::spawn(+ move || {+ let bytes = match b64 {+ Some(url) => match codec::parse_data_url(&url) {+ Some((_, b)) => b,+ None => return Err("malformed data: URL".to_string()),+ },+ None => bytes,+ };+ codec::decode(&bytes)+ },+ move |c, res| {+ let args = match res {+ Ok(d) => {+ let (w, h) = (d.width, d.height);+ let id = registry::insert_image(w, h, d.data);+ [c.num(id as f64), c.num(w as f64), c.num(h as f64), c.undefined()]+ }+ Err(e) => [c.num(0.0), c.num(0.0), c.num(0.0), c.str(&e)],+ };+ if let Err(e) = c.call(cb.get(), None, &args) {+ rt::report("image load callback", &e);+ }+ },+ );+}++pub(crate) fn install(c: Ctx, native: Value) {+ let o = c.object();+ native.set(c, "c2d", o);+ let def = |name: &str, f: Box<dyn Fn(Ctx, &[Value]) -> NativeResult>| {+ o.set(c, name, c.function(move |c, _this, a| f(c, a)));+ };+ macro_rules! f {+ ($body:expr) => {+ Box::new($body)+ };+ }++ // canvases+ def("create", f!(|c, a| Ok(c.num(registry::create_canvas(uid(c, a, 0), uid(c, a, 1)) as f64))));+ def("resize", f!(|c, a| {+ registry::resize_canvas(uid(c, a, 0), uid(c, a, 1), uid(c, a, 2));+ Ok(c.undefined())+ }));+ def("release", f!(|c, a| {+ registry::release(uid(c, a, 0));+ Ok(c.undefined())+ }));+ def("reset", f!(|c, a| {+ registry::with_canvas(uid(c, a, 0), |cv, px| cv.reset(px));+ Ok(c.undefined())+ }));+ def("size", f!(|c, a| match registry::surface_size(uid(c, a, 0)) {+ Some((w, h)) => Ok(c.array(&[c.num(w as f64), c.num(h as f64)])),+ None => Ok(c.null()),+ }));+ def("version", f!(|c, a| Ok(c.num(SURFACES.with(|s| s.borrow().get(&uid(c, a, 0)).map(|s| s.version as f64).unwrap_or(0.0))))));++ // state+ def("save", f!(|c, a| {+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.save());+ Ok(c.undefined())+ }));+ def("restore", f!(|c, a| {+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.restore());+ Ok(c.undefined())+ }));+ def("setTransform", f!(|c, a| {+ let m = matrix(c, a, 1);+ if [m.a, m.b, m.c, m.d, m.tx, m.ty].iter().all(|v| v.is_finite()) {+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.state.ctm = m);+ }+ Ok(c.undefined())+ }));+ def("setFillColor", f!(|c, a| {+ set_paint(c, a, false, 0);+ Ok(c.undefined())+ }));+ def("setStrokeColor", f!(|c, a| {+ set_paint(c, a, true, 0);+ Ok(c.undefined())+ }));+ def("setFillPaint", f!(|c, a| {+ set_paint(c, a, false, 1);+ Ok(c.undefined())+ }));+ def("setStrokePaint", f!(|c, a| {+ set_paint(c, a, true, 1);+ Ok(c.undefined())+ }));+ def("setLine", f!(|c, a| {+ let (w, cap, join, miter) = (num(c, a, 1), uid(c, a, 2), uid(c, a, 3), num(c, a, 4));+ registry::with_canvas(uid(c, a, 0), |cv, _| {+ let s = &mut cv.state;+ if w.is_finite() && w > 0.0 {+ s.line_width = w;+ }+ s.cap = match cap {+ 1 => LineCap::Round,+ 2 => LineCap::Square,+ _ => LineCap::Butt,+ };+ s.join = match join {+ 1 => LineJoin::Round,+ 2 => LineJoin::Bevel,+ _ => LineJoin::Miter,+ };+ if miter.is_finite() && miter > 0.0 {+ s.miter = miter;+ }+ });+ Ok(c.undefined())+ }));+ def("setLineDash", f!(|c, a| {+ let offset = num(c, a, 1);+ let mut dash = Vec::new();+ if let Some(arr) = a.get(2).filter(|v| v.is_object(c)) {+ for i in 0..arr.len(c) {+ dash.push(arr.at(c, i).to_num(c));+ }+ }+ if dash.iter().any(|v| !v.is_finite() || *v < 0.0) {+ return Ok(c.undefined());+ }+ if dash.iter().all(|v| *v == 0.0) {+ dash.clear();+ }+ registry::with_canvas(uid(c, a, 0), |cv, _| {+ cv.state.dash = dash;+ if offset.is_finite() {+ cv.state.dash_offset = offset;+ }+ });+ Ok(c.undefined())+ }));+ def("setAlpha", f!(|c, a| {+ let v = num(c, a, 1);+ if v.is_finite() && (0.0..=1.0).contains(&v) {+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.state.alpha = v);+ }+ Ok(c.undefined())+ }));+ def("setComposite", f!(|c, a| {+ let ok = composite_from_name(&string(c, a, 1));+ if let Some(mode) = ok {+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.state.blend = mode);+ }+ Ok(c.bool(ok.is_some()))+ }));+ def("setShadow", f!(|c, a| {+ let (ox, oy, blur) = (num(c, a, 1), num(c, a, 2), num(c, a, 3));+ let col = rgba(c, a, 4);+ registry::with_canvas(uid(c, a, 0), |cv, _| {+ let s = &mut cv.state;+ if ox.is_finite() {+ s.shadow_x = ox;+ }+ if oy.is_finite() {+ s.shadow_y = oy;+ }+ if blur.is_finite() && blur >= 0.0 {+ s.shadow_blur = blur;+ }+ s.shadow_color = Some(col);+ });+ Ok(c.undefined())+ }));+ def("setSmoothing", f!(|c, a| {+ let (on, q) = (flag(c, a, 1), uid(c, a, 2));+ registry::with_canvas(uid(c, a, 0), |cv, _| {+ cv.state.smoothing = on;+ cv.state.smoothing_quality = q.min(2) as u8;+ });+ Ok(c.undefined())+ }));+ def("setFont", f!(|c, a| {+ let Some(p) = fonts::parse_shorthand(&string(c, a, 1)) else { return Ok(c.null()) };+ let css = p.to_css();+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.state.font = Rc::new(p));+ Ok(c.str(&css))+ }));+ def("setText", f!(|c, a| {+ let (al, bl, rtl, ls, ws, k) = (uid(c, a, 1), uid(c, a, 2), flag(c, a, 3), num(c, a, 4), num(c, a, 5), flag(c, a, 6));+ registry::with_canvas(uid(c, a, 0), |cv, _| {+ let s = &mut cv.state;+ s.align = al.min(4) as u8;+ s.baseline = bl.min(5) as u8;+ s.rtl = rtl;+ s.letter_spacing = if ls.is_finite() { ls } else { 0.0 };+ s.word_spacing = if ws.is_finite() { ws } else { 0.0 };+ s.kerning = k;+ });+ Ok(c.undefined())+ }));++ // paths+ def("newPath", f!(|c, _a| {+ let id = registry::next_id();+ PATHS.with(|p| p.borrow_mut().insert(id, Path::default()));+ Ok(c.num(id as f64))+ }));+ def("copyPath", f!(|c, a| {+ let src = uid(c, a, 0);+ let id = registry::next_id();+ let p = take_path2d(src).unwrap_or_default();+ PATHS.with(|m| m.borrow_mut().insert(id, p));+ Ok(c.num(id as f64))+ }));+ def("addPath", f!(|c, a| {+ let (dst, src) = (uid(c, a, 0), uid(c, a, 1));+ let mut m = matrix(c, a, 2);+ if ![m.a, m.b, m.c, m.d, m.tx, m.ty].iter().all(|v| v.is_finite()) {+ m = IDENTITY;+ }+ if let Some(sp) = take_path2d(src) {+ PATHS.with(|p| {+ if let Some(d) = p.borrow_mut().get_mut(&dst) {+ d.add_path(&sp, &m);+ }+ });+ }+ Ok(c.undefined())+ }));+ def("beginPath", f!(|c, a| {+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.path.clear());+ Ok(c.undefined())+ }));+ def("moveTo", f!(|c, a| {+ let (x, y) = (num(c, a, 1), num(c, a, 2));+ path2d_op(uid(c, a, 0), &|p, m| p.move_to(m, x, y));+ Ok(c.undefined())+ }));+ def("lineTo", f!(|c, a| {+ let (x, y) = (num(c, a, 1), num(c, a, 2));+ path2d_op(uid(c, a, 0), &|p, m| p.line_to(m, x, y));+ Ok(c.undefined())+ }));+ def("quadTo", f!(|c, a| {+ let v: Vec<f64> = (1..5).map(|i| num(c, a, i)).collect();+ path2d_op(uid(c, a, 0), &|p, m| p.quad_to(m, v[0], v[1], v[2], v[3]));+ Ok(c.undefined())+ }));+ def("bezierTo", f!(|c, a| {+ let v: Vec<f64> = (1..7).map(|i| num(c, a, i)).collect();+ path2d_op(uid(c, a, 0), &|p, m| p.bezier_to(m, v[0], v[1], v[2], v[3], v[4], v[5]));+ Ok(c.undefined())+ }));+ def("arcTo", f!(|c, a| {+ let v: Vec<f64> = (1..6).map(|i| num(c, a, i)).collect();+ path2d_op(uid(c, a, 0), &|p, m| p.arc_to(m, v[0], v[1], v[2], v[3], v[4]));+ Ok(c.undefined())+ }));+ def("arc", f!(|c, a| {+ let v: Vec<f64> = (1..6).map(|i| num(c, a, i)).collect();+ let ccw = flag(c, a, 6);+ path2d_op(uid(c, a, 0), &|p, m| p.arc(m, v[0], v[1], v[2], v[3], v[4], ccw));+ Ok(c.undefined())+ }));+ def("ellipse", f!(|c, a| {+ let v: Vec<f64> = (1..8).map(|i| num(c, a, i)).collect();+ let ccw = flag(c, a, 8);+ path2d_op(uid(c, a, 0), &|p, m| p.ellipse(m, v[0], v[1], v[2], v[3], v[4], v[5], v[6], ccw));+ Ok(c.undefined())+ }));+ def("rect", f!(|c, a| {+ let v: Vec<f64> = (1..5).map(|i| num(c, a, i)).collect();+ path2d_op(uid(c, a, 0), &|p, m| p.rect(m, v[0], v[1], v[2], v[3]));+ Ok(c.undefined())+ }));+ def("roundRect", f!(|c, a| {+ let v: Vec<f64> = (1..13).map(|i| num(c, a, i)).collect();+ let r = [v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11]];+ path2d_op(uid(c, a, 0), &|p, m| p.round_rect(m, v[0], v[1], v[2], v[3], r));+ Ok(c.undefined())+ }));+ def("closePath", f!(|c, a| {+ path2d_op(uid(c, a, 0), &|p, _| p.close());+ Ok(c.undefined())+ }));++ // drawing+ def("fill", f!(|c, a| {+ let p = take_path2d(uid(c, a, 1));+ let eo = flag(c, a, 2);+ registry::with_canvas(uid(c, a, 0), |cv, px| cv.fill(px, p.as_ref(), eo));+ Ok(c.undefined())+ }));+ def("stroke", f!(|c, a| {+ let p = take_path2d(uid(c, a, 1));+ registry::with_canvas(uid(c, a, 0), |cv, px| cv.stroke(px, p.as_ref()));+ Ok(c.undefined())+ }));+ def("clip", f!(|c, a| {+ let p = take_path2d(uid(c, a, 1));+ let eo = flag(c, a, 2);+ registry::with_canvas(uid(c, a, 0), |cv, _| cv.clip(p.as_ref(), eo));+ Ok(c.undefined())+ }));+ def("isPointInPath", f!(|c, a| {+ let p = take_path2d(uid(c, a, 1));+ let (x, y, eo) = (num(c, a, 2), num(c, a, 3), flag(c, a, 4));+ Ok(c.bool(registry::with_canvas(uid(c, a, 0), |cv, _| cv.is_point_in_path(p.as_ref(), x, y, eo)).unwrap_or(false)))+ }));+ def("isPointInStroke", f!(|c, a| {+ let p = take_path2d(uid(c, a, 1));+ let (x, y) = (num(c, a, 2), num(c, a, 3));+ Ok(c.bool(registry::with_canvas(uid(c, a, 0), |cv, _| cv.is_point_in_stroke(p.as_ref(), x, y)).unwrap_or(false)))+ }));+ def("fillRect", f!(|c, a| {+ let v: Vec<f64> = (1..5).map(|i| num(c, a, i)).collect();+ registry::with_canvas(uid(c, a, 0), |cv, px| cv.fill_rect(px, v[0], v[1], v[2], v[3]));+ Ok(c.undefined())+ }));+ def("strokeRect", f!(|c, a| {+ let v: Vec<f64> = (1..5).map(|i| num(c, a, i)).collect();+ registry::with_canvas(uid(c, a, 0), |cv, px| cv.stroke_rect(px, v[0], v[1], v[2], v[3]));+ Ok(c.undefined())+ }));+ def("clearRect", f!(|c, a| {+ let v: Vec<f64> = (1..5).map(|i| num(c, a, i)).collect();+ registry::with_canvas(uid(c, a, 0), |cv, px| cv.clear_rect(px, v[0], v[1], v[2], v[3]));+ Ok(c.undefined())+ }));+ for (name, use_) in [("fillText", Use2::Fill), ("strokeText", Use2::Stroke)] {+ def(name, Box::new(move |c, a| {+ let t = utf16(c, a, 1);+ let (x, y, mw) = (num(c, a, 2), num(c, a, 3), num(c, a, 4));+ let max_width = if a.get(4).is_some_and(|v| !v.is_undefined(c)) { Some(mw) } else { None };+ registry::with_canvas(uid(c, a, 0), |cv, px| cv.draw_text(px, &t, x, y, max_width, use_));+ Ok(c.undefined())+ }));+ }+ def("measureText", f!(|c, a| {+ let t = utf16(c, a, 1);+ let r = registry::with_canvas(uid(c, a, 0), |cv, _| cv.measure_text(&t));+ match r {+ Some(v) => Ok(c.array(&v.iter().map(|x| c.num(*x)).collect::<Vec<_>>())),+ None => Ok(c.null()),+ }+ }));+ def("drawImage", f!(|c, a| {+ let (dst, src) = (uid(c, a, 0), uid(c, a, 1));+ let v: Vec<f64> = (2..10).map(|i| num(c, a, i)).collect();+ let Some((img, iw, ih)) = registry::snapshot(src) else { return Ok(c.undefined()) };+ let (iw_f, ih_f) = (iw as f64, ih as f64);+ let (mut sx, mut sy, mut sw, mut sh) = (v[0], v[1], v[2], v[3]);+ let (mut dx, mut dy, mut dw, mut dh) = (v[4], v[5], v[6], v[7]);+ if sw == 0.0 || sh == 0.0 {+ return Ok(c.undefined());+ }+ let (kx, ky) = (dw / sw, dh / sh);+ if sx < 0.0 {+ dx -= sx * kx;+ dw += sx * kx;+ sw += sx;+ sx = 0.0;+ }+ if sy < 0.0 {+ dy -= sy * ky;+ dh += sy * ky;+ sh += sy;+ sy = 0.0;+ }+ if sx + sw > iw_f {+ let over = sx + sw - iw_f;+ dw -= over * kx;+ sw -= over;+ }+ if sy + sh > ih_f {+ let over = sy + sh - ih_f;+ dh -= over * ky;+ sh -= over;+ }+ if sw <= 0.0 || sh <= 0.0 {+ return Ok(c.undefined());+ }+ registry::with_canvas(dst, |cv, px| cv.draw_image(px, &img, iw, ih, sx, sy, sw, sh, dx, dy, dw, dh));+ Ok(c.undefined())+ }));+ def("getImageData", f!(|c, a| {+ let (sx, sy) = (num(c, a, 1).floor() as i64, num(c, a, 2).floor() as i64);+ let (sw, sh) = (uid(c, a, 3) as usize, uid(c, a, 4) as usize);+ let id = uid(c, a, 0);+ let Some(out) = a.get(5).and_then(|v| v.bytes(c)) else { return Err("getImageData: no buffer".into()) };+ if out.len() < sw * sh * 4 {+ return Err("getImageData: buffer too small".into());+ }+ SURFACES.with(|s| {+ let s = s.borrow();+ match s.get(&id) {+ Some(surf) if !surf.data.is_empty() => match &surf.canvas {+ Some(cv) => cv.get_image_data(&surf.data, sx, sy, sw, sh, out),+ None => out[..sw * sh * 4].fill(0),+ },+ _ => out[..sw * sh * 4].fill(0),+ }+ });+ Ok(c.undefined())+ }));+ def("putImageData", f!(|c, a| {+ let id = uid(c, a, 0);+ let (sw, sh) = (uid(c, a, 2) as usize, uid(c, a, 3) as usize);+ let (dx, dy) = (num(c, a, 4) as i64, num(c, a, 5) as i64);+ let dirty = (num(c, a, 6) as i64, num(c, a, 7) as i64, (num(c, a, 6) + num(c, a, 8)) as i64, (num(c, a, 7) + num(c, a, 9)) as i64);+ let Some(src) = a.get(1).and_then(|v| v.bytes(c)) else { return Err("putImageData: no data".into()) };+ if src.len() < sw * sh * 4 {+ return Err("putImageData: data too small".into());+ }+ let src = src.to_vec();+ registry::with_canvas(id, |cv, data| {+ if !data.is_empty() {+ cv.put_image_data(data, &src, sw, sh, dx, dy, dirty);+ }+ });+ Ok(c.undefined())+ }));++ // gradients / patterns+ def("linearGradient", f!(|c, a| {+ let v: Vec<f64> = (0..4).map(|i| num(c, a, i)).collect();+ let id = registry::next_id();+ GRADIENTS.with(|g| g.borrow_mut().insert(id, Rc::new(RefCell::new(Gradient::new(GradientKind::Linear(v[0], v[1], v[2], v[3]))))));+ Ok(c.num(id as f64))+ }));+ def("radialGradient", f!(|c, a| {+ let v: Vec<f64> = (0..6).map(|i| num(c, a, i)).collect();+ let id = registry::next_id();+ GRADIENTS.with(|g| g.borrow_mut().insert(id, Rc::new(RefCell::new(Gradient::new(GradientKind::Radial(v[0], v[1], v[2], v[3], v[4], v[5]))))));+ Ok(c.num(id as f64))+ }));+ def("conicGradient", f!(|c, _a| {+ let id = registry::next_id();+ GRADIENTS.with(|g| g.borrow_mut().insert(id, Rc::new(RefCell::new(Gradient::new(GradientKind::Conic)))));+ Ok(c.num(id as f64))+ }));+ def("addColorStop", f!(|c, a| {+ let (id, off) = (uid(c, a, 0), num(c, a, 1));+ let col = rgba(c, a, 2);+ GRADIENTS.with(|g| {+ if let Some(g) = g.borrow().get(&id) {+ g.borrow_mut().add_stop(off, col);+ }+ });+ Ok(c.undefined())+ }));+ def("pattern", f!(|c, a| {+ let (src, rep) = (uid(c, a, 0), uid(c, a, 1));+ let Some((data, w, h)) = registry::snapshot(src) else { return Ok(c.num(0.0)) };+ let id = registry::next_id();+ let p = Pattern { data, width: w, height: h, repeat_x: rep == 0 || rep == 1, repeat_y: rep == 0 || rep == 2, transform: IDENTITY };+ PATTERNS.with(|m| m.borrow_mut().insert(id, Rc::new(p)));+ Ok(c.num(id as f64))+ }));+ def("patternTransform", f!(|c, a| {+ let id = uid(c, a, 0);+ let m = matrix(c, a, 1);+ if [m.a, m.b, m.c, m.d, m.tx, m.ty].iter().all(|v| v.is_finite()) {+ PATTERNS.with(|p| {+ let mut p = p.borrow_mut();+ if let Some(old) = p.get(&id).cloned() {+ let new = Pattern { data: old.data.clone(), width: old.width, height: old.height, repeat_x: old.repeat_x, repeat_y: old.repeat_y, transform: m };+ p.insert(id, Rc::new(new));+ }+ });+ }+ Ok(c.undefined())+ }));++ // images+ def("decode", f!(|c, a| {+ let bytes = a.first().and_then(|v| v.bytes(c)).map(|b| b.to_vec()).unwrap_or_default();+ decode_async(c, bytes, None, a.get(1).copied().unwrap_or(c.undefined()));+ Ok(c.undefined())+ }));+ def("decodeDataURL", f!(|c, a| {+ let url = utf16(c, a, 0);+ decode_async(c, Vec::new(), Some(url), a.get(1).copied().unwrap_or(c.undefined()));+ Ok(c.undefined())+ }));+ def("imageFromPixels", f!(|c, a| {+ let (w, h) = (uid(c, a, 0), uid(c, a, 1));+ let Some(src) = a.get(2).and_then(|v| v.bytes(c)) else { return Ok(c.num(0.0)) };+ let n = w as usize * h as usize * 4;+ if n == 0 || src.len() < n {+ return Ok(c.num(0.0));+ }+ let mut data = src[..n].to_vec();+ for p in data.chunks_exact_mut(4) {+ let al = p[3];+ p[0] = codec::premul(p[0], al);+ p[1] = codec::premul(p[1], al);+ p[2] = codec::premul(p[2], al);+ }+ Ok(c.num(registry::insert_image(w, h, data) as f64))+ }));+ def("copySurface", f!(|c, a| {+ let src = uid(c, a, 0);+ let copy = SURFACES.with(|s| s.borrow().get(&src).map(|s| (s.width, s.height, s.data.clone())));+ match copy {+ Some((w, h, data)) if !data.is_empty() => Ok(c.num(registry::insert_image(w, h, data) as f64)),+ _ => Ok(c.num(0.0)),+ }+ }));++ // encoding+ def("toDataURL", f!(|c, a| {+ let id = uid(c, a, 0);+ let q = num(c, a, 2);+ let format = Format::from_mime(&string(c, a, 1), q.is_finite().then_some(q));+ let url = SURFACES.with(|s| {+ let s = s.borrow();+ let surf = s.get(&id)?;+ if surf.width == 0 || surf.height == 0 {+ return Some("data:,".to_string());+ }+ if surf.data.is_empty() {+ return Some(blank_data_url(surf.width, surf.height, format));+ }+ codec::encode(surf.width, surf.height, &surf.data, true, format).map(|b| data_url(format, &b))+ });+ Ok(c.str(&url.unwrap_or_else(|| "data:,".into())))+ }));+ def("encodeRGBA", f!(|c, a| {+ let (w, h) = (uid(c, a, 0), uid(c, a, 1));+ let q = num(c, a, 4);+ let format = Format::from_mime(&string(c, a, 3), q.is_finite().then_some(q));+ if w == 0 || h == 0 {+ return Ok(c.str("data:,"));+ }+ let Some(px) = a.get(2).and_then(|v| v.bytes(c)) else { return Ok(c.str(&blank_data_url(w, h, format))) };+ let px = px.to_vec();+ match codec::encode(w, h, &px, false, format) {+ Some(b) => Ok(c.str(&data_url(format, &b))),+ None => Ok(c.str("data:,")),+ }+ }));+ def("blankDataURL", f!(|c, a| {+ let q = num(c, a, 3);+ let format = Format::from_mime(&string(c, a, 2), q.is_finite().then_some(q));+ Ok(c.str(&blank_data_url(uid(c, a, 0), uid(c, a, 1), format)))+ }));++ if std::env::var_os("THREERT_C2D_TEST").is_some() || std::env::var_os("POCKET_C2D_TEST").is_some() {+ def("_writeFile", f!(|c, a| {+ let path = string(c, a, 0);+ let ok = match a.get(1) {+ Some(v) if v.typed_kind(c) != jsc::TypedArrayType::None => std::fs::write(&path, v.bytes(c).unwrap_or_default()).is_ok(),+ Some(v) => {+ let s = v.to_string(c);+ if let Some(b64) = s.strip_prefix("data:image/png;base64,") {+ let u: Vec<u16> = b64.encode_utf16().collect();+ std::fs::write(&path, codec::base64_decode(&u).unwrap_or_default()).is_ok()+ } else {+ std::fs::write(&path, s).is_ok()+ }+ }+ None => false,+ };+ Ok(c.bool(ok))+ }));+ }+}diff --git a/runtime/crates/canvas2d/src/portable/mod.rs b/runtime/crates/canvas2d/src/portable/mod.rsnew file mode 100644index 0000000..8d75c7b--- /dev/null+++ b/runtime/crates/canvas2d/src/portable/mod.rs@@ -0,0 +1,150 @@+//! Pure-Rust Canvas 2D, image codec, and text layout backend (`tiny-skia` + `cosmic-text` + `image`).+use std::cell::{Cell, RefCell};+use std::collections::HashMap;+use std::rc::Rc;++use jsc::{Ctx, Value};++pub mod canvas;+pub mod codec;+pub mod fonts;+mod js;+pub mod textblock;++use crate::Bitmap;+use canvas::{Canvas, Gradient, Path, Pattern};++pub(crate) struct Surface {+ pub width: u32,+ pub height: u32,+ pub canvas: Option<Box<Canvas>>,+ pub version: u64,+ /// premultiplied RGBA8, top-down, stride = width * 4+ pub data: Vec<u8>,+}++thread_local! {+ static NEXT_ID: Cell<u32> = const { Cell::new(1) };+ pub(crate) static SURFACES: RefCell<HashMap<u32, Surface>> = RefCell::new(HashMap::new());+ pub(crate) static PATHS: RefCell<HashMap<u32, Path>> = RefCell::new(HashMap::new());+ pub(crate) static GRADIENTS: RefCell<HashMap<u32, Rc<RefCell<Gradient>>>> = RefCell::new(HashMap::new());+ pub(crate) static PATTERNS: RefCell<HashMap<u32, Rc<Pattern>>> = RefCell::new(HashMap::new());+}++const MAX_SIDE: u32 = 32767;+const MAX_AREA: u64 = 268_435_456;++pub(crate) fn next_id() -> u32 {+ NEXT_ID.with(|n| {+ let v = n.get();+ n.set(if v == u32::MAX { 1 } else { v + 1 });+ v+ })+}++fn alloc_pixels(w: u32, h: u32) -> (u32, u32, Vec<u8>) {+ if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE || w as u64 * h as u64 > MAX_AREA {+ return (w, h, Vec::new());+ }+ let n = w as usize * h as usize * 4;+ let mut v = Vec::new();+ if v.try_reserve_exact(n).is_err() {+ return (w, h, Vec::new());+ }+ v.resize(n, 0);+ (w, h, v)+}++pub(crate) fn create_canvas(w: u32, h: u32) -> u32 {+ let id = next_id();+ let (w, h, data) = alloc_pixels(w, h);+ let canvas = Canvas::new(if data.is_empty() { 0 } else { w }, if data.is_empty() { 0 } else { h });+ SURFACES.with(|s| s.borrow_mut().insert(id, Surface { width: w, height: h, canvas: Some(Box::new(canvas)), version: 1, data }));+ id+}++pub(crate) fn resize_canvas(id: u32, w: u32, h: u32) -> bool {+ SURFACES.with(|s| {+ let mut s = s.borrow_mut();+ let Some(surf) = s.get_mut(&id) else { return false };+ if surf.canvas.is_none() {+ return false;+ }+ let (w, h, data) = alloc_pixels(w, h);+ surf.canvas = Some(Box::new(Canvas::new(if data.is_empty() { 0 } else { w }, if data.is_empty() { 0 } else { h })));+ surf.data = data;+ surf.width = w;+ surf.height = h;+ surf.version += 1;+ true+ })+}++pub(crate) fn insert_image(width: u32, height: u32, data: Vec<u8>) -> u32 {+ let id = next_id();+ SURFACES.with(|s| s.borrow_mut().insert(id, Surface { width, height, canvas: None, version: 1, data }));+ id+}++pub(crate) fn release(id: u32) {+ SURFACES.with(|s| s.borrow_mut().remove(&id));+ PATHS.with(|p| p.borrow_mut().remove(&id));+ GRADIENTS.with(|g| g.borrow_mut().remove(&id));+ PATTERNS.with(|p| p.borrow_mut().remove(&id));+}++pub(crate) fn reset() {+ SURFACES.with(|s| s.borrow_mut().clear());+ PATHS.with(|p| p.borrow_mut().clear());+ GRADIENTS.with(|g| g.borrow_mut().clear());+ PATTERNS.with(|p| p.borrow_mut().clear());+}++pub(crate) fn with_canvas<R>(id: u32, f: impl FnOnce(&mut Canvas, &mut Vec<u8>) -> R) -> Option<R> {+ SURFACES.with(|s| {+ let mut s = s.borrow_mut();+ let surf = s.get_mut(&id)?;+ let canvas = surf.canvas.as_mut()?;+ let r = f(canvas, &mut surf.data);+ if canvas.dirty {+ canvas.dirty = false;+ surf.version += 1;+ }+ Some(r)+ })+}++pub(crate) fn surface_size(id: u32) -> Option<(u32, u32)> {+ SURFACES.with(|s| s.borrow().get(&id).map(|s| (s.width, s.height)))+}++pub(crate) fn snapshot(id: u32) -> Option<(Vec<u8>, u32, u32)> {+ SURFACES.with(|s| {+ let s = s.borrow();+ let surf = s.get(&id)?;+ if surf.data.is_empty() {+ return None;+ }+ Some((surf.data.clone(), surf.width, surf.height))+ })+}++pub fn install(c: Ctx, native: Value) {+ rt::on_reset(reset);+ js::install(c, native);+}++pub fn with_bitmap<R>(id: u32, f: impl FnOnce(&Bitmap) -> R) -> Option<R> {+ SURFACES.with(|s| {+ let s = s.borrow();+ let surf = s.get(&id)?;+ if surf.data.is_empty() {+ return None;+ }+ Some(f(&Bitmap { width: surf.width, height: surf.height, stride: surf.width as usize * 4, data: &surf.data, version: surf.version }))+ })+}++pub fn bitmap_version(id: u32) -> Option<u64> {+ SURFACES.with(|s| s.borrow().get(&id).map(|s| s.version))+}diff --git a/runtime/crates/canvas2d/src/portable/textblock.rs b/runtime/crates/canvas2d/src/portable/textblock.rsnew file mode 100644index 0000000..12c8d06--- /dev/null+++ b/runtime/crates/canvas2d/src/portable/textblock.rs@@ -0,0 +1,275 @@+//! Pure-Rust text measurement, soft wrapping, and rasterization for PocketJS native UI text+//! (`text.layout.native`), backed by `cosmic-text` + `swash`.+use std::cell::RefCell;++use cosmic_text::{Attrs, Buffer, Color, Metrics, Shaping, SwashCache, SwashContent, Weight, Wrap};++use super::fonts::{self, resolve_family, ParsedFont};++thread_local! {+ static SWASH: RefCell<SwashCache> = RefCell::new(SwashCache::new());+}++/// A face request: CSS families, weight (100–900), italic, size in px.+#[derive(Clone, Debug, PartialEq)]+pub struct TextFont {+ pub families: Vec<String>,+ pub weight: u16,+ pub italic: bool,+ pub size: f64,+}++/// A resolved face for text blocks.+pub struct BlockFont {+ parsed: ParsedFont,+}++impl BlockFont {+ pub fn new(spec: &TextFont) -> BlockFont {+ fonts::register();+ BlockFont {+ parsed: ParsedFont {+ families: spec.families.clone(),+ weight: spec.weight,+ italic: spec.italic,+ size: spec.size.max(1.0),+ line_height: None,+ small_caps: false,+ stretch: None,+ oblique: false,+ },+ }+ }++ /// CSS `line-height: normal` for this face, in px.+ pub fn normal_line_height(&self) -> f64 {+ (self.parsed.size * 1.25).ceil()+ }++ /// Advance width of one line (no `'\n'`), in px.+ pub fn measure(&self, line: &str) -> f64 {+ self.measure_spaced(line, 0.0)+ }++ /// Advance width of one line with `tracking` px after each character.+ pub fn measure_spaced(&self, line: &str, tracking: f64) -> f64 {+ if line.is_empty() {+ return 0.0;+ }+ let size = self.parsed.size as f32;+ let lh = self.normal_line_height() as f32;+ let width = fonts::with_font_system(|fs| {+ let fam = resolve_family(fs, &self.parsed.families);+ let attrs = Attrs::new().family(fam).weight(Weight(self.parsed.weight.clamp(100, 900))).style(self.parsed.cosmic_style());+ let mut buf = Buffer::new(fs, Metrics::new(size, lh));+ buf.set_wrap(fs, Wrap::None);+ buf.set_text(fs, line, attrs, Shaping::Advanced);+ buf.shape_until_scroll(fs, false);+ buf.layout_runs().map(|r| r.line_w as f64).fold(0.0, f64::max)+ });+ let extra = if tracking != 0.0 {+ let chars = line.chars().count();+ if chars > 1 { (chars - 1) as f64 * tracking } else { 0.0 }+ } else {+ 0.0+ };+ (width + extra).max(0.0)+ }++ /// Soft-break positions (UTF-16 offsets, ascending) keeping each row within `max_width` px.+ pub fn wrap(&self, line: &str, max_width: f64) -> Vec<u32> {+ let mut breaks = Vec::new();+ if line.is_empty() || !(max_width > 0.0) || self.measure(line) <= max_width {+ return breaks;+ }+ let size = self.parsed.size as f32;+ let lh = self.normal_line_height() as f32;+ let byte_starts: Vec<usize> = fonts::with_font_system(|fs| {+ let fam = resolve_family(fs, &self.parsed.families);+ let attrs = Attrs::new().family(fam).weight(Weight(self.parsed.weight.clamp(100, 900))).style(self.parsed.cosmic_style());+ let mut buf = Buffer::new(fs, Metrics::new(size, lh));+ buf.set_wrap(fs, Wrap::WordOrGlyph);+ buf.set_size(fs, Some(max_width as f32), None);+ buf.set_text(fs, line, attrs, Shaping::Advanced);+ buf.shape_until_scroll(fs, false);+ buf.layout_runs()+ .skip(1)+ .filter_map(|run| run.glyphs.first().map(|g| g.start))+ .collect()+ });+ let mut last = 0u32;+ for byte_idx in byte_starts {+ if byte_idx == 0 || byte_idx >= line.len() || !line.is_char_boundary(byte_idx) {+ continue;+ }+ let u16_off = line[..byte_idx].encode_utf16().count() as u32;+ if u16_off > last {+ breaks.push(u16_off);+ last = u16_off;+ }+ }+ breaks+ }+}++/// Pixels of a painted block.+pub struct PaintedBlock {+ pub width: u32,+ pub height: u32,+ /// straight-alpha RGBA8, sRGB+ pub rgba: Vec<u8>,+ /// logical offset of pixel (0, 0) from the block's origin+ pub offset: [f32; 2],+}++/// Paint `text` (lines separated by `'\n'`) in `color` (straight RGBA), aligned within `box_width`+/// (0 left, 1 center, 2 right), `tracking` px after each character, at `scale` device px per px.+#[allow(clippy::too_many_arguments)]+pub fn paint(font: &BlockFont, text: &str, color: [u8; 4], align: u8, box_width: f32, line_height: f32, tracking: f32, scale: f32) -> Option<PaintedBlock> {+ let lines: Vec<&str> = text.split('\n').collect();+ let widths: Vec<f64> = lines.iter().map(|line| font.measure_spaced(line, tracking as f64)).collect();+ if widths.iter().all(|w| *w <= 0.0) {+ return None;+ }+ let scale = scale.max(1.0) as f64;+ let line_h = (line_height as f64).max(1.0);+ let pad_x = (font.parsed.size * 0.25).ceil() + 2.0;+ let pad_y = (font.parsed.size * 0.25).ceil() + 2.0;+ let content_w = widths.iter().cloned().fold(box_width as f64, f64::max);+ let logical_w = content_w + 2.0 * pad_x;+ let logical_h = line_h * lines.len() as f64 + 2.0 * pad_y;+ let width = (logical_w * scale).ceil() as u32;+ let height = (logical_h * scale).ceil() as u32;+ if width == 0 || height == 0 || width > 16384 || height > 16384 {+ return None;+ }++ // Premultiplied scratch buffer, converted to straight alpha at the end.+ let mut pixels = vec![0u8; width as usize * height as usize * 4];+ let px_size = (font.parsed.size * scale) as f32;+ let px_lh = (line_h * scale) as f32;++ fonts::with_font_system(|fs| {+ let fam = resolve_family(fs, &font.parsed.families);+ let attrs = Attrs::new()+ .family(fam)+ .weight(Weight(font.parsed.weight.clamp(100, 900)))+ .style(font.parsed.cosmic_style())+ .color(Color::rgba(color[0], color[1], color[2], color[3]));+ SWASH.with(|sc| {+ let mut swash = sc.borrow_mut();+ for (row, (line, line_w)) in lines.iter().zip(&widths).enumerate() {+ if line.is_empty() {+ continue;+ }+ let dx = match align {+ 1 => (box_width as f64 - line_w) / 2.0,+ 2 => box_width as f64 - line_w,+ _ => 0.0,+ };+ let origin_x = ((pad_x + dx) * scale) as f32;+ let origin_y = ((pad_y + row as f64 * line_h) * scale) as f32;++ let mut buf = Buffer::new(fs, Metrics::new(px_size, px_lh));+ buf.set_wrap(fs, Wrap::None);+ buf.set_text(fs, line, attrs, Shaping::Advanced);+ buf.shape_until_scroll(fs, false);++ for run in buf.layout_runs() {+ let mut char_idx = 0usize;+ let mut last_start = usize::MAX;+ for glyph in run.glyphs.iter() {+ if glyph.start != last_start {+ if last_start != usize::MAX {+ char_idx += 1;+ }+ last_start = glyph.start;+ }+ let extra_x = char_idx as f32 * tracking * scale as f32;+ let physical = glyph.physical((origin_x + extra_x, origin_y + run.line_y), 1.0);+ let Some(img) = swash.get_image_uncached(fs, physical.cache_key) else { continue };+ let gx = physical.x + img.placement.left;+ let gy = physical.y - img.placement.top;+ blit_glyph(&mut pixels, width, height, gx, gy, &img, color);+ }+ }+ }+ });+ });++ // premultiplied → straight alpha+ for px in pixels.chunks_exact_mut(4) {+ let a = px[3] as u32;+ if a != 0 && a != 255 {+ for c in &mut px[..3] {+ *c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8;+ }+ }+ }++ Some(PaintedBlock { width, height, rgba: pixels, offset: [-pad_x as f32, -pad_y as f32] })+}++pub(crate) fn blit_glyph(dst: &mut [u8], w: u32, h: u32, gx: i32, gy: i32, img: &cosmic_text::SwashImage, color: [u8; 4]) {+ let gw = img.placement.width as i32;+ let gh = img.placement.height as i32;+ if gw <= 0 || gh <= 0 {+ return;+ }+ let cr = color[0] as u32;+ let cg = color[1] as u32;+ let cb = color[2] as u32;+ let ca = color[3] as u32;++ for row in 0..gh {+ let dy = gy + row;+ if dy < 0 || dy >= h as i32 {+ continue;+ }+ for col in 0..gw {+ let dx = gx + col;+ if dx < 0 || dx >= w as i32 {+ continue;+ }+ let src_idx = (row as usize) * (gw as usize) + (col as usize);+ let (sr, sg, sb, sa) = match img.content {+ SwashContent::Mask => {+ let cov = img.data[src_idx] as u32;+ if cov == 0 {+ continue;+ }+ let a = (cov * ca + 127) / 255;+ ((cr * a + 127) / 255, (cg * a + 127) / 255, (cb * a + 127) / 255, a)+ }+ SwashContent::Color => {+ let o = src_idx * 4;+ let a = (img.data[o + 3] as u32 * ca + 127) / 255;+ if a == 0 {+ continue;+ }+ (+ (img.data[o] as u32 * a + 127) / 255,+ (img.data[o + 1] as u32 * a + 127) / 255,+ (img.data[o + 2] as u32 * a + 127) / 255,+ a,+ )+ }+ SwashContent::SubpixelMask => {+ let o = src_idx * 4;+ let cov = ((img.data[o] as u32 + img.data[o + 1] as u32 + img.data[o + 2] as u32) / 3).min(255);+ if cov == 0 {+ continue;+ }+ let a = (cov * ca + 127) / 255;+ ((cr * a + 127) / 255, (cg * a + 127) / 255, (cb * a + 127) / 255, a)+ }+ };+ let di = ((dy as usize) * (w as usize) + (dx as usize)) * 4;+ let inv = 255 - sa;+ dst[di] = (sr + (dst[di] as u32 * inv + 127) / 255).min(255) as u8;+ dst[di + 1] = (sg + (dst[di + 1] as u32 * inv + 127) / 255).min(255) as u8;+ dst[di + 2] = (sb + (dst[di + 2] as u32 * inv + 127) / 255).min(255) as u8;+ dst[di + 3] = (sa + (dst[di + 3] as u32 * inv + 127) / 255).min(255) as u8;+ }+ }+}diff --git a/runtime/crates/canvas2d/src/registry.rs b/runtime/crates/canvas2d/src/registry.rsnew file mode 100644index 0000000..c3bf2bd--- /dev/null+++ b/runtime/crates/canvas2d/src/registry.rs@@ -0,0 +1,166 @@+//! Per-page objects: bitmaps (2D canvases and decoded images share one id space), Path2D+//! objects, gradients and patterns. Main thread only; cleared on page reset.+use std::cell::{Cell, RefCell};+use std::collections::HashMap;+use std::rc::Rc;++use objc2_core_foundation::{CFData, CFRetained};+use objc2_core_graphics::{CGBitmapInfo, CGColorRenderingIntent, CGDataProvider, CGImage, CGImageAlphaInfo};++use crate::canvas::{Canvas, Gradient, Path, Pattern};+use crate::codec::srgb;++pub(crate) struct Surface {+ pub width: u32,+ pub height: u32,+ /// Some for 2D canvases (declared before `data`: the CG context draws into it)+ pub canvas: Option<Box<Canvas>>,+ /// immutable images: CGImage made on first use+ image: Option<CFRetained<CGImage>>,+ pub version: u64,+ /// premultiplied RGBA8, top-down, stride width*4+ pub data: Vec<u8>,+}++thread_local! {+ static NEXT_ID: Cell<u32> = const { Cell::new(1) };+ pub(crate) static SURFACES: RefCell<HashMap<u32, Surface>> = RefCell::new(HashMap::new());+ pub(crate) static PATHS: RefCell<HashMap<u32, Path>> = RefCell::new(HashMap::new());+ pub(crate) static GRADIENTS: RefCell<HashMap<u32, Rc<RefCell<Gradient>>>> = RefCell::new(HashMap::new());+ pub(crate) static PATTERNS: RefCell<HashMap<u32, Rc<Pattern>>> = RefCell::new(HashMap::new());+}++pub(crate) fn next_id() -> u32 {+ NEXT_ID.with(|n| {+ let v = n.get();+ n.set(if v == u32::MAX { 1 } else { v + 1 });+ v+ })+}++/// Largest canvas Chrome allows (area and side).+const MAX_SIDE: u32 = 32767;+const MAX_AREA: u64 = 268_435_456;++fn alloc_pixels(w: u32, h: u32) -> (u32, u32, Vec<u8>) {+ if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE || w as u64 * h as u64 > MAX_AREA {+ return (w, h, Vec::new());+ }+ let n = w as usize * h as usize * 4;+ let mut v = Vec::new();+ if v.try_reserve_exact(n).is_err() {+ return (w, h, Vec::new());+ }+ v.resize(n, 0);+ (w, h, v)+}++pub(crate) fn create_canvas(w: u32, h: u32) -> u32 {+ let id = next_id();+ let (w, h, mut data) = alloc_pixels(w, h);+ let ptr = if data.is_empty() { std::ptr::null_mut() } else { data.as_mut_ptr() };+ let canvas = Canvas::new(ptr, if data.is_empty() { 0 } else { w }, if data.is_empty() { 0 } else { h });+ SURFACES.with(|s| s.borrow_mut().insert(id, Surface { width: w, height: h, canvas: Some(Box::new(canvas)), image: None, version: 1, data }));+ id+}++/// Reallocate a canvas (pixels cleared, state reset — like setting canvas.width).+pub(crate) fn resize_canvas(id: u32, w: u32, h: u32) -> bool {+ SURFACES.with(|s| {+ let mut s = s.borrow_mut();+ let Some(surf) = s.get_mut(&id) else { return false };+ if surf.canvas.is_none() {+ return false;+ }+ surf.canvas = None;+ let (w, h, mut data) = alloc_pixels(w, h);+ let ptr = if data.is_empty() { std::ptr::null_mut() } else { data.as_mut_ptr() };+ surf.canvas = Some(Box::new(Canvas::new(ptr, if data.is_empty() { 0 } else { w }, if data.is_empty() { 0 } else { h })));+ surf.data = data;+ surf.width = w;+ surf.height = h;+ surf.version += 1;+ true+ })+}++pub(crate) fn insert_image(width: u32, height: u32, data: Vec<u8>) -> u32 {+ let id = next_id();+ SURFACES.with(|s| s.borrow_mut().insert(id, Surface { width, height, canvas: None, image: None, version: 1, data }));+ id+}++pub(crate) fn release(id: u32) {+ // Drop outside the borrow (dropping CG objects never re-enters, but keep it tidy).+ let a = SURFACES.with(|s| s.borrow_mut().remove(&id));+ let b = PATHS.with(|s| s.borrow_mut().remove(&id));+ let c = GRADIENTS.with(|s| s.borrow_mut().remove(&id));+ let d = PATTERNS.with(|s| s.borrow_mut().remove(&id));+ drop((a, b, c, d));+}++pub(crate) fn reset() {+ let a = SURFACES.with(|s| std::mem::take(&mut *s.borrow_mut()));+ let b = PATHS.with(|s| std::mem::take(&mut *s.borrow_mut()));+ let c = GRADIENTS.with(|s| std::mem::take(&mut *s.borrow_mut()));+ let d = PATTERNS.with(|s| std::mem::take(&mut *s.borrow_mut()));+ drop((a, b, c, d));+}++/// Run `f` on a canvas; bumps the bitmap version when pixels may have changed.+pub(crate) fn with_canvas<R>(id: u32, f: impl FnOnce(&mut Canvas, &mut Vec<u8>) -> R) -> Option<R> {+ SURFACES.with(|s| {+ let mut s = s.borrow_mut();+ let surf = s.get_mut(&id)?;+ let canvas = surf.canvas.as_mut()?;+ let r = f(canvas, &mut surf.data);+ if canvas.dirty {+ canvas.dirty = false;+ surf.version += 1;+ }+ Some(r)+ })+}++pub(crate) fn surface_size(id: u32) -> Option<(u32, u32)> {+ SURFACES.with(|s| s.borrow().get(&id).map(|s| (s.width, s.height)))+}++/// An immutable CGImage of a bitmap's current pixels (canvases are copied: the image must not+/// change when the canvas is drawn to later).+pub(crate) fn snapshot(id: u32) -> Option<(CFRetained<CGImage>, u32, u32)> {+ SURFACES.with(|s| {+ let mut s = s.borrow_mut();+ let surf = s.get_mut(&id)?;+ if surf.data.is_empty() {+ return None;+ }+ if surf.canvas.is_none() {+ if surf.image.is_none() {+ surf.image = image_from_premul(surf.width, surf.height, &surf.data);+ }+ return surf.image.clone().map(|i| (i, surf.width, surf.height));+ }+ image_from_premul(surf.width, surf.height, &surf.data).map(|i| (i, surf.width, surf.height))+ })+}++pub(crate) fn image_from_premul(w: u32, h: u32, data: &[u8]) -> Option<CFRetained<CGImage>> {+ let cf = CFData::from_bytes(data);+ let provider = CGDataProvider::with_cf_data(Some(&cf))?;+ unsafe {+ CGImage::new(+ w as usize,+ h as usize,+ 8,+ 32,+ w as usize * 4,+ Some(&srgb()),+ CGBitmapInfo(CGImageAlphaInfo::PremultipliedLast.0),+ Some(&provider),+ std::ptr::null(),+ true,+ CGColorRenderingIntent::RenderingIntentDefault,+ )+ }+}diff --git a/runtime/crates/canvas2d/src/text.rs b/runtime/crates/canvas2d/src/text.rsnew file mode 100644index 0000000..d34daf2--- /dev/null+++ b/runtime/crates/canvas2d/src/text.rs@@ -0,0 +1,440 @@+//! Canvas text: layout with CoreText (fonts and fallback from [`crate::fonts`]), glyph placement+//! that reproduces Skia's (subpixel x positions quantized to ¼ px, baselines snapped to whole+//! pixels for axis-aligned transforms), Chrome's baselines and `measureText` metrics.+use std::ptr::NonNull;+use std::rc::Rc;++use objc2_core_foundation::{CFArray, CFAttributedString, CFData, CFDictionary, CFMutableAttributedString, CFNumber, CFRange, CFRetained, CFString, CFType, CGAffineTransform, CGPoint, CGRect, CGSize};+use objc2_core_graphics::{+ CGBitmapContextCreate, CGBitmapInfo, CGColorRenderingIntent, CGColorSpace, CGContext, CGDataProvider, CGImage, CGImageAlphaInfo, CGImageByteOrderInfo, CGLineJoin, CGMutablePath, CGPath,+ CGTextDrawingMode,+};+use objc2_core_text::{kCTFontAttributeName, kCTKernAttributeName, CTFont, CTFontOrientation, CTLine, CTRun};++use crate::canvas::{apply, apply_line_state, concat, fill_clip_with, invert, Paint, State, IDENTITY};+use crate::fonts::{self, Font};++pub(crate) struct GlyphRun {+ pub ct: CFRetained<CTFont>,+ pub font: Rc<Font>,+ pub glyphs: Vec<u16>,+ /// glyph origins in text space (y down, origin = pen start on the baseline)+ pub pos: Vec<(f64, f64)>,+}++pub(crate) struct Layout {+ pub runs: Vec<GlyphRun>,+ pub width: f64,+}++/// Lay out `text` on one line (canvas text never wraps; ASCII whitespace becomes spaces).+pub(crate) fn layout(font: &Rc<Font>, text: &[u16], letter_spacing: f64, word_spacing: f64, kerning: bool) -> Layout {+ let text: Vec<u16> = text.iter().map(|&c| if matches!(c, 0x09 | 0x0A | 0x0C | 0x0D) { 0x20 } else { c }).collect();+ if text.is_empty() {+ return Layout { runs: Vec::new(), width: 0.0 };+ }+ let font_runs = font.runs(&text);+ let s = fonts::cfstring_utf16(&text);+ let Some(attr) = CFMutableAttributedString::new(None, 0) else { return Layout { runs: Vec::new(), width: 0.0 } };+ unsafe { CFMutableAttributedString::replace_string(Some(&attr), CFRange { location: 0, length: 0 }, Some(&s)) };+ for r in &font_runs {+ let range = CFRange { location: r.start as isize, length: (r.end - r.start) as isize };+ unsafe { CFMutableAttributedString::set_attribute(Some(&attr), range, Some(kCTFontAttributeName), Some(&r.font.plain as &CFType)) };+ }+ if !kerning {+ let zero = CFNumber::new_f64(0.0);+ unsafe { CFMutableAttributedString::set_attribute(Some(&attr), CFRange { location: 0, length: text.len() as isize }, Some(kCTKernAttributeName), Some(&*zero as &CFType)) };+ }+ let attr_ref: &CFAttributedString = &attr;+ let line = unsafe { CTLine::with_attributed_string(attr_ref) };+ let mut width = unsafe { line.typographic_bounds(std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut()) };++ // Letter/word spacing: extra advance after each grapheme / space, accumulated per UTF-16 index.+ let spacing = letter_spacing != 0.0 || word_spacing != 0.0;+ let mut extra_at = Vec::new();+ if spacing {+ extra_at = vec![0.0; text.len() + 1];+ let mut acc = 0.0;+ let mut i = 0;+ while i < text.len() {+ let end = fonts::grapheme_end(&text, i);+ for e in extra_at.iter_mut().take(end).skip(i) {+ *e = acc;+ }+ acc += letter_spacing;+ if text[i] == 0x20 || text[i] == 0xA0 {+ acc += word_spacing;+ }+ i = end;+ }+ extra_at[text.len()] = acc;+ width += acc;+ }++ let runs_arr = unsafe { line.glyph_runs() };+ let runs_arr: CFRetained<CFArray<CTRun>> = unsafe { CFRetained::cast_unchecked(runs_arr) };+ let mut runs = Vec::new();+ for run in runs_arr.iter() {+ let n = unsafe { run.glyph_count() } as usize;+ if n == 0 {+ continue;+ }+ let mut glyphs = vec![0u16; n];+ let mut pts = vec![CGPoint { x: 0.0, y: 0.0 }; n];+ let mut idx = vec![0isize; n];+ let all = CFRange { location: 0, length: 0 };+ unsafe {+ run.glyphs(all, NonNull::new_unchecked(glyphs.as_mut_ptr()));+ run.positions(all, NonNull::new_unchecked(pts.as_mut_ptr()));+ run.string_indices(all, NonNull::new_unchecked(idx.as_mut_ptr()));+ }+ let attrs = unsafe { run.attributes() };+ let attrs: CFRetained<CFDictionary<CFString, CFType>> = unsafe { CFRetained::cast_unchecked(attrs) };+ let ct = attrs.get(unsafe { kCTFontAttributeName }).and_then(|v| v.downcast::<CTFont>().ok());+ let first = idx[0].max(0) as usize;+ let ours = font_runs.iter().find(|r| first >= r.start && first < r.end).map(|r| r.font.clone()).unwrap_or_else(|| font.clone());+ let ct = ct.unwrap_or_else(|| ours.plain.clone());+ // If CoreText substituted a face we did not pick, draw with it but without our synthesis.+ let same = unsafe { ct.post_script_name() }.to_string() == unsafe { ours.plain.post_script_name() }.to_string();+ let pos = pts+ .iter()+ .zip(&idx)+ .map(|(p, &i)| {+ let e = if spacing { extra_at[(i.max(0) as usize).min(text.len())] } else { 0.0 };+ (p.x + e, -p.y)+ })+ .collect();+ let font_for_run = if same { ours } else { fonts::resolve(&fonts::FontQuery { families: &[unsafe { ct.family_name() }.to_string()], weight: 400, italic: false, size: font.size }) };+ runs.push(GlyphRun { ct, font: font_for_run, glyphs, pos });+ }+ Layout { runs, width }+}++/// Offset from the `y` passed to fillText to the alphabetic baseline (Blink's GetFontBaseline).+pub(crate) fn baseline_offset(font: &Font, baseline: u8) -> f64 {+ let (em_a, em_d) = font.em_ascent_descent();+ let m = font.line_metrics();+ match baseline {+ 1 => em_a,+ 2 => m.ascent * 0.8,+ 3 => (em_a - em_d) / 2.0,+ 4 => -m.descent,+ 5 => -em_d,+ _ => 0.0,+ }+}++/// Union of glyph ink rects in text space (y down): (left, top, right, bottom).+pub(crate) fn ink_bounds(layout: &Layout) -> Option<(f64, f64, f64, f64)> {+ let mut b: Option<(f64, f64, f64, f64)> = None;+ for run in &layout.runs {+ let mut rects = vec![CGRect::default(); run.glyphs.len()];+ unsafe { run.ct.bounding_rects_for_glyphs(CTFontOrientation::Horizontal, NonNull::new_unchecked(run.glyphs.as_ptr() as *mut u16), rects.as_mut_ptr(), run.glyphs.len() as isize) };+ for (r, &(x, y)) in rects.iter().zip(&run.pos) {+ if r.size.width <= 0.0 || r.size.height <= 0.0 {+ continue;+ }+ let mut l = x + r.origin.x;+ let t = y - (r.origin.y + r.size.height);+ let mut rr = x + r.origin.x + r.size.width;+ let bt = y - r.origin.y;+ if run.font.synthetic_italic {+ // skew moves the top right / bottom left+ l += -(r.origin.y.min(0.0)) * -0.25;+ rr += (r.origin.y + r.size.height).max(0.0) * 0.25;+ }+ let grow = if run.font.synthetic_bold { fonts::fake_bold_stroke(run.font.size) / 2.0 } else { 0.0 };+ let g = (l - grow, t - grow, rr + grow, bt + grow);+ b = Some(match b {+ None => g,+ Some(o) => (o.0.min(g.0), o.1.min(g.1), o.2.max(g.2), o.3.max(g.3)),+ });+ }+ }+ b+}++fn skewed(ct: &CTFont) -> CFRetained<CTFont> {+ let m = CGAffineTransform { a: 1.0, b: 0.0, c: 0.25, d: 1.0, tx: 0.0, ty: 0.0 };+ let desc = unsafe { ct.font_descriptor() };+ unsafe { CTFont::with_font_descriptor(&desc, ct.size(), &m) }+}++/// Device position Skia would put a glyph at: x on a ¼-pixel grid; y on whole pixels when the+/// transform is axis-aligned (¼ grid otherwise). Text drawn as paths (> 256 device px) is exact.+fn quantize(x: f64, y: f64, axis_aligned: bool, as_paths: bool) -> (f64, f64) {+ if as_paths {+ return (x, y);+ }+ let qx = ((x + 0.125) * 4.0).floor() / 4.0;+ let qy = if axis_aligned { (y + 0.5).floor() } else { ((y + 0.125) * 4.0).floor() / 4.0 };+ (qx, qy)+}++/// Draw a laid-out line. `m` maps text space to device pixels; the context CTM on entry is the+/// device (canvas pixel) space.+pub(crate) fn draw(cg: &CGContext, s: &State, layout: &Layout, m: &CGAffineTransform, paint: &Paint, stroke: bool) {+ // Chrome (Skia on macOS) renders ordinary glyphs as CoreGraphics coverage masks; fake-bold,+ // stroked and very large text go through outlines, color glyphs through bitmaps.+ let scale = (m.a * m.d - m.b * m.c).abs().sqrt();+ let (masked, direct): (Vec<&GlyphRun>, Vec<&GlyphRun>) =+ layout.runs.iter().partition(|r| !stroke && !r.font.color && !r.font.synthetic_bold && r.font.size * scale <= 256.0);+ if !masked.is_empty() {+ draw_masked(cg, s, &masked, m, paint);+ }+ if !direct.is_empty() {+ let rest = Layout { runs: direct.into_iter().map(|r| GlyphRun { ct: r.ct.clone(), font: r.font.clone(), glyphs: r.glyphs.clone(), pos: r.pos.clone() }).collect(), width: layout.width };+ draw_direct(cg, s, &rest, m, paint, stroke);+ }+}++/// Device position of each glyph origin (quantized like Skia).+fn device_positions(run: &GlyphRun, m: &CGAffineTransform) -> Vec<(f64, f64)> {+ let axis_aligned = m.b == 0.0 && m.c == 0.0;+ let as_paths = run.font.size * (m.a * m.d - m.b * m.c).abs().sqrt() > 256.0;+ run.pos+ .iter()+ .map(|&(x, y)| {+ let (dx, dy) = apply(m, x, y);+ quantize(dx, dy, axis_aligned, as_paths)+ })+ .collect()+}++/// Skia's glyph masks: each glyph drawn black on white by CoreGraphics into an opaque RGB bitmap+/// with font smoothing, luminance → coverage; the coverage then masks the paint.+fn draw_masked(cg: &CGContext, s: &State, runs: &[&GlyphRun], m: &CGAffineTransform, paint: &Paint) {+ let lin = CGAffineTransform { tx: 0.0, ty: 0.0, ..*m };+ let Some(lin_inv) = invert(&lin) else { return };+ let flip = CGAffineTransform { a: 1.0, b: 0.0, c: 0.0, d: -1.0, tx: 0.0, ty: 0.0 };+ let user = concat(&flip, &lin);+ // Device bounds of all glyphs (+ a margin for smoothing dilation).+ let mut bx0 = f64::INFINITY;+ let mut by0 = f64::INFINITY;+ let mut bx1 = f64::NEG_INFINITY;+ let mut by1 = f64::NEG_INFINITY;+ let mut placed = Vec::with_capacity(runs.len());+ for run in runs {+ let dev = device_positions(run, m);+ let ct = if run.font.synthetic_italic { skewed(&run.ct) } else { run.ct.clone() };+ let mut rects = vec![CGRect::default(); run.glyphs.len()];+ unsafe { ct.bounding_rects_for_glyphs(CTFontOrientation::Horizontal, NonNull::new_unchecked(run.glyphs.as_ptr() as *mut u16), rects.as_mut_ptr(), run.glyphs.len() as isize) };+ for (r, &(qx, qy)) in rects.iter().zip(&dev) {+ if r.size.width <= 0.0 || r.size.height <= 0.0 {+ continue;+ }+ for (cx, cy) in [(r.origin.x, r.origin.y), (r.origin.x + r.size.width, r.origin.y), (r.origin.x, r.origin.y + r.size.height), (r.origin.x + r.size.width, r.origin.y + r.size.height)] {+ // glyph space is y-up: S flips it into text space, `lin` maps to device+ let (ex, ey) = apply(&lin, cx, -cy);+ bx0 = bx0.min(qx + ex);+ by0 = by0.min(qy + ey);+ bx1 = bx1.max(qx + ex);+ by1 = by1.max(qy + ey);+ }+ }+ placed.push((ct, dev));+ }+ if !bx0.is_finite() {+ return;+ }+ let clip = CGContext::clip_bounding_box(Some(cg));+ let x0 = (bx0 - 2.0).floor().max(clip.origin.x.floor());+ let y0 = (by0 - 2.0).floor().max(clip.origin.y.floor());+ let x1 = (bx1 + 2.0).ceil().min((clip.origin.x + clip.size.width).ceil());+ let y1 = (by1 + 2.0).ceil().min((clip.origin.y + clip.size.height).ceil());+ if x1 <= x0 || y1 <= y0 {+ return;+ }+ let (w, h) = ((x1 - x0) as usize, (y1 - y0) as usize);+ if w * h > 64 << 20 {+ return;+ }+ let mut buf = vec![0xFFu8; w * h * 4];+ let Some(rgb) = CGColorSpace::new_device_rgb() else { return };+ let info = CGImageAlphaInfo::NoneSkipFirst.0 | CGImageByteOrderInfo::Order32Little.0;+ let Some(off) = (unsafe { CGBitmapContextCreate(buf.as_mut_ptr().cast(), w, h, 8, w * 4, Some(&rgb), info) }) else { return };+ let o = Some(&*off);+ CGContext::translate_ctm(o, -x0, y1);+ CGContext::scale_ctm(o, 1.0, -1.0);+ CGContext::concat_ctm(o, user);+ CGContext::set_text_matrix(o, IDENTITY);+ CGContext::set_should_antialias(o, true);+ CGContext::set_allows_font_smoothing(o, true);+ CGContext::set_should_smooth_fonts(o, true);+ CGContext::set_allows_font_subpixel_positioning(o, true);+ CGContext::set_should_subpixel_position_fonts(o, true);+ CGContext::set_allows_font_subpixel_quantization(o, false);+ CGContext::set_should_subpixel_quantize_fonts(o, false);+ CGContext::set_text_drawing_mode(o, CGTextDrawingMode::Fill);+ CGContext::set_gray_fill_color(o, 0.0, 1.0);+ let to_user = |dx: f64, dy: f64| {+ let (u, v) = apply(&lin_inv, dx, dy);+ CGPoint { x: u, y: -v }+ };+ for (run, (ct, dev)) in runs.iter().zip(&placed) {+ let pts: Vec<CGPoint> = dev.iter().map(|&(qx, qy)| to_user(qx, qy)).collect();+ unsafe { ct.draw_glyphs(NonNull::new_unchecked(run.glyphs.as_ptr() as *mut u16), NonNull::new_unchecked(pts.as_ptr() as *mut CGPoint), run.glyphs.len(), &off) };+ }+ drop(off);+ // BGRX (little-endian XRGB) → coverage, Skia's luminance weights+ let mut mask = vec![0u8; w * h];+ for (i, p) in buf.chunks_exact(4).enumerate() {+ let (b, g, r) = (255 - p[0] as u32, 255 - p[1] as u32, 255 - p[2] as u32);+ mask[i] = ((r * 54 + g * 183 + b * 19) >> 8) as u8;+ }+ let data = CFData::from_bytes(&mask);+ let Some(provider) = CGDataProvider::with_cf_data(Some(&data)) else { return };+ let Some(gray) = CGColorSpace::new_device_gray() else { return };+ let Some(img) = (unsafe { CGImage::new(w, h, 8, 8, w, Some(&gray), CGBitmapInfo(0), Some(&provider), std::ptr::null(), false, CGColorRenderingIntent::RenderingIntentDefault) }) else { return };+ CGContext::save_g_state(Some(cg));+ // the mask image is y-up: flip around its rect, clip, flip back+ CGContext::translate_ctm(Some(cg), 0.0, y1);+ CGContext::scale_ctm(Some(cg), 1.0, -1.0);+ CGContext::clip_to_mask(Some(cg), CGRect { origin: CGPoint { x: x0, y: 0.0 }, size: CGSize { width: w as f64, height: h as f64 } }, Some(&img));+ CGContext::scale_ctm(Some(cg), 1.0, -1.0);+ CGContext::translate_ctm(Some(cg), 0.0, -y1);+ match paint {+ Paint::Color(c, _) => {+ CGContext::set_fill_color_with_color(Some(cg), Some(c));+ CGContext::fill_rect(Some(cg), CGRect { origin: CGPoint { x: x0, y: y0 }, size: CGSize { width: w as f64, height: h as f64 } });+ }+ _ => fill_clip_with(cg, paint, &s.ctm),+ }+ CGContext::restore_g_state(Some(cg));+}++fn draw_direct(cg: &CGContext, s: &State, layout: &Layout, m: &CGAffineTransform, paint: &Paint, stroke: bool) {+ let lin = CGAffineTransform { tx: 0.0, ty: 0.0, ..*m };+ let Some(lin_inv) = invert(&lin) else { return };+ let axis_aligned = m.b == 0.0 && m.c == 0.0;+ let device_size = |size: f64| size * (m.a * m.d - m.b * m.c).abs().sqrt();+ let flip = CGAffineTransform { a: 1.0, b: 0.0, c: 0.0, d: -1.0, tx: 0.0, ty: 0.0 };+ // CG user space for glyphs: y-up text space mapped by the linear part of `m`.+ let user = concat(&flip, &lin);+ let to_user = |dx: f64, dy: f64| {+ let (u, v) = apply(&lin_inv, dx, dy);+ CGPoint { x: u, y: -v }+ };++ if let Paint::Color(color, _) = paint {+ CGContext::save_g_state(Some(cg));+ CGContext::concat_ctm(Some(cg), user);+ CGContext::set_text_matrix(Some(cg), IDENTITY);+ CGContext::set_should_antialias(Some(cg), true);+ CGContext::set_allows_font_smoothing(Some(cg), true);+ CGContext::set_should_smooth_fonts(Some(cg), false); // outlines and bitmaps: Skia draws these unsmoothed+ CGContext::set_allows_font_subpixel_positioning(Some(cg), true);+ CGContext::set_should_subpixel_position_fonts(Some(cg), true);+ CGContext::set_allows_font_subpixel_quantization(Some(cg), false);+ CGContext::set_should_subpixel_quantize_fonts(Some(cg), false);+ CGContext::set_fill_color_with_color(Some(cg), Some(color));+ CGContext::set_stroke_color_with_color(Some(cg), Some(color));+ for run in &layout.runs {+ let as_paths = device_size(run.font.size) > 256.0;+ let positions: Vec<CGPoint> = run+ .pos+ .iter()+ .map(|&(x, y)| {+ let (dx, dy) = apply(m, x, y);+ let (qx, qy) = quantize(dx, dy, axis_aligned, as_paths);+ to_user(qx, qy)+ })+ .collect();+ let ct = if run.font.synthetic_italic { skewed(&run.ct) } else { run.ct.clone() };+ if stroke {+ apply_line_state(cg, s);+ CGContext::set_text_drawing_mode(Some(cg), CGTextDrawingMode::Stroke);+ } else if run.font.synthetic_bold {+ CGContext::set_line_width(Some(cg), fonts::fake_bold_stroke(run.font.size));+ CGContext::set_line_join(Some(cg), CGLineJoin::Miter);+ CGContext::set_miter_limit(Some(cg), 4.0);+ CGContext::set_text_drawing_mode(Some(cg), CGTextDrawingMode::FillStroke);+ } else {+ CGContext::set_text_drawing_mode(Some(cg), CGTextDrawingMode::Fill);+ }+ unsafe { ct.draw_glyphs(NonNull::new_unchecked(run.glyphs.as_ptr() as *mut u16), NonNull::new_unchecked(positions.as_ptr() as *mut CGPoint), run.glyphs.len(), cg) };+ }+ CGContext::restore_g_state(Some(cg));+ return;+ }++ // Gradient / pattern: build the glyph outlines (device space) and paint through them.+ let outline = CGMutablePath::new();+ let mut color_runs = Vec::new();+ for run in &layout.runs {+ if run.font.color {+ color_runs.push(run);+ continue;+ }+ let ct = if run.font.synthetic_italic { skewed(&run.ct) } else { run.ct.clone() };+ for (g, &(x, y)) in run.glyphs.iter().zip(&run.pos) {+ let Some(gp) = (unsafe { ct.path_for_glyph(*g, std::ptr::null()) }) else { continue };+ // glyph (y-up) → text space at (x, y) → device+ let place = concat(&CGAffineTransform { a: 1.0, b: 0.0, c: 0.0, d: -1.0, tx: x, ty: y }, m);+ unsafe { CGMutablePath::add_path(Some(&outline), &place, Some(&gp)) };+ if run.font.synthetic_bold && !stroke {+ let w = fonts::fake_bold_stroke(run.font.size);+ if let Some(sp) = unsafe { CGPath::new_copy_by_stroking_path(Some(&gp), std::ptr::null(), w, objc2_core_graphics::CGLineCap::Butt, CGLineJoin::Miter, 4.0) } {+ unsafe { CGMutablePath::add_path(Some(&outline), &place, Some(&sp)) };+ }+ }+ }+ }+ CGContext::save_g_state(Some(cg));+ if stroke {+ if let Some(inv) = invert(&s.ctm) {+ let user_path = unsafe { CGPath::new_copy_by_transforming_path(Some(&outline), &inv) };+ CGContext::concat_ctm(Some(cg), s.ctm);+ CGContext::add_path(Some(cg), user_path.as_deref());+ apply_line_state(cg, s);+ CGContext::replace_path_with_stroked_path(Some(cg));+ CGContext::clip(Some(cg));+ CGContext::concat_ctm(Some(cg), inv);+ fill_clip_with(cg, paint, &s.ctm);+ }+ } else if !CGPath::is_empty(Some(&outline)) {+ CGContext::add_path(Some(cg), Some(&outline));+ CGContext::clip(Some(cg));+ fill_clip_with(cg, paint, &s.ctm);+ }+ CGContext::restore_g_state(Some(cg));+ if !color_runs.is_empty() {+ let opaque = Paint::color(0.0, 0.0, 0.0, 1.0);+ for run in color_runs {+ let one = Layout { runs: vec![GlyphRun { ct: run.ct.clone(), font: run.font.clone(), glyphs: run.glyphs.clone(), pos: run.pos.clone() }], width: 0.0 };+ draw_direct(cg, s, &one, m, &opaque, false);+ }+ }+}++/// `measureText` results, in Chrome's order: width, actualBoundingBoxLeft, actualBoundingBoxRight,+/// fontBoundingBoxAscent, fontBoundingBoxDescent, actualBoundingBoxAscent,+/// actualBoundingBoxDescent, emHeightAscent, emHeightDescent, hangingBaseline,+/// alphabeticBaseline, ideographicBaseline.+pub(crate) fn measure(font: &Rc<Font>, s: &State, text: &[u16]) -> [f64; 12] {+ let layout = layout(font, text, s.letter_spacing, s.word_spacing, s.kerning);+ let width = layout.width;+ let m = font.line_metrics();+ let (em_a, em_d) = font.em_ascent_descent();+ let base = baseline_offset(font, s.baseline);+ let dx = match (s.align, s.rtl) {+ (4, _) => -width / 2.0,+ (3, _) | (1, false) | (0, true) => -width,+ _ => 0.0,+ };+ let (l, t, r, b) = ink_bounds(&layout).unwrap_or((0.0, 0.0, 0.0, 0.0));+ [+ width,+ -(l + dx),+ r + dx,+ m.ascent - base,+ m.descent + base,+ -t - base,+ b + base,+ em_a - base,+ em_d + base,+ m.ascent * 0.8 - base,+ -base,+ -m.descent - base,+ ]+}diff --git a/runtime/crates/canvas2d/src/textblock.rs b/runtime/crates/canvas2d/src/textblock.rsnew file mode 100644index 0000000..de1df2a--- /dev/null+++ b/runtime/crates/canvas2d/src/textblock.rs@@ -0,0 +1,171 @@+//! Blocks of text for a native UI text provider: measure a line, find soft breaks, paint lines.+//!+//! The same font resolution, per-character fallback and colour-emoji advances as `fillText`+//! (`text::layout`), so a UI drawn through this matches the canvas and Chrome's text metrics.++use std::rc::Rc;++use objc2_core_foundation::{CFAttributedString, CFDictionary, CFIndex, CFString, CFType, CGAffineTransform};+use objc2_core_text::{kCTFontAttributeName, CTTypesetter};++use crate::canvas::{Canvas, Paint, Use2};+use crate::fonts::{self, Font, ParsedFont};+use crate::text;++/// A face request: CSS families, weight (100–900), italic, size in px.+#[derive(Clone, Debug, PartialEq)]+pub struct TextFont {+ pub families: Vec<String>,+ pub weight: u16,+ pub italic: bool,+ pub size: f64,+}++/// A resolved face for text blocks.+pub struct BlockFont {+ parsed: Rc<ParsedFont>,+ font: Rc<Font>,+}++impl BlockFont {+ pub fn new(spec: &TextFont) -> BlockFont {+ let parsed = Rc::new(ParsedFont {+ families: spec.families.clone(),+ weight: spec.weight,+ italic: spec.italic,+ size: spec.size,+ line_height: None,+ small_caps: false,+ stretch: None,+ oblique: false,+ });+ let font = fonts::resolve_parsed(&parsed);+ BlockFont { parsed, font }+ }+ /// CSS `line-height: normal` for this face, in px.+ pub fn normal_line_height(&self) -> f64 {+ self.font.line_metrics().line_spacing()+ }+ /// The advance width of one line (no `'\n'`), in px.+ pub fn measure(&self, line: &str) -> f64 {+ self.measure_spaced(line, 0.0)+ }+ /// The advance width of one line with `tracking` px after each character (CSS letter-spacing).+ pub fn measure_spaced(&self, line: &str, tracking: f64) -> f64 {+ let utf16: Vec<u16> = line.encode_utf16().collect();+ text::layout(&self.font, &utf16, tracking, 0.0, true).width+ }+ /// Soft-break positions (UTF-16 offsets, ascending) that keep each row of `line` within+ /// `max_width` px: Unicode line breaking as CoreText applies it, trailing spaces hanging.+ /// A row too narrow for one grapheme still takes one.+ pub fn wrap(&self, line: &str, max_width: f64) -> Vec<u32> {+ let utf16: Vec<u16> = line.encode_utf16().collect();+ let mut breaks = Vec::new();+ if utf16.is_empty() || !(max_width > 0.0) || self.measure(line) <= max_width {+ return breaks;+ }+ let string = CFString::from_str(line);+ let key: &CFString = unsafe { kCTFontAttributeName };+ let value: &CFType = self.font.ct.as_ref();+ let attributes = CFDictionary::from_slices(&[key], &[value]);+ let Some(attributed) = (unsafe { CFAttributedString::new(None, Some(&string), Some(attributes.as_opaque())) }) else {+ return breaks;+ };+ let typesetter = unsafe { CTTypesetter::with_attributed_string(&attributed) };+ let mut start = 0usize;+ while start < utf16.len() {+ let mut count = unsafe { typesetter.suggest_line_break(start as CFIndex, max_width) } as usize;+ if count == 0 {+ count = fonts::grapheme_end(&utf16, start) - start;+ }+ // CoreText measures with its own advances; keep the row within our measure.+ while count > 1 {+ let row = String::from_utf16_lossy(&utf16[start..start + count]);+ if self.measure(row.trim_end()) <= max_width + 0.5 {+ break;+ }+ let shorter = unsafe { typesetter.suggest_line_break(start as CFIndex, max_width - 1.0) } as usize;+ count = if shorter > 0 && shorter < count { shorter } else { count - 1 };+ }+ let end = start + count.max(1);+ if end >= utf16.len() {+ break;+ }+ breaks.push(end as u32);+ start = end;+ }+ breaks+ }+}++/// Pixels of a painted block.+pub struct PaintedBlock {+ pub width: u32,+ pub height: u32,+ /// straight-alpha RGBA8, sRGB+ pub rgba: Vec<u8>,+ /// logical offset of pixel (0, 0) from the block's origin+ pub offset: [f32; 2],+}++/// Paint `text` (lines separated by `'\n'`) in `color` (straight RGBA): each line in a row of+/// `line_height` px with CSS half-leading, aligned within `box_width` (0 left, 1 center,+/// 2 right), `tracking` px after each character, at `scale` device px per px.+#[allow(clippy::too_many_arguments)]+pub fn paint(font: &BlockFont, text: &str, color: [u8; 4], align: u8, box_width: f32, line_height: f32, tracking: f32, scale: f32) -> Option<PaintedBlock> {+ let lines: Vec<&str> = text.split('\n').collect();+ let widths: Vec<f64> = lines.iter().map(|line| font.measure_spaced(line, tracking as f64)).collect();+ if widths.iter().all(|w| *w <= 0.0) {+ return None;+ }+ let metrics = font.font.line_metrics();+ let line_h = line_height as f64;+ // ink may leave the line box: emoji and descenders below, accents above, italics sideways+ let pad_x = (font.parsed.size * 0.25).ceil() + 1.0;+ let overflow = ((metrics.ascent + metrics.descent - line_h) / 2.0).max(0.0);+ let pad_y = (overflow + font.parsed.size * 0.15).ceil() + 1.0;+ let content_w = widths.iter().cloned().fold(box_width as f64, f64::max);+ let logical_w = content_w + 2.0 * pad_x;+ let logical_h = line_h * lines.len() as f64 + 2.0 * pad_y;+ let scale = scale as f64;+ let width = (logical_w * scale).ceil() as u32;+ let height = (logical_h * scale).ceil() as u32;+ if width == 0 || height == 0 || width > 16384 || height > 16384 {+ return None;+ }+ let mut pixels = vec![0u8; width as usize * height as usize * 4];+ {+ let mut canvas = Canvas::new(pixels.as_mut_ptr(), width, height);+ canvas.state.ctm = CGAffineTransform { a: scale, b: 0.0, c: 0.0, d: scale, tx: 0.0, ty: 0.0 };+ canvas.state.font = font.parsed.clone();+ canvas.state.resolved = Some(font.font.clone());+ canvas.state.fill = Paint::color(color[0] as f64 / 255.0, color[1] as f64 / 255.0, color[2] as f64 / 255.0, color[3] as f64 / 255.0);+ canvas.state.align = 2; // left: x is the line's start+ canvas.state.letter_spacing = tracking as f64;+ canvas.state.baseline = 0; // alphabetic+ for (row, (line, line_w)) in lines.iter().zip(&widths).enumerate() {+ if line.is_empty() {+ continue;+ }+ let dx = match align {+ 1 => (box_width as f64 - line_w) / 2.0,+ 2 => box_width as f64 - line_w,+ _ => 0.0,+ };+ // CSS: the glyphs' ascent+descent centred in the line box (half-leading)+ let top = row as f64 * line_h + (line_h - (metrics.ascent + metrics.descent)) / 2.0;+ let utf16: Vec<u16> = line.encode_utf16().collect();+ canvas.draw_text(&utf16, pad_x + dx, pad_y + top + metrics.ascent, None, Use2::Fill);+ }+ }+ // premultiplied → straight alpha+ for px in pixels.chunks_exact_mut(4) {+ let a = px[3] as u32;+ if a != 0 && a != 255 {+ for c in &mut px[..3] {+ *c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8;+ }+ }+ }+ Some(PaintedBlock { width, height, rgba: pixels, offset: [-pad_x as f32, -pad_y as f32] })+}diff --git a/runtime/crates/jsc/Cargo.toml b/runtime/crates/jsc/Cargo.tomlnew file mode 100644index 0000000..abe5075--- /dev/null+++ b/runtime/crates/jsc/Cargo.toml@@ -0,0 +1,9 @@+[package]+name = "threert-jsc"+description = "JavaScriptCore bindings for ThreeRT runtime, shared with PocketJS's JavaScriptCore guest"+version.workspace = true+edition.workspace = true+license.workspace = true++[dependencies]+pocket-guest-jsc.workspace = truediff --git a/runtime/crates/jsc/examples/globals.rs b/runtime/crates/jsc/examples/globals.rsnew file mode 100644index 0000000..8bc30c1--- /dev/null+++ b/runtime/crates/jsc/examples/globals.rs@@ -0,0 +1,8 @@+fn main() {+ let cx = threert_jsc::Context::new("t");+ let c = cx.ctx();+ let names = ["console","queueMicrotask","structuredClone","URL","URLSearchParams","TextEncoder","TextDecoder","atob","btoa","setTimeout","Intl","WeakRef","FinalizationRegistry","crypto","AbortController","Event","EventTarget","fetch","WebAssembly","Atomics","SharedArrayBuffer","performance","globalThis","DOMException","Blob","ReadableStream","navigator"];+ for n in names { let v = c.eval(&format!("typeof {n}"), "t").unwrap(); print!("{n}:{} ", v.to_string(c)); }+ println!();+ println!("{}", c.eval(r#"(1234567.891).toLocaleString() + ' ' + new Intl.NumberFormat('zh-CN').format(1234567) + ' ' + [..."🏝️口袋"].length + ' ' + 'x'.at(-1) + ' ' + typeof Array.prototype.findLast + ' ' + typeof Promise.withResolvers + ' ' + typeof Object.groupBy + ' ' + typeof Set.prototype.union + ' ' + typeof Iterator"#, "t").unwrap().to_string(c));+}diff --git a/runtime/crates/jsc/src/lib.rs b/runtime/crates/jsc/src/lib.rsnew file mode 100644index 0000000..d23e7af--- /dev/null+++ b/runtime/crates/jsc/src/lib.rs@@ -0,0 +1,7 @@+//! JavaScriptCore for the desktop runtime: the C API and handle layer of PocketJS's JavaScriptCore+//! guest (`pocket-guest-jsc`), so every native binding (net, Canvas 2D, WebGPU) and the PocketJS+//! `ui` namespace share one realm and one value type.+//!+//! JavaScriptCore ships with macOS, so the engine costs nothing on disk; with the+//! `com.apple.security.cs.allow-jit` entitlement it runs with its full JIT tiers.+pub use pocket_guest_jsc::jsc::*;diff --git a/runtime/crates/net/Cargo.toml b/runtime/crates/net/Cargo.tomlnew file mode 100644index 0000000..29e1453--- /dev/null+++ b/runtime/crates/net/Cargo.toml@@ -0,0 +1,24 @@+[package]+name = "threert-net"+description = "fetch, WebSocket, system TLS, clipboard and audio for ThreeRT runtime"+version.workspace = true+edition.workspace = true+license.workspace = true++[dependencies]+jsc.workspace = true+rt.workspace = true+libc = "0.2"+httparse = "1.10"+# System TLS (Security.framework on macOS, OpenSSL on Linux) instead of bundling rustls + ring.+native-tls = "0.2"+tungstenite = { version = "0.30", default-features = false, features = ["handshake"] }++[target.'cfg(target_os = "macos")'.dependencies]+objc2 = "0.6"+objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSString"] }+objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSPasteboard"] }++[target.'cfg(not(target_os = "macos"))'.dependencies]+flate2 = "1"+brotli = { version = "7", default-features = false, features = ["std"] }diff --git a/runtime/crates/net/src/audio.rs b/runtime/crates/net/src/audio.rsnew file mode 100644index 0000000..e8435d0--- /dev/null+++ b/runtime/crates/net/src/audio.rs@@ -0,0 +1,989 @@+#![cfg_attr(not(target_os = "macos"), allow(dead_code))]+//! The Web Audio subset the page uses: oscillators and gains with AudioParam automation, mixed into+//! the default output device (AUHAL).+//!+//! Energy: the device runs only while something can sound. It starts on the first `start()`+//! (on a helper thread, so the main thread never waits for CoreAudio) and is torn down after 1 s+//! with no live oscillator, so an idle page has no audio thread. While the device is off, every+//! context's `currentTime` follows the monotonic clock instead, so time keeps moving as in Chromium.+//! While the device is starting the clock holds still: a sound scheduled at `currentTime` plays in+//! full once the first buffer renders instead of being cut by the start-up latency.+//!+//! Threads: the main thread queues commands (`submit`); the render callback applies them at the+//! start of each buffer with `try_lock`, so it never waits on the page. Graph state lives in+//! `MIXER`, which only the render callback touches while the device runs.++use std::collections::HashMap;+use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};+use std::sync::{Mutex, OnceLock};+use std::time::Instant;++// ---------------------------------------------------------------- AudioParam timeline++#[derive(Clone, Copy, Debug, PartialEq)]+pub enum Ev {+ Set { t: f64, v: f32 },+ Linear { t: f64, v: f32, t0: f64 },+ Exp { t: f64, v: f32, t0: f64 },+ Target { t: f64, v: f32, tau: f64 },+}++impl Ev {+ fn time(&self) -> f64 {+ match *self {+ Ev::Set { t, .. } | Ev::Linear { t, .. } | Ev::Exp { t, .. } | Ev::Target { t, .. } => t,+ }+ }+ /// Event types as the page encodes them: [type, time, value, tau, scheduledAt] per event.+ pub fn from_flat(f: &[f64]) -> Option<Ev> {+ let (ty, t, v, tau, t0) = (f[0] as u32, f[1], f[2] as f32, f[3], f[4]);+ Some(match ty {+ 0 => Ev::Set { t, v },+ 1 => Ev::Linear { t, v, t0 },+ 2 => Ev::Exp { t, v, t0 },+ 3 => Ev::Target { t, v, tau },+ _ => return None,+ })+ }+}++/// Value of an automation timeline at time `t` (Web Audio §1.6.3). `evs` is sorted by time.+pub fn param_value(evs: &[Ev], intrinsic: f32, t: f64) -> f32 {+ // the last event at or before t+ let i = evs.partition_point(|e| e.time() <= t);+ let (prev, next) = (i.checked_sub(1).map(|j| (j, evs[j])), evs.get(i));+ if let Some(&next) = next {+ if let Ev::Linear { t: t1, v: v1, t0: sched } | Ev::Exp { t: t1, v: v1, t0: sched } = next {+ // A ramp runs from the previous event (or, with none, from when it was scheduled).+ let (ta, va) = match prev {+ Some((j, e)) => (e.time(), end_value(&evs[..=j], intrinsic)),+ None => (sched.min(t1), intrinsic),+ };+ if t1 <= ta {+ return v1;+ }+ let x = ((t - ta) / (t1 - ta)).clamp(0.0, 1.0);+ return match next {+ Ev::Linear { .. } => va + (v1 - va) * x as f32,+ _ => {+ if va == 0.0 || va.signum() != v1.signum() {+ va+ } else {+ va * (v1 / va).powf(x as f32)+ }+ }+ };+ }+ }+ match prev {+ None => intrinsic,+ Some((j, e)) => match e {+ Ev::Set { v, .. } | Ev::Linear { v, .. } | Ev::Exp { v, .. } => v,+ Ev::Target { t: ts, v: target, tau } => {+ let start = param_value(&evs[..j], intrinsic, ts);+ if tau <= 0.0 {+ target+ } else {+ target + (start - target) * (-(t - ts) / tau).exp() as f32+ }+ }+ },+ }+}++/// The value an event leaves behind (for a ramp that follows it).+fn end_value(evs: &[Ev], intrinsic: f32) -> f32 {+ let last = evs[evs.len() - 1];+ match last {+ Ev::Set { v, .. } | Ev::Linear { v, .. } | Ev::Exp { v, .. } => v,+ // A ramp after setTarget starts from where the target curve began.+ Ev::Target { t, .. } => param_value(&evs[..evs.len() - 1], intrinsic, t),+ }+}++#[derive(Clone, Default)]+struct Param {+ events: Vec<Ev>,+ intrinsic: f32,+ /// nodes whose output is added to this param (a-rate modulation)+ inputs: Vec<u32>,+}++// ---------------------------------------------------------------- graph++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum Wave {+ Sine,+ Square,+ Sawtooth,+ Triangle,+}++enum Kind {+ Destination,+ Gain,+ Osc { wave: Wave, phase: f64, start: f64, stop: f64, ended: bool },+}++struct Node {+ ctx: u32,+ kind: Kind,+ inputs: Vec<u32>,+ params: [Param; 2],+ released: bool,+ want_ended: bool,+ out: Vec<f32>,+ stamp: u64,+}++impl Node {+ fn source_alive(&self) -> bool {+ matches!(self.kind, Kind::Osc { start, ended, .. } if !start.is_nan() && !ended)+ }+}++#[derive(Clone, Copy)]+struct CtxClock {+ /// device time at which this context's time is 0 (suspensions add to it)+ offset: f64,+ /// device time of a suspension in progress+ suspended_at: Option<f64>,+ closed: bool,+}++impl CtxClock {+ fn time(&self, dev: f64) -> f64 {+ (self.suspended_at.unwrap_or(dev) - self.offset).max(0.0)+ }+ fn running(&self) -> bool {+ self.suspended_at.is_none() && !self.closed+ }+}++enum Cmd {+ Ctx(u32, CtxClock),+ CloseCtx(u32),+ Node(u32, u32, u8),+ Connect(u32, u32, i32),+ Disconnect(u32, u32, i32),+ Param(u32, usize, f32, Vec<Ev>),+ Wave(u32, Wave),+ Start(u32, f64),+ Stop(u32, f64),+ WantEnded(u32),+ Release(u32),+ Reset,+}++struct Mixer {+ nodes: HashMap<u32, Node>,+ ctxs: HashMap<u32, CtxClock>,+ rate: f64,+ stamp: u64,+ order: Vec<u32>,+ mix: Vec<f32>,+ silent_frames: u64,+ ended: Vec<u32>,+ dests: Vec<u32>,+ stack: Vec<u32>,+}++impl Mixer {+ fn new(rate: f64) -> Self {+ Mixer {+ nodes: HashMap::new(),+ ctxs: HashMap::new(),+ rate,+ stamp: 0,+ order: Vec::new(),+ mix: Vec::new(),+ silent_frames: 0,+ ended: Vec::new(),+ dests: Vec::new(),+ stack: Vec::new(),+ }+ }++ fn apply(&mut self, cmd: Cmd) {+ match cmd {+ Cmd::Ctx(id, c) => {+ self.ctxs.insert(id, c);+ }+ Cmd::CloseCtx(id) => {+ if let Some(c) = self.ctxs.get_mut(&id) {+ c.closed = true;+ }+ self.nodes.retain(|_, n| n.ctx != id);+ self.ctxs.remove(&id);+ }+ Cmd::Node(id, ctx, kind) => {+ let (kind, defaults) = match kind {+ 0 => (Kind::Destination, [0.0, 0.0]),+ 1 => (Kind::Gain, [1.0, 0.0]),+ _ => (Kind::Osc { wave: Wave::Sine, phase: 0.0, start: f64::NAN, stop: f64::INFINITY, ended: false }, [440.0, 0.0]),+ };+ let params = defaults.map(|d| Param { intrinsic: d, ..Default::default() });+ self.nodes.insert(id, Node { ctx, kind, inputs: Vec::new(), params, released: false, want_ended: false, out: Vec::new(), stamp: 0 });+ }+ Cmd::Connect(from, to, param) => {+ if let Some(n) = self.nodes.get_mut(&to) {+ let list = if param < 0 { &mut n.inputs } else { &mut n.params[param as usize & 1].inputs };+ if !list.contains(&from) {+ list.push(from);+ }+ }+ }+ Cmd::Disconnect(from, to, param) => {+ for (id, n) in self.nodes.iter_mut() {+ if to != 0 && *id != to {+ continue;+ }+ if param < 0 || to == 0 {+ n.inputs.retain(|&x| x != from);+ }+ for (i, p) in n.params.iter_mut().enumerate() {+ if to == 0 || param == i as i32 {+ p.inputs.retain(|&x| x != from);+ }+ }+ }+ }+ Cmd::Param(id, i, intrinsic, events) => {+ if let Some(n) = self.nodes.get_mut(&id) {+ let p = &mut n.params[i & 1];+ p.intrinsic = intrinsic;+ p.events = events;+ }+ }+ Cmd::Wave(id, w) => {+ if let Some(Node { kind: Kind::Osc { wave, .. }, .. }) = self.nodes.get_mut(&id) {+ *wave = w;+ }+ }+ Cmd::Start(id, when) => {+ if let Some(Node { kind: Kind::Osc { start, .. }, .. }) = self.nodes.get_mut(&id) {+ *start = when;+ }+ }+ Cmd::Stop(id, when) => {+ if let Some(Node { kind: Kind::Osc { stop, .. }, .. }) = self.nodes.get_mut(&id) {+ *stop = when;+ }+ }+ Cmd::WantEnded(id) => {+ if let Some(n) = self.nodes.get_mut(&id) {+ n.want_ended = true;+ }+ }+ Cmd::Release(id) => {+ if let Some(n) = self.nodes.get_mut(&id) {+ n.released = true;+ }+ }+ Cmd::Reset => {+ self.nodes.clear();+ self.ctxs.clear();+ }+ }+ }++ /// Any oscillator that is playing or scheduled in a running context?+ fn active(&self) -> bool {+ self.nodes.values().any(|n| n.source_alive() && self.ctxs.get(&n.ctx).is_some_and(|c| c.running()))+ }++ /// Drop nodes the page released that can no longer sound.+ fn collect(&mut self) {+ loop {+ let dead: Vec<u32> = self+ .nodes+ .iter()+ .filter(|(_, n)| {+ n.released+ && match n.kind {+ Kind::Osc { start, ended, .. } => ended || start.is_nan(),+ Kind::Gain => n.inputs.is_empty() && n.params.iter().all(|p| p.inputs.is_empty()),+ Kind::Destination => false,+ }+ })+ .map(|(id, _)| *id)+ .collect();+ if dead.is_empty() {+ return;+ }+ for id in &dead {+ self.nodes.remove(id);+ }+ for n in self.nodes.values_mut() {+ n.inputs.retain(|x| !dead.contains(x));+ for p in n.params.iter_mut() {+ p.inputs.retain(|x| !dead.contains(x));+ }+ }+ }+ }++ fn visit(&mut self, id: u32, stack: &mut Vec<u32>) {+ let Some(n) = self.nodes.get_mut(&id) else { return };+ if n.stamp == self.stamp || stack.contains(&id) {+ return; // done, or a cycle (no DelayNode, so cycles are silent)+ }+ stack.push(id);+ let deps: Vec<u32> = n.inputs.iter().chain(n.params.iter().flat_map(|p| p.inputs.iter())).copied().collect();+ for d in deps {+ self.visit(d, stack);+ }+ stack.pop();+ if let Some(n) = self.nodes.get_mut(&id) {+ n.stamp = self.stamp;+ }+ self.order.push(id);+ }++ /// Render `frames` samples starting at device time `dev` into `self.mix` (mono).+ fn render(&mut self, dev: f64, frames: usize) {+ self.stamp += 1;+ self.order.clear();+ self.mix.clear();+ self.mix.resize(frames, 0.0);+ let mut dests = std::mem::take(&mut self.dests);+ dests.clear();+ dests.extend(+ self.nodes+ .iter()+ .filter(|(_, n)| matches!(n.kind, Kind::Destination) && self.ctxs.get(&n.ctx).is_some_and(|c| c.running()))+ .map(|(id, _)| *id),+ );+ let mut stack = std::mem::take(&mut self.stack);+ for d in &dests {+ self.visit(*d, &mut stack);+ }+ self.stack = stack;+ let dt = 1.0 / self.rate;+ let order = std::mem::take(&mut self.order);+ let mut ended_ids = std::mem::take(&mut self.ended);+ for &id in &order {+ let Some(node) = self.nodes.get(&id) else { continue };+ let Some(clock) = self.ctxs.get(&node.ctx).copied() else { continue };+ let t0 = clock.time(dev);+ let mut out = std::mem::take(&mut self.nodes.get_mut(&id).unwrap().out);+ out.clear();+ out.resize(frames, 0.0);+ let node = &self.nodes[&id];+ for inp in &node.inputs {+ if let Some(src) = self.nodes.get(inp) {+ if src.out.len() == frames {+ for (o, s) in out.iter_mut().zip(&src.out) {+ *o += s;+ }+ }+ }+ }+ let param_at = |p: &Param, k: usize, t: f64| -> f32 {+ let mut v = if p.events.is_empty() { p.intrinsic } else { param_value(&p.events, p.intrinsic, t) };+ for inp in &p.inputs {+ if let Some(src) = self.nodes.get(inp) {+ v += src.out.get(k).copied().unwrap_or(0.0);+ }+ }+ v+ };+ let mut new_kind = None;+ match &node.kind {+ Kind::Destination => {}+ Kind::Gain => {+ for (k, o) in out.iter_mut().enumerate() {+ *o *= param_at(&node.params[0], k, t0 + k as f64 * dt);+ }+ }+ &Kind::Osc { wave, mut phase, start, stop, ended } => {+ let mut ended_now = ended;+ if !start.is_nan() && !ended {+ for (k, o) in out.iter_mut().enumerate() {+ let t = t0 + k as f64 * dt;+ if t < start {+ continue;+ }+ if t >= stop {+ ended_now = true;+ break;+ }+ let f = param_at(&node.params[0], k, t) as f64 * (param_at(&node.params[1], k, t) as f64 / 1200.0).exp2();+ let inc = (f * dt).clamp(-0.5, 0.5);+ *o = osc_sample(wave, phase, inc.abs());+ phase += inc;+ phase -= phase.floor();+ }+ // a stop scheduled exactly at the end of this buffer+ if t0 + frames as f64 * dt >= stop {+ ended_now = true;+ }+ }+ new_kind = Some(Kind::Osc { wave, phase, start, stop, ended: ended_now });+ if ended_now && !ended && node.want_ended {+ ended_ids.push(id);+ }+ }+ }+ let n = self.nodes.get_mut(&id).unwrap();+ if let Some(k) = new_kind {+ n.kind = k;+ }+ n.out = out;+ }+ // Oscillators not reachable from a destination still advance and end on time.+ let unreached: Vec<u32> = self.nodes.iter().filter(|(_, n)| n.stamp != self.stamp && n.source_alive()).map(|(id, _)| *id).collect();+ for id in unreached {+ let n = self.nodes.get_mut(&id).unwrap();+ let Some(clock) = self.ctxs.get(&n.ctx) else { continue };+ if !clock.running() {+ continue;+ }+ let end = clock.time(dev) + frames as f64 * dt;+ if let Kind::Osc { stop, ended, .. } = &mut n.kind {+ if end >= *stop {+ *ended = true;+ if n.want_ended {+ ended_ids.push(id);+ }+ }+ }+ }+ for d in &dests {+ if let Some(n) = self.nodes.get(d) {+ for (m, s) in self.mix.iter_mut().zip(&n.out) {+ *m += s;+ }+ }+ }+ self.dests = dests;+ self.order = order;+ self.ended = ended_ids;+ self.collect();+ }+}++fn poly_blep(t: f64, dt: f64) -> f64 {+ if dt <= 0.0 {+ 0.0+ } else if t < dt {+ let x = t / dt;+ x + x - x * x - 1.0+ } else if t > 1.0 - dt {+ let x = (t - 1.0) / dt;+ x * x + x + x + 1.0+ } else {+ 0.0+ }+}++/// One sample of a unit waveform at `phase` (0..1). Phases match Chromium's tables: every shape+/// starts at 0 (square at +1) and rises. Square and sawtooth are band-limited with PolyBLEP.+fn osc_sample(wave: Wave, phase: f64, inc: f64) -> f32 {+ let v = match wave {+ Wave::Sine => (phase * std::f64::consts::TAU).sin(),+ Wave::Square => {+ let mut v = if phase < 0.5 { 1.0 } else { -1.0 };+ v += poly_blep(phase, inc);+ v -= poly_blep((phase + 0.5).fract(), inc);+ v+ }+ Wave::Sawtooth => {+ let p = (phase + 0.5).fract();+ 2.0 * p - 1.0 - poly_blep(p, inc)+ }+ Wave::Triangle => 1.0 - 4.0 * (((phase + 0.25).fract()) - 0.5).abs(),+ };+ v as f32+}++// ---------------------------------------------------------------- device clock++const STOPPED: u8 = 0;+const STARTING: u8 = 1;+const RUNNING: u8 = 2;+const STOPPING: u8 = 3;++static STATE: AtomicU8 = AtomicU8::new(STOPPED);+static FRAMES: AtomicU64 = AtomicU64::new(0);+/// `Clock::dev_base` as f64 bits, so the render callback reads it without a lock.+static DEV_BASE: AtomicU64 = AtomicU64::new(0);+static STOP_REQUESTED: AtomicBool = AtomicBool::new(false);+static RESTART: AtomicBool = AtomicBool::new(false);++struct Clock {+ idle_base: f64,+ idle_since: Instant,+ dev_base: f64,+}++static CLOCK: Mutex<Option<Clock>> = Mutex::new(None);+static CMDS: Mutex<Vec<Cmd>> = Mutex::new(Vec::new());+static MIXER: Mutex<Option<Mixer>> = Mutex::new(None);++/// Device time in seconds: rendered frames while the device runs, the monotonic clock otherwise.+fn device_time() -> f64 {+ let mut g = CLOCK.lock().unwrap();+ let c = g.get_or_insert_with(|| Clock { idle_base: 0.0, idle_since: Instant::now(), dev_base: 0.0 });+ match STATE.load(Ordering::SeqCst) {+ RUNNING | STOPPING => f64::from_bits(DEV_BASE.load(Ordering::SeqCst)) + FRAMES.load(Ordering::SeqCst) as f64 / sample_rate(),+ STARTING => c.idle_base,+ _ => c.idle_base + c.idle_since.elapsed().as_secs_f64(),+ }+}++pub fn sample_rate() -> f64 {+ static RATE: OnceLock<f64> = OnceLock::new();+ *RATE.get_or_init(|| device::default_rate().filter(|r| (8000.0..=384000.0).contains(r)).unwrap_or(48000.0))+}++// ---------------------------------------------------------------- page-facing API (main thread)++thread_local! {+ static CTXS: std::cell::RefCell<HashMap<u32, CtxClock>> = std::cell::RefCell::new(HashMap::new());+}++fn submit(cmd: Cmd) {+ CMDS.lock().unwrap().push(cmd);+ if STATE.load(Ordering::SeqCst) == STOPPED {+ // Nothing renders: apply now so the queue cannot grow while the device is off.+ if let Ok(mut m) = MIXER.try_lock() {+ let m = m.get_or_insert_with(|| Mixer::new(sample_rate()));+ for c in std::mem::take(&mut *CMDS.lock().unwrap()) {+ m.apply(c);+ }+ m.collect();+ }+ }+}++static NEXT_ID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);++/// Node and context ids are process-wide, so a late `ended` from a previous page never matches a+/// node of the next one.+fn next_id() -> u32 {+ NEXT_ID.fetch_add(1, Ordering::Relaxed)+}++/// A new context; its id is also the id of its destination node.+pub fn create_context() -> u32 {+ let id = next_id();+ let c = CtxClock { offset: device_time(), suspended_at: None, closed: false };+ CTXS.with(|m| m.borrow_mut().insert(id, c));+ submit(Cmd::Ctx(id, c));+ submit(Cmd::Node(id, id, 0)); // the destination shares the context's id+ id+}++pub fn context_time(id: u32) -> f64 {+ CTXS.with(|m| m.borrow().get(&id).map(|c| c.time(device_time()))).unwrap_or(0.0)+}++pub fn suspend(id: u32) {+ let dev = device_time();+ let c = CTXS.with(|m| {+ let mut m = m.borrow_mut();+ let c = m.get_mut(&id)?;+ if c.suspended_at.is_none() {+ c.suspended_at = Some(dev);+ }+ Some(*c)+ });+ if let Some(c) = c {+ submit(Cmd::Ctx(id, c));+ }+}++pub fn resume(id: u32) {+ let dev = device_time();+ let c = CTXS.with(|m| {+ let mut m = m.borrow_mut();+ let c = m.get_mut(&id)?;+ if let Some(at) = c.suspended_at.take() {+ c.offset += dev - at;+ }+ Some(*c)+ });+ if let Some(c) = c {+ submit(Cmd::Ctx(id, c));+ ensure_device();+ }+}++pub fn close_context(id: u32) {+ CTXS.with(|m| m.borrow_mut().remove(&id));+ submit(Cmd::CloseCtx(id));+}++/// `kind`: 1 gain, 2 oscillator.+pub fn create_node(ctx: u32, kind: u8) -> u32 {+ let id = next_id();+ submit(Cmd::Node(id, ctx, kind));+ id+}+pub fn connect(from: u32, to: u32, param: i32) {+ submit(Cmd::Connect(from, to, param));+}+pub fn disconnect(from: u32, to: u32, param: i32) {+ submit(Cmd::Disconnect(from, to, param));+}+pub fn set_param(node: u32, index: usize, intrinsic: f32, events: Vec<Ev>) {+ submit(Cmd::Param(node, index, intrinsic, events));+}+pub fn set_wave(node: u32, wave: Wave) {+ submit(Cmd::Wave(node, wave));+}+pub fn start(node: u32, when: f64) {+ submit(Cmd::Start(node, when));+ ensure_device();+}+pub fn stop(node: u32, when: f64) {+ submit(Cmd::Stop(node, when));+}+pub fn want_ended(node: u32) {+ submit(Cmd::WantEnded(node));+}+pub fn release(node: u32) {+ submit(Cmd::Release(node));+}++/// Page teardown: silence everything and drop the graph.+pub fn reset() {+ CTXS.with(|m| m.borrow_mut().clear());+ submit(Cmd::Reset);+ ENDED.lock().unwrap().clear();+}++/// Oscillators that ended (for `onended`), collected by the render thread.+static ENDED: Mutex<Vec<u32>> = Mutex::new(Vec::new());++pub fn take_ended() -> Vec<u32> {+ std::mem::take(&mut *ENDED.lock().unwrap())+}++static ENDED_NOTIFY: OnceLock<Box<dyn Fn() + Send + Sync>> = OnceLock::new();++/// Set how the render thread tells the main thread about ended oscillators.+pub fn set_ended_notify(f: impl Fn() + Send + Sync + 'static) {+ let _ = ENDED_NOTIFY.set(Box::new(f));+}++// ---------------------------------------------------------------- device lifecycle++fn ensure_device() {+ match STATE.load(Ordering::SeqCst) {+ STOPPED => {}+ STOPPING => {+ RESTART.store(true, Ordering::SeqCst);+ return;+ }+ _ => return,+ }+ {+ // Freeze the clock until the first buffer renders.+ let mut g = CLOCK.lock().unwrap();+ let c = g.get_or_insert_with(|| Clock { idle_base: 0.0, idle_since: Instant::now(), dev_base: 0.0 });+ if STATE.compare_exchange(STOPPED, STARTING, Ordering::SeqCst, Ordering::SeqCst).is_err() {+ return;+ }+ c.idle_base += c.idle_since.elapsed().as_secs_f64();+ c.idle_since = Instant::now();+ }+ let _ = std::thread::Builder::new().name("net-audio-start".into()).spawn(|| {+ if !device::start() {+ eprintln!("[audio] could not start the output device");+ let mut g = CLOCK.lock().unwrap();+ if let Some(c) = g.as_mut() {+ c.idle_since = Instant::now();+ }+ STATE.store(STOPPED, Ordering::SeqCst);+ }+ });+}++/// Main thread, posted by the render callback after a second of silence.+fn stop_device() {+ if STATE.compare_exchange(RUNNING, STOPPING, Ordering::SeqCst, Ordering::SeqCst).is_err() {+ STOP_REQUESTED.store(false, Ordering::SeqCst);+ return;+ }+ let _ = std::thread::Builder::new().name("net-audio-stop".into()).spawn(|| {+ device::stop();+ {+ let mut g = CLOCK.lock().unwrap();+ let c = g.as_mut().unwrap();+ c.idle_base = f64::from_bits(DEV_BASE.load(Ordering::SeqCst)) + FRAMES.load(Ordering::SeqCst) as f64 / sample_rate();+ c.idle_since = Instant::now();+ STATE.store(STOPPED, Ordering::SeqCst);+ }+ STOP_REQUESTED.store(false, Ordering::SeqCst);+ // Sounds requested while we were stopping must still play.+ let pending = {+ let mut m = MIXER.lock().unwrap();+ let m = m.get_or_insert_with(|| Mixer::new(sample_rate()));+ for c in std::mem::take(&mut *CMDS.lock().unwrap()) {+ m.apply(c);+ }+ m.active()+ };+ if RESTART.swap(false, Ordering::SeqCst) || pending {+ ensure_device();+ }+ });+}++/// The render callback body: render `frames` samples and hand the mono mix to `out`.+fn render_into(frames: usize, mut out: impl FnMut(&[f32])) {+ let rate = sample_rate();+ if STATE.load(Ordering::SeqCst) == STARTING {+ // First buffer: device time continues from where the idle clock was frozen.+ let mut g = CLOCK.lock().unwrap();+ let c = g.as_mut().unwrap();+ c.dev_base = c.idle_base;+ DEV_BASE.store(c.dev_base.to_bits(), Ordering::SeqCst);+ FRAMES.store(0, Ordering::SeqCst);+ STATE.store(RUNNING, Ordering::SeqCst);+ }+ let dev = f64::from_bits(DEV_BASE.load(Ordering::SeqCst)) + FRAMES.load(Ordering::SeqCst) as f64 / rate;+ let mut guard = MIXER.lock().unwrap();+ let m = guard.get_or_insert_with(|| Mixer::new(rate));+ if let Ok(mut q) = CMDS.try_lock() {+ for c in q.drain(..) {+ m.apply(c);+ }+ }+ m.render(dev, frames);+ for s in m.mix.iter_mut() {+ *s = s.clamp(-1.0, 1.0);+ }+ out(&m.mix);+ FRAMES.fetch_add(frames as u64, Ordering::SeqCst);+ if !m.ended.is_empty() {+ ENDED.lock().unwrap().append(&mut m.ended);+ if let Some(f) = ENDED_NOTIFY.get() {+ f();+ }+ }+ if m.active() {+ m.silent_frames = 0;+ } else {+ m.silent_frames += frames as u64;+ if m.silent_frames as f64 >= rate && !STOP_REQUESTED.swap(true, Ordering::SeqCst) {+ m.silent_frames = 0;+ rt::post(stop_device);+ }+ }+}++#[cfg(target_os = "macos")]+mod device {+ use std::ffi::c_void;+ use super::*;++ #[repr(C)]+ struct AudioComponentDescription {+ ty: u32,+ sub: u32,+ manufacturer: u32,+ flags: u32,+ mask: u32,+ }+ #[repr(C)]+ struct StreamDescription {+ rate: f64,+ format: u32,+ flags: u32,+ bytes_per_packet: u32,+ frames_per_packet: u32,+ bytes_per_frame: u32,+ channels: u32,+ bits: u32,+ reserved: u32,+ }+ type RenderProc = unsafe extern "C" fn(*mut c_void, *mut u32, *const c_void, u32, u32, *mut BufferList) -> i32;+ #[repr(C)]+ struct RenderCallback {+ proc_: RenderProc,+ refcon: *mut c_void,+ }+ #[repr(C)]+ struct Buffer {+ channels: u32,+ size: u32,+ data: *mut c_void,+ }+ #[repr(C)]+ struct BufferList {+ count: u32,+ buffers: [Buffer; 1],+ }+ #[repr(C)]+ struct PropertyAddress {+ selector: u32,+ scope: u32,+ element: u32,+ }++ const fn fourcc(s: &[u8; 4]) -> u32 {+ (s[0] as u32) << 24 | (s[1] as u32) << 16 | (s[2] as u32) << 8 | s[3] as u32+ }++ #[link(name = "AudioToolbox", kind = "framework")]+ unsafe extern "C" {+ fn AudioComponentFindNext(c: *mut c_void, d: *const AudioComponentDescription) -> *mut c_void;+ fn AudioComponentInstanceNew(c: *mut c_void, out: *mut *mut c_void) -> i32;+ fn AudioComponentInstanceDispose(u: *mut c_void) -> i32;+ fn AudioUnitSetProperty(u: *mut c_void, id: u32, scope: u32, elem: u32, data: *const c_void, size: u32) -> i32;+ fn AudioUnitInitialize(u: *mut c_void) -> i32;+ fn AudioUnitUninitialize(u: *mut c_void) -> i32;+ fn AudioOutputUnitStart(u: *mut c_void) -> i32;+ fn AudioOutputUnitStop(u: *mut c_void) -> i32;+ }+ #[link(name = "CoreAudio", kind = "framework")]+ unsafe extern "C" {+ fn AudioObjectGetPropertyData(obj: u32, addr: *const PropertyAddress, qsize: u32, q: *const c_void, size: *mut u32, data: *mut c_void) -> i32;+ }++ struct Unit(*mut c_void);+ unsafe impl Send for Unit {}+ static UNIT: Mutex<Option<Unit>> = Mutex::new(None);++ pub fn default_rate() -> Option<f64> {+ unsafe {+ let mut dev: u32 = 0;+ let mut size = 4u32;+ let addr = PropertyAddress { selector: fourcc(b"dOut"), scope: fourcc(b"glob"), element: 0 };+ if AudioObjectGetPropertyData(1, &addr, 0, std::ptr::null(), &mut size, (&mut dev as *mut u32).cast()) != 0 || dev == 0 {+ return None;+ }+ let mut rate: f64 = 0.0;+ let mut size = 8u32;+ let addr = PropertyAddress { selector: fourcc(b"nsrt"), scope: fourcc(b"glob"), element: 0 };+ if AudioObjectGetPropertyData(dev, &addr, 0, std::ptr::null(), &mut size, (&mut rate as *mut f64).cast()) != 0 {+ return None;+ }+ Some(rate)+ }+ }++ unsafe extern "C" fn render(_refcon: *mut c_void, _flags: *mut u32, _ts: *const c_void, _bus: u32, frames: u32, data: *mut BufferList) -> i32 {+ unsafe {+ let list = &mut *data;+ let bufs = std::slice::from_raw_parts_mut(list.buffers.as_mut_ptr(), list.count as usize);+ render_into(frames as usize, |mix| {+ for b in bufs.iter_mut() {+ // mono mix to every channel (Web Audio's speaker up-mix of a mono source)+ let n = (b.size as usize / 4).min(mix.len());+ std::slice::from_raw_parts_mut(b.data.cast::<f32>(), n).copy_from_slice(&mix[..n]);+ }+ });+ }+ 0+ }++ pub fn start() -> bool {+ unsafe {+ let desc = AudioComponentDescription { ty: fourcc(b"auou"), sub: fourcc(b"def "), manufacturer: fourcc(b"appl"), flags: 0, mask: 0 };+ let comp = AudioComponentFindNext(std::ptr::null_mut(), &desc);+ if comp.is_null() {+ return false;+ }+ let mut unit: *mut c_void = std::ptr::null_mut();+ if AudioComponentInstanceNew(comp, &mut unit) != 0 || unit.is_null() {+ return false;+ }+ let fmt = StreamDescription {+ rate: sample_rate(),+ format: fourcc(b"lpcm"),+ flags: 1 | 8 | 0x20, // float, packed, non-interleaved+ bytes_per_packet: 4,+ frames_per_packet: 1,+ bytes_per_frame: 4,+ channels: 2,+ bits: 32,+ reserved: 0,+ };+ let cb = RenderCallback { proc_: render, refcon: std::ptr::null_mut() };+ let ok = AudioUnitSetProperty(unit, 8, 1, 0, (&fmt as *const StreamDescription).cast(), size_of::<StreamDescription>() as u32) == 0+ && AudioUnitSetProperty(unit, 23, 1, 0, (&cb as *const RenderCallback).cast(), size_of::<RenderCallback>() as u32) == 0+ && AudioUnitInitialize(unit) == 0;+ if !ok || AudioOutputUnitStart(unit) != 0 {+ AudioComponentInstanceDispose(unit);+ return false;+ }+ *UNIT.lock().unwrap() = Some(Unit(unit));+ true+ }+ }++ /// Stop and release the device: nothing of CoreAudio's I/O machinery stays awake.+ pub fn stop() {+ if let Some(Unit(u)) = UNIT.lock().unwrap().take() {+ unsafe {+ AudioOutputUnitStop(u);+ AudioUnitUninitialize(u);+ AudioComponentInstanceDispose(u);+ }+ }+ }+}++#[cfg(not(target_os = "macos"))]+mod device {+ pub fn default_rate() -> Option<f64> {+ None+ }+ pub fn start() -> bool {+ false+ }+ pub fn stop() {}+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn automation() {+ let evs = [Ev::Set { t: 1.0, v: 0.025 }, Ev::Exp { t: 1.05, v: 0.0001, t0: 1.0 }];+ assert_eq!(param_value(&evs, 1.0, 0.5), 1.0);+ assert!((param_value(&evs, 1.0, 1.0) - 0.025).abs() < 1e-6);+ let mid = param_value(&evs, 1.0, 1.025);+ assert!((mid - (0.025f32 * 0.0001).sqrt()).abs() < 1e-5, "{mid}");+ assert!((param_value(&evs, 1.0, 2.0) - 0.0001).abs() < 1e-7);+ let lin = [Ev::Set { t: 0.0, v: 0.0 }, Ev::Linear { t: 1.0, v: 1.0, t0: 0.0 }];+ assert!((param_value(&lin, 5.0, 0.25) - 0.25).abs() < 1e-6);+ let tgt = [Ev::Set { t: 0.0, v: 1.0 }, Ev::Target { t: 1.0, v: 0.0, tau: 0.5 }];+ assert!((param_value(&tgt, 0.0, 1.5) - (-1.0f32).exp()).abs() < 1e-5);+ // ramp with no previous event starts when it was scheduled+ let r = [Ev::Linear { t: 2.0, v: 1.0, t0: 1.0 }];+ assert!((param_value(&r, 0.0, 1.5) - 0.5).abs() < 1e-6);+ }+ #[test]+ fn renders_blip() {+ let mut m = Mixer::new(48000.0);+ m.apply(Cmd::Ctx(1, CtxClock { offset: 0.0, suspended_at: None, closed: false }));+ m.apply(Cmd::Node(1, 1, 0));+ m.apply(Cmd::Node(2, 1, 2));+ m.apply(Cmd::Node(3, 1, 1));+ m.apply(Cmd::Wave(2, Wave::Triangle));+ m.apply(Cmd::Param(3, 0, 1.0, vec![Ev::Set { t: 0.0, v: 0.025 }, Ev::Exp { t: 0.05, v: 0.0001, t0: 0.0 }]));+ m.apply(Cmd::Connect(2, 3, -1));+ m.apply(Cmd::Connect(3, 1, -1));+ m.apply(Cmd::Start(2, 0.0));+ m.apply(Cmd::Stop(2, 0.06));+ m.apply(Cmd::WantEnded(2));+ m.apply(Cmd::Release(2));+ m.apply(Cmd::Release(3));+ m.render(0.0, 512);+ let peak = m.mix.iter().fold(0f32, |a, s| a.max(s.abs()));+ assert!(peak > 0.01 && peak <= 0.026, "{peak}");+ assert!(m.active());+ for i in 1..8 {+ m.render(i as f64 * 512.0 / 48000.0, 512);+ }+ assert!(!m.active());+ assert_eq!(m.ended, vec![2]);+ // released and finished: the oscillator and its gain are gone, the destination stays+ assert_eq!(m.nodes.len(), 1);+ }+}diff --git a/runtime/crates/net/src/clipboard.rs b/runtime/crates/net/src/clipboard.rsnew file mode 100644index 0000000..8786bbd--- /dev/null+++ b/runtime/crates/net/src/clipboard.rs@@ -0,0 +1,69 @@+//! `navigator.clipboard` text (main thread).++#[cfg(target_os = "macos")]+pub fn write(text: &str) -> bool {+ use objc2_app_kit::{NSPasteboard, NSPasteboardTypeString};+ use objc2_foundation::NSString;+ let pb = NSPasteboard::generalPasteboard();+ pb.clearContents();+ pb.setString_forType(&NSString::from_str(text), unsafe { NSPasteboardTypeString })+}++#[cfg(target_os = "macos")]+pub fn read() -> String {+ use objc2_app_kit::{NSPasteboard, NSPasteboardTypeString};+ use objc2_foundation::NSString;+ let _ = NSString::new();+ let pb = NSPasteboard::generalPasteboard();+ pb.stringForType(unsafe { NSPasteboardTypeString }).map(|s| s.to_string()).unwrap_or_default()+}++#[cfg(target_os = "linux")]+pub fn write(text: &str) -> bool {+ use std::io::Write;+ use std::process::{Command, Stdio};+ let candidates: &[(&str, &[&str])] = if std::env::var_os("WAYLAND_DISPLAY").is_some() {+ &[("wl-copy", &[]), ("xclip", &["-selection", "clipboard"])]+ } else {+ &[("xclip", &["-selection", "clipboard"]), ("xsel", &["--clipboard", "--input"]), ("wl-copy", &[])]+ };+ for (bin, args) in candidates {+ if let Ok(mut child) = Command::new(bin).args(*args).stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()).spawn() {+ if let Some(mut stdin) = child.stdin.take() {+ let _ = stdin.write_all(text.as_bytes());+ }+ if child.wait().is_ok_and(|s| s.success()) {+ return true;+ }+ }+ }+ false+}++#[cfg(target_os = "linux")]+pub fn read() -> String {+ use std::process::Command;+ let candidates: &[(&str, &[&str])] = if std::env::var_os("WAYLAND_DISPLAY").is_some() {+ &[("wl-paste", &["--no-newline"]), ("xclip", &["-o", "-selection", "clipboard"])]+ } else {+ &[("xclip", &["-o", "-selection", "clipboard"]), ("xsel", &["--clipboard", "--output"]), ("wl-paste", &["--no-newline"])]+ };+ for (bin, args) in candidates {+ if let Ok(out) = Command::new(bin).args(*args).output() {+ if out.status.success() {+ return String::from_utf8_lossy(&out.stdout).into_owned();+ }+ }+ }+ String::new()+}++#[cfg(not(any(target_os = "macos", target_os = "linux")))]+pub fn write(_text: &str) -> bool {+ false+}++#[cfg(not(any(target_os = "macos", target_os = "linux")))]+pub fn read() -> String {+ String::new()+}diff --git a/runtime/crates/net/src/conn.rs b/runtime/crates/net/src/conn.rsnew file mode 100644index 0000000..5cad34e--- /dev/null+++ b/runtime/crates/net/src/conn.rs@@ -0,0 +1,423 @@+//! Connections: DNS, TCP, proxies (HTTP CONNECT, SOCKS5) and TLS over Security.framework.+//!+//! Everything here blocks and runs on worker threads. A `Cancel` lets the main thread abort an+//! in-flight request: it shuts the socket down, which wakes any blocked read or write at once.++use std::io::{self, Read, Write};+use std::net::{Shutdown, SocketAddr, TcpStream, ToSocketAddrs};+use std::os::fd::AsRawFd;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Mutex, OnceLock};+use std::time::{Duration, Instant};++use crate::proxy::{self, Proxy};++pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);+/// Longest wait for the next byte of a response (Chromium has no fetch timeout; this only stops a+/// dead peer from pinning a worker thread forever).+pub const READ_TIMEOUT: Duration = Duration::from_secs(300);+/// A send that cannot make progress for this long means the peer is gone.+pub const WRITE_TIMEOUT: Duration = Duration::from_secs(30);++/// A failure, named like Chromium's net errors (`net::ERR_…`) so logs read the same.+#[derive(Debug, Clone)]+pub struct NetError {+ pub code: &'static str,+ pub detail: String,+}++impl NetError {+ pub fn new(code: &'static str, detail: impl Into<String>) -> Self {+ NetError { code, detail: detail.into() }+ }+ pub fn io(e: &io::Error) -> Self {+ use io::ErrorKind::*;+ let code = match e.kind() {+ ConnectionRefused => "ERR_CONNECTION_REFUSED",+ ConnectionReset => "ERR_CONNECTION_RESET",+ ConnectionAborted => "ERR_CONNECTION_ABORTED",+ TimedOut | WouldBlock => "ERR_TIMED_OUT",+ UnexpectedEof | BrokenPipe | NotConnected => "ERR_CONNECTION_CLOSED",+ AddrNotAvailable | NetworkUnreachable | HostUnreachable => "ERR_ADDRESS_UNREACHABLE",+ NetworkDown => "ERR_INTERNET_DISCONNECTED",+ _ => "ERR_FAILED",+ };+ NetError::new(code, e.to_string())+ }+ pub fn aborted() -> Self {+ NetError::new("ERR_ABORTED", "aborted")+ }+}++impl std::fmt::Display for NetError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ if self.detail.is_empty() { write!(f, "net::{}", self.code) } else { write!(f, "net::{} ({})", self.code, self.detail) }+ }+}++/// Lets another thread abort a blocking request.+#[derive(Default)]+pub struct Cancel {+ flag: AtomicBool,+ sock: Mutex<Option<TcpStream>>,+}++impl Cancel {+ pub fn cancel(&self) {+ self.flag.store(true, Ordering::SeqCst);+ if let Some(s) = self.sock.lock().unwrap().take() {+ let _ = s.shutdown(Shutdown::Both);+ }+ }+ pub fn is_cancelled(&self) -> bool {+ self.flag.load(Ordering::SeqCst)+ }+ pub fn check(&self) -> Result<(), NetError> {+ if self.is_cancelled() { Err(NetError::aborted()) } else { Ok(()) }+ }+ /// Make `cancel()` shut this socket down (until `release`).+ pub fn watch(&self, tcp: &TcpStream) -> Result<(), NetError> {+ let clone = tcp.try_clone().map_err(|e| NetError::io(&e))?;+ let mut g = self.sock.lock().unwrap();+ if self.is_cancelled() {+ let _ = clone.shutdown(Shutdown::Both);+ return Err(NetError::aborted());+ }+ *g = Some(clone);+ Ok(())+ }+ /// Stop watching (the connection goes back to the pool and must not be shut down later).+ pub fn release(&self) {+ self.sock.lock().unwrap().take();+ }+}++/// A TCP socket whose reads can be switched to non-blocking while writes stay blocking: the+/// WebSocket thread waits for readability with `poll` and drains with non-blocking reads, but a+/// send always completes (bounded by `WRITE_TIMEOUT`), so the TLS layer never has to buffer a+/// partially written record.+pub struct Sock {+ pub tcp: TcpStream,+ nonblocking_reads: bool,+}++impl Sock {+ pub fn set_nonblocking_reads(&mut self, on: bool) {+ self.nonblocking_reads = on;+ }+}++impl Read for Sock {+ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {+ if !self.nonblocking_reads {+ return self.tcp.read(buf);+ }+ loop {+ let n = unsafe { libc::recv(self.tcp.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len(), libc::MSG_DONTWAIT) };+ if n >= 0 {+ return Ok(n as usize);+ }+ let e = io::Error::last_os_error();+ if e.kind() != io::ErrorKind::Interrupted {+ return Err(e);+ }+ }+ }+}++impl Write for Sock {+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {+ self.tcp.write(buf)+ }+ fn flush(&mut self) -> io::Result<()> {+ Ok(())+ }+}++pub enum Stream {+ Plain(Sock),+ Tls(Box<native_tls::TlsStream<Sock>>),+}++impl Stream {+ pub fn sock(&self) -> &Sock {+ match self {+ Stream::Plain(s) => s,+ Stream::Tls(t) => t.get_ref(),+ }+ }+ pub fn sock_mut(&mut self) -> &mut Sock {+ match self {+ Stream::Plain(s) => s,+ Stream::Tls(t) => t.get_mut(),+ }+ }+ pub fn tcp(&self) -> &TcpStream {+ &self.sock().tcp+ }+}++impl Read for Stream {+ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {+ match self {+ Stream::Plain(s) => s.read(buf),+ Stream::Tls(t) => t.read(buf),+ }+ }+}++impl Write for Stream {+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {+ match self {+ Stream::Plain(s) => s.write(buf),+ Stream::Tls(t) => t.write(buf),+ }+ }+ fn flush(&mut self) -> io::Result<()> {+ match self {+ Stream::Plain(s) => s.flush(),+ Stream::Tls(t) => t.flush(),+ }+ }+}++/// Where a request goes: scheme security, host (IPv6 literals without brackets) and port.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Endpoint {+ pub tls: bool,+ pub host: String,+ pub port: u16,+}++impl Endpoint {+ /// `host[:port]` as written in a Host header / CONNECT line.+ pub fn authority(&self, always_port: bool) -> String {+ let h = if self.host.contains(':') { format!("[{}]", self.host) } else { self.host.clone() };+ let default = if self.tls { 443 } else { 80 };+ if always_port || self.port != default { format!("{h}:{}", self.port) } else { h }+ }+ pub fn is_loopback(&self) -> bool {+ let h = self.host.to_ascii_lowercase();+ h == "localhost" || h.ends_with(".localhost") || h == "::1" || h.starts_with("127.")+ }+}++/// An open connection and how it reaches the endpoint.+pub struct Conn {+ pub stream: Stream,+ /// Plain HTTP through an HTTP proxy: requests use the absolute URL as the target.+ pub absolute_form: bool,+ /// Pool key: endpoint + route.+ pub key: String,+}++/// What the connection is for: WebSockets always tunnel through HTTP proxies (as Chromium does).+#[derive(Clone, Copy, PartialEq, Eq)]+pub enum Purpose {+ Http,+ WebSocket,+}++pub fn connect(ep: &Endpoint, purpose: Purpose, cancel: &Cancel) -> Result<Conn, NetError> {+ let proxies = if ep.is_loopback() { vec![Proxy::Direct] } else { proxy::for_endpoint(ep) };+ let mut last = NetError::new("ERR_FAILED", "no route");+ for p in &proxies {+ cancel.check()?;+ match connect_via(ep, p, purpose, cancel) {+ Ok(c) => return Ok(c),+ Err(e) if e.code == "ERR_ABORTED" => return Err(e),+ // TLS and HTTP errors from the origin are final; only proxy failures fall back.+ Err(e) if matches!(p, Proxy::Direct) || !e.code.contains("PROXY") && !e.code.contains("TUNNEL") => return Err(e),+ Err(e) => last = e,+ }+ }+ Err(last)+}++fn connect_via(ep: &Endpoint, p: &Proxy, purpose: Purpose, cancel: &Cancel) -> Result<Conn, NetError> {+ let (tcp, absolute_form, route) = match p {+ Proxy::Direct => (tcp_connect(&ep.host, ep.port, cancel, false)?, false, String::new()),+ Proxy::Http(h, port) => {+ let tcp = tcp_connect(h, *port, cancel, true)?;+ if ep.tls || purpose == Purpose::WebSocket {+ http_tunnel(&tcp, ep)?;+ (tcp, false, format!("|http-tunnel:{h}:{port}"))+ } else {+ (tcp, true, format!("|http-proxy:{h}:{port}"))+ }+ }+ Proxy::Socks(h, port) => {+ let tcp = tcp_connect(h, *port, cancel, true)?;+ socks5(&tcp, ep)?;+ (tcp, false, format!("|socks:{h}:{port}"))+ }+ };+ let key = format!("{}://{}{}", if ep.tls { "https" } else { "http" }, ep.authority(true), route);+ let sock = Sock { tcp, nonblocking_reads: false };+ let stream = if ep.tls {+ Stream::Tls(Box::new(tls_handshake(&ep.host, sock)?))+ } else {+ Stream::Plain(sock)+ };+ cancel.check()?;+ Ok(Conn { stream, absolute_form, key })+}++fn tcp_connect(host: &str, port: u16, cancel: &Cancel, is_proxy: bool) -> Result<TcpStream, NetError> {+ let addrs: Vec<SocketAddr> = match (host, port).to_socket_addrs() {+ Ok(a) => a.collect(),+ Err(e) => {+ let code = if is_proxy { "ERR_PROXY_CONNECTION_FAILED" } else { "ERR_NAME_NOT_RESOLVED" };+ return Err(NetError::new(code, format!("{host}: {e}")));+ }+ };+ if addrs.is_empty() {+ return Err(NetError::new("ERR_NAME_NOT_RESOLVED", host.to_string()));+ }+ cancel.check()?;+ let deadline = Instant::now() + CONNECT_TIMEOUT;+ let mut last = NetError::new("ERR_CONNECTION_FAILED", host.to_string());+ for (i, addr) in addrs.iter().enumerate() {+ let left = deadline.saturating_duration_since(Instant::now());+ if left.is_zero() {+ break;+ }+ // Leave time for the other addresses when the first family is unreachable.+ let budget = if i + 1 < addrs.len() { left.min(Duration::from_secs(5)) } else { left };+ match TcpStream::connect_timeout(addr, budget) {+ Ok(tcp) => {+ configure(&tcp);+ cancel.watch(&tcp)?;+ return Ok(tcp);+ }+ Err(e) => {+ last = NetError::io(&e);+ if is_proxy {+ last.code = "ERR_PROXY_CONNECTION_FAILED";+ }+ }+ }+ cancel.check()?;+ }+ Err(last)+}++fn configure(tcp: &TcpStream) {+ let _ = tcp.set_nodelay(true);+ let _ = tcp.set_read_timeout(Some(READ_TIMEOUT));+ let _ = tcp.set_write_timeout(Some(WRITE_TIMEOUT));+ // A write to a socket the peer closed must return EPIPE, not kill the process.+ #[cfg(target_os = "macos")]+ unsafe {+ let one: libc::c_int = 1;+ libc::setsockopt(tcp.as_raw_fd(), libc::SOL_SOCKET, libc::SO_NOSIGPIPE, (&one as *const libc::c_int).cast(), 4);+ }+ #[cfg(all(unix, not(target_os = "macos")))]+ {+ static IGNORE_SIGPIPE: std::sync::Once = std::sync::Once::new();+ IGNORE_SIGPIPE.call_once(|| unsafe {+ libc::signal(libc::SIGPIPE, libc::SIG_IGN);+ });+ }+}++fn tls_connector() -> Result<&'static native_tls::TlsConnector, NetError> {+ static C: OnceLock<Result<native_tls::TlsConnector, String>> = OnceLock::new();+ C.get_or_init(|| native_tls::TlsConnector::new().map_err(|e| e.to_string()))+ .as_ref()+ .map_err(|e| NetError::new("ERR_SSL_PROTOCOL_ERROR", e.clone()))+}++fn tls_handshake(host: &str, sock: Sock) -> Result<native_tls::TlsStream<Sock>, NetError> {+ let _ = sock.tcp.set_read_timeout(Some(CONNECT_TIMEOUT));+ match tls_connector()?.connect(host, sock) {+ Ok(s) => {+ let _ = s.get_ref().tcp.set_read_timeout(Some(READ_TIMEOUT));+ Ok(s)+ }+ Err(native_tls::HandshakeError::Failure(e)) => {+ let msg = e.to_string();+ let code = if msg.contains("certificate") || msg.contains("trust") { "ERR_CERT_INVALID" } else { "ERR_SSL_PROTOCOL_ERROR" };+ Err(NetError::new(code, msg))+ }+ Err(native_tls::HandshakeError::WouldBlock(_)) => Err(NetError::new("ERR_TIMED_OUT", "TLS handshake timed out")),+ }+}++/// Read an HTTP head (through the blank line) byte by byte, so nothing after it is consumed.+fn read_head_exact(mut r: impl Read, limit: usize) -> io::Result<Vec<u8>> {+ let mut head = Vec::with_capacity(256);+ let mut b = [0u8; 1];+ while !head.ends_with(b"\r\n\r\n") {+ if r.read(&mut b)? == 0 {+ return Err(io::ErrorKind::UnexpectedEof.into());+ }+ head.push(b[0]);+ if head.len() > limit {+ return Err(io::Error::other("response head too large"));+ }+ }+ Ok(head)+}++fn http_tunnel(mut tcp: &TcpStream, ep: &Endpoint) -> Result<(), NetError> {+ let target = ep.authority(true);+ let req = format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\nProxy-Connection: keep-alive\r\nUser-Agent: {}\r\n\r\n", crate::user_agent());+ let fail = |d: String| NetError::new("ERR_TUNNEL_CONNECTION_FAILED", d);+ tcp.write_all(req.as_bytes()).map_err(|e| fail(e.to_string()))?;+ let head = read_head_exact(tcp, 64 * 1024).map_err(|e| fail(e.to_string()))?;+ let mut hs = [httparse::EMPTY_HEADER; 64];+ let mut resp = httparse::Response::new(&mut hs);+ match resp.parse(&head) {+ Ok(httparse::Status::Complete(_)) if resp.code == Some(200) => Ok(()),+ Ok(_) if resp.code == Some(407) => Err(NetError::new("ERR_PROXY_AUTH_UNSUPPORTED", "proxy requires authentication")),+ Ok(_) => Err(fail(format!("proxy answered {}", resp.code.unwrap_or(0)))),+ Err(e) => Err(fail(e.to_string())),+ }+}++fn socks5(mut tcp: &TcpStream, ep: &Endpoint) -> Result<(), NetError> {+ let fail = |d: &str| NetError::new("ERR_SOCKS_CONNECTION_FAILED", d.to_string());+ let io = |e: io::Error| NetError::new("ERR_SOCKS_CONNECTION_FAILED", e.to_string());+ tcp.write_all(&[5, 1, 0]).map_err(io)?;+ let mut r = [0u8; 2];+ tcp.read_exact(&mut r).map_err(io)?;+ if r != [5, 0] {+ return Err(fail("no acceptable authentication method"));+ }+ let host = ep.host.as_bytes();+ if host.len() > 255 {+ return Err(fail("host name too long"));+ }+ // Domain names go to the proxy unresolved (remote DNS, like Chromium's socks5).+ let mut req = vec![5, 1, 0, 3, host.len() as u8];+ req.extend_from_slice(host);+ req.extend_from_slice(&ep.port.to_be_bytes());+ tcp.write_all(&req).map_err(io)?;+ let mut rep = [0u8; 4];+ tcp.read_exact(&mut rep).map_err(io)?;+ if rep[1] != 0 {+ return Err(fail(&format!("proxy replied {}", rep[1])));+ }+ let skip = match rep[3] {+ 1 => 4 + 2,+ 4 => 16 + 2,+ 3 => {+ let mut n = [0u8; 1];+ tcp.read_exact(&mut n).map_err(io)?;+ n[0] as usize + 2+ }+ _ => return Err(fail("bad address type")),+ };+ let mut rest = vec![0u8; skip];+ tcp.read_exact(&mut rest).map_err(io)?;+ Ok(())+}++/// Is a pooled socket still usable? A readable idle socket means EOF, a TLS close alert or+/// stray bytes; any of them makes it unusable.+pub fn idle_socket_alive(tcp: &TcpStream) -> bool {+ let mut p = libc::pollfd { fd: tcp.as_raw_fd(), events: libc::POLLIN, revents: 0 };+ let n = unsafe { libc::poll(&mut p, 1, 0) };+ n == 0+}diff --git a/runtime/crates/net/src/decode.rs b/runtime/crates/net/src/decode.rsnew file mode 100644index 0000000..b2d2b3e--- /dev/null+++ b/runtime/crates/net/src/decode.rs@@ -0,0 +1,175 @@+//! Content-Encoding decoding (gzip, deflate, br): macOS uses the system Compression framework+//! (`libcompression`), other platforms use pure-Rust `flate2` and `brotli`.++#[cfg(target_os = "macos")]+mod imp {+ use std::ffi::c_void;++ const ALG_ZLIB: i32 = 0x205; // raw DEFLATE (RFC 1951)+ const ALG_BROTLI: i32 = 0xB02; // macOS 12++ const OP_DECODE: i32 = 1;+ const STATUS_OK: i32 = 0;+ const STATUS_END: i32 = 1;+ const FLAG_FINALIZE: i32 = 1;++ #[repr(C)]+ struct CompressionStream {+ dst_ptr: *mut u8,+ dst_size: usize,+ src_ptr: *const u8,+ src_size: usize,+ state: *mut c_void,+ }++ #[link(name = "compression")]+ unsafe extern "C" {+ fn compression_stream_init(s: *mut CompressionStream, op: i32, alg: i32) -> i32;+ fn compression_stream_process(s: *mut CompressionStream, flags: i32) -> i32;+ fn compression_stream_destroy(s: *mut CompressionStream) -> i32;+ }++ fn inflate(alg: i32, input: &[u8]) -> Result<(Vec<u8>, usize), String> {+ let mut s = CompressionStream { dst_ptr: std::ptr::null_mut(), dst_size: 0, src_ptr: std::ptr::null(), src_size: 0, state: std::ptr::null_mut() };+ if unsafe { compression_stream_init(&mut s, OP_DECODE, alg) } != STATUS_OK {+ return Err("decoder unavailable".into());+ }+ let mut out: Vec<u8> = Vec::with_capacity((input.len() * 4).clamp(4096, 64 << 20));+ s.src_ptr = input.as_ptr();+ s.src_size = input.len();+ let result = loop {+ if out.capacity() - out.len() < 4096 {+ out.reserve(out.capacity().max(4096));+ }+ let spare = out.capacity() - out.len();+ s.dst_ptr = unsafe { out.as_mut_ptr().add(out.len()) };+ s.dst_size = spare;+ let st = unsafe { compression_stream_process(&mut s, FLAG_FINALIZE) };+ let produced = spare - s.dst_size;+ unsafe { out.set_len(out.len() + produced) };+ match st {+ STATUS_END => break Ok(input.len() - s.src_size),+ STATUS_OK if produced == 0 && s.src_size == 0 => break Err("truncated stream".to_string()),+ STATUS_OK => {}+ _ => break Err("corrupt stream".to_string()),+ }+ };+ unsafe { compression_stream_destroy(&mut s) };+ result.map(|used| (out, used))+ }++ pub fn gunzip(mut data: &[u8]) -> Result<Vec<u8>, String> {+ let mut out = Vec::new();+ loop {+ if data.len() < 18 || data[0] != 0x1f || data[1] != 0x8b || data[2] != 8 {+ return if out.is_empty() { Err("not gzip".into()) } else { Ok(out) };+ }+ let flags = data[3];+ let mut i = 10;+ if flags & 4 != 0 {+ let n = *data.get(i).ok_or("short header")? as usize | (*data.get(i + 1).ok_or("short header")? as usize) << 8;+ i += 2 + n;+ }+ for bit in [8u8, 16] {+ if flags & bit != 0 {+ while *data.get(i).ok_or("short header")? != 0 {+ i += 1;+ }+ i += 1;+ }+ }+ if flags & 2 != 0 {+ i += 2;+ }+ let body = data.get(i..).ok_or("short header")?;+ let (mut part, used) = inflate(ALG_ZLIB, body)?;+ out.append(&mut part);+ data = body.get(used + 8..).unwrap_or(&[]);+ if data.is_empty() {+ return Ok(out);+ }+ }+ }++ pub fn inflate_http_deflate(data: &[u8]) -> Result<Vec<u8>, String> {+ let zlib = data.len() >= 2 && data[0] & 0x0f == 8 && (u16::from(data[0]) << 8 | u16::from(data[1])) % 31 == 0;+ if zlib {+ if data[1] & 0x20 != 0 {+ return Err("preset dictionary".into());+ }+ if let Ok((out, _)) = inflate(ALG_ZLIB, &data[2..]) {+ return Ok(out);+ }+ }+ inflate(ALG_ZLIB, data).map(|r| r.0)+ }++ pub fn inflate_brotli(data: &[u8]) -> Result<Vec<u8>, String> {+ inflate(ALG_BROTLI, data).map(|r| r.0)+ }+}++#[cfg(not(target_os = "macos"))]+mod imp {+ use std::io::Read;++ pub fn gunzip(data: &[u8]) -> Result<Vec<u8>, String> {+ let mut dec = flate2::read::MultiGzDecoder::new(data);+ let mut out = Vec::new();+ dec.read_to_end(&mut out).map_err(|e| format!("gzip: {e}"))?;+ Ok(out)+ }++ pub fn inflate_http_deflate(data: &[u8]) -> Result<Vec<u8>, String> {+ let mut z = flate2::read::ZlibDecoder::new(data);+ let mut out = Vec::new();+ if z.read_to_end(&mut out).is_ok() {+ return Ok(out);+ }+ out.clear();+ let mut raw = flate2::read::DeflateDecoder::new(data);+ raw.read_to_end(&mut out).map_err(|e| format!("deflate: {e}"))?;+ Ok(out)+ }++ pub fn inflate_brotli(data: &[u8]) -> Result<Vec<u8>, String> {+ let mut dec = brotli::Decompressor::new(data, 4096);+ let mut out = Vec::new();+ dec.read_to_end(&mut out).map_err(|e| format!("brotli: {e}"))?;+ Ok(out)+ }+}++/// Undo a `Content-Encoding` header value (codings apply in order, so they are undone in reverse).+/// Unknown codings leave the body as it is, like Chromium.+pub fn decode(encoding: &str, mut body: Vec<u8>) -> Result<Vec<u8>, String> {+ for coding in encoding.split(',').rev().map(|c| c.trim().to_ascii_lowercase()) {+ if body.is_empty() {+ break;+ }+ body = match coding.as_str() {+ "gzip" | "x-gzip" => imp::gunzip(&body)?,+ "deflate" => imp::inflate_http_deflate(&body)?,+ "br" => imp::inflate_brotli(&body)?,+ _ => body,+ };+ }+ Ok(body)+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn gzip_and_deflate() {+ // zlib.gzipSync('hello hello hello')+ let gz = [0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xcb, 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0xc8, 0x40, 0x90, 0x00, 0x80, 0x88, 0xf9, 0xe5, 0x11, 0x00, 0x00, 0x00];+ assert_eq!(decode("gzip", gz.to_vec()).unwrap(), b"hello hello hello");+ // zlib.deflateSync('hello hello hello')+ let z = [0x78, 0x9c, 0xcb, 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0xc8, 0x40, 0x90, 0x00, 0x3a, 0x2e, 0x06, 0x7d];+ assert_eq!(decode("deflate", z.to_vec()).unwrap(), b"hello hello hello");+ // zlib.brotliCompressSync('hello hello hello')+ let br = [0x1b, 0x10, 0x00, 0xf8, 0x8d, 0x94, 0x6e, 0xde, 0x44, 0x55, 0x86, 0x96, 0x6c, 0x20, 0x6f, 0x01, 0x4f, 0x1c, 0x60, 0x1c];+ assert_eq!(decode("br", br.to_vec()).unwrap(), b"hello hello hello");+ assert!(decode("gzip", b"garbage!garbage!garbage!".to_vec()).is_err());+ }+}diff --git a/runtime/crates/net/src/http.rs b/runtime/crates/net/src/http.rsnew file mode 100644index 0000000..f81205e--- /dev/null+++ b/runtime/crates/net/src/http.rs@@ -0,0 +1,573 @@+//! A small blocking HTTP/1.1 client for `fetch`: keep-alive pool, redirects with the Fetch+//! standard's rules, chunked bodies and content decoding. Runs on worker threads.++use std::io::{Read, Write};+use std::sync::Mutex;+use std::time::{Duration, Instant};++use crate::conn::{self, Cancel, Conn, Endpoint, NetError, Purpose, Stream};++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum RedirectMode {+ Follow,+ Error,+ Manual,+}++pub struct Request {+ pub method: String,+ pub url: String,+ /// Header names and values as Latin-1 byte strings, in the page's order.+ pub headers: Vec<(String, String)>,+ pub body: Option<Vec<u8>>,+ pub redirect: RedirectMode,+}++pub struct Head {+ pub status: u16,+ pub status_text: String,+ /// Lower-case names, in arrival order (`set-cookie` removed, as in browsers).+ pub headers: Vec<(String, String)>,+ pub url: String,+ pub redirected: bool,+ /// `redirect: "manual"` met a redirect: an opaque-redirect response.+ pub opaque_redirect: bool,+}++/// A parsed absolute http(s) URL (the page already normalised it with its URL class).+#[derive(Clone, Debug)]+pub struct Url {+ pub ep: Endpoint,+ /// path + query, never empty, no fragment+ pub target: String,+}++impl Url {+ pub fn parse(s: &str) -> Result<Url, NetError> {+ let bad = || NetError::new("ERR_INVALID_URL", s.to_string());+ let (scheme, rest) = s.split_once("://").ok_or_else(bad)?;+ let tls = match scheme.to_ascii_lowercase().as_str() {+ "http" | "ws" => false,+ "https" | "wss" => true,+ _ => return Err(NetError::new("ERR_UNKNOWN_URL_SCHEME", s.to_string())),+ };+ let rest = rest.split('#').next().unwrap_or("");+ let end = rest.find(['/', '?']).unwrap_or(rest.len());+ let authority = rest[..end].rsplit('@').next().unwrap_or("");+ let mut target = rest[end..].to_string();+ if !target.starts_with('/') {+ target.insert(0, '/');+ }+ let (host, port) = if let Some(h) = authority.strip_prefix('[') {+ let (h, p) = h.split_once(']').ok_or_else(bad)?;+ (h.to_string(), p.strip_prefix(':').unwrap_or(""))+ } else {+ match authority.rsplit_once(':') {+ Some((h, p)) => (h.to_string(), p),+ None => (authority.to_string(), ""),+ }+ };+ if host.is_empty() {+ return Err(bad());+ }+ let port = if port.is_empty() { if tls { 443 } else { 80 } } else { port.parse().map_err(|_| bad())? };+ Ok(Url { ep: Endpoint { tls, host: host.to_ascii_lowercase(), port }, target })+ }++ pub fn origin(&self) -> String {+ format!("{}://{}", if self.ep.tls { "https" } else { "http" }, self.ep.authority(false))+ }++ pub fn href(&self) -> String {+ format!("{}{}", self.origin(), self.target)+ }++ /// Resolve a `Location` header against this URL.+ pub fn join(&self, loc: &str) -> Option<String> {+ let loc = loc.trim();+ let loc = loc.split('#').next().unwrap_or("");+ let has_scheme = loc.find(':').is_some_and(|i| {+ i > 0 && loc[..i].bytes().all(|b| b.is_ascii_alphanumeric() || b == b'+' || b == b'-' || b == b'.') && loc.as_bytes()[0].is_ascii_alphabetic()+ });+ let abs = if has_scheme {+ loc.to_string()+ } else if loc.starts_with("//") {+ format!("{}:{loc}", if self.ep.tls { "https" } else { "http" })+ } else if loc.starts_with('/') {+ format!("{}{}", self.origin(), normalize(loc))+ } else if loc.starts_with('?') {+ let path = self.target.split('?').next().unwrap_or("/");+ format!("{}{path}{loc}", self.origin())+ } else if loc.is_empty() {+ self.href()+ } else {+ let path = self.target.split('?').next().unwrap_or("/");+ let dir = &path[..path.rfind('/').map(|i| i + 1).unwrap_or(0)];+ format!("{}{}", self.origin(), normalize(&format!("{dir}{loc}")))+ };+ Some(percent_encode_non_ascii(&abs))+ }+}++/// Resolve `.` and `..` segments in the path part.+fn normalize(path_and_query: &str) -> String {+ let (path, query) = match path_and_query.find('?') {+ Some(i) => path_and_query.split_at(i),+ None => (path_and_query, ""),+ };+ let mut out: Vec<&str> = Vec::new();+ let segs: Vec<&str> = path.split('/').skip(1).collect();+ for (i, seg) in segs.iter().enumerate() {+ let last = i + 1 == segs.len();+ match *seg {+ "." => {+ if last {+ out.push("");+ }+ }+ ".." => {+ out.pop();+ if last {+ out.push("");+ }+ }+ s => out.push(s),+ }+ }+ format!("/{}{query}", out.join("/"))+}++fn percent_encode_non_ascii(s: &str) -> String {+ let mut out = String::with_capacity(s.len());+ for b in s.bytes() {+ if b >= 0x80 || b == b' ' || b < 0x20 {+ out.push_str(&format!("%{b:02X}"));+ } else {+ out.push(b as char);+ }+ }+ out+}++// ---------------------------------------------------------------- keep-alive pool++struct Idle {+ key: String,+ stream: Stream,+ since: Instant,+}++static POOL: Mutex<Vec<Idle>> = Mutex::new(Vec::new());+const IDLE_TTL: Duration = Duration::from_secs(30);+const POOL_MAX: usize = 16;++/// The most recently used idle connection for `prefix` (an origin; any proxy route).+fn pool_take(prefix: &str) -> Option<(String, Stream)> {+ let mut pool = POOL.lock().unwrap();+ pool.retain(|c| c.since.elapsed() < IDLE_TTL);+ let matches = |k: &str| k == prefix || k.strip_prefix(prefix).is_some_and(|r| r.starts_with('|'));+ while let Some(i) = pool.iter().rposition(|c| matches(&c.key)) {+ let c = pool.remove(i);+ if conn::idle_socket_alive(c.stream.tcp()) {+ return Some((c.key, c.stream));+ }+ }+ None+}++/// Drop idle connections (the network changed under them).+#[cfg_attr(not(target_os = "macos"), allow(dead_code))]+pub fn clear_pool() {+ POOL.lock().unwrap().clear();+}++fn pool_put(key: String, stream: Stream) {+ let mut pool = POOL.lock().unwrap();+ if pool.len() >= POOL_MAX {+ pool.remove(0);+ }+ pool.push(Idle { key, stream, since: Instant::now() });+}++// ---------------------------------------------------------------- one exchange++enum Framing {+ None,+ Length(u64),+ Chunked,+ UntilClose,+}++struct Response {+ status: u16,+ reason: String,+ headers: Vec<(String, String)>,+ stream: Stream,+ key: String,+ /// bytes read past the head+ buf: Vec<u8>,+ framing: Framing,+ keep_alive: bool,+}++fn latin1(b: &[u8]) -> String {+ b.iter().map(|&c| c as char).collect()+}++fn to_bytes(s: &str) -> Vec<u8> {+ s.chars().map(|c| if (c as u32) < 256 { c as u8 } else { b'?' }).collect()+}++fn header<'a>(h: &'a [(String, String)], name: &str) -> Option<&'a str> {+ h.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str())+}++fn send_request(conn: &mut Conn, url: &Url, method: &str, headers: &[(String, String)], body: Option<&[u8]>) -> std::io::Result<()> {+ let target = if conn.absolute_form { url.href() } else { url.target.clone() };+ let mut head = Vec::with_capacity(512);+ head.extend_from_slice(format!("{method} {target} HTTP/1.1\r\nHost: {}\r\n", url.ep.authority(false)).as_bytes());+ let has = |name: &str| headers.iter().any(|(k, _)| k.eq_ignore_ascii_case(name));+ let (has_ua, has_accept) = (has("user-agent"), has("accept"));+ head.extend_from_slice(b"Connection: keep-alive\r\n");+ if !has_ua {+ head.extend_from_slice(format!("User-Agent: {}\r\n", crate::user_agent()).as_bytes());+ }+ if !has_accept {+ head.extend_from_slice(b"Accept: */*\r\n");+ }+ head.extend_from_slice(b"Accept-Encoding: gzip, deflate, br\r\n");+ for (k, v) in headers {+ head.extend_from_slice(&to_bytes(k));+ head.extend_from_slice(b": ");+ head.extend_from_slice(&to_bytes(v));+ head.extend_from_slice(b"\r\n");+ }+ // Chromium sends a length for every body, and `0` for bodiless POST/PUT/PATCH.+ let needs_len = body.is_some() || matches!(method, "POST" | "PUT" | "PATCH");+ if needs_len {+ head.extend_from_slice(format!("Content-Length: {}\r\n", body.map_or(0, |b| b.len())).as_bytes());+ }+ head.extend_from_slice(b"\r\n");+ let s = &mut conn.stream;+ match body {+ Some(b) if b.len() <= 64 * 1024 => {+ head.extend_from_slice(b);+ s.write_all(&head)?;+ }+ Some(b) => {+ s.write_all(&head)?;+ s.write_all(b)?;+ }+ None => s.write_all(&head)?,+ }+ s.flush()+}++fn read_head(stream: &mut Stream, cancel: &Cancel) -> Result<(u16, String, Vec<(String, String)>, u8, Vec<u8>), NetError> {+ let mut buf: Vec<u8> = Vec::with_capacity(8192);+ let mut chunk = [0u8; 16 * 1024];+ loop {+ let mut hs = [httparse::EMPTY_HEADER; 128];+ let mut r = httparse::Response::new(&mut hs);+ match r.parse(&buf) {+ Ok(httparse::Status::Complete(n)) => {+ let headers = r.headers.iter().map(|h| (h.name.to_ascii_lowercase(), latin1(h.value).trim().to_string())).collect();+ let rest = buf[n..].to_vec();+ return Ok((r.code.unwrap_or(0), r.reason.unwrap_or("").to_string(), headers, r.version.unwrap_or(1), rest));+ }+ Ok(httparse::Status::Partial) => {}+ Err(e) => return Err(NetError::new("ERR_INVALID_HTTP_RESPONSE", e.to_string())),+ }+ if buf.len() > 256 * 1024 {+ return Err(NetError::new("ERR_RESPONSE_HEADERS_TOO_BIG", ""));+ }+ let n = stream.read(&mut chunk).map_err(|e| if cancel.is_cancelled() { NetError::aborted() } else { NetError::io(&e) })?;+ if n == 0 {+ let code = if buf.is_empty() { "ERR_EMPTY_RESPONSE" } else { "ERR_CONNECTION_CLOSED" };+ return Err(NetError::new(code, ""));+ }+ buf.extend_from_slice(&chunk[..n]);+ }+}++/// Send one request and read the response head (1xx responses skipped). A reused connection+/// that fails before any response byte is retried once on a fresh one, as Chromium does.+fn exchange(url: &Url, method: &str, headers: &[(String, String)], body: Option<&[u8]>, cancel: &Cancel) -> Result<Response, NetError> {+ let mut attempt = 0;+ loop {+ attempt += 1;+ cancel.check()?;+ // The pool key includes the proxy route chosen by `connect`; match any route.+ let prefix = format!("{}://{}", if url.ep.tls { "https" } else { "http" }, url.ep.authority(true));+ let pooled = if attempt == 1 { pool_take(&prefix) } else { None };+ let reused = pooled.is_some();+ let mut conn = match pooled {+ Some((key, stream)) => {+ cancel.watch(stream.tcp())?;+ let absolute_form = key.contains("|http-proxy:");+ Conn { stream, absolute_form, key }+ }+ None => conn::connect(&url.ep, Purpose::Http, cancel)?,+ };+ let sent = send_request(&mut conn, url, method, headers, body);+ let head = match sent {+ Ok(()) => read_head(&mut conn.stream, cancel),+ Err(e) => Err(if cancel.is_cancelled() { NetError::aborted() } else { NetError::io(&e) }),+ };+ let (mut status, mut reason, mut hdrs, mut version, mut rest) = match head {+ Ok(h) => h,+ Err(e) if reused && attempt == 1 && e.code != "ERR_ABORTED" => continue,+ Err(e) => return Err(e),+ };+ // 1xx (100 Continue, 103 Early Hints): another head follows.+ while (100..200).contains(&status) && status != 101 {+ let mut more = rest.clone();+ let mut hs = [httparse::EMPTY_HEADER; 128];+ let mut r = httparse::Response::new(&mut hs);+ if let Ok(httparse::Status::Complete(n)) = r.parse(&more) {+ status = r.code.unwrap_or(0);+ reason = r.reason.unwrap_or("").to_string();+ hdrs = r.headers.iter().map(|h| (h.name.to_ascii_lowercase(), latin1(h.value).trim().to_string())).collect();+ version = r.version.unwrap_or(1);+ rest = more.split_off(n);+ } else {+ let (s, rs, h, v, r2) = read_head_more(&mut conn.stream, more, cancel)?;+ (status, reason, hdrs, version, rest) = (s, rs, h, v, r2);+ }+ }+ let conn_hdr = header(&hdrs, "connection").unwrap_or("").to_ascii_lowercase();+ let mut keep_alive = if version == 0 { conn_hdr.contains("keep-alive") } else { !conn_hdr.contains("close") };+ let te = header(&hdrs, "transfer-encoding").unwrap_or("").to_ascii_lowercase();+ let framing = if method == "HEAD" || status == 204 || status == 304 {+ Framing::None+ } else if te.contains("chunked") {+ Framing::Chunked+ } else if let Some(len) = header(&hdrs, "content-length") {+ let first = len.split(',').next().unwrap_or("").trim();+ Framing::Length(first.parse().map_err(|_| NetError::new("ERR_INVALID_HTTP_RESPONSE", "bad content-length"))?)+ } else {+ keep_alive = false;+ Framing::UntilClose+ };+ let key = conn.key.clone();+ return Ok(Response { status, reason, headers: hdrs, stream: conn.stream, key, buf: rest, framing, keep_alive });+ }+}++type HeadParts = (u16, String, Vec<(String, String)>, u8, Vec<u8>);++fn read_head_more(stream: &mut Stream, mut buf: Vec<u8>, cancel: &Cancel) -> Result<HeadParts, NetError> {+ let mut chunk = [0u8; 8192];+ loop {+ let n = stream.read(&mut chunk).map_err(|e| if cancel.is_cancelled() { NetError::aborted() } else { NetError::io(&e) })?;+ if n == 0 {+ return Err(NetError::new("ERR_CONNECTION_CLOSED", ""));+ }+ buf.extend_from_slice(&chunk[..n]);+ let mut hs = [httparse::EMPTY_HEADER; 128];+ let mut r = httparse::Response::new(&mut hs);+ if let Ok(httparse::Status::Complete(n)) = r.parse(&buf) {+ let h = r.headers.iter().map(|h| (h.name.to_ascii_lowercase(), latin1(h.value).trim().to_string())).collect();+ return Ok((r.code.unwrap_or(0), r.reason.unwrap_or("").to_string(), h, r.version.unwrap_or(1), buf[n..].to_vec()));+ }+ }+}++impl Response {+ fn fill(&mut self, cancel: &Cancel) -> Result<usize, NetError> {+ let mut chunk = [0u8; 64 * 1024];+ let n = self.stream.read(&mut chunk).map_err(|e| if cancel.is_cancelled() { NetError::aborted() } else { NetError::io(&e) })?;+ self.buf.extend_from_slice(&chunk[..n]);+ Ok(n)+ }++ /// Read the whole body (still content-encoded) and, when the connection can be reused,+ /// return it to the pool. `limit` caps memory for bodies we only drain.+ fn read_body(mut self, cancel: &Cancel, limit: usize) -> Result<Vec<u8>, NetError> {+ let too_big = || NetError::new("ERR_FILE_TOO_BIG", "");+ let body = match self.framing {+ Framing::None => Vec::new(),+ Framing::Length(n) => {+ let n = usize::try_from(n).map_err(|_| too_big())?;+ if n > limit {+ return Err(too_big());+ }+ self.buf.reserve(n.saturating_sub(self.buf.len()));+ while self.buf.len() < n {+ if self.fill(cancel)? == 0 {+ return Err(NetError::new("ERR_CONTENT_LENGTH_MISMATCH", ""));+ }+ }+ let extra = self.buf.split_off(n);+ if !extra.is_empty() {+ self.keep_alive = false;+ }+ std::mem::take(&mut self.buf)+ }+ Framing::UntilClose => {+ while self.fill(cancel)? > 0 {+ if self.buf.len() > limit {+ return Err(too_big());+ }+ }+ std::mem::take(&mut self.buf)+ }+ Framing::Chunked => {+ let mut out = Vec::new();+ let mut pos = 0;+ loop {+ // chunk-size [; ext] CRLF+ let line_end = loop {+ if let Some(i) = self.buf[pos..].windows(2).position(|w| w == b"\r\n") {+ break pos + i;+ }+ if self.fill(cancel)? == 0 {+ return Err(NetError::new("ERR_INCOMPLETE_CHUNKED_ENCODING", ""));+ }+ };+ let line = latin1(&self.buf[pos..line_end]);+ let size = usize::from_str_radix(line.split(';').next().unwrap_or("").trim(), 16)+ .map_err(|_| NetError::new("ERR_INVALID_CHUNKED_ENCODING", line.clone()))?;+ pos = line_end + 2;+ if size == 0 {+ // trailers, then a blank line+ loop {+ if let Some(i) = self.buf[pos..].windows(2).position(|w| w == b"\r\n") {+ let blank = i == 0;+ pos += i + 2;+ if blank {+ break;+ }+ } else if self.fill(cancel)? == 0 {+ break;+ }+ }+ if pos < self.buf.len() {+ self.keep_alive = false;+ }+ break;+ }+ if out.len() + size > limit {+ return Err(too_big());+ }+ while self.buf.len() < pos + size + 2 {+ if self.fill(cancel)? == 0 {+ return Err(NetError::new("ERR_INCOMPLETE_CHUNKED_ENCODING", ""));+ }+ }+ out.extend_from_slice(&self.buf[pos..pos + size]);+ pos += size + 2;+ // Keep the buffer small for long streams.+ if pos > 1 << 20 {+ self.buf.drain(..pos);+ pos = 0;+ }+ }+ out+ }+ };+ cancel.release();+ if self.keep_alive {+ pool_put(self.key, self.stream);+ }+ Ok(body)+ }+}++// ---------------------------------------------------------------- fetch++const MAX_REDIRECTS: usize = 20;+const MAX_BODY: usize = 1 << 30;++/// Run a request to completion: `on_head` gets the final response head (before the body is+/// read, so the page's `fetch()` resolves as soon as headers arrive), then the decoded body is+/// returned.+pub fn fetch(req: Request, cancel: &Cancel, on_head: impl FnOnce(Head)) -> Result<Vec<u8>, NetError> {+ let mut url = Url::parse(&req.url)?;+ let mut method = req.method.clone();+ let mut headers = req.headers.clone();+ let mut body = req.body.clone();+ let mut redirected = false;+ for hop in 0..=MAX_REDIRECTS {+ let resp = exchange(&url, &method, &headers, body.as_deref(), cancel)?;+ let status = resp.status;+ let location = header(&resp.headers, "location").map(|s| s.to_string());+ if matches!(status, 301 | 302 | 303 | 307 | 308) && location.is_some() {+ let next = url.join(location.as_deref().unwrap_or("")).ok_or_else(|| NetError::new("ERR_INVALID_REDIRECT", ""))?;+ if req.redirect == RedirectMode::Manual {+ let head = Head { status: 0, status_text: String::new(), headers: Vec::new(), url: url.href(), redirected, opaque_redirect: true };+ let _ = resp.read_body(cancel, 64 * 1024);+ on_head(head);+ return Ok(Vec::new());+ }+ if req.redirect == RedirectMode::Error {+ return Err(NetError::new("ERR_UNSAFE_REDIRECT", "redirect mode is \"error\""));+ }+ if hop == MAX_REDIRECTS {+ return Err(NetError::new("ERR_TOO_MANY_REDIRECTS", ""));+ }+ let next_url = Url::parse(&next).map_err(|_| NetError::new("ERR_UNSAFE_REDIRECT", next.clone()))?;+ // Drain small bodies so the connection can be reused; drop it otherwise.+ let _ = resp.read_body(cancel, 64 * 1024);+ if (matches!(status, 301 | 302) && method == "POST") || (status == 303 && method != "GET" && method != "HEAD") {+ method = "GET".into();+ body = None;+ headers.retain(|(k, _)| {+ !matches!(k.to_ascii_lowercase().as_str(), "content-type" | "content-encoding" | "content-language" | "content-location")+ });+ }+ if next_url.origin() != url.origin() {+ headers.retain(|(k, _)| !k.eq_ignore_ascii_case("authorization"));+ }+ url = next_url;+ redirected = true;+ continue;+ }+ let encoding = header(&resp.headers, "content-encoding").map(|s| s.to_string());+ let head = Head {+ status,+ status_text: resp.reason.clone(),+ headers: resp.headers.iter().filter(|(k, _)| k != "set-cookie" && k != "set-cookie2").cloned().collect(),+ url: url.href(),+ redirected,+ opaque_redirect: false,+ };+ on_head(head);+ let raw = resp.read_body(cancel, MAX_BODY)?;+ return match encoding {+ Some(enc) if !raw.is_empty() => crate::decode::decode(&enc, raw).map_err(|e| NetError::new("ERR_CONTENT_DECODING_FAILED", e)),+ _ => Ok(raw),+ };+ }+ Err(NetError::new("ERR_TOO_MANY_REDIRECTS", ""))+}++/// Blocking GET for other crates' worker threads (images, resources): the decoded body of a+/// 2xx response, following redirects.+pub fn get(url: &str) -> Result<Vec<u8>, String> {+ let cancel = Cancel::default();+ let mut status = 0;+ let req = Request { method: "GET".into(), url: url.to_string(), headers: Vec::new(), body: None, redirect: RedirectMode::Follow };+ let body = fetch(req, &cancel, |h| status = h.status).map_err(|e| e.to_string())?;+ if (200..300).contains(&status) { Ok(body) } else { Err(format!("HTTP {status}")) }+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn urls() {+ let u = Url::parse("http://127.0.0.1:8787/api/a/b?x=1#frag").unwrap();+ assert_eq!(u.ep, Endpoint { tls: false, host: "127.0.0.1".into(), port: 8787 });+ assert_eq!(u.target, "/api/a/b?x=1");+ assert_eq!(u.join("/c").unwrap(), "http://127.0.0.1:8787/c");+ assert_eq!(u.join("c?y").unwrap(), "http://127.0.0.1:8787/api/a/c?y");+ assert_eq!(u.join("../d").unwrap(), "http://127.0.0.1:8787/api/d");+ assert_eq!(u.join("//example.com/x").unwrap(), "http://example.com/x");+ assert_eq!(u.join("https://example.com").unwrap(), "https://example.com");+ assert_eq!(u.join("?q=2").unwrap(), "http://127.0.0.1:8787/api/a/b?q=2");+ let v = Url::parse("https://[::1]/").unwrap();+ assert_eq!((v.ep.host.as_str(), v.ep.port, v.ep.authority(false)), ("::1", 443, "[::1]".to_string()));+ assert_eq!(Url::parse("https://example.com?a").unwrap().target, "/?a");+ }+}diff --git a/runtime/crates/net/src/lib.rs b/runtime/crates/net/src/lib.rsnew file mode 100644index 0000000..eb09676--- /dev/null+++ b/runtime/crates/net/src/lib.rs@@ -0,0 +1,426 @@+//! `__native.net`: fetch, WebSocket, clipboard and audio for `runtime/net.ts`.+//!+//! Network I/O runs on worker threads (one per request, one per socket) and never touches+//! JavaScript; results are posted to the main thread and delivered through one page-installed+//! handler, `handler(kind, id, ...)`, unless the page went away meanwhile. Bodies and binary+//! messages cross as ArrayBuffers that adopt the Rust allocation (no copy, no per-byte JS work).++mod audio;+mod clipboard;+mod conn;+mod decode;+mod http;+mod netwatch;+mod proxy;+mod ws;++use std::cell::RefCell;+use std::collections::HashMap;+use std::ffi::c_void;+use std::sync::{Arc, Mutex};++use jsc::{Ctx, Persistent, TypedArrayType, Value};++pub use http::get as http_get;++// Kinds of native → page events (see `runtime/net.ts`).+const FETCH_HEAD: f64 = 1.0;+const FETCH_BODY: f64 = 2.0;+const FETCH_ERROR: f64 = 3.0;+const WS_OPEN: f64 = 10.0;+const WS_TEXT: f64 = 11.0;+const WS_BINARY: f64 = 12.0;+const WS_CLOSE: f64 = 13.0;+const AUDIO_ENDED: f64 = 20.0;++thread_local! {+ static HANDLER: RefCell<Option<Persistent>> = const { RefCell::new(None) };+ static FETCHES: RefCell<HashMap<u32, Arc<conn::Cancel>>> = RefCell::new(HashMap::new());+ static SOCKETS: RefCell<HashMap<u32, Arc<ws::Shared>>> = RefCell::new(HashMap::new());+}++static USER_AGENT: Mutex<String> = Mutex::new(String::new());++/// The page's `navigator.userAgent` (also used for proxy tunnels and `http_get`).+pub fn user_agent() -> String {+ let ua = USER_AGENT.lock().unwrap();+ if ua.is_empty() {+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) ThreeRT/0.1 Safari/605.1.15".into()+ } else {+ ua.clone()+ }+}++#[cfg_attr(not(target_os = "macos"), allow(dead_code))]+pub(crate) fn http_clear_pool() {+ http::clear_pool();+}++/// Ask every open socket to check that its peer is still there (network change, wake).+pub(crate) fn probe_sockets(why: &str) {+ let n = SOCKETS.with(|s| {+ let s = s.borrow();+ for sh in s.values() {+ sh.push(ws::Cmd::Probe);+ }+ s.len()+ });+ if n > 0 {+ eprintln!("[net] {why}: probing {n} WebSocket(s)");+ }+}++fn dispatch(c: Ctx, args: &[Value]) {+ let Some(h) = HANDLER.with(|h| h.borrow().as_ref().map(|p| p.get())) else { return };+ if let Err(e) = c.call(h, None, args) {+ rt::report("net event", &e);+ }+}++/// Run `f` on the main thread with the page context, unless the page changed since `generation`.+fn post_page(generation: u64, f: impl FnOnce(Ctx) + Send + 'static) {+ rt::post(move || {+ if rt::page_gen() == generation {+ if let Some(c) = rt::ctx() {+ f(c);+ }+ }+ });+}++unsafe extern "C" fn free_bytes(bytes: *mut c_void, len: *mut c_void) {+ unsafe { drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(bytes.cast::<u8>(), len as usize))) }+}++/// An ArrayBuffer that adopts `data` (freed by JavaScriptCore's GC).+fn array_buffer(c: Ctx, data: Vec<u8>) -> Value {+ if data.is_empty() {+ return c.typed_array(TypedArrayType::Uint8, 0, &[]).get(c, "buffer");+ }+ let b = data.into_boxed_slice();+ let len = b.len();+ let p = Box::into_raw(b).cast::<u8>();+ let o = unsafe { jsc::JSObjectMakeArrayBufferWithBytesNoCopy(c.0, p.cast(), len, Some(free_bytes), len as *mut c_void, std::ptr::null_mut()) };+ if o.is_null() {+ unsafe { free_bytes(p.cast(), len as *mut c_void) };+ return c.undefined();+ }+ Value(o)+}++/// A JS string as UTF-8 (lone surrogates become U+FFFD, like a USVString).+fn utf8(c: Ctx, v: Value) -> String {+ String::from_utf16_lossy(v.to_js_string(c).utf16())+}++/// Body bytes from a string (UTF-8) or a buffer source.+fn body_bytes(c: Ctx, v: Value) -> Option<Vec<u8>> {+ if v.is_nullish(c) {+ return None;+ }+ if let Some(b) = v.bytes(c) {+ return Some(b.to_vec());+ }+ Some(utf8(c, v).into_bytes())+}++fn arg(a: &[Value], i: usize, c: Ctx) -> Value {+ a.get(i).copied().unwrap_or_else(|| c.undefined())+}++fn string_list(c: Ctx, v: Value) -> Vec<String> {+ if !v.is_array(c) {+ return Vec::new();+ }+ (0..v.len(c)).map(|i| v.at(c, i).to_string(c)).collect()+}++// ---------------------------------------------------------------- fetch++fn start_fetch(c: Ctx, a: &[Value]) -> jsc::NativeResult {+ let id = arg(a, 0, c).to_u32(c);+ let method = arg(a, 1, c).to_string(c);+ let url = arg(a, 2, c).to_string(c);+ let flat = string_list(c, arg(a, 3, c));+ let headers: Vec<(String, String)> = flat.chunks(2).filter(|p| p.len() == 2).map(|p| (p[0].clone(), p[1].clone())).collect();+ let body = body_bytes(c, arg(a, 4, c));+ let redirect = match arg(a, 5, c).to_u32(c) {+ 1 => http::RedirectMode::Error,+ 2 => http::RedirectMode::Manual,+ _ => http::RedirectMode::Follow,+ };+ let req = http::Request { method, url, headers, body, redirect };+ let generation = rt::page_gen();+ let cancel = Arc::new(conn::Cancel::default());+ FETCHES.with(|f| f.borrow_mut().insert(id, cancel.clone()));+ let spawned = std::thread::Builder::new().name("net-fetch".into()).stack_size(512 * 1024).spawn(move || {+ let result = http::fetch(req, &cancel, |head| {+ post_page(generation, move |c| {+ if !FETCHES.with(|f| f.borrow().contains_key(&id)) {+ return;+ }+ let mut hv = Vec::with_capacity(head.headers.len() * 2);+ for (k, v) in &head.headers {+ hv.push(c.str(k));+ hv.push(c.str(v));+ }+ let args = [+ c.num(FETCH_HEAD),+ c.num(id as f64),+ c.num(head.status as f64),+ c.str(&head.status_text),+ c.array(&hv),+ c.str(&head.url),+ c.bool(head.redirected),+ c.bool(head.opaque_redirect),+ ];+ dispatch(c, &args);+ });+ });+ post_page(generation, move |c| {+ if FETCHES.with(|f| f.borrow_mut().remove(&id)).is_none() {+ return;+ }+ match result {+ Ok(body) => {+ let buf = array_buffer(c, body);+ dispatch(c, &[c.num(FETCH_BODY), c.num(id as f64), buf]);+ }+ Err(e) => dispatch(c, &[c.num(FETCH_ERROR), c.num(id as f64), c.str(&e.to_string())]),+ }+ });+ });+ if spawned.is_err() {+ FETCHES.with(|f| f.borrow_mut().remove(&id));+ return Err("could not start a network thread".into());+ }+ Ok(c.undefined())+}++// ---------------------------------------------------------------- WebSocket++fn deliver_ws(id: u32, generation: u64) {+ if rt::page_gen() != generation {+ return;+ }+ let Some(c) = rt::ctx() else { return };+ let Some(sh) = SOCKETS.with(|s| s.borrow().get(&id).cloned()) else { return };+ for ev in sh.take_events() {+ let idv = c.num(id as f64);+ match ev {+ ws::Event::Open { protocol, extensions } => dispatch(c, &[c.num(WS_OPEN), idv, c.str(&protocol), c.str(&extensions)]),+ ws::Event::Text(s) => dispatch(c, &[c.num(WS_TEXT), idv, c.str(&s)]),+ ws::Event::Binary(b) => {+ let buf = array_buffer(c, b);+ dispatch(c, &[c.num(WS_BINARY), idv, buf]);+ }+ ws::Event::Close { code, reason, clean, error } => {+ SOCKETS.with(|s| s.borrow_mut().remove(&id));+ dispatch(c, &[c.num(WS_CLOSE), idv, c.num(code as f64), c.str(&reason), c.bool(clean), c.bool(error)]);+ return;+ }+ }+ }+}++fn ws_open(c: Ctx, a: &[Value]) -> jsc::NativeResult {+ let id = arg(a, 0, c).to_u32(c);+ let params = ws::Params {+ url: arg(a, 1, c).to_string(c),+ protocols: string_list(c, arg(a, 2, c)),+ origin: arg(a, 3, c).to_string(c),+ user_agent: user_agent(),+ accept_language: arg(a, 4, c).to_string(c),+ };+ netwatch::install();+ let generation = rt::page_gen();+ let shared = ws::open(params, move || rt::post(move || deliver_ws(id, generation))).map_err(|e| e.to_string())?;+ SOCKETS.with(|s| s.borrow_mut().insert(id, shared));+ Ok(c.undefined())+}++fn socket(id: u32) -> Option<Arc<ws::Shared>> {+ SOCKETS.with(|s| s.borrow().get(&id).cloned())+}++// ---------------------------------------------------------------- audio++fn audio_events(c: Ctx, v: Value) -> Vec<audio::Ev> {+ let Some(b) = (if v.typed_kind(c) == TypedArrayType::Float64 { v.bytes(c) } else { None }) else { return Vec::new() };+ let nums: Vec<f64> = b.chunks_exact(8).map(|x| f64::from_ne_bytes(x.try_into().unwrap())).collect();+ nums.chunks_exact(5).filter_map(audio::Ev::from_flat).collect()+}++fn deliver_ended() {+ let ids = audio::take_ended();+ let Some(c) = rt::ctx() else { return };+ for id in ids {+ dispatch(c, &[c.num(AUDIO_ENDED), c.num(id as f64)]);+ }+}++// ---------------------------------------------------------------- install++fn reset() {+ HANDLER.with(|h| h.borrow_mut().take());+ for (_, cancel) in FETCHES.with(|f| std::mem::take(&mut *f.borrow_mut())) {+ cancel.cancel();+ }+ for (_, s) in SOCKETS.with(|s| std::mem::take(&mut *s.borrow_mut())) {+ s.teardown();+ }+ audio::reset();+}++/// Define this module's native functions on `__native.net`.+pub fn install(c: Ctx, native: Value) {+ rt::on_reset(reset);+ audio::set_ended_notify(|| rt::post(deliver_ended));+ let net = c.object();+ native.set(c, "net", net);+ let def = |name: &str, f: Value| net.set(c, name, f);++ def("setHandler", c.function(|c, _, a| {+ let f = arg(a, 0, c);+ if !f.is_function(c) {+ return Err("setHandler: not a function".into());+ }+ HANDLER.with(|h| *h.borrow_mut() = Some(Persistent::new(c, f)));+ let ua = arg(a, 1, c);+ if !ua.is_nullish(c) {+ *USER_AGENT.lock().unwrap() = ua.to_string(c);+ }+ Ok(c.undefined())+ }));++ // fetch(id, method, url, [name, value, …], body, redirect: 0 follow | 1 error | 2 manual)+ def("fetch", c.function(|c, _, a| start_fetch(c, a)));+ def("fetchAbort", c.function(|c, _, a| {+ let id = arg(a, 0, c).to_u32(c);+ if let Some(cancel) = FETCHES.with(|f| f.borrow_mut().remove(&id)) {+ cancel.cancel();+ }+ Ok(c.undefined())+ }));++ // wsOpen(id, url, protocols[], origin, acceptLanguage)+ def("wsOpen", c.function(|c, _, a| ws_open(c, a)));+ def("wsSend", c.function(|c, _, a| {+ let id = arg(a, 0, c).to_u32(c);+ let data = arg(a, 1, c);+ let cmd = match data.bytes(c) {+ Some(b) => ws::Cmd::Binary(b.to_vec()),+ None => ws::Cmd::Text(utf8(c, data)),+ };+ if let Some(s) = socket(id) {+ s.push(cmd);+ }+ Ok(c.undefined())+ }));+ def("wsClose", c.function(|c, _, a| {+ let id = arg(a, 0, c).to_u32(c);+ let code = arg(a, 1, c).to_i32(c);+ let frame = (code > 0).then(|| (code as u16, arg(a, 2, c).to_string(c)));+ if let Some(s) = socket(id) {+ s.push(ws::Cmd::Close(frame));+ }+ Ok(c.undefined())+ }));+ // Check every open socket's peer now (network change and wake do this natively; the app or a+ // test may ask too). A peer that does not answer within 5 s is closed with 1006.+ def("probeSockets", c.function(|c, _, _| {+ probe_sockets("page request");+ Ok(c.undefined())+ }));+ def("wsBuffered", c.function(|c, _, a| {+ let id = arg(a, 0, c).to_u32(c);+ let n = socket(id).map_or(0, |s| s.buffered.load(std::sync::atomic::Ordering::Relaxed));+ Ok(c.num(n as f64))+ }));++ // Text <-> UTF-8 without per-byte JavaScript.+ def("utf8Decode", c.function(|c, _, a| {+ let Some(b) = arg(a, 0, c).bytes(c) else { return Ok(c.str("")) };+ let b = b.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(b);+ let s = String::from_utf8_lossy(b).into_owned();+ Ok(c.str(&s))+ }));+ def("utf8Encode", c.function(|c, _, a| {+ let s = utf8(c, arg(a, 0, c));+ Ok(c.typed_array(TypedArrayType::Uint8, s.len(), s.as_bytes()))+ }));++ def("clipboardWrite", c.function(|c, _, a| {+ let s = utf8(c, arg(a, 0, c));+ Ok(c.bool(clipboard::write(&s)))+ }));+ def("clipboardRead", c.function(|c, _, _| Ok(c.str(&clipboard::read()))));++ // audio+ def("audioRate", c.function(|c, _, _| Ok(c.num(audio::sample_rate()))));+ def("audioCreate", c.function(|c, _, _| Ok(c.num(audio::create_context() as f64))));+ def("audioTime", c.function(|c, _, a| Ok(c.num(audio::context_time(arg(a, 0, c).to_u32(c))))));+ def("audioSuspend", c.function(|c, _, a| {+ audio::suspend(arg(a, 0, c).to_u32(c));+ Ok(c.undefined())+ }));+ def("audioResume", c.function(|c, _, a| {+ audio::resume(arg(a, 0, c).to_u32(c));+ Ok(c.undefined())+ }));+ def("audioClose", c.function(|c, _, a| {+ audio::close_context(arg(a, 0, c).to_u32(c));+ Ok(c.undefined())+ }));+ // audioNode(ctx, kind: 1 gain | 2 oscillator) -> id+ def("audioNode", c.function(|c, _, a| {+ let kind = arg(a, 1, c).to_u32(c).clamp(1, 2) as u8;+ Ok(c.num(audio::create_node(arg(a, 0, c).to_u32(c), kind) as f64))+ }));+ // audioConnect(from, to, paramIndex | -1)+ def("audioConnect", c.function(|c, _, a| {+ audio::connect(arg(a, 0, c).to_u32(c), arg(a, 1, c).to_u32(c), arg(a, 2, c).to_i32(c));+ Ok(c.undefined())+ }));+ // audioDisconnect(from, to | 0 for all, paramIndex | -1)+ def("audioDisconnect", c.function(|c, _, a| {+ audio::disconnect(arg(a, 0, c).to_u32(c), arg(a, 1, c).to_u32(c), arg(a, 2, c).to_i32(c));+ Ok(c.undefined())+ }));+ // audioParam(node, index, intrinsic, Float64Array [type, time, value, tau, scheduledAt]*)+ def("audioParam", c.function(|c, _, a| {+ let evs = audio_events(c, arg(a, 3, c));+ audio::set_param(arg(a, 0, c).to_u32(c), arg(a, 1, c).to_u32(c) as usize, arg(a, 2, c).to_num(c) as f32, evs);+ Ok(c.undefined())+ }));+ def("audioParamValue", c.function(|c, _, a| {+ let evs = audio_events(c, arg(a, 0, c));+ Ok(c.num(audio::param_value(&evs, arg(a, 1, c).to_num(c) as f32, arg(a, 2, c).to_num(c)) as f64))+ }));+ def("audioWave", c.function(|c, _, a| {+ let w = match arg(a, 1, c).to_u32(c) {+ 1 => audio::Wave::Square,+ 2 => audio::Wave::Sawtooth,+ 3 => audio::Wave::Triangle,+ _ => audio::Wave::Sine,+ };+ audio::set_wave(arg(a, 0, c).to_u32(c), w);+ Ok(c.undefined())+ }));+ def("audioStart", c.function(|c, _, a| {+ audio::start(arg(a, 0, c).to_u32(c), arg(a, 1, c).to_num(c));+ Ok(c.undefined())+ }));+ def("audioStop", c.function(|c, _, a| {+ audio::stop(arg(a, 0, c).to_u32(c), arg(a, 1, c).to_num(c));+ Ok(c.undefined())+ }));+ def("audioWantEnded", c.function(|c, _, a| {+ audio::want_ended(arg(a, 0, c).to_u32(c));+ Ok(c.undefined())+ }));+ def("audioRelease", c.function(|c, _, a| {+ audio::release(arg(a, 0, c).to_u32(c));+ Ok(c.undefined())+ }));+}diff --git a/runtime/crates/net/src/netwatch.rs b/runtime/crates/net/src/netwatch.rsnew file mode 100644index 0000000..24cb027--- /dev/null+++ b/runtime/crates/net/src/netwatch.rs@@ -0,0 +1,137 @@+//! System events that can silently kill open connections: the primary network changing (Wi-Fi+//! switch, VPN, cable) and the machine waking from sleep.++#[cfg(target_os = "macos")]+mod imp {+ use std::ffi::c_void;+ use std::ptr::null;++ type CFTypeRef = *const c_void;+ type CFStringRef = *const c_void;+ type CFArrayRef = *const c_void;+ type CFRunLoopRef = *const c_void;+ type CFRunLoopSourceRef = *const c_void;++ #[repr(C)]+ struct SCDynamicStoreContext {+ version: isize,+ info: *mut c_void,+ retain: *const c_void,+ release: *const c_void,+ copy_description: *const c_void,+ }++ #[link(name = "CoreFoundation", kind = "framework")]+ unsafe extern "C" {+ static kCFRunLoopCommonModes: CFStringRef;+ static kCFTypeArrayCallBacks: c_void;+ fn CFRunLoopGetMain() -> CFRunLoopRef;+ fn CFRunLoopAddSource(rl: CFRunLoopRef, src: CFRunLoopSourceRef, mode: CFStringRef);+ fn CFStringCreateWithCString(alloc: CFTypeRef, s: *const i8, enc: u32) -> CFStringRef;+ fn CFArrayCreate(alloc: CFTypeRef, values: *const CFTypeRef, n: isize, cb: *const c_void) -> CFArrayRef;+ }++ #[link(name = "SystemConfiguration", kind = "framework")]+ unsafe extern "C" {+ fn SCDynamicStoreCreate(+ alloc: CFTypeRef,+ name: CFStringRef,+ cb: unsafe extern "C" fn(CFTypeRef, CFArrayRef, *mut c_void),+ ctx: *mut SCDynamicStoreContext,+ ) -> CFTypeRef;+ fn SCDynamicStoreSetNotificationKeys(store: CFTypeRef, keys: CFArrayRef, patterns: CFArrayRef) -> u8;+ fn SCDynamicStoreCreateRunLoopSource(alloc: CFTypeRef, store: CFTypeRef, order: isize) -> CFRunLoopSourceRef;+ }++ #[link(name = "IOKit", kind = "framework")]+ unsafe extern "C" {+ fn IORegisterForSystemPower(+ refcon: *mut c_void,+ port: *mut *mut c_void,+ cb: unsafe extern "C" fn(*mut c_void, u32, u32, *mut c_void),+ notifier: *mut u32,+ ) -> u32;+ fn IONotificationPortSetDispatchQueue(port: *mut c_void, queue: *mut c_void);+ fn IOAllowPowerChange(kernel_port: u32, notification_id: isize) -> i32;+ }++ unsafe extern "C" {+ fn dispatch_get_global_queue(identifier: isize, flags: usize) -> *mut c_void;+ }++ const IO_CAN_SYSTEM_SLEEP: u32 = 0xE000_0270;+ const IO_SYSTEM_WILL_SLEEP: u32 = 0xE000_0280;+ const IO_SYSTEM_HAS_POWERED_ON: u32 = 0xE000_0300;++ static mut ROOT_PORT: u32 = 0;++ thread_local! {+ static INSTALLED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };+ }++ fn on_change(why: &str) {+ crate::proxy::invalidate();+ crate::http_clear_pool();+ crate::probe_sockets(why);+ }++ unsafe extern "C" fn store_changed(_store: CFTypeRef, _keys: CFArrayRef, _info: *mut c_void) {+ on_change("network change");+ }++ unsafe extern "C" fn power_changed(_refcon: *mut c_void, _service: u32, msg: u32, arg: *mut c_void) {+ match msg {+ IO_CAN_SYSTEM_SLEEP | IO_SYSTEM_WILL_SLEEP => unsafe {+ IOAllowPowerChange(ROOT_PORT, arg as isize);+ },+ IO_SYSTEM_HAS_POWERED_ON => rt::post(|| on_change("wake")),+ _ => {}+ }+ }++ pub fn install() {+ if INSTALLED.with(|i| i.replace(true)) {+ return;+ }+ unsafe {+ let main = CFRunLoopGetMain();+ let cfstr = |s: &std::ffi::CStr| CFStringCreateWithCString(null(), s.as_ptr(), 0x0800_0100);+ let keys = [+ cfstr(c"State:/Network/Global/IPv4"),+ cfstr(c"State:/Network/Global/IPv6"),+ cfstr(c"State:/Network/Global/Proxies"),+ ];+ let mut ctx = SCDynamicStoreContext { version: 0, info: std::ptr::null_mut(), retain: null(), release: null(), copy_description: null() };+ let store = SCDynamicStoreCreate(null(), cfstr(c"threert.net"), store_changed, &mut ctx);+ if !store.is_null() {+ let arr = CFArrayCreate(null(), keys.as_ptr(), keys.len() as isize, &kCFTypeArrayCallBacks);+ SCDynamicStoreSetNotificationKeys(store, arr, null());+ let src = SCDynamicStoreCreateRunLoopSource(null(), store, 0);+ if !src.is_null() {+ CFRunLoopAddSource(main, src, kCFRunLoopCommonModes);+ }+ } else {+ eprintln!("[net] could not watch network changes");+ }+ let mut port: *mut c_void = std::ptr::null_mut();+ let mut notifier: u32 = 0;+ let root = IORegisterForSystemPower(std::ptr::null_mut(), &mut port, power_changed, &mut notifier);+ if root != 0 && !port.is_null() {+ ROOT_PORT = root;+ IONotificationPortSetDispatchQueue(port, dispatch_get_global_queue(0, 0));+ } else {+ eprintln!("[net] could not register for wake notifications");+ }+ }+ }+}++#[cfg(not(target_os = "macos"))]+mod imp {+ pub fn install() {}+}++/// Main thread, once per process.+pub fn install() {+ imp::install();+}diff --git a/runtime/crates/net/src/proxy.rs b/runtime/crates/net/src/proxy.rsnew file mode 100644index 0000000..c3178ff--- /dev/null+++ b/runtime/crates/net/src/proxy.rs@@ -0,0 +1,532 @@+//! Proxy resolution like Chromium on macOS: the system settings (System Settings › Network ›+//! Proxies, including PAC files and the bypass list) through CFNetwork, falling back to the+//! `HTTPS_PROXY` / `HTTP_PROXY` / `ALL_PROXY` environment variables when the system has none.+//! Loopback never goes through a proxy (checked by the caller).++use std::collections::HashMap;+use std::sync::Mutex;+use std::time::{Duration, Instant};++use crate::conn::Endpoint;++#[derive(Clone, Debug, PartialEq, Eq)]+pub enum Proxy {+ Direct,+ Http(String, u16),+ Socks(String, u16),+}++/// Decisions are cached per scheme+host+port (PAC scripts can be slow) until the network changes.+static CACHE: Mutex<Option<HashMap<String, (Instant, Vec<Proxy>)>>> = Mutex::new(None);+const CACHE_TTL: Duration = Duration::from_secs(300);++/// Forget cached decisions (network or proxy settings changed).+#[cfg_attr(not(target_os = "macos"), allow(dead_code))]+pub fn invalidate() {+ *CACHE.lock().unwrap() = None;+}++pub fn for_endpoint(ep: &Endpoint) -> Vec<Proxy> {+ let scheme = if ep.tls { "https" } else { "http" };+ let url = format!("{scheme}://{}/", ep.authority(false));+ if let Some((at, v)) = CACHE.lock().unwrap().as_ref().and_then(|c| c.get(&url)) {+ if at.elapsed() < CACHE_TTL {+ return v.clone();+ }+ }+ // Like Chromium, a direct connection is only tried when the configuration lists it (the system+ // resolver says so explicitly; PAC files say `DIRECT`); an empty answer means direct.+ let mut v = system::proxies_for(&url).unwrap_or_default();+ if v.iter().all(|p| *p == Proxy::Direct) {+ v = from_env(ep).into_iter().collect();+ }+ if v.is_empty() {+ v.push(Proxy::Direct);+ }+ v.dedup();+ CACHE.lock().unwrap().get_or_insert_with(HashMap::new).insert(url, (Instant::now(), v.clone()));+ v+}++fn from_env(ep: &Endpoint) -> Option<Proxy> {+ let get = |names: &[&str]| names.iter().find_map(|n| std::env::var(n).ok().filter(|v| !v.trim().is_empty()));+ let raw = if ep.tls { get(&["HTTPS_PROXY", "https_proxy"]) } else { get(&["HTTP_PROXY", "http_proxy"]) }+ .or_else(|| get(&["ALL_PROXY", "all_proxy"]))?;+ if let Some(no) = get(&["NO_PROXY", "no_proxy"]) {+ let host = ep.host.to_ascii_lowercase();+ for pat in no.split(',').map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) {+ if pat == "*" {+ return None;+ }+ let pat = pat.split(':').next().unwrap_or("").trim_start_matches("*.").trim_start_matches('.').to_string();+ if host == pat || host.ends_with(&format!(".{pat}")) {+ return None;+ }+ }+ }+ parse_proxy_url(&raw)+}++fn parse_proxy_url(raw: &str) -> Option<Proxy> {+ let raw = raw.trim();+ let (scheme, rest) = raw.split_once("://").unwrap_or(("http", raw));+ let hostport = rest.split('/').next()?.rsplit('@').next()?;+ let (host, port) = if let Some(h) = hostport.strip_prefix('[') {+ let (h, p) = h.split_once(']')?;+ (h.to_string(), p.strip_prefix(':').and_then(|p| p.parse().ok()))+ } else {+ match hostport.rsplit_once(':') {+ Some((h, p)) => (h.to_string(), p.parse().ok()),+ None => (hostport.to_string(), None),+ }+ };+ if host.is_empty() {+ return None;+ }+ match scheme.to_ascii_lowercase().as_str() {+ "socks5" | "socks5h" | "socks" => Some(Proxy::Socks(host, port.unwrap_or(1080))),+ "http" | "https" => Some(Proxy::Http(host, port.unwrap_or(80))),+ _ => None,+ }+}++#[cfg(target_os = "macos")]+mod system {+ use std::ffi::c_void;+ use super::*;++ type CFTypeRef = *const c_void;+ type CFStringRef = *const c_void;+ type CFDictionaryRef = *const c_void;+ type CFArrayRef = *const c_void;+ type CFURLRef = *const c_void;+ type CFNumberRef = *const c_void;+ type CFErrorRef = *const c_void;+ type CFRunLoopRef = *const c_void;+ type CFRunLoopSourceRef = *const c_void;+ const UTF8: u32 = 0x0800_0100;++ #[repr(C)]+ struct CFStreamClientContext {+ version: isize,+ info: *mut c_void,+ retain: *const c_void,+ release: *const c_void,+ copy_description: *const c_void,+ }++ #[link(name = "CoreFoundation", kind = "framework")]+ unsafe extern "C" {+ static kCFRunLoopDefaultMode: CFStringRef;+ fn CFRelease(cf: CFTypeRef);+ fn CFEqual(a: CFTypeRef, b: CFTypeRef) -> u8;+ fn CFGetTypeID(cf: CFTypeRef) -> usize;+ fn CFStringGetTypeID() -> usize;+ fn CFNumberGetTypeID() -> usize;+ fn CFStringGetCString(s: CFStringRef, buf: *mut u8, size: isize, enc: u32) -> u8;+ fn CFURLCreateWithBytes(alloc: CFTypeRef, bytes: *const u8, len: isize, enc: u32, base: CFURLRef) -> CFURLRef;+ fn CFDictionaryGetValue(d: CFDictionaryRef, key: CFTypeRef) -> CFTypeRef;+ fn CFArrayGetCount(a: CFArrayRef) -> isize;+ fn CFArrayGetValueAtIndex(a: CFArrayRef, i: isize) -> CFTypeRef;+ fn CFNumberGetValue(n: CFNumberRef, ty: isize, out: *mut c_void) -> u8;+ fn CFRunLoopGetCurrent() -> CFRunLoopRef;+ fn CFRunLoopAddSource(rl: CFRunLoopRef, src: CFRunLoopSourceRef, mode: CFStringRef);+ fn CFRunLoopRemoveSource(rl: CFRunLoopRef, src: CFRunLoopSourceRef, mode: CFStringRef);+ fn CFRunLoopRunInMode(mode: CFStringRef, seconds: f64, return_after_source_handled: u8) -> i32;+ fn CFRunLoopSourceInvalidate(src: CFRunLoopSourceRef);+ }++ #[link(name = "CFNetwork", kind = "framework")]+ unsafe extern "C" {+ static kCFProxyTypeKey: CFStringRef;+ static kCFProxyHostNameKey: CFStringRef;+ static kCFProxyPortNumberKey: CFStringRef;+ static kCFProxyAutoConfigurationURLKey: CFStringRef;+ static kCFProxyTypeNone: CFStringRef;+ static kCFProxyTypeHTTP: CFStringRef;+ static kCFProxyTypeHTTPS: CFStringRef;+ static kCFProxyTypeSOCKS: CFStringRef;+ static kCFProxyTypeAutoConfigurationURL: CFStringRef;+ fn CFNetworkCopySystemProxySettings() -> CFDictionaryRef;+ fn CFNetworkCopyProxiesForURL(url: CFURLRef, settings: CFDictionaryRef) -> CFArrayRef;+ fn CFNetworkExecuteProxyAutoConfigurationURL(+ pac: CFURLRef,+ target: CFURLRef,+ cb: unsafe extern "C" fn(*mut c_void, CFArrayRef, CFErrorRef),+ ctx: *mut CFStreamClientContext,+ ) -> CFRunLoopSourceRef;+ }++ struct Owned(CFTypeRef);+ impl Drop for Owned {+ fn drop(&mut self) {+ if !self.0.is_null() {+ unsafe { CFRelease(self.0) }+ }+ }+ }++ fn cf_url(s: &str) -> Owned {+ Owned(unsafe { CFURLCreateWithBytes(std::ptr::null(), s.as_ptr(), s.len() as isize, UTF8, std::ptr::null()) })+ }++ fn cf_string(v: CFTypeRef) -> Option<String> {+ if v.is_null() || unsafe { CFGetTypeID(v) != CFStringGetTypeID() } {+ return None;+ }+ let mut buf = vec![0u8; 1024];+ if unsafe { CFStringGetCString(v, buf.as_mut_ptr(), buf.len() as isize, UTF8) } == 0 {+ return None;+ }+ let n = buf.iter().position(|&b| b == 0).unwrap_or(0);+ buf.truncate(n);+ String::from_utf8(buf).ok()+ }++ fn cf_i32(v: CFTypeRef) -> Option<i32> {+ if v.is_null() || unsafe { CFGetTypeID(v) != CFNumberGetTypeID() } {+ return None;+ }+ let mut out: i32 = 0;+ // kCFNumberSInt32Type = 3+ (unsafe { CFNumberGetValue(v, 3, (&mut out as *mut i32).cast()) } != 0).then_some(out)+ }++ fn eq(a: CFTypeRef, b: CFTypeRef) -> bool {+ !a.is_null() && !b.is_null() && unsafe { CFEqual(a, b) } != 0+ }++ /// Translate a CFNetwork proxy list; PAC entries are evaluated (`depth` guards recursion).+ unsafe fn parse_list(list: CFArrayRef, target: &str, depth: u32) -> Vec<Proxy> {+ let mut out = Vec::new();+ if list.is_null() {+ return out;+ }+ unsafe {+ for i in 0..CFArrayGetCount(list) {+ let d = CFArrayGetValueAtIndex(list, i);+ let ty = CFDictionaryGetValue(d, kCFProxyTypeKey);+ let host = cf_string(CFDictionaryGetValue(d, kCFProxyHostNameKey));+ let port = cf_i32(CFDictionaryGetValue(d, kCFProxyPortNumberKey)).filter(|p| *p > 0 && *p < 65536);+ if eq(ty, kCFProxyTypeNone) {+ out.push(Proxy::Direct);+ } else if eq(ty, kCFProxyTypeHTTP) || eq(ty, kCFProxyTypeHTTPS) {+ if let Some(h) = host {+ out.push(Proxy::Http(h, port.unwrap_or(80) as u16));+ }+ } else if eq(ty, kCFProxyTypeSOCKS) {+ if let Some(h) = host {+ out.push(Proxy::Socks(h, port.unwrap_or(1080) as u16));+ }+ } else if eq(ty, kCFProxyTypeAutoConfigurationURL) && depth == 0 {+ let pac = CFDictionaryGetValue(d, kCFProxyAutoConfigurationURLKey);+ let answer = run_pac(pac, target);+ if !answer.is_empty() {+ // The script decided. CFNetwork lists a direct fallback after the PAC entry for+ // when the script cannot be loaded; Chromium only goes direct if the script+ // says DIRECT.+ return answer;+ }+ }+ }+ }+ out+ }++ struct PacResult {+ done: bool,+ proxies: Vec<Proxy>,+ target: String,+ }++ unsafe extern "C" fn pac_done(info: *mut c_void, list: CFArrayRef, err: CFErrorRef) {+ let r = unsafe { &mut *(info as *mut PacResult) };+ if err.is_null() {+ r.proxies = unsafe { parse_list(list, &r.target, 1) };+ }+ r.done = true;+ }++ /// Evaluate a PAC file for `target` on this (worker) thread's run loop.+ unsafe fn run_pac(pac_url: CFURLRef, target: &str) -> Vec<Proxy> {+ if pac_url.is_null() {+ return Vec::new();+ }+ let t = cf_url(target);+ let mut result = PacResult { done: false, proxies: Vec::new(), target: target.to_string() };+ let mut ctx = CFStreamClientContext {+ version: 0,+ info: (&mut result as *mut PacResult).cast(),+ retain: std::ptr::null(),+ release: std::ptr::null(),+ copy_description: std::ptr::null(),+ };+ unsafe {+ let src = CFNetworkExecuteProxyAutoConfigurationURL(pac_url, t.0, pac_done, &mut ctx);+ if src.is_null() {+ return Vec::new();+ }+ let src = Owned(src);+ let rl = CFRunLoopGetCurrent();+ CFRunLoopAddSource(rl, src.0, kCFRunLoopDefaultMode);+ let deadline = Instant::now() + Duration::from_secs(10);+ while !result.done && Instant::now() < deadline {+ CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0, 1);+ }+ CFRunLoopRemoveSource(rl, src.0, kCFRunLoopDefaultMode);+ CFRunLoopSourceInvalidate(src.0);+ }+ result.proxies+ }++ pub fn proxies_for(url: &str) -> Option<Vec<Proxy>> {+ let settings = Owned(unsafe { CFNetworkCopySystemProxySettings() });+ if settings.0.is_null() {+ return None;+ }+ unsafe { proxies_with(settings.0, url) }+ }++ /// Proxies for `url` under a proxy-settings dictionary (the system's, or a test's).+ pub unsafe fn proxies_with(settings: CFDictionaryRef, url: &str) -> Option<Vec<Proxy>> {+ let u = cf_url(url);+ if u.0.is_null() {+ return None;+ }+ unsafe {+ let list = Owned(CFNetworkCopyProxiesForURL(u.0, settings));+ Some(parse_list(list.0, url, 0))+ }+ }++ #[cfg(test)]+ pub mod testing {+ use super::*;+ #[link(name = "CoreFoundation", kind = "framework")]+ unsafe extern "C" {+ static kCFTypeDictionaryKeyCallBacks: c_void;+ static kCFTypeDictionaryValueCallBacks: c_void;+ static kCFTypeArrayCallBacks: c_void;+ fn CFDictionaryCreate(a: CFTypeRef, k: *const CFTypeRef, v: *const CFTypeRef, n: isize, kc: *const c_void, vc: *const c_void) -> CFDictionaryRef;+ fn CFArrayCreate(a: CFTypeRef, v: *const CFTypeRef, n: isize, cb: *const c_void) -> CFArrayRef;+ fn CFStringCreateWithBytes(a: CFTypeRef, b: *const u8, n: isize, enc: u32, ext: u8) -> CFStringRef;+ fn CFNumberCreate(a: CFTypeRef, ty: isize, v: *const c_void) -> CFNumberRef;+ }+ pub enum V<'a> {+ S(&'a str),+ N(i32),+ A(&'a [&'a str]),+ }+ fn s(x: &str) -> CFTypeRef {+ unsafe { CFStringCreateWithBytes(std::ptr::null(), x.as_ptr(), x.len() as isize, UTF8, 0) }+ }+ /// Resolve `url` under settings given as SCDynamicStore keys (leaks a little; tests only).+ pub fn resolve(entries: &[(&str, V)], url: &str) -> Vec<Proxy> {+ unsafe {+ let keys: Vec<CFTypeRef> = entries.iter().map(|(k, _)| s(k)).collect();+ let vals: Vec<CFTypeRef> = entries+ .iter()+ .map(|(_, v)| match v {+ V::S(x) => s(x),+ V::N(n) => CFNumberCreate(std::ptr::null(), 3, (n as *const i32).cast()),+ V::A(xs) => {+ let items: Vec<CFTypeRef> = xs.iter().map(|x| s(x)).collect();+ CFArrayCreate(std::ptr::null(), items.as_ptr(), items.len() as isize, &kCFTypeArrayCallBacks)+ }+ })+ .collect();+ let d = CFDictionaryCreate(std::ptr::null(), keys.as_ptr(), vals.as_ptr(), keys.len() as isize, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);+ proxies_with(d, url).unwrap_or_default()+ }+ }+ }+}++#[cfg(target_os = "linux")]+mod system {+ use std::process::Command;++ use super::*;++ fn gsettings(schema: &str, key: &str) -> Option<String> {+ let out = Command::new("gsettings").args(["get", schema, key]).output().ok()?;+ if !out.status.success() {+ return None;+ }+ String::from_utf8(out.stdout).ok().map(|s| s.trim().to_string())+ }++ pub(super) fn parse_gsettings_str(raw: &str) -> String {+ let s = raw.trim();+ s.strip_prefix('\'')+ .and_then(|s| s.strip_suffix('\''))+ .or_else(|| s.strip_prefix('"').and_then(|s| s.strip_suffix('"')))+ .unwrap_or(s)+ .to_string()+ }++ pub(super) fn parse_gsettings_list(raw: &str) -> Vec<String> {+ let s = raw.trim();+ let inner = s.strip_prefix('[').and_then(|s| s.strip_suffix(']')).unwrap_or(s);+ inner+ .split(',')+ .map(|item| parse_gsettings_str(item).to_ascii_lowercase())+ .filter(|item| !item.is_empty())+ .collect()+ }++ fn url_host_and_tls(url: &str) -> Option<(String, bool)> {+ let (scheme, rest) = url.split_once("://")?;+ let tls = scheme.eq_ignore_ascii_case("https");+ let authority = rest.split('/').next()?;+ let hostport = authority.rsplit('@').next()?;+ let host = if let Some(h) = hostport.strip_prefix('[') {+ h.split_once(']')?.0+ } else {+ hostport.split(':').next().unwrap_or(hostport)+ };+ if host.is_empty() {+ None+ } else {+ Some((host.to_ascii_lowercase(), tls))+ }+ }++ pub(super) fn host_ignored(host: &str, patterns: &[String]) -> bool {+ let host = host.to_ascii_lowercase();+ for pat in patterns {+ if pat == "*" {+ return true;+ }+ if let Some(prefix) = pat.strip_suffix("/8") {+ if let Some((a, _)) = prefix.split_once('.') {+ if host.starts_with(&format!("{a}.")) {+ return true;+ }+ }+ }+ let clean = pat.split(':').next().unwrap_or("").trim_start_matches("*.").trim_start_matches('.');+ if !clean.is_empty() && (host == clean || host.ends_with(&format!(".{clean}"))) {+ return true;+ }+ }+ false+ }++ fn manual_entry(schema: &str) -> Option<(String, u16)> {+ let host = parse_gsettings_str(&gsettings(schema, "host")?);+ let port: u16 = gsettings(schema, "port")?.parse().ok()?;+ if host.is_empty() || port == 0 {+ None+ } else {+ Some((host, port))+ }+ }++ /// Resolve system proxy via GNOME/freedesktop `gsettings` (`org.gnome.system.proxy`),+ /// which Clash Verge, Mihomo Party, FlClash, and GNOME Settings write on Linux desktops.+ pub fn proxies_for(url: &str) -> Option<Vec<Proxy>> {+ let mode = parse_gsettings_str(&gsettings("org.gnome.system.proxy", "mode")?);+ if mode != "manual" {+ return None;+ }+ let (host, tls) = url_host_and_tls(url)?;+ if let Some(raw_ignore) = gsettings("org.gnome.system.proxy", "ignore-hosts") {+ let ignored = parse_gsettings_list(&raw_ignore);+ if host_ignored(&host, &ignored) {+ return Some(vec![Proxy::Direct]);+ }+ }+ let mut out = Vec::new();+ if tls {+ if let Some((h, p)) = manual_entry("org.gnome.system.proxy.https").or_else(|| manual_entry("org.gnome.system.proxy.http")) {+ out.push(Proxy::Http(h, p));+ }+ } else if let Some((h, p)) = manual_entry("org.gnome.system.proxy.http") {+ out.push(Proxy::Http(h, p));+ }+ if let Some((h, p)) = manual_entry("org.gnome.system.proxy.socks") {+ out.push(Proxy::Socks(h, p));+ }+ if out.is_empty() { None } else { Some(out) }+ }+}++#[cfg(not(any(target_os = "macos", target_os = "linux")))]+mod system {+ use super::*;+ pub fn proxies_for(_url: &str) -> Option<Vec<Proxy>> {+ None+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn env_urls() {+ assert_eq!(parse_proxy_url("http://proxy.local:3128"), Some(Proxy::Http("proxy.local".into(), 3128)));+ assert_eq!(parse_proxy_url("socks5://127.0.0.1:1080/"), Some(Proxy::Socks("127.0.0.1".into(), 1080)));+ assert_eq!(parse_proxy_url("user:[email protected]:8080"), Some(Proxy::Http("10.0.0.1".into(), 8080)));+ assert_eq!(parse_proxy_url("http://[::1]:8080"), Some(Proxy::Http("::1".into(), 8080)));+ }+ #[test]+ fn system_lookup_does_not_crash() {+ let _ = system::proxies_for("https://example.com/");+ }+ #[cfg(target_os = "linux")]+ #[test]+ fn linux_gsettings_parsing_and_ignore_hosts() {+ assert_eq!(system::parse_gsettings_str("'manual'"), "manual");+ assert_eq!(system::parse_gsettings_str("'127.0.0.1'"), "127.0.0.1");+ let list = system::parse_gsettings_list("['localhost', '127.0.0.0/8', '*.local', '::1']");+ assert!(system::host_ignored("localhost", &list));+ assert!(system::host_ignored("127.0.0.1", &list));+ assert!(system::host_ignored("box.local", &list));+ assert!(!system::host_ignored("pocket-agents-island.doodlewind.workers.dev", &list));+ }+ #[cfg(target_os = "macos")]+ #[test]+ fn manual_and_pac_settings() {+ use system::testing::{V, resolve};+ let manual = [+ ("HTTPSEnable", V::N(1)),+ ("HTTPSProxy", V::S("10.1.2.3")),+ ("HTTPSPort", V::N(3128)),+ ("HTTPEnable", V::N(1)),+ ("HTTPProxy", V::S("10.4.5.6")),+ ("HTTPPort", V::N(8080)),+ ("ExceptionsList", V::A(&["*.internal", "192.168.0.0/16"])),+ ];+ assert_eq!(resolve(&manual, "https://example.com/"), vec![Proxy::Http("10.1.2.3".into(), 3128)]);+ assert_eq!(resolve(&manual, "http://example.com/"), vec![Proxy::Http("10.4.5.6".into(), 8080)]);+ assert_eq!(resolve(&manual, "https://db.internal/"), vec![Proxy::Direct]);+ let socks = [("SOCKSEnable", V::N(1)), ("SOCKSProxy", V::S("10.7.7.7")), ("SOCKSPort", V::N(1080))];+ assert_eq!(resolve(&socks, "https://example.com/"), vec![Proxy::Socks("10.7.7.7".into(), 1080)]);+ // PAC: fetched and evaluated by CFNetwork on this thread's run loop (served over HTTP; CFNetwork+ // ignores file: PAC URLs).+ let script = r#"function FindProxyForURL(url, host) {+ if (host == "example.com") return "PROXY 10.9.8.7:3128; DIRECT";+ if (dnsDomainIs(host, ".socks.test")) return "SOCKS 10.1.1.1:1080";+ return "DIRECT";+ }"#;+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let port = listener.local_addr().unwrap().port();+ std::thread::spawn(move || {+ use std::io::{Read, Write};+ for mut s in listener.incoming().flatten() {+ let mut buf = [0u8; 4096];+ let _ = s.read(&mut buf);+ let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Type: application/x-ns-proxy-autoconfig\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{script}", script.len());+ }+ });+ let url = format!("http://127.0.0.1:{port}/proxy.pac");+ let auto = [("ProxyAutoConfigEnable", V::N(1)), ("ProxyAutoConfigURLString", V::S(&url))];+ assert_eq!(resolve(&auto, "https://example.com/"), vec![Proxy::Http("10.9.8.7".into(), 3128), Proxy::Direct]);+ assert_eq!(resolve(&auto, "https://a.socks.test/"), vec![Proxy::Socks("10.1.1.1".into(), 1080)]);+ // An unreachable PAC file falls back to CFNetwork's direct entry.+ let dead = [("ProxyAutoConfigEnable", V::N(1)), ("ProxyAutoConfigURLString", V::S("http://127.0.0.1:1/none.pac"))];+ assert_eq!(resolve(&dead, "https://example.com/"), vec![Proxy::Direct]);+ assert_eq!(resolve(&auto, "https://other.org/"), vec![Proxy::Direct]);+ }+}diff --git a/runtime/crates/net/src/ws.rs b/runtime/crates/net/src/ws.rsnew file mode 100644index 0000000..23968a4--- /dev/null+++ b/runtime/crates/net/src/ws.rs@@ -0,0 +1,437 @@+//! WebSocket connections: one I/O thread per socket, asleep in `poll` until the socket is readable,+//! the page queued something to send (a byte on a wake socket), or a liveness deadline passes.+//!+//! The thread owns the tungstenite state machine. Reads are non-blocking (drained until+//! `WouldBlock` after each wake-up) and writes are blocking, so a send never waits on a read and+//! nothing polls. Events go to the main thread through an inbox; a task is posted only when the+//! inbox goes from empty to non-empty, so a burst of frames costs one wake-up.+//!+//! Liveness: Chromium relies on TCP to notice a dead peer, which after sleep or a Wi-Fi change can+//! take minutes. Here a ping goes out after `IDLE_PING` of silence, and right away when the network+//! changes or the machine wakes (`Cmd::Probe`); no answer within the deadline closes the socket+//! with 1006, so the page's reconnect logic runs promptly.++use std::collections::VecDeque;+use std::io::{self, Read, Write};+use std::os::fd::AsRawFd;+use std::os::unix::net::UnixStream;+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use tungstenite::client::IntoClientRequest;+use tungstenite::protocol::frame::coding::CloseCode;+use tungstenite::protocol::{CloseFrame, WebSocketConfig};+use tungstenite::{Message, WebSocket};++use crate::conn::{self, Cancel, NetError, Purpose, Stream};+use crate::http::Url;++const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30);+const IDLE_PING: Duration = Duration::from_secs(30);+const PING_TIMEOUT: Duration = Duration::from_secs(10);+const PROBE_TIMEOUT: Duration = Duration::from_secs(5);+/// How long we wait for the server's close frame after `close()` (Chromium's closing-handshake+/// timeout; then the socket closes with 1006 and no error event).+const CLOSE_TIMEOUT: Duration = Duration::from_secs(60);+/// After the closing handshake the server should drop TCP; Chromium waits 2 s before doing it.+const CLOSE_LINGER: Duration = Duration::from_secs(2);++pub enum Cmd {+ Text(String),+ Binary(Vec<u8>),+ Close(Option<(u16, String)>),+ Probe,+}++pub enum Event {+ Open { protocol: String, extensions: String },+ Text(String),+ Binary(Vec<u8>),+ Close { code: u16, reason: String, clean: bool, error: bool },+}++pub struct Shared {+ cmds: Mutex<VecDeque<Cmd>>,+ /// Bytes queued by `send` and not yet written (WebSocket.bufferedAmount).+ pub buffered: AtomicU64,+ inbox: Mutex<Vec<Event>>,+ cancel: Cancel,+ open: AtomicBool,+ /// The page went away: exit without events.+ teardown: AtomicBool,+ wake_tx: UnixStream,+}++impl Shared {+ pub fn push(&self, cmd: Cmd) {+ match &cmd {+ Cmd::Text(s) => {+ self.buffered.fetch_add(s.len() as u64, Ordering::Relaxed);+ }+ Cmd::Binary(b) => {+ self.buffered.fetch_add(b.len() as u64, Ordering::Relaxed);+ }+ _ => {}+ }+ let close = matches!(cmd, Cmd::Close(_));+ self.cmds.lock().unwrap().push_back(cmd);+ if close {+ // close() while connecting fails the connection; once open, the I/O thread runs the+ // closing handshake.+ self.cancel_if_connecting();+ }+ self.wake();+ }++ fn cancel_if_connecting(&self) {+ if !self.open.load(Ordering::SeqCst) {+ self.cancel.cancel();+ }+ }++ fn wake(&self) {+ // Non-blocking: a full buffer already means "wake up".+ let _ = (&self.wake_tx).write(&[1]);+ }++ /// The page is going away: stop at once (a best-effort 1001 "going away" if open).+ pub fn teardown(&self) {+ self.teardown.store(true, Ordering::SeqCst);+ self.cancel_if_connecting();+ self.wake();+ }++ pub fn take_events(&self) -> Vec<Event> {+ std::mem::take(&mut *self.inbox.lock().unwrap())+ }+}++pub struct Params {+ pub url: String,+ pub protocols: Vec<String>,+ pub origin: String,+ pub user_agent: String,+ pub accept_language: String,+}++/// Open a socket. `notify` runs on the I/O thread whenever events become available; it posts a+/// main-thread task that calls `take_events`.+pub fn open(p: Params, notify: impl Fn() + Send + 'static) -> io::Result<Arc<Shared>> {+ let (wake_tx, wake_rx) = UnixStream::pair()?;+ wake_tx.set_nonblocking(true)?;+ wake_rx.set_nonblocking(true)?;+ let shared = Arc::new(Shared {+ cmds: Mutex::new(VecDeque::new()),+ buffered: AtomicU64::new(0),+ inbox: Mutex::new(Vec::new()),+ cancel: Cancel::default(),+ open: AtomicBool::new(false),+ teardown: AtomicBool::new(false),+ wake_tx,+ });+ let s = shared.clone();+ std::thread::Builder::new().name("net-websocket".into()).stack_size(256 * 1024).spawn(move || {+ let mut io = Io { shared: s, wake_rx, notify: Box::new(notify), pending: Vec::new() };+ io.run(p);+ })?;+ Ok(shared)+}++struct Io {+ shared: Arc<Shared>,+ wake_rx: UnixStream,+ notify: Box<dyn Fn() + Send>,+ pending: Vec<Event>,+}++enum Flow {+ Continue,+ Done(Option<Event>),+}++fn abnormal(error: bool) -> Event {+ Event::Close { code: 1006, reason: String::new(), clean: false, error }+}++impl Io {+ fn emit(&mut self, ev: Event) {+ self.pending.push(ev);+ }++ fn flush_events(&mut self) {+ if self.pending.is_empty() || self.shared.teardown.load(Ordering::SeqCst) {+ self.pending.clear();+ return;+ }+ let was_empty = {+ let mut inbox = self.shared.inbox.lock().unwrap();+ let was_empty = inbox.is_empty();+ inbox.append(&mut self.pending);+ was_empty+ };+ if was_empty {+ (self.notify)();+ }+ }++ fn run(&mut self, p: Params) {+ let ws = match self.connect(&p) {+ Ok(ws) => ws,+ Err(e) => {+ if !self.shared.teardown.load(Ordering::SeqCst) {+ if !self.shared.cancel.is_cancelled() {+ eprintln!("[net] WebSocket connection to '{}' failed: {e}", p.url);+ }+ self.emit(abnormal(true));+ self.flush_events();+ }+ return;+ }+ };+ self.session(ws);+ self.flush_events();+ }++ fn connect(&mut self, p: &Params) -> Result<WebSocket<Stream>, NetError> {+ let url = Url::parse(&p.url)?;+ let conn = conn::connect(&url.ep, Purpose::WebSocket, &self.shared.cancel)?;+ let stream = conn.stream;+ let _ = stream.tcp().set_read_timeout(Some(HANDSHAKE_TIMEOUT));++ let bad = |e: tungstenite::Error| NetError::new("ERR_INVALID_URL", e.to_string());+ let mut req = p.url.as_str().into_client_request().map_err(bad)?;+ let h = req.headers_mut();+ let mut put = |k: &'static str, v: &str| {+ if let Ok(v) = v.parse() {+ h.insert(k, v);+ }+ };+ put("Pragma", "no-cache");+ put("Cache-Control", "no-cache");+ put("User-Agent", &p.user_agent);+ if !p.origin.is_empty() {+ put("Origin", &p.origin);+ }+ if !p.accept_language.is_empty() {+ put("Accept-Language", &p.accept_language);+ }+ if !p.protocols.is_empty() {+ put("Sec-WebSocket-Protocol", &p.protocols.join(", "));+ }+ let config = WebSocketConfig::default();+ let (mut ws, resp) = match tungstenite::client::client_with_config(req, stream, Some(config)) {+ Ok(r) => r,+ Err(tungstenite::HandshakeError::Failure(e)) => {+ if self.shared.cancel.is_cancelled() {+ return Err(NetError::aborted());+ }+ let detail = match &e {+ tungstenite::Error::Http(r) => format!("Unexpected response code: {}", r.status().as_u16()),+ e => format!("Error during WebSocket handshake: {e}"),+ };+ return Err(NetError::new("ERR_WS_HANDSHAKE", detail));+ }+ Err(tungstenite::HandshakeError::Interrupted(_)) => return Err(NetError::new("ERR_TIMED_OUT", "handshake timed out")),+ };+ let header = |name: &str| resp.headers().get(name).and_then(|v| v.to_str().ok()).unwrap_or("").to_string();+ let protocol = header("sec-websocket-protocol");+ let extensions = header("sec-websocket-extensions");+ if !extensions.is_empty() {+ // We offered none; an extension we cannot speak would corrupt every frame.+ return Err(NetError::new("ERR_WS_HANDSHAKE", "server selected an extension that was not offered"));+ }+ // From here on, reads are drained without blocking; writes still block (bounded).+ let sock = ws.get_mut().sock_mut();+ sock.set_nonblocking_reads(true);+ let _ = sock.tcp.set_read_timeout(None);+ self.shared.cancel.release();+ self.shared.open.store(true, Ordering::SeqCst);+ if self.shared.cancel.is_cancelled() {+ return Err(NetError::aborted());+ }+ self.emit(Event::Open { protocol, extensions });+ self.flush_events();+ Ok(ws)+ }++ fn session(&mut self, mut ws: WebSocket<Stream>) {+ let sock_fd = ws.get_ref().tcp().as_raw_fd();+ let wake_fd = self.wake_rx.as_raw_fd();+ let mut st = State { last_rx: Instant::now(), ping_deadline: None, close_deadline: None, peer_close: None, we_closed: false };+ // Frames may have arrived together with the handshake response.+ let mut readable = true;+ loop {+ if self.shared.teardown.load(Ordering::SeqCst) {+ if !st.we_closed && st.peer_close.is_none() {+ let _ = ws.close(Some(CloseFrame { code: CloseCode::Away, reason: "".into() }));+ }+ return;+ }+ if readable {+ if let Flow::Done(ev) = self.drain_reads(&mut ws, &mut st) {+ if let Some(ev) = ev {+ self.emit(ev);+ }+ return;+ }+ }+ if let Flow::Done(ev) = self.run_commands(&mut ws, &mut st) {+ if let Some(ev) = ev {+ self.emit(ev);+ }+ return;+ }+ self.flush_events();++ let now = Instant::now();+ let mut deadline = st.ping_deadline.unwrap_or(st.last_rx + IDLE_PING);+ if let Some(c) = st.close_deadline {+ deadline = deadline.min(c);+ }+ let wait = deadline.saturating_duration_since(now);+ let timeout = if wait.is_zero() { 0 } else { (wait.as_millis() as i32).saturating_add(1) };+ let mut fds = [+ libc::pollfd { fd: sock_fd, events: libc::POLLIN, revents: 0 },+ libc::pollfd { fd: wake_fd, events: libc::POLLIN, revents: 0 },+ ];+ let n = unsafe { libc::poll(fds.as_mut_ptr(), 2, timeout) };+ if n < 0 {+ let e = io::Error::last_os_error();+ if e.kind() == io::ErrorKind::Interrupted {+ continue;+ }+ self.emit(abnormal(true));+ return;+ }+ readable = fds[0].revents != 0;+ if fds[1].revents != 0 {+ let mut sink = [0u8; 64];+ while matches!((&self.wake_rx).read(&mut sink), Ok(n) if n > 0) {}+ }++ let now = Instant::now();+ if st.close_deadline.is_some_and(|c| now >= c) {+ // Closing handshake done but the server kept TCP open: clean. No reply: 1006.+ let ev = match st.peer_close.take() {+ Some((code, reason)) => Event::Close { code, reason, clean: true, error: false },+ None => abnormal(false),+ };+ self.emit(ev);+ return;+ }+ if st.ping_deadline.is_some_and(|p| now >= p) && !readable {+ eprintln!("[net] WebSocket peer stopped answering; closing");+ self.emit(abnormal(true));+ return;+ }+ if st.ping_deadline.is_none() && st.close_deadline.is_none() && now >= st.last_rx + IDLE_PING {+ if ws.send(Message::Ping(Default::default())).is_err() {+ self.emit(abnormal(true));+ return;+ }+ st.ping_deadline = Some(now + PING_TIMEOUT);+ }+ }+ }++ fn drain_reads(&mut self, ws: &mut WebSocket<Stream>, st: &mut State) -> Flow {+ loop {+ match ws.read() {+ Ok(msg) => {+ st.last_rx = Instant::now();+ st.ping_deadline = None;+ match msg {+ Message::Text(t) => self.emit(Event::Text(t.as_str().to_owned())),+ Message::Binary(b) => self.emit(Event::Binary(b.to_vec())),+ Message::Close(frame) => {+ st.peer_close = Some(frame.map(|f| (u16::from(f.code), f.reason.as_str().to_owned())).unwrap_or((1005, String::new())));+ st.close_deadline = Some(st.last_rx + CLOSE_LINGER);+ }+ Message::Ping(_) | Message::Pong(_) | Message::Frame(_) => {}+ }+ }+ Err(tungstenite::Error::Io(e)) if e.kind() == io::ErrorKind::WouldBlock => return Flow::Continue,+ Err(tungstenite::Error::ConnectionClosed | tungstenite::Error::AlreadyClosed) => {+ let (code, reason) = st.peer_close.take().unwrap_or((1005, String::new()));+ return Flow::Done(Some(Event::Close { code, reason, clean: true, error: false }));+ }+ Err(e) => {+ // A reset after both close frames were exchanged is still a clean close.+ if let Some((code, reason)) = st.peer_close.take() {+ return Flow::Done(Some(Event::Close { code, reason, clean: true, error: false }));+ }+ if !matches!(e, tungstenite::Error::Protocol(tungstenite::error::ProtocolError::ResetWithoutClosingHandshake)) {+ eprintln!("[net] WebSocket error: {e}");+ }+ return Flow::Done(Some(abnormal(true)));+ }+ }+ }+ }++ fn run_commands(&mut self, ws: &mut WebSocket<Stream>, st: &mut State) -> Flow {+ loop {+ let Some(cmd) = self.shared.cmds.lock().unwrap().pop_front() else { return Flow::Continue };+ let closing = st.we_closed || st.peer_close.is_some();+ let result = match cmd {+ Cmd::Text(s) => {+ let n = s.len() as u64;+ let r = if closing { Ok(()) } else { ws.send(Message::text(s)) };+ self.shared.buffered.fetch_sub(n, Ordering::Relaxed);+ r+ }+ Cmd::Binary(b) => {+ let n = b.len() as u64;+ let r = if closing { Ok(()) } else { ws.send(Message::binary(b)) };+ self.shared.buffered.fetch_sub(n, Ordering::Relaxed);+ r+ }+ Cmd::Close(frame) => {+ if closing {+ Ok(())+ } else {+ st.we_closed = true;+ st.close_deadline = Some(Instant::now() + CLOSE_TIMEOUT);+ st.ping_deadline = None;+ let frame = frame.map(|(code, reason)| CloseFrame { code: CloseCode::from(code), reason: reason.into() });+ ws.close(frame)+ }+ }+ Cmd::Probe => {+ let now = Instant::now();+ if closing {+ Ok(())+ } else if let Some(p) = st.ping_deadline {+ st.ping_deadline = Some(p.min(now + PROBE_TIMEOUT));+ Ok(())+ } else {+ st.ping_deadline = Some(now + PROBE_TIMEOUT);+ ws.send(Message::Ping(Default::default()))+ }+ }+ };+ match result {+ Ok(()) | Err(tungstenite::Error::Protocol(tungstenite::error::ProtocolError::SendAfterClosing)) => {}+ Err(tungstenite::Error::ConnectionClosed | tungstenite::Error::AlreadyClosed) => {+ let (code, reason) = st.peer_close.take().unwrap_or((1005, String::new()));+ return Flow::Done(Some(Event::Close { code, reason, clean: true, error: false }));+ }+ Err(e) => {+ eprintln!("[net] WebSocket send failed: {e}");+ return Flow::Done(Some(abnormal(true)));+ }+ }+ }+ }+}++struct State {+ last_rx: Instant,+ /// A ping is outstanding; the peer is dead if nothing arrives by then.+ ping_deadline: Option<Instant>,+ close_deadline: Option<Instant>,+ /// The peer's close frame (code, reason).+ peer_close: Option<(u16, String)>,+ we_closed: bool,+}diff --git a/runtime/crates/pocket-host/Cargo.toml b/runtime/crates/pocket-host/Cargo.tomlnew file mode 100644index 0000000..7d74ec1--- /dev/null+++ b/runtime/crates/pocket-host/Cargo.toml@@ -0,0 +1,21 @@+[package]+name = "threert-pocket-host"+description = "ThreeRT PocketJS UI host: runtime, JavaScriptCore guest, wgpu display and CoreText text"+version.workspace = true+edition.workspace = true+license.workspace = true++[dependencies]+pocket-runtime.workspace = true+pocket-drivers.workspace = true+pocket-package.workspace = true+pocket-guest-jsc.workspace = true+pocket-wgpu-render.workspace = true+pocketjs-core.workspace = true+wgpu.workspace = true+canvas2d.workspace = true+serde_json = "1"+log = "0.4"++[dev-dependencies]+pollster = "0.4"diff --git a/runtime/crates/pocket-host/src/display.rs b/runtime/crates/pocket-host/src/display.rsnew file mode 100644index 0000000..80c0fbb--- /dev/null+++ b/runtime/crates/pocket-host/src/display.rs@@ -0,0 +1,92 @@+//! The window's current drawable as the runtime's primary display.+//!+//! Each frame the host hands the display the texture the window presents next+//! ([`SurfaceDisplay::set_frame`]); the runtime's present then draws the UI's+//! DrawList into it on top of what the game drew (or over a clear colour when+//! the game drew nothing), and the host presents the drawable.++use std::cell::RefCell;+use std::rc::Rc;++use pocket_drivers::target::{RendererCell, TargetSlot};+use pocket_drivers::{+ DisplayDescriptor, DisplayError, DisplayOutput, DisplayRole, PixelFormat, Rect, Target,+ TargetOwnership, VsyncSource,+};+use pocket_wgpu_render::{TargetConfig, WgpuRenderer};++pub(crate) struct DisplayState {+ pub size: (u32, u32),+ pub scale: f32,+ pub pixel_format: PixelFormat,+ pub target: TargetSlot<WgpuRenderer>,+ pub ready: bool,+ pub pending: Option<u64>,+ pub next_token: u64,+}++impl DisplayState {+ pub fn new(renderer: &RendererCell<WgpuRenderer>, size: (u32, u32), scale: f32, pixel_format: PixelFormat) -> Self {+ DisplayState { size, scale, pixel_format, target: TargetSlot::new(renderer.port()), ready: false, pending: None, next_token: 0 }+ }+ /// Draw the next present into `view` (`size` device px), loading what it holds or clearing it.+ pub fn set_frame(&mut self, view: &wgpu::TextureView, size: (u32, u32), scale: f32, clear: Option<wgpu::Color>) -> Result<(), String> {+ if self.pending.is_some() {+ return Err("display transfer is still pending".into());+ }+ self.size = size;+ self.scale = scale;+ let load = match clear {+ Some(color) => wgpu::LoadOp::Clear(color),+ None => wgpu::LoadOp::Load,+ };+ self.target.replace(TargetConfig::new(view, size, scale, load)).map_err(|e| format!("wgpu target: {e:?}"))?;+ self.ready = true;+ Ok(())+ }+}++pub(crate) struct SurfaceDisplay(pub Rc<RefCell<DisplayState>>);++impl DisplayOutput for SurfaceDisplay {+ type Token = u64;+ fn descriptor(&self) -> DisplayDescriptor {+ let state = self.0.borrow();+ DisplayDescriptor::new(DisplayRole::Primary, state.size.0, state.size.1, state.pixel_format, state.size.0 as usize * 4, TargetOwnership::DeviceOwned)+ }+ fn acquire(&mut self, region: Rect) -> Result<Target<'_>, DisplayError> {+ let state = self.0.borrow();+ if state.pending.is_some() || !state.ready {+ return Err(DisplayError::InvalidTarget);+ }+ let target = state.target.target().map_err(|_| DisplayError::InvalidTarget)?;+ if target.region != region {+ return Err(DisplayError::InvalidTarget);+ }+ Ok(Target::DeviceOwned(target))+ }+ fn flush(&mut self, _: &[Rect]) -> Result<u64, DisplayError> {+ let mut state = self.0.borrow_mut();+ if state.pending.is_some() || !state.ready {+ return Err(DisplayError::InvalidTarget);+ }+ state.next_token = state.next_token.checked_add(1).ok_or(DisplayError::Failed)?;+ let token = state.next_token;+ state.pending = Some(token);+ Ok(token)+ }+ fn wait(&mut self, token: u64) -> Result<(), DisplayError> {+ let mut state = self.0.borrow_mut();+ if state.pending != Some(token) {+ return Err(DisplayError::InvalidTarget);+ }+ state.pending = None;+ // the drawable goes to the window after this present; the next frame brings another+ state.ready = false;+ let _ = state.target.release();+ Ok(())+ }+ fn vsync(&mut self) -> VsyncSource {+ VsyncSource::None+ }+}diff --git a/runtime/crates/pocket-host/src/lib.rs b/runtime/crates/pocket-host/src/lib.rsnew file mode 100644index 0000000..67302dd--- /dev/null+++ b/runtime/crates/pocket-host/src/lib.rs@@ -0,0 +1,366 @@+//! ThreeRT PocketJS UI host: one `pocket_runtime::Runtime` whose guest is JavaScriptCore+//! (`pocket-guest-jsc`), whose primary display is the window's drawable (drawn by+//! `pocket-wgpu-render` on the device the game's WebGPU shares), and whose text is the native+//! text path (`text.layout.native`): CoreText measures, wraps and paints the font slots.+//!+//! A frame, driven by the app:+//! 1. [`UiHost::input`] — publish this frame's pointer, scroll and text events;+//! 2. [`UiHost::advance`] — one guest turn: the bundle's `frame` (game update, the game's WebGPU+//! render into the drawable, UI mutations), then the core's tick;+//! 3. [`UiHost::present`] — the UI's DrawList drawn into the same drawable over the game's+//! picture; the app then presents the drawable.++mod display;+mod text;++use std::cell::{Cell, RefCell, RefMut};+use std::rc::Rc;++use pocket_drivers::target::RendererCell;+use pocket_drivers::{InputClasses, InputFrameBuilder, InputSource, PixelFormat, Renderer};+use pocket_guest_jsc::jsc::Ctx;+use pocket_guest_jsc::{JscGuest, Realm};+use pocket_package::source::MemorySource;+use pocket_runtime::generated_ops::BINDING_GENERATION;+use pocket_runtime::{Cow, Profile, Runtime, RuntimeConfig};+use pocket_wgpu_render::WgpuRenderer;++pub use pocket_guest_jsc::jsc;+pub use text::{SlotFont, SlotFonts};++use display::{DisplayState, SurfaceDisplay};++struct StderrLog;+impl log::Log for StderrLog {+ fn enabled(&self, m: &log::Metadata<'_>) -> bool {+ m.level() <= log::max_level()+ }+ fn log(&self, r: &log::Record<'_>) {+ if self.enabled(r.metadata()) {+ eprintln!("[{}] {}", r.level().as_str().to_lowercase(), r.args());+ }+ }+ fn flush(&self) {}+}++/// Route the runtime's and guest's `log` records (warnings and errors; all with `THREERT_TRACE`+/// or `POCKET_TRACE`) to stderr.+pub fn init_logging() {+ static LOG: StderrLog = StderrLog;+ if log::set_logger(&LOG).is_ok() {+ // the level decides at each call site whether a record is built at all: wgpu traces its hot paths+ let verbose = std::env::var_os("THREERT_TRACE").is_some() || std::env::var_os("POCKET_TRACE").is_some();+ log::set_max_level(if verbose { log::LevelFilter::Trace } else { log::LevelFilter::Warn });+ }+}++/// The capabilities this host gives a PocketJS UI bundle.+pub const CAPABILITIES: &[&str] = &[+ "display.viewport.live",+ "host.clipboard",+ "input.buttons",+ "input.cursor",+ "input.ime",+ "input.pointer",+ "input.scroll",+ "input.text",+ "text.layout.native",+];++pub struct HostConfig {+ /// the host id the bundle sees as `ui.__host`+ pub host_id: String,+ /// window size in logical px+ pub logical: [u32; 2],+ /// device px per logical px+ pub scale: f32,+ /// the drawable's format+ pub format: wgpu::TextureFormat,+ /// font slot → face; index = slot number+ pub slots: Vec<Option<SlotFont>>,+}++/// The facts the app published for the next guest turn.+struct Input(Rc<RefCell<InputFrameBuilder>>);++impl InputSource for Input {+ fn classes(&self) -> InputClasses {+ InputClasses::BUTTONS | InputClasses::AXIS_ABSOLUTE | InputClasses::POINTER | InputClasses::CONTACT | InputClasses::TEXT+ }+ fn poll(&mut self, output: &mut InputFrameBuilder) {+ let mut input = self.0.borrow_mut();+ output.buttons |= input.buttons;+ if input.pointer.is_some() {+ output.pointer = input.pointer;+ }+ output.text.append(&mut input.text);+ output.scroll[0] += input.scroll[0];+ output.scroll[1] += input.scroll[1];+ input.scroll = [0.0; 2];+ }+}++pub struct UiHost {+ runtime: Runtime,+ realm: Realm,+ display: Rc<RefCell<DisplayState>>,+ input: Rc<RefCell<InputFrameBuilder>>,+ guest: Option<JscGuest>,+ config: HostConfig,+ fonts: Rc<SlotFonts>,+ /// a presentation waits for completion until the next frame begins+ presenting: bool,+ /// what the last presented frame drew: DrawList words and resource revision+ shown: Option<(u64, u64)>,+ /// cached picture hash from `changed()` for the current frame, consumed by `present()`+ pending: Cell<Option<(u64, u64)>>,+}++fn err<E: std::fmt::Debug>(what: &'static str) -> impl FnOnce(E) -> String {+ move |e| format!("{what}: {e:?}")+}++fn density(scale: f32) -> u32 {+ (scale.round() as u32).clamp(1, 4)+}++impl UiHost {+ /// A runtime drawing with `device`/`queue`. `setup` runs on every new realm after `ui` is+ /// mounted and before the bundle evaluates: the host's own namespaces (fetch, timers,+ /// `navigator.gpu`, storage, …).+ pub fn new(+ device: &wgpu::Device,+ queue: &wgpu::Queue,+ config: HostConfig,+ setup: impl FnMut(Ctx) -> Result<(), String> + 'static,+ ) -> Result<UiHost, String> {+ let logical = config.logical;+ let density = density(config.scale);+ let profile = Profile {+ id: Cow::Owned(config.host_id.clone()),+ cadences: Cow::Owned(vec![60]),+ viewport: [logical[0] * density, logical[1] * density],+ logical_viewports: Cow::Owned(vec![logical]),+ dynamic_viewport: None,+ presentations: Cow::Borrowed(&[Cow::Borrowed("native")]),+ auxiliary: None,+ auxiliary_logical: Cow::Borrowed(&[]),+ density,+ animation: Cow::Borrowed(""),+ capabilities: Cow::Owned(CAPABILITIES.iter().map(|c| Cow::Borrowed(*c)).collect()),+ required_inputs: InputClasses::NONE,+ };+ let mut runtime = Runtime::new(RuntimeConfig {+ profile_hash: [0; 32],+ host_abi: BINDING_GENERATION,+ // JavaScriptCore has no heap limit to apply; the runtime requires a nonzero figure+ heap_limit: 1 << 30,+ frame_buffer_budget: 256 << 20,+ profile,+ })+ .map_err(err("runtime"))?;+ runtime.allow_embedded_viewport_changes().map_err(err("viewport changes"))?;+ let input = Rc::new(RefCell::new(InputFrameBuilder::new()));+ runtime.add_input_source(Box::new(Input(input.clone()))).map_err(err("input"))?;++ // native text: the core measures and wraps through the slots, the renderer paints them+ let fonts = Rc::new(SlotFonts::new(&config.slots));+ {+ let ops = runtime.op_context();+ let mut core = ops.core_mut().map_err(err("core"))?;+ let measure = fonts.clone();+ core.ui.set_text_measure(Some(Box::new(move |text, slot, tracking, line_height| measure.measure(text, slot, tracking, line_height))));+ let wrap = fonts.clone();+ core.ui.set_text_wrap(Some(Box::new(move |text, slot, max_width| wrap.wrap(text, slot, max_width))));+ }+ let mut renderer = WgpuRenderer::new(device, queue, config.format).map_err(err("renderer"))?;+ renderer.set_text_painter(Some(Box::new(text::Painter(fonts.clone()))));+ let pixel_format = renderer.descriptor().formats()[0];+ let cell = RendererCell::new(renderer);+ let physical = [(logical[0] as f32 * config.scale).round() as u32, (logical[1] as f32 * config.scale).round() as u32];+ let display = Rc::new(RefCell::new(DisplayState::new(&cell, (physical[0], physical[1]), config.scale, pixel_format)));+ let registration = cell.registration().map_err(err("registration"))?;+ let renderer_id = runtime.add_renderer(registration).map_err(err("add renderer"))?;+ runtime.add_display(SurfaceDisplay(display.clone()), renderer_id).map_err(err("add display"))?;+ // the cell lives on in the registration and the display's target slot+ drop(cell);++ let guest = JscGuest::new(&config.host_id).with_setup(setup);+ let realm = guest.realm();+ Ok(UiHost { runtime, realm, display, input, guest: Some(guest), config, fonts, presenting: false, shown: None, pending: Cell::new(None) })+ }++ /// Admit `js` (a PocketJS bundle) with its `pak` and evaluate it.+ pub fn boot(&mut self, label: &str, js: &str, pak: &[u8]) -> Result<(), String> {+ let features: serde_json::Map<String, serde_json::Value> = CAPABILITIES.iter().map(|c| (c.to_string(), serde_json::Value::Bool(true))).collect();+ let plan = serde_json::json!({+ "target": { "id": self.config.host_id, "hostAbi": BINDING_GENERATION },+ "profile": { "id": self.config.host_id, "tickHz": 60 },+ "viewport": { "logical": self.config.logical, "presentation": "native", "rasterDensity": density(self.config.scale) },+ "features": features,+ });+ let plan = serde_json::to_vec(&plan).map_err(err("plan"))?;+ let identity = pocket_package::embedded::identity(label, label, label).map_err(err("identity"))?;+ let bytes = pocket_package::embedded::encode(pocket_package::embedded::EmbeddedPackage {+ host_abi: BINDING_GENERATION,+ profile_hash: [0; 32],+ identity: &identity,+ plan: &plan,+ code: js.as_bytes(),+ pak,+ })+ .map_err(err("package"))?;+ self.runtime.set_package_source(Box::new(MemorySource(bytes))).map_err(err("package source"))?;+ let guest = self.guest.take().ok_or("already booted")?;+ self.runtime.set_guest(Box::new(guest)).map_err(err("guest"))?;+ self.runtime.boot_deferred().map_err(err("boot"))?;+ self.runtime.skip_presentation().map_err(err("skip presentation"))?;+ Ok(())+ }++ /// The JavaScript realm (for the host's callbacks into it).+ pub fn realm(&self) -> &Realm {+ &self.realm+ }++ /// The facts the next guest turn sees: pointer (logical px), scroll, text events.+ pub fn input(&self) -> RefMut<'_, InputFrameBuilder> {+ self.input.borrow_mut()+ }++ /// Finish the previous frame's presentation (normally long done on the GPU).+ fn complete(&mut self) -> Result<(), String> {+ if self.presenting {+ self.presenting = false;+ self.runtime.complete_presentation().map_err(err("complete presentation"))?;+ }+ Ok(())+ }++ /// One guest turn.+ pub fn advance(&mut self) -> Result<(), String> {+ self.complete()?;+ self.pending.set(None);+ self.runtime.skip_presentation().map_err(err("skip"))?;+ self.runtime.advance().map_err(err("advance"))+ }++ /// Draw the UI into `view` (`size` device px) over what it holds, or over `clear`.+ pub fn present(&mut self, view: &wgpu::TextureView, size: (u32, u32), clear: Option<wgpu::Color>) -> Result<(), String> {+ if self.display.borrow().size != size && size.0 > 0 && size.1 > 0 {+ self.resize_physical([size.0, size.1], self.config.scale)?;+ }+ self.display.borrow_mut().set_frame(view, size, self.config.scale, clear)?;+ self.runtime.present().map_err(err("present"))?;+ self.presenting = true;+ self.shown = self.pending.take().or_else(|| self.picture());+ Ok(())+ }++ /// The interface's picture after the last turn: a hash of its DrawList and the resource+ /// revision (textures, fonts, styles).+ fn picture(&self) -> Option<(u64, u64)> {+ let ops = self.runtime.op_context();+ let mut core = ops.core_mut().ok()?;+ let words = &core.ui.draw().words;+ // FNV-1a over the words+ let mut hash = 0xcbf2_9ce4_8422_2325u64;+ for w in words {+ hash = (hash ^ *w as u64).wrapping_mul(0x0000_0100_0000_01b3);+ }+ Some((hash, core.ui.raster_revision()))+ }++ /// Whether the interface would draw something other than what the window shows.+ pub fn changed(&self) -> bool {+ let current = self.pending.get().or_else(|| {+ let pic = self.picture();+ self.pending.set(pic);+ pic+ });+ self.shown.is_none() || current != self.shown+ }++ /// The window lost its pictures (resize, new drawable): the next frame presents.+ pub fn invalidate(&mut self) {+ self.shown = None;+ self.pending.set(None);+ }++ /// The window changed size or scale (logical px). Supports both integer and fractional HiDPI scales.+ pub fn resize(&mut self, logical: [u32; 2], scale: f32) -> Result<(), String> {+ let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };+ let logical = [logical[0].max(1), logical[1].max(1)];+ let physical = [+ (logical[0] as f32 * scale).round().max(1.0) as u32,+ (logical[1] as f32 * scale).round().max(1.0) as u32,+ ];+ self.resize_gpu([logical[0] as f32, logical[1] as f32], physical, scale)+ }++ /// The window changed physical surface size or scale (exact swapchain device px).+ /// Preferred on Wayland / fractional HiDPI where physical dimensions may not equal `round(logical) * scale`.+ pub fn resize_physical(&mut self, physical: [u32; 2], scale: f32) -> Result<(), String> {+ let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };+ let physical = [physical[0].max(1), physical[1].max(1)];+ let logical = [+ (physical[0] as f32 / scale).max(1.0),+ (physical[1] as f32 / scale).max(1.0),+ ];+ self.resize_gpu(logical, physical, scale)+ }++ fn resize_gpu(&mut self, logical: [f32; 2], physical: [u32; 2], scale: f32) -> Result<(), String> {+ self.complete()?;+ let prev = {+ let mut d = self.display.borrow_mut();+ let prev = (d.size, d.scale);+ d.size = (physical[0], physical[1]);+ d.scale = scale;+ prev+ };+ if let Err(e) = self.runtime.resize_embedded_gpu(logical, physical) {+ let mut d = self.display.borrow_mut();+ d.size = prev.0;+ d.scale = prev.1;+ return Err(format!("resize: {e:?}"));+ }+ self.config.logical = [logical[0].round().max(1.0) as u32, logical[1].round().max(1.0) as u32];+ self.config.scale = scale;+ self.shown = None;+ self.pending.set(None);+ Ok(())+ }++ /// The CSS cursor the interface's hovered node asks for (`cursor-*` classes).+ pub fn cursor(&self) -> &'static str {+ let ops = self.runtime.op_context();+ let Ok(core) = ops.core() else { return "default" };+ match core.ui.hover_cursor() {+ 2 => "pointer",+ 3 => "text",+ 4 => "not-allowed",+ _ => "default",+ }+ }++ pub fn logical(&self) -> [u32; 2] {+ self.config.logical+ }+ pub fn scale(&self) -> f32 {+ self.config.scale+ }+ pub fn fonts(&self) -> &Rc<SlotFonts> {+ &self.fonts+ }+ pub fn pixel_format(&self) -> PixelFormat {+ self.display.borrow().pixel_format+ }+}++impl Drop for UiHost {+ fn drop(&mut self) {+ let _ = self.complete();+ let _ = self.runtime.shutdown();+ }+}diff --git a/runtime/crates/pocket-host/src/text.rs b/runtime/crates/pocket-host/src/text.rsnew file mode 100644index 0000000..e937850--- /dev/null+++ b/runtime/crates/pocket-host/src/text.rs@@ -0,0 +1,106 @@+//! `text.layout.native`: the UI's font slots measured, wrapped and painted by CoreText through+//! the Canvas 2D text machinery (same faces, fallback and emoji advances as `fillText`).++use std::cell::RefCell;+use std::collections::HashMap;+use std::rc::Rc;++use canvas2d::textblock::{self, BlockFont, TextFont};+use pocket_wgpu_render::{PaintedText, TextPainter, TextRunRequest};++/// What one font slot draws with.+#[derive(Clone, Debug)]+pub struct SlotFont {+ /// CSS family list, e.g. `["-apple-system", "PingFang SC", "sans-serif"]`+ pub families: Vec<String>,+ /// CSS weight, 100–900+ pub weight: u16,+ pub italic: bool,+ /// px+ pub size: f32,+ /// the slot's line pitch in px; `None` = the face's normal line height+ pub line_height: Option<f32>,+}++struct Slot {+ font: BlockFont,+ line_height: f32,+}++/// The resolved slots, shared by the core's measurer and wrapper and the renderer's painter.+pub struct SlotFonts {+ slots: Vec<Option<Slot>>,+ widths: RefCell<HashMap<(u8, u32, String), f64>>,+}++const WIDTH_CACHE: usize = 8192;++impl SlotFonts {+ pub fn new(slots: &[Option<SlotFont>]) -> SlotFonts {+ let slots = slots+ .iter()+ .map(|slot| {+ slot.as_ref().map(|s| {+ let font = BlockFont::new(&TextFont { families: s.families.clone(), weight: s.weight, italic: s.italic, size: s.size as f64 });+ let line_height = s.line_height.unwrap_or_else(|| font.normal_line_height() as f32);+ Slot { font, line_height }+ })+ })+ .collect();+ SlotFonts { slots, widths: RefCell::new(HashMap::new()) }+ }+ fn slot(&self, slot: u8) -> Option<&Slot> {+ self.slots.get(slot as usize).and_then(|s| s.as_ref())+ }+ fn width(&self, slot: u8, font: &BlockFont, line: &str, tracking: f32) -> f64 {+ let key = (slot, tracking.to_bits(), line.to_owned());+ if let Some(w) = self.widths.borrow().get(&key) {+ return *w;+ }+ let w = font.measure_spaced(line, tracking as f64);+ let mut widths = self.widths.borrow_mut();+ if widths.len() >= WIDTH_CACHE {+ widths.clear();+ }+ widths.insert(key, w);+ w+ }+ /// `(widest line, lines × line height)` in logical px, `tracking` px after each character.+ pub fn measure(&self, text: &str, slot: u8, tracking: f32, line_height: f32) -> (f32, f32) {+ let Some(s) = self.slot(slot) else { return (0.0, 0.0) };+ if text.is_empty() {+ return (0.0, 0.0);+ }+ let lh = if line_height.is_nan() { s.line_height } else { line_height };+ let mut widest = 0.0f64;+ let mut lines = 0u32;+ for line in text.split('\n') {+ widest = widest.max(self.width(slot, &s.font, line, tracking));+ lines += 1;+ }+ (widest as f32, lines as f32 * lh)+ }+ /// Soft breaks (UTF-16 columns) for one line under `max_width`.+ pub fn wrap(&self, text: &str, slot: u8, max_width: f32) -> Vec<u32> {+ match self.slot(slot) {+ Some(s) => s.font.wrap(text, max_width as f64),+ None => Vec::new(),+ }+ }+ fn paint(&self, run: &TextRunRequest<'_>) -> Option<PaintedText> {+ let s = self.slot(run.slot)?;+ let lh = if run.line_height.is_nan() { s.line_height } else { run.line_height };+ let [r, g, b, _] = run.color.to_le_bytes();+ let block = textblock::paint(&s.font, run.text, [r, g, b, 255], run.align, run.box_width, lh, run.tracking, run.scale)?;+ Some(PaintedText { width: block.width, height: block.height, rgba: block.rgba, offset: block.offset })+ }+}++/// The renderer's side of the provider.+pub(crate) struct Painter(pub Rc<SlotFonts>);++impl TextPainter for Painter {+ fn paint(&mut self, run: &TextRunRequest<'_>) -> Option<PaintedText> {+ self.0.paint(run)+ }+}diff --git a/runtime/crates/rt/Cargo.toml b/runtime/crates/rt/Cargo.tomlnew file mode 100644index 0000000..02265ae--- /dev/null+++ b/runtime/crates/rt/Cargo.toml@@ -0,0 +1,9 @@+[package]+name = "threert-rt"+description = "Main-thread runtime services for ThreeRT: worker task posting, page lifecycle, monotonic clocks"+version.workspace = true+edition.workspace = true+license.workspace = true++[dependencies]+jsc.workspace = truediff --git a/runtime/crates/rt/src/lib.rs b/runtime/crates/rt/src/lib.rsnew file mode 100644index 0000000..2b11215--- /dev/null+++ b/runtime/crates/rt/src/lib.rs@@ -0,0 +1,172 @@+//! Main-thread runtime services shared by every host module.+//!+//! The JavaScript context, the GL context and the UI tree live on the main (AppKit) thread.+//! Worker threads (network, decoding, host services) never touch them; they `post`+//! closures that the main thread runs between frames, and the app is woken to do so.+//!+//! A "page" is one JS global context (one navigation). Everything a host module keeps for a page+//! — protected callbacks, timers, sockets — must be dropped in `reset_page` before the context is+//! released, so modules register a reset hook when they install themselves.++use std::any::Any;+use std::cell::{Cell, RefCell};+use std::collections::HashMap;+use std::sync::{Mutex, OnceLock};+use std::time::Instant;++use jsc::Ctx;++type Task = Box<dyn FnOnce() + Send>;++static QUEUE: Mutex<Vec<Task>> = Mutex::new(Vec::new());+static WAKER: OnceLock<Box<dyn Fn() + Send + Sync>> = OnceLock::new();+static START: OnceLock<Instant> = OnceLock::new();++/// Install the function that wakes the main event loop (called from any thread).+pub fn set_waker(f: impl Fn() + Send + Sync + 'static) {+ let _ = WAKER.set(Box::new(f));+}++/// Run `task` on the main thread soon. Callable from any thread.+pub fn post(task: impl FnOnce() + Send + 'static) {+ QUEUE.lock().unwrap().push(Box::new(task));+ if let Some(w) = WAKER.get() {+ w();+ }+}++/// Main thread: run everything posted so far. Returns how many tasks ran.+pub fn drain() -> usize {+ let tasks = std::mem::take(&mut *QUEUE.lock().unwrap());+ let n = tasks.len();+ for t in tasks {+ t();+ }+ n+}++/// Milliseconds since process start (monotonic).+pub fn now_ms() -> f64 {+ START.get_or_init(Instant::now).elapsed().as_secs_f64() * 1000.0+}++/// Requests a page makes of the app; handled after the current JS call returns.+#[derive(Debug, Clone)]+pub enum AppRequest {+ /// Load a new URL (location.href = …, location.reload()).+ Navigate(String),+ /// A message for the host shell bridge.+ Shell(String, Vec<String>),+ /// window.close() and similar.+ CloseWindow,+ /// The page wants a frame (rAF registered, UI dirty, …).+ Redraw,+}++type Continuation = Box<dyn FnOnce(Ctx, Box<dyn Any + Send>)>;++thread_local! {+ static CTX: Cell<Option<Ctx>> = const { Cell::new(None) };+ static GEN: Cell<u64> = const { Cell::new(0) };+ static PAGE_START: Cell<f64> = const { Cell::new(0.0) };+ static NEXT_ID: Cell<u64> = const { Cell::new(1) };+ static PENDING: RefCell<HashMap<u64, (u64, Continuation)>> = RefCell::new(HashMap::new());+ static RESETS: RefCell<Vec<fn()>> = const { RefCell::new(Vec::new()) };+ static REQUESTS: RefCell<Vec<AppRequest>> = const { RefCell::new(Vec::new()) };+}++/// Main thread: a new page's context is live.+pub fn begin_page(c: Ctx) {+ GEN.with(|g| g.set(g.get() + 1));+ CTX.with(|x| x.set(Some(c)));+ PAGE_START.with(|p| p.set(now_ms()));+}++/// Main thread: drop every per-page resource (before the context is released).+pub fn reset_page() {+ CTX.with(|x| x.set(None));+ GEN.with(|g| g.set(g.get() + 1));+ let pending = PENDING.with(|p| std::mem::take(&mut *p.borrow_mut()));+ drop(pending);+ let hooks = RESETS.with(|r| r.borrow().clone());+ for h in hooks {+ h();+ }+}++/// Register a hook run by `reset_page` (idempotent per function pointer).+pub fn on_reset(f: fn()) {+ RESETS.with(|r| {+ let mut r = r.borrow_mut();+ if !r.iter().any(|g| std::ptr::fn_addr_eq(*g, f)) {+ r.push(f);+ }+ });+}++/// The live page context, if any.+pub fn ctx() -> Option<Ctx> {+ CTX.with(|x| x.get())+}++/// The current page generation (changes on every navigation / teardown).+pub fn page_gen() -> u64 {+ GEN.with(|g| g.get())+}++/// `performance.now()` for the current page.+pub fn page_now() -> f64 {+ now_ms() - PAGE_START.with(|p| p.get())+}++/// Run `work` on a worker thread, then `then` on the main thread with the page context — unless+/// the page went away meanwhile, in which case the result is dropped.+pub fn spawn<R: Send + 'static>(work: impl FnOnce() -> R + Send + 'static, then: impl FnOnce(Ctx, R) + 'static) {+ let id = NEXT_ID.with(|n| {+ let v = n.get();+ n.set(v + 1);+ v+ });+ let generation = page_gen();+ let cont: Continuation = Box::new(move |c, any| {+ if let Ok(r) = any.downcast::<R>() {+ then(c, *r)+ }+ });+ PENDING.with(|p| p.borrow_mut().insert(id, (generation, cont)));+ std::thread::Builder::new()+ .name("rt-worker".into())+ .spawn(move || {+ let r = work();+ post(move || complete(id, Box::new(r)));+ })+ .expect("spawn worker");+}++fn complete(id: u64, r: Box<dyn Any + Send>) {+ let Some((generation, cont)) = PENDING.with(|p| p.borrow_mut().remove(&id)) else { return };+ if generation != page_gen() {+ return;+ }+ if let Some(c) = ctx() {+ cont(c, r);+ }+}++/// Queue a request for the app (processed after the current JS call returns).+pub fn request(r: AppRequest) {+ REQUESTS.with(|q| q.borrow_mut().push(r));+ if let Some(w) = WAKER.get() {+ w();+ }+}++/// Main thread: take queued app requests.+pub fn take_requests() -> Vec<AppRequest> {+ REQUESTS.with(|q| std::mem::take(&mut *q.borrow_mut()))+}++/// Log an uncaught JS error the same way everywhere.+pub fn report(what: &str, err: &str) {+ eprintln!("[js] {what}: {err}");+}diff --git a/runtime/js/canvas2d.ts b/runtime/js/canvas2d.tsnew file mode 100644index 0000000..a860a99--- /dev/null+++ b/runtime/js/canvas2d.ts@@ -0,0 +1,884 @@+// Canvas 2D over CoreGraphics (crates/canvas2d): CanvasRenderingContext2D, CanvasGradient,+// CanvasPattern, Path2D, ImageData, TextMetrics, ImageBitmap / createImageBitmap, OffscreenCanvas,+// plus the image loader and canvas.toDataURL used by the DOM (see shared/surfaces.ts).+//+// Drawing state lives natively; this side keeps a mirror for the getters (with Chrome's+// serializations) and forwards each call. Colors are parsed here (cached) and sent as numbers.+import { surfaces, type CanvasHost, type ImageHost } from "./shared/surfaces.ts";++const g = globalThis as any;+let c2d: any;++function domError(message: string, name: string): Error {+ const D = g.DOMException;+ return D ? new D(message, name) : Object.assign(new Error(message), { name });+}++// ---------------------------------------------------------------------------------------- colors++type RGBA = { r: number; g: number; b: number; a: number; css: string };++const NAMED: Record<string, number> = {+ aliceblue: 0xf0f8ff, antiquewhite: 0xfaebd7, aqua: 0x00ffff, aquamarine: 0x7fffd4, azure: 0xf0ffff, beige: 0xf5f5dc, bisque: 0xffe4c4, black: 0x000000,+ blanchedalmond: 0xffebcd, blue: 0x0000ff, blueviolet: 0x8a2be2, brown: 0xa52a2a, burlywood: 0xdeb887, cadetblue: 0x5f9ea0, chartreuse: 0x7fff00,+ chocolate: 0xd2691e, coral: 0xff7f50, cornflowerblue: 0x6495ed, cornsilk: 0xfff8dc, crimson: 0xdc143c, cyan: 0x00ffff, darkblue: 0x00008b,+ darkcyan: 0x008b8b, darkgoldenrod: 0xb8860b, darkgray: 0xa9a9a9, darkgreen: 0x006400, darkgrey: 0xa9a9a9, darkkhaki: 0xbdb76b, darkmagenta: 0x8b008b,+ darkolivegreen: 0x556b2f, darkorange: 0xff8c00, darkorchid: 0x9932cc, darkred: 0x8b0000, darksalmon: 0xe9967a, darkseagreen: 0x8fbc8f,+ darkslateblue: 0x483d8b, darkslategray: 0x2f4f4f, darkslategrey: 0x2f4f4f, darkturquoise: 0x00ced1, darkviolet: 0x9400d3, deeppink: 0xff1493,+ deepskyblue: 0x00bfff, dimgray: 0x696969, dimgrey: 0x696969, dodgerblue: 0x1e90ff, firebrick: 0xb22222, floralwhite: 0xfffaf0, forestgreen: 0x228b22,+ fuchsia: 0xff00ff, gainsboro: 0xdcdcdc, ghostwhite: 0xf8f8ff, gold: 0xffd700, goldenrod: 0xdaa520, gray: 0x808080, green: 0x008000,+ greenyellow: 0xadff2f, grey: 0x808080, honeydew: 0xf0fff0, hotpink: 0xff69b4, indianred: 0xcd5c5c, indigo: 0x4b0082, ivory: 0xfffff0, khaki: 0xf0e68c,+ lavender: 0xe6e6fa, lavenderblush: 0xfff0f5, lawngreen: 0x7cfc00, lemonchiffon: 0xfffacd, lightblue: 0xadd8e6, lightcoral: 0xf08080,+ lightcyan: 0xe0ffff, lightgoldenrodyellow: 0xfafad2, lightgray: 0xd3d3d3, lightgreen: 0x90ee90, lightgrey: 0xd3d3d3, lightpink: 0xffb6c1,+ lightsalmon: 0xffa07a, lightseagreen: 0x20b2aa, lightskyblue: 0x87cefa, lightslategray: 0x778899, lightslategrey: 0x778899, lightsteelblue: 0xb0c4de,+ lightyellow: 0xffffe0, lime: 0x00ff00, limegreen: 0x32cd32, linen: 0xfaf0e6, magenta: 0xff00ff, maroon: 0x800000, mediumaquamarine: 0x66cdaa,+ mediumblue: 0x0000cd, mediumorchid: 0xba55d3, mediumpurple: 0x9370db, mediumseagreen: 0x3cb371, mediumslateblue: 0x7b68ee, mediumspringgreen: 0x00fa9a,+ mediumturquoise: 0x48d1cc, mediumvioletred: 0xc71585, midnightblue: 0x191970, mintcream: 0xf5fffa, mistyrose: 0xffe4e1, moccasin: 0xffe4b5,+ navajowhite: 0xffdead, navy: 0x000080, oldlace: 0xfdf5e6, olive: 0x808000, olivedrab: 0x6b8e23, orange: 0xffa500, orangered: 0xff4500, orchid: 0xda70d6,+ palegoldenrod: 0xeee8aa, palegreen: 0x98fb98, paleturquoise: 0xafeeee, palevioletred: 0xdb7093, papayawhip: 0xffefd5, peachpuff: 0xffdab9,+ peru: 0xcd853f, pink: 0xffc0cb, plum: 0xdda0dd, powderblue: 0xb0e0e6, purple: 0x800080, rebeccapurple: 0x663399, red: 0xff0000, rosybrown: 0xbc8f8f,+ royalblue: 0x4169e1, saddlebrown: 0x8b4513, salmon: 0xfa8072, sandybrown: 0xf4a460, seagreen: 0x2e8b57, seashell: 0xfff5ee, sienna: 0xa0522d,+ silver: 0xc0c0c0, skyblue: 0x87ceeb, slateblue: 0x6a5acd, slategray: 0x708090, slategrey: 0x708090, snow: 0xfffafa, springgreen: 0x00ff7f,+ steelblue: 0x4682b4, tan: 0xd2b48c, teal: 0x008080, thistle: 0xd8bfd8, tomato: 0xff6347, turquoise: 0x40e0d0, violet: 0xee82ee, wheat: 0xf5deb3,+ white: 0xffffff, whitesmoke: 0xf5f5f5, yellow: 0xffff00, yellowgreen: 0x9acd32,+};++const hex2 = (n: number) => n.toString(16).padStart(2, "0");++/** Chrome's canvas color serialization: `#rrggbb` when opaque, else `rgba(r, g, b, a)`. */+function serialize(r: number, g: number, b: number, a: number): string {+ if (a >= 1) return "#" + hex2(r) + hex2(g) + hex2(b);+ const a8 = Math.round(a * 255);+ let s = Math.round((a8 / 255) * 100) / 100;+ if (Math.round(s * 255) !== a8) s = Math.round((a8 / 255) * 1000) / 1000;+ return `rgba(${r}, ${g}, ${b}, ${s})`;+}++function make(r: number, g: number, b: number, a: number): RGBA {+ const cl = (v: number) => Math.min(255, Math.max(0, Math.round(v)));+ r = cl(r); g = cl(g); b = cl(b);+ a = Math.min(1, Math.max(0, a));+ return { r, g, b, a, css: serialize(r, g, b, a) };+}++function parseNumberOrPercent(t: string, scale: number): number | null {+ if (t === "none") return 0;+ if (t.endsWith("%")) { const v = parseFloat(t); return Number.isFinite(v) ? (v / 100) * scale : null; }+ const v = Number(t);+ return Number.isFinite(v) && t !== "" ? v : null;+}++function parseHue(t: string): number | null {+ if (t === "none") return 0;+ const m = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(deg|rad|grad|turn)?$/i.exec(t);+ if (!m) return null;+ const v = parseFloat(m[1]);+ switch ((m[2] || "deg").toLowerCase()) {+ case "rad": return (v * 180) / Math.PI;+ case "grad": return v * 0.9;+ case "turn": return v * 360;+ default: return v;+ }+}++function hslToRgb(h: number, s: number, l: number): [number, number, number] {+ h = ((h % 360) + 360) % 360; s = Math.min(1, Math.max(0, s)); l = Math.min(1, Math.max(0, l));+ const f = (n: number) => { const k = (n + h / 30) % 12; const a = s * Math.min(l, 1 - l); return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1)); };+ return [f(0) * 255, f(8) * 255, f(4) * 255];+}++function parseFunc(name: string, body: string): RGBA | null {+ // Accept "a, b, c[, d]" (legacy) and "a b c [/ d]" (modern).+ let parts: string[];+ let alpha: string | undefined;+ if (body.includes(",")) {+ parts = body.split(",").map((s) => s.trim());+ if (parts.length === 4) alpha = parts.pop();+ if (parts.length !== 3 || parts.some((p) => p === "" || p === "none")) return null;+ } else {+ const [main, al, extra] = body.split("/").map((s) => s.trim());+ if (extra !== undefined) return null;+ alpha = al;+ parts = main.split(/\s+/).filter(Boolean);+ if (parts.length !== 3) return null;+ }+ let a = 1;+ if (alpha !== undefined) { const v = parseNumberOrPercent(alpha, 1); if (v === null) return null; a = v; }+ if (name === "rgb" || name === "rgba") {+ const pct = parts.map((p) => p.endsWith("%"));+ if (body.includes(",") && pct.some((p) => p !== pct[0])) return null;+ const v = parts.map((p) => parseNumberOrPercent(p, 255));+ if (v.some((x) => x === null)) return null;+ return make(v[0]!, v[1]!, v[2]!, a);+ }+ if (name === "hsl" || name === "hsla") {+ const h = parseHue(parts[0]);+ const s = parseNumberOrPercent(parts[1], 100), l = parseNumberOrPercent(parts[2], 100);+ if (h === null || s === null || l === null) return null;+ if (body.includes(",") && (!parts[1].endsWith("%") || !parts[2].endsWith("%"))) return null;+ const [r, gg, b] = hslToRgb(h, s / 100, l / 100);+ return make(r, gg, b, a);+ }+ if (name === "hwb") {+ const h = parseHue(parts[0]);+ let w = parseNumberOrPercent(parts[1], 100), bl = parseNumberOrPercent(parts[2], 100);+ if (h === null || w === null || bl === null) return null;+ w /= 100; bl /= 100;+ if (w + bl >= 1) { const gray = (w / (w + bl)) * 255; return make(gray, gray, gray, a); }+ const [r, gg, b] = hslToRgb(h, 1, 0.5);+ const k = 1 - w - bl;+ return make(r * k + w * 255, gg * k + w * 255, b * k + w * 255, a);+ }+ return null;+}++const colorCache = new Map<string, RGBA | null>();++/** Parse a CSS color (named, hex, rgb[a](), hsl[a](), hwb(), transparent, currentcolor). */+export function parseColor(input: string): RGBA | null {+ let c = colorCache.get(input);+ if (c !== undefined) return c;+ c = parseColorUncached(input.trim().toLowerCase());+ if (colorCache.size > 4096) colorCache.clear();+ colorCache.set(input, c);+ return c;+}++function parseColorUncached(s: string): RGBA | null {+ if (s.startsWith("#")) {+ const h = s.slice(1);+ if (!/^[0-9a-f]+$/.test(h)) return null;+ const n = (i: number, len: number) => parseInt(len === 1 ? h[i] + h[i] : h.substr(i, 2), 16);+ if (h.length === 3 || h.length === 4) return make(n(0, 1), n(1, 1), n(2, 1), h.length === 4 ? n(3, 1) / 255 : 1);+ if (h.length === 6 || h.length === 8) return make(n(0, 2), n(2, 2), n(4, 2), h.length === 8 ? n(6, 2) / 255 : 1);+ return null;+ }+ if (s === "transparent") return make(0, 0, 0, 0);+ if (s === "currentcolor") return make(0, 0, 0, 1);+ const named = NAMED[s];+ if (named !== undefined) return make(named >> 16, (named >> 8) & 255, named & 255, 1);+ const m = /^([a-z]+)\((.*)\)$/s.exec(s);+ if (m) return parseFunc(m[1], m[2].trim());+ return null;+}++// --------------------------------------------------------------------------------- small classes++const registry = typeof FinalizationRegistry === "function" ? new FinalizationRegistry<number>((id) => { try { c2d.release(id); } catch { /* page gone */ } }) : null;+const track = (obj: object, id: number) => { registry?.register(obj, id); };++export class CanvasGradient {+ /** @internal */ _id: number;+ /** @internal */ constructor(id: number) { this._id = id; track(this, id); }+ addColorStop(offset: number, color: string) {+ offset = Number(offset);+ if (!(offset >= 0 && offset <= 1)) throw domError("The provided value (" + offset + ") is outside the range (0.0, 1.0).", "IndexSizeError");+ const c = parseColor(String(color));+ if (!c) throw domError("The value provided ('" + color + "') could not be parsed as a color.", "SyntaxError");+ c2d.addColorStop(this._id, offset, c.r, c.g, c.b, c.a);+ }+}++export class CanvasPattern {+ /** @internal */ _id: number;+ /** @internal */ constructor(id: number) { this._id = id; track(this, id); }+ setTransform(m?: any) {+ const t = matrixFrom(m);+ if (t) c2d.patternTransform(this._id, ...t);+ }+}++export class ImageData {+ readonly width: number;+ readonly height: number;+ readonly data: Uint8ClampedArray;+ readonly colorSpace = "srgb";+ constructor(a: number | Uint8ClampedArray, b: number, c?: number | object, _settings?: object) {+ if (a instanceof Uint8ClampedArray) {+ const len = a.length;+ const w = b >>> 0;+ if (!len || len % 4 !== 0) throw domError("The input data length is not a multiple of 4.", "InvalidStateError");+ if (!w) throw domError("The source width is zero or not a number.", "IndexSizeError");+ const h = typeof c === "number" ? c >>> 0 : len / 4 / w;+ if (len / 4 / w !== Math.floor(len / 4 / w) || (typeof c === "number" && w * h * 4 !== len)) throw domError("The input data length is not equal to (4 * width * height).", "IndexSizeError");+ this.width = w; this.height = h; this.data = a;+ } else {+ const w = Number(a), h = Number(b);+ if (!Number.isFinite(w) || !Number.isFinite(h)) throw new TypeError("ImageData dimensions must be finite");+ const wi = Math.trunc(w), hi = Math.trunc(h);+ if (!wi || !hi) throw domError("The source " + (wi ? "height" : "width") + " is zero or not a number.", "IndexSizeError");+ this.width = Math.abs(wi); this.height = Math.abs(hi);+ this.data = new Uint8ClampedArray(this.width * this.height * 4);+ }+ }+}++export class TextMetrics {+ readonly width: number; readonly actualBoundingBoxLeft: number; readonly actualBoundingBoxRight: number;+ readonly fontBoundingBoxAscent: number; readonly fontBoundingBoxDescent: number;+ readonly actualBoundingBoxAscent: number; readonly actualBoundingBoxDescent: number;+ readonly emHeightAscent: number; readonly emHeightDescent: number;+ readonly hangingBaseline: number; readonly alphabeticBaseline: number; readonly ideographicBaseline: number;+ /** @internal */ constructor(v: number[]) {+ [this.width, this.actualBoundingBoxLeft, this.actualBoundingBoxRight, this.fontBoundingBoxAscent, this.fontBoundingBoxDescent,+ this.actualBoundingBoxAscent, this.actualBoundingBoxDescent, this.emHeightAscent, this.emHeightDescent,+ this.hangingBaseline, this.alphabeticBaseline, this.ideographicBaseline] = v;+ }+}++/** Minimal DOMMatrix (2D) for getTransform() / setTransform(matrix), unless the runtime has one. */+class DOMMatrix2D {+ a = 1; b = 0; c = 0; d = 1; e = 0; f = 0;+ constructor(init?: number[] | string) {+ if (Array.isArray(init) && init.length >= 6) [this.a, this.b, this.c, this.d, this.e, this.f] = init.map(Number);+ }+ get m11() { return this.a; } set m11(v) { this.a = v; }+ get m12() { return this.b; } set m12(v) { this.b = v; }+ get m21() { return this.c; } set m21(v) { this.c = v; }+ get m22() { return this.d; } set m22(v) { this.d = v; }+ get m41() { return this.e; } set m41(v) { this.e = v; }+ get m42() { return this.f; } set m42(v) { this.f = v; }+ get m13() { return 0; } get m14() { return 0; } get m23() { return 0; } get m24() { return 0; }+ get m31() { return 0; } get m32() { return 0; } get m33() { return 1; } get m34() { return 0; } get m43() { return 0; } get m44() { return 1; }+ get is2D() { return true; }+ get isIdentity() { return this.a === 1 && this.b === 0 && this.c === 0 && this.d === 1 && this.e === 0 && this.f === 0; }+ multiply(o: any) { const m = mul([this.a, this.b, this.c, this.d, this.e, this.f], [o.a, o.b, o.c, o.d, o.e, o.f]); return new DOMMatrix2D(m); }+ inverse() {+ const det = this.a * this.d - this.b * this.c;+ if (!det) return new DOMMatrix2D([NaN, NaN, NaN, NaN, NaN, NaN]);+ return new DOMMatrix2D([this.d / det, -this.b / det, -this.c / det, this.a / det, (this.c * this.f - this.d * this.e) / det, (this.b * this.e - this.a * this.f) / det]);+ }+ translate(x = 0, y = 0) { return this.multiply({ a: 1, b: 0, c: 0, d: 1, e: x, f: y }); }+ scale(sx = 1, sy = sx) { return this.multiply({ a: sx, b: 0, c: 0, d: sy, e: 0, f: 0 }); }+ rotate(deg = 0) { const r = (deg * Math.PI) / 180; return this.multiply({ a: Math.cos(r), b: Math.sin(r), c: -Math.sin(r), d: Math.cos(r), e: 0, f: 0 }); }+ transformPoint(p: { x?: number; y?: number } = {}) { const x = p.x ?? 0, y = p.y ?? 0; return { x: this.a * x + this.c * y + this.e, y: this.b * x + this.d * y + this.f, z: 0, w: 1 }; }+ toFloat32Array() { return new Float32Array([this.a, this.b, 0, 0, this.c, this.d, 0, 0, 0, 0, 1, 0, this.e, this.f, 0, 1]); }+ toFloat64Array() { return new Float64Array([this.a, this.b, 0, 0, this.c, this.d, 0, 0, 0, 0, 1, 0, this.e, this.f, 0, 1]); }+ toString() { return `matrix(${this.a}, ${this.b}, ${this.c}, ${this.d}, ${this.e}, ${this.f})`; }+ static fromMatrix(o: any) { return new DOMMatrix2D([o?.a ?? o?.m11 ?? 1, o?.b ?? o?.m12 ?? 0, o?.c ?? o?.m21 ?? 0, o?.d ?? o?.m22 ?? 1, o?.e ?? o?.m41 ?? 0, o?.f ?? o?.m42 ?? 0]); }+}++type M = [number, number, number, number, number, number];+/** `m` then `n` (canvas: current × new). Returns current·n. */+function mul(m: number[], n: number[]): M {+ return [m[0] * n[0] + m[2] * n[1], m[1] * n[0] + m[3] * n[1], m[0] * n[2] + m[2] * n[3], m[1] * n[2] + m[3] * n[3], m[0] * n[4] + m[2] * n[5] + m[4], m[1] * n[4] + m[3] * n[5] + m[5]];+}++function matrixFrom(o: any): M | null {+ if (o === undefined || o === null) return [1, 0, 0, 1, 0, 0];+ const v: M = [o.a ?? o.m11 ?? 1, o.b ?? o.m12 ?? 0, o.c ?? o.m21 ?? 0, o.d ?? o.m22 ?? 1, o.e ?? o.m41 ?? 0, o.f ?? o.m42 ?? 0].map(Number) as M;+ return v.every(Number.isFinite) ? v : null;+}++// ---------------------------------------------------------------------------------------- Path2D++/** Feed SVG path data into a native path (absolute/relative commands, implicit repeats, arcs). */+function svgPath(id: number, d: string) {+ const re = /([MmLlHhVvCcSsQqTtAaZz])|([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)/g;+ const toks: (string | number)[] = [];+ for (let m; (m = re.exec(d));) toks.push(m[1] ?? Number(m[2]));+ let i = 0, cmd = "", x = 0, y = 0, sx = 0, sy = 0, cx = 0, cy = 0, qx = 0, qy = 0, prev = "";+ const num = () => { const t = toks[i]; if (typeof t !== "number") throw new Error("bad path"); i++; return t; };+ const flag = () => { const t = num(); if (t !== 0 && t !== 1) throw new Error("bad flag"); return t === 1; };+ try {+ while (i < toks.length) {+ if (typeof toks[i] === "string") cmd = toks[i++] as string;+ else if (!cmd || cmd === "z" || cmd === "Z") break;+ const rel = cmd === cmd.toLowerCase();+ const ox = rel ? x : 0, oy = rel ? y : 0;+ switch (cmd.toLowerCase()) {+ case "m": x = ox + num(); y = oy + num(); c2d.moveTo(id, x, y); sx = x; sy = y; cmd = rel ? "l" : "L"; break;+ case "l": x = ox + num(); y = oy + num(); c2d.lineTo(id, x, y); break;+ case "h": x = ox + num(); c2d.lineTo(id, x, y); break;+ case "v": y = oy + num(); c2d.lineTo(id, x, y); break;+ case "c": { const a = ox + num(), b = oy + num(); cx = ox + num(); cy = oy + num(); x = ox + num(); y = oy + num(); c2d.bezierTo(id, a, b, cx, cy, x, y); break; }+ case "s": { const a = /[cs]/i.test(prev) ? 2 * x - cx : x, b = /[cs]/i.test(prev) ? 2 * y - cy : y; cx = ox + num(); cy = oy + num(); x = ox + num(); y = oy + num(); c2d.bezierTo(id, a, b, cx, cy, x, y); break; }+ case "q": qx = ox + num(); qy = oy + num(); x = ox + num(); y = oy + num(); c2d.quadTo(id, qx, qy, x, y); break;+ case "t": qx = /[qt]/i.test(prev) ? 2 * x - qx : x; qy = /[qt]/i.test(prev) ? 2 * y - qy : y; x = ox + num(); y = oy + num(); c2d.quadTo(id, qx, qy, x, y); break;+ case "a": {+ let rx = Math.abs(num()), ry = Math.abs(num());+ const rot = (num() * Math.PI) / 180, large = flag(), sweep = flag();+ const x2 = ox + num(), y2 = oy + num();+ arcToEndpoint(id, x, y, rx, ry, rot, large, sweep, x2, y2);+ x = x2; y = y2;+ break;+ }+ case "z": c2d.closePath(id); x = sx; y = sy; break;+ }+ if (cmd.toLowerCase() === "z") { prev = "z"; continue; }+ prev = cmd;+ }+ } catch { /* stop at the first error, keeping what was parsed (SVG error handling) */ }+}++function arcToEndpoint(id: number, x1: number, y1: number, rx: number, ry: number, phi: number, large: boolean, sweep: boolean, x2: number, y2: number) {+ if (x1 === x2 && y1 === y2) return;+ if (!rx || !ry) { c2d.lineTo(id, x2, y2); return; }+ const cos = Math.cos(phi), sin = Math.sin(phi);+ const dx = (x1 - x2) / 2, dy = (y1 - y2) / 2;+ const xp = cos * dx + sin * dy, yp = -sin * dx + cos * dy;+ const lam = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);+ if (lam > 1) { rx *= Math.sqrt(lam); ry *= Math.sqrt(lam); }+ const num = rx * rx * ry * ry - rx * rx * yp * yp - ry * ry * xp * xp;+ let k = Math.sqrt(Math.max(0, num / (rx * rx * yp * yp + ry * ry * xp * xp)));+ if (large === sweep) k = -k;+ const cxp = (k * rx * yp) / ry, cyp = (-k * ry * xp) / rx;+ const cx = cos * cxp - sin * cyp + (x1 + x2) / 2, cy = sin * cxp + cos * cyp + (y1 + y2) / 2;+ const ang = (ux: number, uy: number, vx: number, vy: number) => Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);+ const t1 = ang(1, 0, (xp - cxp) / rx, (yp - cyp) / ry);+ let dt = ang((xp - cxp) / rx, (yp - cyp) / ry, (-xp - cxp) / rx, (-yp - cyp) / ry);+ if (!sweep && dt > 0) dt -= 2 * Math.PI;+ else if (sweep && dt < 0) dt += 2 * Math.PI;+ c2d.ellipse(id, cx, cy, rx, ry, phi, t1, t1 + dt, !sweep);+}++/** Path methods shared by Path2D and the context (`_pid()` is the native path target). */+abstract class PathMethods {+ /** @internal */ abstract _pid(): number;+ closePath() { c2d.closePath(this._pid()); }+ moveTo(x: number, y: number) { c2d.moveTo(this._pid(), +x, +y); }+ lineTo(x: number, y: number) { c2d.lineTo(this._pid(), +x, +y); }+ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number) { c2d.quadTo(this._pid(), +cpx, +cpy, +x, +y); }+ bezierCurveTo(a: number, b: number, c: number, d: number, x: number, y: number) { c2d.bezierTo(this._pid(), +a, +b, +c, +d, +x, +y); }+ arcTo(x1: number, y1: number, x2: number, y2: number, r: number) {+ if (+r < 0) throw domError("The radius provided (" + r + ") is negative.", "IndexSizeError");+ c2d.arcTo(this._pid(), +x1, +y1, +x2, +y2, +r);+ }+ rect(x: number, y: number, w: number, h: number) { c2d.rect(this._pid(), +x, +y, +w, +h); }+ arc(x: number, y: number, r: number, a0: number, a1: number, ccw = false) {+ if (+r < 0) throw domError("The radius provided (" + r + ") is negative.", "IndexSizeError");+ c2d.arc(this._pid(), +x, +y, +r, +a0, +a1, !!ccw);+ }+ ellipse(x: number, y: number, rx: number, ry: number, rot: number, a0: number, a1: number, ccw = false) {+ if (+rx < 0) throw domError("The major-axis radius provided (" + rx + ") is negative.", "IndexSizeError");+ if (+ry < 0) throw domError("The minor-axis radius provided (" + ry + ") is negative.", "IndexSizeError");+ c2d.ellipse(this._pid(), +x, +y, +rx, +ry, +rot, +a0, +a1, !!ccw);+ }+ roundRect(x: number, y: number, w: number, h: number, radii: any = 0) {+ x = +x; y = +y; w = +w; h = +h;+ if (![x, y, w, h].every(Number.isFinite)) return;+ const list: any[] = typeof radii === "object" && radii !== null && typeof radii[Symbol.iterator] === "function" ? [...radii] : [radii];+ if (list.length < 1 || list.length > 4) throw new RangeError(`Failed to execute 'roundRect': ${list.length} radii provided. Between one and four radii are necessary.`);+ const pts = list.map((r) => {+ if (typeof r === "object" && r !== null) {+ const rx = +(r.x ?? 0), ry = +(r.y ?? 0);+ if (!Number.isFinite(rx) || !Number.isFinite(ry)) return null;+ if (rx < 0 || ry < 0) throw new RangeError("Failed to execute 'roundRect': Radius value " + (rx < 0 ? rx : ry) + " is negative.");+ return [rx, ry];+ }+ const v = +r;+ if (!Number.isFinite(v)) return null;+ if (v < 0) throw new RangeError("Failed to execute 'roundRect': Radius value " + v + " is negative.");+ return [v, v];+ });+ if (pts.some((p) => p === null)) return;+ const p = pts as number[][];+ let tl: number[], tr: number[], br: number[], bl: number[];+ if (p.length === 4) [tl, tr, br, bl] = p;+ else if (p.length === 3) { tl = p[0]; tr = bl = p[1]; br = p[2]; }+ else if (p.length === 2) { tl = br = p[0]; tr = bl = p[1]; }+ else tl = tr = br = bl = p[0];+ tl = [...tl]; tr = [...tr]; br = [...br]; bl = [...bl];+ if (w < 0) { x += w; w = -w; [tl, tr] = [tr, tl]; [bl, br] = [br, bl]; }+ if (h < 0) { y += h; h = -h; [tl, bl] = [bl, tl]; [tr, br] = [br, tr]; }+ const top = tl[0] + tr[0], right = tr[1] + br[1], bottom = br[0] + bl[0], left = tl[1] + bl[1];+ const scale = Math.min(w / top, h / right, w / bottom, h / left);+ if (scale < 1) for (const c of [tl, tr, br, bl]) { c[0] *= scale; c[1] *= scale; }+ c2d.roundRect(this._pid(), x, y, w, h, tl[0], tl[1], tr[0], tr[1], br[0], br[1], bl[0], bl[1]);+ }+}++export class Path2D extends PathMethods {+ /** @internal */ _id: number;+ constructor(path?: Path2D | string) {+ super();+ if (path instanceof Path2D) this._id = c2d.copyPath(path._id);+ else {+ this._id = c2d.newPath();+ if (typeof path === "string") svgPath(this._id, path);+ }+ track(this, this._id);+ }+ /** @internal */ _pid() { return this._id; }+ addPath(path: Path2D, transform?: any) {+ if (!(path instanceof Path2D)) throw new TypeError("Failed to execute 'addPath' on 'Path2D': parameter 1 is not of type 'Path2D'.");+ const m = matrixFrom(transform) ?? [1, 0, 0, 1, 0, 0];+ c2d.addPath(this._id, path._id, ...m);+ }+}++// --------------------------------------------------------------------------------- image sources++export class ImageBitmap {+ /** @internal */ _imageId: number;+ width: number;+ height: number;+ /** @internal */ constructor(id: number, w: number, h: number) { this._imageId = id; this.width = w; this.height = h; track(this, id); }+ close() { if (this._imageId) { c2d.release(this._imageId); registry?.unregister?.(this); this._imageId = 0; this.width = this.height = 0; } }+}++type Source = { id: number; width: number; height: number; temp?: boolean };++/** Resolve a drawImage / createPattern / createImageBitmap source. `null`: nothing to draw yet. */+function sourceOf(image: any, what: string): Source | null {+ if (!image || typeof image !== "object") throw new TypeError(`Failed to execute '${what}': The provided value is not of type '(HTMLImageElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'.`);+ if (image instanceof ImageBitmap) {+ if (!image._imageId) throw domError("The image source is detached", "InvalidStateError");+ return { id: image._imageId, width: image.width, height: image.height };+ }+ if ("_context" in image || image instanceof OffscreenCanvas) {+ const w = image.width >>> 0, h = image.height >>> 0;+ if (!w || !h) throw domError("The image argument is a canvas element with a width or height of 0.", "InvalidStateError");+ const ctx = image._context;+ if (ctx instanceof CanvasRenderingContext2D) return { id: ctx._id, width: w, height: h };+ if (ctx && typeof ctx._readPixelsForExport === "function") {+ const px = ctx._readPixelsForExport();+ if (!px) return null;+ const id = c2d.imageFromPixels(px.width, px.height, px.data);+ return id ? { id, width: px.width, height: px.height, temp: true } : null;+ }+ return null; // blank canvas: transparent, nothing to draw+ }+ if ("_imageId" in image) {+ if (image._imageId) return { id: image._imageId, width: image.naturalWidth, height: image.naturalHeight };+ if (image.complete && image.src) throw domError("The HTMLImageElement provided is in the 'broken' state.", "InvalidStateError");+ return null;+ }+ if (image instanceof ImageData) {+ const id = c2d.imageFromPixels(image.width, image.height, image.data);+ return id ? { id, width: image.width, height: image.height, temp: true } : null;+ }+ return null; // video frames etc. are not supported+}++// ------------------------------------------------------------------------------------- context++const ALIGN = ["start", "end", "left", "right", "center"];+const BASELINE = ["alphabetic", "top", "hanging", "middle", "ideographic", "bottom"];+const CAPS = ["butt", "round", "square"];+const JOINS = ["miter", "round", "bevel"];+const QUALITY = ["low", "medium", "high"];++interface State {+ m: M;+ fill: string | CanvasGradient | CanvasPattern;+ stroke: string | CanvasGradient | CanvasPattern;+ alpha: number; composite: string;+ lineWidth: number; cap: number; join: number; miter: number; dash: number[]; dashOffset: number;+ shadowX: number; shadowY: number; shadowBlur: number; shadowColor: string;+ smoothing: boolean; quality: number;+ font: string; align: number; baseline: number; direction: string;+ letterSpacing: string; wordSpacing: string; letterPx: number; wordPx: number; kerning: string;+ fontStretch: string; fontVariantCaps: string; textRendering: string; filter: string;+}++const initialState = (): State => ({+ m: [1, 0, 0, 1, 0, 0], fill: "#000000", stroke: "#000000", alpha: 1, composite: "source-over",+ lineWidth: 1, cap: 0, join: 0, miter: 10, dash: [], dashOffset: 0,+ shadowX: 0, shadowY: 0, shadowBlur: 0, shadowColor: "rgba(0, 0, 0, 0)",+ smoothing: true, quality: 0,+ font: "10px sans-serif", align: 0, baseline: 0, direction: "ltr",+ letterSpacing: "0px", wordSpacing: "0px", letterPx: 0, wordPx: 0, kerning: "auto",+ fontStretch: "normal", fontVariantCaps: "normal", textRendering: "auto", filter: "none",+});++function parseLength(v: string, fontPx: number): number | null {+ const m = /^\s*([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(px|em|rem|pt|pc|in|cm|mm|q|ex|ch)?\s*$/i.exec(v);+ if (!m) return null;+ const n = parseFloat(m[1]);+ const u = (m[2] || "").toLowerCase();+ if (!u) return n === 0 ? 0 : null;+ const k: Record<string, number> = { px: 1, em: fontPx, rem: 16, pt: 4 / 3, pc: 16, in: 96, cm: 96 / 2.54, mm: 96 / 25.4, q: 96 / 101.6, ex: fontPx / 2, ch: fontPx / 2 };+ return n * k[u];+}++export class CanvasRenderingContext2D extends PathMethods {+ /** @internal */ _id: number;+ /** @internal */ _canvas: CanvasHost;+ /** @internal */ _s: State = initialState();+ /** @internal */ _stack: State[] = [];+ /** @internal */ _attrs: any;+ /** @internal */ _fontPx = 10;++ /** @internal */ constructor(canvas: CanvasHost, attrs?: any) {+ super();+ this._canvas = canvas;+ this._attrs = { alpha: attrs?.alpha !== false, colorSpace: "srgb", desynchronized: false, willReadFrequently: !!attrs?.willReadFrequently };+ this._id = c2d.create(canvas.width >>> 0, canvas.height >>> 0);+ track(this, this._id);+ }++ /** The native bitmap id (shared with images; WebGL uploads and the UI read it). */+ get _surfaceId() { return this._id; }+ /** @internal */ _pid() { return this._id; }+ /** @internal canvas.width/height changed: reallocate, clear, reset state (as browsers do). */+ _resize(w: number, h: number) {+ c2d.resize(this._id, w >>> 0, h >>> 0);+ this._s = initialState();+ this._stack = [];+ this._fontPx = 10;+ this._canvas._setSurface("2d", this._id);+ }++ get canvas() { return this._canvas as any; }+ getContextAttributes() { return { ...this._attrs }; }+ isContextLost() { return false; }++ // ---- state+ save() { this._stack.push({ ...this._s, dash: this._s.dash.slice() }); c2d.save(this._id); }+ restore() {+ const s = this._stack.pop();+ if (!s) return;+ this._s = s;+ c2d.restore(this._id);+ this._fontPx = 0;+ }+ reset() { c2d.reset(this._id); this._s = initialState(); this._stack = []; this._fontPx = 10; }++ // ---- transforms+ /** @internal */ _setM(m: M) { if (!m.every(Number.isFinite)) return; this._s.m = m; c2d.setTransform(this._id, ...m); }+ scale(x: number, y: number) { this._setM(mul(this._s.m, [+x, 0, 0, +y, 0, 0])); }+ rotate(a: number) { a = +a; if (!Number.isFinite(a)) return; const c = Math.cos(a), s = Math.sin(a); this._setM(mul(this._s.m, [c, s, -s, c, 0, 0])); }+ translate(x: number, y: number) { this._setM(mul(this._s.m, [1, 0, 0, 1, +x, +y])); }+ transform(a: number, b: number, c: number, d: number, e: number, f: number) { this._setM(mul(this._s.m, [+a, +b, +c, +d, +e, +f])); }+ setTransform(a?: any, b?: number, c?: number, d?: number, e?: number, f?: number) {+ if (arguments.length >= 6) this._setM([+a, +b!, +c!, +d!, +e!, +f!]);+ else { const m = matrixFrom(a); if (m) this._setM(m); }+ }+ resetTransform() { this._setM([1, 0, 0, 1, 0, 0]); }+ getTransform() { const DM = g.DOMMatrix ?? DOMMatrix2D; const m = new DM(); [m.a, m.b, m.c, m.d, m.e, m.f] = this._s.m; return m; }++ // ---- compositing+ get globalAlpha() { return this._s.alpha; }+ set globalAlpha(v: number) { v = +v; if (v >= 0 && v <= 1 && v !== this._s.alpha) { this._s.alpha = v; c2d.setAlpha(this._id, v); } }+ get globalCompositeOperation() { return this._s.composite; }+ set globalCompositeOperation(v: string) { v = String(v); if (v !== this._s.composite && c2d.setComposite(this._id, v)) this._s.composite = v; }+ get imageSmoothingEnabled() { return this._s.smoothing; }+ set imageSmoothingEnabled(v: boolean) { this._s.smoothing = !!v; c2d.setSmoothing(this._id, this._s.smoothing, this._s.quality); }+ get imageSmoothingQuality() { return QUALITY[this._s.quality]; }+ set imageSmoothingQuality(v: string) { const i = QUALITY.indexOf(String(v)); if (i >= 0) { this._s.quality = i; c2d.setSmoothing(this._id, this._s.smoothing, i); } }+ get filter() { return this._s.filter; }+ set filter(v: string) { this._s.filter = String(v); }++ // ---- paint+ get fillStyle() { return this._s.fill; }+ set fillStyle(v: any) { this._paint(v, false); }+ get strokeStyle() { return this._s.stroke; }+ set strokeStyle(v: any) { this._paint(v, true); }+ /** @internal */ _paint(v: any, stroke: boolean) {+ if (v instanceof CanvasGradient || v instanceof CanvasPattern) {+ if (stroke) this._s.stroke = v; else this._s.fill = v;+ (stroke ? c2d.setStrokePaint : c2d.setFillPaint)(this._id, v._id);+ return;+ }+ const c = parseColor(String(v));+ if (!c) return;+ if ((stroke ? this._s.stroke : this._s.fill) === c.css) return;+ if (stroke) this._s.stroke = c.css; else this._s.fill = c.css;+ (stroke ? c2d.setStrokeColor : c2d.setFillColor)(this._id, c.r, c.g, c.b, c.a);+ }+ createLinearGradient(x0: number, y0: number, x1: number, y1: number) {+ const v = [+x0, +y0, +x1, +y1];+ if (!v.every(Number.isFinite)) throw new TypeError("Failed to execute 'createLinearGradient': The provided double value is non-finite.");+ return new CanvasGradient(c2d.linearGradient(...v));+ }+ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number) {+ const v = [+x0, +y0, +r0, +x1, +y1, +r1];+ if (!v.every(Number.isFinite)) throw new TypeError("Failed to execute 'createRadialGradient': The provided double value is non-finite.");+ if (r0 < 0 || r1 < 0) throw domError(`The ${r0 < 0 ? "r0" : "r1"} provided is less than 0.`, "IndexSizeError");+ return new CanvasGradient(c2d.radialGradient(...v));+ }+ createConicGradient(angle: number, x: number, y: number) {+ const v = [+angle, +x, +y];+ if (!v.every(Number.isFinite)) throw new TypeError("Failed to execute 'createConicGradient': The provided double value is non-finite.");+ return new CanvasGradient(c2d.conicGradient(...v));+ }+ createPattern(image: any, repetition: string | null) {+ const rep = repetition === null || repetition === "" ? "repeat" : String(repetition);+ const r = ["repeat", "repeat-x", "repeat-y", "no-repeat"].indexOf(rep);+ if (r < 0) throw domError(`The provided type ('${rep}') is not one of 'repeat', 'no-repeat', 'repeat-x', or 'repeat-y'.`, "SyntaxError");+ const src = sourceOf(image, "createPattern");+ if (!src) return null;+ const id = c2d.pattern(src.id, r);+ if (src.temp) c2d.release(src.id);+ return id ? new CanvasPattern(id) : null;+ }++ // ---- lines+ get lineWidth() { return this._s.lineWidth; }+ set lineWidth(v: number) { v = +v; if (v > 0 && Number.isFinite(v)) { this._s.lineWidth = v; this._line(); } }+ get lineCap() { return CAPS[this._s.cap]; }+ set lineCap(v: string) { const i = CAPS.indexOf(String(v)); if (i >= 0) { this._s.cap = i; this._line(); } }+ get lineJoin() { return JOINS[this._s.join]; }+ set lineJoin(v: string) { const i = JOINS.indexOf(String(v)); if (i >= 0) { this._s.join = i; this._line(); } }+ get miterLimit() { return this._s.miter; }+ set miterLimit(v: number) { v = +v; if (v > 0 && Number.isFinite(v)) { this._s.miter = v; this._line(); } }+ /** @internal */ _line() { const s = this._s; c2d.setLine(this._id, s.lineWidth, s.cap, s.join, s.miter); }+ setLineDash(segments: number[]) {+ const v = Array.from(segments ?? [], Number);+ if (v.some((x) => !Number.isFinite(x) || x < 0)) return;+ this._s.dash = v.length % 2 ? v.concat(v) : v;+ c2d.setLineDash(this._id, this._s.dashOffset, this._s.dash);+ }+ getLineDash() { return this._s.dash.slice(); }+ get lineDashOffset() { return this._s.dashOffset; }+ set lineDashOffset(v: number) { v = +v; if (Number.isFinite(v)) { this._s.dashOffset = v; c2d.setLineDash(this._id, v, this._s.dash); } }++ // ---- shadows+ get shadowOffsetX() { return this._s.shadowX; }+ set shadowOffsetX(v: number) { v = +v; if (Number.isFinite(v)) { this._s.shadowX = v; this._shadow(); } }+ get shadowOffsetY() { return this._s.shadowY; }+ set shadowOffsetY(v: number) { v = +v; if (Number.isFinite(v)) { this._s.shadowY = v; this._shadow(); } }+ get shadowBlur() { return this._s.shadowBlur; }+ set shadowBlur(v: number) { v = +v; if (Number.isFinite(v) && v >= 0) { this._s.shadowBlur = v; this._shadow(); } }+ get shadowColor() { return this._s.shadowColor; }+ set shadowColor(v: string) { const c = parseColor(String(v)); if (c) { this._s.shadowColor = c.css; this._shadow(); } }+ /** @internal */ _shadow() {+ const s = this._s, c = parseColor(s.shadowColor)!;+ c2d.setShadow(this._id, s.shadowX, s.shadowY, s.shadowBlur, c.r, c.g, c.b, c.a);+ }++ // ---- rects+ clearRect(x: number, y: number, w: number, h: number) { c2d.clearRect(this._id, +x, +y, +w, +h); }+ fillRect(x: number, y: number, w: number, h: number) { c2d.fillRect(this._id, +x, +y, +w, +h); }+ strokeRect(x: number, y: number, w: number, h: number) { c2d.strokeRect(this._id, +x, +y, +w, +h); }++ // ---- paths+ beginPath() { c2d.beginPath(this._id); }+ fill(a?: any, b?: any) {+ const [p, rule] = a instanceof Path2D ? [a._id, b] : [0, a];+ c2d.fill(this._id, p, rule === "evenodd");+ }+ stroke(path?: Path2D) { c2d.stroke(this._id, path instanceof Path2D ? path._id : 0); }+ clip(a?: any, b?: any) {+ const [p, rule] = a instanceof Path2D ? [a._id, b] : [0, a];+ c2d.clip(this._id, p, rule === "evenodd");+ }+ isPointInPath(a: any, b: any, c?: any, d?: any) {+ if (a instanceof Path2D) return c2d.isPointInPath(this._id, a._id, +b, +c, d === "evenodd");+ return c2d.isPointInPath(this._id, 0, +a, +b, c === "evenodd");+ }+ isPointInStroke(a: any, b: any, c?: any) {+ if (a instanceof Path2D) return c2d.isPointInStroke(this._id, a._id, +b, +c);+ return c2d.isPointInStroke(this._id, 0, +a, +b);+ }+ drawFocusIfNeeded() {}+ scrollPathIntoView() {}++ // ---- text+ get font() { return this._s.font; }+ set font(v: string) {+ const css = c2d.setFont(this._id, String(v));+ if (css !== null) { this._s.font = css; this._fontPx = 0; }+ }+ /** @internal */ _fontSize() {+ if (!this._fontPx) { const m = /(\d*\.?\d+(?:e[+-]?\d+)?)px/.exec(this._s.font); this._fontPx = m ? parseFloat(m[1]) : 10; }+ return this._fontPx;+ }+ get textAlign() { return ALIGN[this._s.align]; }+ set textAlign(v: string) { const i = ALIGN.indexOf(String(v)); if (i >= 0) { this._s.align = i; this._text(); } }+ get textBaseline() { return BASELINE[this._s.baseline]; }+ set textBaseline(v: string) { const i = BASELINE.indexOf(String(v)); if (i >= 0) { this._s.baseline = i; this._text(); } }+ get direction() { return this._s.direction; }+ set direction(v: string) { v = String(v); if (v === "ltr" || v === "rtl" || v === "inherit") { this._s.direction = v; this._text(); } }+ get letterSpacing() { return this._s.letterSpacing; }+ set letterSpacing(v: string) { const px = parseLength(String(v), this._fontSize()); if (px !== null) { this._s.letterSpacing = String(v).trim(); this._s.letterPx = px; this._text(); } }+ get wordSpacing() { return this._s.wordSpacing; }+ set wordSpacing(v: string) { const px = parseLength(String(v), this._fontSize()); if (px !== null) { this._s.wordSpacing = String(v).trim(); this._s.wordPx = px; this._text(); } }+ get fontKerning() { return this._s.kerning; }+ set fontKerning(v: string) { v = String(v); if (v === "auto" || v === "normal" || v === "none") { this._s.kerning = v; this._text(); } }+ get fontStretch() { return this._s.fontStretch; }+ set fontStretch(v: string) { this._s.fontStretch = String(v); }+ get fontVariantCaps() { return this._s.fontVariantCaps; }+ set fontVariantCaps(v: string) { this._s.fontVariantCaps = String(v); }+ get textRendering() { return this._s.textRendering; }+ set textRendering(v: string) { this._s.textRendering = String(v); }+ /** @internal */ _text() {+ const s = this._s;+ c2d.setText(this._id, s.align, s.baseline, s.direction === "rtl", s.letterPx, s.wordPx, s.kerning !== "none");+ }+ fillText(text: string, x: number, y: number, maxWidth?: number) {+ c2d.fillText(this._id, String(text), +x, +y, arguments.length > 3 ? +maxWidth! : undefined);+ }+ strokeText(text: string, x: number, y: number, maxWidth?: number) {+ c2d.strokeText(this._id, String(text), +x, +y, arguments.length > 3 ? +maxWidth! : undefined);+ }+ measureText(text: string) { return new TextMetrics(c2d.measureText(this._id, String(text)) ?? new Array(12).fill(0)); }++ // ---- images+ drawImage(image: any, a1: number, a2: number, a3?: number, a4?: number, a5?: number, a6?: number, a7?: number, a8?: number) {+ const n = arguments.length;+ if (n !== 3 && n !== 5 && n !== 9) throw new TypeError(`Failed to execute 'drawImage': Valid arities are: [3, 5, 9], but ${n} arguments provided.`);+ const src = sourceOf(image, "drawImage");+ if (!src) return;+ let sx = 0, sy = 0, sw = src.width, sh = src.height, dx: number, dy: number, dw: number, dh: number;+ if (n === 3) { dx = +a1; dy = +a2; dw = sw; dh = sh; }+ else if (n === 5) { dx = +a1; dy = +a2; dw = +a3!; dh = +a4!; }+ else { sx = +a1; sy = +a2; sw = +a3!; sh = +a4!; dx = +a5!; dy = +a6!; dw = +a7!; dh = +a8!; }+ if ([sx, sy, sw, sh, dx, dy, dw, dh].every(Number.isFinite) && sw && sh && dw && dh) {+ if (sw < 0) { sx += sw; sw = -sw; }+ if (sh < 0) { sy += sh; sh = -sh; }+ if (dw < 0) { dx += dw; dw = -dw; }+ if (dh < 0) { dy += dh; dh = -dh; }+ c2d.drawImage(this._id, src.id, sx, sy, sw, sh, dx, dy, dw, dh);+ }+ if (src.temp) c2d.release(src.id);+ }+ createImageData(a: number | ImageData, b?: number) {+ if (a instanceof ImageData) return new ImageData(a.width, a.height);+ return new ImageData(Math.abs(Math.trunc(+a)) || (a as number), Math.abs(Math.trunc(+b!)) || (b as number));+ }+ getImageData(sx: number, sy: number, sw: number, sh: number) {+ sx = sx | 0; sy = sy | 0; sw = sw | 0; sh = sh | 0;+ if (!sw || !sh) throw domError(`The source ${sw ? "height" : "width"} is 0.`, "IndexSizeError");+ if (sw < 0) { sx += sw; sw = -sw; }+ if (sh < 0) { sy += sh; sh = -sh; }+ const img = new ImageData(sw, sh);+ c2d.getImageData(this._id, sx, sy, sw, sh, img.data);+ return img;+ }+ putImageData(img: ImageData, dx: number, dy: number, dirtyX = 0, dirtyY = 0, dirtyW?: number, dirtyH?: number) {+ if (!(img instanceof ImageData)) throw new TypeError("Failed to execute 'putImageData': parameter 1 is not of type 'ImageData'.");+ let x = dirtyX | 0, y = dirtyY | 0, w = dirtyW === undefined ? img.width : dirtyW | 0, h = dirtyH === undefined ? img.height : dirtyH | 0;+ if (w < 0) { x += w; w = -w; }+ if (h < 0) { y += h; h = -h; }+ c2d.putImageData(this._id, img.data, img.width, img.height, dx | 0, dy | 0, x, y, w, h);+ }+}++// ----------------------------------------------------------------------------------- OffscreenCanvas++export class OffscreenCanvas {+ /** @internal */ _w: number;+ /** @internal */ _h: number;+ /** @internal */ _context: any = null;+ /** @internal */ _onResize: ((w: number, h: number) => void) | null = null;+ constructor(width: number, height: number) { this._w = width >>> 0; this._h = height >>> 0; }+ get width() { return this._w; }+ set width(v: number) { this._w = v >>> 0; this._onResize?.(this._w, this._h); }+ get height() { return this._h; }+ set height(v: number) { this._h = v >>> 0; this._onResize?.(this._w, this._h); }+ /** @internal */ _setSurface() {}+ getContext(type: string, attrs?: any) {+ if (this._context) return this._context._kind === type || (type === "2d" && this._context instanceof CanvasRenderingContext2D) ? this._context : null;+ const f = surfaces.contextFactories.get(String(type));+ if (!f) return null;+ this._context = f(this as any, attrs);+ return this._context;+ }+ transferToImageBitmap() {+ const ctx = this._context;+ const id = ctx instanceof CanvasRenderingContext2D ? c2d.copySurface(ctx._id) : 0;+ if (ctx instanceof CanvasRenderingContext2D) ctx._resize(this._w, this._h);+ return new ImageBitmap(id, this._w, this._h);+ }+ convertToBlob(opts?: { type?: string; quality?: number }) {+ const url = surfaces.toDataURL!(this as any, opts?.type, opts?.quality);+ return Promise.resolve(dataURLToBlob(url));+ }+}++function dataURLToBlob(url: string) {+ const comma = url.indexOf(",");+ const mime = /^data:([^;,]*)/.exec(url)?.[1] || "image/png";+ const bin = g.atob(url.slice(comma + 1));+ const bytes = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);+ return typeof g.Blob === "function" ? new g.Blob([bytes], { type: mime }) : bytes;+}++// ------------------------------------------------------------------------------- createImageBitmap++function createImageBitmap(image: any, ...rest: any[]): Promise<ImageBitmap> {+ return new Promise((resolve, reject) => {+ try {+ const opts = rest.length === 1 || rest.length === 5 ? rest[rest.length - 1] ?? {} : {};+ const crop = rest.length >= 4 ? rest.slice(0, 4).map(Number) : null;+ const finish = (src: Source | null) => {+ if (!src) { reject(domError("The source image could not be decoded.", "InvalidStateError")); return; }+ let [sx, sy, sw, sh] = crop ?? [0, 0, src.width, src.height];+ if (sw < 0) { sx += sw; sw = -sw; }+ if (sh < 0) { sy += sh; sh = -sh; }+ if (!sw || !sh) { reject(domError("The crop rect width or height is 0.", "IndexSizeError")); return; }+ const ow = (opts.resizeWidth >>> 0) || (opts.resizeHeight ? Math.round((sw * opts.resizeHeight) / sh) : sw);+ const oh = (opts.resizeHeight >>> 0) || (opts.resizeWidth ? Math.round((sh * opts.resizeWidth) / sw) : sh);+ const plain = !crop && ow === src.width && oh === src.height && opts.imageOrientation !== "flipY";+ let id: number;+ if (plain) id = src.temp ? src.id : c2d.copySurface(src.id);+ else {+ id = c2d.create(ow, oh);+ if (opts.imageOrientation === "flipY") c2d.setTransform(id, 1, 0, 0, -1, 0, oh);+ if (opts.resizeQuality === "pixelated") c2d.setSmoothing(id, false, 0);+ c2d.drawImage(id, src.id, sx, sy, sw, sh, 0, 0, ow, oh);+ if (src.temp) c2d.release(src.id);+ }+ resolve(new ImageBitmap(id, ow, oh));+ };+ if (image && typeof image.arrayBuffer === "function" && !("_imageId" in image)) {+ image.arrayBuffer().then((buf: ArrayBuffer) => c2d.decode(buf, (id: number, w: number, h: number) => finish(id ? { id, width: w, height: h, temp: true } : null)), reject);+ return;+ }+ finish(sourceOf(image, "createImageBitmap"));+ } catch (e) { reject(e); }+ });+}++// ------------------------------------------------------------------------------------ installation++export function installCanvas2D() {+ c2d = (globalThis as any).__native.c2d;+ if (!c2d) return;+ Object.assign(g, { CanvasRenderingContext2D, CanvasGradient, CanvasPattern, ImageData, Path2D, TextMetrics, ImageBitmap, OffscreenCanvas, createImageBitmap });+ if (!g.OffscreenCanvasRenderingContext2D) g.OffscreenCanvasRenderingContext2D = CanvasRenderingContext2D;+ if (!g.DOMMatrix) { g.DOMMatrix = DOMMatrix2D; g.DOMMatrixReadOnly = DOMMatrix2D; }+ // Test pages (THREERT_C2D_TEST builds of the host) reach the DOM hooks to stand in for elements.+ if (c2d._writeFile) g.__c2dSurfaces = surfaces;++ surfaces.contextFactories.set("2d", (canvas: CanvasHost, attrs: any) => {+ if (canvas._context instanceof CanvasRenderingContext2D) return canvas._context;+ const ctx = new CanvasRenderingContext2D(canvas, attrs);+ canvas._onResize = (w, h) => ctx._resize(w, h);+ canvas._setSurface("2d", ctx._id);+ return ctx;+ });++ surfaces.toDataURL = (canvas: CanvasHost, type?: string, quality?: number) => {+ const t = type === undefined ? "image/png" : String(type);+ const q = typeof quality === "number" ? quality : NaN;+ const ctx = canvas._context;+ if (ctx instanceof CanvasRenderingContext2D) return c2d.toDataURL(ctx._id, t, q);+ if (ctx && typeof ctx._readPixelsForExport === "function") {+ const px = ctx._readPixelsForExport();+ if (px) return c2d.encodeRGBA(px.width, px.height, px.data, t, q);+ }+ return c2d.blankDataURL(canvas.width >>> 0, canvas.height >>> 0, t, q);+ };++ const loads = new WeakMap<object, object>();+ const images = typeof FinalizationRegistry === "function" ? new FinalizationRegistry<number>((id) => { try { c2d.release(id); } catch { /* */ } }) : null;+ surfaces.loadImage = (img: ImageHost, src: string) => {+ const token = {};+ loads.set(img, token);+ const done = (id: number, w: number, h: number) => {+ if (loads.get(img) !== token) { if (id) c2d.release(id); return; }+ loads.delete(img);+ if (!id) { img._failed(); return; }+ const old = img._imageId;+ if (old) images?.unregister(img);+ images?.register(img, id, img);+ img._loaded(id, w, h);+ if (old && old !== id) c2d.release(old);+ };+ const fail = () => done(0, 0, 0);+ const url = String(src ?? "").trim();+ if (!url) { Promise.resolve().then(fail); return; }+ if (/^data:/i.test(url)) { c2d.decodeDataURL(url, done); return; }+ let abs: string;+ try { abs = new g.URL(url, g.location?.href).href; } catch { Promise.resolve().then(fail); return; }+ if (typeof g.fetch !== "function") { Promise.resolve().then(fail); return; }+ g.fetch(abs).then((r: any) => {+ if (!r.ok) throw new Error("HTTP " + r.status);+ return r.arrayBuffer();+ }).then((buf: ArrayBuffer) => c2d.decode(buf, done), fail);+ };+}diff --git a/runtime/js/core/console.ts b/runtime/js/core/console.tsnew file mode 100644index 0000000..2deb862--- /dev/null+++ b/runtime/js/core/console.ts@@ -0,0 +1,56 @@+// console → native log (stderr of the app process).+const sys = __native.sys;++function inspect(v: unknown, depth = 0, seen = new Set<unknown>()): string {+ if (typeof v === "string") return depth ? JSON.stringify(v) : v;+ if (typeof v === "function") return `[Function ${v.name || "anonymous"}]`;+ if (typeof v !== "object" || v === null) return String(v);+ if (v instanceof Error) return v.stack ? `${v.name}: ${v.message}\n${v.stack}` : `${v.name}: ${v.message}`;+ if (seen.has(v)) return "[Circular]";+ if (depth > 2) return Array.isArray(v) ? "[Array]" : "[Object]";+ seen.add(v);+ try {+ if (Array.isArray(v)) return `[${v.slice(0, 50).map((x) => inspect(x, depth + 1, seen)).join(", ")}${v.length > 50 ? ", …" : ""}]`;+ if (ArrayBuffer.isView(v)) return `${v.constructor.name}(${(v as any).length})`;+ if (v instanceof Map) return `Map(${v.size})`;+ if (v instanceof Set) return `Set(${v.size})`;+ const tag = (v as any).constructor?.name;+ if (tag && /^HTML|Element$|^Text$|^Document$/.test(tag)) return `<${(v as any).tagName?.toLowerCase?.() ?? tag}>`;+ const entries = Object.keys(v as object).slice(0, 30).map((k) => `${k}: ${inspect((v as any)[k], depth + 1, seen)}`);+ return `${tag && tag !== "Object" ? tag + " " : ""}{ ${entries.join(", ")} }`;+ } catch { return "[object]"; }+}++function format(args: unknown[]) {+ if (typeof args[0] === "string" && /%[sdifoOc]/.test(args[0])) {+ let i = 1;+ const head = (args[0] as string).replace(/%[sdifoOc]/g, (m) => {+ if (m === "%c") { i++; return ""; }+ const a = args[i++];+ return m === "%d" || m === "%i" ? String(parseInt(String(a))) : m === "%f" ? String(Number(a)) : inspect(a, 1);+ });+ return [head, ...args.slice(i).map((a) => inspect(a))].join(" ");+ }+ return args.map((a) => inspect(a)).join(" ");+}++const counts = new Map<string, number>();+const times = new Map<string, number>();+export const console = {+ log: (...a: unknown[]) => sys.log("log", format(a)),+ info: (...a: unknown[]) => sys.log("info", format(a)),+ debug: (...a: unknown[]) => sys.log("debug", format(a)),+ warn: (...a: unknown[]) => sys.log("warn", format(a)),+ error: (...a: unknown[]) => sys.log("error", format(a)),+ trace: (...a: unknown[]) => sys.log("debug", format(a) + "\n" + new Error().stack),+ assert: (c: unknown, ...a: unknown[]) => { if (!c) sys.log("error", "Assertion failed: " + format(a)); },+ table: (d: unknown) => sys.log("log", inspect(d)),+ dir: (d: unknown) => sys.log("log", inspect(d)),+ group: (...a: unknown[]) => sys.log("log", format(a)),+ groupCollapsed: (...a: unknown[]) => sys.log("log", format(a)),+ groupEnd: () => {},+ count: (l = "default") => { const n = (counts.get(l) ?? 0) + 1; counts.set(l, n); sys.log("log", `${l}: ${n}`); },+ time: (l = "default") => { times.set(l, sys.now()); },+ timeEnd: (l = "default") => { const t = times.get(l); if (t !== undefined) sys.log("log", `${l}: ${(sys.now() - t).toFixed(2)}ms`); times.delete(l); },+ timeLog: (l = "default") => { const t = times.get(l); if (t !== undefined) sys.log("log", `${l}: ${(sys.now() - t).toFixed(2)}ms`); },+};diff --git a/runtime/js/core/events.ts b/runtime/js/core/events.tsnew file mode 100644index 0000000..f967859--- /dev/null+++ b/runtime/js/core/events.ts@@ -0,0 +1,301 @@+// DOM events: Event, EventTarget and the UI event classes.+//+// Dispatch walks `_eventParent()` from the target up (Node → parent … → Document → window), with the+// capture, target and bubble phases. `on<type>` handler properties are installed per prototype with+// `defineHandlers`, and run in listener order from the moment they are first set (as in browsers).++type Listener = { fn: EventListenerOrEventListenerObject | null; capture: boolean; once: boolean; passive: boolean; removed?: boolean };++export class DOMExceptionImpl extends Error {+ code = 0;+ constructor(message = "", public override name = "Error") { super(message); }+}++export class Event {+ static readonly NONE = 0; static readonly CAPTURING_PHASE = 1; static readonly AT_TARGET = 2; static readonly BUBBLING_PHASE = 3;+ readonly NONE = 0; readonly CAPTURING_PHASE = 1; readonly AT_TARGET = 2; readonly BUBBLING_PHASE = 3;+ readonly type: string;+ readonly bubbles: boolean;+ readonly cancelable: boolean;+ readonly composed: boolean;+ readonly timeStamp = __native.sys.now();+ readonly isTrusted: boolean = false;+ target: any = null;+ currentTarget: any = null;+ eventPhase = 0;+ defaultPrevented = false;+ /** @internal */ _stop = false;+ /** @internal */ _stopNow = false;+ /** @internal */ _passive = false;+ /** @internal */ _path: any[] = [];+ constructor(type: string, init: EventInit = {}) {+ this.type = String(type);+ this.bubbles = !!init.bubbles;+ this.cancelable = !!init.cancelable;+ this.composed = !!init.composed;+ }+ get srcElement() { return this.target; }+ get returnValue() { return !this.defaultPrevented; }+ set returnValue(v: boolean) { if (!v) this.preventDefault(); }+ get cancelBubble() { return this._stop; }+ set cancelBubble(v: boolean) { if (v) this._stop = true; }+ preventDefault() { if (this.cancelable && !this._passive) this.defaultPrevented = true; }+ stopPropagation() { this._stop = true; }+ stopImmediatePropagation() { this._stop = true; this._stopNow = true; }+ composedPath() { return this._path.slice(); }+ initEvent(type: string, bubbles = false, cancelable = false) {+ (this as any).type = type; (this as any).bubbles = bubbles; (this as any).cancelable = cancelable;+ }+}++export class CustomEvent<T = any> extends Event {+ readonly detail: T;+ constructor(type: string, init: CustomEventInit<T> = {}) { super(type, init); this.detail = init.detail as T; }+}++export class UIEvent extends Event {+ readonly view: any; readonly detail: number;+ constructor(type: string, init: UIEventInit = {}) { super(type, init); this.view = init.view ?? null; this.detail = init.detail ?? 0; }+ get which() { return 0; }+}++export class FocusEvent extends UIEvent {+ readonly relatedTarget: any;+ constructor(type: string, init: FocusEventInit = {}) { super(type, init); this.relatedTarget = init.relatedTarget ?? null; }+}++export class MouseEvent extends UIEvent {+ readonly screenX: number; readonly screenY: number; readonly clientX: number; readonly clientY: number;+ readonly ctrlKey: boolean; readonly shiftKey: boolean; readonly altKey: boolean; readonly metaKey: boolean;+ readonly button: number; readonly buttons: number; readonly relatedTarget: any;+ readonly movementX: number; readonly movementY: number;+ offsetX = 0; offsetY = 0;+ constructor(type: string, init: MouseEventInit = {}) {+ super(type, init);+ this.screenX = init.screenX ?? 0; this.screenY = init.screenY ?? 0;+ this.clientX = init.clientX ?? 0; this.clientY = init.clientY ?? 0;+ this.ctrlKey = !!init.ctrlKey; this.shiftKey = !!init.shiftKey; this.altKey = !!init.altKey; this.metaKey = !!init.metaKey;+ this.button = init.button ?? 0; this.buttons = init.buttons ?? 0; this.relatedTarget = init.relatedTarget ?? null;+ this.movementX = init.movementX ?? 0; this.movementY = init.movementY ?? 0;+ }+ get x() { return this.clientX; } get y() { return this.clientY; }+ get pageX() { return this.clientX; } get pageY() { return this.clientY; }+ getModifierState(k: string) { return k === "Shift" ? this.shiftKey : k === "Control" ? this.ctrlKey : k === "Alt" ? this.altKey : k === "Meta" ? this.metaKey : false; }+}++export class PointerEvent extends MouseEvent {+ readonly pointerId: number; readonly pointerType: string; readonly isPrimary: boolean;+ readonly width = 1; readonly height = 1; readonly pressure: number; readonly tiltX = 0; readonly tiltY = 0;+ constructor(type: string, init: PointerEventInit = {}) {+ super(type, init);+ this.pointerId = init.pointerId ?? 1; this.pointerType = init.pointerType ?? "mouse"; this.isPrimary = init.isPrimary ?? true;+ this.pressure = init.pressure ?? (this.buttons ? 0.5 : 0);+ }+}++export class WheelEvent extends MouseEvent {+ static readonly DOM_DELTA_PIXEL = 0; static readonly DOM_DELTA_LINE = 1; static readonly DOM_DELTA_PAGE = 2;+ readonly deltaX: number; readonly deltaY: number; readonly deltaZ: number; readonly deltaMode: number;+ constructor(type: string, init: WheelEventInit = {}) {+ super(type, init);+ this.deltaX = init.deltaX ?? 0; this.deltaY = init.deltaY ?? 0; this.deltaZ = init.deltaZ ?? 0; this.deltaMode = init.deltaMode ?? 0;+ }+}++export class KeyboardEvent extends UIEvent {+ static readonly DOM_KEY_LOCATION_STANDARD = 0;+ readonly key: string; readonly code: string; readonly location: number; readonly repeat: boolean; readonly isComposing: boolean;+ readonly ctrlKey: boolean; readonly shiftKey: boolean; readonly altKey: boolean; readonly metaKey: boolean;+ constructor(type: string, init: KeyboardEventInit = {}) {+ super(type, init);+ this.key = init.key ?? ""; this.code = init.code ?? ""; this.location = init.location ?? 0; this.repeat = !!init.repeat;+ this.isComposing = !!init.isComposing;+ this.ctrlKey = !!init.ctrlKey; this.shiftKey = !!init.shiftKey; this.altKey = !!init.altKey; this.metaKey = !!init.metaKey;+ }+ get keyCode() { return legacyKeyCode(this.key, this.code); }+ get which() { return this.keyCode; }+ get charCode() { return this.type === "keypress" && this.key.length === 1 ? this.key.charCodeAt(0) : 0; }+ getModifierState(k: string) { return k === "Shift" ? this.shiftKey : k === "Control" ? this.ctrlKey : k === "Alt" ? this.altKey : k === "Meta" ? this.metaKey : false; }+}++export class InputEvent extends UIEvent {+ readonly data: string | null; readonly inputType: string; readonly isComposing: boolean;+ constructor(type: string, init: InputEventInit = {}) {+ super(type, init);+ this.data = init.data ?? null; this.inputType = init.inputType ?? ""; this.isComposing = !!init.isComposing;+ }+}++export class CompositionEvent extends UIEvent {+ readonly data: string;+ constructor(type: string, init: CompositionEventInit = {}) { super(type, init); this.data = init.data ?? ""; }+}++export class SubmitEvent extends Event {+ readonly submitter: any;+ constructor(type: string, init: SubmitEventInit = {}) { super(type, init); this.submitter = init.submitter ?? null; }+}++export class ErrorEvent extends Event {+ readonly message: string; readonly error: any; readonly filename = ""; readonly lineno = 0; readonly colno = 0;+ constructor(type: string, init: ErrorEventInit = {}) { super(type, init); this.message = init.message ?? ""; this.error = init.error; }+}++export class MessageEvent<T = any> extends Event {+ readonly data: T; readonly origin: string; readonly lastEventId = ""; readonly source = null; readonly ports = [];+ constructor(type: string, init: MessageEventInit<T> = {}) { super(type, init); this.data = init.data as T; this.origin = init.origin ?? ""; }+}++export class CloseEvent extends Event {+ readonly code: number; readonly reason: string; readonly wasClean: boolean;+ constructor(type: string, init: CloseEventInit = {}) { super(type, init); this.code = init.code ?? 0; this.reason = init.reason ?? ""; this.wasClean = !!init.wasClean; }+}++export class ProgressEvent extends Event {+ readonly lengthComputable: boolean; readonly loaded: number; readonly total: number;+ constructor(type: string, init: ProgressEventInit = {}) { super(type, init); this.lengthComputable = !!init.lengthComputable; this.loaded = init.loaded ?? 0; this.total = init.total ?? 0; }+}++const LISTENERS = Symbol("listeners");+const HANDLERS = Symbol("handlers");++export class EventTarget {+ /** @internal */ [LISTENERS]?: Map<string, Listener[]>;+ /** @internal */ [HANDLERS]?: Map<string, { value: any; wrapper: Listener }>;++ /** The next target up the propagation path (overridden by Node and Document). */+ _eventParent(_e: Event): EventTarget | null { return null; }++ addEventListener(type: string, fn: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions) {+ if (!fn) return;+ const capture = typeof options === "boolean" ? options : !!options?.capture;+ const once = typeof options === "object" && !!options?.once;+ const passive = typeof options === "object" && !!options?.passive;+ const signal = typeof options === "object" ? options?.signal : undefined;+ if (signal?.aborted) return;+ const map: Map<string, Listener[]> = (this[LISTENERS] ??= new Map());+ let list = map.get(type);+ if (!list) { list = []; map.set(type, list); }+ if (list.some((l) => l.fn === fn && l.capture === capture)) return;+ const entry: Listener = { fn, capture, once, passive };+ list.push(entry);+ listenerAdded(this, type);+ signal?.addEventListener("abort", () => this.removeEventListener(type, fn, { capture }));+ }++ removeEventListener(type: string, fn: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions) {+ const capture = typeof options === "boolean" ? options : !!options?.capture;+ const list = this[LISTENERS]?.get(type);+ if (!list) return;+ const i = list.findIndex((l) => l.fn === fn && l.capture === capture);+ if (i >= 0) { list[i].removed = true; list.splice(i, 1); }+ }++ dispatchEvent(event: Event): boolean {+ const path: EventTarget[] = [];+ for (let t: EventTarget | null = this; t; t = t._eventParent(event)) path.push(t);+ event.target = this;+ event._path = path;+ event._stop = false; event._stopNow = false;+ for (let i = path.length - 1; i >= 1 && !event._stop; i--) invoke(path[i], event, Event.CAPTURING_PHASE);+ if (!event._stop) invoke(this, event, Event.AT_TARGET);+ if (event.bubbles) for (let i = 1; i < path.length && !event._stop; i++) invoke(path[i], event, Event.BUBBLING_PHASE);+ event.eventPhase = 0;+ event.currentTarget = null;+ return !event.defaultPrevented;+ }++ /** @internal does anyone listen for `type` here (listeners or an on-handler)? */+ _hasListener(type: string) { return !!this[LISTENERS]?.get(type)?.length; }+}++/** Hook for the UI engine: it only forwards high-frequency events (mousemove …) once someone listens. */+export let listenerAdded: (target: EventTarget, type: string) => void = () => {};+export function onListenerAdded(f: (target: EventTarget, type: string) => void) { listenerAdded = f; }++function invoke(target: EventTarget, event: Event, phase: number) {+ const list = target[LISTENERS]?.get(event.type);+ if (!list || !list.length) return;+ event.currentTarget = target;+ event.eventPhase = phase;+ for (const l of list.slice()) {+ if (l.removed) continue;+ if (phase === Event.CAPTURING_PHASE && !l.capture) continue;+ if (phase === Event.BUBBLING_PHASE && l.capture) continue;+ if (l.once) target.removeEventListener(event.type, l.fn, { capture: l.capture });+ event._passive = l.passive;+ try {+ const fn = l.fn as any;+ if (typeof fn === "function") fn.call(target, event);+ else if (fn && typeof fn.handleEvent === "function") fn.handleEvent(event);+ } catch (e) {+ reportError(e);+ }+ event._passive = false;+ if (event._stopNow) break;+ }+}++export function reportError(e: unknown) {+ const err = e as any;+ try { console.error(err?.stack ? `${err.message}\n${err.stack}` : String(err)); } catch { /* */ }+ try {+ const g = globalThis as any;+ if (typeof g.onerror === "function") g.onerror(String(err?.message ?? err), "", 0, 0, err);+ } catch { /* */ }+}++/** Define `on<type>` handler properties on a prototype. */+export function defineHandlers(proto: object, types: string[]) {+ for (const type of types) {+ Object.defineProperty(proto, "on" + type, {+ configurable: true,+ enumerable: true,+ get(this: EventTarget) { return this[HANDLERS]?.get(type)?.value ?? null; },+ set(this: EventTarget, value: any) {+ const handlers = (this[HANDLERS] ??= new Map());+ const existing = handlers.get(type);+ const fn = typeof value === "function" ? value : null;+ if (existing) {+ existing.value = fn;+ if (!fn) { this.removeEventListener(type, existing.wrapper.fn); handlers.delete(type); }+ return;+ }+ if (!fn) return;+ const self = this;+ const wrapper: Listener = {+ fn: function (this: any, e: Event) {+ const h = self[HANDLERS]?.get(type)?.value;+ if (!h) return;+ const r = h.call(self, e);+ if (r === false && type !== "mouseover" && type !== "error") e.preventDefault();+ } as any,+ capture: false, once: false, passive: false,+ };+ handlers.set(type, { value: fn, wrapper });+ this.addEventListener(type, wrapper.fn);+ },+ });+ }+}++export const HANDLER_TYPES = [+ "abort", "blur", "cancel", "change", "click", "close", "contextmenu", "dblclick", "error", "focus", "focusin", "focusout",+ "input", "invalid", "keydown", "keypress", "keyup", "load", "mousedown", "mouseenter", "mouseleave", "mousemove", "mouseout",+ "mouseover", "mouseup", "pointerdown", "pointermove", "pointerup", "pointercancel", "pointerenter", "pointerleave", "pointerover",+ "pointerout", "reset", "resize", "scroll", "select", "submit", "toggle", "wheel", "animationend", "transitionend",+ "compositionstart", "compositionupdate", "compositionend", "beforeinput",+];++const KEYCODES: Record<string, number> = {+ Backspace: 8, Tab: 9, Enter: 13, Shift: 16, Control: 17, Alt: 18, Pause: 19, CapsLock: 20, Escape: 27, " ": 32,+ PageUp: 33, PageDown: 34, End: 35, Home: 36, ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40, Delete: 46, Meta: 91,+ F1: 112, F2: 113, F3: 114, F4: 115, F5: 116, F6: 117, F7: 118, F8: 119, F9: 120, F10: 121, F11: 122, F12: 123,+};+function legacyKeyCode(key: string, code: string) {+ if (KEYCODES[key] !== undefined) return KEYCODES[key];+ if (/^Key[A-Z]$/.test(code)) return code.charCodeAt(3);+ if (/^Digit[0-9]$/.test(code)) return code.charCodeAt(5);+ if (key.length === 1) return key.toUpperCase().charCodeAt(0);+ return 0;+}diff --git a/runtime/js/core/timers.ts b/runtime/js/core/timers.tsnew file mode 100644index 0000000..e7137bd--- /dev/null+++ b/runtime/js/core/timers.ts@@ -0,0 +1,74 @@+// Timers and animation frames. The host wakes the page at the earliest deadline (`__native.sys.wakeAt`)+// and calls `runTimers(now)`; frames arrive through `runFrame(now)` while callbacks are pending.+import { reportError } from "./events.ts";++const sys = __native.sys;++interface Timer { id: number; at: number; fn: any; args: any[]; every: number }+const timers = new Map<number, Timer>();+let nextId = 1;+let scheduled = Infinity;++function reschedule() {+ let min = Infinity;+ for (const t of timers.values()) if (t.at < min) min = t.at;+ if (min !== scheduled) { scheduled = min; sys.wakeAt(min); }+}++function addTimer(fn: any, ms: any, args: any[], repeat: boolean) {+ const id = nextId++;+ const delay = Math.max(0, Number(ms) || 0);+ timers.set(id, { id, at: sys.now() + delay, fn, args, every: repeat ? Math.max(delay, 1) : 0 });+ reschedule();+ return id;+}++export function setTimeout(fn: any, ms?: any, ...args: any[]) { return addTimer(fn, ms, args, false); }+export function setInterval(fn: any, ms?: any, ...args: any[]) { return addTimer(fn, ms, args, true); }+export function clearTimeout(id: any) { if (timers.delete(Number(id))) reschedule(); }+export const clearInterval = clearTimeout;++export function runTimers(now: number) {+ scheduled = Infinity;+ // Fire in deadline order; timers added while running wait for the next wake.+ const due = [...timers.values()].filter((t) => t.at <= now + 0.5).sort((a, b) => a.at - b.at || a.id - b.id);+ for (const t of due) {+ if (!timers.has(t.id)) continue;+ if (t.every) t.at = Math.max(t.at + t.every, now); else timers.delete(t.id);+ try {+ if (typeof t.fn === "function") t.fn(...t.args);+ else if (typeof t.fn === "string") (0, eval)(t.fn);+ } catch (e) { reportError(e); }+ }+ reschedule();+}++let frameCallbacks = new Map<number, FrameRequestCallback>();+let nextFrameId = 1;++export function requestAnimationFrame(cb: FrameRequestCallback) {+ const id = nextFrameId++;+ frameCallbacks.set(id, cb);+ sys.requestFrame();+ return id;+}+export function cancelAnimationFrame(id: number) { frameCallbacks.delete(id); }++const frameHooks: ((now: number) => void)[] = [];+/** Runtime modules that need a turn every frame after the page's callbacks (DOM commit …). */+export function onFrameEnd(f: (now: number) => void) { frameHooks.push(f); }++export function runFrame(now: number) {+ const cbs = frameCallbacks;+ frameCallbacks = new Map();+ for (const cb of cbs.values()) {+ try { cb(now); } catch (e) { reportError(e); }+ }+ for (const h of frameHooks) {+ try { h(now); } catch (e) { reportError(e); }+ }+}++export function queueMicrotask(fn: () => void) {+ Promise.resolve().then(() => { try { fn(); } catch (e) { reportError(e); } });+}diff --git a/runtime/js/core/web.ts b/runtime/js/core/web.tsnew file mode 100644index 0000000..8209e18--- /dev/null+++ b/runtime/js/core/web.ts@@ -0,0 +1,327 @@+// Web platform utilities JavaScriptCore does not include: URL, URLSearchParams, TextEncoder/Decoder,+// atob/btoa, crypto, AbortController, structuredClone.+import { Event, EventTarget, DOMExceptionImpl } from "./events.ts";++// ---------------------------------------------------------------- URLSearchParams+const enc = (s: string) => encodeURIComponent(s).replace(/%20/g, "+").replace(/[!'()~]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());+const dec = (s: string) => { try { return decodeURIComponent(s.replace(/\+/g, " ")); } catch { return s; } };++export class URLSearchParams {+ /** @internal */ _list: [string, string][] = [];+ /** @internal */ _url: URL | null = null;+ constructor(init?: string | Record<string, string> | [string, string][] | URLSearchParams) {+ if (init == null) return;+ if (typeof init === "string") this._parse(init);+ else if (init instanceof URLSearchParams) this._list = init._list.map(([k, v]) => [k, v]);+ else if (Array.isArray(init) || typeof (init as any)[Symbol.iterator] === "function") for (const [k, v] of init as any) this._list.push([String(k), String(v)]);+ else for (const k of Object.keys(init)) this._list.push([k, String((init as any)[k])]);+ }+ /** @internal */ _parse(s: string) {+ this._list = [];+ for (const part of s.replace(/^\?/, "").split("&")) {+ if (!part) continue;+ const i = part.indexOf("=");+ this._list.push(i < 0 ? [dec(part), ""] : [dec(part.slice(0, i)), dec(part.slice(i + 1))]);+ }+ }+ /** @internal */ _update() { if (this._url) { const s = this.toString(); this._url._search = s ? "?" + s : ""; } }+ get size() { return this._list.length; }+ append(k: string, v: string) { this._list.push([String(k), String(v)]); this._update(); }+ delete(k: string, v?: string) { this._list = this._list.filter(([a, b]) => a !== k || (v !== undefined && b !== v)); this._update(); }+ get(k: string) { return this._list.find(([a]) => a === k)?.[1] ?? null; }+ getAll(k: string) { return this._list.filter(([a]) => a === k).map(([, b]) => b); }+ has(k: string, v?: string) { return this._list.some(([a, b]) => a === k && (v === undefined || b === v)); }+ set(k: string, v: string) {+ const i = this._list.findIndex(([a]) => a === k);+ if (i < 0) this._list.push([String(k), String(v)]);+ else { this._list[i][1] = String(v); this._list = this._list.filter(([a], j) => a !== k || j === i); }+ this._update();+ }+ sort() { this._list.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)); this._update(); }+ forEach(cb: (v: string, k: string, p: URLSearchParams) => void, thisArg?: any) { for (const [k, v] of this._list) cb.call(thisArg, v, k, this); }+ keys() { return this._list.map(([k]) => k)[Symbol.iterator](); }+ values() { return this._list.map(([, v]) => v)[Symbol.iterator](); }+ entries() { return this._list.map(([k, v]) => [k, v] as [string, string])[Symbol.iterator](); }+ [Symbol.iterator]() { return this.entries(); }+ toString() { return this._list.map(([k, v]) => enc(k) + "=" + enc(v)).join("&"); }+}++// ---------------------------------------------------------------- URL+const SPECIAL: Record<string, string> = { "http:": "80", "https:": "443", "ws:": "80", "wss:": "443", "ftp:": "21", "file:": "" };++function normalizePath(path: string, special: boolean) {+ const out: string[] = [];+ const parts = path.split("/");+ for (let i = 0; i < parts.length; i++) {+ const p = parts[i];+ if (p === "." || p.toLowerCase() === "%2e") { if (i === parts.length - 1) out.push(""); continue; }+ if (p === ".." || /^(\.|%2e){2}$/i.test(p)) { if (out.length > 1) out.pop(); if (i === parts.length - 1) out.push(""); continue; }+ out.push(p);+ }+ let s = out.join("/");+ if (special && !s.startsWith("/")) s = "/" + s;+ return s.replace(/[\s"<>`{}]/g, (c) => encodeURIComponent(c));+}++export class URL {+ /** @internal */ _protocol = ""; /** @internal */ _username = ""; /** @internal */ _password = "";+ /** @internal */ _hostname = ""; /** @internal */ _port = ""; /** @internal */ _pathname = "";+ /** @internal */ _search = ""; /** @internal */ _hash = ""; /** @internal */ _opaque = false;+ /** @internal */ _params: URLSearchParams | null = null;++ constructor(input: string | URL, base?: string | URL) {+ const s = String(input).trim().replace(/[\t\n\r]/g, "");+ const m = /^([a-zA-Z][a-zA-Z0-9+.-]*):(.*)$/.exec(s);+ if (m) this._parseAbsolute(m[1].toLowerCase() + ":", m[2]);+ else {+ if (base === undefined) throw new TypeError(`Invalid URL: ${s}`);+ const b = base instanceof URL ? base : new URL(base);+ this._resolve(s, b);+ }+ }+ static canParse(u: string, b?: string) { try { new URL(u, b); return true; } catch { return false; } }+ static parse(u: string, b?: string) { try { return new URL(u, b); } catch { return null; } }++ /** @internal */ _parseAbsolute(protocol: string, rest: string) {+ this._protocol = protocol;+ const special = protocol in SPECIAL;+ if (special) rest = rest.replace(/\\/g, "/");+ if (rest.startsWith("//") || (special && protocol !== "file:")) {+ rest = rest.replace(/^\/*/, "");+ const end = rest.search(/[/?#]/);+ const auth = end < 0 ? rest : rest.slice(0, end);+ this._setAuthority(auth);+ this._splitPath(end < 0 ? "" : rest.slice(end), special);+ } else if (protocol === "file:") {+ this._splitPath(rest, true);+ } else {+ this._opaque = !rest.startsWith("/");+ this._splitPath(rest, false);+ }+ }+ /** @internal */ _setAuthority(auth: string) {+ const at = auth.lastIndexOf("@");+ if (at >= 0) {+ const cred = auth.slice(0, at);+ auth = auth.slice(at + 1);+ const c = cred.indexOf(":");+ this._username = c < 0 ? cred : cred.slice(0, c);+ this._password = c < 0 ? "" : cred.slice(c + 1);+ }+ const pm = /^(\[[^\]]*\]|[^:]*)(?::(\d*))?$/.exec(auth);+ if (!pm) throw new TypeError("Invalid URL host");+ this._hostname = pm[1].toLowerCase();+ const port = pm[2] ?? "";+ this._port = port && SPECIAL[this._protocol] === port ? "" : port;+ if (!this._hostname && this._protocol in SPECIAL && this._protocol !== "file:") throw new TypeError("Invalid URL: empty host");+ }+ /** @internal */ _splitPath(rest: string, special: boolean) {+ const h = rest.indexOf("#");+ if (h >= 0) { this._hash = rest.slice(h) === "#" ? "" : rest.slice(h); rest = rest.slice(0, h); }+ const q = rest.indexOf("?");+ if (q >= 0) { this._search = rest.slice(q) === "?" ? "" : rest.slice(q); rest = rest.slice(0, q); }+ this._pathname = this._opaque ? rest : normalizePath(rest, special);+ }+ /** @internal */ _resolve(s: string, b: URL) {+ Object.assign(this, { _protocol: b._protocol, _username: b._username, _password: b._password, _hostname: b._hostname, _port: b._port });+ const special = b._protocol in SPECIAL;+ if (special) s = s.replace(/\\/g, "/");+ if (s.startsWith("//")) { this._parseAbsolute(b._protocol, s); return; }+ if (s.startsWith("#")) { this._pathname = b._pathname; this._search = b._search; this._hash = s === "#" ? "" : s; return; }+ if (s.startsWith("?")) { this._pathname = b._pathname; this._splitPath(s, special); return; }+ if (s === "") { this._pathname = b._pathname; this._search = b._search; return; }+ if (s.startsWith("/")) { this._splitPath(s, special); return; }+ const dir = b._pathname.slice(0, b._pathname.lastIndexOf("/") + 1);+ this._splitPath(dir + s, special);+ }++ get protocol() { return this._protocol; }+ set protocol(v: string) { const p = String(v).replace(/:?$/, ":").toLowerCase(); if (/^[a-z][a-z0-9+.-]*:$/.test(p)) { this._protocol = p; if (SPECIAL[p] === this._port) this._port = ""; } }+ get username() { return this._username; } set username(v: string) { this._username = String(v); }+ get password() { return this._password; } set password(v: string) { this._password = String(v); }+ get hostname() { return this._hostname; } set hostname(v: string) { this._hostname = String(v).toLowerCase(); }+ get port() { return this._port; } set port(v: string) { const p = String(v); this._port = p === SPECIAL[this._protocol] ? "" : p.replace(/\D.*$/, ""); }+ get host() { return this._hostname + (this._port ? ":" + this._port : ""); }+ set host(v: string) { this._setAuthority(String(v)); }+ get origin() { return this._protocol in SPECIAL && this._protocol !== "file:" ? `${this._protocol}//${this.host}` : "null"; }+ get pathname() { return this._pathname; }+ set pathname(v: string) { if (!this._opaque) this._pathname = normalizePath(String(v), this._protocol in SPECIAL); }+ get search() { return this._search; }+ set search(v: string) { const s = String(v); this._search = s === "" || s === "?" ? "" : s.startsWith("?") ? s : "?" + s; this._params?._parse(this._search); }+ get searchParams() { if (!this._params) { this._params = new URLSearchParams(this._search); this._params._url = this; } return this._params; }+ get hash() { return this._hash; }+ set hash(v: string) { const s = String(v); this._hash = s === "" || s === "#" ? "" : s.startsWith("#") ? s : "#" + s; }+ get href() {+ const auth = this._username ? this._username + (this._password ? ":" + this._password : "") + "@" : "";+ const slashes = this._opaque ? "" : this._protocol in SPECIAL || this._hostname ? "//" : "";+ return this._protocol + slashes + auth + this.host + this._pathname + this._search + this._hash;+ }+ set href(v: string) { const u = new URL(v); Object.assign(this, u); this._params = null; }+ toString() { return this.href; }+ toJSON() { return this.href; }+ static createObjectURL(_b: unknown): string { throw new DOMExceptionImpl("createObjectURL is not supported", "NotSupportedError"); }+ static revokeObjectURL(_u: string) {}+}++// ---------------------------------------------------------------- text encoding+// Native UTF-8 codecs (crates/net) when present; the JS fallbacks below keep the runtime self-contained.+const nativeNet = (globalThis as any).__native?.net as { utf8Decode?(b: ArrayBuffer | ArrayBufferView): string; utf8Encode?(s: string): Uint8Array } | undefined;++export class TextEncoder {+ readonly encoding = "utf-8";+ encode(s = ""): Uint8Array {+ if (nativeNet?.utf8Encode) return nativeNet.utf8Encode(String(s));+ const str = String(s);+ const out = new Uint8Array(str.length * 3);+ let n = 0;+ for (let i = 0; i < str.length; i++) {+ let c = str.charCodeAt(i);+ if (c >= 0xd800 && c < 0xdc00 && i + 1 < str.length) {+ const d = str.charCodeAt(i + 1);+ if (d >= 0xdc00 && d < 0xe000) { c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00); i++; }+ else c = 0xfffd;+ } else if (c >= 0xd800 && c < 0xe000) c = 0xfffd;+ if (c < 0x80) out[n++] = c;+ else if (c < 0x800) { out[n++] = 0xc0 | (c >> 6); out[n++] = 0x80 | (c & 63); }+ else if (c < 0x10000) { out[n++] = 0xe0 | (c >> 12); out[n++] = 0x80 | ((c >> 6) & 63); out[n++] = 0x80 | (c & 63); }+ else { out[n++] = 0xf0 | (c >> 18); out[n++] = 0x80 | ((c >> 12) & 63); out[n++] = 0x80 | ((c >> 6) & 63); out[n++] = 0x80 | (c & 63); }+ }+ return out.slice(0, n);+ }+ encodeInto(s: string, dest: Uint8Array) { const b = this.encode(s); const n = Math.min(b.length, dest.length); dest.set(b.subarray(0, n)); return { read: s.length, written: n }; }+}++export class TextDecoder {+ readonly encoding: string; readonly fatal: boolean; readonly ignoreBOM: boolean;+ constructor(label = "utf-8", opts: { fatal?: boolean; ignoreBOM?: boolean } = {}) {+ this.encoding = label.toLowerCase().replace("utf8", "utf-8"); this.fatal = !!opts.fatal; this.ignoreBOM = !!opts.ignoreBOM;+ }+ decode(input?: ArrayBuffer | ArrayBufferView): string {+ if (!input) return "";+ const b = input instanceof ArrayBuffer ? new Uint8Array(input) : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);+ if ((this.encoding === "utf-8" || this.encoding === "unicode-1-1-utf-8") && !this.fatal && nativeNet?.utf8Decode) {+ const skip = !this.ignoreBOM && b[0] === 0xef && b[1] === 0xbb && b[2] === 0xbf ? 3 : 0;+ return nativeNet.utf8Decode(skip ? b.subarray(skip) : b);+ }+ if (this.encoding === "utf-16le") { let s = ""; for (let i = 0; i + 1 < b.length; i += 2) s += String.fromCharCode(b[i] | (b[i + 1] << 8)); return s; }+ if (this.encoding === "latin1" || this.encoding === "iso-8859-1" || this.encoding === "ascii") { let s = ""; for (const x of b) s += String.fromCharCode(x); return s; }+ const parts: string[] = [];+ let chunk: number[] = [];+ let i = !this.ignoreBOM && b[0] === 0xef && b[1] === 0xbb && b[2] === 0xbf ? 3 : 0;+ while (i < b.length) {+ const c = b[i];+ let cp = 0xfffd, len = 1;+ if (c < 0x80) { cp = c; }+ else if (c >= 0xc2 && c < 0xe0 && (b[i + 1] & 0xc0) === 0x80) { cp = ((c & 31) << 6) | (b[i + 1] & 63); len = 2; }+ else if (c >= 0xe0 && c < 0xf0 && (b[i + 1] & 0xc0) === 0x80 && (b[i + 2] & 0xc0) === 0x80) { cp = ((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63); len = 3; }+ else if (c >= 0xf0 && c < 0xf5 && (b[i + 1] & 0xc0) === 0x80 && (b[i + 2] & 0xc0) === 0x80 && (b[i + 3] & 0xc0) === 0x80) {+ cp = ((c & 7) << 18) | ((b[i + 1] & 63) << 12) | ((b[i + 2] & 63) << 6) | (b[i + 3] & 63); len = 4;+ } else if (this.fatal) throw new TypeError("The encoded data was not valid utf-8");+ i += len;+ if (cp > 0xffff) { cp -= 0x10000; chunk.push(0xd800 + (cp >> 10), 0xdc00 + (cp & 1023)); } else chunk.push(cp);+ if (chunk.length > 8192) { parts.push(String.fromCharCode(...chunk)); chunk = []; }+ }+ parts.push(String.fromCharCode(...chunk));+ return parts.join("");+ }+}++// ---------------------------------------------------------------- base64+const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+const B64R = new Int16Array(128).fill(-1);+for (let i = 0; i < 64; i++) B64R[B64.charCodeAt(i)] = i;++export function btoa(input: string): string {+ const s = String(input);+ let out = "";+ for (let i = 0; i < s.length; i += 3) {+ const a = s.charCodeAt(i), b = s.charCodeAt(i + 1), c = s.charCodeAt(i + 2);+ if (a > 255 || b > 255 || c > 255) throw new DOMExceptionImpl("The string to be encoded contains characters outside of the Latin1 range.", "InvalidCharacterError");+ const n = (a << 16) | ((b || 0) << 8) | (c || 0);+ out += B64[(n >> 18) & 63] + B64[(n >> 12) & 63] + (i + 1 < s.length ? B64[(n >> 6) & 63] : "=") + (i + 2 < s.length ? B64[n & 63] : "=");+ }+ return out;+}++export function atob(input: string): string {+ const s = String(input).replace(/[\t\n\f\r ]/g, "").replace(/={1,2}$/, "");+ if (s.length % 4 === 1 || /[^A-Za-z0-9+/]/.test(s)) throw new DOMExceptionImpl("The string to be decoded is not correctly encoded.", "InvalidCharacterError");+ let out = "";+ let buf = 0, bits = 0;+ for (let i = 0; i < s.length; i++) {+ buf = (buf << 6) | B64R[s.charCodeAt(i)];+ bits += 6;+ if (bits >= 8) { bits -= 8; out += String.fromCharCode((buf >> bits) & 255); }+ }+ return out;+}++/** bytes → base64 (fast path used by canvas.toDataURL etc.) */+export function bytesToBase64(b: Uint8Array): string {+ let s = "";+ for (let i = 0; i < b.length; i += 0x8000) s += String.fromCharCode(...b.subarray(i, i + 0x8000));+ return btoa(s);+}+export function base64ToBytes(s: string): Uint8Array {+ const bin = atob(s);+ const out = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);+ return out;+}++// ---------------------------------------------------------------- crypto+const hex = (b: Uint8Array) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");+export const crypto = {+ getRandomValues<T extends ArrayBufferView | null>(a: T): T {+ if (!a) return a;+ if ((a as any).byteLength > 65536) throw new DOMExceptionImpl("quota exceeded", "QuotaExceededError");+ __native.sys.randomBytes(a as any);+ return a;+ },+ randomUUID(): string {+ const b = crypto.getRandomValues(new Uint8Array(16));+ b[6] = (b[6] & 0x0f) | 0x40; b[8] = (b[8] & 0x3f) | 0x80;+ const h = hex(b);+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;+ },+ subtle: undefined as any,+};++// ---------------------------------------------------------------- AbortController+export class AbortSignal extends EventTarget {+ aborted = false;+ reason: any = undefined;+ onabort: ((e: Event) => void) | null = null;+ static abort(reason?: any) { const c = new AbortController(); c.abort(reason); return c.signal; }+ static timeout(ms: number) { const c = new AbortController(); (globalThis as any).setTimeout(() => c.abort(new DOMExceptionImpl("signal timed out", "TimeoutError")), ms); return c.signal; }+ throwIfAborted() { if (this.aborted) throw this.reason; }+}+export class AbortController {+ readonly signal = new AbortSignal();+ abort(reason?: any) {+ const s = this.signal;+ if (s.aborted) return;+ s.aborted = true;+ s.reason = reason ?? new DOMExceptionImpl("This operation was aborted", "AbortError");+ const e = new Event("abort");+ s.onabort?.(e);+ s.dispatchEvent(e);+ }+}++// ---------------------------------------------------------------- structuredClone+export function structuredClone<T>(v: T, seen = new Map<any, any>()): T {+ if (typeof v !== "object" || v === null) return v;+ if (seen.has(v)) return seen.get(v);+ if (v instanceof Date) return new Date(v.getTime()) as any;+ if (v instanceof RegExp) return new RegExp(v.source, v.flags) as any;+ if (ArrayBuffer.isView(v)) return (v as any).slice() as any;+ if (v instanceof ArrayBuffer) return v.slice(0) as any;+ if (v instanceof Map) { const m = new Map(); seen.set(v, m); for (const [k, x] of v) m.set(structuredClone(k, seen), structuredClone(x, seen)); return m as any; }+ if (v instanceof Set) { const s = new Set(); seen.set(v, s); for (const x of v) s.add(structuredClone(x, seen)); return s as any; }+ if (Array.isArray(v)) { const a: any[] = []; seen.set(v, a); for (const x of v) a.push(structuredClone(x, seen)); return a as any; }+ const o: any = {};+ seen.set(v, o);+ for (const k of Object.keys(v)) o[k] = structuredClone((v as any)[k], seen);+ return o;+}diff --git a/runtime/js/core/window.ts b/runtime/js/core/window.tsnew file mode 100644index 0000000..7dc090a--- /dev/null+++ b/runtime/js/core/window.ts@@ -0,0 +1,171 @@+// The window object's browser-shaped surface: location, history, navigator, storage, viewport, media+// queries, and the host's window-level events.+import { Event, EventTarget } from "./events.ts";+import { URL } from "./web.ts";++const sys = __native.sys as NativeSys & { storageGet(k: string): string | null; storageSet(k: string, v: string): void; locale(): string };++export const viewport = { width: __boot.width, height: __boot.height, dpr: __boot.dpr };++// ---------------------------------------------------------------- location / history+let current = new URL(__boot.url);+const navigate = (href: string, replace = false) => {+ const next = new URL(href, current.href);+ if (next.origin !== current.origin) {+ // Same-origin navigation guard: keep the window on the app's origin.+ console.warn(`navigation outside ${current.origin} blocked: ${next.href}`);+ return;+ }+ void replace;+ sys.navigate(next.href);+};++export const location = {+ get href() { return current.href; }, set href(v: string) { navigate(v); },+ get origin() { return current.origin; },+ get protocol() { return current.protocol; },+ get host() { return current.host; },+ get hostname() { return current.hostname; },+ get port() { return current.port; },+ get pathname() { return current.pathname; }, set pathname(v: string) { const u = new URL(current.href); u.pathname = v; navigate(u.href); },+ get search() { return current.search; }, set search(v: string) { const u = new URL(current.href); u.search = v; navigate(u.href); },+ get hash() { return current.hash; }, set hash(v: string) { current.hash = v; },+ assign(v: string) { navigate(v); },+ replace(v: string) { navigate(v, true); },+ reload() { sys.navigate(current.href); },+ toString() { return current.href; },+};++const stack: { state: any; url: string }[] = [{ state: null, url: current.href }];+export const history = {+ get length() { return stack.length; },+ get state() { return stack[stack.length - 1].state; },+ scrollRestoration: "auto",+ pushState(state: any, _title: string, url?: string | URL | null) {+ if (url != null) { const u = new URL(String(url), current.href); if (u.origin !== current.origin) throw new Error("SecurityError"); current = u; }+ stack.push({ state, url: current.href });+ },+ replaceState(state: any, _title: string, url?: string | URL | null) {+ if (url != null) { const u = new URL(String(url), current.href); if (u.origin !== current.origin) throw new Error("SecurityError"); current = u; }+ stack[stack.length - 1] = { state, url: current.href };+ },+ back() {}, forward() {}, go() {},+};++// ---------------------------------------------------------------- storage+export class Storage {+ /** @internal */ _map = new Map<string, string>();+ /** @internal */ _key: string | null;+ /** @internal */ _timer = 0;+ constructor(key: string | null) {+ this._key = key;+ if (key) {+ try {+ const saved = sys.storageGet(key);+ if (saved) for (const [k, v] of Object.entries(JSON.parse(saved))) this._map.set(k, String(v));+ } catch { /* start empty */ }+ }+ }+ get length() { return this._map.size; }+ key(i: number) { return [...this._map.keys()][i] ?? null; }+ getItem(k: string) { return this._map.get(String(k)) ?? null; }+ setItem(k: string, v: string) { this._map.set(String(k), String(v)); this._save(); }+ removeItem(k: string) { if (this._map.delete(String(k))) this._save(); }+ clear() { this._map.clear(); this._save(); }+ /** @internal */ _save() {+ // Written through immediately: the file is tiny and a crash must not lose the identity secret.+ if (this._key) sys.storageSet(this._key, JSON.stringify(Object.fromEntries(this._map)));+ }+}+export const localStorage = new Storage("local:" + current.origin);+export const sessionStorage = new Storage(null);++// ---------------------------------------------------------------- navigator / screen+const lang = (() => { try { return sys.locale() || "en-US"; } catch { return "en-US"; } })();+export const navigator = {+ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) ThreeRT/0.1 Safari/605.1.15",+ appName: "Netscape", appVersion: "5.0", vendor: "ThreeRT", product: "Gecko",+ platform: "MacIntel",+ language: lang, languages: [lang, "en-US"],+ hardwareConcurrency: 8, deviceMemory: 8, maxTouchPoints: 0,+ onLine: true, cookieEnabled: false, webdriver: false,+ clipboard: {+ writeText: (t: string) => { (__native.net as any)?.clipboardWrite?.(String(t)); return Promise.resolve(); },+ readText: () => Promise.resolve(String((__native.net as any)?.clipboardRead?.() ?? "")),+ },+ sendBeacon: () => false,+ vibrate: () => false,+ mediaDevices: undefined,+ gpu: undefined,+};+export const screen = {+ get width() { return viewport.width; }, get height() { return viewport.height; },+ get availWidth() { return viewport.width; }, get availHeight() { return viewport.height; },+ colorDepth: 24, pixelDepth: 24, orientation: { type: "landscape-primary", angle: 0, addEventListener() {}, removeEventListener() {} },+};++// ---------------------------------------------------------------- media queries+function evalMedia(q: string): boolean {+ return q.split(",").some((part) => {+ const p = part.trim().toLowerCase();+ if (!p) return false;+ return p.split(/\s+and\s+/).every((cond) => {+ const c = cond.trim();+ if (c === "screen" || c === "all") return true;+ if (c === "print") return false;+ const m = /^\(\s*([a-z-]+)\s*(?::\s*([^)]+))?\)$/.exec(c);+ if (!m) return false;+ const [, f, raw] = m;+ const v = (raw ?? "").trim();+ const px = parseFloat(v);+ switch (f) {+ case "max-width": return viewport.width <= px;+ case "min-width": return viewport.width >= px;+ case "max-height": return viewport.height <= px;+ case "min-height": return viewport.height >= px;+ case "prefers-reduced-motion": return v === "no-preference";+ case "prefers-color-scheme": return v === "light";+ case "hover": return v === "hover";+ case "pointer": return v === "fine";+ case "any-pointer": return v === "fine";+ case "orientation": return v === (viewport.width >= viewport.height ? "landscape" : "portrait");+ case "min-resolution": return viewport.dpr * 96 >= parseFloat(v) * (v.endsWith("dppx") ? 96 : 1);+ case "-webkit-min-device-pixel-ratio": return viewport.dpr >= px;+ default: return false;+ }+ });+ });+}+class MediaQueryList extends EventTarget {+ onchange: any = null;+ constructor(public media: string) { super(); }+ get matches() { return evalMedia(this.media); }+ addListener(f: any) { this.addEventListener("change", f); }+ removeListener(f: any) { this.removeEventListener("change", f); }+}+export function matchMedia(q: string) { return new MediaQueryList(String(q)); }+export { evalMedia };++// ---------------------------------------------------------------- dialogs (the game never uses them)+export function alert(m?: unknown) { console.warn("alert:", m); }+export function confirm(m?: unknown) { console.warn("confirm:", m); return false; }+export function prompt(m?: unknown) { console.warn("prompt:", m); return null; }+export function open(url?: string) { console.warn("window.open blocked:", url); return null; }++// ---------------------------------------------------------------- host window events+export function windowEvent(win: EventTarget & any, doc: any, name: string, data: number[]) {+ switch (name) {+ case "resize":+ viewport.width = data[0]; viewport.height = data[1]; viewport.dpr = data[2];+ win.dispatchEvent(new Event("resize"));+ break;+ case "focus": case "blur":+ win.dispatchEvent(new Event(name));+ break;+ case "visibility": {+ const hidden = data[0] === 0;+ if (doc && doc._hidden !== hidden) { doc._hidden = hidden; doc.dispatchEvent(new Event("visibilitychange", { bubbles: true })); }+ break;+ }+ }+}diff --git a/runtime/js/index.ts b/runtime/js/index.tsnew file mode 100644index 0000000..3bda614--- /dev/null+++ b/runtime/js/index.ts@@ -0,0 +1,131 @@+// ThreeRT native runtime (web-platform globals for JavaScriptCore guests):+// events, timers, console, web utilities, window surface, Canvas 2D, and networking.+//+// Dependencies point one way: runtime/js never imports webgpu/js or renderer/.+// WebGPU builds boot through webgpu/js/index.ts, which calls installRuntime() then installWebGPU().+import * as events from "./core/events.ts";+import * as timers from "./core/timers.ts";+import { console } from "./core/console.ts";+import * as web from "./core/web.ts";+import * as win from "./core/window.ts";+import { installCanvas2D } from "./canvas2d.ts";+import { installNet } from "./net.ts";++let installed = false;++export function installRuntime() {+ if (installed) return;+ installed = true;++ const g = globalThis as any;+ g.window = g; g.self = g; g.top = g; g.parent = g; g.frames = g;+ g.console = console;++ // events+ for (const k of ["Event", "CustomEvent", "UIEvent", "FocusEvent", "MouseEvent", "PointerEvent", "WheelEvent", "KeyboardEvent",+ "InputEvent", "CompositionEvent", "SubmitEvent", "ErrorEvent", "MessageEvent", "CloseEvent", "ProgressEvent", "EventTarget"] as const) {+ g[k] = (events as any)[k];+ }+ g.DOMException = events.DOMExceptionImpl;++ // window is an EventTarget whose methods live on the global object+ const windowTarget = new events.EventTarget();+ g.addEventListener = windowTarget.addEventListener.bind(windowTarget);+ g.removeEventListener = windowTarget.removeEventListener.bind(windowTarget);+ g.dispatchEvent = (e: events.Event) => windowTarget.dispatchEvent(e);+ events.defineHandlers(g, [...events.HANDLER_TYPES, "beforeunload", "unload", "pagehide", "pageshow", "message", "online", "offline", "popstate", "hashchange", "storage", "unhandledrejection"]);+ for (const type of [...events.HANDLER_TYPES, "beforeunload", "unload", "pagehide", "message"]) {+ const desc = Object.getOwnPropertyDescriptor(g, "on" + type)!;+ Object.defineProperty(g, "on" + type, {+ configurable: true, enumerable: true,+ get: () => desc.get!.call(windowTarget),+ set: (v) => desc.set!.call(windowTarget, v),+ });+ }+ events.defineHandlers(events.EventTarget.prototype, []);++ // timers+ Object.assign(g, {+ setTimeout: timers.setTimeout, setInterval: timers.setInterval, clearTimeout: timers.clearTimeout, clearInterval: timers.clearInterval,+ requestAnimationFrame: timers.requestAnimationFrame, cancelAnimationFrame: timers.cancelAnimationFrame,+ queueMicrotask: timers.queueMicrotask,+ requestIdleCallback: (cb: any) => timers.setTimeout(() => cb({ didTimeout: false, timeRemaining: () => 8 }), 1),+ cancelIdleCallback: timers.clearTimeout,+ });++ // performance+ const marks = new Map<string, number>();+ g.performance = {+ now: () => __native.sys.now(),+ timeOrigin: Date.now() - __native.sys.now(),+ mark: (n: string) => { marks.set(n, __native.sys.now()); },+ measure: () => {},+ getEntriesByName: () => [], getEntriesByType: () => [], clearMarks: () => marks.clear(), clearMeasures: () => {},+ memory: undefined,+ toJSON() { return {}; },+ };++ // web utilities+ Object.assign(g, {+ URL: web.URL, URLSearchParams: web.URLSearchParams, TextEncoder: web.TextEncoder, TextDecoder: web.TextDecoder,+ atob: web.atob, btoa: web.btoa, crypto: web.crypto, AbortController: web.AbortController, AbortSignal: web.AbortSignal,+ structuredClone: web.structuredClone,+ });++ // window surface+ Object.defineProperties(g, {+ innerWidth: { get: () => win.viewport.width, configurable: true },+ innerHeight: { get: () => win.viewport.height, configurable: true },+ outerWidth: { get: () => win.viewport.width, configurable: true },+ outerHeight: { get: () => win.viewport.height, configurable: true },+ devicePixelRatio: { get: () => win.viewport.dpr, configurable: true },+ scrollX: { value: 0, configurable: true }, scrollY: { value: 0, configurable: true },+ pageXOffset: { value: 0, configurable: true }, pageYOffset: { value: 0, configurable: true },+ screenX: { value: 0, configurable: true }, screenY: { value: 0, configurable: true },+ isSecureContext: { value: true, configurable: true },+ origin: { get: () => win.location.origin, configurable: true },+ closed: { value: false, configurable: true },+ name: { value: "", writable: true, configurable: true },+ });+ Object.assign(g, {+ location: win.location, history: win.history, navigator: win.navigator, screen: win.screen,+ localStorage: win.localStorage, sessionStorage: win.sessionStorage, Storage: win.Storage,+ matchMedia: win.matchMedia, alert: win.alert, confirm: win.confirm, prompt: win.prompt, open: win.open,+ close: () => __native.sys.closeWindow(), focus: () => {}, blur: () => {}, scrollTo: () => {}, scroll: () => {}, scrollBy: () => {},+ print: () => {}, stop: () => {}, postMessage: () => {},+ });++ // optional native subsystems (only mounted when the host installs them on __native)+ if (__native.c2d) installCanvas2D();+ if (__native.net) installNet();++ // Minimal document surface for libraries (three.js, UI helpers) without a browser DOM.+ const documentTarget = new events.EventTarget() as events.EventTarget & { _hidden?: boolean };+ let focused = true;+ windowTarget.addEventListener("focus", () => { focused = true; });+ windowTarget.addEventListener("blur", () => { focused = false; });+ g.document = Object.assign(documentTarget, {+ get hidden() { return !!documentTarget._hidden; },+ get visibilityState() { return documentTarget._hidden ? "hidden" : "visible"; },+ hasFocus: () => focused,+ get title() { return __boot.title ?? ""; },+ set title(_v: string) { /* the shell owns the window title */ },+ documentElement: { lang: __boot.lang ?? "en-US", style: {} },+ createElement(tag: string) {+ if (String(tag).toLowerCase() === "canvas") return new g.OffscreenCanvas(300, 150);+ throw new DOMException(`no DOM in this runtime: <${tag}>`, "NotSupportedError");+ },+ });++ g.__rt = {+ boot() {},+ timers(now: number) { timers.runTimers(now); },+ frame(now: number) { timers.runFrame(now); },+ windowEvent(name: string, ...data: number[]) {+ win.windowEvent(windowTarget, documentTarget, name, data);+ },+ unload() {+ try { windowTarget.dispatchEvent(new events.Event("pagehide")); windowTarget.dispatchEvent(new events.Event("unload")); } catch { /* */ }+ },+ };+}diff --git a/runtime/js/native.d.ts b/runtime/js/native.d.tsnew file mode 100644index 0000000..3ebc565--- /dev/null+++ b/runtime/js/native.d.ts@@ -0,0 +1,52 @@+// The native host API, installed by the Rust runtime as `globalThis.__native` before runtime JS runs.+// Every module owns one namespace (`sys`, `gpu`, `c2d`, `net`).++interface NativeSys {+ /** page time in ms (performance.now()) */+ now(): number;+ /** wake the page at page time `ms` (earliest pending timer); Infinity cancels */+ wakeAt(ms: number): void;+ /** ask for an animation frame (__rt.frame will be called) */+ requestFrame(): void;+ log(level: "log" | "info" | "warn" | "error" | "debug", message: string): void;+ /** load a new page (navigation / reload) */+ navigate(url: string): void;+ /** message to the host shell bridge */+ shell(name: string, ...args: string[]): void;+ closeWindow(): void;+ /** test hook: write a PNG of the next composited frame */+ shot(path: string): void;+ /** test hook: quit the app */+ exit(code?: number): void;+ /** text file shipped next to the bundle, or null */+ resource(name: string): string | null;+ /** fill a typed array with CSPRNG bytes (returns it) */+ randomBytes<T extends ArrayBufferView>(a: T): T;+}++interface NativeHost {+ sys: NativeSys;+ /** WebGPU over wgpu (webgpu/, webgpu/js/webgpu.ts); absent without a GPU device */+ gpu?: any;+ /** Canvas 2D + image decoding/encoding (runtime/crates/canvas2d, runtime/js/canvas2d.ts) */+ c2d?: any;+ /** fetch / WebSocket / storage / clipboard / audio (runtime/crates/net, runtime/js/net.ts) */+ net?: any;+}++declare var __native: NativeHost;++/** Boot parameters from the host. */+declare var __boot: { url: string; width: number; height: number; dpr: number; lang: string; title: string };++/** Entry points the host calls (defined by runtime/index.ts). */+interface RuntimeEntry {+ boot(): void;+ timers(now: number): void;+ frame(now: number): void;+ windowEvent(name: string, ...data: number[]): void;+ unload(): void;+ /** UI engine → DOM events (see runtime/dom/events) */+ [key: string]: any;+}+declare var __rt: RuntimeEntry;diff --git a/runtime/js/net.ts b/runtime/js/net.tsnew file mode 100644index 0000000..bc2f094--- /dev/null+++ b/runtime/js/net.ts@@ -0,0 +1,1201 @@+// Network, clipboard and audio globals on top of `__native.net` (crates/net):+// fetch / Request / Response / Headers / Blob / File / FormData, WebSocket, AudioContext.+//+// Native work happens on worker threads; results come back through one handler installed with+// `setHandler(fn)`: `fn(kind, id, ...)`. Bodies and binary messages arrive as ArrayBuffers and are+// decoded natively (`utf8Decode`), so no byte-by-byte JavaScript runs on network data.+import { Event, EventTarget, MessageEvent, CloseEvent, DOMExceptionImpl as DOMException, defineHandlers } from "./core/events.ts";+import { URL, URLSearchParams, AbortSignal, base64ToBytes } from "./core/web.ts";+import { location, navigator } from "./core/window.ts";++interface NativeNet {+ setHandler(fn: (kind: number, id: number, ...args: any[]) => void, userAgent: string): void;+ fetch(id: number, method: string, url: string, headers: string[], body: string | Uint8Array | null, redirect: number): void;+ fetchAbort(id: number): void;+ wsOpen(id: number, url: string, protocols: string[], origin: string, acceptLanguage: string): void;+ wsSend(id: number, data: string | ArrayBuffer | Uint8Array): void;+ wsClose(id: number, code: number, reason: string): void;+ wsBuffered(id: number): number;+ utf8Decode(b: ArrayBuffer | ArrayBufferView): string;+ utf8Encode(s: string): Uint8Array;+ clipboardWrite(s: string): boolean;+ clipboardRead(): string;+ audioRate(): number;+ audioCreate(): number;+ audioTime(ctx: number): number;+ audioSuspend(ctx: number): void;+ audioResume(ctx: number): void;+ audioClose(ctx: number): void;+ audioNode(ctx: number, kind: number): number;+ audioConnect(from: number, to: number, param: number): void;+ audioDisconnect(from: number, to: number, param: number): void;+ audioParam(node: number, index: number, intrinsic: number, events: Float64Array): void;+ audioParamValue(events: Float64Array, intrinsic: number, t: number): number;+ audioWave(node: number, wave: number): void;+ audioStart(node: number, when: number): void;+ audioStop(node: number, when: number): void;+ audioWantEnded(node: number): void;+ audioRelease(node: number): void;+}++const native = __native.net as NativeNet;+const g = globalThis as any;++const FETCH_HEAD = 1, FETCH_BODY = 2, FETCH_ERROR = 3;+const WS_OPEN = 10, WS_TEXT = 11, WS_BINARY = 12, WS_CLOSE = 13;+const AUDIO_ENDED = 20;++const decodeUtf8 = (b: ArrayBuffer | ArrayBufferView) => native.utf8Decode(b);+const encodeUtf8 = (s: string) => native.utf8Encode(s);+const swallow = () => {};+/** Network errors go to the log the way Chromium's console shows them, without calling the page's+ * (possibly hooked) console.error. */+const netLog = (msg: string) => __native.sys.log("error", msg);++// ---------------------------------------------------------------- byte helpers++function isBufferSource(v: any): v is ArrayBuffer | ArrayBufferView {+ return v instanceof ArrayBuffer || ArrayBuffer.isView(v) || Object.prototype.toString.call(v) === "[object SharedArrayBuffer]";+}++/** A copy of a buffer source's bytes (the page may mutate its buffer afterwards). */+function copyBytes(v: ArrayBuffer | ArrayBufferView): Uint8Array {+ if (ArrayBuffer.isView(v)) return new Uint8Array(v.buffer, v.byteOffset, v.byteLength).slice();+ return new Uint8Array(v as ArrayBuffer).slice();+}++function concat(parts: Uint8Array[]): Uint8Array {+ if (parts.length === 1) return parts[0];+ let n = 0;+ for (const p of parts) n += p.length;+ const out = new Uint8Array(n);+ let o = 0;+ for (const p of parts) { out.set(p, o); o += p.length; }+ return out;+}++/** An ArrayBuffer holding exactly these bytes (no copy when the view covers its buffer). */+function exactBuffer(b: Uint8Array): ArrayBuffer {+ return b.byteOffset === 0 && b.byteLength === b.buffer.byteLength ? (b.buffer as ArrayBuffer) : (b.slice().buffer as ArrayBuffer);+}++function utf8Length(s: string) {+ let n = 0;+ for (let i = 0; i < s.length; i++) {+ const c = s.charCodeAt(i);+ if (c < 0x80) n += 1;+ else if (c < 0x800) n += 2;+ else if (c >= 0xd800 && c < 0xdc00 && i + 1 < s.length && (s.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { n += 4; i++; }+ else n += 3;+ }+ return n;+}++// ---------------------------------------------------------------- Blob / File++const BYTES = Symbol("bytes");++export class Blob {+ /** @internal */ [BYTES]: Uint8Array;+ readonly type: string;+ constructor(parts: any[] = [], options: { type?: string; endings?: string } = {}) {+ if (parts == null || typeof parts !== "object" || typeof (parts as any)[Symbol.iterator] !== "function") {+ throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");+ }+ const chunks: Uint8Array[] = [];+ for (const p of parts) {+ if (p instanceof Blob) chunks.push(p[BYTES]);+ else if (isBufferSource(p)) chunks.push(copyBytes(p));+ else {+ let s = String(p);+ if (options.endings === "native") s = s.replace(/\r\n|\r/g, "\n");+ chunks.push(encodeUtf8(s));+ }+ }+ this[BYTES] = chunks.length ? concat(chunks) : new Uint8Array(0);+ const t = options.type === undefined ? "" : String(options.type);+ this.type = /^[\x20-\x7e]*$/.test(t) ? t.toLowerCase() : "";+ }+ get size() { return this[BYTES].length; }+ slice(start = 0, end = this.size, type = "") {+ const n = this.size;+ const s = start < 0 ? Math.max(n + start, 0) : Math.min(start, n);+ const e = end < 0 ? Math.max(n + end, 0) : Math.min(end, n);+ const b = new Blob([], { type });+ b[BYTES] = this[BYTES].slice(s, Math.max(s, e));+ return b;+ }+ text() { return Promise.resolve(decodeUtf8(this[BYTES])); }+ arrayBuffer() { return Promise.resolve(this[BYTES].slice().buffer as ArrayBuffer); }+ bytes() { return Promise.resolve(this[BYTES].slice()); }+ stream() { return new ByteStream(Promise.resolve(this[BYTES])); }+ get [Symbol.toStringTag]() { return "Blob"; }+}++export class File extends Blob {+ readonly name: string;+ readonly lastModified: number;+ readonly webkitRelativePath = "";+ constructor(parts: any[], name: string, options: { type?: string; lastModified?: number } = {}) {+ super(parts, options);+ if (arguments.length < 2) throw new TypeError("Failed to construct 'File': 2 arguments required, but only " + arguments.length + " present.");+ this.name = String(name);+ this.lastModified = options.lastModified === undefined ? Date.now() : Number(options.lastModified);+ }+ get [Symbol.toStringTag]() { return "File"; }+}++// ---------------------------------------------------------------- ReadableStream (minimal)++/** `Response.body` / `Blob.stream()`: one chunk holding the whole body. Enough for readers and+ * `for await`; JavaScriptCore has no streams of its own here. */+class ByteStream {+ /** @internal */ _bytes: Promise<Uint8Array>;+ /** @internal */ _locked = false;+ /** @internal */ _done = false;+ constructor(bytes: Promise<Uint8Array>) { this._bytes = bytes; }+ get locked() { return this._locked; }+ getReader() {+ if (this._locked) throw new TypeError("ReadableStreamDefaultReader constructor can only accept readable streams that are not yet locked to a reader");+ this._locked = true;+ const self = this;+ return {+ read(): Promise<{ value: Uint8Array | undefined; done: boolean }> {+ if (self._done) return Promise.resolve({ value: undefined, done: true });+ self._done = true;+ return self._bytes.then((b) => (b.length ? { value: b, done: false } : { value: undefined, done: true }));+ },+ releaseLock() { self._locked = false; },+ cancel() { self._done = true; return Promise.resolve(); },+ get closed() { return self._bytes.then(() => undefined); },+ };+ }+ cancel() { this._done = true; return Promise.resolve(); }+ async *[Symbol.asyncIterator]() {+ const r = this.getReader();+ for (;;) { const { value, done } = await r.read(); if (done) return; yield value; }+ }+}++// ---------------------------------------------------------------- FormData++type FormValue = string | File;++const BOUNDARY_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";++export class FormData {+ /** @internal */ _entries: [string, FormValue][] = [];+ constructor(form?: any) {+ if (form == null) return;+ // <form> element: its named, enabled, successful controls.+ const controls: any[] = form.elements ? Array.from(form.elements) : form.querySelectorAll ? Array.from(form.querySelectorAll("input,select,textarea,button")) : [];+ for (const el of controls) {+ const name = el.name ?? el.getAttribute?.("name");+ if (!name || el.disabled) continue;+ const tag = String(el.tagName ?? "").toLowerCase();+ const type = String(el.type ?? "").toLowerCase();+ if (tag === "button" || ["submit", "button", "reset", "image", "file"].includes(type)) continue;+ if ((type === "checkbox" || type === "radio") && !el.checked) continue;+ if (tag === "select") {+ for (const o of Array.from(el.options ?? []) as any[]) if (o.selected) this.append(name, o.value);+ continue;+ }+ this.append(name, type === "checkbox" || type === "radio" ? (el.value || "on") : String(el.value ?? ""));+ }+ }+ /** @internal */ _value(value: any, filename?: string): FormValue {+ if (value instanceof Blob) {+ if (value instanceof File && filename === undefined) return value;+ return new File([value], filename !== undefined ? String(filename) : value instanceof File ? value.name : "blob", { type: value.type });+ }+ return String(value);+ }+ append(name: string, value: any, filename?: string) { this._entries.push([String(name), this._value(value, filename)]); }+ set(name: string, value: any, filename?: string) {+ const n = String(name), v = this._value(value, filename);+ const i = this._entries.findIndex(([k]) => k === n);+ if (i < 0) this._entries.push([n, v]);+ else { this._entries[i] = [n, v]; this._entries = this._entries.filter(([k], j) => k !== n || j === i); }+ }+ get(name: string) { return this._entries.find(([k]) => k === String(name))?.[1] ?? null; }+ getAll(name: string) { return this._entries.filter(([k]) => k === String(name)).map(([, v]) => v); }+ has(name: string) { return this._entries.some(([k]) => k === String(name)); }+ delete(name: string) { this._entries = this._entries.filter(([k]) => k !== String(name)); }+ forEach(cb: (v: FormValue, k: string, f: FormData) => void, thisArg?: any) { for (const [k, v] of this._entries.slice()) cb.call(thisArg, v, k, this); }+ keys() { return this._entries.map(([k]) => k)[Symbol.iterator](); }+ values() { return this._entries.map(([, v]) => v)[Symbol.iterator](); }+ entries() { return this._entries.map(([k, v]) => [k, v] as [string, FormValue])[Symbol.iterator](); }+ [Symbol.iterator]() { return this.entries(); }+ get [Symbol.toStringTag]() { return "FormData"; }++ /** @internal multipart/form-data, laid out like Chromium (`----WebKitFormBoundary…`). */+ _encode(): { bytes: Uint8Array; type: string } {+ const rnd = crypto.getRandomValues(new Uint8Array(16));+ const boundary = "----WebKitFormBoundary" + Array.from(rnd, (b) => BOUNDARY_CHARS[b % 62]).join("");+ const esc = (s: string) => s.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22");+ const parts: Uint8Array[] = [];+ for (const [name, v] of this._entries) {+ let head = `--${boundary}\r\nContent-Disposition: form-data; name="${esc(name.replace(/\r\n|\r|\n/g, "\r\n"))}"`;+ if (typeof v === "string") {+ parts.push(encodeUtf8(head + "\r\n\r\n" + v.replace(/\r\n|\r|\n/g, "\r\n") + "\r\n"));+ } else {+ head += `; filename="${esc(v.name)}"\r\nContent-Type: ${v.type || "application/octet-stream"}\r\n\r\n`;+ parts.push(encodeUtf8(head), v[BYTES], encodeUtf8("\r\n"));+ }+ }+ parts.push(encodeUtf8(`--${boundary}--\r\n`));+ return { bytes: concat(parts), type: `multipart/form-data; boundary=${boundary}` };+ }+}++function parseFormData(bytes: Uint8Array, contentType: string): FormData {+ const fd = new FormData();+ const mime = contentType.split(";")[0].trim().toLowerCase();+ if (mime === "application/x-www-form-urlencoded") {+ for (const [k, v] of new URLSearchParams(decodeUtf8(bytes))) fd.append(k, v);+ return fd;+ }+ if (mime === "multipart/form-data") {+ const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType);+ if (!m) throw new TypeError("Failed to fetch");+ const boundary = "--" + (m[1] ?? m[2]).trim();+ // Latin-1 view of the body keeps byte offsets equal to string offsets.+ let text = "";+ for (let i = 0; i < bytes.length; i += 0x8000) text += String.fromCharCode(...bytes.subarray(i, i + 0x8000));+ let pos = text.indexOf(boundary);+ while (pos >= 0) {+ const start = pos + boundary.length;+ if (text.startsWith("--", start)) break;+ const headEnd = text.indexOf("\r\n\r\n", start);+ const next = text.indexOf("\r\n" + boundary, headEnd);+ if (headEnd < 0 || next < 0) break;+ const head = decodeUtf8(bytes.subarray(start, headEnd));+ const body = bytes.subarray(headEnd + 4, next);+ const name = /name="([^"]*)"/i.exec(head)?.[1] ?? "";+ const filename = /filename="([^"]*)"/i.exec(head)?.[1];+ const type = /content-type:\s*([^\r\n]+)/i.exec(head)?.[1]?.trim() ?? "";+ if (filename !== undefined) fd.append(name, new File([body], filename, { type }));+ else fd.append(name, decodeUtf8(body));+ pos = next + 2;+ }+ return fd;+ }+ throw new TypeError("Failed to execute 'formData' on 'Response': Could not parse content as FormData.");+}++// ---------------------------------------------------------------- Headers++const FORBIDDEN_REQUEST = new Set([+ "accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "connection",+ "content-length", "cookie", "cookie2", "date", "dnt", "expect", "host", "keep-alive", "origin", "referer", "set-cookie",+ "te", "trailer", "transfer-encoding", "upgrade", "user-agent", "via",+]);+const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;++type Guard = "none" | "request" | "response" | "immutable";++function normalizeValue(v: any, method: string) {+ const s = String(v).replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, "");+ if (/[\0\r\n]/.test(s) || /[^\x00-\xff]/.test(s)) throw new TypeError(`Failed to execute '${method}' on 'Headers': Invalid value`);+ return s;+}+function checkName(n: any, method: string) {+ const s = String(n);+ if (!TOKEN.test(s)) throw new TypeError(`Failed to execute '${method}' on 'Headers': Invalid name`);+ return s.toLowerCase();+}++export class Headers {+ /** @internal */ _list: [string, string][] = [];+ /** @internal */ _guard: Guard = "none";+ constructor(init?: any) {+ if (init == null) return;+ if (init instanceof Headers) { this._list = init._list.map(([k, v]) => [k, v]); return; }+ if (typeof init !== "object") throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(record<ByteString, ByteString> or sequence<sequence<ByteString>>)'.");+ if (typeof init[Symbol.iterator] === "function") {+ for (const pair of init) {+ const p = Array.from(pair as any);+ if (p.length !== 2) throw new TypeError("Failed to construct 'Headers': Invalid value");+ this.append(p[0] as string, p[1] as string);+ }+ } else {+ for (const k of Object.keys(init)) this.append(k, init[k]);+ }+ }+ /** @internal */ _allowed(name: string) {+ if (this._guard === "immutable") throw new TypeError("Failed to execute on 'Headers': Headers are immutable");+ if (this._guard === "request" && (FORBIDDEN_REQUEST.has(name) || name.startsWith("proxy-") || name.startsWith("sec-"))) return false;+ if (this._guard === "response" && (name === "set-cookie" || name === "set-cookie2")) return false;+ return true;+ }+ append(name: string, value: string) {+ const n = checkName(name, "append"), v = normalizeValue(value, "append");+ if (this._allowed(n)) this._list.push([n, v]);+ }+ set(name: string, value: string) {+ const n = checkName(name, "set"), v = normalizeValue(value, "set");+ if (!this._allowed(n)) return;+ const i = this._list.findIndex(([k]) => k === n);+ if (i < 0) this._list.push([n, v]);+ else { this._list[i] = [n, v]; this._list = this._list.filter(([k], j) => k !== n || j === i); }+ }+ delete(name: string) {+ const n = checkName(name, "delete");+ if (this._allowed(n)) this._list = this._list.filter(([k]) => k !== n);+ }+ get(name: string) {+ const n = checkName(name, "get");+ const vs = this._list.filter(([k]) => k === n).map(([, v]) => v);+ return vs.length ? vs.join(", ") : null;+ }+ getSetCookie(): string[] { return []; }+ has(name: string) { const n = checkName(name, "has"); return this._list.some(([k]) => k === n); }+ /** @internal sorted, combined (the iteration order of the Fetch standard) */+ _sorted(): [string, string][] {+ const names = [...new Set(this._list.map(([k]) => k))].sort();+ return names.map((n) => [n, this._list.filter(([k]) => k === n).map(([, v]) => v).join(", ")]);+ }+ forEach(cb: (v: string, k: string, h: Headers) => void, thisArg?: any) { for (const [k, v] of this._sorted()) cb.call(thisArg, v, k, this); }+ keys() { return this._sorted().map(([k]) => k)[Symbol.iterator](); }+ values() { return this._sorted().map(([, v]) => v)[Symbol.iterator](); }+ entries() { return this._sorted()[Symbol.iterator](); }+ [Symbol.iterator]() { return this.entries(); }+ get [Symbol.toStringTag]() { return "Headers"; }+}++function guarded(init: any, guard: Guard) {+ const h = new Headers();+ h._guard = guard === "immutable" ? "none" : guard;+ if (init != null) {+ const src = init instanceof Headers ? init._list : new Headers(init)._list;+ for (const [k, v] of src) if (h._allowed(k)) h._list.push([k, v]);+ }+ h._guard = guard;+ return h;+}++// ---------------------------------------------------------------- Body++type BodySource = string | Uint8Array | null;++interface Extracted { src: BodySource; type: string | null }++function extractBody(body: any): Extracted {+ if (body == null) return { src: null, type: null };+ if (typeof body === "string") return { src: body, type: "text/plain;charset=UTF-8" };+ if (body instanceof URLSearchParams) return { src: body.toString(), type: "application/x-www-form-urlencoded;charset=UTF-8" };+ if (body instanceof Blob) return { src: body[BYTES], type: body.type || null };+ if (body instanceof FormData) { const e = body._encode(); return { src: e.bytes, type: e.type }; }+ if (isBufferSource(body)) return { src: copyBytes(body), type: null };+ if (body instanceof ByteStream) throw new TypeError("Streaming request bodies are not supported");+ return { src: String(body), type: "text/plain;charset=UTF-8" };+}++const NULL_BODY_STATUS = new Set([101, 103, 204, 205, 304]);++abstract class Body {+ /** @internal */ _src: BodySource = null;+ /** @internal body still arriving from the network */ _pending: Promise<Uint8Array> | null = null;+ /** @internal */ _used = false;+ /** @internal */ _hasBody = false;+ /** @internal */ _stream: ByteStream | null = null;+ abstract readonly headers: Headers;+ /** @internal */ abstract _kind(): string;++ get bodyUsed() { return this._used; }+ get body(): any {+ if (!this._hasBody) return null;+ return (this._stream ??= new ByteStream(this._peek().then((b) => (typeof b === "string" ? encodeUtf8(b) : b))));+ }+ /** @internal the body without consuming it */+ _peek(): Promise<string | Uint8Array> {+ if (this._pending) return this._pending;+ return Promise.resolve(this._src ?? new Uint8Array(0));+ }+ /** @internal */ _consume(method: string): Promise<string | Uint8Array> {+ if (this._used || this._stream?.locked) {+ return Promise.reject(new TypeError(`Failed to execute '${method}' on '${this._kind()}': body stream already read`));+ }+ if (this._hasBody) this._used = true;+ return this._peek();+ }+ arrayBuffer(): Promise<ArrayBuffer> {+ return this._consume("arrayBuffer").then((b) => (typeof b === "string" ? exactBuffer(encodeUtf8(b)) : exactBuffer(b)));+ }+ bytes(): Promise<Uint8Array> {+ return this._consume("bytes").then((b) => (typeof b === "string" ? encodeUtf8(b) : b));+ }+ text(): Promise<string> {+ return this._consume("text").then((b) => (typeof b === "string" ? b : decodeUtf8(b)));+ }+ json(): Promise<any> {+ return this.text().then((t) => JSON.parse(t));+ }+ blob(): Promise<Blob> {+ const type = this.headers.get("content-type") ?? "";+ return this._consume("blob").then((b) => {+ const blob = new Blob([], { type });+ blob[BYTES] = typeof b === "string" ? encodeUtf8(b) : b;+ return blob;+ });+ }+ formData(): Promise<FormData> {+ const type = this.headers.get("content-type") ?? "";+ return this._consume("formData").then((b) => parseFormData(typeof b === "string" ? encodeUtf8(b) : b, type));+ }+}++// ---------------------------------------------------------------- Request++const NORMALIZED_METHODS = ["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"];++function parseUrl(input: string, what: string) {+ let u: URL;+ try { u = new URL(input, location.href); } catch { throw new TypeError(`Failed to ${what}: Failed to parse URL from ${input}`); }+ if (u.username || u.password) throw new TypeError(`Failed to ${what}: Request cannot be constructed from a URL that includes credentials: ${input}`);+ return u;+}++export class Request extends Body {+ readonly method: string;+ readonly url: string;+ readonly headers: Headers;+ readonly signal: AbortSignal;+ readonly redirect: RequestRedirect;+ readonly mode: RequestMode;+ readonly credentials: RequestCredentials;+ readonly cache: RequestCache;+ readonly referrer: string;+ readonly referrerPolicy: ReferrerPolicy;+ readonly integrity: string;+ readonly keepalive: boolean;+ readonly destination = "";+ readonly duplex = "half";+ constructor(input: any, init: any = {}) {+ super();+ const from = input instanceof Request ? input : null;+ if (init == null) init = {};+ const url = from ? from.url : parseUrl(String(input), "construct 'Request'").href.replace(/#.*$/, "");+ this.url = url;+ let method = init.method !== undefined ? String(init.method) : from ? from.method : "GET";+ if (!TOKEN.test(method)) throw new TypeError(`Failed to construct 'Request': '${method}' is not a valid HTTP method.`);+ const upper = method.toUpperCase();+ if (upper === "CONNECT" || upper === "TRACE" || upper === "TRACK") throw new TypeError(`Failed to construct 'Request': '${method}' HTTP method is unsupported.`);+ if (NORMALIZED_METHODS.includes(upper)) method = upper;+ this.method = method;+ this.mode = init.mode ?? from?.mode ?? "cors";+ if (this.mode === "navigate") throw new TypeError("Failed to construct 'Request': Cannot construct a Request with a RequestInit whose mode member is set as 'navigate'.");+ this.credentials = init.credentials ?? from?.credentials ?? "same-origin";+ this.cache = init.cache ?? from?.cache ?? "default";+ this.redirect = init.redirect ?? from?.redirect ?? "follow";+ if (!["follow", "error", "manual"].includes(this.redirect)) throw new TypeError(`Failed to construct 'Request': The provided value '${this.redirect}' is not a valid enum value of type RequestRedirect.`);+ this.referrer = init.referrer !== undefined ? (init.referrer === "" ? "" : "about:client") : from?.referrer ?? "about:client";+ this.referrerPolicy = init.referrerPolicy ?? from?.referrerPolicy ?? "";+ this.integrity = init.integrity ?? from?.integrity ?? "";+ this.keepalive = !!(init.keepalive ?? from?.keepalive);+ this.signal = init.signal !== undefined ? (init.signal ?? new AbortSignal()) : from?.signal ?? new AbortSignal();+ this.headers = guarded(init.headers !== undefined ? init.headers : from?.headers, "request");++ const hasInitBody = init.body !== undefined && init.body !== null;+ if ((hasInitBody || (from?._hasBody && init.body === undefined)) && (method === "GET" || method === "HEAD")) {+ throw new TypeError("Failed to construct 'Request': Request with GET/HEAD method cannot have body.");+ }+ if (hasInitBody) {+ const e = extractBody(init.body);+ this._src = e.src;+ this._hasBody = true;+ if (e.type && !this.headers.has("content-type")) this.headers._list.push(["content-type", e.type]);+ } else if (from?._hasBody && init.body === undefined) {+ if (from.bodyUsed) throw new TypeError("Failed to construct 'Request': Cannot construct a Request with a Request object that has already been used.");+ this._src = from._src;+ this._pending = from._pending;+ this._hasBody = true;+ from._used = true; // the body moves to the new request+ }+ }+ /** @internal */ _kind() { return "Request"; }+ clone(): Request {+ if (this.bodyUsed) throw new TypeError("Failed to execute 'clone' on 'Request': Request body is already used");+ const r = new Request(this, {});+ // `new Request(this)` moved the body; a clone shares it instead.+ this._used = false;+ return r;+ }+ get [Symbol.toStringTag]() { return "Request"; }+}++// ---------------------------------------------------------------- Response++const STATUS_TEXT_OK = /^[\t\x20-\x7e\x80-\xff]*$/;++export class Response extends Body {+ readonly headers: Headers;+ /** @internal */ _status: number;+ /** @internal */ _statusText: string;+ /** @internal */ _type: ResponseType = "default";+ /** @internal */ _url = "";+ /** @internal */ _redirected = false;+ constructor(body: any = null, init: any = {}) {+ super();+ if (init == null) init = {};+ const status = init.status === undefined ? 200 : Number(init.status);+ if (!(status >= 200 && status <= 599) || !Number.isInteger(status)) {+ throw new RangeError(`Failed to construct 'Response': The status provided (${init.status}) is outside the range [200, 599].`);+ }+ const statusText = init.statusText === undefined ? "" : String(init.statusText);+ if (!STATUS_TEXT_OK.test(statusText)) throw new TypeError("Failed to construct 'Response': Invalid statusText");+ this._status = status;+ this._statusText = statusText;+ this.headers = guarded(init.headers, "response");+ if (body != null) {+ if (NULL_BODY_STATUS.has(status)) throw new TypeError("Failed to construct 'Response': Response with null body status cannot have body");+ const e = extractBody(body);+ this._src = e.src;+ this._hasBody = true;+ if (e.type && !this.headers.has("content-type")) this.headers._list.push(["content-type", e.type]);+ }+ }+ /** @internal */ _kind() { return "Response"; }+ get type() { return this._type; }+ get url() { return this._url; }+ get redirected() { return this._redirected; }+ get status() { return this._status; }+ get ok() { return this._status >= 200 && this._status <= 299; }+ get statusText() { return this._statusText; }+ clone(): Response {+ if (this.bodyUsed || this._stream?.locked) throw new TypeError("Failed to execute 'clone' on 'Response': Response body is already used");+ const r = Object.create(Response.prototype) as Response;+ Object.assign(r, { _src: this._src, _pending: this._pending, _used: false, _hasBody: this._hasBody, _stream: null });+ (r as any).headers = guarded(this.headers, this.headers._guard);+ Object.assign(r, { _status: this._status, _statusText: this._statusText, _type: this._type, _url: this._url, _redirected: this._redirected });+ return r;+ }+ static error(): Response {+ const r = new Response(null, { status: 200 });+ Object.assign(r, { _status: 0, _type: "error" });+ r.headers._guard = "immutable";+ return r;+ }+ static redirect(url: string | URL, status = 302): Response {+ const u = parseUrl(String(url), "execute 'redirect' on 'Response'");+ if (![301, 302, 303, 307, 308].includes(status)) throw new RangeError("Failed to execute 'redirect' on 'Response': Invalid status code");+ const r = new Response(null, { status, headers: { location: u.href } });+ r.headers._guard = "immutable";+ return r;+ }+ static json(data: any, init: any = {}): Response {+ const text = JSON.stringify(data);+ if (text === undefined) throw new TypeError("Failed to execute 'json' on 'Response': The data is not JSON serializable");+ const headers = guarded(init?.headers, "response");+ if (!headers.has("content-type")) headers.set("content-type", "application/json");+ return new Response(text, { ...init, headers });+ }+ get [Symbol.toStringTag]() { return "Response"; }+}++// ---------------------------------------------------------------- fetch++interface PendingFetch {+ method: string;+ resolve: (r: Response) => void;+ reject: (e: any) => void;+ url: URL;+ response: Response | null;+ bodyResolve: ((b: Uint8Array) => void) | null;+ bodyReject: ((e: any) => void) | null;+ cleanup: () => void;+}++const fetches = new Map<number, PendingFetch>();+let nextFetchId = 1;++function acceptLanguage() {+ const langs: string[] = (navigator.languages as string[]) ?? [navigator.language];+ return langs.map((l, i) => (i === 0 ? l : `${l};q=${Math.max(0.1, 1 - i * 0.1).toFixed(1)}`)).join(",");+}++/** Referer under the default policy (strict-origin-when-cross-origin). */+function referer(req: Request, target: URL): string | null {+ if (req.referrer === "") return null;+ const page = new URL(location.href);+ if (page.protocol === "https:" && target.protocol === "http:") return null;+ if (page.origin === target.origin) return page.href.replace(/#.*$/, "");+ return page.origin + "/";+}++function dataUrlResponse(u: URL): Response {+ const href = u.href;+ const comma = href.indexOf(",");+ if (comma < 0) throw new TypeError("Failed to fetch");+ const meta = href.slice(5, comma);+ const data = href.slice(comma + 1);+ const isB64 = /;\s*base64\s*$/i.test(meta);+ const type = (isB64 ? meta.replace(/;\s*base64\s*$/i, "") : meta).trim() || "text/plain;charset=US-ASCII";+ let bytes: Uint8Array;+ if (isB64) bytes = base64ToBytes(decodeURIComponent(data).replace(/\s/g, ""));+ else {+ const raw = unescape(data);+ bytes = new Uint8Array(raw.length);+ for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i) & 0xff;+ }+ const r = new Response(bytes, { status: 200, headers: { "content-type": type } });+ Object.assign(r, { _statusText: "OK", _type: "basic", _url: href });+ r.headers._guard = "immutable";+ return r;+}++export function fetch(input: any, init?: any): Promise<Response> {+ return new Promise<Response>((resolve, reject) => {+ let req: Request;+ try { req = new Request(input, init); } catch (e) { reject(e); return; }+ const signal = req.signal;+ if (signal.aborted) { reject(signal.reason); return; }+ const url = new URL(req.url);+ if (url.protocol === "data:") {+ try { resolve(dataUrlResponse(url)); } catch (e) { reject(e); }+ return;+ }+ if (url.protocol !== "http:" && url.protocol !== "https:") {+ netLog(`Fetch API cannot load ${url.href}. URL scheme "${url.protocol.slice(0, -1)}" is not supported.`);+ reject(new TypeError("Failed to fetch"));+ return;+ }+ if (input instanceof Request && input._hasBody) input._used = true;+ if (req._pending) { reject(new TypeError("Streaming request bodies are not supported")); return; }++ const headers: string[] = [];+ for (const [k, v] of req.headers._list) headers.push(k, v);+ const has = (n: string) => req.headers._list.some(([k]) => k === n);+ const pageOrigin = location.origin;+ const crossOrigin = url.origin !== pageOrigin;+ if (!has("accept")) headers.push("accept", "*/*");+ if (!has("accept-language")) headers.push("accept-language", acceptLanguage());+ if (crossOrigin || (req.method !== "GET" && req.method !== "HEAD")) headers.push("origin", pageOrigin);+ const ref = referer(req, url);+ if (ref) headers.push("referer", ref);+ headers.push("user-agent", navigator.userAgent);+ if (req.cache === "no-store" || req.cache === "reload" || req.cache === "no-cache") headers.push("cache-control", "no-cache", "pragma", "no-cache");++ const id = nextFetchId++;+ const onAbort = () => {+ const p = fetches.get(id);+ if (!p) return;+ fetches.delete(id);+ native.fetchAbort(id);+ if (!p.response) p.reject(signal.reason);+ else p.bodyReject?.(signal.reason);+ };+ signal.addEventListener("abort", onAbort);+ fetches.set(id, {+ method: req.method, resolve, reject, url, response: null, bodyResolve: null, bodyReject: null,+ cleanup: () => signal.removeEventListener("abort", onAbort),+ });+ const redirect = req.redirect === "error" ? 1 : req.redirect === "manual" ? 2 : 0;+ try {+ native.fetch(id, req.method, url.href.replace(/#.*$/, ""), headers, req._src, redirect);+ } catch (e) {+ fetches.delete(id);+ reject(new TypeError("Failed to fetch"));+ }+ });+}++function onFetchHead(id: number, status: number, statusText: string, headerList: string[], url: string, redirected: boolean, opaque: boolean) {+ const p = fetches.get(id);+ if (!p) return;+ const r = Object.create(Response.prototype) as Response;+ const headers = new Headers();+ for (let i = 0; i + 1 < headerList.length; i += 2) headers._list.push([headerList[i], headerList[i + 1]]);+ headers._guard = "immutable";+ const finalUrl = new URL(url);+ Object.assign(r, {+ _src: null, _pending: null, _used: false, _hasBody: false, _stream: null,+ _status: status, _statusText: statusText, _url: url, _redirected: redirected,+ _type: opaque ? "opaqueredirect" : finalUrl.origin === location.origin ? "basic" : "cors",+ });+ (r as any).headers = headers;+ if (!opaque && !NULL_BODY_STATUS.has(status) && p.method !== "HEAD") {+ r._hasBody = true;+ r._pending = new Promise<Uint8Array>((res, rej) => { p.bodyResolve = res; p.bodyReject = rej; });+ r._pending.catch(swallow); // nobody may read the body; that is not an unhandled rejection+ }+ p.response = r;+ p.resolve(r);+}++function onFetchBody(id: number, buf: ArrayBuffer) {+ const p = fetches.get(id);+ if (!p) return;+ fetches.delete(id);+ p.cleanup();+ const bytes = new Uint8Array(buf);+ if (p.response?._pending) {+ p.response._pending = null;+ p.response._src = bytes;+ p.bodyResolve?.(bytes);+ }+}++function onFetchError(id: number, message: string) {+ const p = fetches.get(id);+ if (!p) return;+ fetches.delete(id);+ p.cleanup();+ if (!p.response) {+ netLog(`${p.method} ${p.url.href} ${message}`);+ p.reject(new TypeError("Failed to fetch"));+ } else {+ p.bodyReject?.(new TypeError("network error"));+ }+}++// ---------------------------------------------------------------- WebSocket++const sockets = new Map<number, WebSocket>();+let nextSocketId = 1;++export class WebSocket extends EventTarget {+ static readonly CONNECTING = 0; static readonly OPEN = 1; static readonly CLOSING = 2; static readonly CLOSED = 3;+ declare readonly CONNECTING: 0; declare readonly OPEN: 1; declare readonly CLOSING: 2; declare readonly CLOSED: 3;+ /** @internal */ _id: number;+ /** @internal */ _url: string;+ /** @internal */ _origin: string;+ /** @internal */ _state = 0;+ /** @internal */ _protocol = "";+ /** @internal */ _extensions = "";+ /** @internal */ _binaryType: BinaryType = "blob";+ /** @internal bytes sent while CLOSING/CLOSED: counted, never sent */ _unsent = 0;+ /** @internal close() before the connection opened */ _failed = false;+ constructor(url: string | URL, protocols?: string | string[]) {+ super();+ if (arguments.length < 1) throw new TypeError("Failed to construct 'WebSocket': 1 argument required, but only 0 present.");+ let u: URL;+ try { u = new URL(String(url), location.href); } catch { throw new DOMException(`Failed to construct 'WebSocket': The URL '${url}' is invalid.`, "SyntaxError"); }+ if (u.protocol === "http:") u.protocol = "ws:";+ else if (u.protocol === "https:") u.protocol = "wss:";+ if (u.protocol !== "ws:" && u.protocol !== "wss:") {+ throw new DOMException(`Failed to construct 'WebSocket': The URL's scheme must be either 'http', 'https', 'ws', or 'wss'. '${u.protocol.slice(0, -1)}' is not allowed.`, "SyntaxError");+ }+ if (u.hash) throw new DOMException(`Failed to construct 'WebSocket': The URL contains a fragment identifier ('${u.hash}'). Fragment identifiers are not allowed in WebSocket URLs.`, "SyntaxError");+ const list = protocols === undefined ? [] : typeof protocols === "string" ? [protocols] : Array.from(protocols, String);+ const seen = new Set<string>();+ for (const p of list) {+ if (!TOKEN.test(p)) throw new DOMException(`Failed to construct 'WebSocket': The subprotocol '${p}' is invalid.`, "SyntaxError");+ if (seen.has(p)) throw new DOMException(`Failed to construct 'WebSocket': The subprotocol '${p}' is duplicated.`, "SyntaxError");+ seen.add(p);+ }+ this._url = u.href;+ this._origin = u.origin;+ this._id = nextSocketId++;+ sockets.set(this._id, this);+ native.wsOpen(this._id, u.href, list, location.origin, acceptLanguage());+ }+ get url() { return this._url; }+ get readyState() { return this._state; }+ get protocol() { return this._protocol; }+ get extensions() { return this._extensions; }+ get bufferedAmount() { return (this._state === 1 || this._state === 2 ? native.wsBuffered(this._id) : 0) + this._unsent; }+ get binaryType() { return this._binaryType; }+ set binaryType(v: BinaryType) { if (v === "blob" || v === "arraybuffer") this._binaryType = v; }++ send(data: string | ArrayBufferLike | Blob | ArrayBufferView) {+ if (arguments.length < 1) throw new TypeError("Failed to execute 'send' on 'WebSocket': 1 argument required, but only 0 present.");+ if (this._state === 0) throw new DOMException("Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.", "InvalidStateError");+ let payload: string | ArrayBuffer | Uint8Array;+ let size: number;+ if (data instanceof Blob) { payload = data[BYTES]; size = payload.length; }+ else if (data instanceof ArrayBuffer) { payload = data; size = data.byteLength; }+ else if (ArrayBuffer.isView(data)) { payload = new Uint8Array(data.buffer, data.byteOffset, data.byteLength); size = data.byteLength; }+ else { payload = String(data); size = -1; }+ if (this._state !== 1) {+ // Spec: after close() the data is not sent but still counts towards bufferedAmount.+ this._unsent += size < 0 ? utf8Length(payload as string) : size;+ return;+ }+ native.wsSend(this._id, payload);+ }++ close(code?: number, reason?: string) {+ let c = -1;+ if (code !== undefined) {+ c = Math.min(65535, Math.max(0, Math.round(Number(code) || 0)));+ if (c !== 1000 && (c < 3000 || c > 4999)) {+ throw new DOMException(`Failed to execute 'close' on 'WebSocket': The close code must be either 1000, or between 3000 and 4999. ${c} is neither.`, "InvalidAccessError");+ }+ }+ let r = "";+ if (reason !== undefined) {+ r = String(reason);+ if (utf8Length(r) > 123) throw new DOMException("Failed to execute 'close' on 'WebSocket': The close reason must not be greater than 123 UTF-8 bytes.", "SyntaxError");+ if (c < 0) c = 1000;+ }+ if (this._state === 2 || this._state === 3) return;+ if (this._state === 0) {+ // Fails the connection: error + close(1006) follow once the native side gives up.+ this._failed = true;+ this._state = 2;+ native.wsClose(this._id, -1, "");+ return;+ }+ this._state = 2;+ native.wsClose(this._id, c, r);+ }+ get [Symbol.toStringTag]() { return "WebSocket"; }+}+for (const [k, v] of [["CONNECTING", 0], ["OPEN", 1], ["CLOSING", 2], ["CLOSED", 3]] as const) {+ Object.defineProperty(WebSocket.prototype, k, { value: v, enumerable: true });+}+defineHandlers(WebSocket.prototype, ["open", "message", "error", "close"]);++function onSocketEvent(kind: number, id: number, a: any, b: any, c: any, d: any) {+ const ws = sockets.get(id);+ if (!ws) return;+ switch (kind) {+ case WS_OPEN:+ if (ws._failed) return;+ ws._state = 1;+ ws._protocol = a;+ ws._extensions = b;+ ws.dispatchEvent(new Event("open"));+ break;+ case WS_TEXT:+ if (ws._state !== 1) return;+ ws.dispatchEvent(new MessageEvent("message", { data: a, origin: ws._origin }));+ break;+ case WS_BINARY: {+ if (ws._state !== 1) return;+ let data: any = a;+ if (ws._binaryType === "blob") { data = new Blob([]); data[BYTES] = new Uint8Array(a); }+ ws.dispatchEvent(new MessageEvent("message", { data, origin: ws._origin }));+ break;+ }+ case WS_CLOSE: {+ sockets.delete(id);+ let [code, reason, clean, error] = [a as number, b as string, c as boolean, d as boolean];+ if (ws._failed) { code = 1006; reason = ""; clean = false; error = true; }+ ws._state = 3;+ if (error) ws.dispatchEvent(new Event("error"));+ ws.dispatchEvent(new CloseEvent("close", { code, reason, wasClean: clean }));+ break;+ }+ }+}++// ---------------------------------------------------------------- Web Audio++const nodeRegistry = typeof FinalizationRegistry === "function" ? new FinalizationRegistry<number>((id) => native.audioRelease(id)) : null;++const EV_SET = 0, EV_LINEAR = 1, EV_EXP = 2, EV_TARGET = 3;+interface ParamEvent { type: number; time: number; value: number; tau: number; t0: number }++function finite(v: any, method: string, what = "value") {+ const n = Number(v);+ if (!Number.isFinite(n)) throw new TypeError(`Failed to execute '${method}' on 'AudioParam': The provided ${what} is non-finite.`);+ return n;+}+function timeArg(t: any, method: string) {+ const n = finite(t, method, "double value");+ if (n < 0) throw new RangeError(`Failed to execute '${method}' on 'AudioParam': The time provided (${n}) is less than 0.`);+ return n;+}++export class AudioParam {+ readonly defaultValue: number;+ readonly minValue: number;+ readonly maxValue: number;+ automationRate: "a-rate" | "k-rate" = "a-rate";+ /** @internal */ _node: AudioNode;+ /** @internal */ _index: number;+ /** @internal */ _intrinsic: number;+ /** @internal */ _events: ParamEvent[] = [];+ constructor(node: AudioNode, index: number, defaultValue: number, min: number, max: number) {+ this._node = node; this._index = index;+ this.defaultValue = defaultValue; this.minValue = min; this.maxValue = max;+ this._intrinsic = defaultValue;+ }+ /** @internal */ _flat() {+ const f = new Float64Array(this._events.length * 5);+ this._events.forEach((e, i) => f.set([e.type, e.time, e.value, e.tau, e.t0], i * 5));+ return f;+ }+ /** @internal */ _sync() { native.audioParam(this._node._id, this._index, this._intrinsic, this._flat()); }+ /** @internal */ _now() { return this._node.context.currentTime; }+ /** @internal */ _insert(e: ParamEvent) {+ const evs = this._events;+ // Same time and type replaces; otherwise it goes after events at the same time.+ const same = evs.findIndex((x) => x.time === e.time && x.type === e.type);+ if (same >= 0) evs[same] = e;+ else {+ let i = evs.length;+ while (i > 0 && evs[i - 1].time > e.time) i--;+ evs.splice(i, 0, e);+ }+ this._prune();+ this._sync();+ return this;+ }+ /** @internal Old events stop mattering once a later one has taken over (keeps the list short+ * for pages that set `.value` every frame). */+ _prune() {+ if (this._events.length < 64) return;+ const now = this._now() - 0.5;+ let i = -1;+ for (let j = 0; j < this._events.length && this._events[j].time <= now; j++) i = j;+ if (i <= 0 || this._events[i].type === EV_TARGET) return;+ const v = native.audioParamValue(this._flat(), this._intrinsic, this._events[i].time);+ this._events.splice(0, i + 1, { type: EV_SET, time: this._events[i].time, value: v, tau: 0, t0: 0 });+ }+ get value() {+ if (!this._events.length) return this._intrinsic;+ return Math.fround(native.audioParamValue(this._flat(), this._intrinsic, this._now()));+ }+ set value(v: number) {+ const n = finite(v, "value");+ this._intrinsic = n;+ // Setting value is setValueAtTime(value, currentTime) (Web Audio §1.6.2).+ if (this._events.length) this._insert({ type: EV_SET, time: this._now(), value: n, tau: 0, t0: 0 });+ else this._sync();+ }+ setValueAtTime(value: number, time: number) {+ return this._insert({ type: EV_SET, time: timeArg(time, "setValueAtTime"), value: finite(value, "setValueAtTime"), tau: 0, t0: 0 });+ }+ linearRampToValueAtTime(value: number, time: number) {+ return this._insert({ type: EV_LINEAR, time: timeArg(time, "linearRampToValueAtTime"), value: finite(value, "linearRampToValueAtTime"), tau: 0, t0: this._now() });+ }+ exponentialRampToValueAtTime(value: number, time: number) {+ const v = finite(value, "exponentialRampToValueAtTime");+ if (v === 0) throw new RangeError(`Failed to execute 'exponentialRampToValueAtTime' on 'AudioParam': The float target value provided (0) should not be in the range (${-1.40130e-45}, ${1.40130e-45}).`);+ return this._insert({ type: EV_EXP, time: timeArg(time, "exponentialRampToValueAtTime"), value: v, tau: 0, t0: this._now() });+ }+ setTargetAtTime(target: number, startTime: number, timeConstant: number) {+ const tau = finite(timeConstant, "setTargetAtTime");+ if (tau < 0) throw new RangeError(`Failed to execute 'setTargetAtTime' on 'AudioParam': Time constant (${tau}) is negative.`);+ return this._insert({ type: EV_TARGET, time: timeArg(startTime, "setTargetAtTime"), value: finite(target, "setTargetAtTime"), tau, t0: 0 });+ }+ setValueCurveAtTime(values: ArrayLike<number>, startTime: number, duration: number) {+ const t = timeArg(startTime, "setValueCurveAtTime");+ const d = finite(duration, "setValueCurveAtTime");+ if (d <= 0) throw new RangeError("Failed to execute 'setValueCurveAtTime' on 'AudioParam': The duration must be positive.");+ if (values.length < 2) throw new DOMException("Failed to execute 'setValueCurveAtTime' on 'AudioParam': The curve must have at least 2 values.", "InvalidStateError");+ // A curve is linear interpolation between its points: a set followed by linear ramps.+ const n = values.length;+ this._insert({ type: EV_SET, time: t, value: Number(values[0]), tau: 0, t0: 0 });+ for (let i = 1; i < n; i++) this._insert({ type: EV_LINEAR, time: t + (d * i) / (n - 1), value: Number(values[i]), tau: 0, t0: t });+ return this;+ }+ cancelScheduledValues(cancelTime: number) {+ const t = timeArg(cancelTime, "cancelScheduledValues");+ this._events = this._events.filter((e) => e.time < t);+ this._sync();+ return this;+ }+ cancelAndHoldAtTime(cancelTime: number) {+ const t = timeArg(cancelTime, "cancelAndHoldAtTime");+ const v = native.audioParamValue(this._flat(), this._intrinsic, t);+ const next = this._events.find((e) => e.time >= t);+ this._events = this._events.filter((e) => e.time < t);+ const ramp = next && (next.type === EV_LINEAR || next.type === EV_EXP) ? next.type : EV_SET;+ this._events.push({ type: ramp, time: t, value: v, tau: 0, t0: next?.t0 ?? 0 });+ this._sync();+ return this;+ }+}++export class AudioNode extends EventTarget {+ readonly context: AudioContext;+ readonly numberOfInputs: number;+ readonly numberOfOutputs: number;+ channelCount = 2;+ channelCountMode: ChannelCountMode = "max";+ channelInterpretation: ChannelInterpretation = "speakers";+ /** @internal */ _id: number;+ constructor(context: AudioContext, id: number, inputs: number, outputs: number) {+ super();+ if (!(context instanceof AudioContext)) throw new TypeError("Failed to construct 'AudioNode': parameter 1 is not of type 'BaseAudioContext'.");+ this.context = context; this._id = id; this.numberOfInputs = inputs; this.numberOfOutputs = outputs;+ }+ connect(destination: AudioNode | AudioParam, output = 0, input = 0): any {+ if (destination instanceof AudioParam) {+ if (destination._node.context !== this.context) throw new DOMException("Failed to execute 'connect' on 'AudioNode': cannot connect to an AudioParam belonging to a different audio context.", "InvalidAccessError");+ native.audioConnect(this._id, destination._node._id, destination._index);+ return undefined;+ }+ if (!(destination instanceof AudioNode)) throw new TypeError("Failed to execute 'connect' on 'AudioNode': Overload resolution failed.");+ if (destination.context !== this.context) throw new DOMException("Failed to execute 'connect' on 'AudioNode': cannot connect to an AudioNode belonging to a different audio context.", "InvalidAccessError");+ if (output >= this.numberOfOutputs || input >= destination.numberOfInputs) throw new DOMException("Failed to execute 'connect' on 'AudioNode': output or input index out of range.", "IndexSizeError");+ native.audioConnect(this._id, destination._id, -1);+ return destination;+ }+ disconnect(destination?: AudioNode | AudioParam | number) {+ if (destination instanceof AudioParam) native.audioDisconnect(this._id, destination._node._id, destination._index);+ else if (destination instanceof AudioNode) native.audioDisconnect(this._id, destination._id, -1);+ else native.audioDisconnect(this._id, 0, -1);+ }+}++export class AudioDestinationNode extends AudioNode {+ readonly maxChannelCount = 2;+}++export class GainNode extends AudioNode {+ readonly gain: AudioParam;+ constructor(context: AudioContext, options: { gain?: number } = {}) {+ super(context, native.audioNode(context._id, 1), 1, 1);+ this.gain = new AudioParam(this, 0, 1, -3.4028234663852886e38, 3.4028234663852886e38);+ if (options.gain !== undefined) this.gain.value = options.gain;+ nodeRegistry?.register(this, this._id);+ }+}++const WAVES = ["sine", "square", "sawtooth", "triangle"];++export class PeriodicWave {+ constructor(_context: AudioContext, _options?: any) {}+}++/** Started sources with `ended` listeners stay reachable until they end (as in Chromium), so the+ * event fires even when the page dropped its reference. */+const playing = new Map<number, AudioScheduledSourceNode>();++export class AudioScheduledSourceNode extends AudioNode {+ /** @internal */ _started = false;+ /** @internal */ _wantEnded = false;+ start(when = 0) {+ const t = Number(when);+ if (!Number.isFinite(t)) throw new TypeError("Failed to execute 'start' on 'AudioScheduledSourceNode': The provided double value is non-finite.");+ if (t < 0) throw new RangeError(`Failed to execute 'start' on 'AudioScheduledSourceNode': The start time provided (${t}) is less than the minimum bound (0).`);+ if (this._started) throw new DOMException("Failed to execute 'start' on 'AudioScheduledSourceNode': cannot call start more than once.", "InvalidStateError");+ this._started = true;+ if (this._wantEnded) playing.set(this._id, this);+ native.audioStart(this._id, t);+ }+ stop(when = 0) {+ const t = Number(when);+ if (!Number.isFinite(t)) throw new TypeError("Failed to execute 'stop' on 'AudioScheduledSourceNode': The provided double value is non-finite.");+ if (t < 0) throw new RangeError(`Failed to execute 'stop' on 'AudioScheduledSourceNode': The stop time provided (${t}) is less than the minimum bound (0).`);+ if (!this._started) throw new DOMException("Failed to execute 'stop' on 'AudioScheduledSourceNode': cannot call stop without calling start first.", "InvalidStateError");+ native.audioStop(this._id, t);+ }+ override addEventListener(type: string, fn: any, options?: any) {+ if (type === "ended" && !this._wantEnded) {+ this._wantEnded = true;+ native.audioWantEnded(this._id);+ if (this._started) playing.set(this._id, this);+ }+ super.addEventListener(type, fn, options);+ }+}+defineHandlers(AudioScheduledSourceNode.prototype, ["ended"]);++export class OscillatorNode extends AudioScheduledSourceNode {+ readonly frequency: AudioParam;+ readonly detune: AudioParam;+ /** @internal */ _type: OscillatorType = "sine";+ constructor(context: AudioContext, options: { type?: OscillatorType; frequency?: number; detune?: number } = {}) {+ super(context, native.audioNode(context._id, 2), 0, 1);+ const nyquist = context.sampleRate / 2;+ this.frequency = new AudioParam(this, 0, 440, -nyquist, nyquist);+ this.detune = new AudioParam(this, 1, 0, -153600, 153600);+ if (options.type !== undefined) this.type = options.type;+ if (options.frequency !== undefined) this.frequency.value = options.frequency;+ if (options.detune !== undefined) this.detune.value = options.detune;+ nodeRegistry?.register(this, this._id);+ }+ get type() { return this._type; }+ set type(t: OscillatorType) {+ if (t === "custom") throw new DOMException("Failed to set the 'type' property on 'OscillatorNode': 'type' cannot be set directly to 'custom'. Use setPeriodicWave() to create a custom Oscillator type.", "InvalidStateError");+ const i = WAVES.indexOf(t);+ if (i < 0) return; // invalid enum values are ignored+ this._type = t;+ native.audioWave(this._id, i);+ }+ setPeriodicWave(_wave: PeriodicWave) {+ // Custom waveforms are not synthesised; they play as a sine.+ this._type = "custom";+ native.audioWave(this._id, 0);+ }+}++type AudioState = "suspended" | "running" | "closed";++export class AudioContext extends EventTarget {+ readonly sampleRate: number;+ readonly destination: AudioDestinationNode;+ readonly baseLatency: number;+ readonly outputLatency: number;+ readonly listener = {};+ readonly audioWorklet = undefined;+ /** @internal */ _id: number;+ /** @internal */ _state: AudioState = "running";+ /** @internal */ _closedAt = 0;+ constructor(_options: { latencyHint?: any; sampleRate?: number } = {}) {+ super();+ this._id = native.audioCreate();+ this.sampleRate = native.audioRate();+ this.baseLatency = 256 / this.sampleRate;+ this.outputLatency = 512 / this.sampleRate;+ this.destination = new AudioDestinationNode(this, this._id, 1, 0);+ // Pages that let go of a context without close() still release it.+ contextRegistry?.register(this, this._id);+ }+ get currentTime() { return this._state === "closed" ? this._closedAt : native.audioTime(this._id); }+ get state() { return this._state; }+ /** @internal */ _setState(s: AudioState) {+ if (this._state === s) return;+ this._state = s;+ setTimeout(() => this.dispatchEvent(new Event("statechange")), 0);+ }+ createOscillator() { return new OscillatorNode(this); }+ createGain() { return new GainNode(this); }+ createPeriodicWave(real: ArrayLike<number>, imag: ArrayLike<number>, _constraints?: any) {+ if (real.length !== imag.length || real.length < 2) throw new DOMException("Failed to execute 'createPeriodicWave' on 'BaseAudioContext': length mismatch.", "IndexSizeError");+ return new PeriodicWave(this);+ }+ getOutputTimestamp() { return { contextTime: this.currentTime, performanceTime: performance.now() }; }+ resume(): Promise<void> {+ if (this._state === "closed") return Promise.reject(new DOMException("Cannot resume a closed AudioContext.", "InvalidStateError"));+ native.audioResume(this._id);+ this._setState("running");+ return Promise.resolve();+ }+ suspend(): Promise<void> {+ if (this._state === "closed") return Promise.reject(new DOMException("Cannot suspend a closed AudioContext.", "InvalidStateError"));+ native.audioSuspend(this._id);+ this._setState("suspended");+ return Promise.resolve();+ }+ close(): Promise<void> {+ if (this._state === "closed") return Promise.reject(new DOMException("Cannot close a closed AudioContext.", "InvalidStateError"));+ this._closedAt = this.currentTime;+ native.audioClose(this._id);+ this._setState("closed");+ return Promise.resolve();+ }+}+defineHandlers(AudioContext.prototype, ["statechange"]);+const contextRegistry = typeof FinalizationRegistry === "function" ? new FinalizationRegistry<number>((id) => native.audioClose(id)) : null;++function onAudioEnded(id: number) {+ const node = playing.get(id);+ playing.delete(id);+ node?.dispatchEvent(new Event("ended"));+}++// ---------------------------------------------------------------- install++export function installNet() {+ native.setHandler((kind, id, a, b, c, d, e, f) => {+ switch (kind) {+ case FETCH_HEAD: onFetchHead(id, a, b, c, d, e, f); break;+ case FETCH_BODY: onFetchBody(id, a); break;+ case FETCH_ERROR: onFetchError(id, a); break;+ case AUDIO_ENDED: onAudioEnded(id); break;+ default: onSocketEvent(kind, id, a, b, c, d);+ }+ }, navigator.userAgent);+ Object.assign(g, {+ fetch, Request, Response, Headers, Blob, File, FormData, WebSocket,+ AudioContext, webkitAudioContext: AudioContext, BaseAudioContext: AudioContext, AudioNode, AudioParam, GainNode, OscillatorNode,+ AudioScheduledSourceNode, AudioDestinationNode, PeriodicWave,+ });+}diff --git a/runtime/js/shared/surfaces.ts b/runtime/js/shared/surfaces.tsnew file mode 100644index 0000000..77a7c92--- /dev/null+++ b/runtime/js/shared/surfaces.ts@@ -0,0 +1,35 @@+// Shared hooks between the DOM (canvas / img elements) and the graphics modules, so the modules stay+// independent: canvases never import a context implementation, they look the factories up here.++/** What a canvas element exposes to the context modules. */+export interface CanvasHost {+ width: number;+ height: number;+ /** set by a context module when a context is created: tells the UI engine what to draw */+ _setSurface(kind: "2d" | "webgpu", id: number): void;+ /** the current context, if any */+ _context: any;+ /** context modules register a resize callback (canvas.width/height changed) */+ _onResize: ((w: number, h: number) => void) | null;+}++/** What an img element exposes to the image loader. */+export interface ImageHost {+ /** image id in the native image registry (0 = none) */+ _imageId: number;+ naturalWidth: number;+ naturalHeight: number;+ complete: boolean;+ /** called by the loader when the image is ready / failed */+ _loaded(id: number, width: number, height: number): void;+ _failed(): void;+}++export const surfaces = {+ /** "2d" → Canvas 2D factory, "webgpu" → WebGPU canvas context factory */+ contextFactories: new Map<string, (canvas: CanvasHost, attrs: any) => any>(),+ /** canvas.toDataURL / toBlob for a canvas with a context (or blank) */+ toDataURL: null as null | ((canvas: CanvasHost, type?: string, quality?: number) => string),+ /** start loading `src` into an image element */+ loadImage: null as null | ((img: ImageHost, src: string) => void),+};diff --git a/runtime/js/tsconfig.json b/runtime/js/tsconfig.jsonnew file mode 100644index 0000000..3874059--- /dev/null+++ b/runtime/js/tsconfig.json@@ -0,0 +1,14 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "strict": true,+ "noEmit": true,+ "skipLibCheck": true,+ "allowImportingTsExtensions": true,+ "lib": ["ES2024", "DOM", "DOM.Iterable"],+ "types": []+ },+ "include": ["./**/*.ts"]+}diff --git a/site/README.md b/site/README.mdindex 4463460..5a55f24 100644--- a/site/README.md+++ b/site/README.md@@ -88,8 +88,8 @@ the clients do not get buttons here.6. **What a ray finds:** four close-ups.7. **Open source. MIT.** A strip, where the comparisons end: what is in the repository, why a star helps, the Starbutton, the npm packages.-8. **Traced where it can be, three.js everywhere else:** the native client on ray-tracing hardware and the same scene- as three.js in any browser or WebView, drawn as live three.js device models at real proportions.+8. **One runtime, two renderers, every screen:** the `path` renderer on ray-tracing hardware, the planned `webgpu`+ renderer for clean native three.js apps with zero ray-tracing code, and the same scene in any browser or WebView.9. **Play it with a friend:** OpenStrikeRT (`https://openstrike.threert.app/`), the platform's first multiplayer game:its cover with the words over it, two of its screenshots, three facts (rooms of up to 10, bots when alone, all of itgame code). Its pictures are copies in `media/openstrike/`.diff --git a/site/docs/index.html b/site/docs/index.htmlindex 38903b4..117e805 100644--- a/site/docs/index.html+++ b/site/docs/index.html@@ -199,6 +199,7 @@ export default defineGame({<p>The engine is open source, and its documents live with the code.</p><div class="refs"><a href="rendering/"><b>Rendering settings</b><span>Resolution, denoisers and upscalers (ThreeRT’s, MetalFX, DLSS, FSR), latency: in the clients and in code</span></a>+ <a href="https://github.com/meshy-dev/ThreeRT/blob/main/docs/RENDERING-METHODS.md" rel="noopener"><b>Renderers: path and webgpu</b><span>One runtime, two renderers: hardware path tracing (path) and a clean native WebGPU build (webgpu) with zero path-tracer code</span></a><a href="https://github.com/meshy-dev/ThreeRT/blob/main/docs/RUNTIME.md" rel="noopener"><b>Runtime</b><span>How scene code runs in the engine: setup, handlers, world handlers, frame scripts, physics</span></a><a href="https://github.com/meshy-dev/ThreeRT/blob/main/docs/ARCHITECTURE.md" rel="noopener"><b>Architecture</b><span>The serverless gameplay and rendering runtime the engine was built for</span></a><a href="https://github.com/meshy-dev/ThreeRT/blob/main/docs/MATERIAL_FUNCTIONS.md" rel="noopener"><b>Material functions</b><span>A WGSL body on a material, run by the path tracer at every hit</span></a>@@ -214,7 +215,7 @@ export default defineGame({<div class="wrap cols"><div><a class="logo" href="../" aria-label="ThreeRT home"><img src="../brand/mark.svg" alt=""><span>Three<span class="rt">RT</span></span></a>- <p style="margin-top:14px">Hardware-accelerated ray tracing behind a three.js-style API.</p>+ <p style="margin-top:14px">The native runtime for three.js — hardware path tracing and WebGPU.</p><div class="site"><a href="https://threert.app/" rel="noopener">Apps</a><a href="../download/">Download</a><a href="../docs/">Docs</a><a class="star" href="https://github.com/meshy-dev/ThreeRT" rel="noopener" aria-label="Star ThreeRT on GitHub" title="Star ThreeRT on GitHub"><svg class="si" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><path d="M8 .2a8 8 0 0 0-2.53 15.59c.4.07.55-.17.55-.38v-1.34c-2.23.48-2.7-1.07-2.7-1.07-.36-.93-.89-1.17-.89-1.17-.73-.5.05-.49.05-.49.8.06 1.23.83 1.23.83.72 1.22 1.88.87 2.33.66.07-.52.28-.87.5-1.07-1.77-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82a7.6 7.6 0 0 1 4 0c1.53-1.03 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.28.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48v2.2c0 .21.15.46.55.38A8 8 0 0 0 8 .2Z"/></svg><span>Star</span><b data-stars hidden></b></a><a class="ic" href="https://discord.gg/n7vsVmAKCK" rel="noopener" aria-label="ThreeRT on Discord" title="Discord"><svg class="si" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z"/></svg></a><a class="ic" href="https://x.com/ThreeRT3D" rel="noopener" aria-label="ThreeRT on X" title="X"><svg class="si" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z"/></svg></a></div><p class="legal">A research project from <a href="https://meshy.ai/" rel="noopener">MeshyAI</a> · © 2026 MeshyAI · <a href="../privacy/">Privacy</a></p></div>diff --git a/site/download/index.html b/site/download/index.htmlindex 65bbbd5..5e0f961 100644--- a/site/download/index.html+++ b/site/download/index.html@@ -191,7 +191,7 @@<div class="wrap cols"><div><a class="logo" href="../" aria-label="ThreeRT home"><img src="../brand/mark.svg" alt=""><span>Three<span class="rt">RT</span></span></a>- <p style="margin-top:14px">Hardware-accelerated ray tracing behind a three.js-style API.</p>+ <p style="margin-top:14px">The native runtime for three.js — hardware path tracing and WebGPU.</p><div class="site"><a href="https://threert.app/" rel="noopener">Apps</a><a href="../download/">Download</a><a href="../docs/">Docs</a><a class="star" href="https://github.com/meshy-dev/ThreeRT" rel="noopener" aria-label="Star ThreeRT on GitHub" title="Star ThreeRT on GitHub"><svg class="si" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><path d="M8 .2a8 8 0 0 0-2.53 15.59c.4.07.55-.17.55-.38v-1.34c-2.23.48-2.7-1.07-2.7-1.07-.36-.93-.89-1.17-.89-1.17-.73-.5.05-.49.05-.49.8.06 1.23.83 1.23.83.72 1.22 1.88.87 2.33.66.07-.52.28-.87.5-1.07-1.77-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82a7.6 7.6 0 0 1 4 0c1.53-1.03 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.28.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48v2.2c0 .21.15.46.55.38A8 8 0 0 0 8 .2Z"/></svg><span>Star</span><b data-stars hidden></b></a><a class="ic" href="https://discord.gg/n7vsVmAKCK" rel="noopener" aria-label="ThreeRT on Discord" title="Discord"><svg class="si" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z"/></svg></a><a class="ic" href="https://x.com/ThreeRT3D" rel="noopener" aria-label="ThreeRT on X" title="X"><svg class="si" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z"/></svg></a></div><p class="legal">A research project from <a href="https://meshy.ai/" rel="noopener">MeshyAI</a> · © 2026 MeshyAI · <a href="../privacy/">Privacy</a></p></div>diff --git a/site/index.html b/site/index.htmlindex 7851945..2e8734f 100644--- a/site/index.html+++ b/site/index.html@@ -3,14 +3,14 @@<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">-<title>ThreeRT — Hardware ray-traced three.js</title>-<meta name="description" content="ThreeRT is a real-time path tracer behind a three.js-style API: Bistro and Zero-Day fully path-traced at 60 fps. Open source, MIT. Apps and games made with it are published at threert.app; free clients for macOS, iPhone, Steam Deck and Android.">+<title>ThreeRT — The native runtime for three.js</title>+<meta name="description" content="ThreeRT is the native runtime for three.js with two renderers: a real-time GPU path tracer (path) at 60 fps and a clean native WebGPU renderer (webgpu) with zero ray-tracing overhead. Open source, MIT."><link rel="canonical" href="https://threert.dev/"><meta name="theme-color" content="#060709"><meta property="og:site_name" content="ThreeRT"><meta property="og:type" content="website">-<meta property="og:title" content="ThreeRT — Hardware ray-traced three.js">-<meta property="og:description" content="A real-time path tracer behind a three.js-style API, open source. Apps and games made with it are published at threert.app.">+<meta property="og:title" content="ThreeRT — The native runtime for three.js">+<meta property="og:description" content="One native runtime for three.js: hardware path tracing at 60 fps (path) or a clean native WebGPU app (webgpu), open source. Apps and games live at threert.app."><meta property="og:url" content="https://threert.dev/"><meta property="og:image" content="https://threert.dev/brand/card.jpg"><meta property="og:image:width" content="1200">@@ -179,6 +179,14 @@.branch:last-child::after { content: ""; position: absolute; left: -48px; top: calc(50% + 1.5px); bottom: -4px; width: 8px; background: var(--ink-0); }.tier { border: 1px solid var(--line); border-radius: 22px; padding: 24px 24px 22px 30px; background: var(--ink-1); display: grid; grid-template-columns: 280px 1fr; gap: 24px; align-items: center; overflow: hidden; }.tier.rt-tier { border-color: color-mix(in srgb, var(--tungsten) 45%, transparent); background: radial-gradient(70% 90% at 70% 0%, var(--halo), transparent 70%), var(--ink-1); }+ .tier.wg-tier { border-color: color-mix(in srgb, var(--c-three) 40%, transparent); background: radial-gradient(70% 90% at 70% 0%, color-mix(in srgb, var(--c-three) 10%, transparent), transparent 70%), var(--ink-1); }+ .wg-panel { display: grid; gap: 14px; padding: 20px 22px; border-radius: 16px; border: 1px solid var(--line); background: #0a0b0e; min-width: 0; }+ .wg-panel pre { margin: 0; font: 500 12.5px/1.75 var(--font-mono); color: var(--bone); overflow-x: auto; }+ .wg-panel pre .c { color: var(--mute); }+ .wg-panel .stats { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; padding-top: 14px; border-top: 1px solid var(--line); }+ .wg-panel .stats div b { display: block; font: 600 19px/1.15 var(--font-sans); letter-spacing: -.03em; color: var(--bone); }+ .wg-panel .stats div span { display: block; margin-top: 4px; font: 500 11.5px/1.35 var(--font-mono); color: var(--mute); }+ @media (max-width: 700px) { .wg-panel .stats { grid-template-columns: 1fr; } }.tier h3 { font: 600 28px var(--font-sans); letter-spacing: -.035em; }.tier .req { display: block; margin-top: 8px; font: 500 12px var(--font-mono); color: var(--mute); }.tier .sub { margin-top: 14px; color: var(--bone-2); font-size: 15px; }@@ -241,7 +249,7 @@<div class="copy"><div class="wrap"><h1 class="h-display">Hardware<span class="l2">ray-traced</span><span class="l2 ray-text">three.js.</span></h1>- <p class="lede" style="max-width:52ch">ThreeRT is the first three.js-style engine to fully path-trace industry-standard scenes at 60 fps.<sup>1</sup></p>+ <p class="lede" style="max-width:54ch">The native runtime for three.js: path-trace production scenes at 60 fps with <code>path</code>,<sup>1</sup> or ship a clean native three.js app with the planned <code>webgpu</code> renderer.</p><div class="cta"><a class="btn primary" href="https://threert.app/" rel="noopener"><span>Explore apps</span></a><a class="btn ghost star" href="https://github.com/meshy-dev/ThreeRT" rel="noopener" aria-label="Star ThreeRT on GitHub"><svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><path d="M8 .2a8 8 0 0 0-2.53 15.59c.4.07.55-.17.55-.38v-1.34c-2.23.48-2.7-1.07-2.7-1.07-.36-.93-.89-1.17-.89-1.17-.73-.5.05-.49.05-.49.8.06 1.23.83 1.23.83.72 1.22 1.88.87 2.33.66.07-.52.28-.87.5-1.07-1.77-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82a7.6 7.6 0 0 1 4 0c1.53-1.03 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.28.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48v2.19c0 .21.15.46.55.38A8 8 0 0 0 8 .2Z"/></svg><span>Star<span class="w"> on GitHub</span></span><b data-stars hidden></b></a></div><p class="plat"><a href="download/" data-dl>Download ThreeRT</a> · <span data-dl-others>macOS · iPhone · Steam Deck · Android</span></p></div>@@ -254,7 +262,7 @@<ol class="rv"><li><h3><b>R</b>ay <b>T</b>racing</h3><p>Every light is traced: shadows, bounce light, reflections and glowing surfaces that light the room. No shadow maps, no light probes, no baking.</p></li><li><h3><b>R</b>eal <b>T</b>ime</h3><p>60 fps in production scenes, with the camera moving. Not a still that converges once you stop.</p></li>- <li><h3><b>R</b>un<b>t</b>ime</h3><p>A game runtime, not only a renderer. Scene code and game logic run inside the engine, and the same scene runs as three.js in any browser.</p></li>+ <li><h3><b>R</b>un<b>t</b>ime</h3><p>A native runtime for three.js, not only a path tracer. Build with the <code>path</code> renderer for hardware ray tracing, the planned <code>webgpu</code> renderer for a clean native app with zero ray-tracing overhead, or run as three.js in any browser.</p></li></ol></div></section>@@ -314,7 +322,7 @@<section id="traced" style="padding-top:40px"><div class="wrap"><div class="sec-head rv">- <h2 class="h-1">What a ray finds<br><span class="mute">that a raster can’t.</span></h2>+ <h2 class="h-1">What a ray finds<br><span class="mute">that approximations can’t.</span></h2><p class="lede">Close-ups of the same frames. Left: three.js at its strongest. Right: ThreeRT.</p></div><div class="details">@@ -347,7 +355,7 @@<div class="strip rv"><div><h2>Open source. MIT.</h2>- <p>The path tracer (Rust and wgpu), the three.js-style scene API and the gameplay runtime are one repository, along with every comparison on this page and how it was measured. If it is useful to you, a star helps the next three.js developer find it.</p>+ <p>The native runtime and path tracer (Rust and wgpu), the three.js-style scene API and the gameplay runtime are one repository, along with every comparison on this page, how it was measured, and the architecture for the <code>webgpu</code> renderer. If it is useful to you, a star helps the next three.js developer find it.</p></div><div class="act"><a class="btn ghost star" href="https://github.com/meshy-dev/ThreeRT" rel="noopener" aria-label="Star ThreeRT on GitHub"><svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><path d="M8 .2a8 8 0 0 0-2.53 15.59c.4.07.55-.17.55-.38v-1.34c-2.23.48-2.7-1.07-2.7-1.07-.36-.93-.89-1.17-.89-1.17-.73-.5.05-.49.05-.49.8.06 1.23.83 1.23.83.72 1.22 1.88.87 2.33.66.07-.52.28-.87.5-1.07-1.77-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82a7.6 7.6 0 0 1 4 0c1.53-1.03 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.28.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48v2.19c0 .21.15.46.55.38A8 8 0 0 0 8 .2Z"/></svg><span>Star on GitHub</span><b data-stars hidden></b></a>@@ -360,27 +368,45 @@<section id="everywhere" style="padding-top:40px"><div class="wrap"><div class="sec-head rv" style="grid-template-columns:1fr;gap:24px">- <h2 class="h-1">Traced where it can be.<br><span class="mute">three.js everywhere else.</span></h2>- <p class="lede" style="justify-self:start">One scene, one game. On hardware with ray tracing, the native client traces every light. On every other screen, the same scene opens in the browser as three.js.</p>+ <h2 class="h-1">One runtime.<br><span class="mute">Two renderers, every screen.</span></h2>+ <p class="lede" style="justify-self:start">One engine and one brand — choose the <code>path</code> renderer for 60 fps hardware ray tracing, the planned <code>webgpu</code> renderer for a clean native three.js build with zero ray-tracing code, or open the same project in any browser.</p></div><div class="rv">- <div class="root"><img src="brand/mark-small.svg" alt="">game.ts · one scene, one codebase</div>+ <div class="root"><img src="brand/mark-small.svg" alt="">ThreeRT · one runtime, chosen per build</div><div class="rail"><div class="branch rt-b"><div class="tier rt-tier"><div>- <h3>Native client</h3><span class="req">hardware ray tracing</span>+ <h3>Path Tracer</h3><span class="req">--renderer path · hardware ray tracing</span><p class="sub">Every light path traced, at 60 fps.</p>- <ul><li>Dynamic resolution holds the frame rate</li><li><span>Installs like any game client: <a href="download/">macOS, iPhone, Steam Deck, Android</a></span></li></ul>+ <ul><li>Dynamic resolution, MetalFX / DLSS and OIDN hold the frame rate</li><li><span>Installs like any game client: <a href="download/">macOS, iPhone, Steam Deck, Android</a></span></li></ul></div><div class="shelf3d" id="shelfNative"></div></div></div>+ <div class="branch">+ <div class="tier wg-tier">+ <div>+ <h3>WebGPU</h3><span class="req">--renderer webgpu · planned · any GPU</span>+ <p class="sub">Standard three.js <code>WebGPURenderer</code> over native <code>navigator.gpu</code> (wgpu), with zero path-tracer code linked.</p>+ <ul><li>One-way crates: <code>path → runtime ← webgpu</code></li><li><span>Architecture & size gate: <a href="https://github.com/meshy-dev/ThreeRT/blob/main/docs/RENDERING-METHODS.md" rel="noopener">RENDERING-METHODS.md</a></span></li></ul>+ </div>+ <div class="wg-panel">+ <pre><span class="c">$</span> threert build --renderer webgpu <span class="c"># clean native three.js, zero RT code</span>+<span class="c">$</span> threert build --renderer path <span class="c"># hardware ray tracing (default)</span></pre>+ <div class="stats">+ <div><b>9.9 MB</b><span>installed (vs 445 MB Electron)</span></div>+ <div><b>4.5 MB</b><span>download (vs 170 MB Electron)</span></div>+ <div><b>34.7 %</b><span>CPU on M5 (vs 64.8 % Electron)</span></div>+ </div>+ </div>+ </div>+ </div><div class="branch"><div class="tier"><div>- <h3>WebView</h3><span class="req">any browser, any device</span>- <p class="sub">The same scene as three.js rasterization, in any browser or in-app WebView.</p>+ <h3>Browser</h3><span class="req">any browser, any device</span>+ <p class="sub">The same project running as three.js in any browser or in-app WebView.</p><ul><li>A link instead of a download</li><li>Plain three.js, with its whole ecosystem</li></ul></div><div class="shelf3d" id="shelfWeb"></div>@@ -389,8 +415,8 @@</div></div><div class="payoff rv" style="margin-top:72px">- <h3>AAA games, <span class="ray-text">one link away.</span></h3>- <p>The web version isn’t a port. It is the same game, running as three.js.</p>+ <h3>From a 5 MB app <span class="ray-text">to 60 fps path tracing.</span></h3>+ <p>Pick the renderer your project needs — clean native WebGPU, hardware ray tracing, or the browser — without splitting the engine or leaving three.js.</p></div></div></section>@@ -483,7 +509,7 @@ return { scene, camera };</pre></li><div class="wrap cols"><div><a class="logo" href="./" aria-label="ThreeRT home"><img src="brand/mark.svg" alt=""><span>Three<span class="rt">RT</span></span></a>- <p style="margin-top:14px">Hardware-accelerated ray tracing behind a three.js-style API.</p>+ <p style="margin-top:14px">The native runtime for three.js — hardware path tracing and WebGPU.</p><div class="site"><a href="https://threert.app/" rel="noopener">Apps</a><a href="download/">Download</a><a href="docs/">Docs</a><a class="star" href="https://github.com/meshy-dev/ThreeRT" rel="noopener" aria-label="Star ThreeRT on GitHub" title="Star ThreeRT on GitHub"><svg class="si" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><path d="M8 .2a8 8 0 0 0-2.53 15.59c.4.07.55-.17.55-.38v-1.34c-2.23.48-2.7-1.07-2.7-1.07-.36-.93-.89-1.17-.89-1.17-.73-.5.05-.49.05-.49.8.06 1.23.83 1.23.83.72 1.22 1.88.87 2.33.66.07-.52.28-.87.5-1.07-1.77-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82a7.6 7.6 0 0 1 4 0c1.53-1.03 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.28.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48v2.2c0 .21.15.46.55.38A8 8 0 0 0 8 .2Z"/></svg><span>Star</span><b data-stars hidden></b></a><a class="ic" href="https://discord.gg/n7vsVmAKCK" rel="noopener" aria-label="ThreeRT on Discord" title="Discord"><svg class="si" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z"/></svg></a><a class="ic" href="https://x.com/ThreeRT3D" rel="noopener" aria-label="ThreeRT on X" title="X"><svg class="si" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z"/></svg></a></div><p class="legal">A research project from <a href="https://meshy.ai/" rel="noopener">MeshyAI</a> · © 2026 MeshyAI · <a href="privacy/">Privacy</a></p></div>diff --git a/tools/build.ts b/tools/build.tsnew file mode 100644index 0000000..cbb8c9a--- /dev/null+++ b/tools/build.ts@@ -0,0 +1,133 @@+// Unified ThreeRT build CLI: selects one renderer (`path` or `webgpu`).+// node tools/build.ts --renderer webgpu [--debug] [--js-only]+// node tools/build.ts --renderer path [--debug]+//+// `--renderer webgpu` builds the clean native runtime + WebGPU renderer (linking zero path-tracer code).+// `--renderer path` builds the hardware path tracer (`renderer/`, today's default).+import { spawnSync } from "node:child_process";+import { mkdirSync, statSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { build } from "esbuild";++const root = join(import.meta.dirname, "..");++function parseArgs(argv: string[]) {+ let renderer: "path" | "webgpu" = "path";+ let debug = false;+ let jsOnly = false;+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a === "--renderer") {+ const v = argv[++i];+ if (v !== "path" && v !== "webgpu") {+ throw new Error(`unknown --renderer value: ${String(v)} (expected "path" or "webgpu")`);+ }+ renderer = v;+ } else if (a.startsWith("--renderer=")) {+ const v = a.slice("--renderer=".length);+ if (v !== "path" && v !== "webgpu") {+ throw new Error(`unknown --renderer value: ${v} (expected "path" or "webgpu")`);+ }+ renderer = v;+ } else if (a === "--debug") {+ debug = true;+ } else if (a === "--js-only") {+ jsOnly = true;+ } else if (a === "-h" || a === "--help") {+ console.log("Usage: node tools/build.ts --renderer <path|webgpu> [--debug] [--js-only]");+ process.exit(0);+ } else {+ throw new Error(`unknown argument: ${a}`);+ }+ }+ return { renderer, debug, jsOnly };+}++function run(cmd: string, args: string[], cwd: string) {+ const res = spawnSync(cmd, args, { cwd, stdio: "inherit" });+ if (res.status !== 0) {+ process.exit(res.status ?? 1);+ }+}++function formatMiB(bytes: number): string {+ return `${(bytes / (1024 * 1024)).toFixed(2)} MiB`;+}++async function bundleWebGpuJs() {+ const outDir = join(root, "out", "webgpu");+ mkdirSync(outDir, { recursive: true });++ const rtRes = await build({+ entryPoints: [join(root, "webgpu", "js", "index.ts")],+ bundle: true,+ format: "iife",+ platform: "neutral",+ target: "es2022",+ minify: true,+ legalComments: "none",+ write: false,+ logLevel: "warning",+ });+ const rtPath = join(outDir, "runtime.js");+ writeFileSync(rtPath, rtRes.outputFiles[0].text);++ const sampleRes = await build({+ entryPoints: [join(root, "webgpu", "sample", "scene.ts")],+ bundle: true,+ format: "iife",+ platform: "browser",+ target: "es2022",+ mainFields: ["module", "main"],+ minify: true,+ legalComments: "none",+ write: false,+ logLevel: "warning",+ });+ const samplePath = join(outDir, "sample.js");+ writeFileSync(samplePath, sampleRes.outputFiles[0].text);++ console.log(+ `[build --renderer webgpu] JS bundles: runtime.js (${(rtRes.outputFiles[0].contents.length / 1024).toFixed(1)} KiB), ` ++ `sample.js (${(sampleRes.outputFiles[0].contents.length / 1024).toFixed(1)} KiB)`+ );+}++async function buildWebGpu(debug: boolean, jsOnly: boolean) {+ await bundleWebGpuJs();+ if (jsOnly) return;++ if (process.platform !== "darwin" && process.platform !== "linux") {+ throw new Error(`native --renderer webgpu is supported on macOS and Linux (got ${process.platform})`);+ }+ const cargoArgs = ["build", "--workspace", "--locked"];+ if (!debug) cargoArgs.push("--release");+ run("cargo", cargoArgs, join(root, "webgpu"));++ const profileDir = debug ? "debug" : "release";+ const sampleBin = join(root, "webgpu", "target", profileDir, "threert-webgpu-sample");+ const shotBin = join(root, "webgpu", "target", profileDir, "webgpu-shot");+ console.log(+ `[build --renderer webgpu] binaries (${profileDir}): ` ++ `threert-webgpu-sample=${formatMiB(statSync(sampleBin).size)}, ` ++ `webgpu-shot=${formatMiB(statSync(shotBin).size)}`+ );+}++function buildPath(debug: boolean) {+ run("node", [join(root, "tools", "build-runtime.ts")], root);+ const cargoArgs = ["build", "--locked"];+ if (!debug) cargoArgs.push("--release");+ run("cargo", cargoArgs, join(root, "renderer"));++ const profileDir = debug ? "debug" : "release";+ const bin = join(root, "renderer", "target", profileDir, process.platform === "win32" ? "threert-render.exe" : "threert-render");+ console.log(`[build --renderer path] binary (${profileDir}): threert-render=${formatMiB(statSync(bin).size)}`);+}++const opts = parseArgs(process.argv.slice(2));+if (opts.renderer === "webgpu") {+ await buildWebGpu(opts.debug, opts.jsOnly);+} else {+ buildPath(opts.debug);+}diff --git a/tools/check-webgpu-gate.ts b/tools/check-webgpu-gate.tsnew file mode 100644index 0000000..9346cf9--- /dev/null+++ b/tools/check-webgpu-gate.ts@@ -0,0 +1,168 @@+// Architecture, dependency-isolation, and binary-size gate for ThreeRT `--renderer webgpu`.+// node tools/check-webgpu-gate.ts [--build] [--render]+//+// Enforces docs/RENDERING-METHODS.md:+// 1. One-way JS layering: `runtime/js/` never imports from `webgpu/` or `renderer/`.+// 2. One-way Rust crate graph: `webgpu/` (`threert-webgpu` and `threert-webgpu-sample`) links+// zero path-tracer, denoiser, voxel, physics, QuickJS, or audio crates.+// 3. Release stripped binary size budget for `threert-webgpu-sample` (macOS).+// 4. Optional headless Metal smoke render (`--render`): renders the three.js r187 WebGPURenderer+// sample scene and verifies a non-blank PNG is produced.+import { spawnSync } from "node:child_process";+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";+import { join } from "node:path";+import { PNG } from "pngjs";++const root = join(import.meta.dirname, "..");++// Crates that MUST NEVER appear in the `webgpu/` dependency graph.+const FORBIDDEN_CRATES = [+ "threert-render",+ "threert-path",+ "voxel-core",+ "physics-core",+ "rapier3d",+ "oidn",+ "dlss",+ "rquickjs",+ "rquickjs-core",+ "rquickjs-sys",+ "symphonia",+ "cpal",+ "ureq",+ "rustls",+ "wesl",+ "gltf",+ "bevy_mikktspace",+];++// Budget for the release, fat-LTO, stripped `threert-webgpu-sample` native binary.+// - macOS uses system CoreGraphics/CoreText/ImageIO (baseline 2.98 MiB → budget 4.50 MiB).+// - Linux bundles pure-Rust tiny-skia + cosmic-text + image (budget 8.50 MiB; still zero path-tracer).+const MAX_SAMPLE_BYTES = process.platform === "darwin"+ ? Math.round(4.5 * 1024 * 1024)+ : Math.round(8.5 * 1024 * 1024);++function walkTs(dir: string): string[] {+ const out: string[] = [];+ for (const ent of readdirSync(dir, { withFileTypes: true })) {+ const p = join(dir, ent.name);+ if (ent.isDirectory()) out.push(...walkTs(p));+ else if (ent.isFile() && ent.name.endsWith(".ts")) out.push(p);+ }+ return out;+}++function checkJsLayering() {+ const runtimeJs = join(root, "runtime", "js");+ const files = walkTs(runtimeJs);+ const violations: string[] = [];+ const importRe = /(?:from|import)\s*["']([^"']+)["']/g;+ for (const f of files) {+ const src = readFileSync(f, "utf8");+ for (const m of src.matchAll(importRe)) {+ const spec = m[1];+ if (spec.includes("/webgpu/") || spec.includes("/renderer/")) {+ violations.push(`${f.slice(root.length + 1)}: forbidden import "${spec}"`);+ }+ }+ }+ if (violations.length > 0) {+ throw new Error(`runtime/js layering violations:\n ${violations.join("\n ")}`);+ }+ console.log(`[gate] JS layering OK (${files.length} files in runtime/js; zero webgpu/renderer imports)`);+}++function checkCargoTreeIsolation() {+ const res = spawnSync("cargo", ["tree", "--locked", "--workspace", "--prefix", "none", "--format", "{p}"], {+ cwd: join(root, "webgpu"),+ encoding: "utf8",+ });+ if (res.status !== 0) {+ throw new Error(`cargo tree failed:\n${res.stderr || res.stdout}`);+ }+ const crates = new Set<string>();+ for (const line of res.stdout.split(/\r?\n/)) {+ const name = line.trim().split(/\s+/)[0];+ if (name) crates.add(name);+ }+ const found = FORBIDDEN_CRATES.filter((c) => crates.has(c));+ if (found.length > 0) {+ throw new Error(`forbidden path-tracer/heavy crates in webgpu/ dependency graph: ${found.join(", ")}`);+ }+ console.log(`[gate] cargo tree isolation OK (${crates.size} unique crates; 0 forbidden path-tracer crates)`);+}++function checkBinarySize() {+ const bin = join(root, "webgpu", "target", "release", "threert-webgpu-sample");+ if (!existsSync(bin)) {+ throw new Error(`release binary missing: ${bin} (run \`node tools/build.ts --renderer webgpu\` first)`);+ }+ const size = statSync(bin).size;+ const mib = (size / (1024 * 1024)).toFixed(2);+ const budgetMib = (MAX_SAMPLE_BYTES / (1024 * 1024)).toFixed(2);+ if (size > MAX_SAMPLE_BYTES) {+ throw new Error(`threert-webgpu-sample is ${mib} MiB, over budget ${budgetMib} MiB`);+ }+ console.log(`[gate] binary size OK: threert-webgpu-sample = ${mib} MiB (budget <= ${budgetMib} MiB)`);+}++function checkHeadlessRender() {+ const bin = join(root, "webgpu", "target", "release", "threert-webgpu-sample");+ const rt = join(root, "out", "webgpu", "runtime.js");+ const script = join(root, "out", "webgpu", "sample.js");+ const shot = join(root, "out", "webgpu", "sample.png");+ const res = spawnSync(bin, ["--runtime", rt, "--script", script, "--size", "640x480@1", "--shot", shot], {+ cwd: root,+ encoding: "utf8",+ });+ if (res.status === 2 && (res.stderr || "").includes("GPU unavailable")) {+ console.log(`[gate] headless render skipped (no GPU adapter on runner)`);+ return;+ }+ if (res.status !== 0) {+ throw new Error(`threert-webgpu-sample failed (exit ${res.status}):\n${res.stderr || res.stdout}`);+ }+ if (!existsSync(shot)) {+ throw new Error(`expected screenshot not written: ${shot}`);+ }+ const png = PNG.sync.read(readFileSync(shot));+ if (png.width !== 640 || png.height !== 480) {+ throw new Error(`unexpected PNG dimensions: ${png.width}x${png.height} (expected 640x480)`);+ }+ // Verify the rendered frame is not blank / flat single color+ let minLum = 255;+ let maxLum = 0;+ let nonBg = 0;+ for (let i = 0; i < png.data.length; i += 4) {+ const r = png.data[i], g = png.data[i + 1], b = png.data[i + 2];+ const lum = (r * 77 + g * 150 + b * 29) >> 8;+ if (lum < minLum) minLum = lum;+ if (lum > maxLum) maxLum = lum;+ if (Math.abs(r - 0x10) + Math.abs(g - 0x14) + Math.abs(b - 0x1d) > 20) nonBg++;+ }+ const coverage = (nonBg / (png.width * png.height)) * 100;+ if (maxLum - minLum < 40 || coverage < 5) {+ throw new Error(`rendered frame looks blank/flat: lum=[${minLum}, ${maxLum}], coverage=${coverage.toFixed(1)}%`);+ }+ console.log(+ `[gate] headless Metal render OK: ${shot} (${png.width}x${png.height}, lum=[${minLum},${maxLum}], coverage=${coverage.toFixed(1)}%)`+ );+}++const args = new Set(process.argv.slice(2));+if (args.has("--build")) {+ const res = spawnSync("node", [join(root, "tools", "build.ts"), "--renderer", "webgpu"], { cwd: root, stdio: "inherit" });+ if (res.status !== 0) process.exit(res.status ?? 1);+}++checkJsLayering();+if (process.platform === "darwin" || process.platform === "linux") {+ checkCargoTreeIsolation();+ checkBinarySize();+ if (args.has("--render")) {+ checkHeadlessRender();+ }+} else {+ console.log(`[gate] unsupported native platform ${process.platform}: skipping cargo tree / binary size checks`);+}diff --git a/webgpu/Cargo.lock b/webgpu/Cargo.locknew file mode 100644index 0000000..fa2fb73--- /dev/null+++ b/webgpu/Cargo.lock@@ -0,0 +1,1944 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"++[[package]]+name = "android_system_properties"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"+dependencies = [+ "libc",+]++[[package]]+name = "arrayref"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"++[[package]]+name = "arrayvec"+version = "0.7.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"++[[package]]+name = "ash"+version = "0.38.0+1.3.281"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f"+dependencies = [+ "libloading",+]++[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"++[[package]]+name = "bit-set"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"+dependencies = [+ "bit-vec",+]++[[package]]+name = "bit-vec"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"++[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"++[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"+dependencies = [+ "serde_core",+]++[[package]]+name = "block"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"++[[package]]+name = "bumpalo"+version = "3.20.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db"++[[package]]+name = "bytemuck"+version = "1.25.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"+dependencies = [+ "bytemuck_derive",+]++[[package]]+name = "bytemuck_derive"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "byteorder-lite"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"++[[package]]+name = "cfg-if"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"++[[package]]+name = "cfg_aliases"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"++[[package]]+name = "codespan-reporting"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe6d2e5af09e8c8ad56c969f2157a3d4238cebc7c55f0a517728c38f7b200f81"+dependencies = [+ "serde",+ "termcolor",+ "unicode-width",+]++[[package]]+name = "color_quant"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"++[[package]]+name = "core-foundation"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"++[[package]]+name = "core-graphics-types"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"+dependencies = [+ "bitflags 1.3.2",+ "core-foundation",+ "libc",+]++[[package]]+name = "cosmic-text"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59fd57d82eb4bfe7ffa9b1cec0c05e2fd378155b47f255a67983cb4afe0e80c2"+dependencies = [+ "bitflags 2.13.2",+ "fontdb",+ "log",+ "rangemap",+ "rayon",+ "rustc-hash",+ "rustybuzz",+ "self_cell",+ "swash",+ "sys-locale",+ "ttf-parser 0.21.1",+ "unicode-bidi",+ "unicode-linebreak",+ "unicode-script",+ "unicode-segmentation",+]++[[package]]+name = "crc32fast"+version = "1.5.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"+dependencies = [+ "cfg-if",+]++[[package]]+name = "crossbeam-deque"+version = "0.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"+dependencies = [+ "crossbeam-epoch",+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-epoch"+version = "0.9.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"++[[package]]+name = "crunchy"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"++[[package]]+name = "document-features"+version = "0.2.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"+dependencies = [+ "litrs",+]++[[package]]+name = "either"+version = "1.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"++[[package]]+name = "equivalent"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"++[[package]]+name = "fdeflate"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"+dependencies = [+ "simd-adler32",+]++[[package]]+name = "flate2"+version = "1.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"+dependencies = [+ "crc32fast",+ "miniz_oxide 0.9.1",+ "zlib-rs",+]++[[package]]+name = "foldhash"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"++[[package]]+name = "font-types"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b3971f9a5ca983419cdc386941ba3b9e1feba01a0ab888adf78739feb2798492"+dependencies = [+ "bytemuck",+]++[[package]]+name = "fontconfig-parser"+version = "0.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"+dependencies = [+ "roxmltree",+]++[[package]]+name = "fontdb"+version = "0.16.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b0299020c3ef3f60f526a4f64ab4a3d4ce116b1acbf24cdd22da0068e5d81dc3"+dependencies = [+ "fontconfig-parser",+ "log",+ "memmap2",+ "slotmap",+ "tinyvec",+ "ttf-parser 0.20.0",+]++[[package]]+name = "foreign-types"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"+dependencies = [+ "foreign-types-macros",+ "foreign-types-shared",+]++[[package]]+name = "foreign-types-macros"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "foreign-types-shared"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"++[[package]]+name = "futures-core"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"++[[package]]+name = "futures-task"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"++[[package]]+name = "futures-util"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"+dependencies = [+ "futures-core",+ "futures-task",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "gif"+version = "0.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"+dependencies = [+ "color_quant",+ "weezl",+]++[[package]]+name = "gl_generator"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d"+dependencies = [+ "khronos_api",+ "log",+ "xml-rs",+]++[[package]]+name = "glow"+version = "0.16.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c5e5ea60d70410161c8bf5da3fdfeaa1c72ed2c15f8bbb9d19fe3a4fad085f08"+dependencies = [+ "js-sys",+ "slotmap",+ "wasm-bindgen",+ "web-sys",+]++[[package]]+name = "glutin_wgl_sys"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e"+dependencies = [+ "gl_generator",+]++[[package]]+name = "gpu-alloc"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "45cf04b2726f02df5508c6de726acdc90cdf97ac771a9a0ffd8ba10a6e696bf9"+dependencies = [+ "bitflags 2.13.2",+ "gpu-alloc-types",+]++[[package]]+name = "gpu-alloc-types"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2bbed164dd10ed526c2e4fe3e721ca4a71c61730e5aafac6844b417b3227058"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "gpu-allocator"+version = "0.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c151a2a5ef800297b4e79efa4f4bec035c5f51d5ae587287c9b952bdf734cacd"+dependencies = [+ "log",+ "presser",+ "thiserror 1.0.69",+ "windows",+]++[[package]]+name = "gpu-descriptor"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b89c83349105e3732062a895becfc71a8f921bb71ecbbdd8ff99263e3b53a0ca"+dependencies = [+ "bitflags 2.13.2",+ "gpu-descriptor-types",+ "hashbrown 0.15.5",+]++[[package]]+name = "gpu-descriptor-types"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fdf242682df893b86f33a73828fb09ca4b2d3bb6cc95249707fc684d27484b91"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "half"+version = "2.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"+dependencies = [+ "cfg-if",+ "crunchy",+ "num-traits",+ "zerocopy",+]++[[package]]+name = "hashbrown"+version = "0.15.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"+dependencies = [+ "foldhash",+]++[[package]]+name = "hashbrown"+version = "0.17.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"++[[package]]+name = "heck"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"++[[package]]+name = "hexf-parse"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df"++[[package]]+name = "image"+version = "0.25.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"+dependencies = [+ "bytemuck",+ "byteorder-lite",+ "color_quant",+ "gif",+ "image-webp",+ "moxcms",+ "num-traits",+ "png 0.18.1",+ "zune-core",+ "zune-jpeg",+]++[[package]]+name = "image-webp"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"+dependencies = [+ "byteorder-lite",+ "quick-error",+]++[[package]]+name = "indexmap"+version = "2.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"+dependencies = [+ "equivalent",+ "hashbrown 0.17.2",+]++[[package]]+name = "itoa"+version = "1.0.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"++[[package]]+name = "jni-sys"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"+dependencies = [+ "jni-sys 0.4.1",+]++[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "js-sys"+version = "0.3.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"+dependencies = [+ "cfg-if",+ "futures-util",+ "wasm-bindgen",+]++[[package]]+name = "khronos-egl"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76"+dependencies = [+ "libc",+ "libloading",+ "pkg-config",+]++[[package]]+name = "khronos_api"+version = "3.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"++[[package]]+name = "libc"+version = "0.2.191"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"++[[package]]+name = "libloading"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"+dependencies = [+ "cfg-if",+ "windows-link",+]++[[package]]+name = "libm"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"++[[package]]+name = "litrs"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02b614978e47ce529faee66579f2b2fe19c94aa96d910a6a9a8043b2b02d8175"++[[package]]+name = "lock_api"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"+dependencies = [+ "scopeguard",+]++[[package]]+name = "log"+version = "0.4.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"++[[package]]+name = "malloc_buf"+version = "0.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb"+dependencies = [+ "libc",+]++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "memmap2"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157"+dependencies = [+ "libc",+]++[[package]]+name = "metal"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f569fb946490b5743ad69813cb19629130ce9374034abe31614a36402d18f99e"+dependencies = [+ "bitflags 2.13.2",+ "block",+ "core-graphics-types",+ "foreign-types",+ "log",+ "objc",+ "paste",+]++[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "miniz_oxide"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "moxcms"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"+dependencies = [+ "num-traits",+ "pxfm",+]++[[package]]+name = "naga"+version = "25.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b977c445f26e49757f9aca3631c3b8b836942cb278d69a92e7b80d3b24da632"+dependencies = [+ "arrayvec",+ "bit-set",+ "bitflags 2.13.2",+ "cfg_aliases",+ "codespan-reporting",+ "half",+ "hashbrown 0.15.5",+ "hexf-parse",+ "indexmap",+ "log",+ "num-traits",+ "once_cell",+ "rustc-hash",+ "spirv",+ "strum",+ "thiserror 2.0.21",+ "unicode-ident",+]++[[package]]+name = "ndk-sys"+version = "0.5.0+25.2.9519653"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c196769dd60fd4f363e11d948139556a344e79d451aeb2fa2fd040738ef7691"+dependencies = [+ "jni-sys 0.3.1",+]++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+ "libm",+]++[[package]]+name = "objc"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1"+dependencies = [+ "malloc_buf",+]++[[package]]+name = "objc2-core-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "objc2-core-graphics"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"+dependencies = [+ "bitflags 2.13.2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-core-text"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"+dependencies = [+ "bitflags 2.13.2",+ "objc2-core-foundation",+ "objc2-core-graphics",+]++[[package]]+name = "objc2-image-io"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32b0446e98cf4a784cc7a0177715ff317eeaa8463841c616cfc78aa4f953c4ea"+dependencies = [+ "objc2-core-foundation",+ "objc2-core-graphics",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "ordered-float"+version = "4.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7bb71e1b3fa6ca1c61f383464aaf2bb0e2f8e772a1f01d486832464de363b951"+dependencies = [+ "num-traits",+]++[[package]]+name = "parking_lot"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"+dependencies = [+ "lock_api",+ "parking_lot_core",+]++[[package]]+name = "parking_lot_core"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"+dependencies = [+ "cfg-if",+ "libc",+ "redox_syscall",+ "smallvec",+ "windows-link",+]++[[package]]+name = "paste"+version = "1.0.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"++[[package]]+name = "pin-project-lite"+version = "0.2.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"++[[package]]+name = "pkg-config"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"++[[package]]+name = "png"+version = "0.17.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"+dependencies = [+ "bitflags 1.3.2",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide 0.8.9",+]++[[package]]+name = "png"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"+dependencies = [+ "bitflags 2.13.2",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide 0.8.9",+]++[[package]]+name = "pocket-drivers"+version = "0.17.0"+source = "git+https://github.com/pocket-nexus/pocketjs?rev=72b7d9a8521b7e1aac55c9f1358853ded2076bce#72b7d9a8521b7e1aac55c9f1358853ded2076bce"+dependencies = [+ "pocket-spec",+]++[[package]]+name = "pocket-guest-jsc"+version = "0.17.0"+source = "git+https://github.com/pocket-nexus/pocketjs?rev=72b7d9a8521b7e1aac55c9f1358853ded2076bce#72b7d9a8521b7e1aac55c9f1358853ded2076bce"+dependencies = [+ "log",+ "pocket-drivers",+ "pocket-runtime",+]++[[package]]+name = "pocket-media"+version = "0.17.0"+source = "git+https://github.com/pocket-nexus/pocketjs?rev=72b7d9a8521b7e1aac55c9f1358853ded2076bce#72b7d9a8521b7e1aac55c9f1358853ded2076bce"+dependencies = [+ "pocket-spec",+]++[[package]]+name = "pocket-package"+version = "0.17.0"+source = "git+https://github.com/pocket-nexus/pocketjs?rev=72b7d9a8521b7e1aac55c9f1358853ded2076bce#72b7d9a8521b7e1aac55c9f1358853ded2076bce"+dependencies = [+ "pocket-drivers",+ "pocket-spec",+]++[[package]]+name = "pocket-render"+version = "0.17.0"+source = "git+https://github.com/pocket-nexus/pocketjs?rev=72b7d9a8521b7e1aac55c9f1358853ded2076bce#72b7d9a8521b7e1aac55c9f1358853ded2076bce"+dependencies = [+ "pocket-drivers",+ "pocket-spec",+]++[[package]]+name = "pocket-runtime"+version = "0.17.0"+source = "git+https://github.com/pocket-nexus/pocketjs?rev=72b7d9a8521b7e1aac55c9f1358853ded2076bce#72b7d9a8521b7e1aac55c9f1358853ded2076bce"+dependencies = [+ "pocket-drivers",+ "pocket-package",+ "pocket-render",+ "pocket-spec",+ "pocketjs-core",+]++[[package]]+name = "pocket-spec"+version = "0.17.0"+source = "git+https://github.com/pocket-nexus/pocketjs?rev=72b7d9a8521b7e1aac55c9f1358853ded2076bce#72b7d9a8521b7e1aac55c9f1358853ded2076bce"++[[package]]+name = "pocketjs-core"+version = "0.17.0"+source = "git+https://github.com/pocket-nexus/pocketjs?rev=72b7d9a8521b7e1aac55c9f1358853ded2076bce#72b7d9a8521b7e1aac55c9f1358853ded2076bce"+dependencies = [+ "pocket-drivers",+ "pocket-media",+ "pocket-package",+ "pocket-render",+ "pocket-spec",+ "taffy",+]++[[package]]+name = "pollster"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"++[[package]]+name = "portable-atomic"+version = "1.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"++[[package]]+name = "presser"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "profiling"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"++[[package]]+name = "pxfm"+version = "0.1.30"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"++[[package]]+name = "quick-error"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "range-alloc"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08"++[[package]]+name = "rangemap"+version = "1.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2d43a8c8c74056248124068fde0df374d1ddf9039e747d190f01c36faeaab08"++[[package]]+name = "raw-window-handle"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"++[[package]]+name = "rayon"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"+dependencies = [+ "either",+ "rayon-core",+]++[[package]]+name = "rayon-core"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"+dependencies = [+ "crossbeam-deque",+ "crossbeam-utils",+]++[[package]]+name = "read-fonts"+version = "0.22.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69aacb76b5c29acfb7f90155d39759a29496aebb49395830e928a9703d2eec2f"+dependencies = [+ "bytemuck",+ "font-types",+]++[[package]]+name = "redox_syscall"+version = "0.5.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "renderdoc-sys"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"++[[package]]+name = "roxmltree"+version = "0.20.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"++[[package]]+name = "rustc-hash"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"++[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "rustybuzz"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfb9cf8877777222e4a3bc7eb247e398b56baba500c38c1c46842431adc8b55c"+dependencies = [+ "bitflags 2.13.2",+ "bytemuck",+ "libm",+ "smallvec",+ "ttf-parser 0.21.1",+ "unicode-bidi-mirroring",+ "unicode-ccc",+ "unicode-properties",+ "unicode-script",+]++[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"++[[package]]+name = "self_cell"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813"++[[package]]+name = "serde"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde_core"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "serde_json"+version = "1.0.154"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "simd-adler32"+version = "0.3.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"++[[package]]+name = "skrifa"+version = "0.22.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e1c44ad1f6c5bdd4eefed8326711b7dbda9ea45dfd36068c427d332aa382cbe"+dependencies = [+ "bytemuck",+ "read-fonts",+]++[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"++[[package]]+name = "slotmap"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"+dependencies = [+ "version_check",+]++[[package]]+name = "smallvec"+version = "1.16.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"++[[package]]+name = "spirv"+version = "0.3.0+sdk-1.3.268.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eda41003dc44290527a59b13432d4a0379379fa074b70174882adfbdfd917844"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "static_assertions"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"++[[package]]+name = "strict-num"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"++[[package]]+name = "strum"+version = "0.26.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06"+dependencies = [+ "strum_macros",+]++[[package]]+name = "strum_macros"+version = "0.26.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be"+dependencies = [+ "heck",+ "proc-macro2",+ "quote",+ "rustversion",+ "syn 2.0.119",+]++[[package]]+name = "swash"+version = "0.1.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cbd59f3f359ddd2c95af4758c18270eddd9c730dde98598023cdabff472c2ca2"+dependencies = [+ "skrifa",+ "yazi",+ "zeno",+]++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "3.0.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "sys-locale"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"+dependencies = [+ "libc",+]++[[package]]+name = "taffy"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfde4e2f8595f222ceaae1fb16b4963952e9b33e358869dc4cd6316b0e0790cd"+dependencies = [+ "arrayvec",+ "serde",+ "slotmap",+]++[[package]]+name = "termcolor"+version = "1.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"+dependencies = [+ "winapi-util",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]++[[package]]+name = "thiserror"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"+dependencies = [+ "thiserror-impl 2.0.21",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "thiserror-impl"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "threert-canvas2d"+version = "0.1.0"+dependencies = [+ "cosmic-text",+ "image",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-core-text",+ "objc2-image-io",+ "threert-jsc",+ "threert-rt",+ "tiny-skia",+]++[[package]]+name = "threert-jsc"+version = "0.1.0"+dependencies = [+ "pocket-guest-jsc",+]++[[package]]+name = "threert-rt"+version = "0.1.0"+dependencies = [+ "threert-jsc",+]++[[package]]+name = "threert-webgpu"+version = "0.1.0"+dependencies = [+ "pollster",+ "serde_json",+ "threert-canvas2d",+ "threert-jsc",+ "threert-rt",+ "wgpu",+]++[[package]]+name = "threert-webgpu-sample"+version = "0.1.0"+dependencies = [+ "threert-canvas2d",+ "threert-jsc",+ "threert-rt",+ "threert-webgpu",+ "wgpu",+]++[[package]]+name = "tiny-skia"+version = "0.11.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab"+dependencies = [+ "arrayref",+ "arrayvec",+ "bytemuck",+ "cfg-if",+ "log",+ "png 0.17.16",+ "tiny-skia-path",+]++[[package]]+name = "tiny-skia-path"+version = "0.11.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93"+dependencies = [+ "arrayref",+ "bytemuck",+ "strict-num",+]++[[package]]+name = "tinyvec"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"++[[package]]+name = "tokio"+version = "1.54.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"+dependencies = [+ "pin-project-lite",+]++[[package]]+name = "ttf-parser"+version = "0.20.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "17f77d76d837a7830fe1d4f12b7b4ba4192c1888001c7164257e4bc6d21d96b4"++[[package]]+name = "ttf-parser"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c591d83f69777866b9126b24c6dd9a18351f177e49d625920d19f989fd31cf8"++[[package]]+name = "unicode-bidi"+version = "0.3.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"++[[package]]+name = "unicode-bidi-mirroring"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23cb788ffebc92c5948d0e997106233eeb1d8b9512f93f41651f52b6c5f5af86"++[[package]]+name = "unicode-ccc"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1df77b101bcc4ea3d78dafc5ad7e4f58ceffe0b2b16bf446aeb50b6cb4157656"++[[package]]+name = "unicode-ident"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"++[[package]]+name = "unicode-linebreak"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f"++[[package]]+name = "unicode-properties"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833"++[[package]]+name = "unicode-script"+version = "0.5.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa04c955db05429d464c74d495c1ee677e1866e783a4c3747f9c0cef7756cabf"++[[package]]+name = "unicode-segmentation"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"++[[package]]+name = "unicode-width"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"++[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"++[[package]]+name = "wasm-bindgen"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"+dependencies = [+ "cfg-if",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-futures"+version = "0.4.80"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501"+dependencies = [+ "js-sys",+ "tokio",+ "wasm-bindgen",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn 3.0.10",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "web-sys"+version = "0.3.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "weezl"+version = "0.1.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"++[[package]]+name = "wgpu"+version = "25.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec8fb398f119472be4d80bc3647339f56eb63b2a331f6a3d16e25d8144197dd9"+dependencies = [+ "arrayvec",+ "bitflags 2.13.2",+ "cfg_aliases",+ "document-features",+ "hashbrown 0.15.5",+ "js-sys",+ "log",+ "naga",+ "parking_lot",+ "portable-atomic",+ "profiling",+ "raw-window-handle",+ "smallvec",+ "static_assertions",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+ "wgpu-core",+ "wgpu-hal",+ "wgpu-types",+]++[[package]]+name = "wgpu-core"+version = "25.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f7b882196f8368511d613c6aeec80655160db6646aebddf8328879a88d54e500"+dependencies = [+ "arrayvec",+ "bit-set",+ "bit-vec",+ "bitflags 2.13.2",+ "cfg_aliases",+ "document-features",+ "hashbrown 0.15.5",+ "indexmap",+ "log",+ "naga",+ "once_cell",+ "parking_lot",+ "portable-atomic",+ "profiling",+ "raw-window-handle",+ "rustc-hash",+ "smallvec",+ "thiserror 2.0.21",+ "wgpu-core-deps-apple",+ "wgpu-core-deps-emscripten",+ "wgpu-core-deps-windows-linux-android",+ "wgpu-hal",+ "wgpu-types",+]++[[package]]+name = "wgpu-core-deps-apple"+version = "25.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfd488b3239b6b7b185c3b045c39ca6bf8af34467a4c5de4e0b1a564135d093d"+dependencies = [+ "wgpu-hal",+]++[[package]]+name = "wgpu-core-deps-emscripten"+version = "25.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f09ad7aceb3818e52539acc679f049d3475775586f3f4e311c30165cf2c00445"+dependencies = [+ "wgpu-hal",+]++[[package]]+name = "wgpu-core-deps-windows-linux-android"+version = "25.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cba5fb5f7f9c98baa7c889d444f63ace25574833df56f5b817985f641af58e46"+dependencies = [+ "wgpu-hal",+]++[[package]]+name = "wgpu-hal"+version = "25.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f968767fe4d3d33747bbd1473ccd55bf0f6451f55d733b5597e67b5deab4ad17"+dependencies = [+ "android_system_properties",+ "arrayvec",+ "ash",+ "bit-set",+ "bitflags 2.13.2",+ "block",+ "bytemuck",+ "cfg-if",+ "cfg_aliases",+ "core-graphics-types",+ "glow",+ "glutin_wgl_sys",+ "gpu-alloc",+ "gpu-allocator",+ "gpu-descriptor",+ "hashbrown 0.15.5",+ "js-sys",+ "khronos-egl",+ "libc",+ "libloading",+ "log",+ "metal",+ "naga",+ "ndk-sys",+ "objc",+ "ordered-float",+ "parking_lot",+ "portable-atomic",+ "profiling",+ "range-alloc",+ "raw-window-handle",+ "renderdoc-sys",+ "smallvec",+ "thiserror 2.0.21",+ "wasm-bindgen",+ "web-sys",+ "wgpu-types",+ "windows",+ "windows-core",+]++[[package]]+name = "wgpu-types"+version = "25.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2aa49460c2a8ee8edba3fca54325540d904dd85b2e086ada762767e17d06e8bc"+dependencies = [+ "bitflags 2.13.2",+ "bytemuck",+ "js-sys",+ "log",+ "thiserror 2.0.21",+ "web-sys",+]++[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys",+]++[[package]]+name = "windows"+version = "0.58.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6"+dependencies = [+ "windows-core",+ "windows-targets",+]++[[package]]+name = "windows-core"+version = "0.58.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-result",+ "windows-strings",+ "windows-targets",+]++[[package]]+name = "windows-implement"+version = "0.58.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-interface"+version = "0.58.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-result"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e"+dependencies = [+ "windows-targets",+]++[[package]]+name = "windows-strings"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10"+dependencies = [+ "windows-result",+ "windows-targets",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-targets"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"+dependencies = [+ "windows_aarch64_gnullvm",+ "windows_aarch64_msvc",+ "windows_i686_gnu",+ "windows_i686_gnullvm",+ "windows_i686_msvc",+ "windows_x86_64_gnu",+ "windows_x86_64_gnullvm",+ "windows_x86_64_msvc",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"++[[package]]+name = "windows_aarch64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"++[[package]]+name = "windows_i686_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"++[[package]]+name = "windows_i686_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"++[[package]]+name = "windows_i686_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"++[[package]]+name = "windows_x86_64_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"++[[package]]+name = "windows_x86_64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"++[[package]]+name = "xml-rs"+version = "0.8.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"++[[package]]+name = "yazi"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c94451ac9513335b5e23d7a8a2b61a7102398b8cca5160829d313e84c9d98be1"++[[package]]+name = "zeno"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd15f8e0dbb966fd9245e7498c7e9e5055d9e5c8b676b95bd67091cd11a1e697"++[[package]]+name = "zerocopy"+version = "0.8.66"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.66"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "zlib-rs"+version = "0.6.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac"++[[package]]+name = "zmij"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"++[[package]]+name = "zune-core"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"++[[package]]+name = "zune-jpeg"+version = "0.5.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"+dependencies = [+ "zune-core",+]diff --git a/webgpu/Cargo.toml b/webgpu/Cargo.tomlnew file mode 100644index 0000000..d279c67--- /dev/null+++ b/webgpu/Cargo.toml@@ -0,0 +1,47 @@+[workspace]+resolver = "2"+members = [".", "sample"]+default-members = [".", "sample"]++[workspace.package]+version = "0.1.0"+edition = "2024"+license = "MIT"++[workspace.dependencies]+jsc = { package = "threert-jsc", path = "../runtime/crates/jsc" }+rt = { package = "threert-rt", path = "../runtime/crates/rt" }+canvas2d = { package = "threert-canvas2d", path = "../runtime/crates/canvas2d" }+wgpu = "25"++[package]+name = "threert-webgpu"+description = "ThreeRT WebGPU renderer: navigator.gpu for the JavaScriptCore runtime over wgpu (zero path-tracer code)"+version.workspace = true+edition.workspace = true+license.workspace = true++[dependencies]+jsc.workspace = true+rt.workspace = true+canvas2d.workspace = true+wgpu.workspace = true+serde_json = "1"+pollster = "0.4"++[[bin]]+name = "webgpu-shot"+path = "src/bin/webgpu-shot.rs"++[profile.dev]+opt-level = 1++[profile.dev.package."*"]+opt-level = 3++[profile.release]+opt-level = 3+lto = "fat"+codegen-units = 1+panic = "abort"+strip = truediff --git a/webgpu/js/index.ts b/webgpu/js/index.tsnew file mode 100644index 0000000..c81bf01--- /dev/null+++ b/webgpu/js/index.ts@@ -0,0 +1,7 @@+// ThreeRT WebGPU runtime entrypoint: mounts the shared web-platform runtime (runtime/js)+// followed by native WebGPU (navigator.gpu + __threertGpuCanvas).+import { installRuntime } from "../../runtime/js/index.ts";+import { installWebGPU } from "./webgpu.ts";++installRuntime();+installWebGPU();diff --git a/webgpu/js/tsconfig.json b/webgpu/js/tsconfig.jsonnew file mode 100644index 0000000..bea7109--- /dev/null+++ b/webgpu/js/tsconfig.json@@ -0,0 +1,14 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "strict": true,+ "noEmit": true,+ "skipLibCheck": true,+ "allowImportingTsExtensions": true,+ "lib": ["ES2024", "DOM", "DOM.Iterable"],+ "types": []+ },+ "include": ["../../runtime/js/native.d.ts", "./**/*.ts"]+}diff --git a/webgpu/js/webgpu.ts b/webgpu/js/webgpu.tsnew file mode 100644index 0000000..a5c621c--- /dev/null+++ b/webgpu/js/webgpu.ts@@ -0,0 +1,817 @@+// WebGPU (navigator.gpu) over threert-webgpu (wgpu). See webgpu/src/lib.rs for the+// design; the short version:+//+// * Native objects are integer ids (`_id`). Objects the page drops are released in batches+// (FinalizationRegistry → `N.release` at the next submit), never while a stream may use them.+// * GPUCommandEncoder and its pass encoders write 32-bit words into a pooled growable stream+// (opcodes below mirror webgpu/src/cmd.rs); `finish()` is the only native call of an+// encoder. Render bundles are streams spliced into the pass by `executeBundles`.+// * Creation dictionaries are passed as JSON with GPU objects replaced by their ids.+import { Event, EventTarget } from "../../runtime/js/core/events.ts";+import { surfaces, type CanvasHost } from "../../runtime/js/shared/surfaces.ts";++const g = globalThis as any;+let N: any;++// -------------------------------------------------------------------------------------- constants++export const GPUBufferUsage = Object.freeze({ MAP_READ: 1, MAP_WRITE: 2, COPY_SRC: 4, COPY_DST: 8, INDEX: 16, VERTEX: 32, UNIFORM: 64, STORAGE: 128, INDIRECT: 256, QUERY_RESOLVE: 512 });+export const GPUTextureUsage = Object.freeze({ COPY_SRC: 1, COPY_DST: 2, TEXTURE_BINDING: 4, STORAGE_BINDING: 8, RENDER_ATTACHMENT: 16 });+export const GPUMapMode = Object.freeze({ READ: 1, WRITE: 2 });+export const GPUShaderStage = Object.freeze({ VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 });+export const GPUColorWrite = Object.freeze({ RED: 1, GREEN: 2, BLUE: 4, ALPHA: 8, ALL: 15 });++/** Command stream opcodes (crates/webgpu/src/cmd.rs `op`). */+const OP = {+ BEGIN_RENDER_PASS: 1, BEGIN_COMPUTE_PASS: 2, END_PASS: 3, COPY_B2B: 4, COPY_B2T: 5, COPY_T2B: 6, COPY_T2T: 7, CLEAR_BUFFER: 8, RESOLVE_QUERY_SET: 9,+ SET_PIPELINE: 16, SET_BIND_GROUP: 17, SET_VERTEX_BUFFER: 18, SET_INDEX_BUFFER: 19, DRAW: 20, DRAW_INDEXED: 21, DRAW_INDIRECT: 22, DRAW_INDEXED_INDIRECT: 23,+ SET_VIEWPORT: 24, SET_SCISSOR: 25, SET_BLEND_CONSTANT: 26, SET_STENCIL_REF: 27, BEGIN_OCCLUSION: 28, END_OCCLUSION: 29, DISPATCH: 30, DISPATCH_INDIRECT: 31,+} as const;+const NONE = 0xffffffff;++// -------------------------------------------------------------------------------------- errors++function domError(message: string, name: string) {+ const D = g.DOMException;+ if (typeof D === "function") return new D(message, name);+ const e = new Error(message); e.name = name; return e;+}++/** Native errors are "Kind: message"; map them to the WebGPU exception types. */+function rethrow(e: any): never {+ const m = String(e?.message ?? e);+ const k = /^(TypeError|RangeError|OperationError|InvalidStateError|AbortError): ?([\s\S]*)$/.exec(m);+ if (!k) throw e;+ if (k[1] === "TypeError") throw new TypeError(k[2]);+ if (k[1] === "RangeError") throw new RangeError(k[2]);+ throw domError(k[2], k[1]);+}++export class GPUError { message: string; constructor(message: string) { this.message = String(message ?? ""); } }+export class GPUValidationError extends GPUError {}+export class GPUOutOfMemoryError extends GPUError {}+export class GPUInternalError extends GPUError {}+const ERROR_KINDS = [GPUValidationError, GPUOutOfMemoryError, GPUInternalError];++export class GPUPipelineError extends Error {+ reason: string;+ constructor(message = "", options: { reason?: string } = {}) { super(message); this.name = "GPUPipelineError"; this.reason = options.reason ?? "validation"; }+}++export class GPUUncapturedErrorEvent extends Event {+ error: GPUError;+ constructor(type: string, init: { error: GPUError }) { super(type); this.error = init.error; }+}++export class GPUDeviceLostInfo { reason: string; message: string; constructor(reason: string, message: string) { this.reason = reason; this.message = message; } }+export class GPUCompilationMessage {+ message: string; type: string; lineNum: number; linePos: number; offset: number; length: number;+ constructor(m: any) { this.message = m.message; this.type = m.type; this.lineNum = m.lineNum; this.linePos = m.linePos; this.offset = m.offset; this.length = m.length; }+}+export class GPUCompilationInfo { messages: GPUCompilationMessage[]; constructor(m: GPUCompilationMessage[]) { this.messages = m; } }++const devices = new Set<GPUDevice>();++/** Deliver queued uncaptured errors to the devices' `uncapturederror` listeners. */+function drainErrors() {+ const e = N.takeErrors();+ if (!e) return;+ for (let i = 0; i < e.length; i += 2) {+ const error = new ERROR_KINDS[e[i]](e[i + 1]);+ for (const d of devices) {+ try { d.dispatchEvent(new GPUUncapturedErrorEvent("uncapturederror", { error })); } catch (x) { console.error(x); }+ }+ }+}++function validationError(msg: string) { N.reportError(0, msg); }++// -------------------------------------------------------------------------------------- object lifetime++const released: number[] = [];+const registry = typeof FinalizationRegistry === "function" ? new FinalizationRegistry<number>((id) => { released.push(id); }) : null;+function flushReleased() {+ if (released.length) { N.release(released, released.length); released.length = 0; }+}++/** Base of native-backed objects; JSON descriptors replace them with their id. */+export class GPUObjectBase {+ /** @internal */ _id: number;+ label: string;+ /** @internal */ constructor(id: number, label?: string, track = true) {+ this._id = id; this.label = label ?? "";+ if (track && id && registry) registry.register(this, id);+ }+}+const lower = (_k: string, v: any) => (v instanceof GPUObjectBase ? v._id : v);+const toJSON = (d: any) => JSON.stringify(d ?? {}, lower);++// -------------------------------------------------------------------------------------- async completion++const waiting = new Map<number, (status: number) => void>();+let polling = false;++function wait(token: number, cb: (status: number) => void) {+ waiting.set(token, cb);+ if (!polling) { polling = true; g.setTimeout(pollTick, 0); }+}++function pollTick() {+ polling = false;+ const ev = N.poll();+ if (ev) {+ for (let i = 0; i < ev.length; i += 2) {+ const cb = waiting.get(ev[i]);+ if (cb) { waiting.delete(ev[i]); try { cb(ev[i + 1]); } catch (e) { console.error(e); } }+ }+ }+ drainErrors();+ if (waiting.size) { polling = true; g.setTimeout(pollTick, 1); }+}++// -------------------------------------------------------------------------------------- command streams++class Stream {+ u: Uint32Array; f: Float32Array; i: Int32Array; n = 0;+ constructor(cap = 2048) { this.u = new Uint32Array(cap); this.f = new Float32Array(this.u.buffer); this.i = new Int32Array(this.u.buffer); }+ grow(k: number) {+ const u = new Uint32Array(Math.max(this.u.length * 2, this.n + k + 64));+ u.set(this.u.subarray(0, this.n));+ this.u = u; this.f = new Float32Array(u.buffer); this.i = new Int32Array(u.buffer);+ }+ /** append raw words (bundles) */+ append(w: Uint32Array) { if (this.n + w.length > this.u.length) this.grow(w.length); this.u.set(w, this.n); this.n += w.length; }+}+const streamPool: Stream[] = [];+const takeStream = () => streamPool.pop() ?? new Stream();+function giveStream(s: Stream) { s.n = 0; if (streamPool.length < 8 && s.u.length <= 1 << 20) streamPool.push(s); }++const vu32 = (v: any) => (v === undefined ? NONE : v >>> 0);++function colorOf(c: any): [number, number, number, number] {+ if (!c) return [0, 0, 0, 0];+ if (Array.isArray(c) || ArrayBuffer.isView(c as any)) return [+c[0] || 0, +c[1] || 0, +c[2] || 0, +c[3] || 0];+ return [+c.r || 0, +c.g || 0, +c.b || 0, +c.a || 0];+}+function originOf(o: any): [number, number, number] {+ if (!o) return [0, 0, 0];+ if (Array.isArray(o)) return [o[0] >>> 0, o[1] >>> 0, o[2] >>> 0];+ return [o.x >>> 0, o.y >>> 0, o.z >>> 0];+}+function extentOf(e: any): [number, number, number] {+ if (Array.isArray(e)) return [e[0] >>> 0, e[1] === undefined ? 1 : e[1] >>> 0, e[2] === undefined ? 1 : e[2] >>> 0];+ return [e.width >>> 0, e.height === undefined ? 1 : e.height >>> 0, e.depthOrArrayLayers === undefined ? 1 : e.depthOrArrayLayers >>> 0];+}+const aspectCode = (a: any) => (a === "stencil-only" ? 1 : a === "depth-only" ? 2 : 0);+const viewId = (v: any) => (v instanceof GPUTexture ? v.createView()._id : v ? v._id : 0);++// -------------------------------------------------------------------------------------- pass encoders++/** Commands shared by render passes and render bundles. */+class RenderCommands {+ /** @internal */ _s!: Stream;+ /** @internal */ _ended = false;+ label = "";+ setPipeline(p: GPURenderPipeline) {+ const s = this._s; if (s.n + 2 > s.u.length) s.grow(2);+ const u = s.u, n = s.n; u[n] = OP.SET_PIPELINE; u[n + 1] = p._id; s.n = n + 2;+ }+ setBindGroup(index: number, bg: GPUBindGroup | null, offsets?: any, start?: number, length?: number) {+ let k = 0;+ if (offsets) { k = length !== undefined ? length >>> 0 : offsets.length - (start ?? 0); }+ const s = this._s; if (s.n + 4 + k > s.u.length) s.grow(4 + k);+ const u = s.u; let n = s.n;+ u[n++] = OP.SET_BIND_GROUP; u[n++] = index >>> 0; u[n++] = bg ? bg._id : 0; u[n++] = k;+ if (k) { const o = start ?? 0; for (let j = 0; j < k; j++) u[n++] = offsets[o + j] >>> 0; }+ s.n = n;+ }+ setVertexBuffer(slot: number, b: GPUBuffer | null, offset = 0, size?: number) {+ const s = this._s; if (s.n + 5 > s.u.length) s.grow(5);+ const u = s.u, n = s.n; u[n] = OP.SET_VERTEX_BUFFER; u[n + 1] = slot >>> 0; u[n + 2] = b ? b._id : 0; u[n + 3] = offset >>> 0; u[n + 4] = vu32(size); s.n = n + 5;+ }+ setIndexBuffer(b: GPUBuffer, format: string, offset = 0, size?: number) {+ const s = this._s; if (s.n + 5 > s.u.length) s.grow(5);+ const u = s.u, n = s.n; u[n] = OP.SET_INDEX_BUFFER; u[n + 1] = b._id; u[n + 2] = format === "uint32" ? 1 : 0; u[n + 3] = offset >>> 0; u[n + 4] = vu32(size); s.n = n + 5;+ }+ draw(vertexCount: number, instanceCount = 1, firstVertex = 0, firstInstance = 0) {+ const s = this._s; if (s.n + 5 > s.u.length) s.grow(5);+ const u = s.u, n = s.n; u[n] = OP.DRAW; u[n + 1] = vertexCount >>> 0; u[n + 2] = instanceCount >>> 0; u[n + 3] = firstVertex >>> 0; u[n + 4] = firstInstance >>> 0; s.n = n + 5;+ }+ drawIndexed(indexCount: number, instanceCount = 1, firstIndex = 0, baseVertex = 0, firstInstance = 0) {+ const s = this._s; if (s.n + 6 > s.u.length) s.grow(6);+ const u = s.u, n = s.n; u[n] = OP.DRAW_INDEXED; u[n + 1] = indexCount >>> 0; u[n + 2] = instanceCount >>> 0; u[n + 3] = firstIndex >>> 0; s.i[n + 4] = baseVertex | 0; u[n + 5] = firstInstance >>> 0; s.n = n + 6;+ }+ drawIndirect(b: GPUBuffer, offset: number) { this._op2(OP.DRAW_INDIRECT, b._id, offset >>> 0); }+ drawIndexedIndirect(b: GPUBuffer, offset: number) { this._op2(OP.DRAW_INDEXED_INDIRECT, b._id, offset >>> 0); }+ /** @internal */ _op2(op: number, a: number, b: number) {+ const s = this._s; if (s.n + 3 > s.u.length) s.grow(3);+ const u = s.u, n = s.n; u[n] = op; u[n + 1] = a; u[n + 2] = b; s.n = n + 3;+ }+ pushDebugGroup(_l: string) {}+ popDebugGroup() {}+ insertDebugMarker(_l: string) {}+}++export class GPURenderPassEncoder extends RenderCommands {+ /** @internal */ _enc: GPUCommandEncoder;+ /** @internal */ constructor(enc: GPUCommandEncoder) { super(); this._enc = enc; this._s = enc._s; }+ setViewport(x: number, y: number, w: number, h: number, minDepth: number, maxDepth: number) {+ const s = this._s; if (s.n + 7 > s.u.length) s.grow(7);+ const f = s.f, n = s.n; s.u[n] = OP.SET_VIEWPORT; f[n + 1] = x; f[n + 2] = y; f[n + 3] = w; f[n + 4] = h; f[n + 5] = minDepth; f[n + 6] = maxDepth; s.n = n + 7;+ }+ setScissorRect(x: number, y: number, w: number, h: number) {+ const s = this._s; if (s.n + 5 > s.u.length) s.grow(5);+ const u = s.u, n = s.n; u[n] = OP.SET_SCISSOR; u[n + 1] = x >>> 0; u[n + 2] = y >>> 0; u[n + 3] = w >>> 0; u[n + 4] = h >>> 0; s.n = n + 5;+ }+ setBlendConstant(color: any) {+ const c = colorOf(color);+ const s = this._s; if (s.n + 5 > s.u.length) s.grow(5);+ const f = s.f, n = s.n; s.u[n] = OP.SET_BLEND_CONSTANT; f[n + 1] = c[0]; f[n + 2] = c[1]; f[n + 3] = c[2]; f[n + 4] = c[3]; s.n = n + 5;+ }+ setStencilReference(ref: number) { const s = this._s; if (s.n + 2 > s.u.length) s.grow(2); s.u[s.n] = OP.SET_STENCIL_REF; s.u[s.n + 1] = ref >>> 0; s.n += 2; }+ beginOcclusionQuery(index: number) { const s = this._s; if (s.n + 2 > s.u.length) s.grow(2); s.u[s.n] = OP.BEGIN_OCCLUSION; s.u[s.n + 1] = index >>> 0; s.n += 2; }+ endOcclusionQuery() { const s = this._s; if (s.n + 1 > s.u.length) s.grow(1); s.u[s.n++] = OP.END_OCCLUSION; }+ executeBundles(bundles: Iterable<GPURenderBundle>) {+ for (const b of bundles) { this._s.append(b._words); this._enc._refs.push(b); }+ }+ end() {+ if (this._ended) { validationError("GPURenderPassEncoder.end: the pass already ended"); return; }+ this._ended = true;+ const s = this._s; if (s.n + 1 > s.u.length) s.grow(1); s.u[s.n++] = OP.END_PASS;+ this._enc._state = "open";+ }+}++export class GPUComputePassEncoder {+ /** @internal */ _enc: GPUCommandEncoder;+ /** @internal */ _s: Stream;+ /** @internal */ _ended = false;+ label = "";+ /** @internal */ constructor(enc: GPUCommandEncoder) { this._enc = enc; this._s = enc._s; }+ setPipeline(p: GPUComputePipeline) { RenderCommands.prototype.setPipeline.call(this as any, p as any); }+ setBindGroup(index: number, bg: GPUBindGroup | null, offsets?: any, start?: number, length?: number) { RenderCommands.prototype.setBindGroup.call(this as any, index, bg, offsets, start, length); }+ dispatchWorkgroups(x: number, y = 1, z = 1) {+ const s = this._s; if (s.n + 4 > s.u.length) s.grow(4);+ const u = s.u, n = s.n; u[n] = OP.DISPATCH; u[n + 1] = x >>> 0; u[n + 2] = y >>> 0; u[n + 3] = z >>> 0; s.n = n + 4;+ }+ dispatchWorkgroupsIndirect(b: GPUBuffer, offset: number) { RenderCommands.prototype._op2.call(this as any, OP.DISPATCH_INDIRECT, b._id, offset >>> 0); }+ pushDebugGroup(_l: string) {}+ popDebugGroup() {}+ insertDebugMarker(_l: string) {}+ end() {+ if (this._ended) { validationError("GPUComputePassEncoder.end: the pass already ended"); return; }+ this._ended = true;+ const s = this._s; if (s.n + 1 > s.u.length) s.grow(1); s.u[s.n++] = OP.END_PASS;+ this._enc._state = "open";+ }+}++export class GPURenderBundle { /** @internal */ _words: Uint32Array; /** @internal */ _refs: any[]; label = ""; /** @internal */ constructor(w: Uint32Array, refs: any[]) { this._words = w; this._refs = refs; } }++export class GPURenderBundleEncoder extends RenderCommands {+ /** @internal */ _refs: any[] = [];+ /** @internal */ constructor(desc: any) { super(); this._s = new Stream(256); this.label = desc?.label ?? ""; }+ setPipeline(p: GPURenderPipeline) { this._refs.push(p); super.setPipeline(p); }+ setBindGroup(index: number, bg: GPUBindGroup | null, offsets?: any, start?: number, length?: number) { this._refs.push(bg); super.setBindGroup(index, bg, offsets, start, length); }+ setVertexBuffer(slot: number, b: GPUBuffer | null, offset = 0, size?: number) { this._refs.push(b); super.setVertexBuffer(slot, b, offset, size); }+ setIndexBuffer(b: GPUBuffer, format: string, offset = 0, size?: number) { this._refs.push(b); super.setIndexBuffer(b, format, offset, size); }+ drawIndirect(b: GPUBuffer, offset: number) { this._refs.push(b); super.drawIndirect(b, offset); }+ drawIndexedIndirect(b: GPUBuffer, offset: number) { this._refs.push(b); super.drawIndexedIndirect(b, offset); }+ finish(desc?: any) {+ const b = new GPURenderBundle(this._s.u.slice(0, this._s.n), this._refs);+ b.label = desc?.label ?? "";+ this._refs = [];+ this._s.n = 0;+ return b;+ }+}++// -------------------------------------------------------------------------------------- command encoder++export class GPUCommandBuffer extends GPUObjectBase {}++export class GPUCommandEncoder {+ /** @internal */ _s: Stream;+ /** @internal */ _state: "open" | "locked" | "ended" = "open";+ /** @internal */ _refs: any[] = [];+ label: string;+ /** @internal */ constructor(desc: any) { this._s = takeStream(); this.label = desc?.label ?? ""; }++ /** @internal */ _begin(what: string) {+ if (this._state !== "open") { validationError(`GPUCommandEncoder.${what}: the encoder is ${this._state === "locked" ? "locked by an open pass" : "finished"}`); return false; }+ return true;+ }++ beginRenderPass(desc: any) {+ const ok = this._begin("beginRenderPass");+ const pass = new GPURenderPassEncoder(this);+ if (!ok) { pass._s = new Stream(64); pass._ended = true; return pass; }+ this._state = "locked";+ pass.label = desc?.label ?? "";+ const ca = desc.colorAttachments ?? [];+ const k = ca.length;+ const s = this._s; if (s.n + 2 + k * 8 + 15 > s.u.length) s.grow(2 + k * 8 + 15);+ const u = s.u, f = s.f; let n = s.n;+ u[n++] = OP.BEGIN_RENDER_PASS; u[n++] = k;+ for (let i = 0; i < k; i++) {+ const a = ca[i];+ if (!a) { for (let j = 0; j < 8; j++) u[n++] = 0; continue; }+ u[n++] = viewId(a.view); u[n++] = viewId(a.resolveTarget);+ u[n++] = a.loadOp === "clear" ? 1 : 0; u[n++] = a.storeOp === "discard" ? 1 : 0;+ const c = colorOf(a.clearValue);+ f[n++] = c[0]; f[n++] = c[1]; f[n++] = c[2]; f[n++] = c[3];+ }+ const ds = desc.depthStencilAttachment;+ if (ds) {+ u[n++] = 1; u[n++] = viewId(ds.view);+ u[n++] = ds.depthLoadOp === "clear" ? 2 : ds.depthLoadOp === "load" ? 1 : 0;+ u[n++] = ds.depthStoreOp === "discard" ? 2 : ds.depthStoreOp === "store" ? 1 : 0;+ f[n++] = ds.depthClearValue ?? 0; u[n++] = ds.depthReadOnly ? 1 : 0;+ u[n++] = ds.stencilLoadOp === "clear" ? 2 : ds.stencilLoadOp === "load" ? 1 : 0;+ u[n++] = ds.stencilStoreOp === "discard" ? 2 : ds.stencilStoreOp === "store" ? 1 : 0;+ u[n++] = (ds.stencilClearValue ?? 0) >>> 0; u[n++] = ds.stencilReadOnly ? 1 : 0;+ } else u[n++] = 0;+ u[n++] = desc.occlusionQuerySet ? desc.occlusionQuerySet._id : 0;+ const tw = desc.timestampWrites;+ u[n++] = tw?.querySet ? tw.querySet._id : 0; u[n++] = vu32(tw?.beginningOfPassWriteIndex); u[n++] = vu32(tw?.endOfPassWriteIndex);+ s.n = n;+ return pass;+ }++ beginComputePass(desc?: any) {+ const ok = this._begin("beginComputePass");+ const pass = new GPUComputePassEncoder(this);+ if (!ok) { pass._s = new Stream(64); pass._ended = true; return pass; }+ this._state = "locked";+ const tw = desc?.timestampWrites;+ this._w([OP.BEGIN_COMPUTE_PASS, tw?.querySet ? tw.querySet._id : 0, vu32(tw?.beginningOfPassWriteIndex), vu32(tw?.endOfPassWriteIndex)]);+ return pass;+ }++ /** @internal */ _w(words: number[]) {+ const s = this._s; if (s.n + words.length > s.u.length) s.grow(words.length);+ for (let i = 0; i < words.length; i++) s.u[s.n + i] = words[i];+ s.n += words.length;+ }++ copyBufferToBuffer(src: GPUBuffer, a: any, b?: any, c?: any, d?: any) {+ if (!this._begin("copyBufferToBuffer")) return;+ // (src, srcOffset, dst, dstOffset, size) or (src, dst, size?)+ let so = 0, dst: GPUBuffer, dOff = 0, size: number;+ if (a instanceof GPUBuffer) { dst = a; size = b === undefined ? src.size : b; }+ else { so = a; dst = b; dOff = c; size = d === undefined ? src.size - so : d; }+ this._w([OP.COPY_B2B, src._id, so >>> 0, dst._id, dOff >>> 0, size >>> 0]);+ }+ /** @internal */ _texInfo(t: any) { const o = originOf(t.origin); return [t.texture._id, (t.mipLevel ?? 0) >>> 0, o[0], o[1], o[2], aspectCode(t.aspect)]; }+ /** @internal */ _bufInfo(b: any) { return [b.buffer._id, (b.offset ?? 0) >>> 0, vu32(b.bytesPerRow), vu32(b.rowsPerImage)]; }+ copyBufferToTexture(src: any, dst: any, size: any) {+ if (!this._begin("copyBufferToTexture")) return;+ this._w([OP.COPY_B2T, ...this._bufInfo(src), ...this._texInfo(dst), ...extentOf(size)]);+ }+ copyTextureToBuffer(src: any, dst: any, size: any) {+ if (!this._begin("copyTextureToBuffer")) return;+ this._w([OP.COPY_T2B, ...this._texInfo(src), ...this._bufInfo(dst), ...extentOf(size)]);+ }+ copyTextureToTexture(src: any, dst: any, size: any) {+ if (!this._begin("copyTextureToTexture")) return;+ this._w([OP.COPY_T2T, ...this._texInfo(src), ...this._texInfo(dst), ...extentOf(size)]);+ }+ clearBuffer(b: GPUBuffer, offset = 0, size?: number) {+ if (!this._begin("clearBuffer")) return;+ this._w([OP.CLEAR_BUFFER, b._id, offset >>> 0, vu32(size)]);+ }+ resolveQuerySet(q: GPUQuerySet, first: number, count: number, dst: GPUBuffer, dstOffset: number) {+ if (!this._begin("resolveQuerySet")) return;+ this._w([OP.RESOLVE_QUERY_SET, q._id, first >>> 0, count >>> 0, dst._id, dstOffset >>> 0]);+ }+ writeTimestamp() { validationError("writeTimestamp is not supported (use timestampWrites)"); }+ pushDebugGroup(_l: string) {}+ popDebugGroup() {}+ insertDebugMarker(_l: string) {}++ finish(desc?: any) {+ let id = 0;+ if (this._state !== "open") validationError(`GPUCommandEncoder.finish: the encoder is ${this._state === "locked" ? "locked by an open pass" : "already finished"}`);+ else id = N.finish(this._s.u, this._s.n);+ if (this._state !== "ended") giveStream(this._s);+ this._state = "ended";+ this._refs = [];+ return new GPUCommandBuffer(id, desc?.label, false);+ }+}++// -------------------------------------------------------------------------------------- resources++type MapRange = { offset: number; size: number; ab: ArrayBuffer };++export class GPUBuffer extends GPUObjectBase {+ readonly size: number;+ readonly usage: number;+ /** @internal */ _state: "unmapped" | "pending" | "mapped" = "unmapped";+ /** @internal */ _mode = 0;+ /** @internal */ _mapOff = 0;+ /** @internal */ _mapEnd = 0;+ /** @internal */ _ranges: MapRange[] = [];+ /** @internal */ _pending: { token: number; reject: (e: any) => void } | null = null;+ /** @internal */ _fresh = false;+ /** @internal */ _destroyed = false;+ /** @internal */ constructor(id: number, desc: any) {+ super(id, desc.label);+ this.size = desc.size; this.usage = desc.usage;+ if (desc.mappedAtCreation) { this._state = "mapped"; this._mode = GPUMapMode.WRITE; this._mapOff = 0; this._mapEnd = desc.size; this._fresh = true; }+ }+ get mapState() { return this._state; }+ mapAsync(mode: number, offset = 0, size?: number): Promise<undefined> {+ if (this._state !== "unmapped") {+ validationError("GPUBuffer.mapAsync: the buffer is already mapped or has a pending map");+ return Promise.reject(domError("The buffer is already mapped or has a pending map", "OperationError"));+ }+ const token = N.mapAsync(this._id, mode, offset, size === undefined ? -1 : size);+ if (!token) return Promise.reject(domError("mapAsync failed validation", "OperationError"));+ this._state = "pending";+ return new Promise((resolve, reject) => {+ this._pending = { token, reject };+ wait(token, (status) => {+ if (this._pending?.token !== token) return; // unmapped meanwhile (already rejected)+ this._pending = null;+ if (status !== 0) { this._state = "unmapped"; reject(domError("mapAsync failed", "OperationError")); return; }+ this._state = "mapped"; this._mode = mode; this._mapOff = offset; this._mapEnd = size === undefined ? this.size : offset + size;+ this._fresh = false;+ resolve(undefined);+ });+ });+ }+ getMappedRange(offset = 0, size?: number): ArrayBuffer {+ if (this._state !== "mapped") throw domError("The buffer is not mapped", "OperationError");+ const sz = size === undefined ? Math.max(0, this._mapEnd - offset) : size;+ if (offset % 8 || sz % 4 || offset < this._mapOff || offset + sz > this._mapEnd) throw domError("getMappedRange: range is outside the mapped range or unaligned", "OperationError");+ for (const r of this._ranges) if (offset < r.offset + r.size && r.offset < offset + sz) throw domError("getMappedRange: overlapping range", "OperationError");+ // A JS-created buffer: native access pins an ArrayBuffer (JSObjectGetTypedArrayBytesPtr),+ // and the page's buffer must stay detachable for unmap.+ const ab = new ArrayBuffer(sz);+ if (!this._fresh && sz) { try { new Uint8Array(ab).set(N.getMappedRange(this._id, offset, sz)); } catch (e) { rethrow(e); } }+ this._ranges.push({ offset, size: sz, ab });+ return ab;+ }+ unmap() {+ if (this._state === "pending") {+ const p = this._pending; this._pending = null;+ p?.reject(domError("The buffer was unmapped before mapAsync completed", "AbortError"));+ N.unmap(this._id, null);+ } else if (this._state === "mapped") {+ // Detach the page's buffers like a real unmap does; for write mappings their contents move+ // (transfer) into the buffers handed to native.+ const write = this._mode === GPUMapMode.WRITE;+ const list: any[] = [];+ for (const r of this._ranges) {+ let moved: ArrayBuffer | null = null;+ try { moved = (r.ab as any).transfer ? (r.ab as any).transfer() : r.ab.slice(0); } catch { /* already detached */ }+ if (write && moved && moved.byteLength) list.push(r.offset, new Uint8Array(moved));+ }+ N.unmap(this._id, list.length ? list : null);+ }+ this._ranges = [];+ this._state = "unmapped";+ this._fresh = false;+ }+ destroy() {+ if (this._destroyed) return;+ if (this._state !== "unmapped") this.unmap();+ this._destroyed = true;+ N.bufferDestroy(this._id);+ }+}++export class GPUTextureView extends GPUObjectBase {}++export class GPUTexture extends GPUObjectBase {+ readonly width: number; readonly height: number; readonly depthOrArrayLayers: number;+ readonly mipLevelCount: number; readonly sampleCount: number; readonly dimension: string;+ readonly format: string; readonly usage: number;+ /** @internal */ _view: GPUTextureView | null = null;+ /** @internal */ constructor(id: number, desc: any, track = true) {+ super(id, desc.label, track);+ const [w, h, d] = extentOf(desc.size);+ this.width = w; this.height = h; this.depthOrArrayLayers = d;+ this.mipLevelCount = desc.mipLevelCount ?? 1; this.sampleCount = desc.sampleCount ?? 1;+ this.dimension = desc.dimension ?? "2d"; this.format = desc.format; this.usage = desc.usage;+ }+ createView(desc?: any) {+ const plain = !desc || (desc.format === undefined && desc.dimension === undefined && (desc.aspect ?? "all") === "all" && !desc.baseMipLevel && desc.mipLevelCount === undefined && !desc.baseArrayLayer && desc.arrayLayerCount === undefined && !desc.usage);+ if (plain && this._view) return this._view;+ const v = new GPUTextureView(N.createView(this._id, plain ? null : toJSON(desc)), desc?.label);+ if (plain) this._view = v;+ return v;+ }+ destroy() { N.textureDestroy(this._id); }+}++export class GPUSampler extends GPUObjectBase {}+export class GPUBindGroupLayout extends GPUObjectBase {}+export class GPUBindGroup extends GPUObjectBase {}+export class GPUPipelineLayout extends GPUObjectBase {}+export class GPUShaderModule extends GPUObjectBase {+ getCompilationInfo() {+ const msgs = JSON.parse(N.shaderInfo(this._id)).map((m: any) => new GPUCompilationMessage(m));+ return Promise.resolve(new GPUCompilationInfo(msgs));+ }+}+class PipelineBase extends GPUObjectBase {+ getBindGroupLayout(index: number) { return new GPUBindGroupLayout(N.getBindGroupLayout(this._id, index >>> 0)); }+}+export class GPURenderPipeline extends PipelineBase {}+export class GPUComputePipeline extends PipelineBase {}+export class GPUQuerySet extends GPUObjectBase {+ readonly type: string; readonly count: number;+ /** @internal */ constructor(id: number, desc: any) { super(id, desc.label); this.type = desc.type; this.count = desc.count; }+ destroy() { N.querySetDestroy(this._id); }+}+export class GPUExternalTexture {}++// -------------------------------------------------------------------------------------- queue++/** Pixels of an image source: [kind, source, width, height] (see crates/webgpu js.rs copyExternal). */+function imageSource(src: any): [number, any, number, number] | null {+ if (!src) throw new TypeError("copyExternalImageToTexture: source is null");+ if (src instanceof GPUCanvasContext) src = src.canvas;+ if ("_imageId" in src) { // HTMLImageElement / ImageBitmap+ const w = src.naturalWidth ?? src.width ?? 0, h = src.naturalHeight ?? src.height ?? 0;+ return src._imageId ? [1, src._imageId, w, h] : null;+ }+ if (ArrayBuffer.isView(src.data) && typeof src.width === "number" && typeof src.getContext !== "function") return [2, src.data, src.width, src.height]; // ImageData+ if (typeof src._surfaceId === "number") return [1, src._surfaceId, src.width, src.height];+ const c = src._context;+ if (c instanceof GPUCanvasContext) return [3, c._cid, src.width, src.height];+ if (c && typeof c._surfaceId === "number") return [1, c._surfaceId, src.width >>> 0, src.height >>> 0];+ if (c && typeof c._readPixelsForExport === "function") { const e = c._readPixelsForExport(); return e ? [2, e.data, e.width, e.height] : null; }+ return null;+}++export class GPUQueue {+ label = "";+ submit(cbs: Iterable<GPUCommandBuffer>) {+ const ids: number[] = [];+ for (const cb of cbs) ids.push(cb._id);+ N.submit(ids, ids.length);+ flushReleased();+ drainErrors();+ }+ writeBuffer(b: GPUBuffer, offset: number, data: any, dataOffset = 0, size?: number) {+ const bpe = ArrayBuffer.isView(data) ? ((data as any).BYTES_PER_ELEMENT ?? 1) : 1;+ try { N.writeBuffer(b._id, offset, data, dataOffset * bpe, size === undefined ? -1 : size * bpe); } catch (e) { rethrow(e); }+ }+ writeTexture(dst: any, data: any, layout: any, size: any) {+ const o = originOf(dst.origin), e = extentOf(size);+ try {+ N.writeTexture(dst.texture._id, (dst.mipLevel ?? 0) >>> 0, o[0], o[1], o[2], aspectCode(dst.aspect), data, (layout.offset ?? 0), layout.bytesPerRow ?? -1, layout.rowsPerImage ?? -1, e[0], e[1], e[2]);+ } catch (x) { rethrow(x); }+ }+ copyExternalImageToTexture(source: any, dst: any, size: any) {+ const s = imageSource(source.source);+ const so = Array.isArray(source.origin) ? source.origin : [source.origin?.x ?? 0, source.origin?.y ?? 0];+ const o = originOf(dst.origin), e = extentOf(size);+ if (!s) return; // blank source: nothing to copy+ try {+ N.copyExternal(s[0], s[1], s[2] >>> 0, s[3] >>> 0, so[0] >>> 0, so[1] >>> 0, !!source.flipY, dst.texture._id, (dst.mipLevel ?? 0) >>> 0, o[0], o[1], o[2], !!dst.premultipliedAlpha, e[0], e[1]);+ } catch (x) { rethrow(x); }+ }+ onSubmittedWorkDone(): Promise<undefined> {+ const token = N.workDone();+ return new Promise((resolve) => wait(token, () => resolve(undefined)));+ }+}++// -------------------------------------------------------------------------------------- device++class GPUSupportedFeatures extends Set<string> {}+class GPUSupportedLimits { [k: string]: number; constructor(l: Record<string, number>) { Object.assign(this, l); } }+class GPUAdapterInfo {+ vendor: string; architecture: string; device: string; description: string; subgroupMinSize = 4; subgroupMaxSize = 128; isFallbackAdapter = false;+ constructor(i: any) { this.vendor = i.vendor; this.architecture = i.architecture; this.device = i.device; this.description = i.description; }+}++export class GPUDevice extends EventTarget {+ readonly features: GPUSupportedFeatures;+ readonly limits: GPUSupportedLimits;+ readonly adapterInfo: GPUAdapterInfo;+ readonly queue = new GPUQueue();+ readonly lost: Promise<GPUDeviceLostInfo>;+ label = "";+ /** @internal */ _lost!: (i: GPUDeviceLostInfo) => void;+ /** @internal */ _onerror: any = null;+ /** @internal */ constructor(features: GPUSupportedFeatures, limits: GPUSupportedLimits, info: GPUAdapterInfo) {+ super();+ this.features = features; this.limits = limits; this.adapterInfo = info;+ this.lost = new Promise((r) => (this._lost = r));+ devices.add(this);+ }+ get onuncapturederror() { return this._onerror; }+ set onuncapturederror(f: any) {+ if (this._onerror) this.removeEventListener("uncapturederror", this._onerror);+ this._onerror = typeof f === "function" ? f : null;+ if (this._onerror) this.addEventListener("uncapturederror", this._onerror);+ }+ destroy() {+ if (!devices.has(this)) return;+ devices.delete(this);+ this._lost(new GPUDeviceLostInfo("destroyed", "device.destroy() was called"));+ }+ createBuffer(desc: any) {+ const d = { size: Number(desc.size) || 0, usage: desc.usage >>> 0, mappedAtCreation: !!desc.mappedAtCreation, label: desc.label };+ let id: number;+ try { id = N.createBuffer(d.size, d.usage, d.mappedAtCreation, desc.label ?? null); } catch (e) { rethrow(e); }+ return new GPUBuffer(id, d);+ }+ createTexture(desc: any) {+ let id: number;+ try { id = N.createTexture(toJSON(desc)); } catch (e) { throw new TypeError(String((e as any)?.message ?? e)); }+ return new GPUTexture(id, desc);+ }+ createSampler(desc?: any) { return new GPUSampler(this._create("createSampler", desc), desc?.label); }+ createBindGroupLayout(desc: any) { return new GPUBindGroupLayout(this._create("createBindGroupLayout", desc), desc.label); }+ createPipelineLayout(desc: any) { return new GPUPipelineLayout(this._create("createPipelineLayout", desc), desc.label); }+ createBindGroup(desc: any) { return new GPUBindGroup(this._create("createBindGroup", desc), desc.label); }+ createShaderModule(desc: any) { return new GPUShaderModule(N.createShaderModule(String(desc.code ?? ""), desc.label ?? null), desc.label); }+ createRenderPipeline(desc: any) { return new GPURenderPipeline(this._create("createRenderPipeline", desc), desc.label); }+ createComputePipeline(desc: any) { return new GPUComputePipeline(this._create("createComputePipeline", desc), desc.label); }+ createRenderPipelineAsync(desc: any) { return this._async("createRenderPipelineAsync", desc, GPURenderPipeline); }+ createComputePipelineAsync(desc: any) { return this._async("createComputePipelineAsync", desc, GPUComputePipeline); }+ createCommandEncoder(desc?: any) { return new GPUCommandEncoder(desc); }+ createRenderBundleEncoder(desc: any) { return new GPURenderBundleEncoder(desc); }+ createQuerySet(desc: any) {+ let id: number;+ try { id = N.createQuerySet(desc.type, desc.count >>> 0); } catch (e) { rethrow(e); }+ return new GPUQuerySet(id, desc);+ }+ importExternalTexture(_d: any): any { throw domError("importExternalTexture is not supported", "NotSupportedError"); }+ pushErrorScope(filter: string) { try { N.pushErrorScope(filter); } catch (e) { rethrow(e); } }+ popErrorScope(): Promise<GPUError | null> {+ let r: any;+ try { r = N.popErrorScope(); } catch (e) { return Promise.reject(domError(String((e as any).message).replace(/^OperationError: /, ""), "OperationError")); }+ return Promise.resolve(r ? new ERROR_KINDS[r[0]](r[1]) : null);+ }+ /** @internal */ _create(fn: string, desc: any): number {+ try { return N[fn](toJSON(desc)); } catch (e) { throw new TypeError(String((e as any)?.message ?? e)); }+ }+ /** @internal */ _async(fn: string, desc: any, C: any) {+ let r: any;+ try { r = N[fn](toJSON(desc)); } catch (e) { return Promise.reject(new TypeError(String((e as any)?.message ?? e))); }+ if (r[1] !== null) return Promise.reject(new GPUPipelineError(r[1], { reason: "validation" }));+ return Promise.resolve(new C(r[0], desc.label));+ }+}++export class GPUAdapter {+ readonly features: GPUSupportedFeatures;+ readonly limits: GPUSupportedLimits;+ readonly info: GPUAdapterInfo;+ readonly isFallbackAdapter = false;+ /** @internal */ constructor(info: any) {+ this.features = new GPUSupportedFeatures(info.features);+ this.limits = new GPUSupportedLimits(info.limits);+ this.info = new GPUAdapterInfo(info.info);+ }+ requestAdapterInfo() { return Promise.resolve(this.info); }+ requestDevice(desc?: any): Promise<GPUDevice> {+ for (const f of desc?.requiredFeatures ?? []) {+ if (!this.features.has(f)) return Promise.reject(new TypeError(`requestDevice: feature '${f}' is not supported`));+ }+ const req = desc?.requiredLimits ?? {};+ for (const k of Object.keys(req)) {+ if (req[k] === undefined) continue;+ if (!(k in this.limits)) return Promise.reject(domError(`requestDevice: unknown limit '${k}'`, "OperationError"));+ const better = /^min/.test(k) ? req[k] >= this.limits[k] : req[k] <= this.limits[k];+ if (!better) return Promise.reject(domError(`requestDevice: limit ${k}=${req[k]} exceeds the adapter's ${this.limits[k]}`, "OperationError"));+ }+ return Promise.resolve(new GPUDevice(this.features, this.limits, this.info));+ }+}++export class GPU {+ readonly wgslLanguageFeatures = new Set<string>();+ requestAdapter(_opts?: any): Promise<GPUAdapter | null> {+ const info = N.info();+ return Promise.resolve(info ? new GPUAdapter(JSON.parse(info)) : null);+ }+ getPreferredCanvasFormat() { return N.preferredFormat(); }+}++// -------------------------------------------------------------------------------------- canvas++const canvasRegistry = typeof FinalizationRegistry === "function" ? new FinalizationRegistry<number>((id) => { try { N.canvasRelease(id); } catch { /* */ } }) : null;++export class GPUCanvasContext {+ readonly canvas: any;+ /** @internal */ _cid: number;+ /** @internal */ _config: any = null;+ /** @internal */ _tex: GPUTexture | null = null;+ /** @internal */ constructor(canvas: any, cid: number, track = true) {+ this.canvas = canvas; this._cid = cid;+ if (track && canvasRegistry) canvasRegistry.register(this, cid);+ }+ configure(config: any) {+ if (!config?.device) throw new TypeError("configure: device is required");+ const usage = config.usage ?? GPUTextureUsage.RENDER_ATTACHMENT;+ try { N.canvasConfigure(this._cid, String(config.format), usage, config.alphaMode === "premultiplied", JSON.stringify(config.viewFormats ?? [])); } catch (e) { rethrow(e); }+ this._config = { ...config, usage, alphaMode: config.alphaMode ?? "opaque", viewFormats: config.viewFormats ?? [] };+ this._tex = null;+ }+ unconfigure() { N.canvasUnconfigure(this._cid); this._config = null; this._tex = null; }+ getConfiguration() { return this._config ? { ...this._config } : null; }+ getCurrentTexture(): GPUTexture {+ if (!this._config) throw domError("getCurrentTexture: the context is not configured", "InvalidStateError");+ let id: number;+ try { id = N.canvasTexture(this._cid); } catch (e) { rethrow(e); }+ if (this._tex && this._tex._id === id) return this._tex;+ const c = this._config;+ this._tex = new GPUTexture(id, { size: [this.canvas.width >>> 0, this.canvas.height >>> 0, 1], format: c.format, usage: c.usage, label: "canvas" }, false);+ return this._tex;+ }+ /** @internal canvas.toDataURL / drawImage / texImage2D of this canvas */+ _readPixelsForExport() {+ const r = N.canvasRead(this._cid);+ return r ? { width: r[0], height: r[1], data: r[2] } : null;+ }+}++/** The window canvas: renders into the host's frame texture (webgpu `set_window_target`). */+export class WindowGpuCanvas {+ style: Record<string, string> = {};+ /** @internal */ _cid = 0;+ /** @internal */ _w = -1;+ /** @internal */ _h = -1;+ /** @internal */ _ctx: GPUCanvasContext | null = null;+ /** @internal */ _context: any = null;+ /** @internal */ _id() {+ if (!this._cid) this._cid = N.windowCanvas();+ return this._cid;+ }+ /** @internal */ _init() {+ if (this._w >= 0) return;+ const i = N.windowInfo();+ const dpr = g.devicePixelRatio || 1;+ this._w = i[0] || Math.round((g.innerWidth || 300) * dpr);+ this._h = i[1] || Math.round((g.innerHeight || 150) * dpr);+ N.canvasResize(this._id(), this._w, this._h);+ }+ get width() { this._init(); return this._w; }+ set width(v: number) { this._init(); this._w = Math.max(0, v >>> 0); N.canvasResize(this._id(), this._w, this._h); }+ get height() { this._init(); return this._h; }+ set height(v: number) { this._init(); this._h = Math.max(0, v >>> 0); N.canvasResize(this._id(), this._w, this._h); }+ get clientWidth() { const i = N.windowInfo(); return i[2] || g.innerWidth || this.width / (g.devicePixelRatio || 1); }+ get clientHeight() { const i = N.windowInfo(); return i[3] || g.innerHeight || this.height / (g.devicePixelRatio || 1); }+ get offsetWidth() { return this.clientWidth; }+ get offsetHeight() { return this.clientHeight; }+ get isConnected() { return true; }+ getBoundingClientRect() {+ const w = this.clientWidth, h = this.clientHeight;+ return { x: 0, y: 0, left: 0, top: 0, width: w, height: h, right: w, bottom: h, toJSON() { return this; } };+ }+ getContext(type: string) {+ if (type !== "webgpu") return null;+ if (!this._ctx) { this._init(); this._ctx = new GPUCanvasContext(this, this._id(), false); this._context = this._ctx; }+ return this._ctx;+ }+ addEventListener() {}+ removeEventListener() {}+ dispatchEvent() { return true; }+ setAttribute() {}+ getAttribute() { return null; }+ removeAttribute() {}+ hasAttribute() { return false; }+ focus() {}+ setPointerCapture() {}+ releasePointerCapture() {}+ toDataURL(type?: string, quality?: number) { return surfaces.toDataURL ? surfaces.toDataURL(this as any, type, quality) : "data:,"; }+}++// -------------------------------------------------------------------------------------- installation++export function installWebGPU() {+ N = g.__native?.gpu;+ if (!N) return;+ N.reportError ??= (_k: number, m: string) => console.warn("[webgpu]", m);+ const gpu = new GPU();+ Object.assign(g, {+ GPU, GPUAdapter, GPUDevice, GPUQueue, GPUBuffer, GPUTexture, GPUTextureView, GPUSampler, GPUBindGroupLayout, GPUBindGroup,+ GPUPipelineLayout, GPUShaderModule, GPURenderPipeline, GPUComputePipeline, GPUQuerySet, GPUCommandEncoder, GPUCommandBuffer,+ GPURenderPassEncoder, GPUComputePassEncoder, GPURenderBundleEncoder, GPURenderBundle, GPUCanvasContext, GPUExternalTexture,+ GPUError, GPUValidationError, GPUOutOfMemoryError, GPUInternalError, GPUPipelineError, GPUUncapturedErrorEvent, GPUDeviceLostInfo,+ GPUCompilationInfo, GPUCompilationMessage, GPUSupportedFeatures, GPUSupportedLimits, GPUAdapterInfo,+ GPUBufferUsage, GPUTextureUsage, GPUMapMode, GPUShaderStage, GPUColorWrite,+ });+ if (!g.navigator) g.navigator = {};+ try { Object.defineProperty(g.navigator, "gpu", { value: gpu, configurable: true, enumerable: true }); } catch { g.navigator.gpu = gpu; }++ surfaces.contextFactories.set("webgpu", (canvas: CanvasHost) => {+ if (canvas._context instanceof GPUCanvasContext) return canvas._context;+ const ctx = new GPUCanvasContext(canvas, N.canvasCreate(canvas.width >>> 0, canvas.height >>> 0));+ canvas._onResize = (w, h) => N.canvasResize(ctx._cid, w >>> 0, h >>> 0);+ return ctx;+ });+ // toDataURL of a WebGPU canvas goes through `_readPixelsForExport` (runtime/js/canvas2d.ts)++ const windowCanvas = new WindowGpuCanvas();+ g.__threertGpuCanvas = windowCanvas;+ g.__pocketGpuCanvas = windowCanvas;+}diff --git a/webgpu/sample/Cargo.toml b/webgpu/sample/Cargo.tomlnew file mode 100644index 0000000..d567f4f--- /dev/null+++ b/webgpu/sample/Cargo.toml@@ -0,0 +1,17 @@+[package]+name = "threert-webgpu-sample"+description = "Minimal native three.js WebGPURenderer sample app on threert-runtime + threert-webgpu (zero path-tracer code)"+version.workspace = true+edition.workspace = true+license.workspace = true++[[bin]]+name = "threert-webgpu-sample"+path = "src/main.rs"++[dependencies]+jsc.workspace = true+rt.workspace = true+canvas2d.workspace = true+threert-webgpu = { path = ".." }+wgpu.workspace = truediff --git a/webgpu/sample/scene.ts b/webgpu/sample/scene.tsnew file mode 100644index 0000000..b1b2f7f--- /dev/null+++ b/webgpu/sample/scene.ts@@ -0,0 +1,76 @@+// Minimal native three.js r187 WebGPURenderer + TSL sample scene for ThreeRT `--renderer webgpu`.+// Renders a lit studio scene with TSL node materials into `globalThis.__threertGpuCanvas` over+// native `navigator.gpu` (wgpu), with zero path-tracer code.+import * as THREE from "three/webgpu";+import { color, mix, normalWorld, positionWorld, sin } from "three/tsl";++declare const __threertGpuCanvas: HTMLCanvasElement;+declare const __native: { sys: { exit(code?: number): void } };++async function main() {+ const canvas = __threertGpuCanvas;+ const renderer = new THREE.WebGPURenderer({ canvas, antialias: true });+ renderer.setPixelRatio(window.devicePixelRatio || 1);+ renderer.setSize(window.innerWidth, window.innerHeight, false);+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.1;+ await renderer.init();++ const scene = new THREE.Scene();+ scene.background = new THREE.Color(0x10141d);++ const camera = new THREE.PerspectiveCamera(42, window.innerWidth / window.innerHeight, 0.1, 100);+ camera.position.set(0, 2.1, 6.4);+ camera.lookAt(0, 1.35, 0);++ // Studio lighting+ const hemi = new THREE.HemisphereLight(0xdbe8ff, 0x262936, 1.1);+ scene.add(hemi);++ const key = new THREE.DirectionalLight(0xfff1dc, 2.8);+ key.position.set(4, 6, 4);+ scene.add(key);++ const rim = new THREE.DirectionalLight(0x52a8ff, 1.4);+ rim.position.set(-4, 3, -3);+ scene.add(rim);++ // TSL node material: subtle vertical/normal color gradient on a metallic torus knot+ const knotMat = new THREE.MeshStandardNodeMaterial({ metalness: 0.35, roughness: 0.28 });+ const rimMix = normalWorld.y.mul(0.5).add(0.5);+ knotMat.colorNode = mix(color(0x2d6bff), color(0xff9f43), rimMix);++ const knot = new THREE.Mesh(new THREE.TorusKnotGeometry(0.95, 0.32, 128, 32), knotMat);+ knot.position.set(0, 1.55, 0);+ scene.add(knot);++ // Ground plane with a procedural TSL checkerboard-like wave pattern+ const floorMat = new THREE.MeshStandardNodeMaterial({ roughness: 0.72, metalness: 0.08 });+ const wave = sin(positionWorld.x.mul(3.0)).mul(sin(positionWorld.z.mul(3.0))).mul(0.5).add(0.5);+ floorMat.colorNode = mix(color(0x1c212e), color(0x283042), wave);++ const floor = new THREE.Mesh(new THREE.PlaneGeometry(18, 18), floorMat);+ floor.rotation.x = -Math.PI / 2;+ scene.add(floor);++ // Render a few frames so pipelines compile and steady-state draws complete cleanly.+ let frame = 0;+ const totalFrames = 4;+ const step = () => {+ knot.rotation.y = 0.45 + frame * 0.15;+ knot.rotation.x = 0.25 + frame * 0.05;+ renderer.render(scene, camera);+ frame++;+ if (frame >= totalFrames) {+ __native.sys.exit(0);+ return;+ }+ requestAnimationFrame(step);+ };+ requestAnimationFrame(step);+}++main().catch((err) => {+ console.error("webgpu sample failed:", err);+ __native.sys.exit(1);+});diff --git a/webgpu/sample/src/main.rs b/webgpu/sample/src/main.rsnew file mode 100644index 0000000..0a44073--- /dev/null+++ b/webgpu/sample/src/main.rs@@ -0,0 +1,263 @@+//! Minimal native ThreeRT `--renderer webgpu` sample host:+//! JavaScriptCore realm + shared runtime services + Canvas 2D + native WebGPU (`navigator.gpu`),+//! with zero path-tracer crates linked.+//!+//! Usage:+//! threert-webgpu-sample --runtime <runtime.js> --script <scene.js>+//! [--size 800x600@2] [--timeout 30] [--fps 60]+//! [--format bgra8unorm|rgba8unorm] [--shot <out.png>]+use std::cell::{Cell, RefCell};+use std::time::{Duration, Instant};++use jsc::{Ctx, Value};+use threert_webgpu as webgpu;++thread_local! {+ static WAKE_AT: Cell<f64> = const { Cell::new(f64::INFINITY) };+ static WANT_FRAME: Cell<bool> = const { Cell::new(false) };+ static EXIT: Cell<Option<i32>> = const { Cell::new(None) };+ static SHOT: RefCell<Option<String>> = const { RefCell::new(None) };+ static RNG: Cell<u64> = const { Cell::new(0x9e37_79b9_7f4a_7c15) };+}++struct Opts {+ runtime: String,+ script: String,+ width: u32,+ height: u32,+ dpr: f64,+ timeout: f64,+ fps: f64,+ format: wgpu::TextureFormat,+ shot: Option<String>,+}++fn opts() -> Opts {+ let args: Vec<String> = std::env::args().collect();+ let get = |k: &str| args.iter().position(|x| x == k).and_then(|i| args.get(i + 1)).cloned();+ let size = get("--size").unwrap_or_else(|| "800x600@2".into());+ let (wh, dpr) = size.split_once('@').unwrap_or((&size, "1"));+ let (w, h) = wh.split_once('x').unwrap_or(("800", "600"));+ Opts {+ runtime: get("--runtime").unwrap_or_else(|| "out/webgpu/runtime.js".into()),+ script: get("--script").unwrap_or_else(|| "out/webgpu/sample.js".into()),+ width: w.parse().unwrap_or(800),+ height: h.parse().unwrap_or(600),+ dpr: dpr.parse().unwrap_or(1.0),+ timeout: get("--timeout").and_then(|s| s.parse().ok()).unwrap_or(30.0),+ fps: get("--fps").and_then(|s| s.parse().ok()).unwrap_or(60.0),+ format: match get("--format").as_deref() {+ Some("rgba8unorm") => wgpu::TextureFormat::Rgba8Unorm,+ _ => wgpu::TextureFormat::Bgra8Unorm,+ },+ shot: get("--shot"),+ }+}++fn install_sys(c: Ctx, sys: Value) {+ let def = |name: &str, f: Value| sys.set(c, name, f);+ def("now", c.function(|c, _, _| Ok(c.num(rt::page_now()))));+ def("wakeAt", c.function(|c, _, a| {+ let t = a.first().map(|v| v.to_num(c)).unwrap_or(f64::INFINITY);+ WAKE_AT.with(|w| w.set(if t.is_nan() { f64::INFINITY } else { t }));+ Ok(c.undefined())+ }));+ def("requestFrame", c.function(|c, _, _| {+ WANT_FRAME.with(|w| w.set(true));+ Ok(c.undefined())+ }));+ def("log", c.function(|c, _, a| {+ let level = a.first().map(|v| v.to_string(c)).unwrap_or_default();+ let msg = a.get(1).map(|v| v.to_string(c)).unwrap_or_default();+ eprintln!("[{level}] {msg}");+ Ok(c.undefined())+ }));+ def("exit", c.function(|c, _, a| {+ EXIT.with(|e| e.set(Some(a.first().map(|v| v.to_i32(c)).unwrap_or(0))));+ Ok(c.undefined())+ }));+ def("shot", c.function(|c, _, a| {+ let path = a.first().map(|v| v.to_string(c)).unwrap_or_else(|| "out/webgpu/sample.png".into());+ SHOT.with(|s| *s.borrow_mut() = Some(path));+ Ok(c.undefined())+ }));+ def("randomBytes", c.function(|c, _, a| {+ let v = a.first().copied().unwrap_or(c.undefined());+ if let Some(b) = v.bytes(c) {+ RNG.with(|r| {+ let mut x = r.get();+ for byte in b.iter_mut() {+ x ^= x << 13;+ x ^= x >> 7;+ x ^= x << 17;+ *byte = x as u8;+ }+ r.set(x);+ });+ }+ Ok(v)+ }));+ def("locale", c.function(|c, _, _| Ok(c.str("en-US"))));+ def("storageGet", c.function(|c, _, _| Ok(c.null())));+ def("storageSet", c.function(|c, _, _| Ok(c.undefined())));+ def("resource", c.function(|c, _, _| Ok(c.null())));+ for name in ["navigate", "shell", "closeWindow"] {+ def(name, c.function(|c, _, _| Ok(c.undefined())));+ }+}++fn call_rt(c: Ctx, name: &str, now: f64) {+ let rtv = c.global().get(c, "__rt");+ if !rtv.is_object(c) {+ return;+ }+ let f = rtv.get(c, name);+ if f.is_function(c) {+ if let Err(e) = c.call(f, Some(rtv), &[c.num(now)]) {+ eprintln!("[js] __rt.{name}: {e}");+ }+ }+}++fn write_shot(off: &webgpu::Offscreen, path: &str, opaque: bool, w: u32, h: u32) -> bool {+ match off.read_rgba(opaque) {+ Ok(px) => {+ let png = canvas2d::encode_png(w, h, &px);+ if let Some(dir) = std::path::Path::new(path).parent() {+ if !dir.as_os_str().is_empty() {+ let _ = std::fs::create_dir_all(dir);+ }+ }+ match std::fs::write(path, png) {+ Ok(()) => {+ eprintln!("[threert-webgpu-sample] wrote {path} ({w}x{h})");+ true+ }+ Err(e) => {+ eprintln!("[threert-webgpu-sample] write {path}: {e}");+ false+ }+ }+ }+ Err(e) => {+ eprintln!("[threert-webgpu-sample] readback failed: {e}");+ false+ }+ }+}++fn main() {+ let o = opts();+ let (pw, ph) = ((o.width as f64 * o.dpr).round() as u32, (o.height as f64 * o.dpr).round() as u32);+ if let Err(e) = webgpu::init(&webgpu::GpuOptions::default()) {+ eprintln!("[threert-webgpu-sample] GPU unavailable: {e}");+ std::process::exit(2);+ }+ let runtime = std::fs::read_to_string(&o.runtime).unwrap_or_else(|e| panic!("read {}: {e}", o.runtime));+ let script = std::fs::read_to_string(&o.script).unwrap_or_else(|e| panic!("read {}: {e}", o.script));++ let cx = jsc::Context::new("threert-webgpu-sample");+ let c = cx.ctx();+ rt::begin_page(c);+ let native = c.object();+ c.global().set(c, "__native", native);+ let sys = c.object();+ native.set(c, "sys", sys);+ install_sys(c, sys);+ canvas2d::install(c, native);+ webgpu::install(c, native);+ c.global().set(+ c,+ "__boot",+ c.json(&format!(+ r#"{{"url":"http://localhost/","width":{},"height":{},"dpr":{},"lang":"en-US","title":"ThreeRT WebGPU Sample"}}"#,+ o.width, o.height, o.dpr+ )),+ );++ let off = webgpu::Offscreen::new(pw, ph, o.format);+ let (lw, lh) = (o.width as f64, o.height as f64);+ let mut last_opaque = true;+ let mut shot_written = false;++ let mut turn = |f: &mut dyn FnMut()| -> webgpu::WindowFrame {+ webgpu::set_window_target(off.texture(), lw, lh);+ f();+ let fr = webgpu::end_window_frame();+ if fr.drew {+ last_opaque = fr.opaque;+ }+ if let Some(path) = SHOT.with(|s| s.borrow_mut().take()) {+ shot_written = write_shot(&off, &path, last_opaque, pw, ph);+ }+ fr+ };++ let mut eval_failed = false;+ turn(&mut || {+ if let Err(e) = c.eval(&runtime, &o.runtime) {+ eprintln!("[js] runtime: {e}");+ eval_failed = true;+ }+ if !eval_failed {+ if let Err(e) = c.eval(&script, &o.script) {+ eprintln!("[js] script: {e}");+ eval_failed = true;+ }+ }+ });+ if eval_failed {+ rt::reset_page();+ drop(cx);+ std::process::exit(1);+ }++ let start = Instant::now();+ let frame_ms = 1000.0 / o.fps.max(1.0);+ let mut next_frame = rt::page_now();+ let mut frames = 0u32;++ let code = loop {+ if let Some(code) = EXIT.with(|e| e.get()) {+ break code;+ }+ if start.elapsed().as_secs_f64() > o.timeout {+ eprintln!("[threert-webgpu-sample] timeout after {}s", o.timeout);+ break 3;+ }+ rt::drain();+ let now = rt::page_now();+ if WAKE_AT.with(|w| w.get()) <= now + 0.5 {+ WAKE_AT.with(|w| w.set(f64::INFINITY));+ turn(&mut || call_rt(c, "timers", now));+ }+ if WANT_FRAME.with(|w| w.get()) && now >= next_frame {+ WANT_FRAME.with(|w| w.set(false));+ next_frame = (next_frame + frame_ms).max(now);+ turn(&mut || call_rt(c, "frame", now));+ frames += 1;+ webgpu::wait_idle();+ continue;+ }+ webgpu::poll();+ let wake = WAKE_AT.with(|w| w.get()).min(if WANT_FRAME.with(|w| w.get()) { next_frame } else { f64::INFINITY });+ let sleep = (wake - rt::page_now()).clamp(0.0, 2.0);+ if sleep > 0.05 {+ std::thread::sleep(Duration::from_secs_f64(sleep / 1000.0));+ }+ };++ if let Some(out) = &o.shot {+ if !shot_written {+ write_shot(&off, out, last_opaque, pw, ph);+ }+ }+ eprintln!(+ "[threert-webgpu-sample] frames={} elapsed={:.1}ms",+ frames,+ start.elapsed().as_secs_f64() * 1000.0+ );+ rt::reset_page();+ drop(cx);+ std::process::exit(code);+}diff --git a/webgpu/sample/tsconfig.json b/webgpu/sample/tsconfig.jsonnew file mode 100644index 0000000..2b3d3c3--- /dev/null+++ b/webgpu/sample/tsconfig.json@@ -0,0 +1,13 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "strict": true,+ "noEmit": true,+ "skipLibCheck": true,+ "lib": ["ES2024", "DOM", "DOM.Iterable"],+ "types": []+ },+ "include": ["./scene.ts"]+}diff --git a/webgpu/src/args.rs b/webgpu/src/args.rsnew file mode 100644index 0000000..58374bb--- /dev/null+++ b/webgpu/src/args.rs@@ -0,0 +1,150 @@+//! Argument decoding and result encoding for `__native.gpu` (same NaN-box fast path as+//! `crates/webgl/src/args.rs`; duplicated so this crate does not depend on the GL binding).+//!+//! Hot-path calls (writeBuffer, finish, submit) take numbers and typed arrays and nearly every argument is a number. Going+//! through `JSValueToNumber` costs an API lock round-trip per argument, so on 64-bit JavaScriptCore we+//! decode the NaN-boxed `JSValueRef` bits directly (the C API passes encoded `JSValue`s on 64-bit).+//! `calibrate` checks the encoding against the live engine once per page; if anything differs the+//! slow, fully general API path is used instead.+use std::ptr::null_mut;+use std::sync::atomic::{AtomicBool, Ordering::Relaxed};++use jsc::*;++static FAST: AtomicBool = AtomicBool::new(false);++const NUMBER_TAG: u64 = 0xfffe_0000_0000_0000;+const DOUBLE_OFFSET: u64 = 1 << 49;+const V_NULL: u64 = 0x02;+const V_FALSE: u64 = 0x06;+const V_TRUE: u64 = 0x07;+const V_UNDEF: u64 = 0x0a;+/// Bits that are zero for a cell (object/string/symbol pointer).+const NOT_CELL_MASK: u64 = NUMBER_TAG | 0x2;++/// Verify the value encoding against the engine (cheap; once per page).+pub fn calibrate(c: Ctx) {+ let enc = |v: JSValueRef| v as u64;+ let ok = unsafe {+ enc(JSValueMakeNumber(c.0, 1.5)) == 1.5f64.to_bits() + DOUBLE_OFFSET+ && enc(JSValueMakeNumber(c.0, -2.25)) == (-2.25f64).to_bits().wrapping_add(DOUBLE_OFFSET)+ && enc(JSValueMakeNumber(c.0, 42.0)) == NUMBER_TAG | 42+ && enc(JSValueMakeNumber(c.0, -7.0)) == NUMBER_TAG | (-7i32 as u32 as u64)+ && enc(JSValueMakeBoolean(c.0, true)) == V_TRUE+ && enc(JSValueMakeBoolean(c.0, false)) == V_FALSE+ && enc(JSValueMakeUndefined(c.0)) == V_UNDEF+ && enc(JSValueMakeNull(c.0)) == V_NULL+ && JSValueToNumber(c.0, (1.5f64.to_bits() + DOUBLE_OFFSET) as JSValueRef, null_mut()) == 1.5+ && JSValueToNumber(c.0, (NUMBER_TAG | 9) as JSValueRef, null_mut()) == 9.0+ };+ FAST.store(ok, Relaxed);+}++#[inline(always)]+fn fast() -> bool {+ FAST.load(Relaxed)+}++/// ToNumber.+#[inline(always)]+pub fn num(c: Ctx, v: Value) -> f64 {+ let u = v.0 as u64;+ if fast() {+ if u >= NUMBER_TAG {+ return (u as u32 as i32) as f64;+ }+ if u & NUMBER_TAG != 0 {+ return f64::from_bits(u.wrapping_sub(DOUBLE_OFFSET));+ }+ match u {+ V_UNDEF => return f64::NAN,+ V_NULL | V_FALSE => return 0.0,+ V_TRUE => return 1.0,+ _ => {}+ }+ }+ unsafe { JSValueToNumber(c.0, v.0, null_mut()) }+}+++++/// ToBoolean.+#[inline(always)]+pub fn truthy(c: Ctx, v: Value) -> bool {+ let u = v.0 as u64;+ if fast() {+ match u {+ V_TRUE => return true,+ V_FALSE | V_UNDEF | V_NULL => return false,+ _ => {}+ }+ if u >= NUMBER_TAG {+ return u as u32 != 0;+ }+ if u & NUMBER_TAG != 0 {+ let d = f64::from_bits(u.wrapping_sub(DOUBLE_OFFSET));+ return d != 0.0 && !d.is_nan();+ }+ }+ unsafe { JSValueToBoolean(c.0, v.0) }+}+++#[inline(always)]+pub fn is_nullish(c: Ctx, v: Value) -> bool {+ let u = v.0 as u64;+ if fast() {+ return u == V_NULL || u == V_UNDEF;+ }+ v.is_nullish(c)+}++/// The bytes viewed by an `ArrayBufferView` (typed array or DataView). The JS layer only ever+/// passes views here; anything else yields `None`. Valid until the next call into JavaScriptCore.+#[inline]+pub fn view<'a>(c: Ctx, v: Value) -> Option<&'a mut [u8]> {+ let u = v.0 as u64;+ let is_cell = if fast() { u != 0 && u & NOT_CELL_MASK == 0 } else { v.is_object(c) };+ if !is_cell {+ return None;+ }+ unsafe {+ let o = v.0 as JSObjectRef;+ let p = JSObjectGetTypedArrayBytesPtr(c.0, o, null_mut()) as *mut u8;+ let len = JSObjectGetTypedArrayByteLength(c.0, o, null_mut());+ if p.is_null() {+ return if len == 0 { Some(&mut []) } else { None };+ }+ let off = JSObjectGetTypedArrayByteOffset(c.0, o, null_mut());+ Some(std::slice::from_raw_parts_mut(p.add(off), len))+ }+}++#[inline(always)]+pub fn int_val(c: Ctx, n: i32) -> Value {+ if fast() { Value((NUMBER_TAG | n as u32 as u64) as JSValueRef) } else { c.num(n as f64) }+}++#[inline]+pub fn num_val(c: Ctx, d: f64) -> Value {+ if fast() {+ if d >= -2147483648.0 && d <= 2147483647.0 && d == (d as i32) as f64 && !(d == 0.0 && d.is_sign_negative()) {+ return int_val(c, d as i32);+ }+ let bits = if d.is_nan() { 0x7ff8_0000_0000_0000u64 } else { d.to_bits() };+ return Value(bits.wrapping_add(DOUBLE_OFFSET) as JSValueRef);+ }+ c.num(d)+}+++#[inline(always)]+pub fn undef(c: Ctx) -> Value {+ if fast() { Value(V_UNDEF as JSValueRef) } else { c.undefined() }+}++#[inline(always)]+pub fn null(c: Ctx) -> Value {+ if fast() { Value(V_NULL as JSValueRef) } else { c.null() }+}diff --git a/webgpu/src/bin/webgpu-shot.rs b/webgpu/src/bin/webgpu-shot.rsnew file mode 100644index 0000000..06ed87a--- /dev/null+++ b/webgpu/src/bin/webgpu-shot.rs@@ -0,0 +1,277 @@+//! Headless WebGPU harness: a JavaScriptCore realm with the minimal runtime three.js needs+//! (console, timers / requestAnimationFrame, performance, navigator, Canvas 2D, WebGPU), a page+//! script, frames paced like the app, and a PNG of the window canvas.+//!+//! webgpu-shot --runtime <runtime.js> --script <page.js> [--size 1200x800@2] [--timeout 60]+//! [--fps 60] [--format bgra8unorm|rgba8unorm] [--out <png>]+//!+//! The page renders into `globalThis.__pocketGpuCanvas` (an `Offscreen` target stands in for the+//! window), calls `__native.sys.shot(path)` (written at the end of the current frame) and+//! `__native.sys.exit(code)`. `--out` shoots the last frame at exit if the page never asked.+//! Prints `[webgpu-shot] frames=… cpu.mean=…ms …` (CPU time of each frame: JS + native, without+//! waiting for the GPU) on exit. Sign with the JIT entitlement (see test/webgpu-compare.mjs).+use std::cell::{Cell, RefCell};+use std::time::{Duration, Instant};++use jsc::{Ctx, Value};+use threert_webgpu as webgpu;++thread_local! {+ static WAKE_AT: Cell<f64> = const { Cell::new(f64::INFINITY) };+ static WANT_FRAME: Cell<bool> = const { Cell::new(false) };+ static EXIT: Cell<Option<i32>> = const { Cell::new(None) };+ static SHOT: RefCell<Option<String>> = const { RefCell::new(None) };+ static RNG: Cell<u64> = const { Cell::new(0x9e37_79b9_7f4a_7c15) };+}++struct Opts {+ runtime: String,+ script: String,+ width: u32,+ height: u32,+ dpr: f64,+ timeout: f64,+ fps: f64,+ format: wgpu::TextureFormat,+ out: Option<String>,+}++fn opts() -> Opts {+ let a: Vec<String> = std::env::args().collect();+ let get = |k: &str| a.iter().position(|x| x == k).and_then(|i| a.get(i + 1)).cloned();+ let size = get("--size").unwrap_or_else(|| "1200x800@2".into());+ let (wh, dpr) = size.split_once('@').unwrap_or((&size, "1"));+ let (w, h) = wh.split_once('x').unwrap_or(("1200", "800"));+ Opts {+ runtime: get("--runtime").expect("--runtime <runtime.js>"),+ script: get("--script").expect("--script <page.js>"),+ width: w.parse().unwrap_or(1200),+ height: h.parse().unwrap_or(800),+ dpr: dpr.parse().unwrap_or(1.0),+ timeout: get("--timeout").and_then(|s| s.parse().ok()).unwrap_or(60.0),+ fps: get("--fps").and_then(|s| s.parse().ok()).unwrap_or(60.0),+ format: match get("--format").as_deref() {+ Some("rgba8unorm") => wgpu::TextureFormat::Rgba8Unorm,+ _ => wgpu::TextureFormat::Bgra8Unorm,+ },+ out: get("--out"),+ }+}++fn install_sys(c: Ctx, sys: Value) {+ let def = |name: &str, f: Value| sys.set(c, name, f);+ def("now", c.function(|c, _, _| Ok(c.num(rt::page_now()))));+ def("wakeAt", c.function(|c, _, a| {+ let t = a.first().map(|v| v.to_num(c)).unwrap_or(f64::INFINITY);+ WAKE_AT.with(|w| w.set(if t.is_nan() { f64::INFINITY } else { t }));+ Ok(c.undefined())+ }));+ def("requestFrame", c.function(|c, _, _| {+ WANT_FRAME.with(|w| w.set(true));+ Ok(c.undefined())+ }));+ def("log", c.function(|c, _, a| {+ let level = a.first().map(|v| v.to_string(c)).unwrap_or_default();+ let msg = a.get(1).map(|v| v.to_string(c)).unwrap_or_default();+ eprintln!("[{level}] {msg}");+ Ok(c.undefined())+ }));+ def("exit", c.function(|c, _, a| {+ EXIT.with(|e| e.set(Some(a.first().map(|v| v.to_i32(c)).unwrap_or(0))));+ Ok(c.undefined())+ }));+ def("shot", c.function(|c, _, a| {+ let path = a.first().map(|v| v.to_string(c)).unwrap_or_else(|| "shot.png".into());+ SHOT.with(|s| *s.borrow_mut() = Some(path));+ Ok(c.undefined())+ }));+ def("randomBytes", c.function(|c, _, a| {+ let v = a.first().copied().unwrap_or(c.undefined());+ if let Some(b) = v.bytes(c) {+ RNG.with(|r| {+ let mut x = r.get();+ for byte in b.iter_mut() {+ x ^= x << 13;+ x ^= x >> 7;+ x ^= x << 17;+ *byte = x as u8;+ }+ r.set(x);+ });+ }+ Ok(v)+ }));+ def("storageGet", c.function(|c, _, _| Ok(c.null())));+ def("storageSet", c.function(|c, _, _| Ok(c.undefined())));+ def("resource", c.function(|c, _, _| Ok(c.null())));+ for name in ["navigate", "shell", "closeWindow"] {+ def(name, c.function(|c, _, _| Ok(c.undefined())));+ }+}++fn call_rt(c: Ctx, name: &str, now: f64) {+ let rtv = c.global().get(c, "__rt");+ if !rtv.is_object(c) {+ return;+ }+ let f = rtv.get(c, name);+ if f.is_function(c) {+ if let Err(e) = c.call(f, Some(rtv), &[c.num(now)]) {+ eprintln!("[js] __rt.{name}: {e}");+ }+ }+}++fn write_shot(off: &webgpu::Offscreen, path: &str, opaque: bool, w: u32, h: u32) {+ match off.read_rgba(opaque) {+ Ok(px) => {+ let png = canvas2d::encode_png(w, h, &px);+ if let Some(dir) = std::path::Path::new(path).parent() {+ let _ = std::fs::create_dir_all(dir);+ }+ match std::fs::write(path, png) {+ Ok(()) => eprintln!("[webgpu-shot] wrote {path}"),+ Err(e) => eprintln!("[webgpu-shot] {path}: {e}"),+ }+ }+ Err(e) => eprintln!("[webgpu-shot] readback failed: {e}"),+ }+}++fn pct(v: &mut [f64], p: f64) -> f64 {+ if v.is_empty() {+ return 0.0;+ }+ v.sort_by(|a, b| a.partial_cmp(b).unwrap());+ v[((v.len() - 1) as f64 * p).round() as usize]+}++#[cfg(target_os = "macos")]+unsafe extern "C" {+ fn pthread_set_qos_class_self_np(qos: u32, relative_priority: i32) -> i32;+}+#[cfg(target_os = "macos")]+const QOS_CLASS_USER_INTERACTIVE: u32 = 0x21;++fn main() {+ // The app's main thread (AppKit) runs at user-interactive QoS; without it an idle-between-frames+ // thread lands on efficiency cores and per-frame timings swing by 2x.+ #[cfg(target_os = "macos")]+ unsafe {+ pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);+ }+ let o = opts();+ let (pw, ph) = ((o.width as f64 * o.dpr).round() as u32, (o.height as f64 * o.dpr).round() as u32);+ if let Err(e) = webgpu::init(&webgpu::GpuOptions::default()) {+ eprintln!("[webgpu-shot] {e}");+ std::process::exit(2);+ }+ let runtime = std::fs::read_to_string(&o.runtime).expect("read runtime");+ let script = std::fs::read_to_string(&o.script).expect("read script");++ let cx = jsc::Context::new("webgpu-shot");+ let c = cx.ctx();+ rt::begin_page(c);+ let native = c.object();+ c.global().set(c, "__native", native);+ let sys = c.object();+ native.set(c, "sys", sys);+ install_sys(c, sys);+ canvas2d::install(c, native);+ webgpu::install(c, native);+ c.global().set(c, "__boot", c.json(&format!(r#"{{"url":"http://localhost/","width":{},"height":{},"dpr":{}}}"#, o.width, o.height, o.dpr)));++ let off = webgpu::Offscreen::new(pw, ph, o.format);+ let (lw, lh) = (o.width as f64, o.height as f64);+ let mut last_opaque = true;+ // Every entry into JS is a window frame for the WebGPU binding: the target is set, and the+ // frame ends (flush, blit, release) when the call returns.+ let mut turn = |f: &mut dyn FnMut()| -> webgpu::WindowFrame {+ webgpu::set_window_target(off.texture(), lw, lh);+ f();+ let fr = webgpu::end_window_frame();+ if fr.drew {+ last_opaque = fr.opaque;+ }+ if let Some(path) = SHOT.with(|s| s.borrow_mut().take()) {+ write_shot(&off, &path, last_opaque, pw, ph);+ }+ fr+ };++ turn(&mut || {+ if let Err(e) = c.eval(&runtime, &o.runtime) {+ eprintln!("[js] runtime: {e}");+ }+ if let Err(e) = c.eval(&script, &o.script) {+ eprintln!("[js] script: {e}");+ }+ });++ let start = Instant::now();+ let frame_ms = 1000.0 / o.fps.max(1.0);+ let mut next_frame = rt::page_now();+ let mut cpu: Vec<f64> = Vec::new();+ let mut stats: Vec<webgpu::Stats> = Vec::new();+ let code = loop {+ if let Some(code) = EXIT.with(|e| e.get()) {+ break code;+ }+ if start.elapsed().as_secs_f64() > o.timeout {+ eprintln!("[webgpu-shot] timeout after {}s", o.timeout);+ break 3;+ }+ rt::drain();+ let now = rt::page_now();+ if WAKE_AT.with(|w| w.get()) <= now + 0.5 {+ WAKE_AT.with(|w| w.set(f64::INFINITY));+ turn(&mut || call_rt(c, "timers", now));+ }+ if WANT_FRAME.with(|w| w.get()) && now >= next_frame {+ WANT_FRAME.with(|w| w.set(false));+ next_frame = (next_frame + frame_ms).max(now);+ webgpu::take_stats();+ let t0 = Instant::now();+ turn(&mut || call_rt(c, "frame", now));+ cpu.push(t0.elapsed().as_secs_f64() * 1000.0);+ stats.push(webgpu::take_stats());+ // keep at most one frame in flight, like a vsync-paced swapchain+ webgpu::wait_idle();+ continue;+ }+ webgpu::poll();+ let wake = WAKE_AT.with(|w| w.get()).min(if WANT_FRAME.with(|w| w.get()) { next_frame } else { f64::INFINITY });+ let sleep = (wake - rt::page_now()).clamp(0.0, 2.0);+ if sleep > 0.05 {+ std::thread::sleep(Duration::from_secs_f64(sleep / 1000.0));+ }+ };+ if let Some(out) = &o.out {+ write_shot(&off, out, last_opaque, pw, ph);+ }+ // per-frame CPU (skip warm-up frames: pipeline compilation, first uploads)+ let skip = (cpu.len() / 4).min(30);+ let mut steady: Vec<f64> = cpu.iter().skip(skip).copied().collect();+ let n = steady.len().max(1) as f64;+ let mean = steady.iter().sum::<f64>() / n;+ let st = &stats[skip.min(stats.len())..];+ let avg = |f: fn(&webgpu::Stats) -> f64| st.iter().map(f).sum::<f64>() / st.len().max(1) as f64;+ eprintln!(+ "[webgpu-shot] frames={} steady={} cpu.mean={:.3}ms cpu.p50={:.3}ms cpu.p95={:.3}ms native.finish={:.3}ms native.submit={:.3}ms native.write={:.3}ms draws={:.0} passes={:.1} writes={:.0} calls={:.0}",+ cpu.len(),+ steady.len(),+ mean,+ pct(&mut steady.clone(), 0.5),+ pct(&mut steady, 0.95),+ avg(|s| s.finish_ns as f64 / 1e6),+ avg(|s| s.submit_ns as f64 / 1e6),+ avg(|s| s.write_ns as f64 / 1e6),+ avg(|s| s.draws as f64),+ avg(|s| s.passes as f64),+ avg(|s| s.writes as f64),+ avg(|s| s.calls as f64),+ );+ rt::reset_page();+ drop(cx);+ std::process::exit(code);+}diff --git a/webgpu/src/canvas.rs b/webgpu/src/canvas.rsnew file mode 100644index 0000000..b430825--- /dev/null+++ b/webgpu/src/canvas.rs@@ -0,0 +1,230 @@+//! `GPUCanvasContext` backing: the window canvas (renders into a texture the host supplies each+//! frame) and owned canvases (DOM / OffscreenCanvas / headless: an owned texture).+use crate::res::{Res, Slab, TextureRes};++#[derive(Clone, Debug, PartialEq)]+pub struct Config {+ pub format: wgpu::TextureFormat,+ pub usage: wgpu::TextureUsages,+ /// alphaMode "premultiplied" (else "opaque")+ pub premultiplied: bool,+ pub view_formats: Vec<wgpu::TextureFormat>,+}++pub struct Canvas {+ pub window: bool,+ pub width: u32,+ pub height: u32,+ pub config: Option<Config>,+ /// owned texture (owned canvases, or the window canvas when it cannot render direct)+ pub owned: Option<(u32, wgpu::Texture)>,+ /// texture id handed out since the last frame boundary (0 = none)+ pub current: u32,+ /// the current texture still needs its implicit clear (first pass loads → clears)+ pub pending_clear: bool,+}++/// What the host gave us for this frame.+pub struct Target {+ pub texture: wgpu::Texture,+ pub logical: (f64, f64),+}++impl Canvas {+ pub fn new(window: bool, width: u32, height: u32) -> Self {+ Canvas { window, width, height, config: None, owned: None, current: 0, pending_clear: false }+ }++ /// Drop textures (unconfigure / resize / reset). Removes our slab entries; JS objects for+ /// them become invalid like a destroyed texture.+ pub fn drop_textures(&mut self, slab: &mut Slab) {+ if let Some((id, tex)) = self.owned.take() {+ tex.destroy();+ slab.remove(id);+ }+ self.release_current(slab);+ }++ /// End of a frame: the current texture is "presented"; the next getCurrentTexture starts a+ /// new one (owned textures are reused but cleared again).+ pub fn release_current(&mut self, slab: &mut Slab) {+ if self.current != 0 && self.owned.as_ref().map(|o| o.0) != Some(self.current) {+ // a host target registered for this frame+ slab.remove(self.current);+ }+ self.current = 0;+ self.pending_clear = false;+ }++ /// The window canvas can render straight into the host's texture.+ pub fn direct_ok(&self, t: &Target) -> bool {+ let Some(c) = &self.config else { return false };+ c.format == t.texture.format() && self.width == t.texture.width() && self.height == t.texture.height() && t.texture.usage().contains(c.usage)+ }++ /// getCurrentTexture: `Err` = InvalidStateError (not configured / zero size).+ pub fn current_texture(&mut self, dev: &wgpu::Device, slab: &mut Slab, target: Option<&Target>) -> Result<u32, String> {+ let Some(cfg) = self.config.clone() else { return Err("the canvas context is not configured".into()) };+ if self.width == 0 || self.height == 0 {+ return Err("the canvas has a zero size".into());+ }+ if self.current != 0 && slab.get(self.current).is_some() {+ return Ok(self.current);+ }+ let usage_for = |u: wgpu::TextureUsages| u | wgpu::TextureUsages::COPY_SRC | if self.window { wgpu::TextureUsages::TEXTURE_BINDING } else { wgpu::TextureUsages::empty() };+ let id = match target.filter(|t| self.window && self.direct_ok(t)) {+ Some(t) => {+ // direct: no intermediate; drop a stale one+ if let Some((id, tex)) = self.owned.take() {+ tex.destroy();+ slab.remove(id);+ }+ let tex = t.texture.clone();+ slab.insert(Res::Texture(TextureRes {+ format: tex.format(),+ size: tex.size(),+ mips: 1,+ samples: 1,+ dimension: wgpu::TextureDimension::D2,+ usage: tex.usage(),+ canvas: true,+ tex,+ }))+ }+ None => {+ let ok = self.owned.as_ref().is_some_and(|(_, t)| t.width() == self.width && t.height() == self.height && t.format() == cfg.format && t.usage() == usage_for(cfg.usage));+ if !ok {+ if let Some((id, tex)) = self.owned.take() {+ tex.destroy();+ slab.remove(id);+ }+ let usage = usage_for(cfg.usage);+ let size = wgpu::Extent3d { width: self.width, height: self.height, depth_or_array_layers: 1 };+ let tex = dev.create_texture(&wgpu::TextureDescriptor {+ label: Some("canvas"),+ size,+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: cfg.format,+ usage,+ view_formats: &cfg.view_formats,+ });+ let id = slab.insert(Res::Texture(TextureRes { tex: tex.clone(), format: cfg.format, size, mips: 1, samples: 1, dimension: wgpu::TextureDimension::D2, usage, canvas: true }));+ self.owned = Some((id, tex));+ }+ self.owned.as_ref().unwrap().0+ }+ };+ self.current = id;+ self.pending_clear = true;+ Ok(id)+ }++ /// The texture with this frame's (or the last) content.+ pub fn content(&self, slab: &Slab) -> Option<wgpu::Texture> {+ if self.current != 0 {+ if let Ok(t) = slab.texture(self.current) {+ return Some(t.tex.clone());+ }+ }+ self.owned.as_ref().map(|(_, t)| t.clone())+ }+}++/// Scales/converts the window canvas's own texture into the host target.+pub struct Blitter {+ shader: wgpu::ShaderModule,+ layout: wgpu::BindGroupLayout,+ sampler: wgpu::Sampler,+ pipelines: Vec<((wgpu::TextureFormat, bool), wgpu::RenderPipeline)>,+}++const BLIT_WGSL: &str = r#"+@group(0) @binding(0) var src: texture_2d<f32>;+@group(0) @binding(1) var smp: sampler;+struct VO { @builtin(position) pos: vec4f, @location(0) uv: vec2f };+@vertex fn vs(@builtin(vertex_index) i: u32) -> VO {+ let uv = vec2f(f32((i << 1u) & 2u), f32(i & 2u));+ var o: VO;+ o.pos = vec4f(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0);+ o.uv = uv;+ return o;+}+fn lin(c: vec3f) -> vec3f { return select(pow((c + 0.055) / 1.055, vec3f(2.4)), c / 12.92, c <= vec3f(0.04045)); }+@fragment fn fs(v: VO) -> @location(0) vec4f { return textureSample(src, smp, v.uv); }+@fragment fn fs_opaque(v: VO) -> @location(0) vec4f { return vec4f(textureSample(src, smp, v.uv).rgb, 1.0); }+@fragment fn fs_srgb(v: VO) -> @location(0) vec4f { let c = textureSample(src, smp, v.uv); return vec4f(lin(c.rgb), c.a); }+@fragment fn fs_srgb_opaque(v: VO) -> @location(0) vec4f { return vec4f(lin(textureSample(src, smp, v.uv).rgb), 1.0); }+"#;++impl Blitter {+ pub fn new(dev: &wgpu::Device) -> Self {+ let shader = dev.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("canvas blit"), source: wgpu::ShaderSource::Wgsl(BLIT_WGSL.into()) });+ let layout = dev.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("canvas blit"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false },+ count: None,+ },+ wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), count: None },+ ],+ });+ let sampler = dev.create_sampler(&wgpu::SamplerDescriptor { mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, ..Default::default() });+ Blitter { shader, layout, sampler, pipelines: Vec::new() }+ }++ pub fn blit(&mut self, dev: &wgpu::Device, queue: &wgpu::Queue, src: &wgpu::Texture, dst: &wgpu::Texture, opaque: bool) {+ let format = dst.format();+ let key = (format, opaque);+ if !self.pipelines.iter().any(|(k, _)| *k == key) {+ let pl = dev.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[&self.layout], push_constant_ranges: &[] });+ let fs = match (format.is_srgb(), opaque) {+ (false, false) => "fs",+ (false, true) => "fs_opaque",+ (true, false) => "fs_srgb",+ (true, true) => "fs_srgb_opaque",+ };+ let p = dev.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("canvas blit"),+ layout: Some(&pl),+ vertex: wgpu::VertexState { module: &self.shader, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] },+ primitive: Default::default(),+ depth_stencil: None,+ multisample: Default::default(),+ fragment: Some(wgpu::FragmentState {+ module: &self.shader,+ entry_point: Some(fs),+ compilation_options: Default::default(),+ targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })],+ }),+ multiview: None,+ cache: None,+ });+ self.pipelines.push((key, p));+ }+ let pipeline = &self.pipelines.iter().find(|(k, _)| *k == key).unwrap().1;+ let view = src.create_view(&Default::default());+ let bg = dev.create_bind_group(&wgpu::BindGroupDescriptor {+ label: None,+ layout: &self.layout,+ entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) }, wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.sampler) }],+ });+ let target = dst.create_view(&Default::default());+ let mut enc = dev.create_command_encoder(&Default::default());+ {+ let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: Some("canvas blit"),+ color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &target, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store } })],+ ..Default::default()+ });+ pass.set_pipeline(pipeline);+ pass.set_bind_group(0, &bg, &[]);+ pass.draw(0..3, 0..1);+ }+ queue.submit([enc.finish()]);+ }+}diff --git a/webgpu/src/cmd.rs b/webgpu/src/cmd.rsnew file mode 100644index 0000000..0f034d9--- /dev/null+++ b/webgpu/src/cmd.rs@@ -0,0 +1,530 @@+//! The command stream: what a `GPUCommandEncoder` recorded in JS, replayed into wgpu at+//! `finish()`.+//!+//! JS appends 32-bit words to a growable `Uint32Array` (floats are written through a+//! `Float32Array` over the same buffer); `finish()` hands the whole stream over in one call, which+//! reads it in place. Objects are slab ids (`0` = none); [`NONE`] marks an omitted optional value.+//! The opcode table is mirrored in `runtime/webgpu.ts` (`OP`).+//!+//! Encoder level:+//! ```text+//! BEGIN_RENDER_PASS nColor { view resolve load store r g b a }×nColor hasDS [view dLoad dStore dClear(f32) dRO sLoad sStore sClear sRO]+//! occlusionSet tsSet tsBegin tsEnd load: 0 load/1 clear, store: 0 store/1 discard+//! dLoad/sLoad: 0 none/1 load/2 clear, dStore/sStore: 0 none/1 store/2 discard+//! BEGIN_COMPUTE_PASS tsSet tsBegin tsEnd+//! COPY_B2B src srcOff dst dstOff size+//! COPY_B2T buf off bpr rpi | tex mip x y z aspect | w h d+//! COPY_T2B tex mip x y z aspect | buf off bpr rpi | w h d+//! COPY_T2T tex mip x y z aspect | tex mip x y z aspect | w h d+//! CLEAR_BUFFER buf off size+//! RESOLVE_QUERY_SET set first count buf off+//! ```+//! Pass level (until END_PASS):+//! ```text+//! SET_PIPELINE id · SET_BIND_GROUP index id n off×n · SET_VERTEX_BUFFER slot id off size ·+//! SET_INDEX_BUFFER id fmt(0 u16/1 u32) off size · DRAW vc ic fv fi · DRAW_INDEXED ic inst fi base(i32) finst ·+//! DRAW_INDIRECT id off · DRAW_INDEXED_INDIRECT id off · SET_VIEWPORT x y w h min max (f32) ·+//! SET_SCISSOR x y w h · SET_BLEND_CONSTANT r g b a (f32) · SET_STENCIL_REF ref ·+//! BEGIN_OCCLUSION index · END_OCCLUSION · DISPATCH x y z · DISPATCH_INDIRECT id off · END_PASS+//! ```+use crate::fmt;+use crate::res::Slab;++pub const NONE: u32 = u32::MAX;++pub mod op {+ pub const BEGIN_RENDER_PASS: u32 = 1;+ pub const BEGIN_COMPUTE_PASS: u32 = 2;+ pub const END_PASS: u32 = 3;+ pub const COPY_B2B: u32 = 4;+ pub const COPY_B2T: u32 = 5;+ pub const COPY_T2B: u32 = 6;+ pub const COPY_T2T: u32 = 7;+ pub const CLEAR_BUFFER: u32 = 8;+ pub const RESOLVE_QUERY_SET: u32 = 9;++ pub const SET_PIPELINE: u32 = 16;+ pub const SET_BIND_GROUP: u32 = 17;+ pub const SET_VERTEX_BUFFER: u32 = 18;+ pub const SET_INDEX_BUFFER: u32 = 19;+ pub const DRAW: u32 = 20;+ pub const DRAW_INDEXED: u32 = 21;+ pub const DRAW_INDIRECT: u32 = 22;+ pub const DRAW_INDEXED_INDIRECT: u32 = 23;+ pub const SET_VIEWPORT: u32 = 24;+ pub const SET_SCISSOR: u32 = 25;+ pub const SET_BLEND_CONSTANT: u32 = 26;+ pub const SET_STENCIL_REF: u32 = 27;+ pub const BEGIN_OCCLUSION: u32 = 28;+ pub const END_OCCLUSION: u32 = 29;+ pub const DISPATCH: u32 = 30;+ pub const DISPATCH_INDIRECT: u32 = 31;+}++/// Bounds-checked reader over the words.+pub struct Reader<'a> {+ w: &'a [u32],+ pos: usize,+}++impl<'a> Reader<'a> {+ pub fn new(w: &'a [u32]) -> Self {+ Reader { w, pos: 0 }+ }+ pub fn done(&self) -> bool {+ self.pos >= self.w.len()+ }+ #[inline]+ pub fn u(&mut self) -> Result<u32, String> {+ let v = *self.w.get(self.pos).ok_or("truncated command stream")?;+ self.pos += 1;+ Ok(v)+ }+ #[inline]+ pub fn f(&mut self) -> Result<f32, String> {+ self.u().map(f32::from_bits)+ }+ #[inline]+ pub fn i(&mut self) -> Result<i32, String> {+ self.u().map(|v| v as i32)+ }+ pub fn opt(&mut self) -> Result<Option<u32>, String> {+ self.u().map(|v| if v == NONE { None } else { Some(v) })+ }+ pub fn take(&mut self, n: usize) -> Result<&'a [u32], String> {+ let end = self.pos.checked_add(n).filter(|e| *e <= self.w.len()).ok_or("truncated command stream")?;+ let s = &self.w[self.pos..end];+ self.pos = end;+ Ok(s)+ }+}++/// Builds streams in Rust (tests and internal passes); mirrors the JS encoder.+#[derive(Default)]+pub struct Writer {+ pub w: Vec<u32>,+}++impl Writer {+ pub fn u(&mut self, v: u32) -> &mut Self {+ self.w.push(v);+ self+ }+ pub fn f(&mut self, v: f32) -> &mut Self {+ self.w.push(v.to_bits());+ self+ }+}++/// Per-replay hooks into the canvas module.+pub trait Hooks {+ /// `texture` is used as a color attachment (`load`: with loadOp "load") or resolve target.+ /// Returns whether the load must become a clear: a canvas texture's first use in a frame+ /// sees transparent black, like a freshly presented canvas.+ fn canvas_use(&mut self, texture: u32, load: bool) -> bool;+}++#[derive(Default, Clone, Copy, Debug)]+pub struct Counts {+ pub passes: u32,+ pub draws: u32,+ pub commands: u32,+}++fn buffer_slice<'s>(slab: &'s Slab, id: u32, off: u32, size: u32) -> Result<wgpu::BufferSlice<'s>, String> {+ let b = slab.buffer(id)?;+ let off = off as u64;+ let end = if size == NONE { b.size } else { off + size as u64 };+ if off >= b.size || end > b.size || end <= off {+ return Err(format!("buffer range [{off}, {end}) is empty or outside buffer {id} of size {}", b.size));+ }+ Ok(b.buf.slice(off..end))+}++fn tex_info<'s>(slab: &'s Slab, r: &mut Reader) -> Result<wgpu::TexelCopyTextureInfo<'s>, String> {+ let t = slab.texture(r.u()?)?;+ let mip_level = r.u()?;+ let origin = wgpu::Origin3d { x: r.u()?, y: r.u()?, z: r.u()? };+ let aspect = fmt::aspect_code(r.u()?);+ Ok(wgpu::TexelCopyTextureInfo { texture: &t.tex, mip_level, origin, aspect })+}++fn buf_info<'s>(slab: &'s Slab, r: &mut Reader) -> Result<wgpu::TexelCopyBufferInfo<'s>, String> {+ let b = slab.buffer(r.u()?)?;+ let offset = r.u()? as u64;+ let bytes_per_row = r.opt()?;+ let rows_per_image = r.opt()?;+ Ok(wgpu::TexelCopyBufferInfo { buffer: &b.buf, layout: wgpu::TexelCopyBufferLayout { offset, bytes_per_row, rows_per_image } })+}++fn extent(r: &mut Reader) -> Result<wgpu::Extent3d, String> {+ Ok(wgpu::Extent3d { width: r.u()?, height: r.u()?, depth_or_array_layers: r.u()? })+}++fn timestamp_set<'s>(slab: &'s Slab, r: &mut Reader) -> Result<Option<(&'s wgpu::QuerySet, Option<u32>, Option<u32>)>, String> {+ let set = r.u()?;+ let begin = r.opt()?;+ let end = r.opt()?;+ if set == 0 {+ return Ok(None);+ }+ Ok(Some((&slab.query_set(set)?.set, begin, end)))+}++/// Replay a recorded command encoder. Errors are encoding errors (bad ids, malformed stream);+/// wgpu's own validation errors go to the error sink as usual.+pub fn encode(dev: &wgpu::Device, slab: &Slab, words: &[u32], hooks: &mut dyn Hooks, counts: &mut Counts) -> Result<wgpu::CommandBuffer, String> {+ let mut enc = dev.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });+ encode_into(&mut enc, slab, words, hooks, counts)?;+ Ok(enc.finish())+}++/// Replay a recorded stream into `enc`.+pub fn encode_into(enc: &mut wgpu::CommandEncoder, slab: &Slab, words: &[u32], hooks: &mut dyn Hooks, counts: &mut Counts) -> Result<(), String> {+ let mut enc = enc;+ let mut r = Reader::new(words);+ while !r.done() {+ counts.commands += 1;+ match r.u()? {+ op::BEGIN_RENDER_PASS => render_pass(&mut enc, slab, &mut r, hooks, counts)?,+ op::BEGIN_COMPUTE_PASS => compute_pass(&mut enc, slab, &mut r, counts)?,+ op::COPY_B2B => {+ let src = slab.buffer(r.u()?)?;+ let so = r.u()? as u64;+ let dst = slab.buffer(r.u()?)?;+ let d_o = r.u()? as u64;+ let size = r.u()? as u64;+ enc.copy_buffer_to_buffer(&src.buf, so, &dst.buf, d_o, size);+ }+ op::COPY_B2T => {+ let b = buf_info(slab, &mut r)?;+ let t = tex_info(slab, &mut r)?;+ enc.copy_buffer_to_texture(b, t, extent(&mut r)?);+ }+ op::COPY_T2B => {+ let t = tex_info(slab, &mut r)?;+ let b = buf_info(slab, &mut r)?;+ enc.copy_texture_to_buffer(t, b, extent(&mut r)?);+ }+ op::COPY_T2T => {+ let s = tex_info(slab, &mut r)?;+ let d = tex_info(slab, &mut r)?;+ enc.copy_texture_to_texture(s, d, extent(&mut r)?);+ }+ op::CLEAR_BUFFER => {+ let b = slab.buffer(r.u()?)?;+ let off = r.u()? as u64;+ let size = r.opt()?.map(|s| s as u64);+ enc.clear_buffer(&b.buf, off, size);+ }+ op::RESOLVE_QUERY_SET => {+ let q = slab.query_set(r.u()?)?;+ let first = r.u()?;+ let count = r.u()?;+ let b = slab.buffer(r.u()?)?;+ let off = r.u()? as u64;+ let end = first.checked_add(count).ok_or("query range overflows")?;+ enc.resolve_query_set(&q.set, first..end, &b.buf, off);+ }+ o => return Err(format!("unknown encoder command {o}")),+ }+ }+ Ok(())+}++fn depth_ops<V>(load: u32, store: u32, clear: V) -> Option<wgpu::Operations<V>> {+ if load == 0 && store == 0 {+ return None;+ }+ Some(wgpu::Operations {+ load: if load == 2 { wgpu::LoadOp::Clear(clear) } else { wgpu::LoadOp::Load },+ store: if store == 2 { wgpu::StoreOp::Discard } else { wgpu::StoreOp::Store },+ })+}++fn render_pass(enc: &mut wgpu::CommandEncoder, slab: &Slab, r: &mut Reader, hooks: &mut dyn Hooks, counts: &mut Counts) -> Result<(), String> {+ counts.passes += 1;+ let n = r.u()? as usize;+ if n > 8 {+ return Err(format!("{n} color attachments"));+ }+ let mut colors: Vec<Option<wgpu::RenderPassColorAttachment>> = Vec::with_capacity(n);+ for _ in 0..n {+ let view = r.u()?;+ let resolve = r.u()?;+ let load = r.u()?;+ let store = r.u()?;+ let c = [r.f()?, r.f()?, r.f()?, r.f()?];+ if view == 0 {+ colors.push(None);+ continue;+ }+ let v = slab.view(view)?;+ let resolve_target = if resolve == 0 {+ None+ } else {+ let rv = slab.view(resolve)?;+ hooks.canvas_use(rv.texture, false);+ Some(&rv.view)+ };+ let clear = wgpu::Color { r: c[0] as f64, g: c[1] as f64, b: c[2] as f64, a: c[3] as f64 };+ let mut load = if load == 1 { wgpu::LoadOp::Clear(clear) } else { wgpu::LoadOp::Load };+ if hooks.canvas_use(v.texture, matches!(load, wgpu::LoadOp::Load)) {+ load = wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT);+ }+ let store = if store == 1 { wgpu::StoreOp::Discard } else { wgpu::StoreOp::Store };+ colors.push(Some(wgpu::RenderPassColorAttachment { view: &v.view, resolve_target, ops: wgpu::Operations { load, store } }));+ }+ let depth_stencil_attachment = if r.u()? != 0 {+ let view = &slab.view(r.u()?)?.view;+ let (dl, ds, dc, _dro) = (r.u()?, r.u()?, r.f()?, r.u()?);+ let (sl, ss, sc, _sro) = (r.u()?, r.u()?, r.u()?, r.u()?);+ Some(wgpu::RenderPassDepthStencilAttachment { view, depth_ops: depth_ops(dl, ds, dc), stencil_ops: depth_ops(sl, ss, sc) })+ } else {+ None+ };+ let occ = r.u()?;+ let occlusion_query_set = if occ == 0 { None } else { Some(&slab.query_set(occ)?.set) };+ let timestamp_writes = timestamp_set(slab, r)?.map(|(query_set, b, e)| wgpu::RenderPassTimestampWrites {+ query_set,+ beginning_of_pass_write_index: b,+ end_of_pass_write_index: e,+ });+ let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { label: None, color_attachments: &colors, depth_stencil_attachment, timestamp_writes, occlusion_query_set });+ loop {+ counts.commands += 1;+ match r.u()? {+ op::END_PASS => return Ok(()),+ op::SET_PIPELINE => pass.set_pipeline(slab.render_pipeline(r.u()?)?),+ op::SET_BIND_GROUP => {+ let index = r.u()?;+ let id = r.u()?;+ let n = r.u()? as usize;+ let offsets = r.take(n)?;+ let bg = if id == 0 { None } else { Some(slab.bind_group(id)?) };+ pass.set_bind_group(index, bg, offsets);+ }+ op::SET_VERTEX_BUFFER => {+ let slot = r.u()?;+ let (id, off, size) = (r.u()?, r.u()?, r.u()?);+ if id != 0 && size != 0 {+ pass.set_vertex_buffer(slot, buffer_slice(slab, id, off, size)?);+ }+ }+ op::SET_INDEX_BUFFER => {+ let id = r.u()?;+ let f = if r.u()? == 1 { wgpu::IndexFormat::Uint32 } else { wgpu::IndexFormat::Uint16 };+ let (off, size) = (r.u()?, r.u()?);+ if size != 0 {+ pass.set_index_buffer(buffer_slice(slab, id, off, size)?, f);+ }+ }+ op::DRAW => {+ let (vc, ic, fv, fi) = (r.u()?, r.u()?, r.u()?, r.u()?);+ counts.draws += 1;+ pass.draw(fv..fv.saturating_add(vc), fi..fi.saturating_add(ic));+ }+ op::DRAW_INDEXED => {+ let (ic, inst, fi, base, finst) = (r.u()?, r.u()?, r.u()?, r.i()?, r.u()?);+ counts.draws += 1;+ pass.draw_indexed(fi..fi.saturating_add(ic), base, finst..finst.saturating_add(inst));+ }+ op::DRAW_INDIRECT => {+ let b = slab.buffer(r.u()?)?;+ counts.draws += 1;+ pass.draw_indirect(&b.buf, r.u()? as u64);+ }+ op::DRAW_INDEXED_INDIRECT => {+ let b = slab.buffer(r.u()?)?;+ counts.draws += 1;+ pass.draw_indexed_indirect(&b.buf, r.u()? as u64);+ }+ op::SET_VIEWPORT => {+ let v = [r.f()?, r.f()?, r.f()?, r.f()?, r.f()?, r.f()?];+ pass.set_viewport(v[0], v[1], v[2], v[3], v[4], v[5]);+ }+ op::SET_SCISSOR => {+ let (x, y, w, h) = (r.u()?, r.u()?, r.u()?, r.u()?);+ pass.set_scissor_rect(x, y, w, h);+ }+ op::SET_BLEND_CONSTANT => {+ let c = [r.f()?, r.f()?, r.f()?, r.f()?];+ pass.set_blend_constant(wgpu::Color { r: c[0] as f64, g: c[1] as f64, b: c[2] as f64, a: c[3] as f64 });+ }+ op::SET_STENCIL_REF => pass.set_stencil_reference(r.u()?),+ op::BEGIN_OCCLUSION => pass.begin_occlusion_query(r.u()?),+ op::END_OCCLUSION => pass.end_occlusion_query(),+ o => return Err(format!("command {o} is not valid in a render pass")),+ }+ }+}++fn compute_pass(enc: &mut wgpu::CommandEncoder, slab: &Slab, r: &mut Reader, counts: &mut Counts) -> Result<(), String> {+ counts.passes += 1;+ let timestamp_writes = timestamp_set(slab, r)?.map(|(query_set, b, e)| wgpu::ComputePassTimestampWrites {+ query_set,+ beginning_of_pass_write_index: b,+ end_of_pass_write_index: e,+ });+ let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: None, timestamp_writes });+ loop {+ counts.commands += 1;+ match r.u()? {+ op::END_PASS => return Ok(()),+ op::SET_PIPELINE => pass.set_pipeline(slab.compute_pipeline(r.u()?)?),+ op::SET_BIND_GROUP => {+ let index = r.u()?;+ let id = r.u()?;+ let n = r.u()? as usize;+ let offsets = r.take(n)?;+ let bg = if id == 0 { None } else { Some(slab.bind_group(id)?) };+ pass.set_bind_group(index, bg, offsets);+ }+ op::DISPATCH => {+ let (x, y, z) = (r.u()?, r.u()?, r.u()?);+ pass.dispatch_workgroups(x, y, z);+ }+ op::DISPATCH_INDIRECT => {+ let b = slab.buffer(r.u()?)?;+ pass.dispatch_workgroups_indirect(&b.buf, r.u()? as u64);+ }+ o => return Err(format!("command {o} is not valid in a compute pass")),+ }+ }+}++/// Walk a stream without executing it: the number of passes and draws, or the first structural+/// error. Used by tests and by debug builds to check the JS encoder.+pub fn validate(words: &[u32]) -> Result<Counts, String> {+ let mut c = Counts::default();+ let mut r = Reader::new(words);+ let mut in_pass: Option<bool> = None; // Some(true) render, Some(false) compute+ while !r.done() {+ let o = r.u()?;+ c.commands += 1;+ let n = match (in_pass, o) {+ (None, op::BEGIN_RENDER_PASS) => {+ let k = r.u()? as usize;+ r.take(k * 8)?;+ if r.u()? != 0 {+ r.take(9)?;+ }+ r.take(4)?;+ c.passes += 1;+ in_pass = Some(true);+ 0+ }+ (None, op::BEGIN_COMPUTE_PASS) => {+ c.passes += 1;+ in_pass = Some(false);+ 3+ }+ (None, op::COPY_B2B) => 5,+ (None, op::COPY_B2T | op::COPY_T2B) => 4 + 6 + 3,+ (None, op::COPY_T2T) => 6 + 6 + 3,+ (None, op::CLEAR_BUFFER) => 3,+ (None, op::RESOLVE_QUERY_SET) => 5,+ (Some(_), op::END_PASS) => {+ in_pass = None;+ 0+ }+ (Some(_), op::SET_PIPELINE) => 1,+ (Some(_), op::SET_BIND_GROUP) => {+ r.take(2)?;+ r.u()? as usize+ }+ (Some(true), op::SET_VERTEX_BUFFER) => 4,+ (Some(true), op::SET_INDEX_BUFFER) => 4,+ (Some(true), op::DRAW) => {+ c.draws += 1;+ 4+ }+ (Some(true), op::DRAW_INDEXED) => {+ c.draws += 1;+ 5+ }+ (Some(true), op::DRAW_INDIRECT | op::DRAW_INDEXED_INDIRECT) => {+ c.draws += 1;+ 2+ }+ (Some(true), op::SET_VIEWPORT) => 6,+ (Some(true), op::SET_SCISSOR | op::SET_BLEND_CONSTANT) => 4,+ (Some(true), op::SET_STENCIL_REF | op::BEGIN_OCCLUSION) => 1,+ (Some(true), op::END_OCCLUSION) => 0,+ (Some(false), op::DISPATCH) => 3,+ (Some(false), op::DISPATCH_INDIRECT) => 2,+ (p, o) => return Err(format!("command {o} is not valid {}", if p.is_some() { "in a pass" } else { "outside a pass" })),+ };+ r.take(n)?;+ }+ if in_pass.is_some() {+ return Err("pass not ended".into());+ }+ Ok(c)+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A frame the way the JS encoder writes it: a cleared MSAA pass with depth, two draws, a copy.+ fn sample() -> Vec<u32> {+ let mut w = Writer::default();+ w.u(op::BEGIN_RENDER_PASS).u(1);+ w.u(7).u(8).u(1).u(1).f(0.25).f(0.5).f(0.75).f(1.0); // view, resolve, clear, discard+ w.u(1).u(9).u(2).u(1).f(1.0).u(0).u(0).u(0).u(0).u(0); // depth: clear 1.0 / store, no stencil+ w.u(0).u(0).u(NONE).u(NONE); // no occlusion / timestamps+ w.u(op::SET_VIEWPORT).f(0.0).f(0.0).f(800.0).f(600.0).f(0.0).f(1.0);+ w.u(op::SET_PIPELINE).u(3);+ w.u(op::SET_BIND_GROUP).u(0).u(4).u(2).u(256).u(512);+ w.u(op::SET_VERTEX_BUFFER).u(0).u(5).u(0).u(NONE);+ w.u(op::SET_INDEX_BUFFER).u(6).u(1).u(0).u(NONE);+ w.u(op::DRAW_INDEXED).u(36).u(1).u(0).u((-4i32) as u32).u(0);+ w.u(op::SET_STENCIL_REF).u(1);+ w.u(op::DRAW).u(3).u(1).u(0).u(0);+ w.u(op::END_PASS);+ w.u(op::COPY_B2B).u(5).u(0).u(10).u(0).u(64);+ w.u(op::BEGIN_COMPUTE_PASS).u(0).u(NONE).u(NONE);+ w.u(op::SET_PIPELINE).u(11).u(op::DISPATCH).u(8).u(8).u(1).u(op::END_PASS);+ w.w+ }++ #[test]+ fn stream_structure() {+ let c = validate(&sample()).unwrap();+ assert_eq!((c.passes, c.draws), (2, 2));+ }++ #[test]+ fn reader_decodes_values() {+ let s = sample();+ let mut r = Reader::new(&s);+ assert_eq!(r.u().unwrap(), op::BEGIN_RENDER_PASS);+ assert_eq!(r.u().unwrap(), 1);+ assert_eq!(r.take(4).unwrap(), &[7, 8, 1, 1]);+ assert_eq!([r.f().unwrap(), r.f().unwrap(), r.f().unwrap(), r.f().unwrap()], [0.25, 0.5, 0.75, 1.0]);+ let mut r = Reader::new(&[5, NONE, (-4i32) as u32]);+ assert_eq!(r.opt().unwrap(), Some(5));+ assert_eq!(r.opt().unwrap(), None);+ assert_eq!(r.i().unwrap(), -4);+ assert!(r.u().is_err(), "reads past the end fail instead of panicking");+ assert!(Reader::new(&[1, 2]).take(3).is_err());+ }++ #[test]+ fn malformed_streams_are_rejected() {+ let s = sample();+ for cut in 1..s.len() {+ // every truncation either is a valid prefix (ends between commands) or errors+ let r = validate(&s[..cut]);+ if let Ok(c) = r {+ assert!(c.passes <= 2);+ }+ }+ assert!(validate(&[op::DRAW, 3, 1, 0, 0]).unwrap_err().contains("outside a pass"));+ assert!(validate(&[op::BEGIN_COMPUTE_PASS, 0, NONE, NONE, op::DRAW, 3, 1, 0, 0]).is_err());+ assert!(validate(&[op::BEGIN_COMPUTE_PASS, 0, NONE, NONE]).unwrap_err().contains("not ended"));+ assert!(validate(&[99]).is_err());+ assert!(validate(&[op::BEGIN_RENDER_PASS, u32::MAX]).is_err(), "absurd attachment counts fail cleanly");+ }+}diff --git a/webgpu/src/desc.rs b/webgpu/src/desc.rsnew file mode 100644index 0000000..4271416--- /dev/null+++ b/webgpu/src/desc.rs@@ -0,0 +1,729 @@+//! Descriptor parsing: the JSON the JS layer sends for creation calls (WebGPU dictionaries with+//! every GPU object replaced by its integer id) → owned specs → wgpu objects.+//!+//! Parse errors are WebIDL-level (`TypeError` in the page: missing required members, unknown+//! enum strings); everything else is left to wgpu's validation, which reports GPU errors.+use serde_json::Value as J;+use wgpu::TextureFormat;++use crate::fmt;+use crate::res::{Res, Slab, ViewRes};++pub type R<T> = Result<T, String>;++// ------------------------------------------------------------------------------------- helpers++/// A member, treating `null` like a missing one.+fn get<'a>(j: &'a J, k: &str) -> Option<&'a J> {+ j.get(k).filter(|v| !v.is_null())+}++fn num(j: &J, k: &str, default: f64) -> R<f64> {+ match get(j, k) {+ None => Ok(default),+ Some(J::Number(n)) => Ok(n.as_f64().unwrap_or(default)),+ Some(J::Bool(b)) => Ok(*b as u8 as f64),+ Some(v) => Err(format!("'{k}' must be a number, got {v}")),+ }+}++/// WebIDL `[EnforceRange] unsigned long`-ish: finite, truncated, clamped into u32.+fn u32_of(j: &J, k: &str, default: u32) -> R<u32> {+ let d = num(j, k, default as f64)?;+ if !d.is_finite() || d < 0.0 || d > u32::MAX as f64 {+ return Err(format!("'{k}' is out of range: {d}"));+ }+ Ok(d as u32)+}++fn u64_of(j: &J, k: &str, default: u64) -> R<u64> {+ let d = num(j, k, default as f64)?;+ if !d.is_finite() || d < 0.0 || d > 9007199254740991.0 {+ return Err(format!("'{k}' is out of range: {d}"));+ }+ Ok(d as u64)+}++fn req_u32(j: &J, k: &str) -> R<u32> {+ if get(j, k).is_none() {+ return Err(format!("required member '{k}' is missing"));+ }+ u32_of(j, k, 0)+}++fn boolean(j: &J, k: &str, default: bool) -> bool {+ match get(j, k) {+ None => default,+ Some(J::Bool(b)) => *b,+ Some(J::Number(n)) => n.as_f64().is_some_and(|x| x != 0.0),+ Some(J::String(s)) => !s.is_empty(),+ Some(_) => true,+ }+}++fn string<'a>(j: &'a J, k: &str) -> Option<&'a str> {+ get(j, k).and_then(|v| v.as_str())+}++fn enum_of<T>(j: &J, k: &str, default: T, parse: impl Fn(&str) -> Option<T>) -> R<T> {+ match get(j, k) {+ None => Ok(default),+ Some(J::String(s)) => parse(s).ok_or_else(|| format!("'{s}' is not a valid value for '{k}'")),+ Some(v) => Err(format!("'{k}' must be a string, got {v}")),+ }+}++fn req_enum<T>(j: &J, k: &str, parse: impl Fn(&str) -> Option<T>) -> R<T> {+ match get(j, k) {+ None => Err(format!("required member '{k}' is missing")),+ Some(J::String(s)) => parse(s).ok_or_else(|| format!("'{s}' is not a valid value for '{k}'")),+ Some(v) => Err(format!("'{k}' must be a string, got {v}")),+ }+}++fn label(j: &J) -> Option<String> {+ string(j, "label").filter(|s| !s.is_empty()).map(str::to_owned)+}++fn array<'a>(j: &'a J, k: &str) -> &'a [J] {+ get(j, k).and_then(|v| v.as_array()).map(|v| v.as_slice()).unwrap_or(&[])+}++/// GPUExtent3D: `[w, h?, d?]` or `{width, height?, depthOrArrayLayers?}`.+pub fn extent(j: &J) -> R<wgpu::Extent3d> {+ if let Some(a) = j.as_array() {+ let at = |i: usize, d: u32| -> R<u32> {+ match a.get(i) {+ None | Some(J::Null) => Ok(d),+ Some(v) => v.as_f64().filter(|x| x.is_finite() && *x >= 0.0 && *x <= u32::MAX as f64).map(|x| x as u32).ok_or_else(|| format!("bad extent component {v}")),+ }+ };+ if a.is_empty() || a.len() > 3 {+ return Err("GPUExtent3D sequence must have 1 to 3 elements".into());+ }+ return Ok(wgpu::Extent3d { width: at(0, 1)?, height: at(1, 1)?, depth_or_array_layers: at(2, 1)? });+ }+ if j.is_object() {+ return Ok(wgpu::Extent3d { width: req_u32(j, "width")?, height: u32_of(j, "height", 1)?, depth_or_array_layers: u32_of(j, "depthOrArrayLayers", 1)? });+ }+ Err("GPUExtent3D must be a sequence or a dictionary".into())+}++/// GPUOrigin3D: `[x?, y?, z?]` or `{x?, y?, z?}`.+pub fn origin(j: Option<&J>) -> R<wgpu::Origin3d> {+ let Some(j) = j.filter(|v| !v.is_null()) else { return Ok(wgpu::Origin3d::ZERO) };+ if let Some(a) = j.as_array() {+ let at = |i: usize| a.get(i).and_then(|v| v.as_f64()).unwrap_or(0.0).max(0.0) as u32;+ return Ok(wgpu::Origin3d { x: at(0), y: at(1), z: at(2) });+ }+ Ok(wgpu::Origin3d { x: u32_of(j, "x", 0)?, y: u32_of(j, "y", 0)?, z: u32_of(j, "z", 0)? })+}++// ------------------------------------------------------------------------------------- textures++#[derive(Debug, Clone, PartialEq)]+pub struct TextureSpec {+ pub label: Option<String>,+ pub size: wgpu::Extent3d,+ pub mips: u32,+ pub samples: u32,+ pub dimension: wgpu::TextureDimension,+ pub format: TextureFormat,+ pub usage: wgpu::TextureUsages,+ pub view_formats: Vec<TextureFormat>,+}++pub fn texture(j: &J) -> R<TextureSpec> {+ let size = extent(get(j, "size").ok_or("required member 'size' is missing")?)?;+ let usage = req_u32(j, "usage")?;+ let mut view_formats = Vec::new();+ for v in array(j, "viewFormats") {+ let s = v.as_str().ok_or("viewFormats must be strings")?;+ view_formats.push(fmt::texture_format(s).ok_or_else(|| format!("'{s}' is not a valid GPUTextureFormat"))?);+ }+ Ok(TextureSpec {+ label: label(j),+ size,+ mips: u32_of(j, "mipLevelCount", 1)?,+ samples: u32_of(j, "sampleCount", 1)?,+ dimension: enum_of(j, "dimension", wgpu::TextureDimension::D2, fmt::texture_dimension)?,+ format: req_enum(j, "format", fmt::texture_format)?,+ usage: texture_usage(usage),+ view_formats,+ })+}++/// WebGPU GPUTextureUsage bits are wgpu's for the five core usages; unknown bits are kept so+/// wgpu reports them.+pub fn texture_usage(bits: u32) -> wgpu::TextureUsages {+ wgpu::TextureUsages::from_bits_retain(bits)+}++impl TextureSpec {+ pub fn desc(&self) -> wgpu::TextureDescriptor<'_> {+ wgpu::TextureDescriptor {+ label: self.label.as_deref(),+ size: self.size,+ mip_level_count: self.mips,+ sample_count: self.samples,+ dimension: self.dimension,+ format: self.format,+ usage: self.usage,+ view_formats: &self.view_formats,+ }+ }+}++#[derive(Debug, Clone, PartialEq, Default)]+pub struct ViewSpec {+ pub label: Option<String>,+ pub format: Option<TextureFormat>,+ pub dimension: Option<wgpu::TextureViewDimension>,+ pub usage: Option<wgpu::TextureUsages>,+ pub aspect: wgpu::TextureAspect,+ pub base_mip: u32,+ pub mip_count: Option<u32>,+ pub base_layer: u32,+ pub layer_count: Option<u32>,+}++pub fn view(j: &J) -> R<ViewSpec> {+ if j.is_null() {+ return Ok(ViewSpec::default());+ }+ let opt_u32 = |k: &str| -> R<Option<u32>> { if get(j, k).is_some() { Ok(Some(u32_of(j, k, 0)?)) } else { Ok(None) } };+ let usage = opt_u32("usage")?.filter(|u| *u != 0).map(texture_usage);+ Ok(ViewSpec {+ label: label(j),+ format: if get(j, "format").is_some() { Some(req_enum(j, "format", fmt::texture_format)?) } else { None },+ dimension: if get(j, "dimension").is_some() { Some(req_enum(j, "dimension", fmt::view_dimension)?) } else { None },+ usage,+ aspect: enum_of(j, "aspect", wgpu::TextureAspect::All, fmt::aspect)?,+ base_mip: u32_of(j, "baseMipLevel", 0)?,+ mip_count: opt_u32("mipLevelCount")?,+ base_layer: u32_of(j, "baseArrayLayer", 0)?,+ layer_count: opt_u32("arrayLayerCount")?,+ })+}++impl ViewSpec {+ pub fn desc(&self) -> wgpu::TextureViewDescriptor<'_> {+ wgpu::TextureViewDescriptor {+ label: self.label.as_deref(),+ format: self.format,+ dimension: self.dimension,+ usage: self.usage,+ aspect: self.aspect,+ base_mip_level: self.base_mip,+ mip_level_count: self.mip_count,+ base_array_layer: self.base_layer,+ array_layer_count: self.layer_count,+ }+ }+}++pub fn sampler(j: &J) -> R<wgpu::SamplerDescriptor<'static>> {+ let am = |k: &str| enum_of(j, k, wgpu::AddressMode::ClampToEdge, fmt::address_mode);+ let f = |k: &str| enum_of(j, k, wgpu::FilterMode::Nearest, fmt::filter);+ let aniso = u32_of(j, "maxAnisotropy", 1)?.clamp(1, u16::MAX as u32) as u16;+ Ok(wgpu::SamplerDescriptor {+ label: None,+ address_mode_u: am("addressModeU")?,+ address_mode_v: am("addressModeV")?,+ address_mode_w: am("addressModeW")?,+ mag_filter: f("magFilter")?,+ min_filter: f("minFilter")?,+ mipmap_filter: f("mipmapFilter")?,+ lod_min_clamp: num(j, "lodMinClamp", 0.0)? as f32,+ lod_max_clamp: num(j, "lodMaxClamp", 32.0)? as f32,+ compare: if get(j, "compare").is_some() { Some(req_enum(j, "compare", fmt::compare)?) } else { None },+ anisotropy_clamp: aniso,+ border_color: None,+ })+}++// ------------------------------------------------------------------------------------- bindings++pub fn bind_group_layout(j: &J) -> R<Vec<wgpu::BindGroupLayoutEntry>> {+ let mut out = Vec::new();+ for e in array(j, "entries") {+ let binding = req_u32(e, "binding")?;+ let visibility = wgpu::ShaderStages::from_bits_truncate(req_u32(e, "visibility")?);+ let ty = if let Some(b) = get(e, "buffer") {+ let ty = match string(b, "type").unwrap_or("uniform") {+ "uniform" => wgpu::BufferBindingType::Uniform,+ "storage" => wgpu::BufferBindingType::Storage { read_only: false },+ "read-only-storage" => wgpu::BufferBindingType::Storage { read_only: true },+ s => return Err(format!("'{s}' is not a valid GPUBufferBindingType")),+ };+ wgpu::BindingType::Buffer { ty, has_dynamic_offset: boolean(b, "hasDynamicOffset", false), min_binding_size: wgpu::BufferSize::new(u64_of(b, "minBindingSize", 0)?) }+ } else if let Some(s) = get(e, "sampler") {+ wgpu::BindingType::Sampler(match string(s, "type").unwrap_or("filtering") {+ "filtering" => wgpu::SamplerBindingType::Filtering,+ "non-filtering" => wgpu::SamplerBindingType::NonFiltering,+ "comparison" => wgpu::SamplerBindingType::Comparison,+ s => return Err(format!("'{s}' is not a valid GPUSamplerBindingType")),+ })+ } else if let Some(t) = get(e, "texture") {+ let sample_type = match string(t, "sampleType").unwrap_or("float") {+ "float" => wgpu::TextureSampleType::Float { filterable: true },+ "unfilterable-float" => wgpu::TextureSampleType::Float { filterable: false },+ "depth" => wgpu::TextureSampleType::Depth,+ "sint" => wgpu::TextureSampleType::Sint,+ "uint" => wgpu::TextureSampleType::Uint,+ s => return Err(format!("'{s}' is not a valid GPUTextureSampleType")),+ };+ wgpu::BindingType::Texture {+ sample_type,+ view_dimension: enum_of(t, "viewDimension", wgpu::TextureViewDimension::D2, fmt::view_dimension)?,+ multisampled: boolean(t, "multisampled", false),+ }+ } else if let Some(t) = get(e, "storageTexture") {+ let access = match string(t, "access").unwrap_or("write-only") {+ "write-only" => wgpu::StorageTextureAccess::WriteOnly,+ "read-only" => wgpu::StorageTextureAccess::ReadOnly,+ "read-write" => wgpu::StorageTextureAccess::ReadWrite,+ s => return Err(format!("'{s}' is not a valid GPUStorageTextureAccess")),+ };+ wgpu::BindingType::StorageTexture {+ access,+ format: req_enum(t, "format", fmt::texture_format)?,+ view_dimension: enum_of(t, "viewDimension", wgpu::TextureViewDimension::D2, fmt::view_dimension)?,+ }+ } else if get(e, "externalTexture").is_some() {+ return Err("externalTexture bindings are not supported".into());+ } else {+ // WebGPU: an entry with no binding member is a validation error, but the buffer+ // default is what pages that rely on `{}` dictionaries expect.+ wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }+ };+ out.push(wgpu::BindGroupLayoutEntry { binding, visibility, ty, count: None });+ }+ Ok(out)+}++/// `bindGroupLayouts`: ids, `None` for null entries (filled with an empty layout).+pub fn pipeline_layout(j: &J) -> R<Vec<Option<u32>>> {+ array(j, "bindGroupLayouts")+ .iter()+ .map(|v| match v {+ J::Null => Ok(None),+ J::Number(n) => Ok(Some(n.as_u64().unwrap_or(0) as u32)),+ v => Err(format!("bindGroupLayouts entries must be GPUBindGroupLayout, got {v}")),+ })+ .collect()+}++#[derive(Debug, Clone, PartialEq)]+pub enum BgResource {+ /// GPUBufferBinding+ Buffer { id: u32, offset: u64, size: Option<u64> },+ /// a GPUSampler, GPUTextureView, GPUTexture or GPUBuffer by id+ Object(u32),+}++#[derive(Debug, Clone, PartialEq)]+pub struct BindGroupSpec {+ pub label: Option<String>,+ pub layout: u32,+ pub entries: Vec<(u32, BgResource)>,+}++pub fn bind_group(j: &J) -> R<BindGroupSpec> {+ let layout = req_u32(j, "layout")?;+ let mut entries = Vec::new();+ for e in array(j, "entries") {+ let binding = req_u32(e, "binding")?;+ let r = get(e, "resource").ok_or("required member 'resource' is missing")?;+ let res = match r {+ J::Number(n) => BgResource::Object(n.as_u64().unwrap_or(0) as u32),+ J::Object(_) => BgResource::Buffer {+ id: req_u32(r, "buffer")?,+ offset: u64_of(r, "offset", 0)?,+ size: if get(r, "size").is_some() { Some(u64_of(r, "size", 0)?) } else { None },+ },+ v => return Err(format!("invalid binding resource {v}")),+ };+ entries.push((binding, res));+ }+ Ok(BindGroupSpec { label: label(j), layout, entries })+}++impl BindGroupSpec {+ /// Resolve ids. Bare textures are bound through a default view (kept in `scratch_views`).+ pub fn create(&self, dev: &wgpu::Device, slab: &Slab) -> R<wgpu::BindGroup> {+ let layout = slab.bind_group_layout(self.layout)?;+ let mut views = Vec::new();+ for (_, r) in &self.entries {+ if let BgResource::Object(id) = r {+ if let Some(Res::Texture(t)) = slab.get(*id) {+ views.push((*id, t.tex.create_view(&Default::default())));+ }+ }+ }+ let mut entries = Vec::with_capacity(self.entries.len());+ for (binding, r) in &self.entries {+ let resource = match r {+ BgResource::Buffer { id, offset, size } => {+ let b = slab.buffer(*id)?;+ wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: &b.buf, offset: *offset, size: size.and_then(wgpu::BufferSize::new) })+ }+ BgResource::Object(id) => match slab.get(*id) {+ Some(Res::Sampler(s)) => wgpu::BindingResource::Sampler(s),+ Some(Res::View(ViewRes { view, .. })) => wgpu::BindingResource::TextureView(view),+ Some(Res::Texture(_)) => wgpu::BindingResource::TextureView(&views.iter().find(|(i, _)| i == id).unwrap().1),+ Some(Res::Buffer(b)) => wgpu::BindingResource::Buffer(b.buf.as_entire_buffer_binding()),+ Some(other) => return Err(format!("binding {binding}: a {} cannot be bound", other.kind())),+ None => return Err(format!("binding {binding}: invalid or destroyed object id {id}")),+ },+ };+ entries.push(wgpu::BindGroupEntry { binding: *binding, resource });+ }+ Ok(dev.create_bind_group(&wgpu::BindGroupDescriptor { label: self.label.as_deref(), layout, entries: &entries }))+ }+}++// ------------------------------------------------------------------------------------- pipelines++#[derive(Debug, Clone, PartialEq)]+pub struct StageSpec {+ pub module: u32,+ pub entry: Option<String>,+ pub constants: Vec<(String, f64)>,+}++fn stage(j: &J) -> R<StageSpec> {+ let mut constants = Vec::new();+ if let Some(c) = get(j, "constants").and_then(|c| c.as_object()) {+ for (k, v) in c {+ constants.push((k.clone(), v.as_f64().ok_or_else(|| format!("constant '{k}' must be a number"))?));+ }+ }+ Ok(StageSpec { module: req_u32(j, "module")?, entry: string(j, "entryPoint").map(str::to_owned), constants })+}++/// `"auto"` → `None`.+fn layout_ref(j: &J) -> R<Option<u32>> {+ match get(j, "layout") {+ Some(J::String(s)) if s == "auto" => Ok(None),+ Some(J::Number(n)) => Ok(Some(n.as_u64().unwrap_or(0) as u32)),+ None => Err("required member 'layout' is missing".into()),+ Some(v) => Err(format!("invalid pipeline layout {v}")),+ }+}++#[derive(Debug, Clone, PartialEq)]+pub struct VertexBufferSpec {+ pub stride: u64,+ pub step: wgpu::VertexStepMode,+ pub attributes: Vec<wgpu::VertexAttribute>,+}++#[derive(Debug, Clone, PartialEq)]+pub struct RenderPipelineSpec {+ pub label: Option<String>,+ pub layout: Option<u32>,+ pub vertex: StageSpec,+ pub buffers: Vec<VertexBufferSpec>,+ pub primitive: wgpu::PrimitiveState,+ pub depth_stencil: Option<wgpu::DepthStencilState>,+ pub multisample: wgpu::MultisampleState,+ pub fragment: Option<(StageSpec, Vec<Option<wgpu::ColorTargetState>>)>,+}++fn stencil_face(j: Option<&J>) -> R<wgpu::StencilFaceState> {+ let Some(j) = j else { return Ok(wgpu::StencilFaceState::IGNORE) };+ let op = |k: &str| enum_of(j, k, wgpu::StencilOperation::Keep, fmt::stencil_op);+ Ok(wgpu::StencilFaceState {+ compare: enum_of(j, "compare", wgpu::CompareFunction::Always, fmt::compare)?,+ fail_op: op("failOp")?,+ depth_fail_op: op("depthFailOp")?,+ pass_op: op("passOp")?,+ })+}++fn blend_component(j: Option<&J>) -> R<wgpu::BlendComponent> {+ let Some(j) = j else { return Ok(wgpu::BlendComponent::REPLACE) };+ Ok(wgpu::BlendComponent {+ src_factor: enum_of(j, "srcFactor", wgpu::BlendFactor::One, fmt::blend_factor)?,+ dst_factor: enum_of(j, "dstFactor", wgpu::BlendFactor::Zero, fmt::blend_factor)?,+ operation: enum_of(j, "operation", wgpu::BlendOperation::Add, fmt::blend_op)?,+ })+}++pub fn render_pipeline(j: &J) -> R<RenderPipelineSpec> {+ let vj = get(j, "vertex").ok_or("required member 'vertex' is missing")?;+ let mut buffers = Vec::new();+ for b in array(vj, "buffers") {+ if b.is_null() {+ buffers.push(VertexBufferSpec { stride: 0, step: wgpu::VertexStepMode::Vertex, attributes: Vec::new() });+ continue;+ }+ let mut attributes = Vec::new();+ for a in array(b, "attributes") {+ attributes.push(wgpu::VertexAttribute {+ format: req_enum(a, "format", fmt::vertex_format)?,+ offset: u64_of(a, "offset", 0)?,+ shader_location: req_u32(a, "shaderLocation")?,+ });+ }+ let step = match string(b, "stepMode").unwrap_or("vertex") {+ "vertex" => wgpu::VertexStepMode::Vertex,+ "instance" => wgpu::VertexStepMode::Instance,+ s => return Err(format!("'{s}' is not a valid GPUVertexStepMode")),+ };+ buffers.push(VertexBufferSpec { stride: u64_of(b, "arrayStride", 0)?, step, attributes });+ }+ let p = get(j, "primitive").cloned().unwrap_or(J::Null);+ let primitive = wgpu::PrimitiveState {+ topology: enum_of(&p, "topology", wgpu::PrimitiveTopology::TriangleList, fmt::topology)?,+ strip_index_format: if get(&p, "stripIndexFormat").is_some() { Some(req_enum(&p, "stripIndexFormat", fmt::index_format)?) } else { None },+ front_face: match string(&p, "frontFace").unwrap_or("ccw") {+ "ccw" => wgpu::FrontFace::Ccw,+ "cw" => wgpu::FrontFace::Cw,+ s => return Err(format!("'{s}' is not a valid GPUFrontFace")),+ },+ cull_mode: match string(&p, "cullMode").unwrap_or("none") {+ "none" => None,+ "front" => Some(wgpu::Face::Front),+ "back" => Some(wgpu::Face::Back),+ s => return Err(format!("'{s}' is not a valid GPUCullMode")),+ },+ unclipped_depth: boolean(&p, "unclippedDepth", false),+ polygon_mode: wgpu::PolygonMode::Fill,+ conservative: false,+ };+ let depth_stencil = match get(j, "depthStencil") {+ None => None,+ Some(d) => Some(wgpu::DepthStencilState {+ format: req_enum(d, "format", fmt::texture_format)?,+ depth_write_enabled: boolean(d, "depthWriteEnabled", false),+ depth_compare: enum_of(d, "depthCompare", wgpu::CompareFunction::Always, fmt::compare)?,+ stencil: wgpu::StencilState {+ front: stencil_face(get(d, "stencilFront"))?,+ back: stencil_face(get(d, "stencilBack"))?,+ read_mask: u32_of(d, "stencilReadMask", 0xFFFF_FFFF)?,+ write_mask: u32_of(d, "stencilWriteMask", 0xFFFF_FFFF)?,+ },+ bias: wgpu::DepthBiasState {+ constant: num(d, "depthBias", 0.0)? as i32,+ slope_scale: num(d, "depthBiasSlopeScale", 0.0)? as f32,+ clamp: num(d, "depthBiasClamp", 0.0)? as f32,+ },+ }),+ };+ let m = get(j, "multisample").cloned().unwrap_or(J::Null);+ let multisample = wgpu::MultisampleState {+ count: u32_of(&m, "count", 1)?,+ mask: u32_of(&m, "mask", 0xFFFF_FFFF)? as u64,+ alpha_to_coverage_enabled: boolean(&m, "alphaToCoverageEnabled", false),+ };+ let fragment = match get(j, "fragment") {+ None => None,+ Some(f) => {+ let mut targets = Vec::new();+ for t in array(f, "targets") {+ if t.is_null() {+ targets.push(None);+ continue;+ }+ let blend = match get(t, "blend") {+ None => None,+ Some(b) => Some(wgpu::BlendState { color: blend_component(get(b, "color"))?, alpha: blend_component(get(b, "alpha"))? }),+ };+ targets.push(Some(wgpu::ColorTargetState {+ format: req_enum(t, "format", fmt::texture_format)?,+ blend,+ write_mask: wgpu::ColorWrites::from_bits_truncate(u32_of(t, "writeMask", 0xF)?),+ }));+ }+ Some((stage(f)?, targets))+ }+ };+ Ok(RenderPipelineSpec { label: label(j), layout: layout_ref(j)?, vertex: stage(vj)?, buffers, primitive, depth_stencil, multisample, fragment })+}++fn constants(s: &StageSpec) -> Vec<(&str, f64)> {+ s.constants.iter().map(|(k, v)| (k.as_str(), *v)).collect()+}++fn options<'a>(c: &'a [(&'a str, f64)]) -> wgpu::PipelineCompilationOptions<'a> {+ wgpu::PipelineCompilationOptions { constants: c, zero_initialize_workgroup_memory: true }+}++impl RenderPipelineSpec {+ pub fn create(&self, dev: &wgpu::Device, slab: &Slab) -> R<wgpu::RenderPipeline> {+ let layout = match self.layout {+ Some(id) => Some(slab.pipeline_layout(id)?),+ None => None,+ };+ let vmod = &slab.shader(self.vertex.module)?.module;+ let vconst = constants(&self.vertex);+ let buffers: Vec<wgpu::VertexBufferLayout> =+ self.buffers.iter().map(|b| wgpu::VertexBufferLayout { array_stride: b.stride, step_mode: b.step, attributes: &b.attributes }).collect();+ let fconst = self.fragment.as_ref().map(|(s, _)| constants(s)).unwrap_or_default();+ let fragment = match &self.fragment {+ None => None,+ Some((s, targets)) => Some(wgpu::FragmentState {+ module: &slab.shader(s.module)?.module,+ entry_point: s.entry.as_deref(),+ compilation_options: options(&fconst),+ targets,+ }),+ };+ Ok(dev.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: self.label.as_deref(),+ layout,+ vertex: wgpu::VertexState { module: vmod, entry_point: self.vertex.entry.as_deref(), compilation_options: options(&vconst), buffers: &buffers },+ primitive: self.primitive,+ depth_stencil: self.depth_stencil.clone(),+ multisample: self.multisample,+ fragment,+ multiview: None,+ cache: None,+ }))+ }+}++#[derive(Debug, Clone, PartialEq)]+pub struct ComputePipelineSpec {+ pub label: Option<String>,+ pub layout: Option<u32>,+ pub stage: StageSpec,+}++pub fn compute_pipeline(j: &J) -> R<ComputePipelineSpec> {+ let c = get(j, "compute").ok_or("required member 'compute' is missing")?;+ Ok(ComputePipelineSpec { label: label(j), layout: layout_ref(j)?, stage: stage(c)? })+}++impl ComputePipelineSpec {+ pub fn create(&self, dev: &wgpu::Device, slab: &Slab) -> R<wgpu::ComputePipeline> {+ let layout = match self.layout {+ Some(id) => Some(slab.pipeline_layout(id)?),+ None => None,+ };+ let c = constants(&self.stage);+ Ok(dev.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {+ label: self.label.as_deref(),+ layout,+ module: &slab.shader(self.stage.module)?.module,+ entry_point: self.stage.entry.as_deref(),+ compilation_options: options(&c),+ cache: None,+ }))+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn texture_descriptor() {+ let t = texture(&json!({"size": [256, 128], "format": "rgba8unorm-srgb", "usage": 0x16, "mipLevelCount": 9, "label": "albedo"})).unwrap();+ assert_eq!(t.size, wgpu::Extent3d { width: 256, height: 128, depth_or_array_layers: 1 });+ assert_eq!(t.format, TextureFormat::Rgba8UnormSrgb);+ assert_eq!(t.mips, 9);+ assert_eq!(t.samples, 1);+ assert_eq!(t.dimension, wgpu::TextureDimension::D2);+ assert_eq!(t.usage, wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::RENDER_ATTACHMENT);+ assert_eq!(t.label.as_deref(), Some("albedo"));+ let t = texture(&json!({"size": {"width": 4, "depthOrArrayLayers": 6}, "format": "depth24plus", "usage": 16, "dimension": "2d", "viewFormats": []})).unwrap();+ assert_eq!(t.size, wgpu::Extent3d { width: 4, height: 1, depth_or_array_layers: 6 });+ assert!(texture(&json!({"size": [4, 4], "format": "rgba9unorm", "usage": 1})).unwrap_err().contains("rgba9unorm"));+ assert!(texture(&json!({"format": "rgba8unorm", "usage": 1})).unwrap_err().contains("size"));+ assert!(texture(&json!({"size": [], "format": "rgba8unorm", "usage": 1})).is_err());+ }++ #[test]+ fn view_and_sampler() {+ let v = view(&json!({"dimension": "cube", "aspect": "depth-only", "baseMipLevel": 2, "mipLevelCount": 1})).unwrap();+ assert_eq!(v.dimension, Some(wgpu::TextureViewDimension::Cube));+ assert_eq!(v.aspect, wgpu::TextureAspect::DepthOnly);+ assert_eq!((v.base_mip, v.mip_count, v.layer_count), (2, Some(1), None));+ assert_eq!(view(&J::Null).unwrap(), ViewSpec::default());+ let s = sampler(&json!({"magFilter": "linear", "addressModeU": "repeat", "compare": "less-equal", "maxAnisotropy": 4})).unwrap();+ assert_eq!(s.mag_filter, wgpu::FilterMode::Linear);+ assert_eq!(s.min_filter, wgpu::FilterMode::Nearest);+ assert_eq!(s.address_mode_u, wgpu::AddressMode::Repeat);+ assert_eq!(s.address_mode_v, wgpu::AddressMode::ClampToEdge);+ assert_eq!(s.compare, Some(wgpu::CompareFunction::LessEqual));+ assert_eq!((s.anisotropy_clamp, s.lod_max_clamp), (4, 32.0));+ assert!(sampler(&json!({"magFilter": "cubic"})).is_err());+ }++ #[test]+ fn layouts_and_groups() {+ let e = bind_group_layout(&json!({"entries": [+ {"binding": 0, "visibility": 3, "buffer": {"type": "uniform", "hasDynamicOffset": true}},+ {"binding": 1, "visibility": 2, "sampler": {"type": "comparison"}},+ {"binding": 2, "visibility": 2, "texture": {"sampleType": "depth", "viewDimension": "2d-array"}},+ {"binding": 3, "visibility": 4, "storageTexture": {"format": "rgba16float", "access": "read-write"}},+ {"binding": 4, "visibility": 2, "texture": {}},+ ]}))+ .unwrap();+ assert_eq!(e.len(), 5);+ assert_eq!(e[0].visibility, wgpu::ShaderStages::VERTEX_FRAGMENT);+ assert!(matches!(e[0].ty, wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: true, min_binding_size: None }));+ assert!(matches!(e[1].ty, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison)));+ assert!(matches!(e[2].ty, wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Depth, view_dimension: wgpu::TextureViewDimension::D2Array, multisampled: false }));+ assert!(matches!(e[3].ty, wgpu::BindingType::StorageTexture { access: wgpu::StorageTextureAccess::ReadWrite, format: TextureFormat::Rgba16Float, .. }));+ assert!(matches!(e[4].ty, wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, .. }));+ assert_eq!(pipeline_layout(&json!({"bindGroupLayouts": [5, null, 7]})).unwrap(), vec![Some(5), None, Some(7)]);+ let g = bind_group(&json!({"layout": 9, "entries": [{"binding": 0, "resource": {"buffer": 3, "offset": 256, "size": 64}}, {"binding": 1, "resource": 12}]})).unwrap();+ assert_eq!(g.layout, 9);+ assert_eq!(g.entries, vec![(0, BgResource::Buffer { id: 3, offset: 256, size: Some(64) }), (1, BgResource::Object(12))]);+ assert!(bind_group(&json!({"layout": 9, "entries": [{"binding": 0}]})).is_err());+ }++ #[test]+ fn render_pipeline_descriptor() {+ let p = render_pipeline(&json!({+ "layout": "auto",+ "vertex": {"module": 4, "entryPoint": "main", "buffers": [+ {"arrayStride": 12, "attributes": [{"format": "float32x3", "offset": 0, "shaderLocation": 0}]},+ null,+ {"arrayStride": 64, "stepMode": "instance", "attributes": [{"format": "float32x4", "offset": 16, "shaderLocation": 3}]}+ ]},+ "primitive": {"topology": "triangle-strip", "stripIndexFormat": "uint32", "cullMode": "back", "frontFace": "cw"},+ "depthStencil": {"format": "depth24plus-stencil8", "depthWriteEnabled": true, "depthCompare": "less-equal", "stencilFront": {"passOp": "replace"}, "depthBias": -2},+ "multisample": {"count": 4, "alphaToCoverageEnabled": true},+ "fragment": {"module": 5, "constants": {"k": 2}, "targets": [+ {"format": "bgra8unorm", "blend": {"color": {"srcFactor": "src-alpha", "dstFactor": "one-minus-src-alpha"}, "alpha": {}}, "writeMask": 7},+ null+ ]}+ }))+ .unwrap();+ assert_eq!(p.layout, None);+ assert_eq!(p.vertex, StageSpec { module: 4, entry: Some("main".into()), constants: vec![] });+ assert_eq!(p.buffers.len(), 3);+ assert_eq!(p.buffers[1].stride, 0);+ assert_eq!(p.buffers[2].step, wgpu::VertexStepMode::Instance);+ assert_eq!(p.buffers[2].attributes[0].shader_location, 3);+ assert_eq!(p.primitive.topology, wgpu::PrimitiveTopology::TriangleStrip);+ assert_eq!(p.primitive.strip_index_format, Some(wgpu::IndexFormat::Uint32));+ assert_eq!(p.primitive.cull_mode, Some(wgpu::Face::Back));+ assert_eq!(p.primitive.front_face, wgpu::FrontFace::Cw);+ let ds = p.depth_stencil.unwrap();+ assert!(ds.depth_write_enabled);+ assert_eq!(ds.depth_compare, wgpu::CompareFunction::LessEqual);+ assert_eq!(ds.stencil.front.pass_op, wgpu::StencilOperation::Replace);+ assert_eq!(ds.stencil.back, wgpu::StencilFaceState::IGNORE);+ assert_eq!(ds.bias.constant, -2);+ assert_eq!((p.multisample.count, p.multisample.mask, p.multisample.alpha_to_coverage_enabled), (4, 0xFFFF_FFFF, true));+ let (fs, targets) = p.fragment.unwrap();+ assert_eq!(fs.entry, None);+ assert_eq!(fs.constants, vec![("k".to_string(), 2.0)]);+ let t = targets[0].clone().unwrap();+ assert_eq!(t.write_mask, wgpu::ColorWrites::RED | wgpu::ColorWrites::GREEN | wgpu::ColorWrites::BLUE);+ assert_eq!(t.blend.unwrap().color.src_factor, wgpu::BlendFactor::SrcAlpha);+ assert_eq!(t.blend.unwrap().alpha, wgpu::BlendComponent::REPLACE);+ assert!(targets[1].is_none());+ assert!(render_pipeline(&json!({"layout": "auto", "vertex": {"module": 1}, "primitive": {"topology": "quads"}})).is_err());+ assert!(render_pipeline(&json!({"vertex": {"module": 1}})).unwrap_err().contains("layout"));+ let c = compute_pipeline(&json!({"layout": 8, "compute": {"module": 2, "entryPoint": "cs"}})).unwrap();+ assert_eq!((c.layout, c.stage.module, c.stage.entry.as_deref()), (Some(8), 2, Some("cs")));+ }+}diff --git a/webgpu/src/fmt.rs b/webgpu/src/fmt.rsnew file mode 100644index 0000000..c7bc50e--- /dev/null+++ b/webgpu/src/fmt.rs@@ -0,0 +1,345 @@+//! WebGPU enum strings ↔ wgpu types.+use wgpu::TextureFormat as F;+use wgpu::{AstcBlock, AstcChannel};++const FORMATS: &[(&str, F)] = &[+ ("r8unorm", F::R8Unorm),+ ("r8snorm", F::R8Snorm),+ ("r8uint", F::R8Uint),+ ("r8sint", F::R8Sint),+ ("r16uint", F::R16Uint),+ ("r16sint", F::R16Sint),+ ("r16unorm", F::R16Unorm),+ ("r16snorm", F::R16Snorm),+ ("r16float", F::R16Float),+ ("rg8unorm", F::Rg8Unorm),+ ("rg8snorm", F::Rg8Snorm),+ ("rg8uint", F::Rg8Uint),+ ("rg8sint", F::Rg8Sint),+ ("r32uint", F::R32Uint),+ ("r32sint", F::R32Sint),+ ("r32float", F::R32Float),+ ("rg16uint", F::Rg16Uint),+ ("rg16sint", F::Rg16Sint),+ ("rg16unorm", F::Rg16Unorm),+ ("rg16snorm", F::Rg16Snorm),+ ("rg16float", F::Rg16Float),+ ("rgba8unorm", F::Rgba8Unorm),+ ("rgba8unorm-srgb", F::Rgba8UnormSrgb),+ ("rgba8snorm", F::Rgba8Snorm),+ ("rgba8uint", F::Rgba8Uint),+ ("rgba8sint", F::Rgba8Sint),+ ("bgra8unorm", F::Bgra8Unorm),+ ("bgra8unorm-srgb", F::Bgra8UnormSrgb),+ ("rgb9e5ufloat", F::Rgb9e5Ufloat),+ ("rgb10a2uint", F::Rgb10a2Uint),+ ("rgb10a2unorm", F::Rgb10a2Unorm),+ ("rg11b10ufloat", F::Rg11b10Ufloat),+ ("rg32uint", F::Rg32Uint),+ ("rg32sint", F::Rg32Sint),+ ("rg32float", F::Rg32Float),+ ("rgba16uint", F::Rgba16Uint),+ ("rgba16sint", F::Rgba16Sint),+ ("rgba16unorm", F::Rgba16Unorm),+ ("rgba16snorm", F::Rgba16Snorm),+ ("rgba16float", F::Rgba16Float),+ ("rgba32uint", F::Rgba32Uint),+ ("rgba32sint", F::Rgba32Sint),+ ("rgba32float", F::Rgba32Float),+ ("stencil8", F::Stencil8),+ ("depth16unorm", F::Depth16Unorm),+ ("depth24plus", F::Depth24Plus),+ ("depth24plus-stencil8", F::Depth24PlusStencil8),+ ("depth32float", F::Depth32Float),+ ("depth32float-stencil8", F::Depth32FloatStencil8),+ ("bc1-rgba-unorm", F::Bc1RgbaUnorm),+ ("bc1-rgba-unorm-srgb", F::Bc1RgbaUnormSrgb),+ ("bc2-rgba-unorm", F::Bc2RgbaUnorm),+ ("bc2-rgba-unorm-srgb", F::Bc2RgbaUnormSrgb),+ ("bc3-rgba-unorm", F::Bc3RgbaUnorm),+ ("bc3-rgba-unorm-srgb", F::Bc3RgbaUnormSrgb),+ ("bc4-r-unorm", F::Bc4RUnorm),+ ("bc4-r-snorm", F::Bc4RSnorm),+ ("bc5-rg-unorm", F::Bc5RgUnorm),+ ("bc5-rg-snorm", F::Bc5RgSnorm),+ ("bc6h-rgb-ufloat", F::Bc6hRgbUfloat),+ ("bc6h-rgb-float", F::Bc6hRgbFloat),+ ("bc7-rgba-unorm", F::Bc7RgbaUnorm),+ ("bc7-rgba-unorm-srgb", F::Bc7RgbaUnormSrgb),+ ("etc2-rgb8unorm", F::Etc2Rgb8Unorm),+ ("etc2-rgb8unorm-srgb", F::Etc2Rgb8UnormSrgb),+ ("etc2-rgb8a1unorm", F::Etc2Rgb8A1Unorm),+ ("etc2-rgb8a1unorm-srgb", F::Etc2Rgb8A1UnormSrgb),+ ("etc2-rgba8unorm", F::Etc2Rgba8Unorm),+ ("etc2-rgba8unorm-srgb", F::Etc2Rgba8UnormSrgb),+ ("eac-r11unorm", F::EacR11Unorm),+ ("eac-r11snorm", F::EacR11Snorm),+ ("eac-rg11unorm", F::EacRg11Unorm),+ ("eac-rg11snorm", F::EacRg11Snorm),+];++const ASTC_BLOCKS: &[(&str, AstcBlock)] = &[+ ("4x4", AstcBlock::B4x4),+ ("5x4", AstcBlock::B5x4),+ ("5x5", AstcBlock::B5x5),+ ("6x5", AstcBlock::B6x5),+ ("6x6", AstcBlock::B6x6),+ ("8x5", AstcBlock::B8x5),+ ("8x6", AstcBlock::B8x6),+ ("8x8", AstcBlock::B8x8),+ ("10x5", AstcBlock::B10x5),+ ("10x6", AstcBlock::B10x6),+ ("10x8", AstcBlock::B10x8),+ ("10x10", AstcBlock::B10x10),+ ("12x10", AstcBlock::B12x10),+ ("12x12", AstcBlock::B12x12),+];++pub fn texture_format(s: &str) -> Option<F> {+ if let Some(rest) = s.strip_prefix("astc-") {+ let (block, channel) = if let Some(b) = rest.strip_suffix("-unorm-srgb") {+ (b, AstcChannel::UnormSrgb)+ } else if let Some(b) = rest.strip_suffix("-unorm") {+ (b, AstcChannel::Unorm)+ } else {+ return None;+ };+ let block = ASTC_BLOCKS.iter().find(|(n, _)| *n == block)?.1;+ return Some(F::Astc { block, channel });+ }+ FORMATS.iter().find(|(n, _)| *n == s).map(|(_, f)| *f)+}++pub fn texture_format_name(f: F) -> String {+ if let F::Astc { block, channel } = f {+ let b = ASTC_BLOCKS.iter().find(|(_, x)| *x == block).map(|(n, _)| *n).unwrap_or("4x4");+ return format!("astc-{b}-{}", if channel == AstcChannel::UnormSrgb { "unorm-srgb" } else { "unorm" });+ }+ FORMATS.iter().find(|(_, x)| *x == f).map(|(n, _)| n.to_string()).unwrap_or_else(|| "rgba8unorm".into())+}++pub fn vertex_format(s: &str) -> Option<wgpu::VertexFormat> {+ use wgpu::VertexFormat as V;+ Some(match s {+ "uint8" => V::Uint8,+ "uint8x2" => V::Uint8x2,+ "uint8x4" => V::Uint8x4,+ "sint8" => V::Sint8,+ "sint8x2" => V::Sint8x2,+ "sint8x4" => V::Sint8x4,+ "unorm8" => V::Unorm8,+ "unorm8x2" => V::Unorm8x2,+ "unorm8x4" => V::Unorm8x4,+ "snorm8" => V::Snorm8,+ "snorm8x2" => V::Snorm8x2,+ "snorm8x4" => V::Snorm8x4,+ "uint16" => V::Uint16,+ "uint16x2" => V::Uint16x2,+ "uint16x4" => V::Uint16x4,+ "sint16" => V::Sint16,+ "sint16x2" => V::Sint16x2,+ "sint16x4" => V::Sint16x4,+ "unorm16" => V::Unorm16,+ "unorm16x2" => V::Unorm16x2,+ "unorm16x4" => V::Unorm16x4,+ "snorm16" => V::Snorm16,+ "snorm16x2" => V::Snorm16x2,+ "snorm16x4" => V::Snorm16x4,+ "float16" => V::Float16,+ "float16x2" => V::Float16x2,+ "float16x4" => V::Float16x4,+ "float32" => V::Float32,+ "float32x2" => V::Float32x2,+ "float32x3" => V::Float32x3,+ "float32x4" => V::Float32x4,+ "uint32" => V::Uint32,+ "uint32x2" => V::Uint32x2,+ "uint32x3" => V::Uint32x3,+ "uint32x4" => V::Uint32x4,+ "sint32" => V::Sint32,+ "sint32x2" => V::Sint32x2,+ "sint32x3" => V::Sint32x3,+ "sint32x4" => V::Sint32x4,+ "unorm10-10-10-2" => V::Unorm10_10_10_2,+ "unorm8x4-bgra" => V::Unorm8x4Bgra,+ _ => return None,+ })+}++pub fn compare(s: &str) -> Option<wgpu::CompareFunction> {+ use wgpu::CompareFunction as C;+ Some(match s {+ "never" => C::Never,+ "less" => C::Less,+ "equal" => C::Equal,+ "less-equal" => C::LessEqual,+ "greater" => C::Greater,+ "not-equal" => C::NotEqual,+ "greater-equal" => C::GreaterEqual,+ "always" => C::Always,+ _ => return None,+ })+}++pub fn stencil_op(s: &str) -> Option<wgpu::StencilOperation> {+ use wgpu::StencilOperation as S;+ Some(match s {+ "keep" => S::Keep,+ "zero" => S::Zero,+ "replace" => S::Replace,+ "invert" => S::Invert,+ "increment-clamp" => S::IncrementClamp,+ "decrement-clamp" => S::DecrementClamp,+ "increment-wrap" => S::IncrementWrap,+ "decrement-wrap" => S::DecrementWrap,+ _ => return None,+ })+}++pub fn blend_factor(s: &str) -> Option<wgpu::BlendFactor> {+ use wgpu::BlendFactor as B;+ Some(match s {+ "zero" => B::Zero,+ "one" => B::One,+ "src" => B::Src,+ "one-minus-src" => B::OneMinusSrc,+ "src-alpha" => B::SrcAlpha,+ "one-minus-src-alpha" => B::OneMinusSrcAlpha,+ "dst" => B::Dst,+ "one-minus-dst" => B::OneMinusDst,+ "dst-alpha" => B::DstAlpha,+ "one-minus-dst-alpha" => B::OneMinusDstAlpha,+ "src-alpha-saturated" => B::SrcAlphaSaturated,+ "constant" => B::Constant,+ "one-minus-constant" => B::OneMinusConstant,+ "src1" => B::Src1,+ "one-minus-src1" => B::OneMinusSrc1,+ "src1-alpha" => B::Src1Alpha,+ "one-minus-src1-alpha" => B::OneMinusSrc1Alpha,+ _ => return None,+ })+}++pub fn blend_op(s: &str) -> Option<wgpu::BlendOperation> {+ use wgpu::BlendOperation as B;+ Some(match s {+ "add" => B::Add,+ "subtract" => B::Subtract,+ "reverse-subtract" => B::ReverseSubtract,+ "min" => B::Min,+ "max" => B::Max,+ _ => return None,+ })+}++pub fn topology(s: &str) -> Option<wgpu::PrimitiveTopology> {+ use wgpu::PrimitiveTopology as P;+ Some(match s {+ "point-list" => P::PointList,+ "line-list" => P::LineList,+ "line-strip" => P::LineStrip,+ "triangle-list" => P::TriangleList,+ "triangle-strip" => P::TriangleStrip,+ _ => return None,+ })+}++pub fn index_format(s: &str) -> Option<wgpu::IndexFormat> {+ match s {+ "uint16" => Some(wgpu::IndexFormat::Uint16),+ "uint32" => Some(wgpu::IndexFormat::Uint32),+ _ => None,+ }+}++pub fn address_mode(s: &str) -> Option<wgpu::AddressMode> {+ match s {+ "clamp-to-edge" => Some(wgpu::AddressMode::ClampToEdge),+ "repeat" => Some(wgpu::AddressMode::Repeat),+ "mirror-repeat" => Some(wgpu::AddressMode::MirrorRepeat),+ _ => None,+ }+}++pub fn filter(s: &str) -> Option<wgpu::FilterMode> {+ match s {+ "nearest" => Some(wgpu::FilterMode::Nearest),+ "linear" => Some(wgpu::FilterMode::Linear),+ _ => None,+ }+}++pub fn view_dimension(s: &str) -> Option<wgpu::TextureViewDimension> {+ use wgpu::TextureViewDimension as D;+ Some(match s {+ "1d" => D::D1,+ "2d" => D::D2,+ "2d-array" => D::D2Array,+ "cube" => D::Cube,+ "cube-array" => D::CubeArray,+ "3d" => D::D3,+ _ => return None,+ })+}++pub fn texture_dimension(s: &str) -> Option<wgpu::TextureDimension> {+ match s {+ "1d" => Some(wgpu::TextureDimension::D1),+ "2d" => Some(wgpu::TextureDimension::D2),+ "3d" => Some(wgpu::TextureDimension::D3),+ _ => None,+ }+}++pub fn aspect(s: &str) -> Option<wgpu::TextureAspect> {+ match s {+ "all" => Some(wgpu::TextureAspect::All),+ "stencil-only" => Some(wgpu::TextureAspect::StencilOnly),+ "depth-only" => Some(wgpu::TextureAspect::DepthOnly),+ _ => None,+ }+}++/// Aspect codes used in the command stream (0 all, 1 stencil-only, 2 depth-only).+pub fn aspect_code(c: u32) -> wgpu::TextureAspect {+ match c {+ 1 => wgpu::TextureAspect::StencilOnly,+ 2 => wgpu::TextureAspect::DepthOnly,+ _ => wgpu::TextureAspect::All,+ }+}++/// WebGPU feature name ↔ wgpu feature, for the features this binding exposes to pages.+/// Features that change the WGSL a page generates in ways naga may not accept (`shader-f16`,+/// `subgroups`, `clip-distances`, `dual-source-blending`) are deliberately not exposed, and so is+/// `timestamp-query`: wgpu 25's Metal backend samples pass timestamps at vertex/fragment stage+/// boundaries and the end-of-pass sample reads 0 on Apple GPUs here, so three.js's+/// `trackTimestamp` would report garbage (without the feature it turns tracking off).+pub const FEATURES: &[(&str, wgpu::Features)] = &[+ ("depth-clip-control", wgpu::Features::DEPTH_CLIP_CONTROL),+ ("depth32float-stencil8", wgpu::Features::DEPTH32FLOAT_STENCIL8),+ ("texture-compression-bc", wgpu::Features::TEXTURE_COMPRESSION_BC),+ ("texture-compression-etc2", wgpu::Features::TEXTURE_COMPRESSION_ETC2),+ ("texture-compression-astc", wgpu::Features::TEXTURE_COMPRESSION_ASTC),+ ("indirect-first-instance", wgpu::Features::INDIRECT_FIRST_INSTANCE),+ ("rg11b10ufloat-renderable", wgpu::Features::RG11B10UFLOAT_RENDERABLE),+ ("bgra8unorm-storage", wgpu::Features::BGRA8UNORM_STORAGE),+ ("float32-filterable", wgpu::Features::FLOAT32_FILTERABLE),+];++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn formats_roundtrip() {+ for (name, f) in FORMATS {+ assert_eq!(texture_format(name), Some(*f));+ assert_eq!(texture_format_name(*f), *name);+ }+ let astc = texture_format("astc-10x8-unorm-srgb").unwrap();+ assert_eq!(astc, F::Astc { block: AstcBlock::B10x8, channel: AstcChannel::UnormSrgb });+ assert_eq!(texture_format_name(astc), "astc-10x8-unorm-srgb");+ assert_eq!(texture_format("rgba8"), None);+ assert_eq!(texture_format("astc-3x3-unorm"), None);+ }+}diff --git a/webgpu/src/gpu.rs b/webgpu/src/gpu.rsnew file mode 100644index 0000000..dfc0faf--- /dev/null+++ b/webgpu/src/gpu.rs@@ -0,0 +1,223 @@+//! The process-wide wgpu instance/adapter/device/queue, and the error sink that turns wgpu's+//! errors into WebGPU error scopes and `uncapturederror` events.+use std::sync::{Mutex, OnceLock};++use crate::fmt;++/// The shared GPU: one Metal device for the whole process (JS pages and the host's own+/// renderers use the same `Device`/`Queue`).+pub struct Gpu {+ pub instance: wgpu::Instance,+ pub adapter: wgpu::Adapter,+ pub device: wgpu::Device,+ pub queue: wgpu::Queue,+ /// WebGPU names of the features pages see (subset of the device's features)+ pub js_features: Vec<&'static str>,+}++/// Options for [`crate::init`].+#[derive(Clone, Debug, Default)]+pub struct GpuOptions {+ /// Extra wgpu features the host's own renderers need (requested only if the adapter has them).+ pub extra_features: wgpu::Features,+ /// `wgpu::InstanceFlags` debug/validation (default: off; `THREERT_WGPU_DEBUG=1` turns it on).+ pub debug: bool,+}++static GPU: OnceLock<Gpu> = OnceLock::new();+static INIT: Mutex<()> = Mutex::new(());++pub fn init(opts: &GpuOptions) -> Result<&'static Gpu, String> {+ let _guard = INIT.lock().unwrap_or_else(|e| e.into_inner());+ if let Some(g) = GPU.get() {+ return Ok(g);+ }+ let debug = opts.debug || std::env::var_os("THREERT_WGPU_DEBUG").is_some() || std::env::var_os("POCKET_WGPU_DEBUG").is_some();+ let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {+ backends: wgpu::Backends::PRIMARY,+ flags: if debug { wgpu::InstanceFlags::debugging() } else { wgpu::InstanceFlags::empty() },+ ..Default::default()+ });+ let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {+ power_preference: wgpu::PowerPreference::HighPerformance,+ force_fallback_adapter: false,+ compatible_surface: None,+ }))+ .map_err(|e| format!("no GPU adapter: {e}"))?;+ let have = adapter.features();+ let mut want = opts.extra_features & have;+ let mut js_features = vec!["core-features-and-limits"];+ for (name, f) in fmt::FEATURES {+ if have.contains(*f) {+ want |= *f;+ js_features.push(name);+ }+ }+ let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {+ label: Some("threert-webgpu"),+ required_features: want,+ required_limits: adapter.limits(),+ memory_hints: wgpu::MemoryHints::Performance,+ trace: wgpu::Trace::Off,+ }))+ .map_err(|e| format!("request_device: {e}"))?;+ device.on_uncaptured_error(Box::new(|e| sink_wgpu(e)));+ device.set_device_lost_callback(|reason, msg| {+ if !matches!(reason, wgpu::DeviceLostReason::Destroyed) {+ eprintln!("[webgpu] device lost: {msg}");+ *LOST.lock().unwrap_or_else(|e| e.into_inner()) = Some(msg);+ }+ });+ let _ = GPU.set(Gpu { instance, adapter, device, queue, js_features });+ Ok(GPU.get().unwrap())+}++pub fn get() -> Option<&'static Gpu> {+ GPU.get()+}++/// Set when the device is lost (reported to pages through `GPUDevice.lost`).+pub static LOST: Mutex<Option<String>> = Mutex::new(None);++// ------------------------------------------------------------------------------------------ errors++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ErrKind {+ Validation = 0,+ OutOfMemory = 1,+ Internal = 2,+}++impl ErrKind {+ pub fn from_filter(s: &str) -> Option<ErrKind> {+ match s {+ "validation" => Some(ErrKind::Validation),+ "out-of-memory" => Some(ErrKind::OutOfMemory),+ "internal" => Some(ErrKind::Internal),+ _ => None,+ }+ }+}++#[derive(Default)]+struct Sink {+ /// WebGPU error scopes of the page (innermost last): filter and first captured error+ scopes: Vec<(ErrKind, Option<(ErrKind, String)>)>,+ uncaptured: Vec<(ErrKind, String)>,+ /// >0 while the binding performs internal operations whose errors must not reach the page+ suppress: u32,+ logged: u32,+}++static SINK: Mutex<Sink> = Mutex::new(Sink { scopes: Vec::new(), uncaptured: Vec::new(), suppress: 0, logged: 0 });++fn sink() -> std::sync::MutexGuard<'static, Sink> {+ SINK.lock().unwrap_or_else(|e| e.into_inner())+}++pub(crate) fn sink_wgpu(e: wgpu::Error) {+ let (kind, msg) = match e {+ wgpu::Error::OutOfMemory { source } => (ErrKind::OutOfMemory, source.to_string()),+ wgpu::Error::Validation { description, .. } => (ErrKind::Validation, description),+ wgpu::Error::Internal { description, .. } => (ErrKind::Internal, description),+ };+ report(kind, msg);+}++/// Report an error the WebGPU way: into the innermost matching error scope, else as an+/// uncaptured error (logged, and dispatched to the page's `onuncapturederror`).+pub fn report(kind: ErrKind, msg: String) {+ let mut s = sink();+ if s.suppress > 0 {+ return;+ }+ if let Some(scope) = s.scopes.iter_mut().rev().find(|(f, _)| *f == kind) {+ if scope.1.is_none() {+ scope.1 = Some((kind, msg));+ }+ return;+ }+ if s.logged < 64 {+ s.logged += 1;+ eprintln!("[webgpu] uncaptured {kind:?} error: {msg}");+ }+ if s.uncaptured.len() < 256 {+ s.uncaptured.push((kind, msg));+ }+}++pub fn validation(msg: impl Into<String>) {+ report(ErrKind::Validation, msg.into());+}++pub fn push_scope(filter: ErrKind) {+ sink().scopes.push((filter, None));+}++/// `Err` when the stack is empty (an OperationError for the page).+pub fn pop_scope() -> Result<Option<(ErrKind, String)>, ()> {+ sink().scopes.pop().map(|(_, e)| e).ok_or(())+}++pub fn take_uncaptured() -> Vec<(ErrKind, String)> {+ std::mem::take(&mut sink().uncaptured)+}++pub fn has_uncaptured() -> bool {+ !sink().uncaptured.is_empty()+}++/// Run `f` with errors swallowed (internal bookkeeping calls that may legitimately fail).+pub fn quietly<R>(f: impl FnOnce() -> R) -> R {+ sink().suppress += 1;+ let r = f();+ sink().suppress -= 1;+ r+}++/// Run `f` inside a private validation scope; returns its result and the first error.+pub fn capture<R>(f: impl FnOnce() -> R) -> (R, Option<String>) {+ push_scope(ErrKind::Validation);+ push_scope(ErrKind::Internal);+ push_scope(ErrKind::OutOfMemory);+ let r = f();+ let mut first = None;+ for _ in 0..3 {+ if let Ok(Some((_, m))) = pop_scope() {+ first.get_or_insert(m);+ }+ }+ (r, first)+}++/// Drop the page's scopes and queued errors (page reset).+pub fn reset_errors() {+ let mut s = sink();+ s.scopes.clear();+ s.uncaptured.clear();+ s.logged = 0;+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn scopes_capture_by_filter() {+ reset_errors();+ push_scope(ErrKind::Validation);+ push_scope(ErrKind::OutOfMemory);+ report(ErrKind::Validation, "a".into());+ report(ErrKind::Validation, "b".into());+ assert_eq!(pop_scope(), Ok(None), "the OOM scope saw nothing");+ assert_eq!(pop_scope(), Ok(Some((ErrKind::Validation, "a".into()))), "first error wins");+ assert_eq!(pop_scope(), Err(()), "empty stack");+ report(ErrKind::Internal, "c".into());+ assert!(has_uncaptured());+ assert_eq!(take_uncaptured(), vec![(ErrKind::Internal, "c".into())]);+ quietly(|| report(ErrKind::Validation, "d".into()));+ assert!(!has_uncaptured());+ let ((), e) = capture(|| validation("e"));+ assert_eq!(e.as_deref(), Some("e"));+ assert!(!has_uncaptured());+ }+}diff --git a/webgpu/src/image.rs b/webgpu/src/image.rsnew file mode 100644index 0000000..f85642a--- /dev/null+++ b/webgpu/src/image.rs@@ -0,0 +1,268 @@+//! `copyExternalImageToTexture` from Canvas 2D bitmaps / decoded images / ImageData, and texture+//! readback to RGBA8 (canvas export, headless screenshots).+use wgpu::TextureFormat as F;++/// RGBA8 source pixels, rows top-down.+pub struct Source<'a> {+ pub width: u32,+ pub height: u32,+ pub stride: usize,+ pub data: &'a [u8],+ /// colour channels are premultiplied by alpha (2D canvases and decoded images are)+ pub premultiplied: bool,+}++pub struct CopyParams {+ pub origin: (u32, u32),+ pub flip_y: bool,+ pub size: (u32, u32),+ pub dst_premultiplied: bool,+}++fn bytes_per_texel(f: F) -> Option<usize> {+ Some(match f {+ F::R8Unorm => 1,+ F::Rg8Unorm => 2,+ F::Rgba8Unorm | F::Rgba8UnormSrgb | F::Bgra8Unorm | F::Bgra8UnormSrgb | F::Rgb10a2Unorm => 4,+ F::R16Float => 2,+ F::Rg16Float => 4,+ F::Rgba16Float => 8,+ F::R32Float => 4,+ F::Rg32Float => 8,+ F::Rgba32Float => 16,+ _ => return None,+ })+}++/// IEEE half from f32 (round to nearest even; values here are in [0, 1]).+pub fn f16_bits(x: f32) -> u16 {+ let b = x.to_bits();+ let sign = ((b >> 16) & 0x8000) as u16;+ let exp = ((b >> 23) & 0xff) as i32;+ let mant = b & 0x7f_ffff;+ if exp == 0xff {+ return sign | 0x7c00 | if mant != 0 { 0x200 } else { 0 };+ }+ let e = exp - 127 + 15;+ if e >= 0x1f {+ return sign | 0x7c00;+ }+ if e <= 0 {+ if e < -10 {+ return sign;+ }+ let m = mant | 0x80_0000;+ let shift = (14 - e) as u32;+ let half = m >> shift;+ let rem = m & ((1 << shift) - 1);+ let mid = 1 << (shift - 1);+ let round = if rem > mid || (rem == mid && half & 1 == 1) { 1 } else { 0 };+ return sign | (half + round) as u16;+ }+ let half = ((e as u32) << 10) | (mant >> 13);+ let rem = mant & 0x1fff;+ let round = if rem > 0x1000 || (rem == 0x1000 && half & 1 == 1) { 1 } else { 0 };+ sign | (half + round) as u16+}++pub fn f16_to_f32(h: u16) -> f32 {+ let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 };+ let exp = ((h >> 10) & 0x1f) as i32;+ let mant = (h & 0x3ff) as f32;+ sign * match exp {+ 0 => mant * (2f32).powi(-24),+ 31 => {+ if mant == 0.0 {+ f32::INFINITY+ } else {+ f32::NAN+ }+ }+ e => (1.0 + mant / 1024.0) * (2f32).powi(e - 15),+ }+}++/// Convert a source region into texel bytes of `format` (tightly packed rows). `Err` for formats+/// WebGPU does not allow as copyExternalImageToTexture destinations here.+pub fn convert(src: &Source, p: &CopyParams, format: F) -> Result<Vec<u8>, String> {+ let bpt = bytes_per_texel(format).ok_or_else(|| format!("copyExternalImageToTexture: unsupported destination format {format:?}"))?;+ let (w, h) = p.size;+ let (ox, oy) = p.origin;+ if ox as u64 + w as u64 > src.width as u64 || oy as u64 + h as u64 > src.height as u64 {+ return Err(format!("copyExternalImageToTexture: source region {ox},{oy} {w}x{h} exceeds the {}x{} source", src.width, src.height));+ }+ let mut out = vec![0u8; w as usize * h as usize * bpt];+ let mut px = [0f32; 4];+ for y in 0..h {+ // flipY flips the source image; the origin addresses the flipped image+ let sy = if p.flip_y { src.height - 1 - (oy + y) } else { oy + y } as usize;+ let row = &src.data[sy * src.stride..];+ for x in 0..w {+ let s = &row[(ox + x) as usize * 4..(ox + x) as usize * 4 + 4];+ let (mut r, mut g, mut b, a) = (s[0], s[1], s[2], s[3]);+ if src.premultiplied && !p.dst_premultiplied && a != 0 && a != 255 {+ let un = |c: u8| ((c as u32 * 255 + a as u32 / 2) / a as u32).min(255) as u8;+ (r, g, b) = (un(r), un(g), un(b));+ } else if !src.premultiplied && p.dst_premultiplied && a != 255 {+ let pm = |c: u8| ((c as u32 * a as u32 + 127) / 255) as u8;+ (r, g, b) = (pm(r), pm(g), pm(b));+ }+ let o = &mut out[(y as usize * w as usize + x as usize) * bpt..][..bpt];+ match format {+ F::Rgba8Unorm | F::Rgba8UnormSrgb => o.copy_from_slice(&[r, g, b, a]),+ F::Bgra8Unorm | F::Bgra8UnormSrgb => o.copy_from_slice(&[b, g, r, a]),+ F::R8Unorm => o[0] = r,+ F::Rg8Unorm => o.copy_from_slice(&[r, g]),+ F::Rgb10a2Unorm => {+ let c = |v: u8| (v as u32 * 1023 + 127) / 255;+ let v = c(r) | (c(g) << 10) | (c(b) << 20) | (((a as u32 * 3 + 127) / 255) << 30);+ o.copy_from_slice(&v.to_le_bytes());+ }+ _ => {+ px[0] = r as f32 / 255.0;+ px[1] = g as f32 / 255.0;+ px[2] = b as f32 / 255.0;+ px[3] = a as f32 / 255.0;+ let n = match format {+ F::R16Float | F::R32Float => 1,+ F::Rg16Float | F::Rg32Float => 2,+ _ => 4,+ };+ if matches!(format, F::R16Float | F::Rg16Float | F::Rgba16Float) {+ for i in 0..n {+ o[i * 2..i * 2 + 2].copy_from_slice(&f16_bits(px[i]).to_le_bytes());+ }+ } else {+ for i in 0..n {+ o[i * 4..i * 4 + 4].copy_from_slice(&px[i].to_le_bytes());+ }+ }+ }+ }+ }+ }+ Ok(out)+}++pub fn upload(queue: &wgpu::Queue, tex: &wgpu::Texture, mip: u32, origin: wgpu::Origin3d, size: (u32, u32), format: F, bytes: &[u8]) {+ let bpt = bytes_per_texel(format).unwrap_or(4) as u32;+ queue.write_texture(+ wgpu::TexelCopyTextureInfo { texture: tex, mip_level: mip, origin, aspect: wgpu::TextureAspect::All },+ bytes,+ wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(size.0 * bpt), rows_per_image: Some(size.1) },+ wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },+ );+}++/// Read a 2D texture (mip 0, layer 0) back as RGBA8, rows top-down. Blocks until the GPU is done.+/// `opaque` forces alpha to 255 (an opaque canvas as composited); otherwise colours are+/// un-premultiplied when `premultiplied`.+pub fn read_rgba(dev: &wgpu::Device, queue: &wgpu::Queue, tex: &wgpu::Texture, opaque: bool, premultiplied: bool) -> Result<(u32, u32, Vec<u8>), String> {+ let format = tex.format();+ let bpt = match format {+ F::Rgba8Unorm | F::Rgba8UnormSrgb | F::Bgra8Unorm | F::Bgra8UnormSrgb => 4,+ F::Rgba16Float => 8,+ F::Rgba32Float => 16,+ f => return Err(format!("readback of {f:?} is not supported")),+ };+ if !tex.usage().contains(wgpu::TextureUsages::COPY_SRC) {+ return Err("texture lacks COPY_SRC".into());+ }+ let (w, h) = (tex.width(), tex.height());+ let row = w as u64 * bpt;+ let padded = row.div_ceil(256) * 256;+ let buf = dev.create_buffer(&wgpu::BufferDescriptor { label: Some("readback"), size: (padded * h as u64).max(4), usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });+ let mut enc = dev.create_command_encoder(&Default::default());+ enc.copy_texture_to_buffer(+ wgpu::TexelCopyTextureInfo { texture: tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },+ wgpu::TexelCopyBufferInfo { buffer: &buf, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(padded as u32), rows_per_image: Some(h) } },+ wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },+ );+ queue.submit([enc.finish()]);+ let (tx, rx) = std::sync::mpsc::channel();+ let slice = buf.slice(..);+ slice.map_async(wgpu::MapMode::Read, move |r| {+ let _ = tx.send(r.is_ok());+ });+ let _ = dev.poll(wgpu::PollType::Wait);+ if !rx.recv().unwrap_or(false) {+ return Err("readback map failed".into());+ }+ let data = slice.get_mapped_range();+ let mut out = vec![0u8; w as usize * h as usize * 4];+ for y in 0..h as usize {+ let src = &data[y * padded as usize..][..row as usize];+ let dst = &mut out[y * w as usize * 4..][..w as usize * 4];+ for x in 0..w as usize {+ let mut p = match format {+ F::Bgra8Unorm | F::Bgra8UnormSrgb => [src[x * 4 + 2], src[x * 4 + 1], src[x * 4], src[x * 4 + 3]],+ F::Rgba8Unorm | F::Rgba8UnormSrgb => [src[x * 4], src[x * 4 + 1], src[x * 4 + 2], src[x * 4 + 3]],+ _ => {+ let mut c = [0u8; 4];+ for (i, v) in c.iter_mut().enumerate() {+ let f = if bpt == 8 {+ f16_to_f32(u16::from_le_bytes([src[x * 8 + i * 2], src[x * 8 + i * 2 + 1]]))+ } else {+ f32::from_le_bytes(src[x * 16 + i * 4..x * 16 + i * 4 + 4].try_into().unwrap())+ };+ *v = (f.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;+ }+ c+ }+ };+ if opaque {+ p[3] = 255;+ } else if premultiplied && p[3] != 0 && p[3] != 255 {+ let a = p[3] as u32;+ for c in &mut p[..3] {+ *c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8;+ }+ }+ dst[x * 4..x * 4 + 4].copy_from_slice(&p);+ }+ }+ drop(data);+ buf.unmap();+ Ok((w, h, out))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn half_floats() {+ for v in [0.0f32, 1.0, 0.5, 0.25, 1.0 / 255.0, 0.999, 65504.0, 6.1e-5, 3.0e-7] {+ let back = f16_to_f32(f16_bits(v));+ assert!((back - v).abs() <= v.abs() * 1e-3 + 6e-8, "{v} → {back}");+ }+ assert_eq!(f16_bits(1.0), 0x3c00);+ assert_eq!(f16_bits(-2.0), 0xc000);+ assert_eq!(f16_bits(1e9), 0x7c00);+ }++ #[test]+ fn convert_flip_unpremultiply_swizzle() {+ // 2x2 premultiplied: top row red (opaque) + half-transparent white, bottom row blue + black+ let data = [255, 0, 0, 255, 128, 128, 128, 128, 0, 0, 255, 255, 0, 0, 0, 255];+ let src = Source { width: 2, height: 2, stride: 8, data: &data, premultiplied: true };+ let p = CopyParams { origin: (0, 0), flip_y: false, size: (2, 2), dst_premultiplied: false };+ let out = convert(&src, &p, F::Rgba8Unorm).unwrap();+ assert_eq!(&out[..8], &[255, 0, 0, 255, 255, 255, 255, 128]);+ let flipped = convert(&src, &CopyParams { flip_y: true, ..p }, F::Rgba8Unorm).unwrap();+ assert_eq!(&flipped[..4], &[0, 0, 255, 255], "bottom row first");+ let bgra = convert(&src, &CopyParams { dst_premultiplied: true, ..p }, F::Bgra8Unorm).unwrap();+ assert_eq!(&bgra[..8], &[0, 0, 255, 255, 128, 128, 128, 128]);+ let half = convert(&src, &p, F::Rgba16Float).unwrap();+ assert_eq!(u16::from_le_bytes([half[0], half[1]]), 0x3c00);+ let region = convert(&src, &CopyParams { origin: (1, 1), size: (1, 1), ..p }, F::Rgba8Unorm).unwrap();+ assert_eq!(region, vec![0, 0, 0, 255]);+ assert!(convert(&src, &CopyParams { origin: (1, 1), size: (2, 1), ..p }, F::Rgba8Unorm).is_err());+ assert!(convert(&src, &p, F::Depth24Plus).is_err());+ // ImageData (unpremultiplied) into a premultiplied destination+ let id = [200, 100, 50, 0, 255, 255, 255, 51];+ let src = Source { width: 2, height: 1, stride: 8, data: &id, premultiplied: false };+ let out = convert(&src, &CopyParams { origin: (0, 0), flip_y: false, size: (2, 1), dst_premultiplied: true }, F::Rgba8Unorm).unwrap();+ assert_eq!(out, vec![0, 0, 0, 0, 51, 51, 51, 51]);+ }+}diff --git a/webgpu/src/js.rs b/webgpu/src/js.rsnew file mode 100644index 0000000..b444a63--- /dev/null+++ b/webgpu/src/js.rs@@ -0,0 +1,1152 @@+//! `__native.gpu`: the functions `runtime/webgpu.ts` calls. Ids are slab ids; `Err` results+//! become JS exceptions that the JS layer maps to the WebGPU exception types (TypeError for+//! descriptor parse errors, OperationError for mapping misuse). GPU validation errors are+//! reported through the error sink instead and return an id anyway (an "invalid" object).+use std::time::Instant;++use jsc::{Ctx, NativeResult, TypedArrayType, Value};+use serde_json::Value as J;++use crate::args;+use crate::canvas::{Canvas, Config};+use crate::cmd;+use crate::desc;+use crate::fmt;+use crate::gpu::{self, ErrKind, Gpu};+use crate::image;+use crate::res::{BufferRes, MapState, QuerySetRes, Res, ShaderRes, TextureRes, ViewRes};+use crate::{STATE, State, WINDOW, encode_writes, flush_writes_now, frame_encoder, push_event, token};++type F = fn(Ctx, &[Value]) -> NativeResult;++fn arg(a: &[Value], i: usize) -> Value {+ a.get(i).copied().unwrap_or(Value(std::ptr::null()))+}+fn is_missing(c: Ctx, a: &[Value], i: usize) -> bool {+ a.get(i).is_none_or(|v| args::is_nullish(c, *v))+}+fn num(c: Ctx, a: &[Value], i: usize) -> f64 {+ a.get(i).map(|v| args::num(c, *v)).unwrap_or(f64::NAN)+}+/// Non-negative integer argument (ids, offsets, sizes); NaN/negative → 0.+fn u(c: Ctx, a: &[Value], i: usize) -> u32 {+ let d = num(c, a, i);+ if d.is_finite() && d > 0.0 { d.min(u32::MAX as f64) as u32 } else { 0 }+}+fn u64a(c: Ctx, a: &[Value], i: usize) -> u64 {+ let d = num(c, a, i);+ if d.is_finite() && d > 0.0 { d as u64 } else { 0 }+}+/// Optional size: negative / missing → None.+fn opt_u64(c: Ctx, a: &[Value], i: usize) -> Option<u64> {+ let d = num(c, a, i);+ if d.is_finite() && d >= 0.0 { Some(d as u64) } else { None }+}+fn string(c: Ctx, a: &[Value], i: usize) -> String {+ a.get(i).map(|v| v.to_string(c)).unwrap_or_default()+}+fn json(c: Ctx, a: &[Value], i: usize) -> Result<J, String> {+ if is_missing(c, a, i) {+ return Ok(J::Null);+ }+ serde_json::from_str(&string(c, a, i)).map_err(|e| format!("bad descriptor JSON: {e}"))+}+fn id_val(c: Ctx, id: u32) -> Value {+ args::num_val(c, id as f64)+}+fn gpu() -> Result<&'static Gpu, String> {+ gpu::get().ok_or_else(|| "no GPU device".to_string())+}+fn with<R>(f: impl FnOnce(&mut State) -> R) -> R {+ STATE.with(|s| {+ let mut st = s.borrow_mut();+ st.stats.calls += 1;+ f(&mut st)+ })+}+/// An object for the page whose wgpu creation failed before reaching wgpu (bad id): report a+/// validation error; the page gets id 0, which fails validation wherever it is used.+fn invalid(c: Ctx, msg: String) -> NativeResult {+ gpu::validation(msg);+ Ok(id_val(c, 0))+}++pub fn install(c: Ctx, native: Value) {+ let o = c.object();+ native.set(c, "gpu", o);+ let fns: &[(&str, F)] = &[+ ("info", info),+ ("preferredFormat", preferred_format),+ ("createBuffer", create_buffer),+ ("bufferDestroy", buffer_destroy),+ ("mapAsync", map_async),+ ("getMappedRange", get_mapped_range),+ ("unmap", unmap),+ ("poll", poll),+ ("workDone", work_done),+ ("createTexture", create_texture),+ ("textureDestroy", texture_destroy),+ ("createView", create_view),+ ("createSampler", create_sampler),+ ("createShaderModule", create_shader_module),+ ("shaderInfo", shader_info),+ ("createBindGroupLayout", create_bind_group_layout),+ ("createPipelineLayout", create_pipeline_layout),+ ("createBindGroup", create_bind_group),+ ("createRenderPipeline", create_render_pipeline),+ ("createRenderPipelineAsync", create_render_pipeline_async),+ ("createComputePipeline", create_compute_pipeline),+ ("createComputePipelineAsync", create_compute_pipeline_async),+ ("getBindGroupLayout", get_bind_group_layout),+ ("createQuerySet", create_query_set),+ ("querySetDestroy", query_set_destroy),+ ("finish", finish),+ ("submit", submit),+ ("writeBuffer", write_buffer),+ ("writeTexture", write_texture),+ ("copyExternal", copy_external),+ ("pushErrorScope", push_error_scope),+ ("popErrorScope", pop_error_scope),+ ("takeErrors", take_errors),+ ("reportError", report_error),+ ("release", release),+ ("canvasCreate", canvas_create),+ ("windowCanvas", window_canvas),+ ("windowInfo", window_info),+ ("canvasResize", canvas_resize),+ ("canvasConfigure", canvas_configure),+ ("canvasUnconfigure", canvas_unconfigure),+ ("canvasTexture", canvas_texture),+ ("canvasRead", canvas_read),+ ("canvasRelease", canvas_release),+ ("stats", stats),+ ];+ for (name, f) in fns {+ let f = *f;+ o.set(c, name, c.function(move |c, _this, a| f(c, a)));+ }+}++// ------------------------------------------------------------------------------------- adapter++fn info(c: Ctx, _a: &[Value]) -> NativeResult {+ let Some(g) = gpu::get() else { return Ok(c.null()) };+ let l = g.device.limits();+ let ai = g.adapter.get_info();+ let limits = serde_json::json!({+ "maxTextureDimension1D": l.max_texture_dimension_1d,+ "maxTextureDimension2D": l.max_texture_dimension_2d,+ "maxTextureDimension3D": l.max_texture_dimension_3d,+ "maxTextureArrayLayers": l.max_texture_array_layers,+ "maxBindGroups": l.max_bind_groups,+ "maxBindGroupsPlusVertexBuffers": l.max_bind_groups + l.max_vertex_buffers,+ "maxBindingsPerBindGroup": l.max_bindings_per_bind_group,+ "maxDynamicUniformBuffersPerPipelineLayout": l.max_dynamic_uniform_buffers_per_pipeline_layout,+ "maxDynamicStorageBuffersPerPipelineLayout": l.max_dynamic_storage_buffers_per_pipeline_layout,+ "maxSampledTexturesPerShaderStage": l.max_sampled_textures_per_shader_stage,+ "maxSamplersPerShaderStage": l.max_samplers_per_shader_stage,+ "maxStorageBuffersPerShaderStage": l.max_storage_buffers_per_shader_stage,+ "maxStorageTexturesPerShaderStage": l.max_storage_textures_per_shader_stage,+ "maxUniformBuffersPerShaderStage": l.max_uniform_buffers_per_shader_stage,+ "maxUniformBufferBindingSize": l.max_uniform_buffer_binding_size,+ "maxStorageBufferBindingSize": l.max_storage_buffer_binding_size,+ "minUniformBufferOffsetAlignment": l.min_uniform_buffer_offset_alignment,+ "minStorageBufferOffsetAlignment": l.min_storage_buffer_offset_alignment,+ "maxVertexBuffers": l.max_vertex_buffers,+ "maxBufferSize": l.max_buffer_size,+ "maxVertexAttributes": l.max_vertex_attributes,+ "maxVertexBufferArrayStride": l.max_vertex_buffer_array_stride,+ "maxInterStageShaderVariables": l.max_inter_stage_shader_components / 4,+ "maxColorAttachments": l.max_color_attachments,+ "maxColorAttachmentBytesPerSample": l.max_color_attachment_bytes_per_sample,+ "maxComputeWorkgroupStorageSize": l.max_compute_workgroup_storage_size,+ "maxComputeInvocationsPerWorkgroup": l.max_compute_invocations_per_workgroup,+ "maxComputeWorkgroupSizeX": l.max_compute_workgroup_size_x,+ "maxComputeWorkgroupSizeY": l.max_compute_workgroup_size_y,+ "maxComputeWorkgroupSizeZ": l.max_compute_workgroup_size_z,+ "maxComputeWorkgroupsPerDimension": l.max_compute_workgroups_per_dimension,+ });+ let out = serde_json::json!({+ "features": g.js_features,+ "limits": limits,+ "info": { "vendor": "apple", "architecture": "metal", "device": ai.name, "description": ai.name },+ });+ Ok(c.str(&out.to_string()))+}++/// The host target's format when it is a valid canvas format, else bgra8unorm.+fn preferred_format(c: Ctx, _a: &[Value]) -> NativeResult {+ let f = WINDOW.with(|w| w.borrow().target.as_ref().map(|t| t.texture.format()));+ let name = match f {+ Some(wgpu::TextureFormat::Rgba8Unorm) => "rgba8unorm",+ Some(wgpu::TextureFormat::Rgba16Float) => "rgba16float",+ _ => "bgra8unorm",+ };+ Ok(c.str(name))+}++// ------------------------------------------------------------------------------------- buffers++/// createBuffer(size, usage, mappedAtCreation, label) → id. Throws RangeError text for an+/// unaligned mappedAtCreation size (the JS layer rethrows it as RangeError).+fn create_buffer(c: Ctx, a: &[Value]) -> NativeResult {+ let g = gpu()?;+ let size = u64a(c, a, 0);+ let usage = wgpu::BufferUsages::from_bits_retain(u(c, a, 1));+ let mapped = args::truthy(c, arg(a, 2));+ if mapped && size % 4 != 0 {+ return Err("RangeError: mappedAtCreation buffers need a size that is a multiple of 4".into());+ }+ let label = if is_missing(c, a, 3) { None } else { Some(string(c, a, 3)) };+ // A creation error must not leave wgpu believing an invalid buffer is mapped (reading its+ // mapped range would panic): capture, then re-report to the page.+ let (buf, err) = gpu::capture(|| g.device.create_buffer(&wgpu::BufferDescriptor { label: label.as_deref(), size, usage, mapped_at_creation: mapped }));+ let ok = err.is_none();+ if let Some(e) = err {+ gpu::validation(e);+ }+ let map = if mapped && ok { MapState::Mapped } else { MapState::Unmapped };+ let id = with(|st| st.slab.insert(Res::Buffer(BufferRes { buf, size, usage, map, map_range: 0..size, map_write: mapped, map_token: 0.0, destroyed: !ok })));+ Ok(id_val(c, id))+}++fn buffer_destroy(c: Ctx, a: &[Value]) -> NativeResult {+ let g = gpu()?;+ let id = u(c, a, 0);+ with(|st| {+ flush_writes_now(st, g);+ if let Ok(b) = st.slab.buffer_mut(id) {+ if b.map != MapState::Unmapped && !b.destroyed {+ gpu::quietly(|| b.buf.unmap());+ }+ b.map = MapState::Unmapped;+ b.destroyed = true;+ b.buf.destroy();+ }+ });+ Ok(args::undef(c))+}++/// mapAsync(id, mode, offset, size|-1) → token (> 0), or 0 after a validation error.+fn map_async(c: Ctx, a: &[Value]) -> NativeResult {+ let g = gpu()?;+ let (id, mode, off) = (u(c, a, 0), u(c, a, 1), u64a(c, a, 2));+ let size = opt_u64(c, a, 3);+ let tok = token();+ let r = with(|st| -> Result<(), String> {+ flush_writes_now(st, g);+ let b = st.slab.buffer_mut(id)?;+ if b.map != MapState::Unmapped {+ return Err("mapAsync: the buffer is already mapped or has a pending map".into());+ }+ if b.destroyed {+ return Err("mapAsync: the buffer is destroyed".into());+ }+ let end = match size {+ Some(s) => off.checked_add(s).ok_or("mapAsync: range overflows")?,+ None => b.size.max(off),+ };+ let (m, need) = match mode {+ 1 => (wgpu::MapMode::Read, wgpu::BufferUsages::MAP_READ),+ 2 => (wgpu::MapMode::Write, wgpu::BufferUsages::MAP_WRITE),+ _ => return Err(format!("mapAsync: mode must be READ or WRITE, got {mode}")),+ };+ if !b.usage.contains(need) {+ return Err("mapAsync: the buffer's usage does not allow this map mode".into());+ }+ if off % 8 != 0 || (end - off) % 4 != 0 || end > b.size {+ return Err(format!("mapAsync: invalid range [{off}, {end}) for a buffer of size {}", b.size));+ }+ b.map = MapState::Pending;+ b.map_range = off..end;+ b.map_write = mode == 2;+ b.map_token = tok;+ if end == off {+ push_event(tok, 0, id);+ } else {+ b.buf.slice(off..end).map_async(m, move |r| push_event(tok, if r.is_ok() { 0 } else { 1 }, id));+ }+ Ok(())+ });+ match r {+ Ok(()) => Ok(args::num_val(c, tok)),+ Err(e) => {+ gpu::validation(e);+ Ok(args::num_val(c, 0.0))+ }+ }+}++/// poll() → [token, status, token, status, …] (status 0 ok, 1 failed) or null. Settles the+/// map state of buffers whose mapAsync completed.+fn poll(c: Ctx, _a: &[Value]) -> NativeResult {+ let g = gpu()?;+ let _ = g.device.poll(wgpu::PollType::Poll);+ let events: Vec<(f64, u32, u32)> = std::mem::take(&mut *crate::EVENTS.lock().unwrap_or_else(|e| e.into_inner()));+ if events.is_empty() {+ return Ok(args::null(c));+ }+ with(|st| {+ for &(tok, status, id) in &events {+ if id == 0 {+ continue;+ }+ if let Ok(b) = st.slab.buffer_mut(id) {+ if b.map == MapState::Pending && b.map_token == tok {+ if status == 0 {+ b.map = MapState::Mapped;+ } else {+ b.map = MapState::Unmapped;+ gpu::quietly(|| b.buf.unmap());+ }+ }+ }+ }+ });+ let mut out = Vec::with_capacity(events.len() * 2);+ for (t, s, _) in events {+ out.push(args::num_val(c, t));+ out.push(args::int_val(c, s as i32));+ }+ Ok(c.array(&out))+}++fn work_done(c: Ctx, _a: &[Value]) -> NativeResult {+ let g = gpu()?;+ let tok = token();+ with(|st| flush_writes_now(st, g));+ g.queue.on_submitted_work_done(move || push_event(tok, 0, 0));+ Ok(args::num_val(c, tok))+}++/// getMappedRange(id, offset, size|-1) → Uint8Array with a copy of the mapped bytes.+fn get_mapped_range(c: Ctx, a: &[Value]) -> NativeResult {+ let (id, off) = (u(c, a, 0), u64a(c, a, 1));+ let size = opt_u64(c, a, 2);+ let bytes = with(|st| -> Result<Vec<u8>, String> {+ let b = st.slab.buffer(id)?;+ if b.map != MapState::Mapped {+ return Err("OperationError: the buffer is not mapped".into());+ }+ let end = match size {+ Some(s) => off.checked_add(s).ok_or("OperationError: range overflows")?,+ None => b.map_range.end.max(off),+ };+ if off % 8 != 0 || (end - off) % 4 != 0 || off < b.map_range.start || end > b.map_range.end {+ return Err(format!("OperationError: getMappedRange [{off}, {end}) is outside the mapped range or unaligned"));+ }+ if end == off || b.destroyed {+ return Ok(vec![0; (end - off) as usize]);+ }+ Ok(b.buf.slice(off..end).get_mapped_range().to_vec())+ })?;+ Ok(c.typed_array(TypedArrayType::Uint8, bytes.len(), &bytes))+}++/// unmap(id, [offset, Uint8Array, …] | null): writes back the page's views of a write mapping.+fn unmap(c: Ctx, a: &[Value]) -> NativeResult {+ let id = u(c, a, 0);+ // gather (offset, bytes) before touching the slab (reading arrays calls into JSC)+ let mut writes: Vec<(u64, Vec<u8>)> = Vec::new();+ if !is_missing(c, a, 1) {+ let list = arg(a, 1);+ let n = list.len(c);+ for i in 0..n / 2 {+ let off = list.at(c, i * 2).to_num(c).max(0.0) as u64;+ let v = list.at(c, i * 2 + 1);+ if let Some(b) = v.bytes(c) {+ writes.push((off, b.to_vec()));+ }+ }+ }+ with(|st| {+ let Ok(b) = st.slab.buffer_mut(id) else { return };+ match b.map {+ MapState::Unmapped => {}+ MapState::Pending => {+ b.map = MapState::Unmapped;+ gpu::quietly(|| b.buf.unmap());+ }+ MapState::Mapped => {+ if b.map_write && !b.destroyed {+ for (off, data) in &writes {+ let end = off + data.len() as u64;+ if data.is_empty() || *off < b.map_range.start || end > b.map_range.end {+ continue;+ }+ b.buf.slice(*off..end).get_mapped_range_mut().copy_from_slice(data);+ }+ }+ b.map = MapState::Unmapped;+ if !b.destroyed {+ b.buf.unmap();+ }+ }+ }+ });+ Ok(args::undef(c))+}++/// writeBuffer(id, bufferOffset, data, dataByteOffset, byteSize|-1)+fn write_buffer(c: Ctx, a: &[Value]) -> NativeResult {+ let t0 = Instant::now();+ let (id, dst) = (u(c, a, 0), u64a(c, a, 1));+ let data = arg(a, 2);+ let bytes: &[u8] = match args::view(c, data) {+ Some(b) => b,+ None => match data.bytes(c) {+ Some(b) => b,+ None => return Err("TypeError: writeBuffer data must be an ArrayBuffer or ArrayBufferView".into()),+ },+ };+ let src_off = u64a(c, a, 3) as usize;+ let size = opt_u64(c, a, 4).map(|s| s as usize).unwrap_or(bytes.len().saturating_sub(src_off));+ if src_off > bytes.len() || size > bytes.len() - src_off {+ return Err("OperationError: writeBuffer data range is out of bounds".into());+ }+ let src = &bytes[src_off..src_off + size];+ with(|st| {+ let err = match st.slab.buffer(id) {+ Err(e) => Some(e),+ Ok(b) if b.destroyed => Some("writeBuffer: the buffer is destroyed".into()),+ Ok(b) if b.map != MapState::Unmapped => Some("writeBuffer: the buffer is mapped".into()),+ Ok(b) if !b.usage.contains(wgpu::BufferUsages::COPY_DST) => Some("writeBuffer: the buffer lacks COPY_DST usage".into()),+ Ok(b) if dst % 4 != 0 || size % 4 != 0 || dst + size as u64 > b.size => Some(format!("writeBuffer: invalid range [{dst}, {}) for a buffer of size {}", dst + size as u64, b.size)),+ Ok(_) => None,+ };+ if let Some(e) = err {+ gpu::validation(e);+ return;+ }+ if size == 0 {+ return;+ }+ let w = &mut st.writes;+ let at = w.staging.len();+ w.staging.extend_from_slice(src);+ w.staging.resize((at + size + 3) & !3, 0);+ w.ops.push((id, dst, at as u32, size as u32));+ st.stats.writes += 1;+ st.stats.write_bytes += size as u64;+ st.stats.write_ns += t0.elapsed().as_nanos() as u64;+ });+ Ok(args::undef(c))+}++// ------------------------------------------------------------------------------------- textures++fn create_texture(c: Ctx, a: &[Value]) -> NativeResult {+ let g = gpu()?;+ let spec = desc::texture(&json(c, a, 0)?)?;+ let tex = g.device.create_texture(&spec.desc());+ let id = with(|st| {+ st.slab.insert(Res::Texture(TextureRes { tex, format: spec.format, size: spec.size, mips: spec.mips, samples: spec.samples, dimension: spec.dimension, usage: spec.usage, canvas: false }))+ });+ Ok(id_val(c, id))+}++fn texture_destroy(c: Ctx, a: &[Value]) -> NativeResult {+ let id = u(c, a, 0);+ with(|st| {+ if let Some(g) = gpu::get() {+ flush_writes_now(st, g);+ }+ if let Ok(t) = st.slab.texture(id) {+ // canvas textures belong to the canvas (the host's target must stay usable)+ if !t.canvas {+ t.tex.destroy();+ }+ }+ });+ Ok(args::undef(c))+}++fn create_view(c: Ctx, a: &[Value]) -> NativeResult {+ let tex = u(c, a, 0);+ let spec = desc::view(&json(c, a, 1)?)?;+ let r = with(|st| -> Result<u32, String> {+ let t = st.slab.texture(tex)?;+ let view = t.tex.create_view(&spec.desc());+ Ok(st.slab.insert(Res::View(ViewRes { view, texture: tex })))+ });+ match r {+ Ok(id) => Ok(id_val(c, id)),+ Err(e) => invalid(c, format!("createView: {e}")),+ }+}++fn create_sampler(c: Ctx, a: &[Value]) -> NativeResult {+ let g = gpu()?;+ let d = desc::sampler(&json(c, a, 0)?)?;+ let s = g.device.create_sampler(&d);+ Ok(id_val(c, with(|st| st.slab.insert(Res::Sampler(s)))))+}++// ------------------------------------------------------------------------------------- shaders++fn create_shader_module(c: Ctx, a: &[Value]) -> NativeResult {+ let g = gpu()?;+ let code = string(c, a, 0);+ let label = if is_missing(c, a, 1) { None } else { Some(string(c, a, 1)) };+ g.device.push_error_scope(wgpu::ErrorFilter::Validation);+ let mut module = g.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: label.as_deref(), source: wgpu::ShaderSource::Wgsl(code.as_str().into()) });+ if let Some(e) = pollster::block_on(g.device.pop_error_scope()) {+ // naga 25 rejects abstract-typed expressions outside constant expressions, which Tint+ // concretises (three.js folds e.g. `smoothstep(0.1, 0.9, 1.0)` into such a call): retry with+ // every float literal made f32; any other error goes to the page as it would in a browser.+ let msg = e.to_string();+ if msg.contains("Abstract types may only appear in constant expressions") {+ module = g.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: label.as_deref(), source: wgpu::ShaderSource::Wgsl(concrete_float_literals(&code).into()) });+ } else {+ crate::gpu::sink_wgpu(e);+ }+ }+ Ok(id_val(c, with(|st| st.slab.insert(Res::Shader(ShaderRes { module })))))+}++/// `code` with an `f` suffix on every abstract float literal (`0.5`, `1.`, `.25`, `2e3`), leaving+/// integers, suffixed literals and digits inside identifiers alone.+pub(crate) fn concrete_float_literals(code: &str) -> String {+ let b = code.as_bytes();+ let mut out = String::with_capacity(code.len() + code.len() / 16);+ let ident = |c: u8| c.is_ascii_alphanumeric() || c == b'_';+ let mut i = 0;+ while i < b.len() {+ let c = b[i];+ let starts = c.is_ascii_digit() || (c == b'.' && i + 1 < b.len() && b[i + 1].is_ascii_digit());+ if starts && (i == 0 || !(ident(b[i - 1]) || b[i - 1] == b'.')) {+ let start = i;+ let hex = c == b'0' && i + 1 < b.len() && (b[i + 1] == b'x' || b[i + 1] == b'X');+ if hex {+ i += 2;+ while i < b.len() && (b[i].is_ascii_hexdigit() || b[i] == b'.' || b[i] == b'p' || b[i] == b'P') {+ i += 1;+ }+ out.push_str(&code[start..i]);+ continue;+ }+ let mut float = false;+ while i < b.len() && b[i].is_ascii_digit() {+ i += 1;+ }+ if i < b.len() && b[i] == b'.' {+ float = true;+ i += 1;+ while i < b.len() && b[i].is_ascii_digit() {+ i += 1;+ }+ }+ if i < b.len() && (b[i] == b'e' || b[i] == b'E') {+ let mut j = i + 1;+ if j < b.len() && (b[j] == b'+' || b[j] == b'-') {+ j += 1;+ }+ if j < b.len() && b[j].is_ascii_digit() {+ float = true;+ i = j;+ while i < b.len() && b[i].is_ascii_digit() {+ i += 1;+ }+ }+ }+ out.push_str(&code[start..i]);+ if float && !(i < b.len() && ident(b[i])) {+ out.push('f');+ }+ continue;+ }+ let ch = code[i..].chars().next().unwrap();+ out.push(ch);+ i += ch.len_utf8();+ }+ out+}++#[cfg(test)]+mod literal_tests {+ use super::concrete_float_literals as f;+ #[test]+ fn floats_become_f32_and_the_rest_stays() {+ assert_eq!(f("smoothstep( 0.1, 0.9, 1.0 )"), "smoothstep( 0.1f, 0.9f, 1.0f )");+ assert_eq!(f("let a = 1. + .5 + 2e3 + 3E-2;"), "let a = 1.f + .5f + 2e3f + 3E-2f;");+ assert_eq!(f("nodeVar3 = vec3<f32>( 0.5h, 1u, 2i, 7 ); x.y1 = tex2D;"), "nodeVar3 = vec3<f32>( 0.5h, 1u, 2i, 7 ); x.y1 = tex2D;");+ assert_eq!(f("0x1p4 + 0xFF + 1.0f + 中文 1.5"), "0x1p4 + 0xFF + 1.0f + 中文 1.5f");+ }+}++/// shaderInfo(id) → JSON [{message, type, lineNum, linePos, offset, length}]+fn shader_info(c: Ctx, a: &[Value]) -> NativeResult {+ let id = u(c, a, 0);+ let info = with(|st| st.slab.shader(id).map(|s| pollster::block_on(s.module.get_compilation_info())));+ let mut out = Vec::new();+ if let Ok(info) = info {+ for m in info.messages {+ let ty = match m.message_type {+ wgpu::CompilationMessageType::Error => "error",+ wgpu::CompilationMessageType::Warning => "warning",+ wgpu::CompilationMessageType::Info => "info",+ };+ let (line, pos, off, len) = m.location.map(|l| (l.line_number, l.line_position, l.offset, l.length)).unwrap_or((0, 0, 0, 0));+ out.push(serde_json::json!({"message": m.message, "type": ty, "lineNum": line, "linePos": pos, "offset": off, "length": len}));+ }+ }+ Ok(c.str(&J::Array(out).to_string()))+}++// ------------------------------------------------------------------------------------- layouts, groups, pipelines++fn create_bind_group_layout(c: Ctx, a: &[Value]) -> NativeResult {+ let g = gpu()?;+ let j = json(c, a, 0)?;+ let entries = desc::bind_group_layout(&j)?;+ let label = j.get("label").and_then(|l| l.as_str()).map(str::to_owned);+ let l = g.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: label.as_deref(), entries: &entries });+ Ok(id_val(c, with(|st| st.slab.insert(Res::BindGroupLayout(l)))))+}++fn create_pipeline_layout(c: Ctx, a: &[Value]) -> NativeResult {+ let g = gpu()?;+ let ids = desc::pipeline_layout(&json(c, a, 0)?)?;+ let r = with(|st| -> Result<u32, String> {+ let empty = if ids.iter().any(|i| i.is_none()) { Some(g.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &[] })) } else { None };+ let mut layouts = Vec::with_capacity(ids.len());+ for id in &ids {+ layouts.push(match id {+ Some(id) => st.slab.bind_group_layout(*id)?,+ None => empty.as_ref().unwrap(),+ });+ }+ let l = g.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &layouts, push_constant_ranges: &[] });+ Ok(st.slab.insert(Res::PipelineLayout(l)))+ });+ match r {+ Ok(id) => Ok(id_val(c, id)),+ Err(e) => invalid(c, format!("createPipelineLayout: {e}")),+ }+}++fn create_bind_group(c: Ctx, a: &[Value]) -> NativeResult {+ let g = gpu()?;+ let spec = desc::bind_group(&json(c, a, 0)?)?;+ let r = with(|st| -> Result<u32, String> {+ let bg = spec.create(&g.device, &st.slab)?;+ Ok(st.slab.insert(Res::BindGroup(bg)))+ });+ match r {+ Ok(id) => Ok(id_val(c, id)),+ Err(e) => invalid(c, format!("createBindGroup: {e}")),+ }+}++fn render_pipeline(c: Ctx, a: &[Value]) -> Result<Result<u32, String>, String> {+ let g = gpu()?;+ let spec = desc::render_pipeline(&json(c, a, 0)?)?;+ Ok(with(|st| -> Result<u32, String> {+ let p = spec.create(&g.device, &st.slab)?;+ Ok(st.slab.insert(Res::RenderPipeline(p)))+ }))+}++fn compute_pipeline(c: Ctx, a: &[Value]) -> Result<Result<u32, String>, String> {+ let g = gpu()?;+ let spec = desc::compute_pipeline(&json(c, a, 0)?)?;+ Ok(with(|st| -> Result<u32, String> {+ let p = spec.create(&g.device, &st.slab)?;+ Ok(st.slab.insert(Res::ComputePipeline(p)))+ }))+}++fn create_render_pipeline(c: Ctx, a: &[Value]) -> NativeResult {+ match render_pipeline(c, a)? {+ Ok(id) => Ok(id_val(c, id)),+ Err(e) => invalid(c, format!("createRenderPipeline: {e}")),+ }+}++fn create_compute_pipeline(c: Ctx, a: &[Value]) -> NativeResult {+ match compute_pipeline(c, a)? {+ Ok(id) => Ok(id_val(c, id)),+ Err(e) => invalid(c, format!("createComputePipeline: {e}")),+ }+}++/// → [id, errorMessage | null]: async creation rejects instead of reporting to error scopes.+fn async_result(c: Ctx, r: (Result<Result<u32, String>, String>, Option<String>)) -> NativeResult {+ let (r, err) = r;+ let r = r?;+ let (id, err) = match r {+ Ok(id) => (id, err),+ Err(e) => (0, Some(e)),+ };+ Ok(c.array(&[id_val(c, id), err.map(|e| c.str(&e)).unwrap_or_else(|| c.null())]))+}++fn create_render_pipeline_async(c: Ctx, a: &[Value]) -> NativeResult {+ async_result(c, gpu::capture(|| render_pipeline(c, a)))+}++fn create_compute_pipeline_async(c: Ctx, a: &[Value]) -> NativeResult {+ async_result(c, gpu::capture(|| compute_pipeline(c, a)))+}++fn get_bind_group_layout(c: Ctx, a: &[Value]) -> NativeResult {+ let (id, index) = (u(c, a, 0), u(c, a, 1));+ let r = with(|st| -> Result<u32, String> {+ let l = match st.slab.get(id) {+ Some(Res::RenderPipeline(p)) => p.get_bind_group_layout(index),+ Some(Res::ComputePipeline(p)) => p.get_bind_group_layout(index),+ _ => return Err(format!("invalid pipeline id {id}")),+ };+ Ok(st.slab.insert(Res::BindGroupLayout(l)))+ });+ match r {+ Ok(id) => Ok(id_val(c, id)),+ Err(e) => invalid(c, format!("getBindGroupLayout: {e}")),+ }+}++fn create_query_set(c: Ctx, a: &[Value]) -> NativeResult {+ let g = gpu()?;+ let ty = match string(c, a, 0).as_str() {+ "occlusion" => wgpu::QueryType::Occlusion,+ "timestamp" => wgpu::QueryType::Timestamp,+ t => return Err(format!("TypeError: '{t}' is not a valid GPUQueryType")),+ };+ let count = u(c, a, 1);+ let set = g.device.create_query_set(&wgpu::QuerySetDescriptor { label: None, ty, count });+ Ok(id_val(c, with(|st| st.slab.insert(Res::QuerySet(QuerySetRes { set, ty, count })))))+}++fn query_set_destroy(c: Ctx, a: &[Value]) -> NativeResult {+ let id = u(c, a, 0);+ // wgpu has no QuerySet::destroy; dropping our handle frees it once the GPU is done+ with(|st| {+ if st.slab.query_set(id).is_ok() {+ st.slab.remove(id);+ }+ });+ Ok(args::undef(c))+}++// ------------------------------------------------------------------------------------- encoding, submission++struct CanvasHooks<'a> {+ canvases: &'a mut Vec<Option<Canvas>>,+}++impl cmd::Hooks for CanvasHooks<'_> {+ fn canvas_use(&mut self, texture: u32, load: bool) -> bool {+ for c in self.canvases.iter_mut().flatten() {+ if c.current == texture && c.pending_clear {+ c.pending_clear = false;+ return load;+ }+ }+ false+ }+}++/// finish(words: Uint32Array, length) → command buffer id. The stream is kept and replayed at+/// submit, into the frame's encoder.+fn finish(c: Ctx, a: &[Value]) -> NativeResult {+ let t0 = Instant::now();+ let n = u(c, a, 1) as usize;+ let Some(bytes) = args::view(c, arg(a, 0)) else { return Err("finish: expected a Uint32Array".into()) };+ if n * 4 > bytes.len() || bytes.as_ptr() as usize % 4 != 0 {+ return Err("finish: bad command stream length".into());+ }+ // SAFETY: the view is a Uint32Array (4-byte aligned, checked above) of at least n words, and+ // nothing calls into JavaScriptCore while the slice is alive.+ let words = unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const u32, n) }.to_vec();+ let id = with(|st| {+ st.stats.finish_ns += t0.elapsed().as_nanos() as u64;+ st.slab.insert(Res::CommandBuffer(Some(words)))+ });+ Ok(id_val(c, id))+}++/// Ids from a Uint32Array (or a plain array) argument.+fn ids(c: Ctx, v: Value, n: usize) -> Vec<u32> {+ if let Some(b) = args::view(c, v) {+ if b.as_ptr() as usize % 4 == 0 && b.len() >= n * 4 {+ // SAFETY: aligned and long enough; read before any further JSC call.+ return unsafe { std::slice::from_raw_parts(b.as_ptr() as *const u32, n) }.to_vec();+ }+ }+ if v.is_array(c) {+ let len = (v.len(c) as usize).min(n);+ return (0..len).map(|i| v.at(c, i as u32).to_u32(c)).collect();+ }+ Vec::new()+}++/// submit(ids, n): replay the command buffers into an encoder of their own, after the writes+/// queued before them; the frame's command buffers reach the queue together at the next flush.+fn submit(c: Ctx, a: &[Value]) -> NativeResult {+ let g = gpu()?;+ let t0 = Instant::now();+ let list = ids(c, arg(a, 0), u(c, a, 1) as usize);+ with(|st| {+ let mut streams = Vec::with_capacity(list.len());+ let mut bad = None;+ for id in &list {+ match st.slab.get_mut(*id) {+ Some(Res::CommandBuffer(cb)) => match cb.take() {+ Some(words) => streams.push(words),+ None => bad = Some(format!("submit: command buffer {id} is invalid or was already submitted")),+ },+ _ => bad = Some(format!("submit: {id} is not a command buffer")),+ }+ st.slab.remove(*id);+ }+ if let Some(e) = bad {+ // WebGPU: one invalid command buffer fails the whole submit+ gpu::validation(e);+ return;+ }+ // the writes queued before this submit land whether or not its command buffers are valid+ let mut writes = st.frame.take();+ if !st.writes.ops.is_empty() {+ encode_writes(st, g, frame_encoder(&mut writes, g));+ }+ if let Some(enc) = writes {+ st.finished.push(enc.finish());+ }+ // its command buffers in an encoder of their own: an invalid one is dropped (and its error+ // reported), so it cannot fail the frame's other command buffers in the batched submit+ let mut enc = g.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });+ g.device.push_error_scope(wgpu::ErrorFilter::Validation);+ let State { slab, canvases, stats, finished, .. } = st;+ let mut counts = cmd::Counts::default();+ let mut hooks = CanvasHooks { canvases };+ let mut decoded = Ok(());+ for words in &streams {+ if let Err(e) = cmd::encode_into(&mut enc, slab, words, &mut hooks, &mut counts) {+ decoded = Err(e);+ break;+ }+ }+ let cb = enc.finish();+ let invalid = pollster::block_on(g.device.pop_error_scope());+ match (decoded, invalid) {+ (Ok(()), None) => finished.push(cb),+ (Err(e), _) => gpu::validation(format!("GPUQueue.submit: {e}")),+ (Ok(()), Some(e)) => crate::gpu::sink_wgpu(e),+ }+ stats.passes += counts.passes as u64;+ stats.draws += counts.draws as u64;+ stats.submit_ns += t0.elapsed().as_nanos() as u64;+ if crate::submit_mode() == crate::SubmitMode::Each {+ flush_writes_now(st, g);+ }+ });+ Ok(args::undef(c))+}++/// writeTexture(tex, mip, x, y, z, aspect, data, byteOffset, bytesPerRow|-1, rowsPerImage|-1, w, h, d)+fn write_texture(c: Ctx, a: &[Value]) -> NativeResult {+ let g = gpu()?;+ let tex = u(c, a, 0);+ let mip = u(c, a, 1);+ let origin = wgpu::Origin3d { x: u(c, a, 2), y: u(c, a, 3), z: u(c, a, 4) };+ let aspect = fmt::aspect_code(u(c, a, 5));+ let data = arg(a, 6);+ let bytes: &[u8] = match args::view(c, data).map(|b| &*b).or_else(|| data.bytes(c).map(|b| &*b)) {+ Some(b) => b,+ None => return Err("TypeError: writeTexture data must be an ArrayBuffer or ArrayBufferView".into()),+ };+ let off = u64a(c, a, 7) as usize;+ let bpr = opt_u64(c, a, 8).map(|v| v as u32);+ let rpi = opt_u64(c, a, 9).map(|v| v as u32);+ let size = wgpu::Extent3d { width: u(c, a, 10), height: u(c, a, 11), depth_or_array_layers: u(c, a, 12) };+ if off > bytes.len() {+ gpu::validation("writeTexture: data offset is past the end of the data");+ return Ok(args::undef(c));+ }+ let src = &bytes[off..];+ with(|st| flush_writes_now(st, g));+ with(|st| match st.slab.texture(tex) {+ Ok(t) => g.queue.write_texture(+ wgpu::TexelCopyTextureInfo { texture: &t.tex, mip_level: mip, origin, aspect },+ src,+ wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: bpr, rows_per_image: rpi },+ size,+ ),+ Err(e) => gpu::validation(format!("writeTexture: {e}")),+ });+ Ok(args::undef(c))+}++/// copyExternal(kind, source, srcWidth, srcHeight, srcX, srcY, flipY, tex, mip, x, y, z, premultiplied, w, h)+/// kind 1: canvas2d bitmap id (2D canvas, image, ImageBitmap); 2: unpremultiplied RGBA bytes+/// (ImageData); 3: a WebGPU canvas context id.+fn copy_external(c: Ctx, a: &[Value]) -> NativeResult {+ let g = gpu()?;+ // the upload goes straight to the queue: put deferred work ahead of it+ with(|st| flush_writes_now(st, g));+ let kind = u(c, a, 0);+ let (sw, sh) = (u(c, a, 2), u(c, a, 3));+ let (sx, sy) = (u(c, a, 4), u(c, a, 5));+ let flip_y = args::truthy(c, arg(a, 6));+ let tex = u(c, a, 7);+ let mip = u(c, a, 8);+ let origin = wgpu::Origin3d { x: u(c, a, 9), y: u(c, a, 10), z: u(c, a, 11) };+ let dst_premultiplied = args::truthy(c, arg(a, 12));+ let size = (u(c, a, 13), u(c, a, 14));+ if size.0 == 0 || size.1 == 0 {+ return Ok(args::undef(c));+ }+ let params = image::CopyParams { origin: (sx, sy), flip_y, size, dst_premultiplied };+ let Some((format, dst)) = with(|st| st.slab.texture(tex).ok().map(|t| (t.format, t.tex.clone()))) else {+ gpu::validation(format!("copyExternalImageToTexture: invalid destination texture {tex}"));+ return Ok(args::undef(c));+ };+ let converted: Option<Result<Vec<u8>, String>> = match kind {+ 1 => canvas2d::with_bitmap(u(c, a, 1), |bm| {+ image::convert(&image::Source { width: bm.width, height: bm.height, stride: bm.stride, data: bm.data, premultiplied: true }, ¶ms, format)+ }),+ 2 => {+ let Some(bytes) = args::view(c, arg(a, 1)) else { return Err("TypeError: bad ImageData".into()) };+ if (sw as usize) * (sh as usize) * 4 > bytes.len() {+ return Err("TypeError: ImageData is smaller than its size".into());+ }+ Some(image::convert(&image::Source { width: sw, height: sh, stride: sw as usize * 4, data: bytes, premultiplied: false }, ¶ms, format))+ }+ 3 => {+ let ctx = u(c, a, 1);+ let src = with(|st| st.canvases.get(ctx as usize).and_then(|x| x.as_ref()).and_then(|cv| cv.content(&st.slab).map(|t| (t, cv.config.as_ref().is_some_and(|k| k.premultiplied)))));+ match src {+ Some((t, premul)) => match image::read_rgba(&g.device, &g.queue, &t, !premul, false) {+ Ok((w, h, px)) => Some(image::convert(&image::Source { width: w, height: h, stride: w as usize * 4, data: &px, premultiplied: premul }, ¶ms, format)),+ Err(e) => Some(Err(e)),+ },+ None => None,+ }+ }+ _ => return Err(format!("TypeError: unknown image source kind {kind}")),+ };+ match converted {+ None => {} // blank source (e.g. a canvas without content): nothing to copy+ Some(Err(e)) => gpu::validation(e),+ Some(Ok(bytes)) => image::upload(&g.queue, &dst, mip, origin, size, format, &bytes),+ }+ let _ = sw;+ Ok(args::undef(c))+}++// ------------------------------------------------------------------------------------- errors++fn push_error_scope(c: Ctx, a: &[Value]) -> NativeResult {+ let f = string(c, a, 0);+ let kind = ErrKind::from_filter(&f).ok_or_else(|| format!("TypeError: '{f}' is not a valid GPUErrorFilter"))?;+ gpu::push_scope(kind);+ Ok(args::undef(c))+}++/// → null | [kind, message]; throws when the stack is empty.+fn pop_error_scope(c: Ctx, _a: &[Value]) -> NativeResult {+ match gpu::pop_scope() {+ Err(()) => Err("OperationError: the error scope stack is empty".into()),+ Ok(None) => Ok(args::null(c)),+ Ok(Some((k, m))) => Ok(c.array(&[args::int_val(c, k as i32), c.str(&m)])),+ }+}++/// reportError(kind, message): errors the JS layer detects (encoder state misuse).+fn report_error(c: Ctx, a: &[Value]) -> NativeResult {+ let kind = match u(c, a, 0) {+ 1 => ErrKind::OutOfMemory,+ 2 => ErrKind::Internal,+ _ => ErrKind::Validation,+ };+ gpu::report(kind, string(c, a, 1));+ Ok(args::undef(c))+}++fn take_errors(c: Ctx, _a: &[Value]) -> NativeResult {+ if !gpu::has_uncaptured() {+ return Ok(args::null(c));+ }+ let mut out = Vec::new();+ for (k, m) in gpu::take_uncaptured() {+ out.push(args::int_val(c, k as i32));+ out.push(c.str(&m));+ }+ Ok(c.array(&out))+}++/// release(ids, n): the page dropped these objects.+fn release(c: Ctx, a: &[Value]) -> NativeResult {+ let list = ids(c, arg(a, 0), u(c, a, 1) as usize);+ with(|st| {+ for id in list {+ // canvas textures are owned by their canvas+ if matches!(st.slab.get(id), Some(Res::Texture(t)) if t.canvas) {+ continue;+ }+ st.slab.remove(id);+ }+ });+ Ok(args::undef(c))+}++// ------------------------------------------------------------------------------------- canvases++fn new_canvas(st: &mut State, cv: Canvas) -> u32 {+ if let Some(i) = st.canvases.iter().skip(1).position(|c| c.is_none()) {+ st.canvases[i + 1] = Some(cv);+ return (i + 1) as u32;+ }+ st.canvases.push(Some(cv));+ (st.canvases.len() - 1) as u32+}++fn canvas_create(c: Ctx, a: &[Value]) -> NativeResult {+ let (w, h) = (u(c, a, 0), u(c, a, 1));+ Ok(id_val(c, with(|st| new_canvas(st, Canvas::new(false, w, h)))))+}++/// The page's window canvas context (created on first use, sized like the target).+fn window_canvas(c: Ctx, _a: &[Value]) -> NativeResult {+ let size = WINDOW.with(|w| w.borrow().target.as_ref().map(|t| (t.texture.width(), t.texture.height())));+ let id = with(|st| {+ if st.window_canvas == 0 {+ let (w, h) = size.unwrap_or((300, 150));+ st.window_canvas = new_canvas(st, Canvas::new(true, w, h));+ }+ st.window_canvas+ });+ Ok(id_val(c, id))+}++/// → [targetWidth, targetHeight, logicalWidth, logicalHeight] (0s without a target)+fn window_info(c: Ctx, _a: &[Value]) -> NativeResult {+ let (w, h, lw, lh) = WINDOW.with(|w| w.borrow().target.as_ref().map(|t| (t.texture.width(), t.texture.height(), t.logical.0, t.logical.1)).unwrap_or((0, 0, 0.0, 0.0)));+ Ok(c.array(&[id_val(c, w), id_val(c, h), args::num_val(c, lw), args::num_val(c, lh)]))+}++fn canvas_resize(c: Ctx, a: &[Value]) -> NativeResult {+ let (id, w, h) = (u(c, a, 0), u(c, a, 1), u(c, a, 2));+ with(|st| {+ let State { canvases, slab, .. } = st;+ if let Some(Some(cv)) = canvases.get_mut(id as usize) {+ if cv.width != w || cv.height != h {+ cv.width = w;+ cv.height = h;+ // the current texture keeps its size until the next frame; a new one is made then+ cv.release_current(slab);+ }+ }+ });+ Ok(args::undef(c))+}++/// canvasConfigure(id, format, usage, premultiplied, viewFormats[])+fn canvas_configure(c: Ctx, a: &[Value]) -> NativeResult {+ let id = u(c, a, 0);+ let f = string(c, a, 1);+ let format = match f.as_str() {+ "bgra8unorm" => wgpu::TextureFormat::Bgra8Unorm,+ "rgba8unorm" => wgpu::TextureFormat::Rgba8Unorm,+ "rgba16float" => wgpu::TextureFormat::Rgba16Float,+ _ => return Err(format!("TypeError: '{f}' is not a supported canvas format")),+ };+ let usage = desc::texture_usage(u(c, a, 2));+ let premultiplied = args::truthy(c, arg(a, 3));+ let mut view_formats = Vec::new();+ if let J::Array(v) = json(c, a, 4)? {+ for s in v.iter().filter_map(|x| x.as_str()) {+ view_formats.push(fmt::texture_format(s).ok_or_else(|| format!("TypeError: '{s}' is not a valid GPUTextureFormat"))?);+ }+ }+ with(|st| {+ let State { canvases, slab, .. } = st;+ if let Some(Some(cv)) = canvases.get_mut(id as usize) {+ let cfg = Config { format, usage, premultiplied, view_formats };+ if cv.config.as_ref() != Some(&cfg) {+ cv.drop_textures(slab);+ cv.config = Some(cfg);+ }+ }+ });+ Ok(args::undef(c))+}++fn canvas_unconfigure(c: Ctx, a: &[Value]) -> NativeResult {+ let id = u(c, a, 0);+ with(|st| {+ let State { canvases, slab, .. } = st;+ if let Some(Some(cv)) = canvases.get_mut(id as usize) {+ cv.drop_textures(slab);+ cv.config = None;+ }+ });+ Ok(args::undef(c))+}++/// getCurrentTexture → texture id (throws "InvalidStateError: …" when unconfigured).+fn canvas_texture(c: Ctx, a: &[Value]) -> NativeResult {+ let g = gpu()?;+ let id = u(c, a, 0);+ let r = WINDOW.with(|w| {+ let w = w.borrow();+ with(|st| {+ let State { canvases, slab, .. } = st;+ match canvases.get_mut(id as usize) {+ Some(Some(cv)) => cv.current_texture(&g.device, slab, w.target.as_ref()),+ _ => Err("unknown canvas context".into()),+ }+ })+ });+ match r {+ Ok(t) => Ok(id_val(c, t)),+ Err(e) => Err(format!("InvalidStateError: {e}")),+ }+}++/// canvasRead(id) → [width, height, Uint8Array RGBA (unpremultiplied, top-down)] or null+fn canvas_read(c: Ctx, a: &[Value]) -> NativeResult {+ let g = gpu()?;+ let id = u(c, a, 0);+ let src = with(|st| {+ flush_writes_now(st, g);+ let cv = st.canvases.get(id as usize)?.as_ref()?;+ let premul = cv.config.as_ref().is_some_and(|k| k.premultiplied);+ cv.content(&st.slab).map(|t| (t, premul))+ });+ let Some((tex, premul)) = src else { return Ok(args::null(c)) };+ match image::read_rgba(&g.device, &g.queue, &tex, !premul, premul) {+ Ok((w, h, px)) => Ok(c.array(&[id_val(c, w), id_val(c, h), c.typed_array(TypedArrayType::Uint8, px.len(), &px)])),+ Err(e) => {+ eprintln!("[webgpu] canvas readback: {e}");+ Ok(args::null(c))+ }+ }+}++fn canvas_release(c: Ctx, a: &[Value]) -> NativeResult {+ let id = u(c, a, 0);+ with(|st| {+ if id as usize >= st.canvases.len() || id == st.window_canvas {+ return;+ }+ if let Some(mut cv) = st.canvases[id as usize].take() {+ cv.drop_textures(&mut st.slab);+ }+ });+ Ok(args::undef(c))+}++fn stats(c: Ctx, _a: &[Value]) -> NativeResult {+ let s = with(|st| {+ let mut s = st.stats;+ s.calls -= 1;+ (s, st.slab.live)+ });+ let (s, live) = s;+ let j = serde_json::json!({+ "calls": s.calls, "finishMs": s.finish_ns as f64 / 1e6, "submitMs": s.submit_ns as f64 / 1e6, "writeMs": s.write_ns as f64 / 1e6,+ "writes": s.writes, "writeBytes": s.write_bytes, "passes": s.passes, "draws": s.draws, "submits": s.submits, "liveObjects": live,+ });+ Ok(c.str(&j.to_string()))+}diff --git a/webgpu/src/lib.rs b/webgpu/src/lib.rsnew file mode 100644index 0000000..eb2d5a2--- /dev/null+++ b/webgpu/src/lib.rs@@ -0,0 +1,429 @@+//! WebGPU (`navigator.gpu`) for the JavaScriptCore runtime, over wgpu 25 on Metal.+//!+//! `runtime/webgpu.ts` defines the JS objects (`GPUDevice`, `GPUBuffer`, …); every native-backed+//! object is an integer id into a per-page slab ([`res::Slab`]). The binding is shaped for+//! three.js's `WebGPURenderer` at native speed:+//!+//! * **Command encoders are recorded in JS.** Pass commands (setPipeline / setBindGroup /+//! setVertexBuffer / draw* / …) and copies append words to a typed-array stream; `finish()`+//! hands the stream over in one call and [`cmd::encode`] replays it into wgpu. A frame costs+//! one native call per command encoder plus one per `queue.submit`, not one per command.+//! * **`queue.writeBuffer` is batched.** Data is copied (read in place from the typed array)+//! into a staging blob; at `submit` the blob goes to the GPU with one `write_buffer` and the+//! writes become `copy_buffer_to_buffer` commands ahead of the submitted command buffers (wgpu+//! allocates a staging buffer per `write_buffer`, which dominates with hundreds of uniform+//! updates per frame).+//! * Creation calls with big dictionaries (pipelines, layouts, bind groups, textures) pass JSON.+//!+//! Errors follow WebGPU: wgpu validation errors land in the page's error scopes or become+//! `uncapturederror` events ([`gpu::report`]); bad input never panics (ranges that wgpu would+//! panic on are validated here first).+//!+//! # Host API+//!+//! ```ignore+//! // once per process, before the first page (Metal, high-performance adapter):+//! let gpu = webgpu::init(&webgpu::GpuOptions::default())?;+//! // the PocketJS UI renderer shares the device:+//! let (device, queue) = (webgpu::device(), webgpu::queue());+//!+//! // per page, next to the other modules:+//! webgpu::install(ctx, native); // defines __native.gpu; runtime.js mounts navigator.gpu+//!+//! // per frame:+//! let frame = surface.get_current_texture()?;+//! webgpu::set_window_target(&frame.texture, logical_w, logical_h);+//! /* __rt.frame(now): the page renders into __pocketGpuCanvas */+//! let out = webgpu::end_window_frame(); // flushes, blits if needed, releases the texture+//! if out.drew { /* composite the UI over frame.texture (out.opaque: ignore its alpha) */ }+//! frame.present();+//! ```+//!+//! The window canvas (`globalThis.__pocketGpuCanvas`) renders **directly** into the host texture+//! when the page configured the host texture's format (see `getPreferredCanvasFormat()`, which+//! returns it), its size matches `canvas.width/height`, and the host texture's usage covers the+//! configured usage (three.js asks for `RENDER_ATTACHMENT | COPY_SRC`). Otherwise the page renders+//! into an intermediate texture that [`end_window_frame`] scales/converts into the target.+//!+//! Headless: [`Offscreen`] owns a target texture and reads it back as RGBA8.+//!+//! The device's uncaptured-error handler belongs to this crate; host renderers that want their+//! own errors should use wgpu error scopes (they take precedence over the handler).+use std::cell::RefCell;+use std::mem::ManuallyDrop;+use std::sync::Mutex;+use std::sync::atomic::{AtomicU64, Ordering};+use std::time::Duration;++use jsc::{Ctx, Value};++mod args;+mod canvas;+pub mod cmd;+pub mod desc;+pub mod fmt;+pub mod gpu;+pub mod image;+mod js;+pub mod res;++pub use gpu::{Gpu, GpuOptions};++use canvas::{Blitter, Canvas, Target};+use res::Slab;++/// Create the process-wide instance/adapter/device/queue (idempotent).+pub fn init(opts: &GpuOptions) -> Result<&'static Gpu, String> {+ gpu::init(opts)+}++fn g() -> &'static Gpu {+ gpu::get().expect("webgpu::init() must be called first")+}+pub fn gpu() -> Option<&'static Gpu> {+ gpu::get()+}+pub fn instance() -> &'static wgpu::Instance {+ &g().instance+}+pub fn adapter() -> &'static wgpu::Adapter {+ &g().adapter+}+pub fn device() -> &'static wgpu::Device {+ &g().device+}+pub fn queue() -> &'static wgpu::Queue {+ &g().queue+}++/// Define `__native.gpu` for a page (call after [`init`]; without a device, pages see+/// `navigator.gpu.requestAdapter()` resolve to null).+pub fn install(c: Ctx, native: Value) {+ args::calibrate(c);+ js::install(c, native);+ rt::on_reset(reset);+}++// ------------------------------------------------------------------------------------- state++#[derive(Default)]+pub(crate) struct Writes {+ pub staging: Vec<u8>,+ /// (buffer id, destination offset, staging offset, size)+ pub ops: Vec<(u32, u64, u32, u32)>,+ /// staging buffers for the batches encoded since the last submit: each batch takes its own,+ /// since every `queue.write_buffer` lands before that submit's commands+ pub pool: Vec<wgpu::Buffer>,+ pub used: usize,+}++/// CPU time spent in the binding (for measurements; see [`stats`]).+#[derive(Default, Clone, Copy, Debug)]+pub struct Stats {+ pub calls: u64,+ pub finish_ns: u64,+ pub submit_ns: u64,+ pub write_ns: u64,+ pub writes: u64,+ pub write_bytes: u64,+ pub passes: u64,+ pub draws: u64,+ pub submits: u64,+}++pub(crate) struct State {+ pub slab: Slab,+ /// canvas contexts by id (index 0 unused)+ pub canvases: Vec<Option<Canvas>>,+ pub window_canvas: u32,+ pub writes: Writes,+ pub stats: Stats,+ /// the encoder a submit replays into (writes queued before it, then its command buffers)+ pub frame: Option<wgpu::CommandEncoder>,+ /// command buffers finished since the last flush, each replayed into its own encoder (an+ /// invalid one fails alone, as in WebGPU), submitted together at the flush+ pub finished: Vec<wgpu::CommandBuffer>,+}++/// Host-side window state (survives page navigations).+pub(crate) struct Window {+ pub target: Option<Target>,+ pub drew: bool,+ pub blitter: Option<Blitter>,+}++// `ManuallyDrop`: wgpu-core touches its own thread-locals when objects drop, which fails inside+// thread-local destructors at process exit. Pages drop their objects on reset; at exit the OS+// reclaims the rest.+thread_local! {+ pub(crate) static STATE: ManuallyDrop<RefCell<State>> = ManuallyDrop::new(RefCell::new(State { slab: Slab::default(), canvases: vec![None], window_canvas: 0, writes: Writes::default(), stats: Stats::default(), frame: None, finished: Vec::new() }));+ pub(crate) static WINDOW: ManuallyDrop<RefCell<Window>> = const { ManuallyDrop::new(RefCell::new(Window { target: None, drew: false, blitter: None })) };+}++/// Completed async operations (token, status 0 ok / 1 failed, buffer id or 0), filled by wgpu+/// callbacks on any thread.+pub(crate) static EVENTS: Mutex<Vec<(f64, u32, u32)>> = Mutex::new(Vec::new());+static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1);++pub(crate) fn token() -> f64 {+ NEXT_TOKEN.fetch_add(1, Ordering::Relaxed) as f64+}++pub(crate) fn push_event(token: f64, status: u32, buffer: u32) {+ EVENTS.lock().unwrap_or_else(|e| e.into_inner()).push((token, status, buffer));+}++fn reset() {+ let dropped = STATE.with(|s| {+ let mut st = s.borrow_mut();+ let canvases = std::mem::replace(&mut st.canvases, vec![None]);+ st.window_canvas = 0;+ st.writes.ops.clear();+ st.writes.staging.clear();+ st.writes.used = 0;+ st.frame = None;+ st.finished.clear();+ let slab = std::mem::take(&mut st.slab);+ (canvases, slab)+ });+ drop(dropped);+ gpu::reset_errors();+ EVENTS.lock().unwrap_or_else(|e| e.into_inner()).clear();+ if let Some(g) = gpu::get() {+ let _ = g.device.poll(wgpu::PollType::Poll);+ }+}++/// Submit queued `writeBuffer`s: returns a command buffer to submit ahead of the page's (or+/// `None` when there was nothing or the writes went straight to the queue).+/// Encode the queued `writeBuffer`s into `enc` as copies from a staging buffer of this submit's+/// pool, so they land between the commands submitted before and after them.+pub(crate) fn encode_writes(st: &mut State, g: &Gpu, enc: &mut wgpu::CommandEncoder) {+ let w = &mut st.writes;+ if w.ops.is_empty() {+ return;+ }+ let t0 = std::time::Instant::now();+ let need = w.staging.len() as u64;+ if w.pool.len() <= w.used {+ w.pool.push(staging_buffer(g, need));+ } else if w.pool[w.used].size() < need {+ w.pool[w.used] = staging_buffer(g, need);+ }+ let staging = &w.pool[w.used];+ w.used += 1;+ g.queue.write_buffer(staging, 0, &w.staging);+ for &(id, dst, src, size) in &w.ops {+ if let Ok(b) = st.slab.buffer(id) {+ enc.copy_buffer_to_buffer(staging, src as u64, &b.buf, dst, size as u64);+ }+ }+ w.ops.clear();+ w.staging.clear();+ st.stats.write_ns += t0.elapsed().as_nanos() as u64;+}++fn staging_buffer(g: &Gpu, need: u64) -> wgpu::Buffer {+ let size = need.next_power_of_two().max(64 * 1024);+ g.device.create_buffer(&wgpu::BufferDescriptor { label: Some("writeBuffer staging"), size, usage: wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false })+}++/// The frame's encoder, created on first use.+pub(crate) fn frame_encoder<'a>(frame: &'a mut Option<wgpu::CommandEncoder>, g: &Gpu) -> &'a mut wgpu::CommandEncoder {+ frame.get_or_insert_with(|| g.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") }))+}++/// Put everything the page submitted and wrote so far on the queue with one `submit`. Called at+/// the end of a frame and before anything that must observe or follow that work in queue order+/// (mapping, work-done, destroy, readback, `writeTexture`, image uploads).+pub(crate) fn flush_writes_now(st: &mut State, g: &Gpu) {+ if st.frame.is_none() && st.finished.is_empty() && st.writes.ops.len() <= 2 {+ // nothing deferred: a couple of writes go straight to the queue+ for &(id, dst, src, size) in &st.writes.ops {+ if let Ok(b) = st.slab.buffer(id) {+ g.queue.write_buffer(&b.buf, dst, &st.writes.staging[src as usize..(src + size) as usize]);+ }+ }+ st.writes.ops.clear();+ st.writes.staging.clear();+ st.writes.used = 0;+ return;+ }+ if !st.writes.ops.is_empty() {+ let mut enc = st.frame.take().unwrap_or_else(|| g.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") }));+ encode_writes(st, g, &mut enc);+ st.frame = Some(enc);+ }+ if let Some(enc) = st.frame.take() {+ st.finished.push(enc.finish());+ }+ if !st.finished.is_empty() {+ let t0 = std::time::Instant::now();+ g.queue.submit(std::mem::take(&mut st.finished));+ st.stats.submits += 1;+ st.stats.submit_ns += t0.elapsed().as_nanos() as u64;+ }+ st.writes.used = 0;+}++/// How submits reach the queue: `batch` (default) replays each submit into its own encoder+/// (an invalid command buffer fails alone, as in WebGPU) and queues the frame's command buffers+/// with one `submit` at the flush; `THREERT_WEBGPU_SUBMIT=each` submits at once, as a browser does.+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum SubmitMode {+ Batch,+ Each,+}++pub(crate) fn submit_mode() -> SubmitMode {+ static MODE: std::sync::OnceLock<SubmitMode> = std::sync::OnceLock::new();+ *MODE.get_or_init(|| {+ match std::env::var("THREERT_WEBGPU_SUBMIT").or_else(|_| std::env::var("POCKET_WEBGPU_SUBMIT")).as_deref() {+ Ok("each") => SubmitMode::Each,+ _ => SubmitMode::Batch,+ }+ })+}++// ------------------------------------------------------------------------------------- host API++/// The texture the window canvas renders into this frame (call before running the page's frame).+/// `logical_*` is the canvas's CSS size (`clientWidth/Height`, `getBoundingClientRect()`).+pub fn set_window_target(texture: &wgpu::Texture, logical_width: f64, logical_height: f64) {+ WINDOW.with(|w| {+ let mut w = w.borrow_mut();+ w.target = Some(Target { texture: texture.clone(), logical: (logical_width, logical_height) });+ w.drew = false;+ });+}++/// Forget the window target (e.g. the window closed); the window canvas keeps rendering+/// into its own texture.+pub fn clear_window_target() {+ WINDOW.with(|w| w.borrow_mut().target = None);+}++/// The result of a window frame.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct WindowFrame {+ /// the page acquired the window canvas's texture this frame (`getCurrentTexture()`): the+ /// target holds a new frame; otherwise its contents are whatever the host left there+ pub drew: bool,+ /// the page configured `alphaMode: "opaque"`: composite the target ignoring its alpha+ pub opaque: bool,+ /// the frame went through the intermediate texture (format/size mismatch)+ pub blitted: bool,+}++/// End of the page's frame: flush pending writes, copy the window canvas into the target if it+/// rendered into an intermediate, and release this frame's textures. Then composite and present.+pub fn end_window_frame() -> WindowFrame {+ let Some(g) = gpu::get() else { return WindowFrame::default() };+ let mut out = WindowFrame::default();+ STATE.with(|s| {+ let mut st = s.borrow_mut();+ flush_writes_now(&mut st, g);+ let wid = st.window_canvas;+ let State { canvases, slab, .. } = &mut *st;+ for (i, c) in canvases.iter_mut().enumerate() {+ let Some(c) = c else { continue };+ if i as u32 == wid {+ out.drew = c.current != 0;+ out.opaque = c.config.as_ref().is_some_and(|c| !c.premultiplied);+ if out.drew && c.owned.as_ref().is_some_and(|o| o.0 == c.current) {+ WINDOW.with(|w| {+ let mut w = w.borrow_mut();+ let Window { target, blitter, .. } = &mut *w;+ if let (Some(t), Some((_, src))) = (target.as_ref(), c.owned.as_ref()) {+ blitter.get_or_insert_with(|| Blitter::new(&g.device)).blit(&g.device, &g.queue, src, &t.texture, out.opaque);+ out.blitted = true;+ }+ });+ }+ }+ c.release_current(slab);+ }+ });+ WINDOW.with(|w| {+ let mut w = w.borrow_mut();+ w.drew = out.drew;+ w.target = None;+ });+ out+}++/// Physical size the page set on the window canvas (`canvas.width/height`), if it has one.+pub fn window_canvas_size() -> Option<(u32, u32)> {+ STATE.with(|s| {+ let st = s.borrow();+ st.canvases.get(st.window_canvas as usize)?.as_ref().map(|c| (c.width, c.height))+ })+}++/// Process completed GPU work (map callbacks, work-done); pages also poll on their own while+/// they wait for something.+pub fn poll() {+ if let Some(g) = gpu::get() {+ let _ = g.device.poll(wgpu::PollType::Poll);+ }+}++/// Block until the GPU finished all submitted work (headless pacing, measurements).+pub fn wait_idle() {+ if let Some(g) = gpu::get() {+ let _ = g.device.poll(wgpu::PollType::Wait);+ }+}++/// Counters since the page started (or since the last [`take_stats`]).+pub fn stats() -> Stats {+ STATE.with(|s| s.borrow().stats)+}+pub fn take_stats() -> Stats {+ STATE.with(|s| std::mem::take(&mut s.borrow_mut().stats))+}++/// An owned render target for headless runs: pass `texture()` to [`set_window_target`] each+/// frame and read the result back with [`Offscreen::read_rgba`].+pub struct Offscreen {+ texture: wgpu::Texture,+}++impl Offscreen {+ /// `format`: normally `Bgra8Unorm` (what a Metal surface uses).+ pub fn new(width: u32, height: u32, format: wgpu::TextureFormat) -> Self {+ let texture = device().create_texture(&wgpu::TextureDescriptor {+ label: Some("offscreen window"),+ size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format,+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING,+ view_formats: &[],+ });+ Offscreen { texture }+ }+ pub fn texture(&self) -> &wgpu::Texture {+ &self.texture+ }+ /// RGBA8, rows top-down; alpha forced to 255 when `opaque`.+ pub fn read_rgba(&self, opaque: bool) -> Result<Vec<u8>, String> {+ if let Some(g) = gpu::get() {+ STATE.with(|s| flush_writes_now(&mut s.borrow_mut(), g));+ }+ image::read_rgba(device(), queue(), &self.texture, opaque, !opaque).map(|(_, _, px)| px)+ }+}++/// Sleep-free wait for pending callbacks (tests).+pub fn poll_for(d: Duration) {+ let t0 = std::time::Instant::now();+ while t0.elapsed() < d {+ poll();+ if !EVENTS.lock().unwrap_or_else(|e| e.into_inner()).is_empty() {+ return;+ }+ std::thread::yield_now();+ }+}diff --git a/webgpu/src/res.rs b/webgpu/src/res.rsnew file mode 100644index 0000000..9abb433--- /dev/null+++ b/webgpu/src/res.rs@@ -0,0 +1,233 @@+//! Per-page GPU objects, addressed from JS by integer ids.+//!+//! Ids are `index | generation << INDEX_BITS`: slots are reused, and a stale id (an object the+//! page dropped whose slot now holds something else) fails the generation check instead of+//! aliasing the new object.+use std::ops::Range;++pub const INDEX_BITS: u32 = 22;+const INDEX_MASK: u32 = (1 << INDEX_BITS) - 1;+const GEN_MASK: u32 = (1 << (32 - INDEX_BITS)) - 1;++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum MapState {+ Unmapped,+ Pending,+ Mapped,+}++pub struct BufferRes {+ pub buf: wgpu::Buffer,+ pub size: u64,+ pub usage: wgpu::BufferUsages,+ pub map: MapState,+ /// mapped range and whether it is writable (MAP_WRITE or mappedAtCreation)+ pub map_range: Range<u64>,+ pub map_write: bool,+ /// token of the pending/current mapAsync (late callbacks of aborted maps are ignored)+ pub map_token: f64,+ pub destroyed: bool,+}++pub struct TextureRes {+ pub tex: wgpu::Texture,+ pub format: wgpu::TextureFormat,+ pub size: wgpu::Extent3d,+ pub mips: u32,+ pub samples: u32,+ pub dimension: wgpu::TextureDimension,+ pub usage: wgpu::TextureUsages,+ /// a canvas texture: cleared lazily on first use in a frame+ pub canvas: bool,+}++pub struct ViewRes {+ pub view: wgpu::TextureView,+ /// id of the texture (for canvas lazy clears)+ pub texture: u32,+}++pub struct ShaderRes {+ pub module: wgpu::ShaderModule,+}++pub struct QuerySetRes {+ pub set: wgpu::QuerySet,+ pub ty: wgpu::QueryType,+ pub count: u32,+}++pub enum Res {+ Buffer(BufferRes),+ Texture(TextureRes),+ View(ViewRes),+ Sampler(wgpu::Sampler),+ BindGroupLayout(wgpu::BindGroupLayout),+ PipelineLayout(wgpu::PipelineLayout),+ BindGroup(wgpu::BindGroup),+ Shader(ShaderRes),+ RenderPipeline(wgpu::RenderPipeline),+ ComputePipeline(wgpu::ComputePipeline),+ QuerySet(QuerySetRes),+ /// `None` once submitted (a command buffer can be submitted once) or when encoding failed+ /// the recorded command stream, replayed into the frame's encoder at submit (`None`: invalid or submitted)+ CommandBuffer(Option<Vec<u32>>),+}++impl Res {+ pub fn kind(&self) -> &'static str {+ match self {+ Res::Buffer(_) => "GPUBuffer",+ Res::Texture(_) => "GPUTexture",+ Res::View(_) => "GPUTextureView",+ Res::Sampler(_) => "GPUSampler",+ Res::BindGroupLayout(_) => "GPUBindGroupLayout",+ Res::PipelineLayout(_) => "GPUPipelineLayout",+ Res::BindGroup(_) => "GPUBindGroup",+ Res::Shader(_) => "GPUShaderModule",+ Res::RenderPipeline(_) => "GPURenderPipeline",+ Res::ComputePipeline(_) => "GPUComputePipeline",+ Res::QuerySet(_) => "GPUQuerySet",+ Res::CommandBuffer(_) => "GPUCommandBuffer",+ }+ }+}++struct Slot {+ generation: u32,+ res: Option<Res>,+}++#[derive(Default)]+pub struct Slab {+ slots: Vec<Slot>,+ free: Vec<u32>,+ pub live: usize,+}++macro_rules! getter {+ ($name:ident, $variant:ident, $ty:ty) => {+ pub fn $name(&self, id: u32) -> Result<&$ty, String> {+ match self.get(id) {+ Some(Res::$variant(x)) => Ok(x),+ Some(other) => Err(format!("object {id} is a {}, expected {}", other.kind(), stringify!($variant))),+ None => Err(format!("invalid or destroyed object id {id} (expected {})", stringify!($variant))),+ }+ }+ };+}++impl Slab {+ pub fn insert(&mut self, res: Res) -> u32 {+ self.live += 1;+ if let Some(index) = self.free.pop() {+ let slot = &mut self.slots[index as usize];+ slot.res = Some(res);+ return index | (slot.generation << INDEX_BITS);+ }+ // index 0 is never handed out, so 0 can mean "none" in the command stream+ if self.slots.is_empty() {+ self.slots.push(Slot { generation: 0, res: None });+ }+ let index = self.slots.len() as u32;+ if index > INDEX_MASK {+ // 4M live objects: the page leaks; hand out the "none" id (uses fail validation)+ self.live -= 1;+ return 0;+ }+ self.slots.push(Slot { generation: 0, res: Some(res) });+ index+ }++ fn slot(&self, id: u32) -> Option<&Slot> {+ let slot = self.slots.get((id & INDEX_MASK) as usize)?;+ if slot.generation != id >> INDEX_BITS {+ return None;+ }+ Some(slot)+ }++ #[inline]+ pub fn get(&self, id: u32) -> Option<&Res> {+ self.slot(id)?.res.as_ref()+ }++ pub fn get_mut(&mut self, id: u32) -> Option<&mut Res> {+ let slot = self.slots.get_mut((id & INDEX_MASK) as usize)?;+ if slot.generation != id >> INDEX_BITS {+ return None;+ }+ slot.res.as_mut()+ }++ pub fn remove(&mut self, id: u32) -> Option<Res> {+ let index = id & INDEX_MASK;+ let slot = self.slots.get_mut(index as usize)?;+ if slot.generation != id >> INDEX_BITS || slot.res.is_none() {+ return None;+ }+ let res = slot.res.take();+ slot.generation = (slot.generation + 1) & GEN_MASK;+ self.free.push(index);+ self.live -= 1;+ res+ }++ pub fn clear(&mut self) {+ self.slots.clear();+ self.free.clear();+ self.live = 0;+ }++ getter!(buffer, Buffer, BufferRes);+ getter!(texture, Texture, TextureRes);+ getter!(view, View, ViewRes);+ getter!(sampler, Sampler, wgpu::Sampler);+ getter!(bind_group_layout, BindGroupLayout, wgpu::BindGroupLayout);+ getter!(pipeline_layout, PipelineLayout, wgpu::PipelineLayout);+ getter!(bind_group, BindGroup, wgpu::BindGroup);+ getter!(shader, Shader, ShaderRes);+ getter!(render_pipeline, RenderPipeline, wgpu::RenderPipeline);+ getter!(compute_pipeline, ComputePipeline, wgpu::ComputePipeline);+ getter!(query_set, QuerySet, QuerySetRes);++ pub fn buffer_mut(&mut self, id: u32) -> Result<&mut BufferRes, String> {+ match self.get_mut(id) {+ Some(Res::Buffer(b)) => Ok(b),+ _ => Err(format!("invalid or destroyed buffer id {id}")),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ // Slab bookkeeping is tested with command buffers in the "encoding failed" state, which+ // need no device.+ fn cb() -> Res {+ Res::CommandBuffer(None)+ }++ #[test]+ fn ids_are_generational() {+ let mut s = Slab::default();+ let a = s.insert(cb());+ assert_ne!(a, 0, "0 is reserved for 'none'");+ let b = s.insert(cb());+ assert!(s.get(a).is_some() && s.get(b).is_some());+ assert_eq!(s.live, 2);+ assert!(s.remove(a).is_some());+ assert!(s.get(a).is_none());+ assert!(s.remove(a).is_none(), "double free is ignored");+ let c = s.insert(cb());+ assert_eq!(c & INDEX_MASK, a & INDEX_MASK, "slot reused");+ assert_ne!(c, a, "with a new generation");+ assert!(s.get(a).is_none(), "the stale id does not alias the new object");+ assert!(s.get(c).is_some());+ assert_eq!(s.live, 2);+ assert!(s.buffer(c).err().unwrap().contains("GPUCommandBuffer"));+ assert!(s.get(0).is_none());+ assert!(s.get(u32::MAX).is_none());+ }+}diff --git a/webgpu/tests/host.rs b/webgpu/tests/host.rsnew file mode 100644index 0000000..64c7f62--- /dev/null+++ b/webgpu/tests/host.rs@@ -0,0 +1,39 @@+//! Host API without a page: shared device, offscreen window target, frame bookkeeping, readback.+use threert_webgpu as webgpu;++#[test]+fn host_frame_without_page() {+ let gpu = match webgpu::init(&webgpu::GpuOptions::default()) {+ Ok(g) => g,+ Err(e) => {+ eprintln!("skipping: {e}");+ return;+ }+ };+ assert!(std::ptr::eq(webgpu::device(), &gpu.device), "one shared device");+ assert!(gpu.js_features.contains(&"core-features-and-limits"));++ let off = webgpu::Offscreen::new(8, 4, wgpu::TextureFormat::Bgra8Unorm);+ // the host draws into the target itself (as the UI renderer would) …+ let view = off.texture().create_view(&Default::default());+ let mut enc = webgpu::device().create_command_encoder(&Default::default());+ enc.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: None,+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {+ view: &view,+ resolve_target: None,+ ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }), store: wgpu::StoreOp::Store },+ })],+ ..Default::default()+ });+ webgpu::queue().submit([enc.finish()]);++ // … and a frame in which no page drew leaves it alone+ webgpu::set_window_target(off.texture(), 8.0, 4.0);+ let frame = webgpu::end_window_frame();+ assert_eq!(frame, webgpu::WindowFrame::default());+ let px = off.read_rgba(true).unwrap();+ assert_eq!(px.len(), 8 * 4 * 4);+ assert_eq!(&px[..4], &[255, 0, 0, 255], "BGRA read back as RGBA");+ assert_eq!(webgpu::window_canvas_size(), None, "no page, no window canvas");+}