@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/src/save.js ADDED
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Saving a result: a canvas or a picture ({ data, width, height }, what the
3
+ * CPU runner and applyFilter() in Node return) as a file.
4
+ *
5
+ * const blob = await toBlob(canvas, { type: 'image/jpeg', quality: 0.9 });
6
+ * const png = await toBlob(picture); // PNG in Node too: no canvas needed
7
+ * const gif = await encodeGif(frames, { gifenc, delay: 40 }); // bring your own gifenc
8
+ *
9
+ * PNG is written by the package itself (src/png.js: indexed when the picture
10
+ * has at most 256 colours, RGB when nothing is transparent), so it works
11
+ * anywhere CompressionStream does — every current browser and Node ≥ 18.
12
+ * JPEG and WebP need the browser's encoder (a canvas). GIF needs a colour
13
+ * quantizer and an LZW encoder; the package has no dependencies, so
14
+ * encodeGif() takes gifenc (npm i gifenc) as an option rather than bundling it.
15
+ */
16
+
17
+ import { encodePng } from './png.js';
18
+
19
+ const isPicture = (v) => v && v.data && Number.isFinite(v.width) && Number.isFinite(v.height) && typeof v.getContext !== 'function';
20
+
21
+ /** The RGBA bytes of a canvas or a picture (8-bit, or 0–1 floats as the CPU runner keeps them). */
22
+ export function pictureData(what) {
23
+ if (isPicture(what)) {
24
+ const { data, width, height } = what;
25
+ if (data instanceof Uint8ClampedArray || data instanceof Uint8Array) return { data, width, height };
26
+ const out = new Uint8ClampedArray(width * height * 4);
27
+ const scale = data instanceof Float32Array || data instanceof Float64Array ? 255 : 1;
28
+ for (let j = 0; j < out.length; j++) out[j] = Math.round(data[j] * scale);
29
+ return { data: out, width, height };
30
+ }
31
+ if (what && typeof what.getContext === 'function') {
32
+ const ctx = what.getContext('2d', { willReadFrequently: true });
33
+ if (!ctx) throw new Error('This canvas has a WebGL context: pass the 2D canvas applyFilter() returned, or copy it onto one first');
34
+ return ctx.getImageData(0, 0, what.width, what.height);
35
+ }
36
+ throw new Error('Give a canvas or a picture ({ data, width, height })');
37
+ }
38
+
39
+ /** A canvas (HTMLCanvasElement or OffscreenCanvas) holding the picture; null where there is none (Node). */
40
+ function canvasOf(picture) {
41
+ const { width, height } = picture;
42
+ let canvas = null;
43
+ if (typeof OffscreenCanvas !== 'undefined') canvas = new OffscreenCanvas(width, height);
44
+ else if (typeof document !== 'undefined') canvas = Object.assign(document.createElement('canvas'), { width, height });
45
+ if (!canvas) return null;
46
+ canvas.getContext('2d').putImageData(new ImageData(new Uint8ClampedArray(picture.data), width, height), 0, 0);
47
+ return canvas;
48
+ }
49
+
50
+ /**
51
+ * The picture as a file.
52
+ * @param {HTMLCanvasElement|OffscreenCanvas|{ data, width, height }} what
53
+ * @param {{ type?: string, quality?: number, palette?: 'auto' | 'none' }} [options]
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 colours, 'none' never does.
56
+ * @returns {Promise<Blob>}
57
+ */
58
+ export async function toBlob(what, { type = 'image/png', quality, palette = 'auto' } = {}) {
59
+ if (type === 'image/png') {
60
+ const png = await encodePng({ ...pictureData(what), palette });
61
+ if (png) return png.blob;
62
+ }
63
+ const canvas = isPicture(what) ? canvasOf(pictureData(what)) : what;
64
+ if (!canvas) throw new Error(`Saving as ${type} needs a browser (a canvas encodes it); in Node, save as image/png`);
65
+ if (typeof canvas.convertToBlob === 'function') return canvas.convertToBlob({ type, quality });
66
+ return new Promise((resolve, reject) => canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error(`The browser could not encode ${type}`))), type, quality));
67
+ }
68
+
69
+ /**
70
+ * An animated GIF from frames (canvases or pictures, all one size), each `delay` ms.
71
+ * Needs gifenc: `import * as gifenc from 'gifenc'` and pass it as `{ gifenc }`.
72
+ * Each frame gets its own palette of up to `colours` colours.
73
+ * @param {Iterable|AsyncIterable} frames
74
+ * @param {{ gifenc: object, delay?: number, repeat?: number, colours?: number }} options
75
+ * @returns {Promise<Blob>}
76
+ */
77
+ export async function encodeGif(frames, { gifenc, delay = 1000 / 30, repeat = 0, colours = 256 } = {}) {
78
+ const G = gifenc && (gifenc.GIFEncoder ? gifenc : gifenc.default);
79
+ if (!G || typeof G.GIFEncoder !== 'function') throw new Error('encodeGif needs gifenc: import * as gifenc from \'gifenc\' and pass { gifenc }');
80
+ const encoder = G.GIFEncoder();
81
+ let size = null;
82
+ let count = 0;
83
+ for await (const frame of frames) {
84
+ let { data, width, height } = pictureData(frame);
85
+ if (data.byteOffset || data.byteLength !== data.buffer.byteLength) data = data.slice(); // gifenc reads the whole buffer
86
+ if (size && (size[0] !== width || size[1] !== height)) throw new Error(`Frame ${count + 1} is ${width} × ${height}; the first was ${size[0]} × ${size[1]}`);
87
+ size = [width, height];
88
+ const transparent = hasTransparency(data);
89
+ const format = transparent ? 'rgba4444' : 'rgb565';
90
+ const palette = G.quantize(data, Math.max(2, Math.min(256, colours)), { format, oneBitAlpha: transparent });
91
+ const index = G.applyPalette(data, palette, format);
92
+ const options = { palette, delay: Math.round(delay), repeat };
93
+ if (transparent) {
94
+ const k = palette.findIndex((c) => c.length > 3 && c[3] === 0);
95
+ if (k >= 0) Object.assign(options, { transparent: true, transparentIndex: k });
96
+ }
97
+ encoder.writeFrame(index, width, height, options);
98
+ count++;
99
+ }
100
+ if (!count) throw new Error('encodeGif: no frames');
101
+ encoder.finish();
102
+ return new Blob([encoder.bytes()], { type: 'image/gif' });
103
+ }
104
+
105
+ function hasTransparency(data) {
106
+ for (let i = 3; i < data.length; i += 4) if (data[i] < 255) return true;
107
+ return false;
108
+ }
package/src/strokes.js ADDED
@@ -0,0 +1,350 @@
1
+ /**
2
+ * Brush strokes: a graphic painted by hand, drawn again for every frame.
3
+ *
4
+ * A strokes graphic records each stroke's points as the user drew them —
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 colour:
7
+ *
8
+ * alpha coverage: how much paint is here so far, 0–1
9
+ * red age: how long ago this pixel was last painted, 0 (just now) → 1 (`age` frames or more)
10
+ * green passes ÷ 4: how many strokes have gone over it (soft brushes count partly)
11
+ * blue progress: how far through the whole drawing it was painted, 0 → 1
12
+ *
13
+ * so the maths decides what the paint does:
14
+ *
15
+ * mix(rgb, ink, alpha(brush)) ink
16
+ * mix(rgb, gaussian(2 + 3 min(4 green(brush), 3)), alpha(brush)) a blur that grows with every pass
17
+ * mix(rgb, mix((1, 0.85, 0.35), (0.12, 0.08, 0.06), red(brush)), alpha(brush)) glowing, then cooling
18
+ * mix(rgb, fromhsv(blue(brush), 0.85, 1), alpha(brush)) a rainbow along the drawing
19
+ *
20
+ * Only paint laid down by frame t is there, so the drawing animates.
21
+ * Timing: `recorded` (the user's own speed; pauses between strokes become
22
+ * `gap` frames), `even` (time follows the length drawn), or `per-stroke`
23
+ * (every stroke takes the same time); `speed` scales it, `start` delays it,
24
+ * `fit` stretches the whole drawing to that many frames. `clip` keeps the
25
+ * paint inside (or outside) a mask — the editor passes the selection.
26
+ *
27
+ * normalizeStrokes(name, spec) the spec in full, or an error naming what is wrong
28
+ * strokeTimeline(spec, aspect) every point's frame and width; .total frames
29
+ * rasterizeStrokes(spec, w, h, t, { mask }) → ImageData-like { data, width, height }
30
+ * traceContours(mask, w, h) the outlines of a mask, as polylines (for "outline the selection")
31
+ */
32
+
33
+ export const BRUSHES = ['round', 'soft', 'marker', 'chalk', 'spray'];
34
+ export const TIMINGS = ['recorded', 'even', 'per-stroke'];
35
+ export const WIDTH_FROM = ['pressure', 'speed', 'none'];
36
+ export const CLIPS = ['none', 'inside', 'outside'];
37
+ export const FPS = 30; // t counts frames; recorded milliseconds become frames at this rate
38
+
39
+ export const STROKES_DEFAULTS = {
40
+ type: 'strokes', strokes: [], brush: 'round', size: 0.03, flow: 1, spacing: 0.2, taper: 0, buildUp: false, widthFrom: 'pressure',
41
+ timing: 'recorded', speed: 1, gap: 6, start: 0, fit: 0, age: 30, clip: 'none', shadows: [],
42
+ };
43
+
44
+ const MAX_POINTS = 60000;
45
+
46
+ function fail(name, text) { throw new Error(`Graphic "${name}": ${text}`); }
47
+
48
+ function num(name, key, value, min, max) {
49
+ const v = Number(value);
50
+ if (!Number.isFinite(v) || v < min || v > max) fail(name, `"${key}" is a number from ${min} to ${max}`);
51
+ return v;
52
+ }
53
+
54
+ /** The whole spec, defaults filled in. Points are rounded, so a drawing stays compact. */
55
+ export function normalizeStrokes(name, spec) {
56
+ for (const key of Object.keys(spec)) if (!(key in STROKES_DEFAULTS)) fail(name, `no such setting "${key}" for strokes`);
57
+ const s = { ...STROKES_DEFAULTS, ...spec };
58
+ const choose = (key, list) => { if (!list.includes(s[key])) fail(name, `"${key}" is ${list.join(', ')} — not "${s[key]}"`); return s[key]; };
59
+ const out = {
60
+ type: 'strokes',
61
+ brush: choose('brush', BRUSHES), widthFrom: choose('widthFrom', WIDTH_FROM), timing: choose('timing', TIMINGS), clip: choose('clip', CLIPS),
62
+ size: num(name, 'size', s.size, 0.001, 0.5), flow: num(name, 'flow', s.flow, 0.01, 1), spacing: num(name, 'spacing', s.spacing, 0.02, 2),
63
+ taper: num(name, 'taper', s.taper, 0, 0.5), speed: num(name, 'speed', s.speed, 0.05, 20), gap: num(name, 'gap', s.gap, 0, 600),
64
+ start: num(name, 'start', s.start, 0, 10000), fit: num(name, 'fit', s.fit, 0, 10000), age: num(name, 'age', s.age, 1, 10000),
65
+ buildUp: Boolean(s.buildUp), shadows: [],
66
+ };
67
+ if (!Array.isArray(s.strokes)) fail(name, '"strokes" is a list of { "points": [[x, y, ms, pressure], …] }');
68
+ let count = 0;
69
+ out.strokes = s.strokes.map((stroke, k) => {
70
+ const points = Array.isArray(stroke) ? stroke : stroke?.points;
71
+ if (!Array.isArray(points)) fail(name, `stroke ${k + 1} is { "points": [[x, y, ms, pressure], …] }`);
72
+ count += points.length;
73
+ if (count > MAX_POINTS) fail(name, `a drawing has at most ${MAX_POINTS} points`);
74
+ return {
75
+ points: points.map((p, j) => {
76
+ if (!Array.isArray(p) || p.length < 2 || !p.every((v) => Number.isFinite(Number(v)))) fail(name, `stroke ${k + 1}, point ${j + 1} is [x, y, ms, pressure]`);
77
+ return [+Number(p[0]).toFixed(4), +Number(p[1]).toFixed(4), Math.round(Number(p[2] ?? j * 16)), +Math.min(1, Math.max(0, Number(p[3] ?? 1))).toFixed(2)];
78
+ }),
79
+ };
80
+ });
81
+ return out;
82
+ }
83
+
84
+ /**
85
+ * When each point is painted (frame) and how wide (a factor of the brush size).
86
+ * `aspect` is the frame's width ÷ height, so lengths are measured in frame heights.
87
+ */
88
+ export function strokeTimeline(spec, aspect = 1) {
89
+ const strokes = [];
90
+ let clock = spec.start;
91
+ const evenPace = FPS / spec.speed; // `even`: one frame height of path a second at speed 1
92
+ const perStroke = 20 / spec.speed; // `per-stroke`: frames each
93
+ for (const stroke of spec.strokes) {
94
+ const pts = stroke.points;
95
+ if (!pts.length) continue;
96
+ const lengths = [0];
97
+ for (let j = 1; j < pts.length; j++) lengths.push(lengths[j - 1] + Math.hypot((pts[j][0] - pts[j - 1][0]) * aspect, pts[j][1] - pts[j - 1][1]));
98
+ const length = lengths[lengths.length - 1] || 1e-9;
99
+ const t0 = pts[0][2];
100
+ const out = pts.map((p, j) => {
101
+ let f;
102
+ if (spec.timing === 'recorded') f = ((p[2] - t0) / 1000) * FPS / spec.speed;
103
+ else if (spec.timing === 'even') f = lengths[j] * evenPace;
104
+ else f = (lengths[j] / length) * perStroke;
105
+ // width: pressure, or speed (fast is thin, as with a pen), then the taper at both ends
106
+ let wf = 1;
107
+ if (spec.widthFrom === 'pressure') wf = 0.3 + 0.7 * p[3];
108
+ else if (spec.widthFrom === 'speed' && j > 0) {
109
+ const dt = Math.max(1, p[2] - pts[j - 1][2]);
110
+ const v = ((lengths[j] - lengths[j - 1]) / dt) * 1000; // frame heights a second
111
+ wf = Math.min(1.3, Math.max(0.35, 1.3 - v * 0.6));
112
+ }
113
+ if (spec.taper > 0) wf *= Math.max(0.15, Math.min(1, lengths[j] / length / spec.taper, (1 - lengths[j] / length) / spec.taper));
114
+ return { x: p[0], y: p[1], f, wf };
115
+ });
116
+ if (spec.widthFrom === 'speed' && out.length > 1) out[0].wf = out[1].wf;
117
+ const duration = out[out.length - 1].f;
118
+ for (const p of out) p.f += clock;
119
+ strokes.push({ points: out, start: clock, end: clock + duration });
120
+ clock += duration + spec.gap;
121
+ }
122
+ let total = strokes.length ? strokes[strokes.length - 1].end : spec.start;
123
+ if (spec.fit > 0 && total > spec.start) { // stretch the drawing to `fit` frames after the start
124
+ const k = spec.fit / (total - spec.start);
125
+ for (const s of strokes) {
126
+ for (const p of s.points) p.f = spec.start + (p.f - spec.start) * k;
127
+ s.start = spec.start + (s.start - spec.start) * k;
128
+ s.end = spec.start + (s.end - spec.start) * k;
129
+ }
130
+ total = spec.start + spec.fit;
131
+ }
132
+ return { strokes, total };
133
+ }
134
+
135
+ /** A repeatable random number 0–1 for two integers. */
136
+ function hash(a, b) {
137
+ let x = Math.imul(a | 0, 374761393) + Math.imul(b | 0, 668265263) | 0;
138
+ x = Math.imul(x ^ (x >>> 13), 1274126177);
139
+ return ((x ^ (x >>> 16)) >>> 0) / 4294967296;
140
+ }
141
+
142
+ /** rasterizeStrokes() visits at most this many pixels per pixel of the frame in one call. */
143
+ const WORK_PER_PIXEL = 256;
144
+
145
+ const buffers = new Map();
146
+ function scratch(n) {
147
+ let b = buffers.get(n);
148
+ if (!b) {
149
+ b = { alpha: new Float32Array(n), passes: new Float32Array(n), latest: new Float32Array(n), cov: new Float32Array(n), when: new Float32Array(n), touched: new Int32Array(n) };
150
+ buffers.clear(); // one size at a time: the preview, or an export
151
+ buffers.set(n, b);
152
+ }
153
+ b.alpha.fill(0); b.passes.fill(0); b.latest.fill(-1);
154
+ return b;
155
+ }
156
+
157
+ /**
158
+ * The strokes as painted by frame `t` (Infinity: all of them, as at the end), w × h.
159
+ * `mask` (Float32Array of w × h, 0–1) is the selection for `clip`.
160
+ * @returns {{ data: Uint8ClampedArray, width: number, height: number, total: number }}
161
+ */
162
+ export function rasterizeStrokes(spec, w, h, t = Infinity, { mask = null } = {}) {
163
+ const n = w * h;
164
+ const { alpha, passes, latest, cov, when, touched } = scratch(n);
165
+ const { strokes, total } = strokeTimeline(spec, w / h);
166
+ const now = Number.isFinite(t) ? t : total;
167
+ const base = Math.max(0.5, (spec.size * h) / 2); // brush radius in pixels
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;
173
+
174
+ strokes.forEach((stroke) => {
175
+ if (stroke.start > now || budget <= 0) return;
176
+ let used = 0;
177
+ const stamp = (x, y, r, f) => {
178
+ const k = dabCount++;
179
+ if (spec.brush === 'spray') { // a few dots scattered in the brush's circle
180
+ const dots = Math.max(3, Math.round(r * 0.6));
181
+ const dr = Math.max(0.6, r * 0.07);
182
+ for (let d = 0; d < dots; d++) {
183
+ const a = hash(k, d * 2) * Math.PI * 2, rr = Math.sqrt(hash(k, d * 2 + 1)) * r;
184
+ dab(x + Math.cos(a) * rr, y + Math.sin(a) * rr, dr, f, 'round');
185
+ }
186
+ } else dab(x, y, r, f, spec.brush);
187
+ };
188
+ const dab = (cx, cy, r, f, kind) => {
189
+ const reach = kind === 'marker' ? r : r + 1;
190
+ const x0 = Math.max(0, Math.floor(cx - reach)), x1 = Math.min(w - 1, Math.ceil(cx + reach));
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
193
+ for (let py = y0; py <= y1; py++) {
194
+ for (let px = x0; px <= x1; px++) {
195
+ const dx = px + 0.5 - cx, dy = py + 0.5 - cy;
196
+ let c;
197
+ if (kind === 'soft') { const d = Math.hypot(dx, dy) / r; if (d >= 1) continue; const u = 1 - d; c = u * u * (3 - 2 * u); }
198
+ else if (kind === 'marker') { // a flat nib, 45°, a third as thick as it is wide
199
+ const u = (dx + dy) * Math.SQRT1_2, v = (dy - dx) * Math.SQRT1_2;
200
+ const e = Math.hypot(u / r, v / (r * 0.33));
201
+ c = Math.min(1, Math.max(0, (1 - e) * r * 0.33 + 0.5));
202
+ } else {
203
+ c = Math.min(1, Math.max(0, r - Math.hypot(dx, dy) + 0.5));
204
+ if (kind === 'chalk') c *= hash(px, py * 7919) > 0.42 ? 1 : 0.12; // grain fixed to the paper, so it stays put
205
+ }
206
+ if (c <= 0) continue;
207
+ c *= spec.flow;
208
+ const i = py * w + px;
209
+ if (c > cov[i]) { if (cov[i] === 0) touched[used++] = i; cov[i] = c; }
210
+ if (c > 0.02) when[i] = f;
211
+ }
212
+ }
213
+ };
214
+ // dabs along each segment painted by `now`, `spacing` brush widths apart
215
+ const pts = stroke.points;
216
+ let carry = 0;
217
+ const P = (p) => [p.x * w, p.y * h];
218
+ if (pts.length === 1 || pts.every((p) => p.x === pts[0].x && p.y === pts[0].y)) {
219
+ const [x, y] = P(pts[0]);
220
+ stamp(x, y, base * pts[0].wf, pts[0].f);
221
+ }
222
+ for (let j = 1; j < pts.length; j++) {
223
+ const a = pts[j - 1], b = pts[j];
224
+ if (a.f > now) break;
225
+ const [ax, ay] = P(a), [bx, by] = P(b);
226
+ let u1 = 1;
227
+ if (b.f > now) u1 = (now - a.f) / Math.max(1e-9, b.f - a.f);
228
+ const len = Math.hypot(bx - ax, by - ay);
229
+ let s = j === 1 ? 0 : carry;
230
+ while (s <= len * u1 && budget > 0) {
231
+ const u = len ? s / len : 0;
232
+ const r = base * (a.wf + (b.wf - a.wf) * u);
233
+ stamp(ax + (bx - ax) * u, ay + (by - ay) * u, r, a.f + (b.f - a.f) * u);
234
+ s += Math.max(0.5, spec.spacing * 2 * r);
235
+ }
236
+ carry = s - len;
237
+ if (u1 < 1 || budget <= 0) break;
238
+ }
239
+ // this stroke counts once wherever it went, however often it crossed itself
240
+ for (let k = 0; k < used; k++) {
241
+ const i = touched[k], c = cov[i];
242
+ alpha[i] = spec.buildUp ? 1 - (1 - alpha[i]) * (1 - c) : Math.max(alpha[i], c);
243
+ passes[i] += c;
244
+ if (c > 0.02 && when[i] > latest[i]) latest[i] = when[i];
245
+ cov[i] = 0;
246
+ }
247
+ });
248
+
249
+ const data = new Uint8ClampedArray(n * 4);
250
+ const inside = spec.clip === 'inside', outside = spec.clip === 'outside';
251
+ for (let i = 0; i < n; i++) {
252
+ let a = alpha[i];
253
+ if (a === 0) continue;
254
+ let m = 1;
255
+ if (mask && (inside || outside)) m = inside ? mask[i] : 1 - mask[i];
256
+ a *= m;
257
+ const j = i * 4;
258
+ data[j] = Math.round(Math.min(1, Math.max(0, (now - latest[i]) / spec.age)) * 255);
259
+ data[j + 1] = Math.round(Math.min(1, (passes[i] * m) / 4) * 255);
260
+ data[j + 2] = Math.round(Math.min(1, Math.max(0, latest[i] / Math.max(1e-9, total))) * 255);
261
+ data[j + 3] = Math.round(a * 255);
262
+ }
263
+ return { data, width: w, height: h, total };
264
+ }
265
+
266
+ /**
267
+ * The outlines of a mask (values > 0.5 are in), each a closed polyline of pixel
268
+ * centres, simplified; parts smaller than `minArea` pixels are left out.
269
+ * Moore-neighbour tracing, one outline per connected part.
270
+ */
271
+ export function traceContours(mask, w, h, { minArea = 40, tolerance = 0.8 } = {}) {
272
+ const inside = (x, y) => x >= 0 && y >= 0 && x < w && y < h && mask[y * w + x] > 0.5;
273
+ const label = new Int32Array(w * h).fill(-1);
274
+ const outlines = [];
275
+ const dirs = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]; // clockwise on screen
276
+ let parts = 0;
277
+ for (let y = 0; y < h; y++) {
278
+ for (let x = 0; x < w; x++) {
279
+ if (!inside(x, y) || label[y * w + x] >= 0) continue;
280
+ // the whole part, so its outline is traced once
281
+ const id = parts++;
282
+ const stack = [y * w + x];
283
+ label[y * w + x] = id;
284
+ let area = 0;
285
+ while (stack.length) {
286
+ const p = stack.pop();
287
+ area++;
288
+ const px = p % w, py = (p - px) / w;
289
+ for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
290
+ const qx = px + dx, qy = py + dy;
291
+ if (inside(qx, qy) && label[qy * w + qx] < 0) { label[qy * w + qx] = id; stack.push(qy * w + qx); }
292
+ }
293
+ }
294
+ if (area < minArea) continue;
295
+ // (x, y) is its top-left pixel: the one to its left is outside
296
+ const path = [[x, y]];
297
+ let cx = x, cy = y, back = 4; // we came from the west
298
+ for (let steps = 0; steps < 4 * area + 16; steps++) {
299
+ let found = false;
300
+ for (let k = 1; k <= 8; k++) {
301
+ const d = (back + k) % 8;
302
+ const nx = cx + dirs[d][0], ny = cy + dirs[d][1];
303
+ if (inside(nx, ny) && label[ny * w + nx] === id) {
304
+ back = (d + 4) % 8; // where we came from: the next search starts just past it, clockwise
305
+ cx = nx; cy = ny;
306
+ found = true;
307
+ break;
308
+ }
309
+ }
310
+ if (!found || (cx === x && cy === y)) break;
311
+ path.push([cx, cy]);
312
+ }
313
+ outlines.push(simplifyLoop(path, tolerance));
314
+ }
315
+ }
316
+ return outlines;
317
+ }
318
+
319
+ /**
320
+ * A closed loop (first point not repeated) simplified, and closed again: as two
321
+ * halves split at the point farthest from the start — simplify() alone would measure
322
+ * everything against a line from a point to itself, and keep nothing.
323
+ */
324
+ export function simplifyLoop(points, tolerance) {
325
+ if (points.length < 4) return [...points, points[0]];
326
+ const [x, y] = points[0];
327
+ let far = 0;
328
+ points.forEach(([px, py], i) => { if (Math.hypot(px - x, py - y) > Math.hypot(points[far][0] - x, points[far][1] - y)) far = i; });
329
+ return [...simplify(points.slice(0, far + 1), tolerance), ...simplify([...points.slice(far), points[0]], tolerance).slice(1)];
330
+ }
331
+
332
+ /** Ramer–Douglas–Peucker: fewer points, within `tolerance` pixels of the line. */
333
+ export function simplify(points, tolerance) {
334
+ if (points.length < 3) return points;
335
+ const keep = new Uint8Array(points.length);
336
+ keep[0] = keep[points.length - 1] = 1;
337
+ const stack = [[0, points.length - 1]];
338
+ while (stack.length) {
339
+ const [a, b] = stack.pop();
340
+ const [ax, ay] = points[a], [bx, by] = points[b];
341
+ const len = Math.hypot(bx - ax, by - ay) || 1e-9;
342
+ let worst = -1, at = -1;
343
+ for (let i = a + 1; i < b; i++) {
344
+ const d = Math.abs((bx - ax) * (ay - points[i][1]) - (ax - points[i][0]) * (by - ay)) / len;
345
+ if (d > worst) { worst = d; at = i; }
346
+ }
347
+ if (worst > tolerance) { keep[at] = 1; stack.push([a, at], [at, b]); }
348
+ }
349
+ return points.filter((_, i) => keep[i]);
350
+ }