dsh-game-material-master 0.10.2 → 0.11.1

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/mapgen.js CHANGED
@@ -34,18 +34,19 @@
34
34
  */
35
35
  import { mkdir, readdir, rm, stat, writeFile } from "node:fs/promises";
36
36
  import { existsSync } from "node:fs";
37
- import { randomUUID } from "node:crypto";
37
+ import { createHash, randomUUID } from "node:crypto";
38
38
  import { join } from "node:path";
39
39
  import { appendJobLog, messageOf, readJson, sweepTempFiles, writeJsonAtomic } from "./jsonio.js";
40
40
  import { dataRoot } from "./config.js";
41
41
  import { decodeFile, encodeBitmap, pngSize, probeImageSize, sniffImageExt } from "./bitmap.js";
42
42
  import { keyGreen } from "./chroma.js";
43
- import { addLayer, applyOps, clearLayer, cloneDoc, createMapDoc, filledCount, isDocEmpty, moveLayer, normalizeMapDoc, removeLayer, renameLayer, resizeDoc, revertOps } from "./mapdoc.js";
44
- import { assertGrid, assertMapSize, canonicalChunk, chunkKey, chunksInRange, dirtyChunksFor, layoutOf, normalizeGrid, parseChunkKey, viewCellRange, MAX_MAP_DIM, MAX_PLAN_CHUNKS } from "./mapgeom.js";
45
- import { bitmapToPng, buildPlan, rasterize, stampCellsOf } from "./maprender.js";
46
- import { COMMON_TILE_SIZES, buildTiles, composeAssetSheet, detectLayout, flatIndexByValue, flatTiles, layoutFor, safeAssetStem, sheetPlanOf, tileSeamRatios, trimUniformBorder, sizeFromBytes, parseAssetFps, parseAssetLoop, parseStampSpec, composeStampSource, stampTilesetImage, keyStampBackground, STAMP_KEY_OPTIONS, STAMP_MAX_CELLS, parseAssetScale, parseClarity, resampleToSize, A2_ROWS, MAX_ASSET_SCALE, assertStampFitsProject, } from "./maptiles.js";
43
+ import { keyScreenName, normalizeKeyColor } from "./keycolor.js";
44
+ import { addLayer, applyOps, cellIndex, clearLayer, cloneDoc, createMapDoc, filledCount, isDocEmpty, moveLayer, normalizeMapDoc, removeLayer, renameLayer, resizeDoc, revertOps } from "./mapdoc.js";
45
+ import { assertGrid, assertMapSize, canonicalChunk, chunkKey, chunksInRange, dirtyChunksFor, layoutOf, normalizeGrid, parseChunkKey, viewCellRange, wrapCell, MAX_MAP_DIM, MAX_PLAN_CHUNKS } from "./mapgeom.js";
46
+ import { bitmapToPng, buildPlan, rasterize, renderMapView, stampCellsOf } from "./maprender.js";
47
+ import { COMMON_TILE_SIZES, buildTiles, composeAssetSheet, detectLayout, flatIndexByValue, flatTiles, layoutFor, safeAssetStem, sheetPlanOf, tileSeamRatios, trimUniformBorder, sizeFromBytes, parseAssetFps, parseAssetLoop, parseStampSpec, composeStampSource, stampTilesetImage, keyStampBackground, STAMP_KEY_OPTIONS, STAMP_MAX_CELLS, STAMP_MIN_CELLS, parseAssetScale, parseClarity, resampleToSize, A2_ROWS, MAX_ASSET_SCALE, assertStampFitsProject, } from "./maptiles.js";
47
48
  import { exportMap, safeFileName } from "./mapexport.js";
48
- import { assetBasePath } from "./links.js";
49
+ import { assetBasePath, originForLinks } from "./links.js";
49
50
  import { primeSampleTextures, renderSampleTilesets } from "./mapsamplegen.js";
50
51
  /** 四个阶段(对话面契约:`stage=assets|rules|paint|export`;`rules` 自动完成、界面不显示)。 */
51
52
  export const MAP_STAGES = ["assets", "rules", "paint", "export"];
@@ -531,15 +532,32 @@ function allCells(doc) {
531
532
  export async function applyMapOps(projectId, ops, opts = {}) {
532
533
  const project = await readProjectOrThrow(projectId);
533
534
  const doc = await theDocOrFresh(projectId);
534
- const layout = layoutOf(project.grid, doc.cols, doc.rows);
535
- const result = applyOps(doc, ops, layout, { stampSpecOf: stampSpecResolver(project) });
535
+ const currentRevision = await mapRevision(project, doc);
536
+ if (opts.ifRevision !== undefined && opts.ifRevision !== "" && opts.ifRevision !== currentRevision) {
537
+ throw new Error(`版本不一致:当前 ${currentRevision},请求 ${opts.ifRevision};请重新 mapInspect 后再改。`);
538
+ }
539
+ const target = opts.dryRun === true ? cloneDoc(doc) : doc;
540
+ const layout = layoutOf(project.grid, target.cols, target.rows);
541
+ const result = applyOps(target, ops, layout, { stampSpecOf: stampSpecResolver(project) });
536
542
  // `touched`(标记改名这类不占格的改动)也要记一步撤销 —— 只看 `changed > 0` 的话,
537
543
  // 改名会「生效了但撤不回来」。
538
- if (result.changed > 0 || result.touched === true) {
544
+ if (opts.dryRun !== true && (result.changed > 0 || result.touched === true)) {
539
545
  pushHistory(projectId, { undo: result.undo, redo: ops, stroke: opts.stroke }, doc);
540
546
  scheduleDocWrite(projectId, doc);
541
547
  }
542
- return outcomeOf(projectId, result.changed, result.skipped, layout, result.dirty, opts.have, doc, result.stamps);
548
+ const summary = {
549
+ cells: result.changed,
550
+ markers: ops.filter((op) => op?.kind === "marker").length,
551
+ stamps: result.stamps,
552
+ objects: 0
553
+ };
554
+ const revision = opts.dryRun === true ? currentRevision : await mapRevision(project, doc);
555
+ return {
556
+ ...outcomeOf(projectId, result.changed, result.skipped, layout, result.dirty, opts.have, target, result.stamps),
557
+ revision,
558
+ ...(opts.dryRun === true ? { dryRun: true } : {}),
559
+ summary
560
+ };
543
561
  }
544
562
  export async function undoMap(projectId, have) {
545
563
  const project = await readProjectOrThrow(projectId);
@@ -564,14 +582,14 @@ export async function undoMap(projectId, have) {
564
582
  // (界面里抛异常就是「点了撤销整个面板报错」)。
565
583
  state.entries.splice(state.index, 1);
566
584
  state.index = Math.max(-1, state.index - 1);
567
- return outcomeOf(projectId, 0, [], layoutOf(project.grid, doc.cols, doc.rows), [], have, doc);
585
+ return { ...outcomeOf(projectId, 0, [], layoutOf(project.grid, doc.cols, doc.rows), [], have, doc), revision: await mapRevision(project, doc) };
568
586
  }
569
587
  cells = indexCells(indices, doc);
570
588
  }
571
589
  state.index--;
572
590
  scheduleDocWrite(projectId, doc);
573
591
  // 结构快照可能把尺寸改回去了 —— 脏块必须按**改完之后**的布局算。
574
- return outcomeOf(projectId, cells.length, [], layoutOf(project.grid, doc.cols, doc.rows), cells, have, doc);
592
+ return { ...outcomeOf(projectId, cells.length, [], layoutOf(project.grid, doc.cols, doc.rows), cells, have, doc), revision: await mapRevision(project, doc) };
575
593
  }
576
594
  export async function redoMap(projectId, have) {
577
595
  const project = await readProjectOrThrow(projectId);
@@ -592,14 +610,14 @@ export async function redoMap(projectId, have) {
592
610
  }
593
611
  catch {
594
612
  state.entries.splice(state.index + 1, 1);
595
- return outcomeOf(projectId, 0, [], layoutOf(project.grid, doc.cols, doc.rows), [], have, doc);
613
+ return { ...outcomeOf(projectId, 0, [], layoutOf(project.grid, doc.cols, doc.rows), [], have, doc), revision: await mapRevision(project, doc) };
596
614
  }
597
615
  cells = indexCells(indices, doc);
598
616
  }
599
617
  state.index++;
600
618
  scheduleDocWrite(projectId, doc);
601
619
  // 结构快照可能改掉了尺寸 —— 脏块按**改完之后**的布局算(同 undoMap)。
602
- return outcomeOf(projectId, cells.length, [], layoutOf(project.grid, doc.cols, doc.rows), cells, have, doc);
620
+ return { ...outcomeOf(projectId, cells.length, [], layoutOf(project.grid, doc.cols, doc.rows), cells, have, doc), revision: await mapRevision(project, doc) };
603
621
  }
604
622
  export async function saveMapDocStructure(projectId, patch) {
605
623
  const project = await readProjectOrThrow(projectId);
@@ -684,7 +702,7 @@ export async function saveMapDocStructure(projectId, patch) {
684
702
  }
685
703
  if (structural)
686
704
  await flushMapDoc(projectId);
687
- return { doc: cloneDoc(doc), dropped, warnings };
705
+ return { doc: cloneDoc(doc), dropped, warnings, revision: await mapRevision(await readProjectOrThrow(projectId), doc) };
688
706
  }
689
707
  /**
690
708
  * 导入一张素材图。**属性在这一刻定下来,之后只能删掉重来**(界面上不再提供修改入口)。
@@ -790,7 +808,7 @@ export async function importMapTileset(projectId, name, base64, opts = {}) {
790
808
  id: newTilesetId(),
791
809
  name: name.trim() === "" ? `素材 ${project.tilesets.length + 1}` : name.trim(),
792
810
  bytes,
793
- overrides: { cell: opts.cell, shape: opts.shape, animRows: opts.animRows, fps: opts.fps, clarity: opts.clarity, scale: opts.scale, loop: opts.loop, stamp: opts.stamp, stampKey: opts.stampKey },
811
+ overrides: { cell: opts.cell, shape: opts.shape, animRows: opts.animRows, fps: opts.fps, clarity: opts.clarity, scale: opts.scale, loop: opts.loop, stamp: opts.stamp, stampKey: opts.stampKey, keyColor: opts.keyColor },
794
812
  projectGrid: { width: project.grid.tileWidth, height: project.grid.tileHeight }
795
813
  }, warnings);
796
814
  await patchMapProject(projectId, (fresh) => {
@@ -918,7 +936,7 @@ export async function composeMapAsset(input) {
918
936
  ? parseStampSpec({ cols: input.stampCols, rows: input.stampRows, frames: files.length })
919
937
  : undefined;
920
938
  if (shape === "stamp" && stampSpec === undefined) {
921
- throw new Error(`整图要给「占几格」:stampCols / stampRows(2~${STAMP_MAX_CELLS})。`);
939
+ throw new Error(`整图要给「占几格」:stampCols / stampRows(${STAMP_MIN_CELLS}~${STAMP_MAX_CELLS})。`);
922
940
  }
923
941
  /** 一张整图最多和整张地图一样大(再大地图上也画不全)。 */
924
942
  if (stampSpec !== undefined) {
@@ -940,8 +958,10 @@ export async function composeMapAsset(input) {
940
958
  const frames = [];
941
959
  /** 每张源图裁掉了多少边(全部为 0 时说明没白边,不用提)。 */
942
960
  const trimmedAmounts = [];
943
- /** 整图抠绿幕的结果(keyed = 被判成背景的像素占比;0 = 没抠)。 */
961
+ /** 整图抠背景的结果(keyed = 被判成背景的像素占比;0 = 没抠)。 */
944
962
  const keyedAmounts = [];
963
+ const keyColor = normalizeKeyColor(input.keyColor);
964
+ const screen = keyScreenName(keyColor, "zh");
945
965
  for (const file of files) {
946
966
  let info;
947
967
  try {
@@ -965,7 +985,7 @@ export async function composeMapAsset(input) {
965
985
  * 留着会在地图上出现一块绿框,而且把本该空着的角落也涂满。
966
986
  * 其它形态不抠(它们的背景就是材质本身)。
967
987
  */
968
- const keyed = shape === "stamp" ? keyStampBackground(await decodeFile(file), (rgba, width, height) => keyGreen(rgba, width, height, STAMP_KEY_OPTIONS)) : undefined;
988
+ const keyed = shape === "stamp" ? keyStampBackground(await decodeFile(file), (rgba, width, height) => keyGreen(rgba, width, height, { ...STAMP_KEY_OPTIONS, keyColor })) : undefined;
969
989
  if (keyed !== undefined)
970
990
  keyedAmounts.push(keyed.keyed);
971
991
  const trimmed = trimUniformBorder(keyed === undefined ? (keyed === undefined ? await decodeFile(file) : keyed.bitmap) : keyed.bitmap);
@@ -1003,11 +1023,11 @@ export async function composeMapAsset(input) {
1003
1023
  const keyedCount = keyedAmounts.filter((fraction) => fraction > 0).length;
1004
1024
  if (keyedCount > 0) {
1005
1025
  const average = keyedAmounts.reduce((sum, value) => sum + value, 0) / keyedAmounts.length;
1006
- notes.push(`已抠掉绿幕背景(平均 ${Math.round(average * 100)}% 的像素变成透明${keyedCount < frames.length ? `,${keyedCount}/${frames.length} 张抠掉了` : ""}):` +
1007
- `整图是「立在格子上的物件」,背景要透明才看得见地砖;留着绿幕的话地图上会多出一块绿框。`);
1026
+ notes.push(`已抠掉${screen}背景(平均 ${Math.round(average * 100)}% 的像素变成透明${keyedCount < frames.length ? `,${keyedCount}/${frames.length} 张抠掉了` : ""}):` +
1027
+ `整图是「立在格子上的物件」,背景要透明才看得见地砖;留着背景的话地图上会多出一块色块。`);
1008
1028
  }
1009
1029
  else {
1010
- notes.push("**没检测到绿幕背景**:这次按原图用了(画面会连背景一起印到地图上)。想要背景透明,让模型把背景画成**纯绿**(#00FF00 一类,不要渐变 / 阴影),或者自己用透明 PNG。");
1030
+ notes.push(`**没检测到${screen}背景**:这次按原图用了(画面会连背景一起印到地图上)。想要背景透明,让模型把背景画成**纯色 ${keyColor}**(不要渐变 / 阴影),或者自己用透明 PNG。`);
1011
1031
  }
1012
1032
  }
1013
1033
  {
@@ -1059,8 +1079,11 @@ export async function composeMapAsset(input) {
1059
1079
  await patchMapProject(project.id, (fresh) => {
1060
1080
  appendJobLog(fresh.logs, "info", `整理 AI 素材:${name}(${shapeLabel} / ${frames.length} 张 → ${sheet.width}×${sheet.height}${scale > 1 ? `,每格 ${bigCell.width}px(${scale} 倍,导入时按清晰度缩到 ${cell.width}px)` : ""},落在 ${file},等你在「新增素材」里确认)`);
1061
1081
  });
1082
+ const localPath = mapAssetPath(project.id, file);
1062
1083
  return {
1063
1084
  file,
1085
+ localPath,
1086
+ previewPath: localPath,
1064
1087
  name,
1065
1088
  shape,
1066
1089
  cell,
@@ -1133,9 +1156,10 @@ async function registerTileset(projectId, input, warnings) {
1133
1156
  try {
1134
1157
  // 「导入时抠绿幕」:手动导一张带绿幕的整图时用(AI 那条路在 composeMapAsset 里已经抠过)。
1135
1158
  const keyedSource = input.overrides?.stampKey === true;
1159
+ const keyColor = normalizeKeyColor(input.overrides?.keyColor);
1136
1160
  if (stamp !== undefined && stampCell !== undefined) {
1137
1161
  const rawSource = await decodeFile(target);
1138
- const source = keyedSource ? keyStampBackground(rawSource, (rgba, width, height) => keyGreen(rgba, width, height, STAMP_KEY_OPTIONS)).bitmap : rawSource;
1162
+ const source = keyedSource ? keyStampBackground(rawSource, (rgba, width, height) => keyGreen(rgba, width, height, { ...STAMP_KEY_OPTIONS, keyColor })).bitmap : rawSource;
1139
1163
  if (keyedSource) {
1140
1164
  // 抠完的源图要写回去:下面 resample + 烘焙读的是盘上这份(也便于排查)。
1141
1165
  storedBytes = encodeBitmap(source);
@@ -1282,10 +1306,37 @@ export async function saveMapTileset(projectId, tilesetId, patch) {
1282
1306
  (nextCell !== undefined && (nextCell.width !== tileset.cell.width || nextCell.height !== tileset.cell.height)) ||
1283
1307
  (nextShape !== undefined && nextShape !== tileset.shape);
1284
1308
  if (tileset.builtin === true && touchesGeometry) {
1285
- throw new Error(`「${tileset.name}」是内置素材:名字 / 播放速度 / 循环方式可以改,形态与格子尺寸不能改 —— 想换就自己新增一张。`);
1309
+ throw new Error(`「${tileset.name}」是内置素材:名字 / 播放速度 / 循环方式 / 整图的通行区域可以改,形态与格子尺寸不能改 —— 想换就自己新增一张。`);
1286
1310
  }
1287
1311
  if (typeof patch.name === "string" && patch.name.trim() !== "")
1288
1312
  tileset.name = patch.name.trim();
1313
+ /**
1314
+ * 整图的**逐格通行区域**:只改「这格能不能走 / 谁盖住谁」,不动几何、不动图块序号,
1315
+ * 所以和名字 / 速度一样随时能改(地图上已经印好的整图下一次 `mapPlan` 就用新值)。
1316
+ *
1317
+ * 长度必须与 `cols*rows` 一致:短了会被 `parseStampSpec` 按 0 补齐 ——
1318
+ * 那等于把用户没点过的格子静默改成「不可通过」,不报错、只在走位时绊住。
1319
+ */
1320
+ if (patch.stampPass !== undefined) {
1321
+ if (tileset.shape !== "stamp" || tileset.stamp === undefined) {
1322
+ throw new Error(`「${tileset.name}」不是整图素材,没有「哪些格子能走」这一项可改。`);
1323
+ }
1324
+ const expected = tileset.stamp.cols * tileset.stamp.rows;
1325
+ if (!Array.isArray(patch.stampPass) || patch.stampPass.length !== expected) {
1326
+ throw new Error(`整图的通行区域要给 ${expected} 个值(${tileset.stamp.cols}×${tileset.stamp.rows}),收到 ${Array.isArray(patch.stampPass) ? `${patch.stampPass.length} 个` : "的不是数组"}。`);
1327
+ }
1328
+ const nextStamp = parseStampSpec({
1329
+ cols: tileset.stamp.cols,
1330
+ rows: tileset.stamp.rows,
1331
+ frames: tileset.stamp.frames,
1332
+ pass: patch.stampPass
1333
+ });
1334
+ if (nextStamp !== undefined && JSON.stringify(nextStamp.pass) !== JSON.stringify(tileset.stamp.pass)) {
1335
+ tileset.stamp = nextStamp;
1336
+ const walkable = nextStamp.pass.filter((value) => value !== 0).length;
1337
+ appendJobLog(fresh.logs, "info", `改素材通行区域:${tileset.name}(${walkable}/${expected} 格能走)`);
1338
+ }
1339
+ }
1289
1340
  /**
1290
1341
  * 播放速度是**表现层属性**(不动几何、不动序号),所以单独走一条:不触发重切、
1291
1342
  * 不重映射图层数据,只是换个数 —— 想调快调慢随时改,不用删掉重来。
@@ -1501,7 +1552,7 @@ export async function runMapGenerate(projectId, opts) {
1501
1552
  const label = opts.kind === "random" ? "随机铺满" : opts.kind === "maze" ? "迷宫" : "大陆";
1502
1553
  appendJobLog(fresh.logs, "info", `一键生成(${label}):改了 ${result.changed} 格,种子 ${seed}`);
1503
1554
  });
1504
- return { changed: result.changed, seed, warnings: [...warnings, ...result.skipped] };
1555
+ return { changed: result.changed, seed, warnings: [...warnings, ...result.skipped], revision: result.revision };
1505
1556
  }
1506
1557
  function generateValues(kind, cols, rows, tiles, seed, warnings) {
1507
1558
  if (kind === "random")
@@ -1792,6 +1843,257 @@ async function fileRevision(path) {
1792
1843
  return undefined;
1793
1844
  }
1794
1845
  }
1846
+ const INSPECT_SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1847
+ function inspectInt(value, fallback, min, max) {
1848
+ const n = Math.round(Number(value));
1849
+ if (!Number.isFinite(n))
1850
+ return fallback;
1851
+ return Math.max(min, Math.min(max, n));
1852
+ }
1853
+ function inspectRegion(value, doc) {
1854
+ const raw = (value ?? {});
1855
+ const r0 = inspectInt(raw.r0, 0, -MAX_MAP_DIM, MAX_MAP_DIM);
1856
+ const c0 = inspectInt(raw.c0, 0, -MAX_MAP_DIM, MAX_MAP_DIM);
1857
+ const r1 = inspectInt(raw.r1, doc.rows, -MAX_MAP_DIM, MAX_MAP_DIM);
1858
+ const c1 = inspectInt(raw.c1, doc.cols, -MAX_MAP_DIM, MAX_MAP_DIM);
1859
+ if (r1 <= r0 || c1 <= c0)
1860
+ throw new Error("region 必须是正矩形(r1 > r0、c1 > c0)。");
1861
+ return { r0, c0, r1, c1 };
1862
+ }
1863
+ function regionCellCount(region) {
1864
+ return (region.r1 - region.r0) * (region.c1 - region.c0);
1865
+ }
1866
+ function nextInspectRange(region, limit) {
1867
+ const width = Math.max(1, Math.min(region.c1 - region.c0, limit));
1868
+ const height = Math.max(1, Math.min(region.r1 - region.r0, Math.ceil(limit / width)));
1869
+ return { r0: region.r0, c0: region.c0, r1: region.r0 + height, c1: region.c0 + width };
1870
+ }
1871
+ /**
1872
+ * 读一块地图的语义状态:逐格图块索引(文本 + 可选数组)、标记、整图、通行性、统计。
1873
+ *
1874
+ * 与 `mapPlan` 的区别:这里不返回像素坐标 / chunk / `have`,也不按视口变化。
1875
+ * 它是 Agent 回答「这一片是什么」的稳定入口。
1876
+ */
1877
+ export async function mapInspect(projectId, options = {}) {
1878
+ const project = await readProjectOrThrow(projectId);
1879
+ const doc = await theDocOrFresh(projectId);
1880
+ const layout = layoutOf(project.grid, doc.cols, doc.rows);
1881
+ const region = inspectRegion(options.region, doc);
1882
+ const maxCells = inspectInt(options.maxCells, 4096, 1, 65_536);
1883
+ const maxItems = inspectInt(options.maxItems, 200, 1, 2_000);
1884
+ const format = options.format === "text" || options.format === "json" ? options.format : "both";
1885
+ const include = new Set(options.include ?? ["layers", "markers", "stamps", "pass", "stats", "legend"]);
1886
+ const layerFilter = options.layerIds === undefined ? undefined : new Set(options.layerIds.map(String));
1887
+ const cells = regionCellCount(region);
1888
+ const truncated = cells > maxCells;
1889
+ const nextRange = truncated ? nextInspectRange(region, maxCells) : null;
1890
+ const flat = flatTiles(project.tilesets);
1891
+ const byIndex = new Map(flat.map((entry) => [entry.index, entry]));
1892
+ const used = new Map();
1893
+ const symbolOf = new Map();
1894
+ const symbolFor = (index) => {
1895
+ const existing = symbolOf.get(index);
1896
+ if (existing !== undefined)
1897
+ return existing;
1898
+ const symbol = symbolOf.size < INSPECT_SYMBOLS.length ? INSPECT_SYMBOLS[symbolOf.size] : "?";
1899
+ symbolOf.set(index, symbol);
1900
+ return symbol;
1901
+ };
1902
+ const layers = [];
1903
+ const rowsByLayer = new Map();
1904
+ const histogram = new Map();
1905
+ let filled = 0;
1906
+ const wantRows = !truncated && format !== "json";
1907
+ for (const layer of doc.layers) {
1908
+ if (layerFilter !== undefined && !layerFilter.has(layer.id))
1909
+ continue;
1910
+ const data = doc.data[layer.id] ?? [];
1911
+ const rows = [];
1912
+ let layerFilled = 0;
1913
+ for (let r = region.r0; r < region.r1; r++) {
1914
+ let row = "";
1915
+ for (let c = region.c0; c < region.c1; c++) {
1916
+ const wrapped = wrapCell(layout, r, c);
1917
+ const outside = wrapped.r < 0 || wrapped.c < 0 || wrapped.r >= doc.rows || wrapped.c >= doc.cols;
1918
+ const value = outside ? 0 : data[cellIndex(doc, wrapped.r, wrapped.c)] ?? 0;
1919
+ if (value > 0) {
1920
+ layerFilled++;
1921
+ filled++;
1922
+ used.set(value, (used.get(value) ?? 0) + 1);
1923
+ histogram.set(value, (histogram.get(value) ?? 0) + 1);
1924
+ }
1925
+ if (!wantRows)
1926
+ continue;
1927
+ if (outside)
1928
+ row += "#";
1929
+ else if (value <= 0)
1930
+ row += "·";
1931
+ else
1932
+ row += symbolFor(value);
1933
+ }
1934
+ if (wantRows)
1935
+ rows.push(row);
1936
+ }
1937
+ rowsByLayer.set(layer.id, rows);
1938
+ layers.push({
1939
+ id: layer.id,
1940
+ name: layer.name,
1941
+ filled: layerFilled,
1942
+ ...(format === "text" || truncated ? {} : { rows })
1943
+ });
1944
+ }
1945
+ const legend = [...used.keys()]
1946
+ .sort((a, b) => a - b)
1947
+ .slice(0, INSPECT_SYMBOLS.length)
1948
+ .map((index) => {
1949
+ const entry = byIndex.get(index);
1950
+ const tileset = entry === undefined ? undefined : project.tilesets.find((item) => item.id === entry.tilesetId);
1951
+ return {
1952
+ symbol: symbolFor(index),
1953
+ index,
1954
+ ...(entry === undefined
1955
+ ? {}
1956
+ : {
1957
+ tilesetId: entry.tilesetId,
1958
+ tilesetName: tileset?.name ?? entry.tilesetId,
1959
+ tileId: entry.tile.id,
1960
+ rect: entry.tile.rect,
1961
+ shape: tileset?.shape,
1962
+ mask: entry.tile.mask,
1963
+ variant: entry.tile.variant,
1964
+ frame: entry.tile.frame
1965
+ })
1966
+ };
1967
+ });
1968
+ const markersInRegion = doc.markers.filter((marker) => marker.r >= region.r0 && marker.r < region.r1 && marker.c >= region.c0 && marker.c < region.c1);
1969
+ const markers = markersInRegion
1970
+ .slice(0, maxItems)
1971
+ .map((marker) => ({
1972
+ id: marker.id,
1973
+ n: doc.markers.indexOf(marker) + 1,
1974
+ r: marker.r,
1975
+ c: marker.c,
1976
+ name: marker.name,
1977
+ kind: marker.kind ?? "custom",
1978
+ color: marker.color ?? null,
1979
+ note: marker.note ?? "",
1980
+ tags: marker.tags ?? []
1981
+ }));
1982
+ const stampsInRegion = doc.stamps.filter((stamp) => stamp.r >= region.r0 && stamp.r < region.r1 && stamp.c >= region.c0 && stamp.c < region.c1);
1983
+ const stamps = stampsInRegion
1984
+ .slice(0, maxItems)
1985
+ .map((stamp) => {
1986
+ const tileset = project.tilesets.find((entry) => entry.id === stamp.tilesetId);
1987
+ const spec = tileset?.stamp;
1988
+ return {
1989
+ id: stamp.id,
1990
+ layerId: stamp.layerId,
1991
+ tilesetId: stamp.tilesetId,
1992
+ name: tileset?.name ?? stamp.tilesetId,
1993
+ r: stamp.r,
1994
+ c: stamp.c,
1995
+ rot: stamp.rot,
1996
+ cols: spec?.cols,
1997
+ rows: spec?.rows,
1998
+ frames: spec?.frames
1999
+ };
2000
+ });
2001
+ const pass = passCellsOf(project, doc).filter((cell) => cell.r >= region.r0 && cell.r < region.r1 && cell.c >= region.c0 && cell.c < region.c1);
2002
+ const markersByKind = new Map();
2003
+ for (const marker of doc.markers) {
2004
+ if (marker.r < region.r0 || marker.r >= region.r1 || marker.c < region.c0 || marker.c >= region.c1)
2005
+ continue;
2006
+ const kind = typeof marker.kind === "string" && marker.kind !== "" ? marker.kind : "custom";
2007
+ markersByKind.set(kind, (markersByKind.get(kind) ?? 0) + 1);
2008
+ }
2009
+ const stats = {
2010
+ cells,
2011
+ filled,
2012
+ empty: Math.max(0, cells * Math.max(1, doc.layers.length) - filled),
2013
+ fillRate: cells > 0 ? filled / (cells * Math.max(1, doc.layers.length)) : 0,
2014
+ byLayer: layers.map((layer) => ({ id: layer.id, name: layer.name, filled: layer.filled })),
2015
+ tileHistogram: [...histogram.entries()].sort((a, b) => a[0] - b[0]).map(([index, count]) => ({ index, count })),
2016
+ markersByKind: [...markersByKind.entries()].map(([kind, count]) => ({ kind, count })),
2017
+ stamps: doc.stamps.length,
2018
+ objects: 0
2019
+ };
2020
+ const text = format === "json"
2021
+ ? undefined
2022
+ : [
2023
+ `地图 ${doc.cols}×${doc.rows} · 区域 (${region.r0},${region.c0})–(${region.r1 - 1},${region.c1 - 1})`,
2024
+ ...layers.map((layer) => `${String(layer.name)}\n${(rowsByLayer.get(String(layer.id)) ?? []).join("\n") || "(内容过大,已省略逐格文本)"}`),
2025
+ `图例:${legend.map((entry) => `${String(entry.symbol)}=${String(entry.tilesetName ?? entry.tilesetId ?? "未知")}/${String(entry.index)}`).join(" ")}`
2026
+ ].join("\n\n");
2027
+ return {
2028
+ module: "map",
2029
+ projectId,
2030
+ revision: await mapRevision(project, doc),
2031
+ cols: doc.cols,
2032
+ rows: doc.rows,
2033
+ grid: project.grid,
2034
+ range: region,
2035
+ truncated,
2036
+ nextRange,
2037
+ truncatedItems: [
2038
+ ...(markersInRegion.length > markers.length ? ["markers"] : []),
2039
+ ...(stampsInRegion.length > stamps.length ? ["stamps"] : [])
2040
+ ],
2041
+ legend: include.has("legend") ? legend : [],
2042
+ layers: include.has("layers") ? layers : [],
2043
+ markers: include.has("markers") ? markers : undefined,
2044
+ stamps: include.has("stamps") ? stamps : undefined,
2045
+ pass: include.has("pass") ? pass : undefined,
2046
+ stats,
2047
+ warnings: [...warningsFor(project, doc), ...(used.size > INSPECT_SYMBOLS.length ? [`不同图块超过 ${INSPECT_SYMBOLS.length} 种,文本网格用 ? 代替,精确值请用 format=json。`] : [])],
2048
+ busy: mapBusy(projectId),
2049
+ canUndo: historyState(projectId).canUndo,
2050
+ canRedo: historyState(projectId).canRedo,
2051
+ ...(text === undefined ? {} : { text })
2052
+ };
2053
+ }
2054
+ /**
2055
+ * 文档 + 素材元数据 + 素材图 mtime 的短哈希。
2056
+ *
2057
+ * 不落盘(派生数据),同一状态稳定;写入 / 撤销 / 预览 / 检查图都带它,Agent 用它
2058
+ * 防止拿旧状态覆盖新状态。素材文件 mtime 也进哈希,因为 `recomposeMapTileset`
2059
+ * 会原地换图、元数据一个字段都不变。
2060
+ */
2061
+ export async function mapRevision(project, doc, revisions) {
2062
+ const revs = revisions ?? (await tilesetRevisions(project.id));
2063
+ const payload = JSON.stringify({
2064
+ grid: project.grid,
2065
+ doc: {
2066
+ cols: doc.cols,
2067
+ rows: doc.rows,
2068
+ layers: doc.layers,
2069
+ data: doc.data,
2070
+ markers: doc.markers,
2071
+ stamps: doc.stamps
2072
+ },
2073
+ tilesets: project.tilesets.map((tileset) => ({
2074
+ id: tileset.id,
2075
+ name: tileset.name,
2076
+ file: tileset.file,
2077
+ imageWidth: tileset.imageWidth,
2078
+ imageHeight: tileset.imageHeight,
2079
+ cell: tileset.cell,
2080
+ shape: tileset.shape,
2081
+ animRows: tileset.animRows,
2082
+ variants: tileset.variants,
2083
+ loop: tileset.loop,
2084
+ clarity: tileset.clarity,
2085
+ fps: tileset.fps,
2086
+ stamp: tileset.stamp,
2087
+ builtin: tileset.builtin === true,
2088
+ tileCount: tileset.tiles.length
2089
+ })),
2090
+ files: project.tilesets.map((tileset) => [tileset.id, revisionsOr(revs, tileset.id)])
2091
+ });
2092
+ return createHash("sha1").update(payload).digest("hex").slice(0, 12);
2093
+ }
2094
+ function revisionsOr(revisions, id) {
2095
+ return revisions.get(id) ?? 0;
2096
+ }
1795
2097
  export async function mapView(p, options = {}) {
1796
2098
  void options;
1797
2099
  const doc = await theDocOrFresh(p.id);
@@ -1801,6 +2103,7 @@ export async function mapView(p, options = {}) {
1801
2103
  const layers = doc.layers.map((layer) => ({ id: layer.id, name: layer.name, filled: filledCount(doc, layer.id) }));
1802
2104
  // 素材图的版本号(mtime)先批量取好:`map` 里不能用 await,只能先算。
1803
2105
  const revisions = await tilesetRevisions(p.id);
2106
+ const preview = (await readPreviewFiles(p.id)).map((name) => `preview/${name}`);
1804
2107
  return {
1805
2108
  id: p.id,
1806
2109
  name: p.name,
@@ -1808,6 +2111,7 @@ export async function mapView(p, options = {}) {
1808
2111
  grid: p.grid,
1809
2112
  cols: doc.cols,
1810
2113
  rows: doc.rows,
2114
+ revision: await mapRevision(p, doc, revisions),
1811
2115
  tilesets: p.tilesets.map((tileset) => ({
1812
2116
  id: tileset.id,
1813
2117
  name: tileset.name,
@@ -1830,7 +2134,17 @@ export async function mapView(p, options = {}) {
1830
2134
  })),
1831
2135
  legend: flat.map((tile) => ({ index: tile.index, tilesetId: tile.tilesetId, rect: tile.tile.rect })),
1832
2136
  layers,
1833
- markers: doc.markers.map((marker, index) => ({ id: marker.id, n: index + 1, r: marker.r, c: marker.c, name: marker.name })),
2137
+ markers: doc.markers.map((marker, index) => ({
2138
+ id: marker.id,
2139
+ n: index + 1,
2140
+ r: marker.r,
2141
+ c: marker.c,
2142
+ name: marker.name,
2143
+ ...(marker.kind === undefined ? {} : { kind: marker.kind }),
2144
+ ...(marker.color === undefined ? {} : { color: marker.color }),
2145
+ ...(marker.note === undefined ? {} : { note: marker.note }),
2146
+ ...(marker.tags === undefined ? {} : { tags: marker.tags })
2147
+ })),
1834
2148
  filled: layers.reduce((sum, layer) => sum + layer.filled, 0),
1835
2149
  stages: p.stages,
1836
2150
  reviewMode: p.reviewMode,
@@ -1840,7 +2154,8 @@ export async function mapView(p, options = {}) {
1840
2154
  maxChunks: MAX_PLAN_CHUNKS,
1841
2155
  warnings: warningsFor(p, doc),
1842
2156
  logs: p.logs.slice(-40),
1843
- preview: (await readPreviewFiles(p.id)).map((name) => `preview/${name}`),
2157
+ preview,
2158
+ previewPaths: preview.map((relative) => join(mapProjectDir(p.id), relative)),
1844
2159
  exportBase: listing?.base ?? "",
1845
2160
  exportFiles: listing?.files ?? [],
1846
2161
  exportPath: listing === undefined ? "" : join(mapProjectDir(p.id), "export", listing.dirName)
@@ -2017,10 +2332,12 @@ export async function runPreviewStage(projectId) {
2017
2332
  reserved.delete(projectId);
2018
2333
  throw error;
2019
2334
  }
2335
+ const previewPath = join(mapProjectDir(projectId), "preview", "map.png");
2020
2336
  if (project.tilesets.length === 0) {
2021
2337
  reserved.delete(projectId);
2022
- return { started: false, reason: "还没有导入素材。" };
2338
+ return { started: false, reason: "还没有导入素材。", previewPath };
2023
2339
  }
2340
+ const revisionAtStart = await mapRevision(project, await theDocOrFresh(projectId));
2024
2341
  void background(projectId, "paint", async () => {
2025
2342
  const fresh = await readProjectOrThrow(projectId);
2026
2343
  const doc = await theDocOrFresh(projectId);
@@ -2042,7 +2359,93 @@ export async function runPreviewStage(projectId) {
2042
2359
  appendJobLog(current.logs, "warn", `预览告警:${warning}`);
2043
2360
  });
2044
2361
  });
2045
- return { started: true };
2362
+ return { started: true, previewPath, revisionAtStart };
2363
+ }
2364
+ /** 检查图目录里只留最近 20 张;失败不影响本次渲染。 */
2365
+ async function pruneAgentRenders(projectId, keep = 20) {
2366
+ const dir = join(mapProjectDir(projectId), "preview", "agent");
2367
+ let names;
2368
+ try {
2369
+ names = (await readdir(dir)).filter((name) => name.endsWith(".png"));
2370
+ }
2371
+ catch {
2372
+ return;
2373
+ }
2374
+ if (names.length <= keep)
2375
+ return;
2376
+ const entries = await Promise.all(names.map(async (name) => {
2377
+ try {
2378
+ return { name, mtime: (await stat(join(dir, name))).mtimeMs };
2379
+ }
2380
+ catch {
2381
+ return { name, mtime: 0 };
2382
+ }
2383
+ }));
2384
+ entries.sort((a, b) => b.mtime - a.mtime);
2385
+ for (const entry of entries.slice(keep))
2386
+ await rm(join(dir, entry.name), { force: true }).catch(() => undefined);
2387
+ }
2388
+ /**
2389
+ * 同步渲染一块地图区域,供 Agent 用 `read_image` 看。
2390
+ *
2391
+ * 与 `runMapPreview` 的分工:这个不写阶段、不触发验收、不排队;它就是一张检查图。
2392
+ * 渲染走 `renderMapView`(同一份 `buildPlan`),所以区域图与导出图不会各算一套。
2393
+ */
2394
+ export async function runMapRender(projectId, options = {}) {
2395
+ const startedAt = Date.now();
2396
+ const project = await readProjectOrThrow(projectId);
2397
+ const doc = await theDocOrFresh(projectId);
2398
+ const revisionAtStart = await mapRevision(project, doc);
2399
+ const region = inspectRegion(options.region, doc);
2400
+ const layerIndexes = options.layerIds === undefined
2401
+ ? undefined
2402
+ : options.layerIds
2403
+ .map((id) => doc.layers.findIndex((layer) => layer.id === id))
2404
+ .filter((index) => index >= 0);
2405
+ const context = renderContextFor(project, doc);
2406
+ const lookup = await decodeTilesets(project);
2407
+ const passCells = options.overlay?.pass === true ? passCellsOf(project, doc) : undefined;
2408
+ const rendered = renderMapView(context, doc, lookup, {
2409
+ range: { r0: region.r0, c0: region.c0, r1: region.r1, c1: region.c1 },
2410
+ scale: options.scale,
2411
+ layers: layerIndexes,
2412
+ frame: options.frame,
2413
+ background: options.background,
2414
+ overlay: options.overlay,
2415
+ passCells,
2416
+ maxPixels: options.maxPixels
2417
+ });
2418
+ const dir = join(mapProjectDir(projectId), "preview", "agent");
2419
+ await mkdir(dir, { recursive: true });
2420
+ const safe = safeFileName(options.name ?? "inspect", "inspect");
2421
+ const optionsHash = createHash("sha1")
2422
+ .update(JSON.stringify({ region, scale: rendered.scale, layerIndexes, frame: options.frame ?? 0, background: options.background ?? "transparent", overlay: options.overlay ?? {} }))
2423
+ .digest("hex")
2424
+ .slice(0, 8);
2425
+ const file = `preview/agent/${safe}-${revisionAtStart}-${optionsHash}.png`;
2426
+ const localPath = join(mapProjectDir(projectId), file);
2427
+ await writeFile(localPath, bitmapToPng(rendered.bitmap));
2428
+ await pruneAgentRenders(projectId);
2429
+ const revision = await mapRevision(project, doc);
2430
+ return {
2431
+ module: "map",
2432
+ projectId,
2433
+ revision,
2434
+ revisionAtStart,
2435
+ stale: revision !== revisionAtStart,
2436
+ file,
2437
+ localPath,
2438
+ url: `${originForLinks()}${mapAssetBase(projectId)}${file}`,
2439
+ width: rendered.bitmap.width,
2440
+ height: rendered.bitmap.height,
2441
+ crop: rendered.crop,
2442
+ scale: rendered.scale,
2443
+ range: rendered.range,
2444
+ drawn: rendered.drawn,
2445
+ markersDrawn: rendered.markersDrawn,
2446
+ warnings: rendered.warnings,
2447
+ elapsedMs: Date.now() - startedAt
2448
+ };
2046
2449
  }
2047
2450
  /**
2048
2451
  * 导出目录名:跟着**地图名**走(改名地图 = 换一个自包含目录,旧目录原样留着)。