@xenra/dsh-draworld 0.1.39 → 0.1.41

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/README.md CHANGED
@@ -165,7 +165,8 @@ https://github.com/RUO-MO/dsh-draworld
165
165
  | 动作 | 说明 |
166
166
  |---|---|
167
167
  | `doc` | 看尺寸、图层、笔迹数、颜色、内容范围、版本;图层带 `image` 就是图片层 |
168
- | `copy` | **一键复刻**:`style=lineart/flat/anime`,自动抽轮廓 + 区域配色,建「色块 / 线稿」两层,并顺带跑 compare 返回覆盖率;`colors`、`minFill` 可调;`mode` 不传则自动判断参考图是线稿还是照片(回报 `mode`、`inkRatio`);描线默认做**三次贝塞尔拟合**(`fit=false` 退回磨圆 `smooth=0~3`);每根线按量出来的**原线宽**落笔,`splitLines=true` 再把粗细分到「线稿 / 粗线」两层 |
168
+ | `copy` | **一键复刻**:`style=lineart/flat/anime/paint`。lineart/flat/anime 走「抽轮廓 + 区域配色」,建「色块 / 线稿」两层,并顺带跑 compare 返回覆盖率;`colors`、`minFill` 可调;`mode` 不传则自动判断参考图是线稿还是照片(回报 `mode`、`inkRatio`);描线默认做**三次贝塞尔拟合**(`fit=false` 退回磨圆 `smooth=0~3`);每根线按量出来的**原线宽**落笔,`splitLines=true` 再把粗细分到「线稿 / 粗线」两层。<br>**`style=paint`(0.1.40 起,厚涂/渐变/火焰这种没有闭合边界的图用它)**:不描轮廓,改成笔触铺色——先按大网格把整幅铺一遍(保证不留白),再只在局部对比强的地方(脸、手、褶皱、火焰边缘)补细笔;颜色取该格均色、笔触方向沿等色线、笔宽盖住格子对角线、不透明度随对比度走。默认 8000 笔出结构,`maxStrokes=12000` 接近成图质感(上限 20000);`paintStep` 控细节网格、`paintPasses=1` 只粗铺先看大关系;默认**不叠线稿**(厚涂图硬描会拖出大黑斜线),要叠给 `lineart=true`;`paintBrush` 可选笔刷。返回 `paint`(笔数)、`paintStats`(step/coarse/cells/skippedBg/capped) |
169
+ | `posterize` | **彩图复刻成图(0.1.40 起)**:先 k-means 量化成 `colors` 档(2~12,默认 8),再把每一色的连通区按 marching squares 轮廓各自落成一块可编辑填色(大块先垫、小块压上;细长条不过滤,避免交界白缝),建「色块」层;`lines=true` 顺手把色块边界描成「线稿」层。**彩稿用这个,别用 `copy`**——`copy` 的墨迹阈值会把黑袍当一整块墨,只出 160 根长线。`minArea`(默认面积/4000)、`maxFills`(默认 1600)、`tolerance`、`colors` 可调 |
169
170
  | `fix` | **自动补漏**:只看 compare 的 `topGaps` 重描最漏的几块,`target=90`、`maxRounds=3`,达标或没得补就停,返回每轮数字;落在色块洞里(高光)的缺口会跳过(`skippedHoles`) |
170
171
  | `fill` | **点一下填色**:`x`、`y` 是区域内的种子点,边界取现有笔迹,颜色默认取参考图该点并映射到主色;`color`、`rect`、`fillLayer` 可调;区域里的洞按轮廓嵌套自动挖掉(`evenodd` 填充) |
171
172
  | `select` | 选区:`rect=[x,y,w,h]` 或 `points`(套索),之后落笔只保留选区内的点(越界会切段);`clearSelection=true` 取消 |
@@ -175,26 +176,33 @@ https://github.com/RUO-MO/dsh-draworld
175
176
  | `trace` | 参考图 → 轮廓折线:返回 `paths`(画布坐标,直接当 draw 的 points),`threshold` 调深浅、`tolerance` 调概括;`mode=center` 走骨架中心线(线稿用),默认 `edge` 沿墨迹边界;`smooth=0~3` 控制磨圆遍数(默认 1),`fit=true` 改用三次贝塞尔拟合(长弧一条曲线走完) |
176
177
  | `pick` | 读某点颜色与透明度(`x`、`y`,`on=ref/canvas`):`ink=true` 说明这点在线条上 |
177
178
  | `compare` | 当前画面 vs 参考图:差分图(品红=漏画、青=多画)+ `coveragePct`、`extraPct`、`meanColorDiff`、`topGaps`(最漏的几块) |
178
- | `palette` | 参考图主色聚类(真 k-means,`k` 2~8)+ 每色占比 |
179
+ | `palette` | 参考图主色聚类(真 k-means,`k` 2~12)+ 每色占比 |
179
180
  | `snapshot` / `restore` | 整幅存档 / 回到某一版(比逐笔 undo 干净,跨进程也在) |
180
181
  | `layer` | `layerOp=list/add/select/set/remove`;`set` 改 `name`、`visible`、`layerOpacity`、`blend`、`locked`(锁住就画不上去、也擦不掉) |
181
- | `import` | 本机图片或 dataUrl 导入成最底层;`fit=contain/cover/stretch` |
182
+ | `import` | 本机图片或 dataUrl 导入成最底层;落位用 `placement=contain/cover/stretch`(旧的 `fit` 字符串仍兼容) |
182
183
  | `canvas` | 改尺寸(16~4096)与背景 |
183
184
  | `new` | 另起一幅:可先 `save` 存当前,或给 `path`/`dataUrl` 按图建画布 |
184
- | `export` | 把最新渲染另存 PNG 到保存路径(`transparent=true` 取透明底) |
185
+ | `export` | 把最新渲染另存 PNG(`path` 给路径、`transparent=true` 取透明底);**面板没开时宿主用 `rasterDoc` 自己画一遍再导出(0.1.40 起)**,不再等前端回传 |
185
186
  | `undo` / `redo` | 按全局顺序撤/恢复最近 N 笔 |
186
187
  | `clear` | 清空整幅;带 `layer` 只清那层(`all`/`*` 等同整幅) |
187
188
 
188
- **复刻一张图**的闭环:最省模型能力的是 `copy` → `fix` 两条命令;想手工精修再按 `ref` 看细节 → `palette` 定配色 → `trace` 抽轮廓 → `pick` 确认某点在不在线上 → `draw`(长线用 `batches`)→ `view layer=… rect=… zoom=2` 看自己那块 → `compare` 看差多少(`coveragePct` 往 90+ 推、`extraPct` 压下去)→ 收尾前 `snapshot` 兜底。整段流程与协议文本都写进了会话提示词,模型看得到。
189
+ **复刻一张图**的闭环:彩稿分两种走法——平涂/线色分明的走 `posterize`(色阶分区铺色 ± 边界线稿);厚涂、渐变、火焰、毛发这种没有闭合边界的走 `copy style=paint`(笔触铺色,`maxStrokes=12000` 要质感);纯线稿走 `copy`/`trace` → 再 `fix` 补漏;想手工精修再按 `ref` 看细节 → `palette` 定配色 → `trace` 抽轮廓 → `pick` 确认某点在不在线上 → `draw`(长线用 `batches`)→ `view layer=… rect=… zoom=2` 看自己那块 → `compare` 看差多少(`coveragePct` 往 90+ 推、`extraPct` 压下去)→ 收尾前 `snapshot` 兜底。整段流程与协议文本都写进了会话提示词,模型看得到。
190
+
191
+ **`style=paint` 复刻出来的样子**(1080×1440 彩稿 → 12000 笔触,全矢量可编辑,无图片层):
192
+
193
+ ![笔触复刻](docs/assets/paint-replica.png)
194
+
195
+ **大批落笔能边画边看(0.1.40 起)**:`copy` / `draw batches` 不再一次性把几千笔塞进文档末尾才刷新,而是每 120 笔一块写进去、中间让出事件循环,同时 `state.painting = {layer, done, total}` 通过 `GET /canvas-api/doc` 的 `painting` 字段给面板。侧边标签页的进度条(左上角 ✎ 层名 + `1200/8000`)就是读这个字段,停顿和「卡住不动」能一眼分清。
189
196
 
190
197
  **改局部别糊整幅**:先 `select` 框住范围(`rect` 或套索 `points`),再 `draw` / `fill`,越界点会被裁掉;改完 `select clearSelection=true`。选区存在 `doc.json` 的 `selection` 字段里,会跟着文档走。
191
198
 
192
199
  **像素任务(两套引擎,自动择一)**:裁切、取色、差分、主色、描线、复刻、填色这些活有两处可算。
193
200
 
194
- - **前端**:浏览器早就把参考图解码进 `<canvas>` 了,最快。宿主把任务塞队列,前端 700ms 轮询 `/canvas-api/jobs` 取走,算完 POST `/canvas-api/job`,宿主落盘成 PNG 或转成折线/数值交给模型。
201
+ - **前端**:浏览器早就把参考图解码进 `<canvas>` 了,最快。宿主把任务塞队列,前端 500ms 轮询 `/canvas-api/jobs` 取走(0.1.40 起由 700ms 缩短),算完 POST `/canvas-api/job`,宿主落盘成 PNG 或转成折线/数值交给模型。
195
202
  - **宿主侧(0.1.35 起)**:面板没开(`/jobs` 2.5 秒没人来取)时,宿主自己算——`pixels.js` 是纯 JS 的 PNG 解码/编码(8bit,colorType 0/2/4/6,不支持调色板/隔行/16bit)+ 光栅化 + marching squares / Zhang-Suen 骨架 / RDP / Chaikin / 三次贝塞尔,`pixelops.js` 跑 crop / ref / pick / palette / trace / copy / fill / compare。所以「不开界面也能 `copy` → `fix`」这条已经通了,不再 5 秒超时。非 PNG 参考图(JPEG 等)会用 PowerShell 的 `System.Drawing` 转一次临时 PNG 再读。
196
203
  - 宿主算不出来才回落到队列,超时默认 5 秒(`trace`/`copy`/`fill`/`compare`/`palette` 这类整幅重活 30 秒,`heavyTimeout` 可调)、话术直说「宿主侧没算成、面板也没接任务」。不想让宿主插手、只走浏览器:插件配置写 `headless: false`(也可 `POST /canvas-api/config {"headless": false}` 临时切)。
197
204
  - **`trace` 带调参反馈(0.1.39 起)**:返回体里多了 `stats` —— `inkRatio`(墨迹占比,判断阈值是不是把阴影也吃进来了)、`widthAvg/Min/Max`(量出来的线宽,拿来设笔刷 size)、`pointsPerLine`(重采样疏密,对应 `fitStep`/`step`)、`droppedPct`(被 `minLength` 丢掉的短段比例)。调 `threshold`/`tolerance`/`fitStep` 时看这几个数,不用只靠肉眼比成品。
205
+ - **画的过程能看见了(0.1.40 起)**:前端 tick 里发现「最上层追加了普通笔迹、其他层没变」就直接 paintStroke 补画那一笔(paintAppended),不再整幅
206
+ enderDoc 重绘;轮询 500ms。模型一批 300 笔过去,画布是逐笔长出来的,跳变间隔从 0.7 秒缩到半秒。
198
207
  - **图片类型按内容判**:`import` 不看扩展名,读魔数认 PNG / JPEG / WebP / GIF,缓存名统一是 `img-<stamp>-<rand>.<真扩展名>`;`ref` 遇到非 PNG 会先转一份 `views/ref-…-<mtime>.png` 再交给 `read_image`(同一文件按 mtime 复用,原文件保留不动)。
199
208
 
200
209
  **填色边界**:`copy` 走中心线时,色块另跑一遍边界追踪取闭合轮廓(骨架不闭合),洞按嵌套层数 even-odd 挖掉;`fill` 的泛洪边界只认笔迹(不含已填色块),区域撞到「超过画布 62%」会拒填并提示先有线稿或用 `rect` 收窄。
package/client.js CHANGED
@@ -1046,6 +1046,54 @@ window.__ModuleLoader__.load({
1046
1046
  g.restore();
1047
1047
  }
1048
1048
 
1049
+ /**
1050
+ * 只有「最上面那层追加了普通笔迹」时,直接在现有画布上补画,不整幅重绘。
1051
+ * 模型一批批落笔时,面板因此是「一笔笔长出来」,而不是每 700ms 跳一张新图。
1052
+ * 返回 false 表示这次变动不适合增量,交给 renderDoc 全量画。
1053
+ */
1054
+ function paintAppended(canvas, prevDoc, nextDoc) {
1055
+ if (!canvas || !prevDoc || !nextDoc) return false;
1056
+ if (prevDoc.width !== nextDoc.width || prevDoc.height !== nextDoc.height) return false;
1057
+ const a = layersOf(prevDoc);
1058
+ const b = layersOf(nextDoc);
1059
+ if (a.length !== b.length) return false;
1060
+ let changed = -1;
1061
+ let added = 0;
1062
+ for (let i = 0; i < b.length; i += 1) {
1063
+ const pa = a[i];
1064
+ const pb = b[i];
1065
+ if (pa.id !== pb.id) return false;
1066
+ if (pa.visible !== pb.visible) return false;
1067
+ if ((pa.opacity === undefined ? 1 : Number(pa.opacity)) !== (pb.opacity === undefined ? 1 : Number(pb.opacity))) return false;
1068
+ if ((pa.blend || 'normal') !== (pb.blend || 'normal')) return false;
1069
+ if (Boolean(pa.image && pa.image.file) !== Boolean(pb.image && pb.image.file)) return false;
1070
+ const na = (pa.strokes || []).length;
1071
+ const nb = (pb.strokes || []).length;
1072
+ if (nb < na) return false;
1073
+ if (nb > na) {
1074
+ if (changed >= 0) return false;
1075
+ changed = i;
1076
+ added = nb - na;
1077
+ }
1078
+ }
1079
+ if (changed < 0 || added === 0) return false;
1080
+ const layer = b[changed];
1081
+ if (layer.visible === false) return true; // 看不见的层加了笔,画面本来就不用变
1082
+ if (changed !== b.length - 1) return false; // 不是最上层,叠上去会盖住上面
1083
+ if ((layer.opacity === undefined ? 1 : Number(layer.opacity)) !== 1) return false;
1084
+ if (layer.blend === 'multiply') return false;
1085
+ const fresh = (layer.strokes || []).slice((a[changed].strokes || []).length);
1086
+ if (fresh.some((s) => s.mode === 'eraser')) return false;
1087
+ const g = canvas.getContext('2d');
1088
+ if (!g) return false;
1089
+ g.save();
1090
+ g.globalCompositeOperation = 'source-over';
1091
+ g.globalAlpha = 1;
1092
+ for (const s of fresh) paintStroke(g, s);
1093
+ g.restore();
1094
+ return true;
1095
+ }
1096
+
1049
1097
  /** 造一块离屏画布。 */
1050
1098
  function surface(w, h) {
1051
1099
  const c = document.createElement('canvas');
@@ -2514,6 +2562,9 @@ window.__ModuleLoader__.load({
2514
2562
  const [updateInfo, setUpdateInfo] = React.useState(null);
2515
2563
  const [applying, setApplying] = React.useState(false);
2516
2564
  const [applyNote, setApplyNote] = React.useState('');
2565
+ /** 宿主正在大批落笔时的进度(分块写入,面板能边画边看)。 */
2566
+ const [painting, setPainting] = React.useState(null);
2567
+ const paintingRef = React.useRef(null);
2517
2568
 
2518
2569
  /** 一键更新:宿主拿 pluginManager 按 tag 重装(git 安装也能收更新)。 */
2519
2570
  const applyUpdate = async () => {
@@ -2789,15 +2840,21 @@ window.__ModuleLoader__.load({
2789
2840
  // 宿主有没有 32 支笔刷:旧进程只认 5 支,落笔后笔刷会被丢掉,重画成圆头
2790
2841
  setStaleHost(!(Number(body.brushes) >= BRUSHES.length));
2791
2842
  setUpdateInfo(body.update || null);
2843
+ setPainting(body.painting || null);
2844
+ paintingRef.current = body.painting || null;
2792
2845
  if (body.version) setLocalVer(String(body.version));
2846
+ const prevDoc = docRef.current;
2847
+ const prevRev = revRef.current;
2793
2848
  docRef.current = body.doc;
2794
2849
  await ensureImages(body.doc);
2795
2850
  if (!alive) return;
2796
- if (body.revision !== revRef.current) {
2851
+ if (body.revision !== prevRev) {
2797
2852
  revRef.current = body.revision;
2798
2853
  setRevision(body.revision);
2799
2854
  readMeta(body.doc);
2800
- renderDoc(canvasRef.current, body.doc);
2855
+ if (!paintAppended(canvasRef.current, prevDoc, body.doc)) {
2856
+ renderDoc(canvasRef.current, body.doc);
2857
+ }
2801
2858
  setTimeout(uploadPreview, 300);
2802
2859
  // 第一次拿到文档、或画布尺寸变了,重新适应窗口
2803
2860
  const fit = fitDimsRef.current;
@@ -2810,7 +2867,8 @@ window.__ModuleLoader__.load({
2810
2867
  } catch {
2811
2868
  if (alive) setError(t('syncFailed'));
2812
2869
  } finally {
2813
- if (alive) timer = setTimeout(tick, 700);
2870
+ // 正在落笔就加密轮询,进度条和画布才是「长出来」而不是三跳到底
2871
+ if (alive) timer = setTimeout(tick, paintingRef.current ? 150 : 500);
2814
2872
  }
2815
2873
  };
2816
2874
  tick();
@@ -3279,6 +3337,44 @@ window.__ModuleLoader__.load({
3279
3337
  },
3280
3338
  }),
3281
3339
  ),
3340
+ painting
3341
+ ? h('div', {
3342
+ style: {
3343
+ position: 'absolute',
3344
+ left: 8,
3345
+ top: 8,
3346
+ display: 'flex',
3347
+ alignItems: 'center',
3348
+ gap: 8,
3349
+ padding: '4px 8px',
3350
+ borderRadius: 6,
3351
+ background: 'rgba(0,0,0,0.5)',
3352
+ color: '#f2f2f2',
3353
+ fontSize: 11,
3354
+ pointerEvents: 'none',
3355
+ },
3356
+ },
3357
+ h('span', null, `✎ ${painting.layer || ''}`),
3358
+ h('div', {
3359
+ style: {
3360
+ width: 92,
3361
+ height: 4,
3362
+ borderRadius: 2,
3363
+ background: 'rgba(255,255,255,0.25)',
3364
+ overflow: 'hidden',
3365
+ },
3366
+ }, h('div', {
3367
+ style: {
3368
+ width: `${Math.min(100, Math.round(((painting.done || 0) / Math.max(1, painting.total || 1)) * 100))}%`,
3369
+ height: '100%',
3370
+ background: 'var(--dsw-alias-brand-primary, #4c8bf5)',
3371
+ transition: 'width 120ms linear',
3372
+ },
3373
+ })),
3374
+ h('span', { style: { fontVariantNumeric: 'tabular-nums' } },
3375
+ `${painting.done || 0}/${painting.total || 0}`),
3376
+ )
3377
+ : null,
3282
3378
  h('div', {
3283
3379
  title: t('panHint'),
3284
3380
  style: {
package/index.js CHANGED
@@ -251,7 +251,8 @@ const PROTOCOL = `你可以用 \`paint_canvas\` 在界面里的一块真画布
251
251
  8. 画布本身也能改:\`action=canvas width=… height=… background=#rrggbb\`;\`action=export\` 把当前渲染另存成 PNG。
252
252
 
253
253
  **最省事的复刻就两条命令**(不需要自己估坐标、算配色、找缺口):
254
- - \`action=copy style=anime\`(或 lineart / flat):自动抽轮廓、按区域配主色、建「色块 / 线稿」两层,描线默认走三次贝塞尔拟合(长弧一条曲线走完,比磨圆更像手画),每根线按量出来的原线宽落笔,并顺带跑一次 compare,直接给出覆盖率;要粗细分层加 \`splitLines=true\`;
254
+ - \`action=copy style=anime\`(或 lineart / flat / paint):自动抽轮廓、按区域配主色、建「色块 / 线稿」两层,描线默认走三次贝塞尔拟合(长弧一条曲线走完,比磨圆更像手画),每根线按量出来的原线宽落笔,并顺带跑一次 compare,直接给出覆盖率;要粗细分层加 \`splitLines=true\`;
255
+ \`style=paint\` 是另一条路:不描闭合轮廓,先按大网格把整幅铺一遍色、再只在对比强的地方(脸、手、褶皱、火焰边缘)补细笔,颜色取局部均色、方向沿等色线——厚涂/渐变/火焰这类没有闭合边界的图用这个。默认 8000 笔出结构,\`maxStrokes=12000\` 才接近成图质感;默认不叠线稿(厚涂图没有清晰墨线,硬描会拖出大黑斜线),要叠给 \`lineart=true\`。
255
256
  - \`action=fix target=90 maxRounds=3\`:只看最漏的几块自动补描,到达标或没得补就停,返回每轮数字;落在色块洞里(高光)的缺口会跳过,不会把高光涂掉。
256
257
  - \`action=fill x=… y=…\`:点一片区域就按 palette 填色(边界来自已有笔迹,也能手动给 color),不用一笔笔涂;区域里的洞(高光、瞳孔)会按轮廓嵌套挖掉不涂;
257
258
  - \`action=select rect=[x,y,w,h]\` 或 \`points=[[x,y]…]\`(套索)把落笔限制在选区里,\`clearSelection=true\` 取消;
@@ -1213,6 +1214,8 @@ export function apply(ctx, config = {}) {
1213
1214
  bindError: null,
1214
1215
  // 端点信息:GUI 端口每次重启都可能变,写进 endpoint.json 给脚本用
1215
1216
  endpoint: null,
1217
+ // 正在大批落笔时的进度(/doc 里带出去,侧边面板据此画进度条,不用等全部写完才看见)
1218
+ painting: null,
1216
1219
  // 版本自检:插件自己去 GitHub 看有没有新 Release,界面上给个提示
1217
1220
  update: { checkedAt: null, latest: null, hasUpdate: false, url: null, error: null, enabled: config.updateCheck !== false },
1218
1221
  };
@@ -1224,7 +1227,7 @@ export function apply(ctx, config = {}) {
1224
1227
  const PIXEL_TIMEOUT_MS = Math.max(1500, Number(config.pixelTimeout || 5000));
1225
1228
  // 整幅(1080×1440 这种)做骨架细化+折线拼接是重活,5 秒根本不够:
1226
1229
  // 给这几类单独一档超时,默认 30 秒,可用 heavyTimeout 调。
1227
- const HEAVY_KINDS = new Set(["trace", "copy", "fill", "compare", "palette"]);
1230
+ const HEAVY_KINDS = new Set(["trace", "copy", "posterize", "fill", "compare", "palette"]);
1228
1231
  const HEAVY_TIMEOUT_MS = Math.max(PIXEL_TIMEOUT_MS, Number(config.heavyTimeout || 30000));
1229
1232
  const timeoutFor = (kind) => (HEAVY_KINDS.has(kind) ? HEAVY_TIMEOUT_MS : PIXEL_TIMEOUT_MS);
1230
1233
  const jobs = new Map();
@@ -1233,7 +1236,7 @@ export function apply(ctx, config = {}) {
1233
1236
 
1234
1237
  // 面板在不在:前端每 700ms 轮询一次 /jobs,2.5 秒没动静就当作没有面板 → 宿主机自己算
1235
1238
  const panelLive = () => Date.now() - (state.panelAt || 0) < 2500;
1236
- const HEADLESS_KINDS = new Set(["crop", "ref", "pick", "palette", "trace", "copy", "fill", "compare"]);
1239
+ const HEADLESS_KINDS = new Set(["crop", "ref", "pick", "palette", "trace", "copy", "posterize", "fill", "compare"]);
1237
1240
 
1238
1241
  const runHeadlessPixel = async (kind, params) => {
1239
1242
  try {
@@ -1249,6 +1252,43 @@ export function apply(ctx, config = {}) {
1249
1252
  }
1250
1253
  };
1251
1254
 
1255
+ /** 让出一次事件循环:大批笔迹分块落盘时,前端 700ms 轮询才看得到中间状态。 */
1256
+ const yieldTick = () => new Promise((resolve) => setImmediate(resolve));
1257
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1258
+
1259
+ /**
1260
+ * 分块追加:一次 append 2000 笔会在最后一次性 bump,界面上就是「卡住 → 突然全出来」。
1261
+ * 这里按 120 笔一段写,每段都 bump 一次,并把自己的进度记进 state.painting(/doc 里带出去)。
1262
+ *
1263
+ * 有人开着面板时还要慢放:只 yieldTick 的话 1 万笔在几十毫秒内就全落完,
1264
+ * 700ms 的轮询只能看到最终态,等于没过程。所以按「整批放完约 2 秒」反算每块之间的停顿,
1265
+ * 单块 15~180ms;没人看就全速,不白等。
1266
+ */
1267
+ const appendInChunks = async (strokes, layerRef, chunkSize = 120) => {
1268
+ const total = strokes.length;
1269
+ const chunks = Math.ceil(total / chunkSize);
1270
+ const showProgress = total > chunkSize;
1271
+ const pause = showProgress && panelLive()
1272
+ ? Math.max(15, Math.min(180, Math.round(2000 / chunks)))
1273
+ : 0;
1274
+ let layer = null;
1275
+ let done = 0;
1276
+ for (let i = 0; i < total; i += chunkSize) {
1277
+ const part = strokes.slice(i, i + chunkSize);
1278
+ layer = docs.append(part, layer ? layer.id : layerRef);
1279
+ done += part.length;
1280
+ state.painting = showProgress
1281
+ ? { action: "append", done, total, layer: layer.name, at: Date.now() }
1282
+ : null;
1283
+ if (showProgress) {
1284
+ if (pause > 0) await sleep(pause);
1285
+ else await yieldTick();
1286
+ }
1287
+ }
1288
+ state.painting = null;
1289
+ return layer;
1290
+ };
1291
+
1252
1292
  const runPixelJob = (kind, params = {}, timeoutMs) => new Promise((resolve) => {
1253
1293
  if (config.headless !== false && HEADLESS_KINDS.has(kind) && !panelLive()) {
1254
1294
  // 没有面板 → 直接宿主侧算,不再干等 5 秒超时
@@ -1722,6 +1762,7 @@ export function apply(ctx, config = {}) {
1722
1762
  revision: docs.revision,
1723
1763
  doc: { ...docs.doc, revision: docs.revision },
1724
1764
  update: state.update,
1765
+ painting: state.painting,
1725
1766
  version: localVersion,
1726
1767
  pixelJobs: jobs.size,
1727
1768
  });
@@ -2035,15 +2076,17 @@ export function apply(ctx, config = {}) {
2035
2076
  "view 取最新渲染结果(rect 裁切、zoom 放大、layer 只看单层,并给每层的包围盒与覆盖率);" +
2036
2077
  "ref 把参考图(或它的一块裁切)导出成 PNG,用 read_image 直接看;pick 读某点的颜色/透明度;" +
2037
2078
  "compare 出「当前画面 vs 参考图」的差分图和数值;palette 提参考图主色;" +
2079
+ "copy 按阈值描线复刻(线稿/平涂/两者);posterize 把彩图按色阶分区复刻成可编辑色块(可顺带描边界线稿),彩稿用这个而不是 copy;" +
2038
2080
  "snapshot / restore 整幅存档与回退;undo / redo 撤销重做;clear 清空(给 layer 只清那层);" +
2039
2081
  "layer 增删改图层(name/visible/layerOpacity/blend/locked);" +
2040
- "import 把本机图片导入成最底下的图片层(path 或 dataUrl);canvas 改画布尺寸和背景;export 把当前渲染另存成 PNG。",
2082
+ "import 把本机图片导入成最底下的图片层(path 或 dataUrl);canvas 改画布尺寸和背景;" +
2083
+ "export 把当前渲染另存成 PNG(面板没开时宿主自己光栅化,不依赖前端回传)。",
2041
2084
  parameters: {
2042
2085
  type: "object",
2043
2086
  properties: {
2044
2087
  action: {
2045
2088
  type: "string",
2046
- enum: ["doc", "copy", "fix", "fill", "draw", "view", "ref", "trace", "pick", "compare", "palette", "select", "snapshot", "restore", "undo", "redo", "clear", "layer", "import", "canvas", "export", "new"],
2089
+ enum: ["doc", "copy", "posterize", "fix", "fill", "draw", "view", "ref", "trace", "pick", "compare", "palette", "select", "snapshot", "restore", "undo", "redo", "clear", "layer", "import", "canvas", "export", "new"],
2047
2090
  description: "要执行的动作。new 是另起一幅(可先保存当前、也可用图片建画布)。",
2048
2091
  },
2049
2092
  points: {
@@ -2074,6 +2117,11 @@ export function apply(ctx, config = {}) {
2074
2117
  + "特效 halftone 漫画网点 / glow 光效 / sparkle 粒子。默认 round。",
2075
2118
  },
2076
2119
  taper: { type: "boolean", description: "draw: 起收笔渐细(手绘感),默认 false。" },
2120
+ widths: {
2121
+ type: "boolean",
2122
+ description: "trace: 回一份 pathsWidth(每个点带第 3 个压力值),配合 size=sizeHint、minSize=0 让笔迹按原图局部线宽变粗变细。",
2123
+ },
2124
+ sizeHint: { type: "number", description: "trace widths=true 时返回的建议笔刷 size(≈ 原图 p90 线宽)。" },
2077
2125
  minSize: {
2078
2126
  type: "number",
2079
2127
  description: "draw: 最小笔宽占 size 的比例 0..1,默认 0.3;压力最轻时也不会细成一条线。",
@@ -2107,11 +2155,6 @@ export function apply(ctx, config = {}) {
2107
2155
  description: "import: 本机图片的绝对路径(PNG/JPEG/WebP/GIF)。",
2108
2156
  },
2109
2157
  dataUrl: { type: "string", description: "import: 图片 dataURL,和 path 二选一。" },
2110
- fit: {
2111
- type: "string",
2112
- enum: ["contain", "cover", "stretch"],
2113
- description: "import: 落位方式,默认 contain(整张居中放进画布)。",
2114
- },
2115
2158
  width: { type: "number", description: "canvas: 新宽度 16~4096。" },
2116
2159
  height: { type: "number", description: "canvas: 新高度 16~4096。" },
2117
2160
  background: { type: "string", description: "canvas: 背景色 #rrggbb。" },
@@ -2156,7 +2199,21 @@ export function apply(ctx, config = {}) {
2156
2199
  description: "trace: 折线简化容差(像素),默认 2.5。大一点更概括,小一点更贴边。",
2157
2200
  },
2158
2201
  minLength: { type: "number", description: "trace: 丢掉的短线段长度下限(像素),默认 12(copy 默认 16),用来滤掉噪点。" },
2159
- maxLines: { type: "number", description: "trace: 最多返回几条折线,默认 80。" },
2202
+ maxLines: { type: "number", description: "trace / posterize: 最多返回几条折线,trace 默认 80,posterize 描边界时默认 1600。" },
2203
+ minArea: {
2204
+ type: "number",
2205
+ description: "posterize: 小于多少像素的色块丢掉,默认画布面积/4000(1080×1440 约 389)。小一点细节多但笔迹暴增。",
2206
+ },
2207
+ maxFills: { type: "number", description: "posterize: 最多铺几块色,默认 3000。" },
2208
+ lines: {
2209
+ type: "boolean",
2210
+ description: "posterize: 顺手把色块之间的边界描成线稿层(默认 false,只要色块)。",
2211
+ },
2212
+ placement: {
2213
+ type: "string",
2214
+ enum: ["contain", "cover", "stretch"],
2215
+ description: "import: 落位方式,默认 contain(整张居中放进画布)。",
2216
+ },
2160
2217
  smooth: {
2161
2218
  type: "number",
2162
2219
  description: "trace / copy: 描线后磨圆几遍 0~3,默认 trace 1、copy 2。觉得线还是抖就给 3;要贴原图硬边就给 0。",
@@ -2168,10 +2225,15 @@ export function apply(ctx, config = {}) {
2168
2225
  fitStep: { type: "number", description: "trace / copy: 拟合后采样间距(像素),默认 3。小一点更贴原线,点也更多。" },
2169
2226
  style: {
2170
2227
  type: "string",
2171
- enum: ["lineart", "flat", "anime"],
2172
- description: "copy: 复刻风格。lineart 只出线稿;flat 只出区域色块;anime 出线稿+色块(默认)。",
2228
+ enum: ["lineart", "flat", "anime", "paint"],
2229
+ description: "copy: 复刻风格。lineart 只出线稿;flat 只出区域色块;anime 出线稿+色块(默认);paint 笔触复刻——按网格铺彩色短线(颜色取局部均色、方向沿等色线、透明度随对比度),适合厚涂/渐变/火焰这种没有闭合边界的图,再叠一层线稿。",
2173
2230
  },
2174
- colors: { type: "number", description: "copy / palette: 主色档数 2~8,默认 6。" },
2231
+ paintStep: { type: "number", description: "copy style=paint: 细节网格边长(像素),默认按画布面积与 maxStrokes 自动算(一般 8~24)。越小越细,笔数也越多。" },
2232
+ maxStrokes: { type: "number", description: "copy style=paint: 笔触总额,默认 8000(上限 20000)。6000 快、看结构;12000 才接近成图质感,代价是面板重绘更慢。" },
2233
+ paintPasses: { type: "number", description: "copy style=paint: 2=先粗铺整幅再补细节(默认),1=只粗铺(快,适合先看大关系)。" },
2234
+ paintMinLum: { type: "number", description: "copy style=paint: 比这个亮度更白的格子当背景跳过,默认 240。" },
2235
+ lineart: { type: "boolean", description: "copy style=paint: 是否再叠一层线稿,默认 true;只要笔触就 false。" },
2236
+ colors: { type: "number", description: "copy / posterize / palette: 主色档数 2~12(copy 默认 6,posterize 默认 8)。彩稿要火、金、肤这些颜色都出来,给 10~12。" },
2175
2237
  minFill: { type: "number", description: "copy: 小于多少像素的闭合区域不填色,默认 320。" },
2176
2238
  target: { type: "number", description: "fix: 目标覆盖率百分比,默认 90。到了就停。" },
2177
2239
  maxRounds: { type: "number", description: "fix: 最多迭代几轮,默认 3(上限 5)。" },
@@ -2189,7 +2251,7 @@ export function apply(ctx, config = {}) {
2189
2251
  type: "boolean",
2190
2252
  description: "select: 清掉选区,恢复整幅可画。",
2191
2253
  },
2192
- k: { type: "number", description: "palette: 要几档主色,默认 6(上限 8)。" },
2254
+ k: { type: "number", description: "palette: 要几档主色,默认 6(上限 12)。" },
2193
2255
  snapshotId: { type: "string", description: "restore: 回退到哪一版快照(snapshot 返回的 id);不给回最近一版。" },
2194
2256
  label: { type: "string", description: "snapshot: 这版备注,比如「上色前」。" },
2195
2257
  locked: { type: "boolean", description: "layer.set:锁定这层(参考图锁住,模型就盖不上去,也不会被误擦)。" },
@@ -2297,7 +2359,7 @@ export function apply(ctx, config = {}) {
2297
2359
  // 镜像:一笔画两边(对称复刻人像/建筑)
2298
2360
  const axis = args.mirror === "x" || args.mirror === "y" ? args.mirror : null;
2299
2361
  const strokes = axis ? list.concat(list.map((s) => ({ ...s, points: mirrorPoints(s.points, axis, W, H) }))) : list;
2300
- const layer = docs.append(strokes, args.layer);
2362
+ const layer = await appendInChunks(strokes, args.layer);
2301
2363
  return {
2302
2364
  ok: true,
2303
2365
  revision: docs.revision,
@@ -2370,7 +2432,7 @@ export function apply(ctx, config = {}) {
2370
2432
  const result = docs.importImage({
2371
2433
  buffer,
2372
2434
  name: args.name || fallbackName,
2373
- fit: args.fit,
2435
+ fit: args.placement || (typeof args.fit === "string" ? args.fit : undefined),
2374
2436
  opacity: args.layerOpacity,
2375
2437
  });
2376
2438
  return {
@@ -2394,20 +2456,46 @@ export function apply(ctx, config = {}) {
2394
2456
  };
2395
2457
  }
2396
2458
  case "export": {
2397
- const source = args.transparent ? docs.previewAlpha : docs.preview;
2398
- if (!existsSync(source)) {
2399
- throw new Error(args.transparent
2400
- ? "还没有透明底渲染:先在界面里打开画界,等前端回传一帧"
2401
- : "还没有渲染结果:先在界面里打开画界画一笔,前端会把渲染回传");
2402
- }
2403
2459
  const now = new Date();
2404
2460
  const pad = (n) => String(n).padStart(2, "0");
2405
2461
  const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
2406
2462
  const saveDir = paths.saveDir();
2407
2463
  mkdirSync(saveDir, { recursive: true });
2408
- const target = path.join(saveDir, `画界-${stamp}${args.transparent ? "-alpha" : ""}.png`);
2409
- copyFileSync(source, target);
2410
- return { ok: true, path: target, saveDir, transparent: Boolean(args.transparent) };
2464
+ const target = args.path
2465
+ ? path.resolve(String(args.path))
2466
+ : path.join(saveDir, `画界-${stamp}${args.transparent ? "-alpha" : ""}.png`);
2467
+ const source = args.transparent ? docs.previewAlpha : docs.preview;
2468
+ if (existsSync(source) && !args.path) {
2469
+ copyFileSync(source, target);
2470
+ return { ok: true, path: target, saveDir, transparent: Boolean(args.transparent), rendered: "panel" };
2471
+ }
2472
+ // 面板没开、没有前端帧:宿主自己光栅化(0.1.40 起),不开界面也能导出/验收
2473
+ try {
2474
+ const mod = await import("./pixels.js");
2475
+ const docSurf = await mod.rasterDoc(docs.doc, { resolve: (f) => path.resolve(dir, f) });
2476
+ let out = docSurf;
2477
+ if (!args.transparent) {
2478
+ const hex = String(docs.doc.background || "#ffffff").replace("#", "");
2479
+ const rgb = [0, 1, 2].map((k) => {
2480
+ const v = parseInt(hex.slice(k * 2, k * 2 + 2), 16);
2481
+ return Number.isFinite(v) ? v : 255;
2482
+ });
2483
+ const bg = mod.makeSurface(docSurf.w, docSurf.h);
2484
+ for (let i = 0; i < bg.data.length; i += 4) {
2485
+ bg.data[i] = rgb[0];
2486
+ bg.data[i + 1] = rgb[1];
2487
+ bg.data[i + 2] = rgb[2];
2488
+ bg.data[i + 3] = 255;
2489
+ }
2490
+ mod.blitImage(bg, { data: docSurf.data, width: docSurf.w, height: docSurf.h }, 0, 0, docSurf.w, docSurf.h);
2491
+ out = bg;
2492
+ }
2493
+ mkdirSync(path.dirname(target), { recursive: true });
2494
+ writeFileSync(target, mod.encodePng(out.data, out.w, out.h));
2495
+ return { ok: true, path: target, saveDir, transparent: Boolean(args.transparent), rendered: "host" };
2496
+ } catch (err) {
2497
+ throw new Error(`没有前端渲染帧,宿主侧光栅化也没成:${(err && err.message) || err}`);
2498
+ }
2411
2499
  }
2412
2500
  case "undo":
2413
2501
  docs.undo(Math.max(1, Math.round(Number(args.count) || 1)));
@@ -2572,7 +2660,7 @@ export function apply(ctx, config = {}) {
2572
2660
  throw new Error("select 需要 rect=[x,y,w,h]、points=[[x,y]…](套索),或 clearSelection=true 清掉");
2573
2661
  }
2574
2662
  case "copy": {
2575
- const style = args.style === "lineart" || args.style === "flat" ? args.style : "anime";
2663
+ const style = args.style === "lineart" || args.style === "flat" || args.style === "paint" ? args.style : "anime";
2576
2664
  const rect = parseRect(args.rect, docs.doc.width, docs.doc.height);
2577
2665
  const job = await runPixelJob("copy", {
2578
2666
  rect,
@@ -2588,6 +2676,10 @@ export function apply(ctx, config = {}) {
2588
2676
  fit: args.fit === undefined ? true : args.fit === true,
2589
2677
  fitStep: args.fitStep,
2590
2678
  mode: args.mode,
2679
+ paintStep: args.paintStep,
2680
+ maxStrokes: args.maxStrokes,
2681
+ paintPasses: args.paintPasses,
2682
+ paintMinLum: args.paintMinLum,
2591
2683
  }, PIXEL_TIMEOUT_MS * 3);
2592
2684
  if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
2593
2685
  const created = [];
@@ -2598,16 +2690,32 @@ export function apply(ctx, config = {}) {
2598
2690
  if (found && !found.locked && !found.image && (found.strokes || []).length === 0) return found;
2599
2691
  return docs.addLayer(want || undefined);
2600
2692
  };
2601
- // 先铺色块(在线稿下面),再描线,顺序就是画师的习惯
2693
+ // 先铺底色(笔触 / 色块都在线稿下面),再描线,顺序就是画师的习惯
2694
+ if (style === "paint" && Array.isArray(job.paint) && job.paint.length > 0) {
2695
+ const layer = pickLayer(args.fillLayer || "笔触");
2696
+ await appendInChunks(
2697
+ job.paint.map((p) => ({
2698
+ mode: "brush",
2699
+ color: p.color,
2700
+ size: p.size,
2701
+ opacity: p.opacity,
2702
+ brush: BRUSH_IDS.includes(args.paintBrush) ? args.paintBrush : "round",
2703
+ points: p.points,
2704
+ })),
2705
+ layer.id,
2706
+ );
2707
+ created.push({ name: layer.name, kind: "paint", items: job.paint.length });
2708
+ }
2602
2709
  if (style !== "lineart" && job.fills.length > 0) {
2603
2710
  const layer = pickLayer(args.fillLayer || "色块");
2604
- docs.append(
2711
+ await appendInChunks(
2605
2712
  job.fills.map((f) => ({ mode: "fill", color: f.color, size: 1, opacity: 1, points: f.points, holes: f.holes })),
2606
2713
  layer.id,
2607
2714
  );
2608
2715
  created.push({ name: layer.name, kind: "fill", items: job.fills.length });
2609
2716
  }
2610
- if (style !== "flat" && job.paths.length > 0) {
2717
+ // 厚涂图没有清晰墨线,默认不描线(强行描会拖出大黑斜线);要就显式 lineart=true
2718
+ if (style !== "flat" && (style !== "paint" || args.lineart === true) && job.paths.length > 0) {
2611
2719
  const palette = job.palette || [];
2612
2720
  const darkest = palette.length
2613
2721
  ? palette.reduce((a, b) => (lumOf(a) <= lumOf(b) ? a : b))
@@ -2630,19 +2738,19 @@ export function apply(ctx, config = {}) {
2630
2738
  const thick = pairs.filter((p) => p.size >= avg * 0.8);
2631
2739
  if (thin.length === 0 || thick.length === 0) {
2632
2740
  const layer = pickLayer(args.layer || "线稿");
2633
- docs.append(pairs.map(strokeOf), layer.id);
2741
+ await appendInChunks(pairs.map(strokeOf), layer.id);
2634
2742
  created.push({ name: layer.name, kind: "line", items: pairs.length });
2635
2743
  } else {
2636
2744
  const lineLayer = pickLayer(args.layer || "线稿");
2637
- docs.append(thin.map(strokeOf), lineLayer.id);
2745
+ await appendInChunks(thin.map(strokeOf), lineLayer.id);
2638
2746
  created.push({ name: lineLayer.name, kind: "line", items: thin.length });
2639
2747
  const heavyLayer = pickLayer("粗线");
2640
- docs.append(thick.map(strokeOf), heavyLayer.id);
2748
+ await appendInChunks(thick.map(strokeOf), heavyLayer.id);
2641
2749
  created.push({ name: heavyLayer.name, kind: "line", items: thick.length });
2642
2750
  }
2643
2751
  } else {
2644
2752
  const layer = pickLayer(args.layer || "线稿");
2645
- docs.append(pairs.map(strokeOf), layer.id);
2753
+ await appendInChunks(pairs.map(strokeOf), layer.id);
2646
2754
  created.push({ name: layer.name, kind: "line", items: pairs.length });
2647
2755
  }
2648
2756
  }
@@ -2663,6 +2771,8 @@ export function apply(ctx, config = {}) {
2663
2771
  palette: job.palette,
2664
2772
  lines: job.lines,
2665
2773
  fills: job.fills.length,
2774
+ paint: Array.isArray(job.paint) ? job.paint.length : 0,
2775
+ paintStats: job.paintStats || null,
2666
2776
  points: job.points,
2667
2777
  metrics: cmp.ok ? cmp.metrics : null,
2668
2778
  hint: `已按 ${style} 复刻:${created.map((c) => `${c.name}(${c.items})`).join(" + ") || "没有可画的内容"}。`
@@ -2670,6 +2780,62 @@ export function apply(ctx, config = {}) {
2670
2780
  + "想补差距就 action=fix。",
2671
2781
  };
2672
2782
  }
2783
+ case "posterize": {
2784
+ // 彩图复刻成图:按色阶分区,每块是一个可编辑填色(不是黑线),
2785
+ // 需要线稿再 lines=true 描色块边界。
2786
+ const rect = parseRect(args.rect, docs.doc.width, docs.doc.height);
2787
+ const job = await runPixelJob("posterize", {
2788
+ rect,
2789
+ layer: args.refLayer === undefined ? null : args.refLayer,
2790
+ colors: args.colors,
2791
+ minArea: args.minArea,
2792
+ tolerance: args.tolerance,
2793
+ maxFills: args.maxFills,
2794
+ lines: args.lines === true,
2795
+ minLength: args.minLength,
2796
+ maxLines: args.maxLines,
2797
+ }, PIXEL_TIMEOUT_MS * 3);
2798
+ if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
2799
+ const created = [];
2800
+ const pickLayer = (name) => {
2801
+ const want = String(name || "").trim();
2802
+ const found = want ? docs.layer(want) : null;
2803
+ if (found && !found.locked && !found.image && (found.strokes || []).length === 0) return found;
2804
+ return docs.addLayer(want || undefined);
2805
+ };
2806
+ if (Array.isArray(job.fills) && job.fills.length > 0) {
2807
+ const layer = pickLayer(args.fillLayer || "色块");
2808
+ docs.append(
2809
+ job.fills.map((f) => ({ mode: "fill", color: f.color, size: 1, opacity: 1, points: f.points, holes: f.holes || [] })),
2810
+ layer.id,
2811
+ );
2812
+ created.push({ name: layer.name, kind: "fill", items: job.fills.length });
2813
+ }
2814
+ if (Array.isArray(job.paths) && job.paths.length > 0) {
2815
+ const layer = pickLayer(args.layer || "线稿");
2816
+ const color = args.color || "#111111";
2817
+ const brush = BRUSH_IDS.includes(args.brush) ? args.brush : "liner";
2818
+ const base = Math.max(1, Number(args.size) || 2);
2819
+ docs.append(
2820
+ job.paths.filter((p) => p && p.length >= 2).map((points) => ({ color, size: base, brush, opacity: 1, points })),
2821
+ layer.id,
2822
+ );
2823
+ created.push({ name: layer.name, kind: "line", items: job.paths.length });
2824
+ }
2825
+ const cmp = await runPixelJob("compare", { rect }, PIXEL_TIMEOUT_MS * 2);
2826
+ return {
2827
+ ok: true,
2828
+ revision: docs.revision,
2829
+ rect,
2830
+ created,
2831
+ palette: job.stats && job.stats.palette,
2832
+ stats: job.stats,
2833
+ metrics: cmp.ok ? cmp.metrics : null,
2834
+ hint: `已按 ${job.stats ? job.stats.colorCount : "?"} 色阶分区复刻:${created.map((c) => `${c.name}(${c.items})`).join(" + ") || "没有可画的内容"}。`
2835
+ + (cmp.ok ? `覆盖率 ${cmp.metrics.coveragePct}%,多画 ${cmp.metrics.extraPct}%,色差 ${cmp.metrics.meanColorDiff}。` : "")
2836
+ + "要更像原图就调 colors(色阶数)/ minArea(细节门槛),或者 lines=true 补边界线稿。",
2837
+ };
2838
+ }
2673
2839
  case "fix": {
2674
2840
  const rect = parseRect(args.rect, docs.doc.width, docs.doc.height);
2675
2841
  const maxRounds = Math.max(1, Math.min(5, Math.round(Number(args.maxRounds) || 3)));
@@ -2746,6 +2912,7 @@ export function apply(ctx, config = {}) {
2746
2912
  smooth: args.smooth,
2747
2913
  fit: args.fit === true,
2748
2914
  fitStep: args.fitStep,
2915
+ widths: args.widths === true,
2749
2916
  mode: args.mode === "center" ? "center" : "edge",
2750
2917
  });
2751
2918
  if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
@@ -2762,7 +2929,11 @@ export function apply(ctx, config = {}) {
2762
2929
  fit: job.fit === undefined ? null : job.fit,
2763
2930
  paths: job.paths,
2764
2931
  stats: job.stats,
2932
+ ...(job.pathsWidth ? { pathsWidth: job.pathsWidth, sizeHint: job.sizeHint } : {}),
2765
2933
  hint: "paths 是从参考图抽出的轮廓折线(画布坐标),每段直接当 draw 的 points 用;长图可分批 batches=[…]。"
2934
+ + (job.pathsWidth
2935
+ ? ` width=true 时用 pathsWidth(点带第 3 个压力值,sizeHint=${job.sizeHint}):draw 时 size=sizeHint、minSize=0,笔迹就会按原图局部线宽自己变粗变细。`
2936
+ : " 想要粗细跟着原图走,加 widths=true,会多回一份带逐点压力的 pathsWidth。")
2766
2937
  + "stats 给的是 inkRatio/widthAvg/widthMin/widthMax/droppedPct,调 threshold/tolerance/fitStep 时看这几个数,不用只靠肉眼。"
2767
2938
  + "描完用 view rect+zoom 对照,再用 compare 看 coveragePct。",
2768
2939
  };
@@ -2905,3 +3076,4 @@ export function apply(ctx, config = {}) {
2905
3076
  }
2906
3077
  };
2907
3078
  }
3079
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xenra/dsh-draworld",
3
- "version": "0.1.39",
3
+ "version": "0.1.41",
4
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
5
  "type": "module",
6
6
  "license": "MIT",
package/pixelops.js CHANGED
@@ -6,11 +6,125 @@ import path from "node:path";
6
6
  import {
7
7
  loadImage, inkMask, blurMask, marchingSquares, stitchSegments, rdp, traceInk,
8
8
  kmeansColors, polygonArea, pointInPolygon, pathWidths, rasterDoc, cropSurface, zoomSurface,
9
- encodePng, makeSurface, toHex,
9
+ encodePng, makeSurface, toHex, inkDistance, pathPointWidths, posterizeFills,
10
10
  } from "./pixels.js";
11
11
 
12
12
  const dataUrlOf = (surf) => `data:image/png;base64,${encodePng(surf.data, surf.w, surf.h).toString("base64")}`;
13
13
 
14
+ /** 某点的亮度(0~255),越界就夹回边缘。 */
15
+ function lumAt(data, w, h, x, y) {
16
+ const xi = Math.max(0, Math.min(w - 1, Math.round(x)));
17
+ const yi = Math.max(0, Math.min(h - 1, Math.round(y)));
18
+ const i = (yi * w + xi) * 4;
19
+ return 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
20
+ }
21
+
22
+ /**
23
+ * 笔触复刻(style=paint):把参考图按网格取样,每格出 1~2 笔
24
+ * 「沿等色线方向」的短线,颜色取该格均色、笔宽取格宽、不透明度随局部对比度走。
25
+ *
26
+ * 跟 copy 的 edge/中心线不同,这不是"描轮廓",而是像画师铺色:先大片铺,再靠笔触的边缘留给线稿层去压。
27
+ * 好处是不依赖闭合区域(厚涂、渐变、火焰这类没有明确边界的也能出效果),缺点是笔数多、只近似。
28
+ */
29
+ function paintStrokesFromBitmap(cut, rect, palette, opts = {}) {
30
+ const w = cut.w;
31
+ const h = cut.h;
32
+ const d = cut.data;
33
+ const maxStrokes = Math.max(100, Math.min(20000, Number(opts.maxStrokes) || 8000));
34
+ // 网格边长跟笔数上限挂钩:粗铺吃掉约 45% 预算,剩的留给细节
35
+ const coarseAuto = Math.sqrt((w * h) / Math.max(200, maxStrokes * 0.45));
36
+ const step = Math.max(4, Math.min(48, Math.round(Number(opts.step) || coarseAuto / 2)));
37
+ const minLum = opts.minLum === undefined ? 240 : Number(opts.minLum);
38
+ const passes = Number(opts.passes) === 1 ? 1 : 2;
39
+ const strokes = [];
40
+ let cells = 0;
41
+ let skippedBg = 0;
42
+ let seed = 20261128;
43
+ const rnd = () => {
44
+ seed = (seed * 1103515245 + 12345) % 2147483648;
45
+ return seed / 2147483648;
46
+ };
47
+ const hex2 = (v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, "0");
48
+ // 取样一格:均色 + 平均亮度 + 局部对比度(mag)
49
+ const sample = (cx, cy, size) => {
50
+ let r = 0, g = 0, b = 0, n = 0, lumSum = 0;
51
+ const half = Math.max(1, Math.round(size / 2));
52
+ const wob = Math.max(2, Math.round(size / 8));
53
+ for (let y = Math.round(cy) - half; y < Math.round(cy) + half; y += wob) {
54
+ for (let x = Math.round(cx) - half; x < Math.round(cx) + half; x += wob) {
55
+ if (x < 0 || y < 0 || x >= w || y >= h) continue;
56
+ const i = (y * w + x) * 4;
57
+ if (d[i + 3] < 16) continue;
58
+ r += d[i]; g += d[i + 1]; b += d[i + 2];
59
+ n += 1;
60
+ lumSum += lumAt(d, w, h, x, y);
61
+ }
62
+ }
63
+ if (n === 0) return null;
64
+ const gx = lumAt(d, w, h, cx + size, cy) - lumAt(d, w, h, cx - size, cy);
65
+ const gy = lumAt(d, w, h, cx, cy + size) - lumAt(d, w, h, cx, cy - size);
66
+ return {
67
+ color: `#${hex2(r / n)}${hex2(g / n)}${hex2(b / n)}`,
68
+ lum: lumSum / n,
69
+ mag: Math.min(1, Math.hypot(gx, gy) / 90),
70
+ ang: Math.atan2(gy, gx) + Math.PI / 2,
71
+ };
72
+ };
73
+ // 落一笔:长度/抖动跟格子走,宽高都盖住格子的对角线,否则会透白底、整片发灰
74
+ const push = (cx, cy, size, s, wide, alpha) => {
75
+ const len = size * (1.15 + 0.5 * rnd());
76
+ const jx = (rnd() - 0.5) * size * 0.4;
77
+ const jy = (rnd() - 0.5) * size * 0.4;
78
+ const pts = [];
79
+ for (let t = -1; t <= 1; t += 1) {
80
+ pts.push([
81
+ Math.round(rect.x + cx + jx + Math.cos(s.ang) * (len / 2) * t),
82
+ Math.round(rect.y + cy + jy + Math.sin(s.ang) * (len / 2) * t),
83
+ ]);
84
+ }
85
+ strokes.push({
86
+ color: s.color,
87
+ size: Number((size * (wide + 0.25 * s.mag)).toFixed(2)),
88
+ opacity: Number((alpha + 0.1 * s.mag).toFixed(2)),
89
+ points: pts,
90
+ });
91
+ };
92
+
93
+ // 第一遍:粗铺。网格放大一倍,保证先整幅有颜色,不做成一半空白一半细节
94
+ const coarse = Math.min(48, Math.max(6, Math.round(step * 2)));
95
+ for (let cy = coarse / 2; cy < h; cy += coarse) {
96
+ for (let cx = coarse / 2; cx < w; cx += coarse) {
97
+ if (strokes.length >= maxStrokes) break;
98
+ const s = sample(cx, cy, coarse);
99
+ if (!s) continue;
100
+ if (s.lum >= minLum) { skippedBg += 1; continue; }
101
+ cells += 1;
102
+ push(cx, cy, coarse, s, 1.05, 0.9);
103
+ }
104
+ if (strokes.length >= maxStrokes) break;
105
+ }
106
+ // 第二遍:细节。只补局部对比强的地方(脸、手、火焰边缘、褶皱),平涂区不再叠
107
+ const wantDetail = Number(opts.passes) !== 1;
108
+ if (wantDetail) {
109
+ for (let cy = step / 2; cy < h; cy += step) {
110
+ for (let cx = step / 2; cx < w; cx += step) {
111
+ if (strokes.length >= maxStrokes) break;
112
+ const s = sample(cx, cy, step);
113
+ if (!s) continue;
114
+ if (s.lum >= minLum) continue;
115
+ if (s.mag < 0.16) continue;
116
+ cells += 1;
117
+ push(cx, cy, step, s, 1.15, 0.88);
118
+ }
119
+ if (strokes.length >= maxStrokes) break;
120
+ }
121
+ }
122
+ return {
123
+ strokes,
124
+ stats: { step, passes: wantDetail ? 2 : 1, coarse, cells, skippedBg, strokes: strokes.length, capped: strokes.length >= maxStrokes },
125
+ };
126
+ }
127
+
14
128
  function refLayer(doc, wanted) {
15
129
  const layers = (doc.layers || []).filter((l) => l.image);
16
130
  if (wanted) return layers.find((l) => l.id === wanted || l.name === wanted) || null;
@@ -121,9 +235,31 @@ export async function runHeadless(kind, params, doc, resolve) {
121
235
  pointsPerLine: t.lines ? Number((t.points / t.lines).toFixed(1)) : null,
122
236
  droppedPct: t.lines + t.dropped > 0 ? Number((t.dropped / (t.lines + t.dropped) * 100).toFixed(1)) : null,
123
237
  };
238
+
239
+ // widths=true:折线带上逐点压力(第 3 个数),让笔迹自己长成原图的粗细,
240
+ // 而不是一条从头到尾同宽的「硬线」。pressure = 局部线宽 / p90 线宽,配合 size=sizeHint、minSize=0 用。
241
+ let pathsWidth = null;
242
+ let sizeHint = null;
243
+ if (params.widths) {
244
+ const dist = inkDistance(mask, cut.w, cut.h);
245
+ const perPath = t.paths.map((line) => pathPointWidths(mask, cut.w, cut.h, line, dist));
246
+ const all = perPath.reduce((acc, arr) => acc.concat(arr), []);
247
+ all.sort((a, b) => a - b);
248
+ const p90 = all.length ? all[Math.floor(all.length * 0.9)] : 1;
249
+ sizeHint = Math.max(2, Math.round(p90));
250
+ pathsWidth = t.paths.map((line, li) => line.map((p, k) => [
251
+ Math.round(rect.x + p[0]),
252
+ Math.round(rect.y + p[1]),
253
+ Number(Math.min(1, Math.max(0.05, perPath[li][k] / sizeHint)).toFixed(3)),
254
+ ]));
255
+ stats.sizeHint = sizeHint;
256
+ stats.widthP90 = Number(p90.toFixed(2));
257
+ }
258
+
124
259
  return {
125
260
  ok: true, rect, paths, lines: t.lines, points: t.points, dropped: t.dropped,
126
261
  tolerance: t.tolerance, smooth: t.smooth, fit: t.fit, mode: t.mode, headless: true, stats,
262
+ ...(pathsWidth ? { pathsWidth, sizeHint } : {}),
127
263
  };
128
264
  }
129
265
  if (kind === "copy") {
@@ -151,6 +287,7 @@ export async function runHeadless(kind, params, doc, resolve) {
151
287
  const widths = pathWidths(inkMask(cut.data, cut.w, cut.h, params.threshold), cut.w, cut.h, t.paths);
152
288
  const lineWidth = widths.length ? Number((widths.reduce((a, b) => a + b, 0) / widths.length).toFixed(2)) : null;
153
289
  const wantFill = params.style === "flat" || params.style === "anime";
290
+ const wantPaint = params.style === "paint";
154
291
  // 色块必须靠闭合轮廓;中心线模式下的路径是骨架,不闭合,所以填色另跑一遍边界追踪
155
292
  let edgeTrace = t;
156
293
  if (wantFill && mode === "center") {
@@ -168,11 +305,38 @@ export async function runHeadless(kind, params, doc, resolve) {
168
305
  const fills = wantFill
169
306
  ? regionFillsFromBitmap(cut, edgeTrace, palette, { minFill: params.minFill, maxFills: params.maxFills || 40, rect })
170
307
  : [];
308
+ const paint = wantPaint
309
+ ? paintStrokesFromBitmap(cut, rect, palette, {
310
+ step: params.paintStep,
311
+ maxStrokes: params.maxStrokes,
312
+ minLum: params.paintMinLum,
313
+ passes: params.paintPasses,
314
+ })
315
+ : null;
171
316
  return {
172
317
  ok: true, rect, paths, widths, lineWidth, closed: t.closed, fills, palette, mode,
173
318
  smooth: t.smooth, fit: t.fit, inkRatio, lines: t.lines, points: t.points, dropped: t.dropped, headless: true,
319
+ ...(paint ? { paint: paint.strokes, paintStats: paint.stats } : {}),
174
320
  };
175
321
  }
322
+ if (kind === "posterize") {
323
+ const surf = await refSurface(doc, resolve, params);
324
+ const rect = clampRect(params.rect, surf.w, surf.h);
325
+ const cut = cropSurface(surf, rect);
326
+ const res = posterizeFills(cut.data, cut.w, cut.h, {
327
+ colors: params.colors,
328
+ minArea: params.minArea,
329
+ tolerance: params.tolerance,
330
+ maxFills: params.maxFills,
331
+ lines: params.lines === true,
332
+ minLength: params.minLength,
333
+ maxLines: params.maxLines,
334
+ });
335
+ const shift = (pts) => pts.map((p) => [Math.round(rect.x + p[0]), Math.round(rect.y + p[1])]);
336
+ const fills = res.fills.map((f) => ({ color: f.color, points: shift(f.points), holes: (f.holes || []).map(shift), area: f.area }));
337
+ const paths = res.paths.map(shift);
338
+ return { ok: true, rect, fills, paths, stats: res.stats, headless: true };
339
+ }
176
340
  if (kind === "fill") {
177
341
  const sx = Math.round(Number(params.x));
178
342
  const sy = Math.round(Number(params.y));
package/pixels.js CHANGED
@@ -647,6 +647,57 @@ export function pathWidths(mask, w, h, paths) {
647
647
  });
648
648
  }
649
649
 
650
+ /** 墨迹到背景的 chamfer 距离(两遍扫描,8 邻域 1 / 1.414)。返回值 ×2 就是局部线宽。 */
651
+ export function inkDistance(mask, w, h) {
652
+ const INF = 1e9;
653
+ const d = new Float32Array(w * h);
654
+ for (let i = 0; i < d.length; i += 1) d[i] = mask[i] ? INF : 0;
655
+ for (let y = 0; y < h; y += 1) {
656
+ for (let x = 0; x < w; x += 1) {
657
+ const i = y * w + x;
658
+ if (d[i] === 0) continue;
659
+ let v = d[i];
660
+ if (x > 0) v = Math.min(v, d[i - 1] + 1);
661
+ if (y > 0) {
662
+ if (x > 0) v = Math.min(v, d[i - w - 1] + 1.414);
663
+ v = Math.min(v, d[i - w] + 1);
664
+ if (x + 1 < w) v = Math.min(v, d[i - w + 1] + 1.414);
665
+ }
666
+ d[i] = v;
667
+ }
668
+ }
669
+ for (let y = h - 1; y >= 0; y -= 1) {
670
+ for (let x = w - 1; x >= 0; x -= 1) {
671
+ const i = y * w + x;
672
+ if (d[i] === 0) continue;
673
+ let v = d[i];
674
+ if (x + 1 < w) v = Math.min(v, d[i + 1] + 1);
675
+ if (y + 1 < h) {
676
+ if (x + 1 < w) v = Math.min(v, d[i + w + 1] + 1.414);
677
+ v = Math.min(v, d[i + w] + 1);
678
+ if (x > 0) v = Math.min(v, d[i + w - 1] + 1.414);
679
+ }
680
+ d[i] = v;
681
+ }
682
+ }
683
+ return d;
684
+ }
685
+
686
+ /** 折线上每个点的局部线宽(像素);没给距离图就现算一张。 */
687
+ export function pathPointWidths(mask, w, h, path, dist, cap = 0) {
688
+ const d = dist || inkDistance(mask, w, h);
689
+ const out = new Array(path.length);
690
+ for (let k = 0; k < path.length; k += 1) {
691
+ const p = path[k];
692
+ const x = Math.max(0, Math.min(w - 1, Math.round(p[0])));
693
+ const y = Math.max(0, Math.min(h - 1, Math.round(p[1])));
694
+ let v = 2 * d[y * w + x];
695
+ if (cap > 0) v = Math.min(v, cap);
696
+ out[k] = Number(Math.max(1, v).toFixed(2));
697
+ }
698
+ return out;
699
+ }
700
+
650
701
  export function kmeansColors(data, k, stepPx = 2) {
651
702
  const samples = [];
652
703
  for (let i = 0; i < data.length; i += 4 * stepPx) {
@@ -654,7 +705,7 @@ export function kmeansColors(data, k, stepPx = 2) {
654
705
  samples.push([data[i], data[i + 1], data[i + 2]]);
655
706
  }
656
707
  if (samples.length === 0) throw new Error("这块区域里没有不透明的像素");
657
- const kk = Math.max(2, Math.min(8, Math.round(k)));
708
+ const kk = Math.max(2, Math.min(12, Math.round(k)));
658
709
  const buckets = new Map();
659
710
  for (const s of samples) {
660
711
  const key = ((s[0] >> 3) << 10) | ((s[1] >> 3) << 5) | (s[2] >> 3);
@@ -700,6 +751,171 @@ export function toHex(r, g, b) {
700
751
  return `#${h(r)}${h(g)}${h(b)}`;
701
752
  }
702
753
 
754
+ function signedArea(pts) {
755
+ let a = 0;
756
+ for (let i = 0, j = pts.length - 1; i < pts.length; j = i, i += 1) {
757
+ a += pts[j][0] * pts[i][1] - pts[i][0] * pts[j][1];
758
+ }
759
+ return a / 2;
760
+ }
761
+
762
+ function bboxOf(pts) {
763
+ let x0 = Infinity;
764
+ let y0 = Infinity;
765
+ let x1 = -Infinity;
766
+ let y1 = -Infinity;
767
+ for (const p of pts) {
768
+ if (p[0] < x0) x0 = p[0];
769
+ if (p[1] < y0) y0 = p[1];
770
+ if (p[0] > x1) x1 = p[0];
771
+ if (p[1] > y1) y1 = p[1];
772
+ }
773
+ return { x0, y0, x1, y1 };
774
+ }
775
+
776
+ /**
777
+ * 彩图 → 按色阶分区填色(posterize)。比阈值描线适合彩稿:
778
+ * 先把整幅图量化成 k 色,每一色的连通区按轮廓各自成一块可编辑填色,
779
+ * 大块先铺、小块压在上面,孔洞挂到外层多边形上当 holes。
780
+ * opts.lines=true 时再把色块之间的边界trace成线稿。
781
+ */
782
+ export function posterizeFills(imageData, w, h, opts = {}) {
783
+ const k = Math.max(2, Math.min(12, Math.round(Number(opts.colors) || 8)));
784
+ const minArea = Math.max(4, Number(opts.minArea) || Math.round((w * h) / 4000));
785
+ const tolerance = Math.max(0.5, Number(opts.tolerance) || 1.2);
786
+ const maxFills = Math.max(1, Number(opts.maxFills) || 1600);
787
+ const thinKeep = Math.max(0, Number(opts.thinKeep) || 30);
788
+ const palette = kmeansColors(imageData, k, Math.max(1, Math.round(Number(opts.sampleStep) || 3)));
789
+ const pal = palette.map((p) => p.rgb);
790
+ const idx = new Uint8Array(w * h).fill(255);
791
+ for (let p = 0; p < w * h; p += 1) {
792
+ const i = p * 4;
793
+ if (imageData[i + 3] < 16) continue;
794
+ let best = 0;
795
+ let bd = Infinity;
796
+ for (let c = 0; c < pal.length; c += 1) {
797
+ const d = (imageData[i] - pal[c][0]) ** 2 + (imageData[i + 1] - pal[c][1]) ** 2 + (imageData[i + 2] - pal[c][2]) ** 2;
798
+ if (d < bd) {
799
+ bd = d;
800
+ best = c;
801
+ }
802
+ }
803
+ idx[p] = best;
804
+ }
805
+ // 色阶图先做一遍众数滤波:把彩稿里的渐变噪点和零星小岛抹掉,
806
+ // 不然轮廓会碎成一地碎屑,线稿层也跟着炸。
807
+ const passes = Math.max(0, Math.min(3, opts.denoise === undefined ? 1 : Number(opts.denoise) || 0));
808
+ for (let pass = 0; pass < passes; pass += 1) {
809
+ const out = Uint8Array.from(idx);
810
+ const counts = new Uint16Array(pal.length + 1);
811
+ for (let y = 1; y < h - 1; y += 1) {
812
+ for (let x = 1; x < w - 1; x += 1) {
813
+ const p = y * w + x;
814
+ if (idx[p] === 255) continue;
815
+ counts.fill(0);
816
+ for (let dy = -1; dy <= 1; dy += 1) {
817
+ for (let dx = -1; dx <= 1; dx += 1) {
818
+ const q = idx[p + dy * w + dx];
819
+ if (q !== 255) counts[q] += 1;
820
+ }
821
+ }
822
+ let best = idx[p];
823
+ let bc = counts[best];
824
+ for (let c = 0; c < pal.length; c += 1) {
825
+ if (counts[c] > bc) {
826
+ bc = counts[c];
827
+ best = c;
828
+ }
829
+ }
830
+ out[p] = best;
831
+ }
832
+ }
833
+ idx.set(out);
834
+ }
835
+ // 相邻像素属于不同色阶的地方,就是色块边界(后面可选地描成线稿)
836
+ const edge = new Uint8Array(w * h);
837
+ let edgePixels = 0;
838
+ for (let y = 0; y < h; y += 1) {
839
+ for (let x = 0; x < w; x += 1) {
840
+ const p = y * w + x;
841
+ const v = idx[p];
842
+ if (v === 255) continue;
843
+ if ((x + 1 < w && idx[p + 1] !== 255 && idx[p + 1] !== v) || (y + 1 < h && idx[p + w] !== 255 && idx[p + w] !== v)) {
844
+ edge[p] = 1;
845
+ edgePixels += 1;
846
+ }
847
+ }
848
+ }
849
+ const rings = [];
850
+ for (let c = 0; c < pal.length; c += 1) {
851
+ const mask = new Uint8Array(w * h);
852
+ let area = 0;
853
+ for (let p = 0; p < w * h; p += 1) {
854
+ if (idx[p] === c) {
855
+ mask[p] = 1;
856
+ area += 1;
857
+ }
858
+ }
859
+ if (area < minArea) continue;
860
+ for (const raw of stitchSegments(marchingSquares(mask, w, h))) {
861
+ const pts = raw.map((p) => [p[0] / 2, p[1] / 2]);
862
+ if (pts.length < 4) continue;
863
+ if (Math.hypot(pts[0][0] - pts[pts.length - 1][0], pts[0][1] - pts[pts.length - 1][1]) > 2) continue;
864
+ pts.pop();
865
+ const sa = signedArea(pts);
866
+ const bb = bboxOf(pts);
867
+ const span = Math.hypot(bb.x1 - bb.x0, bb.y1 - bb.y0);
868
+ // 细长条(衣褶高光、发丝边)面积小但很长,一律扔掉会在交界处留白缝,
869
+ // 所以面积不够但跨度够的也留着。
870
+ if (Math.abs(sa) < minArea && span < thinKeep) continue;
871
+ const simplified = rdp(pts, tolerance).map((p) => [
872
+ Number(Math.max(0, Math.min(w - 1, p[0])).toFixed(1)),
873
+ Number(Math.max(0, Math.min(h - 1, p[1])).toFixed(1)),
874
+ ]);
875
+ if (simplified.length < 3) continue;
876
+ rings.push({ color: palette[c].hex, c, pts: simplified, area: Math.abs(sa), sign: Math.sign(sa), bbox: bboxOf(simplified), holes: [] });
877
+ }
878
+ }
879
+ // 正反两种环都当成独立色块,按面积从大到小铺:大块先垫底,小块压上去。
880
+ // 不把反向环当 holes 扣掉——扣掉会在彩色交界处留出一圈白缝,肉眼就是「没画满」。
881
+ const fills = rings
882
+ .sort((a, b) => b.area - a.area)
883
+ .slice(0, maxFills)
884
+ .map((r) => ({ color: r.color, points: r.pts, holes: [], area: Math.round(r.area) }));
885
+ const stats = {
886
+ colorCount: pal.length,
887
+ palette: palette.map((p) => p.hex),
888
+ fills: fills.length,
889
+ fillPixels: fills.reduce((n, f) => n + f.area, 0),
890
+ coveragePct: Number(((fills.reduce((n, f) => n + f.area, 0) / (w * h)) * 100).toFixed(1)),
891
+ edgePixels,
892
+ };
893
+ let lines = { paths: [], widths: [] };
894
+ if (opts.lines === true) {
895
+ const ink = new Uint8Array(w * h * 4);
896
+ for (let p = 0; p < w * h; p += 1) {
897
+ const i = p * 4;
898
+ const on = edge[p] === 1;
899
+ ink[i] = on ? 0 : 255;
900
+ ink[i + 1] = on ? 0 : 255;
901
+ ink[i + 2] = on ? 0 : 255;
902
+ ink[i + 3] = 255;
903
+ }
904
+ lines = traceInk(ink, w, h, {
905
+ threshold: 0.4,
906
+ minLength: Number(opts.minLength) || 24,
907
+ maxLines: Math.max(1, Number(opts.maxLines) || 900),
908
+ tolerance: Number(opts.lineTolerance) || 1.4,
909
+ smooth: 1,
910
+ fit: false,
911
+ });
912
+ stats.lineCount = lines.lines;
913
+ stats.linePoints = lines.points;
914
+ stats.lineColors = pal.length;
915
+ }
916
+ return { fills, stats, paths: lines.paths || [], widths: lines.widths || [] };
917
+ }
918
+
703
919
  /** 参考图 → 折线(和前端 traceInk 同一套参数)。 */
704
920
  export function traceInk(imageData, w, h, opts = {}) {
705
921
  const center = opts.mode === "center";