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,411 @@
1
+ /**
2
+ * 骨骼动画的**部件语义层**(纯计算,不碰文件系统)。
3
+ *
4
+ * v1 把「第几个格子 = 哪个部件」当成确定事实:分割时按网格给名字,装配按名字查
5
+ * 固定表推父级与锚点(`spine.ts` 的 `RIG_SLOTS`)。规则简单、可复现,但有两个代价:
6
+ *
7
+ * 1. 生图模型一不按网格摆,整条链就失效,只能告警 + 让用户重新生成
8
+ * (见 `riggen.ts` 的 `missing >= 40%` 分支);
9
+ * 2. 非标准角色(兽耳、尾巴、裙摆、武器、多肢体)没有任何表达位置——表外的名字
10
+ * 只能靠关键词瞎猜宿主(`parentBoneOf`)。
11
+ *
12
+ * 所以 v2 把「语义」从**隐含的网格约定**提成**显式数据**:每个部件带一组
13
+ * `{role, parent, proximal, distal, tags}`,它既是装配与骨骼推导的输入,
14
+ * 也是 AI 可以提案、人可以修改、脚本可以校验的对象。
15
+ *
16
+ * 这一层的设计原则:
17
+ * - **纯函数、无 I/O**:方便单测,也方便被宿主与客户端同时使用;
18
+ * - **校验失败不抛异常,而是返回诊断**:UI 需要把「哪一条不合法、为什么」
19
+ * 展示给用户,而不是让整个保存动作失败;
20
+ * - **可降级**:没给语义时,用默认人形表 + 关键词启发式补齐,
21
+ * 所以 v1 的历史任务与「直接上传部件 PNG」的路径都不需要用户先填表。
22
+ */
23
+ // ── 语义角色 ────────────────────────────────────────────────────────────
24
+ /**
25
+ * 角色枚举。刻意比「部位名」宽一档:`accessory` / `prop` / `weapon` / `hair` /
26
+ * `cloth` 这类没有固定解剖位置的部件,靠 `parent` 决定挂在谁身上。
27
+ */
28
+ export const RIG_ROLES = [
29
+ "head",
30
+ "neck",
31
+ "torso",
32
+ "hip",
33
+ "upperArm",
34
+ "lowerArm",
35
+ "hand",
36
+ "upperLeg",
37
+ "lowerLeg",
38
+ "foot",
39
+ "hair",
40
+ "cloth",
41
+ "accessory",
42
+ "weapon"
43
+ ];
44
+ const ROLE_SET = new Set(RIG_ROLES);
45
+ export function isRigRole(value) {
46
+ return typeof value === "string" && ROLE_SET.has(value);
47
+ }
48
+ /** 角色的中文名,界面与验收包都用它。 */
49
+ export const ROLE_LABELS = {
50
+ head: "头部",
51
+ neck: "脖子",
52
+ torso: "躯干",
53
+ hip: "胯部",
54
+ upperArm: "上臂",
55
+ lowerArm: "小臂",
56
+ hand: "手",
57
+ upperLeg: "大腿",
58
+ lowerLeg: "小腿",
59
+ foot: "脚",
60
+ hair: "头发",
61
+ cloth: "衣料",
62
+ accessory: "配饰",
63
+ weapon: "武器"
64
+ };
65
+ /**
66
+ * 角色的**英文名词**,给生图提示词用。
67
+ *
68
+ * 为什么需要它:给模型的提示词里必须有一个**具体的主语**。实测过一次很有代表性
69
+ * 的失败——提示词里最具体的一句是「flat clean background of a single solid colour」,
70
+ * 于是模型就真的交回一张纯色图(补边是白底就返回白、改灰底就返回灰)。
71
+ * 说清「这是一只手」比反复强调整体约束有用得多,而这个信息语义层本来就有。
72
+ */
73
+ export const ROLE_NOUNS = {
74
+ head: "head",
75
+ neck: "neck",
76
+ torso: "torso",
77
+ hip: "hip / pelvis",
78
+ upperArm: "upper arm",
79
+ lowerArm: "lower arm (forearm)",
80
+ hand: "hand",
81
+ upperLeg: "upper leg (thigh)",
82
+ lowerLeg: "lower leg (shin)",
83
+ foot: "foot",
84
+ hair: "lock of hair",
85
+ cloth: "piece of clothing",
86
+ accessory: "accessory",
87
+ weapon: "weapon"
88
+ };
89
+ /**
90
+ * 每个角色的**默认锚点**(归一化到部件包围盒,x 向右、y **向下**)。
91
+ *
92
+ * 语义:`proximal` 是「近端」——骨骼的原点落在这里,也是它绕着自己转的那一点;
93
+ * `distal` 是「远端」,骨骼朝向 = 近端 → 远端。
94
+ * 四肢取「上端为近端」(上臂的肩、大腿的胯),躯干链取「下端为近端」(头挂在脖子上)。
95
+ */
96
+ export const ROLE_ANCHORS = {
97
+ head: { proximal: [0.5, 1], distal: [0.5, 0] },
98
+ neck: { proximal: [0.5, 1], distal: [0.5, 0] },
99
+ torso: { proximal: [0.5, 1], distal: [0.5, 0] },
100
+ hip: { proximal: [0.5, 1], distal: [0.5, 0] },
101
+ upperArm: { proximal: [0.5, 0], distal: [0.5, 1] },
102
+ lowerArm: { proximal: [0.5, 0], distal: [0.5, 1] },
103
+ hand: { proximal: [0.5, 0], distal: [0.5, 1] },
104
+ upperLeg: { proximal: [0.5, 0], distal: [0.5, 1] },
105
+ lowerLeg: { proximal: [0.5, 0], distal: [0.5, 1] },
106
+ foot: { proximal: [0.5, 0], distal: [0.5, 1] },
107
+ // 头发/衣料通常从根部往下(或往后)延伸;配饰与武器整体朝上,绕底边中点转。
108
+ hair: { proximal: [0.5, 0], distal: [0.5, 1] },
109
+ cloth: { proximal: [0.5, 0], distal: [0.5, 1] },
110
+ accessory: { proximal: [0.5, 1], distal: [0.5, 0] },
111
+ weapon: { proximal: [0.5, 1], distal: [0.5, 0] }
112
+ };
113
+ /**
114
+ * 每个角色的**默认父级角色**(不是骨骼名——骨骼名要等具体部件名确定后才知道)。
115
+ * `undefined` 表示直接挂在 root 下。
116
+ */
117
+ export const ROLE_PARENT_ROLE = {
118
+ head: "neck",
119
+ neck: "torso",
120
+ torso: "hip",
121
+ hip: undefined,
122
+ upperArm: "torso",
123
+ lowerArm: "upperArm",
124
+ hand: "lowerArm",
125
+ upperLeg: "hip",
126
+ lowerLeg: "upperLeg",
127
+ foot: "lowerLeg",
128
+ hair: "head",
129
+ cloth: "torso",
130
+ accessory: "torso",
131
+ weapon: "torso"
132
+ };
133
+ export function isFinitePair(value) {
134
+ return (Array.isArray(value) &&
135
+ value.length === 2 &&
136
+ Number.isFinite(value[0]) &&
137
+ Number.isFinite(value[1]));
138
+ }
139
+ function clamp01(value) {
140
+ return Math.min(1, Math.max(0, value));
141
+ }
142
+ function normalizePair(value, fallback) {
143
+ if (!isFinitePair(value))
144
+ return [fallback[0], fallback[1]];
145
+ return [clamp01(Number(value[0])), clamp01(Number(value[1]))];
146
+ }
147
+ // ── 从部件名推断语义(兜底路径)────────────────────────────────────────
148
+ /**
149
+ * 关键词 → 角色。用于两条路径:
150
+ * ① v1 历史任务的迁移(只有名字,没有语义);
151
+ * ② 用户直接上传部件 PNG(文件名即部件名)。
152
+ *
153
+ * 顺序很重要:先匹配更具体的词(`forearm` 先于 `arm`),否则「左小臂」会被
154
+ * 「上臂」的规则抢走。
155
+ */
156
+ const ROLE_KEYWORDS = [
157
+ ["lowerArm", ["lower-arm", "lowerarm", "forearm", "小臂", "前臂"]],
158
+ ["upperArm", ["upper-arm", "upperarm", "上臂", "大臂"]],
159
+ ["lowerLeg", ["lower-leg", "lowerleg", "calf", "shin", "小腿"]],
160
+ ["upperLeg", ["upper-leg", "upperleg", "thigh", "大腿"]],
161
+ ["hand", ["hand", "wrist", "手"]],
162
+ ["foot", ["foot", "feet", "ankle", "脚", "足"]],
163
+ ["head", ["head", "face", "头", "脸"]],
164
+ ["neck", ["neck", "脖", "颈"]],
165
+ ["torso", ["torso", "chest", "body", "trunk", "躯干", "身体", "胸"]],
166
+ ["hip", ["hip", "pelvis", "waist", "胯", "臀", "腰"]],
167
+ ["hair", ["hair", "ponytail", "bangs", "发", "辫"]],
168
+ ["weapon", ["weapon", "sword", "blade", "bow", "gun", "staff", "wand", "刀", "剑", "弓", "杖", "枪"]],
169
+ ["cloth", ["skirt", "cape", "cloak", "sleeve", "dress", "coat", "裙", "披风", "袖", "衣"]],
170
+ ["accessory", ["hat", "cap", "helmet", "horn", "ear", "eye", "tail", "wing", "belt", "scarf", "帽", "盔", "角", "耳", "眼", "尾", "翅", "带", "围巾", "饰"]]
171
+ ];
172
+ /** 从部件名猜角色。猜不到就是 `accessory`——比瞎猜成某个解剖部位安全。 */
173
+ export function roleOfName(name) {
174
+ const lower = name.toLowerCase();
175
+ for (const [role, keys] of ROLE_KEYWORDS) {
176
+ if (keys.some((key) => lower.includes(key)))
177
+ return role;
178
+ }
179
+ return "accessory";
180
+ }
181
+ /**
182
+ * 从「部件名 → 角色」的映射推出父级**部件名**。
183
+ *
184
+ * 与 v1 的 `parentBoneOf`(`spine.ts`)的区别:v1 是「按名字猜父级名字」,
185
+ * 这里多一层「角色 → 角色」的映射,因此能正确处理 `left-lower-arm` 这种
186
+ * 名字里既有 `left` 又有 `arm` 的情况,也能让用户改角色后自动重算父级。
187
+ *
188
+ * **理想父级角色不存在时会沿角色链向上退**:例如「裙摆」的理想父级是躯干,
189
+ * 但一个只有「头 + 裙摆 + 胯」的集合里没有躯干,此时退到胯(`torso → hip`)。
190
+ * 这条兜底是必要的——v1 的注释就写过「猜不到就挂到躯干上,总比散落一地强」;
191
+ * 没有它,任何理想父级缺席的部件都会掉到 root,看起来就是「飘着」。
192
+ *
193
+ * 返回 `undefined` 表示挂 root(整条角色链都不存在)。
194
+ */
195
+ export function parentNameOf(name, roleByName) {
196
+ const role = roleByName.get(name) ?? roleOfName(name);
197
+ const side = sideOfName(name);
198
+ // 沿「角色 → 它的父角色」向上找第一个真实存在的角色。
199
+ // `visited` 只是为了防御性 —— ROLE_PARENT_ROLE 本身是无环的。
200
+ const visited = new Set();
201
+ let parentRole = ROLE_PARENT_ROLE[role];
202
+ while (parentRole !== undefined && !visited.has(parentRole)) {
203
+ visited.add(parentRole);
204
+ const candidates = [...roleByName.entries()].filter(([other, otherRole]) => other !== name && otherRole === parentRole);
205
+ if (candidates.length > 0) {
206
+ // 优先同侧:左小臂的父级应该是左上臂,不是右上臂。
207
+ if (candidates.length === 1)
208
+ return candidates[0][0];
209
+ if (side !== "") {
210
+ const sameSide = candidates.find(([other]) => sideOfName(other) === side);
211
+ if (sameSide !== undefined)
212
+ return sameSide[0];
213
+ }
214
+ // 同侧也分不出来时按名字排序取第一个,保证结果确定(同样的输入永远同样的输出)。
215
+ return candidates.map(([other]) => other).sort()[0];
216
+ }
217
+ parentRole = ROLE_PARENT_ROLE[parentRole];
218
+ }
219
+ return undefined;
220
+ }
221
+ /** 从部件名抽出左右侧;没有侧别信息返回空串。 */
222
+ export function sideOfName(name) {
223
+ const lower = name.toLowerCase();
224
+ if (lower.includes("left") || name.includes("左"))
225
+ return "left";
226
+ if (lower.includes("right") || name.includes("右"))
227
+ return "right";
228
+ return "";
229
+ }
230
+ /**
231
+ * 给一批部件名生成**默认语义**(角色、父级、锚点、标签)。
232
+ *
233
+ * 这是「不填表也能跑」的保证:AI 不需要出手、用户不需要动手,也能得到一份
234
+ * 结构上说得通的语义表;AI 或人之后只需要改**不对的那几条**。
235
+ */
236
+ export function defaultSemanticsOf(names) {
237
+ const roleByName = new Map();
238
+ for (const name of names)
239
+ roleByName.set(name, roleOfName(name));
240
+ return names.map((name) => {
241
+ const role = roleByName.get(name);
242
+ const anchors = ROLE_ANCHORS[role];
243
+ const tags = new Set([role]);
244
+ const side = sideOfName(name);
245
+ if (side !== "")
246
+ tags.add(side);
247
+ return {
248
+ name,
249
+ role,
250
+ parent: parentNameOf(name, roleByName),
251
+ proximal: [anchors.proximal[0], anchors.proximal[1]],
252
+ distal: [anchors.distal[0], anchors.distal[1]],
253
+ tags: [...tags],
254
+ source: "default"
255
+ };
256
+ });
257
+ }
258
+ /**
259
+ * 校验并归一化一份语义表。
260
+ *
261
+ * **永远返回可用的 `parts`**:把非法字段就地修成安全值并记一条 issue,
262
+ * 而不是整体拒绝。理由是这一层的用户是「正在用界面调参数的人」——
263
+ * 他要看到的是「哪个部件、哪个字段、为什么不合法」,而不是一个保存失败的红点。
264
+ *
265
+ * error 与 warning 的分界:
266
+ * - **error**:会让下游(骨骼推导 / 导出)产生**错误结果**的问题,
267
+ * 例如父级成环、父级不存在、角色未知;
268
+ * - **warning**:能跑但很可能不符合预期,例如锚点退化(近端 = 远端,
269
+ * 骨骼长度为 0)、左右镜像缺失、人形结构可疑。
270
+ */
271
+ export function validateSemantics(input, options = {}) {
272
+ const errors = [];
273
+ const warnings = [];
274
+ // ① 名字唯一且非空。
275
+ const seen = new Set();
276
+ const unique = [];
277
+ for (const raw of input) {
278
+ const name = typeof raw.name === "string" ? raw.name.trim() : "";
279
+ if (name === "") {
280
+ errors.push({ name: "", level: "error", message: "存在没有名字的部件" });
281
+ continue;
282
+ }
283
+ if (seen.has(name)) {
284
+ errors.push({ name, level: "error", message: `部件名重复:${name}` });
285
+ continue;
286
+ }
287
+ seen.add(name);
288
+ unique.push({ ...raw, name });
289
+ }
290
+ const nameSet = new Set(unique.map((item) => item.name));
291
+ // ② 角色与锚点。
292
+ const parts = unique.map((raw) => {
293
+ let role;
294
+ if (isRigRole(raw.role)) {
295
+ role = raw.role;
296
+ }
297
+ else {
298
+ role = roleOfName(raw.name);
299
+ if (raw.role !== undefined) {
300
+ errors.push({ name: raw.name, level: "error", message: `未知的角色「${String(raw.role)}」,已按名字推断为「${role}」` });
301
+ }
302
+ }
303
+ const fallback = ROLE_ANCHORS[role];
304
+ const proximal = normalizePair(raw.proximal, fallback.proximal);
305
+ const distal = normalizePair(raw.distal, fallback.distal);
306
+ // 锚点退化会让骨骼长度为 0,方向也失去意义——自动推开一点点并告警。
307
+ if (Math.abs(proximal[0] - distal[0]) < 1e-6 && Math.abs(proximal[1] - distal[1]) < 1e-6) {
308
+ warnings.push({ name: raw.name, level: "warning", message: "近端与远端锚点重合,骨骼长度为 0;已按角色默认锚点纠正" });
309
+ proximal[0] = fallback.proximal[0];
310
+ proximal[1] = fallback.proximal[1];
311
+ distal[0] = fallback.distal[0];
312
+ distal[1] = fallback.distal[1];
313
+ }
314
+ const tags = Array.isArray(raw.tags)
315
+ ? [...new Set(raw.tags.filter((tag) => typeof tag === "string" && tag.trim() !== "").map((tag) => tag.trim()))]
316
+ : [];
317
+ const source = raw.source === "ai" || raw.source === "human" ? raw.source : "default";
318
+ return { name: raw.name, role, parent: typeof raw.parent === "string" && raw.parent.trim() !== "" ? raw.parent.trim() : undefined, proximal, distal, tags, source };
319
+ });
320
+ // ③ 父级存在性与自环。
321
+ for (const part of parts) {
322
+ if (part.parent === undefined)
323
+ continue;
324
+ if (part.parent === part.name) {
325
+ errors.push({ name: part.name, level: "error", message: "父级指向自己" });
326
+ part.parent = undefined;
327
+ continue;
328
+ }
329
+ if (!nameSet.has(part.parent)) {
330
+ errors.push({ name: part.name, level: "error", message: `父级「${part.parent}」不存在` });
331
+ part.parent = undefined;
332
+ }
333
+ }
334
+ // ④ 成环检测:沿 parent 链走,走到自己就是环。
335
+ // 成环的骨骼表在渲染时会无限递归,必须在写入前拦住(v1 只在推导时兜底)。
336
+ const byName = new Map(parts.map((part) => [part.name, part]));
337
+ for (const part of parts) {
338
+ const path = new Set([part.name]);
339
+ let cursor = part.parent;
340
+ while (cursor !== undefined) {
341
+ if (path.has(cursor)) {
342
+ errors.push({ name: part.name, level: "error", message: `父级链成环:${[...path].join(" → ")} → ${cursor};已改挂 root` });
343
+ part.parent = undefined;
344
+ break;
345
+ }
346
+ path.add(cursor);
347
+ cursor = byName.get(cursor)?.parent;
348
+ }
349
+ }
350
+ // ⑤ 人形结构自洽:只有在「看起来是人形」时才检查,否则会误伤四足/机械角色。
351
+ const humanoid = options.humanoid ?? parts.some((part) => part.role === "head");
352
+ if (humanoid) {
353
+ const has = (role) => parts.some((part) => part.role === role);
354
+ if (!has("head"))
355
+ warnings.push({ name: "", level: "warning", message: "判定为人形,但没有角色为「头部」的部件" });
356
+ if (!has("torso") && !has("hip"))
357
+ warnings.push({ name: "", level: "warning", message: "判定为人形,但没有躯干或胯部,骨骼会以 root 为中心" });
358
+ // 头的祖先链**不能经过肢体**——「头挂在腿上」是最典型的语义/装配错误,
359
+ // 也正是 v1 只能靠几何(比 y 大小)事后发现的那一类问题。
360
+ //
361
+ // 注意不要写成「祖先链必须包含 neck/torso/hip」:那会把「头 → 躯干 →
362
+ // 胯」这种完全正常的极简骨架误判(它的链就是 torso → hip)。真正要拦的是
363
+ // **肢体**出现在头的上方。
364
+ const LIMB_ROLES = ["upperArm", "lowerArm", "hand", "upperLeg", "lowerLeg", "foot"];
365
+ for (const part of parts.filter((item) => item.role === "head")) {
366
+ const chain = [];
367
+ let cursor = part.parent;
368
+ let guard = 0;
369
+ while (cursor !== undefined && guard++ < 64) {
370
+ const parent = byName.get(cursor);
371
+ if (parent === undefined)
372
+ break;
373
+ chain.push(parent.role);
374
+ cursor = parent.parent;
375
+ }
376
+ const limb = chain.find((role) => LIMB_ROLES.includes(role));
377
+ if (limb !== undefined) {
378
+ warnings.push({ name: part.name, level: "warning", message: `「头部」的祖先链经过肢体(${chain.join(" → ")}),结构可疑` });
379
+ }
380
+ }
381
+ // 左右镜像:人形角色的成对部件应该左右都在,少一边通常意味着分割丢了东西。
382
+ for (const role of ["upperArm", "lowerArm", "hand", "upperLeg", "lowerLeg", "foot"]) {
383
+ const sides = new Set(parts.filter((part) => part.role === role).map((part) => sideOfName(part.name)));
384
+ if (sides.has("left") && !sides.has("right"))
385
+ warnings.push({ name: "", level: "warning", message: `有左侧${ROLE_LABELS[role]}但没有右侧` });
386
+ if (sides.has("right") && !sides.has("left"))
387
+ warnings.push({ name: "", level: "warning", message: `有右侧${ROLE_LABELS[role]}但没有左侧` });
388
+ }
389
+ }
390
+ return { ok: errors.length === 0, errors, warnings, parts };
391
+ }
392
+ /**
393
+ * 把「局部语义补丁」合并进现有语义表。
394
+ *
395
+ * 只改传进来的字段——这是 §4.4 细粒度失效传播的前提:改一个部件的 `parent`
396
+ * 不应该让整份语义表重新生成,也不应该丢掉别人改过的锚点。
397
+ */
398
+ export function mergeSemantics(current, patches) {
399
+ const byName = new Map(current.map((part) => [part.name, { ...part }]));
400
+ for (const patch of patches) {
401
+ const base = byName.get(patch.name);
402
+ if (base === undefined) {
403
+ // 新部件(例如 AI 建议把一条长发拆成 3 节):用默认语义起头再套补丁。
404
+ const fresh = defaultSemanticsOf([patch.name])[0];
405
+ byName.set(patch.name, { ...fresh, ...patch });
406
+ continue;
407
+ }
408
+ byName.set(patch.name, { ...base, ...patch, name: patch.name });
409
+ }
410
+ return [...byName.values()];
411
+ }