dsh-game-material-master 0.4.0 → 0.7.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/rigexport.js CHANGED
@@ -21,8 +21,9 @@
21
21
  * 处(`dragonBones/armature/Slot.ts:409-461`)。所以「图片中心落在骨骼原点」
22
22
  * 这件事要靠 `pivot = 0.5/0.5` + `frameX = 裁剪偏移` 一起凑出来,裁剪过的部件
23
23
  * 少给 `frame*` 就会整体偏掉。
24
- * - **坐标系是 y 向下**(`DragonBones.yDown` 默认 `true`),与我们的图像坐标一致,
25
- * 旋转角不需要取反。
24
+ * - **坐标系是 y 向下**(`DragonBones.yDown` 默认 `true`),Spine 输入却是 y 向上。
25
+ * 骨骼、图片挂点及动画的 y/旋转必须取反,不能直接复制 Spine 的数值。
26
+ * - 当前 DragonBones 只保证刚体贴图与骨骼动画;网格/FFD/Path 明确降级并报告限制。
26
27
  */
27
28
  import { animationPresetOf } from "./spine.js";
28
29
  export const DRAGONBONES_VERSION = "5.5";
@@ -64,11 +65,11 @@ export function encodeDragonBonesCurve(control) {
64
65
  const TIMELINE_KINDS = {
65
66
  rotate: {
66
67
  frameKey: "rotateFrame",
67
- valueOf: (frame) => ({ rotate: round(num(frame.angle, 0), 4) })
68
+ valueOf: (frame) => ({ rotate: round(-num(frame.angle, 0), 4) })
68
69
  },
69
70
  translate: {
70
71
  frameKey: "translateFrame",
71
- valueOf: (frame) => ({ x: round(num(frame.x, 0), 4), y: round(num(frame.y, 0), 4) })
72
+ valueOf: (frame) => ({ x: round(num(frame.x, 0), 4), y: round(-num(frame.y, 0), 4) })
72
73
  },
73
74
  scale: {
74
75
  frameKey: "scaleFrame",
@@ -124,20 +125,24 @@ export function buildDragonBonesTimeline(kind, frames, frameRate) {
124
125
  export function buildDragonBonesSkeleton(options) {
125
126
  const frameRate = options.frameRate ?? DRAGONBONES_FRAME_RATE;
126
127
  const spine = options.spine;
128
+ const exportWarnings = [];
129
+ for (const constraint of spine?.path ?? []) {
130
+ exportWarnings.push(`Path「${constraint.name}」未导出到 DragonBones:请使用 Spine 导出保留路径约束`);
131
+ }
127
132
  const bones = (spine?.bones ?? []).map((bone) => {
128
- const rotation = round(num(bone.rotation, 0), 4);
133
+ const rotation = round(-num(bone.rotation, 0), 4);
129
134
  return {
130
135
  name: bone.name,
131
136
  ...(bone.parent === undefined ? {} : { parent: bone.parent }),
132
137
  length: round(num(bone.length, 0), 4),
133
138
  transform: {
134
139
  x: round(num(bone.x, 0), 4),
135
- y: round(num(bone.y, 0), 4),
140
+ y: round(-num(bone.y, 0), 4),
136
141
  // `skX === skY` 时 `skew === 0`;故意不引入双角度,见方案 §7.3。
137
142
  skX: rotation,
138
143
  skY: rotation,
139
- scX: 1,
140
- scY: 1
144
+ scX: num(bone.scaleX, 1),
145
+ scY: num(bone.scaleY, 1)
141
146
  },
142
147
  inheritTranslation: true,
143
148
  inheritRotation: true,
@@ -145,55 +150,31 @@ export function buildDragonBonesSkeleton(options) {
145
150
  inheritReflection: true
146
151
  };
147
152
  });
148
- const slots = (spine?.slots ?? []).map((slot) => ({
153
+ const attachments = spine?.skins?.[0]?.attachments ?? {};
154
+ const imageSlots = (spine?.slots ?? []).filter((slot) => attachments[slot.name]?.[slot.attachment]?.type !== "path");
155
+ const slots = imageSlots.map((slot) => ({
149
156
  name: slot.name,
150
157
  parent: slot.bone,
151
158
  displayIndex: 0
152
159
  }));
153
- const attachments = spine?.skins?.[0]?.attachments ?? {};
154
- const skinSlots = (spine?.slots ?? []).map((slot) => {
160
+ const skinSlots = imageSlots.map((slot) => {
155
161
  const attachment = attachments[slot.name]?.[slot.attachment] ?? {};
156
- const rotation = round(num(attachment.rotation, 0), 4);
157
- // 有网格的部件出 `mesh`,其余出 `image`。
158
- // 顶点沿用骨架里的坐标(部件中心为原点),两条导出路径共用同一份——
159
- // 各自重算一次网格迟早会因为参数不同而错位,而错位的表现是「贴图按错误的拓扑贴」。
160
- const isMesh = attachment.type === "mesh" && Array.isArray(attachment.vertices);
161
- // **加权网格在 DragonBones 里是另一套编码**(顶点流 + `weights` + `slotPose` +
162
- // `bonePose` 四件套),不能直接吃 Spine 的交错流——喂错了不会报错,只会把
163
- // 「骨骼下标」当成坐标画出一团乱线。所以这里只处理**非加权**网格;
164
- // 检测到加权就退回 `image`(贴图仍然正确显示,只是这一块不参与 LBS)。
165
- // 判定方式:加权的顶点流比 uvs 长(每顶点额外带骨骼下标与权重)。
166
- const isWeighted = isMesh && Array.isArray(attachment.uvs) && attachment.vertices.length !== attachment.uvs.length;
167
- const useMesh = isMesh && !isWeighted;
168
- // `path` 附件也不是贴图:它是一串顶点 + 闭合标记,给 Path 约束当轨道用。
169
- const isPath = attachment.type === "path";
162
+ const rotation = round(-num(attachment.rotation, 0), 4);
163
+ if (attachment.type === "mesh") {
164
+ exportWarnings.push(`网格「${slot.name}」在 DragonBones 中退回刚体贴图,未保留蒙皮或 FFD:请使用 Spine 导出保留这些效果`);
165
+ }
170
166
  return {
171
167
  name: slot.name,
172
168
  display: [
173
169
  {
174
- type: useMesh ? "mesh" : isPath ? "path" : "image",
170
+ type: "image",
175
171
  name: slot.attachment,
176
172
  // 图集里的区域名就是部件名,`path` 与之一致才能取到贴图。
177
173
  path: slot.attachment,
178
- ...(useMesh
179
- ? {
180
- vertices: attachment.vertices,
181
- uvs: attachment.uvs,
182
- triangles: attachment.triangles,
183
- width: round(num(attachment.width, 0), 4),
184
- height: round(num(attachment.height, 0), 4)
185
- }
186
- : {}),
187
- ...(isPath
188
- ? {
189
- vertices: attachment.vertices,
190
- closed: attachment.closed === true
191
- }
192
- : {}),
193
174
  pivot: { x: 0.5, y: 0.5 },
194
175
  transform: {
195
176
  x: round(num(attachment.x, 0), 4),
196
- y: round(num(attachment.y, 0), 4),
177
+ y: round(-num(attachment.y, 0), 4),
197
178
  skX: rotation,
198
179
  skY: rotation,
199
180
  scX: 1,
@@ -220,36 +201,12 @@ export function buildDragonBonesSkeleton(options) {
220
201
  // 我们的 `chain` 字段是「链长」(两骨 = 1);Spine 那边写的是骨骼数组长度,
221
202
  // 所以这里优先用显式字段,缺了才从数组长度反推。
222
203
  chain: Math.max(1, num(constraint.chain, chain.length - 1)),
223
- bendPositive: constraint.bendPositive !== false,
204
+ // y 反射同时反转两骨 IK 的弯曲方向。
205
+ bendPositive: constraint.bendPositive === false,
224
206
  weight: Math.max(0, Math.min(1, num(constraint.mix, 1))),
225
207
  scale: false
226
208
  });
227
209
  }
228
- // ── Path 约束 ────────────────────────────────────────────────────────
229
- //
230
- // Spine 用的是字符串枚举,DragonBones 用数字:不转的话运行时会把
231
- // `"percent"` 当成 0(fixed),于是「均匀铺满」悄悄变成「只铺开头一段」。
232
- const PATH_POSITION_MODE = { fixed: 0, percent: 1 };
233
- const PATH_SPACING_MODE = { length: 0, fixed: 1, percent: 2, proportional: 3 };
234
- const PATH_ROTATE_MODE = { tangent: 0, chain: 1, chainScale: 2 };
235
- const pathConstraints = [];
236
- for (const constraint of Array.isArray(spine?.path) ? spine.path : []) {
237
- const chain = Array.isArray(constraint?.bones) ? constraint.bones.filter((name) => typeof name === "string") : [];
238
- if (chain.length === 0)
239
- continue;
240
- pathConstraints.push({
241
- name: String(constraint.name ?? `path-${pathConstraints.length}`),
242
- // DragonBones 用「链的**第一根**骨 + 目标骨骼」,与 Spine 的「整条数组」不同。
243
- bone: chain[0],
244
- target: String(constraint.target ?? "root"),
245
- positionMode: PATH_POSITION_MODE[String(constraint.positionMode ?? "percent")] ?? 1,
246
- spacingMode: PATH_SPACING_MODE[String(constraint.spacingMode ?? "length")] ?? 0,
247
- rotateMode: PATH_ROTATE_MODE[String(constraint.rotateMode ?? "tangent")] ?? 0,
248
- rotation: num(constraint.rotation, 0),
249
- translateMix: Math.max(0, Math.min(1, num(constraint.translateMix, 1))),
250
- rotateMix: Math.max(0, Math.min(1, num(constraint.rotateMix, 1)))
251
- });
252
- }
253
210
  const animation = [];
254
211
  for (const [id, value] of Object.entries(options.animations ?? {})) {
255
212
  const timelines = value?.bones;
@@ -276,37 +233,12 @@ export function buildDragonBonesSkeleton(options) {
276
233
  const explicit = num(value?.duration, 0);
277
234
  const seconds = explicit > 0 ? explicit : durationSecondsOf(value, preset?.duration ?? 1);
278
235
  const loop = typeof value?.loop === "boolean" ? value.loop : preset?.loop !== false;
279
- // FFD 变形:Spine 的 `deform`(按秒)转成 DragonBones 的 `ffd`(按帧)。
280
- //
281
- // 顺序必须与骨架里 mesh 的 `vertices` 完全一致——两边都是同一份规则网格算出来的,
282
- // 一旦这里改了顶点的排列或数量,位移就会对到别的顶点上,表现是「裙摆乱扭」而不是报错。
283
- const ffd = [];
284
- const spineDeform = spine?.animations?.[id]?.deform;
285
- if (spineDeform !== null && typeof spineDeform === "object") {
286
- for (const [slotName, bySkin] of Object.entries(spineDeform)) {
287
- const frames = Array.isArray(bySkin?.default) ? bySkin.default : [];
288
- if (frames.length === 0)
289
- continue;
290
- ffd.push({
291
- name: slotName,
292
- skin: "default",
293
- slot: slotName,
294
- frame: frames.map((frame, index) => ({
295
- // 末帧的 duration 被解析器忽略(与骨骼时间轴同一条规则)。
296
- duration: index === frames.length - 1 ? 0 : Math.max(1, Math.round(((frames[index + 1].time ?? 0) - (frame.time ?? 0)) * frameRate)),
297
- offset: num(frame.offset, 0),
298
- vertices: Array.isArray(frame.vertices) ? frame.vertices.map((n) => num(n, 0)) : []
299
- }))
300
- });
301
- }
302
- }
303
236
  animation.push({
304
237
  duration: Math.max(1, Math.round(seconds * frameRate)),
305
238
  name: id,
306
239
  // 0 = 无限循环。六个预设都是首尾闭合的(`validateAnimationLoops` 盯着)。
307
240
  playTimes: loop ? 0 : 1,
308
- bone: boneTimelines,
309
- ...(ffd.length === 0 ? {} : { ffd })
241
+ bone: boneTimelines
310
242
  });
311
243
  }
312
244
  const width = Math.round(options.canvasWidth);
@@ -316,18 +248,17 @@ export function buildDragonBonesSkeleton(options) {
316
248
  name: options.name,
317
249
  version: DRAGONBONES_VERSION,
318
250
  compatibleVersion: DRAGONBONES_COMPATIBLE_VERSION,
251
+ ...(exportWarnings.length === 0 ? {} : { exportWarnings }),
319
252
  armature: [
320
253
  {
321
254
  type: "Armature",
322
255
  frameRate,
323
256
  name: options.name,
324
- aabb: { x: 0, y: 0, width, height },
325
- // 画布原点按 Spine 那边的习惯放在水平中线,y 从 0 起(y 向下)。
326
- canvas: { x: -width / 2, y: 0, width, height },
257
+ aabb: { x: -width / 2, y: -height, width, height },
258
+ canvas: { x: -width / 2, y: -height, width, height },
327
259
  bone: bones,
328
260
  slot: slots,
329
261
  ...(ik.length === 0 ? {} : { ik }),
330
- ...(pathConstraints.length === 0 ? {} : { path: pathConstraints }),
331
262
  skin: [{ name: "default", slot: skinSlots }],
332
263
  animation,
333
264
  defaultActions: []
package/lib/riggen.js CHANGED
@@ -28,7 +28,7 @@ import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
28
28
  import { basename, join, resolve, sep } from "node:path";
29
29
  import { randomUUID } from "node:crypto";
30
30
  import { loadConfig, rigJobsRoot } from "./config.js";
31
- import { generateImage } from "./ark.js";
31
+ import { assertImageProviderReady, generateImageWithProvider, imageModelOf, imageProviderBlocker, imageSizeOf, imageTimeoutOf, imageWatermarkOf, isCustomProvider } from "./imageprovider.js";
32
32
  import { decodeToRgba, mimeOf, toDataUri } from "./media.js";
33
33
  import { encodePng } from "./png.js";
34
34
  import { appendJobLog, messageOf, readJson, writeJsonAtomic } from "./jsonio.js";
@@ -154,9 +154,9 @@ export async function createRigJob(name) {
154
154
  updatedAt: now,
155
155
  prompts: { sheet: "", suffix: "" },
156
156
  settings: {
157
- model: config.arkModel,
158
- size: config.arkSize,
159
- watermark: config.arkWatermark,
157
+ model: imageModelOf(config),
158
+ size: imageSizeOf(config),
159
+ watermark: imageWatermarkOf(config),
160
160
  gridColumns: RIG_GRID_COLUMNS,
161
161
  gridRows: RIG_GRID_ROWS,
162
162
  backgroundTolerance: 30,
@@ -261,7 +261,7 @@ function normalizeRigJob(raw) {
261
261
  error: typeof part.error === "string" ? part.error : undefined,
262
262
  updatedAt: Number.isFinite(part.updatedAt) ? part.updatedAt : undefined,
263
263
  role: typeof part.role === "string" && part.role !== "" ? part.role : undefined,
264
- parent: typeof part.parent === "string" && part.parent !== "" ? part.parent : undefined,
264
+ parent: part.parent === null ? null : typeof part.parent === "string" && part.parent !== "" ? part.parent : undefined,
265
265
  proximal: Array.isArray(part.proximal) && part.proximal.length === 2 ? [num(part.proximal[0], 0.5), num(part.proximal[1], 0)] : undefined,
266
266
  distal: Array.isArray(part.distal) && part.distal.length === 2 ? [num(part.distal[0], 0.5), num(part.distal[1], 1)] : undefined,
267
267
  tags: Array.isArray(part.tags) ? part.tags.filter((tag) => typeof tag === "string") : undefined,
@@ -1450,22 +1450,24 @@ export async function redrawRigPart(jobId, name, prompt, options = {}) {
1450
1450
  if (active === undefined)
1451
1451
  throw new Error(`「${name}」还没有贴图`);
1452
1452
  const config = await loadConfig();
1453
- if (config.arkApiKey.trim() === "")
1454
- throw new Error("尚未配置火山方舟 API Key,无法重绘(可以在界面里手工换色或上传替换,都不花钱)");
1453
+ const blocker = imageProviderBlocker(config);
1454
+ if (blocker !== undefined) {
1455
+ throw new Error(`${blocker},无法重绘(可以在界面里手工换色或上传替换,都不花钱)`);
1456
+ }
1455
1457
  const decoded = await decodeToRgba(rigAssetPath(jobId, active.file), 2048);
1456
1458
  const original = { data: decoded.rgba, width: decoded.width, height: decoded.height };
1457
1459
  const square = padToSquare(original, REDRAW_PAD_COLOR);
1458
1460
  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,
1461
+ // 部件重绘单独指定模型的开关只在火山方舟下有意义;自定义后端只有一个模型名。
1462
+ const redrawModel = isCustomProvider(config) ? "" : config.arkRedrawModel.trim();
1463
+ /** 这一次真正会用的模型名(只用于报错文案)。 */
1464
+ const modelUsedForRedraw = isCustomProvider(config) ? config.customModel : redrawModel || config.arkModel;
1465
+ const result = await generateImageWithProvider({
1463
1466
  model: redrawModel,
1464
1467
  prompt: buildRedrawPrompt(prompt, { role: part.role }),
1465
1468
  images: [dataUri],
1466
- size: config.arkSize,
1467
- watermark: config.arkWatermark,
1468
- timeoutMs: config.arkTimeoutMs
1469
+ size: imageSizeOf(config),
1470
+ watermark: imageWatermarkOf(config)
1469
1471
  });
1470
1472
  // 模型交回来的图要落盘才能解码(解码器是 ffmpeg,吃文件路径)。
1471
1473
  const tempFile = join(rigJobDir(jobId), "parts", `.redraw-${Date.now()}.${result.ext}`);
@@ -1491,8 +1493,8 @@ export async function redrawRigPart(jobId, name, prompt, options = {}) {
1491
1493
  }
1492
1494
  if (stats.stdDev < MIN_REDRAW_CONTRAST) {
1493
1495
  throw new Error(`重绘结果几乎是纯色(亮度 ${stats.meanLuma.toFixed(0)}、标准差 ${stats.stdDev.toFixed(1)}),` +
1494
- `模型「${redrawModel}」没有画出内容,已丢弃(没有新增版本)。` +
1495
- "可以换个更具体的提示词,或在「设置 → 游戏素材大师 → 部件重绘模型」里换一个模型;" +
1496
+ `模型「${modelUsedForRedraw}」没有画出内容,已丢弃(没有新增版本)。` +
1497
+ "可以换个更具体的提示词,或在「设置 → 游戏素材大师 → 生图后端」里换一个模型;" +
1496
1498
  "只是想让颜色变一下的话,「换色」是免费的。");
1497
1499
  }
1498
1500
  // 重新读一次:生图可能耗时很久,期间任务可能已经被改过。
@@ -1950,12 +1952,14 @@ export async function setRigConstraints(jobId, patches, options = {}) {
1950
1952
  name: patch.name,
1951
1953
  bone: patch.bone ?? (index >= 0 ? current[index].bone : ""),
1952
1954
  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)))),
1955
+ chain: num(patch.chain, index >= 0 ? current[index].chain : 1),
1954
1956
  bendPositive: patch.bendPositive ?? (index >= 0 ? current[index].bendPositive : true),
1955
1957
  weight: Math.max(0, Math.min(1, num(patch.weight, index >= 0 ? current[index].weight : 1)))
1956
1958
  };
1957
1959
  if (merged.bone === "")
1958
1960
  throw new Error(`IK「${merged.name}」缺少被约束的骨骼`);
1961
+ if (merged.chain !== 1)
1962
+ throw new Error(`IK「${merged.name}」目前只支持两根骨骼(chain = 1)`);
1959
1963
  if (index >= 0)
1960
1964
  current[index] = merged;
1961
1965
  else
@@ -2404,26 +2408,26 @@ export async function generateSheet(jobId) {
2404
2408
  if (job === undefined)
2405
2409
  throw new Error(`任务不存在:${jobId}`);
2406
2410
  const config = await loadConfig();
2407
- if (config.arkApiKey.trim() === "")
2408
- throw new Error("尚未配置火山方舟 API Key");
2411
+ assertImageProviderReady(config);
2409
2412
  if (job.source === undefined)
2410
2413
  throw new Error("还没有角色参考图,请先上传一张整图");
2411
2414
  const prompt = buildSheetRequest(job);
2412
- job.settings.model = config.arkModel;
2415
+ const model = imageModelOf(config);
2416
+ job.settings.model = model;
2417
+ if (isCustomProvider(config))
2418
+ job.settings.size = config.customSize;
2413
2419
  job.sheet = { ...job.sheet, status: "running", error: undefined };
2414
- appendJobLog(job.log, "info", `开始拆件生图(模型 ${config.arkModel})`);
2420
+ appendJobLog(job.log, "info", `开始拆件生图(模型 ${model})`);
2415
2421
  await writeRigJob(job);
2416
2422
  try {
2417
2423
  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,
2424
+ const result = await generateImageWithProvider({
2422
2425
  prompt,
2423
2426
  images: [reference],
2424
- size: job.settings.size || config.arkSize,
2425
- watermark: job.settings.watermark,
2426
- timeoutMs: config.arkTimeoutMs
2427
+ size: job.settings.size || imageSizeOf(config),
2428
+ // 与图片生成那条路同口径:全局设置或任务上的旧覆盖位,任一为真就带水印。
2429
+ watermark: imageWatermarkOf(config) || job.settings.watermark === true,
2430
+ timeoutMs: imageTimeoutOf(config)
2427
2431
  });
2428
2432
  const relative = `sheet/parts-sheet.${result.ext}`;
2429
2433
  await mkdir(join(rigJobDir(jobId), "sheet"), { recursive: true });
@@ -3307,8 +3311,8 @@ export async function buildRigOutput(jobId) {
3307
3311
  scale: item.scale,
3308
3312
  rotation: item.rotation,
3309
3313
  z: item.z,
3310
- // 语义层的父级与锚点优先;没给时 `buildSkeleton` 会回落到按名字推断。
3311
- parent: node?.parent,
3314
+ // 语义已补齐:没有语义父级也属于已确定的 root,不再按名字兜底。
3315
+ parent: node?.parent ?? null,
3312
3316
  proximal: node?.proximal,
3313
3317
  distal: node?.distal,
3314
3318
  // 三通道的中间那一层:人的手工偏置,任何自动重跑都不碰它。
package/lib/rigpath.js CHANGED
@@ -5,9 +5,8 @@
5
5
  * DragonBones / 我们的预览器)都能表达的最小共同集:路径是一串折线点,
6
6
  * 骨骼沿弧长均匀(或按固定间距)铺上去,每根骨取所在位置的切线。
7
7
  *
8
- * 不做贝塞尔路径:Spine 的 PathAttachment 存的本来就是**采样后的折线**
9
- * (`vertices` + `lengths`),编辑器里的曲线在导出前也会被压平。我们直接收折线,
10
- * 少一层「曲线 → 折线」的采样,也就少一个「预览和导出不一样」的可能。
8
+ * 编辑数据保留折线;Spine 的 PathAttachment 实际存三次贝塞尔控制点,
9
+ * 导出时把每条直线段编码为两个共线控制点,形状与弧长不变。
11
10
  *
12
11
  * 坐标系与部件一致:**参考图像素、Y 向下**。转成骨骼世界坐标由调用方负责
13
12
  * (`toWorld` 那一步),这里只做纯几何。
@@ -20,7 +19,7 @@ export function normalizePath(raw) {
20
19
  const source = Array.isArray(value.points) ? value.points : [];
21
20
  // 扁平数组 `[x0,y0,x1,y1,…]`:**内部表示就是这个形状**(`RigPathEntry.points` 是扁平的),
22
21
  // wire 上传过来时也是最省事的一种。另外两种写法是给人手写 JSON 用的。
23
- if (source.length >= 4 && source.every((entry) => typeof entry === "number" && Number.isFinite(entry))) {
22
+ if (source.length >= 4 && source.length % 2 === 0 && source.every((entry) => typeof entry === "number" && Number.isFinite(entry))) {
24
23
  return { points: source.map((n) => Number(n.toFixed(3))), closed: value.closed === true };
25
24
  }
26
25
  const flat = [];
@@ -42,7 +41,7 @@ export function pathSegmentCount(path) {
42
41
  const count = path.points.length / 2;
43
42
  return path.closed === true ? count : count - 1;
44
43
  }
45
- /** 每段的长度——**这就是 Spine 的 `PathAttachment.lengths`**。 */
44
+ /** 每段的长度;Spine 导出另行编成累计弧长表。 */
46
45
  export function pathSegmentLengths(path) {
47
46
  const count = path.points.length / 2;
48
47
  const segments = [];
@@ -59,21 +58,59 @@ export function pathTotalLength(path, lengths) {
59
58
  const segments = lengths ?? pathSegmentLengths(path);
60
59
  return Number(segments.reduce((sum, value) => sum + value, 0).toFixed(4));
61
60
  }
61
+ /** 折线 → Spine 三次曲线顶点。输入已是槽位局部坐标(Y 向上)。 */
62
+ export function spinePathGeometry(path) {
63
+ const points = [];
64
+ for (let i = 0; i + 1 < path.points.length; i += 2) {
65
+ if (points.length > 0 && Math.hypot(path.points[i] - points[points.length - 2], path.points[i + 1] - points[points.length - 1]) <= 1e-6)
66
+ continue;
67
+ points.push(path.points[i], path.points[i + 1]);
68
+ }
69
+ if (path.closed && points.length > 4 && Math.hypot(points[0] - points[points.length - 2], points[1] - points[points.length - 1]) <= 1e-6)
70
+ points.splice(-2);
71
+ const count = points.length / 2;
72
+ const segments = path.closed ? count : count - 1;
73
+ // 每段 [起点, 1/3 控制点, 2/3 控制点, 终点],相邻段共用端点。
74
+ const curve = [points[0], points[1]];
75
+ const lengths = [];
76
+ let total = 0;
77
+ for (let i = 0; i < segments; i++) {
78
+ const j = (i + 1) % count;
79
+ const x = points[i * 2], y = points[i * 2 + 1];
80
+ const dx = points[j * 2] - x, dy = points[j * 2 + 1] - y;
81
+ curve.push(x + dx / 3, y + dy / 3, x + dx * 2 / 3, y + dy * 2 / 3, points[j * 2], points[j * 2 + 1]);
82
+ total += Math.hypot(dx, dy);
83
+ lengths.push(Number(total.toFixed(4)));
84
+ }
85
+ // 开放路径的首尾额外控制点不参与曲线;闭合路径把末段第二控制点放在首位。
86
+ const vertices = path.closed
87
+ ? [...curve.slice(-4, -2), ...curve.slice(0, -4)]
88
+ : [points[0], points[1], ...curve, points[points.length - 2], points[points.length - 1]];
89
+ if (!path.closed)
90
+ lengths.push(Number(total.toFixed(4)));
91
+ return { vertices: vertices.map((n) => Number(n.toFixed(6))), vertexCount: vertices.length / 2, lengths };
92
+ }
62
93
  /**
63
94
  * 按**弧长**采样:给出沿路径走 `distance` 之后的位置与切线角(弧度)。
64
95
  *
65
- * 用弧长而不是"按段索引"是因为骨骼要**等距**铺开:段长不等时按索引分会让骨骼在
66
- * 长段上稀疏、短段上挤成一团。`distance` 会被夹进 `[0, 总长]`,越界不报错——
67
- * 调用方(排列骨链)本来就会算出越界值,那时"停在端点"才是想要的行为。
96
+ * 用弧长而不是"按段索引"让骨骼等距。与 Spine 一致:闭合路径按总长循环,
97
+ * 开放路径越界时沿首/末段切线外推,固定间距不会在端点挤成一团。
68
98
  */
69
99
  export function samplePath(path, distance, lengths, total) {
70
100
  const segments = lengths ?? pathSegmentLengths(path);
71
101
  const sum = total ?? segments.reduce((acc, value) => acc + value, 0);
72
102
  const count = path.points.length / 2;
73
- let remaining = Math.max(0, Math.min(sum, distance));
103
+ if (sum <= 1e-6)
104
+ return { x: path.points[0], y: path.points[1], angle: 0 };
105
+ let remaining = path.closed ? ((distance % sum) + sum) % sum : distance;
106
+ let lastSegment = segments.length - 1;
107
+ while (lastSegment >= 0 && segments[lastSegment] <= 1e-6)
108
+ lastSegment--;
74
109
  for (let i = 0; i < segments.length; i++) {
75
110
  const length = segments[i];
76
- if (remaining <= length || i === segments.length - 1) {
111
+ if (length <= 1e-6)
112
+ continue;
113
+ if (remaining <= length || i === lastSegment) {
77
114
  const t = length > 1e-9 ? remaining / length : 0;
78
115
  const j = (i + 1) % count;
79
116
  const x0 = path.points[i * 2];