@xenra/dsh-draworld 0.0.0-stage → 0.1.39

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/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Draworld",
4
+ "description": "One shared canvas in the right sidebar: strokes are data, so they undo cleanly and stay editable"
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "星染世界",
4
+ "description": "在右侧栏和模型共用一块可继续修改的画布:笔迹是数据,能撤销、能接着改"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@xenra/dsh-draworld",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.39",
4
+ "description": "星染世界:DeepSeek Harness 里的一块真画布: a right-sidebar canvas tab plus a paint_canvas tool, so the model and the human draw on the same document.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "RUO-MO",
8
+ "publishConfig": {
9
+ "access": "public",
10
+ "registry": "https://registry.npmjs.org/"
11
+ },
12
+ "engines": {
13
+ "node": ">=20"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/RUO-MO/dsh-draworld.git"
18
+ },
19
+ "homepage": "https://github.com/RUO-MO/dsh-draworld#readme",
20
+ "bugs": {
21
+ "url": "https://github.com/RUO-MO/dsh-draworld/issues"
22
+ },
23
+ "keywords": [
24
+ "dsh",
25
+ "deepseek-harness",
26
+ "plugin",
27
+ "canvas",
28
+ "painting",
29
+ "paint_canvas"
30
+ ],
31
+ "exports": {
32
+ ".": "./index.js",
33
+ "./client": "./client.js",
34
+ "./locale/*.json": "./locale/*.json",
35
+ "./icon": "./icon.svg",
36
+ "./package.json": "./package.json"
37
+ },
38
+ "scripts": {
39
+ "version:bump": "node tools/bump-version.mjs",
40
+ "version:watch": "node tools/watch-version.mjs"
41
+ },
42
+ "files": [
43
+ "index.js",
44
+ "client.js",
45
+ "pixels.js",
46
+ "pixelops.js",
47
+ "cordis.patch.yml",
48
+ "locale/*.json",
49
+ "icon.svg",
50
+ "README.md",
51
+ "LICENSE"
52
+ ],
53
+ "dsh": {
54
+ "bundle": {
55
+ "patch": "./cordis.patch.yml"
56
+ },
57
+ "client": {
58
+ "platform": "web",
59
+ "immediately": true,
60
+ "inject": [
61
+ "@deepseek-ai/dsh-client-ui-conversation"
62
+ ]
63
+ }
64
+ }
65
+ }
package/pixelops.js ADDED
@@ -0,0 +1,420 @@
1
+ /**
2
+ * 宿主侧像素任务实现:crop / ref / pick / palette / trace / copy / fill / compare。
3
+ * 依赖 ./pixels.js(纯 JS 解码、光栅化、折线、聚类);不依赖浏览器。
4
+ */
5
+ import path from "node:path";
6
+ import {
7
+ loadImage, inkMask, blurMask, marchingSquares, stitchSegments, rdp, traceInk,
8
+ kmeansColors, polygonArea, pointInPolygon, pathWidths, rasterDoc, cropSurface, zoomSurface,
9
+ encodePng, makeSurface, toHex,
10
+ } from "./pixels.js";
11
+
12
+ const dataUrlOf = (surf) => `data:image/png;base64,${encodePng(surf.data, surf.w, surf.h).toString("base64")}`;
13
+
14
+ function refLayer(doc, wanted) {
15
+ const layers = (doc.layers || []).filter((l) => l.image);
16
+ if (wanted) return layers.find((l) => l.id === wanted || l.name === wanted) || null;
17
+ return layers.find((l) => l.visible !== false) || layers[0] || null;
18
+ }
19
+
20
+ function clampRect(rect, w, h) {
21
+ const r = rect || {};
22
+ const x = Math.max(0, Math.min(w - 1, Math.round(Number(r.x) || 0)));
23
+ const y = Math.max(0, Math.min(h - 1, Math.round(Number(r.y) || 0)));
24
+ const cw = Math.max(1, Math.min(w - x, Math.round(Number(r.w) || w)));
25
+ const ch = Math.max(1, Math.min(h - y, Math.round(Number(r.h) || h)));
26
+ return { x, y, w: cw, h: ch };
27
+ }
28
+
29
+ /** 只画参考图那一层,得到整幅位图。 */
30
+ async function refSurface(doc, resolve, params) {
31
+ const layer = refLayer(doc, params.layer);
32
+ if (!layer) throw new Error("画布上没有可用的参考图:先 import 一张");
33
+ const img = await loadImage(resolve(layer.image.file));
34
+ const surf = makeSurface(doc.width || 1024, doc.height || 1024);
35
+ const { blitImage } = await import("./pixels.js");
36
+ blitImage(surf, img, layer.image.x || 0, layer.image.y || 0, layer.image.w || img.width, layer.image.h || img.height);
37
+ return surf;
38
+ }
39
+
40
+ export async function runHeadless(kind, params, doc, resolve) {
41
+ const W = doc.width || 1024;
42
+ const H = doc.height || 1024;
43
+ if (kind === "crop") {
44
+ const rect = clampRect(params.rect, W, H);
45
+ const zoom = Math.max(1, Math.min(8, Math.round(Number(params.zoom) || 1)));
46
+ let surf;
47
+ if (params.layer) {
48
+ const one = { ...doc, layers: (doc.layers || []).filter((l) => l.id === params.layer || l.name === params.layer) };
49
+ surf = await rasterDoc(one, { resolve });
50
+ } else {
51
+ surf = await rasterDoc(doc, { resolve });
52
+ }
53
+ const cut = cropSurface(surf, rect);
54
+ const zoomed = zoomSurface(cut, zoom);
55
+ return { ok: true, dataUrl: dataUrlOf(zoomed), rect, zoom, layer: params.layer || null, width: zoomed.w, height: zoomed.h, headless: true };
56
+ }
57
+ if (kind === "ref") {
58
+ const layer = refLayer(doc, params.layer);
59
+ if (!layer) throw new Error(params.layer ? `没有这个图片层:${params.layer}` : "画布上还没有图片层,先 action=import");
60
+ const img = await loadImage(resolve(layer.image.file));
61
+ const surf = makeSurface(img.width, img.height);
62
+ const { blitImage } = await import("./pixels.js");
63
+ blitImage(surf, img, 0, 0, img.width, img.height);
64
+ const rect = clampRect(params.rect || { x: 0, y: 0, w: img.width, h: img.height }, img.width, img.height);
65
+ const cut = cropSurface(surf, rect);
66
+ const zoomed = zoomSurface(cut, Math.max(1, Math.min(8, Math.round(Number(params.zoom) || 1))));
67
+ return { ok: true, dataUrl: dataUrlOf(zoomed), rect, zoom: Number(params.zoom) || 1, width: zoomed.w, height: zoomed.h, headless: true };
68
+ }
69
+ if (kind === "pick") {
70
+ const x = Math.round(Number(params.x));
71
+ const y = Math.round(Number(params.y));
72
+ const surf = params.on === "canvas" ? await rasterDoc(doc, { resolve }) : await refSurface(doc, resolve, params);
73
+ if (x < 0 || y < 0 || x >= surf.w || y >= surf.h) throw new Error("坐标超出画布");
74
+ const i = (y * surf.w + x) * 4;
75
+ const data = surf.data;
76
+ return {
77
+ ok: true,
78
+ x, y,
79
+ hex: toHex(data[i], data[i + 1], data[i + 2]),
80
+ rgb: [data[i], data[i + 1], data[i + 2]],
81
+ alpha: data[i + 3] / 255,
82
+ ink: data[i + 3] > 12 && (0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2]) < 128,
83
+ headless: true,
84
+ };
85
+ }
86
+ if (kind === "palette") {
87
+ const surf = await refSurface(doc, resolve, params);
88
+ const rect = clampRect(params.rect, surf.w, surf.h);
89
+ const cut = cropSurface(surf, rect);
90
+ const k = Math.max(2, Math.min(8, Math.round(Number(params.k) || 6)));
91
+ const colors = kmeansColors(cut.data, k);
92
+ return { ok: true, colors, sampled: Math.round((rect.w * rect.h) / 2), rect, method: "kmeans", headless: true };
93
+ }
94
+ if (kind === "trace") {
95
+ const surf = await refSurface(doc, resolve, params);
96
+ const rect = clampRect(params.rect, surf.w, surf.h);
97
+ const cut = cropSurface(surf, rect);
98
+ const t = traceInk(cut.data, cut.w, cut.h, {
99
+ mode: params.mode === "center" ? "center" : "edge",
100
+ smooth: params.smooth,
101
+ fit: params.fit === true,
102
+ fitStep: params.fitStep,
103
+ threshold: params.threshold,
104
+ tolerance: params.tolerance,
105
+ minLength: params.minLength,
106
+ maxLines: params.maxLines,
107
+ });
108
+ const paths = t.paths.map((line) => line.map((p) => [Math.round(rect.x + p[0]), Math.round(rect.y + p[1])]));
109
+ // 调 THRESHOLD/TOLERANCE/STEP 时得有反馈:给线宽分布和墨迹占比,
110
+ // 不然只能肉眼反复试(0.1.38 之前 trace 只回 lines/points/dropped)。
111
+ const mask = inkMask(cut.data, cut.w, cut.h, params.threshold);
112
+ let inkPx = 0;
113
+ for (let i = 0; i < mask.length; i += 1) inkPx += mask[i];
114
+ const widths = pathWidths(mask, cut.w, cut.h, t.paths);
115
+ const widthAvg = widths.length ? Number((widths.reduce((a, b) => a + b, 0) / widths.length).toFixed(2)) : null;
116
+ const stats = {
117
+ inkRatio: Number((inkPx / (cut.w * cut.h)).toFixed(4)),
118
+ widthAvg,
119
+ widthMin: widths.length ? Number(Math.min(...widths).toFixed(2)) : null,
120
+ widthMax: widths.length ? Number(Math.max(...widths).toFixed(2)) : null,
121
+ pointsPerLine: t.lines ? Number((t.points / t.lines).toFixed(1)) : null,
122
+ droppedPct: t.lines + t.dropped > 0 ? Number((t.dropped / (t.lines + t.dropped) * 100).toFixed(1)) : null,
123
+ };
124
+ return {
125
+ ok: true, rect, paths, lines: t.lines, points: t.points, dropped: t.dropped,
126
+ tolerance: t.tolerance, smooth: t.smooth, fit: t.fit, mode: t.mode, headless: true, stats,
127
+ };
128
+ }
129
+ if (kind === "copy") {
130
+ const surf = await refSurface(doc, resolve, params);
131
+ const rect = clampRect(params.rect, surf.w, surf.h);
132
+ const cut = cropSurface(surf, rect);
133
+ const mask = inkMask(cut.data, cut.w, cut.h, params.threshold);
134
+ let inkPx = 0;
135
+ for (let i = 0; i < mask.length; i += 1) inkPx += mask[i];
136
+ const inkRatio = Number((inkPx / (cut.w * cut.h)).toFixed(3));
137
+ const mode = params.mode === "center" || params.mode === "edge" ? params.mode : (inkRatio < 0.13 ? "center" : "edge");
138
+ const t = traceInk(cut.data, cut.w, cut.h, {
139
+ mode,
140
+ smooth: params.smooth === undefined ? 2 : params.smooth,
141
+ fit: params.fit === undefined ? true : params.fit,
142
+ fitStep: params.fitStep || 3,
143
+ threshold: params.threshold,
144
+ tolerance: params.tolerance,
145
+ minLength: params.minLength === undefined ? 16 : params.minLength,
146
+ maxLines: params.maxLines || 160,
147
+ maxPointsPerLine: params.maxPointsPerLine || 120,
148
+ });
149
+ const palette = kmeansColors(cut.data, Math.max(2, Math.min(8, Number(params.colors) || 6)));
150
+ const paths = t.paths.map((line) => line.map((p) => [Math.round(rect.x + p[0]), Math.round(rect.y + p[1])]));
151
+ const widths = pathWidths(inkMask(cut.data, cut.w, cut.h, params.threshold), cut.w, cut.h, t.paths);
152
+ const lineWidth = widths.length ? Number((widths.reduce((a, b) => a + b, 0) / widths.length).toFixed(2)) : null;
153
+ const wantFill = params.style === "flat" || params.style === "anime";
154
+ // 色块必须靠闭合轮廓;中心线模式下的路径是骨架,不闭合,所以填色另跑一遍边界追踪
155
+ let edgeTrace = t;
156
+ if (wantFill && mode === "center") {
157
+ edgeTrace = traceInk(cut.data, cut.w, cut.h, {
158
+ mode: "edge",
159
+ smooth: params.smooth === undefined ? 2 : params.smooth,
160
+ fit: false,
161
+ threshold: params.threshold,
162
+ tolerance: params.tolerance,
163
+ minLength: params.minLength === undefined ? 16 : params.minLength,
164
+ maxLines: params.maxLines || 160,
165
+ maxPointsPerLine: params.maxPointsPerLine || 120,
166
+ });
167
+ }
168
+ const fills = wantFill
169
+ ? regionFillsFromBitmap(cut, edgeTrace, palette, { minFill: params.minFill, maxFills: params.maxFills || 40, rect })
170
+ : [];
171
+ return {
172
+ ok: true, rect, paths, widths, lineWidth, closed: t.closed, fills, palette, mode,
173
+ smooth: t.smooth, fit: t.fit, inkRatio, lines: t.lines, points: t.points, dropped: t.dropped, headless: true,
174
+ };
175
+ }
176
+ if (kind === "fill") {
177
+ const sx = Math.round(Number(params.x));
178
+ const sy = Math.round(Number(params.y));
179
+ if (!Number.isFinite(sx) || !Number.isFinite(sy) || sx < 0 || sy < 0 || sx >= W || sy >= H) throw new Error("fill 的种子点超出画布");
180
+ // 屏障只认笔迹(不含色块),否则第二次填会被自己的色块挡住
181
+ const barrierDoc = { ...doc, layers: (doc.layers || []).map((l) => ({ ...l, image: null, strokes: (l.strokes || []).filter((s) => s.mode !== "fill") })) };
182
+ const drawn = await rasterDoc(barrierDoc, { resolve, withImages: false });
183
+ const barrier = new Uint8Array(W * H);
184
+ for (let i = 0, p = 0; p < W * H; p += 1, i += 4) barrier[p] = drawn.data[i + 3] > 24 ? 1 : 0;
185
+ if (barrier[sy * W + sx]) throw new Error("这个点落在线上:换一个区域内部的点");
186
+ const rect = clampRect(params.rect, W, H);
187
+ const region = new Uint8Array(W * H);
188
+ const stack = [sy * W + sx];
189
+ let count = 0;
190
+ while (stack.length) {
191
+ const q = stack.pop();
192
+ if (region[q] || barrier[q]) continue;
193
+ const x = q % W;
194
+ const y = (q - x) / W;
195
+ if (x < rect.x || y < rect.y || x >= rect.x + rect.w || y >= rect.y + rect.h) continue;
196
+ region[q] = 1;
197
+ count += 1;
198
+ if (x > 0) stack.push(q - 1);
199
+ if (x < W - 1) stack.push(q + 1);
200
+ if (y > 0) stack.push(q - W);
201
+ if (y < H - 1) stack.push(q + W);
202
+ }
203
+ if (count === 0) throw new Error("这个种子点没围出可填的区域");
204
+ if (count > W * H * 0.62) throw new Error("这块区域连到了整片背景(超过画布 62%):先有线稿,或者用 rect 缩小范围");
205
+ const loops = stitchSegments(marchingSquares(region, W, H))
206
+ .map((raw) => {
207
+ const pts = raw.map((p) => [p[0] / 2, p[1] / 2]);
208
+ // stitch 会把首点重复接在末尾;rdp 对首尾同点的折线会直接塌成两点
209
+ if (pts.length > 3 && Math.hypot(pts[0][0] - pts[pts.length - 1][0], pts[0][1] - pts[pts.length - 1][1]) < 1.5) pts.pop();
210
+ return { pts: rdp(pts, 1.5) };
211
+ })
212
+ .map((v) => ({ ...v, area: polygonArea(v.pts) }))
213
+ .filter((v) => v.area > 40)
214
+ .sort((a, b) => b.area - a.area)
215
+ .slice(0, 40);
216
+ const parents = loops.map(() => -1);
217
+ for (let i = 0; i < loops.length; i += 1) {
218
+ const p0 = loops[i].pts[0];
219
+ let best = -1;
220
+ for (let j = 0; j < i; j += 1) {
221
+ if (loops[j].area <= loops[i].area) continue;
222
+ if (!pointInPolygon(p0[0], p0[1], loops[j].pts)) continue;
223
+ if (best === -1 || loops[j].area < loops[best].area) best = j;
224
+ }
225
+ parents[i] = best;
226
+ }
227
+ const depths = loops.map((_, i) => {
228
+ let d = 0;
229
+ let p = parents[i];
230
+ while (p !== -1 && d < 8) {
231
+ d += 1;
232
+ p = parents[p];
233
+ }
234
+ return d;
235
+ });
236
+ const polys = [];
237
+ for (let i = 0; i < loops.length; i += 1) {
238
+ if (depths[i] % 2 !== 0) continue;
239
+ const holes = loops.filter((_, j) => parents[j] === i).slice(0, 10).map((hh) => hh.pts.map((p) => [Math.round(p[0]), Math.round(p[1])]));
240
+ polys.push({ points: loops[i].pts.map((p) => [Math.round(p[0]), Math.round(p[1])]), holes, area: Math.round(loops[i].area) });
241
+ if (polys.length >= 12) break;
242
+ }
243
+ let color = params.color || null;
244
+ if (!color) {
245
+ const ref = await refSurface(doc, resolve, params);
246
+ const pal = kmeansColors(ref.data, 6, 4);
247
+ const i = (sy * W + sx) * 4;
248
+ const rgb = [ref.data[i], ref.data[i + 1], ref.data[i + 2]];
249
+ let best = pal[0];
250
+ let bestD = Infinity;
251
+ for (const c of pal) {
252
+ const d = (c.rgb[0] - rgb[0]) ** 2 + (c.rgb[1] - rgb[1]) ** 2 + (c.rgb[2] - rgb[2]) ** 2;
253
+ if (d < bestD) { bestD = d; best = c; }
254
+ }
255
+ color = best ? best.hex : toHex(rgb[0], rgb[1], rgb[2]);
256
+ }
257
+ return { ok: true, seed: [sx, sy], area: count, color, polygons: polys, headless: true };
258
+ }
259
+ if (kind === "compare") {
260
+ const rect = clampRect(params.rect, W, H);
261
+ const ref = await refSurface(doc, resolve, params);
262
+ const drawn = await rasterDoc({ ...doc, layers: (doc.layers || []).map((l) => ({ ...l, image: null })) }, { resolve, withImages: false });
263
+ return compareSurfaces(ref, drawn, rect);
264
+ }
265
+ throw new Error(`无界面模式不支持这个像素任务:${kind}`);
266
+ }
267
+
268
+ /** 参考图 vs 当前画面:品红=漏画、青=多画,给出覆盖率与最漏的几块。 */
269
+ export function compareSurfaces(ref, drawn, rect) {
270
+ const rd = ref.data;
271
+ const dd = drawn.data;
272
+ const diff = makeSurface(rect.w, rect.h);
273
+ const out = diff.data;
274
+ let refInk = 0;
275
+ let drawInk = 0;
276
+ let covered = 0;
277
+ let extra = 0;
278
+ let sumDiff = 0;
279
+ const GRID = 32;
280
+ const cells = new Map();
281
+ for (let y = 0; y < rect.h; y += 1) {
282
+ for (let x = 0; x < rect.w; x += 1) {
283
+ const si = ((rect.y + y) * ref.w + (rect.x + x)) * 4;
284
+ const di = (y * rect.w + x) * 4;
285
+ const ra = rd[si + 3];
286
+ const da = dd[si + 3];
287
+ const isRef = ra > 12;
288
+ const isDraw = da > 12;
289
+ if (isRef) refInk += 1;
290
+ if (isDraw) drawInk += 1;
291
+ if (isRef && isDraw) {
292
+ covered += 1;
293
+ sumDiff += (Math.abs(rd[si] - dd[si]) + Math.abs(rd[si + 1] - dd[si + 1]) + Math.abs(rd[si + 2] - dd[si + 2])) / 3;
294
+ out[di] = Math.round((rd[si] + dd[si]) / 2);
295
+ out[di + 1] = Math.round((rd[si + 1] + dd[si + 1]) / 2);
296
+ out[di + 2] = Math.round((rd[si + 2] + dd[si + 2]) / 2);
297
+ out[di + 3] = 140;
298
+ } else if (isRef) {
299
+ out[di] = 255;
300
+ out[di + 1] = 0;
301
+ out[di + 2] = 255;
302
+ out[di + 3] = 235;
303
+ const key = `${Math.floor((x / rect.w) * GRID)},${Math.floor((y / rect.h) * GRID)}`;
304
+ const cell = cells.get(key) || { x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity, n: 0 };
305
+ cell.n += 1;
306
+ if (rect.x + x < cell.x0) cell.x0 = rect.x + x;
307
+ if (rect.y + y < cell.y0) cell.y0 = rect.y + y;
308
+ if (rect.x + x > cell.x1) cell.x1 = rect.x + x;
309
+ if (rect.y + y > cell.y1) cell.y1 = rect.y + y;
310
+ cells.set(key, cell);
311
+ } else if (isDraw) {
312
+ out[di] = 0;
313
+ out[di + 1] = 210;
314
+ out[di + 2] = 255;
315
+ out[di + 3] = 200;
316
+ extra += 1;
317
+ }
318
+ }
319
+ }
320
+ const gaps = [...cells.values()].sort((a, b) => b.n - a.n).slice(0, 4).map((c) => ({
321
+ x: Math.round(c.x0), y: Math.round(c.y0), w: Math.round(c.x1 - c.x0) + 1, h: Math.round(c.y1 - c.y0) + 1, missed: c.n,
322
+ }));
323
+ return {
324
+ ok: true,
325
+ dataUrl: dataUrlOf(diff),
326
+ rect,
327
+ metrics: {
328
+ rect,
329
+ refInkPixels: refInk,
330
+ drawnInkPixels: drawInk,
331
+ coveredPixels: covered,
332
+ extraPixels: extra,
333
+ coveragePct: refInk ? Number(((covered / refInk) * 100).toFixed(1)) : 100,
334
+ extraPct: drawInk ? Number(((extra / drawInk) * 100).toFixed(1)) : 0,
335
+ meanColorDiff: covered ? Number((sumDiff / covered).toFixed(1)) : null,
336
+ topGaps: gaps,
337
+ },
338
+ headless: true,
339
+ };
340
+ }
341
+
342
+ /** 闭合轮廓取内部主色(宿主版:按点在多边形内采样,不依赖 canvas 遮罩)。 */
343
+ function regionFillsFromBitmap(cut, traced, palette, opts = {}) {
344
+ const minFill = Math.max(20, Number(opts.minFill) || 320);
345
+ const maxFills = Math.max(1, Number(opts.maxFills) || 60);
346
+ const cands = traced.paths
347
+ .map((p, i) => ({ pts: p, closed: Boolean(traced.closed && traced.closed[i]), area: polygonArea(p) }))
348
+ .filter((c) => c.closed && c.area >= minFill)
349
+ .sort((a, b) => b.area - a.area);
350
+ const parents = cands.map(() => -1);
351
+ for (let i = 0; i < cands.length; i += 1) {
352
+ const p0 = cands[i].pts[0];
353
+ let best = -1;
354
+ for (let j = 0; j < i; j += 1) {
355
+ if (cands[j].area <= cands[i].area) continue;
356
+ if (!pointInPolygon(p0[0], p0[1], cands[j].pts)) continue;
357
+ if (best === -1 || cands[j].area < cands[best].area) best = j;
358
+ }
359
+ parents[i] = best;
360
+ }
361
+ const depths = cands.map((_, i) => {
362
+ let d = 0;
363
+ let p = parents[i];
364
+ while (p !== -1 && d < 8) { d += 1; p = parents[p]; }
365
+ return d;
366
+ });
367
+ const fills = [];
368
+ for (const [ci, cand] of cands.entries()) {
369
+ if (fills.length >= maxFills) break;
370
+ if (depths[ci] % 2 !== 0) continue;
371
+ const holes = cands.filter((_, j) => parents[j] === ci).slice(0, 10);
372
+ let x0 = Infinity;
373
+ let y0 = Infinity;
374
+ let x1 = -Infinity;
375
+ let y1 = -Infinity;
376
+ for (const p of cand.pts) {
377
+ if (p[0] < x0) x0 = p[0];
378
+ if (p[1] < y0) y0 = p[1];
379
+ if (p[0] > x1) x1 = p[0];
380
+ if (p[1] > y1) y1 = p[1];
381
+ }
382
+ if ((x1 - x0) * (y1 - y0) > cut.w * cut.h * 0.82) continue;
383
+ const buckets = new Map();
384
+ const step = 3;
385
+ for (let y = Math.max(0, Math.floor(y0)); y <= Math.min(cut.h - 1, Math.ceil(y1)); y += step) {
386
+ for (let x = Math.max(0, Math.floor(x0)); x <= Math.min(cut.w - 1, Math.ceil(x1)); x += step) {
387
+ if (!pointInPolygon(x, y, cand.pts)) continue;
388
+ if (holes.some((hh) => pointInPolygon(x, y, hh.pts))) continue;
389
+ const i = (y * cut.w + x) * 4;
390
+ if (cut.data[i + 3] < 32) continue;
391
+ const key = ((cut.data[i] >> 3) << 10) | ((cut.data[i + 1] >> 3) << 5) | (cut.data[i + 2] >> 3);
392
+ const cur = buckets.get(key) || { r: 0, g: 0, b: 0, n: 0 };
393
+ cur.r += cut.data[i];
394
+ cur.g += cut.data[i + 1];
395
+ cur.b += cut.data[i + 2];
396
+ cur.n += 1;
397
+ buckets.set(key, cur);
398
+ }
399
+ }
400
+ if (buckets.size === 0) continue;
401
+ const top = [...buckets.values()].sort((a, b) => b.n - a.n)[0];
402
+ const rgb = [top.r / top.n, top.g / top.n, top.b / top.n];
403
+ let best = palette[0];
404
+ let bestD = Infinity;
405
+ for (const c of palette) {
406
+ const d = (c.rgb[0] - rgb[0]) ** 2 + (c.rgb[1] - rgb[1]) ** 2 + (c.rgb[2] - rgb[2]) ** 2;
407
+ if (d < bestD) { bestD = d; best = c; }
408
+ }
409
+ const rect = opts.rect || { x: 0, y: 0 };
410
+ fills.push({
411
+ points: cand.pts.map((p) => [Math.round(rect.x + p[0]), Math.round(rect.y + p[1])]),
412
+ holes: holes.map((hh) => hh.pts.map((p) => [Math.round(rect.x + p[0]), Math.round(rect.y + p[1])])),
413
+ color: best ? best.hex : toHex(Math.round(rgb[0]), Math.round(rgb[1]), Math.round(rgb[2])),
414
+ area: Math.round(cand.area),
415
+ });
416
+ }
417
+ return fills;
418
+ }
419
+
420
+ export { inkMask, blurMask, marchingSquares, stitchSegments, rdp };