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/isogen.js CHANGED
@@ -6,21 +6,22 @@
6
6
  * 编辑期间文档以内存为权威副本、防抖落盘;导出前强制 flush。
7
7
  */
8
8
  import { mkdir, readdir, rm, stat, writeFile } from "node:fs/promises";
9
- import { randomUUID } from "node:crypto";
9
+ import { createHash, randomUUID } from "node:crypto";
10
10
  import { join } from "node:path";
11
11
  import { appendJobLog, messageOf, readJson, sweepTempFiles, writeJsonAtomic } from "./jsonio.js";
12
12
  import { dataRoot } from "./config.js";
13
13
  import { decodeFile, encodeBitmap, pngSize, probeImageSize, sniffImageExt } from "./bitmap.js";
14
14
  import { keyGreen } from "./chroma.js";
15
+ import { keyScreenName, normalizeKeyColor } from "./keycolor.js";
15
16
  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";
17
+ import { DEFAULT_ISO_CELL, MAX_ISO_DIM, MAX_ISO_PLAN_CHUNKS, assertIsoCell, assertIsoMapSize, chunkKey, chunksInRange, dirtyChunksFor, layoutOf, normalizeIsoCell, viewCellRange, wrapCell } from "./isogeom.js";
18
+ import { addLayer as docAddLayer, applyIsoOps as applyOpsToDoc, clearLayer as docClearLayer, cellIndex, cloneIsoDoc, createIsoDoc, filledCount, moveLayer as docMoveLayer, normalizeIsoDoc, objectCount, removeLayer as docRemoveLayer, renameLayer as docRenameLayer, resizeDoc } from "./isodoc.js";
18
19
  import { briefOf, parseIsoAnchor, parseIsoObjectScale, parseIsoTilesetKind, parsePassCells, rebuildIsoTiles, shapeOfKind } from "./isotiles.js";
19
- import { buildIsoPlan, isoBitmapToPng, isoRenderContext, passCellsOf, planBounds, rasterizeIso } from "./isorender.js";
20
+ import { buildIsoPlan, isoBitmapToPng, isoRenderContext, passCellsOf, planBounds, rasterizeIso, renderIsoView } from "./isorender.js";
20
21
  import { exportIsoMap } from "./isoexport.js";
21
22
  import { renderIsoSamples } from "./isosamplegen.js";
22
23
  import { composeIsoFrames } from "./isocompose.js";
23
- import { assetBasePath } from "./links.js";
24
+ import { assetBasePath, originForLinks } from "./links.js";
24
25
  export const ISO_STAGES = ["assets", "paint", "export"];
25
26
  // ── 路径与 id ─────────────────────────────────────────────────────────────
26
27
  export function isoJobsRoot() {
@@ -555,10 +556,12 @@ export async function importIsoTileset(projectId, name, base64, opts = {}) {
555
556
  anchor = parseIsoAnchor(opts.anchor) ?? { x: 0.5, y: 1 };
556
557
  pass = parsePassCells(opts.pass, footprint) ?? new Array(footprint.cols * footprint.rows).fill(1);
557
558
  if (opts.keyGreen === true) {
558
- const keyed = keyStampBackground(bitmap, (rgba, width, height) => keyGreen(rgba, width, height, STAMP_KEY_OPTIONS));
559
+ const keyColor = normalizeKeyColor(opts.keyColor);
560
+ const screen = keyScreenName(keyColor, "zh");
561
+ const keyed = keyStampBackground(bitmap, (rgba, width, height) => keyGreen(rgba, width, height, { ...STAMP_KEY_OPTIONS, keyColor }));
559
562
  bitmap = keyed.bitmap;
560
563
  if (keyed.keyed === 0)
561
- warnings.push("没有检测到绿幕背景,按原图用了。");
564
+ warnings.push(`没有检测到${screen}背景,按原图用了。`);
562
565
  }
563
566
  const targetWidth = Math.max(1, Math.round(footprint.cols * project.cell.width * (objectScale ?? 1)));
564
567
  stored = objectSheet(bitmap, sourceCell, frames, targetWidth, clarity);
@@ -652,7 +655,8 @@ export async function composeIsoAsset(input) {
652
655
  kind: input.kind,
653
656
  cell: project.cell,
654
657
  footprint,
655
- keyGreen: input.keyGreen !== false
658
+ keyGreen: input.keyGreen !== false,
659
+ keyColor: input.keyColor
656
660
  });
657
661
  const name = input.name === undefined || String(input.name).trim() === "" ? "AI 素材" : String(input.name).trim();
658
662
  const file = `ai/${safeAssetStem(name)}.png`;
@@ -662,8 +666,11 @@ export async function composeIsoAsset(input) {
662
666
  await patchIsoProject(project.id, (fresh) => {
663
667
  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
668
  });
669
+ const localPath = isoAssetPath(project.id, file);
665
670
  return {
666
671
  file,
672
+ localPath,
673
+ previewPath: localPath,
667
674
  name,
668
675
  kind: input.kind,
669
676
  cell: project.cell,
@@ -871,6 +878,49 @@ export async function tilesetRevisions(projectId) {
871
878
  const project = await readProjectOrThrow(projectId);
872
879
  return new Map(await Promise.all(project.tilesets.map(async (tileset) => [tileset.id, await fileRevision(join(isoProjectDir(projectId), tileset.file))])));
873
880
  }
881
+ /**
882
+ * 文档 + 素材元数据 + 素材图 mtime 的短哈希(与 `mapgen.mapRevision` 同口径)。
883
+ * 不落盘;同一状态稳定。
884
+ */
885
+ export async function isoRevision(project, doc, revisions) {
886
+ const revs = revisions ?? (await tilesetRevisions(project.id));
887
+ const payload = JSON.stringify({
888
+ cell: project.cell,
889
+ wrap: project.wrap,
890
+ doc: {
891
+ cols: doc.cols,
892
+ rows: doc.rows,
893
+ layers: doc.layers,
894
+ data: doc.data,
895
+ objects: doc.objects,
896
+ markers: doc.markers
897
+ },
898
+ tilesets: project.tilesets.map((tileset) => ({
899
+ id: tileset.id,
900
+ name: tileset.name,
901
+ file: tileset.file,
902
+ imageWidth: tileset.imageWidth,
903
+ imageHeight: tileset.imageHeight,
904
+ cell: tileset.cell,
905
+ kind: tileset.kind,
906
+ columns: tileset.columns,
907
+ frames: tileset.frames,
908
+ variants: tileset.variants,
909
+ animRows: tileset.animRows,
910
+ footprint: tileset.footprint,
911
+ anchor: tileset.anchor,
912
+ objectScale: tileset.objectScale,
913
+ pass: tileset.pass,
914
+ loop: tileset.loop,
915
+ clarity: tileset.clarity,
916
+ fps: tileset.fps,
917
+ builtin: tileset.builtin === true,
918
+ tileCount: tileset.tiles.length
919
+ })),
920
+ files: project.tilesets.map((tileset) => [tileset.id, revs.get(tileset.id) ?? 0])
921
+ });
922
+ return createHash("sha1").update(payload).digest("hex").slice(0, 12);
923
+ }
874
924
  export async function isoView(project) {
875
925
  const doc = await theDocOrFresh(project.id);
876
926
  const layout = layoutOf(project.cell, doc.cols, doc.rows, project.wrap);
@@ -879,6 +929,7 @@ export async function isoView(project) {
879
929
  const state = historyState(project.id);
880
930
  const layers = doc.layers.map((layer) => ({ ...layer, filled: filledCount(doc, layer.id) }));
881
931
  const listing = await readExportListingRelative(project);
932
+ const preview = (await readPreviewFiles(project.id)).map((name) => `preview/${name}`);
882
933
  return {
883
934
  id: project.id,
884
935
  name: project.name,
@@ -887,6 +938,7 @@ export async function isoView(project) {
887
938
  wrap: project.wrap,
888
939
  cols: doc.cols,
889
940
  rows: doc.rows,
941
+ revision: await isoRevision(project, doc, revisions),
890
942
  layout: { stepX: layout.stepX, stepY: layout.stepY, diamondHeight: layout.diamondHeight },
891
943
  bounds: planBounds(isoRenderContext(project, doc, project.tilesets), doc),
892
944
  tilesets: project.tilesets.map((tileset) => briefOf(tileset, revisions.get(tileset.id), project.tilesets)),
@@ -895,7 +947,17 @@ export async function isoView(project) {
895
947
  return { index: flat.index, tilesetId: flat.tilesetId, rect: flat.tile.rect, kind: (tileset?.kind ?? "ground") };
896
948
  }),
897
949
  layers,
898
- markers: doc.markers.map((marker, index) => ({ id: marker.id, n: index + 1, r: marker.r, c: marker.c, name: marker.name })),
950
+ markers: doc.markers.map((marker, index) => ({
951
+ id: marker.id,
952
+ n: index + 1,
953
+ r: marker.r,
954
+ c: marker.c,
955
+ name: marker.name,
956
+ ...(marker.kind === undefined ? {} : { kind: marker.kind }),
957
+ ...(marker.color === undefined ? {} : { color: marker.color }),
958
+ ...(marker.note === undefined ? {} : { note: marker.note }),
959
+ ...(marker.tags === undefined ? {} : { tags: marker.tags })
960
+ })),
899
961
  filled: filledCount(doc),
900
962
  objects: objectCount(doc),
901
963
  objectList: doc.objects.map((object) => {
@@ -910,12 +972,229 @@ export async function isoView(project) {
910
972
  maxChunks: MAX_ISO_PLAN_CHUNKS,
911
973
  warnings: warningsFor(project, doc),
912
974
  logs: project.logs.slice(-40),
913
- preview: (await readPreviewFiles(project.id)).map((name) => `preview/${name}`),
975
+ preview,
976
+ previewPaths: preview.map((relative) => join(isoProjectDir(project.id), relative)),
914
977
  exportBase: listing?.base ?? "",
915
978
  exportFiles: listing?.files ?? [],
916
979
  exportPath: listing === undefined ? "" : join(isoProjectDir(project.id), "export", isoExportDirName(doc, project))
917
980
  };
918
981
  }
982
+ const ISO_INSPECT_SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
983
+ function isoInspectInt(value, fallback, min, max) {
984
+ const n = Math.round(Number(value));
985
+ if (!Number.isFinite(n))
986
+ return fallback;
987
+ return Math.max(min, Math.min(max, n));
988
+ }
989
+ function isoInspectRegion(value, doc) {
990
+ const raw = (value ?? {});
991
+ const r0 = isoInspectInt(raw.r0, 0, -MAX_ISO_DIM, MAX_ISO_DIM);
992
+ const c0 = isoInspectInt(raw.c0, 0, -MAX_ISO_DIM, MAX_ISO_DIM);
993
+ const r1 = isoInspectInt(raw.r1, doc.rows, -MAX_ISO_DIM, MAX_ISO_DIM);
994
+ const c1 = isoInspectInt(raw.c1, doc.cols, -MAX_ISO_DIM, MAX_ISO_DIM);
995
+ if (r1 <= r0 || c1 <= c0)
996
+ throw new Error("region 必须是正矩形(r1 > r0、c1 > c0)。");
997
+ return { r0, c0, r1, c1 };
998
+ }
999
+ function isoInspectNextRange(region, limit) {
1000
+ const width = Math.max(1, Math.min(region.c1 - region.c0, limit));
1001
+ const height = Math.max(1, Math.min(region.r1 - region.r0, Math.ceil(limit / width)));
1002
+ return { r0: region.r0, c0: region.c0, r1: region.r0 + height, c1: region.c0 + width };
1003
+ }
1004
+ function isoObjectInRegion(object, footprint, region) {
1005
+ for (let dr = 0; dr < footprint.rows; dr++) {
1006
+ for (let dc = 0; dc < footprint.cols; dc++) {
1007
+ const r = object.r + dr;
1008
+ const c = object.c + dc;
1009
+ if (r >= region.r0 && r < region.r1 && c >= region.c0 && c < region.c1)
1010
+ return true;
1011
+ }
1012
+ }
1013
+ return false;
1014
+ }
1015
+ /**
1016
+ * 读一块 45° 地图的语义状态:地面网格、物件、标记、通行性、统计。
1017
+ * 与 `isoPlan` 分开:这里没有像素坐标 / chunk / visibleKeys。
1018
+ */
1019
+ export async function isoInspect(projectId, options = {}) {
1020
+ const project = await readProjectOrThrow(projectId);
1021
+ const doc = await theDocOrFresh(projectId);
1022
+ const layout = layoutOf(project.cell, doc.cols, doc.rows, project.wrap);
1023
+ const region = isoInspectRegion(options.region, doc);
1024
+ const maxCells = isoInspectInt(options.maxCells, 4096, 1, 65_536);
1025
+ const maxItems = isoInspectInt(options.maxItems, 200, 1, 2_000);
1026
+ const format = options.format === "text" || options.format === "json" ? options.format : "both";
1027
+ const include = new Set(options.include ?? ["layers", "markers", "objects", "pass", "stats", "legend"]);
1028
+ const layerFilter = options.layerIds === undefined ? undefined : new Set(options.layerIds.map(String));
1029
+ const cells = (region.r1 - region.r0) * (region.c1 - region.c0);
1030
+ const truncated = cells > maxCells;
1031
+ const nextRange = truncated ? isoInspectNextRange(region, maxCells) : null;
1032
+ const flat = flatTiles(project.tilesets);
1033
+ const byIndex = new Map(flat.map((entry) => [entry.index, entry]));
1034
+ const used = new Map();
1035
+ const symbolOf = new Map();
1036
+ const symbolFor = (index) => {
1037
+ const existing = symbolOf.get(index);
1038
+ if (existing !== undefined)
1039
+ return existing;
1040
+ const symbol = symbolOf.size < ISO_INSPECT_SYMBOLS.length ? ISO_INSPECT_SYMBOLS[symbolOf.size] : "?";
1041
+ symbolOf.set(index, symbol);
1042
+ return symbol;
1043
+ };
1044
+ const layers = [];
1045
+ const rowsByLayer = new Map();
1046
+ const histogram = new Map();
1047
+ let filled = 0;
1048
+ const wantRows = !truncated && format !== "json";
1049
+ for (const layer of doc.layers) {
1050
+ if (layerFilter !== undefined && !layerFilter.has(layer.id))
1051
+ continue;
1052
+ if (layer.kind === "object") {
1053
+ const count = objectCount(doc, layer.id);
1054
+ layers.push({ id: layer.id, name: layer.name, kind: layer.kind, filled: count });
1055
+ rowsByLayer.set(layer.id, []);
1056
+ continue;
1057
+ }
1058
+ const data = doc.data[layer.id] ?? [];
1059
+ const rows = [];
1060
+ let layerFilled = 0;
1061
+ for (let r = region.r0; r < region.r1; r++) {
1062
+ let row = "";
1063
+ for (let c = region.c0; c < region.c1; c++) {
1064
+ const wrapped = wrapCell(layout, r, c);
1065
+ const outside = wrapped.r < 0 || wrapped.c < 0 || wrapped.r >= doc.rows || wrapped.c >= doc.cols;
1066
+ const value = outside ? 0 : data[cellIndex(doc, wrapped.r, wrapped.c)] ?? 0;
1067
+ if (value > 0) {
1068
+ layerFilled++;
1069
+ filled++;
1070
+ used.set(value, (used.get(value) ?? 0) + 1);
1071
+ histogram.set(value, (histogram.get(value) ?? 0) + 1);
1072
+ }
1073
+ if (!wantRows)
1074
+ continue;
1075
+ if (outside)
1076
+ row += "#";
1077
+ else if (value <= 0)
1078
+ row += "·";
1079
+ else
1080
+ row += symbolFor(value);
1081
+ }
1082
+ if (wantRows)
1083
+ rows.push(row);
1084
+ }
1085
+ rowsByLayer.set(layer.id, rows);
1086
+ layers.push({ id: layer.id, name: layer.name, kind: layer.kind, filled: layerFilled, ...(format === "text" || truncated ? {} : { rows }) });
1087
+ }
1088
+ const legend = [...used.keys()]
1089
+ .sort((a, b) => a - b)
1090
+ .slice(0, ISO_INSPECT_SYMBOLS.length)
1091
+ .map((index) => {
1092
+ const entry = byIndex.get(index);
1093
+ const tileset = entry === undefined ? undefined : project.tilesets.find((item) => item.id === entry.tilesetId);
1094
+ return {
1095
+ symbol: symbolFor(index),
1096
+ index,
1097
+ ...(entry === undefined
1098
+ ? {}
1099
+ : {
1100
+ tilesetId: entry.tilesetId,
1101
+ tilesetName: tileset?.name ?? entry.tilesetId,
1102
+ tileId: entry.tile.id,
1103
+ rect: entry.tile.rect,
1104
+ kind: tileset?.kind,
1105
+ mask: entry.tile.mask,
1106
+ variant: entry.tile.variant,
1107
+ frame: entry.tile.frame
1108
+ })
1109
+ };
1110
+ });
1111
+ const markersInRegion = doc.markers.filter((marker) => marker.r >= region.r0 && marker.r < region.r1 && marker.c >= region.c0 && marker.c < region.c1);
1112
+ const markers = markersInRegion.slice(0, maxItems).map((marker) => ({
1113
+ id: marker.id,
1114
+ n: doc.markers.indexOf(marker) + 1,
1115
+ r: marker.r,
1116
+ c: marker.c,
1117
+ name: marker.name,
1118
+ kind: marker.kind ?? "custom",
1119
+ color: marker.color ?? null,
1120
+ note: marker.note ?? "",
1121
+ tags: marker.tags ?? []
1122
+ }));
1123
+ const objectsInRegion = doc.objects.filter((object) => {
1124
+ if (layerFilter !== undefined && !layerFilter.has(object.layerId))
1125
+ return false;
1126
+ const tileset = project.tilesets.find((entry) => entry.id === object.tilesetId);
1127
+ return isoObjectInRegion(object, tileset?.footprint ?? { cols: 1, rows: 1 }, region);
1128
+ });
1129
+ const objects = objectsInRegion.slice(0, maxItems).map((object) => {
1130
+ const tileset = project.tilesets.find((entry) => entry.id === object.tilesetId);
1131
+ const footprint = tileset?.footprint ?? { cols: 1, rows: 1 };
1132
+ return {
1133
+ id: object.id,
1134
+ layerId: object.layerId,
1135
+ tilesetId: object.tilesetId,
1136
+ name: tileset?.name ?? object.tilesetId,
1137
+ r: object.r,
1138
+ c: object.c,
1139
+ cols: footprint.cols,
1140
+ rows: footprint.rows,
1141
+ pass: tileset?.pass ?? []
1142
+ };
1143
+ });
1144
+ const pass = passCellsOf(isoRenderContext(project, doc, project.tilesets), doc).filter((cell) => cell.r >= region.r0 && cell.r < region.r1 && cell.c >= region.c0 && cell.c < region.c1);
1145
+ const markersByKind = new Map();
1146
+ for (const marker of markersInRegion) {
1147
+ const kind = typeof marker.kind === "string" && marker.kind !== "" ? marker.kind : "custom";
1148
+ markersByKind.set(kind, (markersByKind.get(kind) ?? 0) + 1);
1149
+ }
1150
+ const stats = {
1151
+ cells,
1152
+ filled,
1153
+ objects: objectsInRegion.length,
1154
+ markers: markersInRegion.length,
1155
+ tileHistogram: [...histogram.entries()].sort((a, b) => a[0] - b[0]).map(([index, count]) => ({ index, count })),
1156
+ markersByKind: [...markersByKind.entries()].map(([kind, count]) => ({ kind, count }))
1157
+ };
1158
+ const text = format === "json"
1159
+ ? undefined
1160
+ : [
1161
+ `45° 地图 ${doc.cols}×${doc.rows} · 区域 (${region.r0},${region.c0})–(${region.r1 - 1},${region.c1 - 1})`,
1162
+ ...layers.map((layer) => `${String(layer.name)}\n${layer.kind === "object"
1163
+ ? "(物件层,见 objects)"
1164
+ : (rowsByLayer.get(String(layer.id)) ?? []).join("\n") || "(内容过大,已省略逐格文本)"}`),
1165
+ `图例:${legend.map((entry) => `${String(entry.symbol)}=${String(entry.tilesetName ?? entry.tilesetId ?? "未知")}/${String(entry.index)}`).join(" ")}`
1166
+ ].join("\n\n");
1167
+ return {
1168
+ module: "iso",
1169
+ projectId,
1170
+ revision: await isoRevision(project, doc),
1171
+ cols: doc.cols,
1172
+ rows: doc.rows,
1173
+ cell: project.cell,
1174
+ wrap: project.wrap,
1175
+ range: region,
1176
+ truncated,
1177
+ nextRange,
1178
+ truncatedItems: [
1179
+ ...(markersInRegion.length > markers.length ? ["markers"] : []),
1180
+ ...(objectsInRegion.length > objects.length ? ["objects"] : [])
1181
+ ],
1182
+ legend: include.has("legend") ? legend : [],
1183
+ layers: include.has("layers") ? layers : [],
1184
+ markers: include.has("markers") ? markers : undefined,
1185
+ objects: include.has("objects") ? objects : undefined,
1186
+ pass: include.has("pass") ? pass : undefined,
1187
+ stats,
1188
+ warnings: [
1189
+ ...warningsFor(project, doc),
1190
+ ...(used.size > ISO_INSPECT_SYMBOLS.length ? [`不同图块超过 ${ISO_INSPECT_SYMBOLS.length} 种,文本网格用 ? 代替,精确值请用 format=json。`] : [])
1191
+ ],
1192
+ busy: isoBusy(projectId),
1193
+ canUndo: historyState(projectId).canUndo,
1194
+ canRedo: historyState(projectId).canRedo,
1195
+ ...(text === undefined ? {} : { text })
1196
+ };
1197
+ }
919
1198
  function warningsFor(project, doc) {
920
1199
  const out = [];
921
1200
  if (project.tilesets.length === 0)
@@ -989,9 +1268,14 @@ export async function isoPlan(projectId, o) {
989
1268
  export async function applyIsoOps(projectId, ops, options = {}) {
990
1269
  const project = await readProjectOrThrow(projectId);
991
1270
  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) {
1271
+ const currentRevision = await isoRevision(project, doc);
1272
+ if (options.ifRevision !== undefined && options.ifRevision !== "" && options.ifRevision !== currentRevision) {
1273
+ throw new Error(`版本不一致:当前 ${currentRevision},请求 ${options.ifRevision};请重新 isoInspect 后再改。`);
1274
+ }
1275
+ const target = options.dryRun === true ? cloneIsoDoc(doc) : doc;
1276
+ const layout = layoutOf(project.cell, target.cols, target.rows, project.wrap);
1277
+ const result = applyDocOps(target, ops, layout, project);
1278
+ if (options.dryRun !== true && (result.changed > 0 || result.touched)) {
995
1279
  pushHistory(projectId, { undo: result.undo, redo: result.redo, stroke: options.stroke }, doc);
996
1280
  scheduleDocWrite(projectId, doc);
997
1281
  }
@@ -999,14 +1283,30 @@ export async function applyIsoOps(projectId, ops, options = {}) {
999
1283
  const have = new Set(options.have ?? []);
1000
1284
  const dropKeys = dirty.filter((key) => have.has(key));
1001
1285
  const state = historyState(projectId);
1002
- return { changed: result.changed, skipped: result.skipped, dirtyChunks: dirty, dropKeys, canUndo: state.canUndo, canRedo: state.canRedo, touched: result.touched };
1286
+ return {
1287
+ changed: result.changed,
1288
+ skipped: result.skipped,
1289
+ dirtyChunks: dirty,
1290
+ dropKeys,
1291
+ canUndo: state.canUndo,
1292
+ canRedo: state.canRedo,
1293
+ touched: result.touched,
1294
+ revision: options.dryRun === true ? currentRevision : await isoRevision(project, doc),
1295
+ ...(options.dryRun === true ? { dryRun: true } : {}),
1296
+ summary: {
1297
+ cells: result.changed,
1298
+ markers: ops.filter((op) => op?.kind === "marker").length,
1299
+ stamps: 0,
1300
+ objects: ops.filter((op) => op?.kind === "object").length
1301
+ }
1302
+ };
1003
1303
  }
1004
1304
  export async function isoUndo(projectId, have = []) {
1005
1305
  const project = await readProjectOrThrow(projectId);
1006
1306
  const doc = await theDocOrFresh(projectId);
1007
1307
  const state = history.get(projectId);
1008
1308
  if (state === undefined || state.index < 0) {
1009
- return { changed: 0, skipped: [], dirtyChunks: [], dropKeys: [], canUndo: false, canRedo: false, touched: false };
1309
+ return { changed: 0, skipped: [], dirtyChunks: [], dropKeys: [], canUndo: false, canRedo: false, touched: false, revision: await isoRevision(project, doc) };
1010
1310
  }
1011
1311
  const entry = state.entries[state.index];
1012
1312
  const layout = layoutOf(project.cell, doc.cols, doc.rows, project.wrap);
@@ -1030,7 +1330,8 @@ export async function isoUndo(projectId, have = []) {
1030
1330
  dropKeys: dirtyChunks.filter((key) => haveSet.has(key)),
1031
1331
  canUndo: state.index >= 0,
1032
1332
  canRedo: state.index < state.entries.length - 1,
1033
- touched: true
1333
+ touched: true,
1334
+ revision: await isoRevision(project, doc)
1034
1335
  };
1035
1336
  }
1036
1337
  export async function isoRedo(projectId, have = []) {
@@ -1038,7 +1339,7 @@ export async function isoRedo(projectId, have = []) {
1038
1339
  const doc = await theDocOrFresh(projectId);
1039
1340
  const state = history.get(projectId);
1040
1341
  if (state === undefined || state.index >= state.entries.length - 1) {
1041
- return { changed: 0, skipped: [], dirtyChunks: [], dropKeys: [], canUndo: false, canRedo: false, touched: false };
1342
+ return { changed: 0, skipped: [], dirtyChunks: [], dropKeys: [], canUndo: false, canRedo: false, touched: false, revision: await isoRevision(project, doc) };
1042
1343
  }
1043
1344
  const entry = state.entries[state.index + 1];
1044
1345
  const layout = layoutOf(project.cell, doc.cols, doc.rows, project.wrap);
@@ -1062,7 +1363,8 @@ export async function isoRedo(projectId, have = []) {
1062
1363
  dropKeys: dirtyChunks.filter((key) => haveSet.has(key)),
1063
1364
  canUndo: state.index >= 0,
1064
1365
  canRedo: state.index < state.entries.length - 1,
1065
- touched: true
1366
+ touched: true,
1367
+ revision: await isoRevision(project, doc)
1066
1368
  };
1067
1369
  }
1068
1370
  export async function saveIsoDoc(projectId, patch) {
@@ -1118,7 +1420,14 @@ export async function saveIsoDoc(projectId, patch) {
1118
1420
  scheduleDocWrite(projectId, doc);
1119
1421
  await flushIsoDoc(projectId);
1120
1422
  }
1121
- return { doc: cloneIsoDoc(doc), dropped: 0, droppedMarkers: 0, droppedObjects: 0, warnings };
1423
+ return {
1424
+ doc: cloneIsoDoc(doc),
1425
+ dropped: 0,
1426
+ droppedMarkers: 0,
1427
+ droppedObjects: 0,
1428
+ warnings,
1429
+ revision: await isoRevision(await readProjectOrThrow(projectId), doc)
1430
+ };
1122
1431
  }
1123
1432
  export async function saveIsoProject(projectId, patch) {
1124
1433
  const project = await patchIsoProject(projectId, (fresh) => {
@@ -1270,7 +1579,7 @@ export async function runIsoGenerate(projectId, options) {
1270
1579
  }
1271
1580
  }
1272
1581
  const outcome = await applyIsoOps(projectId, [{ kind: "paint", layerId: layer.id, cells }], { stroke: `generate-${seed}` });
1273
- return { changed: outcome.changed, seed, warnings: outcome.skipped };
1582
+ return { changed: outcome.changed, seed, warnings: outcome.skipped, revision: outcome.revision };
1274
1583
  }
1275
1584
  // ── 预览 / 导出 ─────────────────────────────────────────────────────────
1276
1585
  const reserved = new Set();
@@ -1336,10 +1645,12 @@ export async function runIsoPreview(projectId) {
1336
1645
  reserved.delete(projectId);
1337
1646
  throw error;
1338
1647
  }
1648
+ const previewPath = join(isoProjectDir(projectId), "preview", "map.png");
1339
1649
  if (project.tilesets.length === 0) {
1340
1650
  reserved.delete(projectId);
1341
- return { started: false, reason: "还没有素材。" };
1651
+ return { started: false, reason: "还没有素材。", previewPath };
1342
1652
  }
1653
+ const revisionAtStart = await isoRevision(project, await theDocOrFresh(projectId));
1343
1654
  void background(projectId, "paint", async () => {
1344
1655
  const fresh = await readProjectOrThrow(projectId);
1345
1656
  const doc = await theDocOrFresh(projectId);
@@ -1359,7 +1670,87 @@ export async function runIsoPreview(projectId) {
1359
1670
  appendJobLog(current.logs, "warn", `预览告警:${warning}`);
1360
1671
  });
1361
1672
  });
1362
- return { started: true };
1673
+ return { started: true, previewPath, revisionAtStart };
1674
+ }
1675
+ async function pruneAgentRenders(projectId, keep = 20) {
1676
+ const dir = join(isoProjectDir(projectId), "preview", "agent");
1677
+ let names;
1678
+ try {
1679
+ names = (await readdir(dir)).filter((name) => name.endsWith(".png"));
1680
+ }
1681
+ catch {
1682
+ return;
1683
+ }
1684
+ if (names.length <= keep)
1685
+ return;
1686
+ const entries = await Promise.all(names.map(async (name) => {
1687
+ try {
1688
+ return { name, mtime: (await stat(join(dir, name))).mtimeMs };
1689
+ }
1690
+ catch {
1691
+ return { name, mtime: 0 };
1692
+ }
1693
+ }));
1694
+ entries.sort((a, b) => b.mtime - a.mtime);
1695
+ for (const entry of entries.slice(keep))
1696
+ await rm(join(dir, entry.name), { force: true }).catch(() => undefined);
1697
+ }
1698
+ /** 同步渲染一块 45° 地图区域;与导出共用 `buildIsoPlan` 和同一个 z 排序。 */
1699
+ export async function runIsoRender(projectId, options = {}) {
1700
+ const startedAt = Date.now();
1701
+ const project = await readProjectOrThrow(projectId);
1702
+ const doc = await theDocOrFresh(projectId);
1703
+ const revisionAtStart = await isoRevision(project, doc);
1704
+ const region = isoInspectRegion(options.region, doc);
1705
+ const layerIndexes = options.layerIds === undefined
1706
+ ? undefined
1707
+ : options.layerIds
1708
+ .map((id) => doc.layers.findIndex((layer) => layer.id === id))
1709
+ .filter((index) => index >= 0);
1710
+ const context = isoRenderContext(project, doc, project.tilesets);
1711
+ const lookup = await decodeTilesetsForProject(project);
1712
+ const passCells = options.overlay?.pass === true ? passCellsOf(context, doc) : undefined;
1713
+ const rendered = renderIsoView(context, doc, lookup, {
1714
+ range: { r0: region.r0, c0: region.c0, r1: region.r1, c1: region.c1 },
1715
+ scale: options.scale,
1716
+ layers: layerIndexes,
1717
+ frame: options.frame,
1718
+ background: options.background,
1719
+ overlay: options.overlay,
1720
+ passCells,
1721
+ maxPixels: options.maxPixels
1722
+ });
1723
+ const dir = join(isoProjectDir(projectId), "preview", "agent");
1724
+ await mkdir(dir, { recursive: true });
1725
+ const safe = (options.name ?? "inspect").replace(/[^\w\u4e00-\u9fa5.-]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 40) || "inspect";
1726
+ const optionsHash = createHash("sha1")
1727
+ .update(JSON.stringify({ region, scale: rendered.scale, layerIndexes, frame: options.frame ?? 0, background: options.background ?? "transparent", overlay: options.overlay ?? {} }))
1728
+ .digest("hex")
1729
+ .slice(0, 8);
1730
+ const file = `preview/agent/${safe}-${revisionAtStart}-${optionsHash}.png`;
1731
+ const localPath = join(isoProjectDir(projectId), file);
1732
+ await writeFile(localPath, isoBitmapToPng(rendered.bitmap));
1733
+ await pruneAgentRenders(projectId);
1734
+ const revision = await isoRevision(project, doc);
1735
+ return {
1736
+ module: "iso",
1737
+ projectId,
1738
+ revision,
1739
+ revisionAtStart,
1740
+ stale: revision !== revisionAtStart,
1741
+ file,
1742
+ localPath,
1743
+ url: `${originForLinks()}${isoAssetBase(projectId)}${file}`,
1744
+ width: rendered.bitmap.width,
1745
+ height: rendered.bitmap.height,
1746
+ crop: rendered.crop,
1747
+ scale: rendered.scale,
1748
+ range: rendered.range,
1749
+ drawn: rendered.drawn,
1750
+ markersDrawn: rendered.markersDrawn,
1751
+ warnings: rendered.warnings,
1752
+ elapsedMs: Date.now() - startedAt
1753
+ };
1363
1754
  }
1364
1755
  export function isoExportDirName(doc, project) {
1365
1756
  const name = doc?.name ?? project.name;