@mathzetta/qblur 0.1.0 → 0.2.0

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/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
- if (pool === null) pool = await createPool(wanted, compiled.passes, options.workerUrl).catch(() => false); // false: workers can't start here
102
- if (!pool) return runner.draw({ t, canvas });
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 = () => (pool.shared ? new Float32Array(new SharedArrayBuffer(n * 4)) : new Float32Array(n));
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 pool.broadcast({ type: 'picture', name, picture: pool.shared ? sharedPicture(picture) : picture });
114
+ await ready.broadcast({ type: 'picture', name, picture: ready.shared ? sharedPicture(picture) : picture });
109
115
  sent.set(name, picture);
110
116
  }
111
- let input = pool.shared ? sharedPicture(source).data : source.data;
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, pool.size);
124
- const replies = await Promise.all(bands.map(([y0, y1], k) => pool.ask(k, {
125
- type: 'run', pass: i, input, output: pool.shared ? output : null, width, height, t, params,
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 (!pool.shared) replies.forEach((r, k) => output.set(r.band, bands[k][0] * width * 4));
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 (pool) pool.close();
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 ??= { data, width: picture.width, height: picture.height };
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: () => workers.forEach((w) => w.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
@@ -4,61 +4,85 @@
4
4
  * The same language as the shaders (mathzetta/glsl's filterShader): the
5
5
  * same names (r g b a x y px py w h t gray rgb unchanged), the same
6
6
  * functions (pixel, blur, gaussian, sobel, zoom, the pictures a filter
7
- * names…), the same rules for turning a number or a colour into a pixel.
7
+ * names…), the same rules for turning a number or a color into a pixel.
8
8
  * The GLSL is typed and so is this: every node of the expression gets a
9
9
  * type — float, bool, vec2, vec3 or vec4 — and becomes one local variable
10
10
  * per component inside a loop over the pixels. No vector objects exist at
11
11
  * run time; a filter is one straight-line loop body.
12
12
  *
13
- * Neighbourhood functions whose argument is the same for every pixel
13
+ * Neighborhood functions whose argument is the same for every pixel
14
14
  * (blur(radius) with radius a parameter) are worked out once per pass,
15
15
  * over the whole picture and separably — blur, gaussian, dilate and erode
16
16
  * over a square are a horizontal pass then a vertical one, the same sums
17
17
  * in a different order — then read per pixel. An argument that changes
18
- * per pixel falls back to computing that pixel's neighbourhood directly.
18
+ * per pixel falls back to computing that pixel's neighborhood directly.
19
19
  *
20
20
  * The generated code is compiled with new Function only after mathzetta's
21
21
  * checkGeneratedJs has passed it: every name in it is one this file
22
22
  * generates ($-prefixed) or a Math member, it holds no strings, and only
23
23
  * the arrays made here can be indexed. A filter is user input — shared by
24
- * link, pasted as JSON — and can read the picture and write colours,
24
+ * link, pasted as JSON — and can read the picture and write colors,
25
25
  * nothing else.
26
26
  */
27
27
 
28
28
  import { parseTree } from 'mathzetta';
29
29
  import { checkGeneratedJs } from 'mathzetta/formulas';
30
- import { FILTER_VALUES, FILTER_FUNCTIONS, NEIGHBOURHOOD, COLOUR_FUNCTIONS, filterPictureCalls } from 'mathzetta/glsl';
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)', '°': '(Math.PI / 180)' }); // 30° as the shader's radians(30.0)
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})))`,
45
48
  csc: (x) => `(1 / Math.sin(${x}))`, sec: (x) => `(1 / Math.cos(${x}))`, cot: (x) => `(1 / Math.tan(${x}))`,
46
49
  fract: (x) => `(${x} - Math.floor(${x}))`, radians: (x) => `(${x} * 0.017453292519943295)`, degrees: (x) => `(${x} * 57.29577951308232)`,
47
50
  inversesqrt: (x) => `(1 / Math.sqrt(${x}))`,
51
+ // as MathZetta's shaders write them: acos(1/x), asin(1/x), π/2 − atan(x)
52
+ arcsec: (x) => `Math.acos(1 / ${x})`, arccsc: (x) => `Math.asin(1 / ${x})`, arccot: (x) => `(Math.PI / 2 - Math.atan(${x}))`,
48
53
  atan2: (y, x) => `Math.atan2(${y}, ${x})`, pow: (x, y) => `Math.pow(${x}, ${y})`,
49
54
  mod: (x, y) => `(${x} - ${y} * Math.floor(${x} / ${y}))`,
50
55
  step: (edge, x) => `(${x} < ${edge} ? 0 : 1)`,
51
56
  clamp: (x, lo, hi) => `Math.min(Math.max(${x}, ${lo}), ${hi})`,
52
57
  mix: (a, b, k) => `(${a} + (${b} - ${a}) * ${k})`,
53
58
  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 };
59
+ });
60
+ const FIXED_ARITY = table({ atan2: 2, pow: 2, mod: 2, step: 2, clamp: 3, mix: 3, smoothstep: 3 });
61
+
62
+ /** y ∈ {x | P} (or {x ∈ S | P}) as the test it stands for: P with y for x; null for any other membership. */
63
+ function setCondition(node) {
64
+ const [y, set] = node.args;
65
+ if (set.type !== 'op' || set.op !== 'setbuilder') return null;
66
+ let [element, condition] = set.args;
67
+ let domain = null;
68
+ if (element.type === 'op' && element.op === '∈') [element, domain] = element.args;
69
+ const put = (n) => (n.type === 'symbol' && n.value === element.value ? y : n.type === 'op' ? { ...n, args: n.args.map(put) } : n);
70
+ const test = domain ? { type: 'op', op: '&', args: [{ type: 'op', op: '∈', args: [y, domain] }, put(condition)] } : put(condition);
71
+ return node.op === '∉' ? { type: 'op', op: '\\not', args: [test] } : test;
72
+ }
56
73
 
57
- /** Neighbourhood functions: the result kind, and whether the per-pass plane is computed once for a constant argument. */
58
- const PLANES = {
74
+ /** [F]_a^b (F x a b evaluated) as F with b put in for x, minus F with a: what MathZetta's GLSL writes. */
75
+ function evaluationDifference(node) {
76
+ const [body, variable, lo, hi] = node.args;
77
+ const put = (n, value) => (n.type === 'symbol' && n.value === variable.value ? value : n.type === 'op' ? { ...n, args: n.args.map((a) => put(a, value)) } : n);
78
+ return { type: 'op', op: '-', args: [put(body, hi), put(body, lo)] };
79
+ }
80
+
81
+ /** Neighborhood functions: the result kind, and whether the per-pass plane is computed once for a constant argument. */
82
+ const PLANES = table({
59
83
  blur: 3, blurx: 3, blury: 3, gaussian: 3, gaussianx: 3, gaussiany: 3, dilate: 3, erode: 3, sharpen: 3,
60
84
  sobel: 1, sobelx: 1, sobely: 1, laplacian: 1, emboss: 1,
61
- };
85
+ });
62
86
 
63
87
  /** A value: a kind ('f' number, 'b' true/false, 'v' vector) and one JS expression per component. */
64
88
  const val = (kind, c) => ({ kind, c });
@@ -81,7 +105,7 @@ export function compileCpuPass(pass) {
81
105
  const pictures = new Set([...Object.keys(pass.placements ?? {}), 'source', 'selection']);
82
106
  const g = new Generator(params, pictures, pass.space ?? 'srgb');
83
107
  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
108
+ g.bind = table(pass.bind ?? {}); // a graphic's name here → the key its picture is bound under
85
109
  const channels = typeof pass.color === 'string' ? { rgba: pass.color } : pass.color;
86
110
  const parse = (text, whole) => {
87
111
  const names = [...FILTER_FUNCTIONS, ...Object.keys(pass.placements ?? {})];
@@ -138,8 +162,10 @@ class Generator {
138
162
 
139
163
  leaf(node) {
140
164
  if (node.type === 'number') return f(`(${node.value.replace(/\.+$/, '')})`);
141
- if (node.type === 'string') this.fail('a filter has no text: numbers and colours only');
165
+ if (node.type === 'string') this.fail('a filter has no text: numbers and colors only');
142
166
  const v = node.value;
167
+ const percent = /^(-?(?:\d+\.?\d*|\.\d+))%$/.exec(v);
168
+ if (percent) return f(`(${percent[1]} / 100)`); // 50% is 0.5, as in the shader
143
169
  if (v === 't') this.uses.add('t'); // the filter animates (the page hides time for a still one)
144
170
  if (SCALARS[v]) return f(SCALARS[v]);
145
171
  if (v === 'rgb') return vec(['$r', '$g', '$b']);
@@ -156,7 +182,7 @@ class Generator {
156
182
  this.fail(`unknown name "${v}"`);
157
183
  }
158
184
 
159
- /** A named picture's colour at this pixel (vec4), sampled once per pixel. */
185
+ /** A named picture's color at this pixel (vec4), sampled once per pixel. */
160
186
  pictureHere(name) {
161
187
  if (!this.perPixel.has(name)) {
162
188
  const s = this.sampler(name, '$px', '$py');
@@ -175,7 +201,7 @@ class Generator {
175
201
  this.pictureNames.add(name);
176
202
  this.body.push(`$h_picture($Q_${name}, $qw_${name}, $qh_${name}, $w, $h, $qz_${name}, $qx_${name}, $qy_${name}, $qa_${name}, $qm_${name}, ${X}, ${Y}, ${out});`);
177
203
  }
178
- if (this.space && name !== 'selection') this.body.push(`$h_col_to${this.space}(${out}[0], ${out}[1], ${out}[2], ${out});`); // a mask is not a colour
204
+ if (this.space && name !== 'selection') this.body.push(`$h_col_to${this.space}(${out}[0], ${out}[1], ${out}[2], ${out});`); // a mask is not a color
179
205
  return vec([0, 1, 2, 3].map((k) => `${out}[${k}]`));
180
206
  }
181
207
 
@@ -221,6 +247,8 @@ class Generator {
221
247
  case '\\xor': { const [a, b] = A(); return bool(`(${this.truth(a)} !== ${this.truth(b)})`); }
222
248
  case '\\nand': { const [a, b] = A(); return bool(`!(${this.truth(a)} && ${this.truth(b)})`); }
223
249
  case '\\nor': { const [a, b] = A(); return bool(`!(${this.truth(a)} || ${this.truth(b)})`); }
250
+ case '\\implies': { const [a, b] = A(); return bool(`(!${this.truth(a)} || ${this.truth(b)})`); }
251
+ case '\\iff': { const [a, b] = A(); return bool(`(${this.truth(a)} === ${this.truth(b)})`); }
224
252
  case '\\not': { const [a] = A(); return bool(`!${this.truth(a)}`); }
225
253
  case '?:': return this.ternary(args);
226
254
  case 'max': case 'min': return this.componentwise(A(), (...xs) => `Math.${op}(${xs.join(', ')})`);
@@ -229,7 +257,7 @@ class Generator {
229
257
  case 'mean': return this.componentwise(A(), (...xs) => `((${xs.join(' + ')}) / ${xs.length})`);
230
258
  case '()': case '[]': case '{}': case '(]': case '[)': {
231
259
  const parts = A().flatMap((v) => (v.kind === 'b' ? [num(v)] : v.c.map((_, k) => num(v, k))));
232
- if (parts.length > 4) this.fail('a colour has at most 4 values (r, g, b, a)');
260
+ if (parts.length > 4) this.fail('a color has at most 4 values (r, g, b, a)');
233
261
  return vec(parts);
234
262
  }
235
263
  case '!': return this.componentwise(A(), (x) => `$h_factorial(${x})`);
@@ -238,12 +266,16 @@ class Generator {
238
266
  case 'gcd': return this.componentwise(A(), (...xs) => xs.reduce((acc, x) => `$h_gcd(${acc}, ${x})`));
239
267
  case 'round': {
240
268
  const [v, d] = A();
241
- return this.componentwise([v, d], (x, digits) => `(Math.floor(${x} * Math.pow(10, ${digits}) + 0.5) / Math.pow(10, ${digits}))`);
269
+ return this.componentwise([v, d], (x, digits) => `$h_round(${x}, ${digits})`);
242
270
  }
243
271
  case 'log': { const [base, x] = A(); return this.componentwise([base, x], (b, xx) => `(Math.log(${xx}) / Math.log(${b}))`); }
244
272
  case 'root': { const [n, x] = A(); return this.componentwise([n, x], (nn, xx) => `$h_root(${nn}, ${xx})`); }
245
- case '∈': case '∉': return this.membership(node);
273
+ case '∈': case '∉': {
274
+ const test = setCondition(node); // y ∈ {x | P}: P with y for x, as the shader writes it
275
+ return test ? this.value(test) : this.membership(node);
276
+ }
246
277
  case 'random': return this.random();
278
+ case 'evaluated': return this.value(evaluationDifference(node)); // [F]_a^b: F at b minus F at a, as the shader writes it
247
279
  case '_': {
248
280
  const [a, b] = args;
249
281
  if (a.type === 'symbol' && (b.type === 'number' || b.type === 'symbol')) return this.leaf({ type: 'symbol', value: `${a.value}_${b.value}` });
@@ -313,7 +345,8 @@ class Generator {
313
345
  const [lo, hi] = set.args.map((a) => num(this.value(a)));
314
346
  test = `(${v} ${set.op[0] === '[' ? '>=' : '>'} ${lo} && ${v} ${set.op[1] === ']' ? '<=' : '<'} ${hi})`;
315
347
  } else if (set.type === 'op' && set.op === '{}') {
316
- test = `(${set.args.map((item) => `${v} === ${num(this.value(item))}`).join(' || ')})`;
348
+ // ∅ (an empty {}): nothing is in it — `false`, as the shader's
349
+ test = set.args.length ? `(${set.args.map((item) => `${v} === ${num(this.value(item))}`).join(' || ')})` : 'false';
317
350
  } else if (set.type === 'symbol' && ['ℝ', 'ℤ', 'ℕ'].includes(set.value)) {
318
351
  test = { 'ℝ': `Number.isFinite(${v})`, 'ℤ': `Number.isInteger(${v})`, 'ℕ': `(Number.isInteger(${v}) && ${v} > 0)` }[set.value];
319
352
  } else this.fail('∈ needs an interval [a, b], a set {…}, ℝ, ℤ or ℕ');
@@ -325,7 +358,7 @@ class Generator {
325
358
  return f(this.temp('$h_random($px, $py, $h, ++$seed)'));
326
359
  }
327
360
 
328
- // ---- functions: pictures, geometry, neighbourhoods, GLSL built-ins ------------
361
+ // ---- functions: pictures, geometry, neighborhoods, GLSL built-ins ------------
329
362
 
330
363
  call(name, args, node) {
331
364
  const A = () => args.map((a) => this.value(a));
@@ -369,7 +402,7 @@ class Generator {
369
402
  let v;
370
403
  if (args.length === 2) v = this.call('pixel', args);
371
404
  else if (args.length === 1) v = this.value(args[0]);
372
- else this.fail(`${name}() takes a colour, or a position px, py`);
405
+ else this.fail(`${name}() takes a color, or a position px, py`);
373
406
  const k = { red: 0, green: 1, blue: 2, alpha: 3 }[name];
374
407
  if (name === 'luma') return f(`(${num(v, 0)} * 0.299 + ${num(v, 1)} * 0.587 + ${num(v, 2)} * 0.114)`);
375
408
  if (name === 'alpha' && size(v) === 3) return f('1');
@@ -393,7 +426,7 @@ class Generator {
393
426
  }
394
427
  case 'cross': {
395
428
  const [a, b] = A();
396
- if (size(a) !== 3 || size(b) !== 3) this.fail('cross() takes two colours (3 values each)');
429
+ if (size(a) !== 3 || size(b) !== 3) this.fail('cross() takes two colors (3 values each)');
397
430
  const [x1, y1, z1] = a.c; const [x2, y2, z2] = b.c;
398
431
  return this.keep(vec([`(${y1} * ${z2} - ${z1} * ${y2})`, `(${z1} * ${x2} - ${x1} * ${z2})`, `(${x1} * ${y2} - ${y1} * ${x2})`]));
399
432
  }
@@ -409,8 +442,8 @@ class Generator {
409
442
  case 'tolinear': case 'fromlinear': case 'tohsv': case 'fromhsv': case 'tohsl': case 'fromhsl':
410
443
  case 'tolab': case 'fromlab': case 'tooklab': case 'fromoklab': case 'toycbcr': case 'fromycbcr': {
411
444
  const a = A();
412
- const c = a.length === 3 ? a.map((v) => num(v)) : [0, 1, 2].map((k) => num(a[0], k)); // a colour, or three numbers
413
- if (a.length !== 1 && a.length !== 3) this.fail(`${name}() takes a colour`);
445
+ const c = a.length === 3 ? a.map((v) => num(v)) : [0, 1, 2].map((k) => num(a[0], k)); // a color, or three numbers
446
+ if (a.length !== 1 && a.length !== 3) this.fail(`${name}() takes a color`);
414
447
  const out = this.scratchArray();
415
448
  this.body.push(`$h_col_${name}(${c.join(', ')}, ${out});`);
416
449
  return this.keep(vec([0, 1, 2].map((k) => `${out}[${k}]`)));
@@ -426,7 +459,7 @@ class Generator {
426
459
  case 'log': return this.builtin('ln', A());
427
460
  case 'max': case 'min': return this.componentwise(A(), (...xs) => `Math.${name}(${xs.join(', ')})`);
428
461
  }
429
- if (PLANES[name]) return this.neighbourhood(name, args);
462
+ if (PLANES[name]) return this.neighborhood(name, args);
430
463
  this.fail(`unknown function "${name}"`);
431
464
  }
432
465
 
@@ -466,9 +499,9 @@ class Generator {
466
499
 
467
500
  /**
468
501
  * blur(radius) and friends. With an argument the same for every pixel (numbers, params, t),
469
- * the whole plane is computed once before the loop; otherwise this pixel's neighbourhood is.
502
+ * the whole plane is computed once before the loop; otherwise this pixel's neighborhood is.
470
503
  */
471
- neighbourhood(name, args) {
504
+ neighborhood(name, args) {
472
505
  const kind = PLANES[name];
473
506
  const constant = args.every((a) => this.isUniform(a));
474
507
  if (constant) {
@@ -509,7 +542,7 @@ class Generator {
509
542
 
510
543
  // ---- assembling the pass ------------------------------------------------------
511
544
 
512
- /** One channel line of the colour, as filterShader writes it (mz_keep, then mz_rgba / mz_rgb / mz_ch_*). */
545
+ /** One channel line of the color, as filterShader writes it (mz_keep, then mz_rgba / mz_rgb / mz_ch_*). */
513
546
  channel(ch, tree) {
514
547
  const keepValue = ch === 'rgba' || ch === 'rgb' ? '$gray' : `$c${'rgba'.indexOf(ch)}`;
515
548
  this.body.push(`$u = ${keepValue}; $k0 = $c0; $k1 = $c1; $k2 = $c2; $k3 = $c3;`);
@@ -517,11 +550,11 @@ class Generator {
517
550
  const n = size(v);
518
551
  const comp = (k) => num(v, k);
519
552
  if (ch === 'rgba') {
520
- if (n === 2) this.fail('a colour is one number (grey), three (r, g, b) or four (r, g, b, a) — not two');
553
+ if (n === 2) this.fail('a color is one number (gray), three (r, g, b) or four (r, g, b, a) — not two');
521
554
  const c = n === 1 ? [comp(0), comp(0), comp(0), '1'] : n === 3 ? [comp(0), comp(1), comp(2), '1'] : [0, 1, 2, 3].map(comp);
522
555
  this.body.push(`$c0 = ${c[0]}; $c1 = ${c[1]}; $c2 = ${c[2]}; $c3 = ${c[3]};`);
523
556
  } else if (ch === 'rgb') {
524
- if (n === 2) this.fail('a colour is one number (grey), three (r, g, b) or four — not two');
557
+ if (n === 2) this.fail('a color is one number (gray), three (r, g, b) or four — not two');
525
558
  const c = n === 1 ? [comp(0), comp(0), comp(0)] : [comp(0), comp(1), comp(2)];
526
559
  this.body.push(`$c0 = ${c[0]}; $c1 = ${c[1]}; $c2 = ${c[2]};`);
527
560
  } else {
package/src/element.d.ts CHANGED
@@ -3,7 +3,7 @@ export declare class QBlurImage extends HTMLElement {
3
3
  static readonly observedAttributes: string[];
4
4
  /** The drawing, a 2D canvas the picture's size (for toBlob). */
5
5
  readonly canvas: HTMLCanvasElement;
6
- /** Maths, a built-in filter's name, filter JSON or a share link (the `filter` attribute). */
6
+ /** Math, a built-in filter's name, filter JSON or a share link (the `filter` attribute). */
7
7
  filter: string;
8
8
  /** Knob values; set an object, or the `params` attribute as JSON. */
9
9
  params: Record<string, number | [number, number, number]>;
package/src/element.js CHANGED
@@ -1,13 +1,13 @@
1
1
  /**
2
2
  * <qblur-image>: a picture with a filter on it, as an HTML element.
3
3
  *
4
- * <script type="module" src="https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.1/dist/qblur-element.js"></script>
5
- * <qblur-image src="photo.jpg" filter="Sepia" alt="The harbour at dusk"></qblur-image>
4
+ * <script type="module" src="https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.2/dist/qblur-element.js"></script>
5
+ * <qblur-image src="photo.jpg" filter="Sepia" alt="The harbor at dusk"></qblur-image>
6
6
  * <qblur-image src="photo.jpg" filter="if gray > cutoff then 1 else 0" params='{"cutoff": 0.4}'></qblur-image>
7
7
  *
8
8
  * Attributes (each change redraws):
9
9
  * src the picture's address (from another site it must allow CORS; add crossorigin)
10
- * filter maths, a built-in filter's name, filter JSON or a share link
10
+ * filter math, a built-in filter's name, filter JSON or a share link
11
11
  * params JSON of knob values, { "name": value } — or set the `params` property to an object
12
12
  * (whichever was set last counts)
13
13
  * t the frame, for filters that move
package/src/format.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Shareable image filters.
3
3
  *
4
- * A filter is a small JSON document anyone can publish — maths plus a
4
+ * A filter is a small JSON document anyone can publish — math plus a
5
5
  * name, an author, the knobs it exposes and the pictures it needs:
6
6
  *
7
7
  * { "format": "mathzetta-filter/1",
@@ -23,8 +23,8 @@
23
23
  *
24
24
  * A chain is a filter too, so published chains nest inside new ones and
25
25
  * keep their authors' names (compileFilter() lists them as credits).
26
- * Because a filter is only maths, sharing one is safe: it can read the
27
- * picture and write colours, nothing else.
26
+ * Because a filter is only math, sharing one is safe: it can read the
27
+ * picture and write colors, nothing else.
28
28
  *
29
29
  * normalizeFilter() fills in defaults and rejects bad shapes,
30
30
  * validateFilter() lists every problem, and compileFilter() flattens a
@@ -33,13 +33,16 @@
33
33
  * to pass one around; readFilter() accepts either, or a bare expression.
34
34
  */
35
35
  import { filterShader } from 'mathzetta/glsl';
36
- import { FILTER_NAMES, PLACES, COLOUR_SPACES } from 'mathzetta/glsl';
36
+ import { FILTER_NAMES, PLACES, COLOR_SPACES } from 'mathzetta/glsl';
37
37
  import { normalizeGraphic, shadowLayerNames, MAX_SHADOW_LAYERS } from './graphics.js';
38
38
 
39
39
  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([
@@ -96,7 +99,7 @@ export function normalizeFilter(def) {
96
99
  }
97
100
 
98
101
  /**
99
- * The filter's page: Markdown text (with maths: Inline Math draws it, and `{{k}}` is a knob's value)
102
+ * The filter's page: Markdown text (with math: Inline Math draws it, and `{{k}}` is a knob's value)
100
103
  * and where each knob's input goes — `["Darker below the *cutoff*:", { "param": "cutoff" }]`.
101
104
  * Knobs it doesn't place come before it.
102
105
  */
@@ -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 in params)) throw new Error(`"notes" places "${block.param}", but there is no parameter called that`);
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
  }
@@ -114,10 +117,10 @@ function normalizeNotes(notes, params) {
114
117
  function normalizeSpace(space) {
115
118
  if (space === undefined || space === null) return null;
116
119
  const pair = typeof space === 'string' ? { in: space, out: space } : space;
117
- if (!isObject(pair)) throw new Error(`"space" is a colour space (${COLOUR_SPACES.join(', ')}) or { "in": …, "out": … }`);
120
+ if (!isObject(pair)) throw new Error(`"space" is a color space (${COLOR_SPACES.join(', ')}) or { "in": …, "out": … }`);
118
121
  const out = { in: pair.in ?? 'srgb', out: pair.out ?? 'srgb' };
119
122
  for (const key of ['in', 'out']) {
120
- if (!COLOUR_SPACES.includes(out[key])) throw new Error(`"space": "${out[key]}" is not a colour space; they are ${COLOUR_SPACES.join(', ')}`);
123
+ if (!COLOR_SPACES.includes(out[key])) throw new Error(`"space": "${out[key]}" is not a color space; they are ${COLOR_SPACES.join(', ')}`);
121
124
  }
122
125
  return out.in === 'srgb' && out.out === 'srgb' ? null : out;
123
126
  }
@@ -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 (name in params || name in images) throw new Error(`"${name}" is both a graphic and a parameter or picture`);
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 in out)) out[name] = g;
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 in params) throw new Error(`"${name}" is both a parameter and an image`);
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;
@@ -212,7 +216,7 @@ function normalizeParams(params) {
212
216
  return out;
213
217
  }
214
218
 
215
- /** `0.5` → a number 0–1; `[1, 0, 0]` → a colour; or the full `{ type, default, min, max, step, label }`. */
219
+ /** `0.5` → a number 0–1; `[1, 0, 0]` → a color; or the full `{ type, default, min, max, step, label }`. */
216
220
  function normalizeParam(name, spec) {
217
221
  if (typeof spec === 'number') spec = { default: spec };
218
222
  else if (Array.isArray(spec)) spec = { type: 'color', default: spec };
@@ -222,12 +226,12 @@ function normalizeParam(name, spec) {
222
226
  if (spec.label !== undefined) out.label = String(spec.label);
223
227
  if (type === 'color') {
224
228
  const value = spec.default ?? [1, 1, 1];
225
- if (!isColor(value)) throw new Error(`Colour parameter "${name}" needs a default of three numbers, 0–1`);
229
+ if (!isColor(value)) throw new Error(`Color parameter "${name}" needs a default of three numbers, 0–1`);
226
230
  out.default = value.map(Number);
227
231
  return out;
228
232
  }
229
233
  if (type !== 'number') throw new Error(`Parameter "${name}": the type is "number" or "color", not "${type}"`);
230
- // `options`: a choice of values (a menu); `input: "box"`: typed in, as maths; otherwise a slider
234
+ // `options`: a choice of values (a menu); `input: "box"`: typed in, as math; otherwise a slider
231
235
  let options = null;
232
236
  if (spec.options !== undefined) {
233
237
  if (!Array.isArray(spec.options) || !spec.options.length || !spec.options.every((n) => n !== '' && Number.isFinite(Number(n)))) throw new Error(`Parameter "${name}": "options" is a list of numbers`);
@@ -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(...options, value) : Math.min(0, value * 2);
241
- out.max = spec.max !== undefined ? Number(spec.max) : options ? Math.max(...options, value) : Math.max(1, value * 2);
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 in out)) out[name] = image;
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 in out)) out[name] = param;
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,26 +305,26 @@ 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 in graphics) { // changing a graphic: { text, x, color, … }
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 in images) { // placing a picture: { place, zoom, x, y, angle }
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
- problems.push(`${where}: "${name}" should be a ${param.type === 'color' ? 'colour: three numbers, 0–1' : 'number'}`);
320
+ problems.push(`${where}: "${name}" should be a ${param.type === 'color' ? 'color: three numbers, 0–1' : 'number'}`);
317
321
  }
318
322
  }
319
323
  if (filter.steps) {
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]) => k in (filter.graphics ?? {}))), 1, path, 100); } catch (e) { problems.push(`${where}: ${e.message}`); } // with its settings: a "with" may add shadow layers
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,7 +372,12 @@ 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
371
- const rewritten = inColourSpace(step.filter) ?? separableBlur(step.filter);
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
+ }
380
+ const rewritten = inColorSpace(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
374
383
  flatten({ ...step, filter: rewritten }, path, outer, context);
@@ -398,7 +407,7 @@ function flatten(step, path, outer, context) {
398
407
  }
399
408
 
400
409
  /**
401
- * A step whose whole colour is just `gaussian(s)` or `blur(r)` is computed
410
+ * A step whose whole color is just `gaussian(s)` or `blur(r)` is computed
402
411
  * separably — one pass along x, one along y: the same blur for 2n taps
403
412
  * instead of n², and reaching further (±24 pixels instead of ±8). The
404
413
  * step keeps its name, params, pictures and opacity; the two passes share
@@ -411,7 +420,7 @@ function flatten(step, path, outer, context) {
411
420
  * converted too — then convert back. Opacity blends the result over
412
421
  * the input in sRGB, as any chain's does.
413
422
  */
414
- function inColourSpace(filter) {
423
+ function inColorSpace(filter) {
415
424
  if (!filter.space || typeof filter.color === 'undefined') return null;
416
425
  const { space, name, author, description, ...core } = filter; // the chain carries the name; the middle step is nameless, so it is not a credit
417
426
  const step = (f) => ({ filter: f, with: {}, opacity: 1, skip: false });
@@ -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 in settings)) values[name] = param.default;
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 = {};