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.
@@ -0,0 +1,802 @@
1
+ /**
2
+ * 骨骼动画产品的**导出前校验**(纯计算,不碰文件系统)。
3
+ *
4
+ * 为什么要有这一层:Spine 4.2 的 wire format 有四个「写错了不报错、只是坏掉」的
5
+ * 陷阱(见 `spine.ts` 的 `convertTimeline` 注释),而图集的错误同样是静默的
6
+ * (区域越界会被 `paste` 悄悄裁掉、`.atlas` 里却仍写完整尺寸)。
7
+ * 这类问题在插件里一路绿灯,一直到**引擎里打开才发现**——那时候排查成本极高。
8
+ *
9
+ * 所以:**产物写盘之前先校验,error 直接让这一步失败**,并且把「哪里错、为什么」
10
+ * 写进任务日志和界面。宁可生成失败,也不要交出一份看起来正常、实际在引擎里坏掉的资源。
11
+ *
12
+ * 判定分两级:
13
+ * - **error**:产物一定是坏的(引擎会画错 / 崩 / 不显示)→ 拒绝导出;
14
+ * - **warning**:能跑但可疑(多余区域、页尺寸不是 2 的幂)→ 照常导出,但要说出来。
15
+ */
16
+ import { RIG_ANIMATIONS, timelinePropertyCount } from "./spine.js";
17
+ function report(errors, warnings) {
18
+ const ok = errors.length === 0;
19
+ const summary = (ok ? "校验通过" : `校验失败:${errors.length} 处错误`) +
20
+ (warnings.length > 0 ? `,另有 ${warnings.length} 条提示` : "");
21
+ return { ok, errors, warnings, summary };
22
+ }
23
+ /** 控制点允许的浮点误差(源码里按 6 位小数 round 过,这里留一点余量)。 */
24
+ const TIME_TOLERANCE = 1e-3;
25
+ /**
26
+ * Spine 4.2 wire format 的四条地雷校验。
27
+ *
28
+ * 参考项目 `spine-animation-ai` 把仓库里同时躺着**对**与**错**的两份 4.2 样例
29
+ * (`examples/sombrero/skeleton.json` 用 `angle` + 4 个数的 translate curve;
30
+ * `examples/sombrero/sombrero.json` 用 `value` + 8 个数),却没有任何测试去断言
31
+ * 它们的差别。这里的每一条都对应一个**具体的坏结果**:
32
+ *
33
+ * 1. `angle` 而不是 `value` → 4.x 运行时把旋转读成 0,**什么都不转**;
34
+ * 2. bezier 长度不等于「属性数 × 4」→ 越界读 undefined → NaN 扩散 →
35
+ * **渲染一帧后整只骨架消失**;
36
+ * 3. 控制点不是绝对量 → 手柄落到自己所在区间之外 → 运动**突跳**而不是缓动;
37
+ * 4. 末帧带 curve → 归属前移一帧之后,末帧那个 curve 永远不会被读到
38
+ * (多半是手写/拼接时漏删的残留,属于「写了但没生效」的隐性错误)。
39
+ */
40
+ export function validateSpineWire(spine) {
41
+ const errors = [];
42
+ const warnings = [];
43
+ // ⓪ 骨骼必须拓扑序(父级排在自己前面),且不能成环。
44
+ //
45
+ // 这一条是**真的漏过**:语义层被手工改成 `hip.parent = torso` 而 `torso.parent = hip`
46
+ // 时,旧的父级解析函数在「断环」之后又兜底挂回 torso,于是产物里 `hip ← torso`
47
+ // 与 `torso ← hip` 同时存在。Spine 那边一路绿灯,是在 DragonBones 的拓扑序校验
48
+ // 里才暴露出来的——同一个 `RigDocument` 的两种写法,校验器不能只拦一边。
49
+ {
50
+ const bones = Array.isArray(spine?.bones) ? spine.bones : [];
51
+ const seen = new Set();
52
+ for (const bone of bones) {
53
+ const name = bone?.name;
54
+ if (typeof name !== "string" || name === "")
55
+ continue;
56
+ if (bone.parent !== undefined && !seen.has(bone.parent)) {
57
+ errors.push({
58
+ level: "error",
59
+ code: "bone-not-topological",
60
+ where: `bones/${name}`,
61
+ message: `父级「${bone.parent}」不存在或排在自己之后(骨骼表必须拓扑序,否则成环的骨架谁先谁后都不对)`
62
+ });
63
+ }
64
+ seen.add(name);
65
+ }
66
+ }
67
+ // ① IK 约束必须自洽。
68
+ //
69
+ // 这几条都不是「能跑但难看」,而是**静默坏掉**:目标骨拼错 → 运行时找不到目标、
70
+ // 约束被整个丢掉;链上有长度为 0 的骨 → 余弦定理分母为 0、`acos` 参数出界,
71
+ // NaN 顺着矩阵扩散、整只骨架渲染一帧后消失;把被约束的骨自己当目标 → 自环。
72
+ {
73
+ const boneNames = new Set((Array.isArray(spine?.bones) ? spine.bones : []).map((bone) => bone?.name).filter((name) => typeof name === "string"));
74
+ const lengthOf = new Map((Array.isArray(spine?.bones) ? spine.bones : []).map((bone) => [bone?.name, numOr(bone?.length, 0)]));
75
+ for (const constraint of Array.isArray(spine?.ik) ? spine.ik : []) {
76
+ const where = `ik/${constraint?.name ?? "?"}`;
77
+ const chain = Array.isArray(constraint?.bones) ? constraint.bones.filter((name) => typeof name === "string") : [];
78
+ if (chain.length < 2) {
79
+ errors.push({ level: "error", code: "ik-chain", where, message: `IK 的骨骼链至少要有两根骨,当前 ${chain.length} 根` });
80
+ continue;
81
+ }
82
+ for (const name of chain) {
83
+ if (!boneNames.has(name)) {
84
+ errors.push({ level: "error", code: "ik-bone", where, message: `IK 链引用了不存在的骨骼「${name}」,运行时这个约束会被丢掉` });
85
+ }
86
+ }
87
+ // 末端骨必须有长度:它定义了「骨尖」这一端,长度为 0 时目标点无处安放。
88
+ const tipLength = lengthOf.get(chain[chain.length - 1]) ?? 0;
89
+ if (tipLength <= 0.01) {
90
+ errors.push({
91
+ level: "error",
92
+ code: "ik-bone-length",
93
+ where,
94
+ message: `IK 链末端「${chain[chain.length - 1]}」长度为 0:骨尖与骨骼原点重合,余弦定理会除以 0`
95
+ });
96
+ }
97
+ if (typeof constraint?.target !== "string" || !boneNames.has(constraint.target)) {
98
+ errors.push({
99
+ level: "error",
100
+ code: "ik-target",
101
+ where,
102
+ message: `IK 的目标骨「${constraint?.target}」不在骨架里,运行时约束会被丢掉(拖动目标点时手不会跟随)`
103
+ });
104
+ }
105
+ else if (chain.includes(constraint.target)) {
106
+ errors.push({ level: "error", code: "ik-self", where, message: "IK 的目标骨不能是被约束链上的骨骼(自环)" });
107
+ }
108
+ const mix = numOr(constraint?.mix, 1);
109
+ if (mix < 0 || mix > 1) {
110
+ errors.push({ level: "error", code: "ik-mix", where, message: `mix(软 IK 权重)必须在 0~1,当前 ${mix}` });
111
+ }
112
+ }
113
+ }
114
+ // ② Path 约束同样必须自洽。「链上骨骼不存在」与「路径点/段长不匹配」都会让运行时
115
+ // 把这个约束整个丢掉,而丢掉是静默的——表现是「加了路径但骨骼没反应」。
116
+ {
117
+ const boneNames = new Set((Array.isArray(spine?.bones) ? spine.bones : []).map((bone) => bone?.name).filter((name) => typeof name === "string"));
118
+ const slotNames = new Set((Array.isArray(spine?.slots) ? spine.slots : []).map((slot) => slot?.name).filter((name) => typeof name === "string"));
119
+ const attachmentOf = (slotName, attName) => {
120
+ const skin = Array.isArray(spine?.skins) ? spine.skins[0] : undefined;
121
+ return skin?.attachments?.[slotName]?.[attName];
122
+ };
123
+ for (const constraint of Array.isArray(spine?.path) ? spine.path : []) {
124
+ const where = `path/${constraint?.name ?? "?"}`;
125
+ const chain = Array.isArray(constraint?.bones) ? constraint.bones.filter((name) => typeof name === "string") : [];
126
+ if (chain.length === 0) {
127
+ errors.push({ level: "error", code: "path-chain", where, message: "Path 约束没有指定骨骼链" });
128
+ }
129
+ for (const name of chain) {
130
+ if (!boneNames.has(name)) {
131
+ errors.push({ level: "error", code: "path-bone", where, message: `Path 链引用了不存在的骨骼「${name}」,运行时这个约束会被丢掉` });
132
+ }
133
+ }
134
+ const target = typeof constraint?.target === "string" ? constraint.target : "";
135
+ if (!boneNames.has(target)) {
136
+ errors.push({ level: "error", code: "path-target", where, message: `Path 的目标骨骼「${target}」不在骨架里` });
137
+ }
138
+ const slotName = `path:${constraint?.name}`;
139
+ const attachment = attachmentOf(slotName, String(constraint?.name));
140
+ if (!slotNames.has(slotName)) {
141
+ errors.push({ level: "error", code: "path-slot", where, message: `缺少路径槽位「${slotName}」,运行时找不到这条路径` });
142
+ }
143
+ else if (attachment === undefined || attachment.type !== "path") {
144
+ errors.push({ level: "error", code: "path-attachment", where, message: `槽位「${slotName}」上没有 path 附件` });
145
+ }
146
+ else {
147
+ const vertices = Array.isArray(attachment.vertices) ? attachment.vertices : [];
148
+ const lengths = Array.isArray(attachment.lengths) ? attachment.lengths : [];
149
+ if (vertices.length < 4) {
150
+ errors.push({ level: "error", code: "path-vertices", where, message: "Path 附件至少要有两个顶点" });
151
+ }
152
+ // 段数 = 点数 − 1(闭合时 = 点数)。`lengths` 与顶点数不匹配时,
153
+ // 运行时按弧长取位置会直接越界。
154
+ const expected = attachment.closed === true ? vertices.length / 2 : vertices.length / 2 - 1;
155
+ if (lengths.length !== expected) {
156
+ errors.push({
157
+ level: "error",
158
+ code: "path-lengths",
159
+ where,
160
+ message: `Path 的 lengths 段数(${lengths.length})与顶点数(${vertices.length / 2})不匹配,应为 ${expected}`
161
+ });
162
+ }
163
+ }
164
+ for (const key of ["translateMix", "rotateMix"]) {
165
+ const value = numOr(constraint?.[key], 1);
166
+ if (value < 0 || value > 1) {
167
+ errors.push({ level: "error", code: "path-mix", where, message: `${key} 必须在 0~1,当前 ${value}` });
168
+ }
169
+ }
170
+ }
171
+ }
172
+ const animations = spine?.animations;
173
+ if (animations === null || typeof animations !== "object") {
174
+ return report(errors, warnings);
175
+ }
176
+ for (const [animationName, animation] of Object.entries(animations)) {
177
+ const boneTracks = animation?.bones;
178
+ if (boneTracks === null || typeof boneTracks !== "object")
179
+ continue;
180
+ for (const [boneName, timelines] of Object.entries(boneTracks)) {
181
+ if (timelines === null || typeof timelines !== "object")
182
+ continue;
183
+ for (const [kind, frames] of Object.entries(timelines)) {
184
+ if (!Array.isArray(frames))
185
+ continue;
186
+ const where = `${animationName}/${boneName}/${kind}`;
187
+ const properties = timelinePropertyCount(kind);
188
+ if (frames.length === 0) {
189
+ warnings.push({ level: "warning", code: "empty-timeline", where, message: "时间轴没有任何关键帧" });
190
+ continue;
191
+ }
192
+ // ① 旋转必须写在 value 下。
193
+ if (kind === "rotate") {
194
+ for (const [index, frame] of frames.entries()) {
195
+ if (frame !== null && typeof frame === "object" && "angle" in frame) {
196
+ errors.push({
197
+ level: "error",
198
+ code: "rotate-angle",
199
+ where: `${where}[${index}]`,
200
+ message: "旋转写在 `angle` 下——4.x 运行时会读成 0,骨骼不会转(必须用 `value`)"
201
+ });
202
+ }
203
+ }
204
+ }
205
+ // 时间必须单调递增,否则后面的区间判断没有意义。
206
+ for (let i = 1; i < frames.length; i++) {
207
+ if (!(frames[i].time > frames[i - 1].time)) {
208
+ errors.push({
209
+ level: "error",
210
+ code: "time-order",
211
+ where: `${where}[${i}]`,
212
+ message: `关键帧时间必须严格递增:${frames[i - 1].time} → ${frames[i].time}`
213
+ });
214
+ }
215
+ }
216
+ for (let i = 0; i < frames.length; i++) {
217
+ const frame = frames[i];
218
+ if (frame === null || typeof frame !== "object")
219
+ continue;
220
+ const isLast = i === frames.length - 1;
221
+ // ④ 末帧不该带 curve。
222
+ if (isLast && frame.curve !== undefined) {
223
+ errors.push({
224
+ level: "error",
225
+ code: "curve-on-last-frame",
226
+ where: `${where}[${i}]`,
227
+ message: "最后一个关键帧不该携带 `curve`:curve 描述的是「从本帧开始」的那一段,末帧没有下一段"
228
+ });
229
+ }
230
+ if (isLast || frame.curve === undefined)
231
+ continue;
232
+ // `stepped` 是合法值。
233
+ if (frame.curve === "stepped")
234
+ continue;
235
+ if (!Array.isArray(frame.curve)) {
236
+ errors.push({
237
+ level: "error",
238
+ code: "curve-shape",
239
+ where: `${where}[${i}]`,
240
+ message: `curve 必须是数组或 "stepped",实际是 ${typeof frame.curve}`
241
+ });
242
+ continue;
243
+ }
244
+ // ② bezier 每个**被动画属性**一份:rotate 4 个,translate/scale/shear 8 个。
245
+ const expected = properties * 4;
246
+ if (properties > 0 && frame.curve.length !== expected) {
247
+ errors.push({
248
+ level: "error",
249
+ code: "curve-length",
250
+ where: `${where}[${i}]`,
251
+ message: `curve 有 ${frame.curve.length} 个数,${kind} 驱动 ${properties} 个属性、需要 ${expected} 个` +
252
+ (properties === 2 && frame.curve.length === 4
253
+ ? "——只给 4 个会让运行时越界读 undefined,NaN 扩散后骨架渲染一帧就消失"
254
+ : "")
255
+ });
256
+ continue;
257
+ }
258
+ // ③ 控制点是绝对量(时间/值空间),必须落在本段之内。
259
+ const start = frames[i].time;
260
+ const end = frames[i + 1]?.time;
261
+ if (typeof start !== "number" || typeof end !== "number")
262
+ continue;
263
+ for (const [offsetLabel, cx] of [
264
+ ["cx1", frame.curve[0]],
265
+ ["cx2", frame.curve[2]]
266
+ ]) {
267
+ if (typeof cx !== "number" || !Number.isFinite(cx)) {
268
+ errors.push({ level: "error", code: "curve-nan", where: `${where}[${i}]`, message: `${offsetLabel} 不是有限数` });
269
+ continue;
270
+ }
271
+ if (cx < start - TIME_TOLERANCE || cx > end + TIME_TOLERANCE) {
272
+ errors.push({
273
+ level: "error",
274
+ code: "curve-not-absolute",
275
+ where: `${where}[${i}]`,
276
+ message: `${offsetLabel}=${cx} 落在本段 [${start}, ${end}] 之外——控制点是绝对量(时间/值空间),不是 0..1 归一化比例`
277
+ });
278
+ }
279
+ }
280
+ }
281
+ }
282
+ }
283
+ }
284
+ return report(errors, warnings);
285
+ }
286
+ // ── 循环接缝 ────────────────────────────────────────────────────────────
287
+ /** 数值比较的容差:预设的数值都按 2 位小数 round 过,这里留一点余量。 */
288
+ const VALUE_TOLERANCE = 0.05;
289
+ /**
290
+ * 循环接缝校验:**首尾闭合的动作,每条轨道的第一帧与最后一帧必须相等**。
291
+ *
292
+ * 参考项目只在 prose 里写了「All loops must return to starting values」
293
+ * (`SKILL.md:1944`),脚本**完全不校验**——于是一个不闭合的循环在引擎里的表现是
294
+ * 「每次循环突然跳一下」,而排查的时候没人会想到去看首末帧。
295
+ *
296
+ * 这是纯本地、免费、可断言的检查,正好适合放在导出前。
297
+ */
298
+ export function validateAnimationLoops(spine, loopOverrides) {
299
+ const errors = [];
300
+ const warnings = [];
301
+ const loopIds = new Set(RIG_ANIMATIONS.filter((item) => item.loop).map((item) => item.id));
302
+ // 手工/AI 编辑过的动画自己声明是否循环:预设的默认值不能覆盖用户的意图,
303
+ // 一台故意不闭合的「一次性」动作不该被判成错误。
304
+ const isLooping = (id) => loopOverrides?.[id] ?? loopIds.has(id);
305
+ const animations = spine?.animations;
306
+ if (animations === null || typeof animations !== "object")
307
+ return report(errors, warnings);
308
+ for (const [animationName, animation] of Object.entries(animations)) {
309
+ if (!isLooping(animationName))
310
+ continue;
311
+ const boneTracks = animation?.bones;
312
+ if (boneTracks === null || typeof boneTracks !== "object")
313
+ continue;
314
+ for (const [boneName, timelines] of Object.entries(boneTracks)) {
315
+ if (timelines === null || typeof timelines !== "object")
316
+ continue;
317
+ for (const [kind, frames] of Object.entries(timelines)) {
318
+ if (!Array.isArray(frames) || frames.length < 2)
319
+ continue;
320
+ const where = `${animationName}/${boneName}/${kind}`;
321
+ const first = frames[0];
322
+ const last = frames[frames.length - 1];
323
+ for (const property of TIMELINE_VALUE_KEYS[kind] ?? []) {
324
+ const a = first?.[property];
325
+ const b = last?.[property];
326
+ if (typeof a !== "number" || typeof b !== "number")
327
+ continue;
328
+ if (Math.abs(a - b) > VALUE_TOLERANCE) {
329
+ errors.push({
330
+ level: "error",
331
+ code: "loop-not-closed",
332
+ where,
333
+ message: `循环首尾不闭合:${property} 从 ${a} 开始、到 ${b} 结束(差 ${(b - a).toFixed(3)})——` +
334
+ "每次循环会在接缝处跳一下"
335
+ });
336
+ }
337
+ }
338
+ }
339
+ }
340
+ }
341
+ return report(errors, warnings);
342
+ }
343
+ /** 每种时间轴在帧上驱动哪些数值字段。 */
344
+ const TIMELINE_VALUE_KEYS = {
345
+ rotate: ["value"],
346
+ translate: ["x", "y"],
347
+ scale: ["x", "y"],
348
+ shear: ["x", "y"]
349
+ };
350
+ function isPow2(value) {
351
+ return value > 0 && (value & (value - 1)) === 0;
352
+ }
353
+ /**
354
+ * 图集校验。
355
+ *
356
+ * 参考项目在这些地方**只打 WARNING 或者什么都不做**:
357
+ * - `generate_spine_player.py` 找不到图集图片只 WARNING,用户只能去浏览器
358
+ * console 里看白屏原因;
359
+ * - `make_atlas.py` 对超宽件没有扩宽分支,`Image.paste` 静默裁切,而
360
+ * `.atlas` 里仍写完整的 `size` → 引擎里画出错位图。
361
+ *
362
+ * 这里一律升级成 **error**:图集与骨架对不上,产物就是废的。
363
+ */
364
+ export function validateAtlas(pages, options = {}) {
365
+ const errors = [];
366
+ const warnings = [];
367
+ const maxSize = options.maxSize ?? 4096;
368
+ if (pages.length === 0) {
369
+ errors.push({ level: "error", code: "atlas-empty", where: "", message: "图集没有任何页" });
370
+ return report(errors, warnings);
371
+ }
372
+ const seen = new Map();
373
+ for (const page of pages) {
374
+ if (page.width <= 0 || page.height <= 0) {
375
+ errors.push({ level: "error", code: "page-size", where: page.name, message: `页尺寸非法:${page.width}×${page.height}` });
376
+ continue;
377
+ }
378
+ if (page.width > maxSize || page.height > maxSize) {
379
+ errors.push({ level: "error", code: "page-too-big", where: page.name, message: `页尺寸 ${page.width}×${page.height} 超过上限 ${maxSize}` });
380
+ }
381
+ if (!isPow2(page.width) || !isPow2(page.height)) {
382
+ warnings.push({ level: "warning", code: "page-not-pow2", where: page.name, message: `页尺寸 ${page.width}×${page.height} 不是 2 的幂,部分引擎会拒绝` });
383
+ }
384
+ if (page.placements.length === 0) {
385
+ warnings.push({ level: "warning", code: "page-empty", where: page.name, message: "这一页没有任何区域" });
386
+ }
387
+ for (const item of page.placements) {
388
+ const where = item.name;
389
+ if (seen.has(item.name)) {
390
+ errors.push({ level: "error", code: "region-duplicate", where, message: `区域名重复(已在 ${seen.get(item.name)} 出现过)` });
391
+ }
392
+ else {
393
+ seen.set(item.name, page.name);
394
+ }
395
+ if (item.width <= 0 || item.height <= 0) {
396
+ errors.push({ level: "error", code: "region-size", where, message: `区域尺寸非法:${item.width}×${item.height}` });
397
+ continue;
398
+ }
399
+ // 越界:参考项目会静默裁切,这里必须拦住。
400
+ if (item.x < 0 || item.y < 0 || item.x + item.width > page.width || item.y + item.height > page.height) {
401
+ errors.push({
402
+ level: "error",
403
+ code: "region-out-of-bounds",
404
+ where,
405
+ message: `区域 [${item.x},${item.y}] ${item.width}×${item.height} 超出页 ${page.width}×${page.height}`
406
+ });
407
+ }
408
+ const origWidth = item.origWidth ?? item.width;
409
+ const origHeight = item.origHeight ?? item.height;
410
+ if (origWidth < item.width || origHeight < item.height) {
411
+ errors.push({
412
+ level: "error",
413
+ code: "orig-smaller-than-size",
414
+ where,
415
+ message: `orig ${origWidth}×${origHeight} 小于 size ${item.width}×${item.height}——裁剪后的区域不可能比原图大`
416
+ });
417
+ }
418
+ const offsetX = item.offsetX ?? 0;
419
+ const offsetY = item.offsetY ?? 0;
420
+ if (offsetX + item.width > origWidth || offsetY + item.height > origHeight) {
421
+ errors.push({
422
+ level: "error",
423
+ code: "offset-out-of-orig",
424
+ where,
425
+ message: `offset (${offsetX},${offsetY}) + size ${item.width}×${item.height} 超出 orig ${origWidth}×${origHeight}`
426
+ });
427
+ }
428
+ }
429
+ }
430
+ if (options.expected !== undefined) {
431
+ const expected = new Set(options.expected);
432
+ const missing = [...expected].filter((name) => !seen.has(name));
433
+ const extra = [...seen.keys()].filter((name) => !expected.has(name));
434
+ if (missing.length > 0) {
435
+ errors.push({
436
+ level: "error",
437
+ code: "region-missing",
438
+ where: missing.slice(0, 6).join("、"),
439
+ message: `${missing.length} 个部件在图集里没有区域:${missing.slice(0, 8).join("、")}`
440
+ });
441
+ }
442
+ if (extra.length > 0) {
443
+ warnings.push({
444
+ level: "warning",
445
+ code: "region-extra",
446
+ where: extra.slice(0, 6).join("、"),
447
+ message: `图集里有 ${extra.length} 个不属于任何部件的区域:${extra.slice(0, 8).join("、")}`
448
+ });
449
+ }
450
+ }
451
+ return report(errors, warnings);
452
+ }
453
+ /**
454
+ * 骨架 ↔ 图集的一致性:每个 slot 引用的 attachment 名都必须能在图集里找到。
455
+ *
456
+ * 这两边是分别生成的,一旦对不上,运行时的表现是「整个部件不显示」——
457
+ * 而不是报错。参考项目在这里只打 WARNING(`find_atlas_images`),
458
+ * 用户只能去浏览器 console 里找原因。
459
+ */
460
+ export function validateSkeletonAtlasMatch(spine, pages) {
461
+ const errors = [];
462
+ const warnings = [];
463
+ const regions = new Set();
464
+ for (const page of pages)
465
+ for (const item of page.placements)
466
+ regions.add(item.name);
467
+ const attachments = spine?.skins?.[0]?.attachments;
468
+ if (attachments === null || typeof attachments !== "object") {
469
+ return report(errors, warnings);
470
+ }
471
+ for (const [slotName, byName] of Object.entries(attachments)) {
472
+ if (byName === null || typeof byName !== "object")
473
+ continue;
474
+ for (const attachmentName of Object.keys(byName)) {
475
+ // **`path` 附件本来就不需要贴图**:它只是一串顶点 + 段长,用来给 Path 约束当轨道。
476
+ // (mesh 需要,因为它是把同一张图按三角形重画。)这一条起初没排除,于是
477
+ // 「加了 Path 约束 → 图集校验报『挂点找不到同名区域』」,而路径其实完全正常。
478
+ if (byName[attachmentName]?.type === "path")
479
+ continue;
480
+ if (regions.has(attachmentName))
481
+ continue;
482
+ errors.push({
483
+ level: "error",
484
+ code: "attachment-missing-region",
485
+ where: `${slotName}/${attachmentName}`,
486
+ message: `挂点在图集里找不到同名区域「${attachmentName}」,运行时会整个部件不显示`
487
+ });
488
+ }
489
+ }
490
+ return report(errors, warnings);
491
+ }
492
+ /** DragonBones 解析器认识的数据版本(`ObjectDataParser.parseDragonBonesData` 的白名单)。 */
493
+ const DRAGONBONES_VERSIONS = new Set(["2.3", "3.0", "4.0", "4.5", "5.0", "5.5", "5.6"]);
494
+ /**
495
+ * DragonBones 5.5 导出物的校验。
496
+ *
497
+ * 与 Spine 那边同样的理由:下面每一条都对应一个**静默坏掉**的结果,
498
+ * 在插件里看不出来,到了引擎里才发现——
499
+ *
500
+ * 1. `version` 不在白名单 → `parseDragonBonesData` 直接 `return null`,
501
+ * 整个骨架加载不出来(而且只打一句 console.assert);
502
+ * 2. 补间帧既没有 `tweenEasing` 也没有 `curve` → 按**阶跃**解释,
503
+ * 动画一跳一跳(`tweenEasing` 缺省是 `-2` 而不是 `0`);
504
+ * 3. `curve` 长度不是 `3n+1`(紧凑)或 `3n+2`(显式)→ 解析器越界读
505
+ * `undefined`,NaN 顺着采样扩散;
506
+ * 4. 中间帧 `duration` 为 0 → `_parseTimeline` 里 `frameCount === 0`
507
+ * 同样走阶跃分支(末帧的 `duration` 本来就被忽略,不在此列);
508
+ * 5. 骨骼父级缺失 / 出现在子级之后 → 骨骼取不到父级矩阵;
509
+ * 6. 槽位或动画引用了不存在的骨骼 → 该槽位被静默丢弃。
510
+ */
511
+ export function validateDragonBones(skeleton) {
512
+ const errors = [];
513
+ const warnings = [];
514
+ if (skeleton === null || typeof skeleton !== "object") {
515
+ errors.push({ level: "error", code: "db-empty", where: "skeleton", message: "DragonBones 骨架为空" });
516
+ return report(errors, warnings);
517
+ }
518
+ const version = skeleton.version;
519
+ if (typeof version !== "string" || !DRAGONBONES_VERSIONS.has(version)) {
520
+ errors.push({
521
+ level: "error",
522
+ code: "db-version",
523
+ where: "version",
524
+ message: `version=${JSON.stringify(version)} 不在 DragonBones 白名单里,运行时会把整份数据判为不支持并返回 null`
525
+ });
526
+ }
527
+ const frameRate = skeleton.frameRate;
528
+ if (typeof frameRate !== "number" || !(frameRate > 0)) {
529
+ errors.push({ level: "error", code: "db-frame-rate", where: "frameRate", message: `frameRate 必须是正数,当前 ${JSON.stringify(frameRate)}` });
530
+ }
531
+ const armatures = Array.isArray(skeleton.armature) ? skeleton.armature : [];
532
+ if (armatures.length === 0) {
533
+ errors.push({ level: "error", code: "db-no-armature", where: "armature", message: "没有任何 armature" });
534
+ return report(errors, warnings);
535
+ }
536
+ for (const armature of armatures) {
537
+ const where0 = `armature/${armature?.name ?? "?"}`;
538
+ const bones = Array.isArray(armature?.bone) ? armature.bone : [];
539
+ const slots = Array.isArray(armature?.slot) ? armature.slot : [];
540
+ const boneNames = new Set();
541
+ const slotNames = new Set();
542
+ // 骨骼:拓扑序(父级必须先出现)。解析器其实允许后补,但依赖它会让
543
+ // 「父级拼错名字」变成静默失败,索性在这里要求严格。
544
+ for (const bone of bones) {
545
+ const name = bone?.name;
546
+ if (typeof name !== "string" || name === "") {
547
+ errors.push({ level: "error", code: "db-bone-name", where: where0, message: "存在没有名字的骨骼" });
548
+ continue;
549
+ }
550
+ if (boneNames.has(name)) {
551
+ errors.push({ level: "error", code: "db-bone-dup", where: `${where0}/${name}`, message: `骨骼名重复:${name}` });
552
+ }
553
+ if (bone.parent !== undefined) {
554
+ if (!boneNames.has(bone.parent)) {
555
+ errors.push({
556
+ level: "error",
557
+ code: "db-bone-parent",
558
+ where: `${where0}/${name}`,
559
+ message: `父级「${bone.parent}」不存在或出现在子级之后,骨骼取不到父级矩阵`
560
+ });
561
+ }
562
+ }
563
+ const transform = bone.transform;
564
+ if (transform === null || typeof transform !== "object") {
565
+ errors.push({ level: "error", code: "db-bone-transform", where: `${where0}/${name}`, message: "骨骼缺少 transform" });
566
+ }
567
+ else if (Math.abs(numOr(transform.skX, 0) - numOr(transform.skY, 0)) > 1e-6) {
568
+ // 允许(解析器支持双角度),但我们自己从不生成——出现即说明有人手改了。
569
+ warnings.push({
570
+ level: "warning",
571
+ code: "db-bone-skew",
572
+ where: `${where0}/${name}`,
573
+ message: `skX(${transform.skX}) 与 skY(${transform.skY}) 不等,会引入斜切`
574
+ });
575
+ }
576
+ boneNames.add(name);
577
+ }
578
+ // 槽位:数组序即 zOrder。
579
+ for (const slot of slots) {
580
+ const name = slot?.name;
581
+ if (typeof name !== "string" || name === "") {
582
+ errors.push({ level: "error", code: "db-slot-name", where: where0, message: "存在没有名字的槽位" });
583
+ continue;
584
+ }
585
+ if (!boneNames.has(slot.parent)) {
586
+ errors.push({
587
+ level: "error",
588
+ code: "db-slot-parent",
589
+ where: `${where0}/${name}`,
590
+ message: `槽位挂在骨骼「${slot.parent}」上,但这根骨骼不存在(运行时该槽位会被丢掉)`
591
+ });
592
+ }
593
+ slotNames.add(name);
594
+ }
595
+ // 皮肤:槽位名要在 armature 里存在,图片挂点要有名字。
596
+ for (const skin of Array.isArray(armature?.skin) ? armature.skin : []) {
597
+ for (const skinSlot of Array.isArray(skin?.slot) ? skin.slot : []) {
598
+ const name = skinSlot?.name;
599
+ if (!slotNames.has(name)) {
600
+ errors.push({
601
+ level: "error",
602
+ code: "db-skin-slot",
603
+ where: `${where0}/${skin?.name ?? "default"}/${name}`,
604
+ message: `皮肤引用了不存在的槽位「${name}」`
605
+ });
606
+ }
607
+ const displays = Array.isArray(skinSlot?.display) ? skinSlot.display : [];
608
+ if (displays.length === 0) {
609
+ warnings.push({ level: "warning", code: "db-skin-empty", where: `${where0}/${name}`, message: "槽位没有任何 display,运行时会不显示" });
610
+ }
611
+ for (const display of displays) {
612
+ if (display?.type !== undefined && display.type !== "image")
613
+ continue;
614
+ if (typeof display?.path !== "string" || display.path === "") {
615
+ errors.push({
616
+ level: "error",
617
+ code: "db-display-path",
618
+ where: `${where0}/${name}`,
619
+ message: "图片挂点缺少 path,运行时按名字去图集里取不到贴图"
620
+ });
621
+ }
622
+ const pivot = display?.pivot;
623
+ if (pivot === undefined || typeof pivot?.x !== "number" || typeof pivot?.y !== "number") {
624
+ errors.push({
625
+ level: "error",
626
+ code: "db-display-pivot",
627
+ where: `${where0}/${name}`,
628
+ message: "图片挂点缺少 pivot(缺省 0.5/0.5 虽然能跑,但裁剪过的部件会偏)"
629
+ });
630
+ }
631
+ }
632
+ }
633
+ }
634
+ // 动画:时长是**帧数**;补间帧必须显式声明缓动;持续 0 的中间帧会变阶跃。
635
+ for (const animation of Array.isArray(armature?.animation) ? armature.animation : []) {
636
+ const animWhere = `${where0}/animation/${animation?.name ?? "?"}`;
637
+ const duration = animation?.duration;
638
+ if (typeof duration !== "number" || !Number.isInteger(duration) || duration <= 0) {
639
+ errors.push({
640
+ level: "error",
641
+ code: "db-duration",
642
+ where: animWhere,
643
+ message: `duration 必须是正整数帧数(Spine 那边是秒,这里是帧),当前 ${JSON.stringify(duration)}`
644
+ });
645
+ }
646
+ for (const timeline of Array.isArray(animation?.bone) ? animation.bone : []) {
647
+ const boneName = timeline?.name;
648
+ if (!boneNames.has(boneName)) {
649
+ errors.push({
650
+ level: "error",
651
+ code: "db-anim-bone",
652
+ where: `${animWhere}/${boneName}`,
653
+ message: `动画引用了不存在的骨骼「${boneName}」`
654
+ });
655
+ }
656
+ for (const [key, kind] of [
657
+ ["rotateFrame", "rotate"],
658
+ ["translateFrame", "translate"],
659
+ ["scaleFrame", "scale"]
660
+ ]) {
661
+ const frames = timeline?.[key];
662
+ if (frames === undefined)
663
+ continue;
664
+ if (!Array.isArray(frames) || frames.length === 0) {
665
+ errors.push({ level: "error", code: "db-frames-empty", where: `${animWhere}/${boneName}/${kind}`, message: "帧数组为空" });
666
+ continue;
667
+ }
668
+ for (let i = 0; i < frames.length; i++) {
669
+ const frame = frames[i];
670
+ const frameWhere = `${animWhere}/${boneName}/${kind}[${i}]`;
671
+ const isLast = i === frames.length - 1;
672
+ const frameDuration = numOr(frame?.duration, -1);
673
+ if (!Number.isInteger(frameDuration) || frameDuration < 0) {
674
+ errors.push({ level: "error", code: "db-frame-duration", where: frameWhere, message: `duration 必须是非负整数帧数,当前 ${JSON.stringify(frame?.duration)}` });
675
+ }
676
+ else if (!isLast && frameDuration === 0) {
677
+ errors.push({
678
+ level: "error",
679
+ code: "db-frame-step",
680
+ where: frameWhere,
681
+ message: "中间帧的 duration 为 0 会被解析成阶跃(末帧的 duration 本来就被忽略,只有中间帧要求 ≥ 1)"
682
+ });
683
+ }
684
+ if (isLast)
685
+ continue;
686
+ if (frame?.curve === undefined && frame?.tweenEasing === undefined) {
687
+ errors.push({
688
+ level: "error",
689
+ code: "db-frame-easing",
690
+ where: frameWhere,
691
+ message: "补间帧既没有 tweenEasing 也没有 curve;缺省是 -2(阶跃),动画会一跳一跳"
692
+ });
693
+ continue;
694
+ }
695
+ if (frame.curve !== undefined) {
696
+ const length = Array.isArray(frame.curve) ? frame.curve.length : -1;
697
+ if (length < 0 || (length % 3 !== 1 && length % 3 !== 2)) {
698
+ errors.push({
699
+ level: "error",
700
+ code: "db-curve-length",
701
+ where: frameWhere,
702
+ message: `curve 长度 ${length} 非法:紧凑式要 3n+1、显式锚点式要 3n+2,否则解析器越界读到 undefined`
703
+ });
704
+ }
705
+ }
706
+ }
707
+ // 帧位置要严格递增(前 n-1 帧的 duration 之和 == animation.duration)。
708
+ let total = 0;
709
+ for (let i = 0; i < frames.length - 1; i++)
710
+ total += numOr(frames[i]?.duration, 0);
711
+ if (typeof duration === "number" && total !== duration) {
712
+ warnings.push({
713
+ level: "warning",
714
+ code: "db-frame-span",
715
+ where: `${animWhere}/${boneName}/${kind}`,
716
+ message: `关键帧总长 ${total} 帧与动画时长 ${duration} 帧不一致`
717
+ });
718
+ }
719
+ }
720
+ }
721
+ }
722
+ }
723
+ return report(errors, warnings);
724
+ }
725
+ function numOr(value, fallback) {
726
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
727
+ }
728
+ /**
729
+ * `_tex.json` 的校验:区域必须落在图集内,`frame*` 要么一起给、要么都不给。
730
+ *
731
+ * `frameX/frameY/frameWidth/frameHeight` 是「原图(未裁剪)尺寸 + 裁剪偏移」,
732
+ * 运行时用 `pivot.x * frameWidth + frameX` 算挂点位置(`Slot.ts:427-433`)。
733
+ * 只给一半的话,挂点会按「没裁过」算,裁掉透明边的部件整体偏掉。
734
+ */
735
+ export function validateDragonBonesTexture(texture) {
736
+ const errors = [];
737
+ const warnings = [];
738
+ const width = numOr(texture?.width, 0);
739
+ const height = numOr(texture?.height, 0);
740
+ if (!(width > 0) || !(height > 0)) {
741
+ errors.push({ level: "error", code: "db-tex-size", where: "texture", message: `图集尺寸非法:${width}×${height}` });
742
+ return report(errors, warnings);
743
+ }
744
+ if (typeof texture?.imagePath !== "string" || texture.imagePath === "") {
745
+ errors.push({ level: "error", code: "db-tex-image", where: "texture", message: "缺少 imagePath,运行时找不到 png" });
746
+ }
747
+ const subTextures = texture?.SubTexture;
748
+ if (!Array.isArray(subTextures) || subTextures.length === 0) {
749
+ errors.push({ level: "error", code: "db-tex-empty", where: "SubTexture", message: "SubTexture 为空" });
750
+ return report(errors, warnings);
751
+ }
752
+ const seen = new Set();
753
+ for (const item of subTextures) {
754
+ const where = String(item?.name ?? "?");
755
+ if (typeof item?.name !== "string" || item.name === "") {
756
+ errors.push({ level: "error", code: "db-tex-name", where: "SubTexture", message: "存在没有名字的区域" });
757
+ continue;
758
+ }
759
+ if (seen.has(item.name)) {
760
+ errors.push({ level: "error", code: "db-tex-dup", where, message: "区域名重复" });
761
+ }
762
+ seen.add(item.name);
763
+ const x = numOr(item.x, 0);
764
+ const y = numOr(item.y, 0);
765
+ const w = numOr(item.width, 0);
766
+ const h = numOr(item.height, 0);
767
+ if (!(w > 0) || !(h > 0)) {
768
+ errors.push({ level: "error", code: "db-tex-region", where, message: `区域尺寸非法:${w}×${h}` });
769
+ }
770
+ else if (x < 0 || y < 0 || x + w > width || y + h > height) {
771
+ errors.push({
772
+ level: "error",
773
+ code: "db-tex-outside",
774
+ where,
775
+ message: `区域 ${x},${y} ${w}×${h} 超出图集 ${width}×${height}`
776
+ });
777
+ }
778
+ const frameKeys = ["frameX", "frameY", "frameWidth", "frameHeight"];
779
+ const given = frameKeys.filter((key) => item[key] !== undefined);
780
+ if (given.length !== 0 && given.length !== 4) {
781
+ errors.push({
782
+ level: "error",
783
+ code: "db-tex-frame",
784
+ where,
785
+ message: `裁剪信息要给全(${frameKeys.join("/")}),当前只给了 ${given.join("、")}——挂点会按「没裁过」算,部件整体偏掉`
786
+ });
787
+ }
788
+ else if (given.length === 4) {
789
+ const frameWidth = numOr(item.frameWidth, 0);
790
+ const frameHeight = numOr(item.frameHeight, 0);
791
+ if (frameWidth < w || frameHeight < h) {
792
+ errors.push({
793
+ level: "error",
794
+ code: "db-tex-frame-size",
795
+ where,
796
+ message: `frameWidth/frameHeight(${frameWidth}×${frameHeight})不能小于区域尺寸(${w}×${h})`
797
+ });
798
+ }
799
+ }
800
+ }
801
+ return report(errors, warnings);
802
+ }