@beetlebug/ztk 0.0.0-stage → 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/LICENSE +24 -0
- package/NOTICE +20 -0
- package/README.md +100 -2
- package/licenses/LICENSE-Inter.txt +92 -0
- package/licenses/ztcl/LICENSE +24 -0
- package/licenses/ztcl/arm-optimized-routines.txt +249 -0
- package/licenses/ztcl/ghostty-MIT.txt +21 -0
- package/licenses/ztcl/go-BSD-3-Clause.txt +27 -0
- package/licenses/ztcl/musl-MIT.txt +193 -0
- package/licenses/ztcl/simdjson-NOTICE.txt +20 -0
- package/licenses/ztcl/tcl-license.txt +40 -0
- package/licenses/ztcl/unicode-license.txt +39 -0
- package/licenses/ztcl/uucode-MIT.txt +30 -0
- package/licenses/ztcl/wasi-W3C-CLA.md +8 -0
- package/licenses/ztcl/zig-std-MIT.txt +21 -0
- package/package.json +43 -4
- package/webgpu.js +372 -0
- package/ztk.d.ts +121 -0
- package/ztk.js +715 -0
- package/ztk.wasm +0 -0
package/ztk.js
ADDED
|
@@ -0,0 +1,715 @@
|
|
|
1
|
+
// SPDX-License-Identifier: BSD-2-Clause
|
|
2
|
+
// The page side of ztk in a browser. It loads ztk.wasm, gives it the
|
|
3
|
+
// clock, the size, the scale (devicePixelRatio), the color scheme, the
|
|
4
|
+
// reduced motion setting, and the input of the canvas, and draws each
|
|
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
|
|
9
|
+
// (src/render/renderer.zig) and of src/render/shaders/quad.frag. A
|
|
10
|
+
// hidden text area gets the keyboard, so that text input and input
|
|
11
|
+
// methods work. A list of hidden elements with ARIA roles follows the
|
|
12
|
+
// widgets, from ztk_a11y.
|
|
13
|
+
|
|
14
|
+
import { createWebGPU } from "./webgpu.js";
|
|
15
|
+
|
|
16
|
+
const VS = `#version 300 es
|
|
17
|
+
layout(location=0) in vec4 a_rect;
|
|
18
|
+
layout(location=1) in vec4 a_clip;
|
|
19
|
+
layout(location=2) in vec4 a_radii;
|
|
20
|
+
layout(location=3) in vec4 a_border;
|
|
21
|
+
layout(location=4) in vec4 a_fill;
|
|
22
|
+
layout(location=5) in vec4 a_fill2;
|
|
23
|
+
layout(location=6) in vec4 a_border_color;
|
|
24
|
+
layout(location=7) in vec4 a_uv;
|
|
25
|
+
layout(location=8) in vec4 a_params;
|
|
26
|
+
layout(location=9) in uint a_kind;
|
|
27
|
+
uniform vec2 u_target;
|
|
28
|
+
flat out vec4 f_rect; flat out vec4 f_clip; flat out vec4 f_radii; flat out vec4 f_border;
|
|
29
|
+
flat out vec4 f_fill; flat out vec4 f_fill2; flat out vec4 f_border_color; flat out vec4 f_uv;
|
|
30
|
+
flat out vec4 f_params; flat out uint f_kind;
|
|
31
|
+
void main() {
|
|
32
|
+
float pad = 0.0;
|
|
33
|
+
if (a_kind == 0u) pad = 1.0;
|
|
34
|
+
if (a_kind == 1u) pad = max(a_params.z, 1.0) + 1.0;
|
|
35
|
+
vec2 lo = max(a_rect.xy - pad, a_clip.xy);
|
|
36
|
+
vec2 hi = min(a_rect.xy + a_rect.zw + pad, a_clip.xy + a_clip.zw);
|
|
37
|
+
hi = max(hi, lo);
|
|
38
|
+
vec2 corner = vec2(float(gl_VertexID & 1), float(gl_VertexID >> 1));
|
|
39
|
+
vec2 pos = mix(lo, hi, corner);
|
|
40
|
+
vec2 ndc = pos / u_target * 2.0 - 1.0;
|
|
41
|
+
gl_Position = vec4(ndc.x, -ndc.y, 0.0, 1.0);
|
|
42
|
+
f_rect = a_rect; f_clip = a_clip; f_radii = a_radii; f_border = a_border; f_fill = a_fill;
|
|
43
|
+
f_fill2 = a_fill2; f_border_color = a_border_color; f_uv = a_uv; f_params = a_params; f_kind = a_kind;
|
|
44
|
+
}`;
|
|
45
|
+
|
|
46
|
+
const FS = `#version 300 es
|
|
47
|
+
precision highp float;
|
|
48
|
+
flat in vec4 f_rect; flat in vec4 f_clip; flat in vec4 f_radii; flat in vec4 f_border;
|
|
49
|
+
flat in vec4 f_fill; flat in vec4 f_fill2; flat in vec4 f_border_color; flat in vec4 f_uv;
|
|
50
|
+
flat in vec4 f_params; flat in uint f_kind;
|
|
51
|
+
uniform vec2 u_target;
|
|
52
|
+
uniform sampler2D u_atlas;
|
|
53
|
+
uniform sampler2D u_images;
|
|
54
|
+
out vec4 out_color;
|
|
55
|
+
float clamp01(float x) { return clamp(x, 0.0, 1.0); }
|
|
56
|
+
float roundedDistance(vec2 p, vec4 rect, vec4 radii) {
|
|
57
|
+
float hw = rect.z * 0.5; float hh = rect.w * 0.5;
|
|
58
|
+
float dx = p.x - (rect.x + hw); float dy = p.y - (rect.y + hh);
|
|
59
|
+
float limit = min(hw, hh);
|
|
60
|
+
float r = dy < 0.0 ? (dx < 0.0 ? radii.x : radii.y) : (dx < 0.0 ? radii.w : radii.z);
|
|
61
|
+
r = min(r, limit);
|
|
62
|
+
float qx = abs(dx) - hw + r; float qy = abs(dy) - hh + r;
|
|
63
|
+
float mx = max(qx, 0.0); float my = max(qy, 0.0);
|
|
64
|
+
return min(max(qx, qy), 0.0) + sqrt(mx * mx + my * my) - r;
|
|
65
|
+
}
|
|
66
|
+
vec2 boxCoverage(vec2 p) {
|
|
67
|
+
float outer = clamp01(0.5 - roundedDistance(p, f_rect, f_radii));
|
|
68
|
+
float bt = f_border.x; float br = f_border.y; float bb = f_border.z; float bl = f_border.w;
|
|
69
|
+
if (bt == 0.0 && br == 0.0 && bb == 0.0 && bl == 0.0) return vec2(outer, 0.0);
|
|
70
|
+
vec4 ir = vec4(f_rect.x + bl, f_rect.y + bt, f_rect.z - bl - br, f_rect.w - bt - bb);
|
|
71
|
+
if (ir.z <= 0.0 || ir.w <= 0.0) return vec2(0.0, outer);
|
|
72
|
+
vec4 irad = vec4(max(f_radii.x - max(bt, bl), 0.0), max(f_radii.y - max(bt, br), 0.0),
|
|
73
|
+
max(f_radii.z - max(bb, br), 0.0), max(f_radii.w - max(bb, bl), 0.0));
|
|
74
|
+
float inner = clamp01(0.5 - roundedDistance(p, ir, irad));
|
|
75
|
+
return vec2(inner, max(outer - inner, 0.0));
|
|
76
|
+
}
|
|
77
|
+
float shadowCoverage(vec2 p) {
|
|
78
|
+
float d = roundedDistance(p, f_rect, f_radii);
|
|
79
|
+
float t = clamp01(0.5 - d / max(f_params.z, 1.0));
|
|
80
|
+
return t * t * (3.0 - 2.0 * t);
|
|
81
|
+
}
|
|
82
|
+
float gradientT(vec2 p) {
|
|
83
|
+
float dx = f_params.x; float dy = f_params.y;
|
|
84
|
+
float len = abs(f_rect.z * dx) + abs(f_rect.w * dy);
|
|
85
|
+
if (len <= 0.0) return 0.0;
|
|
86
|
+
return clamp01(((p.x - (f_rect.x + f_rect.z * 0.5)) * dx + (p.y - (f_rect.y + f_rect.w * 0.5)) * dy) / len + 0.5);
|
|
87
|
+
}
|
|
88
|
+
void main() {
|
|
89
|
+
vec2 p = vec2(gl_FragCoord.x, u_target.y - gl_FragCoord.y);
|
|
90
|
+
if (p.x < f_clip.x || p.y < f_clip.y || p.x >= f_clip.x + f_clip.z || p.y >= f_clip.y + f_clip.w) discard;
|
|
91
|
+
float opacity = f_params.w;
|
|
92
|
+
if (f_kind == 0u) {
|
|
93
|
+
vec2 c = boxCoverage(p);
|
|
94
|
+
vec4 col = (f_fill == f_fill2) ? f_fill : mix(f_fill, f_fill2, gradientT(p));
|
|
95
|
+
float fa = col.a * c.x * opacity;
|
|
96
|
+
float ba = f_border_color.a * c.y * opacity;
|
|
97
|
+
out_color = vec4(f_border_color.rgb * ba + col.rgb * fa * (1.0 - ba), 1.0 - (1.0 - fa) * (1.0 - ba));
|
|
98
|
+
} else if (f_kind == 1u) {
|
|
99
|
+
float a = f_fill.a * shadowCoverage(p) * opacity;
|
|
100
|
+
out_color = vec4(f_fill.rgb * a, a);
|
|
101
|
+
} else if (f_kind == 2u) {
|
|
102
|
+
ivec2 t = ivec2(f_uv.xy) + ivec2(floor(p)) - ivec2(f_rect.xy);
|
|
103
|
+
float a = f_fill.a * texelFetch(u_atlas, t, 0).r * opacity;
|
|
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);
|
|
114
|
+
} else {
|
|
115
|
+
discard;
|
|
116
|
+
}
|
|
117
|
+
}`;
|
|
118
|
+
|
|
119
|
+
const QUAD_BYTES = 160;
|
|
120
|
+
const ATLAS = 1024;
|
|
121
|
+
|
|
122
|
+
const KEYS = {
|
|
123
|
+
Enter: "Return", Backspace: "BackSpace", Tab: "Tab", Escape: "Escape", Delete: "Delete",
|
|
124
|
+
ArrowLeft: "Left", ArrowRight: "Right", ArrowUp: "Up", ArrowDown: "Down", Home: "Home", End: "End",
|
|
125
|
+
PageUp: "Prior", PageDown: "Next", Insert: "Insert", Shift: "Shift_L", Control: "Control_L", Alt: "Alt_L",
|
|
126
|
+
F1: "F1", F2: "F2", F3: "F3", F4: "F4", F5: "F5", F6: "F6", F7: "F7", F8: "F8", F9: "F9", F10: "F10", F11: "F11", F12: "F12",
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
// The built-in modules of Node.js, through process.getBuiltinModule
|
|
131
|
+
// (Node.js 22.3 and later). The file has no `node:` import, so a
|
|
132
|
+
// bundler for the browser needs no shim.
|
|
133
|
+
function nodeModule(name) {
|
|
134
|
+
return globalThis.process?.getBuiltinModule?.(name);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/// The URL of the ztk.wasm file next to this file. Bundlers (Vite,
|
|
138
|
+
/// webpack 5) find it through the `new URL("./ztk.wasm", import.meta.url)`
|
|
139
|
+
/// form, and a CDN serves it from the folder of this file.
|
|
140
|
+
export function wasmURL() {
|
|
141
|
+
return new URL("./ztk.wasm", import.meta.url);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function compileFrom(u) {
|
|
145
|
+
const url = new URL(u, globalThis.location?.href);
|
|
146
|
+
const fs = nodeModule("node:fs/promises");
|
|
147
|
+
if (url.protocol === "file:" && fs) return WebAssembly.compile(await fs.readFile(url));
|
|
148
|
+
const res = await fetch(url);
|
|
149
|
+
if (!res.ok) throw new Error(`ztk.wasm: HTTP ${res.status}`);
|
|
150
|
+
if (WebAssembly.compileStreaming && res.headers.get("content-type") === "application/wasm") {
|
|
151
|
+
return WebAssembly.compileStreaming(res);
|
|
152
|
+
}
|
|
153
|
+
return WebAssembly.compile(await res.arrayBuffer());
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/// Compiles ztk.wasm one time for each URL. With no URL, it is the
|
|
157
|
+
/// ztk.wasm file next to this file.
|
|
158
|
+
const compiled = new Map();
|
|
159
|
+
export function compileModule(url) {
|
|
160
|
+
const u = String(url || wasmURL());
|
|
161
|
+
if (!compiled.has(u)) {
|
|
162
|
+
const p = compileFrom(u);
|
|
163
|
+
p.catch(() => compiled.delete(u));
|
|
164
|
+
compiled.set(u, p);
|
|
165
|
+
}
|
|
166
|
+
return compiled.get(u);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
let logged = false;
|
|
170
|
+
|
|
171
|
+
/// The renderers that this file has, in the order of "auto".
|
|
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;
|
|
177
|
+
|
|
178
|
+
// The WebGL 2 renderer: the quads of the scene in one instanced draw.
|
|
179
|
+
function webgl2(canvas, ex) {
|
|
180
|
+
const gl = canvas.getContext("webgl2", { premultipliedAlpha: true, antialias: false, alpha: false, preserveDrawingBuffer: true });
|
|
181
|
+
if (!gl) return null;
|
|
182
|
+
const compile = (type, src) => {
|
|
183
|
+
const s = gl.createShader(type);
|
|
184
|
+
gl.shaderSource(s, src);
|
|
185
|
+
gl.compileShader(s);
|
|
186
|
+
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));
|
|
187
|
+
return s;
|
|
188
|
+
};
|
|
189
|
+
const prog = gl.createProgram();
|
|
190
|
+
gl.attachShader(prog, compile(gl.VERTEX_SHADER, VS));
|
|
191
|
+
gl.attachShader(prog, compile(gl.FRAGMENT_SHADER, FS));
|
|
192
|
+
gl.linkProgram(prog);
|
|
193
|
+
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(prog));
|
|
194
|
+
const vao = gl.createVertexArray();
|
|
195
|
+
gl.bindVertexArray(vao);
|
|
196
|
+
const buf = gl.createBuffer();
|
|
197
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
|
|
198
|
+
for (let i = 0; i < 9; i++) {
|
|
199
|
+
gl.enableVertexAttribArray(i);
|
|
200
|
+
gl.vertexAttribPointer(i, 4, gl.FLOAT, false, QUAD_BYTES, i * 16);
|
|
201
|
+
gl.vertexAttribDivisor(i, 1);
|
|
202
|
+
}
|
|
203
|
+
gl.enableVertexAttribArray(9);
|
|
204
|
+
gl.vertexAttribIPointer(9, 1, gl.UNSIGNED_INT, QUAD_BYTES, 144);
|
|
205
|
+
gl.vertexAttribDivisor(9, 1);
|
|
206
|
+
const tex = gl.createTexture();
|
|
207
|
+
gl.bindTexture(gl.TEXTURE_2D, tex);
|
|
208
|
+
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
|
|
209
|
+
gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, ATLAS, ATLAS, 0, gl.RED, gl.UNSIGNED_BYTE, null);
|
|
210
|
+
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
|
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);
|
|
223
|
+
const uTarget = gl.getUniformLocation(prog, "u_target");
|
|
224
|
+
let atlasVersion = -1;
|
|
225
|
+
return {
|
|
226
|
+
name: "webgl2",
|
|
227
|
+
draw(n, w, h) {
|
|
228
|
+
const v = ex.ztk_atlas_version();
|
|
229
|
+
if (v !== atlasVersion) {
|
|
230
|
+
atlasVersion = v;
|
|
231
|
+
const p = ex.ztk_atlas();
|
|
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
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const c = new Float32Array(ex.memory.buffer, ex.ztk_clear_color(), 4);
|
|
243
|
+
gl.viewport(0, 0, w, h);
|
|
244
|
+
gl.disable(gl.SCISSOR_TEST);
|
|
245
|
+
gl.clearColor(c[0], c[1], c[2], c[3]);
|
|
246
|
+
gl.clear(gl.COLOR_BUFFER_BIT);
|
|
247
|
+
if (n > 0) {
|
|
248
|
+
gl.useProgram(prog);
|
|
249
|
+
gl.bindVertexArray(vao);
|
|
250
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
|
|
251
|
+
gl.bufferData(gl.ARRAY_BUFFER, new Uint8Array(ex.memory.buffer, ex.ztk_quads(), n * QUAD_BYTES), gl.STREAM_DRAW);
|
|
252
|
+
gl.uniform2f(uTarget, w, h);
|
|
253
|
+
gl.enable(gl.BLEND);
|
|
254
|
+
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
|
|
255
|
+
gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, n);
|
|
256
|
+
}
|
|
257
|
+
},
|
|
258
|
+
destroy() {
|
|
259
|
+
gl.deleteBuffer(buf);
|
|
260
|
+
gl.deleteTexture(tex);
|
|
261
|
+
gl.deleteTexture(imgTex);
|
|
262
|
+
gl.deleteVertexArray(vao);
|
|
263
|
+
gl.deleteProgram(prog);
|
|
264
|
+
},
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// The CPU renderer: ztk.wasm draws each frame to an RGBA image (the
|
|
269
|
+
// renderer of src/render/cpu.zig), and a 2D context shows it.
|
|
270
|
+
function cpu(canvas, ex) {
|
|
271
|
+
const ctx = canvas.getContext("2d", { alpha: false });
|
|
272
|
+
if (!ctx) return null;
|
|
273
|
+
ex.ztk_cpu(true);
|
|
274
|
+
return {
|
|
275
|
+
name: "cpu",
|
|
276
|
+
draw(_n, w, h) {
|
|
277
|
+
const p = ex.ztk_image();
|
|
278
|
+
if (!p || w === 0 || h === 0) return;
|
|
279
|
+
const px = new Uint8ClampedArray(ex.memory.buffer, p, w * h * 4).slice();
|
|
280
|
+
ctx.putImageData(new ImageData(px, w, h), 0, 0);
|
|
281
|
+
},
|
|
282
|
+
destroy() {},
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/// Starts ztk.wasm on a canvas. `mount` is the API for a page. Options:
|
|
287
|
+
/// module or wasm (the module, or the URL of ztk.wasm), renderer ("auto",
|
|
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
|
|
290
|
+
/// color scheme of the page), width and height (a fixed logical size),
|
|
291
|
+
/// scale (in place of devicePixelRatio), and log (gets the text of puts
|
|
292
|
+
/// and the errors).
|
|
293
|
+
export async function start(firstCanvas, options = {}) {
|
|
294
|
+
let canvas = firstCanvas;
|
|
295
|
+
const enc = new TextEncoder();
|
|
296
|
+
const dec = new TextDecoder();
|
|
297
|
+
let ex = null;
|
|
298
|
+
const log = options.log || ((t) => console.log(t));
|
|
299
|
+
const imports = {
|
|
300
|
+
env: {
|
|
301
|
+
ztk_now_ms: () => performance.now(),
|
|
302
|
+
ztk_print: (p, n) => log(dec.decode(new Uint8Array(ex.memory.buffer, p, n))),
|
|
303
|
+
},
|
|
304
|
+
};
|
|
305
|
+
// A page with several demos compiles the module one time and gives it as options.module.
|
|
306
|
+
const module = options.module || await compileModule(options.wasm);
|
|
307
|
+
const instance = await WebAssembly.instantiate(module, imports);
|
|
308
|
+
ex = instance.exports;
|
|
309
|
+
|
|
310
|
+
// Each listener of the page and of the canvas goes away with destroy().
|
|
311
|
+
const life = new AbortController();
|
|
312
|
+
const signal = life.signal;
|
|
313
|
+
const dark = matchMedia("(prefers-color-scheme: dark)");
|
|
314
|
+
const reduce = matchMedia("(prefers-reduced-motion: reduce)");
|
|
315
|
+
let forceDark = options.dark;
|
|
316
|
+
// The window of the script starts with the size of the element that
|
|
317
|
+
// holds the canvas, or with a fixed logical size (options.width and
|
|
318
|
+
// options.height) that the page shows at the size it gave the canvas.
|
|
319
|
+
// The toplevel then takes its own size, as in Tk (geometry propagation),
|
|
320
|
+
// so the canvas gets its CSS size from the scene after each frame:
|
|
321
|
+
// the scene width times k / scale, where k is the count of CSS pixels in
|
|
322
|
+
// one logical pixel. The backing store is the scene in device pixels.
|
|
323
|
+
// So the window keeps its aspect ratio and is sharp at each
|
|
324
|
+
// devicePixelRatio.
|
|
325
|
+
const fixed = Boolean(options.width && options.height);
|
|
326
|
+
const host = canvas.parentElement;
|
|
327
|
+
const size = () => {
|
|
328
|
+
if (fixed) return [options.width, options.height];
|
|
329
|
+
const r = host.getBoundingClientRect();
|
|
330
|
+
return [Math.max(1, Math.round(r.width)), Math.max(1, Math.round(r.height))];
|
|
331
|
+
};
|
|
332
|
+
let k = 1;
|
|
333
|
+
if (fixed) {
|
|
334
|
+
const r = canvas.getBoundingClientRect();
|
|
335
|
+
if (r.width > 0) k = r.width / options.width;
|
|
336
|
+
}
|
|
337
|
+
const scaleNow = () => options.scale || devicePixelRatio * k;
|
|
338
|
+
const [w0, h0] = size();
|
|
339
|
+
if (!ex.ztk_init(w0, h0, scaleNow(), forceDark ?? dark.matches, reduce.matches)) throw new Error("ztk_init failed");
|
|
340
|
+
dark.addEventListener("change", () => forceDark == null && ex.ztk_dark(dark.matches), { signal });
|
|
341
|
+
reduce.addEventListener("change", () => ex.ztk_reduce_motion(reduce.matches), { signal });
|
|
342
|
+
|
|
343
|
+
const withBytes = (text, f) => {
|
|
344
|
+
const b = enc.encode(text);
|
|
345
|
+
const p = ex.ztk_alloc(Math.max(b.length, 1));
|
|
346
|
+
new Uint8Array(ex.memory.buffer, p, b.length).set(b);
|
|
347
|
+
try { return f(p, b.length); } finally { ex.ztk_free(p, Math.max(b.length, 1)); }
|
|
348
|
+
};
|
|
349
|
+
const result = () => dec.decode(new Uint8Array(ex.memory.buffer, ex.ztk_result_ptr(), ex.ztk_result_len()));
|
|
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));
|
|
354
|
+
const r = result();
|
|
355
|
+
if (code !== 0) log("error: " + r);
|
|
356
|
+
return { ok: code === 0, result: r };
|
|
357
|
+
};
|
|
358
|
+
|
|
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
|
+
};
|
|
380
|
+
if (want !== "auto" && !makers[want]) throw new Error(`ztk: no renderer "${want}"`);
|
|
381
|
+
let renderer = null;
|
|
382
|
+
for (const name of want === "auto" ? renderers : [want]) {
|
|
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
|
+
}
|
|
391
|
+
if (renderer || want !== "auto") break;
|
|
392
|
+
}
|
|
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
|
+
};
|
|
438
|
+
|
|
439
|
+
const draw = (n) => {
|
|
440
|
+
lastN = n;
|
|
441
|
+
// No renderer while a fallback waits for WebGL 2.
|
|
442
|
+
if (!renderer) return;
|
|
443
|
+
const w = ex.ztk_scene_width(), h = ex.ztk_scene_height();
|
|
444
|
+
if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; }
|
|
445
|
+
const sc = scaleNow();
|
|
446
|
+
const cw = `${(w * k) / sc}px`, ch = `${(h * k) / sc}px`;
|
|
447
|
+
if (canvas.style.width !== cw || canvas.style.height !== ch) { canvas.style.width = cw; canvas.style.height = ch; }
|
|
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
|
+
}
|
|
453
|
+
updateA11y();
|
|
454
|
+
};
|
|
455
|
+
|
|
456
|
+
// Input. A hidden text area holds the keyboard focus.
|
|
457
|
+
const on = (target, type, f) => target.addEventListener(type, f, { signal });
|
|
458
|
+
const input = document.createElement("textarea");
|
|
459
|
+
input.setAttribute("aria-hidden", "true");
|
|
460
|
+
input.style.cssText = "position:absolute;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none;";
|
|
461
|
+
canvas.parentElement.style.position ||= "relative";
|
|
462
|
+
canvas.parentElement.appendChild(input);
|
|
463
|
+
const pos = (e) => {
|
|
464
|
+
const r = canvas.getBoundingClientRect();
|
|
465
|
+
return [(e.clientX - r.left) / k, (e.clientY - r.top) / k];
|
|
466
|
+
};
|
|
467
|
+
const mods = (e) => ex.ztk_mods(e.shiftKey, e.ctrlKey || e.metaKey, e.altKey);
|
|
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();
|
|
488
|
+
let composing = false;
|
|
489
|
+
on(input, "compositionstart", () => { composing = true; });
|
|
490
|
+
on(input, "compositionend", (e) => { composing = false; withBytes(e.data || "", (p, n) => ex.ztk_text(p, n)); input.value = ""; });
|
|
491
|
+
on(input, "input", (e) => {
|
|
492
|
+
if (composing || e.isComposing) return;
|
|
493
|
+
if (input.value) withBytes(input.value, (p, n) => ex.ztk_text(p, n));
|
|
494
|
+
input.value = "";
|
|
495
|
+
});
|
|
496
|
+
const key = (e, down) => {
|
|
497
|
+
mods(e);
|
|
498
|
+
const name = KEYS[e.key];
|
|
499
|
+
if (!name) return;
|
|
500
|
+
withBytes(name, (p, n) => ex.ztk_key(p, n, down));
|
|
501
|
+
if (e.key === "Tab" || e.key.startsWith("Arrow") || e.key === "Backspace") e.preventDefault();
|
|
502
|
+
};
|
|
503
|
+
on(input, "keydown", (e) => key(e, true));
|
|
504
|
+
on(input, "keyup", (e) => key(e, false));
|
|
505
|
+
// A change of devicePixelRatio sends the new scale, so the next frame is
|
|
506
|
+
// drawn sharp at the new scale. A change of the size of the page does
|
|
507
|
+
// not resize the window: in Tk a toplevel keeps its own size, and a
|
|
508
|
+
// resize from the platform would stop its geometry propagation.
|
|
509
|
+
// resize() and mount({ size: "fill" }) resize the window.
|
|
510
|
+
const watchScale = () => {
|
|
511
|
+
const m = matchMedia(`(resolution: ${devicePixelRatio}dppx)`);
|
|
512
|
+
m.addEventListener("change", () => { ex.ztk_scale(scaleNow()); watchScale(); }, { once: true, signal });
|
|
513
|
+
};
|
|
514
|
+
watchScale();
|
|
515
|
+
|
|
516
|
+
// Accessibility: hidden elements with ARIA roles over the canvas.
|
|
517
|
+
const tree = document.createElement("div");
|
|
518
|
+
tree.style.cssText = "position:absolute;left:0;top:0;width:0;height:0;overflow:visible;pointer-events:none;";
|
|
519
|
+
canvas.parentElement.appendChild(tree);
|
|
520
|
+
const ARIA = { "button": "button", "check box": "checkbox", "radio button": "radio", "text field": "textbox", "label": "note", "slider": "slider", "group": "group", "window": "dialog" };
|
|
521
|
+
let lastA11y = "";
|
|
522
|
+
const updateA11y = () => {
|
|
523
|
+
const n = ex.ztk_a11y();
|
|
524
|
+
const text = dec.decode(new Uint8Array(ex.memory.buffer, ex.ztk_a11y_ptr(), n));
|
|
525
|
+
if (text === lastA11y) return;
|
|
526
|
+
lastA11y = text;
|
|
527
|
+
tree.replaceChildren(...JSON.parse(text).map((node) => {
|
|
528
|
+
const el = document.createElement("div");
|
|
529
|
+
el.setAttribute("role", ARIA[node.role] || "generic");
|
|
530
|
+
el.setAttribute("aria-label", node.name);
|
|
531
|
+
el.dataset.path = node.path;
|
|
532
|
+
if (node.role === "check box" || node.role === "radio button") el.setAttribute("aria-checked", String(node.selected));
|
|
533
|
+
if (node.disabled) el.setAttribute("aria-disabled", "true");
|
|
534
|
+
el.style.cssText = `position:absolute;left:${node.x}px;top:${node.y}px;width:${node.w}px;height:${node.h}px;opacity:0;`;
|
|
535
|
+
return el;
|
|
536
|
+
}));
|
|
537
|
+
};
|
|
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
|
+
|
|
610
|
+
let raf = 0;
|
|
611
|
+
const loop = (t) => {
|
|
612
|
+
setScreen();
|
|
613
|
+
const n = ex.ztk_frame(t);
|
|
614
|
+
if (n >= 0) draw(n);
|
|
615
|
+
drawPops();
|
|
616
|
+
raf = requestAnimationFrame(loop);
|
|
617
|
+
};
|
|
618
|
+
// options.loop false leaves the frames to the page, for a test.
|
|
619
|
+
if (options.loop !== false) raf = requestAnimationFrame(loop);
|
|
620
|
+
const addFile = (name, text) => withBytes(name, (pn, nn) => withBytes(text, (pt, nt) => ex.ztk_add_file(pn, nn, pt, nt)));
|
|
621
|
+
const frame = (t) => {
|
|
622
|
+
if (signal.aborted) return -1;
|
|
623
|
+
setScreen();
|
|
624
|
+
const n = ex.ztk_frame(t);
|
|
625
|
+
if (n >= 0) draw(n);
|
|
626
|
+
drawPops();
|
|
627
|
+
return n;
|
|
628
|
+
};
|
|
629
|
+
// The window of the script gets a new logical size.
|
|
630
|
+
const resize = (w, h) => ex.ztk_resize(Math.max(1, Math.round(w)), Math.max(1, Math.round(h)), scaleNow());
|
|
631
|
+
// "dark", "light", or "auto" (the color scheme of the page).
|
|
632
|
+
const setTheme = (theme) => {
|
|
633
|
+
forceDark = theme === "dark" ? true : theme === "light" ? false : undefined;
|
|
634
|
+
ex.ztk_dark(forceDark ?? dark.matches);
|
|
635
|
+
};
|
|
636
|
+
const destroy = () => {
|
|
637
|
+
if (signal.aborted) return;
|
|
638
|
+
life.abort();
|
|
639
|
+
cancelAnimationFrame(raf);
|
|
640
|
+
renderer?.destroy();
|
|
641
|
+
input.remove();
|
|
642
|
+
tree.remove();
|
|
643
|
+
layer.remove();
|
|
644
|
+
};
|
|
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 };
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/// Mounts a ztk app on an element. `el` is a canvas, or an element that
|
|
655
|
+
/// gets a new canvas. Options:
|
|
656
|
+
/// script Tcl text to run, after the files.
|
|
657
|
+
/// files { name: text } for `ztk::style load`, for example a style sheet.
|
|
658
|
+
/// theme "auto" (the default: the color scheme of the page), "light", or "dark".
|
|
659
|
+
/// size "auto" (the default: the size of the element at the start,
|
|
660
|
+
/// and then the size the window computes), "fill" (the window
|
|
661
|
+
/// follows the size of the element), or [width, height] in
|
|
662
|
+
/// logical pixels (the canvas shows the window at its CSS size).
|
|
663
|
+
/// renderer "auto" (the default), "webgpu", "webgl2", or "cpu".
|
|
664
|
+
/// scale The device pixels in one logical pixel. The default is devicePixelRatio.
|
|
665
|
+
/// module, wasm, log As for start().
|
|
666
|
+
/// A script error destroys the app and rejects with the error text.
|
|
667
|
+
export async function mount(el, options = {}) {
|
|
668
|
+
if (!el || typeof el.appendChild !== "function") throw new Error("ztk.mount: el must be an element");
|
|
669
|
+
const own = !(el instanceof HTMLCanvasElement);
|
|
670
|
+
const canvas = own ? document.createElement("canvas") : el;
|
|
671
|
+
const { size = "auto", theme = "auto" } = options;
|
|
672
|
+
if (own) {
|
|
673
|
+
// With "fill", the canvas has no part in the layout of the element,
|
|
674
|
+
// so the size of the element comes from the page only.
|
|
675
|
+
canvas.style.cssText = size === "fill" ? "display:block;touch-action:none;position:absolute;left:0;top:0;" : "display:block;touch-action:none;";
|
|
676
|
+
el.appendChild(canvas);
|
|
677
|
+
}
|
|
678
|
+
const opts = { module: options.module, wasm: options.wasm, log: options.log, scale: options.scale, renderer: options.renderer };
|
|
679
|
+
if (theme !== "auto") opts.dark = theme === "dark";
|
|
680
|
+
if (Array.isArray(size)) [opts.width, opts.height] = size;
|
|
681
|
+
else if (size && typeof size === "object") ({ width: opts.width, height: opts.height } = size);
|
|
682
|
+
let app;
|
|
683
|
+
try {
|
|
684
|
+
app = await start(canvas, opts);
|
|
685
|
+
} catch (e) {
|
|
686
|
+
if (own) canvas.remove();
|
|
687
|
+
throw e;
|
|
688
|
+
}
|
|
689
|
+
const destroy = app.destroy;
|
|
690
|
+
let observer = null;
|
|
691
|
+
if (size === "fill" && typeof ResizeObserver !== "undefined") {
|
|
692
|
+
observer = new ResizeObserver(([entry]) => {
|
|
693
|
+
const r = entry.contentRect;
|
|
694
|
+
if (r.width > 0 && r.height > 0) app.resize(r.width, r.height);
|
|
695
|
+
});
|
|
696
|
+
observer.observe(canvas.parentElement);
|
|
697
|
+
}
|
|
698
|
+
app.destroy = () => {
|
|
699
|
+
observer?.disconnect();
|
|
700
|
+
destroy();
|
|
701
|
+
if (own) app.canvas.remove();
|
|
702
|
+
};
|
|
703
|
+
for (const [name, text] of Object.entries(options.files || {})) app.addFile(name, text);
|
|
704
|
+
if (options.script != null) {
|
|
705
|
+
const r = app.eval(options.script);
|
|
706
|
+
if (!r.ok) {
|
|
707
|
+
app.destroy();
|
|
708
|
+
const err = new Error(r.result);
|
|
709
|
+
err.result = r;
|
|
710
|
+
throw err;
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
app.frame(performance.now());
|
|
714
|
+
return app;
|
|
715
|
+
}
|