dsh-game-material-master 0.9.2 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,256 @@
1
+ /**
2
+ * 45° 地图编辑器「AI 生成素材」的**像素整理**:把模型吐出来的原图整理成
3
+ * 可直接交给 `importIsoTileset` 的素材图。
4
+ *
5
+ * 这一层只做几何 / 像素,不碰磁盘上的项目文件;`isogen.composeIsoAsset` 负责
6
+ * 落盘到 `ai/`、写日志与返回回链信息。
7
+ *
8
+ * 首版只支持两种:
9
+ * · `ground`:一块 2:1 菱形地面;多帧竖排成动画地面;
10
+ * · `object`:一张完整物件图(多帧竖排),纯绿幕背景,按 footprint 占格。
11
+ *
12
+ * `autotile`(4×4 = 16 种接法)不在这里做:单张 AI 图无法可靠推导 16 种接法,
13
+ * 继续走手工导入。
14
+ */
15
+ import { stat } from "node:fs/promises";
16
+ import { decodeFile } from "./bitmap.js";
17
+ import { MAX_ASSET_SCALE, keyStampBackground, resampleToSize, STAMP_KEY_OPTIONS } from "./maptiles.js";
18
+ const MAX_AI_FRAME_BYTES = 64 * 1024 * 1024;
19
+ const MAX_AI_FRAMES = 64;
20
+ function clamp(value, min, max) {
21
+ return Math.max(min, Math.min(max, value));
22
+ }
23
+ function messageOf(error) {
24
+ return error instanceof Error ? error.message : String(error);
25
+ }
26
+ /** 按 alpha 裁到真正有内容的包围盒(绿幕 / 透明背景都能用)。 */
27
+ function cropOpaque(source) {
28
+ let left = source.width;
29
+ let top = source.height;
30
+ let right = -1;
31
+ let bottom = -1;
32
+ for (let y = 0; y < source.height; y++) {
33
+ for (let x = 0; x < source.width; x++) {
34
+ if (source.rgba[(y * source.width + x) * 4 + 3] < 8)
35
+ continue;
36
+ if (x < left)
37
+ left = x;
38
+ if (y < top)
39
+ top = y;
40
+ if (x > right)
41
+ right = x;
42
+ if (y > bottom)
43
+ bottom = y;
44
+ }
45
+ }
46
+ if (right < left || bottom < top)
47
+ throw new Error("整理后的素材是空白的(整张图都透明)。");
48
+ const width = right - left + 1;
49
+ const height = bottom - top + 1;
50
+ if (width === source.width && height === source.height)
51
+ return source;
52
+ const rgba = Buffer.alloc(width * height * 4);
53
+ for (let y = 0; y < height; y++) {
54
+ const from = ((top + y) * source.width + left) * 4;
55
+ source.rgba.copy(rgba, y * width * 4, from, from + width * 4);
56
+ }
57
+ return { width, height, rgba };
58
+ }
59
+ /** 读一张原图、抠绿、裁到内容边界;返回可直接缩放的帧。 */
60
+ async function readFrame(file, keyGreen) {
61
+ let info;
62
+ try {
63
+ info = await stat(file);
64
+ }
65
+ catch {
66
+ throw new Error(`读不到帧文件:${file}`);
67
+ }
68
+ if (!info.isFile())
69
+ throw new Error(`不是文件:${file}`);
70
+ if (info.size > MAX_AI_FRAME_BYTES) {
71
+ throw new Error(`帧文件 ${(info.size / 1024 / 1024).toFixed(1)}MB 超过上限 ${MAX_AI_FRAME_BYTES / 1024 / 1024}MB:${file}`);
72
+ }
73
+ let bitmap;
74
+ try {
75
+ bitmap = await decodeFile(file);
76
+ }
77
+ catch (error) {
78
+ throw new Error(`读不出帧文件 ${file}:${messageOf(error)}`);
79
+ }
80
+ let keyed = 0;
81
+ if (keyGreen) {
82
+ const result = keyStampBackground(bitmap, (rgba, width, height) => {
83
+ // 与「整图」同一条严格绿幕参数:只认饱和纯绿,避免把草地 / 深色阴影误判成背景。
84
+ return keyGreenPixels(rgba, width, height);
85
+ });
86
+ bitmap = result.bitmap;
87
+ keyed = result.keyed;
88
+ }
89
+ return { bitmap: cropOpaque(bitmap), keyed };
90
+ }
91
+ /**
92
+ * 严格绿幕(与 maptiles.STAMP_KEY_OPTIONS 同口径)。
93
+ * 这里单独包一层是为了不把 chroma 的默认参数(适合角色)带进地图素材。
94
+ */
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++;
106
+ }
107
+ }
108
+ return { rgba: out, backgroundFraction: hit / Math.max(1, width * height) };
109
+ }
110
+ /** 把一帧贴进目标格子的菱形框;只保留菱形内部。 */
111
+ function drawGroundDiamond(source, cell, scale) {
112
+ const width = Math.max(1, cell.width * scale);
113
+ const height = Math.max(1, cell.height * scale);
114
+ const diamondWidth = width;
115
+ const diamondHeight = Math.max(2, Math.round(width / 2));
116
+ const fitted = resampleToSize(source, diamondWidth, diamondHeight, "smooth");
117
+ const out = { width, height, rgba: Buffer.alloc(width * height * 4) };
118
+ const cx = width / 2;
119
+ const cy = height / 2;
120
+ const halfW = diamondWidth / 2;
121
+ const halfH = diamondHeight / 2;
122
+ const originY = Math.round((height - diamondHeight) / 2);
123
+ const border = averageEdgeColor(fitted);
124
+ const band = Math.max(1, Math.round(diamondWidth * 0.018));
125
+ for (let y = 0; y < diamondHeight; y++) {
126
+ for (let x = 0; x < diamondWidth; x++) {
127
+ const d = Math.abs(x + 0.5 - diamondWidth / 2) / halfW + Math.abs(y + 0.5 - diamondHeight / 2) / halfH;
128
+ // 多铺一点点:相邻菱形共享的那条边必须两边都盖到,否则会留透明缝。
129
+ if (d > 1.008)
130
+ continue;
131
+ const si = (y * diamondWidth + x) * 4;
132
+ if (fitted.rgba[si + 3] === 0)
133
+ continue;
134
+ const tx = x;
135
+ const ty = originY + y;
136
+ const di = (ty * width + tx) * 4;
137
+ const edgeStart = 1 - band / Math.max(1, Math.min(halfW, halfH));
138
+ const t = d <= edgeStart ? 0 : clamp((d - edgeStart) / Math.max(0.0001, 1 - edgeStart), 0, 1);
139
+ // 外圈向该帧的边缘平均色收敛:同一张素材重复铺时,相邻边颜色一致。
140
+ const mix = t * 0.85;
141
+ out.rgba[di] = Math.round(fitted.rgba[si] * (1 - mix) + border.r * mix);
142
+ out.rgba[di + 1] = Math.round(fitted.rgba[si + 1] * (1 - mix) + border.g * mix);
143
+ out.rgba[di + 2] = Math.round(fitted.rgba[si + 2] * (1 - mix) + border.b * mix);
144
+ out.rgba[di + 3] = 255;
145
+ }
146
+ }
147
+ return out;
148
+ }
149
+ /** 取菱形最外圈不透明像素的平均色,作为边缘收敛的目标色。 */
150
+ function averageEdgeColor(source) {
151
+ const halfW = source.width / 2;
152
+ const halfH = source.height / 2;
153
+ let r = 0;
154
+ let g = 0;
155
+ let b = 0;
156
+ let n = 0;
157
+ for (let y = 0; y < source.height; y++) {
158
+ for (let x = 0; x < source.width; x++) {
159
+ const d = Math.abs(x + 0.5 - halfW) / Math.max(1, halfW) + Math.abs(y + 0.5 - halfH) / Math.max(1, halfH);
160
+ if (d < 0.82 || d > 1.01)
161
+ continue;
162
+ const i = (y * source.width + x) * 4;
163
+ if (source.rgba[i + 3] === 0)
164
+ continue;
165
+ r += source.rgba[i];
166
+ g += source.rgba[i + 1];
167
+ b += source.rgba[i + 2];
168
+ n++;
169
+ }
170
+ }
171
+ if (n === 0)
172
+ return { r: 128, g: 128, b: 128 };
173
+ return { r: r / n, g: g / n, b: b / n };
174
+ }
175
+ /** 把一帧贴进物件图;保持第一帧的比例,所有帧共用同一尺寸。 */
176
+ function objectFrame(source, targetWidth, targetHeight) {
177
+ return resampleToSize(source, targetWidth, targetHeight, "smooth");
178
+ }
179
+ /** 竖向拼帧。 */
180
+ function stackFrames(frames) {
181
+ if (frames.length === 0)
182
+ throw new Error("没有可整理的帧。");
183
+ const width = frames[0].width;
184
+ const height = frames[0].height;
185
+ const out = { width, height: height * frames.length, rgba: Buffer.alloc(width * height * frames.length * 4) };
186
+ for (let index = 0; index < frames.length; index++) {
187
+ const frame = frames[index];
188
+ if (frame.width !== width || frame.height !== height)
189
+ throw new Error("各帧尺寸不一致,无法竖排。");
190
+ frame.rgba.copy(out.rgba, index * width * height * 4);
191
+ }
192
+ return out;
193
+ }
194
+ export async function composeIsoFrames(input) {
195
+ const files = (input.files ?? []).map((file) => String(file));
196
+ if (files.length === 0)
197
+ throw new Error("没有可整理的帧:files 不能为空。");
198
+ if (files.length > MAX_AI_FRAMES)
199
+ throw new Error(`一份素材最多 ${MAX_AI_FRAMES} 张图,收到 ${files.length} 张。`);
200
+ if (input.kind !== "ground" && input.kind !== "object") {
201
+ throw new Error(`AI 生成素材目前只支持 ground / object(收到 ${String(input.kind)})。自动连接 4×4 请手工导入。`);
202
+ }
203
+ const cell = { width: Math.max(1, Math.round(input.cell.width)), height: Math.max(1, Math.round(input.cell.height)) };
204
+ const footprint = input.footprint === undefined
205
+ ? { cols: 1, rows: 1 }
206
+ : { cols: Math.max(1, Math.round(input.footprint.cols)), rows: Math.max(1, Math.round(input.footprint.rows)) };
207
+ const keyGreen = input.keyGreen !== false;
208
+ const notes = [];
209
+ const read = [];
210
+ for (const file of files)
211
+ read.push(await readFrame(file, keyGreen));
212
+ const keyedValues = read.map((entry) => entry.keyed);
213
+ const keyedCount = keyedValues.filter((value) => value > 0).length;
214
+ const keyed = keyedValues.length === 0 ? 0 : keyedValues.reduce((sum, value) => sum + value, 0) / keyedValues.length;
215
+ if (keyGreen && keyedCount === 0) {
216
+ notes.push("没检测到绿幕背景:这次按原图用了。想要透明背景,让模型把背景画成纯绿(#00FF00 一类,不要渐变 / 阴影)。");
217
+ }
218
+ else if (keyedCount > 0) {
219
+ notes.push(`已抠掉绿幕背景(平均 ${Math.round(keyed * 100)}% 的像素变成透明)。`);
220
+ }
221
+ if (input.kind === "ground") {
222
+ const first = read[0].bitmap;
223
+ const ratio = first.width / Math.max(1, first.height);
224
+ if (Math.abs(Math.log(ratio / 2)) > Math.log(1.35)) {
225
+ notes.push(`这张图的宽高比是 ${ratio.toFixed(2)},不是 2:1 的等距菱形:已经缩放成菱形,内容会有一点压扁 / 拉长。下次在提示词里要求「严格 2:1 菱形」。`);
226
+ }
227
+ const scale = clamp(Math.floor(first.width / Math.max(1, cell.width)), 1, MAX_ASSET_SCALE);
228
+ const frames = read.map((entry) => drawGroundDiamond(entry.bitmap, cell, scale));
229
+ return {
230
+ bitmap: stackFrames(frames),
231
+ frameCount: frames.length,
232
+ frameHeight: cell.height * scale,
233
+ scale,
234
+ keyed,
235
+ notes
236
+ };
237
+ }
238
+ const first = read[0].bitmap;
239
+ const scale = clamp(Math.round(first.width / Math.max(1, footprint.cols * cell.width)), 1, MAX_ASSET_SCALE);
240
+ const targetWidth = Math.max(1, footprint.cols * cell.width * scale);
241
+ const targetHeight = Math.max(1, Math.round((first.height * targetWidth) / Math.max(1, first.width)));
242
+ const frames = read.map((entry) => {
243
+ if (Math.abs(entry.bitmap.width / Math.max(1, entry.bitmap.height) - first.width / Math.max(1, first.height)) > 0.05) {
244
+ notes.push("各帧的宽高比不一致:已经统一到第一帧的尺寸,画面可能略有拉伸。");
245
+ }
246
+ return objectFrame(entry.bitmap, targetWidth, targetHeight);
247
+ });
248
+ return {
249
+ bitmap: stackFrames(frames),
250
+ frameCount: frames.length,
251
+ frameHeight: targetHeight,
252
+ scale,
253
+ keyed,
254
+ notes
255
+ };
256
+ }