@xenra/dsh-draworld 0.1.41 → 0.1.46

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.
Files changed (6) hide show
  1. package/README.md +80 -12
  2. package/client.js +392 -96
  3. package/index.js +958 -72
  4. package/package.json +1 -1
  5. package/pixelops.js +1260 -96
  6. package/pixels.js +182 -19
package/index.js CHANGED
@@ -43,18 +43,147 @@ const BRUSH_IDS = [
43
43
  ];
44
44
 
45
45
  const DEFAULT_DOC = {
46
- version: 2,
46
+ version: 3,
47
47
  width: 1024,
48
48
  height: 1024,
49
49
  background: "#ffffff",
50
50
  activeLayer: "l1",
51
51
  seq: 0,
52
+ groups: [],
52
53
  layers: [
53
- { id: "l1", name: DEFAULT_LAYER_NAME, visible: true, opacity: 1, blend: "normal", strokes: [] },
54
+ { id: "l1", name: DEFAULT_LAYER_NAME, visible: true, opacity: 1, blend: "normal", role: "base", groupId: "g_color", strokes: [] },
54
55
  ],
55
56
  redo: [],
56
57
  };
57
58
 
59
+ // ---- 图层栈(v3):组 → role → 层;顺序常量是渲染与插入位置的唯一依据 ----
60
+ const GROUP_ORDER = ["ref", "sketch", "lineart", "color", "final"];
61
+ const ROLE_ORDER = {
62
+ sketch: ["sketch", "perspective"],
63
+ lineart: ["line", "lineColor", "occlusion"],
64
+ color: ["base", "shadow1", "shadow2", "lightblock"],
65
+ final: ["texture", "highlight", "iridescent", "atmosphere", "grade"],
66
+ };
67
+ const ROLES = ["ref", ...Object.values(ROLE_ORDER).flat()];
68
+ const ROLE_GROUP = {
69
+ ref: "ref",
70
+ sketch: "sketch", perspective: "sketch",
71
+ line: "lineart", lineColor: "lineart", occlusion: "lineart",
72
+ base: "color", shadow1: "color", shadow2: "color", lightblock: "color",
73
+ texture: "final", highlight: "final", iridescent: "final", atmosphere: "final", grade: "final",
74
+ };
75
+ const ROLE_BLEND = {
76
+ line: "multiply", lineColor: "normal", occlusion: "multiply",
77
+ shadow1: "multiply", shadow2: "multiply", lightblock: "overlay",
78
+ highlight: "screen", iridescent: "linear-dodge", atmosphere: "overlay",
79
+ };
80
+ const BLEND_MODES = ["normal", "multiply", "screen", "overlay", "soft-light", "linear-dodge"];
81
+ const ROLE_LABELS = {
82
+ sketch: "构图草稿", perspective: "透视辅助", line: "精线稿", lineColor: "线稿上色", occlusion: "闭塞线",
83
+ base: "固有色平铺", shadow1: "一级暗部", shadow2: "二级暗部", lightblock: "铺光大关系",
84
+ texture: "材质纹理", highlight: "高光", iridescent: "镭射反光", atmosphere: "氛围光效", grade: "调色调整",
85
+ };
86
+ const GROUP_LABELS = { ref: "参考", sketch: "草图", lineart: "线稿", color: "色稿", final: "成稿" };
87
+ const LEGACY_ROLE = {
88
+ "铺底": "base", "固有色": "base", "色块": "base", "底稿": "base",
89
+ "塑形": "shadow1", "暗部": "shadow1",
90
+ "过渡": "shadow2", "闭塞": "shadow2",
91
+ "收边": "line", "线稿": "line", "粗线": "line",
92
+ "点睛": "highlight", "高光": "highlight",
93
+ "笔触": "base", "绘画": "base",
94
+ };
95
+ const GROUP_TINT = "#8aa0b8";
96
+
97
+ /** 5 个语义组是图层栈的骨架:永远存在、id 固定、顺序即 GROUP_ORDER。 */
98
+ function defaultGroups() {
99
+ return GROUP_ORDER.map((kind) => ({
100
+ id: `g_${kind}`,
101
+ name: GROUP_LABELS[kind],
102
+ kind,
103
+ visible: true,
104
+ locked: false,
105
+ opacity: 1,
106
+ collapsed: false,
107
+ color: GROUP_TINT,
108
+ }));
109
+ }
110
+
111
+ /**
112
+ * 组唯一化 + 补齐 5 个骨架组;自定义组(kind=custom)保留在原位置。
113
+ * 同一 kind 出现多次时,第一个当骨架,其余降级成自定义组——不丢用户数据。
114
+ */
115
+ function normalizeGroups(raw) {
116
+ const list = [];
117
+ const seen = new Set();
118
+ const take = (input, forceKind) => {
119
+ if (!input || typeof input !== "object") return;
120
+ const kind = forceKind || (GROUP_ORDER.includes(input.kind) ? input.kind : "custom");
121
+ let id = String(input.id || "").trim();
122
+ if (!id || seen.has(id)) id = `g_${kind === "custom" ? "c" : kind}${list.length}${Math.random().toString(36).slice(2, 4)}`;
123
+ seen.add(id);
124
+ const label = kind === "custom" ? "图层组" : GROUP_LABELS[kind];
125
+ list.push({
126
+ id,
127
+ name: String(input.name || label).trim().slice(0, 30) || label,
128
+ kind,
129
+ visible: input.visible !== false,
130
+ locked: input.locked === true,
131
+ opacity: clamp01(input.opacity),
132
+ collapsed: input.collapsed === true,
133
+ color: typeof input.color === "string" ? input.color : GROUP_TINT,
134
+ });
135
+ };
136
+ (Array.isArray(raw) ? raw : []).forEach((g) => {
137
+ if (g && GROUP_ORDER.includes(g.kind) && list.some((x) => x.kind === g.kind)) take(g, "custom");
138
+ else take(g);
139
+ });
140
+ for (const kind of GROUP_ORDER) {
141
+ if (list.some((g) => g.kind === kind)) continue;
142
+ const prev = GROUP_ORDER[GROUP_ORDER.indexOf(kind) - 1];
143
+ const at = prev ? list.findIndex((g) => g.kind === prev) : -1;
144
+ const def = defaultGroups().find((g) => g.kind === kind);
145
+ let id = def.id;
146
+ let n = 2;
147
+ while (seen.has(id)) {
148
+ id = `${def.id}_${n}`;
149
+ n += 1;
150
+ }
151
+ seen.add(id);
152
+ list.splice(at + 1, 0, { ...def, id });
153
+ }
154
+ return list;
155
+ }
156
+
157
+ /** layers[] 是唯一 z 顺序,且同组必须连续;按组顺序稳定重排,组内相对顺序不动。 */
158
+ function orderLayers(layers, groups) {
159
+ const order = new Map((groups || []).map((g, i) => [g.id, i]));
160
+ return layers
161
+ .map((layer, i) => ({ layer, i, g: order.has(layer.groupId) ? order.get(layer.groupId) : -1 }))
162
+ .sort((a, b) => (a.g - b.g) || (a.i - b.i))
163
+ .map((x) => x.layer);
164
+ }
165
+
166
+ const roleOfName = (name) => LEGACY_ROLE[String(name || "").trim()] || null;
167
+ const groupOfRole = (role) => ROLE_GROUP[role] || "color";
168
+ const roleIndex = (role) => {
169
+ const group = groupOfRole(role);
170
+ const g = GROUP_ORDER.indexOf(group);
171
+ const r = (ROLE_ORDER[group] || []).indexOf(role);
172
+ return (g < 0 ? 99 : g) * 100 + (r < 0 ? 99 : r);
173
+ };
174
+ const blendOfRole = (role) => ROLE_BLEND[role] || "normal";
175
+ // paint 五步 → v3 图层栈
176
+ const PAINT_STAGE_ROLE = {
177
+ base: "base", block: "shadow1", blend: "shadow2", edge: "line", accent: "highlight",
178
+ sketch: "sketch", lineColor: "lineColor", occlusion: "occlusion", lightblock: "lightblock",
179
+ texture: "texture", iridescent: "iridescent", atmosphere: "atmosphere", grade: "grade",
180
+ };
181
+ const PAINT_STAGE_NAME = {
182
+ base: "固有色平铺", block: "一级暗部", blend: "二级暗部", edge: "精线稿", accent: "高光",
183
+ sketch: "构图草稿", lineColor: "线稿上色", occlusion: "闭塞线", lightblock: "铺光大关系",
184
+ texture: "材质纹理", iridescent: "镭射反光", atmosphere: "氛围光效", grade: "调色调整",
185
+ };
186
+
58
187
  /** 压回 0~1,非数字按 1 处理。 */
59
188
  function clamp01(value) {
60
189
  const n = Number(value);
@@ -148,6 +277,8 @@ function migrateDoc(parsed = {}) {
148
277
  : DEFAULT_DOC.background;
149
278
 
150
279
  let counter = 0;
280
+ const groups = normalizeGroups(parsed.groups);
281
+ const groupIds = new Set(groups.map((g) => g.id));
151
282
  const normalizeLayer = (layer, index) => {
152
283
  const strokes = Array.isArray(layer.strokes) ? layer.strokes : [];
153
284
  for (const s of strokes) {
@@ -159,15 +290,43 @@ function migrateDoc(parsed = {}) {
159
290
  }
160
291
  if (!s.id) s.id = `s${s.seq}`;
161
292
  }
293
+ const hasImage = layer.image && typeof layer.image.file === "string";
294
+ const namedRole = roleOfName(layer.name);
295
+ const role = ROLES.includes(layer.role)
296
+ ? layer.role
297
+ : (hasImage ? "ref" : (namedRole || "base"));
298
+ const wantGroup = String(layer.groupId || "").trim();
299
+ const groupId = groupIds.has(wantGroup)
300
+ ? wantGroup
301
+ : (groups.find((g) => g.kind === wantGroup || g.name === wantGroup) || {}).id || `g_${groupOfRole(role)}`;
302
+ // 旧文档的 paint 层按名字映射 role 时,normal 换成该 role 的默认混合模式
303
+ const blend = BLEND_MODES.includes(layer.blend) && !(namedRole && layer.blend === "normal" && !ROLES.includes(layer.role))
304
+ ? layer.blend
305
+ : blendOfRole(role);
306
+ const hueNum = Number(layer.hue);
162
307
  return {
163
308
  id: String(layer.id || `l${index + 1}`),
164
309
  name: String(layer.name || `图层 ${index + 1}`),
310
+ role,
311
+ groupId,
165
312
  visible: layer.visible !== false,
166
313
  opacity: clamp01(layer.opacity),
167
- blend: layer.blend === "multiply" ? "multiply" : "normal",
314
+ blend,
315
+ clipTo: typeof layer.clipTo === "string" && layer.clipTo ? layer.clipTo : null,
316
+ lockAlpha: layer.lockAlpha === true,
317
+ hue: Number.isFinite(hueNum) ? Math.max(-180, Math.min(180, Math.round(hueNum))) : 0,
318
+ grade: layer.grade && typeof layer.grade === "object"
319
+ ? {
320
+ brightness: Math.max(-1, Math.min(1, Number(layer.grade.brightness) || 0)),
321
+ contrast: Math.max(0, Math.min(3, Number(layer.grade.contrast) === undefined ? 1 : Number(layer.grade.contrast))),
322
+ saturation: Math.max(0, Math.min(3, Number(layer.grade.saturation) === undefined ? 1 : Number(layer.grade.saturation))),
323
+ hue: Math.max(-180, Math.min(180, Number(layer.grade.hue) || 0)),
324
+ }
325
+ : undefined,
326
+ locked: layer.locked === true,
168
327
  strokes,
169
328
  // 图片层:file 相对缓存目录(images/xxx.png),x/y/w/h 是它在画布上的落位
170
- image: layer.image && typeof layer.image.file === "string"
329
+ image: hasImage
171
330
  ? {
172
331
  file: String(layer.image.file).slice(0, 200),
173
332
  x: Number(layer.image.x) || 0,
@@ -182,7 +341,12 @@ function migrateDoc(parsed = {}) {
182
341
  const rawLayers = Array.isArray(parsed.layers) && parsed.layers.length > 0
183
342
  ? parsed.layers
184
343
  : [{ id: "l1", name: DEFAULT_LAYER_NAME, strokes: Array.isArray(parsed.strokes) ? parsed.strokes : [] }];
185
- const layers = rawLayers.map(normalizeLayer);
344
+ // v3 已存组内顺序:尊重它,只按组切块;老文档:先按 role 归位一次再切块
345
+ const normalized = rawLayers.map(normalizeLayer);
346
+ const layers = parsed.version >= 3 && Array.isArray(parsed.groups) && parsed.groups.length
347
+ ? orderLayers(normalized, groups)
348
+ : orderLayers(normalized.sort((a, b) => roleIndex(a.role) - roleIndex(b.role)), groups);
349
+ if (layers.length === 0) layers.push(normalizeLayer({ id: "l1", name: DEFAULT_LAYER_NAME }, 0));
186
350
 
187
351
  const redo = Array.isArray(parsed.redo)
188
352
  ? parsed.redo.filter((entry) => entry && entry.stroke).slice(-200)
@@ -210,12 +374,13 @@ function migrateDoc(parsed = {}) {
210
374
  }
211
375
 
212
376
  return {
213
- version: 2,
377
+ version: 3,
214
378
  width,
215
379
  height,
216
380
  background,
217
381
  activeLayer: layers.some((l) => l.id === parsed.activeLayer) ? parsed.activeLayer : layers[layers.length - 1].id,
218
382
  seq: counter,
383
+ groups,
219
384
  layers,
220
385
  redo,
221
386
  selection,
@@ -243,8 +408,10 @@ const PROTOCOL = `你可以用 \`paint_canvas\` 在界面里的一块真画布
243
408
  4. 每画几笔用 \`action=view\` 看一眼渲染结果(返回 PNG 路径、每层的包围盒与覆盖率),不要假设画对了。
244
409
  要贴脸看细节就带 \`rect=[x,y,w,h]\` 与 \`zoom=2~4\`;只看某一层就带 \`layer="线稿"\`。
245
410
  5. 画错用 \`action=undo\` 撤掉最近一笔,撤多了用 \`action=redo\` 回来;要整幅重来才用 \`action=clear\`。
246
- 6. 图层不只是画布边界:\`action=layer layerOp=add name="上色"\` 建层,\`layerOp=set\` 改名字/显隐/\`layerOpacity\`/\`blend\`/\`locked\`,
247
- \`layerOp=select\` 切成当前层,\`layerOp=list\` 看全部(含每层的图片信息和笔迹数)。
411
+ 6. 图层不只是画布边界:\`action=layer layerOp=add name="上色"\` 建层,\`layerOp=set\` 改名字/显隐/\`layerOpacity\`/\`blend\`/\`locked\`/\`role\`/\`clipTo\`/\`lockAlpha\`/\`hue\`,
412
+ \`layerOp=select\` 切成当前层,\`layerOp=list\` 看全部(含每层的 role、blend、图片信息和笔迹数)。
413
+ **一次只画一层**;v3 图层栈由 role 决定 z 高度与默认混合模式:line/shadow1/shadow2=multiply,highlight=screen,lightblock/atmosphere=overlay,iridescent=linear-dodge,其余 normal。
414
+ 不要再自己算"先画哪层"——建层时给 \`role\`,位置会自动插对。\`clipTo\` 指向显式层 id(跨组也成立),\`lockAlpha=true\` 锁透明像素,\`hue\` 只转本层色相。
248
415
  想让某层淡一点就 \`layerOpacity=0.4\`,想做叠加效果就 \`blend=multiply\`;把参考图那一层 \`locked=true\` 就盖不上去也擦不掉。
249
416
  7. 图片当底稿:\`action=import path="D:\\\\ref\\\\pose.png"\` 会把图存进缓存目录的 images/ 并压成**最底层**(图层 1),
250
417
  默认 contain(整张居中放进画布);之后正常 draw 就是描图。导入后图层里带 \`image\` 字段。
@@ -252,7 +419,7 @@ const PROTOCOL = `你可以用 \`paint_canvas\` 在界面里的一块真画布
252
419
 
253
420
  **最省事的复刻就两条命令**(不需要自己估坐标、算配色、找缺口):
254
421
  - \`action=copy style=anime\`(或 lineart / flat / paint):自动抽轮廓、按区域配主色、建「色块 / 线稿」两层,描线默认走三次贝塞尔拟合(长弧一条曲线走完,比磨圆更像手画),每根线按量出来的原线宽落笔,并顺带跑一次 compare,直接给出覆盖率;要粗细分层加 \`splitLines=true\`;
255
- \`style=paint\` 是另一条路:不描闭合轮廓,先按大网格把整幅铺一遍色、再只在对比强的地方(脸、手、褶皱、火焰边缘)补细笔,颜色取局部均色、方向沿等色线——厚涂/渐变/火焰这类没有闭合边界的图用这个。默认 8000 笔出结构,\`maxStrokes=12000\` 才接近成图质感;默认不叠线稿(厚涂图没有清晰墨线,硬描会拖出大黑斜线),要叠给 \`lineart=true\`。
422
+ \`style=paint\` 是另一条路(0.1.44 起是**完整 14 层栈**,不是网格点彩):01 构图草稿(粗轮廓、锁定、低透明度)→ 03 精线稿(色阶边界、multiply)→ 04 线稿上色(clip 到 03、锁定透明像素)→ 05 闭塞线(比固有色暗很多的窄缝)→ 06 固有色平铺(按颜色+位置拆 06a 皮肤 / 06b 头发 / 06c 上装 / 06d 下装 / 06e 道具,大色块 fill)→ 07 一级暗部 / 08 二级暗部(tone map 暗区、multiply)→ 09 铺光大关系(亮区宽笔、overlay)→ 10 材质纹理(程序纸纹、clip 到 06)→ 11 高光(screen、clip 到 06)→ 12 镭射反光(沿高光、linear-dodge)→ 13 氛围光效(边缘宽笔、overlay)→ 14 调色调整(参数化,不落笔)。**一次只画一层**;\`paintStages="base,edge"\` 只跑其中几步(重跑自动 snapshot)。总笔数默认 4000,按 weight 分给各层。\`paintColors\` / \`paintBlocks\` 调固有色,\`paintStep\` 调笔距(默认 10)。paint 固定走宿主侧引擎,回报 \`computedBy=host\`、\`paintStats\`(覆盖率/场强/丢弃块)和 \`paintLayers\`(每层 role/blend/clipTo)。fix 的墨迹补漏不适用于彩稿;用 \`action=check\` 做关层自检和 06 覆盖率检查。
256
423
  - \`action=fix target=90 maxRounds=3\`:只看最漏的几块自动补描,到达标或没得补就停,返回每轮数字;落在色块洞里(高光)的缺口会跳过,不会把高光涂掉。
257
424
  - \`action=fill x=… y=…\`:点一片区域就按 palette 填色(边界来自已有笔迹,也能手动给 color),不用一笔笔涂;区域里的洞(高光、瞳孔)会按轮廓嵌套挖掉不涂;
258
425
  - \`action=select rect=[x,y,w,h]\` 或 \`points=[[x,y]…]\`(套索)把落笔限制在选区里,\`clearSelection=true\` 取消;
@@ -270,6 +437,8 @@ const PROTOCOL = `你可以用 \`paint_canvas\` 在界面里的一块真画布
270
437
  - 一笔要多处对称就用 \`mirror="x"\` 或 \`"y"\`;一次补很多笔用 \`batches=[…]\`。
271
438
  - 大面积改写前先 \`action=snapshot label="上色前"\`,画崩了 \`action=restore\` 整幅回退(比逐笔 undo 干净)。
272
439
 
440
+ **像素任务走哪条路**:裁切/取色/差分/主色/描线这些会在「浏览器面板」和「宿主 pixelops.js」之间自动选;\`copy style=paint\` 与 \`posterize\` 固定走宿主(两边只保留一份实现,避免结果不一致)。回报里的 \`computedBy\` 写 \`host\` 或 \`panel\`;想强制宿主排查就给 \`forceHeadless=true\`。宿主侧需要画布上有**图片层**当参考图,别把参考层删了。
441
+
273
442
  用户也可能同时在画布上画,所以落笔前先 doc 看一眼版本,必要时以最新内容为准。`;
274
443
 
275
444
  /** 每个缓存目录只留一份内存文档(见 Document.forDir)。挂在 globalThis 上,插件被重新加载也能复用。 */
@@ -464,32 +633,63 @@ class Document {
464
633
  this.save();
465
634
  }
466
635
 
467
- /** 按 id 或名字找一层。 */
636
+ /** 按 id、名字、或「组/层」路径找一层(组可用 id、kind 或名字)。 */
468
637
  layer(idOrName) {
469
638
  const key = String(idOrName || "").trim();
470
639
  if (!key) return null;
471
- return this.doc.layers.find((l) => l.id === key) || this.doc.layers.find((l) => l.name === key) || null;
640
+ const exact = this.doc.layers.find((l) => l.id === key) || this.doc.layers.find((l) => l.name === key);
641
+ if (exact) return exact;
642
+ for (const sep of ["/", ":"]) {
643
+ const at = key.lastIndexOf(sep);
644
+ if (at <= 0) continue;
645
+ const group = this.group(key.slice(0, at).trim());
646
+ if (!group) continue;
647
+ const name = key.slice(at + 1).trim();
648
+ const hit = this.doc.layers.find((l) => l.groupId === group.id && l.name === name);
649
+ if (hit) return hit;
650
+ }
651
+ return null;
472
652
  }
473
653
 
474
654
  active() {
475
655
  return this.layer(this.doc.activeLayer) || this.doc.layers[this.doc.layers.length - 1];
476
656
  }
477
657
 
478
- /** 取一层;不给或没有就建同名层(模型按名字落笔时用)。 */
658
+ /** 取一层;不给或没有就建同名层(模型按名字落笔时用)。支持「组/层」直接建进该组。 */
479
659
  ensureLayer(idOrName) {
480
660
  const key = String(idOrName || "").trim();
481
661
  if (!key) return this.active();
482
662
  const found = this.layer(key);
483
663
  if (found) return found;
664
+ let group = null;
665
+ let layerName = key;
666
+ for (const sep of ["/", ":"]) {
667
+ const at = key.lastIndexOf(sep);
668
+ if (at <= 0) continue;
669
+ const g = this.group(key.slice(0, at).trim());
670
+ if (g) {
671
+ group = g;
672
+ layerName = key.slice(at + 1).trim() || "图层";
673
+ break;
674
+ }
675
+ }
676
+ const role = roleOfName(layerName) || "base";
677
+ const groupId = group ? group.id : `g_${groupOfRole(role)}`;
484
678
  const layer = {
485
679
  id: `l${Date.now().toString(36)}${Math.random().toString(36).slice(2, 5)}`,
486
- name: key.slice(0, 40),
680
+ name: layerName.slice(0, 40),
681
+ role,
682
+ groupId,
487
683
  visible: true,
488
684
  opacity: 1,
489
- blend: "normal",
685
+ blend: blendOfRole(role),
686
+ clipTo: null,
687
+ lockAlpha: false,
688
+ hue: 0,
689
+ locked: false,
490
690
  strokes: [],
491
691
  };
492
- this.doc.layers.push(layer);
692
+ this.insertOrdered(layer);
493
693
  this.doc.activeLayer = layer.id;
494
694
  return layer;
495
695
  }
@@ -567,9 +767,15 @@ class Document {
567
767
  const layer = {
568
768
  id: `l${stamp}${rand}`,
569
769
  name: String(input.name || "").trim().slice(0, 40) || "图片 1",
770
+ role: "ref",
771
+ groupId: "g_ref",
570
772
  visible: true,
571
773
  opacity: clamp01(input.opacity),
572
774
  blend: "normal",
775
+ clipTo: null,
776
+ lockAlpha: false,
777
+ hue: 0,
778
+ locked: false,
573
779
  strokes: [],
574
780
  image: { file: path.posix.join("images", fileName), x, y, w, h },
575
781
  };
@@ -582,16 +788,198 @@ class Document {
582
788
  };
583
789
  }
584
790
 
585
- addLayer(name) {
791
+ /** 插到目标组的连续块里:组内按 role 高度找位置,组块本身不能被打散。 */
792
+ insertOrdered(layer) {
793
+ const layers = this.doc.layers;
794
+ const groups = this.doc.groups || [];
795
+ const want = layer.groupId;
796
+ const gAt = groups.findIndex((g) => g.id === want);
797
+ let start = layers.findIndex((l) => l.groupId === want);
798
+ if (start < 0) {
799
+ // 这一组还没有层:插在该组顺序对应的块起点(保持组块连续)
800
+ if (gAt < 0) {
801
+ layers.push(layer);
802
+ return;
803
+ }
804
+ const next = layers.findIndex((l) => {
805
+ const gi = groups.findIndex((g) => g.id === l.groupId);
806
+ return gi > gAt;
807
+ });
808
+ if (next < 0) layers.push(layer);
809
+ else layers.splice(next, 0, layer);
810
+ return;
811
+ }
812
+ let end = start;
813
+ while (end < layers.length && layers[end].groupId === want) end += 1;
814
+ for (let i = start; i < end; i += 1) {
815
+ if (roleIndex(layers[i].role) > roleIndex(layer.role)) {
816
+ layers.splice(i, 0, layer);
817
+ return;
818
+ }
819
+ }
820
+ layers.splice(end, 0, layer);
821
+ }
822
+
823
+ /** 组既能用 id、kind、名字找。 */
824
+ group(ref) {
825
+ const key = String(ref || "").trim();
826
+ if (!key) return null;
827
+ const list = this.doc.groups || [];
828
+ return list.find((g) => g.id === key) || list.find((g) => g.kind === key) || list.find((g) => g.name === key) || null;
829
+ }
830
+
831
+ addGroup(input = {}) {
832
+ const groups = this.doc.groups || (this.doc.groups = []);
833
+ const list = groups;
834
+ const layerList = this.doc.layers || [];
835
+ const kind = GROUP_ORDER.includes(input.kind) ? input.kind : "custom";
836
+ if (kind !== "custom" && list.some((g) => g.kind === kind)) throw new Error(`已经有 ${GROUP_LABELS[kind]} 组了`);
837
+ let id = String(input.id || "").trim();
838
+ if (!id || list.some((g) => g.id === id)) id = `g_c${Date.now().toString(36)}${Math.random().toString(36).slice(2, 4)}`;
839
+ const group = {
840
+ id,
841
+ name: String(input.name || (kind === "custom" ? "图层组" : GROUP_LABELS[kind])).trim().slice(0, 30) || "图层组",
842
+ kind,
843
+ visible: input.visible !== false,
844
+ locked: input.locked === true,
845
+ opacity: input.opacity === undefined ? 1 : clamp01(input.opacity),
846
+ collapsed: input.collapsed === true,
847
+ color: typeof input.color === "string" ? input.color : GROUP_TINT,
848
+ };
849
+ // 位置:after 指定的组之后;默认压最顶(即 layers 的最上面)
850
+ const afterRef = input.after !== undefined ? input.after : input.afterId;
851
+ const after = afterRef !== undefined ? this.group(afterRef) : null;
852
+ if (after) list.splice(list.indexOf(after) + 1, 0, group);
853
+ else list.push(group);
854
+ // layers 里也要留出这个组的空块:按组顺序重排即可(该组暂无层,天然为空)
855
+ this.doc.layers = orderLayers(layerList, list);
856
+ this.bump();
857
+ return group;
858
+ }
859
+
860
+ updateGroup(ref, patch = {}) {
861
+ const group = this.group(ref);
862
+ if (!group) throw new Error(`没有这个组:${ref}`);
863
+ if (typeof patch.name === "string" && patch.name.trim()) group.name = patch.name.trim().slice(0, 30);
864
+ if (patch.visible !== undefined) group.visible = patch.visible !== false;
865
+ if (patch.locked !== undefined) group.locked = patch.locked === true;
866
+ if (patch.opacity !== undefined) group.opacity = clamp01(patch.opacity);
867
+ if (patch.collapsed !== undefined) group.collapsed = patch.collapsed === true;
868
+ if (typeof patch.color === "string") group.color = patch.color;
869
+ this.bump();
870
+ return group;
871
+ }
872
+
873
+ /** 组上移/下移一格(layers 同步重排,保证组块顺序跟 groups[] 一致)。 */
874
+ moveGroup(ref, offset) {
875
+ const groups = this.doc.groups || [];
876
+ const group = this.group(ref);
877
+ if (!group) throw new Error(`没有这个组:${ref}`);
878
+ const from = groups.indexOf(group);
879
+ const to = Math.max(0, Math.min(groups.length - 1, from + (Number(offset) || 0)));
880
+ if (to !== from) {
881
+ groups.splice(from, 1);
882
+ groups.splice(to, 0, group);
883
+ this.doc.layers = orderLayers(this.doc.layers, groups);
884
+ this.bump();
885
+ }
886
+ return { group, index: to };
887
+ }
888
+
889
+ /** 删组:默认只删空组;force=true 时组内层挪到相邻组,再删。 */
890
+ removeGroup(ref, opts = {}) {
891
+ const groups = this.doc.groups || [];
892
+ const group = this.group(ref);
893
+ if (!group) throw new Error(`没有这个组:${ref}`);
894
+ if (group.kind !== "custom" && !opts.force) throw new Error(`「${group.name}」是图层栈骨架组,不能删`);
895
+ if (groups.length <= 1) throw new Error("至少留一组");
896
+ const inside = this.doc.layers.filter((l) => l.groupId === group.id);
897
+ if (inside.length && !opts.force) throw new Error(`「${group.name}」里还有 ${inside.length} 层:先用 force 把层并到相邻组`);
898
+ if (inside.length) {
899
+ const at = groups.indexOf(group);
900
+ const fallback = groups[at - 1] || groups[at + 1];
901
+ if (!fallback) throw new Error("没有相邻组可以接收这些层");
902
+ for (const layer of inside) layer.groupId = fallback.id;
903
+ }
904
+ groups.splice(groups.indexOf(group), 1);
905
+ this.doc.layers = orderLayers(this.doc.layers, groups);
906
+ this.bump();
907
+ return { id: group.id, moved: inside.length };
908
+ }
909
+
910
+ /** 层跨组移动:落到目标组块内(index 指定组内位置,缺省按 role 找位置)。 */
911
+ moveLayerToGroup(layerRef, groupRef, index) {
912
+ const layer = this.layer(layerRef);
913
+ if (!layer) throw new Error(`没有这一层:${layerRef}`);
914
+ const group = this.group(groupRef);
915
+ if (!group) throw new Error(`没有这个组:${groupRef}`);
916
+ this.doc.layers = this.doc.layers.filter((l) => l !== layer);
917
+ layer.groupId = group.id;
918
+ const start = this.doc.layers.findIndex((l) => l.groupId === group.id);
919
+ if (start < 0) {
920
+ // 这一组还是空的:按组序落位,别甩到数组末尾
921
+ this.insertOrdered(layer);
922
+ } else {
923
+ let end = start;
924
+ while (end < this.doc.layers.length && this.doc.layers[end].groupId === group.id) end += 1;
925
+ const want = Number(index);
926
+ const at = Number.isFinite(want) ? Math.max(start, Math.min(end, start + Math.round(want))) : end;
927
+ this.doc.layers.splice(at, 0, layer);
928
+ }
929
+ this.bump();
930
+ return layer;
931
+ }
932
+
933
+ /** 层在当前组内上移/下移(不跨组)。 */
934
+ moveLayer(ref, offset) {
935
+ const layer = this.layer(ref);
936
+ if (!layer) throw new Error(`没有这一层:${ref}`);
937
+ const layers = this.doc.layers;
938
+ const start = layers.findIndex((l) => l.groupId === layer.groupId);
939
+ let end = start;
940
+ while (end < layers.length && layers[end].groupId === layer.groupId) end += 1;
941
+ const from = layers.indexOf(layer);
942
+ const to = Math.max(start, Math.min(end - 1, from + (Number(offset) || 0)));
943
+ if (to !== from) {
944
+ layers.splice(from, 1);
945
+ layers.splice(to, 0, layer);
946
+ this.bump();
947
+ }
948
+ return { layer, index: to - start };
949
+ }
950
+
951
+ addLayer(name, opts = {}) {
952
+ const role = ROLES.includes(opts.role) ? opts.role : (roleOfName(name) || "base");
953
+ const named = this.group(opts.groupId);
954
+ const groupId = named ? named.id : `g_${groupOfRole(role)}`;
955
+ const blend = BLEND_MODES.includes(opts.blend) ? opts.blend : blendOfRole(role);
956
+ const hueNum = Number(opts.hue);
586
957
  const layer = {
587
958
  id: `l${Date.now().toString(36)}${Math.random().toString(36).slice(2, 5)}`,
588
- name: String(name || `图层 ${this.doc.layers.length + 1}`).trim().slice(0, 40) || `图层 ${this.doc.layers.length + 1}`,
959
+ name: String(name || ROLE_LABELS[role] || `图层 ${this.doc.layers.length + 1}`).trim().slice(0, 40) || `图层 ${this.doc.layers.length + 1}`,
960
+ role,
961
+ groupId,
589
962
  visible: true,
590
- opacity: 1,
591
- blend: "normal",
963
+ opacity: opts.opacity === undefined ? 1 : clamp01(opts.opacity),
964
+ blend,
965
+ clipTo: typeof opts.clipTo === "string" && opts.clipTo ? opts.clipTo : null,
966
+ lockAlpha: opts.lockAlpha === true,
967
+ hue: Number.isFinite(hueNum) ? Math.max(-180, Math.min(180, Math.round(hueNum))) : 0,
968
+ grade: opts.grade && typeof opts.grade === "object" ? opts.grade : undefined,
969
+ locked: opts.locked === true,
592
970
  strokes: [],
593
971
  };
594
- this.doc.layers.push(layer);
972
+ this.insertOrdered(layer);
973
+ // index 给的是组内第几位(0=组内最底),把默认的 role 落位覆盖掉
974
+ if (opts.index !== undefined && opts.index !== null && Number.isFinite(Number(opts.index))) {
975
+ const layers = this.doc.layers;
976
+ const start = layers.findIndex((l) => l.groupId === layer.groupId);
977
+ let end = start;
978
+ while (end < layers.length && layers[end].groupId === layer.groupId) end += 1;
979
+ layers.splice(layers.indexOf(layer), 1);
980
+ const at = Math.max(start, Math.min(end - 1, start + Math.max(0, Math.round(Number(opts.index)))));
981
+ layers.splice(at, 0, layer);
982
+ }
595
983
  this.doc.activeLayer = layer.id;
596
984
  this.bump();
597
985
  return layer;
@@ -603,8 +991,31 @@ class Document {
603
991
  if (typeof patch.name === "string" && patch.name.trim()) layer.name = patch.name.trim().slice(0, 40);
604
992
  if (patch.visible !== undefined) layer.visible = patch.visible !== false;
605
993
  if (patch.opacity !== undefined) layer.opacity = clamp01(patch.opacity);
606
- if (patch.blend !== undefined) layer.blend = patch.blend === "multiply" ? "multiply" : "normal";
994
+ if (patch.blend !== undefined) layer.blend = BLEND_MODES.includes(patch.blend) ? patch.blend : "normal";
607
995
  if (patch.locked !== undefined) layer.locked = patch.locked === true;
996
+ if (patch.role !== undefined && ROLES.includes(patch.role)) {
997
+ layer.role = patch.role;
998
+ // 骨架组跟着 role 走;自定义组是用户自己归的类,不被 role 顶掉
999
+ const current = this.group(layer.groupId);
1000
+ if (!current || current.kind !== "custom") layer.groupId = `g_${groupOfRole(patch.role)}`;
1001
+ this.doc.layers = this.doc.layers.filter((l) => l !== layer);
1002
+ this.insertOrdered(layer);
1003
+ }
1004
+ if (patch.groupId !== undefined) {
1005
+ const target = this.group(patch.groupId);
1006
+ if (target && target.id !== layer.groupId) {
1007
+ this.doc.layers = this.doc.layers.filter((l) => l !== layer);
1008
+ layer.groupId = target.id;
1009
+ this.insertOrdered(layer);
1010
+ }
1011
+ }
1012
+ if (patch.clipTo !== undefined) layer.clipTo = typeof patch.clipTo === "string" && patch.clipTo ? patch.clipTo : null;
1013
+ if (patch.lockAlpha !== undefined) layer.lockAlpha = patch.lockAlpha === true;
1014
+ if (patch.grade !== undefined && patch.grade && typeof patch.grade === "object") layer.grade = patch.grade;
1015
+ if (patch.hue !== undefined) {
1016
+ const hueNum = Number(patch.hue);
1017
+ layer.hue = Number.isFinite(hueNum) ? Math.max(-180, Math.min(180, Math.round(hueNum))) : 0;
1018
+ }
608
1019
  if (patch.active === true) this.doc.activeLayer = layer.id;
609
1020
  this.bump();
610
1021
  return layer;
@@ -623,11 +1034,24 @@ class Document {
623
1034
  append(strokes, layerRef) {
624
1035
  const layer = layerRef ? this.ensureLayer(layerRef) : this.active();
625
1036
  if (layer.locked === true) throw new Error(`图层「${layer.name}」被锁定,画不上去;要动它先 action=layer layerOp=set locked=false`);
1037
+ // 锁定透明像素:裁剪基线 = 落笔前的层内容(不能用落笔后的 alpha,会自举扩张)
1038
+ const baseline = layer.lockAlpha === true ? layer.strokes.slice() : null;
1039
+ if (baseline && baseline.length === 0 && strokes.length > 0) {
1040
+ throw new Error(`图层「${layer.name}」锁定了透明像素但本来就没有内容:先关掉 lockAlpha,铺一层底色再锁`);
1041
+ }
626
1042
  const sel = this.doc.selection || null;
627
1043
  let added = 0;
628
1044
  for (const s of strokes) {
629
1045
  // 有选区就只保留框内的点,一笔越界会被切成几段
630
- const parts = sel && s.mode !== "fill" ? clipPoints(s.points || [], sel) : [s.points];
1046
+ let parts = sel && s.mode !== "fill" ? clipPoints(s.points || [], sel) : [s.points];
1047
+ if (baseline) {
1048
+ if (s.mode === "fill") {
1049
+ const solid = (s.points || []).every((p) => pointInBaseline(baseline, Number(p[0]), Number(p[1])));
1050
+ parts = solid ? parts : [];
1051
+ } else {
1052
+ parts = parts.flatMap((points) => clipToBaseline(points || [], baseline));
1053
+ }
1054
+ }
631
1055
  for (const points of parts) {
632
1056
  if (!points || points.length < 2) continue;
633
1057
  this.doc.seq += 1;
@@ -780,22 +1204,40 @@ class Document {
780
1204
  const colors = new Set();
781
1205
  let strokes = 0;
782
1206
  let points = 0;
1207
+ const groups = (this.doc.groups || []).map((g) => ({
1208
+ id: g.id,
1209
+ name: g.name,
1210
+ kind: g.kind,
1211
+ visible: g.visible !== false,
1212
+ locked: g.locked === true,
1213
+ opacity: g.opacity === undefined ? 1 : g.opacity,
1214
+ collapsed: g.collapsed === true,
1215
+ }));
783
1216
  const layers = this.doc.layers.map((l) => {
784
1217
  strokes += l.strokes.length;
785
1218
  points += l.strokes.reduce((n, s) => n + (s.points ? s.points.length : 0), 0);
786
1219
  for (const s of l.strokes) colors.add(s.color);
1220
+ const ready = l.strokes.length > 0 || Boolean(l.image);
787
1221
  return {
788
1222
  id: l.id,
789
1223
  name: l.name,
790
- visible: l.visible,
1224
+ role: l.role || "base",
1225
+ groupId: l.groupId || null,
1226
+ visible: l.visible !== false,
791
1227
  opacity: l.opacity,
792
- blend: l.blend,
1228
+ blend: l.blend || "normal",
1229
+ clipTo: l.clipTo || null,
1230
+ lockAlpha: l.lockAlpha === true,
1231
+ hue: l.hue || 0,
1232
+ grade: l.grade || null,
793
1233
  locked: l.locked === true,
1234
+ ready,
794
1235
  strokes: l.strokes.length,
795
1236
  image: l.image ? { file: l.image.file, x: l.image.x, y: l.image.y, w: l.image.w, h: l.image.h } : null,
796
1237
  };
797
1238
  });
798
1239
  return {
1240
+ version: this.doc.version || 3,
799
1241
  width: this.doc.width,
800
1242
  height: this.doc.height,
801
1243
  background: this.doc.background,
@@ -805,6 +1247,7 @@ class Document {
805
1247
  points,
806
1248
  colors: [...colors].slice(0, 12),
807
1249
  bounds: this.bounds(),
1250
+ groups,
808
1251
  layers,
809
1252
  selection: this.doc.selection || null,
810
1253
  redo: (this.doc.redo || []).length,
@@ -1017,6 +1460,53 @@ function pointInPoly(x, y, pts) {
1017
1460
  return inside;
1018
1461
  }
1019
1462
 
1463
+ /** 点在一条笔迹的几何范围内(锁定透明像素时的近似裁剪)。 */
1464
+ function pointInStrokeGeometry(stroke, x, y) {
1465
+ if (!Array.isArray(stroke.points) || stroke.points.length === 0) return false;
1466
+ if (stroke.mode === "fill") {
1467
+ if (!pointInPoly(x, y, stroke.points)) return false;
1468
+ for (const hole of stroke.holes || []) if (pointInPoly(x, y, hole)) return false;
1469
+ return true;
1470
+ }
1471
+ const r = Math.max(1, (Number(stroke.size) || 8) / 2) + 1;
1472
+ const pts = stroke.points;
1473
+ if (pts.length === 1) return Math.hypot(x - pts[0][0], y - pts[0][1]) <= r;
1474
+ for (let i = 1; i < pts.length; i += 1) {
1475
+ const ax = Number(pts[i - 1][0]);
1476
+ const ay = Number(pts[i - 1][1]);
1477
+ const bx = Number(pts[i][0]);
1478
+ const by = Number(pts[i][1]);
1479
+ const dx = bx - ax;
1480
+ const dy = by - ay;
1481
+ const len2 = dx * dx + dy * dy;
1482
+ const t = len2 > 0 ? Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / len2)) : 0;
1483
+ if (Math.hypot(x - (ax + dx * t), y - (ay + dy * t)) <= r) return true;
1484
+ }
1485
+ return false;
1486
+ }
1487
+
1488
+ function pointInBaseline(baseline, x, y) {
1489
+ for (const stroke of baseline) if (pointInStrokeGeometry(stroke, x, y)) return true;
1490
+ return false;
1491
+ }
1492
+
1493
+ /** 把点序列裁成「落在基线笔迹里」的连续段。 */
1494
+ function clipToBaseline(points, baseline) {
1495
+ const runs = [];
1496
+ let cur = [];
1497
+ for (const p of points) {
1498
+ const x = Number(p[0]);
1499
+ const y = Number(p[1]);
1500
+ if (pointInBaseline(baseline, x, y)) cur.push(p);
1501
+ else {
1502
+ if (cur.length >= 2) runs.push(cur);
1503
+ cur = [];
1504
+ }
1505
+ }
1506
+ if (cur.length >= 2) runs.push(cur);
1507
+ return runs;
1508
+ }
1509
+
1020
1510
  /** 这点是不是落在某块色块挖的洞里(洞是参考图的高光,不该往上涂)。 */
1021
1511
  function inFillHole(doc, x, y) {
1022
1512
  for (const layer of doc.layers || []) {
@@ -1087,10 +1577,16 @@ function layerDetails(docx) {
1087
1577
  layers.push({
1088
1578
  id: layer.id,
1089
1579
  name: layer.name,
1580
+ role: layer.role || "base",
1581
+ groupId: layer.groupId || null,
1090
1582
  kind: layer.image ? "image" : "draw",
1091
1583
  visible: layer.visible !== false,
1092
1584
  opacity: layer.opacity === undefined ? 1 : layer.opacity,
1093
1585
  blend: layer.blend || "normal",
1586
+ clipTo: layer.clipTo || null,
1587
+ lockAlpha: layer.lockAlpha === true,
1588
+ hue: layer.hue || 0,
1589
+ grade: layer.grade || null,
1094
1590
  locked: layer.locked === true,
1095
1591
  strokes: (layer.strokes || []).length,
1096
1592
  bbox: has ? { x: Math.round(minX), y: Math.round(minY), w: Math.round(maxX - minX), h: Math.round(maxY - minY) } : null,
@@ -1110,6 +1606,45 @@ function mirrorPoints(points, axis, width, height) {
1110
1606
  });
1111
1607
  }
1112
1608
 
1609
+ /**
1610
+ * 工具返回值必须是「无损 JSON」:DSH 会拒绝 undefined、NaN/Infinity、-0、类实例。
1611
+ * 画布坐标用 Math.round 时,-0.4 会变成 -0(JSON.stringify 又写成 0),
1612
+ * 于是 action=doc/view 这种纯读动作也会报「value is not lossless JSON」。
1613
+ * 这里在工具出口统一洗一遍,别让模型以为操作没发生。
1614
+ */
1615
+ function jsonSafe(value, seen = new Set()) {
1616
+ if (value === null) return null;
1617
+ const type = typeof value;
1618
+ if (type === "number") {
1619
+ if (Object.is(value, -0)) return 0;
1620
+ return Number.isFinite(value) ? value : null;
1621
+ }
1622
+ if (type === "string" || type === "boolean") return value;
1623
+ if (type === "undefined" || type === "function" || type === "symbol") return undefined;
1624
+ if (type === "bigint") return value.toString();
1625
+ if (type !== "object") return null;
1626
+ if (seen.has(value)) return null;
1627
+ if (Array.isArray(value)) {
1628
+ seen.add(value);
1629
+ const out = value.map((item) => {
1630
+ const safe = jsonSafe(item, seen);
1631
+ return safe === undefined ? null : safe;
1632
+ });
1633
+ seen.delete(value);
1634
+ return out;
1635
+ }
1636
+ if (value instanceof Date) return value.toISOString();
1637
+ if (ArrayBuffer.isView(value)) return Array.from(value);
1638
+ seen.add(value);
1639
+ const out = {};
1640
+ for (const key of Object.keys(value)) {
1641
+ const safe = jsonSafe(value[key], seen);
1642
+ if (safe !== undefined) out[key] = safe;
1643
+ }
1644
+ seen.delete(value);
1645
+ return out;
1646
+ }
1647
+
1113
1648
  function json(res, status, body) {
1114
1649
  const text = JSON.stringify(body);
1115
1650
  res.writeHead(status, {
@@ -1245,7 +1780,7 @@ export function apply(ctx, config = {}) {
1245
1780
  jobStats.done += 1;
1246
1781
  jobStats.headless += 1;
1247
1782
  jobStats.last = { kind, at: Date.now(), mode: "host" };
1248
- return out;
1783
+ return { ...out, computedBy: "host" };
1249
1784
  } catch (err) {
1250
1785
  jobStats.failed += 1;
1251
1786
  return { ok: false, error: `宿主侧算 ${kind} 失败:${(err && err.message) || err}`, headless: true };
@@ -1289,7 +1824,12 @@ export function apply(ctx, config = {}) {
1289
1824
  return layer;
1290
1825
  };
1291
1826
 
1292
- const runPixelJob = (kind, params = {}, timeoutMs) => new Promise((resolve) => {
1827
+ const runPixelJob = (kind, params = {}, timeoutMs, forceHeadless = false) => new Promise((resolve) => {
1828
+ if (forceHeadless) {
1829
+ // paint / posterize 这类新管线只在宿主侧有一份实现:不交给浏览器,避免两套算法不一致
1830
+ runHeadlessPixel(kind, params).then(resolve);
1831
+ return;
1832
+ }
1293
1833
  if (config.headless !== false && HEADLESS_KINDS.has(kind) && !panelLive()) {
1294
1834
  // 没有面板 → 直接宿主侧算,不再干等 5 秒超时
1295
1835
  runHeadlessPixel(kind, params).then((out) => {
@@ -1337,11 +1877,61 @@ export function apply(ctx, config = {}) {
1337
1877
  if (payload && payload.ok) jobStats.done += 1;
1338
1878
  else if (payload && payload.error === "timeout") jobStats.timeout += 1;
1339
1879
  else jobStats.failed += 1;
1340
- jobStats.last = { id: job.id, kind: job.kind, at: Date.now() };
1341
- job.settle(payload || { ok: false, error: "前端没有回结果" });
1880
+ jobStats.last = { id: job.id, kind: job.kind, at: Date.now(), mode: "panel" };
1881
+ const result = payload || { ok: false, error: "前端没有回结果" };
1882
+ if (result.ok && !result.computedBy) result.computedBy = "panel";
1883
+ job.settle(result);
1342
1884
  return true;
1343
1885
  };
1344
1886
 
1887
+ /**
1888
+ * 关层自检:逐层隐藏后和全图比,变化最大的层可能是「承载太多」;
1889
+ * 同时看 06 固有色覆盖率——没铺到 85% 就提示先别进成稿。
1890
+ */
1891
+ const checkLayers = async () => {
1892
+ const { rasterDoc } = await import("./pixels.js");
1893
+ const resolve = (file) => path.resolve(dir, file);
1894
+ const doc = docs.doc;
1895
+ const artDoc = { ...doc, layers: (doc.layers || []).filter((l) => !l.image) };
1896
+ const total = (doc.width || 1024) * (doc.height || 1024);
1897
+ const full = await rasterDoc(artDoc, { resolve });
1898
+ const rows = [];
1899
+ for (const layer of artDoc.layers || []) {
1900
+ if (layer.visible === false) continue;
1901
+ if (!(layer.strokes || []).length) continue;
1902
+ const alone = await rasterDoc({ ...artDoc, layers: [{ ...layer }] }, { resolve });
1903
+ let alphaPx = 0;
1904
+ for (let i = 3; i < alone.data.length; i += 4) if (alone.data[i] > 16) alphaPx += 1;
1905
+ const areaPct = Number(((alphaPx / total) * 100).toFixed(1));
1906
+ let impactPct = areaPct;
1907
+ if (areaPct >= 2) {
1908
+ const hidden = await rasterDoc({ ...artDoc, layers: artDoc.layers.map((l) => (l.id === layer.id ? { ...l, visible: false } : l)) }, { resolve });
1909
+ let diff = 0;
1910
+ for (let i = 0; i < full.data.length; i += 4) {
1911
+ if (Math.abs(full.data[i] - hidden.data[i]) + Math.abs(full.data[i + 1] - hidden.data[i + 1]) + Math.abs(full.data[i + 2] - hidden.data[i + 2]) + Math.abs(full.data[i + 3] - hidden.data[i + 3]) > 12) diff += 1;
1912
+ }
1913
+ impactPct = Number(((diff / total) * 100).toFixed(1));
1914
+ }
1915
+ rows.push({ id: layer.id, name: layer.name, role: layer.role || "base", areaPct, impactPct });
1916
+ }
1917
+ rows.sort((a, b) => b.impactPct - a.impactPct);
1918
+ const baseLayers = (artDoc.layers || []).filter((l) => l.role === "base" && l.visible !== false);
1919
+ let basePct = 0;
1920
+ if (baseLayers.length) {
1921
+ const baseSurf = await rasterDoc({ ...artDoc, layers: baseLayers }, { resolve });
1922
+ let basePx = 0;
1923
+ for (let i = 3; i < full.data.length; i += 4) if (full.data[i] > 16) basePx += 1;
1924
+ let covered = 0;
1925
+ for (let i = 3; i < baseSurf.data.length; i += 4) if (baseSurf.data[i] > 16) covered += 1;
1926
+ basePct = basePx ? Number(((covered / basePx) * 100).toFixed(1)) : 0;
1927
+ }
1928
+ const warnings = [];
1929
+ for (const row of rows) if (row.impactPct > 35) warnings.push(`「${row.name}」关掉后画面变化 ${row.impactPct}%:这层承载太多,建议拆`);
1930
+ if (basePct > 0 && basePct < 85) warnings.push(`固有色只盖住 ${basePct}% 的画面:先补 06,再进高光/纹理`);
1931
+ if (rows.length > 0 && rows[0].impactPct > 60) warnings.push(`「${rows[0].name}」是画面主体,删/关前先 snapshot`);
1932
+ return { ok: true, baseCoveragePct: basePct, layers: rows, warnings };
1933
+ };
1934
+
1345
1935
  /** 前端回传的 PNG dataURL 落盘,返回可给 read_image 的绝对路径。 */
1346
1936
  const writePng = (dataUrl, prefix) => {
1347
1937
  const m = /^data:image\/png;base64,(.+)$/.exec(String(dataUrl || ""));
@@ -1595,7 +2185,16 @@ export function apply(ctx, config = {}) {
1595
2185
  if (typeof tick.unref === "function") tick.unref();
1596
2186
  }
1597
2187
  }
1598
- return { ok: true, sessionId: id, bound: didBind, pending: !didBind, variant: meta.variant || null };
2188
+ return {
2189
+ ok: true,
2190
+ sessionId: id,
2191
+ bound: didBind,
2192
+ pending: !didBind,
2193
+ variant: meta.variant || null,
2194
+ note: didBind
2195
+ ? "已绑定:paint_canvas 会出现在**下一轮**工具表里(运行中的 agent 不会动态拿到新工具)。这一轮如果还看不见,继续用 /canvas-api/*,或让用户再发一条消息。"
2196
+ : "还没绑定:先看 /diagnostics 的 scope.bound 与 tools.bindError,期间用 /canvas-api/* 顶一下。",
2197
+ };
1599
2198
  };
1600
2199
 
1601
2200
  /** 前端关掉画界时调用:留 15 秒宽限,切标签时不会来回解绑/重绑。 */
@@ -1754,6 +2353,33 @@ export function apply(ctx, config = {}) {
1754
2353
  }
1755
2354
  return;
1756
2355
  }
2356
+ // 关层自检:逐层隐藏 diff + 06 覆盖率,结果给面板/工具
2357
+ if (route === "/check" && req.method === "GET") {
2358
+ try {
2359
+ const result = await checkLayers();
2360
+ json(res, 200, result);
2361
+ } catch (err) {
2362
+ json(res, 500, { ok: false, error: String((err && err.message) || err) });
2363
+ }
2364
+ return;
2365
+ }
2366
+ // 绕过工具层直接跑宿主像素引擎(工具这一轮还没挂上时用;返回结果,不落画布)。
2367
+ // POST {kind:"copy", params:{style:"paint", ...}} / {kind:"posterize", ...}
2368
+ if (route === "/pixel" && req.method === "POST") {
2369
+ try {
2370
+ const body = JSON.parse((await readBody(req)) || "{}");
2371
+ const kind = String(body.kind || "").trim();
2372
+ if (!HEADLESS_KINDS.has(kind)) {
2373
+ json(res, 400, { ok: false, error: `不支持的像素任务:${kind || "(空)"}(可用:${[...HEADLESS_KINDS].join(" / ")})` });
2374
+ return;
2375
+ }
2376
+ const out = await runHeadlessPixel(kind, body.params || body.args || {});
2377
+ json(res, 200, { ok: Boolean(out && out.ok), ...(out || {}) });
2378
+ } catch (err) {
2379
+ json(res, 500, { ok: false, error: String((err && err.message) || err) });
2380
+ }
2381
+ return;
2382
+ }
1757
2383
  if (route === "/doc" && req.method === "GET") {
1758
2384
  json(res, 200, {
1759
2385
  ok: true,
@@ -1865,11 +2491,14 @@ export function apply(ctx, config = {}) {
1865
2491
  color: typeof s.color === "string" ? s.color : "#111111",
1866
2492
  size: Math.max(1, Math.min(400, Number(s.size) || 8)),
1867
2493
  opacity: s.opacity === undefined ? 1 : Math.max(0.02, Math.min(1, Number(s.opacity))),
1868
- mode: s.mode === "eraser" ? "eraser" : "brush",
2494
+ mode: s.mode === "eraser" ? "eraser" : (s.mode === "fill" ? "fill" : "brush"),
1869
2495
  brush: s.brush,
1870
2496
  taper: s.taper === true,
1871
2497
  minSize: s.minSize,
1872
2498
  points: normalizePoints(s.points, docs.doc.width, docs.doc.height),
2499
+ holes: Array.isArray(s.holes) && s.holes.length
2500
+ ? s.holes.map((hole) => normalizePoints(hole, docs.doc.width, docs.doc.height))
2501
+ : undefined,
1873
2502
  }));
1874
2503
  const layer = docs.append(normalized, body.layer);
1875
2504
  json(res, 200, {
@@ -1894,9 +2523,28 @@ export function apply(ctx, config = {}) {
1894
2523
  } else if (body.op === "redo") {
1895
2524
  result = docs.redo(Math.max(1, Math.round(Number(body.count) || 1)));
1896
2525
  } else if (body.op === "layer.add") {
1897
- result = docs.addLayer(body.name);
2526
+ result = docs.addLayer(body.name, body);
1898
2527
  } else if (body.op === "layer.set") {
1899
2528
  result = docs.updateLayer(body.id, body.patch || body);
2529
+ } else if (body.op === "layer.group") {
2530
+ result = docs.updateGroup(body.groupId || body.id, {
2531
+ visible: body.visible,
2532
+ opacity: body.opacity,
2533
+ name: body.name,
2534
+ collapsed: body.collapsed,
2535
+ locked: body.locked,
2536
+ color: body.color,
2537
+ });
2538
+ } else if (body.op === "group.add") {
2539
+ result = docs.addGroup(body);
2540
+ } else if (body.op === "group.remove") {
2541
+ result = docs.removeGroup(body.groupId || body.id, { force: body.force === true });
2542
+ } else if (body.op === "group.move") {
2543
+ result = docs.moveGroup(body.groupId || body.id, body.offset === undefined ? 1 : body.offset);
2544
+ } else if (body.op === "group.moveLayer") {
2545
+ result = docs.moveLayerToGroup(body.layer || body.layerId, body.groupId, body.index);
2546
+ } else if (body.op === "layer.move") {
2547
+ result = docs.moveLayer(body.layer || body.id, body.offset);
1900
2548
  } else if (body.op === "layer.remove") {
1901
2549
  result = docs.removeLayer(body.id);
1902
2550
  } else {
@@ -2086,8 +2734,8 @@ export function apply(ctx, config = {}) {
2086
2734
  properties: {
2087
2735
  action: {
2088
2736
  type: "string",
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"],
2090
- description: "要执行的动作。new 是另起一幅(可先保存当前、也可用图片建画布)。",
2737
+ enum: ["doc", "check", "copy", "posterize", "fix", "fill", "draw", "view", "ref", "trace", "pick", "compare", "palette", "select", "snapshot", "restore", "undo", "redo", "clear", "layer", "group", "import", "canvas", "export", "new"],
2738
+ description: "要执行的动作。new 是另起一幅(可先保存当前、也可用图片建画布);group 管图层组(建组/删组/改组/移层)。",
2091
2739
  },
2092
2740
  points: {
2093
2741
  type: "array",
@@ -2133,8 +2781,8 @@ export function apply(ctx, config = {}) {
2133
2781
  },
2134
2782
  layerOp: {
2135
2783
  type: "string",
2136
- enum: ["list", "add", "select", "set", "remove"],
2137
- description: "layer: list 列图层(默认);add 新建;select 设为当前;set 改属性;remove 删掉。",
2784
+ enum: ["list", "add", "select", "set", "remove", "group"],
2785
+ description: "layer: list 列图层(默认);add 新建;select 设为当前;set 改属性;remove 删掉;group 改组(配合 groupId/visible/layerOpacity/name)。",
2138
2786
  },
2139
2787
  name: {
2140
2788
  type: "string",
@@ -2147,8 +2795,44 @@ export function apply(ctx, config = {}) {
2147
2795
  },
2148
2796
  blend: {
2149
2797
  type: "string",
2150
- enum: ["normal", "multiply"],
2151
- description: "layer.set:混合模式,multiply 是正片叠底。",
2798
+ enum: BLEND_MODES,
2799
+ description: "layer.set / layer.add:混合模式 normal / multiply / screen / overlay / soft-light / linear-dodge。按 role 有默认值(shadow1/2、line=multiply、highlight=screen)。",
2800
+ },
2801
+ role: {
2802
+ type: "string",
2803
+ enum: ROLES,
2804
+ description: "layer.add / set:图层语义(v3 图层栈)。决定插入高度与默认混合模式;不填按层名猜。",
2805
+ },
2806
+ groupId: { type: "string", description: "layer.add / set:归到哪个组(g_ref/g_sketch/g_lineart/g_color/g_final),不填按 role。" },
2807
+ clipTo: { type: "string", description: "layer.set:剪贴到哪个层 id(显式 id,跨组也成立);渲染时用目标层 alpha 做掩码。" },
2808
+ lockAlpha: { type: "boolean", description: "layer.set:锁定透明像素(落笔不超出本层已有 alpha;追加笔迹时按基线裁剪)。" },
2809
+ hue: { type: "number", description: "layer.set:该层色相偏移 -180~180 度,只影响这一层。" },
2810
+ grade: { type: "object", additionalProperties: true, description: "layer.set(role=grade):调色参数 {brightness -1..1, contrast 0..3, saturation 0..3, hue -180..180}。" },
2811
+ collapsed: { type: "boolean", description: "layer group:组是否折叠显示。" },
2812
+ groupOp: {
2813
+ type: "string",
2814
+ enum: ["list", "add", "set", "remove", "move", "moveLayer"],
2815
+ description: "group: list 列组(默认);add 新建组;set 改组属性;remove 删组;move 组上移/下移;moveLayer 把层移进组(配 layer + groupId + index)。",
2816
+ },
2817
+ kind: {
2818
+ type: "string",
2819
+ description: "group.add:组类型 ref/sketch/lineart/color/final 之一,留空就是自定义组。",
2820
+ },
2821
+ index: {
2822
+ type: "number",
2823
+ description: "group.moveLayer / layer.add:组内第几位,0 是组内最底。",
2824
+ },
2825
+ offset: {
2826
+ type: "number",
2827
+ description: "group.move:+1 上移(更靠面)、-1 下移(更靠底)。",
2828
+ },
2829
+ force: {
2830
+ type: "boolean",
2831
+ description: "group.remove:组里还有层时,先把层并到相邻组再删。",
2832
+ },
2833
+ after: {
2834
+ type: "string",
2835
+ description: "group.add:插到这个组之后;不填就压最顶。",
2152
2836
  },
2153
2837
  path: {
2154
2838
  type: "string",
@@ -2226,18 +2910,25 @@ export function apply(ctx, config = {}) {
2226
2910
  style: {
2227
2911
  type: "string",
2228
2912
  enum: ["lineart", "flat", "anime", "paint"],
2229
- description: "copy: 复刻风格。lineart 只出线稿;flat 只出区域色块;anime 出线稿+色块(默认);paint 笔触复刻——按网格铺彩色短线(颜色取局部均色、方向沿等色线、透明度随对比度),适合厚涂/渐变/火焰这种没有闭合边界的图,再叠一层线稿。",
2913
+ description: "copy: 复刻风格。lineart 只出线稿;flat 只出区域色块;anime 出线稿+色块(默认);paint 完整 14 层栈——构图草稿/精线稿/线稿上色/闭塞线/固有色(拆 5 部件)/一级暗部/二级暗部/铺光/纹理/高光/镭射/氛围/调色,role 自动排 z 序与 blend;只在宿主侧算,有面板也一样。",
2230
2914
  },
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。" },
2915
+ paintStep: { type: "number", description: "copy style=paint: 取样与笔距的基准(像素),默认 10。越小笔触越密,但塑形/过渡层会多。" },
2916
+ maxStrokes: { type: "number", description: "copy style=paint: 总笔数上限,默认 4000。按一级暗部/二级暗部/线稿/高光/闭塞/铺光/纹理/镭射/氛围等权重分,改大就是真变多。" },
2917
+ paintStages: { type: "string", description: "copy style=paint: 只跑其中几步,逗号分隔 base,block,blend,edge,accent,sketch,lineColor,occlusion,lightblock,texture,iridescent,atmosphere,grade(默认全跑)。例如只补轮廓 \"base,edge\";重跑某层前先清掉旧层。" },
2918
+ paintColors: { type: "number", description: "copy style=paint: 铺底层并成几档大色,默认 8(3~12)。中间调多给几档,脸/手/腰带才不会被并掉。" },
2919
+ paintBlocks: { type: "number", description: "copy style=paint: 铺底初始块数,默认 120。不足 95% 覆盖率会按面积自动补,最多 400 块;白背景按四边连通域整块剔除。" },
2920
+ paintBaseMinArea: { type: "number", description: "copy style=paint: 铺底最小色块像素,默认画布面积/6000(1080×1440 约 259);脸、手、腰带这些中小色块要留下来。" },
2921
+ paintEdgeMinLength: { type: "number", description: "copy style=paint: 收边用色阶边界折线的最短长度,默认 24。" },
2922
+ paintEdgeMaxLines: { type: "number", description: "copy style=paint: 收边最多取几条色阶边界折线,默认 1800。" },
2923
+ paintPasses: { type: "number", description: "旧参数,已被 paintStages 取代:1 等价于 paintStages=\"base,block\";保留兼容。" },
2924
+ paintMinLum: { type: "number", description: "copy style=paint: 亮度达到这个值就当白底,默认 246。浅色衣袍调低一点(236)。" },
2925
+ lineart: { type: "boolean", description: "旧参数,paint 的「收边」已经是独立一层,不再额外叠线稿;保留兼容。" },
2236
2926
  colors: { type: "number", description: "copy / posterize / palette: 主色档数 2~12(copy 默认 6,posterize 默认 8)。彩稿要火、金、肤这些颜色都出来,给 10~12。" },
2237
2927
  minFill: { type: "number", description: "copy: 小于多少像素的闭合区域不填色,默认 320。" },
2238
2928
  target: { type: "number", description: "fix: 目标覆盖率百分比,默认 90。到了就停。" },
2239
2929
  maxRounds: { type: "number", description: "fix: 最多迭代几轮,默认 3(上限 5)。" },
2240
2930
  refLayer: { type: "string", description: "copy / fix: 用哪一个图片层当参考图,默认第一张可见图片层。" },
2931
+ forceHeadless: { type: "boolean", description: "像素任务强制走宿主侧引擎(copy style=paint / posterize 本来就固定走宿主)。回报里的 computedBy 写 host 或 panel,两条路径行为不一致时用这个对比排查。" },
2241
2932
  mode: {
2242
2933
  type: "string",
2243
2934
  enum: ["edge", "center"],
@@ -2264,9 +2955,10 @@ export function apply(ctx, config = {}) {
2264
2955
  render: (_args, value) => [{ type: "text", text: JSON.stringify(value, null, 2) }],
2265
2956
  },
2266
2957
  async execute(args) {
2267
- const action = args && args.action;
2268
2958
  docs.syncFromDisk();
2269
2959
  try {
2960
+ return jsonSafe(await (async () => {
2961
+ const action = args && args.action;
2270
2962
  switch (action) {
2271
2963
  case "new": {
2272
2964
  let savedPath = null;
@@ -2320,6 +3012,8 @@ export function apply(ctx, config = {}) {
2320
3012
  }
2321
3013
  case "doc":
2322
3014
  return { ok: true, ...docs.summary(), dir };
3015
+ case "check":
3016
+ return { ...(await checkLayers()), revision: docs.revision };
2323
3017
  case "draw": {
2324
3018
  const W = docs.doc.width;
2325
3019
  const H = docs.doc.height;
@@ -2376,8 +3070,18 @@ export function apply(ctx, config = {}) {
2376
3070
  return { ok: true, revision: docs.revision, active: docs.doc.activeLayer, layers: docs.summary().layers };
2377
3071
  }
2378
3072
  if (op === "add") {
2379
- const layer = docs.addLayer(args.name);
2380
- return { ok: true, revision: docs.revision, layer: { id: layer.id, name: layer.name }, layers: docs.summary().layers };
3073
+ const layer = docs.addLayer(args.name, {
3074
+ role: args.role,
3075
+ groupId: args.groupId,
3076
+ blend: args.blend,
3077
+ clipTo: args.clipTo,
3078
+ lockAlpha: args.lockAlpha,
3079
+ hue: args.hue,
3080
+ opacity: args.layerOpacity,
3081
+ locked: args.locked,
3082
+ index: args.index,
3083
+ });
3084
+ return { ok: true, revision: docs.revision, layer: { id: layer.id, name: layer.name, role: layer.role, groupId: layer.groupId, blend: layer.blend }, layers: docs.summary().layers };
2381
3085
  }
2382
3086
  if (op === "select") {
2383
3087
  const layer = docs.layer(target);
@@ -2393,6 +3097,11 @@ export function apply(ctx, config = {}) {
2393
3097
  if (args.layerOpacity !== undefined) patch.opacity = args.layerOpacity;
2394
3098
  if (args.blend !== undefined) patch.blend = args.blend;
2395
3099
  if (args.locked !== undefined) patch.locked = args.locked === true;
3100
+ if (args.role !== undefined) patch.role = args.role;
3101
+ if (args.groupId !== undefined) patch.groupId = args.groupId;
3102
+ if (args.clipTo !== undefined) patch.clipTo = args.clipTo;
3103
+ if (args.lockAlpha !== undefined) patch.lockAlpha = args.lockAlpha === true;
3104
+ if (args.hue !== undefined) patch.hue = args.hue;
2396
3105
  const layer = docs.updateLayer(target, patch);
2397
3106
  return {
2398
3107
  ok: true,
@@ -2400,20 +3109,96 @@ export function apply(ctx, config = {}) {
2400
3109
  layer: {
2401
3110
  id: layer.id,
2402
3111
  name: layer.name,
3112
+ role: layer.role,
3113
+ groupId: layer.groupId,
2403
3114
  visible: layer.visible,
2404
3115
  opacity: layer.opacity,
2405
3116
  blend: layer.blend,
3117
+ clipTo: layer.clipTo,
3118
+ lockAlpha: layer.lockAlpha,
3119
+ hue: layer.hue,
2406
3120
  locked: layer.locked === true,
2407
3121
  },
2408
3122
  layers: docs.summary().layers,
2409
3123
  };
2410
3124
  }
3125
+ if (op === "group") {
3126
+ const want = args.groupId || args.id || args.layer;
3127
+ const group = docs.updateGroup(want, {
3128
+ visible: args.visible,
3129
+ opacity: args.layerOpacity,
3130
+ name: args.name,
3131
+ collapsed: args.collapsed,
3132
+ locked: args.locked,
3133
+ });
3134
+ return { ok: true, revision: docs.revision, group, groups: docs.summary().groups, layers: docs.summary().layers };
3135
+ }
2411
3136
  if (op === "remove") {
2412
3137
  const removed = docs.removeLayer(target);
2413
3138
  return { ok: true, revision: docs.revision, removed, layers: docs.summary().layers };
2414
3139
  }
2415
3140
  throw new Error(`未知 layerOp: ${op}`);
2416
3141
  }
3142
+ case "group": {
3143
+ const op = args.groupOp || "list";
3144
+ if (op === "list") {
3145
+ return {
3146
+ ok: true,
3147
+ revision: docs.revision,
3148
+ groups: docs.summary().groups.map((g) => ({
3149
+ ...g,
3150
+ layers: docs.doc.layers.filter((l) => l.groupId === g.id).map((l) => ({ id: l.id, name: l.name, role: l.role })),
3151
+ })),
3152
+ layers: docs.summary().layers,
3153
+ };
3154
+ }
3155
+ if (op === "add") {
3156
+ const group = docs.addGroup({
3157
+ name: args.name,
3158
+ kind: args.kind,
3159
+ color: args.color,
3160
+ after: args.after !== undefined ? args.after : args.groupId,
3161
+ opacity: args.opacity !== undefined ? args.opacity : args.layerOpacity,
3162
+ visible: args.visible,
3163
+ locked: args.locked,
3164
+ });
3165
+ return { ok: true, revision: docs.revision, group, groups: docs.summary().groups };
3166
+ }
3167
+ if (op === "set") {
3168
+ const group = docs.updateGroup(args.groupId || args.id || args.name, {
3169
+ name: args.name,
3170
+ visible: args.visible,
3171
+ opacity: args.opacity !== undefined ? args.opacity : args.layerOpacity,
3172
+ locked: args.locked,
3173
+ collapsed: args.collapsed,
3174
+ color: args.color,
3175
+ });
3176
+ return { ok: true, revision: docs.revision, group, groups: docs.summary().groups };
3177
+ }
3178
+ if (op === "remove") {
3179
+ const removed = docs.removeGroup(args.groupId || args.id || args.name, { force: args.force === true });
3180
+ return { ok: true, revision: docs.revision, ...removed, groups: docs.summary().groups, layers: docs.summary().layers };
3181
+ }
3182
+ if (op === "move") {
3183
+ const moved = docs.moveGroup(args.groupId || args.id || args.name, args.offset === undefined ? 1 : args.offset);
3184
+ return { ok: true, revision: docs.revision, ...moved, groups: docs.summary().groups, layers: docs.summary().layers };
3185
+ }
3186
+ if (op === "moveLayer") {
3187
+ const moved = docs.moveLayerToGroup(
3188
+ args.layer !== undefined ? args.layer : args.id,
3189
+ args.groupId || args.name,
3190
+ args.index,
3191
+ );
3192
+ return {
3193
+ ok: true,
3194
+ revision: docs.revision,
3195
+ layer: { id: moved.id, name: moved.name, groupId: moved.groupId },
3196
+ groups: docs.summary().groups,
3197
+ layers: docs.summary().layers,
3198
+ };
3199
+ }
3200
+ throw new Error(`未知 groupOp: ${op}`);
3201
+ }
2417
3202
  case "import": {
2418
3203
  let buffer = null;
2419
3204
  if (typeof args.path === "string" && args.path.trim()) {
@@ -2535,7 +3320,7 @@ export function apply(ctx, config = {}) {
2535
3320
  rect,
2536
3321
  zoom: args.zoom === undefined ? 1 : Number(args.zoom),
2537
3322
  layer: args.layer === undefined ? null : args.layer,
2538
- });
3323
+ }, undefined, args.forceHeadless === true);
2539
3324
  if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
2540
3325
  const file = writePng(job.dataUrl, "view");
2541
3326
  return {
@@ -2595,7 +3380,7 @@ export function apply(ctx, config = {}) {
2595
3380
  : "这就是参考图原文件,用 read_image 直接看;要看某一块就带 rect=[x,y,w,h]。",
2596
3381
  };
2597
3382
  }
2598
- const job = await runPixelJob("ref", { rect, zoom: args.zoom === undefined ? 1 : Number(args.zoom), layer: target.id });
3383
+ const job = await runPixelJob("ref", { rect, zoom: args.zoom === undefined ? 1 : Number(args.zoom), layer: target.id }, undefined, args.forceHeadless === true);
2599
3384
  if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
2600
3385
  const file = writePng(job.dataUrl, "ref");
2601
3386
  return {
@@ -2618,7 +3403,7 @@ export function apply(ctx, config = {}) {
2618
3403
  y: Math.round(Number(args.y)),
2619
3404
  rect,
2620
3405
  color: args.color || null,
2621
- }, PIXEL_TIMEOUT_MS * 3);
3406
+ }, PIXEL_TIMEOUT_MS * 3, args.forceHeadless === true);
2622
3407
  if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
2623
3408
  if (!job.polygons || job.polygons.length === 0) throw new Error("这个种子点没围出可填的区域:先有线稿边界,或者换一个点");
2624
3409
  const want = String(args.fillLayer || args.layer || "色块").trim();
@@ -2662,6 +3447,13 @@ export function apply(ctx, config = {}) {
2662
3447
  case "copy": {
2663
3448
  const style = args.style === "lineart" || args.style === "flat" || args.style === "paint" ? args.style : "anime";
2664
3449
  const rect = parseRect(args.rect, docs.doc.width, docs.doc.height);
3450
+ const isPaint = style === "paint";
3451
+ // paint 是五步管线,只在宿主侧算:有面板也走宿主,保证「有面板/没面板」同一套层数和笔法。
3452
+ const paintStages = isPaint
3453
+ ? (typeof args.paintStages === "string" && args.paintStages.trim()
3454
+ ? args.paintStages
3455
+ : (args.paintPasses === 1 ? "base,block" : undefined))
3456
+ : undefined;
2665
3457
  const job = await runPixelJob("copy", {
2666
3458
  rect,
2667
3459
  style,
@@ -2680,7 +3472,13 @@ export function apply(ctx, config = {}) {
2680
3472
  maxStrokes: args.maxStrokes,
2681
3473
  paintPasses: args.paintPasses,
2682
3474
  paintMinLum: args.paintMinLum,
2683
- }, PIXEL_TIMEOUT_MS * 3);
3475
+ paintStages,
3476
+ paintColors: args.paintColors,
3477
+ paintBlocks: args.paintBlocks,
3478
+ paintBaseMinArea: args.paintBaseMinArea,
3479
+ paintEdgeMinLength: args.paintEdgeMinLength,
3480
+ paintEdgeMaxLines: args.paintEdgeMaxLines,
3481
+ }, PIXEL_TIMEOUT_MS * 3, isPaint);
2684
3482
  if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
2685
3483
  const created = [];
2686
3484
  // 同名空层直接复用,避免反复 copy 堆出一串「线稿 2」「色块 3」
@@ -2690,8 +3488,78 @@ export function apply(ctx, config = {}) {
2690
3488
  if (found && !found.locked && !found.image && (found.strokes || []).length === 0) return found;
2691
3489
  return docs.addLayer(want || undefined);
2692
3490
  };
2693
- // 先铺底色(笔触 / 色块都在线稿下面),再描线,顺序就是画师的习惯
2694
- if (style === "paint" && Array.isArray(job.paint) && job.paint.length > 0) {
3491
+ // paint 五步 → v3 图层栈:按 role 找/建层,blend 由 role 决定;重跑先 snapshot 再清空
3492
+ const hasLine = Array.isArray(job.paintStages) && job.paintStages.some((s) => s.key === "edge");
3493
+ const pickStageLayer = (stage, nameOverride) => {
3494
+ const role = PAINT_STAGE_ROLE[stage.key] || "base";
3495
+ const want = nameOverride || PAINT_STAGE_NAME[stage.key] || stage.name || "图层";
3496
+ const legacy = [stage.name, "铺底", "塑形", "过渡", "收边", "点睛"].filter(Boolean);
3497
+ const found = docs.doc.layers.find((l) => !l.image && l.role === role && (l.name === want || legacy.includes(l.name)));
3498
+ if (found) {
3499
+ if ((found.strokes || []).length > 0) {
3500
+ docs.snapshot(`重跑 ${want}`);
3501
+ docs.clear(found.id);
3502
+ }
3503
+ // 草稿/线色这类层可能是锁的,重跑前临时解锁
3504
+ docs.updateLayer(found.id, { role, name: want, blend: blendOfRole(role), locked: false, clipTo: stage.clipTo || null, opacity: stage.opacity === undefined ? 1 : stage.opacity, lockAlpha: false });
3505
+ return found;
3506
+ }
3507
+ return docs.addLayer(want, { role, blend: blendOfRole(role), clipTo: stage.clipTo || null, opacity: stage.opacity });
3508
+ };
3509
+ // 13 步管线:role 决定 z 高度与 blend
3510
+ if (isPaint && Array.isArray(job.paintStages)) {
3511
+ for (const stage of job.paintStages) {
3512
+ const role = PAINT_STAGE_ROLE[stage.key] || "base";
3513
+ if (stage.kind === "grade") {
3514
+ const layer = pickStageLayer(stage);
3515
+ docs.updateLayer(layer.id, { grade: stage.grade || { brightness: 0, contrast: 1, saturation: 1, hue: 0 } });
3516
+ created.push({ name: layer.name, role, kind: "grade", items: 0, stage: stage.key });
3517
+ continue;
3518
+ }
3519
+ if (stage.kind === "fill") {
3520
+ const parts = Array.isArray(stage.parts) && stage.parts.length
3521
+ ? stage.parts
3522
+ : [{ key: "all", name: "", fills: stage.fills || [], outlines: stage.outlines || [] }];
3523
+ for (const part of parts) {
3524
+ if (!Array.isArray(part.fills) || part.fills.length === 0) continue;
3525
+ const layerName = part.key === "all" ? "固有色平铺" : `固有色-${part.name}`;
3526
+ const layer = pickStageLayer(stage, layerName);
3527
+ await appendInChunks(
3528
+ part.fills.map((f) => ({ mode: "fill", color: f.color, size: 1, opacity: 1, points: f.points, holes: f.holes || [] })),
3529
+ layer.id,
3530
+ );
3531
+ if (!hasLine && Array.isArray(part.outlines) && part.outlines.length > 0) {
3532
+ await appendInChunks(
3533
+ part.outlines.map((o) => ({ mode: "brush", color: o.color, size: o.size, opacity: o.opacity, brush: "hard", points: o.points })),
3534
+ layer.id,
3535
+ );
3536
+ }
3537
+ created.push({ name: layer.name, role, part: part.key, kind: "fill", items: part.fills.length, outlines: hasLine ? 0 : (part.outlines ? part.outlines.length : 0), stage: stage.key });
3538
+ }
3539
+ } else {
3540
+ if (!Array.isArray(stage.strokes) || stage.strokes.length === 0) continue;
3541
+ const layer = pickStageLayer(stage);
3542
+ const brush = BRUSH_IDS.includes(stage.brush) ? stage.brush : "round";
3543
+ await appendInChunks(
3544
+ stage.strokes.map((s) => ({
3545
+ mode: "brush",
3546
+ color: s.color,
3547
+ size: s.size,
3548
+ opacity: s.opacity,
3549
+ brush,
3550
+ taper: s.taper === true || stage.taper === true,
3551
+ minSize: s.minSize === undefined ? stage.minSize : s.minSize,
3552
+ points: s.points,
3553
+ })),
3554
+ layer.id,
3555
+ );
3556
+ if (stage.lockAlpha === true) docs.updateLayer(layer.id, { lockAlpha: true });
3557
+ if (stage.locked === true) docs.updateLayer(layer.id, { locked: true });
3558
+ created.push({ name: layer.name, role, blend: blendOfRole(role), clipTo: stage.clipTo || null, kind: "paint", items: stage.strokes.length, stage: stage.key });
3559
+ }
3560
+ }
3561
+ } else if (isPaint && Array.isArray(job.paint) && job.paint.length > 0) {
3562
+ // 兼容旧宿主:只回 job.paint 的单层笔触
2695
3563
  const layer = pickLayer(args.fillLayer || "笔触");
2696
3564
  await appendInChunks(
2697
3565
  job.paint.map((p) => ({
@@ -2699,14 +3567,14 @@ export function apply(ctx, config = {}) {
2699
3567
  color: p.color,
2700
3568
  size: p.size,
2701
3569
  opacity: p.opacity,
2702
- brush: BRUSH_IDS.includes(args.paintBrush) ? args.paintBrush : "round",
3570
+ brush: "hard",
2703
3571
  points: p.points,
2704
3572
  })),
2705
3573
  layer.id,
2706
3574
  );
2707
3575
  created.push({ name: layer.name, kind: "paint", items: job.paint.length });
2708
3576
  }
2709
- if (style !== "lineart" && job.fills.length > 0) {
3577
+ if (!isPaint && style !== "lineart" && Array.isArray(job.fills) && job.fills.length > 0) {
2710
3578
  const layer = pickLayer(args.fillLayer || "色块");
2711
3579
  await appendInChunks(
2712
3580
  job.fills.map((f) => ({ mode: "fill", color: f.color, size: 1, opacity: 1, points: f.points, holes: f.holes })),
@@ -2714,8 +3582,8 @@ export function apply(ctx, config = {}) {
2714
3582
  );
2715
3583
  created.push({ name: layer.name, kind: "fill", items: job.fills.length });
2716
3584
  }
2717
- // 厚涂图没有清晰墨线,默认不描线(强行描会拖出大黑斜线);要就显式 lineart=true
2718
- if (style !== "flat" && (style !== "paint" || args.lineart === true) && job.paths.length > 0) {
3585
+ // 非 paint:厚涂图没有清晰墨线,默认不描线;要就显式 lineart=true
3586
+ if (!isPaint && style !== "flat" && Array.isArray(job.paths) && job.paths.length > 0) {
2719
3587
  const palette = job.palette || [];
2720
3588
  const darkest = palette.length
2721
3589
  ? palette.reduce((a, b) => (lumOf(a) <= lumOf(b) ? a : b))
@@ -2755,7 +3623,8 @@ export function apply(ctx, config = {}) {
2755
3623
  }
2756
3624
  }
2757
3625
  // 自动验收,让模型不用再问一次
2758
- const cmp = await runPixelJob("compare", { rect: job.rect }, PIXEL_TIMEOUT_MS * 2);
3626
+ const cmp = await runPixelJob("compare", { rect: job.rect, paint: isPaint }, PIXEL_TIMEOUT_MS * 2, isPaint);
3627
+ const summary = created.map((c) => `${c.name}(${c.items})`).join(" + ") || "没有可画的内容";
2759
3628
  return {
2760
3629
  ok: true,
2761
3630
  revision: docs.revision,
@@ -2770,14 +3639,20 @@ export function apply(ctx, config = {}) {
2770
3639
  created,
2771
3640
  palette: job.palette,
2772
3641
  lines: job.lines,
2773
- fills: job.fills.length,
2774
- paint: Array.isArray(job.paint) ? job.paint.length : 0,
3642
+ fills: Array.isArray(job.fills) ? job.fills.length : 0,
3643
+ paint: isPaint ? (job.paint || 0) : 0,
3644
+ paintLayers: isPaint ? created.map((c) => ({ name: c.name, role: c.role || null, kind: c.kind, items: c.items, blend: c.blend || null, clipTo: c.clipTo || null })) : null,
2775
3645
  paintStats: job.paintStats || null,
2776
3646
  points: job.points,
3647
+ computedBy: job.computedBy || null,
2777
3648
  metrics: cmp.ok ? cmp.metrics : null,
2778
- hint: `已按 ${style} 复刻:${created.map((c) => `${c.name}(${c.items})`).join(" + ") || "没有可画的内容"}。`
2779
- + (cmp.ok ? `覆盖率 ${cmp.metrics.coveragePct}%,多画 ${cmp.metrics.extraPct}%。` : "(验收没跑成,稍后 action=compare 再看)")
2780
- + "想补差距就 action=fix。",
3649
+ hint: (isPaint
3650
+ ? `14 层复刻完成:${summary};估算覆盖率 ${job.paintStats ? job.paintStats.coveragePct : "?"}%。每层可单独显隐、改 blend/clipTo/hue;只重跑某几步给 paintStages(如 "base,block"),重跑前会自动 snapshot;action=check 可做关层自检。`
3651
+ : `已按 ${style} 复刻:${summary}。`)
3652
+ + (cmp.ok
3653
+ ? `验收覆盖率 ${cmp.metrics.coveragePct}%,多画 ${cmp.metrics.extraPct}%${cmp.metrics.meanColorDiff === null || cmp.metrics.meanColorDiff === undefined ? "" : `,平均色差 ${cmp.metrics.meanColorDiff}`}${cmp.metrics.meanDeltaE === undefined ? "" : `(ΔE≈${cmp.metrics.meanDeltaE})`}。`
3654
+ : "(验收没跑成,稍后 action=compare 再看)")
3655
+ + (isPaint ? "想更细就给更小的 paintStep 或更大的 maxStrokes;fix 的墨迹补漏不适用于彩稿。" : "想补差距就 action=fix。"),
2781
3656
  };
2782
3657
  }
2783
3658
  case "posterize": {
@@ -2794,7 +3669,7 @@ export function apply(ctx, config = {}) {
2794
3669
  lines: args.lines === true,
2795
3670
  minLength: args.minLength,
2796
3671
  maxLines: args.maxLines,
2797
- }, PIXEL_TIMEOUT_MS * 3);
3672
+ }, PIXEL_TIMEOUT_MS * 3, true);
2798
3673
  if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
2799
3674
  const created = [];
2800
3675
  const pickLayer = (name) => {
@@ -2822,7 +3697,7 @@ export function apply(ctx, config = {}) {
2822
3697
  );
2823
3698
  created.push({ name: layer.name, kind: "line", items: job.paths.length });
2824
3699
  }
2825
- const cmp = await runPixelJob("compare", { rect }, PIXEL_TIMEOUT_MS * 2);
3700
+ const cmp = await runPixelJob("compare", { rect }, PIXEL_TIMEOUT_MS * 2, true);
2826
3701
  return {
2827
3702
  ok: true,
2828
3703
  revision: docs.revision,
@@ -2830,6 +3705,7 @@ export function apply(ctx, config = {}) {
2830
3705
  created,
2831
3706
  palette: job.stats && job.stats.palette,
2832
3707
  stats: job.stats,
3708
+ computedBy: job.computedBy || null,
2833
3709
  metrics: cmp.ok ? cmp.metrics : null,
2834
3710
  hint: `已按 ${job.stats ? job.stats.colorCount : "?"} 色阶分区复刻:${created.map((c) => `${c.name}(${c.items})`).join(" + ") || "没有可画的内容"}。`
2835
3711
  + (cmp.ok ? `覆盖率 ${cmp.metrics.coveragePct}%,多画 ${cmp.metrics.extraPct}%,色差 ${cmp.metrics.meanColorDiff}。` : "")
@@ -2837,13 +3713,22 @@ export function apply(ctx, config = {}) {
2837
3713
  };
2838
3714
  }
2839
3715
  case "fix": {
3716
+ // paint 五步画布的「缺口」是彩稿覆盖/色差,不是墨迹漏描;
3717
+ // 用 trace 往 5 层里补黑线只会画脏,直接让调用方去重跑对应层。
3718
+ if (args.layer === undefined && docs.doc.layers.some((l) => ["固有色平铺", "一级暗部", "二级暗部", "精线稿", "高光"].includes(l.name))) {
3719
+ return {
3720
+ ok: false,
3721
+ revision: docs.revision,
3722
+ error: "这是 paint 五步画布:fix 的墨迹补漏不适合彩稿。用 copy style=paint paintStages=... rect=... 局部重跑,或 action=compare 看覆盖率/色差。",
3723
+ };
3724
+ }
2840
3725
  const rect = parseRect(args.rect, docs.doc.width, docs.doc.height);
2841
3726
  const maxRounds = Math.max(1, Math.min(5, Math.round(Number(args.maxRounds) || 3)));
2842
3727
  const target = Math.max(30, Math.min(99, Number(args.target) || 90));
2843
3728
  const rounds = [];
2844
3729
  let last = null;
2845
3730
  for (let i = 0; i < maxRounds; i += 1) {
2846
- const cmp = await runPixelJob("compare", { rect }, PIXEL_TIMEOUT_MS * 2);
3731
+ const cmp = await runPixelJob("compare", { rect }, PIXEL_TIMEOUT_MS * 2, args.forceHeadless === true);
2847
3732
  if (!cmp.ok) return { ok: false, error: cmp.error, rounds, revision: docs.revision };
2848
3733
  last = cmp.metrics;
2849
3734
  const entry = {
@@ -2875,7 +3760,7 @@ export function apply(ctx, config = {}) {
2875
3760
  tolerance: Math.min(2, Number(args.tolerance) || 2),
2876
3761
  minLength: 6,
2877
3762
  maxLines: 30,
2878
- }, PIXEL_TIMEOUT_MS * 2);
3763
+ }, PIXEL_TIMEOUT_MS * 2, args.forceHeadless === true);
2879
3764
  if (!tr.ok || !tr.paths.length) continue;
2880
3765
  const brush = BRUSH_IDS.includes(args.brush) ? args.brush : "liner";
2881
3766
  const strokes = tr.paths
@@ -2889,7 +3774,7 @@ export function apply(ctx, config = {}) {
2889
3774
  if (added === 0) break;
2890
3775
  }
2891
3776
  // 收尾再验收一次,数字才是补完后的
2892
- const final = await runPixelJob("compare", { rect }, PIXEL_TIMEOUT_MS * 2);
3777
+ const final = await runPixelJob("compare", { rect }, PIXEL_TIMEOUT_MS * 2, args.forceHeadless === true);
2893
3778
  return {
2894
3779
  ok: true,
2895
3780
  revision: docs.revision,
@@ -2914,7 +3799,7 @@ export function apply(ctx, config = {}) {
2914
3799
  fitStep: args.fitStep,
2915
3800
  widths: args.widths === true,
2916
3801
  mode: args.mode === "center" ? "center" : "edge",
2917
- });
3802
+ }, undefined, args.forceHeadless === true);
2918
3803
  if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
2919
3804
  return {
2920
3805
  ok: true,
@@ -2944,7 +3829,7 @@ export function apply(ctx, config = {}) {
2944
3829
  y: Math.round(Number(args.y)),
2945
3830
  layer: args.layer === undefined ? null : args.layer,
2946
3831
  on: args.on === "canvas" ? "canvas" : "ref",
2947
- });
3832
+ }, undefined, args.forceHeadless === true);
2948
3833
  if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
2949
3834
  return { ok: true, revision: docs.revision, ...job };
2950
3835
  }
@@ -2952,7 +3837,7 @@ export function apply(ctx, config = {}) {
2952
3837
  const job = await runPixelJob("compare", {
2953
3838
  rect: parseRect(args.rect, docs.doc.width, docs.doc.height),
2954
3839
  layer: args.layer === undefined ? null : args.layer,
2955
- });
3840
+ }, undefined, args.forceHeadless === true);
2956
3841
  if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
2957
3842
  const file = writePng(job.dataUrl, "compare");
2958
3843
  return {
@@ -2966,7 +3851,7 @@ export function apply(ctx, config = {}) {
2966
3851
  }
2967
3852
  case "palette": {
2968
3853
  const k = Math.max(2, Math.min(8, Math.round(Number(args.k) || 6)));
2969
- const job = await runPixelJob("palette", { k, rect: parseRect(args.rect, docs.doc.width, docs.doc.height), layer: args.layer === undefined ? null : args.layer });
3854
+ const job = await runPixelJob("palette", { k, rect: parseRect(args.rect, docs.doc.width, docs.doc.height), layer: args.layer === undefined ? null : args.layer }, undefined, args.forceHeadless === true);
2970
3855
  if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
2971
3856
  return { ok: true, revision: docs.revision, ...job };
2972
3857
  }
@@ -2993,8 +3878,9 @@ export function apply(ctx, config = {}) {
2993
3878
  default:
2994
3879
  return { ok: false, error: `未知 action: ${action}` };
2995
3880
  }
3881
+ })());
2996
3882
  } catch (err) {
2997
- return { ok: false, error: String((err && err.message) || err) };
3883
+ return jsonSafe({ ok: false, error: String((err && err.message) || err) });
2998
3884
  }
2999
3885
  },
3000
3886
  isConcurrencySafe: () => false,