@mathzetta/qblur 0.1.0 → 0.1.2
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/CHANGELOG.md +29 -0
- package/LICENSE +1 -1
- package/README.md +13 -4
- package/dist/cpu-worker.js +2 -2
- package/dist/qblur-apply.js +2 -2
- package/dist/qblur-element.js +2 -2
- package/dist/qblur.core.js +2 -2
- package/dist/qblur.external.global.min.js +2 -2
- package/dist/qblur.external.js +2 -2
- package/dist/qblur.global.min.js +2 -2
- package/dist/qblur.js +2 -2
- package/docs/filters.md +1 -1
- package/docs/library.md +3 -6
- package/package.json +8 -2
- package/src/cpu-helpers.js +2 -0
- package/src/cpu-runner.js +26 -12
- package/src/cpu.js +15 -10
- package/src/format.js +22 -13
- package/src/graphics.js +1 -1
- package/src/png.js +3 -0
- package/src/runtime.js +25 -6
- package/src/strokes.js +11 -3
package/docs/filters.md
CHANGED
package/docs/library.md
CHANGED
|
@@ -5,10 +5,6 @@ WebGL shaders, with the same pixels from plain JavaScript where there is no GPU.
|
|
|
5
5
|
with one `<script>` from a CDN — no build step, no server, nothing uploaded: the pictures stay in the
|
|
6
6
|
visitor's browser.
|
|
7
7
|
|
|
8
|
-
> **Not on npm yet.** The CDN addresses below (`cdn.jsdelivr.net/npm/@mathzetta/qblur@0.1/…`) are where every
|
|
9
|
-
> release will be, and start working with the first one. Until then, `npm run build` in the repository
|
|
10
|
-
> writes the same files to `dist/`: serve them yourself and change the address.
|
|
11
|
-
|
|
12
8
|
## What you can do with it
|
|
13
9
|
|
|
14
10
|
- **Filters on your pictures, live.** Any `<img>`, `<canvas>`, `<video>` or webcam — sepia, blur,
|
|
@@ -190,7 +186,7 @@ at one file:
|
|
|
190
186
|
```
|
|
191
187
|
|
|
192
188
|
With classic scripts: `<script src="…/mathzetta@1/build/mathzetta.glsl.min.js">` (the GLSL flavour, which
|
|
193
|
-
is what filters use) and then
|
|
189
|
+
is what filters use) and then `…/@mathzetta/qblur@0.1/dist/qblur.external.global.min.js`.
|
|
194
190
|
|
|
195
191
|
Pin a version (`@0.1` follows fixes, `@0.1.0` never changes) and, for a fixed version, add an `integrity`
|
|
196
192
|
hash so the browser checks the file. jsDelivr shows each file's hash on its package page, or make it
|
|
@@ -601,4 +597,5 @@ Everything the package exports — from `@mathzetta/qblur/apply`, the first seve
|
|
|
601
597
|
more where the effect needs it (bloom, edge strengths).
|
|
602
598
|
- **Big pictures.** WebGL limits a texture to `gl.getParameter(gl.MAX_TEXTURE_SIZE)` (often 4096 or more);
|
|
603
599
|
the CPU has no limit but takes longer — `drawAsync` uses every core.
|
|
604
|
-
- **Licence.** MIT.
|
|
600
|
+
- **Licence.** MIT ([LICENSE](https://github.com/triplelog/qblur/blob/main/LICENSE), Copyright (c) 2025-2026 Robert Wilcox), and so is
|
|
601
|
+
MathZetta, which the bundles include. The object models used by the editor's "find objects" are not in the package.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mathzetta/qblur",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Shareable image filters written as maths: a JSON format with params, pictures and chains, compiled to WebGL shaders by MathZetta.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "src/index.js",
|
|
@@ -67,7 +67,7 @@
|
|
|
67
67
|
"check:docs": "node tools/check-docs.mjs"
|
|
68
68
|
},
|
|
69
69
|
"peerDependencies": {
|
|
70
|
-
"mathzetta": "^1.
|
|
70
|
+
"mathzetta": "^1.2.0"
|
|
71
71
|
},
|
|
72
72
|
"devDependencies": {
|
|
73
73
|
"@mathzetta/inlinemath": "file:../mathzetta/packages/inlinemath",
|
|
@@ -105,10 +105,16 @@
|
|
|
105
105
|
},
|
|
106
106
|
"keywords": [
|
|
107
107
|
"image",
|
|
108
|
+
"image-processing",
|
|
108
109
|
"filter",
|
|
110
|
+
"photo-filter",
|
|
109
111
|
"webgl",
|
|
110
112
|
"shader",
|
|
111
113
|
"glsl",
|
|
114
|
+
"canvas",
|
|
115
|
+
"gif",
|
|
116
|
+
"web-component",
|
|
117
|
+
"maths",
|
|
112
118
|
"mathzetta"
|
|
113
119
|
]
|
|
114
120
|
}
|
package/src/cpu-helpers.js
CHANGED
|
@@ -29,6 +29,8 @@ export function smoothstep(e0, e1, x) { const t = Math.min(Math.max((x - e0) / (
|
|
|
29
29
|
export function factorial(n) { let r = 1; for (let i = 2; i <= 170; i++) { if (i > n) break; r *= i; } return r; }
|
|
30
30
|
export function perm(n, k) { let r = 1; for (let i = 0; i < 170; i++) { if (i >= k) break; r *= n - i; } return r; }
|
|
31
31
|
export function gcd(a, b) { a = Math.abs(a); b = Math.abs(b); for (let i = 0; i < 64; i++) { if (b === 0) break; const t = fmod(a, b); a = b; b = t; } return a; }
|
|
32
|
+
/** Halves go away from zero, as the shader's mz_round and every other MathZetta output round. */
|
|
33
|
+
export function round(x, digits) { const p = Math.pow(10, digits); return Math.sign(x) * Math.floor(Math.abs(x) * p + 0.5) / p; }
|
|
32
34
|
export function root(n, x) { return n === 2 ? Math.sqrt(x) : n === 3 ? Math.sign(x) * Math.pow(Math.abs(x), 1 / 3) : Math.pow(x, 1 / n); }
|
|
33
35
|
/** The shader's hash: a new value per pixel and per call, seeded with t. (A GPU's float sin differs, so the values do too.) */
|
|
34
36
|
export function random(px, py, h, seed) {
|
package/src/cpu-runner.js
CHANGED
|
@@ -36,6 +36,7 @@ export function createCpuRunner(compiled, options = {}) {
|
|
|
36
36
|
const parallelFrom = options.parallelFrom ?? 250000;
|
|
37
37
|
const wanted = options.workers === undefined || options.workers === 'auto' ? defaultWorkers() : Number(options.workers);
|
|
38
38
|
let pool = null; // created on the first drawAsync() that needs it
|
|
39
|
+
let starting = null; // the promise of that pool: every call shares one
|
|
39
40
|
let sent = new Map(); // picture name → the object last sent to the pool
|
|
40
41
|
|
|
41
42
|
const runner = {
|
|
@@ -98,17 +99,22 @@ export function createCpuRunner(compiled, options = {}) {
|
|
|
98
99
|
if (!source) throw new Error('setImage() first');
|
|
99
100
|
const { width, height } = source;
|
|
100
101
|
if (wanted < 2 || width * height < parallelFrom) return runner.draw({ t, canvas });
|
|
101
|
-
|
|
102
|
-
|
|
102
|
+
// one pool, however many calls arrive before it is ready; false: workers can't start here
|
|
103
|
+
starting ??= createPool(wanted, compiled.passes, options.workerUrl).catch(() => false);
|
|
104
|
+
const mine = starting;
|
|
105
|
+
const ready = await mine;
|
|
106
|
+
if (mine !== starting) throw new Error('The runner was disposed of while drawing');
|
|
107
|
+
pool = ready;
|
|
108
|
+
if (!ready) return runner.draw({ t, canvas });
|
|
103
109
|
const n = width * height * 4;
|
|
104
|
-
const alloc = () => (
|
|
110
|
+
const alloc = () => (ready.shared ? new Float32Array(new SharedArrayBuffer(n * 4)) : new Float32Array(n));
|
|
105
111
|
// pictures the workers haven't seen (as shared copies when we can share)
|
|
106
112
|
for (const [name, picture] of [['source', source], ...Object.entries(pictures)]) {
|
|
107
113
|
if (sent.get(name) === picture) continue;
|
|
108
|
-
await
|
|
114
|
+
await ready.broadcast({ type: 'picture', name, picture: ready.shared ? sharedPicture(picture) : picture });
|
|
109
115
|
sent.set(name, picture);
|
|
110
116
|
}
|
|
111
|
-
let input =
|
|
117
|
+
let input = ready.shared ? sharedPicture(source).data : source.data;
|
|
112
118
|
const kept = [];
|
|
113
119
|
for (let i = 0; i < compiled.passes.length; i++) {
|
|
114
120
|
const pass = compiled.passes[i];
|
|
@@ -120,12 +126,12 @@ export function createCpuRunner(compiled, options = {}) {
|
|
|
120
126
|
if (precision === 'byte') quantize(output);
|
|
121
127
|
} else {
|
|
122
128
|
const params = Object.keys(pass.params ?? {}).map((name) => pass.values[name]);
|
|
123
|
-
const bands = splitRows(height,
|
|
124
|
-
const replies = await Promise.all(bands.map(([y0, y1], k) =>
|
|
125
|
-
type: 'run', pass: i, input, output:
|
|
129
|
+
const bands = splitRows(height, ready.size);
|
|
130
|
+
const replies = await Promise.all(bands.map(([y0, y1], k) => ready.ask(k, {
|
|
131
|
+
type: 'run', pass: i, input, output: ready.shared ? output : null, width, height, t, params,
|
|
126
132
|
opacity: pass.opacity, placements: pass.placements ?? {}, y0, y1, quantize: precision === 'byte',
|
|
127
133
|
})));
|
|
128
|
-
if (!
|
|
134
|
+
if (!ready.shared) replies.forEach((r, k) => output.set(r.band, bands[k][0] * width * 4));
|
|
129
135
|
}
|
|
130
136
|
input = output;
|
|
131
137
|
}
|
|
@@ -146,7 +152,8 @@ export function createCpuRunner(compiled, options = {}) {
|
|
|
146
152
|
dispose() {
|
|
147
153
|
source = null;
|
|
148
154
|
for (const k of Object.keys(pictures)) delete pictures[k];
|
|
149
|
-
if (
|
|
155
|
+
if (starting) starting.then((p) => p && p.close()); // also a pool still starting
|
|
156
|
+
starting = null;
|
|
150
157
|
pool = null;
|
|
151
158
|
sent = new Map();
|
|
152
159
|
},
|
|
@@ -205,9 +212,10 @@ const canShare = () => typeof SharedArrayBuffer !== 'undefined' && (typeof cross
|
|
|
205
212
|
|
|
206
213
|
function sharedPicture(picture) {
|
|
207
214
|
if (picture.data.buffer instanceof (globalThis.SharedArrayBuffer ?? Object)) return picture;
|
|
215
|
+
if (picture.shared) return picture.shared; // copied once, not on every draw
|
|
208
216
|
const data = new Float32Array(new SharedArrayBuffer(picture.data.byteLength));
|
|
209
217
|
data.set(picture.data);
|
|
210
|
-
picture.shared
|
|
218
|
+
picture.shared = { data, width: picture.width, height: picture.height };
|
|
211
219
|
return picture.shared;
|
|
212
220
|
}
|
|
213
221
|
|
|
@@ -254,7 +262,13 @@ async function createPool(size, passes, workerUrl) {
|
|
|
254
262
|
const pool = {
|
|
255
263
|
size, shared: canShare(), ask,
|
|
256
264
|
broadcast: (message) => Promise.all(workers.map((_, k) => ask(k, message))),
|
|
257
|
-
close: () =>
|
|
265
|
+
close: () => {
|
|
266
|
+
workers.forEach((w) => w.close());
|
|
267
|
+
for (const asked of waiting) { // nobody waits for an answer that can't come
|
|
268
|
+
for (const [, cb] of asked) cb.reject(new Error('The runner was disposed of while drawing'));
|
|
269
|
+
asked.clear();
|
|
270
|
+
}
|
|
271
|
+
},
|
|
258
272
|
};
|
|
259
273
|
try {
|
|
260
274
|
await pool.broadcast({ type: 'init', passes: passes.map(({ fragment, ...rest }) => rest) });
|
package/src/cpu.js
CHANGED
|
@@ -27,18 +27,21 @@
|
|
|
27
27
|
|
|
28
28
|
import { parseTree } from 'mathzetta';
|
|
29
29
|
import { checkGeneratedJs } from 'mathzetta/formulas';
|
|
30
|
-
import { FILTER_VALUES, FILTER_FUNCTIONS,
|
|
30
|
+
import { FILTER_VALUES, FILTER_FUNCTIONS, filterPictureCalls } from 'mathzetta/glsl';
|
|
31
31
|
import * as H from './cpu-helpers.js';
|
|
32
32
|
|
|
33
33
|
const CUSTOM = '\\:';
|
|
34
34
|
const HELPERS = Object.keys(H).filter((k) => typeof H[k] === 'function');
|
|
35
35
|
|
|
36
|
+
/** A lookup table with no inherited names: `constructor` and `toString` are a filter's own names, never Object's. */
|
|
37
|
+
const table = (entries) => Object.assign(Object.create(null), entries);
|
|
38
|
+
|
|
36
39
|
/** Constants and leaves every expression has. */
|
|
37
|
-
const SCALARS = { r: '$r', g: '$g', b: '$b', a: '$a', x: '$x', y: '$y', px: '$px', py: '$py', w: '$w', h: '$h', t: '$t', gray: '$gray' };
|
|
38
|
-
const CONSTANTS = { pi: 'Math.PI', 'π': 'Math.PI', e: 'Math.E', tau: '(2 * Math.PI)', 'τ': '(2 * Math.PI)', '∞': 'Infinity', '-∞': '(-Infinity)' };
|
|
40
|
+
const SCALARS = table({ r: '$r', g: '$g', b: '$b', a: '$a', x: '$x', y: '$y', px: '$px', py: '$py', w: '$w', h: '$h', t: '$t', gray: '$gray' });
|
|
41
|
+
const CONSTANTS = table({ pi: 'Math.PI', 'π': 'Math.PI', e: 'Math.E', tau: '(2 * Math.PI)', 'τ': '(2 * Math.PI)', '∞': 'Infinity', '-∞': '(-Infinity)' });
|
|
39
42
|
|
|
40
43
|
/** Functions applied to each component: name → (args as JS) => JS. */
|
|
41
|
-
const COMPONENTWISE = {
|
|
44
|
+
const COMPONENTWISE = table({
|
|
42
45
|
sqrt: 1, abs: 1, floor: 1, ceil: 1, ln: 'log', sin: 1, cos: 1, tan: 1, arcsin: 'asin', arccos: 'acos', arctan: 'atan',
|
|
43
46
|
sinh: 1, cosh: 1, tanh: 1, arcsinh: 'asinh', arccosh: 'acosh', arctanh: 'atanh', sign: 1, exp: 1, exp2: (x) => `Math.pow(2, ${x})`,
|
|
44
47
|
log2: 1, expm1: (x) => `(Math.exp(${x}) - 1)`, loglog: (x) => `Math.log(Math.log(${x}))`, logloglog: (x) => `Math.log(Math.log(Math.log(${x})))`,
|
|
@@ -51,14 +54,14 @@ const COMPONENTWISE = {
|
|
|
51
54
|
clamp: (x, lo, hi) => `Math.min(Math.max(${x}, ${lo}), ${hi})`,
|
|
52
55
|
mix: (a, b, k) => `(${a} + (${b} - ${a}) * ${k})`,
|
|
53
56
|
smoothstep: (e0, e1, x) => `$h_smoothstep(${e0}, ${e1}, ${x})`,
|
|
54
|
-
};
|
|
55
|
-
const FIXED_ARITY = { atan2: 2, pow: 2, mod: 2, step: 2, clamp: 3, mix: 3, smoothstep: 3 };
|
|
57
|
+
});
|
|
58
|
+
const FIXED_ARITY = table({ atan2: 2, pow: 2, mod: 2, step: 2, clamp: 3, mix: 3, smoothstep: 3 });
|
|
56
59
|
|
|
57
60
|
/** Neighbourhood functions: the result kind, and whether the per-pass plane is computed once for a constant argument. */
|
|
58
|
-
const PLANES = {
|
|
61
|
+
const PLANES = table({
|
|
59
62
|
blur: 3, blurx: 3, blury: 3, gaussian: 3, gaussianx: 3, gaussiany: 3, dilate: 3, erode: 3, sharpen: 3,
|
|
60
63
|
sobel: 1, sobelx: 1, sobely: 1, laplacian: 1, emboss: 1,
|
|
61
|
-
};
|
|
64
|
+
});
|
|
62
65
|
|
|
63
66
|
/** A value: a kind ('f' number, 'b' true/false, 'v' vector) and one JS expression per component. */
|
|
64
67
|
const val = (kind, c) => ({ kind, c });
|
|
@@ -81,7 +84,7 @@ export function compileCpuPass(pass) {
|
|
|
81
84
|
const pictures = new Set([...Object.keys(pass.placements ?? {}), 'source', 'selection']);
|
|
82
85
|
const g = new Generator(params, pictures, pass.space ?? 'srgb');
|
|
83
86
|
g.graphics = new Set(Object.keys(pass.graphics ?? {})); // drawn by the caller; transparent until they are
|
|
84
|
-
g.bind = pass.bind ?? {}; // a graphic's name here → the key its picture is bound under
|
|
87
|
+
g.bind = table(pass.bind ?? {}); // a graphic's name here → the key its picture is bound under
|
|
85
88
|
const channels = typeof pass.color === 'string' ? { rgba: pass.color } : pass.color;
|
|
86
89
|
const parse = (text, whole) => {
|
|
87
90
|
const names = [...FILTER_FUNCTIONS, ...Object.keys(pass.placements ?? {})];
|
|
@@ -140,6 +143,8 @@ class Generator {
|
|
|
140
143
|
if (node.type === 'number') return f(`(${node.value.replace(/\.+$/, '')})`);
|
|
141
144
|
if (node.type === 'string') this.fail('a filter has no text: numbers and colours only');
|
|
142
145
|
const v = node.value;
|
|
146
|
+
const percent = /^(-?(?:\d+\.?\d*|\.\d+))%$/.exec(v);
|
|
147
|
+
if (percent) return f(`(${percent[1]} / 100)`); // 50% is 0.5, as in the shader
|
|
143
148
|
if (v === 't') this.uses.add('t'); // the filter animates (the page hides time for a still one)
|
|
144
149
|
if (SCALARS[v]) return f(SCALARS[v]);
|
|
145
150
|
if (v === 'rgb') return vec(['$r', '$g', '$b']);
|
|
@@ -238,7 +243,7 @@ class Generator {
|
|
|
238
243
|
case 'gcd': return this.componentwise(A(), (...xs) => xs.reduce((acc, x) => `$h_gcd(${acc}, ${x})`));
|
|
239
244
|
case 'round': {
|
|
240
245
|
const [v, d] = A();
|
|
241
|
-
return this.componentwise([v, d], (x, digits) =>
|
|
246
|
+
return this.componentwise([v, d], (x, digits) => `$h_round(${x}, ${digits})`);
|
|
242
247
|
}
|
|
243
248
|
case 'log': { const [base, x] = A(); return this.componentwise([base, x], (b, xx) => `(Math.log(${xx}) / Math.log(${b}))`); }
|
|
244
249
|
case 'root': { const [n, x] = A(); return this.componentwise([n, x], (nn, xx) => `$h_root(${nn}, ${xx})`); }
|
package/src/format.js
CHANGED
|
@@ -40,6 +40,9 @@ export const FILTER_FORMAT = 'mathzetta-filter/1';
|
|
|
40
40
|
|
|
41
41
|
const CHANNELS = ['r', 'g', 'b', 'a', 'rgb', 'rgba'];
|
|
42
42
|
const NAME = /^[A-Za-z][A-Za-z0-9_]*$/;
|
|
43
|
+
/** More than any real filter has; a document built to exhaust the page (thousands of shaders or frame-sized pictures) is refused. */
|
|
44
|
+
const MAX_PASSES = 256;
|
|
45
|
+
const MAX_GRAPHICS = 64;
|
|
43
46
|
|
|
44
47
|
/** Names a parameter can't take: what every expression already has, and GLSL's own words. */
|
|
45
48
|
const RESERVED = new Set([
|
|
@@ -105,7 +108,7 @@ function normalizeNotes(notes, params) {
|
|
|
105
108
|
return notes.map((block) => {
|
|
106
109
|
if (typeof block === 'string') return block;
|
|
107
110
|
if (!isObject(block) || typeof block.param !== 'string' || Object.keys(block).length !== 1) throw new Error('"notes": each entry is a Markdown text or { "param": name }');
|
|
108
|
-
if (!(block.param
|
|
111
|
+
if (!Object.hasOwn(params, block.param)) throw new Error(`"notes" places "${block.param}", but there is no parameter called that`);
|
|
109
112
|
return { param: block.param };
|
|
110
113
|
});
|
|
111
114
|
}
|
|
@@ -125,11 +128,12 @@ function normalizeSpace(space) {
|
|
|
125
128
|
/** `{ "title": { "type": "text", "text": "Hello", … } }` → each spec in full (src/graphics.js). */
|
|
126
129
|
function normalizeGraphics(graphics, params, images) {
|
|
127
130
|
if (!isObject(graphics)) throw new Error('"graphics" is an object of name → { "type": "text" | "rect" | "ellipse", … }');
|
|
131
|
+
if (Object.keys(graphics).length > MAX_GRAPHICS) throw new Error(`A filter has at most ${MAX_GRAPHICS} graphics`);
|
|
128
132
|
const out = {};
|
|
129
133
|
for (const [name, spec] of Object.entries(graphics)) {
|
|
130
134
|
if (!NAME.test(name) || name.startsWith('mz_')) throw new Error(`Graphic name "${name}" must be letters, digits and _, starting with a letter`);
|
|
131
135
|
if (RESERVED.has(name) || name === 'source' || name === 'selection') throw new Error(`"${name}" is already defined in every filter; pick another graphic name`);
|
|
132
|
-
if (
|
|
136
|
+
if (Object.hasOwn(params, name) || Object.hasOwn(images, name)) throw new Error(`"${name}" is both a graphic and a parameter or picture`);
|
|
133
137
|
out[name] = normalizeGraphic(name, spec);
|
|
134
138
|
}
|
|
135
139
|
// name_shadow1… are the pictures of its shadow layers: no other name may be one
|
|
@@ -145,7 +149,7 @@ export function filterGraphics(filter) {
|
|
|
145
149
|
if (filter.color) return { ...(filter.graphics ?? {}) };
|
|
146
150
|
const out = {};
|
|
147
151
|
for (const step of filter.steps) {
|
|
148
|
-
for (const [name, g] of Object.entries(filterGraphics(step.filter))) if (!(name
|
|
152
|
+
for (const [name, g] of Object.entries(filterGraphics(step.filter))) if (!Object.hasOwn(out, name)) out[name] = g;
|
|
149
153
|
}
|
|
150
154
|
return out;
|
|
151
155
|
}
|
|
@@ -159,7 +163,7 @@ function normalizeImages(images, params) {
|
|
|
159
163
|
if (!NAME.test(name) || name.startsWith('mz_')) throw new Error(`Image name "${name}" must be letters, digits and _, starting with a letter`);
|
|
160
164
|
if (name === 'source') throw new Error('"source" is always available: the picture the chain started from');
|
|
161
165
|
if (RESERVED.has(name)) throw new Error(`"${name}" is already defined in every filter; pick another image name`);
|
|
162
|
-
if (name
|
|
166
|
+
if (Object.hasOwn(params, name)) throw new Error(`"${name}" is both a parameter and an image`);
|
|
163
167
|
out[name] = normalizeImage(name, spec);
|
|
164
168
|
}
|
|
165
169
|
return out;
|
|
@@ -237,8 +241,8 @@ function normalizeParam(name, spec) {
|
|
|
237
241
|
const value = Number(spec.default ?? (options ? options[0] : 0));
|
|
238
242
|
if (!Number.isFinite(value)) throw new Error(`Parameter "${name}" needs a numeric default`);
|
|
239
243
|
out.default = value;
|
|
240
|
-
out.min = spec.min !== undefined ? Number(spec.min) : options ? Math.min(
|
|
241
|
-
out.max = spec.max !== undefined ? Number(spec.max) : options ? Math.max(
|
|
244
|
+
out.min = spec.min !== undefined ? Number(spec.min) : options ? options.reduce((a, b) => Math.min(a, b), value) : Math.min(0, value * 2);
|
|
245
|
+
out.max = spec.max !== undefined ? Number(spec.max) : options ? options.reduce((a, b) => Math.max(a, b), value) : Math.max(1, value * 2);
|
|
242
246
|
if (spec.step !== undefined) out.step = Number(spec.step);
|
|
243
247
|
if (options) out.options = options;
|
|
244
248
|
if (spec.input === 'box' && !options) out.input = 'box';
|
|
@@ -267,7 +271,7 @@ export function filterImages(filter) {
|
|
|
267
271
|
if (filter.color) return { ...(filter.images ?? {}) };
|
|
268
272
|
const out = {};
|
|
269
273
|
for (const step of filter.steps) {
|
|
270
|
-
for (const [name, image] of Object.entries(filterImages(step.filter))) if (!(name
|
|
274
|
+
for (const [name, image] of Object.entries(filterImages(step.filter))) if (!Object.hasOwn(out, name)) out[name] = image;
|
|
271
275
|
}
|
|
272
276
|
return out;
|
|
273
277
|
}
|
|
@@ -277,7 +281,7 @@ export function filterParams(filter) {
|
|
|
277
281
|
if (filter.color) return { ...(filter.params ?? {}) };
|
|
278
282
|
const out = {};
|
|
279
283
|
for (const step of filter.steps) {
|
|
280
|
-
for (const [name, param] of Object.entries(filterParams(step.filter))) if (!(name
|
|
284
|
+
for (const [name, param] of Object.entries(filterParams(step.filter))) if (!Object.hasOwn(out, name)) out[name] = param;
|
|
281
285
|
}
|
|
282
286
|
return out;
|
|
283
287
|
}
|
|
@@ -301,16 +305,16 @@ function check(step, path, problems, shaders) {
|
|
|
301
305
|
const images = filterImages(filter);
|
|
302
306
|
const graphics = filterGraphics(filter);
|
|
303
307
|
for (const [name, value] of Object.entries(step.with)) {
|
|
304
|
-
if (name
|
|
308
|
+
if (Object.hasOwn(graphics, name)) { // changing a graphic: { text, x, color, … }
|
|
305
309
|
if (!isObject(value)) problems.push(`${where}: "with" for the graphic "${name}" is an object of its settings`);
|
|
306
310
|
else try { normalizeGraphic(name, { ...graphics[name], ...value }); } catch (e) { problems.push(`${where}: ${e.message}`); }
|
|
307
311
|
continue;
|
|
308
312
|
}
|
|
309
|
-
if (name
|
|
313
|
+
if (Object.hasOwn(images, name)) { // placing a picture: { place, zoom, x, y, angle }
|
|
310
314
|
try { normalizeImage(name, value); } catch (e) { problems.push(`${where}: ${e.message}`); }
|
|
311
315
|
continue;
|
|
312
316
|
}
|
|
313
|
-
const param = params[name];
|
|
317
|
+
const param = Object.hasOwn(params, name) ? params[name] : null;
|
|
314
318
|
if (!param) problems.push(`${where}: "with" sets "${name}", but there is no parameter called that`);
|
|
315
319
|
else if (param.type === 'color' ? !isColor(value) : !Number.isFinite(Number(value))) {
|
|
316
320
|
problems.push(`${where}: "${name}" should be a ${param.type === 'color' ? 'colour: three numbers, 0–1' : 'number'}`);
|
|
@@ -320,7 +324,7 @@ function check(step, path, problems, shaders) {
|
|
|
320
324
|
filter.steps.forEach((inner, i) => check(inner, [...path, i], problems, shaders));
|
|
321
325
|
return;
|
|
322
326
|
}
|
|
323
|
-
if (shaders) try { makePass(filter, Object.fromEntries(Object.entries(step.with).filter(([k]) =>
|
|
327
|
+
if (shaders) try { makePass(filter, Object.fromEntries(Object.entries(step.with).filter(([k]) => Object.hasOwn(filter.graphics ?? {}, k))), 1, path, 100); } catch (e) { problems.push(`${where}: ${e.message}`); } // with its settings: a "with" may add shadow layers
|
|
324
328
|
}
|
|
325
329
|
|
|
326
330
|
function describe(filter, path) {
|
|
@@ -368,6 +372,11 @@ export function compileFilter(def, options = {}) {
|
|
|
368
372
|
|
|
369
373
|
function flatten(step, path, outer, context) {
|
|
370
374
|
if (step.skip) return; // switched off: no passes, no credit
|
|
375
|
+
if (context.passes.length > MAX_PASSES) {
|
|
376
|
+
const problem = `A filter has at most ${MAX_PASSES} passes`;
|
|
377
|
+
if (!context.problems.includes(problem)) context.problems.push(problem);
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
371
380
|
const rewritten = inColourSpace(step.filter) ?? separableBlur(step.filter);
|
|
372
381
|
if (rewritten) {
|
|
373
382
|
if (step.filter === context.top) context.top = rewritten; // still the filter itself, not something it uses
|
|
@@ -467,7 +476,7 @@ function makePass(filter, settings, opacity, path, version) {
|
|
|
467
476
|
const params = filter.params ?? {};
|
|
468
477
|
const values = {};
|
|
469
478
|
for (const [name, param] of Object.entries(params)) {
|
|
470
|
-
if (!(name
|
|
479
|
+
if (!Object.hasOwn(settings, name)) values[name] = param.default;
|
|
471
480
|
else values[name] = param.type === 'color' ? settings[name].map(Number) : Number(settings[name]);
|
|
472
481
|
}
|
|
473
482
|
const placements = {};
|
package/src/graphics.js
CHANGED
|
@@ -219,7 +219,7 @@ async function loadFace(spec, fonts) {
|
|
|
219
219
|
try {
|
|
220
220
|
let file = spec.fontUrl;
|
|
221
221
|
if (!/\.(woff2?|ttf|otf)(\?|$)/i.test(new URL(file).pathname) || googleFontFamily(file)) {
|
|
222
|
-
const css = await (await fetch(file)).text();
|
|
222
|
+
const css = await (await fetch(file, { credentials: 'omit', referrerPolicy: 'no-referrer' })).text();
|
|
223
223
|
file = fontFileFromCss(css, spec);
|
|
224
224
|
if (!file || !file.startsWith('https://')) return null;
|
|
225
225
|
}
|
package/src/png.js
CHANGED
|
@@ -88,6 +88,9 @@ function paeth(a, b, c) {
|
|
|
88
88
|
*/
|
|
89
89
|
export async function encodePng({ width, height, data, palette = 'auto', colours = 256, dither = true, quantize = null }) {
|
|
90
90
|
if (typeof CompressionStream === 'undefined') return null;
|
|
91
|
+
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || !data || data.length < width * height * 4) {
|
|
92
|
+
throw new Error('encodePng: width and height are whole numbers of pixels, and data holds 4 bytes for each');
|
|
93
|
+
}
|
|
91
94
|
let indexed = null;
|
|
92
95
|
if (palette === 'auto' || palette === 'force') {
|
|
93
96
|
indexed = exactPalette(data);
|
package/src/runtime.js
CHANGED
|
@@ -25,7 +25,15 @@ export function createFilterRunner(gl, compiled, options = {}) {
|
|
|
25
25
|
if (gl.isContextLost()) throw new Error('The WebGL context is lost');
|
|
26
26
|
const precision = texturePrecision(gl, options.precision);
|
|
27
27
|
const vertex = filterVertexShader({ version: compiled.version });
|
|
28
|
-
const programs =
|
|
28
|
+
const programs = [];
|
|
29
|
+
try {
|
|
30
|
+
for (const pass of compiled.passes) programs.push(link(gl, vertex, pass.fragment, pass.name));
|
|
31
|
+
} catch (error) {
|
|
32
|
+
for (const program of programs) gl.deleteProgram(program); // a later pass refused: the earlier ones go too
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
/** The key a pass's picture is bound under (a graphic's own key; a picture's name). */
|
|
36
|
+
const bound = (pass, name) => (pass.bind && Object.hasOwn(pass.bind, name) ? pass.bind[name] : name);
|
|
29
37
|
const locations = programs.map(() => new Map());
|
|
30
38
|
const location = (i, name) => {
|
|
31
39
|
if (!locations[i].has(name)) locations[i].set(name, gl.getUniformLocation(programs[i], name));
|
|
@@ -147,10 +155,10 @@ export function createFilterRunner(gl, compiled, options = {}) {
|
|
|
147
155
|
if (pass.blendKept) gl.uniform1i(location(i, 'base'), 1);
|
|
148
156
|
pass.images.forEach((name, k) => {
|
|
149
157
|
gl.activeTexture(gl.TEXTURE2 + k);
|
|
150
|
-
gl.bindTexture(gl.TEXTURE_2D, name === 'source' ? source.texture : (pictures.get(pass
|
|
158
|
+
gl.bindTexture(gl.TEXTURE_2D, name === 'source' ? source.texture : (pictures.get(bound(pass, name)) ?? (pass.graphics?.[name] ? clear : blank)));
|
|
151
159
|
gl.uniform1i(location(i, `mz_img_${name}`), 2 + k);
|
|
152
160
|
if (!pass.placements[name]) return; // source, selection: the frame's size, no placement
|
|
153
|
-
const size = sizes.get(pass
|
|
161
|
+
const size = sizes.get(bound(pass, name)) ?? [1, 1];
|
|
154
162
|
const place = pass.placements[name];
|
|
155
163
|
gl.uniform2f(location(i, `mz_size_${name}`), size[0], size[1]);
|
|
156
164
|
gl.uniform4f(location(i, `mz_place_${name}`), Number(place.zoom), Number(place.x), Number(place.y), Number(place.angle));
|
|
@@ -214,16 +222,27 @@ function texturePrecision(gl, wanted = 'byte') {
|
|
|
214
222
|
|
|
215
223
|
function link(gl, vertex, fragment, name) {
|
|
216
224
|
const program = gl.createProgram();
|
|
225
|
+
const shaders = [];
|
|
226
|
+
let problem = null;
|
|
217
227
|
for (const [type, source] of [[gl.VERTEX_SHADER, vertex], [gl.FRAGMENT_SHADER, fragment]]) {
|
|
218
228
|
const shader = gl.createShader(type);
|
|
229
|
+
shaders.push(shader);
|
|
219
230
|
gl.shaderSource(shader, source);
|
|
220
231
|
gl.compileShader(shader);
|
|
221
232
|
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
|
|
222
|
-
|
|
233
|
+
problem = `${name || 'The filter'} does not compile: ${(gl.getShaderInfoLog(shader) ?? '').trim()}`;
|
|
234
|
+
break;
|
|
223
235
|
}
|
|
224
236
|
gl.attachShader(program, shader);
|
|
225
237
|
}
|
|
226
|
-
|
|
227
|
-
|
|
238
|
+
if (!problem) {
|
|
239
|
+
gl.linkProgram(program);
|
|
240
|
+
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) problem = `${name || 'The filter'} does not link: ${(gl.getProgramInfoLog(program) ?? '').trim()}`;
|
|
241
|
+
}
|
|
242
|
+
for (const shader of shaders) gl.deleteShader(shader); // a linked program keeps what it needs of them
|
|
243
|
+
if (problem) {
|
|
244
|
+
gl.deleteProgram(program);
|
|
245
|
+
throw new Error(problem);
|
|
246
|
+
}
|
|
228
247
|
return program;
|
|
229
248
|
}
|
package/src/strokes.js
CHANGED
|
@@ -139,6 +139,9 @@ function hash(a, b) {
|
|
|
139
139
|
return ((x ^ (x >>> 16)) >>> 0) / 4294967296;
|
|
140
140
|
}
|
|
141
141
|
|
|
142
|
+
/** rasterizeStrokes() visits at most this many pixels per pixel of the frame in one call. */
|
|
143
|
+
const WORK_PER_PIXEL = 256;
|
|
144
|
+
|
|
142
145
|
const buffers = new Map();
|
|
143
146
|
function scratch(n) {
|
|
144
147
|
let b = buffers.get(n);
|
|
@@ -163,9 +166,13 @@ export function rasterizeStrokes(spec, w, h, t = Infinity, { mask = null } = {})
|
|
|
163
166
|
const now = Number.isFinite(t) ? t : total;
|
|
164
167
|
const base = Math.max(0.5, (spec.size * h) / 2); // brush radius in pixels
|
|
165
168
|
let dabCount = 0;
|
|
169
|
+
// Work one call may do, in pixels visited: a few hundred frames' worth. A drawing made by hand stays far
|
|
170
|
+
// under it; one built to stall the page (a huge brush crossing the frame for ever, a point a million frames
|
|
171
|
+
// away) stops painting when it runs out, and the page stays alive.
|
|
172
|
+
let budget = Math.max(n, 65536) * WORK_PER_PIXEL;
|
|
166
173
|
|
|
167
174
|
strokes.forEach((stroke) => {
|
|
168
|
-
if (stroke.start > now) return;
|
|
175
|
+
if (stroke.start > now || budget <= 0) return;
|
|
169
176
|
let used = 0;
|
|
170
177
|
const stamp = (x, y, r, f) => {
|
|
171
178
|
const k = dabCount++;
|
|
@@ -182,6 +189,7 @@ export function rasterizeStrokes(spec, w, h, t = Infinity, { mask = null } = {})
|
|
|
182
189
|
const reach = kind === 'marker' ? r : r + 1;
|
|
183
190
|
const x0 = Math.max(0, Math.floor(cx - reach)), x1 = Math.min(w - 1, Math.ceil(cx + reach));
|
|
184
191
|
const y0 = Math.max(0, Math.floor(cy - reach)), y1 = Math.min(h - 1, Math.ceil(cy + reach));
|
|
192
|
+
budget -= x1 >= x0 && y1 >= y0 ? (x1 - x0 + 1) * (y1 - y0 + 1) : 16; // off the frame: only the step
|
|
185
193
|
for (let py = y0; py <= y1; py++) {
|
|
186
194
|
for (let px = x0; px <= x1; px++) {
|
|
187
195
|
const dx = px + 0.5 - cx, dy = py + 0.5 - cy;
|
|
@@ -219,14 +227,14 @@ export function rasterizeStrokes(spec, w, h, t = Infinity, { mask = null } = {})
|
|
|
219
227
|
if (b.f > now) u1 = (now - a.f) / Math.max(1e-9, b.f - a.f);
|
|
220
228
|
const len = Math.hypot(bx - ax, by - ay);
|
|
221
229
|
let s = j === 1 ? 0 : carry;
|
|
222
|
-
while (s <= len * u1) {
|
|
230
|
+
while (s <= len * u1 && budget > 0) {
|
|
223
231
|
const u = len ? s / len : 0;
|
|
224
232
|
const r = base * (a.wf + (b.wf - a.wf) * u);
|
|
225
233
|
stamp(ax + (bx - ax) * u, ay + (by - ay) * u, r, a.f + (b.f - a.f) * u);
|
|
226
234
|
s += Math.max(0.5, spec.spacing * 2 * r);
|
|
227
235
|
}
|
|
228
236
|
carry = s - len;
|
|
229
|
-
if (u1 < 1) break;
|
|
237
|
+
if (u1 < 1 || budget <= 0) break;
|
|
230
238
|
}
|
|
231
239
|
// this stroke counts once wherever it went, however often it crossed itself
|
|
232
240
|
for (let k = 0; k < used; k++) {
|