@beetlebug/ztk 0.2.0-beta → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/NOTICE CHANGED
@@ -11,6 +11,8 @@ Zig standard library MIT licenses/ztcl/zig-std-MIT.txt
11
11
  musl libc (math) MIT licenses/ztcl/musl-MIT.txt
12
12
  Go (parseFloat, pow) BSD-3-Clause licenses/ztcl/go-BSD-3-Clause.txt
13
13
  ARM optimized-routines MIT or Apache licenses/ztcl/arm-optimized-routines.txt
14
+ libghostty-vt (Ghostty) MIT licenses/ztcl/ghostty-MIT.txt
15
+ uucode (Unicode tables) MIT licenses/ztcl/uucode-MIT.txt
14
16
  Inter font OFL-1.1 licenses/LICENSE-Inter.txt
15
17
 
16
18
  ztcl follows the language rules and the command behavior of Tcl, and ztk
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @beetlebug/ztk
2
2
 
3
- ztk is a replacement for Tk, written in Zig, on the Tcl interpreter ztcl. This package runs ztk in a browser. A Tcl script with Tk commands makes the widgets, and ztk draws them on a canvas with WebGL 2, or with its CPU renderer.
3
+ ztk is a replacement for Tk, written in Zig, on the Tcl interpreter ztcl. This package runs ztk in a browser. A Tcl script with Tk commands makes the widgets, and ztk draws them on a canvas with WebGPU, WebGL 2, or its CPU renderer.
4
4
 
5
5
  - `ztk.wasm` has the interpreter, the widgets, the layout, the style sheets, the fonts (Inter), and the CPU renderer. It is 3.0 MB, or 1.0 MB with gzip.
6
6
  - The page side handles the input, the input methods (IME), the HiDPI scale, the color scheme, and ARIA roles for the widgets.
@@ -38,7 +38,7 @@ app.destroy();
38
38
  ```html
39
39
  <div id="app" style="width: 480px; height: 320px"></div>
40
40
  <script type="module">
41
- import * as ztk from "https://cdn.jsdelivr.net/npm/@beetlebug/ztk@0.2.0-beta/ztk.js";
41
+ import * as ztk from "https://cdn.jsdelivr.net/npm/@beetlebug/ztk@1.0.0-beta.1/ztk.js";
42
42
 
43
43
  const app = await ztk.mount(document.getElementById("app"), {
44
44
  script: "button .b -text Hello; pack .b -padx 8 -pady 8",
@@ -67,7 +67,7 @@ The tests of the package run Vite 7. Webpack 5 and Rollup also have support for
67
67
  | `files` | Files by name for `ztk::style load`, for example `{ "app.css": text }`. |
68
68
  | `theme` | `"auto"` (the default) follows `prefers-color-scheme` of the page. `"light"` and `"dark"` set the scheme. |
69
69
  | `size` | `"auto"` (the default): the window starts with the size of the element and then gets the size of its widgets, as a Tk toplevel does. `"fill"`: the window follows the size of the element, so give the element a size. `[width, height]`: a fixed logical size, which the canvas shows at the CSS size that the page gives it. |
70
- | `renderer` | `"auto"` (the default), `"webgl2"`, `"cpu"`, or `"webgpu"`. `"auto"` selects WebGL 2, and the CPU renderer when the browser has no WebGL 2. This version has no WebGPU renderer, so `"webgpu"` rejects. |
70
+ | `renderer` | `"auto"` (the default), `"webgl2"`, `"cpu"`, or `"webgpu"`. `"auto"` selects WebGPU when the browser gives an adapter, else WebGL 2, else the CPU renderer. A forced renderer that the browser does not have rejects. |
71
71
  | `scale` | The device pixels in one logical pixel. The default is `devicePixelRatio`, and a change of it gives a new scale. |
72
72
  | `module` | A module from `compileModule()`, so that many apps on one page compile `ztk.wasm` one time. |
73
73
  | `wasm` | The URL of `ztk.wasm`. The default is the file next to `ztk.js`. |
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Mitchell Hashimoto, Ghostty contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,20 @@
1
+ simdjson
2
+
3
+ The JSON parser of ztcl (src/json/) implements the simdjson algorithm
4
+ in Zig. simdjson is at https://github.com/simdjson/simdjson. Its license
5
+ is the Apache License 2.0 or the MIT license, at the choice of the user.
6
+
7
+ ztcl copies no code, no lookup table, and no constant set from
8
+ simdjson. The Zig code is new, written from the descriptions of the
9
+ method in these papers:
10
+
11
+ - Geoff Langdale and Daniel Lemire, "Parsing Gigabytes of JSON per
12
+ Second", The VLDB Journal 28 (2019).
13
+ - John Keiser and Daniel Lemire, "Validating UTF-8 In Less Than One
14
+ Instruction Per Byte", Software: Practice and Experience 51 (2021).
15
+ - Daniel Lemire, "Number Parsing at a Gigabyte per Second", Software:
16
+ Practice and Experience 51 (2021). ztcl uses the Eisel-Lemire method
17
+ through std.fmt.parseFloat of the Zig standard library.
18
+
19
+ docs/references/stdlib.md says what each part of src/json/ takes from
20
+ each source.
@@ -0,0 +1,39 @@
1
+ UNICODE LICENSE V3
2
+
3
+ COPYRIGHT AND PERMISSION NOTICE
4
+
5
+ Copyright © 1991-2026 Unicode, Inc.
6
+
7
+ NOTICE TO USER: Carefully read the following legal agreement. BY
8
+ DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
9
+ SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
10
+ TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
11
+ DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a
14
+ copy of data files and any associated documentation (the "Data Files") or
15
+ software and any associated documentation (the "Software") to deal in the
16
+ Data Files or Software without restriction, including without limitation
17
+ the rights to use, copy, modify, merge, publish, distribute, and/or sell
18
+ copies of the Data Files or Software, and to permit persons to whom the
19
+ Data Files or Software are furnished to do so, provided that either (a)
20
+ this copyright and permission notice appear with all copies of the Data
21
+ Files or Software, or (b) this copyright and permission notice appear in
22
+ associated Documentation.
23
+
24
+ THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
25
+ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
27
+ THIRD PARTY RIGHTS.
28
+
29
+ IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
30
+ BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
31
+ OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
32
+ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
33
+ ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
34
+ FILES OR SOFTWARE.
35
+
36
+ Except as contained in this notice, the name of a copyright holder shall
37
+ not be used in advertising or otherwise to promote the sale, use or other
38
+ dealings in these Data Files or Software without prior written
39
+ authorization of the copyright holder.
@@ -0,0 +1,30 @@
1
+ # uucode license
2
+
3
+ MIT License
4
+
5
+ Copyright (c) 2026 Jacob Sandlund
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
8
+ this software and associated documentation files (the "Software"), to deal in
9
+ the Software without restriction, including without limitation the rights to
10
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
11
+ of the Software, and to permit persons to whom the Software is furnished to do
12
+ so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
24
+
25
+ ## Other licenses
26
+
27
+ See [./licenses](./licenses) for licenses of code being used in the repo:
28
+
29
+ * [LICENSE_Bjoern_Hoehrmann](./licenses/LICENSE_Bjoern_Hoehrmann)
30
+ * [LICENSE_unicode](./licenses/LICENSE_unicode)
@@ -0,0 +1,8 @@
1
+ Copyright © 2019-2024 the Contributors to the WASI Specification, published
2
+ by the [WebAssembly Community Group][cg] under the
3
+ [W3C Community Contributor License Agreement (CLA)][cla]. A human-readable
4
+ [summary][summary] is available.
5
+
6
+ [cg]: https://www.w3.org/community/webassembly/
7
+ [cla]: https://www.w3.org/community/about/agreements/cla/
8
+ [summary]: https://www.w3.org/community/about/agreements/cla-deed/
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@beetlebug/ztk",
3
- "version": "0.2.0-beta",
3
+ "version": "1.0.0-beta.1",
4
4
  "description": "Tk widgets for the web: Tcl scripts with Tk commands, drawn by ztk in WebAssembly",
5
5
  "license": "BSD-2-Clause",
6
- "author": "The ztk authors",
6
+ "author": "The ztk authors <opensource@beetlebug.org>",
7
7
  "homepage": "https://beetlebug.org/ztk/",
8
8
  "repository": {
9
9
  "type": "git",
@@ -32,6 +32,7 @@
32
32
  },
33
33
  "files": [
34
34
  "ztk.js",
35
+ "webgpu.js",
35
36
  "ztk.wasm",
36
37
  "ztk.d.ts",
37
38
  "NOTICE",
package/webgpu.js ADDED
@@ -0,0 +1,372 @@
1
+ // SPDX-License-Identifier: BSD-2-Clause
2
+ // The WebGPU renderer of the web build. It draws the scene of a frame in
3
+ // one render pass: the quads go into a storage buffer, and one instanced
4
+ // draw of a triangle strip with 4 vertices draws them. The vertex stage
5
+ // reads its quad by the instance index and covers the quad rectangle,
6
+ // with a margin for the anti-aliased edge and the shadow blur, cut to the
7
+ // clip. The fragment stage has the formulas of src/render/renderer.zig:
8
+ // roundedDistance, boxCoverage, shadowCoverage, and gradientT. It gives a
9
+ // premultiplied color, and the blend is ONE and ONE_MINUS_SRC_ALPHA on a
10
+ // UNORM target, so the result equals "source over" on the sRGB values of
11
+ // the CPU renderer. The glyph atlas is an r8unorm texture of 1024 by 1024
12
+ // texels.
13
+ //
14
+ // The canvas color space is sRGB. Where the display has the P3 gamut, the
15
+ // canvas is display-p3 and the vertex stage converts each sRGB color of
16
+ // the scene to P3: the sRGB curve to linear, the 3 by 3 matrix of the two
17
+ // primaries, and the curve back. The blend then works on P3 values.
18
+ //
19
+ // All canvases of a page share one GPUDevice. When the device is lost,
20
+ // each renderer asks for a new device, makes its pipeline again, sets the
21
+ // atlas version back so that the next draw uploads the atlas again, and
22
+ // calls its `restored` function, which draws the last scene again.
23
+ //
24
+ // The renderer calls its `failed` function when the GPU gives an error
25
+ // or when no new device comes after a loss. The page then renders with
26
+ // WebGL 2 (web/ztk.js). An error in the pipeline at the start makes
27
+ // createWebGPU reject before it gets the context of the canvas.
28
+
29
+ const QUAD_BYTES = 160;
30
+ const ATLAS = 1024;
31
+
32
+ const WGSL = /* wgsl */ `
33
+ struct Quad {
34
+ rect: vec4f, clip: vec4f, radii: vec4f, border: vec4f,
35
+ fill: vec4f, fill2: vec4f, border_color: vec4f, uv: vec4f, params: vec4f,
36
+ kind: u32, pad0: u32, pad1: u32, pad2: u32,
37
+ };
38
+ struct Uniforms { size: vec2f, p3: u32, pad: u32 };
39
+ @group(0) @binding(0) var<uniform> u: Uniforms;
40
+ @group(0) @binding(1) var<storage, read> quads: array<Quad>;
41
+ @group(0) @binding(2) var atlas: texture_2d<f32>;
42
+ @group(0) @binding(3) var images: texture_2d<f32>;
43
+
44
+ struct V {
45
+ @builtin(position) pos: vec4f,
46
+ @location(0) @interpolate(flat) idx: u32,
47
+ @location(1) @interpolate(flat) fill: vec4f,
48
+ @location(2) @interpolate(flat) fill2: vec4f,
49
+ @location(3) @interpolate(flat) border_color: vec4f,
50
+ };
51
+
52
+ fn toLinear(c: f32) -> f32 {
53
+ if (c <= 0.04045) { return c / 12.92; }
54
+ return pow((c + 0.055) / 1.055, 2.4);
55
+ }
56
+ fn toCurve(c: f32) -> f32 {
57
+ if (c <= 0.0031308) { return c * 12.92; }
58
+ return 1.055 * pow(c, 1.0 / 2.4) - 0.055;
59
+ }
60
+ // An sRGB color to Display P3, with the alpha kept.
61
+ fn toP3(c: vec4f) -> vec4f {
62
+ let l = vec3f(toLinear(c.r), toLinear(c.g), toLinear(c.b));
63
+ let p = vec3f(
64
+ 0.8224621 * l.r + 0.1775380 * l.g,
65
+ 0.0331941 * l.r + 0.9668058 * l.g,
66
+ 0.0170827 * l.r + 0.0723974 * l.g + 0.9105199 * l.b);
67
+ return vec4f(toCurve(p.r), toCurve(p.g), toCurve(p.b), c.a);
68
+ }
69
+
70
+ @vertex fn vs(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> V {
71
+ let q = quads[ii];
72
+ var pad = 0.0;
73
+ if (q.kind == 0u) { pad = 1.0; }
74
+ if (q.kind == 1u) { pad = max(q.params.z, 1.0) + 1.0; }
75
+ let lo = max(q.rect.xy - pad, q.clip.xy);
76
+ let hi = max(min(q.rect.xy + q.rect.zw + pad, q.clip.xy + q.clip.zw), lo);
77
+ let corner = vec2f(f32(vi & 1u), f32(vi >> 1u));
78
+ let ndc = mix(lo, hi, corner) / u.size * 2.0 - 1.0;
79
+ var v: V;
80
+ v.pos = vec4f(ndc.x, -ndc.y, 0.0, 1.0);
81
+ v.idx = ii;
82
+ v.fill = q.fill;
83
+ v.fill2 = q.fill2;
84
+ v.border_color = q.border_color;
85
+ if (u.p3 != 0u) {
86
+ v.fill = toP3(q.fill);
87
+ v.fill2 = toP3(q.fill2);
88
+ v.border_color = toP3(q.border_color);
89
+ }
90
+ return v;
91
+ }
92
+
93
+ fn clamp01(x: f32) -> f32 { return clamp(x, 0.0, 1.0); }
94
+
95
+ fn roundedDistance(p: vec2f, rect: vec4f, radii: vec4f) -> f32 {
96
+ let hw = rect.z * 0.5;
97
+ let hh = rect.w * 0.5;
98
+ let dx = p.x - (rect.x + hw);
99
+ let dy = p.y - (rect.y + hh);
100
+ let limit = min(hw, hh);
101
+ var r = radii.z;
102
+ if (dy < 0.0) {
103
+ if (dx < 0.0) { r = radii.x; } else { r = radii.y; }
104
+ } else if (dx < 0.0) {
105
+ r = radii.w;
106
+ }
107
+ r = min(r, limit);
108
+ let qx = abs(dx) - hw + r;
109
+ let qy = abs(dy) - hh + r;
110
+ let mx = max(qx, 0.0);
111
+ let my = max(qy, 0.0);
112
+ return min(max(qx, qy), 0.0) + sqrt(mx * mx + my * my) - r;
113
+ }
114
+
115
+ fn boxCoverage(q: Quad, p: vec2f) -> vec2f {
116
+ let outer = clamp01(0.5 - roundedDistance(p, q.rect, q.radii));
117
+ let bt = q.border.x;
118
+ let br = q.border.y;
119
+ let bb = q.border.z;
120
+ let bl = q.border.w;
121
+ if (bt == 0.0 && br == 0.0 && bb == 0.0 && bl == 0.0) { return vec2f(outer, 0.0); }
122
+ let ir = vec4f(q.rect.x + bl, q.rect.y + bt, q.rect.z - bl - br, q.rect.w - bt - bb);
123
+ if (ir.z <= 0.0 || ir.w <= 0.0) { return vec2f(0.0, outer); }
124
+ let irad = vec4f(max(q.radii.x - max(bt, bl), 0.0), max(q.radii.y - max(bt, br), 0.0),
125
+ max(q.radii.z - max(bb, br), 0.0), max(q.radii.w - max(bb, bl), 0.0));
126
+ let inner = clamp01(0.5 - roundedDistance(p, ir, irad));
127
+ return vec2f(inner, max(outer - inner, 0.0));
128
+ }
129
+
130
+ fn shadowCoverage(q: Quad, p: vec2f) -> f32 {
131
+ let d = roundedDistance(p, q.rect, q.radii);
132
+ let t = clamp01(0.5 - d / max(q.params.z, 1.0));
133
+ return t * t * (3.0 - 2.0 * t);
134
+ }
135
+
136
+ fn gradientT(q: Quad, p: vec2f) -> f32 {
137
+ let dx = q.params.x;
138
+ let dy = q.params.y;
139
+ let len = abs(q.rect.z * dx) + abs(q.rect.w * dy);
140
+ if (len <= 0.0) { return 0.0; }
141
+ return clamp01(((p.x - (q.rect.x + q.rect.z * 0.5)) * dx + (p.y - (q.rect.y + q.rect.w * 0.5)) * dy) / len + 0.5);
142
+ }
143
+
144
+ @fragment fn fs(v: V) -> @location(0) vec4f {
145
+ let q = quads[v.idx];
146
+ // The position has the pixel center (x + 0.5, y + 0.5), from the top left.
147
+ let p = v.pos.xy;
148
+ if (p.x < q.clip.x || p.y < q.clip.y || p.x >= q.clip.x + q.clip.z || p.y >= q.clip.y + q.clip.w) { discard; }
149
+ let opacity = q.params.w;
150
+ if (q.kind == 0u) {
151
+ let c = boxCoverage(q, p);
152
+ var col = v.fill;
153
+ if (any(q.fill != q.fill2)) { col = mix(v.fill, v.fill2, gradientT(q, p)); }
154
+ let fa = col.a * c.x * opacity;
155
+ let ba = v.border_color.a * c.y * opacity;
156
+ return vec4f(v.border_color.rgb * ba + col.rgb * fa * (1.0 - ba), 1.0 - (1.0 - fa) * (1.0 - ba));
157
+ }
158
+ if (q.kind == 1u) {
159
+ let a = v.fill.a * shadowCoverage(q, p) * opacity;
160
+ return vec4f(v.fill.rgb * a, a);
161
+ }
162
+ if (q.kind == 2u) {
163
+ let t = vec2i(q.uv.xy) + vec2i(floor(p)) - vec2i(q.rect.xy);
164
+ let a = v.fill.a * textureLoad(atlas, t, 0).r * opacity;
165
+ return vec4f(v.fill.rgb * a, a);
166
+ }
167
+ if (q.kind == 3u) {
168
+ // The bilinear filter of the CPU renderer, on four texels of the image page.
169
+ let uu = clamp(q.uv.xy + (p - q.rect.xy) * (q.uv.zw / q.rect.zw) - 0.5, vec2f(0.0), vec2f(1022.0));
170
+ let f = uu - floor(uu);
171
+ let i = vec2i(floor(uu));
172
+ var c = mix(mix(textureLoad(images, i, 0), textureLoad(images, i + vec2i(1, 0), 0), f.x),
173
+ mix(textureLoad(images, i + vec2i(0, 1), 0), textureLoad(images, i + vec2i(1, 1), 0), f.x), f.y);
174
+ if (u.p3 != 0u) { c = toP3(c); }
175
+ let a = c.a * opacity;
176
+ return vec4f(c.rgb * a, a);
177
+ }
178
+ discard;
179
+ return vec4f(0.0);
180
+ }
181
+ `;
182
+
183
+ // One device for the page.
184
+ let devicePromise = null;
185
+ const lossListeners = new Set();
186
+
187
+ async function requestDevice() {
188
+ if (!globalThis.navigator?.gpu) return null;
189
+ // A browser that gives no answer in 3 seconds counts as one with no adapter.
190
+ const late = new Promise((res) => setTimeout(() => res(null), 3000));
191
+ const adapter = await Promise.race([navigator.gpu.requestAdapter(), late]);
192
+ if (!adapter) return null;
193
+ const device = await adapter.requestDevice();
194
+ device.lost.then((info) => {
195
+ devicePromise = null;
196
+ for (const f of [...lossListeners]) f(info);
197
+ });
198
+ return device;
199
+ }
200
+
201
+ /// The shared device of the page, or null when the browser gives no adapter.
202
+ export function gpuDevice() {
203
+ devicePromise ??= requestDevice().catch(() => null);
204
+ return devicePromise;
205
+ }
206
+
207
+ /// True when the browser gives a WebGPU adapter and a device.
208
+ export async function webgpuAvailable() {
209
+ return (await gpuDevice()) != null;
210
+ }
211
+
212
+ function srgbToP3(c) {
213
+ const lin = (x) => (x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4);
214
+ const cur = (x) => (x <= 0.0031308 ? x * 12.92 : 1.055 * x ** (1 / 2.4) - 0.055);
215
+ const [r, g, b] = [lin(c[0]), lin(c[1]), lin(c[2])];
216
+ return [cur(0.8224621 * r + 0.177538 * g), cur(0.0331941 * r + 0.9668058 * g), cur(0.0170827 * r + 0.0723974 * g + 0.9105199 * b), c[3]];
217
+ }
218
+
219
+ /// Makes the WebGPU renderer for a canvas, or gives null when no adapter
220
+ /// exists. `ex` has the exports of ztk.wasm. `options.colorSpace` forces
221
+ /// "srgb" or "display-p3". `options.restored` runs after a device loss,
222
+ /// when the renderer can draw again. `options.failed(reason)` runs when
223
+ /// the renderer cannot draw.
224
+ export async function createWebGPU(canvas, ex, options = {}) {
225
+ let device = await gpuDevice();
226
+ if (!device) return null;
227
+ const format = navigator.gpu.getPreferredCanvasFormat();
228
+ const p3 = (options.colorSpace ?? (globalThis.matchMedia?.("(color-gamut: p3)").matches ? "display-p3" : "srgb")) === "display-p3";
229
+ let pipeline, uniforms, atlasTex, imageTex, quadBuf, quadCap = 0, bindGroup = null;
230
+ let atlasVersion = -1, configured = "", ready = false, closed = false;
231
+ let restoring = null;
232
+
233
+ const build = () => {
234
+ const module = device.createShaderModule({ code: WGSL });
235
+ pipeline = device.createRenderPipeline({
236
+ layout: "auto",
237
+ vertex: { module, entryPoint: "vs" },
238
+ fragment: {
239
+ module, entryPoint: "fs",
240
+ targets: [{ format, blend: {
241
+ color: { srcFactor: "one", dstFactor: "one-minus-src-alpha", operation: "add" },
242
+ alpha: { srcFactor: "one", dstFactor: "one-minus-src-alpha", operation: "add" },
243
+ } }],
244
+ },
245
+ primitive: { topology: "triangle-strip" },
246
+ });
247
+ uniforms = device.createBuffer({ size: 16, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
248
+ atlasTex = device.createTexture({ size: [ATLAS, ATLAS], format: "r8unorm", usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST });
249
+ imageTex = device.createTexture({ size: [ATLAS, ATLAS], format: "rgba8unorm", usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST });
250
+ quadCap = 0;
251
+ bindGroup = null;
252
+ atlasVersion = -1;
253
+ configured = "";
254
+ ready = true;
255
+ };
256
+ device.pushErrorScope("validation");
257
+ device.pushErrorScope("internal");
258
+ build();
259
+ const errors = [await device.popErrorScope(), await device.popErrorScope()].filter(Boolean);
260
+ if (errors.length > 0) throw new Error(`the pipeline gave an error: ${errors[0].message}`);
261
+ const ctx = canvas.getContext("webgpu");
262
+ if (!ctx) return null;
263
+ const onError = (e) => { if (!closed) options.failed?.(`gave an error: ${e.error?.message}`); };
264
+ let errorDevice = device;
265
+ errorDevice.addEventListener("uncapturederror", onError);
266
+
267
+ const configure = (w, h) => {
268
+ const key = `${w}x${h}`;
269
+ if (configured === key) return;
270
+ configured = key;
271
+ ctx.configure({ device, format, alphaMode: "opaque", colorSpace: p3 ? "display-p3" : "srgb" });
272
+ };
273
+
274
+ const onLoss = (info) => {
275
+ if (closed) return;
276
+ ready = false;
277
+ restoring = (async () => {
278
+ device = await gpuDevice();
279
+ if (closed) return false;
280
+ if (!device) {
281
+ options.failed?.("lost its device");
282
+ return false;
283
+ }
284
+ errorDevice.removeEventListener("uncapturederror", onError);
285
+ errorDevice = device;
286
+ errorDevice.addEventListener("uncapturederror", onError);
287
+ build();
288
+ options.restored?.();
289
+ return true;
290
+ })();
291
+ };
292
+ lossListeners.add(onLoss);
293
+
294
+ const draw = (n) => {
295
+ if (!ready) return;
296
+ const w = canvas.width, h = canvas.height;
297
+ configure(w, h);
298
+ const v = ex.ztk_atlas_version();
299
+ if (v !== atlasVersion) {
300
+ const p = ex.ztk_atlas();
301
+ if (p) {
302
+ device.queue.writeTexture({ texture: atlasTex }, new Uint8Array(ex.memory.buffer, p, ATLAS * ATLAS), { bytesPerRow: ATLAS }, [ATLAS, ATLAS]);
303
+ const ip = ex.ztk_images ? ex.ztk_images() : 0;
304
+ if (ip) device.queue.writeTexture({ texture: imageTex }, new Uint8Array(ex.memory.buffer, ip, ATLAS * ATLAS * 4), { bytesPerRow: ATLAS * 4 }, [ATLAS, ATLAS]);
305
+ atlasVersion = v;
306
+ }
307
+ }
308
+ if (n > quadCap) {
309
+ quadBuf?.destroy();
310
+ quadCap = Math.max(256, 2 ** Math.ceil(Math.log2(n)));
311
+ quadBuf = device.createBuffer({ size: quadCap * QUAD_BYTES, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });
312
+ bindGroup = null;
313
+ }
314
+ if (!quadBuf) {
315
+ quadCap = 256;
316
+ quadBuf = device.createBuffer({ size: quadCap * QUAD_BYTES, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });
317
+ }
318
+ bindGroup ??= device.createBindGroup({
319
+ layout: pipeline.getBindGroupLayout(0),
320
+ entries: [
321
+ { binding: 0, resource: { buffer: uniforms } },
322
+ { binding: 1, resource: { buffer: quadBuf } },
323
+ { binding: 2, resource: atlasTex.createView() },
324
+ { binding: 3, resource: imageTex.createView() },
325
+ ],
326
+ });
327
+ const u = new ArrayBuffer(16);
328
+ new Float32Array(u, 0, 2).set([w, h]);
329
+ new Uint32Array(u, 8, 1)[0] = p3 ? 1 : 0;
330
+ device.queue.writeBuffer(uniforms, 0, u);
331
+ if (n > 0) device.queue.writeBuffer(quadBuf, 0, ex.memory.buffer, ex.ztk_quads(), n * QUAD_BYTES);
332
+ let c = Array.from(new Float32Array(ex.memory.buffer, ex.ztk_clear_color(), 4));
333
+ if (p3) c = srgbToP3(c);
334
+ const enc = device.createCommandEncoder();
335
+ const pass = enc.beginRenderPass({
336
+ colorAttachments: [{ view: ctx.getCurrentTexture().createView(), loadOp: "clear", storeOp: "store", clearValue: { r: c[0], g: c[1], b: c[2], a: 1 } }],
337
+ });
338
+ if (n > 0) {
339
+ pass.setPipeline(pipeline);
340
+ pass.setBindGroup(0, bindGroup);
341
+ pass.draw(4, n);
342
+ }
343
+ pass.end();
344
+ device.queue.submit([enc.finish()]);
345
+ };
346
+
347
+ return {
348
+ name: "webgpu",
349
+ colorSpace: p3 ? "display-p3" : "srgb",
350
+ draw,
351
+ /// Destroys the device, as a lost GPU does, and waits until the renderer draws again.
352
+ async lose() {
353
+ const lost = new Promise((res) => {
354
+ const f = () => { lossListeners.delete(f); res(); };
355
+ lossListeners.add(f);
356
+ });
357
+ device.destroy();
358
+ await lost;
359
+ return (await restoring) ?? false;
360
+ },
361
+ destroy() {
362
+ closed = true;
363
+ lossListeners.delete(onLoss);
364
+ errorDevice.removeEventListener("uncapturederror", onError);
365
+ try { ctx.unconfigure(); } catch (_) { /* the device can be lost */ }
366
+ quadBuf?.destroy();
367
+ uniforms?.destroy();
368
+ atlasTex?.destroy();
369
+ imageTex?.destroy();
370
+ },
371
+ };
372
+ }
package/ztk.d.ts CHANGED
@@ -36,7 +36,7 @@ export interface MountOptions {
36
36
  theme?: Theme;
37
37
  /** The size of the window. The default is "auto". */
38
38
  size?: Size;
39
- /** The renderer. The default is "auto". This version has no WebGPU renderer. */
39
+ /** The renderer. The default is "auto": WebGPU, else WebGL 2, else the CPU renderer. */
40
40
  renderer?: Renderer;
41
41
  /** The device pixels in one logical pixel. The default is `devicePixelRatio`. */
42
42
  scale?: number;
package/ztk.js CHANGED
@@ -2,14 +2,17 @@
2
2
  // The page side of ztk in a browser. It loads ztk.wasm, gives it the
3
3
  // clock, the size, the scale (devicePixelRatio), the color scheme, the
4
4
  // reduced motion setting, and the input of the canvas, and draws each
5
- // scene with WebGL 2, or with the CPU renderer of ztk.wasm and a 2D
6
- // context. mount() is the API for a page, and start() is the API under
7
- // it. The shaders have the formulas of the CPU renderer
5
+ // scene with WebGPU (web/webgpu.js), WebGL 2, or the CPU renderer of
6
+ // ztk.wasm and a 2D context. mount() is the API for a page, and start()
7
+ // is the API under it. The query parameter `?renderer=` with "webgpu",
8
+ // "webgl2", or "cpu" forces a renderer, as the option does. The shaders have the formulas of the CPU renderer
8
9
  // (src/render/renderer.zig) and of src/render/shaders/quad.frag. A
9
10
  // hidden text area gets the keyboard, so that text input and input
10
11
  // methods work. A list of hidden elements with ARIA roles follows the
11
12
  // widgets, from ztk_a11y.
12
13
 
14
+ import { createWebGPU } from "./webgpu.js";
15
+
13
16
  const VS = `#version 300 es
14
17
  layout(location=0) in vec4 a_rect;
15
18
  layout(location=1) in vec4 a_clip;
@@ -47,6 +50,7 @@ flat in vec4 f_fill; flat in vec4 f_fill2; flat in vec4 f_border_color; flat in
47
50
  flat in vec4 f_params; flat in uint f_kind;
48
51
  uniform vec2 u_target;
49
52
  uniform sampler2D u_atlas;
53
+ uniform sampler2D u_images;
50
54
  out vec4 out_color;
51
55
  float clamp01(float x) { return clamp(x, 0.0, 1.0); }
52
56
  float roundedDistance(vec2 p, vec4 rect, vec4 radii) {
@@ -98,6 +102,15 @@ void main() {
98
102
  ivec2 t = ivec2(f_uv.xy) + ivec2(floor(p)) - ivec2(f_rect.xy);
99
103
  float a = f_fill.a * texelFetch(u_atlas, t, 0).r * opacity;
100
104
  out_color = vec4(f_fill.rgb * a, a);
105
+ } else if (f_kind == 3u) {
106
+ // The bilinear filter of the CPU renderer, on four texels of the image page.
107
+ vec2 u = clamp(f_uv.xy + (p - f_rect.xy) * (f_uv.zw / f_rect.zw) - 0.5, 0.0, 1022.0);
108
+ vec2 f = u - floor(u);
109
+ ivec2 i = ivec2(floor(u));
110
+ vec4 c = mix(mix(texelFetch(u_images, i, 0), texelFetch(u_images, i + ivec2(1, 0), 0), f.x),
111
+ mix(texelFetch(u_images, i + ivec2(0, 1), 0), texelFetch(u_images, i + ivec2(1, 1), 0), f.x), f.y);
112
+ float a = c.a * opacity;
113
+ out_color = vec4(c.rgb * a, a);
101
114
  } else {
102
115
  discard;
103
116
  }
@@ -153,8 +166,14 @@ export function compileModule(url) {
153
166
  return compiled.get(u);
154
167
  }
155
168
 
169
+ let logged = false;
170
+
156
171
  /// The renderers that this file has, in the order of "auto".
157
- export const renderers = ["webgl2", "cpu"];
172
+ export const renderers = ["webgpu", "webgl2", "cpu"];
173
+
174
+ // True after a WebGPU canvas of the page fell back to WebGL 2. Each later
175
+ // app of the page with "auto" then starts with WebGL 2.
176
+ let webgpuFailed = false;
158
177
 
159
178
  // The WebGL 2 renderer: the quads of the scene in one instanced draw.
160
179
  function webgl2(canvas, ex) {
@@ -190,6 +209,17 @@ function webgl2(canvas, ex) {
190
209
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, ATLAS, ATLAS, 0, gl.RED, gl.UNSIGNED_BYTE, null);
191
210
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
192
211
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
212
+ // The RGBA image page, on texture unit 1.
213
+ const imgTex = gl.createTexture();
214
+ gl.activeTexture(gl.TEXTURE1);
215
+ gl.bindTexture(gl.TEXTURE_2D, imgTex);
216
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, ATLAS, ATLAS, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
217
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
218
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
219
+ gl.activeTexture(gl.TEXTURE0);
220
+ gl.useProgram(prog);
221
+ gl.uniform1i(gl.getUniformLocation(prog, "u_atlas"), 0);
222
+ gl.uniform1i(gl.getUniformLocation(prog, "u_images"), 1);
193
223
  const uTarget = gl.getUniformLocation(prog, "u_target");
194
224
  let atlasVersion = -1;
195
225
  return {
@@ -200,6 +230,14 @@ function webgl2(canvas, ex) {
200
230
  atlasVersion = v;
201
231
  const p = ex.ztk_atlas();
202
232
  if (p) gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, ATLAS, ATLAS, gl.RED, gl.UNSIGNED_BYTE, new Uint8Array(ex.memory.buffer, p, ATLAS * ATLAS));
233
+ const ip = ex.ztk_images ? ex.ztk_images() : 0;
234
+ if (ip) {
235
+ gl.activeTexture(gl.TEXTURE1);
236
+ gl.bindTexture(gl.TEXTURE_2D, imgTex);
237
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, ATLAS, ATLAS, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(ex.memory.buffer, ip, ATLAS * ATLAS * 4));
238
+ gl.activeTexture(gl.TEXTURE0);
239
+ gl.bindTexture(gl.TEXTURE_2D, tex);
240
+ }
203
241
  }
204
242
  const c = new Float32Array(ex.memory.buffer, ex.ztk_clear_color(), 4);
205
243
  gl.viewport(0, 0, w, h);
@@ -220,6 +258,7 @@ function webgl2(canvas, ex) {
220
258
  destroy() {
221
259
  gl.deleteBuffer(buf);
222
260
  gl.deleteTexture(tex);
261
+ gl.deleteTexture(imgTex);
223
262
  gl.deleteVertexArray(vao);
224
263
  gl.deleteProgram(prog);
225
264
  },
@@ -246,11 +285,13 @@ function cpu(canvas, ex) {
246
285
 
247
286
  /// Starts ztk.wasm on a canvas. `mount` is the API for a page. Options:
248
287
  /// module or wasm (the module, or the URL of ztk.wasm), renderer ("auto",
249
- /// "webgl2", "cpu", or "webgpu"), dark (true, false, or undefined for the
288
+ /// "webgpu", "webgl2", or "cpu"), colorSpace ("srgb" or "display-p3" for
289
+ /// WebGPU), loop (false: the page calls frame()), dark (true, false, or undefined for the
250
290
  /// color scheme of the page), width and height (a fixed logical size),
251
291
  /// scale (in place of devicePixelRatio), and log (gets the text of puts
252
292
  /// and the errors).
253
- export async function start(canvas, options = {}) {
293
+ export async function start(firstCanvas, options = {}) {
294
+ let canvas = firstCanvas;
254
295
  const enc = new TextEncoder();
255
296
  const dec = new TextDecoder();
256
297
  let ex = null;
@@ -306,32 +347,109 @@ export async function start(canvas, options = {}) {
306
347
  try { return f(p, b.length); } finally { ex.ztk_free(p, Math.max(b.length, 1)); }
307
348
  };
308
349
  const result = () => dec.decode(new Uint8Array(ex.memory.buffer, ex.ztk_result_ptr(), ex.ztk_result_len()));
309
- const evalScript = (text) => {
310
- const code = withBytes(text, (p, n) => ex.ztk_eval(p, n));
350
+ // With main true, the debug state keeps the place of the text, for the
351
+ // line in the script of a command in a proc (ztk_eval_main).
352
+ const evalScript = (text, main = false) => {
353
+ const code = withBytes(text, (p, n) => (main ? ex.ztk_eval_main : ex.ztk_eval)(p, n));
311
354
  const r = result();
312
355
  if (code !== 0) log("error: " + r);
313
356
  return { ok: code === 0, result: r };
314
357
  };
315
358
 
316
- // The renderer. "auto" selects the first one that the browser has.
317
- const want = options.renderer || "auto";
318
- if (want === "webgpu") throw new Error("ztk: this version has no WebGPU renderer. Use \"auto\", \"webgl2\", or \"cpu\".");
319
- const makers = { webgl2, cpu };
359
+ // The renderer. "auto" selects the first one that the browser has. A
360
+ // canvas has one context type, so WebGPU asks for its device before it
361
+ // gets the context of the canvas. A forced renderer that the browser
362
+ // does not have rejects.
363
+ const query = globalThis.location ? new URLSearchParams(location.search).get("renderer") : null;
364
+ const want = options.renderer || query || "auto";
365
+ let lastN = 0;
366
+ const makers = {
367
+ webgpu: () => createWebGPU(canvas, ex, { colorSpace: options.colorSpace, restored: () => draw(lastN), failed: (why) => fallback(why) }),
368
+ // A failed WebGPU start can restart the GPU process of the browser,
369
+ // and WebGL 2 has no context for a short time after it. The page
370
+ // then asks again 3 times, 200 ms apart.
371
+ webgl2: async () => {
372
+ for (let i = 0; ; i++) {
373
+ const r = webgl2(canvas, ex);
374
+ if (r || i === 3 || !webgpuFailed) return r;
375
+ await new Promise((res) => setTimeout(res, 200));
376
+ }
377
+ },
378
+ cpu: () => cpu(canvas, ex),
379
+ };
320
380
  if (want !== "auto" && !makers[want]) throw new Error(`ztk: no renderer "${want}"`);
321
381
  let renderer = null;
322
382
  for (const name of want === "auto" ? renderers : [want]) {
323
- renderer = makers[name](canvas, ex);
383
+ if (name === "webgpu" && want === "auto" && webgpuFailed) continue;
384
+ try {
385
+ renderer = await makers[name]();
386
+ } catch (e) {
387
+ if (want !== "auto") throw e;
388
+ if (name === "webgpu") webgpuFailed = true;
389
+ console.warn(`ztk: the renderer ${name} failed: ${e}`);
390
+ }
324
391
  if (renderer || want !== "auto") break;
325
392
  }
326
- if (!renderer) throw new Error(want === "webgl2" ? "WebGL 2 is not available" : `ztk: the renderer "${want}" is not available`);
393
+ const names = { webgpu: "WebGPU", webgl2: "WebGL 2", cpu: "a 2D canvas" };
394
+ if (!renderer) throw new Error(want === "auto" ? "ztk: WebGPU, WebGL 2, and a 2D canvas are not available" : `ztk: ${names[want]} is not available`);
395
+ if (!logged) {
396
+ logged = true;
397
+ console.info(`ztk: the renderer is ${renderer.name}`);
398
+ }
399
+
400
+ // A WebGPU canvas can stay blank on the screen, as on some
401
+ // software adapters. The first frame of WebGPU goes into a 1 by 1 2D
402
+ // canvas: an opaque canvas gives an alpha of 255 there, and a blank one
403
+ // gives 0. A blank first frame, a GPU error, or a loss with no new
404
+ // device makes the page render with WebGL 2, or with the CPU renderer
405
+ // when WebGL 2 is not there. A canvas has one context type, so a new
406
+ // canvas goes in the place of the old one. A forced "webgpu" stays.
407
+ let firstFrame = true;
408
+ const blank = () => {
409
+ try {
410
+ const probe = document.createElement("canvas");
411
+ probe.width = probe.height = 1;
412
+ const g = probe.getContext("2d", { willReadFrequently: true });
413
+ g.drawImage(canvas, 0, 0, 1, 1);
414
+ return g.getImageData(0, 0, 1, 1).data[3] === 0;
415
+ } catch (_) {
416
+ return false;
417
+ }
418
+ };
419
+ let falling = false;
420
+ const fallback = (why) => {
421
+ if (falling || renderer?.name !== "webgpu" || want === "webgpu" || signal.aborted) return;
422
+ falling = true;
423
+ webgpuFailed = true;
424
+ console.warn(`ztk: WebGPU ${why}, so the renderer is now WebGL 2`);
425
+ renderer.destroy();
426
+ const next = canvas.cloneNode(false);
427
+ canvas.replaceWith(next);
428
+ canvas = next;
429
+ bindCanvas();
430
+ renderer = null;
431
+ (async () => {
432
+ try { renderer = await makers.webgl2(); } catch (_) { /* no WebGL 2 */ }
433
+ renderer ??= cpu(canvas, ex);
434
+ falling = false;
435
+ draw(lastN);
436
+ })();
437
+ };
327
438
 
328
439
  const draw = (n) => {
440
+ lastN = n;
441
+ // No renderer while a fallback waits for WebGL 2.
442
+ if (!renderer) return;
329
443
  const w = ex.ztk_scene_width(), h = ex.ztk_scene_height();
330
444
  if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; }
331
445
  const sc = scaleNow();
332
446
  const cw = `${(w * k) / sc}px`, ch = `${(h * k) / sc}px`;
333
447
  if (canvas.style.width !== cw || canvas.style.height !== ch) { canvas.style.width = cw; canvas.style.height = ch; }
334
448
  renderer.draw(n, w, h);
449
+ if (firstFrame && renderer.name === "webgpu") {
450
+ firstFrame = false;
451
+ if (blank()) return fallback("rendered a blank frame");
452
+ }
335
453
  updateA11y();
336
454
  };
337
455
 
@@ -347,15 +465,26 @@ export async function start(canvas, options = {}) {
347
465
  return [(e.clientX - r.left) / k, (e.clientY - r.top) / k];
348
466
  };
349
467
  const mods = (e) => ex.ztk_mods(e.shiftKey, e.ctrlKey || e.metaKey, e.altKey);
350
- on(canvas, "pointermove", (e) => { mods(e); ex.ztk_pointer(...pos(e)); });
351
- on(canvas, "pointerdown", (e) => {
352
- mods(e); ex.ztk_pointer(...pos(e)); ex.ztk_button([1, 2, 3][e.button] || 1, true);
353
- try { canvas.setPointerCapture(e.pointerId); } catch (_) { /* a synthetic event has no capture */ }
354
- input.focus({ preventScroll: true }); e.preventDefault();
355
- });
356
- on(canvas, "pointerup", (e) => { mods(e); ex.ztk_pointer(...pos(e)); ex.ztk_button([1, 2, 3][e.button] || 1, false); });
357
- on(canvas, "pointerleave", () => ex.ztk_leave());
358
- on(canvas, "contextmenu", (e) => e.preventDefault());
468
+ // The listeners of the canvas. A fallback of the renderer puts them on the new canvas.
469
+ const bindCanvas = () => {
470
+ on(canvas, "pointermove", (e) => { mods(e); ex.ztk_pointer(...pos(e)); });
471
+ on(canvas, "pointerdown", (e) => {
472
+ mods(e); ex.ztk_pointer(...pos(e)); ex.ztk_button([1, 2, 3][e.button] || 1, true);
473
+ try { canvas.setPointerCapture(e.pointerId); } catch (_) { /* a synthetic event has no capture */ }
474
+ input.focus({ preventScroll: true }); e.preventDefault();
475
+ });
476
+ on(canvas, "pointerup", (e) => { mods(e); ex.ztk_pointer(...pos(e)); ex.ztk_button([1, 2, 3][e.button] || 1, false); });
477
+ on(canvas, "pointerleave", () => ex.ztk_leave());
478
+ // A wheel step is 100 pixels in deltaMode 0 and 3 lines in deltaMode 1.
479
+ canvas.addEventListener("wheel", (e) => {
480
+ e.preventDefault();
481
+ mods(e); ex.ztk_pointer(...pos(e));
482
+ const k = e.deltaMode === 1 ? 1 / 3 : e.deltaMode === 2 ? 10 : 1 / 100;
483
+ ex.ztk_wheel(e.deltaX * k, e.deltaY * k);
484
+ }, { passive: false, signal });
485
+ on(canvas, "contextmenu", (e) => e.preventDefault());
486
+ };
487
+ bindCanvas();
359
488
  let composing = false;
360
489
  on(input, "compositionstart", () => { composing = true; });
361
490
  on(input, "compositionend", (e) => { composing = false; withBytes(e.data || "", (p, n) => ex.ztk_text(p, n)); input.value = ""; });
@@ -407,18 +536,94 @@ export async function start(canvas, options = {}) {
407
536
  }));
408
537
  };
409
538
 
539
+ // The popups: a posted menu and its cascades. Each popup is a 2D canvas
540
+ // in a fixed layer above the page, at the place of the popup, so a menu
541
+ // can extend past the canvas of the window. The screen of the popups is
542
+ // the viewport. The image of a popup has premultiplied alpha, and a 2D
543
+ // canvas takes straight alpha.
544
+ const layer = document.createElement("div");
545
+ layer.style.cssText = "position:fixed;left:0;top:0;width:0;height:0;overflow:visible;z-index:2147483647;";
546
+ layer.dataset.ztkPopups = "";
547
+ document.body.appendChild(layer);
548
+ const pops = [];
549
+ let popDraws = -1;
550
+ let popPlace = "";
551
+ const popPos = (c, e) => {
552
+ const r = c.getBoundingClientRect();
553
+ return [(e.clientX - r.left) / k, (e.clientY - r.top) / k];
554
+ };
555
+ const makePop = (i) => {
556
+ const c = document.createElement("canvas");
557
+ c.style.cssText = "position:absolute;touch-action:none;";
558
+ c.setAttribute("aria-hidden", "true");
559
+ on(c, "pointermove", (e) => { mods(e); ex.ztk_popup_pointer(i, ...popPos(c, e)); });
560
+ on(c, "pointerdown", (e) => {
561
+ mods(e); ex.ztk_popup_pointer(i, ...popPos(c, e)); ex.ztk_popup_button(i, [1, 2, 3][e.button] || 1, true);
562
+ input.focus({ preventScroll: true }); e.preventDefault();
563
+ });
564
+ on(c, "pointerup", (e) => { mods(e); ex.ztk_popup_pointer(i, ...popPos(c, e)); ex.ztk_popup_button(i, [1, 2, 3][e.button] || 1, false); });
565
+ on(c, "pointerleave", () => ex.ztk_popup_leave(i));
566
+ on(c, "contextmenu", (e) => e.preventDefault());
567
+ layer.appendChild(c);
568
+ return c;
569
+ };
570
+ const drawPops = () => {
571
+ const n = ex.ztk_popups();
572
+ while (pops.length > n) pops.pop().remove();
573
+ while (pops.length < n) pops.push(makePop(pops.length));
574
+ if (n === 0) return;
575
+ const cr = canvas.getBoundingClientRect();
576
+ const draws = ex.ztk_draws();
577
+ const place = `${cr.left},${cr.top},${k}`;
578
+ if (draws === popDraws && place === popPlace) return;
579
+ const fresh = draws !== popDraws;
580
+ popDraws = draws;
581
+ popPlace = place;
582
+ for (let i = 0; i < n; i++) {
583
+ const c = pops[i];
584
+ const r = new Int32Array(ex.memory.buffer, ex.ztk_popup_rect(i), 6);
585
+ const [x, y, w, h, iw, ih] = r;
586
+ c.style.left = `${cr.left + x * k}px`;
587
+ c.style.top = `${cr.top + y * k}px`;
588
+ c.style.width = `${w * k}px`;
589
+ c.style.height = `${h * k}px`;
590
+ const p = ex.ztk_popup_image(i);
591
+ if (!fresh || !p || iw === 0 || ih === 0) continue;
592
+ if (c.width !== iw || c.height !== ih) { c.width = iw; c.height = ih; }
593
+ const px = new Uint8ClampedArray(ex.memory.buffer, p, iw * ih * 4).slice();
594
+ for (let j = 0; j < px.length; j += 4) {
595
+ const a = px[j + 3];
596
+ if (a !== 0 && a !== 255) { px[j] = px[j] * 255 / a; px[j + 1] = px[j + 1] * 255 / a; px[j + 2] = px[j + 2] * 255 / a; }
597
+ }
598
+ c.getContext("2d").putImageData(new ImageData(px, iw, ih), 0, 0);
599
+ }
600
+ };
601
+ // A press outside the window and the popups closes the popups, as a compositor does.
602
+ document.addEventListener("pointerdown", (e) => {
603
+ if (pops.length > 0 && e.target !== canvas && !layer.contains(e.target)) ex.ztk_popup_dismiss();
604
+ }, { capture: true, signal });
605
+ const setScreen = () => {
606
+ const r = canvas.getBoundingClientRect();
607
+ ex.ztk_screen(Math.round(-r.left / k), Math.round(-r.top / k), Math.round(innerWidth / k), Math.round(innerHeight / k));
608
+ };
609
+
410
610
  let raf = 0;
411
611
  const loop = (t) => {
612
+ setScreen();
412
613
  const n = ex.ztk_frame(t);
413
614
  if (n >= 0) draw(n);
615
+ drawPops();
414
616
  raf = requestAnimationFrame(loop);
415
617
  };
416
- raf = requestAnimationFrame(loop);
618
+ // options.loop false leaves the frames to the page, for a test.
619
+ if (options.loop !== false) raf = requestAnimationFrame(loop);
417
620
  const addFile = (name, text) => withBytes(name, (pn, nn) => withBytes(text, (pt, nt) => ex.ztk_add_file(pn, nn, pt, nt)));
418
621
  const frame = (t) => {
419
622
  if (signal.aborted) return -1;
623
+ setScreen();
420
624
  const n = ex.ztk_frame(t);
421
625
  if (n >= 0) draw(n);
626
+ drawPops();
422
627
  return n;
423
628
  };
424
629
  // The window of the script gets a new logical size.
@@ -432,11 +637,18 @@ export async function start(canvas, options = {}) {
432
637
  if (signal.aborted) return;
433
638
  life.abort();
434
639
  cancelAnimationFrame(raf);
435
- renderer.destroy();
640
+ renderer?.destroy();
436
641
  input.remove();
437
642
  tree.remove();
643
+ layer.remove();
438
644
  };
439
- return { eval: evalScript, exports: ex, frame, tree, addFile, canvas, resize, setTheme, destroy, renderer: renderer.name, signal };
645
+ // A WebGPU canvas keeps its image only until the frame is shown, so a
646
+ // snapshot draws the last scene again and reads the canvas at once.
647
+ const redraw = () => draw(lastN);
648
+ const snapshot = (type = "image/png") => { redraw(); return canvas.toDataURL(type); };
649
+ // A test: the GPU device is lost, and the renderer draws on a new one.
650
+ const loseDevice = async () => (renderer?.lose ? renderer.lose() : false);
651
+ return { eval: evalScript, exports: ex, frame, tree, addFile, get canvas() { return canvas; }, resize, setTheme, destroy, get renderer() { return renderer?.name ?? "none"; }, redraw, snapshot, loseDevice, signal };
440
652
  }
441
653
 
442
654
  /// Mounts a ztk app on an element. `el` is a canvas, or an element that
@@ -448,7 +660,7 @@ export async function start(canvas, options = {}) {
448
660
  /// and then the size the window computes), "fill" (the window
449
661
  /// follows the size of the element), or [width, height] in
450
662
  /// logical pixels (the canvas shows the window at its CSS size).
451
- /// renderer "auto" (the default), "webgl2", "cpu", or "webgpu".
663
+ /// renderer "auto" (the default), "webgpu", "webgl2", or "cpu".
452
664
  /// scale The device pixels in one logical pixel. The default is devicePixelRatio.
453
665
  /// module, wasm, log As for start().
454
666
  /// A script error destroys the app and rejects with the error text.
@@ -486,7 +698,7 @@ export async function mount(el, options = {}) {
486
698
  app.destroy = () => {
487
699
  observer?.disconnect();
488
700
  destroy();
489
- if (own) canvas.remove();
701
+ if (own) app.canvas.remove();
490
702
  };
491
703
  for (const [name, text] of Object.entries(options.files || {})) app.addFile(name, text);
492
704
  if (options.script != null) {
package/ztk.wasm CHANGED
Binary file