dsh-game-material-master 0.3.0 → 0.6.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/README.en.md +74 -9
- package/README.md +60 -8
- package/lib/{tilemedia.js → bitmap.js} +21 -3
- package/lib/client.js +2929 -162
- package/lib/config.js +20 -1
- package/lib/index.js +239 -3
- package/lib/jsonio.js +24 -3
- package/lib/links.js +11 -2
- package/lib/mapauto.js +126 -0
- package/lib/mapdoc.js +444 -0
- package/lib/mapexport.js +177 -0
- package/lib/mapgen.js +1579 -0
- package/lib/mapgeom.js +308 -0
- package/lib/maprender.js +430 -0
- package/lib/mapsample.js +36 -0
- package/lib/mapsamplegen.js +760 -0
- package/lib/maptiles.js +253 -0
- package/lib/rigexport.js +29 -98
- package/lib/riggen.js +6 -4
- package/lib/rigpath.js +47 -10
- package/lib/rigpreview.js +91 -84
- package/lib/rigsemantics.js +4 -4
- package/lib/rigvalidate.js +72 -14
- package/lib/spine.js +147 -80
- package/lib/tilegen.js +1 -1
- package/lib/tilegeom.js +1 -1
- package/lib/tools.js +401 -24
- package/lib/wire.js +179 -3
- package/lib/zip.js +127 -0
- package/package.json +10 -4
package/lib/mapgen.js
ADDED
|
@@ -0,0 +1,1579 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 地图编辑器(模块六)的**数据层与作业**:**单项目 = 单张地图**。
|
|
3
|
+
*
|
|
4
|
+
* ## 落盘布局
|
|
5
|
+
*
|
|
6
|
+
* ```
|
|
7
|
+
* <DSH_HOME>/game-material-master/map-jobs/<项目 id>/
|
|
8
|
+
* ├── project.json 元数据:网格、素材、阶段、日志
|
|
9
|
+
* ├── map.json 这张地图:图层元数据 + 每层数据(0 = 空)
|
|
10
|
+
* ├── tilesets/<tsId>.png 导入的素材原图(原样保存,不改写)
|
|
11
|
+
* ├── preview/map.png 验收图:宿主算好的地图渲染图
|
|
12
|
+
* └── export/<安全名>/ 导出:map.png + map.json + manifest.json
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* 参考 AsLib 的 RPG Map Maker:一屏、零术语、地图四周**环绕**、A2 素材自动连接、
|
|
16
|
+
* 动画地块、内置素材、一键生成。旧的「多地图 / 地形族 / 掩码覆盖 / 等距网格 /
|
|
17
|
+
* 层高偏移 / Tiled 导出」全部删掉 —— 那些正是「预览好看、导出位移」「族配不齐
|
|
18
|
+
* 就静默画错块」的来源。
|
|
19
|
+
*
|
|
20
|
+
* ## 编辑路径
|
|
21
|
+
*
|
|
22
|
+
* 界面**不发整份文档**,只发 op;宿主是唯一写者:
|
|
23
|
+
* `applyMapOps` → 改内存里的文档 → 回传「脏 chunk + 该丢哪些客户端缓存」→ 防抖落盘。
|
|
24
|
+
* 落盘是「最多 2 秒一次 + 停了 500ms 再补一次」,所以拖动时不会每笔都重写整个
|
|
25
|
+
* 地图文件;进程被杀最多丢 2 秒的编辑(写入本身仍是原子的)。
|
|
26
|
+
*
|
|
27
|
+
* 撤销 / 重做是宿主侧**逆操作日志**(结构操作才存整份快照),界面不需要自己维护
|
|
28
|
+
* 撤销栈 —— 旧模块那个「整份草稿 + 客户端撤销栈」正是「撤销跳步」的来源。
|
|
29
|
+
*/
|
|
30
|
+
import { mkdir, readdir, rm, writeFile } from "node:fs/promises";
|
|
31
|
+
import { existsSync } from "node:fs";
|
|
32
|
+
import { randomUUID } from "node:crypto";
|
|
33
|
+
import { join } from "node:path";
|
|
34
|
+
import { appendJobLog, messageOf, readJson, sweepTempFiles, writeJsonAtomic } from "./jsonio.js";
|
|
35
|
+
import { dataRoot } from "./config.js";
|
|
36
|
+
import { decodeFile, pngSize, probeImageSize, sniffImageExt } from "./bitmap.js";
|
|
37
|
+
import { addLayer, applyOps, clearLayer, cloneDoc, createMapDoc, filledCount, isDocEmpty, moveLayer, normalizeMapDoc, removeLayer, renameLayer, resizeDoc, revertOps } from "./mapdoc.js";
|
|
38
|
+
import { assertGrid, assertMapSize, canonicalChunk, chunkKey, chunksInRange, dirtyChunksFor, layoutOf, normalizeGrid, parseChunkKey, viewCellRange, MAX_MAP_DIM, MAX_PLAN_CHUNKS } from "./mapgeom.js";
|
|
39
|
+
import { bitmapToPng, buildPlan, rasterize } from "./maprender.js";
|
|
40
|
+
import { COMMON_TILE_SIZES, buildTiles, detectLayout, flatIndexByValue, flatTiles, layoutFor } from "./maptiles.js";
|
|
41
|
+
import { exportMap, safeFileName } from "./mapexport.js";
|
|
42
|
+
import { primeSampleTextures, renderSampleTilesets } from "./mapsamplegen.js";
|
|
43
|
+
/** 四个阶段(对话面契约:`stage=assets|rules|paint|export`;`rules` 自动完成、界面不显示)。 */
|
|
44
|
+
export const MAP_STAGES = ["assets", "rules", "paint", "export"];
|
|
45
|
+
// ── 路径与 id ─────────────────────────────────────────────────────────────
|
|
46
|
+
export function mapJobsRoot() {
|
|
47
|
+
return join(dataRoot(), "map-jobs");
|
|
48
|
+
}
|
|
49
|
+
export function mapProjectDir(id) {
|
|
50
|
+
return join(mapJobsRoot(), id);
|
|
51
|
+
}
|
|
52
|
+
export function mapProjectFile(id) {
|
|
53
|
+
return join(mapProjectDir(id), "project.json");
|
|
54
|
+
}
|
|
55
|
+
/** 单项目 = 单张地图,文档直接放项目根。 */
|
|
56
|
+
export function mapDocFile(id) {
|
|
57
|
+
return join(mapProjectDir(id), "map.json");
|
|
58
|
+
}
|
|
59
|
+
/** 项目内的相对路径 → 绝对路径(挡住目录穿越)。 */
|
|
60
|
+
export function mapAssetPath(id, relative) {
|
|
61
|
+
const base = mapProjectDir(id);
|
|
62
|
+
const target = join(base, relative);
|
|
63
|
+
if (!target.startsWith(base))
|
|
64
|
+
throw new Error(`非法的项目内路径:${relative}`);
|
|
65
|
+
return target;
|
|
66
|
+
}
|
|
67
|
+
/** `m` 前缀,避免与 p / i / s / r / t 撞。 */
|
|
68
|
+
export function isValidMapProjectId(id) {
|
|
69
|
+
return /^m[a-z0-9]{4,40}$/.test(id);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* 子目录白名单(静态资源路由按**第一段**比对,漏一条就是 403 + 图裂)。
|
|
73
|
+
*
|
|
74
|
+
* ⚠️ 与 `index.ts` 的 `AssetScope` 类型、`resolveAssetTarget` 分支、`SCOPES` 数组
|
|
75
|
+
* **四处必须同步**。`maps/` 已经不存在了(单项目单地图 → `map.json` 在项目根)。
|
|
76
|
+
*/
|
|
77
|
+
export const SERVABLE_MAP_DIRS = new Set(["tilesets", "preview", "export"]);
|
|
78
|
+
/** 新项目默认地图尺寸(单屏一屏就能画完)。 */
|
|
79
|
+
const DEFAULT_COLS = 32;
|
|
80
|
+
const DEFAULT_ROWS = 32;
|
|
81
|
+
function freshStages() {
|
|
82
|
+
// `rules`(自动连接)现在没有可配置项:素材形态在导入时就识别好了、过渡是内置的,
|
|
83
|
+
// 所以它一开始就是 done。key 保留只为不破坏对话面的阶段契约。
|
|
84
|
+
return {
|
|
85
|
+
assets: { status: "idle" },
|
|
86
|
+
rules: { status: "done", at: new Date().toISOString() },
|
|
87
|
+
paint: { status: "idle" },
|
|
88
|
+
export: { status: "idle" }
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
// ── 读写(带写队列)──────────────────────────────────────────────────────
|
|
92
|
+
const projectWriteQueue = new Map();
|
|
93
|
+
function enqueueWrite(key, task) {
|
|
94
|
+
const previous = projectWriteQueue.get(key) ?? Promise.resolve();
|
|
95
|
+
const next = previous.catch(() => undefined).then(task);
|
|
96
|
+
projectWriteQueue.set(key, next.catch(() => undefined));
|
|
97
|
+
return next;
|
|
98
|
+
}
|
|
99
|
+
async function writeMapProject(project) {
|
|
100
|
+
project.updatedAt = new Date().toISOString();
|
|
101
|
+
await writeJsonAtomic(mapProjectFile(project.id), project);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* 改项目元数据(改名 / 打勾 / 网格开关)。
|
|
105
|
+
*
|
|
106
|
+
* 读—改—写走同一条队列,两个并发的打勾不会互相覆盖。
|
|
107
|
+
*/
|
|
108
|
+
export async function patchMapProject(id, mutator) {
|
|
109
|
+
return enqueueWrite(id, async () => {
|
|
110
|
+
const project = await readMapProject(id);
|
|
111
|
+
if (project === undefined)
|
|
112
|
+
throw new Error(`项目不存在:${id}`);
|
|
113
|
+
const result = mutator(project);
|
|
114
|
+
await writeMapProject(project);
|
|
115
|
+
return result;
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
function positiveInt(value, fallback) {
|
|
119
|
+
const n = Math.round(Number(value));
|
|
120
|
+
return Number.isFinite(n) && n > 0 ? n : fallback;
|
|
121
|
+
}
|
|
122
|
+
export async function createMapProject(name, options = {}) {
|
|
123
|
+
const grid = normalizeGrid(options.grid);
|
|
124
|
+
assertGrid(grid);
|
|
125
|
+
const cols = positiveInt(options.cols, DEFAULT_COLS);
|
|
126
|
+
const rows = positiveInt(options.rows, DEFAULT_ROWS);
|
|
127
|
+
assertMapSize(cols, rows);
|
|
128
|
+
const id = `m${Date.now().toString(36)}${randomUUID().slice(0, 6)}`;
|
|
129
|
+
const now = new Date().toISOString();
|
|
130
|
+
const project = {
|
|
131
|
+
id,
|
|
132
|
+
name: name.trim() === "" ? "未命名地图" : name.trim(),
|
|
133
|
+
createdAt: now,
|
|
134
|
+
updatedAt: now,
|
|
135
|
+
grid,
|
|
136
|
+
tilesets: [],
|
|
137
|
+
stages: freshStages(),
|
|
138
|
+
logs: []
|
|
139
|
+
};
|
|
140
|
+
await mkdir(mapProjectDir(id), { recursive: true });
|
|
141
|
+
for (const sub of SERVABLE_MAP_DIRS)
|
|
142
|
+
await mkdir(join(mapProjectDir(id), sub), { recursive: true });
|
|
143
|
+
appendJobLog(project.logs, "info", `新建地图项目:${project.name}(${cols}×${rows})`);
|
|
144
|
+
// 顺手建一张空地图:用户导入素材后就能直接画
|
|
145
|
+
await writeTheDoc(id, createMapDoc(id, project.name, cols, rows));
|
|
146
|
+
await writeMapProject(project);
|
|
147
|
+
return project;
|
|
148
|
+
}
|
|
149
|
+
export async function readMapProject(id) {
|
|
150
|
+
const raw = await readJson(mapProjectFile(id));
|
|
151
|
+
if (raw === undefined || typeof raw !== "object")
|
|
152
|
+
return undefined;
|
|
153
|
+
void sweepTempFiles(mapProjectDir(id));
|
|
154
|
+
const stages = { ...freshStages(), ...(raw.stages ?? {}) };
|
|
155
|
+
if (stages.rules.status === "idle")
|
|
156
|
+
stages.rules = { status: "done", at: stages.rules.at ?? new Date().toISOString(), approved: stages.rules.approved };
|
|
157
|
+
return {
|
|
158
|
+
...raw,
|
|
159
|
+
grid: normalizeGrid(raw.grid),
|
|
160
|
+
tilesets: Array.isArray(raw.tilesets) ? raw.tilesets.map(normalizeTileset) : [],
|
|
161
|
+
stages,
|
|
162
|
+
logs: Array.isArray(raw.logs) ? raw.logs : []
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* 素材记录的自愈式归一化:**几何字段是唯一真源,`tiles` 由它现推**。
|
|
167
|
+
*
|
|
168
|
+
* 这样即使某次改了 `buildTiles` 的切分规则、或者老数据缺了新字段,读一次项目就
|
|
169
|
+
* 自动补齐;逐块的人工元数据(名字 / 掩码 / 形状号)按「矩形 id」尽力保留。
|
|
170
|
+
*/
|
|
171
|
+
function normalizeTileset(raw) {
|
|
172
|
+
const source = asRecord(raw);
|
|
173
|
+
const imageWidth = Math.max(1, Math.round(Number(source.imageWidth) || 1));
|
|
174
|
+
const imageHeight = Math.max(1, Math.round(Number(source.imageHeight) || 1));
|
|
175
|
+
const cell = normalizeCell(source.cell) ?? { width: 32, height: 32 };
|
|
176
|
+
const shape = isTilesetShape(source.shape) ? source.shape : "plain";
|
|
177
|
+
const animRows = source.animRows === true;
|
|
178
|
+
const rawTiles = source.tiles;
|
|
179
|
+
const previous = Array.isArray(rawTiles) ? rawTiles : undefined;
|
|
180
|
+
const tiles = buildTiles({ shape, cell, imageWidth, imageHeight, animRows }, previous);
|
|
181
|
+
const tileset = {
|
|
182
|
+
id: typeof source.id === "string" && source.id !== "" ? source.id : `ts${randomUUID().slice(0, 6)}`,
|
|
183
|
+
name: typeof source.name === "string" && source.name !== "" ? source.name : "素材",
|
|
184
|
+
file: typeof source.file === "string" ? source.file : "",
|
|
185
|
+
imageWidth,
|
|
186
|
+
imageHeight,
|
|
187
|
+
cell,
|
|
188
|
+
shape,
|
|
189
|
+
animRows,
|
|
190
|
+
variants: variantsOf(shape, cell, imageWidth, imageHeight, animRows),
|
|
191
|
+
builtin: source.builtin === true ? true : undefined,
|
|
192
|
+
tiles
|
|
193
|
+
};
|
|
194
|
+
// 老数据里「整格自动连接」没配过掩码(旧版本压根没这条路径)——读一次就补齐,
|
|
195
|
+
// 这样不用让用户回去重新切一次形态。告警交给 `warningsFor` 常驻显示。
|
|
196
|
+
assignCorner16Masks(tileset, []);
|
|
197
|
+
return tileset;
|
|
198
|
+
}
|
|
199
|
+
/** JSON 记录收口(读盘数据一律当作不认识的东西看)。 */
|
|
200
|
+
function asRecord(value) {
|
|
201
|
+
return value !== null && typeof value === "object" ? value : {};
|
|
202
|
+
}
|
|
203
|
+
function isTilesetShape(value) {
|
|
204
|
+
return value === "plain" || value === "a2quad" || value === "corner16";
|
|
205
|
+
}
|
|
206
|
+
/** 界面 / 工具面传上来的形态字符串收口:不合法**明确报错**,不静默改成别的值。 */
|
|
207
|
+
export function parseTilesetShape(value) {
|
|
208
|
+
if (value === undefined || value === null || value === "")
|
|
209
|
+
return undefined;
|
|
210
|
+
if (!isTilesetShape(value))
|
|
211
|
+
throw new Error(`未知素材形态:${String(value)}(可选 plain / a2quad / corner16)`);
|
|
212
|
+
return value;
|
|
213
|
+
}
|
|
214
|
+
/** 整数收口;形状不对时抛中文错,不静默改成别的值。 */
|
|
215
|
+
function normalizeCell(input) {
|
|
216
|
+
if (input === undefined || input === null)
|
|
217
|
+
return undefined;
|
|
218
|
+
const source = asRecord(input);
|
|
219
|
+
const width = Math.round(Number(source.width));
|
|
220
|
+
const height = Math.round(Number(source.height));
|
|
221
|
+
if (!Number.isFinite(width) || !Number.isFinite(height) || width < 1 || height < 1 || width > 2048 || height > 2048) {
|
|
222
|
+
throw new Error(`素材格子尺寸不合法:${JSON.stringify(input)}(应为 1..2048 的整数宽高)`);
|
|
223
|
+
}
|
|
224
|
+
return { width, height };
|
|
225
|
+
}
|
|
226
|
+
/** 变体数 / 动画帧数:A2 看块列数,普通形态看行数(`animRows` 时)。 */
|
|
227
|
+
function variantsOf(shape, cell, imageWidth, imageHeight, animRows) {
|
|
228
|
+
if (shape === "a2quad")
|
|
229
|
+
return Math.max(1, Math.floor(imageWidth / cell.width));
|
|
230
|
+
if (animRows)
|
|
231
|
+
return Math.max(1, Math.floor(imageHeight / cell.height));
|
|
232
|
+
return 1;
|
|
233
|
+
}
|
|
234
|
+
export async function listMapProjects() {
|
|
235
|
+
let names = [];
|
|
236
|
+
try {
|
|
237
|
+
names = await readdir(mapJobsRoot());
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
return [];
|
|
241
|
+
}
|
|
242
|
+
const out = [];
|
|
243
|
+
for (const name of names) {
|
|
244
|
+
if (!isValidMapProjectId(name))
|
|
245
|
+
continue;
|
|
246
|
+
const project = await readMapProject(name);
|
|
247
|
+
if (project === undefined)
|
|
248
|
+
continue;
|
|
249
|
+
out.push(await summarizeMapProject(project));
|
|
250
|
+
}
|
|
251
|
+
return out.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1));
|
|
252
|
+
}
|
|
253
|
+
export async function summarizeMapProject(project) {
|
|
254
|
+
return {
|
|
255
|
+
id: project.id,
|
|
256
|
+
name: project.name,
|
|
257
|
+
updatedAt: project.updatedAt,
|
|
258
|
+
grid: project.grid,
|
|
259
|
+
tilesetCount: project.tilesets.length,
|
|
260
|
+
tileCount: flatTiles(project.tilesets).length,
|
|
261
|
+
stages: project.stages
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
export async function deleteMapProject(id) {
|
|
265
|
+
/**
|
|
266
|
+
* ⚠️ 先把**还没落盘的防抖定时器**停掉。
|
|
267
|
+
*
|
|
268
|
+
* 不停的话,用户删完项目、目录已经移走,定时器几秒后照样 fire → 往不存在的
|
|
269
|
+
* 目录里 rename,抛 ENOENT。那是**未处理的 promise 拒绝**(自检里直接把整个
|
|
270
|
+
* 脚本打挂,真机上只是控制台一声闷响,但会污染日志)。
|
|
271
|
+
*/
|
|
272
|
+
const state = docWrites.get(id);
|
|
273
|
+
if (state?.timer != null)
|
|
274
|
+
clearTimeout(state.timer);
|
|
275
|
+
docWrites.delete(id);
|
|
276
|
+
docCache.delete(id);
|
|
277
|
+
history.delete(id);
|
|
278
|
+
await rm(mapProjectDir(id), { recursive: true, force: true });
|
|
279
|
+
}
|
|
280
|
+
async function readProjectOrThrow(projectId) {
|
|
281
|
+
const project = await readMapProject(projectId);
|
|
282
|
+
if (project === undefined)
|
|
283
|
+
throw new Error(`项目不存在:${projectId}`);
|
|
284
|
+
return project;
|
|
285
|
+
}
|
|
286
|
+
// ── 地图文档:内存真源 + 防抖落盘 ─────────────────────────────────────────
|
|
287
|
+
/** `项目id` → 文档。编辑期间这是**权威副本**,磁盘是它的稳态快照。 */
|
|
288
|
+
const docCache = new Map();
|
|
289
|
+
const docWrites = new Map();
|
|
290
|
+
/** 上一笔编辑距今超过它就直接写盘(保证「最多丢 2 秒」)。 */
|
|
291
|
+
const WRITE_MAX_LATENCY_MS = 2000;
|
|
292
|
+
const WRITE_IDLE_MS = 500;
|
|
293
|
+
/** 读当前项目的地图文档(内存优先);没有就返回 undefined。 */
|
|
294
|
+
export async function readTheDoc(projectId) {
|
|
295
|
+
const cached = docCache.get(projectId);
|
|
296
|
+
if (cached !== undefined)
|
|
297
|
+
return cached;
|
|
298
|
+
const raw = await readJson(mapDocFile(projectId));
|
|
299
|
+
const doc = normalizeMapDoc(raw, projectId);
|
|
300
|
+
if (doc === undefined)
|
|
301
|
+
return undefined;
|
|
302
|
+
docCache.set(projectId, doc);
|
|
303
|
+
return doc;
|
|
304
|
+
}
|
|
305
|
+
/** 内部:读不到就给一份空地图(不落盘,第一次写的时候才存)。 */
|
|
306
|
+
async function theDocOrFresh(projectId) {
|
|
307
|
+
const doc = await readTheDoc(projectId);
|
|
308
|
+
if (doc !== undefined)
|
|
309
|
+
return doc;
|
|
310
|
+
const fresh = createMapDoc(projectId, "地图", DEFAULT_COLS, DEFAULT_ROWS);
|
|
311
|
+
docCache.set(projectId, fresh);
|
|
312
|
+
return fresh;
|
|
313
|
+
}
|
|
314
|
+
export async function writeTheDoc(projectId, doc) {
|
|
315
|
+
await enqueueWrite(projectId, async () => {
|
|
316
|
+
await writeJsonAtomic(mapDocFile(projectId), doc);
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* 防抖落盘:**最多 2 秒延迟 + 停笔 500ms 补齐**。
|
|
321
|
+
*
|
|
322
|
+
* 每笔都写的话,拖动笔刷时每 60ms 就要把整张地图(最大 512×512×多层)序列化一遍,
|
|
323
|
+
* 界面会明显发涩;完全不防抖又会丢编辑。这个窗口是两者的折中。
|
|
324
|
+
*/
|
|
325
|
+
function scheduleDocWrite(projectId, doc) {
|
|
326
|
+
const state = docWrites.get(projectId) ?? { timer: null, lastWrite: 0 };
|
|
327
|
+
docWrites.set(projectId, state);
|
|
328
|
+
const now = Date.now();
|
|
329
|
+
const elapsed = now - state.lastWrite;
|
|
330
|
+
if (elapsed >= WRITE_MAX_LATENCY_MS) {
|
|
331
|
+
state.lastWrite = now;
|
|
332
|
+
void writeTheDoc(projectId, doc).catch(() => undefined);
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
if (state.timer !== null)
|
|
336
|
+
return;
|
|
337
|
+
state.timer = setTimeout(() => {
|
|
338
|
+
state.timer = null;
|
|
339
|
+
state.lastWrite = Date.now();
|
|
340
|
+
void writeTheDoc(projectId, doc).catch(() => undefined);
|
|
341
|
+
}, Math.max(WRITE_IDLE_MS, WRITE_MAX_LATENCY_MS - elapsed));
|
|
342
|
+
if (typeof state.timer.unref === "function")
|
|
343
|
+
state.timer.unref();
|
|
344
|
+
}
|
|
345
|
+
/** 立刻落盘(导出前、改结构后、删项目前调用)。 */
|
|
346
|
+
export async function flushMapDoc(projectId) {
|
|
347
|
+
const doc = docCache.get(projectId);
|
|
348
|
+
if (doc === undefined)
|
|
349
|
+
return;
|
|
350
|
+
const state = docWrites.get(projectId);
|
|
351
|
+
if (state?.timer != null) {
|
|
352
|
+
clearTimeout(state.timer);
|
|
353
|
+
state.timer = null;
|
|
354
|
+
}
|
|
355
|
+
await writeTheDoc(projectId, doc);
|
|
356
|
+
}
|
|
357
|
+
const history = new Map();
|
|
358
|
+
const HISTORY_MAX_ENTRIES = 200;
|
|
359
|
+
const HISTORY_MAX_BYTES = 32 * 1024 * 1024;
|
|
360
|
+
function estimateEntryBytes(entry, doc) {
|
|
361
|
+
if (entry.snapshot !== undefined)
|
|
362
|
+
return doc.cols * doc.rows * (doc.layers.length + 1) * 4;
|
|
363
|
+
return (entry.redo.length + entry.undo.length) * 32;
|
|
364
|
+
}
|
|
365
|
+
function pushHistory(projectId, entry, doc) {
|
|
366
|
+
const state = history.get(projectId) ?? { entries: [], index: -1, bytes: 0 };
|
|
367
|
+
// 撤销之后又画了新东西:把「未来」截断
|
|
368
|
+
if (state.index < state.entries.length - 1) {
|
|
369
|
+
for (const dropped of state.entries.slice(state.index + 1))
|
|
370
|
+
state.bytes -= estimateEntryBytes(dropped, doc);
|
|
371
|
+
state.entries = state.entries.slice(0, state.index + 1);
|
|
372
|
+
}
|
|
373
|
+
const previous = state.entries[state.index];
|
|
374
|
+
if (entry.snapshot === undefined &&
|
|
375
|
+
entry.stroke !== undefined &&
|
|
376
|
+
previous !== undefined &&
|
|
377
|
+
previous.snapshot === undefined &&
|
|
378
|
+
previous.stroke === entry.stroke) {
|
|
379
|
+
// 同一笔的后续提交:并进上一条(撤销粒度 = 一笔,而不是一次 flush)
|
|
380
|
+
previous.undo = [...entry.undo, ...previous.undo];
|
|
381
|
+
previous.redo = [...previous.redo, ...entry.redo];
|
|
382
|
+
state.bytes += estimateEntryBytes(entry, doc);
|
|
383
|
+
history.set(projectId, state);
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
state.entries.push(entry);
|
|
387
|
+
state.bytes += estimateEntryBytes(entry, doc);
|
|
388
|
+
state.index = state.entries.length - 1;
|
|
389
|
+
while (state.entries.length > HISTORY_MAX_ENTRIES || (state.bytes > HISTORY_MAX_BYTES && state.entries.length > 1)) {
|
|
390
|
+
const dropped = state.entries.shift();
|
|
391
|
+
if (dropped === undefined)
|
|
392
|
+
break;
|
|
393
|
+
state.bytes -= estimateEntryBytes(dropped, doc);
|
|
394
|
+
state.index--;
|
|
395
|
+
}
|
|
396
|
+
state.index = Math.max(-1, state.index);
|
|
397
|
+
history.set(projectId, state);
|
|
398
|
+
}
|
|
399
|
+
export function historyState(projectId) {
|
|
400
|
+
const state = history.get(projectId);
|
|
401
|
+
if (state === undefined)
|
|
402
|
+
return { canUndo: false, canRedo: false, depth: 0 };
|
|
403
|
+
return { canUndo: state.index >= 0, canRedo: state.index < state.entries.length - 1, depth: state.entries.length };
|
|
404
|
+
}
|
|
405
|
+
function restoreDoc(target, snapshot) {
|
|
406
|
+
target.name = snapshot.name;
|
|
407
|
+
target.cols = snapshot.cols;
|
|
408
|
+
target.rows = snapshot.rows;
|
|
409
|
+
target.layers = snapshot.layers.map((layer) => ({ ...layer }));
|
|
410
|
+
target.data = Object.fromEntries(Object.entries(snapshot.data).map(([key, value]) => [key, [...value]]));
|
|
411
|
+
target.updatedAt = new Date().toISOString();
|
|
412
|
+
}
|
|
413
|
+
// ── 渲染上下文与坐标 ──────────────────────────────────────────────────────
|
|
414
|
+
/**
|
|
415
|
+
* 组装渲染上下文。
|
|
416
|
+
*
|
|
417
|
+
* ⚠️ 多了一个 `doc`:`RenderContext.layout` 的 cols/rows 只存在地图文档里
|
|
418
|
+
* (项目元数据不存尺寸 —— 单项目单地图,尺寸是文档的属性)。
|
|
419
|
+
*/
|
|
420
|
+
export function renderContextFor(project, doc) {
|
|
421
|
+
return {
|
|
422
|
+
grid: project.grid,
|
|
423
|
+
layout: layoutOf(project.grid, doc.cols, doc.rows),
|
|
424
|
+
tilesets: project.tilesets,
|
|
425
|
+
lookup: flatIndexByValue(project.tilesets)
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* 从客户端报上来的 `have` 里挑出「内容真变了」的那些。
|
|
430
|
+
*
|
|
431
|
+
* 客户端缓存的是**未取模**的 chunk key(画布可以拖到任何地方,同一格会以多个
|
|
432
|
+
* 像素位置出现),而宿主算出来的是**规范** key(0..nx-1)。所以两边要先映射到
|
|
433
|
+
* 同一套坐标才能比 —— 这一步刻意留在宿主:客户端一丝几何都不许算。
|
|
434
|
+
*/
|
|
435
|
+
function pickDropKeys(dirtyCanonical, have, doc) {
|
|
436
|
+
if (have === undefined || have.length === 0)
|
|
437
|
+
return [];
|
|
438
|
+
const dirty = new Set(dirtyCanonical);
|
|
439
|
+
const out = [];
|
|
440
|
+
for (const key of have) {
|
|
441
|
+
const chunk = parseChunkKey(key);
|
|
442
|
+
if (chunk === undefined)
|
|
443
|
+
continue;
|
|
444
|
+
if (dirty.has(chunkKey(canonicalChunk(chunk, doc.cols, doc.rows))))
|
|
445
|
+
out.push(key);
|
|
446
|
+
}
|
|
447
|
+
return out;
|
|
448
|
+
}
|
|
449
|
+
function outcomeOf(projectId, changed, skipped, layout, cells, have, doc) {
|
|
450
|
+
const dirtyChunks = cells.length === 0 ? [] : dirtyChunksFor(cells, layout);
|
|
451
|
+
const state = historyState(projectId);
|
|
452
|
+
return { changed, skipped, dirtyChunks, dropKeys: pickDropKeys(dirtyChunks, have, doc), canUndo: state.canUndo, canRedo: state.canRedo };
|
|
453
|
+
}
|
|
454
|
+
function indexCells(indices, doc) {
|
|
455
|
+
const out = [];
|
|
456
|
+
for (const index of indices) {
|
|
457
|
+
if (index < 0 || index >= doc.cols * doc.rows)
|
|
458
|
+
continue;
|
|
459
|
+
out.push({ r: Math.floor(index / doc.cols), c: index % doc.cols });
|
|
460
|
+
}
|
|
461
|
+
return out;
|
|
462
|
+
}
|
|
463
|
+
function allCells(doc) {
|
|
464
|
+
const out = [];
|
|
465
|
+
for (let r = 0; r < doc.rows; r++)
|
|
466
|
+
for (let c = 0; c < doc.cols; c++)
|
|
467
|
+
out.push({ r, c });
|
|
468
|
+
return out;
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* 应用一批编辑 op(界面拖动时按 ~60ms 批量提交)。
|
|
472
|
+
*
|
|
473
|
+
* 返回「脏 chunk + 该丢哪些客户端缓存」:界面照做即可,不需要自己算
|
|
474
|
+
* 「这一笔影响了哪几格的过渡块」—— 那是宿主的知识。
|
|
475
|
+
*/
|
|
476
|
+
export async function applyMapOps(projectId, ops, opts = {}) {
|
|
477
|
+
const project = await readProjectOrThrow(projectId);
|
|
478
|
+
const doc = await theDocOrFresh(projectId);
|
|
479
|
+
const layout = layoutOf(project.grid, doc.cols, doc.rows);
|
|
480
|
+
const result = applyOps(doc, ops, layout);
|
|
481
|
+
if (result.changed > 0) {
|
|
482
|
+
pushHistory(projectId, { undo: result.undo, redo: ops, stroke: opts.stroke }, doc);
|
|
483
|
+
scheduleDocWrite(projectId, doc);
|
|
484
|
+
}
|
|
485
|
+
return outcomeOf(projectId, result.changed, result.skipped, layout, result.dirty, opts.have, doc);
|
|
486
|
+
}
|
|
487
|
+
export async function undoMap(projectId, have) {
|
|
488
|
+
const project = await readProjectOrThrow(projectId);
|
|
489
|
+
const doc = await theDocOrFresh(projectId);
|
|
490
|
+
const state = history.get(projectId);
|
|
491
|
+
if (state === undefined || state.index < 0)
|
|
492
|
+
return outcomeOf(projectId, 0, [], layoutOf(project.grid, doc.cols, doc.rows), [], have, doc);
|
|
493
|
+
const entry = state.entries[state.index];
|
|
494
|
+
let cells;
|
|
495
|
+
if (entry.snapshot !== undefined) {
|
|
496
|
+
restoreDoc(doc, entry.snapshot.before);
|
|
497
|
+
cells = allCells(doc);
|
|
498
|
+
}
|
|
499
|
+
else {
|
|
500
|
+
let indices;
|
|
501
|
+
try {
|
|
502
|
+
indices = revertOps(doc, entry.undo);
|
|
503
|
+
}
|
|
504
|
+
catch {
|
|
505
|
+
// 栈被容量上限裁剪过之后,这一步的逆操作可能已经对不上:**放弃这一步**,
|
|
506
|
+
// 把它从栈里剔掉让下一次撤销落到更早的一步,而不是每次都卡在同一条上
|
|
507
|
+
// (界面里抛异常就是「点了撤销整个面板报错」)。
|
|
508
|
+
state.entries.splice(state.index, 1);
|
|
509
|
+
state.index = Math.max(-1, state.index - 1);
|
|
510
|
+
return outcomeOf(projectId, 0, [], layoutOf(project.grid, doc.cols, doc.rows), [], have, doc);
|
|
511
|
+
}
|
|
512
|
+
cells = indexCells(indices, doc);
|
|
513
|
+
}
|
|
514
|
+
state.index--;
|
|
515
|
+
scheduleDocWrite(projectId, doc);
|
|
516
|
+
// 结构快照可能把尺寸改回去了 —— 脏块必须按**改完之后**的布局算。
|
|
517
|
+
return outcomeOf(projectId, cells.length, [], layoutOf(project.grid, doc.cols, doc.rows), cells, have, doc);
|
|
518
|
+
}
|
|
519
|
+
export async function redoMap(projectId, have) {
|
|
520
|
+
const project = await readProjectOrThrow(projectId);
|
|
521
|
+
const doc = await theDocOrFresh(projectId);
|
|
522
|
+
const state = history.get(projectId);
|
|
523
|
+
if (state === undefined || state.index >= state.entries.length - 1)
|
|
524
|
+
return outcomeOf(projectId, 0, [], layoutOf(project.grid, doc.cols, doc.rows), [], have, doc);
|
|
525
|
+
const entry = state.entries[state.index + 1];
|
|
526
|
+
let cells;
|
|
527
|
+
if (entry.snapshot !== undefined) {
|
|
528
|
+
restoreDoc(doc, entry.snapshot.after);
|
|
529
|
+
cells = allCells(doc);
|
|
530
|
+
}
|
|
531
|
+
else {
|
|
532
|
+
let indices;
|
|
533
|
+
try {
|
|
534
|
+
indices = revertOps(doc, entry.redo);
|
|
535
|
+
}
|
|
536
|
+
catch {
|
|
537
|
+
state.entries.splice(state.index + 1, 1);
|
|
538
|
+
return outcomeOf(projectId, 0, [], layoutOf(project.grid, doc.cols, doc.rows), [], have, doc);
|
|
539
|
+
}
|
|
540
|
+
cells = indexCells(indices, doc);
|
|
541
|
+
}
|
|
542
|
+
state.index++;
|
|
543
|
+
scheduleDocWrite(projectId, doc);
|
|
544
|
+
// 结构快照可能改掉了尺寸 —— 脏块按**改完之后**的布局算(同 undoMap)。
|
|
545
|
+
return outcomeOf(projectId, cells.length, [], layoutOf(project.grid, doc.cols, doc.rows), cells, have, doc);
|
|
546
|
+
}
|
|
547
|
+
export async function saveMapDocStructure(projectId, patch) {
|
|
548
|
+
const project = await readProjectOrThrow(projectId);
|
|
549
|
+
const doc = await theDocOrFresh(projectId);
|
|
550
|
+
const before = cloneDoc(doc);
|
|
551
|
+
const warnings = [];
|
|
552
|
+
let structural = false;
|
|
553
|
+
let dropped = 0;
|
|
554
|
+
if (typeof patch.name === "string" && patch.name.trim() !== "" && patch.name.trim() !== doc.name) {
|
|
555
|
+
doc.name = patch.name.trim();
|
|
556
|
+
structural = true;
|
|
557
|
+
}
|
|
558
|
+
for (const layerPatch of patch.layers ?? []) {
|
|
559
|
+
if (typeof layerPatch?.name !== "string" || layerPatch.name.trim() === "")
|
|
560
|
+
continue;
|
|
561
|
+
if (renameLayer(doc, layerPatch.id, layerPatch.name.trim()))
|
|
562
|
+
structural = true;
|
|
563
|
+
else
|
|
564
|
+
warnings.push(`图层不存在:${layerPatch?.id}`);
|
|
565
|
+
}
|
|
566
|
+
if (patch.addLayer !== undefined) {
|
|
567
|
+
addLayer(doc, patch.addLayer?.name);
|
|
568
|
+
structural = true;
|
|
569
|
+
}
|
|
570
|
+
if (typeof patch.removeLayerId === "string") {
|
|
571
|
+
if (removeLayer(doc, patch.removeLayerId))
|
|
572
|
+
structural = true;
|
|
573
|
+
else
|
|
574
|
+
warnings.push("至少要留一个图层,最后一个删不掉。");
|
|
575
|
+
}
|
|
576
|
+
if (patch.moveLayer !== undefined) {
|
|
577
|
+
if (moveLayer(doc, patch.moveLayer?.id, Math.round(Number(patch.moveLayer?.toIndex)) || 0))
|
|
578
|
+
structural = true;
|
|
579
|
+
else
|
|
580
|
+
warnings.push(`图层不存在:${patch.moveLayer?.id}`);
|
|
581
|
+
}
|
|
582
|
+
if (typeof patch.clearLayerId === "string") {
|
|
583
|
+
// ⚠️ 先判存在性:`clearLayer` 对「图层不存在」与「本来就空」都返回 0,
|
|
584
|
+
// 不判的话用户会拿到一句「这一层本来就是空的。」—— 而那一层根本不存在。
|
|
585
|
+
if (!doc.layers.some((layer) => layer.id === patch.clearLayerId)) {
|
|
586
|
+
warnings.push(`图层不存在:${patch.clearLayerId}`);
|
|
587
|
+
}
|
|
588
|
+
else if (clearLayer(doc, patch.clearLayerId) > 0) {
|
|
589
|
+
structural = true;
|
|
590
|
+
}
|
|
591
|
+
else {
|
|
592
|
+
warnings.push("这一层本来就是空的。");
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
if (Number.isFinite(patch.cols) || Number.isFinite(patch.rows)) {
|
|
596
|
+
const cols = Number.isFinite(patch.cols) ? Math.round(Number(patch.cols)) : doc.cols;
|
|
597
|
+
const rows = Number.isFinite(patch.rows) ? Math.round(Number(patch.rows)) : doc.rows;
|
|
598
|
+
assertMapSize(cols, rows);
|
|
599
|
+
if (cols !== doc.cols || rows !== doc.rows) {
|
|
600
|
+
const result = resizeDoc(doc, cols, rows);
|
|
601
|
+
dropped = result.dropped;
|
|
602
|
+
structural = true;
|
|
603
|
+
if (dropped > 0)
|
|
604
|
+
warnings.push(`缩小地图丢掉了 ${dropped} 个已画的格子(可以撤销)。`);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
if (structural) {
|
|
608
|
+
const after = cloneDoc(doc);
|
|
609
|
+
doc.updatedAt = new Date().toISOString();
|
|
610
|
+
pushHistory(projectId, { undo: [], redo: [], snapshot: { before, after } }, doc);
|
|
611
|
+
scheduleDocWrite(projectId, doc);
|
|
612
|
+
}
|
|
613
|
+
// 环绕开关落在项目网格上:它只影响渲染与命中测试,不动一个格子。
|
|
614
|
+
if (typeof patch.wrap === "boolean" && patch.wrap !== project.grid.wrap) {
|
|
615
|
+
const grid = { ...project.grid, wrap: patch.wrap };
|
|
616
|
+
assertGrid(grid);
|
|
617
|
+
await patchMapProject(projectId, (fresh) => {
|
|
618
|
+
fresh.grid = grid;
|
|
619
|
+
appendJobLog(fresh.logs, "info", `地图环绕:${patch.wrap === true ? "开" : "关"}`);
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
if (structural)
|
|
623
|
+
await flushMapDoc(projectId);
|
|
624
|
+
return { doc: cloneDoc(doc), dropped, warnings };
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* 导入一张素材图。**属性在这一刻定下来,之后只能删掉重来**(界面上不再提供修改入口)。
|
|
628
|
+
*
|
|
629
|
+
* `opts` 里留空的项走自动识别;给了就用用户的(值不合法就退回识别,不静默改)。
|
|
630
|
+
*/
|
|
631
|
+
export async function importMapTileset(projectId, name, base64, opts = {}) {
|
|
632
|
+
const project = await readProjectOrThrow(projectId);
|
|
633
|
+
if (base64.trim() === "")
|
|
634
|
+
throw new Error("图片内容为空。");
|
|
635
|
+
const bytes = Buffer.from(base64, "base64");
|
|
636
|
+
if (bytes.length === 0)
|
|
637
|
+
throw new Error("图片内容为空。");
|
|
638
|
+
const warnings = [];
|
|
639
|
+
const tileset = await registerTileset(projectId, {
|
|
640
|
+
id: newTilesetId(),
|
|
641
|
+
name: name.trim() === "" ? `素材 ${project.tilesets.length + 1}` : name.trim(),
|
|
642
|
+
bytes,
|
|
643
|
+
overrides: { cell: opts.cell, shape: opts.shape, animRows: opts.animRows }
|
|
644
|
+
}, warnings);
|
|
645
|
+
await patchMapProject(projectId, (fresh) => {
|
|
646
|
+
fresh.tilesets.push(tileset);
|
|
647
|
+
fresh.stages.assets = { status: "done", at: new Date().toISOString(), approved: fresh.stages.assets.approved };
|
|
648
|
+
appendJobLog(fresh.logs, "info", `导入素材:${tileset.name}(${tileset.imageWidth}×${tileset.imageHeight} → ${tileset.tiles.length} 块)`);
|
|
649
|
+
});
|
|
650
|
+
return { tilesets: [tileset], warnings };
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* 装内置素材:**本机现算**(`mapsamplegen.renderSampleTilesets()`),零成本、确定性。
|
|
654
|
+
*
|
|
655
|
+
* 4 张 A2 图(草地 / 土路 / 水 / 石墙)+ 1 张道具网格图。同名素材已经在项目里就
|
|
656
|
+
* 跳过(不会因为点两次变成十张图),跳过的原因写进 warnings。
|
|
657
|
+
*/
|
|
658
|
+
export async function importSampleTileset(projectId) {
|
|
659
|
+
// ⚠️ 先 prime 一次纹理覆盖表(幂等):`renderSampleTilesets()` 是**同步**契约,
|
|
660
|
+
// 而覆盖图(`--ark` 生成的那份 base64)解码要走 ffmpeg。配了覆盖却没 prime 时它会
|
|
661
|
+
// 明确抛错(不静默退回程序化纹理),所以这条路径必须先把这一步做掉 ——
|
|
662
|
+
// 现在覆盖表是空的,这一步是空操作。
|
|
663
|
+
await primeSampleTextures();
|
|
664
|
+
const project = await readProjectOrThrow(projectId);
|
|
665
|
+
const existing = new Set(project.tilesets.map((tileset) => tileset.name));
|
|
666
|
+
const warnings = [];
|
|
667
|
+
const created = [];
|
|
668
|
+
for (const sample of renderSampleTilesets()) {
|
|
669
|
+
if (existing.has(sample.name)) {
|
|
670
|
+
warnings.push(`内置素材「${sample.name}」已经在项目里了,跳过。`);
|
|
671
|
+
continue;
|
|
672
|
+
}
|
|
673
|
+
const tileset = await registerTileset(projectId, {
|
|
674
|
+
id: newTilesetId(),
|
|
675
|
+
name: sample.name,
|
|
676
|
+
bytes: sample.bytes,
|
|
677
|
+
known: { shape: sample.shape, cell: sample.cell, animRows: sample.animRows, builtin: true }
|
|
678
|
+
}, warnings);
|
|
679
|
+
await patchMapProject(projectId, (fresh) => {
|
|
680
|
+
fresh.tilesets.push(tileset);
|
|
681
|
+
fresh.stages.assets = { status: "done", at: new Date().toISOString(), approved: fresh.stages.assets.approved };
|
|
682
|
+
});
|
|
683
|
+
created.push(tileset);
|
|
684
|
+
}
|
|
685
|
+
if (created.length > 0) {
|
|
686
|
+
await patchMapProject(projectId, (fresh) => {
|
|
687
|
+
appendJobLog(fresh.logs, "info", `导入内置素材:${created.map((tileset) => tileset.name).join("、")}`);
|
|
688
|
+
});
|
|
689
|
+
}
|
|
690
|
+
return { tilesets: created, warnings };
|
|
691
|
+
}
|
|
692
|
+
function newTilesetId() {
|
|
693
|
+
return `ts${Date.now().toString(36)}${randomUUID().slice(0, 4)}`;
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* 登记一张素材图:写原图 → 量尺寸 → 定形态与格子 → 建块。
|
|
697
|
+
*
|
|
698
|
+
* `known` 是内置素材那条路:它的形态与格子是**生成时就知道的**(不用再猜)。
|
|
699
|
+
*/
|
|
700
|
+
async function registerTileset(projectId, input, warnings) {
|
|
701
|
+
/**
|
|
702
|
+
* ⚠️ 用户填的属性**先校验**,再写文件:`normalizeCell` 对不合法的尺寸是**抛错**的
|
|
703
|
+
* (明确拒绝,不静默改成别的值),而原图是在这个函数里写盘的 —— 先写后抛会留下孤儿图。
|
|
704
|
+
*/
|
|
705
|
+
const overrideCell = input.overrides?.cell === undefined ? undefined : normalizeCell(input.overrides.cell);
|
|
706
|
+
const ext = sniffImageExt(input.bytes);
|
|
707
|
+
const relative = `tilesets/${input.id}.${ext}`;
|
|
708
|
+
await mkdir(join(mapProjectDir(projectId), "tilesets"), { recursive: true });
|
|
709
|
+
// 写原图(不改写:形态参数随便调,随时能重算)
|
|
710
|
+
await writeFile(mapAssetPath(projectId, relative), input.bytes);
|
|
711
|
+
const size = await probeSize(mapAssetPath(projectId, relative), input.bytes);
|
|
712
|
+
const guess = input.known ?? detectLayout(size.width, size.height);
|
|
713
|
+
const shape = parseTilesetShape(input.overrides?.shape) ?? guess.shape;
|
|
714
|
+
const cell = overrideCell ?? guess.cell;
|
|
715
|
+
const animRows = input.known?.animRows ?? (input.overrides?.animRows === true);
|
|
716
|
+
if (!commonSizeFits(size.width, size.height)) {
|
|
717
|
+
// ⚠️ 文案要跟着产品规则走:属性在新增时定死、界面不再提供修改入口 ——
|
|
718
|
+
// 所以这里告诉用户「删掉重新新增」,而不是让他去找一个界面上没有的入口。
|
|
719
|
+
warnings.push(`这张图(${size.width}×${size.height})不是常见瓦片尺寸的整数倍,已按 ${cell.width}×${cell.height} 试切;不对的话删掉它、按你想要的格子大小重新新增一张。`);
|
|
720
|
+
}
|
|
721
|
+
const tiles = buildTiles({ shape, cell, imageWidth: size.width, imageHeight: size.height, animRows });
|
|
722
|
+
const tileset = {
|
|
723
|
+
id: input.id,
|
|
724
|
+
name: input.name,
|
|
725
|
+
file: relative,
|
|
726
|
+
imageWidth: size.width,
|
|
727
|
+
imageHeight: size.height,
|
|
728
|
+
cell,
|
|
729
|
+
shape,
|
|
730
|
+
animRows,
|
|
731
|
+
variants: variantsOf(shape, cell, size.width, size.height, animRows),
|
|
732
|
+
// 内置素材:属性**不允许修改**(见 saveMapTileset),可以整张删掉,也能一键恢复
|
|
733
|
+
builtin: input.known?.builtin === true ? true : undefined,
|
|
734
|
+
tiles
|
|
735
|
+
};
|
|
736
|
+
assignCorner16Masks(tileset, warnings);
|
|
737
|
+
return tileset;
|
|
738
|
+
}
|
|
739
|
+
/** 整格自动连接(corner16)要的块数(就是 16 个邻接掩码)。 */
|
|
740
|
+
const CORNER16_COUNT = 16;
|
|
741
|
+
/**
|
|
742
|
+
* 给「整格自动连接」素材按位序配掩码(`mapauto` 的 N=1 / E=2 / S=4 / W=8)。
|
|
743
|
+
*
|
|
744
|
+
* ⚠️ 这一段以前**根本没人写**:`MapTile.mask` 只声明不赋值,于是 `maprender` 永远走
|
|
745
|
+
* 「一块掩码都没配」的兜底 —— 整张图只画第一块,而界面上「整格自动连接」是个已经
|
|
746
|
+
* 摆出来的选项,用户选了等于什么都没发生(还不报错)。契约 §3 写的是「导入时由宿主
|
|
747
|
+
* 按位序一次性算好」,落点就在这里。
|
|
748
|
+
*
|
|
749
|
+
* - 只有**恰好 16 块**时才自动配(行优先第 i 块 = 掩码 i,正好是 4×4 的位序表);
|
|
750
|
+
* - 块数不对就**一块都不配**,把原因写进 warnings(界面会显示出来);
|
|
751
|
+
* - 已经配过的一律不动:重切 / 换格子尺寸时 `buildTiles` 会按「矩形 id」整份继承旧
|
|
752
|
+
* tile(含 mask),所以人工调过的位序不会被冲掉。
|
|
753
|
+
*/
|
|
754
|
+
function assignCorner16Masks(tileset, warnings) {
|
|
755
|
+
if (tileset.shape !== "corner16")
|
|
756
|
+
return;
|
|
757
|
+
if (tileset.tiles.every((tile) => typeof tile.mask === "number"))
|
|
758
|
+
return;
|
|
759
|
+
if (tileset.tiles.length !== CORNER16_COUNT) {
|
|
760
|
+
warnings.push(`整格自动连接需要 ${CORNER16_COUNT} 块,这张素材有 ${tileset.tiles.length} 块:没有自动配掩码,画出来会统一用第一块。`);
|
|
761
|
+
return;
|
|
762
|
+
}
|
|
763
|
+
tileset.tiles.forEach((tile, index) => {
|
|
764
|
+
tile.mask = index;
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
/** 尺寸能不能被常见瓦片尺寸整除(A2 图另有一条 `height === 5×格子高` 的规则)。 */
|
|
768
|
+
function commonSizeFits(width, height) {
|
|
769
|
+
return COMMON_TILE_SIZES.some((size) => width % size === 0 && height % size === 0) || COMMON_TILE_SIZES.some((size) => height === size * 5 && width % size === 0);
|
|
770
|
+
}
|
|
771
|
+
async function probeSize(file, bytes) {
|
|
772
|
+
const fromHeader = pngSize(bytes);
|
|
773
|
+
if (fromHeader !== undefined)
|
|
774
|
+
return fromHeader;
|
|
775
|
+
return probeImageSize(file);
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* 改素材(名称 / 格子尺寸 / 形态 / 逐行动画)。
|
|
779
|
+
*
|
|
780
|
+
* ⚠️ 改了这些,图块序号可能整体平移 —— 地图里存的是序号,**必须按
|
|
781
|
+
* 「素材 id + 图块 id」把地图的每一格重新映射**,否则会出现「明明画了却
|
|
782
|
+
* 变成别的块」:序号指向了新表里的另一个位置。对不上的格子清零并计数。
|
|
783
|
+
*/
|
|
784
|
+
export async function saveMapTileset(projectId, tilesetId, patch) {
|
|
785
|
+
const project = await readProjectOrThrow(projectId);
|
|
786
|
+
const beforeKeys = indexKeys(project.tilesets);
|
|
787
|
+
const warnings = [];
|
|
788
|
+
const nextCell = normalizeCell(patch.cell);
|
|
789
|
+
const nextShape = parseTilesetShape(patch.shape);
|
|
790
|
+
let updated;
|
|
791
|
+
await patchMapProject(projectId, (fresh) => {
|
|
792
|
+
const tileset = fresh.tilesets.find((item) => item.id === tilesetId);
|
|
793
|
+
if (tileset === undefined)
|
|
794
|
+
throw new Error(`素材不存在:${tilesetId}`);
|
|
795
|
+
/**
|
|
796
|
+
* 内置素材的属性**不允许修改**(这是产品约定:属性在新增那一刻定下来)。
|
|
797
|
+
* 想换形态 / 格子就自己新增一张;内置的可以整张删掉,再用「恢复默认素材」拿回来。
|
|
798
|
+
*/
|
|
799
|
+
if (tileset.builtin === true)
|
|
800
|
+
throw new Error(`「${tileset.name}」是内置素材,属性不能改 —— 可以删掉它,或者自己新增一张素材。`);
|
|
801
|
+
if (typeof patch.name === "string" && patch.name.trim() !== "")
|
|
802
|
+
tileset.name = patch.name.trim();
|
|
803
|
+
const shape = patch.shape ?? tileset.shape;
|
|
804
|
+
const cell = nextCell ?? tileset.cell;
|
|
805
|
+
const animRows = typeof patch.animRows === "boolean" ? patch.animRows : tileset.animRows;
|
|
806
|
+
const changed = shape !== tileset.shape || cell.width !== tileset.cell.width || cell.height !== tileset.cell.height || animRows !== tileset.animRows;
|
|
807
|
+
if (changed) {
|
|
808
|
+
const previousIds = new Set(tileset.tiles.map((tile) => tile.id));
|
|
809
|
+
tileset.shape = shape;
|
|
810
|
+
tileset.cell = cell;
|
|
811
|
+
tileset.animRows = animRows;
|
|
812
|
+
tileset.variants = variantsOf(shape, cell, tileset.imageWidth, tileset.imageHeight, animRows);
|
|
813
|
+
tileset.tiles = buildTiles({ shape, cell, imageWidth: tileset.imageWidth, imageHeight: tileset.imageHeight, animRows }, tileset.tiles);
|
|
814
|
+
const removed = [...previousIds].filter((id) => !tileset.tiles.some((tile) => tile.id === id)).length;
|
|
815
|
+
if (removed > 0)
|
|
816
|
+
warnings.push(`${removed} 块的元数据随切分变化被丢掉(矩形已经不存在了)。`);
|
|
817
|
+
appendJobLog(fresh.logs, "info", `改素材形态:${tileset.name}(${shape} / ${cell.width}×${cell.height})`);
|
|
818
|
+
}
|
|
819
|
+
// 换形态也要能补掩码:用户可能先按普通图块导入、后来才改成「整格自动连接」。
|
|
820
|
+
assignCorner16Masks(tileset, warnings);
|
|
821
|
+
updated = tileset;
|
|
822
|
+
});
|
|
823
|
+
if (updated === undefined)
|
|
824
|
+
throw new Error(`素材不存在:${tilesetId}`);
|
|
825
|
+
const fresh = await readProjectOrThrow(projectId);
|
|
826
|
+
const remap = await remapDocToIndices(projectId, beforeKeys, indexKeys(fresh.tilesets));
|
|
827
|
+
warnings.push(...remap.warnings);
|
|
828
|
+
return { tileset: updated, warnings };
|
|
829
|
+
}
|
|
830
|
+
/** 序号 → 「素材 id / 图块 id」键(重新映射时用它认人,而不是认序号)。 */
|
|
831
|
+
function indexKeys(tilesets) {
|
|
832
|
+
return new Map(flatTiles(tilesets).map((tile) => [tile.index, `${tile.tilesetId}/${tile.tile.id}`]));
|
|
833
|
+
}
|
|
834
|
+
/**
|
|
835
|
+
* 把地图每一格的序号从旧表平移到新表。
|
|
836
|
+
*
|
|
837
|
+
* 找不到对应图块的格子清零并计数:**不清零的后果是静默画错块**(旧序号落到
|
|
838
|
+
* 新表里另一个位置),比报错难查得多。
|
|
839
|
+
*/
|
|
840
|
+
async function remapDocToIndices(projectId, before, after) {
|
|
841
|
+
const doc = await readTheDoc(projectId);
|
|
842
|
+
if (doc === undefined)
|
|
843
|
+
return { pruned: 0, warnings: [] };
|
|
844
|
+
const newIndexByKey = new Map([...after.entries()].map(([index, key]) => [key, index]));
|
|
845
|
+
let lost = 0;
|
|
846
|
+
let remapped = 0;
|
|
847
|
+
for (const layer of doc.layers) {
|
|
848
|
+
const data = doc.data[layer.id];
|
|
849
|
+
if (data === undefined)
|
|
850
|
+
continue;
|
|
851
|
+
for (let i = 0; i < data.length; i++) {
|
|
852
|
+
const value = data[i];
|
|
853
|
+
if (value <= 0)
|
|
854
|
+
continue;
|
|
855
|
+
const key = before.get(value);
|
|
856
|
+
const next = key === undefined ? undefined : newIndexByKey.get(key);
|
|
857
|
+
if (next === undefined) {
|
|
858
|
+
data[i] = 0;
|
|
859
|
+
lost++;
|
|
860
|
+
}
|
|
861
|
+
else if (next !== value) {
|
|
862
|
+
data[i] = next;
|
|
863
|
+
remapped++;
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
const warnings = [];
|
|
868
|
+
if (lost > 0)
|
|
869
|
+
warnings.push(`有 ${lost} 个格子指向的图块已经不存在,已清空。`);
|
|
870
|
+
if (remapped > 0)
|
|
871
|
+
warnings.push(`有 ${remapped} 个格子跟着素材变化重新映射了图块序号。`);
|
|
872
|
+
if (lost > 0 || remapped > 0)
|
|
873
|
+
await writeTheDoc(projectId, doc);
|
|
874
|
+
return { pruned: lost, warnings };
|
|
875
|
+
}
|
|
876
|
+
export async function removeMapTileset(projectId, tilesetId) {
|
|
877
|
+
const project = await readProjectOrThrow(projectId);
|
|
878
|
+
const tileset = project.tilesets.find((item) => item.id === tilesetId);
|
|
879
|
+
if (tileset === undefined)
|
|
880
|
+
throw new Error(`素材不存在:${tilesetId}`);
|
|
881
|
+
const beforeKeys = indexKeys(project.tilesets);
|
|
882
|
+
await patchMapProject(projectId, (fresh) => {
|
|
883
|
+
fresh.tilesets = fresh.tilesets.filter((item) => item.id !== tilesetId);
|
|
884
|
+
appendJobLog(fresh.logs, "info", `移除素材:${tileset.name}`);
|
|
885
|
+
});
|
|
886
|
+
await rm(mapAssetPath(projectId, tileset.file), { force: true });
|
|
887
|
+
const fresh = await readProjectOrThrow(projectId);
|
|
888
|
+
const remap = await remapDocToIndices(projectId, beforeKeys, indexKeys(fresh.tilesets));
|
|
889
|
+
return { removed: tileset.name, pruned: remap.pruned, warnings: remap.warnings };
|
|
890
|
+
}
|
|
891
|
+
function xorshift32(seed) {
|
|
892
|
+
let state = (seed >>> 0) === 0 ? 0xffffffff : seed >>> 0;
|
|
893
|
+
const next = () => {
|
|
894
|
+
state = (state ^ (state << 13)) >>> 0;
|
|
895
|
+
state = (state ^ (state >>> 17)) >>> 0;
|
|
896
|
+
state = (state ^ (state << 5)) >>> 0;
|
|
897
|
+
return state;
|
|
898
|
+
};
|
|
899
|
+
return {
|
|
900
|
+
upto: (inclusiveMax) => (inclusiveMax <= 0 ? 0 : (next() & 0x7fffffff) % (inclusiveMax + 1))
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
/** 不传种子就现抽一个(返回给调用方,方便「同一个种子再铺一次」)。 */
|
|
904
|
+
function normalizeSeed(seed) {
|
|
905
|
+
if (seed === undefined || seed === null)
|
|
906
|
+
return Number.parseInt(randomUUID().slice(0, 8), 16) >>> 0 || 1;
|
|
907
|
+
const n = Math.round(Number(seed));
|
|
908
|
+
if (!Number.isFinite(n))
|
|
909
|
+
throw new Error(`种子必须是整数:${String(seed)}`);
|
|
910
|
+
return (n >>> 0) === 0 ? 0xffffffff : n >>> 0;
|
|
911
|
+
}
|
|
912
|
+
async function normalizeTilePool(tiles, project) {
|
|
913
|
+
const available = flatTiles(project.tilesets).map((tile) => tile.index);
|
|
914
|
+
if (tiles === undefined || tiles.length === 0)
|
|
915
|
+
return available;
|
|
916
|
+
const max = available.length;
|
|
917
|
+
return tiles.map((value) => {
|
|
918
|
+
const n = Math.round(Number(value));
|
|
919
|
+
if (!Number.isFinite(n) || n < 0 || n > max)
|
|
920
|
+
throw new Error(`图块序号越界:${String(value)}(可选 0..${max})`);
|
|
921
|
+
return n;
|
|
922
|
+
});
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* 一键铺满某一层(整个操作是**一次提交**,所以一次撤销就能回到原样)。
|
|
926
|
+
*
|
|
927
|
+
* 三种算法都是本机算的、零计费:
|
|
928
|
+
* - `random`:整层在 `tiles` 里均匀随机。
|
|
929
|
+
* - `maze`:奇数尺寸上的迭代 DFS 挖洞;墙 = `tiles[0]`、通路 = `tiles[1] ?? 0`。
|
|
930
|
+
* - `continent`:17×17 菱形四角递归插值 + 种子随机,按 `tiles` 顺序映射
|
|
931
|
+
* `[浅底, 海, 草地, 雪]`,不足 4 个时回退到 `tiles[0]`。
|
|
932
|
+
*/
|
|
933
|
+
export async function runMapGenerate(projectId, opts) {
|
|
934
|
+
const project = await readProjectOrThrow(projectId);
|
|
935
|
+
const doc = await theDocOrFresh(projectId);
|
|
936
|
+
const layerId = typeof opts.layerId === "string" && doc.layers.some((layer) => layer.id === opts.layerId) ? opts.layerId : doc.layers[0]?.id;
|
|
937
|
+
if (layerId === undefined)
|
|
938
|
+
throw new Error("地图文档没有图层,先建一层。");
|
|
939
|
+
if (opts.kind !== "random" && opts.kind !== "maze" && opts.kind !== "continent")
|
|
940
|
+
throw new Error(`未知生成算法:${String(opts.kind)}(可选 random / maze / continent)`);
|
|
941
|
+
const pool = await normalizeTilePool(opts.tiles, project);
|
|
942
|
+
const seed = normalizeSeed(opts.seed);
|
|
943
|
+
const warnings = [];
|
|
944
|
+
const values = generateValues(opts.kind, doc.cols, doc.rows, pool, seed, warnings);
|
|
945
|
+
const cells = [];
|
|
946
|
+
for (let r = 0; r < doc.rows; r++) {
|
|
947
|
+
for (let c = 0; c < doc.cols; c++)
|
|
948
|
+
cells.push({ r, c, tile: values[r * doc.cols + c] ?? 0 });
|
|
949
|
+
}
|
|
950
|
+
const ops = [{ kind: "paint", layerId, cells }];
|
|
951
|
+
const result = await applyMapOps(projectId, ops, {});
|
|
952
|
+
await patchMapProject(projectId, (fresh) => {
|
|
953
|
+
const label = opts.kind === "random" ? "随机铺满" : opts.kind === "maze" ? "迷宫" : "大陆";
|
|
954
|
+
appendJobLog(fresh.logs, "info", `一键生成(${label}):改了 ${result.changed} 格,种子 ${seed}`);
|
|
955
|
+
});
|
|
956
|
+
return { changed: result.changed, seed, warnings: [...warnings, ...result.skipped] };
|
|
957
|
+
}
|
|
958
|
+
function generateValues(kind, cols, rows, tiles, seed, warnings) {
|
|
959
|
+
if (kind === "random")
|
|
960
|
+
return generateRandom(cols, rows, tiles, seed, warnings);
|
|
961
|
+
if (kind === "maze")
|
|
962
|
+
return generateMaze(cols, rows, tiles, seed, warnings);
|
|
963
|
+
return generateContinent(cols, rows, tiles, seed, warnings);
|
|
964
|
+
}
|
|
965
|
+
function generateRandom(cols, rows, tiles, seed, warnings) {
|
|
966
|
+
if (tiles.length === 0) {
|
|
967
|
+
warnings.push("项目里还没有图块:随机铺出来全是空的。先导入素材(或 importSampleTileset 装内置素材)。");
|
|
968
|
+
return new Array(cols * rows).fill(0);
|
|
969
|
+
}
|
|
970
|
+
const rng = xorshift32(seed);
|
|
971
|
+
const out = new Array(cols * rows);
|
|
972
|
+
for (let i = 0; i < out.length; i++)
|
|
973
|
+
out[i] = tiles[rng.upto(tiles.length - 1)];
|
|
974
|
+
return out;
|
|
975
|
+
}
|
|
976
|
+
/**
|
|
977
|
+
* 迷宫:奇数尺寸上的**迭代 DFS 挖洞**(AsLib `asMazeMapMake` 同款)。
|
|
978
|
+
*
|
|
979
|
+
* 偶数边长按 `cols-1` / `rows-1` 生成,多出来的那一行 / 一列**留空**(0),
|
|
980
|
+
* 并在 warnings 里说清楚 —— 静默丢掉半行比出个缺口更难查。
|
|
981
|
+
*/
|
|
982
|
+
function generateMaze(cols, rows, tiles, seed, warnings) {
|
|
983
|
+
const width = cols % 2 === 1 ? cols : cols - 1;
|
|
984
|
+
const height = rows % 2 === 1 ? rows : rows - 1;
|
|
985
|
+
const wall = tiles[0] ?? 0;
|
|
986
|
+
const path = tiles.length >= 2 ? tiles[1] : 0;
|
|
987
|
+
if (tiles.length === 0)
|
|
988
|
+
warnings.push("没有指定图块:迷宫只画得出 0(空),先导入素材或用 tiles 指定墙与通路。");
|
|
989
|
+
if (cols % 2 === 0 || rows % 2 === 0)
|
|
990
|
+
warnings.push(`地图尺寸 ${cols}×${rows} 是偶数:迷宫按 ${width}×${height} 生成,多出来的那一行 / 一列留空。`);
|
|
991
|
+
const out = new Array(cols * rows).fill(0);
|
|
992
|
+
if (width < 3 || height < 3) {
|
|
993
|
+
warnings.push(`地图太小(${cols}×${rows}):迷宫至少要 3×3,这一层留空。`);
|
|
994
|
+
return out;
|
|
995
|
+
}
|
|
996
|
+
for (let r = 0; r < height; r++)
|
|
997
|
+
for (let c = 0; c < width; c++)
|
|
998
|
+
out[r * cols + c] = wall;
|
|
999
|
+
const rng = xorshift32(seed);
|
|
1000
|
+
const visited = new Uint8Array(cols * rows);
|
|
1001
|
+
const stack = [{ r: 1, c: 1 }];
|
|
1002
|
+
out[cols + 1] = path;
|
|
1003
|
+
visited[cols + 1] = 1;
|
|
1004
|
+
const steps = [
|
|
1005
|
+
{ dr: -1, dc: 0 },
|
|
1006
|
+
{ dr: 0, dc: -1 },
|
|
1007
|
+
{ dr: 1, dc: 0 },
|
|
1008
|
+
{ dr: 0, dc: 1 }
|
|
1009
|
+
];
|
|
1010
|
+
while (stack.length > 0) {
|
|
1011
|
+
const current = stack[stack.length - 1];
|
|
1012
|
+
const options = steps.filter((step) => {
|
|
1013
|
+
const r = current.r + step.dr * 2;
|
|
1014
|
+
const c = current.c + step.dc * 2;
|
|
1015
|
+
return r > 0 && r < height - 1 && c > 0 && c < width - 1 && visited[r * cols + c] === 0;
|
|
1016
|
+
});
|
|
1017
|
+
if (options.length === 0) {
|
|
1018
|
+
stack.pop();
|
|
1019
|
+
continue;
|
|
1020
|
+
}
|
|
1021
|
+
const step = options[rng.upto(options.length - 1)];
|
|
1022
|
+
const nextR = current.r + step.dr * 2;
|
|
1023
|
+
const nextC = current.c + step.dc * 2;
|
|
1024
|
+
out[(current.r + step.dr) * cols + (current.c + step.dc)] = path;
|
|
1025
|
+
out[nextR * cols + nextC] = path;
|
|
1026
|
+
visited[nextR * cols + nextC] = 1;
|
|
1027
|
+
stack.push({ r: nextR, c: nextC });
|
|
1028
|
+
}
|
|
1029
|
+
return out;
|
|
1030
|
+
}
|
|
1031
|
+
/**
|
|
1032
|
+
* 世界地图的节点网格:17×17 个节点 = 16×16 个格子(AsLib 的区块边长同款)。
|
|
1033
|
+
*
|
|
1034
|
+
* 区块边长固定 16:地图尺寸不是 16 的倍数时,最后一个区块照样按 16 格生成高度场,
|
|
1035
|
+
* **只取实际存在的那几格**(补齐 + 裁掉)—— 少这一步,接缝上的节点就对不齐了。
|
|
1036
|
+
*/
|
|
1037
|
+
const WORLD_CHUNK = 16;
|
|
1038
|
+
const WORLD_NODES = WORLD_CHUNK + 1;
|
|
1039
|
+
/**
|
|
1040
|
+
* 大陆 / 海岛:AsLib `asWorldMapSimplePaint` 那套(四角随机 + 菱形方形递归)。
|
|
1041
|
+
*
|
|
1042
|
+
* ## 为什么角点必须是**纯函数**
|
|
1043
|
+
*
|
|
1044
|
+
* 第一版给每个区块开一条独立随机流、各抽四个角,结果相邻区块在共享边上取值不同:
|
|
1045
|
+
* 48×48 导出成 PNG 就是一盘**轴对齐的大矩形**(一整块纯蓝、一整块纯棕,中间一个硬十字)。
|
|
1046
|
+
* 现在角点高度只由「全局角点坐标」决定(`cornerHeight`),于是:
|
|
1047
|
+
*
|
|
1048
|
+
* - 区块 `(i,j)` 的右下角 == 区块 `(i+1,j+1)` 的左上角;
|
|
1049
|
+
* - 区块 `(i,j)` 的右边 == 区块 `(i+1,j)` 的左边(角点相同 ⇒ 两边的第一次插值相同);
|
|
1050
|
+
* - 连**边中点的抖动**也只由「全局节点坐标 + 这一层的 size」决定,所以整条共享边在
|
|
1051
|
+
* 两个区块里算出来的是同一个值 —— 接缝处不会有细缝。
|
|
1052
|
+
*/
|
|
1053
|
+
function generateContinent(cols, rows, tiles, seed, warnings) {
|
|
1054
|
+
const under = tiles[0] ?? 0;
|
|
1055
|
+
const sea = tiles[1] ?? under;
|
|
1056
|
+
const green = tiles[2] ?? under;
|
|
1057
|
+
const snow = tiles[3] ?? under;
|
|
1058
|
+
if (tiles.length < 4)
|
|
1059
|
+
warnings.push(`只给了 ${tiles.length} 个图块:大陆按「浅底 / 海 / 草地 / 雪」的顺序取,缺的回退到第 1 块。`);
|
|
1060
|
+
if (tiles.length === 0)
|
|
1061
|
+
warnings.push("项目里还没有图块:大陆铺出来全是空的。先导入素材(或 importSampleTileset 装内置素材)。");
|
|
1062
|
+
const out = new Array(cols * rows).fill(under);
|
|
1063
|
+
const chunkCols = Math.max(1, Math.ceil(cols / WORLD_CHUNK));
|
|
1064
|
+
const chunkRows = Math.max(1, Math.ceil(rows / WORLD_CHUNK));
|
|
1065
|
+
for (let chunkI = 0; chunkI < chunkCols; chunkI++) {
|
|
1066
|
+
for (let chunkJ = 0; chunkJ < chunkRows; chunkJ++) {
|
|
1067
|
+
const baseI = chunkI * WORLD_CHUNK;
|
|
1068
|
+
const baseJ = chunkJ * WORLD_CHUNK;
|
|
1069
|
+
const levels = worldLevels(seed, chunkI, chunkJ);
|
|
1070
|
+
for (let i2 = 0; i2 < WORLD_CHUNK; i2++) {
|
|
1071
|
+
const r = baseI + i2;
|
|
1072
|
+
if (r >= rows)
|
|
1073
|
+
break;
|
|
1074
|
+
for (let j2 = 0; j2 < WORLD_CHUNK; j2++) {
|
|
1075
|
+
const c = baseJ + j2;
|
|
1076
|
+
if (c >= cols)
|
|
1077
|
+
break;
|
|
1078
|
+
const level = levels[i2][j2];
|
|
1079
|
+
// 色带照 AsLib 原样:<15 雪、≤50 草地、(50,110] 浅底、>110 海。
|
|
1080
|
+
out[r * cols + c] = level < 15 ? snow : level <= 50 ? green : level <= 110 ? under : sea;
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
return out;
|
|
1086
|
+
}
|
|
1087
|
+
/** 全局角点高度:**只看角点坐标**(相邻区块共享的那个角必然算出同一个值)。 */
|
|
1088
|
+
function cornerHeight(seed, cornerI, cornerJ) {
|
|
1089
|
+
// 种子混合式照 AsLib:seed + i + j*0x3220 + (i^j)*0x292。
|
|
1090
|
+
const mixed = (seed + cornerI + Math.imul(cornerJ, 0x3220) + Math.imul(cornerI ^ cornerJ, 0x292)) >>> 0;
|
|
1091
|
+
return xorshift32(mixed === 0 ? 0xffffffff : mixed).upto(255);
|
|
1092
|
+
}
|
|
1093
|
+
/**
|
|
1094
|
+
* 一个节点的抖动:**全局节点坐标 + 这一层的 size** 的纯函数。
|
|
1095
|
+
*
|
|
1096
|
+
* 「纯」是接缝连续的关键:共享边上的节点会被左右两个区块各算一次,只有输入完全一样
|
|
1097
|
+
* 才会得到同一个高度。用 `Map` 缓存没有必要 —— 一次 48×48 也就几千次哈希。
|
|
1098
|
+
*/
|
|
1099
|
+
function nodeJitter(seed, nodeI, nodeJ, size) {
|
|
1100
|
+
if (size <= 0)
|
|
1101
|
+
return 0;
|
|
1102
|
+
let hash = (seed ^ Math.imul(nodeI + 1, 0x3220) ^ Math.imul(nodeJ + 1, 0x292) ^ Math.imul(size + 1, 0x9e3779b1)) >>> 0;
|
|
1103
|
+
hash = (hash ^ (hash >>> 15)) >>> 0;
|
|
1104
|
+
hash = Math.imul(hash, 0x85ebca6b) >>> 0;
|
|
1105
|
+
hash = (hash ^ (hash >>> 13)) >>> 0;
|
|
1106
|
+
hash = Math.imul(hash, 0xc2b2ae35) >>> 0;
|
|
1107
|
+
return ((hash ^ (hash >>> 16)) >>> 0) % (size + 1);
|
|
1108
|
+
}
|
|
1109
|
+
function clamp255(value) {
|
|
1110
|
+
return value < 0 ? 0 : value > 255 ? 255 : value;
|
|
1111
|
+
}
|
|
1112
|
+
/**
|
|
1113
|
+
* 一个区块的高度场:四角取自 `cornerHeight` → 菱形方形递归到 **size === 1**(每格一个节点)。
|
|
1114
|
+
*
|
|
1115
|
+
* 每个节点都只赋值一次(正方形中心 + 四条边中点),所以共享边的两边输入相同、
|
|
1116
|
+
* 结果也相同。边的中点**也加抖动**:只做平均的话一个区块就是一块平板(AsLib 的观感上限)。
|
|
1117
|
+
*/
|
|
1118
|
+
function worldLevels(seed, chunkI, chunkJ) {
|
|
1119
|
+
const levels = Array.from({ length: WORLD_NODES }, () => new Array(WORLD_NODES).fill(0));
|
|
1120
|
+
const baseI = chunkI * WORLD_CHUNK;
|
|
1121
|
+
const baseJ = chunkJ * WORLD_CHUNK;
|
|
1122
|
+
const last = WORLD_CHUNK;
|
|
1123
|
+
const topLeft = cornerHeight(seed, baseI, baseJ);
|
|
1124
|
+
const topRight = cornerHeight(seed, baseI, baseJ + last);
|
|
1125
|
+
const bottomLeft = cornerHeight(seed, baseI + last, baseJ);
|
|
1126
|
+
const bottomRight = cornerHeight(seed, baseI + last, baseJ + last);
|
|
1127
|
+
levels[0][0] = topLeft;
|
|
1128
|
+
levels[0][last] = topRight;
|
|
1129
|
+
levels[last][0] = bottomLeft;
|
|
1130
|
+
levels[last][last] = bottomRight;
|
|
1131
|
+
subdivide(levels, seed, baseI, baseJ, WORLD_CHUNK / 2, WORLD_CHUNK / 2, WORLD_CHUNK / 2, topLeft, topRight, bottomLeft, bottomRight);
|
|
1132
|
+
return levels;
|
|
1133
|
+
}
|
|
1134
|
+
/**
|
|
1135
|
+
* 菱形方形的一步:填正方形中心与四条边中点,再递归四个子方块。
|
|
1136
|
+
*
|
|
1137
|
+
* `(r,c)` 是本区块内**正方形的中心**(也是区块内坐标),`size` 是半边长;
|
|
1138
|
+
* `baseI/baseJ` 把它换算成全局节点坐标 —— 抖动的输入必须是全局坐标,否则相邻区块
|
|
1139
|
+
* 在共享边上各抖各的。
|
|
1140
|
+
*/
|
|
1141
|
+
function subdivide(levels, seed, baseI, baseJ, r, c, size, topLeft, topRight, bottomLeft, bottomRight) {
|
|
1142
|
+
if (size < 1)
|
|
1143
|
+
return;
|
|
1144
|
+
const jitterAt = (nodeI, nodeJ) => nodeJitter(seed, baseI + nodeI, baseJ + nodeJ, size);
|
|
1145
|
+
const center = clamp255(((topLeft + topRight + bottomLeft + bottomRight) >> 2) + jitterAt(r, c));
|
|
1146
|
+
const topEdge = clamp255(((topLeft + topRight) >> 1) + jitterAt(r - size, c));
|
|
1147
|
+
const bottomEdge = clamp255(((bottomLeft + bottomRight) >> 1) + jitterAt(r + size, c));
|
|
1148
|
+
const leftEdge = clamp255(((topLeft + bottomLeft) >> 1) + jitterAt(r, c - size));
|
|
1149
|
+
const rightEdge = clamp255(((topRight + bottomRight) >> 1) + jitterAt(r, c + size));
|
|
1150
|
+
levels[r][c] = center;
|
|
1151
|
+
levels[r - size][c] = topEdge;
|
|
1152
|
+
levels[r + size][c] = bottomEdge;
|
|
1153
|
+
levels[r][c - size] = leftEdge;
|
|
1154
|
+
levels[r][c + size] = rightEdge;
|
|
1155
|
+
const half = size >> 1;
|
|
1156
|
+
if (half < 1)
|
|
1157
|
+
return;
|
|
1158
|
+
subdivide(levels, seed, baseI, baseJ, r - half, c - half, half, topLeft, topEdge, leftEdge, center);
|
|
1159
|
+
subdivide(levels, seed, baseI, baseJ, r - half, c + half, half, topEdge, topRight, center, rightEdge);
|
|
1160
|
+
subdivide(levels, seed, baseI, baseJ, r + half, c - half, half, leftEdge, center, bottomLeft, bottomEdge);
|
|
1161
|
+
subdivide(levels, seed, baseI, baseJ, r + half, c + half, half, center, rightEdge, bottomEdge, bottomRight);
|
|
1162
|
+
}
|
|
1163
|
+
/**
|
|
1164
|
+
* 视口 → 绘制计划。
|
|
1165
|
+
*
|
|
1166
|
+
* `viewCellRange` 会带一行 padding(自动连接要看邻居),环绕时它的起点可以是
|
|
1167
|
+
* 负数、也可以超过地图尺寸 —— 所以同一格会以多个像素位置出现在计划里,这是
|
|
1168
|
+
* 有意的:界面只负责 drawImage,不需要知道环绕。
|
|
1169
|
+
*/
|
|
1170
|
+
export async function mapPlan(projectId, o) {
|
|
1171
|
+
const project = await readProjectOrThrow(projectId);
|
|
1172
|
+
let doc = await theDocOrFresh(projectId);
|
|
1173
|
+
/**
|
|
1174
|
+
* 预览期间必须**强制回传**被这一笔碰到的块,哪怕客户端说「我有」。
|
|
1175
|
+
*
|
|
1176
|
+
* ⚠️ 这是真机踩出来的:客户端查计划时会带 `have`(我有哪些块),而预览改的格子在
|
|
1177
|
+
* 它已有的块里 —— 宿主一看「你有」就不发了,于是**拖了一路什么都没有**,
|
|
1178
|
+
* 松手提交后 `dropKeys` 才让那几块重拉、画面才出现。自检当时那条断言写得太松
|
|
1179
|
+
* (`chunks 有 op` 或 `visibleKeys 非空`),把它放过去了。
|
|
1180
|
+
*/
|
|
1181
|
+
const forced = new Set();
|
|
1182
|
+
if (Array.isArray(o.pending) && o.pending.length > 0) {
|
|
1183
|
+
const preview = cloneDoc(doc);
|
|
1184
|
+
// 同一个 applyOps:预览与真实编辑**走同一套校验与语义**,不会画出「提交后不一样」的东西
|
|
1185
|
+
const previewLayout = layoutOf(project.grid, preview.cols, preview.rows);
|
|
1186
|
+
const overlay = applyOps(preview, o.pending, previewLayout);
|
|
1187
|
+
doc = preview;
|
|
1188
|
+
for (const key of dirtyChunksFor(overlay.dirty, previewLayout))
|
|
1189
|
+
forced.add(key);
|
|
1190
|
+
}
|
|
1191
|
+
const context = renderContextFor(project, doc);
|
|
1192
|
+
const range = viewCellRange(context.layout, o.view);
|
|
1193
|
+
const covering = chunksInRange(range);
|
|
1194
|
+
const truncated = covering.length > MAX_PLAN_CHUNKS;
|
|
1195
|
+
const visible = truncated ? covering.slice(0, MAX_PLAN_CHUNKS) : covering;
|
|
1196
|
+
const visibleKeys = visible.map(chunkKey);
|
|
1197
|
+
const wanted = new Set(visibleKeys);
|
|
1198
|
+
const have = new Set(o.have ?? []);
|
|
1199
|
+
const plan = buildPlan(context, doc, { range, layers: o.layerIds === undefined ? undefined : [...o.layerIds], includeLegend: true });
|
|
1200
|
+
return {
|
|
1201
|
+
grid: project.grid,
|
|
1202
|
+
cols: doc.cols,
|
|
1203
|
+
rows: doc.rows,
|
|
1204
|
+
bounds: plan.bounds,
|
|
1205
|
+
visibleKeys,
|
|
1206
|
+
chunks: plan.chunks.filter((chunk) => wanted.has(chunk.key) && (!have.has(chunk.key) || forced.has(chunk.key))),
|
|
1207
|
+
legend: plan.legend,
|
|
1208
|
+
fps: plan.fps,
|
|
1209
|
+
frameCount: plan.frameCount,
|
|
1210
|
+
truncated,
|
|
1211
|
+
warnings: plan.warnings
|
|
1212
|
+
};
|
|
1213
|
+
}
|
|
1214
|
+
// ── 视图 ──────────────────────────────────────────────────────────────────
|
|
1215
|
+
export function mapAssetBase(projectId) {
|
|
1216
|
+
return `/dsh-game-material-master/map-assets/${projectId}/`;
|
|
1217
|
+
}
|
|
1218
|
+
/**
|
|
1219
|
+
* 界面视图。
|
|
1220
|
+
*
|
|
1221
|
+
* `options` 里的 `projectId` / `origin` 是旧调用的兼容位(**视图一律用相对路径**,
|
|
1222
|
+
* 绝对 URL 由 `mapSnapshot` 拼给模型)—— 留着是为了不改动已有的调用点签名。
|
|
1223
|
+
*/
|
|
1224
|
+
export async function mapView(p, options = {}) {
|
|
1225
|
+
void options;
|
|
1226
|
+
const doc = await theDocOrFresh(p.id);
|
|
1227
|
+
const flat = flatTiles(p.tilesets);
|
|
1228
|
+
const listing = await readExportListingRelative(p);
|
|
1229
|
+
const state = historyState(p.id);
|
|
1230
|
+
const layers = doc.layers.map((layer) => ({ id: layer.id, name: layer.name, filled: filledCount(doc, layer.id) }));
|
|
1231
|
+
return {
|
|
1232
|
+
id: p.id,
|
|
1233
|
+
name: p.name,
|
|
1234
|
+
assetBase: mapAssetBase(p.id),
|
|
1235
|
+
grid: p.grid,
|
|
1236
|
+
cols: doc.cols,
|
|
1237
|
+
rows: doc.rows,
|
|
1238
|
+
tilesets: p.tilesets.map((tileset) => ({
|
|
1239
|
+
id: tileset.id,
|
|
1240
|
+
name: tileset.name,
|
|
1241
|
+
file: tileset.file,
|
|
1242
|
+
imageWidth: tileset.imageWidth,
|
|
1243
|
+
imageHeight: tileset.imageHeight,
|
|
1244
|
+
cell: tileset.cell,
|
|
1245
|
+
shape: tileset.shape,
|
|
1246
|
+
animRows: tileset.animRows,
|
|
1247
|
+
variants: tileset.variants,
|
|
1248
|
+
tileCount: tileset.tiles.length,
|
|
1249
|
+
builtin: tileset.builtin === true ? true : undefined,
|
|
1250
|
+
reason: layoutFor(tileset.shape, tileset.cell, tileset.imageWidth, tileset.imageHeight).reason,
|
|
1251
|
+
palette: paletteFor(tileset, flat)
|
|
1252
|
+
})),
|
|
1253
|
+
legend: flat.map((tile) => ({ index: tile.index, tilesetId: tile.tilesetId, rect: tile.tile.rect })),
|
|
1254
|
+
layers,
|
|
1255
|
+
filled: layers.reduce((sum, layer) => sum + layer.filled, 0),
|
|
1256
|
+
stages: p.stages,
|
|
1257
|
+
reviewMode: p.reviewMode,
|
|
1258
|
+
busy: mapBusy(p.id),
|
|
1259
|
+
canUndo: state.canUndo,
|
|
1260
|
+
canRedo: state.canRedo,
|
|
1261
|
+
maxChunks: MAX_PLAN_CHUNKS,
|
|
1262
|
+
warnings: warningsFor(p, doc),
|
|
1263
|
+
logs: p.logs.slice(-40),
|
|
1264
|
+
preview: (await readPreviewFiles(p.id)).map((name) => `preview/${name}`),
|
|
1265
|
+
exportBase: listing?.base ?? "",
|
|
1266
|
+
exportFiles: listing?.files ?? [],
|
|
1267
|
+
exportPath: listing === undefined ? "" : join(mapProjectDir(p.id), "export", listing.dirName)
|
|
1268
|
+
};
|
|
1269
|
+
}
|
|
1270
|
+
/**
|
|
1271
|
+
* 素材 → 可点的笔刷列表。
|
|
1272
|
+
*
|
|
1273
|
+
* 普通素材每格一个条目;**A2 素材只出一个**:用户点的是「草地」这个自动连接笔刷,
|
|
1274
|
+
* 形状由邻居现推(`mapauto.a2QuadrantShapes`),所以画笔要落在**满格那一行**上 ——
|
|
1275
|
+
* 那一行的 32×32 逻辑块正好是一张完整的缩略图。写进图层数据的值取同一块的第一个
|
|
1276
|
+
* 小格序号:渲染时从它身上认「哪张素材、哪个变体」,形状由宿主现算。
|
|
1277
|
+
*/
|
|
1278
|
+
function paletteFor(tileset, flat) {
|
|
1279
|
+
const mine = flat.filter((tile) => tile.tilesetId === tileset.id);
|
|
1280
|
+
if (tileset.shape !== "a2quad")
|
|
1281
|
+
return mine.map((tile) => ({ index: tile.index, rect: tile.tile.rect }));
|
|
1282
|
+
let fullRow = 0;
|
|
1283
|
+
for (const tile of mine)
|
|
1284
|
+
fullRow = Math.max(fullRow, tile.tile.shape ?? 0);
|
|
1285
|
+
const pick = mine.find((tile) => (tile.tile.shape ?? 0) === fullRow && (tile.tile.variant ?? 0) === 0) ?? mine[0];
|
|
1286
|
+
if (pick === undefined)
|
|
1287
|
+
return [];
|
|
1288
|
+
const variant = pick.tile.variant ?? 0;
|
|
1289
|
+
return [
|
|
1290
|
+
{
|
|
1291
|
+
index: pick.index,
|
|
1292
|
+
rect: { x: variant * tileset.cell.width, y: fullRow * tileset.cell.height, width: tileset.cell.width, height: tileset.cell.height }
|
|
1293
|
+
}
|
|
1294
|
+
];
|
|
1295
|
+
}
|
|
1296
|
+
/**
|
|
1297
|
+
* 观测告警:只在「看出来的确会画错」时才说,全部中文。
|
|
1298
|
+
*
|
|
1299
|
+
* ⚠️ 这里**不放**「尺寸是偶数 ⇒ 迷宫会被截断」:默认尺寸就是 32×32(偶数),
|
|
1300
|
+
* 用户从没点过迷宫也会一直看到它。那条提示留在 `runMapGenerate` 的返回里 ——
|
|
1301
|
+
* 只有真的生成迷宫时才该出现。
|
|
1302
|
+
*/
|
|
1303
|
+
function warningsFor(project, doc) {
|
|
1304
|
+
const out = [];
|
|
1305
|
+
if (project.tilesets.length === 0)
|
|
1306
|
+
out.push("还没有素材:先导入一张 tileset 图,或者用 importSampleTileset 装内置素材。");
|
|
1307
|
+
for (const tileset of project.tilesets) {
|
|
1308
|
+
if (tileset.cell.width !== project.grid.tileWidth || tileset.cell.height !== project.grid.tileHeight) {
|
|
1309
|
+
out.push(`素材「${tileset.name}」的格子是 ${tileset.cell.width}×${tileset.cell.height},项目网格是 ${project.grid.tileWidth}×${project.grid.tileHeight}:画出来会按网格缩放。`);
|
|
1310
|
+
}
|
|
1311
|
+
if (tileset.shape === "a2quad" && tileset.imageHeight !== tileset.cell.height * 5) {
|
|
1312
|
+
out.push(`素材「${tileset.name}」是 A2 拼块,但高度 ${tileset.imageHeight} 不等于 5×格子高(${tileset.cell.height * 5}):形状行数对不上,自动连接会取错块。`);
|
|
1313
|
+
}
|
|
1314
|
+
// 「整格自动连接」但掩码没配齐:`assignCorner16Masks` 只在**恰好 16 块**时按位序配,
|
|
1315
|
+
// 块数不对就一块都不配(掩码不是猜的),画出来会统一用第一块 —— 这件事必须常驻显示。
|
|
1316
|
+
if (tileset.shape === "corner16") {
|
|
1317
|
+
const masks = new Set(tileset.tiles.map((tile) => tile.mask).filter((mask) => typeof mask === "number"));
|
|
1318
|
+
if (masks.size < CORNER16_COUNT) {
|
|
1319
|
+
out.push(`素材「${tileset.name}」是整格自动连接,但 ${tileset.tiles.length} 块里只有 ${masks.size} 个掩码(需要 ${CORNER16_COUNT} 块):没配到的地方会统一用第一块。`);
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
const bottom = doc.layers[0];
|
|
1324
|
+
if (bottom !== undefined && filledCount(doc, bottom.id) === 0)
|
|
1325
|
+
out.push(`第 0 层(${bottom.name})还是空的:先用笔刷铺一层,或者 runMapGenerate 一键生成。`);
|
|
1326
|
+
// 旧版项目(**第一版**模块六)把地图存在 `maps/<mapId>.json`,新版只读项目根的 `map.json`。
|
|
1327
|
+
// 于是用户升级后打开旧项目会看到一张**空的**地图 —— 什么都不说的话就是「我画的东西不见了」。
|
|
1328
|
+
// 旧文件并没有删,所以这里只提醒一句、给个去处(真去读两份数据等于养一套迁移口径)。
|
|
1329
|
+
if (existsSync(join(mapProjectDir(project.id), "maps"))) {
|
|
1330
|
+
out.push("这是旧版地图项目:原来的地图数据在项目目录的 maps/ 里,新版界面只读 map.json,所以现在看到的是一张空地图(maps/ 里的旧文件没有删)。");
|
|
1331
|
+
}
|
|
1332
|
+
return out;
|
|
1333
|
+
}
|
|
1334
|
+
// ── 作业(预览 / 导出)────────────────────────────────────────────────────
|
|
1335
|
+
/**
|
|
1336
|
+
* 「已经有人预定要开工」的项目。
|
|
1337
|
+
*
|
|
1338
|
+
* `mapBusy` 读的就是这个集合,而作业是在**几个 await 之后**才真正开始的 ——
|
|
1339
|
+
* 两次并发提交(界面上手快连点、或工具面重复调用)会双双通过 `mapBusy` 检查,
|
|
1340
|
+
* 然后两个作业抢同一份文档。所以先用一个**同步**的预定集合把位置占住。
|
|
1341
|
+
* 占位一直保留到作业结束(`background` 的 finally 里释放)。
|
|
1342
|
+
*/
|
|
1343
|
+
const reserved = new Set();
|
|
1344
|
+
const cancelled = new Set();
|
|
1345
|
+
export function mapBusy(projectId) {
|
|
1346
|
+
return reserved.has(projectId);
|
|
1347
|
+
}
|
|
1348
|
+
export function cancelMapJob(projectId) {
|
|
1349
|
+
cancelled.add(projectId);
|
|
1350
|
+
}
|
|
1351
|
+
/** 同步占位;占不到就返回原因(调用方直接回 `{started:false, reason}`)。 */
|
|
1352
|
+
function reserve(projectId) {
|
|
1353
|
+
if (reserved.has(projectId))
|
|
1354
|
+
return "这个项目已经有任务在跑了,等它跑完再提交。";
|
|
1355
|
+
reserved.add(projectId);
|
|
1356
|
+
return undefined;
|
|
1357
|
+
}
|
|
1358
|
+
async function background(projectId, stage, run) {
|
|
1359
|
+
cancelled.delete(projectId);
|
|
1360
|
+
await patchMapProject(projectId, (project) => {
|
|
1361
|
+
project.stages[stage] = { status: "running", at: new Date().toISOString() };
|
|
1362
|
+
}).catch(() => undefined);
|
|
1363
|
+
try {
|
|
1364
|
+
await run();
|
|
1365
|
+
await patchMapProject(projectId, (project) => {
|
|
1366
|
+
if (project.stages[stage].status === "running")
|
|
1367
|
+
project.stages[stage] = { status: "done", at: new Date().toISOString(), approved: project.stages[stage].approved };
|
|
1368
|
+
});
|
|
1369
|
+
}
|
|
1370
|
+
catch (error) {
|
|
1371
|
+
const message = messageOf(error);
|
|
1372
|
+
await patchMapProject(projectId, (project) => {
|
|
1373
|
+
project.stages[stage] = { status: "error", error: message, at: new Date().toISOString() };
|
|
1374
|
+
appendJobLog(project.logs, "error", `${stage === "paint" ? "预览" : "导出"}失败:${message}`);
|
|
1375
|
+
}).catch(() => undefined);
|
|
1376
|
+
}
|
|
1377
|
+
finally {
|
|
1378
|
+
reserved.delete(projectId);
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
/** 解一遍素材位图(单张解不开不该让整次渲染失败,缺图的地方按透明跳过)。 */
|
|
1382
|
+
async function decodeTilesets(project) {
|
|
1383
|
+
const lookup = new Map();
|
|
1384
|
+
for (const tileset of project.tilesets) {
|
|
1385
|
+
if (tileset.file === "")
|
|
1386
|
+
continue;
|
|
1387
|
+
try {
|
|
1388
|
+
lookup.set(tileset.id, await decodeFile(mapAssetPath(project.id, tileset.file)));
|
|
1389
|
+
}
|
|
1390
|
+
catch {
|
|
1391
|
+
/* 缺图时渲染按空处理 */
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
return lookup;
|
|
1395
|
+
}
|
|
1396
|
+
/** 验收预览(本地免费):只出**一张**地图渲染图 `preview/map.png`。 */
|
|
1397
|
+
export async function runPreviewStage(projectId) {
|
|
1398
|
+
const reason = reserve(projectId);
|
|
1399
|
+
if (reason !== undefined)
|
|
1400
|
+
return { started: false, reason };
|
|
1401
|
+
let project;
|
|
1402
|
+
try {
|
|
1403
|
+
project = await readProjectOrThrow(projectId);
|
|
1404
|
+
}
|
|
1405
|
+
catch (error) {
|
|
1406
|
+
reserved.delete(projectId);
|
|
1407
|
+
throw error;
|
|
1408
|
+
}
|
|
1409
|
+
if (project.tilesets.length === 0) {
|
|
1410
|
+
reserved.delete(projectId);
|
|
1411
|
+
return { started: false, reason: "还没有导入素材。" };
|
|
1412
|
+
}
|
|
1413
|
+
void background(projectId, "paint", async () => {
|
|
1414
|
+
const fresh = await readProjectOrThrow(projectId);
|
|
1415
|
+
const doc = await theDocOrFresh(projectId);
|
|
1416
|
+
await flushMapDoc(projectId);
|
|
1417
|
+
if (cancelled.has(projectId))
|
|
1418
|
+
return;
|
|
1419
|
+
const bitmaps = await decodeTilesets(fresh);
|
|
1420
|
+
const raster = rasterize(renderContextFor(fresh, doc), doc, bitmaps, { scale: 1 });
|
|
1421
|
+
const previewDir = join(mapProjectDir(projectId), "preview");
|
|
1422
|
+
await mkdir(previewDir, { recursive: true });
|
|
1423
|
+
await writeFile(join(previewDir, "map.png"), bitmapToPng(raster.bitmap));
|
|
1424
|
+
await patchMapProject(projectId, (current) => {
|
|
1425
|
+
appendJobLog(current.logs, "info", `生成地图预览图:preview/map.png(${doc.cols}×${doc.rows},${raster.bitmap.width}×${raster.bitmap.height} 像素)`);
|
|
1426
|
+
// ⚠️ 一条 op 都没画进去 = 全透明 PNG。不提示的话界面只会看到一块空白,
|
|
1427
|
+
// 而阶段照样标 done(导出那条同款提示见 mapexport 的「所有图层都是空的」)。
|
|
1428
|
+
if (raster.drawn === 0)
|
|
1429
|
+
appendJobLog(current.logs, "warn", "地图还是空的:预览图是全透明的,先画点东西再看大图。");
|
|
1430
|
+
for (const warning of raster.warnings)
|
|
1431
|
+
appendJobLog(current.logs, "warn", `预览告警:${warning}`);
|
|
1432
|
+
});
|
|
1433
|
+
});
|
|
1434
|
+
return { started: true };
|
|
1435
|
+
}
|
|
1436
|
+
/**
|
|
1437
|
+
* 导出目录名:跟着**地图名**走(改名地图 = 换一个自包含目录,旧目录原样留着)。
|
|
1438
|
+
*
|
|
1439
|
+
* ⚠️ `runExportStage` / `readExportListingRelative` / `mapRevealDir` 三处必须同口径 ——
|
|
1440
|
+
* 分别算一次的话,会出现「界面列的清单在 A 目录、点开的是 B 目录」这种只看得到空文件夹的坏法。
|
|
1441
|
+
*/
|
|
1442
|
+
export function mapExportDirName(doc, project) {
|
|
1443
|
+
return safeFileName(doc?.name ?? project.name, doc?.id ?? project.id);
|
|
1444
|
+
}
|
|
1445
|
+
/** 导出目录的绝对路径。 */
|
|
1446
|
+
export function mapExportDir(projectId, doc, project) {
|
|
1447
|
+
return join(mapProjectDir(projectId), "export", mapExportDirName(doc, project));
|
|
1448
|
+
}
|
|
1449
|
+
/**
|
|
1450
|
+
* 「在文件夹中显示」要打开的绝对路径。
|
|
1451
|
+
*
|
|
1452
|
+
* `target: "export"` 时打开**导出目录**(用户点的是「打开导出目录」,以前却打开项目根 ——
|
|
1453
|
+
* 那里并没有他要的文件);还没导出过就退回项目目录,并由 `fallback` 告诉调用方,
|
|
1454
|
+
* 免得 explorer 收到一个不存在的路径(macOS 的 open 会直接报错)。
|
|
1455
|
+
*/
|
|
1456
|
+
export async function mapRevealDir(projectId, target) {
|
|
1457
|
+
const project = await readProjectOrThrow(projectId);
|
|
1458
|
+
if (target !== "export")
|
|
1459
|
+
return { dir: mapProjectDir(projectId), fallback: false };
|
|
1460
|
+
const dir = mapExportDir(projectId, await readTheDoc(projectId), project);
|
|
1461
|
+
if (existsSync(dir))
|
|
1462
|
+
return { dir, fallback: false };
|
|
1463
|
+
return { dir: mapProjectDir(projectId), fallback: true };
|
|
1464
|
+
}
|
|
1465
|
+
/** 导出(本地免费):`map.png` + `map.json`(+ 素材原图 / zip) + `manifest.json`。 */
|
|
1466
|
+
export async function runExportStage(projectId, options = {}) {
|
|
1467
|
+
const reason = reserve(projectId);
|
|
1468
|
+
if (reason !== undefined)
|
|
1469
|
+
return { started: false, reason };
|
|
1470
|
+
let project;
|
|
1471
|
+
try {
|
|
1472
|
+
project = await readProjectOrThrow(projectId);
|
|
1473
|
+
if (project.tilesets.length === 0) {
|
|
1474
|
+
reserved.delete(projectId);
|
|
1475
|
+
return { started: false, reason: "还没有导入素材,导出的地图会是空的。" };
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
catch (error) {
|
|
1479
|
+
reserved.delete(projectId);
|
|
1480
|
+
throw error;
|
|
1481
|
+
}
|
|
1482
|
+
const scale = Number.isFinite(options.scale) ? Math.max(1, Math.round(Number(options.scale))) : undefined;
|
|
1483
|
+
void background(projectId, "export", async () => {
|
|
1484
|
+
const fresh = await readProjectOrThrow(projectId);
|
|
1485
|
+
const doc = await theDocOrFresh(projectId);
|
|
1486
|
+
if (isDocEmpty(doc))
|
|
1487
|
+
throw new Error("地图还是空的,先画点东西再导出。");
|
|
1488
|
+
await flushMapDoc(projectId);
|
|
1489
|
+
if (cancelled.has(projectId))
|
|
1490
|
+
return;
|
|
1491
|
+
// 导出目录按**地图名**取(改名地图 = 换一个自包含目录,旧目录原样留着)。
|
|
1492
|
+
const dirName = mapExportDirName(doc, fresh);
|
|
1493
|
+
const manifest = await exportMap({
|
|
1494
|
+
project: { id: fresh.id, name: fresh.name },
|
|
1495
|
+
doc,
|
|
1496
|
+
context: renderContextFor(fresh, doc),
|
|
1497
|
+
dir: join(mapProjectDir(projectId), "export", dirName),
|
|
1498
|
+
formats: { ...(options.formats ?? {}), ...(scale === undefined ? {} : { scale }) },
|
|
1499
|
+
// ⚠️ 一定要显式给 `lookup`:mapexport 的兜底分支会自己 `import` 本模块取路径 ——
|
|
1500
|
+
// 那是条循环引用(本模块 → mapexport → 本模块)。给我们已经解好的位图,
|
|
1501
|
+
// 运行时永远走不到那条兜底。
|
|
1502
|
+
lookup: await decodeTilesets(fresh)
|
|
1503
|
+
});
|
|
1504
|
+
await patchMapProject(projectId, (current) => {
|
|
1505
|
+
appendJobLog(current.logs, "info", `导出「${doc.name}」:${manifest.files.length} 个文件 → export/${dirName}/`);
|
|
1506
|
+
});
|
|
1507
|
+
});
|
|
1508
|
+
return { started: true };
|
|
1509
|
+
}
|
|
1510
|
+
/** 相对路径版的导出清单(界面用;绝对 URL 版见 `readExportListing`)。 */
|
|
1511
|
+
async function readExportListingRelative(project) {
|
|
1512
|
+
// 目录名跟着**地图名**走(与 runExportStage 同一处口径)。
|
|
1513
|
+
const doc = await readTheDoc(project.id);
|
|
1514
|
+
const dirName = mapExportDirName(doc, project);
|
|
1515
|
+
const manifest = await readJson(join(mapProjectDir(project.id), "export", dirName, "manifest.json"));
|
|
1516
|
+
if (manifest === undefined)
|
|
1517
|
+
return undefined;
|
|
1518
|
+
return { base: `export/${dirName}/`, files: (manifest.files ?? []).map((file) => file.path), warnings: manifest.warnings ?? [], dirName };
|
|
1519
|
+
}
|
|
1520
|
+
/** 最近的导出清单(验收包用):`base` 与每个文件都是**绝对 URL**。 */
|
|
1521
|
+
export async function readExportListing(projectId, origin) {
|
|
1522
|
+
const project = await readMapProject(projectId);
|
|
1523
|
+
if (project === undefined)
|
|
1524
|
+
return undefined;
|
|
1525
|
+
const listing = await readExportListingRelative(project);
|
|
1526
|
+
if (listing === undefined)
|
|
1527
|
+
return undefined;
|
|
1528
|
+
return {
|
|
1529
|
+
base: absoluteAssetUrl(projectId, origin, listing.base),
|
|
1530
|
+
files: listing.files.map((file) => absoluteAssetUrl(projectId, origin, `${listing.base}${file}`))
|
|
1531
|
+
};
|
|
1532
|
+
}
|
|
1533
|
+
async function readPreviewFiles(projectId) {
|
|
1534
|
+
try {
|
|
1535
|
+
const names = await readdir(join(mapProjectDir(projectId), "preview"));
|
|
1536
|
+
return names.filter((name) => name.endsWith(".png")).sort();
|
|
1537
|
+
}
|
|
1538
|
+
catch {
|
|
1539
|
+
return [];
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
function absoluteAssetUrl(projectId, origin, relative) {
|
|
1543
|
+
return `${origin}/dsh-game-material-master/map-assets/${projectId}/${relative}`;
|
|
1544
|
+
}
|
|
1545
|
+
/**
|
|
1546
|
+
* 工具用的快照:把界面里的**相对**资源路径全部换成可点的**绝对** URL
|
|
1547
|
+
* (模型要直接贴给用户),并附上「下一步该做什么」。
|
|
1548
|
+
*/
|
|
1549
|
+
export async function mapSnapshot(project, origin, options = {}) {
|
|
1550
|
+
void options;
|
|
1551
|
+
const view = await mapView(project);
|
|
1552
|
+
const { preview, exportBase, ...rest } = view;
|
|
1553
|
+
const listing = await readExportListing(project.id, origin);
|
|
1554
|
+
const relative = await readExportListingRelative(project);
|
|
1555
|
+
const nextActions = [];
|
|
1556
|
+
if (view.tilesets.length === 0) {
|
|
1557
|
+
nextActions.push({ step: "assets", why: "还没有素材:importMapTileset({projectId,name,data}) 传图片 base64,或者 importSampleTileset({projectId}) 装内置素材(免费、本机现算)。" });
|
|
1558
|
+
}
|
|
1559
|
+
if (view.filled === 0) {
|
|
1560
|
+
nextActions.push({ step: "paint", why: "地图还是空的:runMapGenerate({projectId,kind:'random'|'maze'|'continent'}) 一键铺,或者 applyMapOps({projectId,ops}) 直接画。" });
|
|
1561
|
+
}
|
|
1562
|
+
else if (exportBase === "") {
|
|
1563
|
+
nextActions.push({ step: "export", why: "还没导出过:runMapExport({projectId}) 出 map.png + map.json(本地免费)。" });
|
|
1564
|
+
}
|
|
1565
|
+
if (nextActions.length === 0)
|
|
1566
|
+
nextActions.push({ step: "done", why: "素材、地图、导出都有产物了。可以继续改地图,或 runMapPreview({projectId}) 重新出验收图。" });
|
|
1567
|
+
return {
|
|
1568
|
+
...rest,
|
|
1569
|
+
assetBase: `${origin}/dsh-game-material-master/map-assets/${project.id}/`,
|
|
1570
|
+
tilesets: view.tilesets.map((tileset) => ({ ...tileset, url: absoluteAssetUrl(project.id, origin, tileset.file) })),
|
|
1571
|
+
previewUrls: preview.map((relative) => absoluteAssetUrl(project.id, origin, relative)),
|
|
1572
|
+
exportBaseUrl: listing?.base ?? "",
|
|
1573
|
+
exportWarnings: relative?.warnings ?? [],
|
|
1574
|
+
nextActions
|
|
1575
|
+
};
|
|
1576
|
+
}
|
|
1577
|
+
// 尺寸上限是几何模块的口径,但网关与自检脚本一直是按 `mapgen.MAX_MAP_DIM` 读的
|
|
1578
|
+
// (模块六的公开面就是这个文件),所以在这里转出去,别让调用方猜它搬去了哪。
|
|
1579
|
+
export { MAX_MAP_DIM };
|