@mathzetta/qblur 0.0.0-stage → 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 +58 -0
- package/LICENSE +21 -0
- package/README.md +152 -2
- package/dist/cpu-worker.js +2 -0
- package/dist/qblur-apply.js +2 -0
- package/dist/qblur-element.js +2 -0
- package/dist/qblur.core.js +2 -0
- package/dist/qblur.external.global.min.js +2 -0
- package/dist/qblur.external.js +2 -0
- package/dist/qblur.global.min.js +2 -0
- package/dist/qblur.js +2 -0
- package/docs/filters.md +841 -0
- package/docs/library.md +601 -0
- package/package.json +118 -4
- package/src/apply-filter.js +245 -0
- package/src/apply.d.ts +64 -0
- package/src/apply.js +14 -0
- package/src/auto.js +41 -0
- package/src/cpu-helpers.js +418 -0
- package/src/cpu-runner.js +282 -0
- package/src/cpu-worker.js +58 -0
- package/src/cpu.js +586 -0
- package/src/element.d.ts +16 -0
- package/src/element.js +142 -0
- package/src/format.js +614 -0
- package/src/graphics.js +305 -0
- package/src/index.d.ts +283 -0
- package/src/index.js +13 -0
- package/src/library.js +173 -0
- package/src/png.js +157 -0
- package/src/runtime.js +248 -0
- package/src/save.js +108 -0
- package/src/strokes.js +350 -0
package/src/graphics.js
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Text and shapes as pictures.
|
|
3
|
+
*
|
|
4
|
+
* A filter's `graphics` names things to draw — text, rectangles, ovals —
|
|
5
|
+
* each rasterized into a transparent picture the size of the frame under
|
|
6
|
+
* its name. The maths then treats it like any picture: `title` is its
|
|
7
|
+
* colour, `alpha(title)` where it is, so
|
|
8
|
+
*
|
|
9
|
+
* mix(rgb, title, alpha(title)) lays the text on
|
|
10
|
+
* mix(rgb, gaussian(6) * 0.8, alpha(panel)) frosts the picture behind a panel
|
|
11
|
+
* mix(rgb, shift(title, 3t, 0), alpha(shift(title, 3t, 0))) scrolls it
|
|
12
|
+
*
|
|
13
|
+
* A graphic's `shadow` is drawn into it. Its `shadows` — a list, back to
|
|
14
|
+
* front — are drawn each into a picture of its own, `title_shadow1`,
|
|
15
|
+
* `title_shadow2`…, so every shadow layer can have its own maths:
|
|
16
|
+
*
|
|
17
|
+
* mix(mix(rgb, gaussian(4), alpha(title_shadow1)), title, alpha(title))
|
|
18
|
+
* mix(mix(rgb, (1, 0.3, 0.6) , alpha(shift(title_shadow1, 2 sin(t / 9), 0))), title, alpha(title))
|
|
19
|
+
*
|
|
20
|
+
* Positions and sizes are fractions of the frame (x, y 0–1; sizes of its
|
|
21
|
+
* height), so a graphic drawn again at export size is crisp and in the
|
|
22
|
+
* same place. Angles are radians, like everything else here.
|
|
23
|
+
*
|
|
24
|
+
* normalizeGraphic(name, spec) the full spec, or an error naming what is wrong
|
|
25
|
+
* drawGraphic(ctx, spec, w, h) onto any 2D context (canvas, OffscreenCanvas)
|
|
26
|
+
* await loadGraphicFonts(graphics) web fonts named by fontUrl, before drawing
|
|
27
|
+
* await renderGraphics(compiled, w, h) → { key: canvas } for runner.setImage(key, canvas)
|
|
28
|
+
* (keys are the names, made unique across a chain: `title`, `title~2`…)
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import { normalizeStrokes, rasterizeStrokes } from './strokes.js';
|
|
32
|
+
|
|
33
|
+
export const GRAPHIC_TYPES = ['text', 'rect', 'ellipse', 'strokes'];
|
|
34
|
+
|
|
35
|
+
/** What each kind of graphic is, unless said otherwise. */
|
|
36
|
+
export const GRAPHIC_DEFAULTS = {
|
|
37
|
+
text: {
|
|
38
|
+
type: 'text', text: 'Text', font: 'sans-serif', weight: 'bold', style: 'normal', size: 0.08,
|
|
39
|
+
x: 0.5, y: 0.85, align: 'center', angle: 0, lineHeight: 1.2, color: '#ffffff',
|
|
40
|
+
outline: null, shadow: { color: 'rgba(0,0,0,0.6)', blur: 0.15, dx: 0.04, dy: 0.06 }, shadows: [],
|
|
41
|
+
},
|
|
42
|
+
rect: { type: 'rect', x: 0.5, y: 0.85, w: 0.8, h: 0.18, radius: 0.15, angle: 0, color: '#ffffff', outline: null, shadow: null, shadows: [] },
|
|
43
|
+
ellipse: { type: 'ellipse', x: 0.5, y: 0.5, w: 0.4, h: 0.4, angle: 0, color: '#ffffff', outline: null, shadow: null, shadows: [] },
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** At most this many separate shadow layers per graphic. */
|
|
47
|
+
export const MAX_SHADOW_LAYERS = 8;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The picture names of a graphic's separate shadow layers, back to front:
|
|
51
|
+
* title_shadow1, title_shadow2… Each is a picture of that shadow alone, so
|
|
52
|
+
* the maths can treat it on its own (blur it, colour it, move it with t).
|
|
53
|
+
*/
|
|
54
|
+
export const shadowLayerNames = (name, spec) => (spec.shadows ?? []).map((_, k) => `${name}_shadow${k + 1}`);
|
|
55
|
+
|
|
56
|
+
/** The maths that lays a graphic on with its shadow layers, back to front — what a new text step starts with. */
|
|
57
|
+
export function layeredExpression(name, spec) {
|
|
58
|
+
let base = 'rgb';
|
|
59
|
+
for (const layer of shadowLayerNames(name, spec)) base = `mix(${base}, ${layer}, alpha(${layer}))`;
|
|
60
|
+
return `mix(${base}, ${name}, alpha(${name}))`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const COLOUR = /^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d.,\s%deg/]+\)|[a-z]{3,20}|transparent)$/i;
|
|
64
|
+
const FAMILY = /^[\w\s,'"-]{1,80}$/;
|
|
65
|
+
const WEIGHTS = ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'];
|
|
66
|
+
|
|
67
|
+
function colour(name, key, value) {
|
|
68
|
+
if (typeof value !== 'string' || !COLOUR.test(value.trim())) throw new Error(`Graphic "${name}": "${key}" is a colour like "#ffcc00", "rgba(0,0,0,0.5)" or "white"`);
|
|
69
|
+
return value.trim();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function number(name, key, value, min = -Infinity, max = Infinity) {
|
|
73
|
+
const v = Number(value);
|
|
74
|
+
if (!Number.isFinite(v) || v < min || v > max) throw new Error(`Graphic "${name}": "${key}" is a number${Number.isFinite(min) ? ` from ${min} to ${max}` : ''}`);
|
|
75
|
+
return v;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** `{ color, width }` around the text or shape; width is a fraction of the text size (or of the frame height for shapes). */
|
|
79
|
+
function outline(name, value) {
|
|
80
|
+
if (value === null || value === false) return null;
|
|
81
|
+
if (typeof value !== 'object') throw new Error(`Graphic "${name}": "outline" is { "color", "width" } or null`);
|
|
82
|
+
return { color: colour(name, 'outline.color', value.color ?? '#000000'), width: number(name, 'outline.width', value.width ?? 0.06, 0, 1) };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** `{ color, blur, dx, dy }` behind it; blur and offsets are fractions of the text size (frame height for shapes). */
|
|
86
|
+
function shadow(name, value) {
|
|
87
|
+
if (value === null || value === false) return null;
|
|
88
|
+
if (typeof value !== 'object') throw new Error(`Graphic "${name}": "shadow" is { "color", "blur", "dx", "dy" } or null`);
|
|
89
|
+
return {
|
|
90
|
+
color: colour(name, 'shadow.color', value.color ?? 'rgba(0,0,0,0.6)'),
|
|
91
|
+
blur: number(name, 'shadow.blur', value.blur ?? 0.15, 0, 2),
|
|
92
|
+
dx: number(name, 'shadow.dx', value.dx ?? 0, -2, 2),
|
|
93
|
+
dy: number(name, 'shadow.dy', value.dy ?? 0, -2, 2),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The whole spec, defaults filled in; throws a message naming the graphic and the setting. */
|
|
98
|
+
export function normalizeGraphic(name, spec) {
|
|
99
|
+
if (!spec || typeof spec !== 'object' || Array.isArray(spec)) throw new Error(`Graphic "${name}": give { "type": "text" | "rect" | "ellipse", … }`);
|
|
100
|
+
const type = spec.type ?? 'text';
|
|
101
|
+
if (!GRAPHIC_TYPES.includes(type)) throw new Error(`Graphic "${name}": "type" is text, rect, ellipse or strokes — not "${type}"`);
|
|
102
|
+
if (type === 'strokes') return normalizeStrokes(name, spec); // brush strokes: src/strokes.js
|
|
103
|
+
const base = GRAPHIC_DEFAULTS[type];
|
|
104
|
+
for (const key of Object.keys(spec)) if (!(key in base) && key !== 'fontUrl' && key !== 'onlyShadow') throw new Error(`Graphic "${name}": no such setting "${key}" for ${type}`);
|
|
105
|
+
const out = { type };
|
|
106
|
+
for (const [key, fallback] of Object.entries(base)) {
|
|
107
|
+
if (key === 'type') continue;
|
|
108
|
+
const value = key in spec && spec[key] !== undefined ? spec[key] : fallback; // null is a value: "no shadow"
|
|
109
|
+
if (key === 'color') out.color = colour(name, key, value);
|
|
110
|
+
else if (key === 'outline') out.outline = outline(name, value);
|
|
111
|
+
else if (key === 'shadow') out.shadow = shadow(name, value);
|
|
112
|
+
else if (key === 'shadows') {
|
|
113
|
+
if (!Array.isArray(value) || value.length > MAX_SHADOW_LAYERS) throw new Error(`Graphic "${name}": "shadows" is a list of up to ${MAX_SHADOW_LAYERS} { "color", "blur", "dx", "dy" }`);
|
|
114
|
+
out.shadows = value.map((layer, k) => {
|
|
115
|
+
if (!layer || typeof layer !== 'object') throw new Error(`Graphic "${name}": shadow layer ${k + 1} is { "color", "blur", "dx", "dy" }`);
|
|
116
|
+
return shadow(name, layer);
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
else if (key === 'text') {
|
|
120
|
+
if (typeof value !== 'string' || value.length > 500) throw new Error(`Graphic "${name}": "text" is up to 500 characters`);
|
|
121
|
+
out.text = value;
|
|
122
|
+
} else if (key === 'font') {
|
|
123
|
+
if (typeof value !== 'string' || !FAMILY.test(value)) throw new Error(`Graphic "${name}": "font" is a font family, like "Georgia" or "sans-serif"`);
|
|
124
|
+
out.font = value;
|
|
125
|
+
} else if (key === 'weight') {
|
|
126
|
+
if (!WEIGHTS.includes(String(value))) throw new Error(`Graphic "${name}": "weight" is normal, bold or 100–900`);
|
|
127
|
+
out.weight = String(value);
|
|
128
|
+
} else if (key === 'style') {
|
|
129
|
+
if (!['normal', 'italic'].includes(value)) throw new Error(`Graphic "${name}": "style" is normal or italic`);
|
|
130
|
+
out.style = value;
|
|
131
|
+
} else if (key === 'align') {
|
|
132
|
+
if (!['left', 'center', 'right'].includes(value)) throw new Error(`Graphic "${name}": "align" is left, center or right`);
|
|
133
|
+
out.align = value;
|
|
134
|
+
} else if (key === 'size') out.size = number(name, key, value, 0.005, 2);
|
|
135
|
+
else if (key === 'w' || key === 'h') out[key] = number(name, key, value, 0, 4);
|
|
136
|
+
else if (key === 'radius') out.radius = number(name, key, value, 0, 0.5);
|
|
137
|
+
else if (key === 'lineHeight') out.lineHeight = number(name, key, value, 0.5, 4);
|
|
138
|
+
else out[key] = number(name, key, value); // x, y, angle
|
|
139
|
+
}
|
|
140
|
+
if (spec.fontUrl !== undefined && spec.fontUrl !== null && spec.fontUrl !== '') {
|
|
141
|
+
if (type !== 'text') throw new Error(`Graphic "${name}": "fontUrl" is for text`);
|
|
142
|
+
let url;
|
|
143
|
+
try { url = new URL(spec.fontUrl); } catch { url = null; }
|
|
144
|
+
if (!url || url.protocol !== 'https:') throw new Error(`Graphic "${name}": "fontUrl" is an https:// address of a font file (.woff2, .woff, .ttf, .otf) or of a Google Fonts stylesheet`);
|
|
145
|
+
out.fontUrl = url.href;
|
|
146
|
+
}
|
|
147
|
+
if (spec.onlyShadow !== undefined) out.onlyShadow = number(name, 'onlyShadow', spec.onlyShadow, 0, MAX_SHADOW_LAYERS - 1); // set by the compiler for a layer's picture
|
|
148
|
+
return out;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** A Google Fonts stylesheet address for a family name: "Lobster" → https://fonts.googleapis.com/css2?family=Lobster:… */
|
|
152
|
+
export function googleFontUrl(family) {
|
|
153
|
+
const name = String(family).trim().replace(/\s+/g, ' ');
|
|
154
|
+
if (!/^[A-Za-z0-9 ]{1,60}$/.test(name)) throw new Error('A Google Fonts name is letters, digits and spaces, like "Lobster" or "Playfair Display"');
|
|
155
|
+
return `https://fonts.googleapis.com/css2?family=${name.replace(/ /g, '+')}:ital,wght@0,400;0,700;1,400;1,700&display=swap`;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The family a Google Fonts address names ("Playfair Display"), or null. */
|
|
159
|
+
export function googleFontFamily(url) {
|
|
160
|
+
try {
|
|
161
|
+
const u = new URL(url);
|
|
162
|
+
if (u.hostname !== 'fonts.googleapis.com') return null;
|
|
163
|
+
return (u.searchParams.get('family') ?? '').split(':')[0].replace(/\+/g, ' ') || null;
|
|
164
|
+
} catch { return null; }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The font file a stylesheet points at — for a Google Fonts css2 address, the
|
|
169
|
+
* latin face of the weight and style wanted (its last block for that face).
|
|
170
|
+
*/
|
|
171
|
+
export function fontFileFromCss(css, { weight = '400', style = 'normal' } = {}) {
|
|
172
|
+
const faces = [...css.matchAll(/@font-face\s*{([^}]*)}/g)].map((m) => m[1]);
|
|
173
|
+
const prop = (block, key) => (new RegExp(`${key}\\s*:\\s*([^;]+);`).exec(block)?.[1] ?? '').trim();
|
|
174
|
+
const want = String(weight === 'bold' ? 700 : weight === 'normal' ? 400 : weight);
|
|
175
|
+
const pick = faces.filter((f) => prop(f, 'font-weight') === want && prop(f, 'font-style') === style);
|
|
176
|
+
const block = (pick.length ? pick : faces).at(-1);
|
|
177
|
+
return block ? (/url\(([^)]+)\)/.exec(block)?.[1] ?? '').replace(/^['"]|['"]$/g, '') || null : null;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** The CSS font for a text graphic at frame height `h`. Fonts loaded from fontUrl are known by the url-derived family. */
|
|
181
|
+
export function cssFont(spec, h) {
|
|
182
|
+
const family = spec.fontUrl ? `"${familyFor(spec.fontUrl)}", ${spec.font}` : spec.font;
|
|
183
|
+
return `${spec.style} ${spec.weight} ${Math.max(1, spec.size * h)}px ${family}`;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** A stable, safe family name for a font loaded from a URL. */
|
|
187
|
+
export function familyFor(url) {
|
|
188
|
+
let hash = 0;
|
|
189
|
+
for (const ch of url) hash = (hash * 31 + ch.charCodeAt(0)) >>> 0;
|
|
190
|
+
return `mz-font-${hash.toString(36)}`;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const loadedFonts = new Map();
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Loads every fontUrl among the graphics (once each per weight and style) and waits for
|
|
197
|
+
* the families to be usable. A font file is used as it is; a stylesheet (Google Fonts)
|
|
198
|
+
* is read for the file of the weight and style the text uses.
|
|
199
|
+
* @returns {Promise<string[]>} the addresses that could not be loaded
|
|
200
|
+
*/
|
|
201
|
+
export async function loadGraphicFonts(graphics, h = 100) {
|
|
202
|
+
if (typeof document === 'undefined' && typeof self === 'undefined') return [];
|
|
203
|
+
const fonts = typeof document !== 'undefined' ? document.fonts : self.fonts;
|
|
204
|
+
if (!fonts) return [];
|
|
205
|
+
const failed = [];
|
|
206
|
+
for (const spec of Object.values(graphics ?? {})) {
|
|
207
|
+
if (spec.type !== 'text') continue;
|
|
208
|
+
if (spec.fontUrl && typeof FontFace !== 'undefined') {
|
|
209
|
+
const key = `${spec.fontUrl} ${spec.weight} ${spec.style}`;
|
|
210
|
+
if (!loadedFonts.has(key)) loadedFonts.set(key, loadFace(spec, fonts));
|
|
211
|
+
if (!(await loadedFonts.get(key))) failed.push(spec.fontUrl);
|
|
212
|
+
}
|
|
213
|
+
try { await fonts.load(cssFont(spec, h), spec.text); } catch { /* an unknown family falls back, as CSS does */ }
|
|
214
|
+
}
|
|
215
|
+
return [...new Set(failed)];
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async function loadFace(spec, fonts) {
|
|
219
|
+
try {
|
|
220
|
+
let file = spec.fontUrl;
|
|
221
|
+
if (!/\.(woff2?|ttf|otf)(\?|$)/i.test(new URL(file).pathname) || googleFontFamily(file)) {
|
|
222
|
+
const css = await (await fetch(file, { credentials: 'omit', referrerPolicy: 'no-referrer' })).text();
|
|
223
|
+
file = fontFileFromCss(css, spec);
|
|
224
|
+
if (!file || !file.startsWith('https://')) return null;
|
|
225
|
+
}
|
|
226
|
+
const face = new FontFace(familyFor(spec.fontUrl), `url(${JSON.stringify(file)})`, { weight: spec.weight, style: spec.style });
|
|
227
|
+
fonts.add(await face.load());
|
|
228
|
+
return face;
|
|
229
|
+
} catch { return null; }
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Draws one graphic onto a w × h context (cleared first by the caller). */
|
|
233
|
+
export function drawGraphic(ctx, spec, w, h) {
|
|
234
|
+
ctx.save();
|
|
235
|
+
const unit = spec.type === 'text' ? spec.size * h : h; // shadow and outline sizes scale with this
|
|
236
|
+
// A shadow layer alone: the shape is drawn far off to the left and only its shadow is thrown back onto the frame.
|
|
237
|
+
const layer = spec.onlyShadow !== undefined ? spec.shadows[spec.onlyShadow] : null;
|
|
238
|
+
const away = layer ? 2 * (w + h) + 1000 : 0;
|
|
239
|
+
const cast = layer ?? spec.shadow;
|
|
240
|
+
ctx.translate(spec.x * w - away, spec.y * h);
|
|
241
|
+
if (spec.angle) ctx.rotate(spec.angle);
|
|
242
|
+
if (cast) {
|
|
243
|
+
ctx.shadowColor = cast.color;
|
|
244
|
+
ctx.shadowBlur = cast.blur * unit;
|
|
245
|
+
ctx.shadowOffsetX = cast.dx * unit + away;
|
|
246
|
+
ctx.shadowOffsetY = cast.dy * unit;
|
|
247
|
+
}
|
|
248
|
+
ctx.fillStyle = layer ? '#000000' : spec.color; // an opaque body throws the full shadow
|
|
249
|
+
if (spec.outline) {
|
|
250
|
+
ctx.strokeStyle = spec.outline.color;
|
|
251
|
+
ctx.lineWidth = spec.outline.width * unit;
|
|
252
|
+
ctx.lineJoin = 'round';
|
|
253
|
+
}
|
|
254
|
+
if (spec.type === 'text') {
|
|
255
|
+
ctx.font = cssFont(spec, h);
|
|
256
|
+
ctx.textAlign = spec.align;
|
|
257
|
+
ctx.textBaseline = 'middle';
|
|
258
|
+
const lines = spec.text.split('\n');
|
|
259
|
+
const step = spec.size * h * spec.lineHeight;
|
|
260
|
+
lines.forEach((line, i) => {
|
|
261
|
+
const y = (i - (lines.length - 1) / 2) * step;
|
|
262
|
+
if (spec.outline) ctx.strokeText(line, 0, y); // the outline under the fill, so the letters keep their shape
|
|
263
|
+
if (spec.outline && cast && !layer) { ctx.shadowColor = 'transparent'; }
|
|
264
|
+
ctx.fillText(line, 0, y);
|
|
265
|
+
if (spec.outline && cast && !layer) ctx.shadowColor = cast.color;
|
|
266
|
+
});
|
|
267
|
+
} else {
|
|
268
|
+
const W = spec.w * w, H = spec.h * h;
|
|
269
|
+
ctx.beginPath();
|
|
270
|
+
if (spec.type === 'ellipse') ctx.ellipse(0, 0, W / 2, H / 2, 0, 0, Math.PI * 2);
|
|
271
|
+
else {
|
|
272
|
+
const r = Math.min(W, H) * spec.radius;
|
|
273
|
+
if (ctx.roundRect) ctx.roundRect(-W / 2, -H / 2, W, H, r);
|
|
274
|
+
else ctx.rect(-W / 2, -H / 2, W, H);
|
|
275
|
+
}
|
|
276
|
+
ctx.fill();
|
|
277
|
+
if (spec.outline) { if (!layer) ctx.shadowColor = 'transparent'; ctx.stroke(); }
|
|
278
|
+
}
|
|
279
|
+
ctx.restore();
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Every graphic of a compiled filter drawn at w × h, fonts loaded first: { name: canvas }.
|
|
284
|
+
* Brush strokes are drawn as at frame `t` (all of them, by default), clipped by `mask`
|
|
285
|
+
* (a w × h Float32Array, the selection) when they ask to be, as ImageData-like objects.
|
|
286
|
+
*/
|
|
287
|
+
export async function renderGraphics(compiled, w, h, { t = Infinity, mask = null } = {}) {
|
|
288
|
+
const graphics = compiled.graphics ?? {};
|
|
289
|
+
const failed = await loadGraphicFonts(graphics, h);
|
|
290
|
+
const out = {};
|
|
291
|
+
for (const [name, spec] of Object.entries(graphics)) {
|
|
292
|
+
if (spec.type === 'strokes') {
|
|
293
|
+
const r = rasterizeStrokes(spec, w, h, t, { mask });
|
|
294
|
+
out[name] = typeof ImageData !== 'undefined' ? new ImageData(r.data, w, h) : r; // not via a canvas: it would premultiply the data channels away
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
const canvas = typeof OffscreenCanvas !== 'undefined' && typeof document === 'undefined'
|
|
298
|
+
? new OffscreenCanvas(w, h)
|
|
299
|
+
: Object.assign(document.createElement('canvas'), { width: w, height: h });
|
|
300
|
+
drawGraphic(canvas.getContext('2d'), spec, w, h);
|
|
301
|
+
out[name] = canvas;
|
|
302
|
+
}
|
|
303
|
+
Object.defineProperty(out, 'failedFonts', { value: failed }); // addresses that could not be loaded (the text fell back to its family)
|
|
304
|
+
return out;
|
|
305
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* qblur — image filters written as maths. Types for `import … from '@mathzetta/qblur'`
|
|
3
|
+
* (and dist/qblur.js, dist/qblur.external.js, window.QBlur in the classic builds).
|
|
4
|
+
* The format itself is described in docs/filters.md; these follow src/.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
// ---- the filter document (mathzetta-filter/1) ----------------------------------------------
|
|
8
|
+
|
|
9
|
+
export type Colour = [number, number, number];
|
|
10
|
+
|
|
11
|
+
/** A knob: `0.5` (a number 0–1), `[1, 0, 0]` (a colour), or in full. */
|
|
12
|
+
export type ParamSpec = number | Colour | {
|
|
13
|
+
type?: 'number' | 'color';
|
|
14
|
+
default?: number | Colour;
|
|
15
|
+
min?: number;
|
|
16
|
+
max?: number;
|
|
17
|
+
step?: number;
|
|
18
|
+
label?: string;
|
|
19
|
+
/** A menu of these values. */
|
|
20
|
+
options?: number[];
|
|
21
|
+
/** "box": typed in, as maths; the default is a slider. */
|
|
22
|
+
input?: 'slider' | 'box';
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export interface NormalizedParam {
|
|
26
|
+
type: 'number' | 'color';
|
|
27
|
+
default: number | Colour;
|
|
28
|
+
min?: number;
|
|
29
|
+
max?: number;
|
|
30
|
+
step?: number;
|
|
31
|
+
label?: string;
|
|
32
|
+
options?: number[];
|
|
33
|
+
input?: 'box';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** How a picture sits over the frame. */
|
|
37
|
+
export interface Placement {
|
|
38
|
+
place: 'cover' | 'fit' | 'stretch' | 'tile';
|
|
39
|
+
zoom: number;
|
|
40
|
+
x: number;
|
|
41
|
+
y: number;
|
|
42
|
+
angle: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface ImageSpec extends Partial<Placement> {
|
|
46
|
+
description?: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A text, rectangle, ellipse or brush-strokes graphic (src/graphics.js, src/strokes.js). */
|
|
50
|
+
export interface GraphicSpec {
|
|
51
|
+
type?: 'text' | 'rect' | 'ellipse' | 'strokes';
|
|
52
|
+
[setting: string]: unknown;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** One expression for every channel, or one per channel. */
|
|
56
|
+
export type ColorExpression = string | Partial<Record<'r' | 'g' | 'b' | 'a' | 'rgb' | 'rgba', string>>;
|
|
57
|
+
|
|
58
|
+
export type ColourSpace = 'srgb' | 'linear' | 'hsv' | 'hsl' | 'lab' | 'oklab' | 'ycbcr';
|
|
59
|
+
|
|
60
|
+
/** A step of a chain: an expression, a filter, or a filter with settings. */
|
|
61
|
+
export type Step = string | FilterDocument | {
|
|
62
|
+
filter: string | FilterDocument;
|
|
63
|
+
/** Knob values, picture placements and graphic settings for this step. */
|
|
64
|
+
with?: Record<string, unknown>;
|
|
65
|
+
/** How much of the step's result shows over its input, 0–1. */
|
|
66
|
+
opacity?: number;
|
|
67
|
+
skip?: boolean;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/** A filter as published: maths plus a name, an author, its knobs and the pictures it needs. */
|
|
71
|
+
export interface FilterDocument {
|
|
72
|
+
format?: 'mathzetta-filter/1';
|
|
73
|
+
name?: string;
|
|
74
|
+
author?: string;
|
|
75
|
+
description?: string;
|
|
76
|
+
/** The filter's page: Markdown, and where each knob goes. */
|
|
77
|
+
notes?: Array<string | { param: string }>;
|
|
78
|
+
params?: Record<string, ParamSpec>;
|
|
79
|
+
images?: string[] | Record<string, ImageSpec>;
|
|
80
|
+
graphics?: Record<string, GraphicSpec>;
|
|
81
|
+
space?: ColourSpace | { in?: ColourSpace; out?: ColourSpace };
|
|
82
|
+
/** A filter has either `color` or `steps`. */
|
|
83
|
+
color?: ColorExpression;
|
|
84
|
+
steps?: Step[];
|
|
85
|
+
[extra: string]: unknown;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Anything a filter can be given as: an expression or a document. */
|
|
89
|
+
export type FilterInput = string | FilterDocument;
|
|
90
|
+
|
|
91
|
+
export interface NormalizedStep {
|
|
92
|
+
filter: NormalizedFilter;
|
|
93
|
+
with: Record<string, unknown>;
|
|
94
|
+
opacity: number;
|
|
95
|
+
skip: boolean;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export interface NormalizedFilter {
|
|
99
|
+
format: 'mathzetta-filter/1';
|
|
100
|
+
name?: string;
|
|
101
|
+
author?: string;
|
|
102
|
+
description?: string;
|
|
103
|
+
notes?: Array<string | { param: string }>;
|
|
104
|
+
params?: Record<string, NormalizedParam>;
|
|
105
|
+
images?: Record<string, ImageSpec>;
|
|
106
|
+
graphics?: Record<string, GraphicSpec>;
|
|
107
|
+
space?: { in: ColourSpace; out: ColourSpace };
|
|
108
|
+
color?: string | Partial<Record<'r' | 'g' | 'b' | 'a' | 'rgb' | 'rgba', string>>;
|
|
109
|
+
steps?: NormalizedStep[];
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ---- compiled ------------------------------------------------------------------------------
|
|
113
|
+
|
|
114
|
+
export interface Pass {
|
|
115
|
+
name: string;
|
|
116
|
+
author: string;
|
|
117
|
+
/** Where the pass came from in the chain (step indexes). */
|
|
118
|
+
path: number[];
|
|
119
|
+
/** The fragment shader. */
|
|
120
|
+
fragment: string;
|
|
121
|
+
/** The filter's own expression(s), which the CPU runner compiles. */
|
|
122
|
+
color?: NormalizedFilter['color'];
|
|
123
|
+
space?: string;
|
|
124
|
+
params: Record<string, NormalizedParam>;
|
|
125
|
+
/** The knobs' values: change them and draw again, no recompiling. */
|
|
126
|
+
values: Record<string, number | number[]>;
|
|
127
|
+
opacity: number;
|
|
128
|
+
images: string[];
|
|
129
|
+
placements: Record<string, Placement>;
|
|
130
|
+
graphics: Record<string, GraphicSpec>;
|
|
131
|
+
/** Graphic names → their keys in compiled.graphics (`title` → `title~2`). */
|
|
132
|
+
bind?: Record<string, string>;
|
|
133
|
+
keepInput: number;
|
|
134
|
+
blendKept: boolean;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export interface CompiledFilter {
|
|
138
|
+
name: string;
|
|
139
|
+
author: string;
|
|
140
|
+
description: string;
|
|
141
|
+
version: 100 | 300;
|
|
142
|
+
passes: Pass[];
|
|
143
|
+
/** The named filters used inside a chain, with their authors. */
|
|
144
|
+
credits: Array<{ name: string; author: string }>;
|
|
145
|
+
images: Record<string, ImageSpec>;
|
|
146
|
+
graphics: Record<string, GraphicSpec>;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export const FILTER_FORMAT: 'mathzetta-filter/1';
|
|
150
|
+
export const PLACEMENT: Placement;
|
|
151
|
+
|
|
152
|
+
/** The full form of a filter; throws on anything that isn't one. */
|
|
153
|
+
export function normalizeFilter(def: FilterInput): NormalizedFilter;
|
|
154
|
+
/** Every problem with a filter, as messages; empty when it will compile. */
|
|
155
|
+
export function validateFilter(def: FilterInput): string[];
|
|
156
|
+
/** A filter flattened into shader passes. Throws with every problem found. */
|
|
157
|
+
export function compileFilter(def: FilterInput, options?: { version?: 100 | 300 }): CompiledFilter;
|
|
158
|
+
export function filterParams(filter: NormalizedFilter): Record<string, NormalizedParam>;
|
|
159
|
+
export function filterImages(filter: NormalizedFilter): Record<string, ImageSpec>;
|
|
160
|
+
export function filterGraphics(filter: NormalizedFilter): Record<string, GraphicSpec>;
|
|
161
|
+
/** The filter as JSON to publish (normalized, defaults left out). */
|
|
162
|
+
export function filterToJSON(def: FilterInput): string;
|
|
163
|
+
export function filterFromJSON(text: string): NormalizedFilter;
|
|
164
|
+
/** `base + '#' + the filter`, URL-safe. */
|
|
165
|
+
export function filterToLink(def: FilterInput, base?: string): string;
|
|
166
|
+
export function filterFromLink(text: string): NormalizedFilter;
|
|
167
|
+
/** JSON, a share link, or a bare expression. */
|
|
168
|
+
export function readFilter(text: string): NormalizedFilter;
|
|
169
|
+
|
|
170
|
+
// ---- running -------------------------------------------------------------------------------
|
|
171
|
+
|
|
172
|
+
/** What the CPU side reads and writes: RGBA, 8-bit (or 0–1 floats), row by row from the top. */
|
|
173
|
+
export interface Picture {
|
|
174
|
+
data: Uint8ClampedArray | Uint8Array | Float32Array | Float64Array | number[];
|
|
175
|
+
width: number;
|
|
176
|
+
height: number;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export interface Picture8 {
|
|
180
|
+
data: Uint8ClampedArray;
|
|
181
|
+
width: number;
|
|
182
|
+
height: number;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** A picture the runners take: an <img>, <video>, canvas, ImageBitmap, ImageData, or { data, width, height }. */
|
|
186
|
+
export type PictureSource = CanvasImageSource | ImageData | Picture;
|
|
187
|
+
|
|
188
|
+
export type Precision = 'byte' | 'half' | 'float';
|
|
189
|
+
|
|
190
|
+
export interface FilterRunner {
|
|
191
|
+
readonly passes: Pass[];
|
|
192
|
+
/** What the GPU granted for the textures between passes. */
|
|
193
|
+
readonly precision: Precision | string;
|
|
194
|
+
/** The main picture; with a name first, one of compiled.images (or a graphic's key). */
|
|
195
|
+
setImage(image: PictureSource): this;
|
|
196
|
+
setImage(name: string, image: PictureSource): this;
|
|
197
|
+
/** Draws onto gl's canvas; `t` is the frame. */
|
|
198
|
+
draw(options?: { t?: number }): this;
|
|
199
|
+
dispose(): void;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export interface CpuRunner {
|
|
203
|
+
readonly passes: Pass[];
|
|
204
|
+
readonly precision: 'byte' | 'float';
|
|
205
|
+
/** The generated JavaScript of each pass. */
|
|
206
|
+
readonly sources: string[];
|
|
207
|
+
/** How many workers drawAsync() uses (0 until it needs them). */
|
|
208
|
+
readonly workers: number;
|
|
209
|
+
setImage(image: PictureSource): this;
|
|
210
|
+
setImage(name: string, image: PictureSource): this;
|
|
211
|
+
/** Runs every pass here; draws on `canvas` when given. */
|
|
212
|
+
draw(options?: { t?: number; canvas?: HTMLCanvasElement | OffscreenCanvas | null }): Picture8;
|
|
213
|
+
/** As draw(), with big pictures' rows spread over workers. */
|
|
214
|
+
drawAsync(options?: { t?: number; canvas?: HTMLCanvasElement | OffscreenCanvas | null }): Promise<Picture8>;
|
|
215
|
+
dispose(): void;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export interface CpuRunnerOptions {
|
|
219
|
+
precision?: Precision;
|
|
220
|
+
/** 'auto' (cores − 1, at most 8) or a number; below 2, drawAsync() runs here. */
|
|
221
|
+
workers?: number | 'auto';
|
|
222
|
+
/** Pixels from which drawAsync() uses workers (250 000). */
|
|
223
|
+
parallelFrom?: number;
|
|
224
|
+
/** Where cpu-worker.js is, when not beside the module. */
|
|
225
|
+
workerUrl?: string | URL;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export function createFilterRunner(gl: WebGLRenderingContext | WebGL2RenderingContext, compiled: CompiledFilter, options?: { precision?: Precision }): FilterRunner;
|
|
229
|
+
export function createCpuRunner(compiled: CompiledFilter, options?: CpuRunnerOptions): CpuRunner;
|
|
230
|
+
/** ImageData, { data, width, height }, or a drawable in a browser → 0–1 floats. */
|
|
231
|
+
export function toPicture(image: PictureSource): { data: Float32Array; width: number; height: number };
|
|
232
|
+
/** One pass compiled to JavaScript for the CPU (after the generated-code gate). */
|
|
233
|
+
export function compileCpuPass(pass: Pass): { source: string; uses: Set<string>; pictures: string[]; run(ctx: object): void };
|
|
234
|
+
|
|
235
|
+
export type Engine = 'gpu' | 'cpu';
|
|
236
|
+
export function chooseEngine(options?: { webgl?: boolean; prefer?: 'auto' | Engine }): { engine: Engine; reason: string };
|
|
237
|
+
/** The GPU when `gl` is given and takes the shaders, the CPU otherwise. */
|
|
238
|
+
export function createRunner(compiled: CompiledFilter, options?: CpuRunnerOptions & {
|
|
239
|
+
gl?: WebGLRenderingContext | WebGL2RenderingContext | null;
|
|
240
|
+
prefer?: 'auto' | Engine;
|
|
241
|
+
}): { runner: FilterRunner | CpuRunner; engine: Engine; reason: string };
|
|
242
|
+
|
|
243
|
+
// ---- the built-in library ------------------------------------------------------------------
|
|
244
|
+
|
|
245
|
+
export type LibraryFilter = FilterDocument & { name: string; group: string };
|
|
246
|
+
export const LIBRARY: LibraryFilter[];
|
|
247
|
+
export const GROUPS: string[];
|
|
248
|
+
|
|
249
|
+
// ---- brush strokes (src/strokes.js) --------------------------------------------------------
|
|
250
|
+
|
|
251
|
+
export const BRUSHES: string[];
|
|
252
|
+
export const TIMINGS: string[];
|
|
253
|
+
export const WIDTH_FROM: string[];
|
|
254
|
+
export const CLIPS: string[];
|
|
255
|
+
/** t counts frames at this rate. */
|
|
256
|
+
export const FPS: number;
|
|
257
|
+
export const STROKES_DEFAULTS: GraphicSpec;
|
|
258
|
+
export type Point = [number, number];
|
|
259
|
+
export function normalizeStrokes(name: string, spec: GraphicSpec): GraphicSpec;
|
|
260
|
+
export function strokeTimeline(spec: GraphicSpec, aspect?: number): { strokes: unknown[]; total: number; [key: string]: unknown };
|
|
261
|
+
export function rasterizeStrokes(spec: GraphicSpec, w: number, h: number, t?: number, options?: { mask?: Float32Array | null }): Picture8 & { total: number };
|
|
262
|
+
export function traceContours(mask: ArrayLike<number>, w: number, h: number, options?: { minArea?: number; tolerance?: number }): Point[][];
|
|
263
|
+
export function simplify(points: Point[], tolerance: number): Point[];
|
|
264
|
+
export function simplifyLoop(points: Point[], tolerance: number): Point[];
|
|
265
|
+
|
|
266
|
+
// ---- text and shapes (src/graphics.js) -----------------------------------------------------
|
|
267
|
+
|
|
268
|
+
export const GRAPHIC_TYPES: Array<'text' | 'rect' | 'ellipse' | 'strokes'>;
|
|
269
|
+
export const GRAPHIC_DEFAULTS: Record<'text' | 'rect' | 'ellipse', GraphicSpec>;
|
|
270
|
+
export const MAX_SHADOW_LAYERS: number;
|
|
271
|
+
export function normalizeGraphic(name: string, spec: GraphicSpec): GraphicSpec;
|
|
272
|
+
export function drawGraphic(ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D, spec: GraphicSpec, w: number, h: number): void;
|
|
273
|
+
/** Loads every fontUrl among the graphics; resolves with the addresses that failed. */
|
|
274
|
+
export function loadGraphicFonts(graphics: Record<string, GraphicSpec>, h?: number): Promise<string[]>;
|
|
275
|
+
/** Every graphic of a compiled filter drawn at w × h: { key: canvas or ImageData }, for runner.setImage(key, …). */
|
|
276
|
+
export function renderGraphics(compiled: CompiledFilter, w: number, h: number, options?: { t?: number; mask?: Float32Array | null }): Promise<Record<string, HTMLCanvasElement | OffscreenCanvas | ImageData | Picture8> & { readonly failedFonts: string[] }>;
|
|
277
|
+
export function cssFont(spec: GraphicSpec, h: number): string;
|
|
278
|
+
export function familyFor(url: string): string;
|
|
279
|
+
export function shadowLayerNames(name: string, spec: GraphicSpec): string[];
|
|
280
|
+
export function layeredExpression(name: string, spec: GraphicSpec): string;
|
|
281
|
+
export function googleFontUrl(family: string): string;
|
|
282
|
+
export function googleFontFamily(url: string): string | null;
|
|
283
|
+
export function fontFileFromCss(css: string, options?: { weight?: string; style?: string }): string | null;
|
package/src/index.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Shareable image filters: the JSON format (format.js), the GPU and CPU runners, the library, graphics and strokes. Two more entries:
|
|
2
|
+
* @mathzetta/qblur/apply (applyFilter and saving: apply.js) and @mathzetta/qblur/element (<qblur-image>: element.js). */
|
|
3
|
+
export {
|
|
4
|
+
FILTER_FORMAT, PLACEMENT, normalizeFilter, validateFilter, compileFilter, filterParams, filterImages, filterGraphics,
|
|
5
|
+
filterToJSON, filterFromJSON, filterToLink, filterFromLink, readFilter,
|
|
6
|
+
} from './format.js';
|
|
7
|
+
export { createFilterRunner } from './runtime.js';
|
|
8
|
+
export { createCpuRunner, toPicture } from './cpu-runner.js';
|
|
9
|
+
export { compileCpuPass } from './cpu.js';
|
|
10
|
+
export { createRunner, chooseEngine } from './auto.js';
|
|
11
|
+
export { LIBRARY, GROUPS } from './library.js';
|
|
12
|
+
export { BRUSHES, TIMINGS, WIDTH_FROM, CLIPS, FPS, STROKES_DEFAULTS, normalizeStrokes, strokeTimeline, rasterizeStrokes, traceContours, simplify, simplifyLoop } from './strokes.js';
|
|
13
|
+
export { GRAPHIC_TYPES, GRAPHIC_DEFAULTS, normalizeGraphic, drawGraphic, loadGraphicFonts, renderGraphics, cssFont, familyFor, shadowLayerNames, layeredExpression, googleFontUrl, googleFontFamily, fontFileFromCss, MAX_SHADOW_LAYERS } from './graphics.js';
|