dsh-game-material-master 0.9.2 → 0.10.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/isogen.js ADDED
@@ -0,0 +1,1475 @@
1
+ /**
2
+ * 45° 地图编辑器(模块五 · iso)的**宿主业务层**:项目、素材、文档、计划、
3
+ * 撤销重做、一键生成、预览 / 导出。
4
+ *
5
+ * 一条项目 = 一张地图(`map.json`)+ 若干素材原图(`tilesets/`)。
6
+ * 编辑期间文档以内存为权威副本、防抖落盘;导出前强制 flush。
7
+ */
8
+ import { mkdir, readdir, rm, stat, writeFile } from "node:fs/promises";
9
+ import { randomUUID } from "node:crypto";
10
+ import { join } from "node:path";
11
+ import { appendJobLog, messageOf, readJson, sweepTempFiles, writeJsonAtomic } from "./jsonio.js";
12
+ import { dataRoot } from "./config.js";
13
+ import { decodeFile, encodeBitmap, pngSize, probeImageSize, sniffImageExt } from "./bitmap.js";
14
+ import { keyGreen } from "./chroma.js";
15
+ import { MAX_ASSET_SCALE, cropTile, flatTiles, keyStampBackground, parseAssetFps, parseAssetLoop, parseClarity, resampleToSize, safeAssetStem, STAMP_KEY_OPTIONS } from "./maptiles.js";
16
+ import { DEFAULT_ISO_CELL, MAX_ISO_DIM, MAX_ISO_PLAN_CHUNKS, assertIsoCell, assertIsoMapSize, chunkKey, chunksInRange, dirtyChunksFor, layoutOf, normalizeIsoCell, viewCellRange } from "./isogeom.js";
17
+ import { addLayer as docAddLayer, applyIsoOps as applyOpsToDoc, clearLayer as docClearLayer, cloneIsoDoc, createIsoDoc, filledCount, moveLayer as docMoveLayer, normalizeIsoDoc, objectCount, removeLayer as docRemoveLayer, renameLayer as docRenameLayer, resizeDoc } from "./isodoc.js";
18
+ import { briefOf, parseIsoAnchor, parseIsoObjectScale, parseIsoTilesetKind, parsePassCells, rebuildIsoTiles, shapeOfKind } from "./isotiles.js";
19
+ import { buildIsoPlan, isoBitmapToPng, isoRenderContext, passCellsOf, planBounds, rasterizeIso } from "./isorender.js";
20
+ import { exportIsoMap } from "./isoexport.js";
21
+ import { renderIsoSamples } from "./isosamplegen.js";
22
+ import { composeIsoFrames } from "./isocompose.js";
23
+ import { assetBasePath } from "./links.js";
24
+ export const ISO_STAGES = ["assets", "paint", "export"];
25
+ // ── 路径与 id ─────────────────────────────────────────────────────────────
26
+ export function isoJobsRoot() {
27
+ return join(dataRoot(), "iso-jobs");
28
+ }
29
+ export function isoProjectDir(id) {
30
+ return join(isoJobsRoot(), id);
31
+ }
32
+ export function isoProjectFile(id) {
33
+ return join(isoProjectDir(id), "project.json");
34
+ }
35
+ export function isoDocFile(id) {
36
+ return join(isoProjectDir(id), "map.json");
37
+ }
38
+ export function isoAssetPath(id, relative) {
39
+ const base = isoProjectDir(id);
40
+ const target = join(base, relative);
41
+ if (!target.startsWith(base))
42
+ throw new Error(`非法的项目内路径:${relative}`);
43
+ return target;
44
+ }
45
+ /** `g` 前缀,避免与 p / i / s / r / m / a / f 撞。 */
46
+ export function isValidIsoProjectId(id) {
47
+ return /^g[a-z0-9]{4,40}$/.test(id);
48
+ }
49
+ /**
50
+ * 子目录白名单。**唯一真源**:`index.ts` 的资源路由直接引用它。
51
+ * 少一条只表现为图裂 / 403,不报错。
52
+ */
53
+ export const SERVABLE_ISO_DIRS = new Set(["tilesets", "preview", "export", "ai"]);
54
+ const DEFAULT_COLS = 32;
55
+ const DEFAULT_ROWS = 32;
56
+ function freshStages() {
57
+ return {
58
+ assets: { status: "idle" },
59
+ paint: { status: "idle" },
60
+ export: { status: "idle" }
61
+ };
62
+ }
63
+ // ── 读写(带写队列)──────────────────────────────────────────────────────
64
+ const projectWriteQueue = new Map();
65
+ function enqueueWrite(key, task) {
66
+ const previous = projectWriteQueue.get(key) ?? Promise.resolve();
67
+ const next = previous.catch(() => undefined).then(task);
68
+ projectWriteQueue.set(key, next.catch(() => undefined));
69
+ return next;
70
+ }
71
+ async function writeIsoProject(project) {
72
+ project.updatedAt = new Date().toISOString();
73
+ await writeJsonAtomic(isoProjectFile(project.id), project);
74
+ }
75
+ export async function patchIsoProject(id, mutator) {
76
+ return enqueueWrite(id, async () => {
77
+ const project = await readIsoProject(id);
78
+ if (project === undefined)
79
+ throw new Error(`项目不存在:${id}`);
80
+ const result = mutator(project);
81
+ await writeIsoProject(project);
82
+ return result;
83
+ });
84
+ }
85
+ function positiveInt(value, fallback) {
86
+ const n = Math.round(Number(value));
87
+ return Number.isFinite(n) && n > 0 ? n : fallback;
88
+ }
89
+ export async function createIsoProject(name, options = {}) {
90
+ const cell = normalizeIsoCell(options.cell);
91
+ assertIsoCell(cell);
92
+ const cols = positiveInt(options.cols, DEFAULT_COLS);
93
+ const rows = positiveInt(options.rows, DEFAULT_ROWS);
94
+ assertIsoMapSize(cols, rows);
95
+ const id = `g${Date.now().toString(36)}${randomUUID().slice(0, 6)}`;
96
+ const now = new Date().toISOString();
97
+ const project = {
98
+ id,
99
+ name: name.trim() === "" ? "未命名地图" : name.trim(),
100
+ createdAt: now,
101
+ updatedAt: now,
102
+ cell,
103
+ wrap: options.wrap !== false,
104
+ tilesets: [],
105
+ stages: freshStages(),
106
+ logs: []
107
+ };
108
+ await mkdir(isoProjectDir(id), { recursive: true });
109
+ for (const sub of SERVABLE_ISO_DIRS)
110
+ await mkdir(join(isoProjectDir(id), sub), { recursive: true });
111
+ appendJobLog(project.logs, "info", `新建 45° 地图项目:${project.name}(${cols}×${rows},格子 ${cell.width}×${cell.height})`);
112
+ await writeTheDoc(id, createIsoDoc(id, project.name, cols, rows));
113
+ await writeIsoProject(project);
114
+ return project;
115
+ }
116
+ export async function readIsoProject(id) {
117
+ const raw = await readJson(isoProjectFile(id));
118
+ if (raw === undefined || typeof raw !== "object")
119
+ return undefined;
120
+ void sweepTempFiles(isoProjectDir(id));
121
+ const stages = { ...freshStages(), ...(raw.stages ?? {}) };
122
+ return {
123
+ ...raw,
124
+ cell: normalizeIsoCell(raw.cell),
125
+ wrap: raw.wrap !== false,
126
+ tilesets: Array.isArray(raw.tilesets) ? raw.tilesets.map(normalizeIsoTileset).filter((tileset) => tileset !== undefined) : [],
127
+ stages,
128
+ logs: Array.isArray(raw.logs) ? raw.logs : []
129
+ };
130
+ }
131
+ function normalizeIsoTileset(raw) {
132
+ if (raw === null || typeof raw !== "object")
133
+ return undefined;
134
+ const source = raw;
135
+ const imageWidth = Math.max(1, Math.round(Number(source.imageWidth) || 1));
136
+ const imageHeight = Math.max(1, Math.round(Number(source.imageHeight) || 1));
137
+ const cell = normalizeIsoCell(source.cell);
138
+ const kind = (() => {
139
+ try {
140
+ return parseIsoTilesetKind(source.kind);
141
+ }
142
+ catch {
143
+ return "ground";
144
+ }
145
+ })();
146
+ const framesRaw = Math.round(Number(source.frames));
147
+ const frames = Number.isFinite(framesRaw) && framesRaw >= 1 && framesRaw <= 64 ? framesRaw : 1;
148
+ const footprint = source.footprint === undefined ? undefined : normalizeFootprintFrom(source.footprint);
149
+ const anchor = (() => {
150
+ try {
151
+ return parseIsoAnchor(source.anchor);
152
+ }
153
+ catch {
154
+ return undefined;
155
+ }
156
+ })();
157
+ const pass = (() => {
158
+ try {
159
+ return footprint === undefined ? undefined : parsePassCells(source.pass, footprint);
160
+ }
161
+ catch {
162
+ return undefined;
163
+ }
164
+ })();
165
+ const objectScale = (() => {
166
+ try {
167
+ return kind === "object" ? parseIsoObjectScale(source.objectScale) : undefined;
168
+ }
169
+ catch {
170
+ return undefined;
171
+ }
172
+ })();
173
+ const previous = Array.isArray(source.tiles) ? source.tiles : [];
174
+ let tiles = [];
175
+ try {
176
+ tiles = rebuildIsoTiles({ kind, cell, imageWidth, imageHeight, frames, animRows: source.animRows === true, footprint }, previous);
177
+ }
178
+ catch {
179
+ tiles = previous;
180
+ }
181
+ const columns = kind === "object" ? 1 : Math.max(1, Math.floor(imageWidth / Math.max(1, cell.width)));
182
+ const animRows = kind === "ground" && source.animRows === true;
183
+ const variants = kind === "object" || kind === "autotile" ? 1 : animRows ? columns : Math.max(1, tiles.length);
184
+ return {
185
+ id: typeof source.id === "string" && source.id !== "" ? source.id : `ts${randomUUID().slice(0, 6)}`,
186
+ name: typeof source.name === "string" && source.name !== "" ? source.name : "素材",
187
+ file: typeof source.file === "string" ? source.file : "",
188
+ imageWidth,
189
+ imageHeight,
190
+ cell,
191
+ kind,
192
+ shape: shapeOfKind(kind),
193
+ columns,
194
+ frames,
195
+ variants,
196
+ animRows,
197
+ footprint,
198
+ anchor,
199
+ objectScale,
200
+ pass,
201
+ loop: (() => {
202
+ try {
203
+ return parseAssetLoop(source.loop);
204
+ }
205
+ catch {
206
+ return "forward";
207
+ }
208
+ })(),
209
+ fps: (() => {
210
+ try {
211
+ return parseAssetFps(source.fps);
212
+ }
213
+ catch {
214
+ return undefined;
215
+ }
216
+ })(),
217
+ clarity: (() => {
218
+ try {
219
+ return parseClarity(source.clarity);
220
+ }
221
+ catch {
222
+ return undefined;
223
+ }
224
+ })(),
225
+ builtin: source.builtin === true ? true : undefined,
226
+ tiles
227
+ };
228
+ }
229
+ function normalizeFootprintFrom(value) {
230
+ const raw = value;
231
+ return { cols: Math.max(1, Math.round(Number(raw?.cols) || 1)), rows: Math.max(1, Math.round(Number(raw?.rows) || 1)) };
232
+ }
233
+ export async function listIsoProjects() {
234
+ let names = [];
235
+ try {
236
+ names = await readdir(isoJobsRoot());
237
+ }
238
+ catch {
239
+ return [];
240
+ }
241
+ const out = [];
242
+ for (const name of names) {
243
+ if (!isValidIsoProjectId(name))
244
+ continue;
245
+ const project = await readIsoProject(name);
246
+ if (project === undefined)
247
+ continue;
248
+ out.push(await summarizeIsoProject(project));
249
+ }
250
+ return out.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1));
251
+ }
252
+ export async function summarizeIsoProject(project) {
253
+ const doc = (await readTheDoc(project.id)) ?? createIsoDoc(project.id, project.name, 32, 32);
254
+ return {
255
+ id: project.id,
256
+ name: project.name,
257
+ updatedAt: project.updatedAt,
258
+ cell: project.cell,
259
+ wrap: project.wrap,
260
+ tilesetCount: project.tilesets.length,
261
+ tileCount: flatTiles(project.tilesets).length,
262
+ objectCount: doc.objects.length,
263
+ filled: filledCount(doc),
264
+ stages: project.stages
265
+ };
266
+ }
267
+ export async function deleteIsoProject(id) {
268
+ const state = docWrites.get(id);
269
+ if (state?.timer != null)
270
+ clearTimeout(state.timer);
271
+ docWrites.delete(id);
272
+ docCache.delete(id);
273
+ history.delete(id);
274
+ await rm(isoProjectDir(id), { recursive: true, force: true });
275
+ }
276
+ async function readProjectOrThrow(projectId) {
277
+ const project = await readIsoProject(projectId);
278
+ if (project === undefined)
279
+ throw new Error(`项目不存在:${projectId}`);
280
+ return project;
281
+ }
282
+ // ── 文档:内存真源 + 防抖落盘 ────────────────────────────────────────────
283
+ const docCache = new Map();
284
+ const docWrites = new Map();
285
+ const WRITE_MAX_LATENCY_MS = 2000;
286
+ const WRITE_IDLE_MS = 500;
287
+ export async function readTheDoc(projectId) {
288
+ const cached = docCache.get(projectId);
289
+ if (cached !== undefined)
290
+ return cached;
291
+ const raw = await readJson(isoDocFile(projectId));
292
+ const doc = normalizeIsoDoc(raw, projectId);
293
+ if (doc === undefined)
294
+ return undefined;
295
+ docCache.set(projectId, doc);
296
+ return doc;
297
+ }
298
+ async function theDocOrFresh(projectId) {
299
+ const doc = await readTheDoc(projectId);
300
+ if (doc !== undefined)
301
+ return doc;
302
+ const fresh = createIsoDoc(projectId, "地图", DEFAULT_COLS, DEFAULT_ROWS);
303
+ docCache.set(projectId, fresh);
304
+ return fresh;
305
+ }
306
+ export async function writeTheDoc(projectId, doc) {
307
+ await enqueueWrite(projectId, async () => {
308
+ await writeJsonAtomic(isoDocFile(projectId), doc);
309
+ });
310
+ }
311
+ function scheduleDocWrite(projectId, doc) {
312
+ const state = docWrites.get(projectId) ?? { timer: null, lastWrite: 0 };
313
+ docWrites.set(projectId, state);
314
+ const now = Date.now();
315
+ const elapsed = now - state.lastWrite;
316
+ if (elapsed >= WRITE_MAX_LATENCY_MS) {
317
+ state.lastWrite = now;
318
+ void writeTheDoc(projectId, doc).catch(() => undefined);
319
+ return;
320
+ }
321
+ if (state.timer !== null)
322
+ return;
323
+ state.timer = setTimeout(() => {
324
+ state.timer = null;
325
+ state.lastWrite = Date.now();
326
+ void writeTheDoc(projectId, doc).catch(() => undefined);
327
+ }, Math.max(WRITE_IDLE_MS, WRITE_MAX_LATENCY_MS - elapsed));
328
+ if (typeof state.timer.unref === "function")
329
+ state.timer.unref();
330
+ }
331
+ export async function flushIsoDoc(projectId) {
332
+ const doc = docCache.get(projectId);
333
+ if (doc === undefined)
334
+ return;
335
+ const state = docWrites.get(projectId);
336
+ if (state?.timer != null) {
337
+ clearTimeout(state.timer);
338
+ state.timer = null;
339
+ }
340
+ await writeTheDoc(projectId, doc);
341
+ }
342
+ const history = new Map();
343
+ const HISTORY_MAX_ENTRIES = 200;
344
+ const HISTORY_MAX_BYTES = 32 * 1024 * 1024;
345
+ function estimateEntryBytes(entry, doc) {
346
+ if (entry.snapshot !== undefined)
347
+ return doc.cols * doc.rows * (doc.layers.length + 1) * 4;
348
+ return (entry.redo.length + entry.undo.length) * 32;
349
+ }
350
+ function pushHistory(projectId, entry, doc) {
351
+ const state = history.get(projectId) ?? { entries: [], index: -1, bytes: 0 };
352
+ if (state.index < state.entries.length - 1) {
353
+ for (const dropped of state.entries.slice(state.index + 1))
354
+ state.bytes -= estimateEntryBytes(dropped, doc);
355
+ state.entries = state.entries.slice(0, state.index + 1);
356
+ }
357
+ const previous = state.entries[state.index];
358
+ if (entry.snapshot === undefined && entry.stroke !== undefined && previous !== undefined && previous.snapshot === undefined && previous.stroke === entry.stroke) {
359
+ previous.undo = [...entry.undo, ...previous.undo];
360
+ previous.redo = [...previous.redo, ...entry.redo];
361
+ state.bytes += estimateEntryBytes(entry, doc);
362
+ history.set(projectId, state);
363
+ return;
364
+ }
365
+ state.entries.push(entry);
366
+ state.bytes += estimateEntryBytes(entry, doc);
367
+ state.index = state.entries.length - 1;
368
+ while (state.entries.length > HISTORY_MAX_ENTRIES || (state.bytes > HISTORY_MAX_BYTES && state.entries.length > 1)) {
369
+ const dropped = state.entries.shift();
370
+ if (dropped === undefined)
371
+ break;
372
+ state.bytes -= estimateEntryBytes(dropped, doc);
373
+ state.index--;
374
+ }
375
+ state.index = Math.max(-1, state.index);
376
+ history.set(projectId, state);
377
+ }
378
+ export function historyState(projectId) {
379
+ const state = history.get(projectId);
380
+ if (state === undefined)
381
+ return { canUndo: false, canRedo: false, depth: 0 };
382
+ return { canUndo: state.index >= 0, canRedo: state.index < state.entries.length - 1, depth: state.entries.length };
383
+ }
384
+ function restoreDoc(target, snapshot) {
385
+ target.name = snapshot.name;
386
+ target.cols = snapshot.cols;
387
+ target.rows = snapshot.rows;
388
+ target.layers = snapshot.layers.map((layer) => ({ ...layer }));
389
+ target.data = Object.fromEntries(Object.entries(snapshot.data).map(([key, value]) => [key, [...value]]));
390
+ target.objects = snapshot.objects.map((object) => ({ ...object }));
391
+ target.markers = snapshot.markers.map((marker) => ({ ...marker }));
392
+ target.updatedAt = new Date().toISOString();
393
+ }
394
+ function footprintResolver(project) {
395
+ return (tilesetId) => project.tilesets.find((tileset) => tileset.id === tilesetId)?.footprint;
396
+ }
397
+ function objectTilesetResolver(project) {
398
+ return (tilesetId) => project.tilesets.some((tileset) => tileset.id === tilesetId && tileset.kind === "object");
399
+ }
400
+ function applyDocOps(doc, ops, layout, project) {
401
+ return applyOpsToDoc(doc, ops, layout, { footprintOf: footprintResolver(project), isObjectTileset: objectTilesetResolver(project) });
402
+ }
403
+ function newTilesetId() {
404
+ return `ts${randomUUID().slice(0, 8)}`;
405
+ }
406
+ async function registerIsoTileset(project, input) {
407
+ const tiles = rebuildIsoTiles({
408
+ kind: input.kind,
409
+ cell: project.cell,
410
+ imageWidth: input.imageWidth,
411
+ imageHeight: input.imageHeight,
412
+ frames: input.frames,
413
+ animRows: input.animRows,
414
+ footprint: input.footprint
415
+ }, []);
416
+ const columns = input.kind === "object" ? 1 : Math.max(1, Math.floor(input.imageWidth / Math.max(1, project.cell.width)));
417
+ const variants = input.kind === "object" || input.kind === "autotile" ? 1 : input.animRows ? columns : Math.max(1, tiles.length);
418
+ const file = `tilesets/${input.id}.${sniffImageExt(input.bytes)}`;
419
+ await writeFile(isoAssetPath(project.id, file), input.bytes);
420
+ return {
421
+ id: input.id,
422
+ name: input.name,
423
+ file,
424
+ imageWidth: input.imageWidth,
425
+ imageHeight: input.imageHeight,
426
+ cell: project.cell,
427
+ kind: input.kind,
428
+ shape: shapeOfKind(input.kind),
429
+ columns,
430
+ frames: input.frames,
431
+ variants,
432
+ animRows: input.animRows,
433
+ footprint: input.footprint,
434
+ anchor: input.anchor,
435
+ objectScale: input.kind === "object" ? input.objectScale ?? 1 : undefined,
436
+ pass: input.pass,
437
+ loop: input.loop,
438
+ fps: input.fps,
439
+ clarity: input.clarity,
440
+ builtin: input.builtin === true ? true : undefined,
441
+ tiles
442
+ };
443
+ }
444
+ function blitBitmap(dst, src, dx, dy) {
445
+ for (let y = 0; y < src.height; y++) {
446
+ const ty = dy + y;
447
+ if (ty < 0 || ty >= dst.height)
448
+ continue;
449
+ for (let x = 0; x < src.width; x++) {
450
+ const tx = dx + x;
451
+ if (tx < 0 || tx >= dst.width)
452
+ continue;
453
+ const si = (y * src.width + x) * 4;
454
+ const di = (ty * dst.width + tx) * 4;
455
+ const sa = src.rgba[si + 3];
456
+ if (sa === 0)
457
+ continue;
458
+ if (sa === 255) {
459
+ dst.rgba[di] = src.rgba[si];
460
+ dst.rgba[di + 1] = src.rgba[si + 1];
461
+ dst.rgba[di + 2] = src.rgba[si + 2];
462
+ dst.rgba[di + 3] = 255;
463
+ continue;
464
+ }
465
+ const a = sa / 255;
466
+ const inv = 1 - a;
467
+ const da = dst.rgba[di + 3] / 255;
468
+ const outA = a + da * inv;
469
+ if (outA <= 0)
470
+ continue;
471
+ dst.rgba[di] = Math.round((src.rgba[si] * a + dst.rgba[di] * da * inv) / outA);
472
+ dst.rgba[di + 1] = Math.round((src.rgba[si + 1] * a + dst.rgba[di + 1] * da * inv) / outA);
473
+ dst.rgba[di + 2] = Math.round((src.rgba[si + 2] * a + dst.rgba[di + 2] * da * inv) / outA);
474
+ dst.rgba[di + 3] = Math.round(outA * 255);
475
+ }
476
+ }
477
+ }
478
+ function sheetFromSource(source, sourceCell, targetCell, clarity) {
479
+ const cols = Math.max(1, Math.floor(source.width / sourceCell.width));
480
+ const rows = Math.max(1, Math.floor(source.height / sourceCell.height));
481
+ const out = { width: cols * targetCell.width, height: rows * targetCell.height, rgba: Buffer.alloc(cols * targetCell.width * rows * targetCell.height * 4) };
482
+ for (let r = 0; r < rows; r++) {
483
+ for (let c = 0; c < cols; c++) {
484
+ const cropped = cropTile(source, { x: c * sourceCell.width, y: r * sourceCell.height, width: sourceCell.width, height: sourceCell.height });
485
+ const fitted = cropped.width === targetCell.width && cropped.height === targetCell.height ? cropped : resampleToSize(cropped, targetCell.width, targetCell.height, clarity);
486
+ blitBitmap(out, fitted, c * targetCell.width, r * targetCell.height);
487
+ }
488
+ }
489
+ return out;
490
+ }
491
+ function objectSheet(source, sourceCell, frameCount, targetWidth, clarity) {
492
+ const sourceFrameHeight = source.height / frameCount;
493
+ if (!Number.isFinite(sourceFrameHeight) || sourceFrameHeight <= 0)
494
+ throw new Error("物件图的帧高不合法");
495
+ const targetFrameHeight = Math.max(1, Math.round((sourceFrameHeight * targetWidth) / Math.max(1, source.width)));
496
+ const out = { width: targetWidth, height: targetFrameHeight * frameCount, rgba: Buffer.alloc(targetWidth * targetFrameHeight * frameCount * 4) };
497
+ for (let frame = 0; frame < frameCount; frame++) {
498
+ const cropped = cropTile(source, { x: 0, y: Math.round(frame * sourceFrameHeight), width: source.width, height: Math.round(sourceFrameHeight) });
499
+ const fitted = resampleToSize(cropped, targetWidth, targetFrameHeight, clarity);
500
+ blitBitmap(out, fitted, 0, frame * targetFrameHeight);
501
+ }
502
+ return out;
503
+ }
504
+ export async function importIsoTileset(projectId, name, base64, opts = {}) {
505
+ const project = await readProjectOrThrow(projectId);
506
+ if (base64.trim() === "")
507
+ throw new Error("图片内容为空。");
508
+ const bytes = Buffer.from(base64, "base64");
509
+ if (bytes.length === 0)
510
+ throw new Error("图片内容为空。");
511
+ const kind = parseIsoTilesetKind(opts.kind);
512
+ const size = pngSize(bytes) ?? (await probeImageSizeFromBytes(bytes));
513
+ if (size === undefined || size.width < 1 || size.height < 1)
514
+ throw new Error("读不出图片尺寸:请换一张 PNG / JPG / WebP。");
515
+ const sourceCell = {
516
+ width: Math.max(1, Math.round(Number(opts.sourceCell?.width ?? project.cell.width) || project.cell.width)),
517
+ height: Math.max(1, Math.round(Number(opts.sourceCell?.height ?? project.cell.height) || project.cell.height))
518
+ };
519
+ const clarity = (() => {
520
+ try {
521
+ return parseClarity(opts.clarity);
522
+ }
523
+ catch (error) {
524
+ throw new Error(messageOf(error));
525
+ }
526
+ })();
527
+ const objectScale = (() => {
528
+ try {
529
+ return kind === "object" ? parseIsoObjectScale(opts.objectScale) ?? 1 : undefined;
530
+ }
531
+ catch (error) {
532
+ throw new Error(messageOf(error));
533
+ }
534
+ })();
535
+ const warnings = [];
536
+ let bitmap = await decodeBytesToBitmap(bytes);
537
+ let frames = 1;
538
+ let animRows = false;
539
+ let footprint;
540
+ let anchor;
541
+ let pass;
542
+ let stored;
543
+ if (kind === "object") {
544
+ const rawFrames = Math.round(Number(opts.frames ?? 1));
545
+ if (!Number.isFinite(rawFrames) || rawFrames < 1 || rawFrames > 64)
546
+ throw new Error(`物件帧数必须是 1~64 的整数,收到 ${String(opts.frames)}`);
547
+ frames = rawFrames;
548
+ if (size.height % frames !== 0)
549
+ throw new Error(`物件图高 ${size.height} 不能被帧数 ${frames} 整除`);
550
+ footprint = normalizeFootprintFrom(opts.footprint);
551
+ const layoutDoc = await theDocOrFresh(projectId);
552
+ if (footprint.cols > layoutDoc.cols || footprint.rows > layoutDoc.rows) {
553
+ throw new Error(`物件占格 ${footprint.cols}×${footprint.rows} 比地图(${layoutDoc.cols}×${layoutDoc.rows})还大`);
554
+ }
555
+ anchor = parseIsoAnchor(opts.anchor) ?? { x: 0.5, y: 1 };
556
+ pass = parsePassCells(opts.pass, footprint) ?? new Array(footprint.cols * footprint.rows).fill(1);
557
+ if (opts.keyGreen === true) {
558
+ const keyed = keyStampBackground(bitmap, (rgba, width, height) => keyGreen(rgba, width, height, STAMP_KEY_OPTIONS));
559
+ bitmap = keyed.bitmap;
560
+ if (keyed.keyed === 0)
561
+ warnings.push("没有检测到绿幕背景,按原图用了。");
562
+ }
563
+ const targetWidth = Math.max(1, Math.round(footprint.cols * project.cell.width * (objectScale ?? 1)));
564
+ stored = objectSheet(bitmap, sourceCell, frames, targetWidth, clarity);
565
+ }
566
+ else {
567
+ const cols = Math.floor(size.width / sourceCell.width);
568
+ const rows = Math.floor(size.height / sourceCell.height);
569
+ if (cols < 1 || rows < 1)
570
+ throw new Error(`图片 ${size.width}×${size.height} 比一格 ${sourceCell.width}×${sourceCell.height} 还小,切不出地块。`);
571
+ if (kind === "autotile" && (cols !== 4 || rows !== 4)) {
572
+ throw new Error(`自动连接必须是 4×4 = 16 块(当前 ${cols}×${rows}),请按行优先 mask 0..15 排版`);
573
+ }
574
+ animRows = kind === "ground" && (opts.animRows === true || String(opts.animRows) === "true");
575
+ frames = animRows ? rows : 1;
576
+ const resized = sheetFromSource(bitmap, sourceCell, project.cell, clarity);
577
+ stored = resized;
578
+ if (size.width % sourceCell.width !== 0 || size.height % sourceCell.height !== 0) {
579
+ warnings.push(`图片尺寸不是格子的整数倍(${size.width}×${size.height} / ${sourceCell.width}×${sourceCell.height}),右边 / 下边多出来的部分被忽略。`);
580
+ }
581
+ if (sourceCell.width !== project.cell.width || sourceCell.height !== project.cell.height) {
582
+ warnings.push(`源图每格 ${sourceCell.width}×${sourceCell.height},已按项目格子 ${project.cell.width}×${project.cell.height} 重采样。`);
583
+ }
584
+ }
585
+ const id = newTilesetId();
586
+ const tileset = await registerIsoTileset(project, {
587
+ id,
588
+ name: name.trim() === "" ? `素材 ${project.tilesets.length + 1}` : name.trim(),
589
+ bytes: encodeBitmap(stored),
590
+ kind,
591
+ imageWidth: stored.width,
592
+ imageHeight: stored.height,
593
+ frames,
594
+ animRows,
595
+ footprint,
596
+ anchor,
597
+ objectScale,
598
+ pass,
599
+ fps: (() => {
600
+ try {
601
+ return parseAssetFps(opts.fps);
602
+ }
603
+ catch {
604
+ return undefined;
605
+ }
606
+ })(),
607
+ loop: (() => {
608
+ try {
609
+ return parseAssetLoop(opts.loop);
610
+ }
611
+ catch {
612
+ return undefined;
613
+ }
614
+ })(),
615
+ clarity
616
+ });
617
+ await patchIsoProject(projectId, (fresh) => {
618
+ fresh.tilesets.push(tileset);
619
+ fresh.stages.assets = { status: "done", at: new Date().toISOString(), approved: fresh.stages.assets.approved };
620
+ appendJobLog(fresh.logs, "info", `导入素材:${tileset.name}(${tileset.kind},${tileset.imageWidth}×${tileset.imageHeight} → ${tileset.tiles.length} 块)`);
621
+ });
622
+ return { tilesets: [tileset], warnings };
623
+ }
624
+ /**
625
+ * 「AI 生成素材」的终点:把模型给的几张原图整理成 `ai/<名字>.png`。
626
+ *
627
+ * **只整理、不进素材列表**。素材属性在「新增素材」那一刻定死,所以最后一步
628
+ * 必须由用户点「确定」;返链只负责把图与建议属性预填。
629
+ */
630
+ export async function composeIsoAsset(input) {
631
+ const project = await readProjectOrThrow(input.projectId);
632
+ const files = (input.files ?? []).map((file) => String(file));
633
+ if (files.length === 0)
634
+ throw new Error("没有可整理的帧:files 不能为空。");
635
+ if (input.kind !== "ground" && input.kind !== "object") {
636
+ throw new Error(`AI 生成素材目前只支持 ground / object(收到 ${String(input.kind)})。自动连接 4×4 请手工导入。`);
637
+ }
638
+ const footprint = input.kind === "object"
639
+ ? {
640
+ cols: Math.max(1, Math.round(Number(input.footprint?.cols ?? 1) || 1)),
641
+ rows: Math.max(1, Math.round(Number(input.footprint?.rows ?? 1) || 1))
642
+ }
643
+ : undefined;
644
+ if (footprint !== undefined) {
645
+ const doc = await theDocOrFresh(project.id);
646
+ if (footprint.cols > doc.cols || footprint.rows > doc.rows) {
647
+ throw new Error(`物件占格 ${footprint.cols}×${footprint.rows} 比地图(${doc.cols}×${doc.rows})还大`);
648
+ }
649
+ }
650
+ const composed = await composeIsoFrames({
651
+ files,
652
+ kind: input.kind,
653
+ cell: project.cell,
654
+ footprint,
655
+ keyGreen: input.keyGreen !== false
656
+ });
657
+ const name = input.name === undefined || String(input.name).trim() === "" ? "AI 素材" : String(input.name).trim();
658
+ const file = `ai/${safeAssetStem(name)}.png`;
659
+ await mkdir(join(isoProjectDir(project.id), "ai"), { recursive: true });
660
+ await writeFile(isoAssetPath(project.id, file), encodeBitmap(composed.bitmap));
661
+ const animRows = input.kind === "ground" && composed.frameCount > 1;
662
+ await patchIsoProject(project.id, (fresh) => {
663
+ appendJobLog(fresh.logs, "info", `整理 AI 素材:${name}(${input.kind} / ${composed.frameCount} 帧 → ${composed.bitmap.width}×${composed.bitmap.height}${composed.scale > 1 ? `,每格 ${project.cell.width * composed.scale}px(${composed.scale} 倍)` : ""},落在 ${file},等你在「新增素材」里确认)`);
664
+ });
665
+ return {
666
+ file,
667
+ name,
668
+ kind: input.kind,
669
+ cell: project.cell,
670
+ width: composed.bitmap.width,
671
+ height: composed.bitmap.height,
672
+ frameCount: composed.frameCount,
673
+ animRows,
674
+ footprint,
675
+ scale: composed.scale,
676
+ keyed: composed.keyed,
677
+ notes: composed.notes
678
+ };
679
+ }
680
+ async function probeImageSizeFromBytes(bytes) {
681
+ const ext = sniffImageExt(bytes);
682
+ const scratch = join(dataRoot(), `iso-probe-${randomUUID().slice(0, 8)}.${ext}`);
683
+ try {
684
+ await writeFile(scratch, bytes);
685
+ return await probeImageSize(scratch);
686
+ }
687
+ catch {
688
+ return undefined;
689
+ }
690
+ finally {
691
+ await rm(scratch, { force: true });
692
+ }
693
+ }
694
+ async function decodeBytesToBitmap(bytes) {
695
+ const ext = sniffImageExt(bytes);
696
+ const scratch = join(dataRoot(), `iso-decode-${randomUUID().slice(0, 8)}.${ext}`);
697
+ try {
698
+ await writeFile(scratch, bytes);
699
+ return await decodeFile(scratch);
700
+ }
701
+ finally {
702
+ await rm(scratch, { force: true });
703
+ }
704
+ }
705
+ export async function importIsoSampleTileset(projectId) {
706
+ const project = await readProjectOrThrow(projectId);
707
+ const byName = new Map(project.tilesets.map((tileset) => [tileset.name, tileset]));
708
+ const warnings = [];
709
+ const created = [];
710
+ for (const sample of renderIsoSamples(project.cell)) {
711
+ const existing = byName.get(sample.name);
712
+ if (existing !== undefined && existing.builtin !== true) {
713
+ warnings.push(`素材「${sample.name}」是你自己导入的,同名内置素材跳过。`);
714
+ continue;
715
+ }
716
+ const size = pngSize(sample.bytes);
717
+ if (size === undefined)
718
+ throw new Error(`内置素材「${sample.name}」生成失败`);
719
+ /**
720
+ * 同名内置素材**原地刷新**(保留 id / 名字 / 速度 / 循环)。
721
+ *
722
+ * 为什么不是跳过:内置素材的生成代码改了(例如这次修水面接缝),老项目里那张图
723
+ * 还是旧版本;跳过的表现就是「点了恢复默认素材,缝还在」。刷新时图块顺序不变,
724
+ * `map.json` 里的序号仍然指同一块,已画的地图不用重画。
725
+ */
726
+ const replacing = existing !== undefined;
727
+ if (replacing && existing.tiles.length !== rebuildIsoTiles({ kind: sample.kind, cell: project.cell, imageWidth: size.width, imageHeight: size.height, frames: sample.frames, animRows: sample.animRows, footprint: sample.footprint }).length) {
728
+ warnings.push(`内置素材「${sample.name}」的图块数变了,为避免错位已跳过刷新;请新建项目。`);
729
+ continue;
730
+ }
731
+ const tileset = await registerIsoTileset(project, {
732
+ id: existing?.id ?? newTilesetId(),
733
+ name: existing?.name ?? sample.name,
734
+ bytes: sample.bytes,
735
+ kind: sample.kind,
736
+ imageWidth: size.width,
737
+ imageHeight: size.height,
738
+ frames: sample.frames,
739
+ animRows: sample.animRows,
740
+ footprint: sample.footprint,
741
+ pass: sample.pass,
742
+ builtin: true,
743
+ fps: existing?.fps,
744
+ loop: existing?.loop,
745
+ clarity: existing?.clarity
746
+ });
747
+ await patchIsoProject(projectId, (fresh) => {
748
+ const at = fresh.tilesets.findIndex((entry) => entry.id === tileset.id);
749
+ if (at >= 0)
750
+ fresh.tilesets[at] = tileset;
751
+ else
752
+ fresh.tilesets.push(tileset);
753
+ fresh.stages.assets = { status: "done", at: new Date().toISOString(), approved: fresh.stages.assets.approved };
754
+ });
755
+ created.push(tileset);
756
+ }
757
+ if (created.length > 0) {
758
+ await patchIsoProject(projectId, (fresh) => {
759
+ appendJobLog(fresh.logs, "info", `导入 / 刷新内置素材:${created.map((tileset) => tileset.name).join("、")}`);
760
+ });
761
+ }
762
+ return { tilesets: created, warnings };
763
+ }
764
+ // ── 素材属性 / 删除 ──────────────────────────────────────────────────────
765
+ export async function saveIsoTileset(projectId, tilesetId, patch) {
766
+ const project = await readProjectOrThrow(projectId);
767
+ const index = project.tilesets.findIndex((tileset) => tileset.id === tilesetId);
768
+ if (index < 0)
769
+ throw new Error(`没有这块素材:${tilesetId}`);
770
+ const current = project.tilesets[index];
771
+ const next = { ...current, tiles: current.tiles };
772
+ if (patch.name !== undefined) {
773
+ const trimmed = String(patch.name).trim();
774
+ if (trimmed !== "")
775
+ next.name = trimmed;
776
+ }
777
+ if (patch.fps !== undefined) {
778
+ if (patch.fps === null)
779
+ next.fps = undefined;
780
+ else {
781
+ const fps = parseAssetFps(patch.fps);
782
+ if (fps === undefined)
783
+ throw new Error(`播放速度必须是 ${0.5}~${30} 帧/秒`);
784
+ next.fps = fps;
785
+ }
786
+ }
787
+ if (patch.loop !== undefined)
788
+ next.loop = parseAssetLoop(patch.loop);
789
+ const warnings = [];
790
+ await patchIsoProject(projectId, (fresh) => {
791
+ const at = fresh.tilesets.findIndex((tileset) => tileset.id === tilesetId);
792
+ if (at >= 0)
793
+ fresh.tilesets[at] = next;
794
+ appendJobLog(fresh.logs, "info", `修改素材属性:${next.name}`);
795
+ });
796
+ return { tileset: next, warnings };
797
+ }
798
+ export async function removeIsoTileset(projectId, tilesetId) {
799
+ const project = await readProjectOrThrow(projectId);
800
+ const index = project.tilesets.findIndex((tileset) => tileset.id === tilesetId);
801
+ if (index < 0)
802
+ throw new Error(`没有这块素材:${tilesetId}`);
803
+ const removed = project.tilesets[index];
804
+ const nextTilesets = project.tilesets.filter((tileset) => tileset.id !== tilesetId);
805
+ const doc = await theDocOrFresh(projectId);
806
+ const oldFlat = new Map(flatTiles(project.tilesets).map((flat) => [flat.index, flat]));
807
+ const newFlat = new Map();
808
+ for (const flat of flatTiles(nextTilesets))
809
+ newFlat.set(`${flat.tilesetId}|${flat.tile.id}`, flat);
810
+ let clearedCells = 0;
811
+ for (const layer of doc.layers) {
812
+ if (layer.kind !== "ground")
813
+ continue;
814
+ const data = doc.data[layer.id];
815
+ if (data === undefined)
816
+ continue;
817
+ for (let i = 0; i < data.length; i++) {
818
+ const value = data[i] ?? 0;
819
+ if (value <= 0)
820
+ continue;
821
+ const flat = oldFlat.get(value);
822
+ if (flat === undefined || flat.tilesetId === removed.id) {
823
+ data[i] = 0;
824
+ clearedCells++;
825
+ continue;
826
+ }
827
+ const mapped = newFlat.get(`${flat.tilesetId}|${flat.tile.id}`);
828
+ if (mapped === undefined) {
829
+ data[i] = 0;
830
+ clearedCells++;
831
+ }
832
+ else {
833
+ data[i] = mapped.index;
834
+ }
835
+ }
836
+ }
837
+ const before = doc.objects.length;
838
+ doc.objects = doc.objects.filter((object) => object.tilesetId !== removed.id);
839
+ const removedObjects = before - doc.objects.length;
840
+ doc.updatedAt = new Date().toISOString();
841
+ await patchIsoProject(projectId, (fresh) => {
842
+ fresh.tilesets = nextTilesets;
843
+ appendJobLog(fresh.logs, "info", `删除素材:${removed.name}`);
844
+ });
845
+ scheduleDocWrite(projectId, doc);
846
+ await flushIsoDoc(projectId);
847
+ const warnings = [];
848
+ if (clearedCells > 0)
849
+ warnings.push(`清掉了 ${clearedCells} 个用这张素材画过的格子。`);
850
+ if (removedObjects > 0)
851
+ warnings.push(`删掉了 ${removedObjects} 个用这张素材放的物件。`);
852
+ return { removedObjects, clearedCells, warnings };
853
+ }
854
+ /** 网关 / 工具面用的素材摘要(补上 rev)。 */
855
+ export function isoTilesetBrief(tileset, rev, allTilesets) {
856
+ return briefOf(tileset, rev, allTilesets ?? [tileset]);
857
+ }
858
+ export function isoAssetBase(projectId) {
859
+ return assetBasePath(`/dsh-game-material-master/iso-assets/${projectId}/`);
860
+ }
861
+ async function fileRevision(path) {
862
+ try {
863
+ const info = await stat(path);
864
+ return Math.round(info.mtimeMs);
865
+ }
866
+ catch {
867
+ return undefined;
868
+ }
869
+ }
870
+ export async function tilesetRevisions(projectId) {
871
+ const project = await readProjectOrThrow(projectId);
872
+ return new Map(await Promise.all(project.tilesets.map(async (tileset) => [tileset.id, await fileRevision(join(isoProjectDir(projectId), tileset.file))])));
873
+ }
874
+ export async function isoView(project) {
875
+ const doc = await theDocOrFresh(project.id);
876
+ const layout = layoutOf(project.cell, doc.cols, doc.rows, project.wrap);
877
+ const flat = flatTiles(project.tilesets);
878
+ const revisions = await tilesetRevisions(project.id);
879
+ const state = historyState(project.id);
880
+ const layers = doc.layers.map((layer) => ({ ...layer, filled: filledCount(doc, layer.id) }));
881
+ const listing = await readExportListingRelative(project);
882
+ return {
883
+ id: project.id,
884
+ name: project.name,
885
+ assetBase: isoAssetBase(project.id),
886
+ cell: project.cell,
887
+ wrap: project.wrap,
888
+ cols: doc.cols,
889
+ rows: doc.rows,
890
+ layout: { stepX: layout.stepX, stepY: layout.stepY, diamondHeight: layout.diamondHeight },
891
+ bounds: planBounds(isoRenderContext(project, doc, project.tilesets), doc),
892
+ tilesets: project.tilesets.map((tileset) => briefOf(tileset, revisions.get(tileset.id), project.tilesets)),
893
+ legend: flat.map((flat) => {
894
+ const tileset = project.tilesets.find((entry) => entry.id === flat.tilesetId);
895
+ return { index: flat.index, tilesetId: flat.tilesetId, rect: flat.tile.rect, kind: (tileset?.kind ?? "ground") };
896
+ }),
897
+ layers,
898
+ markers: doc.markers.map((marker, index) => ({ id: marker.id, n: index + 1, r: marker.r, c: marker.c, name: marker.name })),
899
+ filled: filledCount(doc),
900
+ objects: objectCount(doc),
901
+ objectList: doc.objects.map((object) => {
902
+ const tileset = project.tilesets.find((entry) => entry.id === object.tilesetId);
903
+ return { id: object.id, layerId: object.layerId, tilesetId: object.tilesetId, r: object.r, c: object.c, cols: tileset?.footprint?.cols ?? 1, rows: tileset?.footprint?.rows ?? 1 };
904
+ }),
905
+ stages: project.stages,
906
+ reviewMode: project.reviewMode,
907
+ busy: isoBusy(project.id),
908
+ canUndo: state.canUndo,
909
+ canRedo: state.canRedo,
910
+ maxChunks: MAX_ISO_PLAN_CHUNKS,
911
+ warnings: warningsFor(project, doc),
912
+ logs: project.logs.slice(-40),
913
+ preview: (await readPreviewFiles(project.id)).map((name) => `preview/${name}`),
914
+ exportBase: listing?.base ?? "",
915
+ exportFiles: listing?.files ?? [],
916
+ exportPath: listing === undefined ? "" : join(isoProjectDir(project.id), "export", isoExportDirName(doc, project))
917
+ };
918
+ }
919
+ function warningsFor(project, doc) {
920
+ const out = [];
921
+ if (project.tilesets.length === 0)
922
+ out.push("还没有素材:先导入一张素材图,或者用「恢复默认素材」装一套内置素材。");
923
+ for (const tileset of project.tilesets) {
924
+ if (tileset.kind === "autotile" && tileset.tiles.length !== 16)
925
+ out.push(`素材「${tileset.name}」是自动连接,但只有 ${tileset.tiles.length} 块(需要 16 块)。`);
926
+ if (tileset.kind === "object" && tileset.footprint !== undefined) {
927
+ if (tileset.footprint.cols > doc.cols || tileset.footprint.rows > doc.rows)
928
+ out.push(`素材「${tileset.name}」的占格比地图还大,放不下去。`);
929
+ }
930
+ }
931
+ const ground = doc.layers.find((layer) => layer.kind === "ground");
932
+ if (ground !== undefined && filledCount(doc, ground.id) === 0)
933
+ out.push(`「${ground.name}」还是空的:先用笔刷铺一层,或者一键生成。`);
934
+ return out;
935
+ }
936
+ /** 物件可能高出很多格:视口范围要多给多少格 padding。 */
937
+ function planPadding(project) {
938
+ let pad = 2;
939
+ for (const tileset of project.tilesets) {
940
+ if (tileset.kind !== "object")
941
+ continue;
942
+ const rect = tileset.tiles.find((tile) => (tile.frame ?? 0) === 0)?.rect ?? tileset.tiles[0]?.rect;
943
+ if (rect === undefined)
944
+ continue;
945
+ pad = Math.max(pad, Math.ceil(rect.width / Math.max(1, project.cell.width / 2)) + 1, Math.ceil(rect.height / Math.max(1, project.cell.width / 4)) + 1);
946
+ }
947
+ return Math.min(24, pad);
948
+ }
949
+ export async function isoPlan(projectId, o) {
950
+ const project = await readProjectOrThrow(projectId);
951
+ let doc = await theDocOrFresh(projectId);
952
+ const forced = new Set();
953
+ if (Array.isArray(o.pending) && o.pending.length > 0) {
954
+ const preview = cloneIsoDoc(doc);
955
+ const previewLayout = layoutOf(project.cell, preview.cols, preview.rows, project.wrap);
956
+ const overlay = applyDocOps(preview, o.pending, previewLayout, project);
957
+ doc = preview;
958
+ for (const key of dirtyChunksFor(overlay.dirty, previewLayout))
959
+ forced.add(key);
960
+ }
961
+ const context = isoRenderContext(project, doc, project.tilesets);
962
+ const range = viewCellRange(context.layout, o.view, planPadding(project));
963
+ const covering = chunksInRange(range);
964
+ const truncated = covering.length > MAX_ISO_PLAN_CHUNKS;
965
+ const visible = truncated ? covering.slice(0, MAX_ISO_PLAN_CHUNKS) : covering;
966
+ const visibleKeys = visible.map(chunkKey);
967
+ const wanted = new Set(visibleKeys);
968
+ const have = new Set(o.have ?? []);
969
+ const plan = buildIsoPlan(context, doc, { range, layers: o.layerIds === undefined ? undefined : [...o.layerIds], includeLegend: true });
970
+ return {
971
+ cell: project.cell,
972
+ wrap: project.wrap,
973
+ cols: doc.cols,
974
+ rows: doc.rows,
975
+ layout: { stepX: context.layout.stepX, stepY: context.layout.stepY, diamondHeight: context.layout.diamondHeight },
976
+ bounds: plan.bounds,
977
+ visibleKeys,
978
+ chunks: plan.chunks.filter((chunk) => wanted.has(chunk.key) && (!have.has(chunk.key) || forced.has(chunk.key))),
979
+ legend: plan.legend,
980
+ markers: plan.markers,
981
+ ...(o.pass === true ? { pass: passCellsOf(context, doc) } : {}),
982
+ fps: plan.fps,
983
+ fpsMax: plan.fpsMax,
984
+ frameCount: plan.frameCount,
985
+ truncated,
986
+ warnings: plan.warnings
987
+ };
988
+ }
989
+ export async function applyIsoOps(projectId, ops, options = {}) {
990
+ const project = await readProjectOrThrow(projectId);
991
+ const doc = await theDocOrFresh(projectId);
992
+ const layout = layoutOf(project.cell, doc.cols, doc.rows, project.wrap);
993
+ const result = applyDocOps(doc, ops, layout, project);
994
+ if (result.changed > 0 || result.touched) {
995
+ pushHistory(projectId, { undo: result.undo, redo: result.redo, stroke: options.stroke }, doc);
996
+ scheduleDocWrite(projectId, doc);
997
+ }
998
+ const dirty = dirtyChunksFor(result.dirty, layout);
999
+ const have = new Set(options.have ?? []);
1000
+ const dropKeys = dirty.filter((key) => have.has(key));
1001
+ const state = historyState(projectId);
1002
+ return { changed: result.changed, skipped: result.skipped, dirtyChunks: dirty, dropKeys, canUndo: state.canUndo, canRedo: state.canRedo, touched: result.touched };
1003
+ }
1004
+ export async function isoUndo(projectId, have = []) {
1005
+ const project = await readProjectOrThrow(projectId);
1006
+ const doc = await theDocOrFresh(projectId);
1007
+ const state = history.get(projectId);
1008
+ if (state === undefined || state.index < 0) {
1009
+ return { changed: 0, skipped: [], dirtyChunks: [], dropKeys: [], canUndo: false, canRedo: false, touched: false };
1010
+ }
1011
+ const entry = state.entries[state.index];
1012
+ const layout = layoutOf(project.cell, doc.cols, doc.rows, project.wrap);
1013
+ let dirty = [];
1014
+ if (entry.snapshot !== undefined) {
1015
+ restoreDoc(doc, entry.snapshot.before);
1016
+ dirty = Array.from({ length: doc.rows * doc.cols }, (_unused, index) => ({ r: Math.floor(index / doc.cols), c: index % doc.cols }));
1017
+ }
1018
+ else {
1019
+ const result = applyDocOps(doc, entry.undo, layout, project);
1020
+ dirty = result.dirty;
1021
+ }
1022
+ state.index--;
1023
+ scheduleDocWrite(projectId, doc);
1024
+ const dirtyChunks = dirtyChunksFor(dirty, layout);
1025
+ const haveSet = new Set(have);
1026
+ return {
1027
+ changed: dirty.length,
1028
+ skipped: [],
1029
+ dirtyChunks,
1030
+ dropKeys: dirtyChunks.filter((key) => haveSet.has(key)),
1031
+ canUndo: state.index >= 0,
1032
+ canRedo: state.index < state.entries.length - 1,
1033
+ touched: true
1034
+ };
1035
+ }
1036
+ export async function isoRedo(projectId, have = []) {
1037
+ const project = await readProjectOrThrow(projectId);
1038
+ const doc = await theDocOrFresh(projectId);
1039
+ const state = history.get(projectId);
1040
+ if (state === undefined || state.index >= state.entries.length - 1) {
1041
+ return { changed: 0, skipped: [], dirtyChunks: [], dropKeys: [], canUndo: false, canRedo: false, touched: false };
1042
+ }
1043
+ const entry = state.entries[state.index + 1];
1044
+ const layout = layoutOf(project.cell, doc.cols, doc.rows, project.wrap);
1045
+ let dirty = [];
1046
+ if (entry.snapshot !== undefined) {
1047
+ restoreDoc(doc, entry.snapshot.after);
1048
+ dirty = Array.from({ length: doc.rows * doc.cols }, (_unused, index) => ({ r: Math.floor(index / doc.cols), c: index % doc.cols }));
1049
+ }
1050
+ else {
1051
+ const result = applyDocOps(doc, entry.redo, layout, project);
1052
+ dirty = result.dirty;
1053
+ }
1054
+ state.index++;
1055
+ scheduleDocWrite(projectId, doc);
1056
+ const dirtyChunks = dirtyChunksFor(dirty, layout);
1057
+ const haveSet = new Set(have);
1058
+ return {
1059
+ changed: dirty.length,
1060
+ skipped: [],
1061
+ dirtyChunks,
1062
+ dropKeys: dirtyChunks.filter((key) => haveSet.has(key)),
1063
+ canUndo: state.index >= 0,
1064
+ canRedo: state.index < state.entries.length - 1,
1065
+ touched: true
1066
+ };
1067
+ }
1068
+ export async function saveIsoDoc(projectId, patch) {
1069
+ const project = await readProjectOrThrow(projectId);
1070
+ const doc = await theDocOrFresh(projectId);
1071
+ const before = cloneIsoDoc(doc);
1072
+ const warnings = [];
1073
+ let structural = false;
1074
+ if (typeof patch.name === "string" && patch.name.trim() !== "" && patch.name.trim() !== doc.name) {
1075
+ doc.name = patch.name.trim();
1076
+ structural = true;
1077
+ }
1078
+ if (patch.cols !== undefined || patch.rows !== undefined) {
1079
+ const cols = positiveInt(patch.cols, doc.cols);
1080
+ const rows = positiveInt(patch.rows, doc.rows);
1081
+ if (cols !== doc.cols || rows !== doc.rows) {
1082
+ const result = resizeDoc(doc, cols, rows);
1083
+ warnings.push(`地图改成 ${cols}×${rows}${result.dropped > 0 ? `,丢掉 ${result.dropped} 个格子` : ""}${result.droppedObjects > 0 ? `、${result.droppedObjects} 个物件` : ""}${result.droppedMarkers > 0 ? `、${result.droppedMarkers} 个标记` : ""}。`);
1084
+ structural = true;
1085
+ }
1086
+ }
1087
+ if (Array.isArray(patch.layers)) {
1088
+ for (const item of patch.layers) {
1089
+ if (docRenameLayer(doc, item.id, item.name))
1090
+ structural = true;
1091
+ }
1092
+ }
1093
+ if (patch.addLayer !== undefined) {
1094
+ const kind = patch.addLayer.kind === "object" ? "object" : "ground";
1095
+ docAddLayer(doc, patch.addLayer.name, kind);
1096
+ structural = true;
1097
+ }
1098
+ if (patch.removeLayerId !== undefined) {
1099
+ const removed = docRemoveLayer(doc, patch.removeLayerId);
1100
+ if (removed)
1101
+ structural = true;
1102
+ else
1103
+ warnings.push("至少要留一层,不能把最后一层删掉。");
1104
+ }
1105
+ if (patch.moveLayer !== undefined) {
1106
+ if (docMoveLayer(doc, patch.moveLayer.id, patch.moveLayer.toIndex))
1107
+ structural = true;
1108
+ }
1109
+ if (patch.clearLayerId !== undefined) {
1110
+ const cleared = docClearLayer(doc, patch.clearLayerId);
1111
+ if (cleared > 0)
1112
+ structural = true;
1113
+ }
1114
+ if (structural) {
1115
+ const after = cloneIsoDoc(doc);
1116
+ doc.updatedAt = new Date().toISOString();
1117
+ pushHistory(projectId, { undo: [], redo: [], snapshot: { before, after } }, doc);
1118
+ scheduleDocWrite(projectId, doc);
1119
+ await flushIsoDoc(projectId);
1120
+ }
1121
+ return { doc: cloneIsoDoc(doc), dropped: 0, droppedMarkers: 0, droppedObjects: 0, warnings };
1122
+ }
1123
+ export async function saveIsoProject(projectId, patch) {
1124
+ const project = await patchIsoProject(projectId, (fresh) => {
1125
+ if (typeof patch.name === "string" && patch.name.trim() !== "")
1126
+ fresh.name = patch.name.trim();
1127
+ if (typeof patch.wrap === "boolean" && patch.wrap !== fresh.wrap) {
1128
+ fresh.wrap = patch.wrap;
1129
+ appendJobLog(fresh.logs, "info", `地图环绕:${patch.wrap ? "开" : "关"}`);
1130
+ }
1131
+ return fresh;
1132
+ });
1133
+ return isoView(project);
1134
+ }
1135
+ // ── 一键生成 ────────────────────────────────────────────────────────────
1136
+ function mulberry32(seed) {
1137
+ let a = seed >>> 0;
1138
+ return () => {
1139
+ a = (a + 0x6d2b79f5) >>> 0;
1140
+ let t = a;
1141
+ t = Math.imul(t ^ (t >>> 15), t | 1);
1142
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
1143
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
1144
+ };
1145
+ }
1146
+ export async function runIsoGenerate(projectId, options) {
1147
+ const project = await readProjectOrThrow(projectId);
1148
+ const doc = await theDocOrFresh(projectId);
1149
+ const layout = layoutOf(project.cell, doc.cols, doc.rows, project.wrap);
1150
+ const layer = options.layerId === undefined ? doc.layers.find((entry) => entry.kind === "ground") : doc.layers.find((entry) => entry.id === options.layerId);
1151
+ if (layer === undefined || layer.kind !== "ground")
1152
+ throw new Error("一键生成只能铺在地面层");
1153
+ const tiles = (options.tiles ?? []).map((value) => Math.round(Number(value))).filter((value) => Number.isFinite(value) && value > 0);
1154
+ if (tiles.length === 0)
1155
+ throw new Error("先至少选一块地面素材:在左边点一下,再点一键生成。");
1156
+ const seed = Number.isFinite(Number(options.seed)) ? Math.round(Number(options.seed)) : 20261024;
1157
+ const rng = mulberry32(seed);
1158
+ const data = doc.data[layer.id];
1159
+ const cells = [];
1160
+ if (options.kind === "random") {
1161
+ for (let r = 0; r < doc.rows; r++)
1162
+ for (let c = 0; c < doc.cols; c++)
1163
+ cells.push({ r, c, tile: tiles[Math.floor(rng() * tiles.length)] ?? tiles[0] });
1164
+ }
1165
+ else if (options.kind === "maze") {
1166
+ if (tiles.length < 2)
1167
+ throw new Error("迷宫需要两块素材:第一块当墙、第二块当通路。");
1168
+ const wall = tiles[0];
1169
+ const floor = tiles[1];
1170
+ const maze = new Array(doc.cols * doc.rows).fill(wall);
1171
+ const visited = new Set();
1172
+ const stack = [{ r: 1, c: 1 }];
1173
+ visited.add("1,1");
1174
+ maze[1 * doc.cols + 1] = floor;
1175
+ while (stack.length > 0) {
1176
+ const at = stack[stack.length - 1];
1177
+ const dirs = [
1178
+ { dr: -2, dc: 0 },
1179
+ { dr: 2, dc: 0 },
1180
+ { dr: 0, dc: -2 },
1181
+ { dr: 0, dc: 2 }
1182
+ ].filter((dir) => {
1183
+ const nr = at.r + dir.dr;
1184
+ const nc = at.c + dir.dc;
1185
+ return nr > 0 && nc > 0 && nr < doc.rows - 1 && nc < doc.cols - 1 && !visited.has(`${nr},${nc}`);
1186
+ });
1187
+ if (dirs.length === 0) {
1188
+ stack.pop();
1189
+ continue;
1190
+ }
1191
+ const dir = dirs[Math.floor(rng() * dirs.length)];
1192
+ const nr = at.r + dir.dr;
1193
+ const nc = at.c + dir.dc;
1194
+ maze[(at.r + dir.dr / 2) * doc.cols + (at.c + dir.dc / 2)] = floor;
1195
+ maze[nr * doc.cols + nc] = floor;
1196
+ visited.add(`${nr},${nc}`);
1197
+ stack.push({ r: nr, c: nc });
1198
+ }
1199
+ for (let r = 0; r < doc.rows; r++)
1200
+ for (let c = 0; c < doc.cols; c++)
1201
+ cells.push({ r, c, tile: maze[r * doc.cols + c] ?? wall });
1202
+ }
1203
+ else {
1204
+ if (tiles.length < 4)
1205
+ throw new Error("大陆需要按顺序选 4 块素材:深水 / 浅水 / 草地 / 高地。");
1206
+ const size = 17;
1207
+ const grid = Array.from({ length: size }, () => new Array(size).fill(0));
1208
+ const corners = [
1209
+ [0, 0],
1210
+ [0, size - 1],
1211
+ [size - 1, 0],
1212
+ [size - 1, size - 1]
1213
+ ];
1214
+ const vals = [0, 0.3, 0.65, 1];
1215
+ corners.forEach(([r, c], index) => {
1216
+ grid[r][c] = vals[index] + rng() * 0.08;
1217
+ });
1218
+ const mid = Math.floor(size / 2);
1219
+ grid[mid][mid] = 0.55 + rng() * 0.1;
1220
+ for (let step = mid; step > 0; step = Math.floor(step / 2)) {
1221
+ for (let r = 0; r < size; r += step) {
1222
+ for (let c = 0; c < size; c += step) {
1223
+ if (r % (step * 2) === 0 && c % (step * 2) === 0)
1224
+ continue;
1225
+ const neighbors = [];
1226
+ if (r - step >= 0)
1227
+ neighbors.push(grid[r - step][c]);
1228
+ if (r + step < size)
1229
+ neighbors.push(grid[r + step][c]);
1230
+ if (c - step >= 0)
1231
+ neighbors.push(grid[r][c - step]);
1232
+ if (c + step < size)
1233
+ neighbors.push(grid[r][c + step]);
1234
+ if (neighbors.length === 0)
1235
+ continue;
1236
+ grid[r][c] = neighbors.reduce((sum, value) => sum + value, 0) / neighbors.length + (rng() - 0.5) * 0.08;
1237
+ }
1238
+ }
1239
+ for (let r = 0; r < size; r += step * 2) {
1240
+ for (let c = 0; c < size; c += step * 2) {
1241
+ if (r + step < size && c + step < size) {
1242
+ const avg = (grid[r][c] + grid[r + step][c] + grid[r][c + step] + grid[r + step][c + step]) / 4;
1243
+ if (r + step < size)
1244
+ grid[r + step][c + step / 2] = avg + (rng() - 0.5) * 0.06;
1245
+ if (c + step < size)
1246
+ grid[r + step / 2][c + step] = avg + (rng() - 0.5) * 0.06;
1247
+ }
1248
+ }
1249
+ }
1250
+ }
1251
+ const tileFor = (value) => {
1252
+ if (value < 0.28)
1253
+ return tiles[0];
1254
+ if (value < 0.48)
1255
+ return tiles[1];
1256
+ if (value < 0.72)
1257
+ return tiles[2];
1258
+ return tiles[3];
1259
+ };
1260
+ for (let r = 0; r < doc.rows; r++) {
1261
+ for (let c = 0; c < doc.cols; c++) {
1262
+ const sr = Math.min(size - 1, Math.floor((r / Math.max(1, doc.rows)) * size));
1263
+ const sc = Math.min(size - 1, Math.floor((c / Math.max(1, doc.cols)) * size));
1264
+ cells.push({ r, c, tile: tileFor(grid[sr][sc]) });
1265
+ }
1266
+ }
1267
+ }
1268
+ const outcome = await applyIsoOps(projectId, [{ kind: "paint", layerId: layer.id, cells }], { stroke: `generate-${seed}` });
1269
+ return { changed: outcome.changed, seed, warnings: outcome.skipped };
1270
+ }
1271
+ // ── 预览 / 导出 ─────────────────────────────────────────────────────────
1272
+ const reserved = new Set();
1273
+ const cancelled = new Set();
1274
+ export function isoBusy(projectId) {
1275
+ return reserved.has(projectId);
1276
+ }
1277
+ export function cancelIsoJob(projectId) {
1278
+ cancelled.add(projectId);
1279
+ }
1280
+ function reserve(projectId) {
1281
+ if (reserved.has(projectId))
1282
+ return "这个项目已经有任务在跑了,等它跑完再提交。";
1283
+ reserved.add(projectId);
1284
+ return undefined;
1285
+ }
1286
+ async function background(projectId, stage, run) {
1287
+ cancelled.delete(projectId);
1288
+ await patchIsoProject(projectId, (project) => {
1289
+ project.stages[stage] = { status: "running", at: new Date().toISOString() };
1290
+ }).catch(() => undefined);
1291
+ try {
1292
+ await run();
1293
+ await patchIsoProject(projectId, (project) => {
1294
+ if (project.stages[stage].status === "running")
1295
+ project.stages[stage] = { status: "done", at: new Date().toISOString(), approved: project.stages[stage].approved };
1296
+ });
1297
+ }
1298
+ catch (error) {
1299
+ const message = messageOf(error);
1300
+ await patchIsoProject(projectId, (project) => {
1301
+ project.stages[stage] = { status: "error", error: message, at: new Date().toISOString() };
1302
+ appendJobLog(project.logs, "error", `${stage === "paint" ? "预览" : "导出"}失败:${message}`);
1303
+ }).catch(() => undefined);
1304
+ }
1305
+ finally {
1306
+ reserved.delete(projectId);
1307
+ }
1308
+ }
1309
+ async function decodeTilesetsForProject(project) {
1310
+ const lookup = new Map();
1311
+ for (const tileset of project.tilesets) {
1312
+ if (tileset.file === "")
1313
+ continue;
1314
+ try {
1315
+ lookup.set(tileset.id, await decodeFile(isoAssetPath(project.id, tileset.file)));
1316
+ }
1317
+ catch {
1318
+ /* 缺图按透明跳过,rasterize 会报警 */
1319
+ }
1320
+ }
1321
+ return lookup;
1322
+ }
1323
+ export async function runIsoPreview(projectId) {
1324
+ const reason = reserve(projectId);
1325
+ if (reason !== undefined)
1326
+ return { started: false, reason };
1327
+ let project;
1328
+ try {
1329
+ project = await readProjectOrThrow(projectId);
1330
+ }
1331
+ catch (error) {
1332
+ reserved.delete(projectId);
1333
+ throw error;
1334
+ }
1335
+ if (project.tilesets.length === 0) {
1336
+ reserved.delete(projectId);
1337
+ return { started: false, reason: "还没有素材。" };
1338
+ }
1339
+ void background(projectId, "paint", async () => {
1340
+ const fresh = await readProjectOrThrow(projectId);
1341
+ const doc = await theDocOrFresh(projectId);
1342
+ await flushIsoDoc(projectId);
1343
+ if (cancelled.has(projectId))
1344
+ return;
1345
+ const bitmaps = await decodeTilesetsForProject(fresh);
1346
+ const raster = rasterizeIso(isoRenderContext(fresh, doc, fresh.tilesets), doc, bitmaps, { scale: 1 });
1347
+ const previewDir = join(isoProjectDir(projectId), "preview");
1348
+ await mkdir(previewDir, { recursive: true });
1349
+ await writeFile(join(previewDir, "map.png"), isoBitmapToPng(raster.bitmap));
1350
+ await patchIsoProject(projectId, (current) => {
1351
+ appendJobLog(current.logs, "info", `生成地图预览图:preview/map.png(${doc.cols}×${doc.rows},${raster.bitmap.width}×${raster.bitmap.height} 像素)`);
1352
+ if (raster.drawn === 0)
1353
+ appendJobLog(current.logs, "warn", "地图还是空的:预览图是全透明的,先画点东西再看大图。");
1354
+ for (const warning of raster.warnings)
1355
+ appendJobLog(current.logs, "warn", `预览告警:${warning}`);
1356
+ });
1357
+ });
1358
+ return { started: true };
1359
+ }
1360
+ export function isoExportDirName(doc, project) {
1361
+ const name = doc?.name ?? project.name;
1362
+ const safe = name.replace(/[^\w\u4e00-\u9fa5.-]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 60);
1363
+ return safe === "" ? project.id : safe;
1364
+ }
1365
+ export function isoExportDir(projectId, doc, project) {
1366
+ return join(isoProjectDir(projectId), "export", isoExportDirName(doc, project));
1367
+ }
1368
+ async function readExportListingRelative(project) {
1369
+ const doc = await readTheDoc(project.id);
1370
+ if (doc === undefined)
1371
+ return undefined;
1372
+ const dir = isoExportDir(project.id, doc, project);
1373
+ try {
1374
+ const names = await readdir(dir);
1375
+ return { base: `export/${isoExportDirName(doc, project)}/`, files: names.sort(), warnings: [] };
1376
+ }
1377
+ catch {
1378
+ return undefined;
1379
+ }
1380
+ }
1381
+ async function readPreviewFiles(projectId) {
1382
+ try {
1383
+ const names = await readdir(join(isoProjectDir(projectId), "preview"));
1384
+ return names.filter((name) => name.endsWith(".png")).sort();
1385
+ }
1386
+ catch {
1387
+ return [];
1388
+ }
1389
+ }
1390
+ export async function runIsoExport(projectId, options = {}) {
1391
+ const reason = reserve(projectId);
1392
+ if (reason !== undefined)
1393
+ return { started: false, reason };
1394
+ let project;
1395
+ try {
1396
+ project = await readProjectOrThrow(projectId);
1397
+ }
1398
+ catch (error) {
1399
+ reserved.delete(projectId);
1400
+ throw error;
1401
+ }
1402
+ void background(projectId, "export", async () => {
1403
+ const fresh = await readProjectOrThrow(projectId);
1404
+ const doc = await theDocOrFresh(projectId);
1405
+ await flushIsoDoc(projectId);
1406
+ if (cancelled.has(projectId))
1407
+ return;
1408
+ const dir = isoExportDir(projectId, doc, fresh);
1409
+ const manifest = await exportIsoMap({
1410
+ project: { id: fresh.id, name: fresh.name },
1411
+ doc,
1412
+ context: isoRenderContext(fresh, doc, fresh.tilesets),
1413
+ dir,
1414
+ formats: { ...options.formats, scale: options.scale },
1415
+ tilesetPath: (file) => isoAssetPath(projectId, file)
1416
+ });
1417
+ await patchIsoProject(projectId, (current) => {
1418
+ appendJobLog(current.logs, "info", `导出完成:${dir}(${manifest.files.length} 个文件)`);
1419
+ for (const warning of manifest.warnings)
1420
+ appendJobLog(current.logs, "warn", `导出告警:${warning}`);
1421
+ });
1422
+ });
1423
+ return { started: true };
1424
+ }
1425
+ export async function isoRevealDir(projectId, target = "project") {
1426
+ const project = await readProjectOrThrow(projectId);
1427
+ if (target === "export") {
1428
+ const doc = await readTheDoc(projectId);
1429
+ const dir = isoExportDir(projectId, doc, project);
1430
+ try {
1431
+ await stat(dir);
1432
+ return dir;
1433
+ }
1434
+ catch {
1435
+ return isoProjectDir(projectId);
1436
+ }
1437
+ }
1438
+ return isoProjectDir(projectId);
1439
+ }
1440
+ function absoluteIsoAssetUrl(projectId, origin, relative) {
1441
+ return `${origin}${assetBasePath(`/dsh-game-material-master/iso-assets/${projectId}/`)}${relative}`;
1442
+ }
1443
+ export async function isoSnapshot(project, origin) {
1444
+ const view = await isoView(project);
1445
+ const doc = await theDocOrFresh(project.id);
1446
+ const listing = await readExportListingRelative(project);
1447
+ const preview = view.preview;
1448
+ const nextActions = [];
1449
+ if (view.tilesets.length === 0)
1450
+ nextActions.push({ step: "assets", why: "还没有素材:importIsoTileset 传图片 base64,或者 importIsoSampleTileset 装内置素材(免费)。" });
1451
+ if (view.filled === 0)
1452
+ nextActions.push({ step: "paint", why: "地图还是空的:runIsoGenerate 一键铺,或者 applyIsoOps 直接画。" });
1453
+ else if (listing === undefined)
1454
+ nextActions.push({ step: "export", why: "还没导出过:runIsoExport 出 map.png + map.json(本地免费)。" });
1455
+ if (nextActions.length === 0)
1456
+ nextActions.push({ step: "done", why: "素材、地图、导出都有产物了。可以继续改地图,或 runIsoPreview 重新出验收图。" });
1457
+ return {
1458
+ ...view,
1459
+ projection: "isometric-2:1",
1460
+ assetBase: `${origin}${isoAssetBase(project.id)}`,
1461
+ tilesets: view.tilesets.map((tileset) => ({ ...tileset, url: absoluteIsoAssetUrl(project.id, origin, tileset.file) })),
1462
+ stages: ISO_STAGES.map((stage) => {
1463
+ const node = view.stages[stage];
1464
+ return { stage, status: node?.status ?? "idle", approved: node?.approved, error: node?.error, at: node?.at };
1465
+ }),
1466
+ previewUrls: preview.map((relative) => absoluteIsoAssetUrl(project.id, origin, relative)),
1467
+ exportBaseUrl: listing === undefined ? "" : absoluteIsoAssetUrl(project.id, origin, listing.base),
1468
+ exportWarnings: listing?.warnings ?? [],
1469
+ nextActions,
1470
+ exportPath: listing === undefined ? "" : isoExportDir(project.id, doc, project),
1471
+ exportFiles: listing?.files ?? []
1472
+ };
1473
+ }
1474
+ /** 给工具面 / 自检用的类型出口。 */
1475
+ export { MAX_ISO_DIM, MAX_ISO_PLAN_CHUNKS, MAX_ASSET_SCALE, DEFAULT_ISO_CELL };