dsh-game-material-master 0.1.0

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/lib/riggen.js ADDED
@@ -0,0 +1,3639 @@
1
+ /**
2
+ * 骨骼动画生成模块(第四个物料模块)。
3
+ *
4
+ * 把参考项目 [spine-animation-ai](https://github.com/GenielabsOpenSource/spine-animation-ai)
5
+ * 的整条 Python 流水线搬进插件,并且**拆成可单独重跑的四个阶段**——参考项目是一条
6
+ * 跑到底的脚本,任何一步出问题都只能从头再来;这里每一步都有自己的状态、验收打标
7
+ * 与单独重跑入口,和八方向图模块的手感保持一致。
8
+ *
9
+ * ```
10
+ * ① parts 拆件 :生图模型把角色拆成部件 → 连通域分割 → 逐件透明 PNG
11
+ * (也可以跳过生图,直接上传现成的部件 PNG)
12
+ * ② layout 装配 :多尺度模板匹配把每个部件摆回参考图 → 合成对比图供肉眼验收
13
+ * ③ rig 骨骼 :自动推骨骼层级 + 六个动画预设 → skeleton.json + 自包含预览
14
+ * ④ atlas 图集 :打包成 Spine 纹理图集(.png + .atlas),可直接导入引擎
15
+ * ```
16
+ *
17
+ * 目录结构:
18
+ * <DSH_HOME>/game-material-master/rig-jobs/<任务 id>/
19
+ * job.json 任务状态(本文件的 RigJob)
20
+ * source/ 用户上传的角色参考图
21
+ * sheet/ 生图模型产出的「拆件摊平图」
22
+ * parts/ 分割后的部件透明 PNG
23
+ * layout/ 装配结果:layout.json / composite.png / comparison.png
24
+ * rig/ skeleton.json / preview.html
25
+ * atlas/ skeleton.png / skeleton.atlas
26
+ */
27
+ import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
28
+ import { basename, join, resolve, sep } from "node:path";
29
+ import { randomUUID } from "node:crypto";
30
+ import { loadConfig, rigJobsRoot } from "./config.js";
31
+ import { generateImage } from "./ark.js";
32
+ import { decodeToRgba, mimeOf, toDataUri } from "./media.js";
33
+ import { encodePng } from "./png.js";
34
+ import { appendJobLog, messageOf, readJson, writeJsonAtomic } from "./jsonio.js";
35
+ import { safeName, sniffImage } from "./imagegen.js";
36
+ import { alphaBounds, blitRgba, boxMask, compositeParts, createRgba, detectBackground, erodeAlpha, groupComponentsByProximity, imageStats, maskAndFit, padToSquare, resizeRgba, rotateRgba, segmentWithLabels, sideBySide, solveLayout, tintRgba } from "./rigpose.js";
37
+ import { DEFAULT_DRAW_ORDER, RIG_ANIMATIONS, RIG_GRID_COLUMNS, RIG_GRID_ROWS, animationDurationOf, animationPresetOf, buildAtlasText, buildSkeleton, defaultAnimationIds, defaultPartNames, drawRankOf, instantiateAnimation, isAnimationId, keyframeValueKeys, normalizeAnimationSettings, packAtlas, partLabel, rigSlotOf } from "./spine.js";
38
+ import { buildPreviewHtml } from "./rigpreview.js";
39
+ import { buildDragonBonesSkeleton, buildDragonBonesTexture } from "./rigexport.js";
40
+ import { assessParts } from "./rigqa.js";
41
+ import { MESH_DEFAULT_DIVISIONS, MESH_MAX_DIVISIONS } from "./rigmesh.js";
42
+ import { normalizePath } from "./rigpath.js";
43
+ import { validateAnimationLoops, validateAtlas, validateDragonBones, validateDragonBonesTexture, validateSkeletonAtlasMatch, validateSpineWire } from "./rigvalidate.js";
44
+ import { defaultSemanticsOf, mergeSemantics, validateSemantics, ROLE_NOUNS } from "./rigsemantics.js";
45
+ export const RIG_STAGES = [
46
+ { key: "parts", label: "① 拆件", summary: "把角色拆成独立部件(头/躯干/四肢),逐件透明 PNG" },
47
+ { key: "layout", label: "② 装配", summary: "把部件摆回参考姿态,出合成对比图供肉眼验收" },
48
+ { key: "rig", label: "③ 骨骼动画", summary: "自动推骨骼层级 + 待机/行走/奔跑/挥手/跳跃/攻击" },
49
+ { key: "atlas", label: "④ 图集", summary: "打包 Spine 纹理图集,可直接导入引擎" }
50
+ ];
51
+ /** 单页纹理的边长上限;超过就分页。4096 是移动端 GPU 最普遍的保证值。 */
52
+ export const ATLAS_MAX_SIZE = 4096;
53
+ const JOB_ID_PATTERN = /^r[a-z0-9]{4,40}$/;
54
+ export function rigJobDir(id) {
55
+ return join(rigJobsRoot(), id);
56
+ }
57
+ function jobFile(id) {
58
+ return join(rigJobDir(id), "job.json");
59
+ }
60
+ /** 任务内相对路径 → 绝对路径,并挡住目录穿越。 */
61
+ export function rigAssetPath(id, relative) {
62
+ const base = resolve(rigJobDir(id));
63
+ const target = resolve(base, relative);
64
+ if (target !== base && !target.startsWith(base + sep))
65
+ throw new Error(`非法的任务内路径:${relative}`);
66
+ return target;
67
+ }
68
+ export function isValidRigJobId(id) {
69
+ return JOB_ID_PATTERN.test(id);
70
+ }
71
+ export async function ensureRigJobLayout(id) {
72
+ for (const sub of ["source", "sheet", "parts", "layout", "rig", "atlas"]) {
73
+ await mkdir(join(rigJobDir(id), sub), { recursive: true });
74
+ }
75
+ }
76
+ // ── 拆件提示词 ──────────────────────────────────────────────────────────
77
+ /**
78
+ * 拆件提示词。
79
+ *
80
+ * 参考项目直接把「把所有部件摊开」交给模型,然后靠连通域分割,部件叫什么全靠
81
+ * 事后猜。这里额外要求模型**按严格网格摆放**:格子位置 = 部件身份,是确定事实,
82
+ * 于是「头」真的是头,骨骼层级和动画预设才能自动套上去,而不必让用户手工命名
83
+ * 十几个文件。
84
+ *
85
+ * 底下那三条硬约束是**用真实数据换来的**。拿一张真实立绘跑出来过:
86
+ * 18 块里 6 块是同一部位重画(4 段大腿、4 只鞋、3 条袖子)、标着 `hip` 的格子画的是
87
+ * 裙子、标着 `neck` 的画的是大腿、两条「左右袖」同向重合 0.901(应该是镜像)。
88
+ * 根因都在提示词没说清:
89
+ *
90
+ * ① 只说「一格一件」,没说「每件必须不同」——于是模型把同一块内容画了很多遍;
91
+ * ② 只给了格子名(`hip`/`neck`),没给部位描述——模型对这些短名字的理解与我们的
92
+ * 骨骼语义不一致,而骨架是靠「名字 → 语义」推的,名字错了骨架从第一根骨头起就错;
93
+ * ③ 没有说明「参考图里被衣服遮住的部位要按解剖结构补全」——模型看不到大腿,
94
+ * 就把小腿反复画成「大腿」交差。
95
+ */
96
+ export function buildSheetPrompt(columns, rows, names) {
97
+ const grid = [];
98
+ for (let row = 0; row < rows; row++) {
99
+ const cells = [];
100
+ for (let column = 0; column < columns; column++) {
101
+ const index = row * columns + column;
102
+ const name = names[index];
103
+ const slot = name === undefined ? undefined : rigSlotOf(name);
104
+ cells.push(slot === undefined ? (name ?? "-") : `${slot.name} = ${slot.en}`);
105
+ }
106
+ grid.push(`row ${row + 1}: ${cells.join(" | ")}`);
107
+ }
108
+ return [
109
+ "A flat 2D game sprite sheet for skeletal (Spine) cut-out animation, showing the EXACT same character as the reference image, completely taken apart into separate body parts.",
110
+ "",
111
+ `The image is a SQUARE canvas divided into an even ${columns} × ${rows} grid of equal cells. Each cell contains exactly ONE detached body part, centered in its cell. Cells in reading order — the text before the "=" is the part's name, the text after it says what that part IS:`,
112
+ ...grid,
113
+ "",
114
+ "Hard requirements:",
115
+ "- the canvas is square and the grid lines are perfectly even; every cell is the same size;",
116
+ "- exactly one body part per cell, and nothing else in that cell;",
117
+ "- **every cell shows a DIFFERENT part. Draw each body part exactly ONCE in the whole image.** Never repeat the same part in a second cell. The character has exactly two arms, two hands, two legs and two feet — never draw a third one;",
118
+ "- **draw what the cell says.** A cell labelled `neck` shows a neck, not a thigh or a leg. If a name seems ambiguous, follow the description after the \"=\";",
119
+ "- **CUT, do not redesign.** Every piece must look exactly like the corresponding region of the reference image: same garment, same colours, same silhouette, same proportions. The cell name only tells you *which body region to cut out*; the reference image tells you what it *looks like*. If the hip region is covered by a skirt in the reference image, the `hip` cell shows that skirt — never invent clothing that is not in the reference image (no shorts, no different outfit);",
120
+ "- **left and right parts are MIRRORED, not copies.** `left-upper-arm` and `right-upper-arm` must face opposite ways (one mirrored copy of the other), and the same for every other left/right pair;",
121
+ "- every part is COMPLETELY DETACHED: upper arm and forearm and hand are three separate pieces, never joined; upper leg, lower leg and foot are three separate pieces, never joined;",
122
+ "- no piece crosses a cell boundary, no piece touches or overlaps another piece;",
123
+ "- generous empty white space around every piece;",
124
+ "- parts are NOT assembled: no standing character, no connected body;",
125
+ "- CRITICAL: identical art style, identical shading, identical face, identical colours and identical proportions as the reference image;",
126
+ "- plain solid pure white background everywhere, flat 2D game asset, character part sheet;",
127
+ "",
128
+ "Negative: assembled body, connected limbs, joined arm, joined leg, overlapping parts, duplicated part, repeated part, three arms, three legs, extra limb, wrong part in cell, mismatched cell content, grid lines drawn, borders, labels, text, watermark, drop shadows, gradients, background scenery, 3D, realistic, redesigned character, different face, different colours."
129
+ ].join("\n");
130
+ }
131
+ export function buildSheetRequest(job) {
132
+ const base = job.prompts.sheet.trim() === "" ? buildSheetPrompt(job.settings.gridColumns, job.settings.gridRows, rigSlotNames(job)) : job.prompts.sheet;
133
+ const suffix = job.prompts.suffix.trim();
134
+ return suffix === "" ? base : `${base}\n${suffix}`;
135
+ }
136
+ /** 网格槽位名:优先用用户已经存在的部件名,否则用默认 16 件套。 */
137
+ export function rigSlotNames(job) {
138
+ const defaults = defaultPartNames();
139
+ const count = job.settings.gridColumns * job.settings.gridRows;
140
+ const out = [];
141
+ for (let i = 0; i < count; i++)
142
+ out.push(defaults[i] ?? `slot-${i + 1}`);
143
+ return out;
144
+ }
145
+ // ── 持久化 ──────────────────────────────────────────────────────────────
146
+ export async function createRigJob(name) {
147
+ const config = await loadConfig();
148
+ const id = `r${Date.now().toString(36)}${randomUUID().slice(0, 6)}`;
149
+ const now = Date.now();
150
+ const job = {
151
+ id,
152
+ name: name.trim() === "" ? "未命名骨骼动画任务" : name.trim().slice(0, 80),
153
+ createdAt: now,
154
+ updatedAt: now,
155
+ prompts: { sheet: "", suffix: "" },
156
+ settings: {
157
+ model: config.arkModel,
158
+ size: config.arkSize,
159
+ watermark: config.arkWatermark,
160
+ gridColumns: RIG_GRID_COLUMNS,
161
+ gridRows: RIG_GRID_ROWS,
162
+ backgroundTolerance: 30,
163
+ feather: 26,
164
+ minArea: 0,
165
+ partPadding: 4,
166
+ matchLongEdge: 448,
167
+ animations: defaultAnimationIds()
168
+ },
169
+ sheet: { status: "empty" },
170
+ parts: [],
171
+ layout: { status: "empty", items: {} },
172
+ rig: { status: "empty" },
173
+ atlas: { status: "empty" },
174
+ log: []
175
+ };
176
+ await ensureRigJobLayout(id);
177
+ await writeJsonAtomic(jobFile(id), job);
178
+ return job;
179
+ }
180
+ export async function readRigJob(id) {
181
+ if (!isValidRigJobId(id))
182
+ return undefined;
183
+ const raw = await readJson(jobFile(id));
184
+ if (raw === undefined)
185
+ return undefined;
186
+ return normalizeRigJob(raw);
187
+ }
188
+ export async function writeRigJob(job) {
189
+ job.updatedAt = Date.now();
190
+ await writeJsonAtomic(jobFile(job.id), job);
191
+ }
192
+ export async function listRigJobs() {
193
+ const { readdir } = await import("node:fs/promises");
194
+ let entries = [];
195
+ try {
196
+ const dirents = await readdir(rigJobsRoot(), { withFileTypes: true });
197
+ entries = dirents.filter((d) => d.isDirectory() && isValidRigJobId(d.name)).map((d) => d.name);
198
+ }
199
+ catch {
200
+ return [];
201
+ }
202
+ const out = [];
203
+ for (const id of entries) {
204
+ const job = await readRigJob(id);
205
+ if (job === undefined)
206
+ continue;
207
+ out.push(summarizeRigJob(job));
208
+ }
209
+ out.sort((a, b) => b.updatedAt - a.updatedAt);
210
+ return out;
211
+ }
212
+ export function summarizeRigJob(job) {
213
+ return {
214
+ id: job.id,
215
+ name: job.name,
216
+ createdAt: job.createdAt,
217
+ updatedAt: job.updatedAt,
218
+ hasSource: job.source !== undefined,
219
+ partCount: job.parts.filter((part) => part.status === "ready").length,
220
+ placedCount: Object.values(job.layout.items).filter((item) => item.matched).length,
221
+ rigReady: job.rig.status === "ready",
222
+ atlasReady: job.atlas.status === "ready"
223
+ };
224
+ }
225
+ export async function deleteRigJob(id) {
226
+ stopRigPoller(id);
227
+ await rm(rigJobDir(id), { recursive: true, force: true });
228
+ }
229
+ export async function rigJobExists(id) {
230
+ try {
231
+ return (await stat(rigJobDir(id))).isDirectory();
232
+ }
233
+ catch {
234
+ return false;
235
+ }
236
+ }
237
+ function num(value, fallback) {
238
+ const n = typeof value === "number" ? value : Number.parseFloat(String(value ?? ""));
239
+ return Number.isFinite(n) ? n : fallback;
240
+ }
241
+ function clampInt(value, fallback, min, max) {
242
+ return Math.min(max, Math.max(min, Math.round(num(value, fallback))));
243
+ }
244
+ function normalizeRigJob(raw) {
245
+ const parts = Array.isArray(raw?.parts)
246
+ ? raw.parts
247
+ .filter((part) => typeof part?.name === "string")
248
+ .map((part) => ({
249
+ name: String(part.name),
250
+ label: typeof part.label === "string" ? part.label : partLabel(String(part.name)),
251
+ status: (part.status ?? "empty"),
252
+ file: typeof part.file === "string" ? part.file : undefined,
253
+ width: Number.isFinite(part.width) ? part.width : undefined,
254
+ height: Number.isFinite(part.height) ? part.height : undefined,
255
+ gridX: Number.isFinite(part.gridX) ? part.gridX : undefined,
256
+ gridY: Number.isFinite(part.gridY) ? part.gridY : undefined,
257
+ opacity: Number.isFinite(part.opacity) ? part.opacity : undefined,
258
+ source: part.source === "uploaded" ? "uploaded" : "generated",
259
+ approved: part.approved === true,
260
+ hidden: part.hidden === true,
261
+ error: typeof part.error === "string" ? part.error : undefined,
262
+ updatedAt: Number.isFinite(part.updatedAt) ? part.updatedAt : undefined,
263
+ role: typeof part.role === "string" && part.role !== "" ? part.role : undefined,
264
+ parent: typeof part.parent === "string" && part.parent !== "" ? part.parent : undefined,
265
+ proximal: Array.isArray(part.proximal) && part.proximal.length === 2 ? [num(part.proximal[0], 0.5), num(part.proximal[1], 0)] : undefined,
266
+ distal: Array.isArray(part.distal) && part.distal.length === 2 ? [num(part.distal[0], 0.5), num(part.distal[1], 1)] : undefined,
267
+ tags: Array.isArray(part.tags) ? part.tags.filter((tag) => typeof tag === "string") : undefined,
268
+ semanticsSource: part.semanticsSource === "ai" || part.semanticsSource === "human" ? part.semanticsSource : part.semanticsSource === "default" ? "default" : undefined,
269
+ versions: Array.isArray(part.versions)
270
+ ? part.versions
271
+ .filter((item) => typeof item?.file === "string" && Number.isFinite(item?.v))
272
+ .map((item) => ({
273
+ v: num(item.v, 1),
274
+ file: String(item.file),
275
+ width: num(item.width, 0),
276
+ height: num(item.height, 0),
277
+ source: item.source === "upload" || item.source === "tint" || item.source === "redraw"
278
+ ? item.source
279
+ : "generated",
280
+ note: typeof item.note === "string" ? item.note : undefined,
281
+ createdAt: num(item.createdAt, Date.now())
282
+ }))
283
+ : undefined,
284
+ activeTexture: Number.isFinite(part.activeTexture) ? part.activeTexture : undefined
285
+ }))
286
+ // 建完立刻对齐一次:`file/width/height` 永远是当前生效版本的镜像,
287
+ // 于是既有代码(装配/骨骼/图集/预览/资源路由)都不需要知道版本的存在。
288
+ .map((part) => {
289
+ syncActiveTexture(part);
290
+ return part;
291
+ })
292
+ : [];
293
+ const items = {};
294
+ const rawItems = raw?.layout?.items;
295
+ if (rawItems !== null && typeof rawItems === "object") {
296
+ for (const [name, value] of Object.entries(rawItems)) {
297
+ items[name] = {
298
+ x: num(value?.x, 0),
299
+ y: num(value?.y, 0),
300
+ width: Math.max(1, num(value?.width, 1)),
301
+ height: Math.max(1, num(value?.height, 1)),
302
+ scale: num(value?.scale, 1),
303
+ rotation: num(value?.rotation, 0),
304
+ z: num(value?.z, 0),
305
+ score: Number.isFinite(value?.score) ? value.score : undefined,
306
+ coverage: Number.isFinite(value?.coverage) ? value.coverage : undefined,
307
+ matched: value?.matched !== false,
308
+ manual: value?.manual === true
309
+ };
310
+ }
311
+ }
312
+ const animations = Array.isArray(raw?.settings?.animations)
313
+ ? raw.settings.animations.filter((value) => isAnimationId(value))
314
+ : [];
315
+ return {
316
+ id: String(raw?.id ?? ""),
317
+ name: typeof raw?.name === "string" && raw.name.trim() !== "" ? raw.name : "未命名骨骼动画任务",
318
+ createdAt: num(raw?.createdAt, Date.now()),
319
+ updatedAt: num(raw?.updatedAt, Date.now()),
320
+ source: typeof raw?.source?.file === "string"
321
+ ? {
322
+ file: raw.source.file,
323
+ name: String(raw.source.name ?? basename(raw.source.file)),
324
+ width: num(raw.source.width, 0),
325
+ height: num(raw.source.height, 0)
326
+ }
327
+ : undefined,
328
+ prompts: {
329
+ sheet: typeof raw?.prompts?.sheet === "string" ? raw.prompts.sheet : "",
330
+ suffix: typeof raw?.prompts?.suffix === "string" ? raw.prompts.suffix : ""
331
+ },
332
+ settings: {
333
+ model: typeof raw?.settings?.model === "string" ? raw.settings.model : "",
334
+ size: typeof raw?.settings?.size === "string" ? raw.settings.size : "2K",
335
+ watermark: raw?.settings?.watermark === true,
336
+ gridColumns: clampInt(raw?.settings?.gridColumns, RIG_GRID_COLUMNS, 1, 8),
337
+ gridRows: clampInt(raw?.settings?.gridRows, RIG_GRID_ROWS, 1, 8),
338
+ backgroundTolerance: clampInt(raw?.settings?.backgroundTolerance, 30, 1, 200),
339
+ feather: clampInt(raw?.settings?.feather, 26, 1, 200),
340
+ minArea: clampInt(raw?.settings?.minArea, 0, 0, 100000),
341
+ partPadding: clampInt(raw?.settings?.partPadding, 4, 0, 64),
342
+ matchLongEdge: clampInt(raw?.settings?.matchLongEdge, 448, 128, 1024),
343
+ animations: animations.length > 0 ? animations : defaultAnimationIds()
344
+ },
345
+ sheet: {
346
+ status: (raw?.sheet?.status ?? "empty"),
347
+ file: typeof raw?.sheet?.file === "string" ? raw.sheet.file : undefined,
348
+ width: Number.isFinite(raw?.sheet?.width) ? raw.sheet.width : undefined,
349
+ height: Number.isFinite(raw?.sheet?.height) ? raw.sheet.height : undefined,
350
+ error: typeof raw?.sheet?.error === "string" ? raw.sheet.error : undefined,
351
+ approved: raw?.sheet?.approved === true,
352
+ updatedAt: Number.isFinite(raw?.sheet?.updatedAt) ? raw.sheet.updatedAt : undefined
353
+ },
354
+ parts,
355
+ layout: {
356
+ status: (raw?.layout?.status ?? "empty"),
357
+ approved: raw?.layout?.approved === true,
358
+ error: typeof raw?.layout?.error === "string" ? raw.layout.error : undefined,
359
+ composite: typeof raw?.layout?.composite === "string" ? raw.layout.composite : undefined,
360
+ comparison: typeof raw?.layout?.comparison === "string" ? raw.layout.comparison : undefined,
361
+ hint: Number.isFinite(raw?.layout?.hint) ? raw.layout.hint : undefined,
362
+ meanScore: Number.isFinite(raw?.layout?.meanScore) ? raw.layout.meanScore : undefined,
363
+ suggestedOrder: Array.isArray(raw?.layout?.suggestedOrder) ? raw.layout.suggestedOrder.map(String) : undefined,
364
+ moved: Array.isArray(raw?.layout?.moved) ? raw.layout.moved.map(String) : undefined,
365
+ resolved: Array.isArray(raw?.layout?.resolved) ? raw.layout.resolved.map(String) : undefined,
366
+ items,
367
+ hints: normalizeHints(raw?.layout?.hints),
368
+ updatedAt: Number.isFinite(raw?.layout?.updatedAt) ? raw.layout.updatedAt : undefined
369
+ },
370
+ rig: {
371
+ status: (raw?.rig?.status ?? "empty"),
372
+ approved: raw?.rig?.approved === true,
373
+ error: typeof raw?.rig?.error === "string" ? raw.rig.error : undefined,
374
+ skeleton: typeof raw?.rig?.skeleton === "string" ? raw.rig.skeleton : undefined,
375
+ preview: typeof raw?.rig?.preview === "string" ? raw.rig.preview : undefined,
376
+ bones: Number.isFinite(raw?.rig?.bones) ? raw.rig.bones : undefined,
377
+ slots: Number.isFinite(raw?.rig?.slots) ? raw.rig.slots : undefined,
378
+ animations: Array.isArray(raw?.rig?.animations) ? raw.rig.animations.map(String) : undefined,
379
+ warnings: Array.isArray(raw?.rig?.warnings) ? raw.rig.warnings.map(String) : undefined,
380
+ boneList: Array.isArray(raw?.rig?.boneList)
381
+ ? raw.rig.boneList
382
+ .filter((bone) => typeof bone?.name === "string")
383
+ .map((bone) => ({
384
+ name: String(bone.name),
385
+ parent: typeof bone.parent === "string" ? bone.parent : undefined,
386
+ x: num(bone.x, 0),
387
+ y: num(bone.y, 0),
388
+ rotation: num(bone.rotation, 0),
389
+ length: num(bone.length, 0),
390
+ offset: pruneBoneOffset(bone.offset)
391
+ }))
392
+ : undefined,
393
+ // 同源的第二条导出路径(DragonBones 5.5)。
394
+ dragonBones: typeof raw?.rig?.dragonBones?.skeleton === "string" ? { skeleton: raw.rig.dragonBones.skeleton } : undefined,
395
+ updatedAt: Number.isFinite(raw?.rig?.updatedAt) ? raw.rig.updatedAt : undefined
396
+ },
397
+ atlas: {
398
+ status: (raw?.atlas?.status ?? "empty"),
399
+ approved: raw?.atlas?.approved === true,
400
+ error: typeof raw?.atlas?.error === "string" ? raw.atlas.error : undefined,
401
+ image: typeof raw?.atlas?.image === "string" ? raw.atlas.image : undefined,
402
+ text: typeof raw?.atlas?.text === "string" ? raw.atlas.text : undefined,
403
+ width: Number.isFinite(raw?.atlas?.width) ? raw.atlas.width : undefined,
404
+ height: Number.isFinite(raw?.atlas?.height) ? raw.atlas.height : undefined,
405
+ regions: Number.isFinite(raw?.atlas?.regions) ? raw.atlas.regions : undefined,
406
+ pages: Array.isArray(raw?.atlas?.pages)
407
+ ? raw.atlas.pages
408
+ .filter((page) => typeof page?.file === "string")
409
+ .map((page) => ({
410
+ file: String(page.file),
411
+ width: num(page.width, 0),
412
+ height: num(page.height, 0),
413
+ regions: num(page.regions, 0)
414
+ }))
415
+ : undefined,
416
+ warnings: Array.isArray(raw?.atlas?.warnings) ? raw.atlas.warnings.map(String) : undefined,
417
+ // DragonBones 贴图描述(逐页一份),与 `.atlas` 同一次装箱出来。
418
+ dragonBones: Array.isArray(raw?.atlas?.dragonBones?.textures)
419
+ ? { textures: raw.atlas.dragonBones.textures.filter((file) => typeof file === "string").map(String) }
420
+ : undefined,
421
+ updatedAt: Number.isFinite(raw?.atlas?.updatedAt) ? raw.atlas.updatedAt : undefined
422
+ },
423
+ reviewMode: raw?.reviewMode === "manual" ? "manual" : raw?.reviewMode === "auto" ? "auto" : undefined,
424
+ boneOffsets: normalizeBoneOffsets(raw?.boneOffsets),
425
+ animationSettings: normalizeAnimationSettings(raw?.animationSettings),
426
+ // 手工动画:读盘时也过一遍归一化(比写入时更宽松——老文件可能是手改的)。
427
+ animations: (() => {
428
+ const input = raw?.animations;
429
+ if (input === null || typeof input !== "object")
430
+ return undefined;
431
+ const out = {};
432
+ for (const [id, value] of Object.entries(input)) {
433
+ if (!isAnimationId(id))
434
+ continue;
435
+ const ignored = [];
436
+ const parsed = normalizeCustomAnimation(value, { duration: animationDurationOf(id, {}), loop: true }, ignored);
437
+ if (parsed !== undefined)
438
+ out[id] = parsed;
439
+ }
440
+ return Object.keys(out).length === 0 ? undefined : out;
441
+ })(),
442
+ qa: normalizeQaState(raw?.qa),
443
+ constraints: normalizeConstraints(raw?.constraints),
444
+ meshes: normalizeMeshes(raw?.meshes),
445
+ deforms: normalizeDeforms(raw?.deforms),
446
+ paths: normalizePaths(raw?.paths),
447
+ log: Array.isArray(raw?.log) ? raw.log.slice(-200) : []
448
+ };
449
+ }
450
+ /**
451
+ * 读盘时的 IK 约束归一化。
452
+ *
453
+ * 骨架那一侧还有一道更严的校验(`validateSpineWire`),这里只保证「读得出来、
454
+ * 字段类型对」——盘上的数据可能是手改的,不能让一条写坏的约束把整个任务卡死。
455
+ */
456
+ function normalizeConstraints(raw) {
457
+ if (!Array.isArray(raw))
458
+ return undefined;
459
+ const out = [];
460
+ for (const entry of raw) {
461
+ if (entry === null || typeof entry !== "object")
462
+ continue;
463
+ const value = entry;
464
+ if (typeof value.name !== "string" || value.name === "")
465
+ continue;
466
+ if (typeof value.bone !== "string" || value.bone === "")
467
+ continue;
468
+ out.push({
469
+ type: "ik",
470
+ name: value.name,
471
+ bone: value.bone,
472
+ target: typeof value.target === "string" && value.target !== "" ? value.target : `${value.name}-target`,
473
+ chain: Math.max(1, Math.min(8, Math.round(num(value.chain, 1)))),
474
+ bendPositive: value.bendPositive !== false,
475
+ weight: Math.max(0, Math.min(1, num(value.weight, 1)))
476
+ });
477
+ }
478
+ return out.length === 0 ? undefined : out;
479
+ }
480
+ /**
481
+ * 读盘时的蒙皮网格归一化。
482
+ *
483
+ * ⚠️ `normalizeRigJob` 是**白名单式**的:字段不在这里列出来就会被静默丢掉。
484
+ * 实测踩过——`setRigMesh` 明明写盘成功、日志也有记录,读回来却是 `undefined`,
485
+ * 表现是「加了网格但骨架里还是 region 附件」(排查时最容易怀疑错地方)。
486
+ */
487
+ function normalizeMeshes(raw) {
488
+ if (raw === null || typeof raw !== "object")
489
+ return undefined;
490
+ const out = {};
491
+ for (const [name, value] of Object.entries(raw)) {
492
+ if (value === null || typeof value !== "object")
493
+ continue;
494
+ out[name] = {
495
+ cols: Math.max(1, Math.min(MESH_MAX_DIVISIONS, Math.round(num(value.cols, MESH_DEFAULT_DIVISIONS)))),
496
+ rows: Math.max(1, Math.min(MESH_MAX_DIVISIONS, Math.round(num(value.rows, MESH_DEFAULT_DIVISIONS))))
497
+ };
498
+ }
499
+ return Object.keys(out).length === 0 ? undefined : out;
500
+ }
501
+ /** 读盘时的 FFD 变形归一化(同上:白名单字段,漏了就会静默丢)。 */
502
+ function normalizeDeforms(raw) {
503
+ if (raw === null || typeof raw !== "object")
504
+ return undefined;
505
+ const out = {};
506
+ for (const [name, value] of Object.entries(raw)) {
507
+ if (value === null || typeof value !== "object")
508
+ continue;
509
+ if (value.mode !== undefined && value.mode !== "wave")
510
+ continue;
511
+ out[name] = {
512
+ mode: "wave",
513
+ amplitude: Math.max(0, Math.min(400, num(value.amplitude, 0))),
514
+ cycles: Math.max(0.25, Math.min(8, num(value.cycles, 1))),
515
+ direction: num(value.direction, 0),
516
+ anchor: value.anchor === "bottom" || value.anchor === "none" ? value.anchor : "top",
517
+ duration: Math.max(0.1, Math.min(10, num(value.duration, 1.6)))
518
+ };
519
+ }
520
+ return Object.keys(out).length === 0 ? undefined : out;
521
+ }
522
+ /** 读盘时的 Path 约束归一化(同上:白名单字段,漏了就会静默丢)。 */
523
+ function normalizePaths(raw) {
524
+ if (raw === null || typeof raw !== "object")
525
+ return undefined;
526
+ const out = {};
527
+ for (const [name, value] of Object.entries(raw)) {
528
+ if (value === null || typeof value !== "object")
529
+ continue;
530
+ const path = normalizePath(value);
531
+ if (path === undefined)
532
+ continue;
533
+ const bones = Array.isArray(value.bones) ? value.bones.filter((entry) => typeof entry === "string") : [];
534
+ if (bones.length === 0)
535
+ continue;
536
+ out[name] = {
537
+ points: path.points,
538
+ closed: path.closed,
539
+ bones,
540
+ spacing: Math.max(0, num(value.spacing, 0)),
541
+ translateMix: Math.max(0, Math.min(1, num(value.translateMix, 1))),
542
+ rotateMix: Math.max(0, Math.min(1, num(value.rotateMix, 1)))
543
+ };
544
+ }
545
+ return Object.keys(out).length === 0 ? undefined : out;
546
+ }
547
+ /** 读盘时的质检状态归一化:字段缺失/手改过都不该让整个任务读不出来。 */
548
+ function normalizeQaState(raw) {
549
+ if (raw === null || typeof raw !== "object")
550
+ return undefined;
551
+ if (typeof raw.summary !== "string")
552
+ return undefined;
553
+ return {
554
+ ok: raw.ok === true,
555
+ score: num(raw.score, 0),
556
+ summary: raw.summary,
557
+ checked: num(raw.checked, 0),
558
+ duplicates: Array.isArray(raw.duplicates)
559
+ ? raw.duplicates
560
+ .filter((group) => Array.isArray(group?.parts))
561
+ .map((group) => ({
562
+ parts: group.parts.map(String),
563
+ minOverlap: num(group.minOverlap, 0),
564
+ mirroredOverlap: num(group.mirroredOverlap, 0),
565
+ symmetric: group.symmetric === true
566
+ }))
567
+ : [],
568
+ issues: Array.isArray(raw.issues)
569
+ ? raw.issues.map((issue) => ({
570
+ level: issue?.level === "error" ? "error" : "warning",
571
+ code: String(issue?.code ?? ""),
572
+ parts: Array.isArray(issue?.parts) ? issue.parts.map(String) : [],
573
+ message: String(issue?.message ?? ""),
574
+ suggestion: typeof issue?.suggestion === "string" ? issue.suggestion : undefined
575
+ }))
576
+ : [],
577
+ expectedParts: Number.isFinite(raw.expectedParts) ? raw.expectedParts : undefined,
578
+ updatedAt: Number.isFinite(raw.updatedAt) ? raw.updatedAt : Date.now()
579
+ };
580
+ }
581
+ // ── 对外视图 ────────────────────────────────────────────────────────────
582
+ /**
583
+ * 任务视图:界面与对话工具用的是**同一份形状**。
584
+ *
585
+ * 这里刻意做成「原始任务 + 算好的派生字段」的超集:
586
+ * - 界面需要原始字段(`settings` / `prompts` / `layout.items`)来编辑;
587
+ * - 对话工具需要派生字段(每个产物的绝对 URL、逐阶段状态、未命中清单)。
588
+ * 两处各拼一份的话,字段名迟早会漂移——实测就踩过:界面按派生字段写、
589
+ * 网关却返回原始任务,结果按钮因为读不到 `sourceUrl` 一直是灰的。
590
+ *
591
+ * `origin` 为空时返回**相对路径**(浏览器直接用);工具侧传 origin,
592
+ * 拿到的是可以直接贴给用户的绝对 URL。
593
+ */
594
+ /**
595
+ * 递归丢掉 `undefined` 属性。
596
+ *
597
+ * 工具返回值必须是**无损 JSON**:`undefined` 一旦出现在对象里,序列化时会静默
598
+ * 丢掉那个键,宿主据此判定「结果不是无损 JSON」并直接让整个工具调用报错
599
+ * (实测表现是 `game_material_status` / `game_material_wait` / `getRigJob`
600
+ * 全部返回 `value is not lossless JSON`)。视图里有大量可选字段,逐个写
601
+ * `?? null` 太容易漏,统一在出口处清一遍。
602
+ */
603
+ function lossless(value) {
604
+ if (Array.isArray(value))
605
+ return value.map((item) => lossless(item));
606
+ if (value !== null && typeof value === "object") {
607
+ const out = {};
608
+ for (const [key, item] of Object.entries(value)) {
609
+ if (item === undefined)
610
+ continue;
611
+ out[key] = lossless(item);
612
+ }
613
+ return out;
614
+ }
615
+ return value;
616
+ }
617
+ export function rigSnapshot(job, origin = "") {
618
+ const assetBase = `${origin}/dsh-game-material-master/rig-assets/${job.id}/`;
619
+ const url = (relative) => typeof relative === "string" && relative !== "" ? `${assetBase}${relative}` : undefined;
620
+ const items = job.layout.items;
621
+ const parts = job.parts.map((part) => {
622
+ const item = items[part.name];
623
+ return {
624
+ name: part.name,
625
+ label: part.label,
626
+ status: part.status,
627
+ source: part.source,
628
+ hidden: part.hidden === true,
629
+ approved: part.approved === true,
630
+ width: part.width,
631
+ height: part.height,
632
+ opacity: part.opacity,
633
+ gridX: part.gridX,
634
+ gridY: part.gridY,
635
+ file: part.file,
636
+ url: url(part.file),
637
+ placed: item !== undefined && item.matched === true,
638
+ manual: item?.manual === true,
639
+ score: item?.score,
640
+ coverage: item?.coverage,
641
+ error: part.error,
642
+ // 语义层:界面要能就地改,agent 要能读到「它认为这块是什么」。
643
+ role: part.role ?? null,
644
+ parent: part.parent ?? null,
645
+ proximal: part.proximal ?? null,
646
+ distal: part.distal ?? null,
647
+ tags: part.tags ?? [],
648
+ semanticsSource: part.semanticsSource ?? null,
649
+ // 贴图版本:界面要能在版本间切换(「这张 AI 头发不行,换回原版」)。
650
+ activeTexture: activeVersionOf(part)?.v ?? null,
651
+ versions: versionsOf(part).map((version) => ({
652
+ v: version.v,
653
+ file: version.file,
654
+ url: url(version.file),
655
+ width: version.width,
656
+ height: version.height,
657
+ source: version.source,
658
+ note: version.note ?? null,
659
+ createdAt: version.createdAt
660
+ }))
661
+ };
662
+ });
663
+ const stages = [
664
+ {
665
+ stage: "parts",
666
+ title: "① 拆件",
667
+ status: job.sheet.status,
668
+ approved: job.sheet.approved === true,
669
+ url: url(job.sheet.file),
670
+ file: job.sheet.file,
671
+ error: job.sheet.error,
672
+ partReady: parts.filter((part) => part.status === "ready").length
673
+ },
674
+ {
675
+ stage: "layout",
676
+ title: "② 装配定位",
677
+ status: job.layout.status,
678
+ approved: job.layout.approved === true,
679
+ composite: url(job.layout.composite),
680
+ comparison: url(job.layout.comparison),
681
+ hint: job.layout.hint ?? null,
682
+ meanScore: job.layout.meanScore ?? null,
683
+ hints: job.layout.hints ?? {},
684
+ moved: job.layout.moved ?? [],
685
+ resolved: job.layout.resolved ?? [],
686
+ unmatched: parts.filter((part) => part.status === "ready" && !part.placed).map((part) => part.name),
687
+ error: job.layout.error
688
+ },
689
+ {
690
+ stage: "rig",
691
+ title: "③ 骨骼与动画",
692
+ status: job.rig.status,
693
+ approved: job.rig.approved === true,
694
+ skeleton: url(job.rig.skeleton),
695
+ preview: url(job.rig.preview),
696
+ bones: job.rig.bones,
697
+ slots: job.rig.slots,
698
+ animations: job.rig.animations ?? [],
699
+ warnings: job.rig.warnings ?? [],
700
+ error: job.rig.error
701
+ },
702
+ {
703
+ stage: "atlas",
704
+ title: "④ 图集",
705
+ status: job.atlas.status,
706
+ approved: job.atlas.approved === true,
707
+ image: url(job.atlas.image),
708
+ text: url(job.atlas.text),
709
+ width: job.atlas.width,
710
+ height: job.atlas.height,
711
+ regions: job.atlas.regions,
712
+ error: job.atlas.error
713
+ }
714
+ ];
715
+ return lossless({
716
+ module: "rig",
717
+ id: job.id,
718
+ name: job.name,
719
+ /**
720
+ * 任务最后更新时间。客户端把它放在本地草稿的重置依赖里
721
+ * (`useEffect(..., [job.id, job.updatedAt])`)——缺了它,服务端状态变了
722
+ * 界面也不会清掉旧草稿,看起来就像「改了没反应」。
723
+ */
724
+ updatedAt: job.updatedAt,
725
+ reviewMode: job.reviewMode ?? null,
726
+ assetBase,
727
+ /**
728
+ * 任务目录的**本机绝对路径**。agent 要自己做视觉先验就得能直接看图,
729
+ * 而 read_image 之类只能读本机路径,给它 URL 没用。
730
+ */
731
+ dataDir: rigJobDir(job.id),
732
+ /** 「一眼看全部部件」的蒙太奇图(本机路径与 URL 都给)。 */
733
+ partsMontage: job.sheet.file === undefined ? null : "sheet/parts-montage.png",
734
+ partsMontageUrl: url("sheet/parts-montage.png"),
735
+ partsMontagePath: join(rigJobDir(job.id), "sheet/parts-montage.png"),
736
+ partsOrder: job.parts.map((part) => part.name),
737
+ sourcePath: job.source === undefined ? null : join(rigJobDir(job.id), job.source.file),
738
+ sourceFile: job.source?.file ?? null,
739
+ sourceUrl: url(job.source?.file),
740
+ canvas: job.source === undefined ? null : { width: job.source.width, height: job.source.height },
741
+ prompts: { sheet: job.prompts.sheet, suffix: job.prompts.suffix },
742
+ prompt: job.prompts.sheet,
743
+ suffix: job.prompts.suffix,
744
+ settings: job.settings,
745
+ /**
746
+ * 语义层的整体视图。
747
+ *
748
+ * 放在顶层而不是塞进某个阶段里,因为它是**装配与骨骼的共同输入**:
749
+ * 界面要在两个阶段都能看到「这块是什么、挂在谁身上」,agent 也要能拿到
750
+ * 「语义是否已经确认过、有没有结构问题」再决定下一步。
751
+ */
752
+ semantics: (() => {
753
+ const view = validateRigSemantics(job);
754
+ const ready = semanticPartsOf(job);
755
+ return {
756
+ ready: ready.length > 0 && ready.every((part) => part.role !== undefined),
757
+ confirmed: ready.length > 0 && ready.every((part) => part.semanticsSource === "human" || part.semanticsSource === "ai"),
758
+ count: ready.length,
759
+ ok: view.ok,
760
+ errors: view.errors,
761
+ warnings: view.warnings
762
+ };
763
+ })(),
764
+ // 拆件图阶段单独给一份,界面要直接拿 url 显示原图。
765
+ sheet: { status: job.sheet.status, approved: job.sheet.approved === true, url: url(job.sheet.file), file: job.sheet.file, error: job.sheet.error },
766
+ layout: {
767
+ status: job.layout.status,
768
+ approved: job.layout.approved === true,
769
+ error: job.layout.error,
770
+ items,
771
+ composite: url(job.layout.composite),
772
+ comparison: url(job.layout.comparison),
773
+ hint: job.layout.hint ?? null,
774
+ meanScore: job.layout.meanScore ?? null,
775
+ hints: job.layout.hints ?? {},
776
+ moved: job.layout.moved ?? [],
777
+ resolved: job.layout.resolved ?? []
778
+ },
779
+ rig: {
780
+ status: job.rig.status,
781
+ approved: job.rig.approved === true,
782
+ error: job.rig.error,
783
+ skeleton: url(job.rig.skeleton),
784
+ preview: url(job.rig.preview),
785
+ bones: job.rig.bones,
786
+ slots: job.rig.slots,
787
+ animations: job.rig.animations ?? [],
788
+ warnings: job.rig.warnings ?? [],
789
+ /**
790
+ * 上一次成功构建的骨骼表(含每根的手工偏移),界面用它画骨骼编辑器。
791
+ * 放在顶层 `rig` 而不是 `stages[]` 里:客户端读的是前者,
792
+ * 两个形状各拼一份的话字段名迟早会漂移(这个坑本项目以前踩过)。
793
+ */
794
+ boneList: job.rig.boneList ?? [],
795
+ /** DragonBones 5.5(`_ske.json`):与 `skeleton` 同源的第二条导出路径。 */
796
+ dragonBones: { skeleton: url(job.rig.dragonBones?.skeleton) },
797
+ /**
798
+ * 产物更新时间。
799
+ *
800
+ * 客户端拿它给预览 iframe 做缓存破除(`?v=`)——少了它,改完关键帧 / 骨骼偏移后
801
+ * 重算产物,React 会认为 iframe 的 src 没变、不重新挂载,**预览一直是旧的**。
802
+ * 这是「改了没反应」里最难查的一种:数据全对,只是没人让浏览器重新去拉。
803
+ */
804
+ updatedAt: job.rig.updatedAt,
805
+ /** 手工偏移的**当前真源**:骨骼还没重跑时,界面上也要能看到自己调过什么。 */
806
+ boneOffsets: job.boneOffsets ?? {},
807
+ /**
808
+ * 动画参数与**生效后的时长**。
809
+ *
810
+ * `presets` 给界面渲染可调项(连同预设的原始时长,好显示「你把它从 1.6 改成 1.0」),
811
+ * `durations` 是本次实际会写进 skeleton.json 的时长。
812
+ */
813
+ animationSettings: job.animationSettings ?? {},
814
+ /**
815
+ * 已经被手工/AI 编辑过的动画 id。时间轴编辑器据此标「已改」与给「还原」按钮;
816
+ * 具体的关键帧数据走 `getRigAnimation` 按需取,不塞进每 2 秒轮询的快照里。
817
+ */
818
+ customAnimations: Object.keys(job.animations ?? {}),
819
+ /**
820
+ * IK 约束(M5)。
821
+ *
822
+ * 连同**自动补出来的目标骨**一起给:界面要显示「这个点可以拖」,
823
+ * 而目标骨不在部件表里,界面无从推断。
824
+ */
825
+ constraints: job.constraints ?? [],
826
+ constraintTargets: (job.constraints ?? []).map((entry) => entry.target),
827
+ /**
828
+ * 蒙皮网格与 FFD 变形(M5)。
829
+ *
830
+ * 一起给界面,是因为编辑面板必须能回答「这块细分了吗、现在摆幅多大」——
831
+ * 少一个字段,界面上那个滑杆就只能显示默认值,用户改完看不出到底存了什么。
832
+ */
833
+ meshes: job.meshes ?? {},
834
+ /** Path 约束:点仍是**参考图像素**,界面/脚本读它来显示与编辑。 */
835
+ paths: job.paths ?? {},
836
+ deforms: job.deforms ?? {},
837
+ animationPresets: RIG_ANIMATIONS.map((preset) => ({
838
+ id: preset.id,
839
+ label: preset.label,
840
+ summary: preset.summary,
841
+ loop: preset.loop,
842
+ defaultDuration: preset.duration,
843
+ duration: animationDurationOf(preset.id, job.animationSettings ?? {}),
844
+ amplitude: job.animationSettings?.[preset.id]?.amplitude ?? 1,
845
+ enabled: (job.settings.animations ?? []).includes(preset.id)
846
+ }))
847
+ },
848
+ atlas: {
849
+ status: job.atlas.status,
850
+ approved: job.atlas.approved === true,
851
+ error: job.atlas.error,
852
+ image: url(job.atlas.image),
853
+ text: url(job.atlas.text),
854
+ url: url(job.atlas.image),
855
+ width: job.atlas.width,
856
+ height: job.atlas.height,
857
+ regions: job.atlas.regions,
858
+ /** 多页图集(单页时只有一项)。界面要能逐页预览。 */
859
+ pages: job.atlas.pages ?? [],
860
+ /** DragonBones 贴图描述(`_tex.json`,逐页一份):与 `.atlas` 同一次装箱的孪生兄弟。 */
861
+ dragonBones: (job.atlas.dragonBones?.textures ?? []).map((file) => ({ file, url: url(file) })),
862
+ /** 校验给出的提示(错误会让图集阶段直接失败,不会走到这里)。 */
863
+ warnings: job.atlas.warnings ?? []
864
+ },
865
+ busy: stages.some((stage) => stage.status === "running") || listRigTasks(job.id).length > 0,
866
+ stages,
867
+ parts,
868
+ /**
869
+ * 拆件质检:**装配之前**就该看的结论。
870
+ *
871
+ * 放在顶层而不是塞进某个阶段:它同时管「拆件可不可信」与「装配准不准」,
872
+ * 而这两件事分别属于①②两个阶段。`null` = 还没跑过(老任务)。
873
+ */
874
+ qa: job.qa ?? null,
875
+ review: {
876
+ parts: parts.filter((part) => part.status === "ready").length,
877
+ approved: parts.filter((part) => part.approved).length,
878
+ placed: parts.filter((part) => part.placed).length,
879
+ unmatched: parts.filter((part) => part.status === "ready" && !part.placed).map((part) => part.name),
880
+ errors: stages.filter((stage) => stage.status === "error").map((stage) => stage.stage)
881
+ },
882
+ runningTasks: listRigTasks(job.id),
883
+ log: job.log
884
+ });
885
+ }
886
+ // ── 素材上传 ────────────────────────────────────────────────────────────
887
+ export async function setRigSource(jobId, name, base64) {
888
+ const job = await readRigJob(jobId);
889
+ if (job === undefined)
890
+ throw new Error(`任务不存在:${jobId}`);
891
+ const clean = base64.replace(/^data:[^;]+;base64,/, "");
892
+ const sniffed = sniffImage(clean);
893
+ if (sniffed === undefined)
894
+ throw new Error("无法识别的图片格式(支持 PNG / JPEG / WebP / BMP)");
895
+ const bytes = Buffer.from(clean, "base64");
896
+ if (bytes.length === 0)
897
+ throw new Error("图片数据为空");
898
+ if (bytes.length > 30 * 1024 * 1024)
899
+ throw new Error("参考图超过 30 MB,请先压缩后再上传");
900
+ const stem = safeName(name).replace(/\.[^.]+$/, "") || "character";
901
+ const relative = `source/${stem}.${sniffed.ext}`;
902
+ await mkdir(join(rigJobDir(jobId), "source"), { recursive: true });
903
+ await writeFile(rigAssetPath(jobId, relative), bytes);
904
+ const decoded = await decodeToRgba(rigAssetPath(jobId, relative), 2048);
905
+ job.source = { file: relative, name: safeName(name), width: decoded.width, height: decoded.height };
906
+ appendJobLog(job.log, "info", `已上传角色参考图:${safeName(name)}(${decoded.width}×${decoded.height})`);
907
+ await writeRigJob(job);
908
+ return { width: decoded.width, height: decoded.height };
909
+ }
910
+ /** 上传一张现成的部件 PNG(跳过生图拆件,直接进入装配)。 */
911
+ export async function uploadRigPart(jobId, name, base64) {
912
+ const job = await readRigJob(jobId);
913
+ if (job === undefined)
914
+ throw new Error(`任务不存在:${jobId}`);
915
+ const clean = base64.replace(/^data:[^;]+;base64,/, "");
916
+ const sniffed = sniffImage(clean);
917
+ if (sniffed === undefined)
918
+ throw new Error("无法识别的图片格式(支持 PNG / JPEG / WebP / BMP)");
919
+ const bytes = Buffer.from(clean, "base64");
920
+ if (bytes.length === 0)
921
+ throw new Error("图片数据为空");
922
+ if (bytes.length > 30 * 1024 * 1024)
923
+ throw new Error("部件图超过 30 MB");
924
+ // 用文件名(去掉扩展名)当部件名:这是用户表达「这块是什么」的唯一通道,
925
+ // 骨骼层级完全依赖它。
926
+ const rawName = safeName(name).replace(/\.[^.]+$/, "");
927
+ const partName = (rawName === "" ? `part-${job.parts.length + 1}` : rawName).slice(0, 48);
928
+ await mkdir(join(rigJobDir(jobId), "parts"), { recursive: true });
929
+ // 统一落到临时文件再解码:上传的可能是 JPEG(部件目录要保持只有 PNG),
930
+ // 而且「新增一版」需要先拿到 RGBA 再编码。
931
+ const tempFile = join(rigJobDir(jobId), "parts", `.incoming-${Date.now()}.${sniffed.ext}`);
932
+ await writeFile(tempFile, bytes);
933
+ let decoded;
934
+ try {
935
+ decoded = await decodeToRgba(tempFile, 2048);
936
+ }
937
+ finally {
938
+ await rm(tempFile, { force: true }).catch(() => undefined);
939
+ }
940
+ const rgba = { data: decoded.rgba, width: decoded.width, height: decoded.height };
941
+ const existing = job.parts.find((part) => part.name === partName);
942
+ if (existing !== undefined) {
943
+ // **同名上传 = 顶掉当前贴图**,但是新增一个版本,不覆盖原图——
944
+ // 这正是方案里「手工上传替换」应有的手感:换错了随时切回来。
945
+ const created = await addTextureVersion(jobId, existing, { source: "upload", note: "手工上传", rgba });
946
+ invalidateFrom(job, "parts");
947
+ ensurePartSemantics(job);
948
+ appendJobLog(job.log, "info", `已上传「${partName}」的新贴图 v${created.v}(${created.width}×${created.height})`);
949
+ await writeRigJob(job);
950
+ return { name: partName, width: created.width, height: created.height };
951
+ }
952
+ const relative = textureFileName(partName, 1);
953
+ await writeFile(rigAssetPath(jobId, relative), encodePng(rgba.data, rgba.width, rgba.height));
954
+ const node = {
955
+ name: partName,
956
+ label: partLabel(partName),
957
+ status: "ready",
958
+ file: relative,
959
+ width: rgba.width,
960
+ height: rgba.height,
961
+ source: "uploaded",
962
+ approved: false,
963
+ versions: [
964
+ {
965
+ v: 1,
966
+ file: relative,
967
+ width: rgba.width,
968
+ height: rgba.height,
969
+ source: "upload",
970
+ note: "手工上传",
971
+ createdAt: Date.now()
972
+ }
973
+ ],
974
+ activeTexture: 1,
975
+ updatedAt: Date.now()
976
+ };
977
+ job.parts.push(node);
978
+ // 部件变了,后面的阶段全部作废。
979
+ invalidateFrom(job, "parts");
980
+ // 新上传的部件补一次语义——文件名就是它唯一的语义线索(`head.png` → 头部),
981
+ // 其余字段按角色默认填上;用户之后可以只改不对的那几条。
982
+ ensurePartSemantics(job);
983
+ appendJobLog(job.log, "info", `已上传部件「${partName}」(${rgba.width}×${rgba.height})`);
984
+ await writeRigJob(job);
985
+ return { name: partName, width: rgba.width, height: rgba.height };
986
+ }
987
+ export async function removeRigPart(jobId, name) {
988
+ const job = await readRigJob(jobId);
989
+ if (job === undefined)
990
+ throw new Error(`任务不存在:${jobId}`);
991
+ const node = job.parts.find((part) => part.name === name);
992
+ if (node === undefined)
993
+ throw new Error(`没有这个部件:${name}`);
994
+ job.parts = job.parts.filter((part) => part.name !== name);
995
+ delete job.layout.items[name];
996
+ // 它的**所有**贴图版本都要删掉,否则会在 parts/ 下留一堆孤儿文件。
997
+ for (const version of versionsOf(node)) {
998
+ await rm(rigAssetPath(jobId, version.file), { force: true }).catch(() => undefined);
999
+ }
1000
+ // 别的部件的父级可能指向它;先摘掉再修复,避免留下悬空父级。
1001
+ for (const other of job.parts)
1002
+ if (other.parent === name)
1003
+ other.parent = undefined;
1004
+ // 它自己的手工偏移也一并清掉,否则会留下一条永远用不上的孤儿记录。
1005
+ if (job.boneOffsets?.[name] !== undefined) {
1006
+ const rest = { ...job.boneOffsets };
1007
+ delete rest[name];
1008
+ job.boneOffsets = Object.keys(rest).length === 0 ? undefined : rest;
1009
+ }
1010
+ invalidateFrom(job, "parts");
1011
+ ensurePartSemantics(job);
1012
+ appendJobLog(job.log, "info", `已删除部件「${name}」`);
1013
+ await writeRigJob(job);
1014
+ }
1015
+ /**
1016
+ * 给部件改名(拆件图没按网格摆时,用户需要手工把它命名成 head / torso / …)。
1017
+ * 名字直接决定骨骼层级与动画能否套上,所以这里是主要的人工兜底通道。
1018
+ */
1019
+ export async function renameRigPart(jobId, from, to) {
1020
+ const job = await readRigJob(jobId);
1021
+ if (job === undefined)
1022
+ throw new Error(`任务不存在:${jobId}`);
1023
+ const node = job.parts.find((part) => part.name === from);
1024
+ if (node === undefined)
1025
+ throw new Error(`没有这个部件:${from}`);
1026
+ const name = to.trim().replace(/[^\w\-\u4e00-\u9fa5]/g, "-").slice(0, 48);
1027
+ if (name === "")
1028
+ throw new Error("部件名不能为空");
1029
+ if (job.parts.some((part) => part.name === name && part.name !== from))
1030
+ throw new Error(`已经有叫「${name}」的部件了`);
1031
+ if (node.file !== undefined) {
1032
+ // 改名要连**所有贴图版本**一起搬:只搬当前那一版的话,之后回退会指到
1033
+ // 一个已经不存在的文件(而文件其实还在,只是名字对不上)。
1034
+ const versions = versionsOf(node);
1035
+ for (const version of versions) {
1036
+ const target = textureFileName(name, version.v);
1037
+ if (version.file === target)
1038
+ continue;
1039
+ await rename(rigAssetPath(jobId, version.file), rigAssetPath(jobId, target)).catch(() => undefined);
1040
+ version.file = target;
1041
+ }
1042
+ node.versions = versions;
1043
+ node.file = textureFileName(name, node.activeTexture ?? versions[versions.length - 1]?.v ?? 1);
1044
+ }
1045
+ if (job.layout.items[from] !== undefined) {
1046
+ job.layout.items[name] = job.layout.items[from];
1047
+ delete job.layout.items[from];
1048
+ }
1049
+ node.name = name;
1050
+ node.label = partLabel(name);
1051
+ // 改名会改变语义推断(`left-lower-arm` 与 `blob-3` 的角色完全不同),
1052
+ // 所以把别人的父级引用改过来,再重算这一条的角色/锚点。
1053
+ for (const other of job.parts)
1054
+ if (other.parent === from)
1055
+ other.parent = name;
1056
+ // 手工骨骼偏移是按名字索引的,改名要跟着搬——否则用户改个名就「白调了」。
1057
+ if (job.boneOffsets?.[from] !== undefined) {
1058
+ const moved = { ...job.boneOffsets };
1059
+ moved[name] = moved[from];
1060
+ delete moved[from];
1061
+ job.boneOffsets = moved;
1062
+ }
1063
+ node.role = undefined;
1064
+ node.proximal = undefined;
1065
+ node.distal = undefined;
1066
+ node.semanticsSource = undefined;
1067
+ // ⚠️ 只作废「骨骼与图集」,**不动装配结果**:改名改的是角色/父级/锚点,
1068
+ // 而布局位置与名字无关。作废到 layout 会让用户白丢一次手工摆位。
1069
+ invalidateFrom(job, "rig");
1070
+ ensurePartSemantics(job);
1071
+ appendJobLog(job.log, "info", `部件「${from}」已改名为「${name}」(语义已按新名字重算)`);
1072
+ await writeRigJob(job);
1073
+ }
1074
+ export async function setRigPartVisibility(jobId, name, hidden) {
1075
+ const job = await readRigJob(jobId);
1076
+ if (job === undefined)
1077
+ throw new Error(`任务不存在:${jobId}`);
1078
+ const node = job.parts.find((part) => part.name === name);
1079
+ if (node === undefined)
1080
+ throw new Error(`没有这个部件:${name}`);
1081
+ node.hidden = hidden;
1082
+ invalidateFrom(job, "layout");
1083
+ await writeRigJob(job);
1084
+ }
1085
+ export async function setRigPartApproved(jobId, name, approved) {
1086
+ const job = await readRigJob(jobId);
1087
+ if (job === undefined)
1088
+ throw new Error(`任务不存在:${jobId}`);
1089
+ let touched = 0;
1090
+ for (const part of job.parts) {
1091
+ if (name === undefined || part.name === name) {
1092
+ part.approved = approved;
1093
+ touched++;
1094
+ }
1095
+ }
1096
+ if (name !== undefined && touched === 0)
1097
+ throw new Error(`没有这个部件:${name}`);
1098
+ await writeRigJob(job);
1099
+ return touched;
1100
+ }
1101
+ export async function setRigStageApproved(jobId, stage, approved) {
1102
+ const job = await readRigJob(jobId);
1103
+ if (job === undefined)
1104
+ throw new Error(`任务不存在:${jobId}`);
1105
+ if (stage === "parts") {
1106
+ job.sheet.approved = approved;
1107
+ for (const part of job.parts)
1108
+ if (part.status === "ready")
1109
+ part.approved = approved;
1110
+ }
1111
+ else if (stage === "layout") {
1112
+ job.layout.approved = approved;
1113
+ }
1114
+ else if (stage === "rig") {
1115
+ job.rig.approved = approved;
1116
+ }
1117
+ else if (stage === "atlas") {
1118
+ job.atlas.approved = approved;
1119
+ }
1120
+ else {
1121
+ throw new Error(`未知阶段:${stage}`);
1122
+ }
1123
+ await writeRigJob(job);
1124
+ }
1125
+ export async function saveRigPrompts(jobId, patch) {
1126
+ const job = await readRigJob(jobId);
1127
+ if (job === undefined)
1128
+ throw new Error(`任务不存在:${jobId}`);
1129
+ if (typeof patch.sheet === "string")
1130
+ job.prompts.sheet = patch.sheet;
1131
+ if (typeof patch.suffix === "string")
1132
+ job.prompts.suffix = patch.suffix;
1133
+ if (patch.resetSheet === true)
1134
+ job.prompts.sheet = buildSheetPrompt(job.settings.gridColumns, job.settings.gridRows, rigSlotNames(job));
1135
+ await writeRigJob(job);
1136
+ }
1137
+ export async function saveRigSettings(jobId, raw) {
1138
+ const job = await readRigJob(jobId);
1139
+ if (job === undefined)
1140
+ throw new Error(`任务不存在:${jobId}`);
1141
+ const before = { ...job.settings };
1142
+ job.settings.gridColumns = clampInt(raw.gridColumns, job.settings.gridColumns, 1, 8);
1143
+ job.settings.gridRows = clampInt(raw.gridRows, job.settings.gridRows, 1, 8);
1144
+ job.settings.backgroundTolerance = clampInt(raw.backgroundTolerance, job.settings.backgroundTolerance, 1, 200);
1145
+ job.settings.feather = clampInt(raw.feather, job.settings.feather, 1, 200);
1146
+ job.settings.minArea = clampInt(raw.minArea, job.settings.minArea, 0, 100000);
1147
+ job.settings.partPadding = clampInt(raw.partPadding, job.settings.partPadding, 0, 64);
1148
+ job.settings.matchLongEdge = clampInt(raw.matchLongEdge, job.settings.matchLongEdge, 128, 1024);
1149
+ job.settings.size = typeof raw.size === "string" && raw.size.trim() !== "" ? raw.size : job.settings.size;
1150
+ job.settings.watermark = raw.watermark === true;
1151
+ if (Array.isArray(raw.animations)) {
1152
+ const list = raw.animations.filter((value) => isAnimationId(value));
1153
+ job.settings.animations = list.length > 0 ? list : defaultAnimationIds();
1154
+ }
1155
+ // 分割参数改了,已经切出来的部件就作废;网格尺寸改了连摊平图都要重生成。
1156
+ const segmentationChanged = before.backgroundTolerance !== job.settings.backgroundTolerance ||
1157
+ before.feather !== job.settings.feather ||
1158
+ before.minArea !== job.settings.minArea ||
1159
+ before.partPadding !== job.settings.partPadding;
1160
+ const gridChanged = before.gridColumns !== job.settings.gridColumns || before.gridRows !== job.settings.gridRows;
1161
+ const animationsChanged = JSON.stringify(before.animations) !== JSON.stringify(job.settings.animations);
1162
+ if (gridChanged || segmentationChanged)
1163
+ invalidateFrom(job, "sheet");
1164
+ else if (animationsChanged)
1165
+ invalidateFrom(job, "rig");
1166
+ await writeRigJob(job);
1167
+ return { changed: gridChanged || segmentationChanged };
1168
+ }
1169
+ /**
1170
+ * 让某个阶段**及其之后**的产物失效。
1171
+ *
1172
+ * 流水线的依赖是一条直线(拆件图 → 部件 → 装配 → 骨骼 → 图集),任何上游变化都会
1173
+ * 让下游的产物对不上。这里集中处理,避免每个入口各写一遍、漏掉某一层。
1174
+ *
1175
+ * 两个阶段的处理**故意不同**:
1176
+ *
1177
+ * - **`layout` 保留 `items`,只取消「通过」**。装配结果里存的是**人的劳动**
1178
+ * (手工拖过的每一个位置),而「改一个先验」「隐藏一个部件」都只是让它需要重算——
1179
+ * 顺手清空等于把用户摆好的位置一次抹掉。
1180
+ * - **`rig` / `atlas` 直接置空**。它们是纯派生物(重跑就有),而改了骨骼偏移、
1181
+ * 动画或语义之后它们确实是旧的:只清「通过」标记的话,界面继续显示「已完成」,
1182
+ * 用户以为改动已经生效了(实测踩过:改完动画参数后 `rig.status` 仍是 `ready`)。
1183
+ */
1184
+ const STAGE_ORDER = ["sheet", "parts", "layout", "rig", "atlas"];
1185
+ function invalidateFrom(job, stage) {
1186
+ const from = STAGE_ORDER.indexOf(stage);
1187
+ const at = (key) => STAGE_ORDER.indexOf(key);
1188
+ if (from <= at("sheet")) {
1189
+ // 拆件图要重画:生图切出来的部件全部作废,用户手工上传的保留。
1190
+ job.parts = job.parts.filter((part) => part.source === "uploaded" && part.status === "ready");
1191
+ job.sheet = { ...job.sheet, approved: false };
1192
+ }
1193
+ else {
1194
+ for (const part of job.parts)
1195
+ part.approved = false;
1196
+ }
1197
+ // 只有**上游**变了才谈得上清空装配结果(部件本身都换了,旧位置没有意义)。
1198
+ if (from < at("layout"))
1199
+ job.layout = { status: "empty", items: {} };
1200
+ else
1201
+ job.layout.approved = false;
1202
+ if (from <= at("rig"))
1203
+ job.rig = { status: "empty" };
1204
+ if (from <= at("atlas"))
1205
+ job.atlas = { status: "empty" };
1206
+ }
1207
+ // ── 后台任务 ────────────────────────────────────────────────────────────
1208
+ const running = new Map();
1209
+ const pollers = new Map();
1210
+ let disposed = false;
1211
+ export function disposeRig() {
1212
+ disposed = true;
1213
+ for (const timer of pollers.values())
1214
+ clearInterval(timer);
1215
+ pollers.clear();
1216
+ running.clear();
1217
+ }
1218
+ export function listRigTasks(jobId) {
1219
+ return [...(running.get(jobId) ?? [])];
1220
+ }
1221
+ function kick(jobId, taskKey, fn) {
1222
+ if (disposed)
1223
+ return false;
1224
+ const set = running.get(jobId) ?? new Set();
1225
+ running.set(jobId, set);
1226
+ if (set.has(taskKey))
1227
+ return false;
1228
+ set.add(taskKey);
1229
+ void (async () => {
1230
+ try {
1231
+ await fn();
1232
+ }
1233
+ catch (error) {
1234
+ const job = await readRigJob(jobId);
1235
+ if (job !== undefined) {
1236
+ appendJobLog(job.log, "error", `${taskKey} 失败:${messageOf(error)}`);
1237
+ await writeRigJob(job);
1238
+ }
1239
+ }
1240
+ finally {
1241
+ set.delete(taskKey);
1242
+ if (set.size === 0)
1243
+ running.delete(jobId);
1244
+ }
1245
+ })();
1246
+ return true;
1247
+ }
1248
+ function assertIdle(jobId, taskKey, what) {
1249
+ if (running.get(jobId)?.has(taskKey) === true)
1250
+ throw new Error(`${what}已在进行中,请等它跑完`);
1251
+ }
1252
+ /** 生图任务要轮询,占位保持接口形状(当前只在任务内轮询,不需要外部驱动)。 */
1253
+ export function stopRigPoller(jobId) {
1254
+ const timer = pollers.get(jobId);
1255
+ if (timer !== undefined)
1256
+ clearInterval(timer);
1257
+ pollers.delete(jobId);
1258
+ }
1259
+ // ── 贴图版本(阶段⑦)────────────────────────────────────────────────────
1260
+ /** 某个部件的版本列表;老任务没有这个字段时按「当前文件就是 v1」合成一份。 */
1261
+ export function versionsOf(part) {
1262
+ if (Array.isArray(part.versions) && part.versions.length > 0)
1263
+ return part.versions;
1264
+ if (part.file === undefined)
1265
+ return [];
1266
+ return [
1267
+ {
1268
+ v: 1,
1269
+ file: part.file,
1270
+ width: part.width ?? 0,
1271
+ height: part.height ?? 0,
1272
+ source: part.source === "uploaded" ? "upload" : "generated",
1273
+ createdAt: part.updatedAt ?? Date.now()
1274
+ }
1275
+ ];
1276
+ }
1277
+ export function activeVersionOf(part) {
1278
+ const versions = versionsOf(part);
1279
+ if (versions.length === 0)
1280
+ return undefined;
1281
+ const wanted = part.activeTexture;
1282
+ return versions.find((item) => item.v === wanted) ?? versions[versions.length - 1];
1283
+ }
1284
+ /**
1285
+ * 把当前生效版本镜像到 `part.file` / `width` / `height`。
1286
+ *
1287
+ * **这是整套版本机制能向后兼容的关键**:所有既有代码(装配、骨骼、图集、
1288
+ * 预览、资源路由)读的仍然是 `part.file`,它们完全不需要知道版本的存在。
1289
+ */
1290
+ function syncActiveTexture(part) {
1291
+ const active = activeVersionOf(part);
1292
+ if (active === undefined)
1293
+ return;
1294
+ part.versions = versionsOf(part);
1295
+ part.activeTexture = active.v;
1296
+ part.file = active.file;
1297
+ part.width = active.width;
1298
+ part.height = active.height;
1299
+ }
1300
+ function textureFileName(name, version) {
1301
+ // v1 沿用旧命名,这样已存在的任务与文件不用搬家。
1302
+ return version <= 1 ? `parts/${name}.png` : `parts/${name}.v${version}.png`;
1303
+ }
1304
+ /**
1305
+ * 追加一个版本并把它设为当前生效。
1306
+ *
1307
+ * 三种来源共用这一条路径(换色 / 重绘 / 手工上传),所以「回退」的实现只有一份,
1308
+ * 而且任何一版都**不会被覆盖**——这是「这张不行换回原版」能零成本做到的前提。
1309
+ */
1310
+ async function addTextureVersion(jobId, part, input) {
1311
+ const versions = versionsOf(part);
1312
+ const nextVersion = versions.reduce((max, item) => Math.max(max, item.v), 0) + 1;
1313
+ const relative = textureFileName(part.name, nextVersion);
1314
+ await mkdir(join(rigJobDir(jobId), "parts"), { recursive: true });
1315
+ await writeFile(rigAssetPath(jobId, relative), encodePng(input.rgba.data, input.rgba.width, input.rgba.height));
1316
+ const version = {
1317
+ v: nextVersion,
1318
+ file: relative,
1319
+ width: input.rgba.width,
1320
+ height: input.rgba.height,
1321
+ source: input.source,
1322
+ note: input.note,
1323
+ createdAt: Date.now()
1324
+ };
1325
+ part.versions = [...versions, version];
1326
+ part.activeTexture = version.v;
1327
+ syncActiveTexture(part);
1328
+ return version;
1329
+ }
1330
+ /** 把一批部件标成「贴图变了」:预览内联图片、图集要重打包,但装配位置不受影响。 */
1331
+ function invalidateTextures(job) {
1332
+ invalidateFrom(job, "rig");
1333
+ }
1334
+ /** 解析「改哪些部件」:名字优先,其次按标签;两者都没给就是全部。 */
1335
+ function resolveTextureTargets(job, target) {
1336
+ const ready = job.parts.filter((part) => part.status === "ready");
1337
+ if (target.names !== undefined && target.names.length > 0) {
1338
+ const missing = target.names.filter((name) => !ready.some((part) => part.name === name));
1339
+ if (missing.length > 0)
1340
+ throw new Error(`没有这些部件:${missing.join("、")}`);
1341
+ return ready.filter((part) => target.names.includes(part.name));
1342
+ }
1343
+ if (target.tag !== undefined && target.tag !== "") {
1344
+ const matched = ready.filter((part) => (part.tags ?? []).includes(target.tag));
1345
+ if (matched.length === 0)
1346
+ throw new Error(`没有带「${target.tag}」标签的部件`);
1347
+ return matched;
1348
+ }
1349
+ return ready;
1350
+ }
1351
+ /**
1352
+ * 换色(本地计算,免费)。
1353
+ *
1354
+ * 之所以**烤成一个新版本**而不是每次渲染时实时算:渲染发生在浏览器(预览)
1355
+ * 与宿主(合成图/图集)两处,各自实现一遍着色只会让两边漂移;而且版本机制
1356
+ * 天然给了「换个色不满意 → 回退」,不需要额外的撤销栈。
1357
+ */
1358
+ export async function tintRigParts(jobId, target, tint, options = {}) {
1359
+ const job = await readRigJob(jobId);
1360
+ if (job === undefined)
1361
+ throw new Error(`任务不存在:${jobId}`);
1362
+ const parts = resolveTextureTargets(job, target);
1363
+ if (parts.length === 0)
1364
+ throw new Error("没有可换色的部件");
1365
+ const versions = {};
1366
+ for (const part of parts) {
1367
+ const active = activeVersionOf(part);
1368
+ if (active === undefined)
1369
+ continue;
1370
+ const decoded = await decodeToRgba(rigAssetPath(jobId, active.file), 2048);
1371
+ const tinted = tintRgba({ data: decoded.rgba, width: decoded.width, height: decoded.height }, tint);
1372
+ const created = await addTextureVersion(jobId, part, { source: "tint", note: options.note, rgba: tinted });
1373
+ versions[part.name] = created.v;
1374
+ }
1375
+ invalidateTextures(job);
1376
+ appendJobLog(job.log, "info", `${options.by === "ai" ? "AI" : "手工"}换色:${parts.map((part) => part.name).join("、")}` +
1377
+ (options.note === undefined ? "" : `(${options.note})`));
1378
+ await writeRigJob(job);
1379
+ return { touched: parts.length, versions };
1380
+ }
1381
+ // ── AI 逐部件重绘(花钱,可选)──────────────────────────────────────────
1382
+ export const REDRAW_TASK_KEY = "redraw";
1383
+ /**
1384
+ * 补边用的底色。
1385
+ *
1386
+ * **不能用白色**:部件常有浅色的(浅肤色手、白袜、白围裙),补成白底之后整张图
1387
+ * 几乎是纯白,模型看不到主体,实测会直接交回一张空白图。
1388
+ * 中灰对浅色与深色部件都有对比度,而且这一层底色在结果里会被 alpha 掩码切掉,
1389
+ * 不会污染像素。
1390
+ */
1391
+ const REDRAW_PAD_COLOR = [128, 128, 128];
1392
+ /** 结果的最低亮度标准差:低于它就认为「模型没画出内容」。 */
1393
+ const MIN_REDRAW_CONTRAST = 6;
1394
+ /** 一次重绘的提示词。
1395
+ *
1396
+ * 写法上踩过两个真实的坑,注释留在原处免得后人重踩:
1397
+ *
1398
+ * ① **必须有具体主语**。实测提示词里最具体的一句是「flat clean background of a
1399
+ * single solid colour」,模型就老老实实交回一张纯色图——补边是白底就返回白、
1400
+ * 换成灰底就返回灰。所以主语(「一只手」这类)由**语义层的角色**给出,
1401
+ * 这比反复强调整体约束有用得多。
1402
+ * ② **不要叫模型去画背景**。背景在我们的流水线里会被 alpha 掩码切掉,
1403
+ * 提它只会分散模型的注意力。
1404
+ */
1405
+ export function buildRedrawPrompt(instruction, options = {}) {
1406
+ const detail = instruction.trim() === "" ? "keep the original look, only clean it up" : instruction.trim();
1407
+ const noun = ROLE_NOUNS[(options.role ?? "")] ?? "body part";
1408
+ return [
1409
+ `A single detached ${noun} of a 2D game character, shown alone on a plain background.`,
1410
+ "",
1411
+ `Repaint it as follows: ${detail}.`,
1412
+ "",
1413
+ "Requirements:",
1414
+ `- draw the ${noun} clearly, filling roughly the same area and position as in the reference image;`,
1415
+ "- keep the same silhouette and pose as the reference image;",
1416
+ "- it is ONE body part only; never assemble a whole character;",
1417
+ "- no text, no watermark, no background scenery.",
1418
+ "",
1419
+ "Negative: blank image, empty canvas, missing subject, full body, multiple connected parts."
1420
+ ].join("\n");
1421
+ }
1422
+ /** 提示词摘要:写进版本的 `note`,回退时能看懂这一版是什么。 */
1423
+ function summarizePrompt(prompt) {
1424
+ const flat = prompt.replace(/\s+/g, " ").trim();
1425
+ return flat.length <= 28 ? flat : `${flat.slice(0, 28)}…`;
1426
+ }
1427
+ /**
1428
+ * 用生图模型重绘**单个部件**(花钱:一次 Seedream 调用)。
1429
+ *
1430
+ * 与参考项目 reskin-app 的根本区别:它把**整张 atlas / 整张合成图**丢给模型,
1431
+ * 回来必须再用 SAM / 连通域 / IoU 模板反向切回各个 slot。这里是**一个部件进、
1432
+ * 一个部件出**——所以那一整套反向切分**完全不需要**。
1433
+ *
1434
+ * 三步保证「重绘后位置不乱」:
1435
+ * ① 先把部件补成**正方形**再送出去(模型会按自己的画幅习惯重排画面);
1436
+ * ② 按同样的正方形裁回来、缩回原尺寸;
1437
+ * ③ 用原图的 **alpha 当掩码**——轮廓保持原样,模型画出来的背景被切掉。
1438
+ * 轮廓不变是硬要求:装配框与骨骼锚点都绑在原来的轮廓上。
1439
+ *
1440
+ * 结果落成**新版本**(`source: "redraw"`),所以「这张不行」随时切回上一版。
1441
+ */
1442
+ export async function redrawRigPart(jobId, name, prompt, options = {}) {
1443
+ const job = await readRigJob(jobId);
1444
+ if (job === undefined)
1445
+ throw new Error(`任务不存在:${jobId}`);
1446
+ const part = job.parts.find((entry) => entry.name === name);
1447
+ if (part === undefined)
1448
+ throw new Error(`没有这个部件:${name}`);
1449
+ const active = activeVersionOf(part);
1450
+ if (active === undefined)
1451
+ throw new Error(`「${name}」还没有贴图`);
1452
+ const config = await loadConfig();
1453
+ if (config.arkApiKey.trim() === "")
1454
+ throw new Error("尚未配置火山方舟 API Key,无法重绘(可以在界面里手工换色或上传替换,都不花钱)");
1455
+ const decoded = await decodeToRgba(rigAssetPath(jobId, active.file), 2048);
1456
+ const original = { data: decoded.rgba, width: decoded.width, height: decoded.height };
1457
+ const square = padToSquare(original, REDRAW_PAD_COLOR);
1458
+ const dataUri = `data:image/png;base64,${encodePng(square.image.data, square.image.width, square.image.height).toString("base64")}`;
1459
+ const redrawModel = config.arkRedrawModel.trim() === "" ? config.arkModel : config.arkRedrawModel.trim();
1460
+ const result = await generateImage({
1461
+ baseUrl: config.arkBaseUrl,
1462
+ apiKey: config.arkApiKey,
1463
+ model: redrawModel,
1464
+ prompt: buildRedrawPrompt(prompt, { role: part.role }),
1465
+ images: [dataUri],
1466
+ size: config.arkSize,
1467
+ watermark: config.arkWatermark,
1468
+ timeoutMs: config.arkTimeoutMs
1469
+ });
1470
+ // 模型交回来的图要落盘才能解码(解码器是 ffmpeg,吃文件路径)。
1471
+ const tempFile = join(rigJobDir(jobId), "parts", `.redraw-${Date.now()}.${result.ext}`);
1472
+ await mkdir(join(rigJobDir(jobId), "parts"), { recursive: true });
1473
+ let finished;
1474
+ try {
1475
+ await writeFile(tempFile, result.bytes);
1476
+ const raw = await decodeToRgba(tempFile, 2048);
1477
+ const masked = maskAndFit({ data: raw.rgba, width: raw.width, height: raw.height }, original, square, original.width, original.height);
1478
+ // 边缘白晕是这类流程的普遍问题;按半径分档腐蚀最外圈。
1479
+ finished = erodeAlpha(masked, Math.max(0, Math.round(options.erode ?? 1)));
1480
+ }
1481
+ finally {
1482
+ await rm(tempFile, { force: true }).catch(() => undefined);
1483
+ }
1484
+ // **落盘前先判断「模型到底画出东西没有」。**
1485
+ // 实测过:送进浅色部件 + 白底补边时,模型会直接交回一张纯白;照单全收的话
1486
+ // 用户拿到的是一版白块贴图,而且从版本列表上看不出它坏了。
1487
+ // 宁可这一次明确失败(日志与错误里说清原因),也不要留下坏数据。
1488
+ const stats = imageStats(finished);
1489
+ if (stats.opaque === 0) {
1490
+ throw new Error("重绘结果在轮廓内没有任何不透明像素,已丢弃(没有新增版本)");
1491
+ }
1492
+ if (stats.stdDev < MIN_REDRAW_CONTRAST) {
1493
+ throw new Error(`重绘结果几乎是纯色(亮度 ${stats.meanLuma.toFixed(0)}、标准差 ${stats.stdDev.toFixed(1)}),` +
1494
+ `模型「${redrawModel}」没有画出内容,已丢弃(没有新增版本)。` +
1495
+ "可以换个更具体的提示词,或在「设置 → 游戏素材大师 → 部件重绘模型」里换一个模型;" +
1496
+ "只是想让颜色变一下的话,「换色」是免费的。");
1497
+ }
1498
+ // 重新读一次:生图可能耗时很久,期间任务可能已经被改过。
1499
+ const fresh = await readRigJob(jobId);
1500
+ if (fresh === undefined)
1501
+ throw new Error(`任务不存在:${jobId}`);
1502
+ const node = fresh.parts.find((entry) => entry.name === name);
1503
+ if (node === undefined)
1504
+ throw new Error(`部件已被删除:${name}`);
1505
+ const created = await addTextureVersion(jobId, node, {
1506
+ source: "redraw",
1507
+ note: options.note ?? summarizePrompt(prompt),
1508
+ rgba: finished
1509
+ });
1510
+ invalidateTextures(fresh);
1511
+ appendJobLog(fresh.log, "info", `已重绘「${name}」(v${created.v},提示词:${summarizePrompt(prompt)})`);
1512
+ await writeRigJob(fresh);
1513
+ return { name, version: created.v, width: created.width, height: created.height };
1514
+ }
1515
+ /** 后台执行重绘(生图要几十秒,不能阻塞 RPC)。 */
1516
+ export function startRigRedraw(jobId, name, prompt, options = {}) {
1517
+ try {
1518
+ assertIdle(jobId, REDRAW_TASK_KEY, "部件重绘");
1519
+ }
1520
+ catch (error) {
1521
+ return { started: false, reason: messageOf(error) };
1522
+ }
1523
+ const started = kick(jobId, REDRAW_TASK_KEY, async () => {
1524
+ await redrawRigPart(jobId, name, prompt, options);
1525
+ });
1526
+ return started ? { started: true } : { started: false, reason: "重绘已在进行中" };
1527
+ }
1528
+ /** 手工上传一张贴图顶掉当前版本(同样是**新增一版**,不覆盖)。 */ export async function uploadRigTexture(jobId, name, base64, options = {}) {
1529
+ const job = await readRigJob(jobId);
1530
+ if (job === undefined)
1531
+ throw new Error(`任务不存在:${jobId}`);
1532
+ const part = job.parts.find((entry) => entry.name === name);
1533
+ if (part === undefined)
1534
+ throw new Error(`没有这个部件:${name}`);
1535
+ const bytes = Buffer.from(base64, "base64");
1536
+ const sniffed = sniffImage(base64);
1537
+ if (sniffed === undefined)
1538
+ throw new Error("不认识的图片格式(支持 PNG / JPEG / WebP)");
1539
+ if (bytes.length > 30 * 1024 * 1024)
1540
+ throw new Error("贴图超过 30 MB");
1541
+ const tempFile = join(rigJobDir(jobId), "parts", `.incoming-${Date.now()}.${sniffed.ext}`);
1542
+ await mkdir(join(rigJobDir(jobId), "parts"), { recursive: true });
1543
+ await writeFile(tempFile, bytes);
1544
+ try {
1545
+ const decoded = await decodeToRgba(tempFile, 2048);
1546
+ const created = await addTextureVersion(jobId, part, {
1547
+ source: "upload",
1548
+ note: options.note,
1549
+ rgba: { data: decoded.rgba, width: decoded.width, height: decoded.height }
1550
+ });
1551
+ invalidateTextures(job);
1552
+ appendJobLog(job.log, "info", `已上传「${name}」的新贴图(v${created.v},${decoded.width}×${decoded.height})`);
1553
+ await writeRigJob(job);
1554
+ return { name, version: created.v, width: created.width, height: created.height };
1555
+ }
1556
+ finally {
1557
+ await rm(tempFile, { force: true }).catch(() => undefined);
1558
+ }
1559
+ }
1560
+ /** 切到某一版(「这张 AI 头发不行,换回原版」)。 */
1561
+ export async function setRigTextureVersion(jobId, name, version) {
1562
+ const job = await readRigJob(jobId);
1563
+ if (job === undefined)
1564
+ throw new Error(`任务不存在:${jobId}`);
1565
+ const part = job.parts.find((entry) => entry.name === name);
1566
+ if (part === undefined)
1567
+ throw new Error(`没有这个部件:${name}`);
1568
+ const versions = versionsOf(part);
1569
+ const target = versions.find((item) => item.v === version);
1570
+ if (target === undefined)
1571
+ throw new Error(`「${name}」没有 v${version}(现有:${versions.map((item) => `v${item.v}`).join("、")})`);
1572
+ if (part.activeTexture === version)
1573
+ return { version };
1574
+ part.versions = versions;
1575
+ part.activeTexture = version;
1576
+ syncActiveTexture(part);
1577
+ invalidateTextures(job);
1578
+ appendJobLog(job.log, "info", `「${name}」已切到贴图 v${version}${target.note === undefined ? "" : `(${target.note})`}`);
1579
+ await writeRigJob(job);
1580
+ return { version };
1581
+ }
1582
+ /** 删掉某一版(当前生效的那版不允许删;最后一版也不允许删)。 */
1583
+ export async function removeRigTextureVersion(jobId, name, version) {
1584
+ const job = await readRigJob(jobId);
1585
+ if (job === undefined)
1586
+ throw new Error(`任务不存在:${jobId}`);
1587
+ const part = job.parts.find((entry) => entry.name === name);
1588
+ if (part === undefined)
1589
+ throw new Error(`没有这个部件:${name}`);
1590
+ const versions = versionsOf(part);
1591
+ const target = versions.find((item) => item.v === version);
1592
+ if (target === undefined)
1593
+ throw new Error(`「${name}」没有 v${version}`);
1594
+ if (versions.length <= 1)
1595
+ throw new Error("这是最后一个版本,删掉部件就没有贴图了");
1596
+ if ((part.activeTexture ?? versions[versions.length - 1].v) === version)
1597
+ throw new Error("不能删除当前生效的版本,先切到别的版本");
1598
+ part.versions = versions.filter((item) => item.v !== version);
1599
+ await rm(rigAssetPath(jobId, target.file), { force: true }).catch(() => undefined);
1600
+ syncActiveTexture(part);
1601
+ invalidateTextures(job);
1602
+ appendJobLog(job.log, "info", `已删除「${name}」的贴图 v${version}`);
1603
+ await writeRigJob(job);
1604
+ return { removed: 1 };
1605
+ }
1606
+ // ── 动画参数(M3:让动画从代码常量变成数据)─────────────────────────────
1607
+ /**
1608
+ * 写入逐动画的可调参数。
1609
+ *
1610
+ * 只改骨骼与图集(动画变了、骨架没变),不动装配。
1611
+ */
1612
+ export async function setRigAnimationSettings(jobId, patches, options = {}) {
1613
+ const job = await readRigJob(jobId);
1614
+ if (job === undefined)
1615
+ throw new Error(`任务不存在:${jobId}`);
1616
+ const unknown = patches.filter((patch) => animationPresetOf(patch.id) === undefined);
1617
+ if (unknown.length > 0)
1618
+ throw new Error(`没有这个动画:${unknown.map((patch) => patch.id).join("、")}`);
1619
+ if (patches.length === 0)
1620
+ return { touched: 0, settings: job.animationSettings ?? {} };
1621
+ const current = { ...(job.animationSettings ?? {}) };
1622
+ let touched = 0;
1623
+ for (const patch of patches) {
1624
+ const merged = normalizeAnimationSettings({ [patch.id]: { ...(current[patch.id] ?? {}), ...patch } })?.[patch.id];
1625
+ // 归一化后为空 = 这个动画的参数回到了默认值,条目直接删掉(与骨骼偏移同一套语义)。
1626
+ if (merged === undefined)
1627
+ delete current[patch.id];
1628
+ else
1629
+ current[patch.id] = merged;
1630
+ touched++;
1631
+ }
1632
+ job.animationSettings = Object.keys(current).length === 0 ? undefined : current;
1633
+ invalidateFrom(job, "rig");
1634
+ appendJobLog(job.log, "info", `${options.by === "ai" ? "AI" : "手工"}调整动画参数:${patches.map((patch) => patch.id).join("、")}`);
1635
+ await writeRigJob(job);
1636
+ return { touched, settings: job.animationSettings ?? {} };
1637
+ }
1638
+ /** 清除动画参数(全部,或点名几个),回到预设的原始数值。 */
1639
+ export async function resetRigAnimationSettings(jobId, ids) {
1640
+ const job = await readRigJob(jobId);
1641
+ if (job === undefined)
1642
+ throw new Error(`任务不存在:${jobId}`);
1643
+ const current = { ...(job.animationSettings ?? {}) };
1644
+ const targets = ids === undefined || ids.length === 0 ? Object.keys(current) : ids;
1645
+ let touched = 0;
1646
+ for (const id of targets) {
1647
+ if (current[id] === undefined)
1648
+ continue;
1649
+ delete current[id];
1650
+ touched++;
1651
+ }
1652
+ job.animationSettings = Object.keys(current).length === 0 ? undefined : current;
1653
+ invalidateFrom(job, "rig");
1654
+ appendJobLog(job.log, "info", touched > 0 ? `已重置 ${touched} 个动画的参数` : "没有需要重置的动画参数");
1655
+ await writeRigJob(job);
1656
+ return { touched };
1657
+ }
1658
+ // ── 关键帧编辑(阶段⑥:动画从「参数」变成「数据」)─────────────────────
1659
+ /** 一条时间轴最多多少关键帧——不是产品限制,是防止一份失控的数据把预览拖死。 */
1660
+ export const MAX_KEYFRAMES_PER_TRACK = 240;
1661
+ /** 一台动画最多多少条轨道。 */
1662
+ export const MAX_TRACKS_PER_ANIMATION = 96;
1663
+ /**
1664
+ * 关键帧时间的对齐网格。
1665
+ *
1666
+ * 必须与导出用的帧率一致(`rigexport.ts` 的 `DRAGONBONES_FRAME_RATE`):
1667
+ * DragonBones 的 `duration` 以帧为单位,两帧落在同一帧上时中间那帧的 duration 为 0,
1668
+ * 会被解析成阶跃并在导出校验里被拦下。对齐之后这种数据根本进不来。
1669
+ */
1670
+ export const ANIMATION_FRAME_RATE = 30;
1671
+ /**
1672
+ * 归一化一份手工动画。
1673
+ *
1674
+ * 校验尽量往前放:进去之后它就只是「一堆数字」,再想区分「用户打错了」和
1675
+ * 「渲染器算错了」就很难了。这里丢掉的东西一定伴随一条 warning,
1676
+ * 不做静默修正——静默修正是最伤人的那种「贴心」。
1677
+ */
1678
+ function normalizeCustomAnimation(raw, fallback, issues) {
1679
+ if (raw === null || typeof raw !== "object") {
1680
+ issues.push("动画数据不是对象");
1681
+ return undefined;
1682
+ }
1683
+ const input = raw;
1684
+ const duration = Number.isFinite(input.duration) && input.duration > 0 ? Math.min(30, input.duration) : fallback.duration;
1685
+ const loop = typeof input.loop === "boolean" ? input.loop : fallback.loop;
1686
+ if (input.bones === null || typeof input.bones !== "object") {
1687
+ issues.push("动画里没有 bones");
1688
+ return undefined;
1689
+ }
1690
+ const bones = {};
1691
+ let tracks = 0;
1692
+ for (const [boneName, kindsRaw] of Object.entries(input.bones)) {
1693
+ if (typeof boneName !== "string" || boneName === "")
1694
+ continue;
1695
+ if (kindsRaw === null || typeof kindsRaw !== "object")
1696
+ continue;
1697
+ const kinds = {};
1698
+ for (const [kind, framesRaw] of Object.entries(kindsRaw)) {
1699
+ if (kind !== "rotate" && kind !== "translate" && kind !== "scale")
1700
+ continue;
1701
+ if (!Array.isArray(framesRaw))
1702
+ continue;
1703
+ if (tracks >= MAX_TRACKS_PER_ANIMATION) {
1704
+ issues.push(`轨道数超过上限 ${MAX_TRACKS_PER_ANIMATION},多余的已忽略`);
1705
+ break;
1706
+ }
1707
+ const valueKeys = keyframeValueKeys(kind);
1708
+ const frames = [];
1709
+ for (const frameRaw of framesRaw.slice(0, MAX_KEYFRAMES_PER_TRACK)) {
1710
+ if (frameRaw === null || typeof frameRaw !== "object")
1711
+ continue;
1712
+ const time = Number(frameRaw.time);
1713
+ if (!Number.isFinite(time) || time < 0) {
1714
+ issues.push(`${boneName}/${kind} 有一个时间非法的关键帧,已丢弃`);
1715
+ continue;
1716
+ }
1717
+ const frame = { time: Number(Math.min(time, duration).toFixed(4)) };
1718
+ for (const key of valueKeys) {
1719
+ const value = Number(frameRaw[key]);
1720
+ if (Number.isFinite(value))
1721
+ frame[key] = Number(value.toFixed(4));
1722
+ }
1723
+ if (valueKeys.some((key) => frame[key] === undefined)) {
1724
+ issues.push(`${boneName}/${kind} 有一个关键帧缺少 ${valueKeys.join("/")},已丢弃`);
1725
+ continue;
1726
+ }
1727
+ // curve:null = 线性,`"stepped"` = 阶跃,4 个数 = 归一化控制点。
1728
+ const curve = frameRaw.curve;
1729
+ if (curve === "stepped")
1730
+ frame.curve = "stepped";
1731
+ else if (Array.isArray(curve) && curve.length === 4 && curve.every((n) => Number.isFinite(Number(n)))) {
1732
+ frame.curve = curve.map((n) => Number(Number(n).toFixed(4)));
1733
+ }
1734
+ else if (curve === null || curve === undefined)
1735
+ frame.curve = null;
1736
+ else {
1737
+ issues.push(`${boneName}/${kind} 有一个关键帧的 curve 不是 4 个数,已归为线性`);
1738
+ frame.curve = null;
1739
+ }
1740
+ frames.push(frame);
1741
+ }
1742
+ if (frames.length === 0)
1743
+ continue;
1744
+ // 时间必须严格递增:同一时刻两个帧在两条导出路径里的归属都是未定义的。
1745
+ frames.sort((a, b) => a.time - b.time);
1746
+ // **对齐到 30fps 的帧网格**,并丢掉会塌缩的相邻帧。
1747
+ //
1748
+ // 为什么必须对齐:DragonBones 的 `duration` 单位是帧,两帧相隔不足一帧时
1749
+ // 它们会落在同一个 `frameStart` 上,中间那一帧的 `duration` 就是 0 ——
1750
+ // 而 0 会被解析成**阶跃**,导出前校验也会直接拦下(实测:把一帧拖到
1751
+ // 0.401s、它前面那帧在 0.4s,整条骨骼链路就这样失败了)。
1752
+ // 在保存时对齐,坏数据根本进不了任务。
1753
+ const dedup = [];
1754
+ for (const frame of frames) {
1755
+ const snapped = { ...frame, time: Number((Math.round(frame.time * ANIMATION_FRAME_RATE) / ANIMATION_FRAME_RATE).toFixed(4)) };
1756
+ if (snapped.time > duration)
1757
+ continue;
1758
+ if (dedup.length > 0 && snapped.time <= dedup[dedup.length - 1].time) {
1759
+ issues.push(`${boneName}/${kind} 有两个关键帧落在同一帧上(${snapped.time}s),已保留后一个`);
1760
+ dedup[dedup.length - 1] = snapped;
1761
+ continue;
1762
+ }
1763
+ dedup.push(snapped);
1764
+ }
1765
+ if (dedup.length === 0)
1766
+ continue;
1767
+ // 末帧永不携带 curve(它描述的是「以本帧为起点」的那一段,末帧没有下一段)。
1768
+ dedup[dedup.length - 1].curve = null;
1769
+ // 首帧必须是 0:否则 0 → 首帧之间是一段「没有定义的静默区」。
1770
+ if (dedup[0].time > 1e-4) {
1771
+ issues.push(`${boneName}/${kind} 的首帧不在 0 秒,已丢弃这段轨道`);
1772
+ continue;
1773
+ }
1774
+ kinds[kind] = dedup;
1775
+ tracks++;
1776
+ }
1777
+ if (Object.keys(kinds).length > 0)
1778
+ bones[boneName] = kinds;
1779
+ }
1780
+ if (Object.keys(bones).length === 0) {
1781
+ issues.push("没有任何可用的轨道");
1782
+ return undefined;
1783
+ }
1784
+ return { duration, loop, bones, source: input.source === "ai" ? "ai" : "human", updatedAt: Date.now() };
1785
+ }
1786
+ /**
1787
+ * 把一台动画变成**可编辑数据**,并(可选)整份写回。
1788
+ *
1789
+ * 不传 `animation` 就是「实例化」:用当前参数把预设烘成显式关键帧,之后以数据为准。
1790
+ * 传了就是「整份替换」——界面上的每次拖动都提交一份完整的时间轴,
1791
+ * 而不是一条 patch:时间轴的「增删改」三者互相牵连(删一帧会改两个段的归属),
1792
+ * 服务端再去解析 patch 只会把同一套语义实现两遍。
1793
+ */
1794
+ export async function saveRigAnimation(jobId, input) {
1795
+ const job = await readRigJob(jobId);
1796
+ if (job === undefined)
1797
+ throw new Error(`任务不存在:${jobId}`);
1798
+ const id = typeof input.id === "string" ? input.id : "";
1799
+ const preset = animationPresetOf(id);
1800
+ if (preset === undefined)
1801
+ throw new Error(`没有这台动画:${id}`);
1802
+ const names = input.boneNames !== undefined && input.boneNames.length > 0 ? input.boneNames : boneNamesOf(job);
1803
+ const settings = job.animationSettings ?? {};
1804
+ const base = instantiateAnimation(id, names, settings);
1805
+ if (base === undefined)
1806
+ throw new Error(`这台动画在当前部件集下没有任何轨道(预设依赖的骨骼都不存在):${id}`);
1807
+ const issues = [];
1808
+ const source = input.animation === undefined ? undefined : input.animation;
1809
+ const next = source === undefined
1810
+ ? {
1811
+ duration: base.duration,
1812
+ loop: base.loop,
1813
+ bones: base.bones,
1814
+ source: "human",
1815
+ updatedAt: Date.now()
1816
+ }
1817
+ : normalizeCustomAnimation(source, { duration: base.duration, loop: base.loop }, issues);
1818
+ if (next === undefined) {
1819
+ throw new Error(`动画数据不可用:${issues.slice(0, 3).join(";") || "解析失败"}`);
1820
+ }
1821
+ const animations = { ...(job.animations ?? {}) };
1822
+ animations[id] = next;
1823
+ job.animations = animations;
1824
+ invalidateFrom(job, "rig");
1825
+ let frames = 0;
1826
+ let tracks = 0;
1827
+ for (const kinds of Object.values(next.bones)) {
1828
+ for (const list of Object.values(kinds)) {
1829
+ tracks++;
1830
+ frames += list.length;
1831
+ }
1832
+ }
1833
+ appendJobLog(job.log, "info", `${source === undefined ? "开始编辑" : "已更新"}动画「${preset.label}」:${tracks} 条轨道 / ${frames} 个关键帧`);
1834
+ for (const issue of issues.slice(0, 6))
1835
+ appendJobLog(job.log, "warn", `动画「${preset.label}」:${issue}`);
1836
+ await writeRigJob(job);
1837
+ return { id, tracks, keyframes: frames, issues };
1838
+ }
1839
+ /**
1840
+ * 取一台动画的**可编辑数据**,供时间轴编辑器渲染。
1841
+ *
1842
+ * 没编辑过时返回「预设实例化」的结果(同样是一份显式关键帧),界面因此可以
1843
+ * 一视同仁地渲染,不需要「预设模式 / 编辑模式」两套代码。`custom` 告诉界面
1844
+ * 这份数据是磁盘上的还是临时算的。
1845
+ *
1846
+ * 逐台取而不是塞进快照:一台动画几十条轨道、每条十几个关键帧,塞进每 2 秒
1847
+ * 轮询一次的 `getRigJob` 里,为一个大多数人不会打开的编辑器付全量代价。
1848
+ */
1849
+ export async function getRigAnimation(jobId, id) {
1850
+ const job = await readRigJob(jobId);
1851
+ if (job === undefined)
1852
+ throw new Error(`任务不存在:${jobId}`);
1853
+ const preset = animationPresetOf(id);
1854
+ if (preset === undefined)
1855
+ throw new Error(`没有这台动画:${id}`);
1856
+ const custom = job.animations?.[id];
1857
+ const names = boneNamesOf(job);
1858
+ const draft = custom ?? instantiateAnimation(id, names, job.animationSettings ?? {});
1859
+ if (draft === undefined)
1860
+ throw new Error(`这台动画在当前部件集下没有任何轨道:${id}`);
1861
+ // 骨骼顺序按骨架层级给,界面上的轨道列表才跟骨骼编辑器对得上。
1862
+ const order = boneOrderOf(job);
1863
+ const bones = {};
1864
+ for (const name of order)
1865
+ if (draft.bones[name] !== undefined)
1866
+ bones[name] = draft.bones[name];
1867
+ for (const [name, kinds] of Object.entries(draft.bones))
1868
+ if (bones[name] === undefined)
1869
+ bones[name] = kinds;
1870
+ return {
1871
+ id,
1872
+ label: preset.label,
1873
+ custom: custom !== undefined,
1874
+ duration: draft.duration,
1875
+ loop: draft.loop,
1876
+ bones,
1877
+ // 预设里没有轨道的骨骼(例如这台动作不动的部件)界面也要能「加一条轨道」。
1878
+ boneOrder: names
1879
+ };
1880
+ }
1881
+ /**
1882
+ * 骨骼顺序:直接用**上一次推导出来的骨骼表**(它本来就是拓扑序),
1883
+ * 没跑过骨骼、或之后新增了部件,才按部件顺序补齐。
1884
+ *
1885
+ * 不在这里重新推一遍父级:那正是 `spine.ts` 里刚修过的坑(父级在两处各算一次,
1886
+ * 结果可以不同),界面上的轨道顺序没必要再冒一次险。
1887
+ */
1888
+ function boneOrderOf(job) {
1889
+ const names = boneNamesOf(job);
1890
+ const known = new Set(names);
1891
+ const seen = new Set();
1892
+ const out = [];
1893
+ for (const bone of job.rig.boneList ?? []) {
1894
+ if (bone.name === "root" || !known.has(bone.name) || seen.has(bone.name))
1895
+ continue;
1896
+ seen.add(bone.name);
1897
+ out.push(bone.name);
1898
+ }
1899
+ for (const name of names) {
1900
+ if (seen.has(name))
1901
+ continue;
1902
+ seen.add(name);
1903
+ out.push(name);
1904
+ }
1905
+ return out;
1906
+ }
1907
+ /** 丢掉手工数据,回到预设实例化(等于「还原这台动画」)。 */
1908
+ export async function resetRigAnimation(jobId, id) {
1909
+ const job = await readRigJob(jobId);
1910
+ if (job === undefined)
1911
+ throw new Error(`任务不存在:${jobId}`);
1912
+ const animations = { ...(job.animations ?? {}) };
1913
+ if (animations[id] === undefined)
1914
+ return { touched: 0 };
1915
+ delete animations[id];
1916
+ job.animations = Object.keys(animations).length === 0 ? undefined : animations;
1917
+ invalidateFrom(job, "rig");
1918
+ appendJobLog(job.log, "info", `已还原动画「${animationPresetOf(id)?.label ?? id}」到预设`);
1919
+ await writeRigJob(job);
1920
+ return { touched: 1 };
1921
+ }
1922
+ /** 当前参与骨架的部件名(= 骨骼名,root 除外)。 */
1923
+ function boneNamesOf(job) {
1924
+ return job.parts.filter((part) => part.status === "ready" && part.hidden !== true).map((part) => part.name);
1925
+ }
1926
+ // ── IK 约束(M5)────────────────────────────────────────────────────────
1927
+ /**
1928
+ * 写入 / 覆盖 IK 约束。
1929
+ *
1930
+ * 不传 `constraints` 的那条会被删掉;传了的整条替换。约束是**结构**(不是动画),
1931
+ * 所以改动会作废骨骼与图集——骨架的求值链里多了一步求解。
1932
+ */
1933
+ export async function setRigConstraints(jobId, patches, options = {}) {
1934
+ const job = await readRigJob(jobId);
1935
+ if (job === undefined)
1936
+ throw new Error(`任务不存在:${jobId}`);
1937
+ const current = [...(job.constraints ?? [])];
1938
+ let touched = 0;
1939
+ for (const patch of patches) {
1940
+ const index = current.findIndex((entry) => entry.name === patch.name);
1941
+ if (patch.type === "none") {
1942
+ if (index >= 0) {
1943
+ current.splice(index, 1);
1944
+ touched++;
1945
+ }
1946
+ continue;
1947
+ }
1948
+ const merged = {
1949
+ type: "ik",
1950
+ name: patch.name,
1951
+ bone: patch.bone ?? (index >= 0 ? current[index].bone : ""),
1952
+ target: patch.target ?? (index >= 0 ? current[index].target : `${patch.name}-target`),
1953
+ chain: Math.max(1, Math.min(8, Math.round(num(patch.chain, index >= 0 ? current[index].chain : 1)))),
1954
+ bendPositive: patch.bendPositive ?? (index >= 0 ? current[index].bendPositive : true),
1955
+ weight: Math.max(0, Math.min(1, num(patch.weight, index >= 0 ? current[index].weight : 1)))
1956
+ };
1957
+ if (merged.bone === "")
1958
+ throw new Error(`IK「${merged.name}」缺少被约束的骨骼`);
1959
+ if (index >= 0)
1960
+ current[index] = merged;
1961
+ else
1962
+ current.push(merged);
1963
+ touched++;
1964
+ }
1965
+ job.constraints = current.length === 0 ? undefined : current;
1966
+ invalidateFrom(job, "rig");
1967
+ appendJobLog(job.log, "info", `${options.by === "ai" ? "AI" : "手工"}编辑 IK 约束:${patches.map((patch) => patch.name).join("、")}`);
1968
+ await writeRigJob(job);
1969
+ return { touched };
1970
+ }
1971
+ /** 清除 IK 约束(全部,或点名几条)。 */
1972
+ export async function resetRigConstraints(jobId, names) {
1973
+ const job = await readRigJob(jobId);
1974
+ if (job === undefined)
1975
+ throw new Error(`任务不存在:${jobId}`);
1976
+ const current = [...(job.constraints ?? [])];
1977
+ const targets = names === undefined || names.length === 0 ? current.map((entry) => entry.name) : names;
1978
+ const next = current.filter((entry) => !targets.includes(entry.name));
1979
+ const touched = current.length - next.length;
1980
+ job.constraints = next.length === 0 ? undefined : next;
1981
+ invalidateFrom(job, "rig");
1982
+ appendJobLog(job.log, "info", touched > 0 ? `已清除 ${touched} 条 IK 约束` : "没有需要清除的 IK 约束");
1983
+ await writeRigJob(job);
1984
+ return { touched };
1985
+ }
1986
+ // ── 蒙皮网格与 FFD 变形(M5 的 L1 / L3)──────────────────────────────────
1987
+ /**
1988
+ * 给部件加/改网格与变形。
1989
+ *
1990
+ * `mesh: null` 表示取消这个部件的细分(回到整块贴图渲染)。`deform: null` 表示取消变形
1991
+ * 但保留网格——两者分开是因为「细分了但暂时不加变形」是调试时的常见状态。
1992
+ */
1993
+ export async function setRigMesh(jobId, patches, options = {}) {
1994
+ const job = await readRigJob(jobId);
1995
+ if (job === undefined)
1996
+ throw new Error(`任务不存在:${jobId}`);
1997
+ const meshes = { ...(job.meshes ?? {}) };
1998
+ const deforms = { ...(job.deforms ?? {}) };
1999
+ const warnings = [];
2000
+ let touched = 0;
2001
+ for (const patch of patches) {
2002
+ const part = job.parts.find((entry) => entry.name === patch.name && entry.status === "ready");
2003
+ if (part === undefined) {
2004
+ warnings.push(`没有这个可用部件:${patch.name}`);
2005
+ continue;
2006
+ }
2007
+ if (patch.cols === null || patch.rows === null) {
2008
+ delete meshes[patch.name];
2009
+ delete deforms[patch.name];
2010
+ touched++;
2011
+ continue;
2012
+ }
2013
+ const current = meshes[patch.name] ?? { cols: MESH_DEFAULT_DIVISIONS, rows: MESH_DEFAULT_DIVISIONS };
2014
+ const cols = Math.max(1, Math.min(MESH_MAX_DIVISIONS, Math.round(num(patch.cols, current.cols))));
2015
+ const rows = Math.max(1, Math.min(MESH_MAX_DIVISIONS, Math.round(num(patch.rows, current.rows))));
2016
+ meshes[patch.name] = { cols, rows };
2017
+ touched++;
2018
+ if (patch.deform === null) {
2019
+ delete deforms[patch.name];
2020
+ continue;
2021
+ }
2022
+ if (patch.deform === undefined)
2023
+ continue;
2024
+ const previous = deforms[patch.name];
2025
+ const fallback = previous ?? {
2026
+ mode: "wave",
2027
+ // 默认幅度取部件短边的一个比例:裙子这么大一块,6% 大约是「一眼看得出来」的程度。
2028
+ amplitude: Math.max(4, Math.round(Math.min(part.width, part.height) * 0.06)),
2029
+ cycles: 1,
2030
+ direction: 0,
2031
+ anchor: "top",
2032
+ duration: 1.6
2033
+ };
2034
+ deforms[patch.name] = {
2035
+ mode: "wave",
2036
+ amplitude: Math.max(0, Math.min(400, num(patch.deform.amplitude, fallback.amplitude))),
2037
+ cycles: Math.max(0.25, Math.min(8, num(patch.deform.cycles, fallback.cycles))),
2038
+ direction: num(patch.deform.direction, fallback.direction),
2039
+ anchor: patch.deform.anchor === "bottom" || patch.deform.anchor === "none" ? patch.deform.anchor : fallback.anchor,
2040
+ duration: Math.max(0.1, Math.min(10, num(patch.deform.duration, fallback.duration)))
2041
+ };
2042
+ }
2043
+ job.meshes = Object.keys(meshes).length === 0 ? undefined : meshes;
2044
+ job.deforms = Object.keys(deforms).length === 0 ? undefined : deforms;
2045
+ // 网格会改变附件的**类型**(region → mesh),骨骼与图集都得重做。
2046
+ invalidateFrom(job, "rig");
2047
+ appendJobLog(job.log, "info", `${options.by === "ai" ? "AI" : "手工"}编辑蒙皮:${patches.map((patch) => patch.name).join("、")}` +
2048
+ (Object.keys(deforms).length > 0 ? `(带变形的 ${Object.keys(deforms).join("、")})` : ""));
2049
+ await writeRigJob(job);
2050
+ return { touched, warnings };
2051
+ }
2052
+ // ── Path 约束(M5)──────────────────────────────────────────────────────
2053
+ /**
2054
+ * 把路径点从**参考图像素**转成**骨骼世界坐标**(y 向上),供预览内联。
2055
+ *
2056
+ * 换算与 `buildSkeleton` 里的 `toWorld` 必须一致,所以直接读骨架自己写下来的
2057
+ * `x/y/width/height`(那是导出时真正用的画布参数),而不是另取一份 settings。
2058
+ */
2059
+ function previewPathsOf(job, spine) {
2060
+ const out = {};
2061
+ const entries = Object.entries(job.paths ?? {});
2062
+ if (entries.length === 0)
2063
+ return out;
2064
+ // 画布尺寸只有骨架自己写下来的那份是准的——导出时用的就是它。
2065
+ const width = num(spine?.skeleton?.width, 0);
2066
+ const height = num(spine?.skeleton?.height, 0);
2067
+ if (width <= 0 || height <= 0)
2068
+ return out;
2069
+ for (const [name, entry] of entries) {
2070
+ const points = [];
2071
+ for (let i = 0; i + 1 < entry.points.length; i += 2) {
2072
+ points.push(Number((entry.points[i] - width / 2).toFixed(3)), Number((height - entry.points[i + 1]).toFixed(3)));
2073
+ }
2074
+ out[name] = {
2075
+ points,
2076
+ closed: entry.closed,
2077
+ bones: entry.bones,
2078
+ spacing: entry.spacing,
2079
+ translateMix: entry.translateMix,
2080
+ rotateMix: entry.rotateMix
2081
+ };
2082
+ }
2083
+ return out;
2084
+ }
2085
+ /**
2086
+ * 写入 / 覆盖一条路径约束。
2087
+ *
2088
+ * `bones` 不传时会用「沿路径最近的若干根骨」猜一条链——但那只是给个起点,
2089
+ * 猜错了用户要能一眼看出来(面板里会把骨链列出来)。
2090
+ */
2091
+ export async function setRigPath(jobId, patches, options = {}) {
2092
+ const job = await readRigJob(jobId);
2093
+ if (job === undefined)
2094
+ throw new Error(`任务不存在:${jobId}`);
2095
+ const paths = { ...(job.paths ?? {}) };
2096
+ const warnings = [];
2097
+ let touched = 0;
2098
+ const available = new Set(boneNamesOf(job));
2099
+ for (const patch of patches) {
2100
+ const previous = paths[patch.name];
2101
+ const normalized = normalizePath(patch.points !== undefined ? { points: patch.points, closed: patch.closed } : previous ?? { points: [] });
2102
+ if (normalized === undefined) {
2103
+ warnings.push(`路径「${patch.name}」至少需要两个有效点`);
2104
+ continue;
2105
+ }
2106
+ const chain = (patch.bones ?? previous?.bones ?? []).filter((name) => available.has(name));
2107
+ if (chain.length === 0) {
2108
+ warnings.push(`路径「${patch.name}」没有指定沿路径排列的骨骼`);
2109
+ continue;
2110
+ }
2111
+ paths[patch.name] = {
2112
+ points: normalized.points,
2113
+ closed: normalized.closed,
2114
+ bones: chain,
2115
+ spacing: Math.max(0, num(patch.spacing, previous?.spacing ?? 0)),
2116
+ translateMix: Math.max(0, Math.min(1, num(patch.translateMix, previous?.translateMix ?? 1))),
2117
+ rotateMix: Math.max(0, Math.min(1, num(patch.rotateMix, previous?.rotateMix ?? 1)))
2118
+ };
2119
+ touched++;
2120
+ }
2121
+ job.paths = Object.keys(paths).length === 0 ? undefined : paths;
2122
+ invalidateFrom(job, "rig");
2123
+ appendJobLog(job.log, "info", `${options.by === "ai" ? "AI" : "手工"}编辑路径约束:${patches.map((patch) => patch.name).join("、")}`);
2124
+ await writeRigJob(job);
2125
+ return { touched, warnings };
2126
+ }
2127
+ /** 清除路径约束(全部,或点名几条)。 */
2128
+ export async function resetRigPath(jobId, names) {
2129
+ const job = await readRigJob(jobId);
2130
+ if (job === undefined)
2131
+ throw new Error(`任务不存在:${jobId}`);
2132
+ const paths = { ...(job.paths ?? {}) };
2133
+ const targets = names === undefined || names.length === 0 ? Object.keys(paths) : names;
2134
+ let touched = 0;
2135
+ for (const name of targets) {
2136
+ if (paths[name] === undefined)
2137
+ continue;
2138
+ delete paths[name];
2139
+ touched++;
2140
+ }
2141
+ job.paths = Object.keys(paths).length === 0 ? undefined : paths;
2142
+ invalidateFrom(job, "rig");
2143
+ appendJobLog(job.log, "info", touched > 0 ? `已清除 ${touched} 条路径约束` : "没有需要清除的路径约束");
2144
+ await writeRigJob(job);
2145
+ return { touched };
2146
+ }
2147
+ /** 清除网格与变形(全部,或点名几个部件)。 */ export async function resetRigMesh(jobId, names) {
2148
+ const job = await readRigJob(jobId);
2149
+ if (job === undefined)
2150
+ throw new Error(`任务不存在:${jobId}`);
2151
+ const meshes = { ...(job.meshes ?? {}) };
2152
+ const deforms = { ...(job.deforms ?? {}) };
2153
+ const targets = names === undefined || names.length === 0 ? Object.keys(meshes) : names;
2154
+ let touched = 0;
2155
+ for (const name of targets) {
2156
+ if (meshes[name] === undefined)
2157
+ continue;
2158
+ delete meshes[name];
2159
+ delete deforms[name];
2160
+ touched++;
2161
+ }
2162
+ job.meshes = Object.keys(meshes).length === 0 ? undefined : meshes;
2163
+ job.deforms = Object.keys(deforms).length === 0 ? undefined : deforms;
2164
+ invalidateFrom(job, "rig");
2165
+ appendJobLog(job.log, "info", touched > 0 ? `已清除 ${touched} 个部件的网格与变形` : "没有需要清除的网格");
2166
+ await writeRigJob(job);
2167
+ return { touched };
2168
+ }
2169
+ export const EMPTY_BONE_OFFSET_TOLERANCE = 0.01;
2170
+ function roundOffset(value) {
2171
+ return Number(value.toFixed(2));
2172
+ }
2173
+ /**
2174
+ * 归一化一枚偏移:**去掉等于默认值的字段**。
2175
+ *
2176
+ * 这不是洁癖:`boneOffsets` 的语义是「人相对绑定姿势改了什么」,
2177
+ * 全零的条目意味着「什么都没改」。把它留在文件里会让「改回去了没有」
2178
+ * 变成一个需要比较数值才能回答的问题,也会让 JSON diff 噪音很大。
2179
+ * 返回 `undefined` 表示这枚偏移是空的。
2180
+ */
2181
+ export function pruneBoneOffset(value) {
2182
+ const record = value !== null && typeof value === "object" ? value : {};
2183
+ const out = {};
2184
+ const x = num(record.x, 0);
2185
+ const y = num(record.y, 0);
2186
+ const rotation = num(record.rotation, 0);
2187
+ if (Math.abs(x) > EMPTY_BONE_OFFSET_TOLERANCE)
2188
+ out.x = roundOffset(x);
2189
+ if (Math.abs(y) > EMPTY_BONE_OFFSET_TOLERANCE)
2190
+ out.y = roundOffset(y);
2191
+ if (Math.abs(rotation) > EMPTY_BONE_OFFSET_TOLERANCE)
2192
+ out.rotation = roundOffset(rotation);
2193
+ return Object.keys(out).length === 0 ? undefined : out;
2194
+ }
2195
+ function normalizeBoneOffsets(raw) {
2196
+ if (raw === null || typeof raw !== "object")
2197
+ return undefined;
2198
+ const out = {};
2199
+ for (const [name, value] of Object.entries(raw)) {
2200
+ const item = pruneBoneOffset(value);
2201
+ if (item !== undefined)
2202
+ out[name] = item;
2203
+ }
2204
+ return Object.keys(out).length === 0 ? undefined : out;
2205
+ }
2206
+ /**
2207
+ * 写入手工骨骼偏移(人在界面上拖/转骨骼,或 agent 给出建议)。
2208
+ *
2209
+ * 与 `setRigSemantics` 一样只作废**骨骼与图集**:偏移只影响骨骼推导,
2210
+ * 部件摆在画布上的位置与它无关,作废到 layout 会让用户白丢一次手工摆位。
2211
+ */
2212
+ export async function setRigBoneOffsets(jobId, patches, options = {}) {
2213
+ const job = await readRigJob(jobId);
2214
+ if (job === undefined)
2215
+ throw new Error(`任务不存在:${jobId}`);
2216
+ if (patches.length === 0)
2217
+ return { touched: 0 };
2218
+ const known = new Set(job.parts.map((part) => part.name));
2219
+ for (const patch of patches) {
2220
+ if (!known.has(patch.name))
2221
+ throw new Error(`没有这个部件:${patch.name}`);
2222
+ }
2223
+ const current = { ...(job.boneOffsets ?? {}) };
2224
+ let touched = 0;
2225
+ for (const patch of patches) {
2226
+ const merged = pruneBoneOffset({ ...(current[patch.name] ?? {}), ...patch });
2227
+ if (merged === undefined)
2228
+ delete current[patch.name];
2229
+ else
2230
+ current[patch.name] = merged;
2231
+ touched++;
2232
+ }
2233
+ job.boneOffsets = Object.keys(current).length === 0 ? undefined : current;
2234
+ invalidateFrom(job, "rig");
2235
+ appendJobLog(job.log, "info", `${options.by === "ai" ? "AI" : "手工"}骨骼偏移:${patches.map((patch) => patch.name).join("、")}` +
2236
+ (options.label === undefined ? "" : `(${options.label})`));
2237
+ await writeRigJob(job);
2238
+ return { touched };
2239
+ }
2240
+ /** 清除手工骨骼偏移(全部,或点名几根)。这是「回到 AI 推的姿势」的唯一入口。 */
2241
+ export async function resetRigBoneOffsets(jobId, names) {
2242
+ const job = await readRigJob(jobId);
2243
+ if (job === undefined)
2244
+ throw new Error(`任务不存在:${jobId}`);
2245
+ const current = { ...(job.boneOffsets ?? {}) };
2246
+ const targets = names === undefined || names.length === 0 ? Object.keys(current) : names;
2247
+ let touched = 0;
2248
+ for (const name of targets) {
2249
+ if (current[name] === undefined)
2250
+ continue;
2251
+ delete current[name];
2252
+ touched++;
2253
+ }
2254
+ job.boneOffsets = Object.keys(current).length === 0 ? undefined : current;
2255
+ invalidateFrom(job, "rig");
2256
+ appendJobLog(job.log, "info", touched > 0 ? `已清除 ${touched} 根骨骼的手工偏移` : "没有需要清除的手工偏移");
2257
+ await writeRigJob(job);
2258
+ return { touched };
2259
+ }
2260
+ // ── 语义层(阶段③)──────────────────────────────────────────────────────
2261
+ /** 参与语义的部件:只有 ready 且没被隐藏的部件才进骨架。 */
2262
+ function semanticPartsOf(job) {
2263
+ return job.parts.filter((part) => part.status === "ready" && part.hidden !== true);
2264
+ }
2265
+ /** 把一个部件节点摊成语义层的输入形状。 */
2266
+ function semanticsInputOf(parts) {
2267
+ return parts.map((part) => ({
2268
+ name: part.name,
2269
+ role: part.role,
2270
+ parent: part.parent,
2271
+ proximal: part.proximal,
2272
+ distal: part.distal,
2273
+ tags: part.tags,
2274
+ source: part.semanticsSource
2275
+ }));
2276
+ }
2277
+ /**
2278
+ * 补齐缺失的语义。
2279
+ *
2280
+ * **这是「不填表也能跑」的落点**:拆件刚跑完、或用户刚上传完部件时,每个部件
2281
+ * 都还没有语义;这里用 `defaultSemanticsOf` 一次性补全(角色按名字推断、父级按
2282
+ * 角色链推导、锚点取角色默认)。之后 AI 或人只需要改**不对的那几条**。
2283
+ *
2284
+ * 返回补齐的条数,便于在日志里说清楚「这一步做了什么」。
2285
+ */
2286
+ export function ensurePartSemantics(job) {
2287
+ const parts = semanticPartsOf(job);
2288
+ if (parts.length === 0)
2289
+ return 0;
2290
+ const fresh = defaultSemanticsOf(parts.map((part) => part.name));
2291
+ const byName = new Map(fresh.map((item) => [item.name, item]));
2292
+ let filled = 0;
2293
+ for (const part of parts) {
2294
+ if (part.role !== undefined && part.proximal !== undefined && part.distal !== undefined)
2295
+ continue;
2296
+ const item = byName.get(part.name);
2297
+ if (item === undefined)
2298
+ continue;
2299
+ if (part.role === undefined)
2300
+ part.role = item.role;
2301
+ if (part.parent === undefined)
2302
+ part.parent = item.parent;
2303
+ if (part.proximal === undefined)
2304
+ part.proximal = item.proximal;
2305
+ if (part.distal === undefined)
2306
+ part.distal = item.distal;
2307
+ if (part.tags === undefined)
2308
+ part.tags = item.tags;
2309
+ if (part.semanticsSource === undefined)
2310
+ part.semanticsSource = "default";
2311
+ filled++;
2312
+ }
2313
+ // 顺手做一次**修复**:删部件 / 隐藏部件 / 改名字之后,父级可能指向已经不存在的
2314
+ // 部件。悬空父级会让骨架断链,成环会让渲染无限递归——两者都必须在写入前清掉。
2315
+ // 放在这里而不是每个调用点,是因为「改变部件集合」的入口有好几个(分割、上传、
2316
+ // 删除、隐藏、改名),漏掉任何一个都会留下坏数据。
2317
+ const repaired = validateSemantics(semanticsInputOf(semanticPartsOf(job)));
2318
+ writeSemantics(job, repaired.parts);
2319
+ return filled;
2320
+ }
2321
+ /**
2322
+ * 校验当前任务的语义。
2323
+ *
2324
+ * 失败也返回可用的 `parts`(语义层的校验函数保证这一点),所以界面永远能显示
2325
+ * 「哪里不对」,而不是一片空白。
2326
+ */
2327
+ export function validateRigSemantics(job, options = {}) {
2328
+ const parts = semanticPartsOf(job);
2329
+ const result = validateSemantics(semanticsInputOf(parts), options);
2330
+ return { parts: result.parts, errors: result.errors, warnings: result.warnings, ok: result.ok };
2331
+ }
2332
+ /** 把校验后的语义写回部件节点。 */
2333
+ function writeSemantics(job, parts) {
2334
+ const byName = new Map(parts.map((part) => [part.name, part]));
2335
+ for (const node of job.parts) {
2336
+ const item = byName.get(node.name);
2337
+ if (item === undefined)
2338
+ continue;
2339
+ node.role = item.role;
2340
+ node.parent = item.parent;
2341
+ node.proximal = item.proximal;
2342
+ node.distal = item.distal;
2343
+ node.tags = item.tags;
2344
+ node.semanticsSource = item.source;
2345
+ }
2346
+ }
2347
+ /**
2348
+ * 局部修改语义(AI 或人)。
2349
+ *
2350
+ * 只改传进来的字段——这是细粒度失效传播的前提:改一个部件的 `parent` 不应该
2351
+ * 让整份语义表重新生成,也不应该丢掉别人调过的锚点。
2352
+ *
2353
+ * 校验不通过时**不落盘**:错误会原样返回给调用方(界面/agent),
2354
+ * 由它决定是修正还是强制写入。理由是语义错误会一路传到骨架与导出,
2355
+ * 静默写进去比直接拒绝代价大得多。
2356
+ */
2357
+ export async function setRigSemantics(jobId, patches, options = {}) {
2358
+ const job = await readRigJob(jobId);
2359
+ if (job === undefined)
2360
+ throw new Error(`任务不存在:${jobId}`);
2361
+ if (patches.length === 0)
2362
+ return { ok: true, touched: 0, errors: [], warnings: [] };
2363
+ const known = new Set(job.parts.map((part) => part.name));
2364
+ for (const patch of patches) {
2365
+ if (!known.has(patch.name))
2366
+ throw new Error(`没有这个部件:${patch.name}`);
2367
+ }
2368
+ ensurePartSemantics(job);
2369
+ const by = options.by ?? "human";
2370
+ const merged = mergeSemantics(semanticsInputOf(semanticPartsOf(job)), patches).map((item) => {
2371
+ const touched = patches.some((patch) => patch.name === item.name);
2372
+ return touched ? { ...item, source: by } : item;
2373
+ });
2374
+ const validated = validateSemantics(merged, { humanoid: options.humanoid });
2375
+ if (!validated.ok) {
2376
+ return { ok: false, touched: 0, errors: validated.errors, warnings: validated.warnings };
2377
+ }
2378
+ writeSemantics(job, validated.parts);
2379
+ // ⚠️ 只作废「骨骼与图集」,**不动装配结果**:语义(角色/父级/锚点)只影响
2380
+ // 骨骼推导,而部件摆在画布上的位置与语义无关。作废到 layout 会让用户改一次
2381
+ // 角色就白丢一次手工摆位——而角色恰恰是最需要反复试的字段。
2382
+ invalidateFrom(job, "rig");
2383
+ appendJobLog(job.log, "info", `语义已更新:${patches.map((patch) => patch.name).join("、")}` +
2384
+ (validated.warnings.length > 0 ? `;${validated.warnings.length} 条提示` : ""));
2385
+ await writeRigJob(job);
2386
+ return { ok: true, touched: patches.length, errors: [], warnings: validated.warnings };
2387
+ }
2388
+ // ── 阶段①:拆件 ────────────────────────────────────────────────────────
2389
+ /**
2390
+ * 用生图模型生成「拆件摊平图」。**这一步是唯一花钱的阶段**:一次 Seedream 调用。
2391
+ */
2392
+ export function startSheetGeneration(jobId) {
2393
+ try {
2394
+ assertIdle(jobId, "sheet", "拆件生图");
2395
+ }
2396
+ catch (error) {
2397
+ return { started: false, reason: messageOf(error) };
2398
+ }
2399
+ const started = kick(jobId, "sheet", () => generateSheet(jobId));
2400
+ return started ? { started: true } : { started: false, reason: "拆件生图已在进行中" };
2401
+ }
2402
+ export async function generateSheet(jobId) {
2403
+ const job = await readRigJob(jobId);
2404
+ if (job === undefined)
2405
+ throw new Error(`任务不存在:${jobId}`);
2406
+ const config = await loadConfig();
2407
+ if (config.arkApiKey.trim() === "")
2408
+ throw new Error("尚未配置火山方舟 API Key");
2409
+ if (job.source === undefined)
2410
+ throw new Error("还没有角色参考图,请先上传一张整图");
2411
+ const prompt = buildSheetRequest(job);
2412
+ job.settings.model = config.arkModel;
2413
+ job.sheet = { ...job.sheet, status: "running", error: undefined };
2414
+ appendJobLog(job.log, "info", `开始拆件生图(模型 ${config.arkModel})`);
2415
+ await writeRigJob(job);
2416
+ try {
2417
+ const reference = await toDataUri(rigAssetPath(jobId, job.source.file), mimeOf(job.source.file));
2418
+ const result = await generateImage({
2419
+ baseUrl: config.arkBaseUrl,
2420
+ apiKey: config.arkApiKey,
2421
+ model: config.arkModel,
2422
+ prompt,
2423
+ images: [reference],
2424
+ size: job.settings.size || config.arkSize,
2425
+ watermark: job.settings.watermark,
2426
+ timeoutMs: config.arkTimeoutMs
2427
+ });
2428
+ const relative = `sheet/parts-sheet.${result.ext}`;
2429
+ await mkdir(join(rigJobDir(jobId), "sheet"), { recursive: true });
2430
+ await writeFile(rigAssetPath(jobId, relative), result.bytes);
2431
+ const fresh = await readRigJob(jobId);
2432
+ if (fresh === undefined)
2433
+ return;
2434
+ fresh.sheet = { status: "ready", file: relative, error: undefined, updatedAt: Date.now() };
2435
+ appendJobLog(fresh.log, "info", `拆件图已生成(${(result.bytes.length / 1024).toFixed(0)} KB)`);
2436
+ await writeRigJob(fresh);
2437
+ }
2438
+ catch (error) {
2439
+ const fresh = await readRigJob(jobId);
2440
+ if (fresh === undefined)
2441
+ return;
2442
+ fresh.sheet = { ...fresh.sheet, status: "error", error: messageOf(error), updatedAt: Date.now() };
2443
+ appendJobLog(fresh.log, "error", `拆件生图失败:${messageOf(error)}`);
2444
+ await writeRigJob(fresh);
2445
+ throw error;
2446
+ }
2447
+ // 生图成功后立刻分割,用户拿到的是一个可以直接验收的部件列表。
2448
+ await segmentSheet(jobId);
2449
+ }
2450
+ export function startSegmentation(jobId) {
2451
+ try {
2452
+ assertIdle(jobId, "segment", "分割");
2453
+ }
2454
+ catch (error) {
2455
+ return { started: false, reason: messageOf(error) };
2456
+ }
2457
+ const started = kick(jobId, "segment", () => segmentSheet(jobId));
2458
+ return started ? { started: true } : { started: false, reason: "分割已在进行中" };
2459
+ }
2460
+ /**
2461
+ * 把摊平图切成部件。
2462
+ *
2463
+ * 分割依赖「格子 = 部件身份」这个约定:连通域按质心归到某个格子,格子名就是
2464
+ * 部件名。一个格子里出现多块时取最大的一块,其余作为 `名字-2` 之类的附加件保留
2465
+ * ——生图模型偶尔会把配饰画成独立小块,直接丢掉不如留给用户判断。
2466
+ */
2467
+ export async function segmentSheet(jobId) {
2468
+ const job = await readRigJob(jobId);
2469
+ if (job === undefined)
2470
+ throw new Error(`任务不存在:${jobId}`);
2471
+ if (job.sheet.file === undefined)
2472
+ throw new Error("还没有拆件图,请先在第 ① 步生成或上传");
2473
+ const decoded = await decodeToRgba(rigAssetPath(jobId, job.sheet.file), 2048);
2474
+ const atlas = { data: decoded.rgba, width: decoded.width, height: decoded.height };
2475
+ const background = detectBackground(atlas);
2476
+ const columns = job.settings.gridColumns;
2477
+ const rows = job.settings.gridRows;
2478
+ const cellWidth = atlas.width / columns;
2479
+ const cellHeight = atlas.height / rows;
2480
+ const autoMinArea = Math.max(120, Math.round((atlas.width * atlas.height) / (columns * rows) * 0.004));
2481
+ const minArea = job.settings.minArea > 0 ? job.settings.minArea : autoMinArea;
2482
+ const segmented = segmentWithLabels(atlas, {
2483
+ background,
2484
+ tolerance: job.settings.backgroundTolerance,
2485
+ minArea,
2486
+ padding: job.settings.partPadding,
2487
+ feather: job.settings.feather
2488
+ });
2489
+ const components = segmented.components;
2490
+ appendJobLog(job.log, "info", `分割:底色 rgb(${background.join(",")}),连通域 ${components.length} 块(最小面积 ${minArea})`);
2491
+ await mkdir(join(rigJobDir(jobId), "parts"), { recursive: true });
2492
+ // 先把「挨在一起的碎块」并成一个部件,再按格子命名。两步都不能省:
2493
+ //
2494
+ // ① **按包围盒邻近合并**,而不是「一格合并所有」。实测生图模型会把一件东西画成
2495
+ // 互不相连的几块(围裙的白布片、鲸鱼刺绣、裙摆高光都是独立连通域),按格子
2496
+ // 一把抓会把它们和同格的**别的**部件揉在一起——实测出现过「一只手 + 两段袖子」
2497
+ // 被并成一个部件,那种部件根本没法摆。
2498
+ // ② 命名另算(见 cellOfGroup):溢出多半是往下的(裙摆、头发、尾巴),按面积最大
2499
+ // 归属会把整条裙子判给下面那格,于是它被命名成 right-lower-arm。
2500
+ // 合并阈值取「格子的 1.5%」,实测 4~8px:同一件东西被画成几块时(围裙的白布片、
2501
+ // 鲸鱼刺绣)它们真的挨得很近,而不同部件之间模型会留出明显空白。
2502
+ const MERGE_GAP = Math.max(3, Math.round(Math.min(cellWidth, cellHeight) * 0.015));
2503
+ const rootOf = groupComponentsByProximity(segmented.labels, segmented.width, segmented.height, MERGE_GAP);
2504
+ const groups = new Map();
2505
+ for (let i = 0; i < components.length; i++) {
2506
+ const root = rootOf[components[i].label];
2507
+ const list = groups.get(root) ?? [];
2508
+ list.push(i);
2509
+ groups.set(root, list);
2510
+ }
2511
+ /** 一组连通域的并集包围盒。 */
2512
+ const groupBox = (indices) => {
2513
+ let x0 = Number.POSITIVE_INFINITY;
2514
+ let y0 = Number.POSITIVE_INFINITY;
2515
+ let x1 = 0;
2516
+ let y1 = 0;
2517
+ for (const item of indices) {
2518
+ const component = components[item];
2519
+ x0 = Math.min(x0, component.x);
2520
+ y0 = Math.min(y0, component.y);
2521
+ x1 = Math.max(x1, component.x + component.width);
2522
+ y1 = Math.max(y1, component.y + component.height);
2523
+ }
2524
+ return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };
2525
+ };
2526
+ const overlapWithCell = (box, cell) => {
2527
+ const column = cell % columns;
2528
+ const row = Math.floor(cell / columns);
2529
+ const overlapX = Math.max(0, Math.min(box.x + box.width, (column + 1) * cellWidth) - Math.max(box.x, column * cellWidth));
2530
+ const overlapY = Math.max(0, Math.min(box.y + box.height, (row + 1) * cellHeight) - Math.max(box.y, row * cellHeight));
2531
+ return overlapX * overlapY;
2532
+ };
2533
+ /**
2534
+ * 组 → 格子:在覆盖率不低于最大值一半的候选里,取**最靠上**(再最靠左)的那格。
2535
+ * 部件溢出多半往下(裙摆、头发、尾巴),取最上那格正好对上模型的意图:
2536
+ * 实测整条裙子若按面积最大归属会被判给下面那格,命名成 right-lower-arm。
2537
+ */
2538
+ const cellOfGroup = (box) => {
2539
+ const cells = [...Array(columns * rows).keys()].map((cell) => ({ cell, overlap: overlapWithCell(box, cell) }));
2540
+ const best = Math.max(...cells.map((item) => item.overlap));
2541
+ return cells
2542
+ .filter((item) => item.overlap >= best * 0.5)
2543
+ .sort((left, right) => Math.floor(left.cell / columns) - Math.floor(right.cell / columns) ||
2544
+ (left.cell % columns) - (right.cell % columns))[0].cell;
2545
+ };
2546
+ // 面积大的先占格子,避免小碎块把格子抢走。
2547
+ const orderedGroups = [...groups.values()].sort((left, right) => right.reduce((sum, item) => sum + components[item].area, 0) - left.reduce((sum, item) => sum + components[item].area, 0));
2548
+ const slotNames = rigSlotNames(job);
2549
+ /** 手工上传的部件不受网格分割影响,保留下来。 */
2550
+ const uploaded = job.parts.filter((part) => part.source === "uploaded" && part.status === "ready");
2551
+ const next = [...uploaded];
2552
+ const claimed = new Set(uploaded.map((part) => part.name));
2553
+ const takenCells = new Set();
2554
+ /** 质检要用的像素:分割出来的部件图本来就在内存里,顺手留一份,不必再解一遍盘。 */
2555
+ const qaParts = [];
2556
+ let mergedFragments = 0;
2557
+ let order = 0;
2558
+ for (const group of orderedGroups) {
2559
+ order++;
2560
+ const box = groupBox(group);
2561
+ let cell = cellOfGroup(box);
2562
+ if (takenCells.has(cell)) {
2563
+ const free = [...Array(columns * rows).keys()]
2564
+ .filter((candidate) => !takenCells.has(candidate))
2565
+ .sort((left, right) => overlapWithCell(box, right) - overlapWithCell(box, left) || left - right);
2566
+ cell = free[0] ?? cell;
2567
+ }
2568
+ const slot = slotNames[cell] ?? `slot-${cell + 1}`;
2569
+ const name = claimed.has(slot) ? `${slot}-${order}` : slot;
2570
+ claimed.add(name);
2571
+ takenCells.add(cell);
2572
+ const merged = mergeComponents(group.map((item) => components[item]), atlas.width, atlas.height);
2573
+ const trimmed = trimTransparent(merged);
2574
+ qaParts.push({ name, rgba: trimmed });
2575
+ const relative = `parts/${name}.png`;
2576
+ await writeFile(rigAssetPath(jobId, relative), encodePng(trimmed.data, trimmed.width, trimmed.height));
2577
+ let opaque = 0;
2578
+ for (let k = 0; k < trimmed.width * trimmed.height; k++)
2579
+ if (trimmed.data[k * 4 + 3] > 128)
2580
+ opaque++;
2581
+ if (group.length > 1)
2582
+ mergedFragments += group.length - 1;
2583
+ next.push({
2584
+ name,
2585
+ label: partLabel(name),
2586
+ status: "ready",
2587
+ file: relative,
2588
+ width: trimmed.width,
2589
+ height: trimmed.height,
2590
+ gridX: cell % columns,
2591
+ gridY: Math.floor(cell / columns),
2592
+ opacity: Number((opaque / (trimmed.width * trimmed.height)).toFixed(3)),
2593
+ source: "generated",
2594
+ approved: false,
2595
+ updatedAt: Date.now()
2596
+ });
2597
+ }
2598
+ // 删掉旧的 slotNames/uploaded/claimed 声明(现在在上面)
2599
+ const fresh = await readRigJob(jobId);
2600
+ if (fresh === undefined)
2601
+ return;
2602
+ fresh.parts = next;
2603
+ // 分割完立刻补齐语义:这样「格子名 → 角色 → 父级/锚点」是一条确定链路,
2604
+ // 用户可以先去装配、也可以先改语义,两条路都不需要先填一张表。
2605
+ const filledSemantics = ensurePartSemantics(fresh);
2606
+ fresh.layout = { status: "empty", items: {} };
2607
+ fresh.rig = { status: "empty" };
2608
+ fresh.atlas = { status: "empty" };
2609
+ // 生成部件蒙太奇:把分割出来的部件按**与 parts 数组相同的顺序**拼成一张图。
2610
+ // 这是「视觉先验」那一步的输入——多模态模型看一张图比逐个打开十几个文件省事得多,
2611
+ // 而且顺序固定,它说「第 7 格是左手」我们就能直接换算成部件名。
2612
+ const generated = next.filter((part) => part.source === "generated" && part.file !== undefined);
2613
+ if (generated.length > 0) {
2614
+ const CELL = 200;
2615
+ const COLS = Math.min(6, generated.length);
2616
+ const ROWS = Math.ceil(generated.length / COLS);
2617
+ const canvas = createRgba(CELL * COLS, CELL * ROWS, [246, 246, 249, 255]);
2618
+ for (let i = 0; i < generated.length; i++) {
2619
+ const decoded = await decodeCached(rigAssetPath(jobId, generated[i].file), 1024);
2620
+ const scale = Math.min((CELL - 14) / decoded.width, (CELL - 14) / decoded.height);
2621
+ const scaled = resizeRgba({ data: decoded.rgba, width: decoded.width, height: decoded.height }, Math.max(1, Math.round(decoded.width * scale)), Math.max(1, Math.round(decoded.height * scale)));
2622
+ const column = i % COLS;
2623
+ const row = Math.floor(i / COLS);
2624
+ blitRgba(canvas, scaled, column * CELL + Math.round((CELL - scaled.width) / 2), row * CELL + Math.round((CELL - scaled.height) / 2));
2625
+ // 画格线,让「第几格」在图上可以直接数出来。
2626
+ for (let x = column * CELL; x < column * CELL + CELL && x < canvas.width; x++) {
2627
+ const at = (row * CELL) * canvas.width * 4 + x * 4;
2628
+ canvas.data[at] = 208;
2629
+ canvas.data[at + 1] = 208;
2630
+ canvas.data[at + 2] = 216;
2631
+ }
2632
+ for (let y = row * CELL; y < row * CELL + CELL && y < canvas.height; y++) {
2633
+ const at = (y * canvas.width + column * CELL) * 4;
2634
+ canvas.data[at] = 208;
2635
+ canvas.data[at + 1] = 208;
2636
+ canvas.data[at + 2] = 216;
2637
+ }
2638
+ }
2639
+ await mkdir(join(rigJobDir(jobId), "sheet"), { recursive: true });
2640
+ await writeFile(rigAssetPath(jobId, "sheet/parts-montage.png"), encodePng(canvas.data, canvas.width, canvas.height));
2641
+ await writeFile(rigAssetPath(jobId, "sheet/parts.json"), `${JSON.stringify({ columns: COLS, cell: CELL, order: generated.map((part) => part.name) }, null, 2)}\n`, "utf8");
2642
+ }
2643
+ const missing = slotNames.filter((name) => !next.some((part) => part.name === name));
2644
+ appendJobLog(fresh.log, "info", `分割完成:${next.filter((p) => p.source === "generated").length} 个部件` +
2645
+ (missing.length > 0 ? `;这些格子没有检测到部件:${missing.join("、")}` : "") +
2646
+ (mergedFragments > 0 ? `;有 ${mergedFragments} 个碎块被并进了相邻的部件` : "") +
2647
+ (filledSemantics > 0 ? `;已补齐 ${filledSemantics} 个部件的语义(角色/父级/锚点)` : ""));
2648
+ // 生图模型不按网格摆的情况并不罕见(实测常把「上臂+小臂+手」连成一整块,
2649
+ // 或者把角色摊成两三行松散布局)。这时格子归属就没有意义了,与其让骨架
2650
+ // 挂着一堆错名字,不如明确告诉用户:重新生成,或者手工上传命名部件。
2651
+ if (missing.length >= Math.ceil(slotNames.length * 0.4)) {
2652
+ appendJobLog(fresh.log, "warn", `拆件图有 ${missing.length}/${slotNames.length} 个格子是空的——生图模型很可能没有按网格摆放。` +
2653
+ `建议:① 重新生成拆件图;② 或者用「部件 PNG」上传框自己传(文件名即部件名,如 head.png、torso.png)。` +
2654
+ `空着的部件会被跳过,不会进入骨架。`);
2655
+ }
2656
+ // 拆件质检:**在装配之前**就把「这批拆件能不能信」说出来。
2657
+ //
2658
+ // 这一步专门为这次踩的坑而加:18 块里 6 块是同一部位重画、名字与实际内容错位,
2659
+ // 而界面当时显示的是"部件(18)——逐件验收",一切正常。要等到装配完、
2660
+ // 看见"头长在脚上"才发现,那时已经花掉了一次生图调用和一轮手工排查。
2661
+ fresh.qa = buildQaState(assessParts({
2662
+ parts: qaParts,
2663
+ expectedParts: fresh.qa?.expectedParts
2664
+ }));
2665
+ appendJobLog(fresh.log, fresh.qa.ok ? "info" : "warn", `拆件质检:${fresh.qa.summary}`);
2666
+ for (const issue of fresh.qa.issues) {
2667
+ appendJobLog(fresh.log, issue.level === "error" ? "warn" : "info", `拆件质检 · ${issue.message}`);
2668
+ }
2669
+ await writeRigJob(fresh);
2670
+ }
2671
+ /** 把质检报告压成任务里存的那份(去掉只在计算时有意义的字段)。 */
2672
+ function buildQaState(report, expectedParts) {
2673
+ return {
2674
+ ok: report.ok,
2675
+ score: report.score,
2676
+ summary: report.summary,
2677
+ checked: report.checked,
2678
+ duplicates: report.duplicates.map((group) => ({
2679
+ parts: group.parts,
2680
+ minOverlap: group.minOverlap,
2681
+ mirroredOverlap: group.mirroredOverlap,
2682
+ symmetric: group.symmetric
2683
+ })),
2684
+ issues: report.issues.map((issue) => ({
2685
+ level: issue.level,
2686
+ code: issue.code,
2687
+ parts: issue.parts,
2688
+ message: issue.message,
2689
+ suggestion: issue.suggestion
2690
+ })),
2691
+ // `expectedParts` 是人/agent 给的输入,不随重算丢失——否则装配重跑一次它就没了。
2692
+ ...(expectedParts === undefined ? {} : { expectedParts }),
2693
+ updatedAt: Date.now()
2694
+ };
2695
+ }
2696
+ /**
2697
+ * 重跑拆件质检(从磁盘读部件像素)。
2698
+ *
2699
+ * `expectedParts`(参考图里大致有几个独立部位)只能靠视觉判断,所以留成参数:
2700
+ * agent 看图后填,用户也可以自己填。给不出就不做这项判断——
2701
+ * 宁可不报,也不要瞎报。
2702
+ */
2703
+ export async function runRigQa(jobId, expectedParts) {
2704
+ const job = await readRigJob(jobId);
2705
+ if (job === undefined)
2706
+ throw new Error(`任务不存在:${jobId}`);
2707
+ const parts = [];
2708
+ for (const part of job.parts) {
2709
+ if (part.status !== "ready" || part.file === undefined)
2710
+ continue;
2711
+ if (part.hidden === true)
2712
+ continue;
2713
+ try {
2714
+ const decoded = await decodeCached(rigAssetPath(jobId, part.file), 1024);
2715
+ parts.push({ name: part.name, rgba: { data: decoded.rgba, width: decoded.width, height: decoded.height } });
2716
+ }
2717
+ catch {
2718
+ // 读不出来的部件不参与质检——它是另一个问题(文件坏了),不该在这里报。
2719
+ }
2720
+ }
2721
+ const matches = job.layout.items === undefined
2722
+ ? []
2723
+ : Object.entries(job.layout.items)
2724
+ // 人给过位置的部件不参与「匹配质量」评估:那个分数要么已经被清掉,
2725
+ // 要么描述的是它被挪走**之前**的自动结果。
2726
+ .filter(([, item]) => item.manual !== true)
2727
+ .map(([name, item]) => ({ name, score: item.score, matched: item.matched }));
2728
+ const report = assessParts({
2729
+ parts,
2730
+ matches,
2731
+ expectedParts: expectedParts ?? job.qa?.expectedParts
2732
+ });
2733
+ job.qa = buildQaState(report);
2734
+ if (expectedParts !== undefined)
2735
+ job.qa.expectedParts = expectedParts;
2736
+ appendJobLog(job.log, report.ok ? "info" : "warn", `拆件质检:${report.summary}`);
2737
+ await writeRigJob(job);
2738
+ return job.qa;
2739
+ }
2740
+ /**
2741
+ * 把同一格里的多个连通域合并成一张部件图(各块保留自己的透明通道,按位置贴回去)。
2742
+ */
2743
+ function mergeComponents(list, canvasWidth, canvasHeight) {
2744
+ let minX = canvasWidth;
2745
+ let minY = canvasHeight;
2746
+ let maxX = 0;
2747
+ let maxY = 0;
2748
+ for (const item of list) {
2749
+ minX = Math.min(minX, item.x);
2750
+ minY = Math.min(minY, item.y);
2751
+ maxX = Math.max(maxX, item.x + item.width);
2752
+ maxY = Math.max(maxY, item.y + item.height);
2753
+ }
2754
+ const width = Math.max(1, maxX - minX);
2755
+ const height = Math.max(1, maxY - minY);
2756
+ const out = createRgba(width, height);
2757
+ for (const item of list) {
2758
+ for (let y = 0; y < item.rgba.height; y++) {
2759
+ const ty = item.y - minY + y;
2760
+ if (ty < 0 || ty >= height)
2761
+ continue;
2762
+ for (let x = 0; x < item.rgba.width; x++) {
2763
+ const tx = item.x - minX + x;
2764
+ if (tx < 0 || tx >= width)
2765
+ continue;
2766
+ const src = (y * item.rgba.width + x) * 4;
2767
+ if (item.rgba.data[src + 3] === 0)
2768
+ continue;
2769
+ const dst = (ty * width + tx) * 4;
2770
+ out.data[dst] = item.rgba.data[src];
2771
+ out.data[dst + 1] = item.rgba.data[src + 1];
2772
+ out.data[dst + 2] = item.rgba.data[src + 2];
2773
+ out.data[dst + 3] = Math.max(out.data[dst + 3], item.rgba.data[src + 3]);
2774
+ }
2775
+ }
2776
+ }
2777
+ return out;
2778
+ }
2779
+ /** 去掉四周全透明边,让部件坐标都从自己的左上角量起。 */
2780
+ function trimTransparent(rgba) {
2781
+ let minX = rgba.width;
2782
+ let minY = rgba.height;
2783
+ let maxX = -1;
2784
+ let maxY = -1;
2785
+ for (let y = 0; y < rgba.height; y++) {
2786
+ for (let x = 0; x < rgba.width; x++) {
2787
+ if (rgba.data[(y * rgba.width + x) * 4 + 3] <= 8)
2788
+ continue;
2789
+ if (x < minX)
2790
+ minX = x;
2791
+ if (y < minY)
2792
+ minY = y;
2793
+ if (x > maxX)
2794
+ maxX = x;
2795
+ if (y > maxY)
2796
+ maxY = y;
2797
+ }
2798
+ }
2799
+ if (maxX < 0)
2800
+ return rgba;
2801
+ const width = maxX - minX + 1;
2802
+ const height = maxY - minY + 1;
2803
+ const out = Buffer.alloc(width * height * 4);
2804
+ for (let y = 0; y < height; y++) {
2805
+ rgba.data.copy(out, y * width * 4, ((minY + y) * rgba.width + minX) * 4, ((minY + y) * rgba.width + minX + width) * 4);
2806
+ }
2807
+ return { data: out, width, height };
2808
+ }
2809
+ // ── 阶段②:装配定位 ────────────────────────────────────────────────────
2810
+ export function startLayout(jobId, names) {
2811
+ try {
2812
+ assertIdle(jobId, "layout", "装配定位");
2813
+ }
2814
+ catch (error) {
2815
+ return { started: false, reason: messageOf(error) };
2816
+ }
2817
+ const started = kick(jobId, "layout", () => solveRigLayout(jobId, names));
2818
+ return started ? { started: true } : { started: false, reason: "装配定位已在进行中" };
2819
+ }
2820
+ /**
2821
+ * 把部件摆回参考姿态。
2822
+ *
2823
+ * `names` 为空时求解全部(并做冲突消解与遮挡修正);只给部分名字时**只重跑这些
2824
+ * 部件**,保留其余结果——失败一两个部件时用户只需要重试那几个,不必整批重算。
2825
+ */
2826
+ export async function solveRigLayout(jobId, names) {
2827
+ const job = await readRigJob(jobId);
2828
+ if (job === undefined)
2829
+ throw new Error(`任务不存在:${jobId}`);
2830
+ if (job.source === undefined)
2831
+ throw new Error("还没有角色参考图,请先上传一张整图");
2832
+ const ready = job.parts.filter((part) => part.status === "ready" && part.hidden !== true && part.file !== undefined);
2833
+ if (ready.length === 0)
2834
+ throw new Error("还没有可用部件,请先在第 ① 步拆件或上传部件 PNG");
2835
+ const subset = names === undefined || names.length === 0 ? undefined : ready.filter((part) => names.includes(part.name));
2836
+ if (subset !== undefined && subset.length === 0)
2837
+ throw new Error("指定的部件都不存在或还不可用");
2838
+ const referenceDecoded = await decodeToRgba(rigAssetPath(jobId, job.source.file), 2048);
2839
+ const reference = { data: referenceDecoded.rgba, width: referenceDecoded.width, height: referenceDecoded.height };
2840
+ const inputs = [];
2841
+ for (const part of subset ?? ready) {
2842
+ const decoded = await decodeCached(rigAssetPath(jobId, part.file), 2048);
2843
+ inputs.push({ name: part.name, rgba: { data: decoded.rgba, width: decoded.width, height: decoded.height } });
2844
+ part.width = decoded.width;
2845
+ part.height = decoded.height;
2846
+ }
2847
+ job.layout.status = "running";
2848
+ job.layout.error = undefined;
2849
+ appendJobLog(job.log, "info", `开始装配定位:${inputs.length} 个部件${subset === undefined ? "(全量)" : "(部分重跑)"}`);
2850
+ await writeRigJob(job);
2851
+ try {
2852
+ const solved = solveLayout(reference, inputs, {
2853
+ longEdge: job.settings.matchLongEdge,
2854
+ drawOrder: subset === undefined ? DEFAULT_DRAW_ORDER : undefined,
2855
+ // 视觉先验只在**全量**装配时用:局部重跑(用户点名几个部件)时不带先验,
2856
+ // 否则「重新自动定位」会变成「又回到我上次说的那个位置」,用户没法纠正它。
2857
+ hints: subset === undefined ? job.layout.hints : undefined
2858
+ });
2859
+ const fresh = await readRigJob(jobId);
2860
+ if (fresh === undefined)
2861
+ return;
2862
+ if (subset === undefined)
2863
+ fresh.layout.items = {};
2864
+ for (const [name, result] of Object.entries(solved.placements)) {
2865
+ fresh.layout.items[name] = {
2866
+ x: result.x,
2867
+ y: result.y,
2868
+ width: result.width,
2869
+ height: result.height,
2870
+ scale: result.scale,
2871
+ rotation: result.rotation,
2872
+ z: drawRankOf(name),
2873
+ score: result.score,
2874
+ coverage: result.coverage,
2875
+ matched: true,
2876
+ manual: false
2877
+ };
2878
+ }
2879
+ // 没匹配上的部件放到画布左下角的「待摆放」区,而不是 (0,0):
2880
+ // 界面上的方块可以拖动,用户直接把它们拖到正确位置即可。
2881
+ const stagingScale = solved.hint || 0.2;
2882
+ solved.failed.forEach((name, order) => {
2883
+ if (fresh.layout.items[name] !== undefined)
2884
+ return;
2885
+ const node = fresh.parts.find((part) => part.name === name);
2886
+ const width = Math.max(8, Math.round((node?.width ?? 64) * stagingScale));
2887
+ const height = Math.max(8, Math.round((node?.height ?? 64) * stagingScale));
2888
+ fresh.layout.items[name] = {
2889
+ x: 6 + (order % 6) * 56,
2890
+ y: Math.max(0, referenceDecoded.height - height - 4),
2891
+ width,
2892
+ height,
2893
+ scale: stagingScale,
2894
+ rotation: 0,
2895
+ z: drawRankOf(name),
2896
+ matched: false,
2897
+ manual: false
2898
+ };
2899
+ });
2900
+ if (subset === undefined) {
2901
+ fresh.layout.hint = Number(solved.hint.toFixed(4));
2902
+ fresh.layout.moved = solved.moved;
2903
+ fresh.layout.resolved = solved.resolved;
2904
+ }
2905
+ fresh.layout.status = "ready";
2906
+ fresh.layout.approved = false;
2907
+ fresh.layout.updatedAt = Date.now();
2908
+ // 匹配质量本身就是一个**信号**:如果整批部件的相似度都很低,通常不是「参数没调好」,
2909
+ // 而是拆件图里的角色和参考图根本不是同一个(实测生图模型会把角色换成另一个:
2910
+ // 原图是穿深蓝连衣裙的女仆,拆件图给的却是白短裤 + 光腿的一具裸身)。
2911
+ // 这种情况下再怎么调匹配都是白费力气,必须直说,并给出真正能走通的两条路。
2912
+ // 结构合理性检查:这些名字本身就带着人体结构信息,装配结果必须自洽。
2913
+ // 分数高不代表摆得对——实测有一版「头」落在画面下半部分、裙摆放到了最上面,
2914
+ // 平均相似度却还有 0.48,纯靠分数根本发现不了。人形的基本约束(头在最上面、
2915
+ // 脚在最下面)是免费的强信号,违反它就直接判定自动定位不可信。
2916
+ const verticalOrderProblem = (() => {
2917
+ const centerYOf = (name) => {
2918
+ const item = fresh.layout.items[name];
2919
+ if (item === undefined || item.matched !== true || partHidden(fresh, name))
2920
+ return undefined;
2921
+ return item.y + item.height / 2;
2922
+ };
2923
+ const headY = centerYOf("head");
2924
+ const footY = centerYOf("left-foot") ?? centerYOf("right-foot");
2925
+ const legY = centerYOf("left-upper-leg") ?? centerYOf("right-upper-leg");
2926
+ if (headY === undefined)
2927
+ return undefined;
2928
+ if (footY !== undefined && headY > footY)
2929
+ return "「头」被摆到了「脚」的下面";
2930
+ if (legY !== undefined && headY > legY)
2931
+ return "「头」被摆到了「大腿」的下面";
2932
+ return undefined;
2933
+ })();
2934
+ const matchedScores = Object.values(solved.placements).map((item) => item.score);
2935
+ const meanScore = matchedScores.length > 0 ? matchedScores.reduce((sum, value) => sum + value, 0) / matchedScores.length : 0;
2936
+ fresh.layout.meanScore = Number(meanScore.toFixed(4));
2937
+ const weak = solved.failed.length > 0 ? `这些部件没匹配上,需要人工摆放:${solved.failed.join("、")}` : undefined;
2938
+ if (meanScore < 0.32 && matchedScores.length > 0) {
2939
+ // 阈值定在 0.32:实测「拆件图是同一个角色」时均值约 0.38(而且受服装
2940
+ // 裁片影响本身就不会很高),「角色被换成另一个」时约 0.28 且个别部件
2941
+ // 直接匹配不上。低于 0.32 基本可以判定是后者,再调参数没有意义。
2942
+ const hint = `整批部件的平均相似度只有 ${meanScore.toFixed(2)},自动定位不可信。常见原因:` +
2943
+ `① 拆件图里的角色与参考图不是同一个(生图模型在「拆件」时换掉服装 / 发型 / 体型);` +
2944
+ `② 部件是按「服装裁片」拆的(裙摆、袖子、领子),外观本来就只覆盖参考图的一小块。` +
2945
+ `建议:① 用「部件 PNG」上传框传自己的部件(文件名即部件名,完全绕开生图);` +
2946
+ `② 或换更强的生图模型(设置 → 游戏素材大师 → 生图模型,实测 Seedream 5.0 Pro 明显更守角色设定)重新拆件;` +
2947
+ `③ 也可以在下面的合成图上手工拖到正确位置。`;
2948
+ appendJobLog(fresh.log, "warn", hint);
2949
+ fresh.layout.error = weak === undefined ? hint : `${weak};另外,${hint}`;
2950
+ }
2951
+ else if (verticalOrderProblem !== undefined) {
2952
+ const hint = `自动定位结果明显不合理:${verticalOrderProblem}。这通常意味着拆件图里的部件与参考图对不上` +
2953
+ `(部件可能是重新绘制的服装裁片,或角色被换过),继续相信自动结果反而更费时间。` +
2954
+ `建议:① 直接用「部件 PNG」上传框传自己的部件(文件名即部件名);② 在下面的合成图上手工拖到正确位置。`;
2955
+ appendJobLog(fresh.log, "warn", hint);
2956
+ fresh.layout.error = weak === undefined ? hint : `${weak};另外,${hint}`;
2957
+ }
2958
+ else {
2959
+ fresh.layout.error = weak;
2960
+ }
2961
+ fresh.rig = { status: "empty" };
2962
+ fresh.atlas = { status: "empty" };
2963
+ if (solved.hintedCount !== undefined && solved.hintedCount > 0) {
2964
+ appendJobLog(fresh.log, "info", `本次装配用了 ${solved.hintedCount} 个视觉先验(限制在给定区域附近搜索)`);
2965
+ }
2966
+ appendJobLog(fresh.log, "info", `装配完成:命中 ${Object.keys(solved.placements).length}/${inputs.length}` +
2967
+ (solved.failed.length > 0 ? `,未命中 ${solved.failed.join("、")}` : ""));
2968
+ // 装配完成后把相似度并进质检结论。
2969
+ //
2970
+ // 重复件那部分复用拆件时算好的结果(这里没有像素,重算要再解一遍全部 PNG,
2971
+ // 而这个函数每次拖动部件都会跑)。
2972
+ const matches = Object.entries(fresh.layout.items ?? {})
2973
+ // 同上:手工摆过的不算匹配质量。
2974
+ .filter(([, item]) => item.manual !== true)
2975
+ .map(([name, item]) => ({
2976
+ name,
2977
+ score: item.score,
2978
+ matched: item.matched
2979
+ }));
2980
+ fresh.qa = buildQaState(assessParts({
2981
+ duplicates: (fresh.qa?.duplicates ?? []).map((group) => ({
2982
+ parts: group.parts,
2983
+ minOverlap: group.minOverlap,
2984
+ mirroredOverlap: group.mirroredOverlap,
2985
+ symmetric: group.symmetric,
2986
+ width: 0,
2987
+ height: 0
2988
+ })),
2989
+ matches,
2990
+ partCount: fresh.parts.filter((part) => part.hidden !== true && part.status === "ready").length,
2991
+ expectedParts: fresh.qa?.expectedParts
2992
+ }));
2993
+ if (fresh.qa.expectedParts !== undefined)
2994
+ fresh.qa.expectedParts = fresh.qa.expectedParts;
2995
+ await writeRigJob(fresh);
2996
+ await renderLayoutImages(jobId);
2997
+ await writeLayoutJson(jobId);
2998
+ }
2999
+ catch (error) {
3000
+ const fresh = await readRigJob(jobId);
3001
+ if (fresh === undefined)
3002
+ return;
3003
+ fresh.layout.status = "error";
3004
+ fresh.layout.error = messageOf(error);
3005
+ appendJobLog(fresh.log, "error", `装配定位失败:${messageOf(error)}`);
3006
+ await writeRigJob(fresh);
3007
+ throw error;
3008
+ }
3009
+ }
3010
+ /** 手工调整某个部件的位置/尺寸/层级。 */
3011
+ /**
3012
+ * 记录/清除视觉先验。
3013
+ *
3014
+ * 这是「自动摆位」的关键入口:先验把「全图盲搜」降级成「在指定区域里精修」。
3015
+ * 先验来自多模态模型看一眼图(对话里就是 agent 自己),所以只要求**区域大致对**,
3016
+ * 不要求精确——实测重画过的部件在错误位置也能拿到不低的分数,盲搜正是因此失手。
3017
+ */
3018
+ export async function setRigLayoutHints(jobId, hints) {
3019
+ const job = await readRigJob(jobId);
3020
+ if (job === undefined)
3021
+ throw new Error(`任务不存在:${jobId}`);
3022
+ const current = { ...(job.layout.hints ?? {}) };
3023
+ let touched = 0;
3024
+ for (const [name, hint] of Object.entries(hints)) {
3025
+ if (!job.parts.some((part) => part.name === name))
3026
+ throw new Error(`没有这个部件:${name}`);
3027
+ if (hint === null) {
3028
+ delete current[name];
3029
+ touched++;
3030
+ continue;
3031
+ }
3032
+ const x = num(hint.x, NaN);
3033
+ const y = num(hint.y, NaN);
3034
+ const width = num(hint.width, NaN);
3035
+ const height = num(hint.height, NaN);
3036
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
3037
+ throw new Error(`「${name}」的先验框不合法:需要 x / y / width / height 四个正数`);
3038
+ }
3039
+ current[name] = { x, y, width, height };
3040
+ touched++;
3041
+ }
3042
+ job.layout.hints = Object.keys(current).length === 0 ? undefined : current;
3043
+ invalidateFrom(job, "layout");
3044
+ appendJobLog(job.log, "info", `已记录 ${touched} 个部件的视觉先验(装配时会限制在这些区域附近搜索)`);
3045
+ await writeRigJob(job);
3046
+ return { count: touched };
3047
+ }
3048
+ /**
3049
+ * 批量写入手动装配结果。
3050
+ *
3051
+ * 为什么是批量:手动装配是**拖出来**的——一次拖动、一次键盘微调都会改一个部件,
3052
+ * 逐条提交就是逐条「读盘 + 改 + 落盘 + 重出合成图」。重出合成图要解码参考图和全部
3053
+ * 部件,一条几百毫秒,连续微调会明显卡顿。批量提交把「一次编辑动作」收敛成一次写盘
3054
+ * 与一次渲染。
3055
+ *
3056
+ * 另外这里**允许为还不存在的摆放记录创建条目**:手动装配不该依赖先跑过自动定位
3057
+ * (拆完件直接手工拼是完全合理的用法),所以记录不存在时按部件的原始像素尺寸建一条。
3058
+ */
3059
+ export async function saveRigLayoutItems(jobId, patches) {
3060
+ const job = await readRigJob(jobId);
3061
+ if (job === undefined)
3062
+ throw new Error(`任务不存在:${jobId}`);
3063
+ if (patches.length === 0)
3064
+ return { touched: 0 };
3065
+ let touched = 0;
3066
+ for (const patch of patches) {
3067
+ const part = job.parts.find((entry) => entry.name === patch.name);
3068
+ if (part === undefined)
3069
+ throw new Error(`没有这个部件:${patch.name}`);
3070
+ let item = job.layout.items[patch.name];
3071
+ if (item === undefined) {
3072
+ // 没有记录:按部件的原始像素尺寸 + 全局缩放先验建一条,摆到画布左上角附近。
3073
+ const hint = job.layout.hint ?? 0.5;
3074
+ item = {
3075
+ x: 0,
3076
+ y: 0,
3077
+ width: Math.max(1, Math.round((part.width ?? 64) * (patch.width === undefined ? hint : 1))),
3078
+ height: Math.max(1, Math.round((part.height ?? 64) * (patch.height === undefined ? hint : 1))),
3079
+ scale: hint,
3080
+ rotation: 0,
3081
+ z: drawRankOf(patch.name),
3082
+ matched: false,
3083
+ manual: false
3084
+ };
3085
+ job.layout.items[patch.name] = item;
3086
+ }
3087
+ if (Number.isFinite(patch.x))
3088
+ item.x = Math.round(patch.x);
3089
+ if (Number.isFinite(patch.y))
3090
+ item.y = Math.round(patch.y);
3091
+ if (Number.isFinite(patch.width))
3092
+ item.width = Math.max(1, Math.round(patch.width));
3093
+ if (Number.isFinite(patch.height))
3094
+ item.height = Math.max(1, Math.round(patch.height));
3095
+ if (Number.isFinite(patch.rotation))
3096
+ item.rotation = num(patch.rotation, item.rotation);
3097
+ if (Number.isFinite(patch.z))
3098
+ item.z = Math.round(patch.z);
3099
+ if (patch.placed === false) {
3100
+ item.matched = false;
3101
+ item.manual = true;
3102
+ }
3103
+ else {
3104
+ item.matched = true;
3105
+ item.manual = true;
3106
+ }
3107
+ // 位置由人给了之后,`score` 就不再代表任何东西——它描述的是**自动匹配**的质量。
3108
+ // 留着它的后果是拆件质检会拿一个陈旧分数当"这次装配准不准"的证据
3109
+ // (实测:手工摆对之后质检仍然报"平均相似度 0.326,不可信")。
3110
+ delete item.score;
3111
+ delete item.coverage;
3112
+ // scale 只是自动匹配的副产物,手动改过尺寸之后它就不再代表任何东西;
3113
+ // 仍然按「最终宽度 / 部件原始宽度」回填,导出的 layout.json 才有意义。
3114
+ if (part.width !== undefined && part.width > 0)
3115
+ item.scale = Number((item.width / part.width).toFixed(4));
3116
+ touched++;
3117
+ }
3118
+ // 手动装配会改动骨架上挂点的位置/尺寸,骨骼与图集必须重做——但只标一次。
3119
+ job.layout.approved = false;
3120
+ job.layout.status = "ready";
3121
+ job.layout.error = undefined;
3122
+ job.rig = { status: "empty" };
3123
+ job.atlas = { status: "empty" };
3124
+ appendJobLog(job.log, "info", `手动装配:更新了 ${touched} 个部件`);
3125
+ await writeRigJob(job);
3126
+ await renderLayoutImages(jobId);
3127
+ await writeLayoutJson(jobId);
3128
+ return { touched };
3129
+ }
3130
+ /** 单条改动(界面上的小操作、脚本与测试都用它)。 */
3131
+ export async function saveLayoutItem(jobId, name, patch) {
3132
+ await saveRigLayoutItems(jobId, [{ name, ...patch }]);
3133
+ }
3134
+ /**
3135
+ * 解码缓存。
3136
+ *
3137
+ * 手动装配是交互式的:每落一次位就要重出合成图,而重出图要解码参考图 + 全部部件。
3138
+ * 每次 17 次 ffmpeg 调用(~1.4 秒)在连续微调时是灾难。部件文件在两次装配之间不会变,
3139
+ * 所以按「路径 + mtime + 大小」缓存解码结果。
3140
+ */
3141
+ const decodeCache = new Map();
3142
+ const DECODE_CACHE_LIMIT = 64;
3143
+ async function decodeCached(file, maxEdge = 2048) {
3144
+ let key = file;
3145
+ try {
3146
+ const info = await stat(file);
3147
+ key = `${file}:${info.mtimeMs}:${info.size}`;
3148
+ }
3149
+ catch {
3150
+ /* 取不到 stat 就退化成按路径缓存 */
3151
+ }
3152
+ const hit = decodeCache.get(file);
3153
+ if (hit !== undefined && hit.key === key)
3154
+ return hit.image;
3155
+ const decoded = await decodeToRgba(file, maxEdge);
3156
+ if (decodeCache.size >= DECODE_CACHE_LIMIT) {
3157
+ const oldest = decodeCache.keys().next().value;
3158
+ if (oldest !== undefined)
3159
+ decodeCache.delete(oldest);
3160
+ }
3161
+ decodeCache.set(file, { key, image: decoded });
3162
+ return decoded;
3163
+ }
3164
+ export async function renderLayoutImages(jobId) {
3165
+ const job = await readRigJob(jobId);
3166
+ if (job === undefined)
3167
+ throw new Error(`任务不存在:${jobId}`);
3168
+ if (job.source === undefined)
3169
+ throw new Error("还没有角色参考图");
3170
+ const referenceDecoded = await decodeCached(rigAssetPath(jobId, job.source.file));
3171
+ const reference = { data: referenceDecoded.rgba, width: referenceDecoded.width, height: referenceDecoded.height };
3172
+ const ordered = orderedItems(job);
3173
+ const placed = [];
3174
+ for (const [name, item] of ordered) {
3175
+ const part = job.parts.find((entry) => entry.name === name);
3176
+ if (part?.file === undefined)
3177
+ continue;
3178
+ const decoded = await decodeCached(rigAssetPath(jobId, part.file));
3179
+ const scaled = resizeRgba({ data: decoded.rgba, width: decoded.width, height: decoded.height }, Math.max(1, item.width), Math.max(1, item.height));
3180
+ // 旋转要真的画出来:手动装配里能改旋转,如果合成图忽略它,用户拧了半天看不到变化,
3181
+ // 而导出的骨架也会和看到的不一致。旋转后尺寸会变大,按中心对齐回原来的框。
3182
+ const rotated = Math.abs(item.rotation) < 0.01 ? scaled : rotateRgba(scaled, item.rotation);
3183
+ placed.push({
3184
+ name,
3185
+ x: item.x + (item.width - rotated.width) / 2,
3186
+ y: item.y + (item.height - rotated.height) / 2,
3187
+ width: rotated.width,
3188
+ height: rotated.height,
3189
+ rgba: rotated
3190
+ });
3191
+ }
3192
+ const composite = compositeParts(reference.width, reference.height, placed);
3193
+ const comparison = sideBySide(reference, composite);
3194
+ await mkdir(join(rigJobDir(jobId), "layout"), { recursive: true });
3195
+ await writeFile(rigAssetPath(jobId, "layout/composite.png"), encodePng(composite.data, composite.width, composite.height));
3196
+ await writeFile(rigAssetPath(jobId, "layout/comparison.png"), encodePng(comparison.data, comparison.width, comparison.height));
3197
+ const fresh = await readRigJob(jobId);
3198
+ if (fresh === undefined)
3199
+ return;
3200
+ fresh.layout.composite = "layout/composite.png";
3201
+ fresh.layout.comparison = "layout/comparison.png";
3202
+ await writeRigJob(fresh);
3203
+ }
3204
+ function normalizeHints(value) {
3205
+ if (value === null || typeof value !== "object")
3206
+ return undefined;
3207
+ const out = {};
3208
+ for (const [name, raw] of Object.entries(value)) {
3209
+ const x = num(raw?.x, NaN);
3210
+ const y = num(raw?.y, NaN);
3211
+ const width = num(raw?.width, NaN);
3212
+ const height = num(raw?.height, NaN);
3213
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(width) || !Number.isFinite(height))
3214
+ continue;
3215
+ if (width <= 0 || height <= 0)
3216
+ continue;
3217
+ out[name] = { x, y, width, height };
3218
+ }
3219
+ return Object.keys(out).length === 0 ? undefined : out;
3220
+ }
3221
+ /** 部件是否被用户隐藏。 */
3222
+ function partHidden(job, name) {
3223
+ return job.parts.find((part) => part.name === name)?.hidden === true;
3224
+ }
3225
+ /** 按绘制顺序(z 升序)列出已经摆放好的部件。 */
3226
+ function orderedItems(job) {
3227
+ return Object.entries(job.layout.items)
3228
+ .filter(([name]) => {
3229
+ const part = job.parts.find((entry) => entry.name === name);
3230
+ return part?.status === "ready" && part.hidden !== true;
3231
+ })
3232
+ .sort((a, b) => a[1].z - b[1].z || a[0].localeCompare(b[0]));
3233
+ }
3234
+ /** 导出 layout.json(供外部工具或人工核对)。 */
3235
+ export async function writeLayoutJson(jobId) {
3236
+ const job = await readRigJob(jobId);
3237
+ if (job === undefined)
3238
+ throw new Error(`任务不存在:${jobId}`);
3239
+ const parts = {};
3240
+ for (const [name, item] of Object.entries(job.layout.items)) {
3241
+ parts[name] = {
3242
+ x: item.x,
3243
+ y: item.y,
3244
+ width: item.width,
3245
+ height: item.height,
3246
+ scale: item.scale,
3247
+ rotation: item.rotation,
3248
+ z_index: item.z,
3249
+ score: item.score,
3250
+ coverage: item.coverage,
3251
+ matched: item.matched,
3252
+ manual: item.manual === true
3253
+ };
3254
+ }
3255
+ const payload = {
3256
+ reference_image: job.source?.file ?? null,
3257
+ canvas_width: job.source?.width ?? 0,
3258
+ canvas_height: job.source?.height ?? 0,
3259
+ hint_scale: job.layout.hint ?? null,
3260
+ z_order: orderedItems(job).map(([name]) => name),
3261
+ parts
3262
+ };
3263
+ await writeFile(rigAssetPath(jobId, "layout/layout.json"), `${JSON.stringify(payload, null, 2)}\n`, "utf8");
3264
+ }
3265
+ // ── 阶段③:骨骼与动画 ──────────────────────────────────────────────────
3266
+ export function startRig(jobId) {
3267
+ try {
3268
+ assertIdle(jobId, "rig", "骨骼构建");
3269
+ }
3270
+ catch (error) {
3271
+ return { started: false, reason: messageOf(error) };
3272
+ }
3273
+ const started = kick(jobId, "rig", () => buildRigOutput(jobId));
3274
+ return started ? { started: true } : { started: false, reason: "骨骼构建已在进行中" };
3275
+ }
3276
+ /**
3277
+ * 生成 `skeleton.json` 与自包含预览 `preview.html`。
3278
+ *
3279
+ * 这一步不调任何模型:骨骼位置/朝向由装配结果直接算出来,动画是查表生成的。
3280
+ */
3281
+ export async function buildRigOutput(jobId) {
3282
+ const job = await readRigJob(jobId);
3283
+ if (job === undefined)
3284
+ throw new Error(`任务不存在:${jobId}`);
3285
+ if (job.source === undefined)
3286
+ throw new Error("还没有角色参考图");
3287
+ const ordered = orderedItems(job);
3288
+ if (ordered.length === 0)
3289
+ throw new Error("还没有摆放好的部件,请先在第 ② 步装配定位");
3290
+ job.rig.status = "running";
3291
+ job.rig.error = undefined;
3292
+ await writeRigJob(job);
3293
+ try {
3294
+ // 语义是骨骼推导的输入;到这里还缺就补一次(例如用户全程没打开过语义页)。
3295
+ const filled = ensurePartSemantics(job);
3296
+ if (filled > 0)
3297
+ appendJobLog(job.log, "info", `构建骨骼前补齐了 ${filled} 个部件的语义`);
3298
+ const placedParts = ordered.map(([name, item]) => {
3299
+ const node = job.parts.find((part) => part.name === name);
3300
+ return {
3301
+ name,
3302
+ file: node?.file ?? `parts/${name}.png`,
3303
+ x: item.x,
3304
+ y: item.y,
3305
+ width: item.width,
3306
+ height: item.height,
3307
+ scale: item.scale,
3308
+ rotation: item.rotation,
3309
+ z: item.z,
3310
+ // 语义层的父级与锚点优先;没给时 `buildSkeleton` 会回落到按名字推断。
3311
+ parent: node?.parent,
3312
+ proximal: node?.proximal,
3313
+ distal: node?.distal,
3314
+ // 三通道的中间那一层:人的手工偏置,任何自动重跑都不碰它。
3315
+ offset: job.boneOffsets?.[name]
3316
+ };
3317
+ });
3318
+ const { spine, bones, warnings, animationsRaw } = buildSkeleton({
3319
+ name: job.name,
3320
+ canvasWidth: job.source.width,
3321
+ canvasHeight: job.source.height,
3322
+ parts: placedParts,
3323
+ animationIds: job.settings.animations,
3324
+ animationSettings: job.animationSettings,
3325
+ // 手工编辑过的动画顶掉预设实例。传的是**简写**,转换只发生一次。
3326
+ customAnimations: job.animations,
3327
+ // IK 约束:目标骨不存在时 buildSkeleton 会补一根可拖的点。
3328
+ constraints: job.constraints,
3329
+ // 蒙皮网格:只有列在这里的部件才细分(其余仍走整块贴图渲染)。
3330
+ meshes: job.meshes,
3331
+ // FFD 变形:导出时被采样成 deform/ffd 时间轴(每个动画各一份、首尾闭合)。
3332
+ deforms: job.deforms,
3333
+ // Path 约束:点用参考图像素,由 buildSkeleton 转成骨骼世界坐标。
3334
+ paths: job.paths
3335
+ });
3336
+ // **写盘之前先校验 wire format**。这四条地雷的共同特征是「插件里一路绿灯,
3337
+ // 到引擎里才发现」:`angle` 让骨骼不转、bezier 少几个数让骨架渲染一帧后消失、
3338
+ // 控制点不绝对化让运动突跳。宁可这一步失败,也不要交出一份坏资源。
3339
+ const wireReport = validateSpineWire(spine);
3340
+ const loopReport = validateAnimationLoops(spine,
3341
+ // 手工动画的「是否循环」由数据自己说,不能拿预设当标准:
3342
+ // 用户故意做一台不闭合的「一次性」动作是完全合理的。
3343
+ Object.fromEntries(Object.entries(job.animations ?? {}).map(([id, value]) => [id, value.loop])));
3344
+ if (!wireReport.ok || !loopReport.ok) {
3345
+ const all = [...wireReport.errors, ...loopReport.errors];
3346
+ throw new Error(`skeleton.json 未通过导出前校验(${all.length} 处):` +
3347
+ all.slice(0, 3).map((issue) => `${issue.where} ${issue.message}`).join(";"));
3348
+ }
3349
+ await mkdir(join(rigJobDir(jobId), "rig"), { recursive: true });
3350
+ await writeFile(rigAssetPath(jobId, "rig/skeleton.json"), `${JSON.stringify(spine, null, 2)}\n`, "utf8");
3351
+ // 同一份骨架再出一份 DragonBones 5.5(`_ske.json`)。
3352
+ //
3353
+ // 两条导出路径共用**布局与简写动画**,只在字段名与编码器上分岔——尤其是
3354
+ // curve:Spine 是绝对量、DragonBones 是 0~1 归一化,不能复用同一份已转换
3355
+ // 的结果(见 `rigexport.ts` 的文件头注释)。
3356
+ const dragonBones = buildDragonBonesSkeleton({
3357
+ name: job.name,
3358
+ canvasWidth: job.source.width,
3359
+ canvasHeight: job.source.height,
3360
+ spine,
3361
+ animations: animationsRaw
3362
+ });
3363
+ const dragonBonesReport = validateDragonBones(dragonBones);
3364
+ if (!dragonBonesReport.ok) {
3365
+ throw new Error(`DragonBones 骨架未通过导出前校验(${dragonBonesReport.errors.length} 处):` +
3366
+ dragonBonesReport.errors.slice(0, 3).map((issue) => `${issue.where} ${issue.message}`).join(";"));
3367
+ }
3368
+ await mkdir(join(rigJobDir(jobId), "export/dragonbones"), { recursive: true });
3369
+ const dragonBonesFile = "export/dragonbones/skeleton_ske.json";
3370
+ await writeFile(rigAssetPath(jobId, dragonBonesFile), `${JSON.stringify(dragonBones, null, 2)}\n`, "utf8");
3371
+ // 预览把部件图内联成 data URI:离线打开也能看,不依赖 CDN。
3372
+ const images = [];
3373
+ for (const [name] of ordered) {
3374
+ const part = job.parts.find((entry) => entry.name === name);
3375
+ if (part?.file === undefined)
3376
+ continue;
3377
+ const bytes = await readFile(rigAssetPath(jobId, part.file));
3378
+ images.push({ name, dataUri: `data:${mimeOf(part.file)};base64,${bytes.toString("base64")}` });
3379
+ }
3380
+ const html = buildPreviewHtml({
3381
+ title: `${job.name} · 骨骼动画预览`,
3382
+ spine,
3383
+ images,
3384
+ defaultAnimation: job.settings.animations.includes("idle") ? "idle" : job.settings.animations[0],
3385
+ // FFD 变形参数内联进预览:波形位移要在播放时**逐帧**算,把参数带过去比
3386
+ // 预烘焙一串位移更省体积,也不会在改幅度之后留下一堆过期数据。
3387
+ deforms: job.deforms,
3388
+ // 路径点在这里就转成**骨骼世界坐标**(y 向上):预览既不知道画布尺寸、
3389
+ // 也不知道 toWorld 的约定,让它自己转迟早会转错——而且转错的表现是
3390
+ // 「骨骼排到画面外」,很难联想到是坐标系的事。
3391
+ paths: previewPathsOf(job, spine)
3392
+ });
3393
+ await writeFile(rigAssetPath(jobId, "rig/preview.html"), html, "utf8");
3394
+ const fresh = await readRigJob(jobId);
3395
+ if (fresh === undefined)
3396
+ return;
3397
+ fresh.rig = {
3398
+ status: "ready",
3399
+ approved: false,
3400
+ skeleton: "rig/skeleton.json",
3401
+ preview: "rig/preview.html",
3402
+ bones: bones.length,
3403
+ slots: spine.slots.length,
3404
+ animations: Object.keys(spine.animations),
3405
+ // 几何推导的告警 + 导出校验的提示合并在一起给界面看。
3406
+ warnings: [
3407
+ ...warnings,
3408
+ ...wireReport.warnings.map((issue) => `${issue.where} ${issue.message}`),
3409
+ ...loopReport.warnings.map((issue) => `${issue.where} ${issue.message}`),
3410
+ ...dragonBonesReport.warnings.map((issue) => `${issue.where} ${issue.message}`)
3411
+ ],
3412
+ // 第二条导出路径(同一个 RigDocument 的另一种写法)。
3413
+ dragonBones: { skeleton: dragonBonesFile },
3414
+ // 派生数据:给界面展示「这根骨头现在是什么样、我挪了多少」。
3415
+ boneList: bones.map((bone) => ({
3416
+ name: bone.name,
3417
+ parent: bone.parent,
3418
+ x: bone.x,
3419
+ y: bone.y,
3420
+ rotation: bone.rotation,
3421
+ length: bone.length,
3422
+ offset: job.boneOffsets?.[bone.name]
3423
+ })),
3424
+ updatedAt: Date.now()
3425
+ };
3426
+ fresh.atlas = { status: "empty" };
3427
+ appendJobLog(fresh.log, "info", `骨骼构建完成:${bones.length} 根骨骼 / ${spine.slots.length} 个挂点 / 动画 ${Object.keys(spine.animations).join("、")}` +
3428
+ `;Spine 4.2 校验通过${wireReport.warnings.length > 0 ? `(${wireReport.warnings.length} 条提示)` : ""}`);
3429
+ await writeRigJob(fresh);
3430
+ }
3431
+ catch (error) {
3432
+ const fresh = await readRigJob(jobId);
3433
+ if (fresh === undefined)
3434
+ return;
3435
+ fresh.rig = { ...fresh.rig, status: "error", error: messageOf(error) };
3436
+ appendJobLog(fresh.log, "error", `骨骼构建失败:${messageOf(error)}`);
3437
+ await writeRigJob(fresh);
3438
+ throw error;
3439
+ }
3440
+ }
3441
+ // ── 阶段④:图集 ────────────────────────────────────────────────────────
3442
+ export function startAtlas(jobId) {
3443
+ try {
3444
+ assertIdle(jobId, "atlas", "图集打包");
3445
+ }
3446
+ catch (error) {
3447
+ return { started: false, reason: messageOf(error) };
3448
+ }
3449
+ const started = kick(jobId, "atlas", () => buildAtlas(jobId));
3450
+ return started ? { started: true } : { started: false, reason: "图集打包已在进行中" };
3451
+ }
3452
+ /**
3453
+ * 打包 Spine 纹理图集。
3454
+ *
3455
+ * 部件按**装配后的尺寸**入图,这样 `.atlas` 里的区域尺寸和 `skeleton.json` 里
3456
+ * 挂点的 `width` / `height` 完全一致——导入 Spine 时不会出现「图对不上骨骼」。
3457
+ */
3458
+ export async function buildAtlas(jobId) {
3459
+ const job = await readRigJob(jobId);
3460
+ if (job === undefined)
3461
+ throw new Error(`任务不存在:${jobId}`);
3462
+ const ordered = orderedItems(job);
3463
+ if (ordered.length === 0)
3464
+ throw new Error("还没有摆放好的部件,请先在第 ② 步装配定位");
3465
+ job.atlas.status = "running";
3466
+ job.atlas.error = undefined;
3467
+ await writeRigJob(job);
3468
+ try {
3469
+ const images = [];
3470
+ for (const [name, item] of ordered) {
3471
+ const part = job.parts.find((entry) => entry.name === name);
3472
+ if (part?.file === undefined)
3473
+ continue;
3474
+ const decoded = await decodeToRgba(rigAssetPath(jobId, part.file), 2048);
3475
+ images.push({
3476
+ name,
3477
+ rgba: resizeRgba({ data: decoded.rgba, width: decoded.width, height: decoded.height }, Math.max(1, item.width), Math.max(1, item.height))
3478
+ });
3479
+ }
3480
+ if (images.length === 0)
3481
+ throw new Error("没有可打包的部件");
3482
+ // 裁掉每件的透明边再入图,并把**真实的 orig / offset** 写进 .atlas。
3483
+ // 挂点的 width/height 仍是原尺寸(= orig),所以渲染结果不变——
3484
+ // 参考项目恒写 `orig == size` 且 `offset: 0,0`,等于把透明边一起塞进图集。
3485
+ const packed = packAtlas(images.map((image) => {
3486
+ const bounds = alphaBounds(image.rgba);
3487
+ if (bounds === undefined) {
3488
+ return { name: image.name, width: image.rgba.width, height: image.rgba.height };
3489
+ }
3490
+ return {
3491
+ name: image.name,
3492
+ width: bounds.width,
3493
+ height: bounds.height,
3494
+ origWidth: image.rgba.width,
3495
+ origHeight: image.rgba.height,
3496
+ offsetX: -bounds.x,
3497
+ offsetY: -bounds.y
3498
+ };
3499
+ }), { padding: 2, maxSize: ATLAS_MAX_SIZE, pageName: "skeleton.png" });
3500
+ await mkdir(join(rigJobDir(jobId), "atlas"), { recursive: true });
3501
+ const pageFiles = [];
3502
+ for (const page of packed.pages) {
3503
+ // 页名由 `packAtlas` 统一给(`skeleton.png` / `skeleton2.png`…),
3504
+ // 磁盘文件名与 `.atlas` 第一行严格一致——两边各起一次名字迟早会对不上。
3505
+ const fileName = page.name;
3506
+ const canvas = createRgba(page.width, page.height);
3507
+ for (const placement of page.placements) {
3508
+ const image = images.find((entry) => entry.name === placement.name);
3509
+ if (image === undefined)
3510
+ continue;
3511
+ blitOpaque(canvas, cropRgba(image.rgba, placement), placement.x, placement.y);
3512
+ }
3513
+ await writeFile(rigAssetPath(jobId, `atlas/${fileName}`), encodePng(canvas.data, canvas.width, canvas.height));
3514
+ pageFiles.push(`atlas/${fileName}`);
3515
+ }
3516
+ // 写盘之前先校验:图集对不上骨架的产物是废的,不能交出去。
3517
+ const expectedNames = images.map((image) => image.name);
3518
+ const atlasReport = validateAtlas(packed.pages, { expected: expectedNames, maxSize: ATLAS_MAX_SIZE });
3519
+ if (!atlasReport.ok) {
3520
+ throw new Error(`图集校验失败:${atlasReport.errors.map((issue) => `${issue.where} ${issue.message}`).join(";")}`);
3521
+ }
3522
+ // 骨架若已生成,顺带核对「每个挂点都有对应区域」。
3523
+ if (job.rig.skeleton !== undefined) {
3524
+ try {
3525
+ const spine = JSON.parse(await readFile(rigAssetPath(jobId, job.rig.skeleton), "utf8"));
3526
+ const match = validateSkeletonAtlasMatch(spine, packed.pages);
3527
+ if (!match.ok) {
3528
+ throw new Error(`骨架与图集不一致:${match.errors.map((issue) => `${issue.where} ${issue.message}`).join(";")}`);
3529
+ }
3530
+ }
3531
+ catch (error) {
3532
+ // 骨架文件读不出来不算图集的错,但要说清楚。
3533
+ if (error instanceof Error && error.message.startsWith("骨架与图集不一致"))
3534
+ throw error;
3535
+ appendJobLog(job.log, "warn", `跳过骨架↔图集一致性检查:${messageOf(error)}`);
3536
+ }
3537
+ }
3538
+ await writeFile(rigAssetPath(jobId, "atlas/skeleton.atlas"), buildAtlasText(packed.pages), "utf8");
3539
+ // 同一份图集再出一份 DragonBones 的贴图描述(`_tex.json`,逐页一份)。
3540
+ // 两边必须同源:分开各装一次箱,坐标迟早对不上,而运行时的表现只是「画错位」。
3541
+ const textureFiles = [];
3542
+ for (const page of packed.pages) {
3543
+ const base = page.name.replace(/\.png$/i, "");
3544
+ const texture = buildDragonBonesTexture(page, { imagePath: page.name, name: base });
3545
+ const textureReport = validateDragonBonesTexture(texture);
3546
+ if (!textureReport.ok) {
3547
+ throw new Error(`DragonBones 贴图描述未通过校验:${textureReport.errors.map((issue) => `${issue.where} ${issue.message}`).join(";")}`);
3548
+ }
3549
+ for (const issue of textureReport.warnings) {
3550
+ appendJobLog(job.log, "warn", `DragonBones 贴图提示:${issue.where} ${issue.message}`);
3551
+ }
3552
+ await writeFile(rigAssetPath(jobId, `atlas/${base}_tex.json`), `${JSON.stringify(texture, null, 2)}\n`, "utf8");
3553
+ textureFiles.push(`atlas/${base}_tex.json`);
3554
+ }
3555
+ const fresh = await readRigJob(jobId);
3556
+ if (fresh === undefined)
3557
+ return;
3558
+ const first = packed.pages[0];
3559
+ const regionCount = packed.pages.reduce((sum, page) => sum + page.placements.length, 0);
3560
+ fresh.atlas = {
3561
+ status: "ready",
3562
+ approved: false,
3563
+ image: "atlas/skeleton.png",
3564
+ text: "atlas/skeleton.atlas",
3565
+ width: first.width,
3566
+ height: first.height,
3567
+ regions: regionCount,
3568
+ pages: packed.pages.map((page, index) => ({
3569
+ file: pageFiles[index],
3570
+ width: page.width,
3571
+ height: page.height,
3572
+ regions: page.placements.length
3573
+ })),
3574
+ warnings: atlasReport.warnings.map((issue) => `${issue.where} ${issue.message}`),
3575
+ // DragonBones 侧的派生物:`.atlas` 的孪生兄弟,同一次装箱出来的。
3576
+ dragonBones: { textures: textureFiles },
3577
+ updatedAt: Date.now()
3578
+ };
3579
+ for (const warning of atlasReport.warnings) {
3580
+ appendJobLog(fresh.log, "warn", `图集提示:${warning.where} ${warning.message}`);
3581
+ }
3582
+ const trimmed = packed.pages
3583
+ .flatMap((page) => page.placements)
3584
+ .filter((item) => item.origWidth !== undefined && item.origWidth !== item.width).length;
3585
+ appendJobLog(fresh.log, "info", `图集打包完成:${packed.pages.length} 页,共 ${regionCount} 个区域` +
3586
+ (packed.pages.length > 1 ? `(${packed.pages.map((page) => `${page.width}×${page.height}`).join(" + ")})` : `(${first.width}×${first.height})`) +
3587
+ (trimmed > 0 ? `;${trimmed} 个部件裁掉了透明边` : ""));
3588
+ await writeRigJob(fresh);
3589
+ }
3590
+ catch (error) {
3591
+ const fresh = await readRigJob(jobId);
3592
+ if (fresh === undefined)
3593
+ return;
3594
+ fresh.atlas = { ...fresh.atlas, status: "error", error: messageOf(error) };
3595
+ appendJobLog(fresh.log, "error", `图集打包失败:${messageOf(error)}`);
3596
+ await writeRigJob(fresh);
3597
+ throw error;
3598
+ }
3599
+ }
3600
+ /** 图集里的区域互不重叠,直接整块覆盖写入即可(不走 source-over 混合)。 */
3601
+ function blitOpaque(dst, src, x, y) {
3602
+ for (let row = 0; row < src.height; row++) {
3603
+ const ty = y + row;
3604
+ if (ty < 0 || ty >= dst.height)
3605
+ continue;
3606
+ src.data.copy(dst.data, (ty * dst.width + x) * 4, row * src.width * 4, (row + 1) * src.width * 4);
3607
+ }
3608
+ }
3609
+ /**
3610
+ * 按 placement 的 orig/offset 从原图裁出**要入图的那一块**。
3611
+ *
3612
+ * `offset` 是 Spine 语义(裁剪矩形相对原图左上角的偏移,通常是负数),
3613
+ * 所以原图里的起点是 `-offset`;没写 offset 就是整张。
3614
+ */
3615
+ function cropRgba(src, placement) {
3616
+ const offsetX = placement.offsetX ?? 0;
3617
+ const offsetY = placement.offsetY ?? 0;
3618
+ if (offsetX === 0 && offsetY === 0 && placement.width === src.width && placement.height === src.height)
3619
+ return src;
3620
+ const out = createRgba(placement.width, placement.height);
3621
+ for (let row = 0; row < placement.height; row++) {
3622
+ const sy = -offsetY + row;
3623
+ if (sy < 0 || sy >= src.height)
3624
+ continue;
3625
+ for (let column = 0; column < placement.width; column++) {
3626
+ const sx = -offsetX + column;
3627
+ if (sx < 0 || sx >= src.width)
3628
+ continue;
3629
+ const from = (sy * src.width + sx) * 4;
3630
+ const to = (row * placement.width + column) * 4;
3631
+ out.data[to] = src.data[from];
3632
+ out.data[to + 1] = src.data[from + 1];
3633
+ out.data[to + 2] = src.data[from + 2];
3634
+ out.data[to + 3] = src.data[from + 3];
3635
+ }
3636
+ }
3637
+ return out;
3638
+ }
3639
+ export { RIG_ANIMATIONS, boxMask };