dsh-game-material-master 0.6.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/mapgeom.js CHANGED
@@ -270,6 +270,13 @@ function clampInt(value, low, high) {
270
270
  * 画了也看不见,却会把 chunk 数与计划条数按倍数放大(`MAP_CHUNK_SIZE` 那一侧
271
271
  * 还有 `MAX_PLAN_CHUNKS` 兜着,这里必须自己收口)。非环绕下裁到 `0..cols/rows`,
272
272
  * 视口完全在图外时返回空 range(`r1 === r0`),`chunksInRange` 会给出空数组。
273
+ *
274
+ * ⚠️ **一整轮要取「地图自己那一轮」,不能从视口左上角起算**。
275
+ *
276
+ * 视口比地图还大时(画布大、地图只占左上角一片,相机被夹在 0),`padding` 会把
277
+ * 起点推到 `-1`:再一刀切在 `c0 + cols` 上,得到的其实是 `[-1, cols-1)` ——
278
+ * 地图自己的**最后一列**只以「视口左上角外侧的环绕副本」出现,而那一份落在画布
279
+ * 外面。真机表现:地图右边缘少一列、底边少一行;摆在那一列上的标记点直接看不见。
273
280
  */
274
281
  export function viewCellRange(layout, view, padding = 1) {
275
282
  const corners = [
@@ -290,12 +297,17 @@ export function viewCellRange(layout, view, padding = 1) {
290
297
  c1: clampInt(c1, 0, layout.cols)
291
298
  };
292
299
  }
293
- return {
294
- r0,
295
- c0,
296
- r1: Math.min(r1, r0 + layout.rows),
297
- c1: Math.min(c1, c0 + layout.cols)
298
- };
300
+ /**
301
+ * 环绕:视口某一维比地图还长 → 那一维**直接给整张地图**(`0..cols` / `0..rows`)。
302
+ *
303
+ * 取的是「地图自己那一轮」而不是「视口左上角起的一轮」:后者会被 padding 推成
304
+ * `[-padding, cols-padding)`,把地图最后几列挤出窗口(见上面的注释)。
305
+ * 收在一轮以内,所以条数仍然有界;自动连接要看的邻居在环绕下就在这一轮里。
306
+ */
307
+ const whole = (from, to, span) => (to - from > span ? [0, span] : [from, to]);
308
+ const [rr0, rr1] = whole(r0, r1, layout.rows);
309
+ const [cc0, cc1] = whole(c0, c1, layout.cols);
310
+ return { r0: rr0, r1: rr1, c0: cc0, c1: cc1 };
299
311
  }
300
312
  /** 导出用:把(可能越界的)范围裁到 `0..cols` × `0..rows`。 */
301
313
  export function clampRangeToMap(layout, range) {
package/lib/maprender.js CHANGED
@@ -30,7 +30,7 @@
30
30
  */
31
31
  import { encodePng } from "./png.js";
32
32
  import { cellIndex } from "./mapdoc.js";
33
- import { cellTopLeft, chunkKey, chunkOf, layoutOf, parseChunkKey, wrapCell } from "./mapgeom.js";
33
+ import { cellCenter, cellTopLeft, chunkKey, chunkOf, layoutOf, parseChunkKey, wrapCell } from "./mapgeom.js";
34
34
  import { a2QuadrantShapes, corner16Mask, nearestMask } from "./mapauto.js";
35
35
  import { flatTiles } from "./maptiles.js";
36
36
  /** 单张导出图的最大像素数(超过就明确拒绝,而不是把进程 OOM 掉)。 */
@@ -326,7 +326,61 @@ export function buildPlan(context, doc, opts = {}) {
326
326
  }
327
327
  chunks.push({ key, ops: list.map((item) => item.op) });
328
328
  }
329
- return { chunks, bounds: planBounds(context, doc), legend, fps: DEFAULT_FPS, frameCount, cycles, warnings };
329
+ return {
330
+ chunks,
331
+ bounds: planBounds(context, doc),
332
+ legend,
333
+ fps: DEFAULT_FPS,
334
+ frameCount,
335
+ cycles,
336
+ markers: buildMarkers(context, doc, range),
337
+ warnings
338
+ };
339
+ }
340
+ /**
341
+ * 落在 `range` 里的标记。
342
+ *
343
+ * 与 `cellOpsAt` 同一套走法:按**未 wrap** 的格坐标遍历视口,读格时 `wrapCell` ——
344
+ * 于是环绕接缝处的标记会以多个像素位置各出一条,界面不需要知道环绕。
345
+ *
346
+ * 一格最多一个标记(宿主 `applyOps` 已经拦住重复放置),所以这里是 1:1 的查表。
347
+ */
348
+ export function buildMarkers(context, doc, range) {
349
+ if (doc.markers.length === 0)
350
+ return [];
351
+ const layout = layoutOf(context.grid, doc.cols, doc.rows);
352
+ const byCell = new Map();
353
+ doc.markers.forEach((marker, index) => {
354
+ byCell.set(marker.r * doc.cols + marker.c, { n: index + 1, marker });
355
+ });
356
+ // 圆别比格子还大(小网格 + 大标记会互相盖住),字号跟着半径走。
357
+ const radius = Math.max(5, Math.round(Math.min(layout.stepX, layout.stepY) * 0.42));
358
+ const font = Math.max(8, Math.round(radius * 1.2));
359
+ const out = [];
360
+ for (let rr = range.r0; rr < range.r1; rr++) {
361
+ for (let cc = range.c0; cc < range.c1; cc++) {
362
+ const w = wrapCell(layout, rr, cc);
363
+ // 非环绕时越界就是越界(`wrapCell` 原样返回)。
364
+ if (w.r < 0 || w.c < 0 || w.r >= doc.rows || w.c >= doc.cols)
365
+ continue;
366
+ const hit = byCell.get(w.r * doc.cols + w.c);
367
+ if (hit === undefined)
368
+ continue;
369
+ const center = cellCenter(layout, rr, cc);
370
+ out.push({
371
+ id: hit.marker.id,
372
+ n: hit.n,
373
+ name: hit.marker.name,
374
+ r: w.r,
375
+ c: w.c,
376
+ x: Math.round(center.x),
377
+ y: Math.round(center.y),
378
+ radius,
379
+ font
380
+ });
381
+ }
382
+ }
383
+ return out;
330
384
  }
331
385
  // ── 光栅化(导出 PNG 用)──────────────────────────────────────────────────
332
386
  /** source-over 合成(与浏览器 canvas 的默认混合一致)。 */
package/lib/media.js CHANGED
@@ -196,6 +196,40 @@ export async function makeThumbnail(source, dest, maxEdge = 768) {
196
196
  dest
197
197
  ], 120000);
198
198
  }
199
+ /**
200
+ * 按**文件头**认一段本地视频的容器(用户自选的本地视频走这条路)。
201
+ *
202
+ * 为什么不看扩展名:从手机 / 剪辑软件 / 聊天工具里拿到的文件经常被改名或根本
203
+ * 没有正确的后缀(`.mp4` 其实是 MOV、`.bin` 其实是 MP4)。这里只在本机交给
204
+ * ffmpeg 解码,容器认错了不会当场报错,而是**抽帧时**才失败——那时用户已经
205
+ * 以为「导入成功了」。
206
+ *
207
+ * 认三种,覆盖游戏素材的常见来源:
208
+ * - ISO BMFF(MP4 / MOV / M4V):第 4~8 字节是 `ftyp`,再按 brand 区分 MOV 与 MP4;
209
+ * - Matroska / WebM:EBML 头 `1A 45 DF A3`(两者同族,统一按 webm 存);
210
+ * - AVI:`RIFF` + 第 8~12 字节 `AVI `。
211
+ *
212
+ * 返回的 `ext` 直接当落盘后缀,所以它必须是 ffmpeg 认得的容器名。
213
+ */
214
+ export function sniffVideo(base64) {
215
+ // 48 字节足够覆盖三种文件头里的判别字段。
216
+ const head = Buffer.from(base64.slice(0, 64), "base64");
217
+ if (head.length >= 12 && head.toString("ascii", 4, 8) === "ftyp") {
218
+ const brand = head.toString("ascii", 8, 12).trim().toLowerCase();
219
+ if (brand === "qt")
220
+ return { ext: "mov", mime: "video/quicktime", label: "MOV" };
221
+ if (brand === "m4v" || brand === "m4vh")
222
+ return { ext: "m4v", mime: "video/x-m4v", label: "M4V" };
223
+ return { ext: "mp4", mime: "video/mp4", label: "MP4" };
224
+ }
225
+ if (head.length >= 4 && head[0] === 0x1a && head[1] === 0x45 && head[2] === 0xdf && head[3] === 0xa3) {
226
+ return { ext: "webm", mime: "video/webm", label: "WebM / MKV" };
227
+ }
228
+ if (head.length >= 12 && head.toString("ascii", 0, 4) === "RIFF" && head.toString("ascii", 8, 12) === "AVI ") {
229
+ return { ext: "avi", mime: "video/x-msvideo", label: "AVI" };
230
+ }
231
+ return undefined;
232
+ }
199
233
  /** 读取文件并组装成 data URI(Ark 参考图用)。 */
200
234
  export async function toDataUri(file, mime) {
201
235
  const bytes = await readFile(file);
package/lib/pipeline.js CHANGED
@@ -21,11 +21,12 @@ import { mkdir, readFile, writeFile } from "node:fs/promises";
21
21
  import { dirname } from "node:path";
22
22
  import { loadConfig } from "./config.js";
23
23
  import { DEFAULT_TURN_PROMPT, DIRECTIONS, DIRECTION_KEYS, TURN_DIRECTION_DEFAULT, TURN_FRAME_COUNT_MAX, TURN_FRAME_COUNT_MIN, directionOf, turnOrder } from "./directions.js";
24
- import { generateImage } from "./ark.js";
24
+ import { assertImageProviderReady, generateImageWithProvider, imageModelOf, imageSizeOf, imageWatermarkOf } from "./imageprovider.js";
25
25
  import { downloadVideo, queryVideo, retrieveFile, submitVideo } from "./minimax.js";
26
- import { extractFrames, mimeOf, toDataUri, toJpegDataUri } from "./media.js";
26
+ import { extractFrames, mimeOf, sniffVideo, toDataUri, toJpegDataUri } from "./media.js";
27
27
  import { composeSheet, keyGreen } from "./chroma.js";
28
28
  import { encodePng } from "./png.js";
29
+ import { zipEntries } from "./zip.js";
29
30
  import { assetPath, freshPicks, log, patchProject, readProject, referenceFiles } from "./store.js";
30
31
  /** 生图的依赖分层:同一层内可并发,层与层之间必须按序。 */
31
32
  const IMAGE_STAGES = [
@@ -51,14 +52,6 @@ export function listJobs(projectId) {
51
52
  function messageOf(error) {
52
53
  return error instanceof Error ? error.message : String(error);
53
54
  }
54
- function arkRequest(config) {
55
- return {
56
- baseUrl: config.arkBaseUrl,
57
- apiKey: config.arkApiKey,
58
- model: config.arkModel,
59
- timeoutMs: config.arkTimeoutMs
60
- };
61
- }
62
55
  function miniMaxRequest(config) {
63
56
  return {
64
57
  baseUrl: config.minimaxBaseUrl,
@@ -140,6 +133,8 @@ async function generateOne(projectId, key, promptOverride) {
140
133
  if (project === undefined)
141
134
  throw new Error(`项目不存在:${projectId}`);
142
135
  const config = await loadConfig();
136
+ // 后端没配好就不要往下走:这一步会真实计费,早失败比「跑到一半报错」好。
137
+ assertImageProviderReady(config);
143
138
  const basePrompt = (promptOverride ?? project.prompts.images[key] ?? "").trim();
144
139
  if (basePrompt === "")
145
140
  throw new Error("提示词为空,请先填写生图提示词");
@@ -161,12 +156,11 @@ async function generateOne(projectId, key, promptOverride) {
161
156
  const startedAt = Date.now();
162
157
  try {
163
158
  const images = await Promise.all(refs.map((file) => toDataUri(file, mimeOf(file))));
164
- const result = await generateImage({
165
- ...arkRequest(config),
159
+ const result = await generateImageWithProvider({
166
160
  prompt,
167
161
  images,
168
- size: config.arkSize,
169
- watermark: config.arkWatermark
162
+ size: imageSizeOf(config),
163
+ watermark: imageWatermarkOf(config)
170
164
  });
171
165
  const relative = `images/${key}.${result.ext}`;
172
166
  await mkdir(dirname(assetPath(projectId, relative)), { recursive: true });
@@ -179,7 +173,7 @@ async function generateOne(projectId, key, promptOverride) {
179
173
  file: relative,
180
174
  approved: false,
181
175
  stale: false,
182
- model: config.arkModel,
176
+ model: imageModelOf(config),
183
177
  elapsedMs: elapsed,
184
178
  updatedAt: Date.now()
185
179
  };
@@ -642,6 +636,194 @@ export async function setImageMode(projectId, mode) {
642
636
  log(project, "info", mode === "turn" ? "阶段①改用「转圈截帧」" : "阶段①改用「逐方向生图」");
643
637
  });
644
638
  }
639
+ // ── 本地自选视频:阶段①(转圈)与阶段②(八段行走)的第三条输入 ────────────
640
+ //
641
+ // 两处「需要生成视频」的地方都可以直接**自己选一段本地视频**,跳过远程生成:
642
+ // · `turn` → 一段原地转圈的绿幕视频(导入后自动抽候选帧、切八张方向图);
643
+ // · 八个方向 key → 某一段行走视频(导入后照旧在第 3 步抽帧)。
644
+ //
645
+ // 产物与远端生成的**完全同形**(同一个 `videos/` 目录、同一个 VideoNode 形状,
646
+ // 只有 `origin: "local"` 这一个字段不同),所以阶段 3、4 一行都不用改。
647
+ // 这条链路只在本机跑 ffmpeg,没有任何网络调用,因此上限比「发给模型」宽得多。
648
+ /** 本地自选视频的大小上限(只受本机内存与传输体量限制,见 `importLocalVideo`)。 */
649
+ export const LOCAL_VIDEO_MAX_BYTES = 100 * 1024 * 1024;
650
+ /** 落盘用的文件名安全化:用户给的名字会直接拼进项目目录。 */
651
+ function safeFileStem(input, fallback) {
652
+ const cleaned = (input ?? "")
653
+ .replace(/[^\p{L}\p{N}_-]+/gu, "_")
654
+ .replace(/^_+|_+$/g, "")
655
+ .slice(0, 40);
656
+ return cleaned === "" ? fallback : cleaned;
657
+ }
658
+ /**
659
+ * 把一段本地视频放进 `turn` 或某个方向的槽位。
660
+ *
661
+ * 除了写文件,还要做三件“不写就会静默坏掉”的事:
662
+ * 1. **作废旧产物**:这个槽位原来的视频、它抽出来的帧、以及由那些帧合成的
663
+ * 整图都属于上一段视频。尤其是抽帧缓存 `raw.bin`,留着就会拿旧帧去合成
664
+ * (界面看着一切正常,只是人物朝向对不上)。
665
+ * 2. **摘掉远端任务号**:如果这一刻正好有一个远端任务在跑,它的结果稍后会
666
+ * 把我们的本地视频**直接覆盖掉**。写 `status: ready` 并清掉 `taskId`,
667
+ * 轮询器下一轮就不会再认领它(单次已经在下载途中的那一轮仍可能落盘,
668
+ * 所以日志里明确写一条)。
669
+ * 3. **转圈模式顺手抽帧**:远端路径也是「视频到手就抽候选帧」,这里保持一致,
670
+ * 否则用户导入完还得自己找「抽取候选帧」按钮,而且不知道时间轴为什么是空的。
671
+ */
672
+ export async function importLocalVideo(projectId, key, name, base64) {
673
+ const project = await readProject(projectId);
674
+ if (project === undefined)
675
+ throw new Error(`项目不存在:${projectId}`);
676
+ const isTurn = key === "turn";
677
+ if (!isTurn && directionOf(key) === undefined) {
678
+ throw new Error(`未知方位:${key}(可用 turn 或 ${DIRECTION_KEYS.join(" / ")})`);
679
+ }
680
+ const clean = base64.replace(/^data:[^;]+;base64,/, "");
681
+ if (clean.trim() === "")
682
+ throw new Error("没有收到视频数据");
683
+ const bytes = Buffer.from(clean, "base64");
684
+ if (bytes.length === 0)
685
+ throw new Error("视频数据为空");
686
+ if (bytes.length > LOCAL_VIDEO_MAX_BYTES) {
687
+ throw new Error(`视频 ${(bytes.length / 1024 / 1024).toFixed(1)}MB 超过上限 ${Math.round(LOCAL_VIDEO_MAX_BYTES / 1024 / 1024)}MB,请先压缩或裁剪`);
688
+ }
689
+ const sniffed = sniffVideo(clean);
690
+ if (sniffed === undefined) {
691
+ throw new Error("无法识别的视频格式(支持 MP4 / MOV / M4V / WebM / MKV / AVI)");
692
+ }
693
+ const originalName = safeFileStem(name.replace(/\.[^.]+$/, ""), `local-${key}`) + "." + sniffed.ext;
694
+ const relative = `videos/${isTurn ? "turn" : key}.${sniffed.ext}`;
695
+ const mb = (bytes.length / 1024 / 1024).toFixed(1);
696
+ await mkdir(dirname(assetPath(projectId, relative)), { recursive: true });
697
+ await writeFile(assetPath(projectId, relative), bytes);
698
+ if (isTurn) {
699
+ await patchProject(projectId, (current) => {
700
+ const droppedTask = current.turn.video?.taskId;
701
+ current.turn.video = {
702
+ status: "ready",
703
+ file: relative,
704
+ approved: false,
705
+ // 远端状态这一栏在界面上同时是「这段视频的来路」,本地导入就照实写。
706
+ remoteStatus: "本地视频",
707
+ origin: "local",
708
+ originalName,
709
+ // 首帧只对「图生视频」有意义,本地视频没有输入图,清掉免得界面指向一张无关的图。
710
+ firstFrame: undefined,
711
+ updatedAt: Date.now()
712
+ };
713
+ if (current.turn.frames.frames.length > 0)
714
+ current.turn.frames.stale = true;
715
+ log(current, "info", `已选用本地视频作为转圈视频:${originalName}(${mb} MB)`);
716
+ if (droppedTask !== undefined) {
717
+ log(current, "warn", `原先的转圈视频远端任务(${droppedTask})已作废,它的结果不会再被采用`);
718
+ }
719
+ });
720
+ const started = startTurnFrames(projectId);
721
+ return {
722
+ key,
723
+ file: relative,
724
+ name: originalName,
725
+ bytes: bytes.length,
726
+ extractStarted: started.started === true,
727
+ extractReason: started.reason
728
+ };
729
+ }
730
+ const label = directionOf(key)?.label ?? key;
731
+ await patchProject(projectId, (current) => {
732
+ const droppedTask = current.videos[key]?.taskId;
733
+ current.videos[key] = {
734
+ status: "ready",
735
+ file: relative,
736
+ approved: false,
737
+ remoteStatus: "本地视频",
738
+ origin: "local",
739
+ originalName,
740
+ updatedAt: Date.now()
741
+ };
742
+ // 旧帧与整图都属于上一段视频:不清掉就会拿另一段视频的帧继续往下走。
743
+ current.frames[key] = { status: "empty", frames: [], keyed: [], approved: false };
744
+ current.sheet = { status: "empty", approved: false };
745
+ log(current, "info", `已选用本地视频作为「${label}」的行走视频:${originalName}(${mb} MB),需要到第 3 步重新抽帧`);
746
+ if (droppedTask !== undefined) {
747
+ log(current, "warn", `「${label}」原先的远端任务(${droppedTask})已作废,它的结果不会再被采用`);
748
+ }
749
+ });
750
+ return { key, file: relative, name: originalName, bytes: bytes.length };
751
+ }
752
+ /**
753
+ * 这个项目里所有**中间图片**的相对路径。
754
+ *
755
+ * 「中间」= 一路生成下来留下的每一张图:八方向绿幕图、转圈候选帧与整圈条带、
756
+ * 每段视频抽出来的绿幕帧与它的手动选帧候选、抠完绿幕的帧、以及最后合成的整图。
757
+ * 源图(用户自己的输入)不算,它不是这条路产出的东西。
758
+ *
759
+ * 顺序刻意按阶段走(① → ② → ③ → ④),解压出来的人眼一翻就能对上流程。
760
+ */
761
+ export function intermediateImagePaths(project) {
762
+ const out = [];
763
+ const push = (value) => {
764
+ if (typeof value === "string" && value !== "")
765
+ out.push(value);
766
+ };
767
+ for (const key of DIRECTION_KEYS) {
768
+ push(project.images[key]?.file);
769
+ const node = project.frames[key];
770
+ for (const file of node?.frames ?? [])
771
+ push(file);
772
+ for (const file of node?.keyed ?? [])
773
+ push(file);
774
+ for (const file of node?.candidates?.frames ?? [])
775
+ push(file);
776
+ push(node?.strip);
777
+ push(node?.candidates?.strip);
778
+ }
779
+ push(project.turn?.frames?.strip);
780
+ for (const file of project.turn?.frames?.frames ?? [])
781
+ push(file);
782
+ push(project.sheet?.file);
783
+ push(project.sheet?.thumb);
784
+ return [...new Set(out)];
785
+ }
786
+ /**
787
+ * 把所有中间图片打成一个 zip,落在 `out/` 下(静态资源路由可直接下载)。
788
+ *
789
+ * 为什么是 zip 而不是几十个下载链接:转圈模式的候选帧一抽就是 32~64 张,
790
+ * 一张一个按钮既点不完也看不清。包里保留**项目内的相对路径**
791
+ * (`images/front.png`、`turn/frames/f00.png`、`frames/front/f00.png`…),
792
+ * 这样解压出来还能和项目目录对上号。
793
+ */
794
+ export async function exportImages(projectId) {
795
+ const project = await readProject(projectId);
796
+ if (project === undefined)
797
+ throw new Error(`项目不存在:${projectId}`);
798
+ const wanted = intermediateImagePaths(project);
799
+ if (wanted.length === 0) {
800
+ throw new Error("还没有任何图片可保存:先在阶段①出绿幕图,或在阶段③抽取序列帧");
801
+ }
802
+ const entries = [];
803
+ let bytes = 0;
804
+ let skipped = 0;
805
+ for (const relative of wanted) {
806
+ try {
807
+ const data = await readFile(assetPath(projectId, relative));
808
+ entries.push({ path: relative, data });
809
+ bytes += data.length;
810
+ }
811
+ catch {
812
+ // 单张读不到不该让整包失败(可能是手删过的旧记录):跳过并如实报数。
813
+ skipped++;
814
+ }
815
+ }
816
+ if (entries.length === 0)
817
+ throw new Error("这些图片文件都不在了,请重新生成或重新抽帧");
818
+ const zip = zipEntries(entries);
819
+ const relative = `out/${safeFileStem(project.name, project.id)}-images.zip`;
820
+ await mkdir(dirname(assetPath(projectId, relative)), { recursive: true });
821
+ await writeFile(assetPath(projectId, relative), zip);
822
+ await patchProject(projectId, (current) => {
823
+ log(current, "info", `已打包 ${entries.length} 张图片(${(zip.length / 1024 / 1024).toFixed(1)} MB)${skipped > 0 ? `,${skipped} 张读不到已跳过` : ""}`);
824
+ });
825
+ return { file: relative, count: entries.length, skipped, bytes };
826
+ }
645
827
  // ── 阶段 2:八段视频 ──────────────────────────────────────────────────────
646
828
  export function startVideos(projectId, keys) {
647
829
  const started = kick(projectId, "videos:submit", "提交视频任务", async () => {
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,
@@ -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
  // 重新读一次:生图可能耗时很久,期间任务可能已经被改过。
@@ -2406,26 +2408,26 @@ export async function generateSheet(jobId) {
2406
2408
  if (job === undefined)
2407
2409
  throw new Error(`任务不存在:${jobId}`);
2408
2410
  const config = await loadConfig();
2409
- if (config.arkApiKey.trim() === "")
2410
- throw new Error("尚未配置火山方舟 API Key");
2411
+ assertImageProviderReady(config);
2411
2412
  if (job.source === undefined)
2412
2413
  throw new Error("还没有角色参考图,请先上传一张整图");
2413
2414
  const prompt = buildSheetRequest(job);
2414
- 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;
2415
2419
  job.sheet = { ...job.sheet, status: "running", error: undefined };
2416
- appendJobLog(job.log, "info", `开始拆件生图(模型 ${config.arkModel})`);
2420
+ appendJobLog(job.log, "info", `开始拆件生图(模型 ${model})`);
2417
2421
  await writeRigJob(job);
2418
2422
  try {
2419
2423
  const reference = await toDataUri(rigAssetPath(jobId, job.source.file), mimeOf(job.source.file));
2420
- const result = await generateImage({
2421
- baseUrl: config.arkBaseUrl,
2422
- apiKey: config.arkApiKey,
2423
- model: config.arkModel,
2424
+ const result = await generateImageWithProvider({
2424
2425
  prompt,
2425
2426
  images: [reference],
2426
- size: job.settings.size || config.arkSize,
2427
- watermark: job.settings.watermark,
2428
- timeoutMs: config.arkTimeoutMs
2427
+ size: job.settings.size || imageSizeOf(config),
2428
+ // 与图片生成那条路同口径:全局设置或任务上的旧覆盖位,任一为真就带水印。
2429
+ watermark: imageWatermarkOf(config) || job.settings.watermark === true,
2430
+ timeoutMs: imageTimeoutOf(config)
2429
2431
  });
2430
2432
  const relative = `sheet/parts-sheet.${result.ext}`;
2431
2433
  await mkdir(join(rigJobDir(jobId), "sheet"), { recursive: true });
package/lib/store.js CHANGED
@@ -233,8 +233,15 @@ function normalizeProject(raw) {
233
233
  const videos = emptyVideos();
234
234
  for (const key of DIRECTION_KEYS) {
235
235
  const node = raw?.videos?.[key];
236
- if (node !== undefined)
237
- videos[key] = { ...videos[key], ...node, approved: node.approved === true };
236
+ if (node !== undefined) {
237
+ videos[key] = {
238
+ ...videos[key],
239
+ ...node,
240
+ approved: node.approved === true,
241
+ origin: node.origin === "local" ? "local" : undefined,
242
+ originalName: typeof node.originalName === "string" ? node.originalName : undefined
243
+ };
244
+ }
238
245
  }
239
246
  const frames = emptyFrames();
240
247
  for (const key of DIRECTION_KEYS) {
@@ -359,7 +366,9 @@ function normalizeTurn(raw, frameCount) {
359
366
  error: typeof raw?.video?.error === "string" ? raw.video.error : undefined,
360
367
  firstFrame: typeof raw?.video?.firstFrame === "string" ? raw.video.firstFrame : undefined,
361
368
  elapsedMs: typeof raw?.video?.elapsedMs === "number" ? raw.video.elapsedMs : undefined,
362
- updatedAt: typeof raw?.video?.updatedAt === "number" ? raw.video.updatedAt : undefined
369
+ updatedAt: typeof raw?.video?.updatedAt === "number" ? raw.video.updatedAt : undefined,
370
+ origin: raw?.video?.origin === "local" ? "local" : undefined,
371
+ originalName: typeof raw?.video?.originalName === "string" ? raw.video.originalName : undefined
363
372
  },
364
373
  frames: {
365
374
  status: (raw?.frames?.status ?? "empty"),
package/lib/tilegen.js CHANGED
@@ -31,7 +31,8 @@ import { existsSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs
31
31
  import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
32
32
  import { randomUUID } from "node:crypto";
33
33
  import { basename, join } from "node:path";
34
- import { generateImage, ArkError } from "./ark.js";
34
+ import { ArkError } from "./ark.js";
35
+ import { assertImageProviderReady, generateImageWithProvider, imageSizeOf, imageWatermarkOf } from "./imageprovider.js";
35
36
  import { loadConfig, tileJobsRoot } from "./config.js";
36
37
  import { messageOf, readJson, writeJsonAtomic, appendJobLog, sweepTempFiles } from "./jsonio.js";
37
38
  import { DEFAULT_SETTINGS, assertSettings, decorAnchorY, diamondHeight, measureGroundDiamond, measurementLooksSane, regularizeBuilding, regularizeDecorSprite, regularizeToCell, renderBuildingTemplate, renderTemplate, upscale } from "./tilegeom.js";
@@ -672,8 +673,7 @@ export async function runGenerateStage(projectId, options = {}) {
672
673
  if (project === undefined)
673
674
  throw new Error(`项目不存在:${projectId}`);
674
675
  const config = await loadConfig();
675
- if (config.arkApiKey.trim() === "")
676
- throw new Error("尚未配置火山方舟 API Key(设置 → 游戏素材大师)");
676
+ assertImageProviderReady(config);
677
677
  const selected = options.key !== undefined
678
678
  ? project.items.filter((item) => item.key === options.key)
679
679
  : options.keys !== undefined && options.keys.length > 0
@@ -773,15 +773,11 @@ async function generateOne(project, item, variantIndex, ctx) {
773
773
  images.push(await dataUri(existsSync(file) ? file : ctx.templateCell));
774
774
  }
775
775
  const prompt = buildTilePrompt(item, project.style);
776
- const result = await generateImage({
777
- baseUrl: config.arkBaseUrl,
778
- apiKey: config.arkApiKey,
779
- model: config.arkModel,
776
+ const result = await generateImageWithProvider({
780
777
  prompt,
781
778
  images,
782
- size: config.arkSize,
783
- watermark: config.arkWatermark,
784
- timeoutMs: config.arkTimeoutMs
779
+ size: imageSizeOf(config),
780
+ watermark: imageWatermarkOf(config)
785
781
  });
786
782
  const ext = sniffImageExt(result.bytes);
787
783
  // ⚠️ 存进 project.json 的相对路径一律用 `/`,**不能用 `join()`**。