dsh-game-material-master 0.2.1 → 0.4.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/tilegen.js ADDED
@@ -0,0 +1,1702 @@
1
+ /**
2
+ * 地图地块生成(模块五)· 数据层与流水线。
3
+ *
4
+ * 四个阶段:
5
+ * ① generate 生成地块 真实计费(每类 × 变体一次 Seedream 调用)
6
+ * ② review 逐项验收 免费
7
+ * ③ map 拼成地图 本地 · 免费 · 可反复
8
+ * ④ export 导出 本地 · 免费
9
+ *
10
+ * **参考图(等距模板)不是阶段**:它是「占格形状」的纯函数,
11
+ * 在 ① 开始时由 `ensureTemplates` 自动准备(按形状 + 格子尺寸的指纹复用)。
12
+ * 详见该函数的注释。
13
+ *
14
+ * ## 磁盘布局
15
+ *
16
+ * ```
17
+ * $DSH_HOME/game-material-master/tile-jobs/<projectId>/
18
+ * project.json 唯一状态文件
19
+ * template/ 等距参考图(按形状自动出)+ .stamp.json(指纹)
20
+ * raw/ 原始生成结果(**保留**)
21
+ * cell/ 规整后的单元格地块
22
+ * decor/ 独立装饰图层
23
+ * map/ map.png + map.json
24
+ * export/ 导出包
25
+ * ```
26
+ *
27
+ * **为什么 raw/ 要保留**:规整参数(单元格尺寸等)改了以后可以零成本重跑规整,
28
+ * 不必重新花钱生成。这是本模块最实用的一条降本设计。
29
+ */
30
+ import { existsSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
31
+ import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
32
+ import { randomUUID } from "node:crypto";
33
+ import { basename, join } from "node:path";
34
+ import { generateImage, ArkError } from "./ark.js";
35
+ import { loadConfig, tileJobsRoot } from "./config.js";
36
+ import { messageOf, readJson, writeJsonAtomic, appendJobLog, sweepTempFiles } from "./jsonio.js";
37
+ import { DEFAULT_SETTINGS, assertSettings, decorAnchorY, diamondHeight, measureGroundDiamond, measurementLooksSane, regularizeBuilding, regularizeDecorSprite, regularizeToCell, renderBuildingTemplate, renderTemplate, upscale } from "./tilegeom.js";
38
+ import { assembleMap, cropBitmap, emptyMapState, measureAssemblyBounds, pickVariantIndex, shapeOfEntry } from "./tilemap.js";
39
+ import { decodeFile, encodeBitmap, pngSize, sniffImageExt } from "./tilemedia.js";
40
+ export const TILE_STAGES = ["generate", "review", "map", "export"];
41
+ export const TILE_INVALIDATION_ORDER = ["template", "generate", "review", "map", "export"];
42
+ /** 由「列 × 行」矩形造形状。 */
43
+ export function rectShape(cols, rows) {
44
+ const shape = [];
45
+ for (let r = 0; r < rows; r++) {
46
+ for (let c = 0; c < cols; c++)
47
+ shape.push([r, c]);
48
+ }
49
+ return shape;
50
+ }
51
+ /** 形状是否恰好是一个**实心矩形**(是的话返回 [列, 行],否则 undefined)。 */
52
+ export function rectOfShape(shape) {
53
+ if (shape.length === 0)
54
+ return undefined;
55
+ const rows = Math.max(...shape.map((p) => p[0])) + 1;
56
+ const cols = Math.max(...shape.map((p) => p[1])) + 1;
57
+ return shape.length === cols * rows ? [cols, rows] : undefined;
58
+ }
59
+ /**
60
+ * 取一个地块的形状 —— **兼容老的 `footprint`**。
61
+ *
62
+ * ⚠️ 迁移点只有这一个:只要都从这里取形状,老项目(只有 `footprint`)
63
+ * 就自动等价成矩形形状,不需要改数据文件。
64
+ */
65
+ export function shapeOf(item) {
66
+ if (Array.isArray(item.shape) && item.shape.length > 0) {
67
+ return item.shape.map((p) => [p[0], p[1]]);
68
+ }
69
+ const fp = item.footprint ?? [1, 1];
70
+ return rectShape(Math.max(1, fp[0]), Math.max(1, fp[1]));
71
+ }
72
+ /**
73
+ * 形状的**包围菱形半宽**(1× 像素)。
74
+ *
75
+ * ```
76
+ * 半宽 = ((max x − min x)·cellWidth/2 + cellWidth) / 2 // x = c − r
77
+ * ```
78
+ *
79
+ * ★ 与 `tilemap.shapeDiamondHalf`(拼图/裁剪用)**逐字相同** ——
80
+ * 三处口径必须一致,否则模板画的框和实际摆放的格子对不上。
81
+ *
82
+ * ⚠️ **真机踩过**:老公式是「列数 + 行数」那一类
83
+ * (`cellWidth·(Δdc + Δdr + 2)/4`)。它对**实心矩形**恰好等价
84
+ * (矩形里 `x` 的极差正好等于 `Δdc + Δdr`),但形状一旦**沿对角线走**
85
+ * (L 形、T 形…),`x = c − r` 会把两项**抵消**,真实极差**小于**行列之和。
86
+ * 实测 L 形(2×2 缺一格):老公式给半宽 64,真实只要 32 ——
87
+ * 蓝色立方体线框比洋红底面宽一倍多(底面/线框宽比 **0.373**,
88
+ * 矩形是 0.991),模型照着一个**过大的空框**去长高。
89
+ *
90
+ * 矩形下本式等价于 `(cols+rows)/2`,所以 2×2 模板逐字节不变。
91
+ */
92
+ export function shapeHalfWidth(shape, settings) {
93
+ if (shape.length === 0)
94
+ return settings.cellWidth / 2;
95
+ let minX = Infinity;
96
+ let maxX = -Infinity;
97
+ for (const [r, c] of shape) {
98
+ const x = c - r;
99
+ if (x < minX)
100
+ minX = x;
101
+ if (x > maxX)
102
+ maxX = x;
103
+ }
104
+ return ((maxX - minX) * (settings.cellWidth / 2) + settings.cellWidth) / 2;
105
+ }
106
+ /**
107
+ * 把(可能来自界面/老数据的)原始形状**规范化**。
108
+ *
109
+ * - 给 `shape`(格子集合)→ 去重、按行优先排序;
110
+ * - 只给 `footprint` → 转成矩形形状(老项目走这条);
111
+ * - 都没有 → 退回 `previous` 的形状;
112
+ * - 输入不合法(空集合、非数字)→ 退回 1×1。
113
+ *
114
+ * 形状**不限格子数**,但会做基本的合法性校验(非负、整数、有界去重)。
115
+ */
116
+ export function normalizeShape(raw, previous) {
117
+ const fromRaw = parseShape(raw?.shape);
118
+ if (fromRaw !== undefined)
119
+ return fromRaw;
120
+ const fp = parseFootprint(raw?.footprint);
121
+ if (fp !== undefined)
122
+ return rectShape(fp[0], fp[1]);
123
+ if (previous !== undefined)
124
+ return shapeOf(previous);
125
+ return [[0, 0]];
126
+ }
127
+ /** 解析格子集合;非法就返回 undefined(交给调用方回退)。 */
128
+ export function parseShape(value) {
129
+ if (!Array.isArray(value) || value.length === 0)
130
+ return undefined;
131
+ const seen = new Set();
132
+ const shape = [];
133
+ for (const entry of value) {
134
+ if (!Array.isArray(entry) || entry.length < 2)
135
+ return undefined;
136
+ const r = Number(entry[0]);
137
+ const c = Number(entry[1]);
138
+ if (!Number.isInteger(r) || !Number.isInteger(c) || r < 0 || c < 0)
139
+ return undefined;
140
+ const k = `${r},${c}`;
141
+ if (seen.has(k))
142
+ continue;
143
+ seen.add(k);
144
+ shape.push([r, c]);
145
+ }
146
+ if (shape.length === 0)
147
+ return undefined;
148
+ shape.sort((a, b) => (a[0] - b[0]) || (a[1] - b[1]));
149
+ return shape;
150
+ }
151
+ function parseFootprint(value) {
152
+ if (!Array.isArray(value) || value.length !== 2)
153
+ return undefined;
154
+ const cols = Math.trunc(Number(value[0]));
155
+ const rows = Math.trunc(Number(value[1]));
156
+ if (!Number.isFinite(cols) || !Number.isFinite(rows) || cols < 1 || rows < 1)
157
+ return undefined;
158
+ return [cols, rows];
159
+ }
160
+ /** 形状的**包围矩形** `[列, 行]`(给只认 `footprint` 的老路径用)。 */
161
+ export function boundingRectOf(shape) {
162
+ if (shape.length === 0)
163
+ return [1, 1];
164
+ let maxR = 0, maxC = 0;
165
+ for (const [r, c] of shape) {
166
+ if (r > maxR)
167
+ maxR = r;
168
+ if (c > maxC)
169
+ maxC = c;
170
+ }
171
+ return [maxC + 1, maxR + 1];
172
+ }
173
+ /** 形状的稳定字符串(比较用)。 */
174
+ export function shapeKey(shape) {
175
+ return shape.map(([r, c]) => `${r},${c}`).join(";");
176
+ }
177
+ // ── 默认地块清单 ──────────────────────────────────────────────────────────
178
+ /** 两类默认文案(中 / 英)。改一份必须改另一份(AGENTS.md 的硬约束)。 */
179
+ const STYLE_ZH = "像素画风的干净色块,色彩明快饱和,无噪点。";
180
+ const STYLE_EN = "Clean pixel-art color blocks, bright saturated colors, no noise.";
181
+ const ITEMS_ZH = [
182
+ { key: "grass", label: "草地", kind: "terrain", family: "grass", footprint: [1, 1], variantCount: 2, mode: "template",
183
+ content: "鲜绿色的短草地。均匀细密的草叶纹理,深浅绿色随机交错的斑块,整体明亮清新。" },
184
+ { key: "grass2", label: "草地(野趣)", kind: "terrain", family: "grass", footprint: [1, 1], variantCount: 1, mode: "template",
185
+ content: "鲜绿色草地,草叶稍长、夹杂少量浅黄绿色的干草与零星小白花,自然野趣。" },
186
+ { key: "dirt", label: "土地", kind: "terrain", family: "dirt", footprint: [1, 1], variantCount: 2, mode: "template",
187
+ content: "棕褐色的翻耕土地。细碎的土块与深浅不一的泥土颗粒,夹杂少量灰色小石子,温暖的土地色调。" },
188
+ { key: "dirt2", label: "土地(湿润)", kind: "terrain", family: "dirt", footprint: [1, 1], variantCount: 1, mode: "template",
189
+ content: "棕褐色土地。颜色更深、更湿润,有明显的小土垄与几颗小石子。" },
190
+ { key: "rock", label: "石块", kind: "terrain", family: "rock", footprint: [1, 1], variantCount: 2, mode: "template",
191
+ content: "灰白色的岩石地面。大小不一的灰色石块、碎石与浅色裂隙拼在一起,表面接近平坦只有很轻微的体积感,石块严格限制在菱形内部。" },
192
+ { key: "rock2", label: "石块(巨石)", kind: "terrain", family: "rock", footprint: [1, 1], variantCount: 1, mode: "template",
193
+ content: "灰白色岩石地面。以一块较大的灰色巨石为主体,周围散落几块小碎石,石块严格限制在菱形内部。" },
194
+ { key: "bush", label: "灌木", kind: "terrain", family: "bush", footprint: [1, 1], variantCount: 2, mode: "template",
195
+ content: "草地加灌木。地面是鲜绿色短草地;菱形中央偏后长着一丛圆润茂密的深绿色灌木,灌木高度约为菱形高度的二分之一,灌木底部落在菱形内部。" },
196
+ { key: "bush2", label: "灌木(矮丛)", kind: "terrain", family: "bush", footprint: [1, 1], variantCount: 1, mode: "template",
197
+ content: "草地加灌木。地面是鲜绿色短草地;菱形右前方长着一丛矮胖圆润的深绿色灌木,灌木高度约为菱形高度的三分之一。" },
198
+ { key: "bush3", label: "灌木(浆果)", kind: "terrain", family: "bush", footprint: [1, 1], variantCount: 1, mode: "template",
199
+ content: "草地加灌木。地面是鲜绿色短草地;菱形中央有一丛深绿色灌木,灌木上有少量浅绿色高光与几个红色小浆果。" },
200
+ { key: "tree", label: "阔叶树", kind: "decor", family: "tree", footprint: [1, 1], variantCount: 2, mode: "plain",
201
+ content: "一棵枝繁叶茂的阔叶树:棕色树干从底部直立向上,顶端是一整团圆润茂密的深绿色树冠,树冠比树干宽得多;能看到树冠的底面。" },
202
+ { key: "tree2", label: "阔叶树(蓬松)", kind: "decor", family: "tree", footprint: [1, 1], variantCount: 1, mode: "plain",
203
+ content: "一棵高大的阔叶树:粗短的棕色树干,顶部是蓬松的深绿色树冠,树冠由几团绿色圆球堆成,能看到树冠底面。" },
204
+ { key: "tree3", label: "松树", kind: "decor", family: "tree", footprint: [1, 1], variantCount: 1, mode: "plain",
205
+ content: "一棵松树:细直的棕色树干,上面是上尖下宽的深绿色圆锥形针叶树冠。" },
206
+ { key: "boulder", label: "巨石", kind: "decor", family: "boulder", footprint: [1, 1], variantCount: 1, mode: "plain",
207
+ content: "一块灰色的巨石,表面有棱角和轻微明暗,底部略平,落在画面中央。" },
208
+ { key: "building", label: "中世纪石屋", kind: "building", family: "building", footprint: [2, 2], variantCount: 1, mode: "grid2x2",
209
+ content: "一座中世纪风格的石头房屋:灰白色石墙、深蓝灰色石板尖顶屋顶、正面一扇木门和两扇小窗、墙角有深色木结构装饰。" }
210
+ ];
211
+ const ITEMS_EN = [
212
+ { key: "grass", label: "Grass", kind: "terrain", family: "grass", footprint: [1, 1], variantCount: 2, mode: "template",
213
+ content: "Bright green short grass. Even, fine grass-blade texture with randomly interleaved patches of light and dark green, fresh and bright overall." },
214
+ { key: "grass2", label: "Grass (wild)", kind: "terrain", family: "grass", footprint: [1, 1], variantCount: 1, mode: "template",
215
+ content: "Bright green grass with slightly longer blades, a few pale yellow-green dry strands and scattered tiny white flowers." },
216
+ { key: "dirt", label: "Dirt", kind: "terrain", family: "dirt", footprint: [1, 1], variantCount: 2, mode: "template",
217
+ content: "Brown tilled soil. Small clods and grains of earth in varying shades, with a few small grey pebbles; warm earthy tone." },
218
+ { key: "dirt2", label: "Dirt (damp)", kind: "terrain", family: "dirt", footprint: [1, 1], variantCount: 1, mode: "template",
219
+ content: "Brown soil, darker and damper, with visible small ridges and a few pebbles." },
220
+ { key: "rock", label: "Rock", kind: "terrain", family: "rock", footprint: [1, 1], variantCount: 2, mode: "template",
221
+ content: "Off-white rock ground. Grey stones and gravel of various sizes with pale cracks between them, nearly flat with only the slightest sense of volume; stones strictly inside the diamond." },
222
+ { key: "rock2", label: "Rock (boulder)", kind: "terrain", family: "rock", footprint: [1, 1], variantCount: 1, mode: "template",
223
+ content: "Off-white rock ground dominated by one large grey boulder with a few small stones scattered around it; stones strictly inside the diamond." },
224
+ { key: "bush", label: "Bush", kind: "terrain", family: "bush", footprint: [1, 1], variantCount: 2, mode: "template",
225
+ content: "Grass with a bush. Ground is bright green short grass; a rounded dense dark-green bush grows slightly behind the centre of the diamond, about half the diamond's height, with its base inside the diamond." },
226
+ { key: "bush2", label: "Bush (low)", kind: "terrain", family: "bush", footprint: [1, 1], variantCount: 1, mode: "template",
227
+ content: "Grass with a bush. Ground is bright green short grass; a squat rounded dark-green bush sits toward the front-right of the diamond, about a third of its height." },
228
+ { key: "bush3", label: "Bush (berries)", kind: "terrain", family: "bush", footprint: [1, 1], variantCount: 1, mode: "template",
229
+ content: "Grass with a bush. Ground is bright green short grass; a dark-green bush in the centre carries a few pale-green highlights and small red berries." },
230
+ { key: "tree", label: "Broadleaf tree", kind: "decor", family: "tree", footprint: [1, 1], variantCount: 2, mode: "plain",
231
+ content: "A leafy broadleaf tree: a brown trunk rising straight from the base, topped by one rounded dense dark-green crown much wider than the trunk; the underside of the crown is visible." },
232
+ { key: "tree2", label: "Broadleaf tree (fluffy)", kind: "decor", family: "tree", footprint: [1, 1], variantCount: 1, mode: "plain",
233
+ content: "A tall broadleaf tree: a short thick brown trunk with a fluffy dark-green crown built from several rounded clumps; the underside of the crown is visible." },
234
+ { key: "tree3", label: "Pine", kind: "decor", family: "tree", footprint: [1, 1], variantCount: 1, mode: "plain",
235
+ content: "A pine tree: a thin straight brown trunk with a dark-green conical crown, narrow at the top and wide at the bottom." },
236
+ { key: "boulder", label: "Boulder", kind: "decor", family: "boulder", footprint: [1, 1], variantCount: 1, mode: "plain",
237
+ content: "A large grey boulder with faceted surfaces and subtle shading, slightly flat at the bottom, resting in the centre of the frame." },
238
+ { key: "building", label: "Medieval stone house", kind: "building", family: "building", footprint: [2, 2], variantCount: 1, mode: "grid2x2",
239
+ content: "A medieval style stone house: off-white stone walls, a dark blue-grey slate pitched roof, a wooden door and two small windows on the front, dark timber framing at the corners." }
240
+ ];
241
+ /** 按界面语言取默认画风描述。 */
242
+ export function defaultTileStyle(lang) {
243
+ return lang === "en" ? STYLE_EN : STYLE_ZH;
244
+ }
245
+ /** 按界面语言取默认地块清单。 */
246
+ export function defaultTileItems(lang) {
247
+ const seeds = lang === "en" ? ITEMS_EN : ITEMS_ZH;
248
+ return seeds.map((seed) => ({ ...seed, footprint: [...seed.footprint], variants: [] }));
249
+ }
250
+ // ── 磁盘路径 ──────────────────────────────────────────────────────────────
251
+ export function tileProjectDir(id) {
252
+ return join(tileJobsRoot(), id);
253
+ }
254
+ export function tileProjectFile(id) {
255
+ return join(tileProjectDir(id), "project.json");
256
+ }
257
+ /** 项目内的相对路径 → 绝对路径(挡住目录穿越)。 */
258
+ export function tileAssetPath(id, relative) {
259
+ const base = tileProjectDir(id);
260
+ const target = join(base, relative);
261
+ if (!target.startsWith(base))
262
+ throw new Error(`非法的项目内路径:${relative}`);
263
+ return target;
264
+ }
265
+ export function isValidTileProjectId(id) {
266
+ return /^t[a-z0-9]{4,40}$/.test(id);
267
+ }
268
+ /** 模板与产物的子目录白名单(静态资源路由用)。 */
269
+ export const SERVABLE_TILE_DIRS = new Set(["template", "raw", "cell", "decor", "map", "export"]);
270
+ // ── 读 / 写 ───────────────────────────────────────────────────────────────
271
+ function freshStages() {
272
+ return {
273
+ generate: { status: "idle" },
274
+ review: { status: "idle" },
275
+ map: { status: "idle" },
276
+ export: { status: "idle" }
277
+ };
278
+ }
279
+ /**
280
+ * 读老项目时把已废弃的 `stages.template` 丢掉。
281
+ *
282
+ * 模板不再是阶段了,留着这个键会让界面/工具读到一条永远 idle 的幽灵阶段。
283
+ */
284
+ function dropLegacyTemplateStage(project) {
285
+ const stages = project.stages;
286
+ if ("template" in stages)
287
+ delete stages.template;
288
+ }
289
+ export async function createTileProject(name, options = {}) {
290
+ const settings = { ...DEFAULT_SETTINGS, ...(options.settings ?? {}) };
291
+ assertSettings(settings);
292
+ const id = `t${Date.now().toString(36)}${randomUUID().slice(0, 6)}`;
293
+ const now = new Date().toISOString();
294
+ const project = {
295
+ id,
296
+ name: name.trim() === "" ? "未命名地图" : name.trim(),
297
+ createdAt: now,
298
+ updatedAt: now,
299
+ style: options.style ?? defaultTileStyle(options.lang),
300
+ settings,
301
+ items: defaultTileItems(options.lang),
302
+ map: emptyMapState(14, 14, ""),
303
+ stages: freshStages(),
304
+ logs: []
305
+ };
306
+ await mkdir(tileProjectDir(id), { recursive: true });
307
+ for (const sub of ["template", "raw", "cell", "decor", "map", "export"]) {
308
+ await mkdir(join(tileProjectDir(id), sub), { recursive: true });
309
+ }
310
+ appendJobLog(project.logs, "info", `新建地图地块项目:${project.name}`);
311
+ await writeJsonAtomic(tileProjectFile(id), project);
312
+ return project;
313
+ }
314
+ export async function readTileProject(id, lang) {
315
+ const raw = await readJson(tileProjectFile(id));
316
+ if (raw === undefined || typeof raw !== "object")
317
+ return undefined;
318
+ // 顺手清掉写失败留下的 `project.json.<uuid>.tmp`(进程被杀时来不及自己删)。
319
+ // 不 await:它是清理工作,不该拖慢读项目。
320
+ void sweepTempFiles(tileProjectDir(id));
321
+ // 兼容性:老项目缺字段时补默认值,而不是让界面崩在 `undefined.x` 上
322
+ const project = {
323
+ ...raw,
324
+ settings: { ...DEFAULT_SETTINGS, ...(raw.settings ?? {}) },
325
+ items: Array.isArray(raw.items) ? raw.items : defaultTileItems(lang),
326
+ map: raw.map ?? emptyMapState(14, 14, ""),
327
+ stages: { ...freshStages(), ...(raw.stages ?? {}) },
328
+ logs: Array.isArray(raw.logs) ? raw.logs : [],
329
+ style: typeof raw.style === "string" && raw.style !== "" ? raw.style : defaultTileStyle(lang)
330
+ };
331
+ // `template` 已经不是一个阶段了 —— 老项目里那条记录要丢掉
332
+ dropLegacyTemplateStage(project);
333
+ return project;
334
+ }
335
+ export async function writeTileProject(project) {
336
+ project.updatedAt = new Date().toISOString();
337
+ await writeJsonAtomic(tileProjectFile(project.id), project);
338
+ }
339
+ /**
340
+ * 每个项目一条写队列。
341
+ *
342
+ * ⚠️ 少了它,「读 → 改 → 写」会互相踩:后台作业的 `report()` 每次写一次
343
+ * project.json,用户这时点「保存布局」也在写同一个文件,两个 rename 撞在一起
344
+ * 就报 `EPERM`(Windows),而且**用户那边表现为「保存总是失败」**。
345
+ * 更糟的是丢更新:A 读、B 读、A 写、B 写 —— A 的改动被 B 覆盖掉。
346
+ *
347
+ * 用 promise 链把同一个项目的写入串起来:后来的等前面的写完再读。
348
+ * 不同项目互不影响(各排各的队)。
349
+ */
350
+ const projectWriteQueue = new Map();
351
+ function enqueueProjectWrite(id, task) {
352
+ const previous = projectWriteQueue.get(id) ?? Promise.resolve();
353
+ // 前一个失败也要继续(用 catch 把错误吞在链上,真正结果由本次的 promise 给出)
354
+ const next = previous.catch(() => undefined).then(task);
355
+ projectWriteQueue.set(id, next.catch(() => undefined));
356
+ return next;
357
+ }
358
+ /** 读 → 改 → 写。同一个项目的多次调用会被串行化(见 enqueueProjectWrite)。 */
359
+ export async function patchTileProject(id, mutator) {
360
+ return enqueueProjectWrite(id, async () => {
361
+ const project = await readTileProject(id);
362
+ if (project === undefined)
363
+ throw new Error(`项目不存在:${id}`);
364
+ const result = mutator(project);
365
+ await writeTileProject(project);
366
+ return result;
367
+ });
368
+ }
369
+ export async function deleteTileProject(id) {
370
+ await rm(tileProjectDir(id), { recursive: true, force: true });
371
+ }
372
+ export function summarizeTileProject(project) {
373
+ let generated = 0;
374
+ let expected = 0;
375
+ let approved = 0;
376
+ for (const item of project.items) {
377
+ expected += Math.max(1, item.variantCount);
378
+ for (const variant of item.variants) {
379
+ if (variant.cell !== undefined)
380
+ generated++;
381
+ if (variant.approved === true)
382
+ approved++;
383
+ }
384
+ }
385
+ return {
386
+ id: project.id,
387
+ name: project.name,
388
+ updatedAt: project.updatedAt,
389
+ itemCount: project.items.length,
390
+ generatedCount: generated,
391
+ expectedCount: expected,
392
+ approvedCount: approved,
393
+ mapReady: project.map.png !== undefined
394
+ };
395
+ }
396
+ export async function listTileProjects() {
397
+ const dirents = await readdir(tileJobsRoot(), { withFileTypes: true }).catch(() => []);
398
+ const out = [];
399
+ for (const dirent of dirents) {
400
+ if (!dirent.isDirectory())
401
+ continue;
402
+ const project = await readTileProject(dirent.name);
403
+ if (project !== undefined)
404
+ out.push(summarizeTileProject(project));
405
+ }
406
+ out.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1));
407
+ return out;
408
+ }
409
+ // ── 提示词 ────────────────────────────────────────────────────────────────
410
+ /**
411
+ * 地形地块的固定前缀:**不许用户删,只能在其后追加**。
412
+ *
413
+ * 这套措辞是研究期反复调出来的,实测「模板填充」的菱形比例达标率 100%;
414
+ * 换成自由生成的提示词会掉到 0%(见研究报告第三章)。
415
+ */
416
+ export const TERRAIN_PREFIX = [
417
+ "参考图里那个洋红色菱形就是地块的确切形状与位置。请只把菱形内部填成下面的内容。",
418
+ "硬性要求:菱形的四个顶点、四条边、大小、位置必须与参考图完全一致;",
419
+ "不要改变或描画轮廓,不要加边框、描边、外发光、阴影、厚度、侧面墙、立体底座,",
420
+ "不要旋转、不要缩放、不要裁切、不要把菱形画成方块。",
421
+ "菱形之外的区域必须保持完全透明,不要出现任何其他元素、文字、数字、标记、水印。",
422
+ "输出正方形画布,画面里只有一个菱形。"
423
+ ].join("\n");
424
+ /**
425
+ * 独立装饰的前缀。
426
+ *
427
+ * 关键差异:**背景要「纯白色」而不是请求透明**。
428
+ * `background:"transparent"` 在火山方舟上要求「必须带且只带一张输入图」,
429
+ * 纯文生图传它会直接 400;而白底反而更好抠(边框众数色一定就是背景色)。
430
+ */
431
+ export const DECOR_PREFIX = "画一个斜45度等轴测(isometric)视角的游戏装饰物贴图,正交投影,观察者从画面下方看。" +
432
+ "正方形画布,装饰物居中,纯白色背景,画面里只有这一个东西:";
433
+ export const BUILDING_PREFIX = [
434
+ "参考图是一张斜45度等轴测(isometric)的建筑施工参考图。",
435
+ "图中:浅灰色的菱形是建筑的**地基**,洋红色线是地基的边界,",
436
+ "蓝色的线框是从地基四个角**垂直向上**拉出来的立方体,表示这栋建筑可以占据的空间。",
437
+ "请画一栋**立体的建筑**:",
438
+ "· 底面(建筑与地面的接触面)必须与浅灰色菱形地基完全重合,四个角对准洋红线,不要超出也不要缩小;",
439
+ "· 墙体从底面**垂直向上**立起来,屋顶盖在最上面,整体高度填满蓝色立方体线框(约为地基菱形高度的 1.5 倍);",
440
+ "· 能看见屋顶的两个斜面和朝向观众的两面墙 —— 这是等轴测视角,不是俯视图;",
441
+ "· 绝对不要把地基菱形涂成一块平铺的地面或地砖 —— 建筑要**有高度、有墙、有屋顶**。"
442
+ ].join("\n");
443
+ /** 组装一个地块的提示词。 */
444
+ /**
445
+ * 把占格形状写成**人话**,塞进建筑提示词。
446
+ *
447
+ * ⚠️ 为什么非写不可(真机实测):形状以前只用参考图里的洋红轮廓表达,
448
+ * 模型看到 L 形(缺一格)时把它理解成「一栋方楼中间有个天井」——
449
+ * 生成出来是一圈房间围着一个内院,底面**仍然填满整个包围菱形**
450
+ * (实测底面宽度 1921→611 对称收敛到一点,就是完整的 2×2 菱形)。
451
+ * 加上这句文字描述后模型才知道「有一格地不属于这栋楼」。
452
+ *
453
+ * ⚠️ 方位词只用**行列序号**,不用「左上 / 右上」:
454
+ * 等轴测视角下屏幕上的左右和格子的行列**不是一回事**,说「右上角」会让模型猜错。
455
+ * 同时明确「以参考图的洋红轮廓为准」——文字只是辅助,轮廓才是权威。
456
+ *
457
+ * 纯函数、不花钱;矩形不写(矩形本来就没歧义)。
458
+ */
459
+ export function describeShape(shape) {
460
+ if (shape.length === 0)
461
+ return undefined;
462
+ const rect = rectOfShape(shape);
463
+ const [cols, rows] = boundingRectOf(shape);
464
+ if (rect !== undefined) {
465
+ /**
466
+ * ★ 实心矩形**也要写一句**(内容不同:不提「哪格是空地」)。
467
+ *
468
+ * ⚠️ **等距投影下 `3×1` 与 `2×2` 是同一个形状**:两者半宽都是 `cellWidth`
469
+ * (`x = c − r` 的极差都是 2),格子在同一个包围菱形里排布。
470
+ * 实测两者的模板**逐字节相同** —— 光靠轮廓**永远区分不了**。
471
+ * 所以行列数只能由文字交代,否则模型不知道要盖多长。
472
+ */
473
+ return (`⚠️ 占地形状:地基是 ${cols}×${rows} 的等距菱形,**共 ${cols * rows} 格**` +
474
+ `(沿两条斜边分别 ${cols} 格、${rows} 格)。` +
475
+ `建筑的底面必须覆盖这个范围内的**全部 ${cols * rows} 格**,不要缩小成单格,也不要超出边界。`);
476
+ }
477
+ const missing = [];
478
+ const has = (r, c) => shape.some(([sr, sc]) => sr === r && sc === c);
479
+ for (let r = 0; r < rows; r++) {
480
+ for (let c = 0; c < cols; c++) {
481
+ if (!has(r, c))
482
+ missing.push(`第 ${r + 1} 行第 ${c + 1} 列`);
483
+ }
484
+ }
485
+ return (`⚠️ 占地形状:地基区域是 ${cols}×${rows} 格、共 ${cols * rows} 格,但**这栋建筑只占其中 ${shape.length} 格**,` +
486
+ `${missing.join("、")}那${missing.length > 1 ? "几" : ""}格是空地,不属于建筑。` +
487
+ `参考图上那几格没有洋红轮廓、是透空的,成品里也必须完全透明。` +
488
+ `不要把空地当成天井或内院围起来 —— 建筑的墙要沿着**洋红轮廓**拐进去,` +
489
+ `底面必须与洋红轮廓逐格重合(以参考图的洋红轮廓为准)。`);
490
+ }
491
+ export function buildTilePrompt(item, style) {
492
+ const tail = style.trim() === "" ? "" : ` ${style.trim()}`;
493
+ if (item.kind === "decor" || item.mode === "plain") {
494
+ return `${DECOR_PREFIX}${item.content}${tail}`;
495
+ }
496
+ if (item.mode === "grid2x2" || item.kind === "building") {
497
+ const shapeNote = describeShape(shapeOf(item));
498
+ return [
499
+ BUILDING_PREFIX,
500
+ item.content,
501
+ ...(shapeNote === undefined ? [] : [shapeNote]),
502
+ "再次强调:底面 = 浅灰菱形地基,建筑往上长高,不要把它画成平铺的地面。",
503
+ "请把参考图里的洋红线、蓝线、浅灰地基**全部覆盖掉**,成品里不要保留任何参考线条。",
504
+ "线框之外的区域完全透明。",
505
+ "像素画风,色彩明快饱和,干净色块,无文字、无数字、无边框、无投影。"
506
+ ].join("\n");
507
+ }
508
+ return `${TERRAIN_PREFIX}\n\n内容:${item.content}${tail}`;
509
+ }
510
+ const jobs = new Map();
511
+ const cancelled = new Set();
512
+ export function currentTileJob(projectId) {
513
+ return jobs.get(projectId);
514
+ }
515
+ export function cancelTileJob(projectId) {
516
+ cancelled.add(projectId);
517
+ }
518
+ /**
519
+ * 有没有任务在跑。
520
+ *
521
+ * 判据是 `running !== null` —— 作业跑完之后记录**保留**(界面要用 `done` / `error`
522
+ * 显示最终状态),所以不能按「表里有没有记录」来判断在跑。
523
+ */
524
+ export function tileBusy(projectId) {
525
+ const job = jobs.get(projectId);
526
+ return job !== undefined && job.running !== null;
527
+ }
528
+ // ── 参考图(内部步骤,本地免费;不是用户阶段)──────────────────────────────
529
+ /**
530
+ * 某个形状对应的模板文件名(相对 `template/`)。
531
+ *
532
+ * 命名规则:
533
+ * - 单格 → `cell.png`(沿用老名字,老项目与界面预览都认它);
534
+ * - **实心矩形** → `grid{C}x{R}.png`(2×2 正好是 `grid2x2.png`,与老文件名逐字一致,
535
+ * 所以老项目不用重跑模板);
536
+ * - **非矩形**(L 形 / T 形 / 十字…)→ `shape-{格子集合}.png`,
537
+ * 例如 L 形是 `shape-0-0_1-0_1-1.png`、T 形是 `shape-0-0_0-1_0-2_1-1.png`。
538
+ *
539
+ * ⚠️ 非矩形**不能**按包围矩形命名。L 形与 2×2 的包围矩形都是 2×2,
540
+ * 两者会撞同一个 `grid2x2.png` —— 先渲染的那张被后渲染的覆盖,
541
+ * 于是其中一个形状拿到**别人的**参考图,模型照着画出来的底面就是错的。
542
+ * 用形状本身做名字才能保证「一种形状一张图」。
543
+ */
544
+ export function templateNameFor(shape) {
545
+ const [cols, rows] = boundingRectOf(shape);
546
+ if (cols === 1 && rows === 1)
547
+ return "cell.png";
548
+ if (rectOfShape(shape) !== undefined)
549
+ return `grid${cols}x${rows}.png`;
550
+ // ⚠️ 先排序再拼名字:形状是**集合**,同一个形状用不同顺序传进来
551
+ // (界面按行优先排、手工写的可能是别的顺序)必须解析到**同一个**文件名,
552
+ // 否则同一种形状会被渲染两遍、还白占一个文件名。
553
+ const key = [...shape]
554
+ .sort((a, b) => (a[0] - b[0]) || (a[1] - b[1]))
555
+ .map(([r, c]) => `${r}-${c}`)
556
+ .join("_");
557
+ return `shape-${key}.png`;
558
+ }
559
+ /**
560
+ * 保证 `template/` 里的模板与**当前形状 + 格子尺寸**一致。
561
+ *
562
+ * ★ 模板不再是一个要用户手动跑的阶段 —— 「生成地块」开始时会自己调这里。
563
+ *
564
+ * 为什么仍落到磁盘而不是每次现渲染:一次渲染 120~390ms、约 14MB。
565
+ * 十几次变体每次现渲染就是几十秒白等。所以按「形状集合 + 格子尺寸」算一个指纹,
566
+ * 指纹没变就直接复用;变了(改了形状或格子尺寸)才重渲染,
567
+ * 并删掉**上一版留下、这一版不再需要的**文件(否则界面会列出过期的模板)。
568
+ *
569
+ * 返回这次真渲染出来的文件名;什么都没变就是空数组。
570
+ */
571
+ export async function ensureTemplates(project) {
572
+ assertSettings(project.settings);
573
+ const want = collectBuildingShapes(project);
574
+ const wantAll = ["cell.png", ...[...want.keys()].filter((n) => n !== "cell.png")].sort();
575
+ const stamp = templateStamp(project, wantAll);
576
+ const dir = join(tileProjectDir(project.id), "template");
577
+ const stampFile = join(dir, ".stamp.json");
578
+ const previous = (() => {
579
+ try {
580
+ return JSON.parse(readFileSync(stampFile, "utf8"));
581
+ }
582
+ catch {
583
+ return undefined;
584
+ }
585
+ })();
586
+ const present = (() => {
587
+ try {
588
+ return readdirSync(dir).filter((n) => n.endsWith(".png")).sort();
589
+ }
590
+ catch {
591
+ return [];
592
+ }
593
+ })();
594
+ // 指纹一致、文件一个不少 → 直接复用
595
+ if (previous?.stamp === stamp && wantAll.every((n) => present.includes(n)))
596
+ return [];
597
+ await mkdir(dir, { recursive: true });
598
+ const single = renderTemplate({ size: 2048, cols: 1, rows: 1 });
599
+ await writeFile(join(dir, "cell.png"), encodeBitmap(single.bitmap));
600
+ const rendered = ["cell.png"];
601
+ // 每种建筑形状一张:洋红**逐格轮廓**画底面 + 蓝色线框画「能长多高」。
602
+ // 不能用实心洋红菱形 —— 模型会把它当「把这块地填满」,
603
+ // 实测生成出来是一张平铺的菱形石板地面(没有墙和屋顶)。
604
+ for (const [name, shape] of want) {
605
+ if (name === "cell.png")
606
+ continue;
607
+ const grid = renderBuildingTemplate({ settings: project.settings, shape, size: 2048 });
608
+ await writeFile(join(dir, name), encodeBitmap(grid.bitmap));
609
+ rendered.push(name);
610
+ }
611
+ for (const name of present) {
612
+ if (wantAll.includes(name))
613
+ continue;
614
+ try {
615
+ await rm(join(dir, name), { force: true });
616
+ }
617
+ catch {
618
+ // 删不掉就留着,不影响正确性
619
+ }
620
+ }
621
+ await writeFile(stampFile, JSON.stringify({ stamp, files: wantAll }, null, 2));
622
+ return rendered;
623
+ }
624
+ /**
625
+ * 模板指纹:形状集合 + 格子尺寸 + **渲染器版本**。任一变化都要重渲染。
626
+ *
627
+ * ⚠️ 必须带上 `TEMPLATE_RENDER_VERSION`:指纹原来只算「形状 + 格子尺寸」,
628
+ * 于是**改了渲染代码也不会重渲染** —— 升级后用户一直看着旧模板,
629
+ * 以为修复没生效(实测踩过:加了逐格分格线之后 `ensureTemplates` 还是返回空数组、
630
+ * 磁盘上仍是旧图)。**改了 `renderBuildingTemplate` / `renderTemplate` 的绘制
631
+ * 就必须把这个版本号 +1。**
632
+ */
633
+ export const TEMPLATE_RENDER_VERSION = 2;
634
+ export function templateStamp(project, names) {
635
+ const s = [
636
+ `v${TEMPLATE_RENDER_VERSION}`,
637
+ `cell:${project.settings.cellWidth}x${project.settings.cellHeight}`,
638
+ ...[...names].sort()
639
+ ].join("|");
640
+ // FNV-1a,够用(不需要密码学强度)
641
+ let h = 0x811c9dc5;
642
+ for (let i = 0; i < s.length; i++) {
643
+ h ^= s.charCodeAt(i);
644
+ h = Math.imul(h, 0x01000193) >>> 0;
645
+ }
646
+ return `${h.toString(16)}-${s.length}`;
647
+ }
648
+ /** 项目里所有**建筑**地块的形状 → 模板名。同名(同形状)只留一个。 */
649
+ function collectBuildingShapes(project) {
650
+ const out = new Map();
651
+ for (const item of project.items) {
652
+ if (item.kind !== "building")
653
+ continue;
654
+ const shape = shapeOf(item);
655
+ const name = templateNameFor(shape);
656
+ if (!out.has(name))
657
+ out.set(name, shape);
658
+ }
659
+ return out;
660
+ }
661
+ /** 这个项目**应该**有哪些模板文件(纯函数;界面预览与自检都用它)。 */
662
+ export function expectedTemplateNames(project) {
663
+ const names = [...collectBuildingShapes(project).keys()];
664
+ if (!names.includes("cell.png"))
665
+ names.unshift("cell.png");
666
+ return names.sort();
667
+ }
668
+ export async function runGenerateStage(projectId, options = {}) {
669
+ if (tileBusy(projectId))
670
+ return { started: false, reason: "已有任务在跑" };
671
+ const project = await readTileProject(projectId);
672
+ if (project === undefined)
673
+ throw new Error(`项目不存在:${projectId}`);
674
+ const config = await loadConfig();
675
+ if (config.arkApiKey.trim() === "")
676
+ throw new Error("尚未配置火山方舟 API Key(设置 → 游戏素材大师)");
677
+ const selected = options.key !== undefined
678
+ ? project.items.filter((item) => item.key === options.key)
679
+ : options.keys !== undefined && options.keys.length > 0
680
+ ? project.items.filter((item) => options.keys.includes(item.key))
681
+ : project.items;
682
+ if (selected.length === 0)
683
+ throw new Error("没有匹配的地块条目");
684
+ const targets = [];
685
+ for (const item of selected) {
686
+ if (options.key !== undefined && options.variant !== undefined) {
687
+ targets.push(`${item.key}#v${options.variant + 1}`);
688
+ }
689
+ else {
690
+ const count = Math.max(1, item.variantCount);
691
+ for (let i = 0; i < count; i++)
692
+ targets.push(`${item.key}#v${i + 1}`);
693
+ }
694
+ }
695
+ void background(projectId, "generate", targets, async (job, report) => {
696
+ const dir = tileProjectDir(projectId);
697
+ await mkdir(join(dir, "raw"), { recursive: true });
698
+ await mkdir(join(dir, "cell"), { recursive: true });
699
+ await mkdir(join(dir, "decor"), { recursive: true });
700
+ // ★ 参考图在这里自动准备好(原来的「① 模板」那一步)。
701
+ // 形状或格子尺寸变了才重渲染,否则直接用上次那份(省十几秒)。
702
+ const rendered = await ensureTemplates(project);
703
+ if (rendered.length > 0) {
704
+ (job.logs ?? (job.logs = [])).push(`已按当前形状准备模板:${rendered.join("、")}(本地计算,免费)`);
705
+ }
706
+ const templateCell = join(dir, "template", "cell.png");
707
+ /** 建筑模板按**这个地块自己的形状**取(`grid{C}x{R}.png`)。 */
708
+ const templateForItem = (entry) => join(dir, "template", templateNameFor(shapeOf(entry)));
709
+ for (const target of targets) {
710
+ if (cancelled.has(projectId))
711
+ break;
712
+ const [key, variantTag] = target.split("#");
713
+ const variantIndex = Number.parseInt(variantTag.replace("v", ""), 10) - 1;
714
+ const item = project.items.find((entry) => entry.key === key);
715
+ if (item === undefined)
716
+ continue;
717
+ job.running = target;
718
+ await report();
719
+ try {
720
+ const outcome = await generateOne(project, item, variantIndex, {
721
+ templateCell, templateForItem, dir,
722
+ retried: options.retried === true
723
+ });
724
+ await patchTileProject(projectId, (fresh) => {
725
+ const freshItem = fresh.items.find((entry) => entry.key === key);
726
+ if (freshItem === undefined)
727
+ return;
728
+ freshItem.variants[variantIndex] = outcome;
729
+ freshItem.approved = undefined;
730
+ appendJobLog(fresh.logs, outcome.error === undefined ? "info" : "error", outcome.error === undefined
731
+ ? `生成 ${item.label} 第 ${variantIndex + 1} 张`
732
+ : `${item.label} 第 ${variantIndex + 1} 张失败:${outcome.error}`);
733
+ });
734
+ }
735
+ catch (error) {
736
+ const message = messageOf(error);
737
+ await patchTileProject(projectId, (fresh) => {
738
+ const freshItem = fresh.items.find((entry) => entry.key === key);
739
+ if (freshItem !== undefined) {
740
+ freshItem.variants[variantIndex] = { index: variantIndex, error: message };
741
+ }
742
+ appendJobLog(fresh.logs, "error", `${item.label} 第 ${variantIndex + 1} 张失败:${message}`);
743
+ });
744
+ }
745
+ job.done.push(target);
746
+ await report();
747
+ }
748
+ job.running = null;
749
+ }, async () => {
750
+ await patchTileProject(projectId, (fresh) => {
751
+ const allDone = fresh.items.every((item) => item.variants.length >= item.variantCount && item.variants.every((v) => v.cell !== undefined));
752
+ fresh.stages.generate = { status: allDone ? "done" : "idle", at: new Date().toISOString() };
753
+ fresh.stages.review = { status: "idle" };
754
+ invalidateFrom(fresh, "map");
755
+ });
756
+ });
757
+ return { started: true };
758
+ }
759
+ /**
760
+ * 生成一个变体:调 Ark → 规整 → 写盘。
761
+ *
762
+ * 规整失败(测量不可信)时回退到模板几何,并在报告里标注原因 ——
763
+ * 界面据此提示「请目视确认」,而不是静默给一个错的几何。
764
+ */
765
+ async function generateOne(project, item, variantIndex, ctx) {
766
+ const config = await loadConfig();
767
+ const images = [];
768
+ if (item.mode === "template")
769
+ images.push(await dataUri(ctx.templateCell));
770
+ if (item.mode === "grid2x2") {
771
+ // 按**这个地块的形状**取模板;文件不在就退回单格模板(不至于整块失败)。
772
+ const file = ctx.templateForItem(item);
773
+ images.push(await dataUri(existsSync(file) ? file : ctx.templateCell));
774
+ }
775
+ const prompt = buildTilePrompt(item, project.style);
776
+ const result = await generateImage({
777
+ baseUrl: config.arkBaseUrl,
778
+ apiKey: config.arkApiKey,
779
+ model: config.arkModel,
780
+ prompt,
781
+ images,
782
+ size: config.arkSize,
783
+ watermark: config.arkWatermark,
784
+ timeoutMs: config.arkTimeoutMs
785
+ });
786
+ const ext = sniffImageExt(result.bytes);
787
+ // ⚠️ 存进 project.json 的相对路径一律用 `/`,**不能用 `join()`**。
788
+ // `join` 在 Windows 上给的是 `cell\grass.v1.png`,而这个字符串会被直接拼进
789
+ // 资源路由的 URL(`${assetBase}${relative}`)—— 浏览器把反斜杠宽容地当分隔符,
790
+ // 所以本地看着正常,但在 POSIX 上文件名/URL 都对不上。
791
+ // 写盘用绝对路径(join(dir, …))不受影响。
792
+ const rawRelative = `raw/${item.key}.v${variantIndex + 1}.${ext}`;
793
+ await writeFile(tileAssetPath(project.id, rawRelative), result.bytes);
794
+ const decoded = await decodeFile(tileAssetPath(project.id, rawRelative));
795
+ const variant = { index: variantIndex, raw: rawRelative };
796
+ if (item.kind === "decor" || item.mode === "plain") {
797
+ const { bitmap, report } = regularizeDecorSprite(decoded, project.settings);
798
+ const cellRelative = `decor/${item.key}.v${variantIndex + 1}.png`;
799
+ await writeFile(tileAssetPath(project.id, cellRelative), encodeBitmap(bitmap));
800
+ variant.cell = cellRelative;
801
+ variant.report = { mode: "sprite", scale: [report.scale, report.scale], retried: ctx.retried };
802
+ return variant;
803
+ }
804
+ // 建筑:底面占 2×2 格、往上长高 —— 用专门的落位算法,不能走地形的「压进 1 格」
805
+ if (item.kind === "building" || item.mode === "grid2x2") {
806
+ const { bitmap, report } = regularizeBuilding(decoded, project.settings, {
807
+ cols: item.footprint[0],
808
+ rows: item.footprint[1],
809
+ mode: "measured"
810
+ });
811
+ const cellRelative = `cell/${item.key}.v${variantIndex + 1}.png`;
812
+ await writeFile(tileAssetPath(project.id, cellRelative), encodeBitmap(bitmap));
813
+ variant.cell = cellRelative;
814
+ // ⚠️ `baseFraction` 必须写进 variant —— 拼图阶段是**从磁盘重新读**贴图的,
815
+ // 那时候 `bitmap` 上挂的属性已经没了。少了它拼图会退化成「靠贴图底边猜」,
816
+ // 建筑就会整体错位(实测偏了一大截)。
817
+ variant.report = { ...report, baseFraction: bitmap.baseFraction, retried: ctx.retried };
818
+ return variant;
819
+ }
820
+ // 地形:测量 → 规整(不可信就回退模板几何)
821
+ const templateFile = ctx.templateCell;
822
+ const templateGeom = await templateGeometry(templateFile);
823
+ let measure;
824
+ let fallback;
825
+ /** 实测比例(即便不可信也记下来)—— 用来诊断「是不是模型把菱形画歪了」。 */
826
+ let measuredRatio;
827
+ try {
828
+ const candidate = measureGroundDiamond(decoded);
829
+ measuredRatio = candidate.ratio;
830
+ const reason = measurementLooksSane(decoded, candidate);
831
+ if (reason === undefined)
832
+ measure = candidate;
833
+ else
834
+ fallback = reason;
835
+ }
836
+ catch (error) {
837
+ fallback = messageOf(error);
838
+ }
839
+ const { bitmap, report } = measure !== undefined
840
+ ? regularizeToCell(decoded, project.settings, measure, "measured")
841
+ : regularizeToCell(decoded, project.settings, templateGeom, "template", fallback);
842
+ // 模型把菱形画变形时,给一条**可操作**的提示,而不是只丢一句测量失败。
843
+ // 实测 `doubao-seedream-4-0-*` 会把 2:1 菱形画成近正方形(比例 ≈ 1.06),
844
+ // 而且只输出 JPEG;换 5.0 系列立刻恢复(≈ 1.99)。这是这个模块最常踩的坑。
845
+ const offRatio = measuredRatio !== undefined && Math.abs(measuredRatio - 2) > 0.1;
846
+ const hint = fallback === undefined ? undefined
847
+ : offRatio
848
+ ? `模型没有画出 2:1 的等距菱形(实测 ${measuredRatio.toFixed(3)}),已按模板几何回退。请换用 Seedream 5.0 系列模型(4.0 会把菱形画成近正方形),或在「设置 → 游戏素材大师」里改模型后重跑这一张。`
849
+ : fallback;
850
+ const cellRelative = `cell/${item.key}.v${variantIndex + 1}.png`;
851
+ await writeFile(tileAssetPath(project.id, cellRelative), encodeBitmap(bitmap));
852
+ variant.cell = cellRelative;
853
+ variant.report = { ...report, ratioMeasured: report.ratioMeasured ?? measuredRatio, fallbackReason: hint, retried: ctx.retried };
854
+ return variant;
855
+ }
856
+ /** 从模板图里量出菱形几何(**不硬编码尺寸**)。 */
857
+ async function templateGeometry(file) {
858
+ const bitmap = await decodeFile(file);
859
+ // 模板是不透明的洋红菱形 + 透明背景 → 前景就是菱形本身
860
+ let left = bitmap.width;
861
+ let top = bitmap.height;
862
+ let right = -1;
863
+ let bottom = -1;
864
+ for (let y = 0; y < bitmap.height; y++) {
865
+ for (let x = 0; x < bitmap.width; x++) {
866
+ if (bitmap.rgba[(y * bitmap.width + x) * 4 + 3] < 128)
867
+ continue;
868
+ if (x < left)
869
+ left = x;
870
+ if (x > right)
871
+ right = x;
872
+ if (y < top)
873
+ top = y;
874
+ if (y > bottom)
875
+ bottom = y;
876
+ }
877
+ }
878
+ if (right < 0)
879
+ throw new Error(`模板 ${basename(file)} 里没有找到菱形`);
880
+ return {
881
+ centerX: (left + right + 1) / 2,
882
+ centerY: (top + bottom + 1) / 2,
883
+ halfWidth: (right - left + 1) / 2,
884
+ halfHeight: (bottom - top + 1) / 2
885
+ };
886
+ }
887
+ async function dataUri(file) {
888
+ const bytes = await readFile(file);
889
+ const ext = sniffImageExt(bytes);
890
+ const mime = ext === "jpg" ? "image/jpeg" : ext === "webp" ? "image/webp" : "image/png";
891
+ return `data:${mime};base64,${bytes.toString("base64")}`;
892
+ }
893
+ export async function runMapStage(projectId, options = {}) {
894
+ if (tileBusy(projectId))
895
+ return { started: false, reason: "已有任务在跑" };
896
+ const project = await readTileProject(projectId);
897
+ if (project === undefined)
898
+ throw new Error(`项目不存在:${projectId}`);
899
+ const lookup = new Map();
900
+ const families = {};
901
+ /** 每个**格子键**(`cells` 里写的那个)有哪些可用变体。 */
902
+ const byCellKey = {};
903
+ for (const item of project.items) {
904
+ const candidates = [];
905
+ for (const variant of item.variants) {
906
+ if (variant.cell === undefined)
907
+ continue;
908
+ const bitmap = await decodeFile(tileAssetPath(projectId, variant.cell));
909
+ // 建筑贴图的底面位置是**量出来的**,存在 report 里。这里把磁盘读回来的
910
+ // 位图重新挂上它,拼图才知道该对齐哪里(见 generateOne 里的注释)。
911
+ if (typeof variant.report?.baseFraction === "number") {
912
+ bitmap.baseFraction = variant.report.baseFraction;
913
+ }
914
+ lookup.set(`${item.key}#${variant.index}`, bitmap);
915
+ candidates.push(`${item.key}#${variant.index}`);
916
+ }
917
+ if (candidates.length > 0) {
918
+ families[item.family] = [...(families[item.family] ?? []), ...candidates];
919
+ byCellKey[item.key] = [...(byCellKey[item.key] ?? []), ...candidates];
920
+ }
921
+ }
922
+ if (lookup.size === 0)
923
+ throw new Error("还没有已通过的地块,请先在第 ③ 步生成并验收");
924
+ const rows = clampInt(options.rows ?? project.map.rows, project.map.rows, 1, 64);
925
+ const cols = clampInt(options.cols ?? project.map.cols, project.map.cols, 1, 64);
926
+ const seed = Number.isFinite(options.seed) ? Math.trunc(options.seed) : project.map.seed;
927
+ const fill = options.fill ?? "grass";
928
+ // 显式要的 fill 必须先校验存在:现在有「沿用已存布局」这条路径,
929
+ // 光靠后面按 cells 校验会漏掉「fill 本身就不存在」的情况
930
+ //(那种情况下用户以为会铺满 fill,实际铺的是旧布局)。
931
+ if (options.fill !== undefined && (families[options.fill] ?? []).length === 0) {
932
+ throw new Error(`没有可用的地块类别「${options.fill}」。可选:${Object.keys(families).filter((k) => families[k].length > 0).join("、")}`);
933
+ }
934
+ /**
935
+ * 要铺的那份状态。
936
+ *
937
+ * ⚠️ **必须优先沿用项目里存着的布局**(那是用户在「手动编辑布局」里一格一格涂出来的)。
938
+ * 之前只要传了任意一个覆盖参数(界面永远会传 `decorDensity`)就走
939
+ * `emptyMapState(rows, cols, fill)` —— **整份手改布局被丢掉**,重新铺出一张
940
+ * 纯 fill 的规则地图,而且不报任何错。
941
+ *
942
+ * ⚠️ 但 `hasSaved` 不能只看「网格非空」:新建项目的 `emptyMapState(14,14,"")`
943
+ * 就是一张 14×14 的**空字符串**网格,那也是「非空」。把它当成有布局,
944
+ * 就会去渲染一张 14×14 的空地图 —— 画布按 14×14 撑到 896×768、
945
+ * 实际一个像素都没画(实测:第一次铺图得到 896×768 的全透明图,
946
+ * 而 `map.pixel` 还是 (0,0),界面的可点格子与预览图完全对不上)。
947
+ * 判据必须是「**至少有一格填了东西**」。
948
+ */
949
+ const saved = project.map.cells;
950
+ const hasSaved = Array.isArray(saved) && saved.some((row) => Array.isArray(row) && row.some((cell) => cell !== "" && cell !== undefined));
951
+ const state = hasSaved
952
+ ? { ...project.map, rows, cols, seed, cells: resizeCells(saved, rows, cols, fill) }
953
+ : emptyMapState(rows, cols, fill, seed);
954
+ // 先定下「到底铺哪张图」:装饰与建筑都在这步决定(含它们占掉的格子)。
955
+ // 建筑会把占格的键**清空**,所以预校验必须查**这份**状态 —— 查原始 state
956
+ // 会看到建筑键(如 `building`)而去 `byCellKey` 里找它,但建筑根本没有
957
+ // 「按类别铺的地块」,于是误报「这些地块还没有已生成的图:building」。
958
+ // 实测:布局里放一栋建筑就再也拼不出图。
959
+ //
960
+ // 垫底用的地面:优先取布局里第一个真的存在的地面地块,退化到任意地形地块。
961
+ //
962
+ // ⚠️ 这里要的是**变体名**(`grass#0`)而不是地块键(`grass`)——
963
+ // `lookup` / `families` 里的键都是 `key#vN`。传裸键进去 `lookup.get()` 会是
964
+ // undefined,垫底静默不画(实测建筑脚下还是一块透明洞),而且不报任何错。
965
+ const groundItemKey = (byCellKey[fill] ?? []).length > 0
966
+ ? fill
967
+ : (Object.keys(byCellKey).find((k) => project.items.find((it) => it.key === k)?.kind === "terrain") ?? "");
968
+ const groundKey = groundItemKey === "" ? "" : (byCellKey[groundItemKey] ?? [])[0] ?? "";
969
+ // 还要把**地块键**也传进去:`cells` 里混进装饰/建筑键时要按它补默认地面
970
+ const decorated = decorateState(state, families, options.decorDensity ?? 0, project.items, groundKey, options.reroll === true, groundItemKey);
971
+ // 预校验:地图里引用的**格子键**必须真的有已生成的变体。
972
+ //
973
+ // ⚠️ 这里必须查 `byCellKey` 而不是 `families`。`families` 是按**类别**聚合的,
974
+ // 而 `cells` 里存的是**地块键** —— 两者只在这两套名字恰好相同时才一样。
975
+ // 实测踩过:`dirt2` 的类别是 `dirt`,查 `families["dirt2"]` 得 undefined,
976
+ // 于是「拼成地图」直接报「这些类别还没有已生成的地块:dirt2」,
977
+ // 而 `dirt2` 明明已经生成好了 —— 整个第 ④ 步直接不可用。
978
+ const missing = new Set();
979
+ for (const row of decorated.cells) {
980
+ for (const key of row) {
981
+ if (key === "" || key === undefined)
982
+ continue;
983
+ if ((byCellKey[key] ?? []).length === 0)
984
+ missing.add(key);
985
+ }
986
+ }
987
+ if (missing.size > 0) {
988
+ const available = Object.keys(byCellKey).join("、");
989
+ throw new Error(`这些地块还没有已生成的图:${[...missing].join("、")}。请先在第 ③ 步生成,或把它换成已有的地块(${available})。`);
990
+ }
991
+ void background(projectId, "map", ["map"], async (job, report) => {
992
+ const dir = tileProjectDir(projectId);
993
+ await mkdir(join(dir, "map"), { recursive: true });
994
+ job.running = "map";
995
+ await report();
996
+ const assembled = assembleMap(lookup, decorated, {
997
+ settings: project.settings,
998
+ // ⚠️ 这里必须传 `byCellKey`(**地块键** → 变体名),不是 `families`(**类别** → 变体名)。
999
+ //
1000
+ // `state.cells` 里存的是地块键(`rock2`),而 `assembleMap` 拿它直接查
1001
+ // `options.families[键]`。传按类别聚合的那份时,凡是「地块键 ≠ 类别名」的
1002
+ // 都会查不到、**整格静默跳过**,地图上留下一个个透明菱形洞。
1003
+ // 实测:`rock2` 的类别是 `rock`,于是 6 个 rock2 格全是洞 ——
1004
+ // 而预校验查的是 `byCellKey`、判定「有图」,所以**不报任何错**。
1005
+ families: byCellKey,
1006
+ background: options.background ?? [0, 0, 0, 0]
1007
+ });
1008
+ // ★ 裁剪与上报用**同一个矩形**(几何口径),这样界面的坐标换算必然成立。
1009
+ //
1010
+ // 以前是 `trimTransparent` 自己去量不透明像素、再把量到的 `left/top` 报给界面 ——
1011
+ // 界面算不出同一个值,两份数据一旦不同步就是「房子上移一格 /
1012
+ // 点到的格子和涂到的差一格」。现在两边共用 `measureAssemblyBounds`。
1013
+ const bounds = measureAssemblyBounds(lookup, decorated, { settings: project.settings, families: byCellKey });
1014
+ const trimmed = cropBitmap(assembled, bounds);
1015
+ // 交付尺寸放大 2 倍(最近邻,保持像素画硬边)
1016
+ const big = upscale(trimmed, 2);
1017
+ await writeFile(join(dir, "map", "map.png"), encodeBitmap(big));
1018
+ await writeFile(join(dir, "map", "map.json"), JSON.stringify({
1019
+ rows: decorated.rows,
1020
+ cols: decorated.cols,
1021
+ seed: decorated.seed,
1022
+ cells: decorated.cells,
1023
+ decor: decorated.decor,
1024
+ buildings: decorated.buildings,
1025
+ settings: project.settings,
1026
+ families
1027
+ }, null, 2));
1028
+ job.done.push("map");
1029
+ job.running = null;
1030
+ await report();
1031
+ await patchTileProject(projectId, (fresh) => {
1032
+ fresh.map = {
1033
+ ...decorated,
1034
+ png: "map/map.png",
1035
+ json: "map/map.json",
1036
+ // 记下成品的像素信息:界面叠可点格子时要用 left/top 对齐裁剪后的画布。
1037
+ //
1038
+ // ⚠️ 必须与上面 `cropBitmap` 用的是**同一个矩形**(`trimmed.left/top` 就是
1039
+ // 夹过之后的真值)。界面拿 `measureAssemblyBounds` 各算一遍也得到同一个值,
1040
+ // 所以不会出现「宿主的值是旧的、界面已经按新布局排好了」这种错位 ——
1041
+ // 那正是「房子上移一格 / 点到的格子和涂到的不是同一格」的来源。
1042
+ pixel: {
1043
+ width: big.width,
1044
+ height: big.height,
1045
+ left: trimmed.left * 2,
1046
+ top: trimmed.top * 2,
1047
+ scale: 2
1048
+ }
1049
+ };
1050
+ fresh.stages.map = { status: "done", at: new Date().toISOString() };
1051
+ invalidateFrom(fresh, "export");
1052
+ appendJobLog(fresh.logs, "info", `已拼图:${decorated.cols}×${decorated.rows}(本地计算,免费)`);
1053
+ });
1054
+ });
1055
+ return { started: true };
1056
+ }
1057
+ /**
1058
+ * 把存下来的布局裁剪 / 扩展到目标行列。
1059
+ *
1060
+ * 扩出来的格子用 `fill` 铺(用户改大行列时不会得到一片空格),
1061
+ * 裁掉的部分直接丢。这样做是为了「改行 / 列」不要连带丢掉整份手改布局。
1062
+ */
1063
+ function resizeCells(cells, rows, cols, fill) {
1064
+ const out = [];
1065
+ for (let r = 0; r < rows; r++) {
1066
+ const row = [];
1067
+ for (let c = 0; c < cols; c++) {
1068
+ row.push(cells[r]?.[c] ?? fill);
1069
+ }
1070
+ out.push(row);
1071
+ }
1072
+ return out;
1073
+ }
1074
+ /** 从 `families`(类别 → 变体名)里挑一个「像地面」的类别当兜底:优先 grass。 */
1075
+ function groundFillKey(families) {
1076
+ const keys = Object.keys(families).filter((k) => (families[k] ?? []).length > 0);
1077
+ if (keys.length === 0)
1078
+ return "";
1079
+ return keys.find((k) => k === "grass") ?? keys[0];
1080
+ }
1081
+ /**
1082
+ * 按装饰密度随机撒装饰、放置建筑 —— 用确定性 PRNG,保证同种子可复现。
1083
+ *
1084
+ * ⚠️ **已经存下来的布局是唯一真源,不能每次拼图都重随一遍。**
1085
+ * 以前这里无条件重撒装饰:同种子确实逐像素一致,但只要换个种子就整张变样,
1086
+ * 而且用户「开始编辑布局」时拿到的又是另一套 —— 看起来像在编辑别的图。
1087
+ * 现在只有「还没有装饰记录」或显式要求 `reroll` 时才撒。
1088
+ *
1089
+ * **建筑**:布局里写了某个建筑地块的键(例如 `building`)时,就把它的
1090
+ * 占格(如 2×2)铺在那个位置,并登记进 `out.buildings` 让拼图把立体贴图画上去。
1091
+ * 以前这里只撒装饰、从不放建筑 —— `buildings` 永远是空的,所以**建筑根本不会出现在地图上**。
1092
+ */
1093
+ function decorateState(state, families, density, items = [], groundKey = "",
1094
+ /** 重撒装饰(用户点了「换个种子重铺」)。默认沿用存下来的布局。 */
1095
+ reroll = false,
1096
+ /** 默认地面的**地块键**(`grass`)—— 补「cells 里混进装饰/建筑键」那些格子用。 */
1097
+ groundItemKey = "") {
1098
+ const out = {
1099
+ ...state,
1100
+ cells: state.cells.map((row) => [...row]),
1101
+ decor: { ...state.decor },
1102
+ buildings: []
1103
+ };
1104
+ // ── 建筑:按布局里出现的键放置 ──────────────────────────────────────────
1105
+ const buildingByKey = new Map(items.filter((it) => it.kind === "building" || it.mode === "grid2x2").map((it) => [it.key, it]));
1106
+ /** 被建筑占掉的格子(不再撒装饰)。 */
1107
+ const occupied = new Set();
1108
+ /**
1109
+ * 放置一栋建筑。
1110
+ *
1111
+ * ⚠️ 占格的键**不能留着建筑键** —— 留着的话 `assembleMap` 会把这些格子当成
1112
+ * 「地面地块」,再拿同一个建筑贴图当 1 格地面画 4 次,地图上多出一大块残影。
1113
+ *
1114
+ * ⚠️ 但也**不能清成空串**:空串等于这一格什么都不铺,建筑底面菱形的四个角
1115
+ * 是透明的,露出来的就是**一块纯色垫底**(`fillDiamondSolid` 填的平均色),
1116
+ * 和周围有纹理的草地格格不入 —— 看着像建筑拖着一块塑料板。
1117
+ * 所以这里把它换成**默认地面**:该铺的地面照铺,建筑贴图盖在上面。
1118
+ *
1119
+ * ⚠️ 换成地面之后**布局里就再也看不到这栋楼了**(键没了)。所以 `buildings` 与
1120
+ * `buildingGround` 必须作为「已放置」的记录一起存回去,重跑时先沿用它们;
1121
+ * 只看 `cells` 的话,第二次拼图时建筑的键已经被自己换掉了 —— 楼会凭空消失。
1122
+ *
1123
+ * `ground` 存的是**变体名**(`grass#0`)—— `lookup` 的键就是这个形状。
1124
+ */
1125
+ const place = (r, c, item, fw, fh, ground) => {
1126
+ const name = (families[item.family] ?? [])[0];
1127
+ if (name === undefined)
1128
+ return;
1129
+ // 同一个位置别放两次
1130
+ if (out.buildings.some((b) => b[0] === r && b[1] === c))
1131
+ return;
1132
+ out.buildings.push([r, c, name]);
1133
+ (out.buildingGround ??= []).push([r, c, fw, fh, ground]);
1134
+ // 占格铺回默认地面(地块键,不是变体名 —— `cells` 存的是地块键)
1135
+ const fillKey = groundItemKey !== "" ? groundItemKey : groundFillKey(families);
1136
+ for (let dr = 0; dr < fh; dr++) {
1137
+ for (let dc = 0; dc < fw; dc++) {
1138
+ occupied.add(`${r + dr},${c + dc}`);
1139
+ if (fillKey !== "")
1140
+ out.cells[r + dr][c + dc] = fillKey;
1141
+ }
1142
+ }
1143
+ };
1144
+ /** 把存下来的垫底键规整成变体名;规整不出来就退回 `groundKey`(调用方已解析好)。 */
1145
+ const asVariantName = (ground) => {
1146
+ if (ground === "")
1147
+ return groundKey;
1148
+ if (ground.includes("#"))
1149
+ return ground;
1150
+ return (families[ground] ?? [])[0] ?? groundKey;
1151
+ };
1152
+ // 1) 沿用上一轮已经放好的建筑(它们的键已经从 cells 里清掉了)
1153
+ // 先照抄记录,再由下面的 place() 去重
1154
+ const carried = (state.buildingGround ?? []).slice();
1155
+ const carriedBuildings = (state.buildings ?? []).slice();
1156
+ out.buildings = [];
1157
+ out.buildingGround = [];
1158
+ for (const [r, c, name] of carriedBuildings) {
1159
+ const entry = carried.find((g) => g[0] === r && g[1] === c);
1160
+ if (entry === undefined)
1161
+ continue;
1162
+ const item = items.find((it) => it.kind === "building" && (families[it.family] ?? [])[0] === name)
1163
+ ?? items.find((it) => it.kind === "building");
1164
+ if (item === undefined)
1165
+ continue;
1166
+ place(r, c, item, entry[2], entry[3], asVariantName(entry[4]));
1167
+ }
1168
+ // 2) 再从布局里找新放置的建筑(键还在 cells 里的那些)
1169
+ for (let r = 0; r < out.rows; r++) {
1170
+ for (let c = 0; c < out.cols; c++) {
1171
+ const key = out.cells[r]?.[c];
1172
+ if (key === undefined || key === "")
1173
+ continue;
1174
+ const item = buildingByKey.get(key);
1175
+ if (item === undefined)
1176
+ continue;
1177
+ const [fw, fh] = item.footprint;
1178
+ // 占格必须完整落在图内
1179
+ if (r + fh > out.rows || c + fw > out.cols)
1180
+ continue;
1181
+ // 底下的格子引用同一个键时说明这是同一栋楼(避免重复放置)
1182
+ let sameBuilding = true;
1183
+ for (let dr = 0; dr < fh; dr++) {
1184
+ for (let dc = 0; dc < fw; dc++) {
1185
+ if (out.cells[r + dr]?.[c + dc] !== key) {
1186
+ sameBuilding = false;
1187
+ break;
1188
+ }
1189
+ }
1190
+ if (!sameBuilding)
1191
+ break;
1192
+ }
1193
+ if (!sameBuilding)
1194
+ continue;
1195
+ place(r, c, item, fw, fh, groundKey);
1196
+ }
1197
+ }
1198
+ /**
1199
+ * ★ `cells` 里可能是**装饰或建筑的键**(用户早年用手涂的方式写进去的,
1200
+ * 那时的编辑器只有单层布局)。这些格子必须补上默认地面。
1201
+ *
1202
+ * 不补的话 `assembleMap` 会拿这个键去查地面变体、查不到就整格跳过 ——
1203
+ * 地图上留下一个个**透明菱形洞**(实测:一个 13 个 tree 格的项目就是 13 个白洞)。
1204
+ * 界面预览已经按同样口径处理了,这里补齐两边才一致。
1205
+ *
1206
+ * 顺带:**装饰键要就地升格成真正的装饰**。用户手涂一棵树时想看到的是「草地上
1207
+ * 有棵树」,只把键换成草地会把树**弄丢**(实测修复后白洞没了、树也没了)。
1208
+ *
1209
+ * ⚠️ 必须放在**建筑放置之后**:建筑也是靠 `cells` 里的键识别的,
1210
+ * 先跑这一段会把 `building` 键换成草地,建筑就再也放不出来了(实测踩过)。
1211
+ */
1212
+ {
1213
+ // ⚠️ 填回去的是**地块键**(`grass`),不是变体名(`grass#0`)。
1214
+ // `cells` 存的一直是地块键,变体由 `families` 再展开一层;
1215
+ // 传变体名进去会被预校验判成「还没有已生成的图」(实测就是这么炸的)。
1216
+ const fillKey = groundItemKey !== "" ? groundItemKey : groundFillKey(families);
1217
+ const byKey = new Map(items.map((it) => [it.key, it]));
1218
+ if (fillKey !== "") {
1219
+ for (let r = 0; r < out.rows; r++) {
1220
+ for (let c = 0; c < out.cols; c++) {
1221
+ const key = out.cells[r]?.[c];
1222
+ // 建筑占格已经被 place() 清空了,这里只处理「还留着非地面键」的格子
1223
+ if (key === undefined || key === "")
1224
+ continue;
1225
+ const item = byKey.get(key);
1226
+ if (item !== undefined && item.kind === "terrain")
1227
+ continue; // 本来就是地面
1228
+ // 装饰键 → 升格成装饰层的一条记录(贴图取该类别第一个变体)
1229
+ if (item !== undefined && item.kind === "decor") {
1230
+ const name = (families[item.family] ?? [])[0];
1231
+ const pos = `${r},${c}`;
1232
+ if (name !== undefined && out.decor[pos] === undefined)
1233
+ out.decor[pos] = name;
1234
+ }
1235
+ out.cells[r][c] = fillKey;
1236
+ }
1237
+ }
1238
+ }
1239
+ }
1240
+ if (density <= 0)
1241
+ return out;
1242
+ const decorKeys = Object.keys(families).filter((key) => key === "tree" || key === "boulder");
1243
+ if (decorKeys.length === 0)
1244
+ return out;
1245
+ // ⚠️ 已经有装饰记录了就不再重撒 —— 那份记录是用户看到、也可能手工改过的布局。
1246
+ // 无条件重撒会让「换个种子」把整张图连同建筑位置一起打乱,
1247
+ // 也会让「开始编辑布局」拿到的和刚才看到的不是同一张。
1248
+ if (reroll !== true && Object.keys(out.decor).length > 0)
1249
+ return out;
1250
+ out.decor = {};
1251
+ // mulberry32 的种子:只用 state.seed,保证「同种子 + 同布局 = 逐像素一致」
1252
+ let a = (state.seed ^ 0x9e3779b9) >>> 0;
1253
+ const rand = () => {
1254
+ a = (a + 0x6d2b79f5) >>> 0;
1255
+ let t = a;
1256
+ t = Math.imul(t ^ (t >>> 15), t | 1);
1257
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
1258
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
1259
+ };
1260
+ for (let r = 0; r < out.rows; r++) {
1261
+ for (let c = 0; c < out.cols; c++) {
1262
+ if (occupied.has(`${r},${c}`))
1263
+ continue;
1264
+ if (rand() > density)
1265
+ continue;
1266
+ const family = decorKeys[Math.floor(rand() * decorKeys.length)];
1267
+ const candidates = families[family] ?? [];
1268
+ if (candidates.length === 0)
1269
+ continue;
1270
+ out.decor[`${r},${c}`] = candidates[Math.floor(rand() * candidates.length)];
1271
+ }
1272
+ }
1273
+ return out;
1274
+ }
1275
+ // ── ⑤ 导出(本地,免费)──────────────────────────────────────────────────
1276
+ export async function runExportStage(projectId) {
1277
+ if (tileBusy(projectId))
1278
+ return { started: false, reason: "已有任务在跑" };
1279
+ const project = await readTileProject(projectId);
1280
+ if (project === undefined)
1281
+ throw new Error(`项目不存在:${projectId}`);
1282
+ if (project.map.png === undefined)
1283
+ throw new Error("还没拼图,请先在第 ④ 步拼一张地图");
1284
+ void background(projectId, "export", ["tiles"], async (job, report) => {
1285
+ const dir = tileProjectDir(projectId);
1286
+ await mkdir(join(dir, "export", "tiles"), { recursive: true });
1287
+ for (const item of project.items) {
1288
+ for (const variant of item.variants) {
1289
+ if (variant.cell === undefined)
1290
+ continue;
1291
+ const bytes = await readFile(tileAssetPath(projectId, variant.cell));
1292
+ await writeFile(join(dir, "export", "tiles", `${item.key}.v${variant.index + 1}.png`), bytes);
1293
+ }
1294
+ }
1295
+ const mapBytes = await readFile(tileAssetPath(projectId, project.map.png));
1296
+ await writeFile(join(dir, "export", "map.png"), mapBytes);
1297
+ if (project.map.json !== undefined) {
1298
+ const jsonBytes = await readFile(tileAssetPath(projectId, project.map.json));
1299
+ await writeFile(join(dir, "export", "map.json"), jsonBytes);
1300
+ }
1301
+ job.done.push("tiles");
1302
+ job.running = null;
1303
+ await report();
1304
+ await patchTileProject(projectId, (fresh) => {
1305
+ fresh.stages.export = { status: "done", at: new Date().toISOString() };
1306
+ appendJobLog(fresh.logs, "info", "已导出地块包与地图(本地计算,免费)");
1307
+ });
1308
+ });
1309
+ return { started: true };
1310
+ }
1311
+ // ── 阶段失效传播 ──────────────────────────────────────────────────────────
1312
+ /**
1313
+ * 从某个阶段开始把下游全部作废(含它自己)。
1314
+ *
1315
+ * 注意 `generate` 一旦作废,重新跑要**真实计费** —— 所以「改画风」「改内容描述」
1316
+ * 「重新生成模板」都会走到这里,界面上必须二次确认。
1317
+ */
1318
+ export function invalidateFrom(project, from) {
1319
+ const order = TILE_INVALIDATION_ORDER;
1320
+ const start = order.indexOf(from);
1321
+ if (start < 0)
1322
+ return;
1323
+ for (let i = start; i < order.length; i++) {
1324
+ const stage = order[i];
1325
+ // `template` 是内部锚点:它没有自己的阶段状态,在它那里只清模板文件指纹,
1326
+ // 真正的下游作废由紧接着的 `generate` 那一步完成。
1327
+ if (stage !== "template")
1328
+ project.stages[stage] = { status: "idle" };
1329
+ if (stage === "template") {
1330
+ // 几何规格变了 → 把模板指纹作废,下次「生成地块」会自动重渲染。
1331
+ try {
1332
+ rmSync(join(tileProjectDir(project.id), "template", ".stamp.json"), { force: true });
1333
+ }
1334
+ catch {
1335
+ // 删不掉也不影响:`ensureTemplates` 还会核对文件是否齐全
1336
+ }
1337
+ }
1338
+ if (stage === "generate") {
1339
+ // ⚠️ 这一步是**全量销毁**:清空所有地块的变体(那是花了钱的)。
1340
+ // 所以调用方必须只在「提示词真的变了」时才走到这里 —— 见 `invalidateItems`。
1341
+ invalidateItems(project);
1342
+ }
1343
+ if (stage === "map") {
1344
+ // ⚠️ **只清产物,不清几何。**
1345
+ //
1346
+ // `pixel` 记的是成品画布尺寸与裁剪偏移,界面靠它把叠层对齐到预览图。
1347
+ // 以前这里把它一起抹掉,于是保存布局之后界面拿不到偏移、退回「未裁画布」
1348
+ // 的估算尺寸 —— 画布从 900 高变成 1600 高,`fit` 缩放跟着变,
1349
+ // 整张图**看起来被抬高/缩小了**(真机反馈:「保存时地块整体抬高」)。
1350
+ // 布局一改,尺寸与偏移并不会变,所以留着一份没有坏处。
1351
+ project.map = { ...project.map, png: undefined, json: undefined };
1352
+ }
1353
+ }
1354
+ }
1355
+ /**
1356
+ * 只作废「某一组地块」的产物。
1357
+ *
1358
+ * 与 `invalidateFrom(project, "generate")` 的区别:后者会把**所有**地块的变体
1359
+ * 清空(那是花钱生成的)。用户只改了一个地块的描述、甚至只改了个标签,
1360
+ * 都不该把别的地块一起废掉。
1361
+ *
1362
+ * `keys` 为空 / 省略时退化成全量作废(与 invalidateFrom 一致)。
1363
+ */
1364
+ export function invalidateItems(project, keys) {
1365
+ const targets = keys === undefined || keys.length === 0 ? undefined : new Set(keys);
1366
+ for (const item of project.items) {
1367
+ if (targets !== undefined && !targets.has(item.key))
1368
+ continue;
1369
+ item.variants = [];
1370
+ item.approved = undefined;
1371
+ }
1372
+ project.stages.generate = { status: "idle" };
1373
+ project.stages.review = { status: "idle" };
1374
+ invalidateFrom(project, "map");
1375
+ }
1376
+ // ── 作业执行器 ────────────────────────────────────────────────────────────
1377
+ /**
1378
+ * 跑一个后台作业。
1379
+ *
1380
+ * `targets` 是硬要求:界面遮罩按它盖住**还没轮到**的项。不盖遮罩时界面看着
1381
+ * 完全正常,只是「点了没反应」,用户会反复点 —— 而每次点击都真实计费。
1382
+ */
1383
+ async function background(projectId, kind, targets, run, after) {
1384
+ const job = {
1385
+ projectId,
1386
+ kind,
1387
+ targets,
1388
+ done: [],
1389
+ running: targets[0] ?? null,
1390
+ startedAt: Date.now()
1391
+ };
1392
+ jobs.set(projectId, job);
1393
+ cancelled.delete(projectId);
1394
+ const report = async () => {
1395
+ await patchTileProject(projectId, (fresh) => {
1396
+ fresh.stages[kind === "generate" ? "generate" : kind] = {
1397
+ status: "running",
1398
+ at: new Date().toISOString()
1399
+ };
1400
+ }).catch(() => undefined);
1401
+ };
1402
+ try {
1403
+ await run(job, report);
1404
+ job.running = null;
1405
+ if (after !== undefined)
1406
+ await after();
1407
+ await patchTileProject(projectId, (fresh) => {
1408
+ if (fresh.stages[kind].status === "running") {
1409
+ fresh.stages[kind] = { status: "done", at: new Date().toISOString() };
1410
+ }
1411
+ });
1412
+ }
1413
+ catch (error) {
1414
+ job.error = messageOf(error);
1415
+ job.running = null;
1416
+ await patchTileProject(projectId, (fresh) => {
1417
+ fresh.stages[kind] = { status: "error", error: job.error, at: new Date().toISOString() };
1418
+ appendJobLog(fresh.logs, "error", `${kind} 阶段失败:${job.error}`);
1419
+ }).catch(() => undefined);
1420
+ }
1421
+ finally {
1422
+ cancelled.delete(projectId);
1423
+ }
1424
+ }
1425
+ function clampInt(value, fallback, min, max) {
1426
+ const n = typeof value === "number" ? value : Number.parseFloat(String(value ?? ""));
1427
+ if (!Number.isFinite(n))
1428
+ return fallback;
1429
+ return Math.min(max, Math.max(min, Math.round(n)));
1430
+ }
1431
+ export function tileView(project) {
1432
+ // ⚠️ `progress` 与 `map.png` 都是**宿主算给界面看的派生字段**,必须在这里显式给出。
1433
+ // 踩过两次:
1434
+ // · 界面读 `project.progress` → undefined,头部永远显示「已生成 0 / 0」
1435
+ // · 界面读 `project.map.ready` → 宿主从来没算过这个字段(只有 `png`),
1436
+ // 于是**拼好的地图永远不显示**,界面一直停在「还没有拼图」
1437
+ // 客户端读的键必须在这里算出来;verify-tile-client.mjs 现在会断言这一点。
1438
+ return {
1439
+ ...project,
1440
+ job: jobs.get(project.id),
1441
+ assetBase: `/dsh-game-material-master/tile-assets/${project.id}/`,
1442
+ progress: tileProgress(project),
1443
+ // 参考图预览(原「① 模板」阶段,现在是 ② 里的只读面板)。
1444
+ //
1445
+ // ⚠️ **两个清单都要给**,界面才能既不裂图、又不漏掉「将会有哪些」:
1446
+ // · `templates` = **期望**清单(形状的纯函数)——告诉用户将要生成什么;
1447
+ // · `templatesPresent` = 磁盘上**真实存在**的 —— 只有这些才能挂 `<img>`。
1448
+ // 只给期望清单会怎样:界面给不存在的文件也挂 `<img>`,浏览器请求 404,
1449
+ // 面板上全是裂图(实测:任何还没跑过生成的干净项目都是这样)。
1450
+ templates: expectedTemplateNames(project),
1451
+ templatesPresent: listTemplateFiles(project.id),
1452
+ templateRev: templateRev(project.id),
1453
+ // 界面「手动编辑布局」要用的即时预览素材:每个地块有哪些变体贴图。
1454
+ // 不给的话界面只能画出空的菱形格子 —— 用户看不见自己涂的是什么,
1455
+ // 得先「保存布局 → 铺成地图」才能看到效果,那就谈不上预览了。
1456
+ preview: tilePreview(project)
1457
+ };
1458
+ }
1459
+ /** 磁盘上真实存在的参考图文件名(目录不存在就空数组)。 */
1460
+ function listTemplateFiles(projectId) {
1461
+ try {
1462
+ return readdirSync(join(tileProjectDir(projectId), "template"))
1463
+ .filter((name) => name.endsWith(".png"))
1464
+ .sort();
1465
+ }
1466
+ catch {
1467
+ return [];
1468
+ }
1469
+ }
1470
+ /**
1471
+ * 参考图的缓存指纹(界面拼在图片 URL 的 `?v=` 后面)。
1472
+ *
1473
+ * ⚠️ **不能用 `updatedAt`。** 图片 404 之后浏览器会把**那次失败一起缓存**,
1474
+ * 而「只是图片 404」并不会改 `updatedAt` —— 于是生成完了、图还是裂的。
1475
+ * 这里用「模板目录的 mtime + 文件清单」,每次 `ensureTemplates` 落盘后都会变,
1476
+ * 强制浏览器重新取一次。
1477
+ */
1478
+ function templateRev(projectId) {
1479
+ const dir = join(tileProjectDir(projectId), "template");
1480
+ try {
1481
+ const files = readdirSync(dir).filter((n) => n.endsWith(".png")).sort();
1482
+ const mtime = statSync(dir).mtimeMs;
1483
+ return `${Math.round(mtime)}-${files.join(".").length}-${files.length}`;
1484
+ }
1485
+ catch {
1486
+ return "0";
1487
+ }
1488
+ }
1489
+ /**
1490
+ * 量一张贴图的「自然高 / 宽」。
1491
+ *
1492
+ * ⚠️ **同步**读:`tileView` 是每次读项目都会走的同步路径,为了一个比例把它改成
1493
+ * async 会牵动所有调用点(gateway / 工具面 / 自检)。这里只读 PNG 文件头的
1494
+ * 前 24 字节(`pngSize`),代价极小。
1495
+ * 读不到就退回 1(宽高相等的保守假设)。
1496
+ */
1497
+ function spriteRatio(projectId, rel) {
1498
+ try {
1499
+ const head = readFileSync(tileAssetPath(projectId, rel));
1500
+ const size = pngSize(head);
1501
+ if (size.width > 0 && size.height > 0)
1502
+ return size.height / size.width;
1503
+ }
1504
+ catch {
1505
+ // 文件不在或不是 PNG:退回 1
1506
+ }
1507
+ return 1;
1508
+ }
1509
+ export function tilePreview(project) {
1510
+ const cells = {};
1511
+ const kinds = {};
1512
+ const footprints = {};
1513
+ /** 地块键 → 形状(相对锚点的格子集合)。摆放用它,`footprints` 只作兼容。 */
1514
+ const shapes = {};
1515
+ /** 地块键 → `key#index` → 该变体的贴图路径与底面比例。 */
1516
+ const byVariant = new Map();
1517
+ for (const item of project.items) {
1518
+ const urls = [];
1519
+ for (const variant of item.variants) {
1520
+ if (variant.cell === undefined)
1521
+ continue;
1522
+ urls.push(variant.cell);
1523
+ byVariant.set(`${item.key}#${variant.index}`, {
1524
+ cell: variant.cell,
1525
+ baseFraction: typeof variant.report?.baseFraction === "number" ? variant.report.baseFraction : 0.5
1526
+ });
1527
+ }
1528
+ if (urls.length > 0)
1529
+ cells[item.key] = urls;
1530
+ kinds[item.key] = item.kind;
1531
+ footprints[item.key] = [item.footprint[0], item.footprint[1]];
1532
+ // ★ 形状是**摆放的唯一真源**(`footprints` 只是它的包围矩形,老字段)。
1533
+ // 界面必须读这一份:非矩形形状(L 形)按包围矩形算会多占格、错半格。
1534
+ shapes[item.key] = shapeOf(item).map(([r, c]) => [r, c]);
1535
+ }
1536
+ const rows = project.map.rows;
1537
+ const cols = project.map.cols;
1538
+ const seed = project.map.seed;
1539
+ // 地面:每格挑一个变体 —— **必须与宿主 `assembleMap` 用同一个函数**,
1540
+ // 否则预览和成品会挑到不同的变体(用了不同公式,同种子也会错开)。
1541
+ const ground = [];
1542
+ for (let r = 0; r < rows; r++) {
1543
+ const row = [];
1544
+ for (let c = 0; c < cols; c++) {
1545
+ const key = project.map.cells?.[r]?.[c] ?? "";
1546
+ const list = cells[key];
1547
+ row.push(list === undefined || list.length === 0 ? -1 : pickVariantIndex(seed, r, c, list.length));
1548
+ }
1549
+ ground.push(row);
1550
+ }
1551
+ /**
1552
+ * 把「地块键」或「贴图路径」都解析成 `{ cell, baseFraction, index }`。
1553
+ *
1554
+ * 两种写法都要认:界面回传的是**键**,而早期存下来的数据里可能是**路径**。
1555
+ * 只认一种,另一种会被静默跳过 —— 装饰/建筑直接消失,且不报任何错。
1556
+ */
1557
+ const resolveArt = (value) => {
1558
+ if (value === "")
1559
+ return null;
1560
+ const direct = byVariant.get(value);
1561
+ if (direct !== undefined) {
1562
+ const hash = value.indexOf("#");
1563
+ const index = hash < 0 ? 0 : Number.parseInt(value.slice(hash + 1), 10);
1564
+ return { cell: direct.cell, baseFraction: direct.baseFraction, index: Number.isFinite(index) ? index : 0 };
1565
+ }
1566
+ if (cells[value] !== undefined && cells[value].length > 0) {
1567
+ return { cell: cells[value][0], baseFraction: 0.5, index: 0 };
1568
+ }
1569
+ for (const list of Object.values(cells)) {
1570
+ if (list.includes(value))
1571
+ return { cell: value, baseFraction: 0.5, index: 0 };
1572
+ }
1573
+ return null;
1574
+ };
1575
+ // 装饰:成品里存的 `"r,c" -> key#index`(早期可能是贴图路径)
1576
+ const decor = {};
1577
+ for (const [pos, name] of Object.entries(project.map.decor ?? {})) {
1578
+ const found = resolveArt(name);
1579
+ if (found === null)
1580
+ continue;
1581
+ decor[pos] = [found.index, found.cell];
1582
+ }
1583
+ // 建筑:锚点 + 占格 + 贴图(界面要按 2×2 摆,不能只画一格)
1584
+ const buildings = [];
1585
+ for (const [r, c, name] of project.map.buildings ?? []) {
1586
+ const found = resolveArt(name);
1587
+ if (found === null)
1588
+ continue;
1589
+ const entry = (project.map.buildingGround ?? []).find((g) => g[0] === r && g[1] === c);
1590
+ buildings.push({
1591
+ r, c,
1592
+ fw: entry?.[2] ?? 2,
1593
+ fh: entry?.[3] ?? 2,
1594
+ // ★ 形状:摆放的唯一真源(`fw/fh` 只是包围矩形)。
1595
+ // 界面按形状铺格子 / 算底心,按包围矩形算会让 L 形错位。
1596
+ shape: shapeOfEntry(entry),
1597
+ index: found.index,
1598
+ cell: found.cell,
1599
+ baseFraction: found.baseFraction,
1600
+ // 自然高宽比:从 PNG 文件头量(不进内存解整图)。界面算包围盒要用它,
1601
+ // 而浏览器半区拿不到自然尺寸(贴图是异步加载的)。
1602
+ ratio: spriteRatio(project.id, found.cell)
1603
+ });
1604
+ }
1605
+ const groundName = (project.map.buildingGround ?? [])[0]?.[4];
1606
+ const groundUnder = groundName === undefined ? null : (byVariant.get(groundName)?.cell ?? null);
1607
+ return {
1608
+ cells,
1609
+ kinds,
1610
+ footprints,
1611
+ shapes,
1612
+ cellWidth: project.settings.cellWidth,
1613
+ cellHeight: project.settings.cellHeight,
1614
+ seed,
1615
+ ground,
1616
+ decor,
1617
+ buildings,
1618
+ groundUnder
1619
+ };
1620
+ }
1621
+ /** 生成 / 期望 / 已验收三件套(界面与工具共用一份算法)。 */
1622
+ export function tileProgress(project) {
1623
+ let generated = 0;
1624
+ let expected = 0;
1625
+ let approved = 0;
1626
+ for (const item of project.items) {
1627
+ expected += Math.max(1, item.variantCount);
1628
+ for (const variant of item.variants) {
1629
+ if (variant.cell !== undefined)
1630
+ generated++;
1631
+ if (variant.approved === true)
1632
+ approved++;
1633
+ }
1634
+ }
1635
+ return { generated, expected, approved };
1636
+ }
1637
+ /** 装饰锚点(界面显示用)。 */
1638
+ export function tileAnchorY(project) {
1639
+ return decorAnchorY(project.settings);
1640
+ }
1641
+ /**
1642
+ * 给**对话工具**用的快照:产物一律是绝对 URL(会直接贴给用户点)。
1643
+ *
1644
+ * 与 `tileView` 的区别:`tileView` 给界面用相对路径(界面自己拼 origin),
1645
+ * 这里给模型用绝对 URL。两者都只带「判断所需的最小字段」,不是整个 project.json。
1646
+ */
1647
+ export function tileSnapshot(project, origin) {
1648
+ const assetBase = `${origin}/dsh-game-material-master/tile-assets/${project.id}/`;
1649
+ const url = (relative) => typeof relative === "string" && relative !== "" ? `${assetBase}${relative}` : undefined;
1650
+ const items = project.items.map((item) => ({
1651
+ key: item.key,
1652
+ label: item.label,
1653
+ kind: item.kind,
1654
+ approved: item.approved === true,
1655
+ expected: Math.max(1, item.variantCount),
1656
+ variants: item.variants.map((variant) => ({
1657
+ index: variant.index,
1658
+ file: variant.cell,
1659
+ url: url(variant.cell),
1660
+ approved: variant.approved === true,
1661
+ /** 实测菱形比例(理想 2.0);1.98~2.02 视为正常。 */
1662
+ ratio: variant.report?.ratioMeasured,
1663
+ /** 规整方式:measured = 量测成功;template = 测量失败退回模板几何。 */
1664
+ geomMode: variant.report?.mode,
1665
+ fallbackReason: variant.report?.fallbackReason,
1666
+ error: variant.error
1667
+ }))
1668
+ }));
1669
+ const total = items.reduce((sum, item) => sum + item.variants.filter((v) => v.file !== undefined).length, 0);
1670
+ const expected = items.reduce((sum, item) => sum + item.expected, 0);
1671
+ const approved = items.reduce((sum, item) => sum + item.variants.filter((v) => v.approved).length, 0);
1672
+ return {
1673
+ id: project.id,
1674
+ name: project.name,
1675
+ /** 界面 / 模型拼产物 URL 用。工具侧产物已经是绝对 URL,这里给基址留一份兜底。 */
1676
+ assetBase,
1677
+ style: project.style,
1678
+ settings: project.settings,
1679
+ reviewMode: project.reviewMode,
1680
+ stages: project.stages,
1681
+ job: jobs.get(project.id),
1682
+ progress: { generated: total, expected, approved },
1683
+ items,
1684
+ map: {
1685
+ rows: project.map.rows,
1686
+ cols: project.map.cols,
1687
+ seed: project.map.seed,
1688
+ ready: project.map.png !== undefined,
1689
+ file: project.map.png,
1690
+ url: url(project.map.png),
1691
+ json: project.map.json,
1692
+ buildings: project.map.buildings.length,
1693
+ decor: Object.keys(project.map.decor).length
1694
+ },
1695
+ logs: project.logs.slice(-20)
1696
+ };
1697
+ }
1698
+ /** 菱形高(界面显示用)。 */
1699
+ export function tileDiamondHeight(project) {
1700
+ return diamondHeight(project.settings);
1701
+ }
1702
+ export { ArkError };