@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/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
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Types of ztk.js: Tk widgets in a browser, drawn by ztk.wasm.
|
|
2
|
+
// SPDX-License-Identifier: BSD-2-Clause
|
|
3
|
+
|
|
4
|
+
/** A renderer. "auto" selects the first one that the browser has, in the order of {@link renderers}. */
|
|
5
|
+
export type Renderer = "auto" | "webgpu" | "webgl2" | "cpu";
|
|
6
|
+
|
|
7
|
+
/** The color scheme of the app. "auto" follows `prefers-color-scheme` of the page. */
|
|
8
|
+
export type Theme = "auto" | "light" | "dark";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The size of the window of the script, in logical pixels.
|
|
12
|
+
*
|
|
13
|
+
* - "auto": the size of the element at the start. Then the window gets
|
|
14
|
+
* the size of its widgets, as a Tk toplevel does.
|
|
15
|
+
* - "fill": the window follows the size of the element. Give the element a size.
|
|
16
|
+
* - `[width, height]` or `{ width, height }`: a fixed logical size. The
|
|
17
|
+
* canvas shows the window at the CSS size that the page gives it.
|
|
18
|
+
*/
|
|
19
|
+
export type Size = "auto" | "fill" | [number, number] | { width: number; height: number };
|
|
20
|
+
|
|
21
|
+
/** The result of one `eval`. */
|
|
22
|
+
export interface EvalResult {
|
|
23
|
+
/** True when the script ended with no error. */
|
|
24
|
+
ok: boolean;
|
|
25
|
+
/** The value of the script, or the error message when `ok` is false. */
|
|
26
|
+
result: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The options of {@link mount}. */
|
|
30
|
+
export interface MountOptions {
|
|
31
|
+
/** Tcl text with Tk commands. It runs after `files` are added. */
|
|
32
|
+
script?: string;
|
|
33
|
+
/** Files by name for `ztk::style load`, for example `{ "app.css": text }`. */
|
|
34
|
+
files?: Record<string, string>;
|
|
35
|
+
/** The color scheme. The default is "auto". */
|
|
36
|
+
theme?: Theme;
|
|
37
|
+
/** The size of the window. The default is "auto". */
|
|
38
|
+
size?: Size;
|
|
39
|
+
/** The renderer. The default is "auto": WebGPU, else WebGL 2, else the CPU renderer. */
|
|
40
|
+
renderer?: Renderer;
|
|
41
|
+
/** The device pixels in one logical pixel. The default is `devicePixelRatio`. */
|
|
42
|
+
scale?: number;
|
|
43
|
+
/** A module from {@link compileModule}, so that many apps compile `ztk.wasm` one time. */
|
|
44
|
+
module?: WebAssembly.Module;
|
|
45
|
+
/** The URL of `ztk.wasm`. The default is {@link wasmURL}. */
|
|
46
|
+
wasm?: string | URL;
|
|
47
|
+
/** Gets the text of `puts` and the error messages. The default is `console.log`. */
|
|
48
|
+
log?: (text: string) => void;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The options of {@link start}. */
|
|
52
|
+
export interface StartOptions {
|
|
53
|
+
module?: WebAssembly.Module;
|
|
54
|
+
wasm?: string | URL;
|
|
55
|
+
renderer?: Renderer;
|
|
56
|
+
/** True for dark, false for light, undefined for the color scheme of the page. */
|
|
57
|
+
dark?: boolean;
|
|
58
|
+
/** A fixed logical width. Give it with `height`. */
|
|
59
|
+
width?: number;
|
|
60
|
+
/** A fixed logical height. Give it with `width`. */
|
|
61
|
+
height?: number;
|
|
62
|
+
scale?: number;
|
|
63
|
+
log?: (text: string) => void;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A running ztk app on a canvas. */
|
|
67
|
+
export interface App {
|
|
68
|
+
/** Runs Tcl text in the interpreter of the app. The next frame shows the change. */
|
|
69
|
+
eval(script: string): EvalResult;
|
|
70
|
+
/** Adds a file by name for `ztk::style load`. */
|
|
71
|
+
addFile(name: string, text: string): boolean;
|
|
72
|
+
/** Gives the window of the script a new logical size. */
|
|
73
|
+
resize(width: number, height: number): void;
|
|
74
|
+
/** Sets the color scheme. */
|
|
75
|
+
setTheme(theme: Theme): void;
|
|
76
|
+
/**
|
|
77
|
+
* Stops the frame loop, removes the event listeners and the elements
|
|
78
|
+
* that the app added, and frees the renderer. Drop the object after this call.
|
|
79
|
+
*/
|
|
80
|
+
destroy(): void;
|
|
81
|
+
/** Runs the events and draws one frame now, at the time `ms`. Returns the count of quads, or -1 when no frame was drawn. */
|
|
82
|
+
frame(ms: number): number;
|
|
83
|
+
/** The canvas of the app. */
|
|
84
|
+
readonly canvas: HTMLCanvasElement;
|
|
85
|
+
/** The renderer in use. */
|
|
86
|
+
readonly renderer: "webgl2" | "cpu";
|
|
87
|
+
/** The hidden elements with ARIA roles that follow the widgets. */
|
|
88
|
+
readonly tree: HTMLDivElement;
|
|
89
|
+
/** Aborts when the app is destroyed. */
|
|
90
|
+
readonly signal: AbortSignal;
|
|
91
|
+
/** The exports of the WebAssembly instance, for tests and tools. */
|
|
92
|
+
readonly exports: WebAssembly.Exports;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Mounts a ztk app on an element.
|
|
97
|
+
* @param el A canvas, or an element that gets a new canvas.
|
|
98
|
+
* @returns The app, after the script ran and the first frame is drawn.
|
|
99
|
+
* A script error destroys the app and rejects with the error message,
|
|
100
|
+
* and the error has the field `result`.
|
|
101
|
+
*
|
|
102
|
+
* @example
|
|
103
|
+
* const app = await mount(document.getElementById("app"), {
|
|
104
|
+
* script: "button .b -text Hello; pack .b",
|
|
105
|
+
* });
|
|
106
|
+
* app.eval(".b configure -text Bye");
|
|
107
|
+
* app.destroy();
|
|
108
|
+
*/
|
|
109
|
+
export function mount(el: HTMLElement, options?: MountOptions): Promise<App>;
|
|
110
|
+
|
|
111
|
+
/** Starts ztk.wasm on a canvas. {@link mount} is the API for a page. */
|
|
112
|
+
export function start(canvas: HTMLCanvasElement, options?: StartOptions): Promise<App>;
|
|
113
|
+
|
|
114
|
+
/** Compiles `ztk.wasm` one time for each URL. The default is {@link wasmURL}. */
|
|
115
|
+
export function compileModule(url?: string | URL): Promise<WebAssembly.Module>;
|
|
116
|
+
|
|
117
|
+
/** The URL of the `ztk.wasm` file next to `ztk.js`. */
|
|
118
|
+
export function wasmURL(): URL;
|
|
119
|
+
|
|
120
|
+
/** The renderers of this version, in the order of "auto". */
|
|
121
|
+
export const renderers: readonly ("webgl2" | "cpu")[];
|