dsh-game-material-master 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/store.js ADDED
@@ -0,0 +1,309 @@
1
+ /**
2
+ * 项目持久化。
3
+ *
4
+ * 每个项目一个目录:`${DSH_HOME}/game-material-master/projects/<id>/`
5
+ *
6
+ * project.json 项目状态(本文件的 Project 结构)
7
+ * source/ 用户上传的源图
8
+ * images/<方向>.png 八张绿幕图
9
+ * videos/<方向>.mp4 八段视频
10
+ * frames/<方向>/*.png 抽出来的原始绿幕帧
11
+ * keyed/<方向>/*.png 抠完绿幕的帧
12
+ * preview/<方向>.png 方向预览带(帧横向拼接)
13
+ * out/sheet.png 最终整图
14
+ */
15
+ import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
16
+ import { join, resolve, sep } from "node:path";
17
+ import { randomUUID } from "node:crypto";
18
+ import { DEFAULT_VIDEO_PROMPT, DIRECTION_KEYS, DEFAULT_ROW_ORDER, defaultImagePrompts } from "./directions.js";
19
+ import { DEFAULT_CONFIG, ROW_ORDER_VERSION, isLegacyRowOrder, loadConfig, projectsRoot } from "./config.js";
20
+ /** 每个项目一条读-改-写串行链,见 patchProject。 */
21
+ const locks = new Map();
22
+ export function projectDir(id) {
23
+ return join(projectsRoot(), id);
24
+ }
25
+ export function projectFile(id) {
26
+ return join(projectDir(id), "project.json");
27
+ }
28
+ /** 把项目内的相对路径解析成绝对路径,并挡住目录穿越。 */
29
+ export function assetPath(id, relative) {
30
+ const base = resolve(projectDir(id));
31
+ const target = resolve(base, relative);
32
+ if (target !== base && !target.startsWith(base + sep)) {
33
+ throw new Error(`非法的项目内路径:${relative}`);
34
+ }
35
+ return target;
36
+ }
37
+ export function settingsFromConfig(config, rowOrder) {
38
+ return {
39
+ cellWidth: config.cellWidth,
40
+ cellHeight: config.cellHeight,
41
+ frameCount: config.frameCount,
42
+ fitMode: config.fitMode,
43
+ workingLongEdge: config.workingLongEdge,
44
+ pixelSize: config.pixelSize,
45
+ autoCrop: config.autoCrop,
46
+ fillRatio: config.fillRatio,
47
+ bottomMargin: config.bottomMargin,
48
+ cropInset: config.cropInset,
49
+ keyLow: config.keyLow,
50
+ keyHigh: config.keyHigh,
51
+ despill: config.despill,
52
+ bgTolerance: config.bgTolerance,
53
+ edgeShrink: config.edgeShrink,
54
+ rowOrder: rowOrder ?? (config.rowOrder.length > 0 ? [...config.rowOrder] : [...DEFAULT_ROW_ORDER]),
55
+ rowOrderVersion: ROW_ORDER_VERSION,
56
+ concurrency: config.concurrency
57
+ };
58
+ }
59
+ function emptyImages() {
60
+ const out = {};
61
+ for (const key of DIRECTION_KEYS)
62
+ out[key] = { status: "empty", approved: false };
63
+ return out;
64
+ }
65
+ function emptyVideos() {
66
+ const out = {};
67
+ for (const key of DIRECTION_KEYS)
68
+ out[key] = { status: "empty", approved: false };
69
+ return out;
70
+ }
71
+ function emptyFrames() {
72
+ const out = {};
73
+ for (const key of DIRECTION_KEYS)
74
+ out[key] = { status: "empty", frames: [], keyed: [], approved: false };
75
+ return out;
76
+ }
77
+ export async function ensureLayout(id) {
78
+ const base = projectDir(id);
79
+ for (const sub of ["source", "images", "videos", "frames", "keyed", "preview", "out"]) {
80
+ await mkdir(join(base, sub), { recursive: true });
81
+ }
82
+ }
83
+ export async function createProject(name) {
84
+ const config = await loadConfig();
85
+ const id = `p${Date.now().toString(36)}${randomUUID().slice(0, 6)}`;
86
+ const now = Date.now();
87
+ const project = {
88
+ id,
89
+ name: name.trim() === "" ? "未命名项目" : name.trim(),
90
+ createdAt: now,
91
+ updatedAt: now,
92
+ source: null,
93
+ prompts: {
94
+ images: defaultImagePrompts(),
95
+ video: DEFAULT_VIDEO_PROMPT,
96
+ videoPerDirection: {},
97
+ suffix: ""
98
+ },
99
+ images: emptyImages(),
100
+ videos: emptyVideos(),
101
+ frames: emptyFrames(),
102
+ sheet: { status: "empty", approved: false },
103
+ settings: settingsFromConfig(config),
104
+ log: []
105
+ };
106
+ await ensureLayout(id);
107
+ await writeProject(project);
108
+ return project;
109
+ }
110
+ export async function readProject(id) {
111
+ try {
112
+ const text = await readFile(projectFile(id), "utf8");
113
+ return normalizeProject(JSON.parse(text));
114
+ }
115
+ catch {
116
+ return undefined;
117
+ }
118
+ }
119
+ export async function writeProject(project) {
120
+ project.updatedAt = Date.now();
121
+ const target = projectFile(project.id);
122
+ await mkdir(projectDir(project.id), { recursive: true });
123
+ const tmp = `${target}.tmp`;
124
+ await writeFile(tmp, `${JSON.stringify(project, null, 2)}\n`, "utf8");
125
+ await rename(tmp, target);
126
+ }
127
+ export async function deleteProject(id) {
128
+ await rm(projectDir(id), { recursive: true, force: true });
129
+ }
130
+ /**
131
+ * 串行化同一项目的「读-改-写」。
132
+ * mutator 必须是短操作且不要发网络请求——真正耗时的调用要放在锁外,
133
+ * 只把状态变更包进这里,否则并发任务会互相排队。
134
+ */
135
+ export function patchProject(id, mutator) {
136
+ const previous = locks.get(id) ?? Promise.resolve();
137
+ const run = previous.then(async () => {
138
+ const project = await readProject(id);
139
+ if (project === undefined)
140
+ throw new Error(`项目不存在:${id}`);
141
+ const result = await mutator(project);
142
+ await writeProject(project);
143
+ return result;
144
+ });
145
+ locks.set(id, run.then(() => undefined, () => undefined));
146
+ return run;
147
+ }
148
+ export async function listProjects() {
149
+ let entries = [];
150
+ try {
151
+ const dirents = await readdir(projectsRoot(), { withFileTypes: true });
152
+ entries = dirents.filter((d) => d.isDirectory() && d.name.startsWith("p")).map((d) => d.name);
153
+ }
154
+ catch {
155
+ return [];
156
+ }
157
+ const summaries = [];
158
+ for (const id of entries) {
159
+ const project = await readProject(id);
160
+ if (project === undefined)
161
+ continue;
162
+ summaries.push(summarize(project));
163
+ }
164
+ summaries.sort((a, b) => b.updatedAt - a.updatedAt);
165
+ return summaries;
166
+ }
167
+ export function summarize(project) {
168
+ return {
169
+ id: project.id,
170
+ name: project.name,
171
+ createdAt: project.createdAt,
172
+ updatedAt: project.updatedAt,
173
+ hasSource: project.source !== null,
174
+ imageReady: DIRECTION_KEYS.filter((k) => project.images[k]?.status === "ready").length,
175
+ videoReady: DIRECTION_KEYS.filter((k) => project.videos[k]?.status === "ready").length,
176
+ framesReady: DIRECTION_KEYS.filter((k) => project.frames[k]?.status === "ready").length,
177
+ sheetReady: project.sheet.status === "ready"
178
+ };
179
+ }
180
+ /** 补齐历史版本缺字段,保证读进来的对象形状永远完整。 */
181
+ function normalizeProject(raw) {
182
+ const now = Date.now();
183
+ const settings = { ...(raw?.settings ?? {}) };
184
+ const defaults = settingsFromConfig(DEFAULT_CONFIG);
185
+ const merged = {
186
+ cellWidth: num(settings.cellWidth, defaults.cellWidth),
187
+ cellHeight: num(settings.cellHeight, defaults.cellHeight),
188
+ frameCount: num(settings.frameCount, defaults.frameCount),
189
+ fitMode: settings.fitMode === "stretch" ? "stretch" : "contain",
190
+ workingLongEdge: num(settings.workingLongEdge, defaults.workingLongEdge),
191
+ pixelSize: num(settings.pixelSize, defaults.pixelSize),
192
+ autoCrop: settings.autoCrop !== false,
193
+ fillRatio: num(settings.fillRatio, defaults.fillRatio),
194
+ bottomMargin: num(settings.bottomMargin, defaults.bottomMargin),
195
+ cropInset: num(settings.cropInset, defaults.cropInset),
196
+ keyLow: num(settings.keyLow, defaults.keyLow),
197
+ keyHigh: num(settings.keyHigh, defaults.keyHigh),
198
+ despill: num(settings.despill, defaults.despill),
199
+ bgTolerance: num(settings.bgTolerance, defaults.bgTolerance),
200
+ edgeShrink: num(settings.edgeShrink, defaults.edgeShrink),
201
+ rowOrder: Array.isArray(settings.rowOrder) && settings.rowOrder.length > 0 && !(settings.rowOrderVersion === undefined && isLegacyRowOrder(settings.rowOrder))
202
+ ? settings.rowOrder.map(String)
203
+ : [...DEFAULT_ROW_ORDER],
204
+ rowOrderVersion: ROW_ORDER_VERSION,
205
+ concurrency: num(settings.concurrency, defaults.concurrency)
206
+ };
207
+ const images = emptyImages();
208
+ for (const key of DIRECTION_KEYS) {
209
+ const node = raw?.images?.[key];
210
+ if (node !== undefined)
211
+ images[key] = { ...images[key], ...node, approved: node.approved === true };
212
+ }
213
+ const videos = emptyVideos();
214
+ for (const key of DIRECTION_KEYS) {
215
+ const node = raw?.videos?.[key];
216
+ if (node !== undefined)
217
+ videos[key] = { ...videos[key], ...node, approved: node.approved === true };
218
+ }
219
+ const frames = emptyFrames();
220
+ for (const key of DIRECTION_KEYS) {
221
+ const node = raw?.frames?.[key];
222
+ if (node !== undefined) {
223
+ frames[key] = {
224
+ ...frames[key],
225
+ ...node,
226
+ frames: Array.isArray(node.frames) ? node.frames.map(String) : [],
227
+ keyed: Array.isArray(node.keyed) ? node.keyed.map(String) : [],
228
+ approved: node.approved === true,
229
+ stale: node.stale === true
230
+ };
231
+ }
232
+ }
233
+ const defaultPrompts = defaultImagePrompts();
234
+ const images_prompts = {};
235
+ for (const key of DIRECTION_KEYS) {
236
+ const value = raw?.prompts?.images?.[key];
237
+ images_prompts[key] = typeof value === "string" && value.trim() !== "" ? value : defaultPrompts[key];
238
+ }
239
+ return {
240
+ id: String(raw?.id ?? ""),
241
+ name: typeof raw?.name === "string" && raw.name.trim() !== "" ? raw.name : "未命名项目",
242
+ createdAt: num(raw?.createdAt, now),
243
+ updatedAt: num(raw?.updatedAt, now),
244
+ source: raw?.source?.file ? { file: String(raw.source.file), name: String(raw.source.name ?? "source") } : null,
245
+ prompts: {
246
+ images: images_prompts,
247
+ video: typeof raw?.prompts?.video === "string" && raw.prompts.video.trim() !== "" ? raw.prompts.video : DEFAULT_VIDEO_PROMPT,
248
+ videoPerDirection: raw?.prompts?.videoPerDirection !== null && typeof raw?.prompts?.videoPerDirection === "object"
249
+ ? { ...raw.prompts.videoPerDirection }
250
+ : {},
251
+ suffix: typeof raw?.prompts?.suffix === "string" ? raw.prompts.suffix : ""
252
+ },
253
+ images,
254
+ videos,
255
+ frames,
256
+ sheet: {
257
+ status: raw?.sheet?.status ?? "empty",
258
+ file: raw?.sheet?.file,
259
+ thumb: raw?.sheet?.thumb,
260
+ approved: raw?.sheet?.approved === true,
261
+ error: raw?.sheet?.error,
262
+ width: raw?.sheet?.width,
263
+ height: raw?.sheet?.height,
264
+ generatedAt: raw?.sheet?.generatedAt,
265
+ rowOrder: Array.isArray(raw?.sheet?.rowOrder) ? raw.sheet.rowOrder.map(String) : undefined,
266
+ cellWidth: raw?.sheet?.cellWidth,
267
+ cellHeight: raw?.sheet?.cellHeight,
268
+ frameCount: raw?.sheet?.frameCount
269
+ },
270
+ settings: merged,
271
+ reviewMode: raw?.reviewMode === "manual" ? "manual" : raw?.reviewMode === "auto" ? "auto" : undefined,
272
+ log: Array.isArray(raw?.log) ? raw.log.slice(-200) : []
273
+ };
274
+ }
275
+ function num(value, fallback) {
276
+ const n = typeof value === "number" ? value : Number.parseFloat(String(value ?? ""));
277
+ return Number.isFinite(n) ? n : fallback;
278
+ }
279
+ /** 往项目日志里追加一条(最多保留 200 条)。 */
280
+ export function log(project, level, message) {
281
+ project.log.push({ at: Date.now(), level, message });
282
+ if (project.log.length > 200)
283
+ project.log.splice(0, project.log.length - 200);
284
+ }
285
+ /** 某个方向的参考图绝对路径列表(source 或其它方向的产出)。 */
286
+ export function referenceFiles(project, refs) {
287
+ const out = [];
288
+ for (const ref of refs) {
289
+ if (ref === "source") {
290
+ if (project.source !== null)
291
+ out.push(assetPath(project.id, project.source.file));
292
+ continue;
293
+ }
294
+ const node = project.images[ref];
295
+ if (node?.file !== undefined)
296
+ out.push(assetPath(project.id, node.file));
297
+ }
298
+ return out;
299
+ }
300
+ /** 项目目录是否真实存在。 */
301
+ export async function projectExists(id) {
302
+ try {
303
+ const info = await stat(projectDir(id));
304
+ return info.isDirectory();
305
+ }
306
+ catch {
307
+ return false;
308
+ }
309
+ }