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/index.js CHANGED
@@ -10,17 +10,18 @@ import { assertVideoBackendReady, videoBackendOf } from "./videogen.js";
10
10
  * 直接发给浏览器——否则界面每帧都要靠 RPC 传 base64,又慢又费内存。
11
11
  */
12
12
  import { createReadStream, readdirSync, statSync } from "node:fs";
13
- import { mkdir, stat, writeFile } from "node:fs/promises";
14
- import { basename, dirname, extname, join } from "node:path";
13
+ import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
14
+ import { basename, dirname, extname, join, resolve } from "node:path";
15
15
  import { fileURLToPath } from "node:url";
16
16
  import { spawn } from "node:child_process";
17
17
  import { TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
18
18
  import { appendJobLog } from "./jsonio.js";
19
19
  import { ARK_MODEL_PRESETS, CUSTOM_PROTOCOLS, CUSTOM_PROTOCOL_DEFAULTS, DEFAULT_CONFIG, ROW_ORDER_VERSION, MINIMAX_HOST_PRESETS, MINIMAX_MODEL_PRESETS, loadConfig, maskConfig, migrateLegacyDataRoot, projectsRoot, saveConfig } from "./config.js";
20
- import { DEFAULT_ROW_ORDER, DIRECTION_KEYS, TURN_DIRECTION_DEFAULT, TURN_FRAME_COUNT_MAX, TURN_FRAME_COUNT_MIN, defaultPrompts, directionOf, localizePrompts, normalizePromptLang } from "./directions.js";
20
+ import { DEFAULT_ROW_ORDER, DIRECTION_KEYS, TURN_DIRECTION_DEFAULT, TURN_FRAME_COUNT_MAX, TURN_FRAME_COUNT_MIN, defaultPrompts, directionOf, localizePrompts, applyKeyColorToPrompts, normalizePromptLang } from "./directions.js";
21
+ import { DEFAULT_KEY_COLOR, normalizeKeyColor } from "./keycolor.js";
21
22
  import { checkFfmpeg } from "./media.js";
22
23
  import { testArk } from "./ark.js";
23
- import { customImageBlocker, imageModelOf, imageSizeOf, imageProviderBlocker, imageProviderSummary, imageUsesConfiguredSize, testCustomImage } from "./imageprovider.js";
24
+ import { customImageBlocker, imageModelOf, imageSizeOf, imageProviderBlocker, imageProviderSummary, testCustomImage } from "./imageprovider.js";
24
25
  import { detectComfyBindings, fetchComfyObjectInfo, formatBinding, normalizeComfyBaseUrl, normalizeComfyCookies, parseComfyWorkflow, testComfy } from "./comfy.js";
25
26
  import { COMP_SHARE_BASE_URL, COMP_SHARE_MODEL_ID, capabilityOf, isCompshareModel, normalizeDuration, normalizeResolution, pathPrefixOf, testMiniMax } from "./minimax.js";
26
27
  import { activatePipeline, applyTurnPicks, clearVideos, disposePipeline, ensurePoller, exportImages, importLocalVideo, listJobs, pollVideosOnce, resetFramePicks, resetTurnPicks, setFramePick, setFramePicks, setImageMode, setTurnPick, setTurnPicks, startAllImages, startCompose, startFramePick, startExtract, startImage, startRekey, startTurnFrames, startTurnVideo, startVideos } from "./pipeline.js";
@@ -200,6 +201,19 @@ function safeFileName(input) {
200
201
  const base = basename(input).replace(/[^\w.\-()\u4e00-\u9fa5]+/g, "_");
201
202
  return base === "" ? "source" : base.slice(0, 120);
202
203
  }
204
+ /** 工具面路径导入:宿主读盘、按文件头嗅探,返回 base64(供 import* 复用)。 */
205
+ async function readImageBase64FromPath(path) {
206
+ const absolute = resolve(path);
207
+ const info = await stat(absolute);
208
+ if (!info.isFile())
209
+ throw new Error(`不是文件:${absolute}`);
210
+ if (info.size > 30 * 1024 * 1024)
211
+ throw new Error(`素材图 ${(info.size / 1024 / 1024).toFixed(1)}MB 超过 30MB 上限:${absolute}`);
212
+ const base64 = (await readFile(absolute)).toString("base64");
213
+ if (sniffImage(base64) === undefined)
214
+ throw new Error(`无法识别的图片格式(支持 PNG / JPEG / WebP / GIF / BMP):${absolute}`);
215
+ return base64;
216
+ }
203
217
  export class GameStudioGateway extends TypertRemoteService {
204
218
  ffmpegCache;
205
219
  constructor(ctx) {
@@ -376,6 +390,7 @@ export class GameStudioGateway extends TypertRemoteService {
376
390
  "fillRatio",
377
391
  "bottomMargin",
378
392
  "cropInset",
393
+ "keyColor",
379
394
  "keyLow",
380
395
  "keyHigh",
381
396
  "despill",
@@ -585,9 +600,22 @@ export class GameStudioGateway extends TypertRemoteService {
585
600
  let project = await readProject(projectId);
586
601
  if (project === undefined)
587
602
  throw new Error(`项目不存在:${projectId}`);
588
- if (lang !== undefined && localizePrompts(project.prompts, lang)) {
603
+ // 底色也是项目级设置:没在项目里显式改过时跟随全局配置。
604
+ const config = await loadConfig();
605
+ const effectiveKeyColor = project.settings.keyColorOverride === true ? project.settings.keyColor : config.keyColor;
606
+ const effectiveChanged = project.settings.keyColor !== effectiveKeyColor;
607
+ if (effectiveChanged)
608
+ project.settings.keyColor = effectiveKeyColor;
609
+ // 读项目时把「仍是默认句式」的提示词同步到它的底色,这样老项目 / 刚改过底色的
610
+ // 项目在界面上看到的就是生成时会用的那一版。
611
+ const colorChanged = applyKeyColorToPrompts(project.prompts, effectiveKeyColor);
612
+ const localized = lang !== undefined ? localizePrompts(project.prompts, lang, effectiveKeyColor) : false;
613
+ if (colorChanged || localized || effectiveChanged) {
589
614
  project = await patchProject(projectId, (draft) => {
590
- localizePrompts(draft.prompts, lang);
615
+ draft.settings.keyColor = effectiveKeyColor;
616
+ applyKeyColorToPrompts(draft.prompts, effectiveKeyColor);
617
+ if (lang !== undefined)
618
+ localizePrompts(draft.prompts, lang, effectiveKeyColor);
591
619
  return draft;
592
620
  });
593
621
  }
@@ -676,7 +704,12 @@ export class GameStudioGateway extends TypertRemoteService {
676
704
  const resetVideo = input.resetVideoToDefault === true;
677
705
  const resetTurn = input.resetTurnToDefault === true;
678
706
  // 「重置为默认」要重置成**当前界面语言**的默认值,否则英文界面点一下会掉出中文提示词。
679
- const defaults = defaultPrompts(normalizePromptLang(input.lang));
707
+ const configured = await loadConfig();
708
+ const projectForColor = await readProject(projectId);
709
+ const effectiveKeyColor = projectForColor?.settings?.keyColorOverride === true
710
+ ? projectForColor.settings.keyColor
711
+ : configured.keyColor;
712
+ const defaults = defaultPrompts(normalizePromptLang(input.lang), effectiveKeyColor);
680
713
  await patchProject(projectId, (project) => {
681
714
  // 提示词模板升级后(例如这次把方位语义改对),老项目要能一键重新套用默认值。
682
715
  if (resetImages)
@@ -714,6 +747,7 @@ export class GameStudioGateway extends TypertRemoteService {
714
747
  const input = asRecord(payload);
715
748
  const projectId = asString(input.projectId);
716
749
  const raw = asRecord(input.settings);
750
+ const config = await loadConfig();
717
751
  const changed = await patchProject(projectId, (project) => {
718
752
  const before = { ...project.settings };
719
753
  const current = project.settings;
@@ -728,6 +762,10 @@ export class GameStudioGateway extends TypertRemoteService {
728
762
  fillRatio: clampFloat(raw.fillRatio, current.fillRatio, 0.5, 1),
729
763
  bottomMargin: clampInt(raw.bottomMargin, current.bottomMargin, 0, 64),
730
764
  cropInset: clampFloat(raw.cropInset, current.cropInset, 0, 0.2),
765
+ keyColor: normalizeKeyColor(raw.keyColor, current.keyColor),
766
+ keyColorOverride: raw.keyColor === undefined
767
+ ? current.keyColorOverride === true
768
+ : normalizeKeyColor(raw.keyColor, current.keyColor) !== config.keyColor,
731
769
  keyLow: clampInt(raw.keyLow, current.keyLow, 0, 255),
732
770
  keyHigh: clampInt(raw.keyHigh, current.keyHigh, 1, 255),
733
771
  despill: clampFloat(raw.despill, current.despill, 0, 1),
@@ -746,6 +784,9 @@ export class GameStudioGateway extends TypertRemoteService {
746
784
  project.settings.rowOrder = [...DEFAULT_ROW_ORDER];
747
785
  if (project.settings.keyHigh <= project.settings.keyLow)
748
786
  project.settings.keyHigh = Math.min(255, project.settings.keyLow + 1);
787
+ // 改底色时,把「还是默认句式」的提示词一起换过去;用户手改过一个字都不动。
788
+ if (before.keyColor !== project.settings.keyColor)
789
+ applyKeyColorToPrompts(project.prompts, project.settings.keyColor);
749
790
  const differs = (fields) => fields.some((field) => JSON.stringify(before[field]) !== JSON.stringify(project.settings[field]));
750
791
  if (differs(["workingLongEdge", "cropInset"])) {
751
792
  // 抽帧参数变了:raw.bin 已经作废,必须重抽,不能只重新合成。
@@ -946,7 +987,10 @@ export class GameStudioGateway extends TypertRemoteService {
946
987
  }
947
988
  async importIsoTileset(payload) {
948
989
  const input = asRecord(payload);
949
- const result = await isogen.importIsoTileset(asString(input.projectId), asString(input.name), asString(input.data), {
990
+ const data = asString(input.path) !== "" ? await readImageBase64FromPath(asString(input.path)) : asString(input.data);
991
+ if (data === "")
992
+ throw new Error("importIsoTileset 需要 data(base64)或 path(本机绝对路径)。");
993
+ const result = await isogen.importIsoTileset(asString(input.projectId), asString(input.name), data, {
950
994
  kind: input.kind,
951
995
  sourceCell: input.sourceCell,
952
996
  animRows: input.animRows,
@@ -958,7 +1002,8 @@ export class GameStudioGateway extends TypertRemoteService {
958
1002
  anchor: input.anchor,
959
1003
  objectScale: input.objectScale,
960
1004
  pass: input.pass,
961
- keyGreen: input.keyGreen
1005
+ keyGreen: input.keyGreen,
1006
+ keyColor: typeof input.keyColor === "string" && input.keyColor.trim() !== "" ? input.keyColor : (await loadConfig()).keyColor
962
1007
  });
963
1008
  const project = await isogen.readIsoProject(asString(input.projectId));
964
1009
  const revisions = await isogen.tilesetRevisions(asString(input.projectId));
@@ -972,13 +1017,15 @@ export class GameStudioGateway extends TypertRemoteService {
972
1017
  }
973
1018
  async composeIsoAsset(payload) {
974
1019
  const input = asRecord(payload);
1020
+ const config = await loadConfig();
975
1021
  return isogen.composeIsoAsset({
976
1022
  projectId: asString(input.projectId),
977
1023
  name: asString(input.name),
978
1024
  files: Array.isArray(input.files) ? input.files.map((file) => asString(file)) : [],
979
1025
  kind: input.kind,
980
1026
  footprint: input.footprint,
981
- keyGreen: input.keyGreen === false ? false : true
1027
+ keyGreen: input.keyGreen === false ? false : true,
1028
+ keyColor: typeof input.keyColor === "string" && input.keyColor.trim() !== "" ? input.keyColor : config.keyColor
982
1029
  });
983
1030
  }
984
1031
  async saveIsoTileset(payload) {
@@ -1013,7 +1060,9 @@ export class GameStudioGateway extends TypertRemoteService {
1013
1060
  const input = asRecord(payload);
1014
1061
  return isogen.applyIsoOps(asString(input.projectId), Array.isArray(input.ops) ? input.ops : [], {
1015
1062
  stroke: typeof input.stroke === "string" ? input.stroke : undefined,
1016
- have: Array.isArray(input.have) ? input.have : undefined
1063
+ have: Array.isArray(input.have) ? input.have : undefined,
1064
+ dryRun: input.dryRun === true,
1065
+ ifRevision: typeof input.ifRevision === "string" ? input.ifRevision : undefined
1017
1066
  });
1018
1067
  }
1019
1068
  async isoUndo(payload) {
@@ -1034,6 +1083,30 @@ export class GameStudioGateway extends TypertRemoteService {
1034
1083
  pass: input.pass === true
1035
1084
  });
1036
1085
  }
1086
+ async isoInspect(payload) {
1087
+ const input = asRecord(payload);
1088
+ return isogen.isoInspect(asString(input.projectId), {
1089
+ region: input.region,
1090
+ layerIds: Array.isArray(input.layerIds) ? input.layerIds.map((entry) => String(entry)) : undefined,
1091
+ include: Array.isArray(input.include) ? input.include.map((entry) => String(entry)) : undefined,
1092
+ format: input.format === "text" || input.format === "json" || input.format === "both" ? input.format : undefined,
1093
+ maxCells: typeof input.maxCells === "number" ? input.maxCells : undefined,
1094
+ maxItems: typeof input.maxItems === "number" ? input.maxItems : undefined
1095
+ });
1096
+ }
1097
+ async isoRender(payload) {
1098
+ const input = asRecord(payload);
1099
+ return isogen.runIsoRender(asString(input.projectId), {
1100
+ region: input.region,
1101
+ scale: typeof input.scale === "number" ? input.scale : undefined,
1102
+ layerIds: Array.isArray(input.layerIds) ? input.layerIds.map((entry) => String(entry)) : undefined,
1103
+ frame: typeof input.frame === "number" ? input.frame : undefined,
1104
+ background: input.background,
1105
+ overlay: input.overlay,
1106
+ maxPixels: typeof input.maxPixels === "number" ? input.maxPixels : undefined,
1107
+ name: typeof input.name === "string" ? input.name : undefined
1108
+ });
1109
+ }
1037
1110
  async runIsoGenerate(payload) {
1038
1111
  const input = asRecord(payload);
1039
1112
  const kind = input.kind === "maze" || input.kind === "continent" ? input.kind : "random";
@@ -1130,7 +1203,10 @@ export class GameStudioGateway extends TypertRemoteService {
1130
1203
  }
1131
1204
  async importMapTileset(payload) {
1132
1205
  const input = asRecord(payload);
1133
- const result = await mapgen.importMapTileset(asString(input.projectId), asString(input.name), asString(input.data), {
1206
+ const data = asString(input.path) !== "" ? await readImageBase64FromPath(asString(input.path)) : asString(input.data);
1207
+ if (data === "")
1208
+ throw new Error("importMapTileset 需要 data(base64)或 path(本机绝对路径)。");
1209
+ const result = await mapgen.importMapTileset(asString(input.projectId), asString(input.name), data, {
1134
1210
  cell: input.cell,
1135
1211
  shape: input.shape,
1136
1212
  animRows: input.animRows,
@@ -1143,8 +1219,9 @@ export class GameStudioGateway extends TypertRemoteService {
1143
1219
  loop: input.loop,
1144
1220
  // 整图规格(给了它就是整图;校验在 mapgen.parseStampSpec 里)。
1145
1221
  stamp: input.stamp,
1146
- // 整图:导入时抠绿幕(手动那条路;AI 那条在 composeMapAsset 里已经抠过)。
1147
- stampKey: input.stampKey
1222
+ // 整图:导入时抠背景(手动那条路;AI 那条在 composeMapAsset 里已经抠过)。
1223
+ stampKey: input.stampKey,
1224
+ keyColor: typeof input.keyColor === "string" && input.keyColor.trim() !== "" ? input.keyColor : (await loadConfig()).keyColor
1148
1225
  });
1149
1226
  // `rev` 不在 project.json 里(派生数据),要在回给界面时现取 —— 少了它重烘后界面会拿旧缓存图。
1150
1227
  const revisions = await mapgen.tilesetRevisions(asString(input.projectId));
@@ -1168,6 +1245,7 @@ export class GameStudioGateway extends TypertRemoteService {
1168
1245
  async composeMapAsset(payload) {
1169
1246
  const input = asRecord(payload);
1170
1247
  const files = Array.isArray(input.files) ? input.files.map((file) => asString(file)) : [];
1248
+ const config = await loadConfig();
1171
1249
  return mapgen.composeMapAsset({
1172
1250
  projectId: asString(input.projectId),
1173
1251
  name: asString(input.name),
@@ -1177,7 +1255,8 @@ export class GameStudioGateway extends TypertRemoteService {
1177
1255
  animRows: input.animRows === true ? true : input.animRows === false ? false : undefined,
1178
1256
  // 整图:占几格(校验在 mapgen.parseStampSpec 里;不给就按 3×3 常见尺寸?不 —— 明确报错)。
1179
1257
  stampCols: input.stampCols,
1180
- stampRows: input.stampRows
1258
+ stampRows: input.stampRows,
1259
+ keyColor: typeof input.keyColor === "string" && input.keyColor.trim() !== "" ? input.keyColor : config.keyColor
1181
1260
  });
1182
1261
  }
1183
1262
  async recomposeMapTileset(payload) {
@@ -1196,7 +1275,9 @@ export class GameStudioGateway extends TypertRemoteService {
1196
1275
  animRows: typeof input.animRows === "boolean" ? input.animRows : undefined,
1197
1276
  // `null` = 清掉自己的速度(跟全局);`undefined` = 这次不动它。
1198
1277
  fps: input.fps === undefined ? undefined : input.fps === null ? null : Number(input.fps),
1199
- loop: input.loop
1278
+ loop: input.loop,
1279
+ // 仅整图:逐格通行区域(长度 / 取值由 mapgen 校验,这里只透传)。
1280
+ stampPass: Array.isArray(input.stampPass) ? input.stampPass : undefined
1200
1281
  });
1201
1282
  return { tileset: mapTilesetBrief(result.tileset), warnings: result.warnings };
1202
1283
  }
@@ -1232,7 +1313,9 @@ export class GameStudioGateway extends TypertRemoteService {
1232
1313
  const input = asRecord(payload);
1233
1314
  return mapgen.applyMapOps(asString(input.projectId), Array.isArray(input.ops) ? input.ops : [], {
1234
1315
  stroke: typeof input.stroke === "string" && input.stroke !== "" ? input.stroke : undefined,
1235
- have: mapHave(input.have)
1316
+ have: mapHave(input.have),
1317
+ dryRun: input.dryRun === true,
1318
+ ifRevision: typeof input.ifRevision === "string" ? input.ifRevision : undefined
1236
1319
  });
1237
1320
  }
1238
1321
  async mapUndo(payload) {
@@ -1254,6 +1337,30 @@ export class GameStudioGateway extends TypertRemoteService {
1254
1337
  pass: input.pass === true
1255
1338
  });
1256
1339
  }
1340
+ async mapInspect(payload) {
1341
+ const input = asRecord(payload);
1342
+ return mapgen.mapInspect(asString(input.projectId), {
1343
+ region: input.region,
1344
+ layerIds: Array.isArray(input.layerIds) ? input.layerIds.map((entry) => String(entry)) : undefined,
1345
+ include: Array.isArray(input.include) ? input.include.map((entry) => String(entry)) : undefined,
1346
+ format: input.format === "text" || input.format === "json" || input.format === "both" ? input.format : undefined,
1347
+ maxCells: typeof input.maxCells === "number" ? input.maxCells : undefined,
1348
+ maxItems: typeof input.maxItems === "number" ? input.maxItems : undefined
1349
+ });
1350
+ }
1351
+ async mapRender(payload) {
1352
+ const input = asRecord(payload);
1353
+ return mapgen.runMapRender(asString(input.projectId), {
1354
+ region: input.region,
1355
+ scale: typeof input.scale === "number" ? input.scale : undefined,
1356
+ layerIds: Array.isArray(input.layerIds) ? input.layerIds.map((entry) => String(entry)) : undefined,
1357
+ frame: typeof input.frame === "number" ? input.frame : undefined,
1358
+ background: input.background,
1359
+ overlay: input.overlay,
1360
+ maxPixels: typeof input.maxPixels === "number" ? input.maxPixels : undefined,
1361
+ name: typeof input.name === "string" ? input.name : undefined
1362
+ });
1363
+ }
1257
1364
  /** 一键生成:整层一次提交(一次撤销就能回去),同种子逐字节可复现。 */
1258
1365
  async runMapGenerate(payload) {
1259
1366
  const input = asRecord(payload);
@@ -1587,8 +1694,8 @@ export class GameStudioGateway extends TypertRemoteService {
1587
1694
  const current = await loadConfig();
1588
1695
  // 生图模型是全局设置(设置 → 游戏素材大师 → 生图后端),任务里不保留可覆盖的副本。
1589
1696
  job.settings.model = imageModelOf(current);
1590
- // 自定义后端的尺寸也是全局参数;火山方舟下才保留任务级覆盖。
1591
- job.settings.size = imageUsesConfiguredSize(current) ? imageSizeOf(current) : asString(raw.size, job.settings.size);
1697
+ // 尺寸是全局设置:任务不再保留会过期的覆盖值(见 imagegen 的同名注释)。
1698
+ job.settings.size = imageSizeOf(current);
1592
1699
  job.settings.count = clampInt(raw.count, job.settings.count, 1, 8);
1593
1700
  job.settings.watermark = raw.watermark === true;
1594
1701
  }
@@ -2574,6 +2681,8 @@ export class GameStudioGateway extends TypertRemoteService {
2574
2681
  * 三个模块共用同一套参数名,所以收敛逻辑也共用。
2575
2682
  */
2576
2683
  function applyKeying(target, raw) {
2684
+ if (typeof raw.keyColor === "string")
2685
+ target.keyColor = normalizeKeyColor(raw.keyColor, target.keyColor || DEFAULT_KEY_COLOR);
2577
2686
  target.keyLow = clampInt(raw.keyLow, target.keyLow, 0, 255);
2578
2687
  target.keyHigh = clampInt(raw.keyHigh, target.keyHigh, 1, 255);
2579
2688
  if (target.keyHigh <= target.keyLow)
package/lib/isocompose.js CHANGED
@@ -15,6 +15,8 @@
15
15
  import { stat } from "node:fs/promises";
16
16
  import { decodeFile } from "./bitmap.js";
17
17
  import { MAX_ASSET_SCALE, keyStampBackground, resampleToSize, STAMP_KEY_OPTIONS } from "./maptiles.js";
18
+ import { isGreenKeyColor, keyScreenName, normalizeKeyColor } from "./keycolor.js";
19
+ import { keyGreen } from "./chroma.js";
18
20
  const MAX_AI_FRAME_BYTES = 64 * 1024 * 1024;
19
21
  const MAX_AI_FRAMES = 64;
20
22
  function clamp(value, min, max) {
@@ -57,7 +59,7 @@ function cropOpaque(source) {
57
59
  return { width, height, rgba };
58
60
  }
59
61
  /** 读一张原图、抠绿、裁到内容边界;返回可直接缩放的帧。 */
60
- async function readFrame(file, keyGreen) {
62
+ async function readFrame(file, keyGreen, keyColor) {
61
63
  let info;
62
64
  try {
63
65
  info = await stat(file);
@@ -81,7 +83,7 @@ async function readFrame(file, keyGreen) {
81
83
  if (keyGreen) {
82
84
  const result = keyStampBackground(bitmap, (rgba, width, height) => {
83
85
  // 与「整图」同一条严格绿幕参数:只认饱和纯绿,避免把草地 / 深色阴影误判成背景。
84
- return keyGreenPixels(rgba, width, height);
86
+ return keyBackgroundPixels(rgba, width, height, keyColor);
85
87
  });
86
88
  bitmap = result.bitmap;
87
89
  keyed = result.keyed;
@@ -92,20 +94,25 @@ async function readFrame(file, keyGreen) {
92
94
  * 严格绿幕(与 maptiles.STAMP_KEY_OPTIONS 同口径)。
93
95
  * 这里单独包一层是为了不把 chroma 的默认参数(适合角色)带进地图素材。
94
96
  */
95
- function keyGreenPixels(rgba, width, height) {
96
- const out = Buffer.from(rgba);
97
- let hit = 0;
98
- for (let i = 0; i < width * height; i++) {
99
- const r = out[i * 4];
100
- const g = out[i * 4 + 1];
101
- const b = out[i * 4 + 2];
102
- const advantage = g - Math.max(r, b);
103
- if (g >= STAMP_KEY_OPTIONS.keyLow && advantage >= STAMP_KEY_OPTIONS.keyHigh) {
104
- out[i * 4 + 3] = 0;
105
- hit++;
97
+ function keyBackgroundPixels(rgba, width, height, keyColor) {
98
+ const color = normalizeKeyColor(keyColor);
99
+ // 绿色保持原来的严格判据(只认饱和纯绿),避免把草地 / 深色阴影误判成背景。
100
+ if (isGreenKeyColor(color)) {
101
+ const out = Buffer.from(rgba);
102
+ let hit = 0;
103
+ for (let i = 0; i < width * height; i++) {
104
+ const r = out[i * 4];
105
+ const g = out[i * 4 + 1];
106
+ const b = out[i * 4 + 2];
107
+ const advantage = g - Math.max(r, b);
108
+ if (g >= STAMP_KEY_OPTIONS.keyLow && advantage >= STAMP_KEY_OPTIONS.keyHigh) {
109
+ out[i * 4 + 3] = 0;
110
+ hit++;
111
+ }
106
112
  }
113
+ return { rgba: out, backgroundFraction: hit / Math.max(1, width * height) };
107
114
  }
108
- return { rgba: out, backgroundFraction: hit / Math.max(1, width * height) };
115
+ return keyGreen(rgba, width, height, { ...STAMP_KEY_OPTIONS, keyColor: color });
109
116
  }
110
117
  /** 把一帧贴进目标格子的菱形框;只保留菱形内部。 */
111
118
  function drawGroundDiamond(source, cell, scale) {
@@ -205,18 +212,20 @@ export async function composeIsoFrames(input) {
205
212
  ? { cols: 1, rows: 1 }
206
213
  : { cols: Math.max(1, Math.round(input.footprint.cols)), rows: Math.max(1, Math.round(input.footprint.rows)) };
207
214
  const keyGreen = input.keyGreen !== false;
215
+ const keyColor = normalizeKeyColor(input.keyColor);
208
216
  const notes = [];
209
217
  const read = [];
210
218
  for (const file of files)
211
- read.push(await readFrame(file, keyGreen));
219
+ read.push(await readFrame(file, keyGreen, keyColor));
212
220
  const keyedValues = read.map((entry) => entry.keyed);
213
221
  const keyedCount = keyedValues.filter((value) => value > 0).length;
214
222
  const keyed = keyedValues.length === 0 ? 0 : keyedValues.reduce((sum, value) => sum + value, 0) / keyedValues.length;
223
+ const screen = keyScreenName(keyColor, "zh");
215
224
  if (keyGreen && keyedCount === 0) {
216
- notes.push("没检测到绿幕背景:这次按原图用了。想要透明背景,让模型把背景画成纯绿(#00FF00 一类,不要渐变 / 阴影)。");
225
+ notes.push(`没检测到${screen}背景:这次按原图用了。想要透明背景,让模型把背景画成纯色 ${keyColor}(不要渐变 / 阴影)。`);
217
226
  }
218
227
  else if (keyedCount > 0) {
219
- notes.push(`已抠掉绿幕背景(平均 ${Math.round(keyed * 100)}% 的像素变成透明)。`);
228
+ notes.push(`已抠掉${screen}背景(平均 ${Math.round(keyed * 100)}% 的像素变成透明)。`);
220
229
  }
221
230
  if (input.kind === "ground") {
222
231
  const first = read[0].bitmap;
package/lib/isodoc.js CHANGED
@@ -147,7 +147,20 @@ function normalizeMarkers(raw, cols, rows) {
147
147
  const given = typeof marker?.id === "string" && marker.id !== "" ? marker.id : "";
148
148
  const id = given !== "" && !used.has(given) ? given : nextId();
149
149
  used.add(id);
150
- out.push({ id, r, c, name: typeof marker?.name === "string" ? marker.name : "" });
150
+ const kind = typeof marker?.kind === "string" && marker.kind.trim() !== "" ? marker.kind.trim() : undefined;
151
+ const color = typeof marker?.color === "string" && /^#[0-9a-f]{6}$/i.test(marker.color.trim()) ? marker.color.trim() : undefined;
152
+ const note = typeof marker?.note === "string" && marker.note !== "" ? marker.note : undefined;
153
+ const tags = Array.isArray(marker?.tags) ? marker.tags.filter((tag) => typeof tag === "string" && tag !== "") : undefined;
154
+ out.push({
155
+ id,
156
+ r,
157
+ c,
158
+ name: typeof marker?.name === "string" ? marker.name : "",
159
+ ...(kind === undefined ? {} : { kind }),
160
+ ...(color === undefined ? {} : { color }),
161
+ ...(note === undefined ? {} : { note }),
162
+ ...(tags === undefined || tags.length === 0 ? {} : { tags })
163
+ });
151
164
  }
152
165
  return out;
153
166
  }
@@ -435,6 +448,41 @@ export function applyIsoOps(doc, ops, layout, options = {}) {
435
448
  redo.push({ kind: "object", op: "move", id: object.id, r: op.r, c: op.c });
436
449
  }
437
450
  };
451
+ const applyObjectDuplicate = (op, recordUndo) => {
452
+ const object = doc.objects.find((entry) => entry.id === op.id);
453
+ if (object === undefined) {
454
+ skipped.push(`没有这个物件:${op.id}`);
455
+ return;
456
+ }
457
+ const fp = footprintOf(object.tilesetId) ?? { cols: 1, rows: 1 };
458
+ if (!footprintInside(layout, op.r, op.c, fp)) {
459
+ skipped.push("物件放不下:占格超出了地图");
460
+ return;
461
+ }
462
+ if (doc.objects.length >= MAX_ISO_OBJECTS) {
463
+ skipped.push(`物件太多了(上限 ${MAX_ISO_OBJECTS} 个)`);
464
+ return;
465
+ }
466
+ const occupied = objectOccupied(doc, layout, footprintOf);
467
+ for (const cell of footprintCells(op.r, op.c, fp)) {
468
+ const wrapped = wrapPoint(layout, cell.r, cell.c);
469
+ if (wrapped === undefined)
470
+ continue;
471
+ if (occupied.has(`${object.layerId}|${wrapped.r},${wrapped.c}`)) {
472
+ skipped.push("目标位置已经有物件了");
473
+ return;
474
+ }
475
+ }
476
+ let id = typeof op.newId === "string" && op.newId !== "" && !doc.objects.some((entry) => entry.id === op.newId) ? op.newId : makeObjectId(doc);
477
+ doc.objects.push({ id, tilesetId: object.tilesetId, layerId: object.layerId, r: op.r, c: op.c });
478
+ for (const cell of footprintCells(op.r, op.c, fp))
479
+ markDirty(changedCells, cell.r, cell.c);
480
+ changed++;
481
+ if (recordUndo) {
482
+ undo.push({ kind: "object", op: "remove", id });
483
+ redo.push({ kind: "object", op: "add", layerId: object.layerId, tilesetId: object.tilesetId, r: op.r, c: op.c, id });
484
+ }
485
+ };
438
486
  const applyObjectRemove = (op, recordUndo) => {
439
487
  const index = doc.objects.findIndex((entry) => entry.id === op.id);
440
488
  if (index < 0) {
@@ -561,6 +609,16 @@ export function applyIsoOps(doc, ops, layout, options = {}) {
561
609
  else if (action === "move") {
562
610
  applyObjectMove({ kind: "object", op: "move", id: String(op.id ?? ""), r: Math.round(Number(op.r)), c: Math.round(Number(op.c)) }, true);
563
611
  }
612
+ else if (action === "duplicate") {
613
+ applyObjectDuplicate({
614
+ kind: "object",
615
+ op: "duplicate",
616
+ id: String(op.id ?? ""),
617
+ r: Math.round(Number(op.r)),
618
+ c: Math.round(Number(op.c)),
619
+ newId: typeof op.newId === "string" ? op.newId : undefined
620
+ }, true);
621
+ }
564
622
  else if (action === "remove") {
565
623
  applyObjectRemove({ kind: "object", op: "remove", id: String(op.id ?? "") }, true);
566
624
  }
@@ -571,6 +629,19 @@ export function applyIsoOps(doc, ops, layout, options = {}) {
571
629
  }
572
630
  if (kind === "marker") {
573
631
  const action = op.op;
632
+ const meta = (input, includeKind = true) => {
633
+ const rawKind = input.markerKind !== undefined ? input.markerKind : includeKind ? input.kind : undefined;
634
+ const kindValue = typeof rawKind === "string" && rawKind.trim() !== "" ? rawKind.trim() : undefined;
635
+ const color = typeof input.color === "string" && /^#[0-9a-f]{6}$/i.test(input.color.trim()) ? input.color.trim() : undefined;
636
+ const note = typeof input.note === "string" && input.note !== "" ? input.note : undefined;
637
+ const tags = Array.isArray(input.tags) ? input.tags.filter((tag) => typeof tag === "string" && tag !== "") : undefined;
638
+ return {
639
+ ...(kindValue === undefined ? {} : { kind: kindValue }),
640
+ ...(color === undefined ? {} : { color }),
641
+ ...(note === undefined ? {} : { note }),
642
+ ...(tags === undefined || tags.length === 0 ? {} : { tags })
643
+ };
644
+ };
574
645
  if (action === "add") {
575
646
  const hit = wrapPoint(layout, Math.round(Number(op.r)), Math.round(Number(op.c)));
576
647
  if (hit === undefined) {
@@ -583,12 +654,24 @@ export function applyIsoOps(doc, ops, layout, options = {}) {
583
654
  }
584
655
  const id = typeof op.id === "string" && op.id !== "" && !doc.markers.some((marker) => marker.id === op.id) ? op.id : makeMarkerId(doc);
585
656
  const name = typeof op.name === "string" ? op.name : "";
586
- doc.markers.push({ id, r: hit.r, c: hit.c, name });
657
+ doc.markers.push({ id, r: hit.r, c: hit.c, name, ...meta(op, false) });
587
658
  markDirty(changedCells, hit.r, hit.c);
588
659
  changed++;
589
660
  touched = true;
590
661
  undo.push({ kind: "marker", op: "remove", id });
591
- redo.push({ kind: "marker", op: "add", r: hit.r, c: hit.c, name, id });
662
+ const added = meta(op, false);
663
+ redo.push({
664
+ kind: "marker",
665
+ op: "add",
666
+ r: hit.r,
667
+ c: hit.c,
668
+ name,
669
+ id,
670
+ ...(added.kind === undefined ? {} : { markerKind: added.kind }),
671
+ ...(added.color === undefined ? {} : { color: added.color }),
672
+ ...(added.note === undefined ? {} : { note: added.note }),
673
+ ...(added.tags === undefined ? {} : { tags: added.tags })
674
+ });
592
675
  continue;
593
676
  }
594
677
  if (action === "remove") {
@@ -604,7 +687,19 @@ export function applyIsoOps(doc, ops, layout, options = {}) {
604
687
  markDirty(changedCells, marker.r, marker.c);
605
688
  changed++;
606
689
  touched = true;
607
- undo.push({ kind: "marker", op: "add", r: marker.r, c: marker.c, name: marker.name, id: marker.id });
690
+ const saved = meta(marker);
691
+ undo.push({
692
+ kind: "marker",
693
+ op: "add",
694
+ r: marker.r,
695
+ c: marker.c,
696
+ name: marker.name,
697
+ id: marker.id,
698
+ ...(saved.kind === undefined ? {} : { markerKind: saved.kind }),
699
+ ...(saved.color === undefined ? {} : { color: saved.color }),
700
+ ...(saved.note === undefined ? {} : { note: saved.note }),
701
+ ...(saved.tags === undefined ? {} : { tags: saved.tags })
702
+ });
608
703
  redo.push({ kind: "marker", op: "remove", id: marker.id });
609
704
  continue;
610
705
  }
@@ -634,6 +729,60 @@ export function applyIsoOps(doc, ops, layout, options = {}) {
634
729
  redo.push({ kind: "marker", op: "move", id: marker.id, r: hit.r, c: hit.c });
635
730
  continue;
636
731
  }
732
+ if (action === "update") {
733
+ const marker = doc.markers.find((entry) => entry.id === op.id);
734
+ if (marker === undefined) {
735
+ skipped.push(`没有这个标记:${String(op.id)}`);
736
+ continue;
737
+ }
738
+ const updateOp = op;
739
+ const patch = updateOp.patch ?? {};
740
+ const before = { ...marker };
741
+ if (typeof patch.name === "string")
742
+ marker.name = patch.name;
743
+ if (patch.kind !== undefined) {
744
+ if (patch.kind.trim() === "")
745
+ delete marker.kind;
746
+ else
747
+ marker.kind = patch.kind.trim();
748
+ }
749
+ if (patch.color !== undefined) {
750
+ if (patch.color.trim() === "")
751
+ delete marker.color;
752
+ else if (/^#[0-9a-f]{6}$/i.test(patch.color.trim()))
753
+ marker.color = patch.color.trim();
754
+ }
755
+ if (patch.note !== undefined) {
756
+ if (patch.note === "")
757
+ delete marker.note;
758
+ else
759
+ marker.note = patch.note;
760
+ }
761
+ if (patch.tags !== undefined) {
762
+ const tags = patch.tags.filter((tag) => typeof tag === "string" && tag !== "");
763
+ if (tags.length === 0)
764
+ delete marker.tags;
765
+ else
766
+ marker.tags = tags;
767
+ }
768
+ if (JSON.stringify(before) === JSON.stringify(marker))
769
+ continue;
770
+ touched = true;
771
+ undo.push({
772
+ kind: "marker",
773
+ op: "update",
774
+ id: marker.id,
775
+ patch: {
776
+ name: before.name,
777
+ kind: before.kind ?? "",
778
+ color: before.color ?? "",
779
+ note: before.note ?? "",
780
+ tags: before.tags ?? []
781
+ }
782
+ });
783
+ redo.push({ kind: "marker", op: "update", id: marker.id, patch });
784
+ continue;
785
+ }
637
786
  if (action === "rename") {
638
787
  const marker = doc.markers.find((entry) => entry.id === op.id);
639
788
  if (marker === undefined) {
package/lib/isoexport.js CHANGED
@@ -16,11 +16,14 @@ import { buildIsoPlan, isoBitmapToPng, passCellsOf, planBounds, rasterizeIso } f
16
16
  import { safeFileName } from "./mapexport.js";
17
17
  import { zipEntries } from "./zip.js";
18
18
  export const OWN_ISO_JSON_FORMAT = "dsh-gem-iso-map@1";
19
+ /** 带标记语义字段时使用;没有新字段的老文档仍然写 @1。 */
20
+ export const OWN_ISO_JSON_FORMAT_META = "dsh-gem-iso-map@2";
19
21
  /** `dsh-gem-iso-map@1` 的内容。 */
20
22
  export function buildIsoJson(context, doc, project) {
21
23
  const legend = buildIsoPlan(context, doc, { includeLegend: true }).legend;
24
+ const hasMarkerMeta = doc.markers.some((marker) => marker.kind !== undefined || marker.color !== undefined || marker.note !== undefined || marker.tags !== undefined);
22
25
  return {
23
- format: OWN_ISO_JSON_FORMAT,
26
+ format: hasMarkerMeta ? OWN_ISO_JSON_FORMAT_META : OWN_ISO_JSON_FORMAT,
24
27
  projection: "isometric-2:1",
25
28
  cell: { width: context.cell.width, height: context.cell.height },
26
29
  grid: { stepX: context.layout.stepX, stepY: context.layout.stepY, wrap: context.layout.wrap },
@@ -48,7 +51,16 @@ export function buildIsoJson(context, doc, project) {
48
51
  .filter((layer) => layer.kind === "ground")
49
52
  .map((layer) => ({ layerId: layer.id, data: doc.data[layer.id] ?? [] })),
50
53
  objects: doc.objects.map((object) => ({ id: object.id, layerId: object.layerId, tilesetId: object.tilesetId, r: object.r, c: object.c })),
51
- markers: doc.markers.map((marker, index) => ({ n: index + 1, name: marker.name, r: marker.r, c: marker.c })),
54
+ markers: doc.markers.map((marker, index) => ({
55
+ n: index + 1,
56
+ name: marker.name,
57
+ r: marker.r,
58
+ c: marker.c,
59
+ ...(marker.kind === undefined ? {} : { kind: marker.kind }),
60
+ ...(marker.color === undefined ? {} : { color: marker.color }),
61
+ ...(marker.note === undefined ? {} : { note: marker.note }),
62
+ ...(marker.tags === undefined ? {} : { tags: marker.tags })
63
+ })),
52
64
  pass: passCellsOf(context, doc)
53
65
  };
54
66
  }