@xenra/dsh-draworld 0.1.38 → 0.1.40
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 +28 -12
- package/client.js +55 -3
- package/index.js +222 -32
- package/package.json +1 -1
- package/pixelops.js +57 -2
- package/pixels.js +217 -1
package/README.md
CHANGED
|
@@ -16,9 +16,17 @@
|
|
|
16
16
|
|
|
17
17
|
## 安装
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
插件没有第三方依赖(纯 ESM,渲染在浏览器里做)。三种装法:
|
|
20
20
|
|
|
21
|
-
**A.
|
|
21
|
+
**A. 从 npm 装(推荐:管理页会显示「版本 / 可更新到 x」,能一键更新)**
|
|
22
|
+
|
|
23
|
+
```
|
|
24
|
+
@xenra/dsh-draworld
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
装完在插件详情里就有「版本」区块(`可更新到 x.y.z` / `已是最新` / `上次检查于`)和原生「更新」按钮——这块只有注册表安装才渲染,git 安装没有。
|
|
28
|
+
|
|
29
|
+
**B. 从仓库地址装(便于改源码,但没有管理页的版本区块)**
|
|
22
30
|
|
|
23
31
|
在 DeepSeek Harness 的插件管理里填安装地址,任选其一:
|
|
24
32
|
|
|
@@ -28,17 +36,18 @@ https://github.com/RUO-MO/dsh-draworld
|
|
|
28
36
|
```
|
|
29
37
|
|
|
30
38
|
插件管理器会先用 `git ls-remote` 检查仓库连通性,再用 pnpm 装源码(仓库无构建脚本,`--ignore-scripts` 即可)。
|
|
31
|
-
需要本机有 `git`、能访问 `github.com`;**用 https,不要用 ssh**——很多网络下 22 端口被拒。
|
|
39
|
+
需要本机有 `git`、能访问 `github.com`;**用 https,不要用 ssh**——很多网络下 22 端口被拒。git 装的情况下更新走画界自己的一键更新(见下)。
|
|
32
40
|
|
|
33
|
-
**
|
|
41
|
+
**C. 从本地目录装**
|
|
34
42
|
|
|
35
43
|
1. 下载 [最新 Release](https://github.com/RUO-MO/dsh-draworld/releases) 的 zip 解压,或 `git clone https://github.com/RUO-MO/dsh-draworld.git`。
|
|
36
44
|
2. 插件管理里添加这个目录。
|
|
37
45
|
|
|
38
46
|
装完都要**停用再启用**(宿主代码生效);只改界面代码时 `Ctrl+R` 刷新页面即可。
|
|
39
|
-
想确认装的是新版本:打开画界后访问 `http://127.0.0.1:<DSH端口>/canvas-api/diagnostics`,`api=3`、`scope.mode=session
|
|
47
|
+
想确认装的是新版本:打开画界后访问 `http://127.0.0.1:<DSH端口>/canvas-api/diagnostics`,`api=3`、`scope.mode=session`;
|
|
48
|
+
不确定端口就打开画界右列的「版本」卡,或直接读 `<数据目录>/endpoint.json`(里面有 `origin`/`port`/`pid`/`version`)。
|
|
40
49
|
|
|
41
|
-
> **更新**:
|
|
50
|
+
> **更新**:npm 装的,管理页自己会查、点「更新」即可;git 装的,画界右列「版本」卡里有「检查更新 / 一键更新」(走宿主 `pluginManager.updateBundle`,按 tag 重装)。两条路都不用重新找安装地址。
|
|
42
51
|
|
|
43
52
|
> 插件管理按 `package.json` 的 `version` 判断版本。本地目录装了插件、文件改了但版本号没动,它不认——升级请先改版本号。
|
|
44
53
|
|
|
@@ -157,6 +166,7 @@ https://github.com/RUO-MO/dsh-draworld
|
|
|
157
166
|
|---|---|
|
|
158
167
|
| `doc` | 看尺寸、图层、笔迹数、颜色、内容范围、版本;图层带 `image` 就是图片层 |
|
|
159
168
|
| `copy` | **一键复刻**:`style=lineart/flat/anime`,自动抽轮廓 + 区域配色,建「色块 / 线稿」两层,并顺带跑 compare 返回覆盖率;`colors`、`minFill` 可调;`mode` 不传则自动判断参考图是线稿还是照片(回报 `mode`、`inkRatio`);描线默认做**三次贝塞尔拟合**(`fit=false` 退回磨圆 `smooth=0~3`);每根线按量出来的**原线宽**落笔,`splitLines=true` 再把粗细分到「线稿 / 粗线」两层 |
|
|
169
|
+
| `posterize` | **彩图复刻成图(0.1.40 起)**:先 k-means 量化成 `colors` 档(2~12,默认 8),再把每一色的连通区按 marching squares 轮廓各自落成一块可编辑填色(大块先垫、小块压上;细长条不过滤,避免交界白缝),建「色块」层;`lines=true` 顺手把色块边界描成「线稿」层。**彩稿用这个,别用 `copy`**——`copy` 的墨迹阈值会把黑袍当一整块墨,只出 160 根长线。`minArea`(默认面积/4000)、`maxFills`(默认 1600)、`tolerance`、`colors` 可调 |
|
|
160
170
|
| `fix` | **自动补漏**:只看 compare 的 `topGaps` 重描最漏的几块,`target=90`、`maxRounds=3`,达标或没得补就停,返回每轮数字;落在色块洞里(高光)的缺口会跳过(`skippedHoles`) |
|
|
161
171
|
| `fill` | **点一下填色**:`x`、`y` 是区域内的种子点,边界取现有笔迹,颜色默认取参考图该点并映射到主色;`color`、`rect`、`fillLayer` 可调;区域里的洞按轮廓嵌套自动挖掉(`evenodd` 填充) |
|
|
162
172
|
| `select` | 选区:`rect=[x,y,w,h]` 或 `points`(套索),之后落笔只保留选区内的点(越界会切段);`clearSelection=true` 取消 |
|
|
@@ -166,31 +176,35 @@ https://github.com/RUO-MO/dsh-draworld
|
|
|
166
176
|
| `trace` | 参考图 → 轮廓折线:返回 `paths`(画布坐标,直接当 draw 的 points),`threshold` 调深浅、`tolerance` 调概括;`mode=center` 走骨架中心线(线稿用),默认 `edge` 沿墨迹边界;`smooth=0~3` 控制磨圆遍数(默认 1),`fit=true` 改用三次贝塞尔拟合(长弧一条曲线走完) |
|
|
167
177
|
| `pick` | 读某点颜色与透明度(`x`、`y`,`on=ref/canvas`):`ink=true` 说明这点在线条上 |
|
|
168
178
|
| `compare` | 当前画面 vs 参考图:差分图(品红=漏画、青=多画)+ `coveragePct`、`extraPct`、`meanColorDiff`、`topGaps`(最漏的几块) |
|
|
169
|
-
| `palette` | 参考图主色聚类(真 k-means,`k` 2~
|
|
179
|
+
| `palette` | 参考图主色聚类(真 k-means,`k` 2~12)+ 每色占比 |
|
|
170
180
|
| `snapshot` / `restore` | 整幅存档 / 回到某一版(比逐笔 undo 干净,跨进程也在) |
|
|
171
181
|
| `layer` | `layerOp=list/add/select/set/remove`;`set` 改 `name`、`visible`、`layerOpacity`、`blend`、`locked`(锁住就画不上去、也擦不掉) |
|
|
172
|
-
| `import` | 本机图片或 dataUrl
|
|
182
|
+
| `import` | 本机图片或 dataUrl 导入成最底层;落位用 `placement=contain/cover/stretch`(旧的 `fit` 字符串仍兼容) |
|
|
173
183
|
| `canvas` | 改尺寸(16~4096)与背景 |
|
|
174
184
|
| `new` | 另起一幅:可先 `save` 存当前,或给 `path`/`dataUrl` 按图建画布 |
|
|
175
|
-
| `export` | 把最新渲染另存 PNG
|
|
185
|
+
| `export` | 把最新渲染另存 PNG(`path` 给路径、`transparent=true` 取透明底);**面板没开时宿主用 `rasterDoc` 自己画一遍再导出(0.1.40 起)**,不再等前端回传 |
|
|
176
186
|
| `undo` / `redo` | 按全局顺序撤/恢复最近 N 笔 |
|
|
177
187
|
| `clear` | 清空整幅;带 `layer` 只清那层(`all`/`*` 等同整幅) |
|
|
178
188
|
|
|
179
|
-
|
|
189
|
+
**复刻一张图**的闭环:彩稿走 `posterize`(色阶分区铺色 ± 边界线稿),线稿走 `copy`/`trace` → 再 `fix` 补漏;想手工精修再按 `ref` 看细节 → `palette` 定配色 → `trace` 抽轮廓 → `pick` 确认某点在不在线上 → `draw`(长线用 `batches`)→ `view layer=… rect=… zoom=2` 看自己那块 → `compare` 看差多少(`coveragePct` 往 90+ 推、`extraPct` 压下去)→ 收尾前 `snapshot` 兜底。整段流程与协议文本都写进了会话提示词,模型看得到。
|
|
180
190
|
|
|
181
191
|
**改局部别糊整幅**:先 `select` 框住范围(`rect` 或套索 `points`),再 `draw` / `fill`,越界点会被裁掉;改完 `select clearSelection=true`。选区存在 `doc.json` 的 `selection` 字段里,会跟着文档走。
|
|
182
192
|
|
|
183
193
|
**像素任务(两套引擎,自动择一)**:裁切、取色、差分、主色、描线、复刻、填色这些活有两处可算。
|
|
184
194
|
|
|
185
|
-
- **前端**:浏览器早就把参考图解码进 `<canvas>` 了,最快。宿主把任务塞队列,前端
|
|
195
|
+
- **前端**:浏览器早就把参考图解码进 `<canvas>` 了,最快。宿主把任务塞队列,前端 500ms 轮询 `/canvas-api/jobs` 取走(0.1.40 起由 700ms 缩短),算完 POST `/canvas-api/job`,宿主落盘成 PNG 或转成折线/数值交给模型。
|
|
186
196
|
- **宿主侧(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 再读。
|
|
187
|
-
-
|
|
197
|
+
- 宿主算不出来才回落到队列,超时默认 5 秒(`trace`/`copy`/`fill`/`compare`/`palette` 这类整幅重活 30 秒,`heavyTimeout` 可调)、话术直说「宿主侧没算成、面板也没接任务」。不想让宿主插手、只走浏览器:插件配置写 `headless: false`(也可 `POST /canvas-api/config {"headless": false}` 临时切)。
|
|
198
|
+
- **`trace` 带调参反馈(0.1.39 起)**:返回体里多了 `stats` —— `inkRatio`(墨迹占比,判断阈值是不是把阴影也吃进来了)、`widthAvg/Min/Max`(量出来的线宽,拿来设笔刷 size)、`pointsPerLine`(重采样疏密,对应 `fitStep`/`step`)、`droppedPct`(被 `minLength` 丢掉的短段比例)。调 `threshold`/`tolerance`/`fitStep` 时看这几个数,不用只靠肉眼比成品。
|
|
199
|
+
- **画的过程能看见了(0.1.40 起)**:前端 tick 里发现「最上层追加了普通笔迹、其他层没变」就直接 paintStroke 补画那一笔(paintAppended),不再整幅
|
|
200
|
+
enderDoc 重绘;轮询 500ms。模型一批 300 笔过去,画布是逐笔长出来的,跳变间隔从 0.7 秒缩到半秒。
|
|
188
201
|
- **图片类型按内容判**:`import` 不看扩展名,读魔数认 PNG / JPEG / WebP / GIF,缓存名统一是 `img-<stamp>-<rand>.<真扩展名>`;`ref` 遇到非 PNG 会先转一份 `views/ref-…-<mtime>.png` 再交给 `read_image`(同一文件按 mtime 复用,原文件保留不动)。
|
|
189
202
|
|
|
190
203
|
**填色边界**:`copy` 走中心线时,色块另跑一遍边界追踪取闭合轮廓(骨架不闭合),洞按嵌套层数 even-odd 挖掉;`fill` 的泛洪边界只认笔迹(不含已填色块),区域撞到「超过画布 62%」会拒填并提示先有线稿或用 `rect` 收窄。
|
|
191
204
|
|
|
192
205
|
**会话绑定**:工具和画布协议挂在 `agent.ctx` 上,只有打开过画界的会话才有。打开画界时前端 POST `/canvas-api/attach`(带 `sessionId`),关掉 15 秒后 `/detach`。attach 会先按 id 找 agent(`get` 找不到就从列表里翻),找不到就每秒重试、最多 20 秒;20 秒还拿不到就**退回全局注册**(`diagnostics.scope.fallback = "attach-pending"`),保证工具至少能用。想直接退回「所有会话都有」:插件配置写 `toolScope: "global"`(不推荐,会把正在写代码的会话带偏)。
|
|
193
206
|
|
|
207
|
+
**服务是懒注入的(0.1.39 修)**:`tools` / `systemPrompt` / `agents` 不能在 `apply()` 里 `ctx.get` 一次就算——DSH 的 cordis 容器按需注入,插件加载那一刻这几个常常还是 `undefined`,于是 `paint_canvas` 永远挂不上(`diagnostics.tools.service:false`)。现在改成 `ctx.inject(["tools"|"systemPrompt"|"agents"], cb)`,服务一到位就把 `wanted` 里的会话重绑一遍,所以「先开会话、后开面板」也不会再丢工具。诊断里新增 `services`(四个服务到没到位)、`tools.bindError`(绑不上的具体原因)、`endpoint`、`timeouts`,出问题不用再猜。
|
|
208
|
+
|
|
194
209
|
**单一文档**:同一缓存目录只保留一个内存文档(`Document.forDir`,按目录缓存到 `globalThis`),插件被重复加载也不会出现两份各画各的;每次请求与每次工具执行前都核对 `doc.json` mtime,别的窗口刚画过就整份换成更新的那版,避免「模型画了但界面不更新」。
|
|
195
210
|
|
|
196
211
|
## HTTP 接口
|
|
@@ -211,6 +225,7 @@ POST /canvas-api/detach 解绑(15 秒宽限)
|
|
|
211
225
|
GET /canvas-api/jobs 前端取像素任务(crop / ref / pick / compare / palette)
|
|
212
226
|
POST /canvas-api/job 前端回传任务结果(body: id, result)
|
|
213
227
|
GET /canvas-api/update 版本自检(`?force=1` 立刻查一次)
|
|
228
|
+
GET /canvas-api/endpoint 当前端点(origin/port/pid/version/dataDir),也落盘成 `<数据目录>/endpoint.json`
|
|
214
229
|
GET /canvas-api/image/<file> 取素材原字节
|
|
215
230
|
GET /canvas-api/diagnostics 工具/路由/文档/绑定/任务队列/版本状态
|
|
216
231
|
```
|
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');
|
|
@@ -2790,14 +2838,18 @@ window.__ModuleLoader__.load({
|
|
|
2790
2838
|
setStaleHost(!(Number(body.brushes) >= BRUSHES.length));
|
|
2791
2839
|
setUpdateInfo(body.update || null);
|
|
2792
2840
|
if (body.version) setLocalVer(String(body.version));
|
|
2841
|
+
const prevDoc = docRef.current;
|
|
2842
|
+
const prevRev = revRef.current;
|
|
2793
2843
|
docRef.current = body.doc;
|
|
2794
2844
|
await ensureImages(body.doc);
|
|
2795
2845
|
if (!alive) return;
|
|
2796
|
-
if (body.revision !==
|
|
2846
|
+
if (body.revision !== prevRev) {
|
|
2797
2847
|
revRef.current = body.revision;
|
|
2798
2848
|
setRevision(body.revision);
|
|
2799
2849
|
readMeta(body.doc);
|
|
2800
|
-
|
|
2850
|
+
if (!paintAppended(canvasRef.current, prevDoc, body.doc)) {
|
|
2851
|
+
renderDoc(canvasRef.current, body.doc);
|
|
2852
|
+
}
|
|
2801
2853
|
setTimeout(uploadPreview, 300);
|
|
2802
2854
|
// 第一次拿到文档、或画布尺寸变了,重新适应窗口
|
|
2803
2855
|
const fit = fitDimsRef.current;
|
|
@@ -2810,7 +2862,7 @@ window.__ModuleLoader__.load({
|
|
|
2810
2862
|
} catch {
|
|
2811
2863
|
if (alive) setError(t('syncFailed'));
|
|
2812
2864
|
} finally {
|
|
2813
|
-
if (alive) timer = setTimeout(tick,
|
|
2865
|
+
if (alive) timer = setTimeout(tick, 500);
|
|
2814
2866
|
}
|
|
2815
2867
|
};
|
|
2816
2868
|
tick();
|
package/index.js
CHANGED
|
@@ -1185,9 +1185,12 @@ function shapeToPoints(shape, points) {
|
|
|
1185
1185
|
}
|
|
1186
1186
|
|
|
1187
1187
|
export function apply(ctx, config = {}) {
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1188
|
+
// 服务不能在 apply 时直接 get:DSH 的 cordis 容器是按需注入的,
|
|
1189
|
+
// ctx.get("tools") 在插件加载那一刻经常还是 undefined(0.1.39 前一直因此挂不上工具)。
|
|
1190
|
+
// 先在 get 里碰碰运气,真正的来源走下面的 ctx.inject([...])。
|
|
1191
|
+
let tool = ctx.get ? ctx.get("tools") : ctx.tools;
|
|
1192
|
+
let prompt = ctx.get ? ctx.get("systemPrompt") : ctx.systemPrompt;
|
|
1193
|
+
let agents = ctx.get ? ctx.get("agents") : ctx.agents;
|
|
1191
1194
|
let webServer = ctx.get ? ctx.get("webServer") : ctx.webServer;
|
|
1192
1195
|
const rootDir = path.resolve(config.dir || path.join(process.cwd(), ".dsh-draworld"));
|
|
1193
1196
|
const paths = new PathSettings(rootDir);
|
|
@@ -1204,6 +1207,12 @@ export function apply(ctx, config = {}) {
|
|
|
1204
1207
|
scope: config.toolScope === "global" ? "global" : "session",
|
|
1205
1208
|
// 会话补绑 20 秒还没成功,会退回全局注册并把原因记在这(诊断里可见)
|
|
1206
1209
|
scopeFallback: null,
|
|
1210
|
+
// 各服务到没到位:诊断里直接列出来,省得靠 bound:false 猜
|
|
1211
|
+
services: { tools: false, systemPrompt: false, agents: false, webServer: false },
|
|
1212
|
+
// 最近一次绑定失败的原因(resolveAgent 找不到 / register 抛错)
|
|
1213
|
+
bindError: null,
|
|
1214
|
+
// 端点信息:GUI 端口每次重启都可能变,写进 endpoint.json 给脚本用
|
|
1215
|
+
endpoint: null,
|
|
1207
1216
|
// 版本自检:插件自己去 GitHub 看有没有新 Release,界面上给个提示
|
|
1208
1217
|
update: { checkedAt: null, latest: null, hasUpdate: false, url: null, error: null, enabled: config.updateCheck !== false },
|
|
1209
1218
|
};
|
|
@@ -1213,13 +1222,18 @@ export function apply(ctx, config = {}) {
|
|
|
1213
1222
|
// 宿主这边没有图像解码依赖,硬塞 @napi-rs/canvas 会让安装变重。
|
|
1214
1223
|
// 流程:工具 execute 把任务塞进队列 → 前端 700ms 轮询取走 → 算完 POST 回来 → 这里转成工具输出。
|
|
1215
1224
|
const PIXEL_TIMEOUT_MS = Math.max(1500, Number(config.pixelTimeout || 5000));
|
|
1225
|
+
// 整幅(1080×1440 这种)做骨架细化+折线拼接是重活,5 秒根本不够:
|
|
1226
|
+
// 给这几类单独一档超时,默认 30 秒,可用 heavyTimeout 调。
|
|
1227
|
+
const HEAVY_KINDS = new Set(["trace", "copy", "posterize", "fill", "compare", "palette"]);
|
|
1228
|
+
const HEAVY_TIMEOUT_MS = Math.max(PIXEL_TIMEOUT_MS, Number(config.heavyTimeout || 30000));
|
|
1229
|
+
const timeoutFor = (kind) => (HEAVY_KINDS.has(kind) ? HEAVY_TIMEOUT_MS : PIXEL_TIMEOUT_MS);
|
|
1216
1230
|
const jobs = new Map();
|
|
1217
1231
|
let jobSeq = 0;
|
|
1218
1232
|
const jobStats = { done: 0, timeout: 0, failed: 0, queued: 0, headless: 0, last: null };
|
|
1219
1233
|
|
|
1220
1234
|
// 面板在不在:前端每 700ms 轮询一次 /jobs,2.5 秒没动静就当作没有面板 → 宿主机自己算
|
|
1221
1235
|
const panelLive = () => Date.now() - (state.panelAt || 0) < 2500;
|
|
1222
|
-
const HEADLESS_KINDS = new Set(["crop", "ref", "pick", "palette", "trace", "copy", "fill", "compare"]);
|
|
1236
|
+
const HEADLESS_KINDS = new Set(["crop", "ref", "pick", "palette", "trace", "copy", "posterize", "fill", "compare"]);
|
|
1223
1237
|
|
|
1224
1238
|
const runHeadlessPixel = async (kind, params) => {
|
|
1225
1239
|
try {
|
|
@@ -1249,7 +1263,7 @@ export function apply(ctx, config = {}) {
|
|
|
1249
1263
|
function enqueue() {
|
|
1250
1264
|
jobSeq += 1;
|
|
1251
1265
|
const id = `j${jobSeq}`;
|
|
1252
|
-
const limit = Math.max(1500, Number(timeoutMs) ||
|
|
1266
|
+
const limit = Math.max(1500, Number(timeoutMs) || timeoutFor(kind));
|
|
1253
1267
|
const timer = setTimeout(() => {
|
|
1254
1268
|
if (!jobs.has(id)) return;
|
|
1255
1269
|
jobs.delete(id);
|
|
@@ -1404,7 +1418,7 @@ export function apply(ctx, config = {}) {
|
|
|
1404
1418
|
|
|
1405
1419
|
/** 兜底把工具挂到插件全局:会话补绑失败时至少还能用(诊断里会标 scopeFallback)。 */
|
|
1406
1420
|
const enableGlobalFallback = (reason) => {
|
|
1407
|
-
if (state.scope === "global") return false;
|
|
1421
|
+
if (state.scope === "global" && state.toolOk) return false;
|
|
1408
1422
|
state.scope = "global";
|
|
1409
1423
|
state.scopeFallback = String(reason || "attach-pending");
|
|
1410
1424
|
if (prompt) {
|
|
@@ -1472,6 +1486,11 @@ export function apply(ctx, config = {}) {
|
|
|
1472
1486
|
}
|
|
1473
1487
|
bound.set(agent.id, { agent, disposers: list });
|
|
1474
1488
|
state.toolOk = list.length > 0;
|
|
1489
|
+
if (list.length === 0) {
|
|
1490
|
+
state.bindError = "agent.ctx 上没有 tools/systemPrompt 的注册口(宿主版本不同?)";
|
|
1491
|
+
} else {
|
|
1492
|
+
state.bindError = null;
|
|
1493
|
+
}
|
|
1475
1494
|
return true;
|
|
1476
1495
|
};
|
|
1477
1496
|
|
|
@@ -1502,6 +1521,7 @@ export function apply(ctx, config = {}) {
|
|
|
1502
1521
|
wanted.add(id);
|
|
1503
1522
|
const agent = resolveAgent(id);
|
|
1504
1523
|
const didBind = agent ? bindAgent(agent) : false;
|
|
1524
|
+
if (!didBind) state.bindError = `找不到会话 ${id} 的 agent(agents 服务未就绪或 id 不是 agent id)`;
|
|
1505
1525
|
if (!didBind) {
|
|
1506
1526
|
// 会话在 attach 之前就建好了、又拿不到 agent:定时重试,20 秒还没成再退到全局
|
|
1507
1527
|
if (!bindRetries.has(id)) {
|
|
@@ -1581,6 +1601,26 @@ export function apply(ctx, config = {}) {
|
|
|
1581
1601
|
state.routeError = `getOrigin 失败: ${(err && err.message) || err}`;
|
|
1582
1602
|
return;
|
|
1583
1603
|
}
|
|
1604
|
+
// 端口每个进程都可能变(59311 → 54578 这种):把端点写进数据目录,
|
|
1605
|
+
// 外部脚本读 endpoint.json 就行,不用再去猜端口。
|
|
1606
|
+
try {
|
|
1607
|
+
const info = {
|
|
1608
|
+
ok: true,
|
|
1609
|
+
api: 3,
|
|
1610
|
+
plugin: name,
|
|
1611
|
+
version: readLocalVersion(),
|
|
1612
|
+
origin: state.origin,
|
|
1613
|
+
port: Number((String(state.origin).match(/:(\d+)/) || [])[1] || 0),
|
|
1614
|
+
pid: process.pid,
|
|
1615
|
+
dataDir: dir,
|
|
1616
|
+
updatedAt: Date.now(),
|
|
1617
|
+
};
|
|
1618
|
+
state.endpoint = info;
|
|
1619
|
+
mkdirSync(dir, { recursive: true });
|
|
1620
|
+
writeFileSync(path.join(dir, "endpoint.json"), JSON.stringify(info, null, 2), "utf8");
|
|
1621
|
+
} catch {
|
|
1622
|
+
/* 写不了就只留在内存里,诊断还能看到 */
|
|
1623
|
+
}
|
|
1584
1624
|
try {
|
|
1585
1625
|
const dispose = webServer.register({
|
|
1586
1626
|
kind: "prefix",
|
|
@@ -1610,15 +1650,23 @@ export function apply(ctx, config = {}) {
|
|
|
1610
1650
|
return;
|
|
1611
1651
|
}
|
|
1612
1652
|
|
|
1653
|
+
// 端点:脚本先问这里(或者直接读 <数据目录>/endpoint.json),别去猜端口
|
|
1654
|
+
if (route === "/endpoint" && req.method === "GET") {
|
|
1655
|
+
json(res, 200, { ok: true, ...(state.endpoint || { origin: state.origin, dataDir: dir }) });
|
|
1656
|
+
return;
|
|
1657
|
+
}
|
|
1613
1658
|
if (route === "/diagnostics" && req.method === "GET") {
|
|
1614
1659
|
json(res, 200, {
|
|
1615
1660
|
ok: true,
|
|
1616
1661
|
api: 3,
|
|
1617
1662
|
plugin: "@xenra/dsh-draworld",
|
|
1618
1663
|
brushes: BRUSH_IDS.length,
|
|
1619
|
-
tools: { service: Boolean(tool), ok: state.toolOk, error: state.toolError },
|
|
1664
|
+
tools: { service: Boolean(tool), ok: state.toolOk, error: state.toolError, bindError: state.bindError },
|
|
1665
|
+
services: state.services,
|
|
1620
1666
|
scope: { mode: state.scope, fallback: state.scopeFallback, attached: [...wanted], bound: [...bound.keys()], retries: [...bindRetries.entries()] },
|
|
1621
1667
|
routes: { error: state.routeError, origin: state.origin },
|
|
1668
|
+
endpoint: state.endpoint,
|
|
1669
|
+
timeouts: { light: PIXEL_TIMEOUT_MS, heavy: HEAVY_TIMEOUT_MS },
|
|
1622
1670
|
doc: {
|
|
1623
1671
|
dir,
|
|
1624
1672
|
revision: docs.revision,
|
|
@@ -1987,15 +2035,17 @@ export function apply(ctx, config = {}) {
|
|
|
1987
2035
|
"view 取最新渲染结果(rect 裁切、zoom 放大、layer 只看单层,并给每层的包围盒与覆盖率);" +
|
|
1988
2036
|
"ref 把参考图(或它的一块裁切)导出成 PNG,用 read_image 直接看;pick 读某点的颜色/透明度;" +
|
|
1989
2037
|
"compare 出「当前画面 vs 参考图」的差分图和数值;palette 提参考图主色;" +
|
|
2038
|
+
"copy 按阈值描线复刻(线稿/平涂/两者);posterize 把彩图按色阶分区复刻成可编辑色块(可顺带描边界线稿),彩稿用这个而不是 copy;" +
|
|
1990
2039
|
"snapshot / restore 整幅存档与回退;undo / redo 撤销重做;clear 清空(给 layer 只清那层);" +
|
|
1991
2040
|
"layer 增删改图层(name/visible/layerOpacity/blend/locked);" +
|
|
1992
|
-
"import 把本机图片导入成最底下的图片层(path 或 dataUrl);canvas 改画布尺寸和背景;
|
|
2041
|
+
"import 把本机图片导入成最底下的图片层(path 或 dataUrl);canvas 改画布尺寸和背景;" +
|
|
2042
|
+
"export 把当前渲染另存成 PNG(面板没开时宿主自己光栅化,不依赖前端回传)。",
|
|
1993
2043
|
parameters: {
|
|
1994
2044
|
type: "object",
|
|
1995
2045
|
properties: {
|
|
1996
2046
|
action: {
|
|
1997
2047
|
type: "string",
|
|
1998
|
-
enum: ["doc", "copy", "fix", "fill", "draw", "view", "ref", "trace", "pick", "compare", "palette", "select", "snapshot", "restore", "undo", "redo", "clear", "layer", "import", "canvas", "export", "new"],
|
|
2048
|
+
enum: ["doc", "copy", "posterize", "fix", "fill", "draw", "view", "ref", "trace", "pick", "compare", "palette", "select", "snapshot", "restore", "undo", "redo", "clear", "layer", "import", "canvas", "export", "new"],
|
|
1999
2049
|
description: "要执行的动作。new 是另起一幅(可先保存当前、也可用图片建画布)。",
|
|
2000
2050
|
},
|
|
2001
2051
|
points: {
|
|
@@ -2026,6 +2076,11 @@ export function apply(ctx, config = {}) {
|
|
|
2026
2076
|
+ "特效 halftone 漫画网点 / glow 光效 / sparkle 粒子。默认 round。",
|
|
2027
2077
|
},
|
|
2028
2078
|
taper: { type: "boolean", description: "draw: 起收笔渐细(手绘感),默认 false。" },
|
|
2079
|
+
widths: {
|
|
2080
|
+
type: "boolean",
|
|
2081
|
+
description: "trace: 回一份 pathsWidth(每个点带第 3 个压力值),配合 size=sizeHint、minSize=0 让笔迹按原图局部线宽变粗变细。",
|
|
2082
|
+
},
|
|
2083
|
+
sizeHint: { type: "number", description: "trace widths=true 时返回的建议笔刷 size(≈ 原图 p90 线宽)。" },
|
|
2029
2084
|
minSize: {
|
|
2030
2085
|
type: "number",
|
|
2031
2086
|
description: "draw: 最小笔宽占 size 的比例 0..1,默认 0.3;压力最轻时也不会细成一条线。",
|
|
@@ -2059,11 +2114,6 @@ export function apply(ctx, config = {}) {
|
|
|
2059
2114
|
description: "import: 本机图片的绝对路径(PNG/JPEG/WebP/GIF)。",
|
|
2060
2115
|
},
|
|
2061
2116
|
dataUrl: { type: "string", description: "import: 图片 dataURL,和 path 二选一。" },
|
|
2062
|
-
fit: {
|
|
2063
|
-
type: "string",
|
|
2064
|
-
enum: ["contain", "cover", "stretch"],
|
|
2065
|
-
description: "import: 落位方式,默认 contain(整张居中放进画布)。",
|
|
2066
|
-
},
|
|
2067
2117
|
width: { type: "number", description: "canvas: 新宽度 16~4096。" },
|
|
2068
2118
|
height: { type: "number", description: "canvas: 新高度 16~4096。" },
|
|
2069
2119
|
background: { type: "string", description: "canvas: 背景色 #rrggbb。" },
|
|
@@ -2108,7 +2158,21 @@ export function apply(ctx, config = {}) {
|
|
|
2108
2158
|
description: "trace: 折线简化容差(像素),默认 2.5。大一点更概括,小一点更贴边。",
|
|
2109
2159
|
},
|
|
2110
2160
|
minLength: { type: "number", description: "trace: 丢掉的短线段长度下限(像素),默认 12(copy 默认 16),用来滤掉噪点。" },
|
|
2111
|
-
maxLines: { type: "number", description: "trace:
|
|
2161
|
+
maxLines: { type: "number", description: "trace / posterize: 最多返回几条折线,trace 默认 80,posterize 描边界时默认 1600。" },
|
|
2162
|
+
minArea: {
|
|
2163
|
+
type: "number",
|
|
2164
|
+
description: "posterize: 小于多少像素的色块丢掉,默认画布面积/4000(1080×1440 约 389)。小一点细节多但笔迹暴增。",
|
|
2165
|
+
},
|
|
2166
|
+
maxFills: { type: "number", description: "posterize: 最多铺几块色,默认 3000。" },
|
|
2167
|
+
lines: {
|
|
2168
|
+
type: "boolean",
|
|
2169
|
+
description: "posterize: 顺手把色块之间的边界描成线稿层(默认 false,只要色块)。",
|
|
2170
|
+
},
|
|
2171
|
+
placement: {
|
|
2172
|
+
type: "string",
|
|
2173
|
+
enum: ["contain", "cover", "stretch"],
|
|
2174
|
+
description: "import: 落位方式,默认 contain(整张居中放进画布)。",
|
|
2175
|
+
},
|
|
2112
2176
|
smooth: {
|
|
2113
2177
|
type: "number",
|
|
2114
2178
|
description: "trace / copy: 描线后磨圆几遍 0~3,默认 trace 1、copy 2。觉得线还是抖就给 3;要贴原图硬边就给 0。",
|
|
@@ -2123,7 +2187,7 @@ export function apply(ctx, config = {}) {
|
|
|
2123
2187
|
enum: ["lineart", "flat", "anime"],
|
|
2124
2188
|
description: "copy: 复刻风格。lineart 只出线稿;flat 只出区域色块;anime 出线稿+色块(默认)。",
|
|
2125
2189
|
},
|
|
2126
|
-
colors: { type: "number", description: "copy / palette: 主色档数 2~8
|
|
2190
|
+
colors: { type: "number", description: "copy / posterize / palette: 主色档数 2~12(copy 默认 6,posterize 默认 8)。彩稿要火、金、肤这些颜色都出来,给 10~12。" },
|
|
2127
2191
|
minFill: { type: "number", description: "copy: 小于多少像素的闭合区域不填色,默认 320。" },
|
|
2128
2192
|
target: { type: "number", description: "fix: 目标覆盖率百分比,默认 90。到了就停。" },
|
|
2129
2193
|
maxRounds: { type: "number", description: "fix: 最多迭代几轮,默认 3(上限 5)。" },
|
|
@@ -2141,7 +2205,7 @@ export function apply(ctx, config = {}) {
|
|
|
2141
2205
|
type: "boolean",
|
|
2142
2206
|
description: "select: 清掉选区,恢复整幅可画。",
|
|
2143
2207
|
},
|
|
2144
|
-
k: { type: "number", description: "palette: 要几档主色,默认 6(上限
|
|
2208
|
+
k: { type: "number", description: "palette: 要几档主色,默认 6(上限 12)。" },
|
|
2145
2209
|
snapshotId: { type: "string", description: "restore: 回退到哪一版快照(snapshot 返回的 id);不给回最近一版。" },
|
|
2146
2210
|
label: { type: "string", description: "snapshot: 这版备注,比如「上色前」。" },
|
|
2147
2211
|
locked: { type: "boolean", description: "layer.set:锁定这层(参考图锁住,模型就盖不上去,也不会被误擦)。" },
|
|
@@ -2322,7 +2386,7 @@ export function apply(ctx, config = {}) {
|
|
|
2322
2386
|
const result = docs.importImage({
|
|
2323
2387
|
buffer,
|
|
2324
2388
|
name: args.name || fallbackName,
|
|
2325
|
-
fit: args.fit,
|
|
2389
|
+
fit: args.placement || (typeof args.fit === "string" ? args.fit : undefined),
|
|
2326
2390
|
opacity: args.layerOpacity,
|
|
2327
2391
|
});
|
|
2328
2392
|
return {
|
|
@@ -2346,20 +2410,46 @@ export function apply(ctx, config = {}) {
|
|
|
2346
2410
|
};
|
|
2347
2411
|
}
|
|
2348
2412
|
case "export": {
|
|
2349
|
-
const source = args.transparent ? docs.previewAlpha : docs.preview;
|
|
2350
|
-
if (!existsSync(source)) {
|
|
2351
|
-
throw new Error(args.transparent
|
|
2352
|
-
? "还没有透明底渲染:先在界面里打开画界,等前端回传一帧"
|
|
2353
|
-
: "还没有渲染结果:先在界面里打开画界画一笔,前端会把渲染回传");
|
|
2354
|
-
}
|
|
2355
2413
|
const now = new Date();
|
|
2356
2414
|
const pad = (n) => String(n).padStart(2, "0");
|
|
2357
2415
|
const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
|
|
2358
2416
|
const saveDir = paths.saveDir();
|
|
2359
2417
|
mkdirSync(saveDir, { recursive: true });
|
|
2360
|
-
const target =
|
|
2361
|
-
|
|
2362
|
-
|
|
2418
|
+
const target = args.path
|
|
2419
|
+
? path.resolve(String(args.path))
|
|
2420
|
+
: path.join(saveDir, `画界-${stamp}${args.transparent ? "-alpha" : ""}.png`);
|
|
2421
|
+
const source = args.transparent ? docs.previewAlpha : docs.preview;
|
|
2422
|
+
if (existsSync(source) && !args.path) {
|
|
2423
|
+
copyFileSync(source, target);
|
|
2424
|
+
return { ok: true, path: target, saveDir, transparent: Boolean(args.transparent), rendered: "panel" };
|
|
2425
|
+
}
|
|
2426
|
+
// 面板没开、没有前端帧:宿主自己光栅化(0.1.40 起),不开界面也能导出/验收
|
|
2427
|
+
try {
|
|
2428
|
+
const mod = await import("./pixels.js");
|
|
2429
|
+
const docSurf = await mod.rasterDoc(docs.doc, { resolve: (f) => path.resolve(dir, f) });
|
|
2430
|
+
let out = docSurf;
|
|
2431
|
+
if (!args.transparent) {
|
|
2432
|
+
const hex = String(docs.doc.background || "#ffffff").replace("#", "");
|
|
2433
|
+
const rgb = [0, 1, 2].map((k) => {
|
|
2434
|
+
const v = parseInt(hex.slice(k * 2, k * 2 + 2), 16);
|
|
2435
|
+
return Number.isFinite(v) ? v : 255;
|
|
2436
|
+
});
|
|
2437
|
+
const bg = mod.makeSurface(docSurf.w, docSurf.h);
|
|
2438
|
+
for (let i = 0; i < bg.data.length; i += 4) {
|
|
2439
|
+
bg.data[i] = rgb[0];
|
|
2440
|
+
bg.data[i + 1] = rgb[1];
|
|
2441
|
+
bg.data[i + 2] = rgb[2];
|
|
2442
|
+
bg.data[i + 3] = 255;
|
|
2443
|
+
}
|
|
2444
|
+
mod.blitImage(bg, { data: docSurf.data, width: docSurf.w, height: docSurf.h }, 0, 0, docSurf.w, docSurf.h);
|
|
2445
|
+
out = bg;
|
|
2446
|
+
}
|
|
2447
|
+
mkdirSync(path.dirname(target), { recursive: true });
|
|
2448
|
+
writeFileSync(target, mod.encodePng(out.data, out.w, out.h));
|
|
2449
|
+
return { ok: true, path: target, saveDir, transparent: Boolean(args.transparent), rendered: "host" };
|
|
2450
|
+
} catch (err) {
|
|
2451
|
+
throw new Error(`没有前端渲染帧,宿主侧光栅化也没成:${(err && err.message) || err}`);
|
|
2452
|
+
}
|
|
2363
2453
|
}
|
|
2364
2454
|
case "undo":
|
|
2365
2455
|
docs.undo(Math.max(1, Math.round(Number(args.count) || 1)));
|
|
@@ -2622,6 +2712,62 @@ export function apply(ctx, config = {}) {
|
|
|
2622
2712
|
+ "想补差距就 action=fix。",
|
|
2623
2713
|
};
|
|
2624
2714
|
}
|
|
2715
|
+
case "posterize": {
|
|
2716
|
+
// 彩图复刻成图:按色阶分区,每块是一个可编辑填色(不是黑线),
|
|
2717
|
+
// 需要线稿再 lines=true 描色块边界。
|
|
2718
|
+
const rect = parseRect(args.rect, docs.doc.width, docs.doc.height);
|
|
2719
|
+
const job = await runPixelJob("posterize", {
|
|
2720
|
+
rect,
|
|
2721
|
+
layer: args.refLayer === undefined ? null : args.refLayer,
|
|
2722
|
+
colors: args.colors,
|
|
2723
|
+
minArea: args.minArea,
|
|
2724
|
+
tolerance: args.tolerance,
|
|
2725
|
+
maxFills: args.maxFills,
|
|
2726
|
+
lines: args.lines === true,
|
|
2727
|
+
minLength: args.minLength,
|
|
2728
|
+
maxLines: args.maxLines,
|
|
2729
|
+
}, PIXEL_TIMEOUT_MS * 3);
|
|
2730
|
+
if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
|
|
2731
|
+
const created = [];
|
|
2732
|
+
const pickLayer = (name) => {
|
|
2733
|
+
const want = String(name || "").trim();
|
|
2734
|
+
const found = want ? docs.layer(want) : null;
|
|
2735
|
+
if (found && !found.locked && !found.image && (found.strokes || []).length === 0) return found;
|
|
2736
|
+
return docs.addLayer(want || undefined);
|
|
2737
|
+
};
|
|
2738
|
+
if (Array.isArray(job.fills) && job.fills.length > 0) {
|
|
2739
|
+
const layer = pickLayer(args.fillLayer || "色块");
|
|
2740
|
+
docs.append(
|
|
2741
|
+
job.fills.map((f) => ({ mode: "fill", color: f.color, size: 1, opacity: 1, points: f.points, holes: f.holes || [] })),
|
|
2742
|
+
layer.id,
|
|
2743
|
+
);
|
|
2744
|
+
created.push({ name: layer.name, kind: "fill", items: job.fills.length });
|
|
2745
|
+
}
|
|
2746
|
+
if (Array.isArray(job.paths) && job.paths.length > 0) {
|
|
2747
|
+
const layer = pickLayer(args.layer || "线稿");
|
|
2748
|
+
const color = args.color || "#111111";
|
|
2749
|
+
const brush = BRUSH_IDS.includes(args.brush) ? args.brush : "liner";
|
|
2750
|
+
const base = Math.max(1, Number(args.size) || 2);
|
|
2751
|
+
docs.append(
|
|
2752
|
+
job.paths.filter((p) => p && p.length >= 2).map((points) => ({ color, size: base, brush, opacity: 1, points })),
|
|
2753
|
+
layer.id,
|
|
2754
|
+
);
|
|
2755
|
+
created.push({ name: layer.name, kind: "line", items: job.paths.length });
|
|
2756
|
+
}
|
|
2757
|
+
const cmp = await runPixelJob("compare", { rect }, PIXEL_TIMEOUT_MS * 2);
|
|
2758
|
+
return {
|
|
2759
|
+
ok: true,
|
|
2760
|
+
revision: docs.revision,
|
|
2761
|
+
rect,
|
|
2762
|
+
created,
|
|
2763
|
+
palette: job.stats && job.stats.palette,
|
|
2764
|
+
stats: job.stats,
|
|
2765
|
+
metrics: cmp.ok ? cmp.metrics : null,
|
|
2766
|
+
hint: `已按 ${job.stats ? job.stats.colorCount : "?"} 色阶分区复刻:${created.map((c) => `${c.name}(${c.items})`).join(" + ") || "没有可画的内容"}。`
|
|
2767
|
+
+ (cmp.ok ? `覆盖率 ${cmp.metrics.coveragePct}%,多画 ${cmp.metrics.extraPct}%,色差 ${cmp.metrics.meanColorDiff}。` : "")
|
|
2768
|
+
+ "要更像原图就调 colors(色阶数)/ minArea(细节门槛),或者 lines=true 补边界线稿。",
|
|
2769
|
+
};
|
|
2770
|
+
}
|
|
2625
2771
|
case "fix": {
|
|
2626
2772
|
const rect = parseRect(args.rect, docs.doc.width, docs.doc.height);
|
|
2627
2773
|
const maxRounds = Math.max(1, Math.min(5, Math.round(Number(args.maxRounds) || 3)));
|
|
@@ -2698,6 +2844,7 @@ export function apply(ctx, config = {}) {
|
|
|
2698
2844
|
smooth: args.smooth,
|
|
2699
2845
|
fit: args.fit === true,
|
|
2700
2846
|
fitStep: args.fitStep,
|
|
2847
|
+
widths: args.widths === true,
|
|
2701
2848
|
mode: args.mode === "center" ? "center" : "edge",
|
|
2702
2849
|
});
|
|
2703
2850
|
if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
|
|
@@ -2713,7 +2860,13 @@ export function apply(ctx, config = {}) {
|
|
|
2713
2860
|
smooth: job.smooth === undefined ? null : job.smooth,
|
|
2714
2861
|
fit: job.fit === undefined ? null : job.fit,
|
|
2715
2862
|
paths: job.paths,
|
|
2863
|
+
stats: job.stats,
|
|
2864
|
+
...(job.pathsWidth ? { pathsWidth: job.pathsWidth, sizeHint: job.sizeHint } : {}),
|
|
2716
2865
|
hint: "paths 是从参考图抽出的轮廓折线(画布坐标),每段直接当 draw 的 points 用;长图可分批 batches=[…]。"
|
|
2866
|
+
+ (job.pathsWidth
|
|
2867
|
+
? ` width=true 时用 pathsWidth(点带第 3 个压力值,sizeHint=${job.sizeHint}):draw 时 size=sizeHint、minSize=0,笔迹就会按原图局部线宽自己变粗变细。`
|
|
2868
|
+
: " 想要粗细跟着原图走,加 widths=true,会多回一份带逐点压力的 pathsWidth。")
|
|
2869
|
+
+ "stats 给的是 inkRatio/widthAvg/widthMin/widthMax/droppedPct,调 threshold/tolerance/fitStep 时看这几个数,不用只靠肉眼。"
|
|
2717
2870
|
+ "描完用 view rect+zoom 对照,再用 compare 看 coveragePct。",
|
|
2718
2871
|
};
|
|
2719
2872
|
}
|
|
@@ -2779,18 +2932,55 @@ export function apply(ctx, config = {}) {
|
|
|
2779
2932
|
isConcurrencySafe: () => false,
|
|
2780
2933
|
};
|
|
2781
2934
|
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
|
|
2785
|
-
|
|
2935
|
+
let globalRegistered = false;
|
|
2936
|
+
|
|
2937
|
+
/** 服务到位后统一收口:刷新诊断字段、把等着绑的会话重绑一遍、必要时补全局注册。 */
|
|
2938
|
+
const onServicesReady = () => {
|
|
2939
|
+
state.services.tools = Boolean(tool);
|
|
2940
|
+
state.services.systemPrompt = Boolean(prompt);
|
|
2941
|
+
state.services.agents = Boolean(agents);
|
|
2942
|
+
state.services.webServer = Boolean(webServer);
|
|
2943
|
+
for (const id of wanted) {
|
|
2944
|
+
if (bound.has(id)) continue;
|
|
2945
|
+
const agent = resolveAgent(id);
|
|
2946
|
+
if (agent) bindAgent(agent);
|
|
2947
|
+
}
|
|
2948
|
+
if (state.scope === "global" && tool && !globalRegistered) {
|
|
2949
|
+
if (prompt) {
|
|
2950
|
+
try {
|
|
2951
|
+
disposers.push(prompt.section({ name: SECTION_NAME, order: SECTION_ORDER, text: PROTOCOL }));
|
|
2952
|
+
} catch (err) {
|
|
2953
|
+
state.toolError = `section: ${(err && err.message) || err}`;
|
|
2954
|
+
}
|
|
2955
|
+
}
|
|
2786
2956
|
try {
|
|
2787
2957
|
disposers.push(tool.register(definition));
|
|
2788
2958
|
state.toolOk = true;
|
|
2959
|
+
globalRegistered = true;
|
|
2960
|
+
state.bindError = null;
|
|
2789
2961
|
} catch (err) {
|
|
2790
|
-
state.toolError =
|
|
2962
|
+
state.toolError = `register: ${(err && err.message) || err}`;
|
|
2791
2963
|
}
|
|
2792
2964
|
}
|
|
2965
|
+
};
|
|
2966
|
+
|
|
2967
|
+
// cordis 的服务是懒注入的:ctx.get 在 apply 那一刻常常拿不到,
|
|
2968
|
+
// 必须用 ctx.inject 等回调(回调就是「该服务可用」的时刻)。
|
|
2969
|
+
if (typeof ctx.inject === "function") {
|
|
2970
|
+
ctx.inject(["tools"], (scope) => {
|
|
2971
|
+
tool = (scope && scope.tools) || (scope && scope.get ? scope.get("tools") : null);
|
|
2972
|
+
onServicesReady();
|
|
2973
|
+
});
|
|
2974
|
+
ctx.inject(["systemPrompt"], (scope) => {
|
|
2975
|
+
prompt = (scope && scope.systemPrompt) || (scope && scope.get ? scope.get("systemPrompt") : null);
|
|
2976
|
+
onServicesReady();
|
|
2977
|
+
});
|
|
2978
|
+
ctx.inject(["agents"], (scope) => {
|
|
2979
|
+
agents = (scope && scope.agents) || (scope && scope.get ? scope.get("agents") : null);
|
|
2980
|
+
onServicesReady();
|
|
2981
|
+
});
|
|
2793
2982
|
}
|
|
2983
|
+
onServicesReady();
|
|
2794
2984
|
|
|
2795
2985
|
if (webServer) mount();
|
|
2796
2986
|
else if (typeof ctx.inject === "function") {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xenra/dsh-draworld",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.40",
|
|
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,7 +6,7 @@ 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")}`;
|
|
@@ -106,9 +106,46 @@ export async function runHeadless(kind, params, doc, resolve) {
|
|
|
106
106
|
maxLines: params.maxLines,
|
|
107
107
|
});
|
|
108
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
|
+
|
|
125
|
+
// widths=true:折线带上逐点压力(第 3 个数),让笔迹自己长成原图的粗细,
|
|
126
|
+
// 而不是一条从头到尾同宽的「硬线」。pressure = 局部线宽 / p90 线宽,配合 size=sizeHint、minSize=0 用。
|
|
127
|
+
let pathsWidth = null;
|
|
128
|
+
let sizeHint = null;
|
|
129
|
+
if (params.widths) {
|
|
130
|
+
const dist = inkDistance(mask, cut.w, cut.h);
|
|
131
|
+
const perPath = t.paths.map((line) => pathPointWidths(mask, cut.w, cut.h, line, dist));
|
|
132
|
+
const all = perPath.reduce((acc, arr) => acc.concat(arr), []);
|
|
133
|
+
all.sort((a, b) => a - b);
|
|
134
|
+
const p90 = all.length ? all[Math.floor(all.length * 0.9)] : 1;
|
|
135
|
+
sizeHint = Math.max(2, Math.round(p90));
|
|
136
|
+
pathsWidth = t.paths.map((line, li) => line.map((p, k) => [
|
|
137
|
+
Math.round(rect.x + p[0]),
|
|
138
|
+
Math.round(rect.y + p[1]),
|
|
139
|
+
Number(Math.min(1, Math.max(0.05, perPath[li][k] / sizeHint)).toFixed(3)),
|
|
140
|
+
]));
|
|
141
|
+
stats.sizeHint = sizeHint;
|
|
142
|
+
stats.widthP90 = Number(p90.toFixed(2));
|
|
143
|
+
}
|
|
144
|
+
|
|
109
145
|
return {
|
|
110
146
|
ok: true, rect, paths, lines: t.lines, points: t.points, dropped: t.dropped,
|
|
111
|
-
tolerance: t.tolerance, smooth: t.smooth, fit: t.fit, mode: t.mode, headless: true,
|
|
147
|
+
tolerance: t.tolerance, smooth: t.smooth, fit: t.fit, mode: t.mode, headless: true, stats,
|
|
148
|
+
...(pathsWidth ? { pathsWidth, sizeHint } : {}),
|
|
112
149
|
};
|
|
113
150
|
}
|
|
114
151
|
if (kind === "copy") {
|
|
@@ -158,6 +195,24 @@ export async function runHeadless(kind, params, doc, resolve) {
|
|
|
158
195
|
smooth: t.smooth, fit: t.fit, inkRatio, lines: t.lines, points: t.points, dropped: t.dropped, headless: true,
|
|
159
196
|
};
|
|
160
197
|
}
|
|
198
|
+
if (kind === "posterize") {
|
|
199
|
+
const surf = await refSurface(doc, resolve, params);
|
|
200
|
+
const rect = clampRect(params.rect, surf.w, surf.h);
|
|
201
|
+
const cut = cropSurface(surf, rect);
|
|
202
|
+
const res = posterizeFills(cut.data, cut.w, cut.h, {
|
|
203
|
+
colors: params.colors,
|
|
204
|
+
minArea: params.minArea,
|
|
205
|
+
tolerance: params.tolerance,
|
|
206
|
+
maxFills: params.maxFills,
|
|
207
|
+
lines: params.lines === true,
|
|
208
|
+
minLength: params.minLength,
|
|
209
|
+
maxLines: params.maxLines,
|
|
210
|
+
});
|
|
211
|
+
const shift = (pts) => pts.map((p) => [Math.round(rect.x + p[0]), Math.round(rect.y + p[1])]);
|
|
212
|
+
const fills = res.fills.map((f) => ({ color: f.color, points: shift(f.points), holes: (f.holes || []).map(shift), area: f.area }));
|
|
213
|
+
const paths = res.paths.map(shift);
|
|
214
|
+
return { ok: true, rect, fills, paths, stats: res.stats, headless: true };
|
|
215
|
+
}
|
|
161
216
|
if (kind === "fill") {
|
|
162
217
|
const sx = Math.round(Number(params.x));
|
|
163
218
|
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(
|
|
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";
|