dsh-game-material-master 0.4.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/lib/mapdoc.js ADDED
@@ -0,0 +1,444 @@
1
+ /**
2
+ * 地图编辑器(模块六)的**文档模型与编辑操作**。
3
+ *
4
+ * 一张地图 = 若干图层,每个图层是一段 `cols × rows` 的数组:
5
+ * `0` 表示空,其余是**全局图块序号**(见 `maptiles.flatTiles`)。
6
+ *
7
+ * ## 三条口径
8
+ *
9
+ * 1. **宿主是唯一写者**:界面不发「整份文档」,只发 op(`applyOps`)。
10
+ * 撤销 = 逆操作日志,因此撤销栈不占内存、也不需要 diff。
11
+ * 2. **派生数据不落盘**:A2 的象限形状、动画帧、脏 chunk 全在渲染 / 应用时算
12
+ * (`maprender.buildPlan` / `mapgeom.dirtyChunksFor`)。旧模块把「自动过渡的
13
+ * 最终贴图、跨格占格、垫底」存成三份缓存,各自都出过「过期后凭空多出一栋楼」。
14
+ * 3. **操作必须是纯函数**:`applyOps(doc, ops, layout)` 直接改传入的 doc 并返回被
15
+ * 改的格子与逆操作。界面拖动时按 ~60ms 批量提交,宿主应用后回传脏 chunk。
16
+ *
17
+ * ## 图层为什么瘦成 `{ id, name }`
18
+ *
19
+ * 旧模型的 `kind` / `heightOffset` / `opacity` / `visible` / `locked` / `baseFamilyId`
20
+ * 全部删掉:前四个只在界面与导出之间制造「两边口径不同」的空间(层高偏移与层不透明度
21
+ * 各出过「预览 ≠ 导出」),`baseFamilyId` 是族体系的遗留,`locked` 则是一个纯界面状态
22
+ * 却写在文档里、还会让 op 静默整批跳过。AsLib 的做法就是「只有名字的叠放顺序」。
23
+ */
24
+ import { DEFAULT_GRID, MAX_MAP_DIM, assertMapSize, layoutOf, wrapCell } from "./mapgeom.js";
25
+ export function cellIndex(doc, r, c) {
26
+ return r * doc.cols + c;
27
+ }
28
+ export function emptyData(cols, rows) {
29
+ return new Array(cols * rows).fill(0);
30
+ }
31
+ /** 默认图层。名字缺省时只给一个中性名 —— 具体名字由调用方(`createMapDoc` / `addLayer`)给。 */
32
+ export function defaultLayer(id, name) {
33
+ return { id, name: typeof name === "string" && name !== "" ? name : "图层" };
34
+ }
35
+ /** 默认两层(AsLib 同款:一层地面、一层装饰)。名字**中文硬编码** —— 宿主侧没有 i18n 通道。 */
36
+ function defaultLayers() {
37
+ return [defaultLayer("l0", "图层 1"), defaultLayer("l1", "图层 2")];
38
+ }
39
+ export function createMapDoc(id, name, cols, rows) {
40
+ assertMapSize(cols, rows);
41
+ const now = new Date().toISOString();
42
+ const layers = defaultLayers();
43
+ const data = {};
44
+ for (const layer of layers)
45
+ data[layer.id] = emptyData(cols, rows);
46
+ return { id, name, cols, rows, layers, data, createdAt: now, updatedAt: now };
47
+ }
48
+ /** 读盘 / 外部输入 → 合法文档:补缺字段、把图层数据裁齐到 `cols × rows`。 */
49
+ export function normalizeMapDoc(raw, fallbackId) {
50
+ if (raw === null || typeof raw !== "object")
51
+ return undefined;
52
+ const input = raw;
53
+ const cols = Math.max(1, Math.min(MAX_MAP_DIM, Math.round(Number(input.cols) || 32)));
54
+ const rows = Math.max(1, Math.min(MAX_MAP_DIM, Math.round(Number(input.rows) || 32)));
55
+ const rawLayers = Array.isArray(input.layers) ? input.layers : [];
56
+ // id 重复会让两层共用同一段数据(改一层等于同时改两层,且不报错)—— 这里必须去重。
57
+ const used = new Set();
58
+ const layers = [];
59
+ for (const [index, item] of rawLayers.entries()) {
60
+ const layer = item;
61
+ const id = typeof layer?.id === "string" && layer.id !== "" ? layer.id : `l${index}`;
62
+ const name = typeof layer?.name === "string" && layer.name !== "" ? layer.name : `图层 ${index + 1}`;
63
+ let unique = id;
64
+ if (used.has(unique)) {
65
+ let bump = 0;
66
+ while (used.has(`l${bump}`))
67
+ bump++;
68
+ unique = `l${bump}`;
69
+ }
70
+ used.add(unique);
71
+ layers.push({ id: unique, name });
72
+ }
73
+ if (layers.length === 0)
74
+ layers.push(...defaultLayers());
75
+ const layersData = (input.data ?? {});
76
+ const data = {};
77
+ for (const layer of layers) {
78
+ const source = layersData[layer.id];
79
+ const target = emptyData(cols, rows);
80
+ if (Array.isArray(source)) {
81
+ for (let i = 0; i < target.length; i++) {
82
+ const value = Number(source[i]);
83
+ target[i] = Number.isFinite(value) && value > 0 ? Math.round(value) : 0;
84
+ }
85
+ }
86
+ data[layer.id] = target;
87
+ }
88
+ const now = new Date().toISOString();
89
+ return {
90
+ id: typeof input.id === "string" && input.id !== "" ? input.id : fallbackId,
91
+ name: typeof input.name === "string" && input.name !== "" ? input.name : "未命名地图",
92
+ cols,
93
+ rows,
94
+ layers,
95
+ data,
96
+ createdAt: typeof input.createdAt === "string" ? input.createdAt : now,
97
+ updatedAt: typeof input.updatedAt === "string" ? input.updatedAt : now
98
+ };
99
+ }
100
+ export function cloneDoc(doc) {
101
+ const data = {};
102
+ for (const [key, value] of Object.entries(doc.data))
103
+ data[key] = [...value];
104
+ return { ...doc, layers: doc.layers.map((layer) => ({ ...layer })), data };
105
+ }
106
+ // ── 结构操作(图层 / 尺寸)────────────────────────────────────────────────
107
+ export function nextLayerId(doc) {
108
+ let index = doc.layers.length;
109
+ while (doc.layers.some((layer) => layer.id === `l${index}`))
110
+ index++;
111
+ return `l${index}`;
112
+ }
113
+ export function addLayer(doc, name) {
114
+ const layer = defaultLayer(nextLayerId(doc), name !== undefined && name !== "" ? name : `图层 ${doc.layers.length + 1}`);
115
+ doc.layers.push(layer);
116
+ doc.data[layer.id] = emptyData(doc.cols, doc.rows);
117
+ doc.updatedAt = new Date().toISOString();
118
+ return layer;
119
+ }
120
+ export function removeLayer(doc, layerId) {
121
+ if (doc.layers.length <= 1)
122
+ return false;
123
+ const index = doc.layers.findIndex((layer) => layer.id === layerId);
124
+ if (index < 0)
125
+ return false;
126
+ doc.layers.splice(index, 1);
127
+ delete doc.data[layerId];
128
+ doc.updatedAt = new Date().toISOString();
129
+ return true;
130
+ }
131
+ export function moveLayer(doc, layerId, toIndex) {
132
+ const index = doc.layers.findIndex((layer) => layer.id === layerId);
133
+ if (index < 0)
134
+ return false;
135
+ const target = Math.min(doc.layers.length - 1, Math.max(0, Math.round(toIndex)));
136
+ if (target === index)
137
+ return false;
138
+ const [layer] = doc.layers.splice(index, 1);
139
+ doc.layers.splice(target, 0, layer);
140
+ doc.updatedAt = new Date().toISOString();
141
+ return true;
142
+ }
143
+ /** 改名。空名字**明确拒绝**(返回 false),不静默换成「图层」。 */
144
+ export function renameLayer(doc, layerId, name) {
145
+ const layer = doc.layers.find((item) => item.id === layerId);
146
+ if (layer === undefined)
147
+ return false;
148
+ const trimmed = typeof name === "string" ? name.trim() : "";
149
+ if (trimmed === "")
150
+ return false;
151
+ if (layer.name === trimmed)
152
+ return false;
153
+ layer.name = trimmed;
154
+ doc.updatedAt = new Date().toISOString();
155
+ return true;
156
+ }
157
+ /** 清空一层,返回**清掉的格子数**(已经是空的就返回 0,不改 `updatedAt`)。 */
158
+ export function clearLayer(doc, layerId) {
159
+ const data = doc.data[layerId];
160
+ if (data === undefined)
161
+ return 0;
162
+ let cleared = 0;
163
+ for (let i = 0; i < data.length; i++) {
164
+ if (data[i] !== 0) {
165
+ data[i] = 0;
166
+ cleared++;
167
+ }
168
+ }
169
+ if (cleared > 0)
170
+ doc.updatedAt = new Date().toISOString();
171
+ return cleared;
172
+ }
173
+ /**
174
+ * 改地图尺寸(左上角对齐)。缩小时被丢掉的格子**计数返回**,且可撤销
175
+ * (调用方在改之前存一份快照)。
176
+ */
177
+ export function resizeDoc(doc, cols, rows) {
178
+ assertMapSize(cols, rows);
179
+ if (cols === doc.cols && rows === doc.rows)
180
+ return { dropped: 0 };
181
+ let dropped = 0;
182
+ for (const layer of doc.layers) {
183
+ const source = doc.data[layer.id] ?? emptyData(doc.cols, doc.rows);
184
+ const target = emptyData(cols, rows);
185
+ const copyCols = Math.min(cols, doc.cols);
186
+ const copyRows = Math.min(rows, doc.rows);
187
+ for (let r = 0; r < copyRows; r++) {
188
+ for (let c = 0; c < copyCols; c++)
189
+ target[r * cols + c] = source[r * doc.cols + c];
190
+ }
191
+ for (let r = 0; r < doc.rows; r++) {
192
+ for (let c = 0; c < doc.cols; c++) {
193
+ if (r < copyRows && c < copyCols)
194
+ continue;
195
+ if (source[r * doc.cols + c] > 0)
196
+ dropped++;
197
+ }
198
+ }
199
+ doc.data[layer.id] = target;
200
+ }
201
+ doc.cols = cols;
202
+ doc.rows = rows;
203
+ doc.updatedAt = new Date().toISOString();
204
+ return { dropped };
205
+ }
206
+ /** 画一条线(Bresenham):拖动时两点之间的格子不能漏(漏了就是「虚线」)。 */
207
+ export function lineCells(r0, c0, r1, c1) {
208
+ const out = [];
209
+ let r = Math.round(r0);
210
+ let c = Math.round(c0);
211
+ const rEnd = Math.round(r1);
212
+ const cEnd = Math.round(c1);
213
+ const dr = Math.abs(rEnd - r);
214
+ const dc = Math.abs(cEnd - c);
215
+ const sr = r < rEnd ? 1 : -1;
216
+ const sc = c < cEnd ? 1 : -1;
217
+ let err = dr - dc;
218
+ for (;;) {
219
+ out.push({ r, c });
220
+ if (r === rEnd && c === cEnd)
221
+ break;
222
+ const e2 = 2 * err;
223
+ if (e2 > -dc) {
224
+ err -= dc;
225
+ r += sr;
226
+ }
227
+ if (e2 < dr) {
228
+ err += dr;
229
+ c += sc;
230
+ }
231
+ if (out.length > 1_000_000)
232
+ break;
233
+ }
234
+ return out;
235
+ }
236
+ /** 图块序号收口:非正数与 NaN 一律当「清空」(0),小数取整。 */
237
+ function tileValue(input) {
238
+ const value = Number(input);
239
+ return Number.isFinite(value) && value > 0 ? Math.round(value) : 0;
240
+ }
241
+ /**
242
+ * 应用一批 op。
243
+ *
244
+ * **不会抛异常**:拖动时指针滑出地图是常事,越界条目记进 `skipped` 由界面提示。
245
+ * 坐标一律不取整(不合法就是 `越界格`)—— `Math.round` 会把用户根本没点到的格子
246
+ * 悄悄涂上,这正是旧模块「涂在隔壁格」那类问题的来源。
247
+ *
248
+ * `layout` 是**双层保险**:上游(`mapPlan` / 客户端命中测试)已经给过规范坐标,
249
+ * 这里再按 `layout` wrap 一次。`layout.wrap` 为 false 时越界就是越界,直接跳过。
250
+ */
251
+ export function applyOps(doc, ops, layout) {
252
+ const changed = new Set();
253
+ const dirty = new Map();
254
+ const undo = [];
255
+ const skipped = [];
256
+ const canonical = (r, c) => {
257
+ if (!Number.isInteger(r) || !Number.isInteger(c))
258
+ return undefined;
259
+ // 不环绕时 `wrapCell` 原样返回,下面的范围判断就是唯一的拦截。
260
+ const wrapped = wrapCell(layout, r, c);
261
+ if (wrapped.r < 0 || wrapped.c < 0 || wrapped.r >= doc.rows || wrapped.c >= doc.cols)
262
+ return undefined;
263
+ return wrapped;
264
+ };
265
+ const paintValue = (layerId, cells) => {
266
+ const data = doc.data[layerId];
267
+ const before = [];
268
+ for (const cell of cells) {
269
+ // 单元格本身不成形(null / 数字)时 `cell.r` 会直接抛 —— 校验层的承诺是「不抛」。
270
+ if (cell === null || typeof cell !== "object") {
271
+ skipped.push("认不出的 op");
272
+ continue;
273
+ }
274
+ const target = canonical(cell.r, cell.c);
275
+ if (target === undefined) {
276
+ skipped.push(`越界格 (${cell.r},${cell.c})`);
277
+ continue;
278
+ }
279
+ const index = target.r * doc.cols + target.c;
280
+ const tile = tileValue(cell.tile);
281
+ const previous = data[index];
282
+ if (previous === tile)
283
+ continue;
284
+ before.push({ r: target.r, c: target.c, tile: previous });
285
+ data[index] = tile;
286
+ changed.add(index);
287
+ dirty.set(index, target);
288
+ }
289
+ return before;
290
+ };
291
+ for (const raw of ops) {
292
+ const op = raw;
293
+ if (op === null || typeof op !== "object" || typeof op.kind !== "string") {
294
+ skipped.push("认不出的 op");
295
+ continue;
296
+ }
297
+ if (typeof op.layerId !== "string" || doc.data[op.layerId] === undefined) {
298
+ skipped.push(`图层不存在:${String(op.layerId)}`);
299
+ continue;
300
+ }
301
+ if (op.kind === "paint") {
302
+ if (!Array.isArray(op.cells)) {
303
+ skipped.push("paint 缺 cells");
304
+ continue;
305
+ }
306
+ const before = paintValue(op.layerId, op.cells);
307
+ if (before.length > 0)
308
+ undo.push({ kind: "paint", layerId: op.layerId, cells: before });
309
+ }
310
+ else if (op.kind === "fill") {
311
+ const start = canonical(op.r, op.c);
312
+ if (start === undefined) {
313
+ skipped.push(`越界格 (${op.r},${op.c})`);
314
+ continue;
315
+ }
316
+ const data = doc.data[op.layerId];
317
+ const tile = tileValue(op.tile);
318
+ const target = data[cellIndex(doc, start.r, start.c)];
319
+ if (target === tile)
320
+ continue;
321
+ // 洪水填充**不跨环绕接缝**(AsLib 同款):在 0..cols / 0..rows 平面上做,
322
+ // 越界邻居直接停。跨接缝填会把整张图一圈一圈填满,而且没人能预期到。
323
+ const cells = [];
324
+ const seen = new Set();
325
+ const stack = [start];
326
+ while (stack.length > 0) {
327
+ const cell = stack.pop();
328
+ if (cell.r < 0 || cell.c < 0 || cell.r >= doc.rows || cell.c >= doc.cols)
329
+ continue;
330
+ const index = cell.r * doc.cols + cell.c;
331
+ if (seen.has(index))
332
+ continue;
333
+ if (data[index] !== target)
334
+ continue;
335
+ seen.add(index);
336
+ cells.push({ r: cell.r, c: cell.c, tile });
337
+ stack.push({ r: cell.r + 1, c: cell.c }, { r: cell.r - 1, c: cell.c }, { r: cell.r, c: cell.c + 1 }, { r: cell.r, c: cell.c - 1 });
338
+ }
339
+ const before = paintValue(op.layerId, cells);
340
+ if (before.length > 0)
341
+ undo.push({ kind: "paint", layerId: op.layerId, cells: before });
342
+ }
343
+ else if (op.kind === "rect") {
344
+ // 四个角一起校验:不合法就整条跳过。只按格遍历、让 paintValue 逐格报错的话,
345
+ // 一个浮点矩形会刷出上百条同样的 `越界格`,真正的问题被淹掉。
346
+ if (![op.r0, op.c0, op.r1, op.c1].every((value) => Number.isInteger(value))) {
347
+ skipped.push(`越界格 (${op.r0},${op.c0})`);
348
+ continue;
349
+ }
350
+ const r0 = Math.min(op.r0, op.r1);
351
+ const r1 = Math.max(op.r0, op.r1);
352
+ const c0 = Math.min(op.c0, op.c1);
353
+ const c1 = Math.max(op.c0, op.c1);
354
+ const tile = tileValue(op.tile);
355
+ const cells = [];
356
+ for (let r = r0; r <= r1; r++) {
357
+ for (let c = c0; c <= c1; c++) {
358
+ const onEdge = r === r0 || r === r1 || c === c0 || c === c1;
359
+ if (onEdge || op.filled !== false)
360
+ cells.push({ r, c, tile });
361
+ }
362
+ }
363
+ const before = paintValue(op.layerId, cells);
364
+ if (before.length > 0)
365
+ undo.push({ kind: "paint", layerId: op.layerId, cells: before });
366
+ }
367
+ else if (op.kind === "replace") {
368
+ const data = doc.data[op.layerId];
369
+ const from = Math.round(Number(op.from));
370
+ const to = tileValue(op.to);
371
+ const cells = [];
372
+ for (let index = 0; index < data.length; index++) {
373
+ if (data[index] !== from)
374
+ continue;
375
+ cells.push({ r: Math.floor(index / doc.cols), c: index % doc.cols, tile: to });
376
+ }
377
+ const before = paintValue(op.layerId, cells);
378
+ if (before.length > 0)
379
+ undo.push({ kind: "paint", layerId: op.layerId, cells: before });
380
+ }
381
+ else {
382
+ skipped.push(`不支持的 op:${String(op.kind)}`);
383
+ }
384
+ }
385
+ if (changed.size > 0)
386
+ doc.updatedAt = new Date().toISOString();
387
+ return {
388
+ changed: changed.size,
389
+ skipped,
390
+ dirty: [...dirty.values()].sort((a, b) => a.r - b.r || a.c - b.c),
391
+ undo: undo.reverse()
392
+ };
393
+ }
394
+ /**
395
+ * 撤销:把逆操作原样应用(它本身也是 op)。
396
+ *
397
+ * 契约里没有 `layout` 参数 —— 逆操作记下来的坐标本来就是**规范坐标**,这里补一个
398
+ * 只为了能复用 `applyOps`;wrap 对规范坐标是恒等变换,所以用哪个网格都不影响结果。
399
+ */
400
+ export function revertOps(doc, undo) {
401
+ const layout = layoutOf(DEFAULT_GRID, doc.cols, doc.rows);
402
+ return applyOps(doc, undo, layout).dirty.map((cell) => cell.r * doc.cols + cell.c);
403
+ }
404
+ /** 用到的图块序号(删图集 / 改切分前查引用)。 */
405
+ export function usedTileIndices(doc) {
406
+ const out = new Set();
407
+ for (const layer of doc.layers) {
408
+ for (const value of doc.data[layer.id] ?? []) {
409
+ if (value > 0)
410
+ out.add(value);
411
+ }
412
+ }
413
+ return out;
414
+ }
415
+ export function filledCount(doc, layerId) {
416
+ let n = 0;
417
+ for (const layer of doc.layers) {
418
+ if (layerId !== undefined && layer.id !== layerId)
419
+ continue;
420
+ for (const value of doc.data[layer.id] ?? [])
421
+ if (value > 0)
422
+ n++;
423
+ }
424
+ return n;
425
+ }
426
+ export function isDocEmpty(doc) {
427
+ return filledCount(doc) === 0;
428
+ }
429
+ /** 把越界 / 不存在的图块序号清掉:返回被清掉的格子数(删图集 / 改切分之后要调用)。 */
430
+ export function pruneTileIndices(doc, maxIndex) {
431
+ let pruned = 0;
432
+ for (const layer of doc.layers) {
433
+ const data = doc.data[layer.id];
434
+ if (data === undefined)
435
+ continue;
436
+ for (let i = 0; i < data.length; i++) {
437
+ if (data[i] > maxIndex) {
438
+ data[i] = 0;
439
+ pruned++;
440
+ }
441
+ }
442
+ }
443
+ return pruned;
444
+ }
@@ -0,0 +1,177 @@
1
+ /**
2
+ * 地图编辑器(模块六)的**导出**:`map.png`(合并所有层)+ `map.json` + `manifest.json`,
3
+ * 需要时再加一份 `tilesets/`(素材原图)和一个 `.zip` 包。
4
+ *
5
+ * ## 为什么是这几个文件
6
+ *
7
+ * 旧实现导 PNG(分层 + 合并)+ 自有 JSON + Tiled 的 `.tmj` / `.tsj`(含 wangsets、
8
+ * firstgid、图集 PNG 拷贝)。删掉的理由:
9
+ *
10
+ * - **Tiled 那套没人验证得了**:本机联不上 Tiled 本体,wangsets 的位序只能照文档写,
11
+ * 自检断言的是「我们写出来的字段」,不是「Tiled 读得懂」。等于把风险留在发布里。
12
+ * - **分层 PNG 是重复的**:合并图 + `map.json` 里的每层语义序号已经能还原每一层,
13
+ * 多出来的文件只会各自过期(旧模块就出过「改了地图,分层图还是旧的」)。
14
+ *
15
+ * 素材原图是**用户显式勾选**才拷的(`formats.tilesets`):勾了以后 `map.json` 里
16
+ * `tilesets[].image`(形如 `tilesets/tsxxxx.png`)**在导出目录里也成立** —— 拷进去的
17
+ * 相对路径与项目里同形,所以整包自包含,拿到别处(别的机器 / 引擎工程)能直接用。
18
+ * 不勾就还是老样子:目录里只有地图本身的产物,图集回项目目录取。
19
+ *
20
+ * `.zip` 是**打包给用户下载**用的(`formats.zip`;不给 = 产物超过一个就自动打):
21
+ * 界面上的「导出」是一次点击,多个文件分头下载既麻烦又容易被浏览器拦。
22
+ * `manifest.json` 是**我们自己的账本**,不进 zip。
23
+ *
24
+ * ## 三条口径
25
+ *
26
+ * 1. `map.json` 里 `layers[].data` 写的是**语义序号**(1-based 全局图块序号,0 = 空),
27
+ * 不是解析后的贴图 —— 自己格式要能继续改(A2 的形状是渲染时现算的)。
28
+ * 2. `map.png` 走 `maprender.rasterize`,也就是**与界面预览同一份绘制计划**。
29
+ * 3. **每次导出先把这个导出目录清空**:`export/<安全名>/` 整份是我们生成的,
30
+ * 不清的话「上次导了 JSON、这次只导 PNG」会留下一份过期的 `map.json`,
31
+ * 用户打开文件夹看到的东西和界面上列的清单对不上。
32
+ */
33
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
34
+ import { dirname, join } from "node:path";
35
+ import { decodeFile } from "./bitmap.js";
36
+ import { flatTiles } from "./maptiles.js";
37
+ import { bitmapToPng, planBounds, rasterize } from "./maprender.js";
38
+ // ⚠️ `mapgen` 反过来也 import 本文件(`runExportStage` 调 `exportMap`)。ESM 的循环
39
+ // 引用对「只在函数体里用到的绑定」是安全的(下面只在调用时读 `mapAssetPath`)。
40
+ import { mapAssetPath } from "./mapgen.js";
41
+ import { zipEntries } from "./zip.js";
42
+ export const OWN_JSON_FORMAT = "dsh-gem-map@2";
43
+ /** 文件名安全化:名字直接进目录会踩到 `/`、`:` 与超长名。 */
44
+ export function safeFileName(input, fallback = "map") {
45
+ const cleaned = (input ?? "")
46
+ .replace(/[^\p{L}\p{N}_-]+/gu, "_")
47
+ .replace(/^_+|_+$/g, "")
48
+ .slice(0, 40);
49
+ return cleaned === "" ? fallback : cleaned;
50
+ }
51
+ /**
52
+ * `map.json`。
53
+ *
54
+ * ⚠️ `tilesets[].image` 是**相对导出目录 / 项目目录**的同一条路径(`tilesets/<id>.png`)。
55
+ *
56
+ * - 勾了「素材原图」(`formats.tilesets`):这个路径在导出目录里成立,整包自包含;
57
+ * - 没勾:导出目录里没有这些图,读 `map.json` 的人得回项目目录取 —— 这条写在这里,
58
+ * 免得把 `image` 当成「相对导出目录」而在别处找不到文件。
59
+ *
60
+ * `project` 按契约留在签名上(旧版写过 `project` 段),`dsh-gem-map@2` 的形态里不带它:
61
+ * 一张地图就是一个项目,再套一层只是重复。
62
+ */
63
+ export function buildOwnJson(context, doc, project) {
64
+ void project;
65
+ return {
66
+ format: OWN_JSON_FORMAT,
67
+ grid: { tileWidth: context.grid.tileWidth, tileHeight: context.grid.tileHeight, wrap: context.grid.wrap },
68
+ cols: doc.cols,
69
+ rows: doc.rows,
70
+ tilesets: context.tilesets.map((tileset) => ({
71
+ id: tileset.id,
72
+ name: tileset.name,
73
+ image: tileset.file,
74
+ cell: { width: tileset.cell.width, height: tileset.cell.height },
75
+ shape: tileset.shape,
76
+ variants: tileset.variants,
77
+ tileCount: tileset.tiles.length
78
+ })),
79
+ legend: flatTiles(context.tilesets).map((flat) => ({ index: flat.index, tilesetId: flat.tilesetId, rect: flat.tile.rect })),
80
+ layers: doc.layers.map((layer) => ({ name: layer.name, data: [...(doc.data[layer.id] ?? [])] }))
81
+ };
82
+ }
83
+ /** 解出导出用的图集位图。解不出来的留给 `rasterize` 报警(不能静默缺图)。 */
84
+ async function decodeTilesets(projectId, context) {
85
+ const out = new Map();
86
+ for (const tileset of context.tilesets) {
87
+ const file = mapAssetPath(projectId, tileset.file);
88
+ const bitmap = await decodeFile(file).catch(() => undefined);
89
+ if (bitmap !== undefined)
90
+ out.set(tileset.id, bitmap);
91
+ }
92
+ return out;
93
+ }
94
+ /** 素材图在 zip / 导出目录里的落点:与项目里同形(`tilesets/<文件名>`),所以 `map.json` 的引用不用改。 */
95
+ function tilesetExportPath(file) {
96
+ const name = file.split(/[\\/]/u).pop() ?? "";
97
+ return `tilesets/${name}`;
98
+ }
99
+ /**
100
+ * 导出:`map.png` + `map.json` + 可选的 `tilesets/**` + 可选的 zip,外加自己的 `manifest.json`。
101
+ *
102
+ * 会抛错的地方只有一处:图超过 `MAX_RENDER_PIXELS`(那是明确的用户错误,不是坏数据)。
103
+ * 其余问题(图集解不出来、地图是空的、缺掩码、某张素材原图读不到)一律进 `warnings`
104
+ * 并继续导出 —— 导出失败时用户至少还能拿到 `map.json` 里的数据。
105
+ */
106
+ export async function exportMap(input) {
107
+ const { dir, context, doc } = input;
108
+ const formats = input.formats ?? {};
109
+ const wantPng = formats.png !== false;
110
+ const wantJson = formats.json !== false;
111
+ const wantTilesets = formats.tilesets === true;
112
+ const scale = Math.max(1, Math.round(formats.scale ?? 1));
113
+ const files = [];
114
+ const warnings = [];
115
+ const manifest = { files, warnings, bounds: planBounds(context, doc) };
116
+ // 整份目录是我们生成的:先清空,免得上一轮「导过 JSON」留下的 map.json 混在这一轮里
117
+ // (用户打开文件夹看到的东西必须与界面上那份清单一致)。
118
+ await rm(dir, { recursive: true, force: true });
119
+ await mkdir(dir, { recursive: true });
120
+ const write = async (path, content, kind) => {
121
+ const file = join(dir, path);
122
+ // ⚠️ 子目录(`tilesets/x.png`)要先建出来:`writeFile` 不会替你建父目录,
123
+ // 少了这一句,拷素材原图那条路会以 ENOENT 静默失败(表现为「勾了却没拷进去」)。
124
+ await mkdir(dirname(file), { recursive: true });
125
+ const data = typeof content === "string" ? Buffer.from(content, "utf8") : content;
126
+ await writeFile(file, data);
127
+ files.push({ path, bytes: data.length, kind });
128
+ };
129
+ const writeJson = (path, value) => write(path, `${JSON.stringify(value, null, 2)}\n`, "json");
130
+ /** 参与打包的产物(相对导出目录)。`manifest.json` 是我们自己的账本,不进 zip。 */
131
+ const content = [];
132
+ if (wantPng) {
133
+ const lookup = input.lookup ?? (await decodeTilesets(input.project.id, context));
134
+ const raster = rasterize(context, doc, lookup, { scale });
135
+ manifest.bounds = raster.bounds;
136
+ warnings.push(...raster.warnings);
137
+ if (raster.drawn === 0)
138
+ warnings.push("这张地图所有图层都是空的,导出的 PNG 是全透明的。");
139
+ await write("map.png", bitmapToPng(raster.bitmap), "image");
140
+ manifest.mapPng = "map.png";
141
+ content.push("map.png");
142
+ }
143
+ if (wantTilesets) {
144
+ for (const tileset of context.tilesets) {
145
+ if (tileset.file === "")
146
+ continue;
147
+ const relative = tilesetExportPath(tileset.file);
148
+ try {
149
+ await write(relative, await readFile(mapAssetPath(input.project.id, tileset.file)), "image");
150
+ content.push(relative);
151
+ }
152
+ catch (error) {
153
+ warnings.push(`素材「${tileset.name}」的原图没能放进包里(${error instanceof Error ? error.message : String(error)})。`);
154
+ }
155
+ }
156
+ }
157
+ if (wantJson) {
158
+ await writeJson("map.json", buildOwnJson(context, doc, input.project));
159
+ manifest.mapJson = "map.json";
160
+ content.push("map.json");
161
+ }
162
+ /** 打了包才 download 得动:多选一次点击给一个文件,比让浏览器连下好几个靠谱。 */
163
+ const wantZip = formats.zip === true || (formats.zip !== false && content.length > 1);
164
+ if (wantZip && content.length > 0) {
165
+ const entries = [];
166
+ for (const path of content)
167
+ entries.push({ path, data: await readFile(join(dir, path)) });
168
+ const zipName = `${safeFileName(doc.name, doc.id)}.zip`;
169
+ await write(zipName, zipEntries(entries), "archive");
170
+ manifest.mapZip = zipName;
171
+ }
172
+ // 清单自己也要落盘:验收包(`game_material_review`)与「在文件夹中显示」都读它。
173
+ // 盘上的 files 里补一条 manifest.json(bytes 0 —— 序列化那一刻还不知道自己的大小);
174
+ // `write` 随后往 `files` 里 push 的是带真实字节数的那条,返回值与旧实现一致地含它。
175
+ await writeJson("manifest.json", { ...manifest, files: [...manifest.files, { path: "manifest.json", bytes: 0, kind: "json" }] });
176
+ return manifest;
177
+ }