@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/CHANGELOG.md +63 -0
- package/LICENSE +1 -1
- package/README.md +34 -22
- 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 +92 -89
- package/docs/library.md +52 -55
- package/package.json +9 -3
- package/src/apply-filter.js +8 -7
- package/src/apply.d.ts +12 -11
- package/src/cpu-helpers.js +9 -7
- package/src/cpu-runner.js +26 -12
- package/src/cpu.js +65 -32
- package/src/element.d.ts +1 -1
- package/src/element.js +3 -3
- package/src/format.js +36 -27
- package/src/graphics.js +12 -12
- package/src/index.d.ts +11 -11
- package/src/library.js +29 -29
- package/src/png.js +21 -17
- package/src/runtime.js +25 -6
- package/src/save.js +7 -7
- package/src/strokes.js +15 -7
package/src/graphics.js
CHANGED
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
*
|
|
4
4
|
* A filter's `graphics` names things to draw — text, rectangles, ovals —
|
|
5
5
|
* each rasterized into a transparent picture the size of the frame under
|
|
6
|
-
* its name. The
|
|
7
|
-
*
|
|
6
|
+
* its name. The math then treats it like any picture: `title` is its
|
|
7
|
+
* color, `alpha(title)` where it is, so
|
|
8
8
|
*
|
|
9
9
|
* mix(rgb, title, alpha(title)) lays the text on
|
|
10
10
|
* mix(rgb, gaussian(6) * 0.8, alpha(panel)) frosts the picture behind a panel
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
*
|
|
13
13
|
* A graphic's `shadow` is drawn into it. Its `shadows` — a list, back to
|
|
14
14
|
* front — are drawn each into a picture of its own, `title_shadow1`,
|
|
15
|
-
* `title_shadow2`…, so every shadow layer can have its own
|
|
15
|
+
* `title_shadow2`…, so every shadow layer can have its own math:
|
|
16
16
|
*
|
|
17
17
|
* mix(mix(rgb, gaussian(4), alpha(title_shadow1)), title, alpha(title))
|
|
18
18
|
* mix(mix(rgb, (1, 0.3, 0.6) , alpha(shift(title_shadow1, 2 sin(t / 9), 0))), title, alpha(title))
|
|
@@ -49,23 +49,23 @@ export const MAX_SHADOW_LAYERS = 8;
|
|
|
49
49
|
/**
|
|
50
50
|
* The picture names of a graphic's separate shadow layers, back to front:
|
|
51
51
|
* title_shadow1, title_shadow2… Each is a picture of that shadow alone, so
|
|
52
|
-
* the
|
|
52
|
+
* the math can treat it on its own (blur it, color it, move it with t).
|
|
53
53
|
*/
|
|
54
54
|
export const shadowLayerNames = (name, spec) => (spec.shadows ?? []).map((_, k) => `${name}_shadow${k + 1}`);
|
|
55
55
|
|
|
56
|
-
/** The
|
|
56
|
+
/** The math that lays a graphic on with its shadow layers, back to front — what a new text step starts with. */
|
|
57
57
|
export function layeredExpression(name, spec) {
|
|
58
58
|
let base = 'rgb';
|
|
59
59
|
for (const layer of shadowLayerNames(name, spec)) base = `mix(${base}, ${layer}, alpha(${layer}))`;
|
|
60
60
|
return `mix(${base}, ${name}, alpha(${name}))`;
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
-
const
|
|
63
|
+
const COLOR = /^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d.,\s%deg/]+\)|[a-z]{3,20}|transparent)$/i;
|
|
64
64
|
const FAMILY = /^[\w\s,'"-]{1,80}$/;
|
|
65
65
|
const WEIGHTS = ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'];
|
|
66
66
|
|
|
67
|
-
function
|
|
68
|
-
if (typeof value !== 'string' || !
|
|
67
|
+
function color(name, key, value) {
|
|
68
|
+
if (typeof value !== 'string' || !COLOR.test(value.trim())) throw new Error(`Graphic "${name}": "${key}" is a color like "#ffcc00", "rgba(0,0,0,0.5)" or "white"`);
|
|
69
69
|
return value.trim();
|
|
70
70
|
}
|
|
71
71
|
|
|
@@ -79,7 +79,7 @@ function number(name, key, value, min = -Infinity, max = Infinity) {
|
|
|
79
79
|
function outline(name, value) {
|
|
80
80
|
if (value === null || value === false) return null;
|
|
81
81
|
if (typeof value !== 'object') throw new Error(`Graphic "${name}": "outline" is { "color", "width" } or null`);
|
|
82
|
-
return { color:
|
|
82
|
+
return { color: color(name, 'outline.color', value.color ?? '#000000'), width: number(name, 'outline.width', value.width ?? 0.06, 0, 1) };
|
|
83
83
|
}
|
|
84
84
|
|
|
85
85
|
/** `{ color, blur, dx, dy }` behind it; blur and offsets are fractions of the text size (frame height for shapes). */
|
|
@@ -87,7 +87,7 @@ function shadow(name, value) {
|
|
|
87
87
|
if (value === null || value === false) return null;
|
|
88
88
|
if (typeof value !== 'object') throw new Error(`Graphic "${name}": "shadow" is { "color", "blur", "dx", "dy" } or null`);
|
|
89
89
|
return {
|
|
90
|
-
color:
|
|
90
|
+
color: color(name, 'shadow.color', value.color ?? 'rgba(0,0,0,0.6)'),
|
|
91
91
|
blur: number(name, 'shadow.blur', value.blur ?? 0.15, 0, 2),
|
|
92
92
|
dx: number(name, 'shadow.dx', value.dx ?? 0, -2, 2),
|
|
93
93
|
dy: number(name, 'shadow.dy', value.dy ?? 0, -2, 2),
|
|
@@ -106,7 +106,7 @@ export function normalizeGraphic(name, spec) {
|
|
|
106
106
|
for (const [key, fallback] of Object.entries(base)) {
|
|
107
107
|
if (key === 'type') continue;
|
|
108
108
|
const value = key in spec && spec[key] !== undefined ? spec[key] : fallback; // null is a value: "no shadow"
|
|
109
|
-
if (key === 'color') out.color =
|
|
109
|
+
if (key === 'color') out.color = color(name, key, value);
|
|
110
110
|
else if (key === 'outline') out.outline = outline(name, value);
|
|
111
111
|
else if (key === 'shadow') out.shadow = shadow(name, value);
|
|
112
112
|
else if (key === 'shadows') {
|
|
@@ -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/index.d.ts
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* qblur — image filters written as
|
|
2
|
+
* qblur — image filters written as math. Types for `import … from '@mathzetta/qblur'`
|
|
3
3
|
* (and dist/qblur.js, dist/qblur.external.js, window.QBlur in the classic builds).
|
|
4
4
|
* The format itself is described in docs/filters.md; these follow src/.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
// ---- the filter document (mathzetta-filter/1) ----------------------------------------------
|
|
8
8
|
|
|
9
|
-
export type
|
|
9
|
+
export type Color = [number, number, number];
|
|
10
10
|
|
|
11
|
-
/** A knob: `0.5` (a number 0–1), `[1, 0, 0]` (a
|
|
12
|
-
export type ParamSpec = number |
|
|
11
|
+
/** A knob: `0.5` (a number 0–1), `[1, 0, 0]` (a color), or in full. */
|
|
12
|
+
export type ParamSpec = number | Color | {
|
|
13
13
|
type?: 'number' | 'color';
|
|
14
|
-
default?: number |
|
|
14
|
+
default?: number | Color;
|
|
15
15
|
min?: number;
|
|
16
16
|
max?: number;
|
|
17
17
|
step?: number;
|
|
18
18
|
label?: string;
|
|
19
19
|
/** A menu of these values. */
|
|
20
20
|
options?: number[];
|
|
21
|
-
/** "box": typed in, as
|
|
21
|
+
/** "box": typed in, as math; the default is a slider. */
|
|
22
22
|
input?: 'slider' | 'box';
|
|
23
23
|
};
|
|
24
24
|
|
|
25
25
|
export interface NormalizedParam {
|
|
26
26
|
type: 'number' | 'color';
|
|
27
|
-
default: number |
|
|
27
|
+
default: number | Color;
|
|
28
28
|
min?: number;
|
|
29
29
|
max?: number;
|
|
30
30
|
step?: number;
|
|
@@ -55,7 +55,7 @@ export interface GraphicSpec {
|
|
|
55
55
|
/** One expression for every channel, or one per channel. */
|
|
56
56
|
export type ColorExpression = string | Partial<Record<'r' | 'g' | 'b' | 'a' | 'rgb' | 'rgba', string>>;
|
|
57
57
|
|
|
58
|
-
export type
|
|
58
|
+
export type ColorSpace = 'srgb' | 'linear' | 'hsv' | 'hsl' | 'lab' | 'oklab' | 'ycbcr';
|
|
59
59
|
|
|
60
60
|
/** A step of a chain: an expression, a filter, or a filter with settings. */
|
|
61
61
|
export type Step = string | FilterDocument | {
|
|
@@ -67,7 +67,7 @@ export type Step = string | FilterDocument | {
|
|
|
67
67
|
skip?: boolean;
|
|
68
68
|
};
|
|
69
69
|
|
|
70
|
-
/** A filter as published:
|
|
70
|
+
/** A filter as published: math plus a name, an author, its knobs and the pictures it needs. */
|
|
71
71
|
export interface FilterDocument {
|
|
72
72
|
format?: 'mathzetta-filter/1';
|
|
73
73
|
name?: string;
|
|
@@ -78,7 +78,7 @@ export interface FilterDocument {
|
|
|
78
78
|
params?: Record<string, ParamSpec>;
|
|
79
79
|
images?: string[] | Record<string, ImageSpec>;
|
|
80
80
|
graphics?: Record<string, GraphicSpec>;
|
|
81
|
-
space?:
|
|
81
|
+
space?: ColorSpace | { in?: ColorSpace; out?: ColorSpace };
|
|
82
82
|
/** A filter has either `color` or `steps`. */
|
|
83
83
|
color?: ColorExpression;
|
|
84
84
|
steps?: Step[];
|
|
@@ -104,7 +104,7 @@ export interface NormalizedFilter {
|
|
|
104
104
|
params?: Record<string, NormalizedParam>;
|
|
105
105
|
images?: Record<string, ImageSpec>;
|
|
106
106
|
graphics?: Record<string, GraphicSpec>;
|
|
107
|
-
space?: { in:
|
|
107
|
+
space?: { in: ColorSpace; out: ColorSpace };
|
|
108
108
|
color?: string | Partial<Record<'r' | 'g' | 'b' | 'a' | 'rgb' | 'rgba', string>>;
|
|
109
109
|
steps?: NormalizedStep[];
|
|
110
110
|
}
|
package/src/library.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The built-in filters: what the editor offers, and a
|
|
2
|
+
* The built-in filters: what the editor offers, and a catalog anyone
|
|
3
3
|
* embedding the runner can show. Each is a filter document (docs/filters.md)
|
|
4
4
|
* plus a `group` for display (not part of the format; sharing drops it);
|
|
5
5
|
* `npm test` checks that every one validates, compiles and survives a link.
|
|
@@ -9,25 +9,25 @@ const FILTERS = [
|
|
|
9
9
|
{ name: 'Wave', group: 'Shape & motion', description: 'Rows slide back and forth as t advances',
|
|
10
10
|
params: { amplitude: { default: 8, min: 0, max: 40 }, wavelength: { default: 10, min: 1, max: 60 }, speed: { default: 5, min: 1, max: 30 } },
|
|
11
11
|
color: 'pixel(px + amplitude sin(py / wavelength + t / speed), py)' },
|
|
12
|
-
{ name: 'Invert', group: '
|
|
13
|
-
{ name: 'Grayscale', group: '
|
|
14
|
-
{ name: 'Threshold', group: '
|
|
15
|
-
{ name: 'Posterize', group: '
|
|
16
|
-
{ name: 'Brightness & contrast', group: '
|
|
12
|
+
{ name: 'Invert', group: 'Color & tone', color: '(1 - r, 1 - g, 1 - b)' },
|
|
13
|
+
{ name: 'Grayscale', group: 'Color & tone', color: 'gray' },
|
|
14
|
+
{ name: 'Threshold', group: 'Color & tone', params: { cutoff: 0.5 }, color: 'if gray > cutoff then 1 else 0' },
|
|
15
|
+
{ name: 'Posterize', group: 'Color & tone', params: { levels: { default: 4, min: 2, max: 16, step: 1 } }, color: 'min(floor(rgb * levels) / (levels - 1), 1)' },
|
|
16
|
+
{ name: 'Brightness & contrast', group: 'Color & tone',
|
|
17
17
|
params: { brightness: { default: 0, min: -0.5, max: 0.5 }, contrast: { default: 1, min: 0, max: 3 } },
|
|
18
18
|
color: '(rgb - 0.5) contrast + 0.5 + brightness' },
|
|
19
|
-
{ name: 'Tint', group: '
|
|
20
|
-
{ name: 'Sepia', group: '
|
|
21
|
-
{ name: '
|
|
19
|
+
{ name: 'Tint', group: 'Color & tone', params: { tint: [1, 0.85, 0.7] }, color: 'rgb * tint' },
|
|
20
|
+
{ name: 'Sepia', group: 'Color & tone', color: '(0.393r + 0.769g + 0.189b, 0.349r + 0.686g + 0.168b, 0.272r + 0.534g + 0.131b)' },
|
|
21
|
+
{ name: 'Color circle', group: 'Color & tone', description: 'Black and white, except a soft circle that keeps its color',
|
|
22
22
|
params: { across: { default: 0.5, min: 0, max: 1, label: 'where, across' }, down: { default: 0.5, min: 0, max: 1, label: 'where, down' },
|
|
23
23
|
radius: { default: 0.3, min: 0, max: 1 }, softness: { default: 0.08, min: 0, max: 0.5 } },
|
|
24
|
-
notes: ['The
|
|
24
|
+
notes: ['The color stays inside a circle and fades to gray over the softness. Sizes are parts of the picture\'s shorter side, so it stays round.',
|
|
25
25
|
{ param: 'across' }, { param: 'down' }, { param: 'radius' }, { param: 'softness' }],
|
|
26
26
|
color: 'mix((gray, gray, gray), rgb, 1 - smoothstep(radius, radius + softness, distance((px, py), (across w, down h)) / min(w, h)))' },
|
|
27
|
-
{ name: 'Vignette', group: '
|
|
27
|
+
{ name: 'Vignette', group: 'Color & tone', params: { strength: { default: 1.6, min: 0, max: 4 } }, color: 'rgb * (1 - strength ((x - 0.5)^2 + (y - 0.5)^2))' },
|
|
28
28
|
{ name: 'Sobel edges', group: 'Blur & edges', description: 'How fast the brightness changes', params: { gain: { default: 2, min: 0.2, max: 10 } }, color: 'gain sobel()' },
|
|
29
29
|
{ name: 'Edge map', group: 'Blur & edges', description: 'White where an edge is stronger than the cutoff', params: { cutoff: { default: 0.3, min: 0, max: 2 } }, color: 'if sobel() > cutoff then 1 else 0' },
|
|
30
|
-
{ name: 'Outline', group: 'Blur & edges', description: 'Ink lines over the
|
|
30
|
+
{ name: 'Outline', group: 'Blur & edges', description: 'Ink lines over the color', params: { gain: { default: 3, min: 0, max: 10 } }, color: 'rgb (1 - gain sobel())' },
|
|
31
31
|
{ name: 'Box blur', group: 'Blur & edges', params: { radius: { default: 2, min: 0, max: 8, step: 1 } }, color: 'blur(radius)' },
|
|
32
32
|
{ name: 'Gaussian blur', group: 'Blur & edges', description: 'Computed in two passes, across then down, so it can be wide', params: { sigma: { default: 3, min: 0, max: 8 } }, color: 'gaussian(sigma)' },
|
|
33
33
|
{ name: 'Canny edges', group: 'Blur & edges', description: 'Thin, clean edge lines: smooth, gradient, thinning, two thresholds, hysteresis — a chain',
|
|
@@ -35,7 +35,7 @@ const FILTERS = [
|
|
|
35
35
|
{ params: { sigma: { default: 1.4, min: 0.5, max: 4 } }, color: 'gaussian(sigma)' },
|
|
36
36
|
// gradient strength (r) and its direction as one of four buckets (g: 0, ¼, ½, ¾ for 0°, 45°, 90°, 135°)
|
|
37
37
|
{ color: '(min(sobel() / 4, 1), floor(fract((atan2(sobely(), sobelx()) + π/8) / π) 4) / 4, 0)' },
|
|
38
|
-
// non-maximum suppression: keep a pixel only if it is at least as strong as its two
|
|
38
|
+
// non-maximum suppression: keep a pixel only if it is at least as strong as its two neighbors along the gradient
|
|
39
39
|
{ color: 'if green(px, py) < 0.125 then (if r >= red(px - 1, py) & r >= red(px + 1, py) then r else 0)'
|
|
40
40
|
+ ' else if green(px, py) < 0.375 then (if r >= red(px + 1, py + 1) & r >= red(px - 1, py - 1) then r else 0)'
|
|
41
41
|
+ ' else if green(px, py) < 0.625 then (if r >= red(px, py - 1) & r >= red(px, py + 1) then r else 0)'
|
|
@@ -62,7 +62,7 @@ const FILTERS = [
|
|
|
62
62
|
{ name: 'Scanlines', group: 'Shape & motion', params: { period: { default: 4, min: 2, max: 16, step: 1 } }, color: 'if py mod period < period / 2 then rgb else rgb * 0.6' },
|
|
63
63
|
{ name: 'Pulse', group: 'Shape & motion', description: 'Brightness breathes with t', params: { speed: { default: 6, min: 1, max: 30 }, depth: { default: 0.25, min: 0, max: 1 } },
|
|
64
64
|
color: 'rgb (1 - depth + depth sin(t / speed))' },
|
|
65
|
-
{ name: 'Chroma key', group: '
|
|
65
|
+
{ name: 'Chroma key', group: 'Color & tone', description: 'Replaces one color with another',
|
|
66
66
|
params: { key: [0.22, 0.71, 0.29], tolerance: { default: 0.35, min: 0, max: 1 }, background: [0.1, 0.1, 0.4] },
|
|
67
67
|
color: 'if distance(rgb, key) < tolerance then background else rgb' },
|
|
68
68
|
{ name: 'Through a mask', group: 'Other pictures', description: 'Put this last: the steps above show only where the mask is light',
|
|
@@ -84,28 +84,28 @@ const FILTERS = [
|
|
|
84
84
|
{ name: 'Poster title', group: 'Text & shapes', description: 'Big outlined letters across the top',
|
|
85
85
|
graphics: { title: { text: 'BIG TITLE', font: 'Impact, Haettenschweiler, sans-serif', weight: 'normal', size: 0.16, y: 0.14, outline: { color: '#000000', width: 0.08 }, shadow: null } },
|
|
86
86
|
color: 'mix(rgb, title, alpha(title))' },
|
|
87
|
-
{ name: 'Gradient text', group: 'Text & shapes', description: 'The letters
|
|
87
|
+
{ name: 'Gradient text', group: 'Text & shapes', description: 'The letters colored by math: a sunset from left to right',
|
|
88
88
|
graphics: { title: { text: 'Golden hour', font: 'Georgia, serif', size: 0.13, y: 0.5, shadow: { color: 'rgba(0,0,0,0.5)', blur: 0.2, dx: 0, dy: 0.05 } } },
|
|
89
89
|
color: 'mix(rgb, mix((1, 0.35, 0.3), (1, 0.85, 0.25), x), alpha(title))' },
|
|
90
|
-
{ name: 'Neon sign', group: 'Text & shapes', description: 'White letters with a
|
|
90
|
+
{ name: 'Neon sign', group: 'Text & shapes', description: 'White letters with a colored glow',
|
|
91
91
|
graphics: { title: { text: 'OPEN', font: 'Trebuchet MS, sans-serif', size: 0.18, y: 0.5, shadow: { color: '#00e5ff', blur: 0.45, dx: 0, dy: 0 } } },
|
|
92
92
|
color: 'mix(rgb * 0.6, title, alpha(title))' },
|
|
93
|
-
{ name: 'Layered shadow', group: 'Text & shapes', description: 'Two shadow layers, each with its own filter: a soft glow that darkens and breathes with t, and a hard offset
|
|
93
|
+
{ name: 'Layered shadow', group: 'Text & shapes', description: 'Two shadow layers, each with its own filter: a soft glow that darkens and breathes with t, and a hard offset colored by a gradient',
|
|
94
94
|
graphics: { title: { text: 'LAYERS', font: 'Impact, Haettenschweiler, sans-serif', weight: 'normal', size: 0.17, y: 0.5, shadow: null,
|
|
95
95
|
shadows: [{ color: '#000000', blur: 0.7, dx: 0, dy: 0.08 }, { color: '#000000', blur: 0, dx: 0.07, dy: 0.07 }] } },
|
|
96
96
|
color: 'mix(mix(mix(rgb, rgb * 0.25, alpha(title_shadow1) (0.7 + 0.3 sin(t / 10))), mix((1, 0.2, 0.6), (0.2, 0.6, 1), x), alpha(title_shadow2)), title, alpha(title))' },
|
|
97
|
-
{ name: 'Ink brush', group: 'Brushes', description: 'Paint in a
|
|
97
|
+
{ name: 'Ink brush', group: 'Brushes', description: 'Paint in a color; draw on the picture with "draw" under the step',
|
|
98
98
|
graphics: { brush: { type: 'strokes', brush: 'round', size: 0.025 } }, params: { ink: [0.95, 0.2, 0.25] }, color: 'mix(rgb, ink, alpha(brush))' },
|
|
99
99
|
{ name: 'Blur brush', group: 'Brushes', description: 'Paint a blur in — stronger every time a stroke goes over the same place',
|
|
100
100
|
graphics: { brush: { type: 'strokes', brush: 'soft', size: 0.08 } }, color: 'mix(rgb, gaussian(2 + 3 min(4 green(brush), 3)), alpha(brush))' },
|
|
101
101
|
{ name: 'Darken brush', group: 'Brushes', description: 'Each pass darkens a little more, like layers of a wash',
|
|
102
102
|
graphics: { brush: { type: 'strokes', brush: 'soft', size: 0.07, flow: 0.7 } }, color: 'rgb (1 - 0.22 min(4 green(brush), 4))' },
|
|
103
|
-
{ name: '
|
|
103
|
+
{ name: 'Color reveal brush', group: 'Brushes', description: 'The picture starts gray; the brush paints its color back',
|
|
104
104
|
graphics: { brush: { type: 'strokes', brush: 'soft', size: 0.1 } }, color: 'mix((gray, gray, gray), rgb, alpha(brush))' },
|
|
105
105
|
{ name: 'Fuse brush', group: 'Brushes', description: 'Paint glows as it goes down, then cools to charcoal (red(brush) is its age)',
|
|
106
106
|
graphics: { brush: { type: 'strokes', brush: 'round', size: 0.02, age: 40 } },
|
|
107
107
|
color: 'mix(rgb, mix((1, 0.9, 0.5), (0.1, 0.07, 0.06), red(brush)), alpha(brush)) + (1, 0.5, 0.1) alpha(brush) max(0, 1 - 3 red(brush)) 0.6' },
|
|
108
|
-
{ name: 'Rainbow brush', group: 'Brushes', description: 'The
|
|
108
|
+
{ name: 'Rainbow brush', group: 'Brushes', description: 'The color runs round the wheel along the drawing (blue(brush) is how far through it)',
|
|
109
109
|
graphics: { brush: { type: 'strokes', brush: 'marker', size: 0.035 } }, color: 'mix(rgb, fromhsv(blue(brush), 0.85, 1), alpha(brush))' },
|
|
110
110
|
{ name: 'Chalk outline', group: 'Brushes', description: 'Chalk round an object: select it, then "outline the selection" under the step',
|
|
111
111
|
graphics: { brush: { type: 'strokes', brush: 'chalk', size: 0.018, timing: 'even', speed: 2 } }, color: 'mix(rgb, (0.97, 0.97, 0.92), alpha(brush))' },
|
|
@@ -134,17 +134,17 @@ const FILTERS = [
|
|
|
134
134
|
images: { inset: { description: 'any size: it is fitted whole', place: 'fit', zoom: 0.35, x: 0.8, y: 0.78 } }, color: 'mix(rgb, inset, alpha(inset))' },
|
|
135
135
|
{ name: 'Moving overlay', group: 'Other pictures', description: 'Another picture scrolling across at half strength', images: ['overlay'], params: { speed: { default: 2, min: -10, max: 10 } },
|
|
136
136
|
color: 'mix(rgb, shift(overlay, speed t, 0), 0.5)' },
|
|
137
|
-
{ name: 'Hue shift', group: '
|
|
137
|
+
{ name: 'Hue shift', group: 'Color & tone', description: 'Turns every color around the hue wheel (in HSV)', space: 'hsv',
|
|
138
138
|
params: { amount: { default: 0.1, min: -0.5, max: 0.5 } }, color: '(fract(r + amount), g, b)' },
|
|
139
|
-
{ name: 'Saturation', group: '
|
|
139
|
+
{ name: 'Saturation', group: 'Color & tone', description: 'More or less color (in HSV)', space: 'hsv',
|
|
140
140
|
params: { amount: { default: 1.5, min: 0, max: 3 } }, color: '(r, clamp(g amount, 0, 1), b)' },
|
|
141
|
-
{ name: 'Lightness', group: '
|
|
141
|
+
{ name: 'Lightness', group: 'Color & tone', description: 'Lighter or darker without changing the colors (in Lab)', space: 'lab',
|
|
142
142
|
params: { amount: { default: 1.15, min: 0.5, max: 2 } }, color: '(clamp(r amount, 0, 1), g, b)' },
|
|
143
|
-
{ name: 'Vivid', group: '
|
|
143
|
+
{ name: 'Vivid', group: 'Color & tone', description: 'Colorfulness, perceptually even (in OKLab)', space: 'oklab',
|
|
144
144
|
params: { amount: { default: 1.6, min: 0, max: 3 } }, color: '(r, 0.5 + (g - 0.5) amount, 0.5 + (b - 0.5) amount)' },
|
|
145
145
|
{ name: 'Linear-light blur', group: 'Blur & edges', description: 'A Gaussian in linear light: bright spots stay bright, as a lens does', space: 'linear',
|
|
146
146
|
params: { sigma: { default: 3, min: 0, max: 8 } }, color: 'gaussian(sigma)' },
|
|
147
|
-
{ name: 'Film grain', group: '
|
|
147
|
+
{ name: 'Film grain', group: 'Color & tone', description: 'Noise that changes every frame', params: { amount: { default: 0.15, min: 0, max: 0.6 } }, color: 'rgb + amount (random() - 0.5)' },
|
|
148
148
|
{ name: 'Swirl', group: 'Shape & motion', params: { strength: { default: 0.02, min: 0, max: 0.1 } },
|
|
149
149
|
color: 'pixel(w/2 + (px - w/2) cos(strength t gray) - (py - h/2) sin(strength t gray), h/2 + (px - w/2) sin(strength t gray) + (py - h/2) cos(strength t gray))' },
|
|
150
150
|
];
|
|
@@ -152,10 +152,10 @@ const byName = (name) => FILTERS.find((f) => f.name === name);
|
|
|
152
152
|
FILTERS.push(
|
|
153
153
|
{ name: 'Old film', group: 'Chains', description: 'Sepia, a vignette and faint scanlines — a chain of three',
|
|
154
154
|
steps: [byName('Sepia'), { filter: byName('Vignette'), with: { strength: 1.2 } }, { filter: byName('Scanlines'), opacity: 0.5 }] },
|
|
155
|
-
{ name: 'Comic', group: 'Chains', description: 'Bold flat
|
|
155
|
+
{ name: 'Comic', group: 'Chains', description: 'Bold flat colors with ink lines: a small blur first, so a photo\'s fine texture isn\'t inked — a chain of four',
|
|
156
156
|
steps: [{ filter: byName('Gaussian blur'), with: { sigma: 1.6 } }, { filter: byName('Vivid'), with: { amount: 1.5 } },
|
|
157
157
|
{ filter: byName('Posterize'), with: { levels: 4 } }, { filter: byName('Outline'), with: { gain: 1.2 } }] },
|
|
158
|
-
{ name: 'Cartoon', group: 'Chains', description: 'Blur, then flatten the
|
|
158
|
+
{ name: 'Cartoon', group: 'Chains', description: 'Blur, then flatten the colors, then outline — a chain of three',
|
|
159
159
|
steps: [{ filter: byName('Gaussian blur'), with: { sigma: 1.5 } }, { filter: byName('Posterize'), with: { levels: 6 } }, { filter: byName('Outline'), with: { gain: 2 } }] },
|
|
160
160
|
{ name: 'Dreamy', group: 'Chains', description: 'A soft glow mixed over the picture',
|
|
161
161
|
steps: [{ filter: byName('Bloom'), with: { amount: 1.2 } }, { filter: byName('Gaussian blur'), with: { sigma: 2 }, opacity: 0.4 }] },
|
|
@@ -163,11 +163,11 @@ FILTERS.push(
|
|
|
163
163
|
steps: [{ filter: byName('Gaussian blur'), with: { sigma: 4 } }, byName('Through a mask')] },
|
|
164
164
|
{ name: 'Title card', group: 'Chains', description: 'A frosted panel with a caption on it — a chain of two',
|
|
165
165
|
steps: [byName('Frosted panel'), { filter: byName('Caption'), with: { title: { text: 'A title on a panel', y: 0.86 } } }] },
|
|
166
|
-
{ name: '
|
|
166
|
+
{ name: 'Color spotlight', group: 'Chains', description: 'Gray except where the mask is dark — a chain',
|
|
167
167
|
steps: [byName('Grayscale'), byName('Through a mask')] },
|
|
168
168
|
);
|
|
169
169
|
|
|
170
170
|
export const LIBRARY = FILTERS;
|
|
171
171
|
|
|
172
172
|
/** The groups the editor shows the library in, in this order; every filter names one. */
|
|
173
|
-
export const GROUPS = ['
|
|
173
|
+
export const GROUPS = ['Color & tone', 'Blur & edges', 'Shape & motion', 'Text & shapes', 'Brushes', 'Other pictures', 'Chains'];
|
package/src/png.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* A PNG writer that can do what the browser's cannot: an indexed picture
|
|
3
|
-
* (PNG-8) at 1, 2, 4 or 8 bits a pixel when the picture has few
|
|
3
|
+
* (PNG-8) at 1, 2, 4 or 8 bits a pixel when the picture has few colors —
|
|
4
4
|
* a threshold or posterize result is 5–20× smaller that way — and RGB
|
|
5
|
-
* rather than RGBA when nothing is transparent.
|
|
5
|
+
* rather than RGBA when nothing is transparent. Truecolor rows use the
|
|
6
6
|
* Paeth filter, which deflate likes for photos.
|
|
7
7
|
*
|
|
8
|
-
* const { blob, kind,
|
|
8
|
+
* const { blob, kind, colors, bits } = await encodePng({ width, height, data, palette: 'auto', colors: 256, dither: true });
|
|
9
9
|
*
|
|
10
|
-
* `palette`: 'auto' (indexed if the picture has ≤ 256
|
|
11
|
-
*
|
|
12
|
-
* optional dithering — that needs a `quantize(data,
|
|
10
|
+
* `palette`: 'auto' (indexed if the picture has ≤ 256 colors, else
|
|
11
|
+
* truecolor), 'none', or 'force' (reduce to `colors` colors, with
|
|
12
|
+
* optional dithering — that needs a `quantize(data, colors, { dither, width })`
|
|
13
13
|
* returning { palette, indices }: the package has no quantizer of its own,
|
|
14
14
|
* so it stays dependency-free; the editor passes one built on gifenc).
|
|
15
15
|
* Deflate comes from CompressionStream (every current browser, and Node
|
|
@@ -48,8 +48,8 @@ async function deflate(bytes) {
|
|
|
48
48
|
return new Uint8Array(await new Response(stream.readable).arrayBuffer());
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
/** How many distinct RGBA
|
|
52
|
-
export function
|
|
51
|
+
/** How many distinct RGBA colors, counting up to `limit`. */
|
|
52
|
+
export function colorCount(data, limit = 257) {
|
|
53
53
|
const seen = new Set();
|
|
54
54
|
for (let i = 0; i < data.length; i += 4) {
|
|
55
55
|
seen.add(((data[i] << 24) | (data[i + 1] << 16) | (data[i + 2] << 8) | data[i + 3]) >>> 0);
|
|
@@ -58,7 +58,7 @@ export function colourCount(data, limit = 257) {
|
|
|
58
58
|
return seen.size;
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
-
/** Every
|
|
61
|
+
/** Every color as it is, when there are at most 256: { palette: [[r, g, b, a]…], indices }. */
|
|
62
62
|
export function exactPalette(data) {
|
|
63
63
|
const index = new Map();
|
|
64
64
|
const palette = [];
|
|
@@ -83,18 +83,21 @@ function paeth(a, b, c) {
|
|
|
83
83
|
}
|
|
84
84
|
|
|
85
85
|
/**
|
|
86
|
-
* @param {object} o { width, height, data: RGBA bytes, palette: 'auto' | 'none' | 'force',
|
|
87
|
-
* @returns {Promise<{ blob: Blob, kind: 'palette' | 'rgb' | 'rgba',
|
|
86
|
+
* @param {object} o { width, height, data: RGBA bytes, palette: 'auto' | 'none' | 'force', colors, dither, quantize }
|
|
87
|
+
* @returns {Promise<{ blob: Blob, kind: 'palette' | 'rgb' | 'rgba', colors: number, bits: number } | null>}
|
|
88
88
|
*/
|
|
89
|
-
export async function encodePng({ width, height, data, palette = 'auto',
|
|
89
|
+
export async function encodePng({ width, height, data, palette = 'auto', colors = 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);
|
|
94
|
-
if (indexed && indexed.palette.length >
|
|
97
|
+
if (indexed && indexed.palette.length > colors) indexed = null;
|
|
95
98
|
if (!indexed && palette === 'force') {
|
|
96
|
-
if (!quantize) throw new Error('encodePng: palette "force" needs a quantize function (the picture has more than `
|
|
97
|
-
indexed = quantize(data, Math.min(256, Math.max(2,
|
|
99
|
+
if (!quantize) throw new Error('encodePng: palette "force" needs a quantize function (the picture has more than `colors` colors)');
|
|
100
|
+
indexed = quantize(data, Math.min(256, Math.max(2, colors)), { dither, width });
|
|
98
101
|
}
|
|
99
102
|
}
|
|
100
103
|
const chunks = [new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10])];
|
|
@@ -107,7 +110,7 @@ export async function encodePng({ width, height, data, palette = 'auto', colours
|
|
|
107
110
|
const n = indexed.palette.length;
|
|
108
111
|
bits = n <= 2 ? 1 : n <= 4 ? 2 : n <= 16 ? 4 : 8;
|
|
109
112
|
kind = 'palette';
|
|
110
|
-
ihdr[8] = bits; ihdr[9] = 3; //
|
|
113
|
+
ihdr[8] = bits; ihdr[9] = 3; // color type 3: indexed
|
|
111
114
|
const stride = Math.ceil(width * bits / 8);
|
|
112
115
|
rows = new Uint8Array(height * (1 + stride));
|
|
113
116
|
for (let y = 0; y < height; y++) {
|
|
@@ -150,5 +153,6 @@ export async function encodePng({ width, height, data, palette = 'auto', colours
|
|
|
150
153
|
chunks.push(chunk('IHDR', ihdr));
|
|
151
154
|
}
|
|
152
155
|
chunks.push(chunk('IDAT', await deflate(rows)), chunk('IEND', new Uint8Array(0)));
|
|
153
|
-
|
|
156
|
+
const count = indexed ? indexed.palette.length : colorCount(data);
|
|
157
|
+
return { blob: new Blob(chunks, { type: 'image/png' }), kind, colors: count, bits };
|
|
154
158
|
}
|
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/save.js
CHANGED
|
@@ -7,9 +7,9 @@
|
|
|
7
7
|
* const gif = await encodeGif(frames, { gifenc, delay: 40 }); // bring your own gifenc
|
|
8
8
|
*
|
|
9
9
|
* PNG is written by the package itself (src/png.js: indexed when the picture
|
|
10
|
-
* has at most 256
|
|
10
|
+
* has at most 256 colors, RGB when nothing is transparent), so it works
|
|
11
11
|
* anywhere CompressionStream does — every current browser and Node ≥ 18.
|
|
12
|
-
* JPEG and WebP need the browser's encoder (a canvas). GIF needs a
|
|
12
|
+
* JPEG and WebP need the browser's encoder (a canvas). GIF needs a color
|
|
13
13
|
* quantizer and an LZW encoder; the package has no dependencies, so
|
|
14
14
|
* encodeGif() takes gifenc (npm i gifenc) as an option rather than bundling it.
|
|
15
15
|
*/
|
|
@@ -52,7 +52,7 @@ function canvasOf(picture) {
|
|
|
52
52
|
* @param {HTMLCanvasElement|OffscreenCanvas|{ data, width, height }} what
|
|
53
53
|
* @param {{ type?: string, quality?: number, palette?: 'auto' | 'none' }} [options]
|
|
54
54
|
* type: 'image/png' (the default), 'image/jpeg' or 'image/webp' (browser only); quality 0–1 for the last two.
|
|
55
|
-
* palette (PNG): 'auto' writes an indexed PNG when there are at most 256
|
|
55
|
+
* palette (PNG): 'auto' writes an indexed PNG when there are at most 256 colors, 'none' never does.
|
|
56
56
|
* @returns {Promise<Blob>}
|
|
57
57
|
*/
|
|
58
58
|
export async function toBlob(what, { type = 'image/png', quality, palette = 'auto' } = {}) {
|
|
@@ -69,12 +69,12 @@ export async function toBlob(what, { type = 'image/png', quality, palette = 'aut
|
|
|
69
69
|
/**
|
|
70
70
|
* An animated GIF from frames (canvases or pictures, all one size), each `delay` ms.
|
|
71
71
|
* Needs gifenc: `import * as gifenc from 'gifenc'` and pass it as `{ gifenc }`.
|
|
72
|
-
* Each frame gets its own palette of up to `
|
|
72
|
+
* Each frame gets its own palette of up to `colors` colors.
|
|
73
73
|
* @param {Iterable|AsyncIterable} frames
|
|
74
|
-
* @param {{ gifenc: object, delay?: number, repeat?: number,
|
|
74
|
+
* @param {{ gifenc: object, delay?: number, repeat?: number, colors?: number }} options
|
|
75
75
|
* @returns {Promise<Blob>}
|
|
76
76
|
*/
|
|
77
|
-
export async function encodeGif(frames, { gifenc, delay = 1000 / 30, repeat = 0,
|
|
77
|
+
export async function encodeGif(frames, { gifenc, delay = 1000 / 30, repeat = 0, colors = 256 } = {}) {
|
|
78
78
|
const G = gifenc && (gifenc.GIFEncoder ? gifenc : gifenc.default);
|
|
79
79
|
if (!G || typeof G.GIFEncoder !== 'function') throw new Error('encodeGif needs gifenc: import * as gifenc from \'gifenc\' and pass { gifenc }');
|
|
80
80
|
const encoder = G.GIFEncoder();
|
|
@@ -87,7 +87,7 @@ export async function encodeGif(frames, { gifenc, delay = 1000 / 30, repeat = 0,
|
|
|
87
87
|
size = [width, height];
|
|
88
88
|
const transparent = hasTransparency(data);
|
|
89
89
|
const format = transparent ? 'rgba4444' : 'rgb565';
|
|
90
|
-
const palette = G.quantize(data, Math.max(2, Math.min(256,
|
|
90
|
+
const palette = G.quantize(data, Math.max(2, Math.min(256, colors)), { format, oneBitAlpha: transparent });
|
|
91
91
|
const index = G.applyPalette(data, palette, format);
|
|
92
92
|
const options = { palette, delay: Math.round(delay), repeat };
|
|
93
93
|
if (transparent) {
|
package/src/strokes.js
CHANGED
|
@@ -3,14 +3,14 @@
|
|
|
3
3
|
*
|
|
4
4
|
* A strokes graphic records each stroke's points as the user drew them —
|
|
5
5
|
* [x, y, ms, pressure], x and y as fractions of the frame — and a brush.
|
|
6
|
-
* For frame t it becomes a picture whose channels are data, not
|
|
6
|
+
* For frame t it becomes a picture whose channels are data, not color:
|
|
7
7
|
*
|
|
8
8
|
* alpha coverage: how much paint is here so far, 0–1
|
|
9
9
|
* red age: how long ago this pixel was last painted, 0 (just now) → 1 (`age` frames or more)
|
|
10
10
|
* green passes ÷ 4: how many strokes have gone over it (soft brushes count partly)
|
|
11
11
|
* blue progress: how far through the whole drawing it was painted, 0 → 1
|
|
12
12
|
*
|
|
13
|
-
* so the
|
|
13
|
+
* so the math decides what the paint does:
|
|
14
14
|
*
|
|
15
15
|
* mix(rgb, ink, alpha(brush)) ink
|
|
16
16
|
* mix(rgb, gaussian(2 + 3 min(4 green(brush), 3)), alpha(brush)) a blur that grows with every pass
|
|
@@ -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++) {
|
|
@@ -257,8 +265,8 @@ export function rasterizeStrokes(spec, w, h, t = Infinity, { mask = null } = {})
|
|
|
257
265
|
|
|
258
266
|
/**
|
|
259
267
|
* The outlines of a mask (values > 0.5 are in), each a closed polyline of pixel
|
|
260
|
-
*
|
|
261
|
-
* Moore-
|
|
268
|
+
* centers, simplified; parts smaller than `minArea` pixels are left out.
|
|
269
|
+
* Moore-neighbor tracing, one outline per connected part.
|
|
262
270
|
*/
|
|
263
271
|
export function traceContours(mask, w, h, { minArea = 40, tolerance = 0.8 } = {}) {
|
|
264
272
|
const inside = (x, y) => x >= 0 && y >= 0 && x < w && y < h && mask[y * w + x] > 0.5;
|