dsh-game-material-master 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +104 -0
- package/cordis.patch.yml +6 -0
- package/lib/ark.js +128 -0
- package/lib/chroma.js +466 -0
- package/lib/client.js +5106 -0
- package/lib/config.js +252 -0
- package/lib/directions.js +141 -0
- package/lib/imagegen.js +388 -0
- package/lib/index.js +1602 -0
- package/lib/jsonio.js +38 -0
- package/lib/links.js +125 -0
- package/lib/media.js +235 -0
- package/lib/minimax.js +390 -0
- package/lib/pipeline.js +650 -0
- package/lib/png.js +57 -0
- package/lib/rigexport.js +391 -0
- package/lib/riggen.js +3639 -0
- package/lib/rigmesh.js +167 -0
- package/lib/rigpath.js +125 -0
- package/lib/rigpose.js +1872 -0
- package/lib/rigpreview.js +816 -0
- package/lib/rigqa.js +271 -0
- package/lib/rigsemantics.js +411 -0
- package/lib/rigvalidate.js +802 -0
- package/lib/seqgen.js +686 -0
- package/lib/spine.js +1392 -0
- package/lib/store.js +309 -0
- package/lib/tools.js +1365 -0
- package/lib/wire.js +535 -0
- package/package.json +49 -0
package/lib/rigpose.js
ADDED
|
@@ -0,0 +1,1872 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 骨骼动画的「看图」层:拆件分割、装配定位、遮挡排序、合成与图集。
|
|
3
|
+
*
|
|
4
|
+
* 参考项目用 Python + OpenCV 做这几件事(SIFT+RANSAC 定位、连通域分割、
|
|
5
|
+
* 遮挡投票排 z 序)。本插件不引任何原生依赖,所以这里用纯 TypeScript 重做,
|
|
6
|
+
* 并且刻意选择**不依赖 SIFT** 的路线:
|
|
7
|
+
*
|
|
8
|
+
* - 定位主力是「多尺度掩码模板匹配 + 金字塔由粗到细搜索」。参考项目里
|
|
9
|
+
* 它本来是 SIFT 失败时的兜底(`template_match_fallback`,用 alpha 掩码
|
|
10
|
+
* 的归一化相关 + 前景惩罚),但在**生图模型重新绘制过的**部件上,
|
|
11
|
+
* 它比稀疏特征匹配更稳:色块、线条、渐变都能提供相关性,不需要角点。
|
|
12
|
+
* - 打分用零均值归一化互相关(ZNCC),天然免疫整体明暗差异。
|
|
13
|
+
* - 排序仍按参考项目的思路做**逐对遮挡投票**:重叠区域里,谁的像素更接近
|
|
14
|
+
* 参考图,谁就压在别人上面。
|
|
15
|
+
*
|
|
16
|
+
* 所有函数都是纯函数(输入 RGBA Buffer,输出 RGBA Buffer / 数字),
|
|
17
|
+
* 不碰文件系统,方便脚本直接做验证。
|
|
18
|
+
*/
|
|
19
|
+
/** 这些参数是否等价于「什么都不做」——用来跳过整趟像素循环。 */
|
|
20
|
+
export function isIdentityTint(options) {
|
|
21
|
+
const close = (value, target) => Math.abs((value ?? target) - target) < 1e-6;
|
|
22
|
+
const [r, g, b] = options.rgb ?? [0, 0, 0];
|
|
23
|
+
return (close(options.hue, 0) &&
|
|
24
|
+
close(options.saturation, 1) &&
|
|
25
|
+
close(options.lightness, 0) &&
|
|
26
|
+
close(options.brightness, 0) &&
|
|
27
|
+
close(options.contrast, 1) &&
|
|
28
|
+
Math.abs(r) < 1e-6 &&
|
|
29
|
+
Math.abs(g) < 1e-6 &&
|
|
30
|
+
Math.abs(b) < 1e-6);
|
|
31
|
+
}
|
|
32
|
+
function clamp255(value) {
|
|
33
|
+
return value < 0 ? 0 : value > 255 ? 255 : Math.round(value);
|
|
34
|
+
}
|
|
35
|
+
/** RGB(0~1) → HSL(0~1)。 */
|
|
36
|
+
function rgbToHsl(r, g, b) {
|
|
37
|
+
const max = Math.max(r, g, b);
|
|
38
|
+
const min = Math.min(r, g, b);
|
|
39
|
+
const l = (max + min) / 2;
|
|
40
|
+
if (max === min)
|
|
41
|
+
return [0, 0, l];
|
|
42
|
+
const d = max - min;
|
|
43
|
+
const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
|
44
|
+
let h;
|
|
45
|
+
if (max === r)
|
|
46
|
+
h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
|
|
47
|
+
else if (max === g)
|
|
48
|
+
h = ((b - r) / d + 2) / 6;
|
|
49
|
+
else
|
|
50
|
+
h = ((r - g) / d + 4) / 6;
|
|
51
|
+
return [h, s, l];
|
|
52
|
+
}
|
|
53
|
+
function hue2rgb(p, q, t) {
|
|
54
|
+
let value = t;
|
|
55
|
+
if (value < 0)
|
|
56
|
+
value += 1;
|
|
57
|
+
if (value > 1)
|
|
58
|
+
value -= 1;
|
|
59
|
+
if (value < 1 / 6)
|
|
60
|
+
return p + (q - p) * 6 * value;
|
|
61
|
+
if (value < 1 / 2)
|
|
62
|
+
return q;
|
|
63
|
+
if (value < 2 / 3)
|
|
64
|
+
return p + (q - p) * (2 / 3 - value) * 6;
|
|
65
|
+
return p;
|
|
66
|
+
}
|
|
67
|
+
/** HSL(0~1) → RGB(0~1)。 */
|
|
68
|
+
function hslToRgb(h, s, l) {
|
|
69
|
+
if (s === 0)
|
|
70
|
+
return [l, l, l];
|
|
71
|
+
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
|
72
|
+
const p = 2 * l - q;
|
|
73
|
+
return [hue2rgb(p, q, h + 1 / 3), hue2rgb(p, q, h), hue2rgb(p, q, h - 1 / 3)];
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* 对一个部件贴图换色,返回**新图**(不改原图)。
|
|
77
|
+
*
|
|
78
|
+
* 全透明的像素直接跳过:换色不该把「没有像素」变成「有一点像素」,
|
|
79
|
+
* 而且边缘像素的 RGB 在透明处往往是无意义的残留值,动它反而会污染抗锯齿。
|
|
80
|
+
*
|
|
81
|
+
* 顺序与参考项目一致:先 HSL(色相/饱和/明度),再 RGB 域的对比度/亮度/RGB 平衡。
|
|
82
|
+
* 注意这是**逐像素循环**——部件尺寸在几百像素量级(几十万像素),
|
|
83
|
+
* 单张几十毫秒;这也是为什么换色走「生成一个新版本」而不是每次渲染时实时算。
|
|
84
|
+
*/
|
|
85
|
+
export function tintRgba(src, options) {
|
|
86
|
+
const out = Buffer.from(src.data);
|
|
87
|
+
if (isIdentityTint(options))
|
|
88
|
+
return { data: out, width: src.width, height: src.height };
|
|
89
|
+
const hueShift = (options.hue ?? 0) / 360;
|
|
90
|
+
const satMul = options.saturation ?? 1;
|
|
91
|
+
const lightAdd = options.lightness ?? 0;
|
|
92
|
+
const brightness = options.brightness ?? 0;
|
|
93
|
+
const contrast = options.contrast ?? 1;
|
|
94
|
+
const [balanceR, balanceG, balanceB] = options.rgb ?? [0, 0, 0];
|
|
95
|
+
for (let i = 0; i < src.width * src.height; i++) {
|
|
96
|
+
const at = i * 4;
|
|
97
|
+
if (src.data[at + 3] === 0)
|
|
98
|
+
continue;
|
|
99
|
+
let [h, s, l] = rgbToHsl(src.data[at] / 255, src.data[at + 1] / 255, src.data[at + 2] / 255);
|
|
100
|
+
h = (h + hueShift + 1) % 1;
|
|
101
|
+
s = Math.min(1, Math.max(0, s * satMul));
|
|
102
|
+
l = Math.min(1, Math.max(0, l + lightAdd));
|
|
103
|
+
let [r, g, b] = hslToRgb(h, s, l);
|
|
104
|
+
// 对比度绕 0.5 缩放,再叠亮度与 RGB 平衡。
|
|
105
|
+
r = (r - 0.5) * contrast + 0.5 + brightness + balanceR;
|
|
106
|
+
g = (g - 0.5) * contrast + 0.5 + brightness + balanceG;
|
|
107
|
+
b = (b - 0.5) * contrast + 0.5 + brightness + balanceB;
|
|
108
|
+
out[at] = clamp255(r * 255);
|
|
109
|
+
out[at + 1] = clamp255(g * 255);
|
|
110
|
+
out[at + 2] = clamp255(b * 255);
|
|
111
|
+
// alpha 原样保留:换色不改变轮廓。
|
|
112
|
+
}
|
|
113
|
+
return { data: out, width: src.width, height: src.height };
|
|
114
|
+
}
|
|
115
|
+
// ── 逐部件重绘的两个基础操作 ────────────────────────────────────────────
|
|
116
|
+
/**
|
|
117
|
+
* 把一张图**居中放进正方形画布**,并返回裁回来所需的信息。
|
|
118
|
+
*
|
|
119
|
+
* 为什么需要它:生图模型会按自己的画幅习惯重排画面(reskin-app 的
|
|
120
|
+
* `_pad_to_aspect_ratio` 就是为这件事写的——「把『生成模型会改画幅』消灭在
|
|
121
|
+
* 进入流水线之前」)。部件图往往是细长的(胳膊、腿),直接丢给模型极易被重新
|
|
122
|
+
* 构图。先补成正方、让模型在正方里画,再按同样的正方裁回来,最后缩回原尺寸,
|
|
123
|
+
* 位置关系就稳定了。
|
|
124
|
+
*/
|
|
125
|
+
export function padToSquare(src, background = [255, 255, 255]) {
|
|
126
|
+
const size = Math.max(src.width, src.height);
|
|
127
|
+
const image = createRgba(size, size, [background[0], background[1], background[2], 255]);
|
|
128
|
+
const padX = Math.floor((size - src.width) / 2);
|
|
129
|
+
const padY = Math.floor((size - src.height) / 2);
|
|
130
|
+
for (let y = 0; y < src.height; y++) {
|
|
131
|
+
for (let x = 0; x < src.width; x++) {
|
|
132
|
+
const from = (y * src.width + x) * 4;
|
|
133
|
+
const alpha = src.data[from + 3];
|
|
134
|
+
if (alpha === 0)
|
|
135
|
+
continue;
|
|
136
|
+
const to = ((y + padY) * size + (x + padX)) * 4;
|
|
137
|
+
image.data[to] = src.data[from];
|
|
138
|
+
image.data[to + 1] = src.data[from + 1];
|
|
139
|
+
image.data[to + 2] = src.data[from + 2];
|
|
140
|
+
image.data[to + 3] = alpha;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return { image, padX, padY, size };
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* 按给定的 alpha 掩码裁剪 + 缩放回目标尺寸。
|
|
147
|
+
*
|
|
148
|
+
* 这是「AI 重绘」闭环的最后一步:模型交回来的图**尺寸与构图都不可信**,
|
|
149
|
+
* 所以先按正方形裁回来、缩回原尺寸,再用原图的 alpha 当掩码——
|
|
150
|
+
* **轮廓保持原样**,模型画出来的任何背景都被切掉。
|
|
151
|
+
*
|
|
152
|
+
* 这对本插件尤其重要:装配框与骨骼锚点都绑定在原来的轮廓上,
|
|
153
|
+
* 轮廓一变,摆好的位置就全错了。
|
|
154
|
+
*
|
|
155
|
+
* ⚠️ **`crop` 的坐标是「补边后正方形」的坐标系**(例如 216×216),而模型返回的
|
|
156
|
+
* 图往往完全是另一个尺寸(Seedream 固定给 2048×2048)。所以这里必须**先把结果
|
|
157
|
+
* 缩放到正方形尺寸再裁**——不缩放就直接按 `padX/padY` 取样,读到的只是大图左上角
|
|
158
|
+
* 一小块平坦区域,表现是「模型明明画对了,我们却拿到一片纯色」。
|
|
159
|
+
* 这个坑很隐蔽:失败症状看起来像模型不行,实际是自己的坐标错了。
|
|
160
|
+
*/
|
|
161
|
+
export function maskAndFit(src, mask, crop, targetWidth, targetHeight) {
|
|
162
|
+
// ⓪ 先把模型输出对齐到补边正方形的尺寸。
|
|
163
|
+
const square = src.width === crop.size && src.height === crop.size
|
|
164
|
+
? src
|
|
165
|
+
: resizeRgba(src, Math.max(1, crop.size), Math.max(1, crop.size));
|
|
166
|
+
// ① 从正方形里裁掉补边,得到与原图同构的矩形。
|
|
167
|
+
const rect = createRgba(mask.width, mask.height);
|
|
168
|
+
for (let y = 0; y < mask.height; y++) {
|
|
169
|
+
for (let x = 0; x < mask.width; x++) {
|
|
170
|
+
const sx = x + crop.padX;
|
|
171
|
+
const sy = y + crop.padY;
|
|
172
|
+
if (sx < 0 || sy < 0 || sx >= square.width || sy >= square.height)
|
|
173
|
+
continue;
|
|
174
|
+
const from = (sy * square.width + sx) * 4;
|
|
175
|
+
const to = (y * mask.width + x) * 4;
|
|
176
|
+
rect.data[to] = square.data[from];
|
|
177
|
+
rect.data[to + 1] = square.data[from + 1];
|
|
178
|
+
rect.data[to + 2] = square.data[from + 2];
|
|
179
|
+
rect.data[to + 3] = square.data[from + 3];
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
// ② 缩回原尺寸。
|
|
183
|
+
const fitted = resizeRgba(rect, Math.max(1, targetWidth), Math.max(1, targetHeight));
|
|
184
|
+
// ③ 用原图 alpha 当掩码:轮廓不变,模型的背景被切掉。
|
|
185
|
+
for (let i = 0; i < fitted.width * fitted.height; i++) {
|
|
186
|
+
const at = i * 4;
|
|
187
|
+
const maskAlpha = i < mask.width * mask.height ? mask.data[at + 3] : 0;
|
|
188
|
+
fitted.data[at + 3] = Math.min(fitted.data[at + 3], maskAlpha);
|
|
189
|
+
}
|
|
190
|
+
return fitted;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* 腐蚀 alpha(每次是 3×3 的最小值滤波,重复 `radius` 次)。
|
|
194
|
+
*
|
|
195
|
+
* 用途:AI 生成的部件边缘几乎总有一圈**白晕**(模型把「纯白背景」和「发光的
|
|
196
|
+
* 边缘」混在一起)。按半径分档腐蚀掉最外圈,可以显著减轻它。
|
|
197
|
+
* 参考项目 reskin-app 用的也是这个思路(形态学 erode,且**细部件腐蚀更小**)。
|
|
198
|
+
*/
|
|
199
|
+
export function erodeAlpha(src, radius) {
|
|
200
|
+
if (radius <= 0)
|
|
201
|
+
return { data: Buffer.from(src.data), width: src.width, height: src.height };
|
|
202
|
+
let current = Buffer.from(src.data);
|
|
203
|
+
const { width, height } = src;
|
|
204
|
+
const next = Buffer.alloc(width * height * 4);
|
|
205
|
+
for (let step = 0; step < radius; step++) {
|
|
206
|
+
next.set(current);
|
|
207
|
+
for (let y = 0; y < height; y++) {
|
|
208
|
+
for (let x = 0; x < width; x++) {
|
|
209
|
+
let min = 255;
|
|
210
|
+
for (let dy = -1; dy <= 1; dy++) {
|
|
211
|
+
const ny = y + dy;
|
|
212
|
+
if (ny < 0 || ny >= height) {
|
|
213
|
+
min = 0;
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
for (let dx = -1; dx <= 1; dx++) {
|
|
217
|
+
const nx = x + dx;
|
|
218
|
+
if (nx < 0 || nx >= width) {
|
|
219
|
+
min = 0;
|
|
220
|
+
break;
|
|
221
|
+
}
|
|
222
|
+
const alpha = current[(ny * width + nx) * 4 + 3];
|
|
223
|
+
if (alpha < min)
|
|
224
|
+
min = alpha;
|
|
225
|
+
}
|
|
226
|
+
if (min === 0)
|
|
227
|
+
break;
|
|
228
|
+
}
|
|
229
|
+
next[(y * width + x) * 4 + 3] = min;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
current = Buffer.from(next);
|
|
233
|
+
}
|
|
234
|
+
return { data: current, width, height };
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* 图像统计:不透明像素数、平均亮度、亮度标准差。
|
|
238
|
+
*
|
|
239
|
+
* 用途是**判定「模型到底画出东西没有」**。实测过一次很有代表性的失败:
|
|
240
|
+
* 送进去的是一张「浅肤色手 + 白底补边」的图,生图模型直接交回一张纯白——
|
|
241
|
+
* 如果照单全收,用户拿到的就是一版白块贴图,而且**从版本列表上看不出它坏了**。
|
|
242
|
+
* 有这组数字就能在落盘前拦住,并说清原因。
|
|
243
|
+
*/
|
|
244
|
+
export function imageStats(src, alphaThreshold = 128) {
|
|
245
|
+
let opaque = 0;
|
|
246
|
+
let sum = 0;
|
|
247
|
+
let sumSquares = 0;
|
|
248
|
+
for (let i = 0; i < src.width * src.height; i++) {
|
|
249
|
+
const at = i * 4;
|
|
250
|
+
if (src.data[at + 3] < alphaThreshold)
|
|
251
|
+
continue;
|
|
252
|
+
const luma = (src.data[at] + src.data[at + 1] + src.data[at + 2]) / 3;
|
|
253
|
+
sum += luma;
|
|
254
|
+
sumSquares += luma * luma;
|
|
255
|
+
opaque++;
|
|
256
|
+
}
|
|
257
|
+
if (opaque === 0)
|
|
258
|
+
return { opaque: 0, meanLuma: 0, stdDev: 0 };
|
|
259
|
+
const mean = sum / opaque;
|
|
260
|
+
const variance = Math.max(0, sumSquares / opaque - mean * mean);
|
|
261
|
+
return { opaque, meanLuma: mean, stdDev: Math.sqrt(variance) };
|
|
262
|
+
}
|
|
263
|
+
// ── 基础像素操作 ────────────────────────────────────────────────────────
|
|
264
|
+
export function createRgba(width, height, fill = [0, 0, 0, 0]) {
|
|
265
|
+
const data = Buffer.alloc(width * height * 4);
|
|
266
|
+
for (let i = 0; i < width * height; i++) {
|
|
267
|
+
data[i * 4] = fill[0];
|
|
268
|
+
data[i * 4 + 1] = fill[1];
|
|
269
|
+
data[i * 4 + 2] = fill[2];
|
|
270
|
+
data[i * 4 + 3] = fill[3];
|
|
271
|
+
}
|
|
272
|
+
return { data, width, height };
|
|
273
|
+
}
|
|
274
|
+
/** 双线性缩放 RGBA(alpha 用最近邻阈值化,避免半透明边缘糊成毛边)。 */
|
|
275
|
+
export function resizeRgba(src, width, height) {
|
|
276
|
+
const dw = Math.max(1, Math.round(width));
|
|
277
|
+
const dh = Math.max(1, Math.round(height));
|
|
278
|
+
if (dw === src.width && dh === src.height)
|
|
279
|
+
return { data: Buffer.from(src.data), width: dw, height: dh };
|
|
280
|
+
const out = Buffer.alloc(dw * dh * 4);
|
|
281
|
+
const xRatio = src.width / dw;
|
|
282
|
+
const yRatio = src.height / dh;
|
|
283
|
+
for (let y = 0; y < dh; y++) {
|
|
284
|
+
const sy = Math.min(src.height - 1, (y + 0.5) * yRatio - 0.5);
|
|
285
|
+
const y0 = Math.max(0, Math.floor(sy));
|
|
286
|
+
const y1 = Math.min(src.height - 1, y0 + 1);
|
|
287
|
+
const wy = sy - y0;
|
|
288
|
+
for (let x = 0; x < dw; x++) {
|
|
289
|
+
const sx = Math.min(src.width - 1, (x + 0.5) * xRatio - 0.5);
|
|
290
|
+
const x0 = Math.max(0, Math.floor(sx));
|
|
291
|
+
const x1 = Math.min(src.width - 1, x0 + 1);
|
|
292
|
+
const wx = sx - x0;
|
|
293
|
+
const idx = (y * dw + x) * 4;
|
|
294
|
+
for (let c = 0; c < 3; c++) {
|
|
295
|
+
const p00 = src.data[(y0 * src.width + x0) * 4 + c];
|
|
296
|
+
const p10 = src.data[(y0 * src.width + x1) * 4 + c];
|
|
297
|
+
const p01 = src.data[(y1 * src.width + x0) * 4 + c];
|
|
298
|
+
const p11 = src.data[(y1 * src.width + x1) * 4 + c];
|
|
299
|
+
const top = p00 + (p10 - p00) * wx;
|
|
300
|
+
const bottom = p01 + (p11 - p01) * wx;
|
|
301
|
+
out[idx + c] = Math.max(0, Math.min(255, Math.round(top + (bottom - top) * wy)));
|
|
302
|
+
}
|
|
303
|
+
// alpha:取最近邻,保住硬边
|
|
304
|
+
const nearest = (Math.min(src.height - 1, Math.round(sy)) * src.width + Math.min(src.width - 1, Math.round(sx))) * 4;
|
|
305
|
+
out[idx + 3] = src.data[nearest + 3];
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
return { data: out, width: dw, height: dh };
|
|
309
|
+
}
|
|
310
|
+
/** 绕中心旋转 RGBA,输出尺寸自动扩到旋转后的包围盒。 */
|
|
311
|
+
export function rotateRgba(src, degrees) {
|
|
312
|
+
if (Math.abs(degrees) < 0.01)
|
|
313
|
+
return { data: Buffer.from(src.data), width: src.width, height: src.height };
|
|
314
|
+
const rad = (degrees * Math.PI) / 180;
|
|
315
|
+
const cos = Math.cos(rad);
|
|
316
|
+
const sin = Math.sin(rad);
|
|
317
|
+
const outW = Math.max(1, Math.ceil(Math.abs(src.width * cos) + Math.abs(src.height * sin)));
|
|
318
|
+
const outH = Math.max(1, Math.ceil(Math.abs(src.width * sin) + Math.abs(src.height * cos)));
|
|
319
|
+
const out = Buffer.alloc(outW * outH * 4);
|
|
320
|
+
const cx = src.width / 2;
|
|
321
|
+
const cy = src.height / 2;
|
|
322
|
+
const ocx = outW / 2;
|
|
323
|
+
const ocy = outH / 2;
|
|
324
|
+
for (let y = 0; y < outH; y++) {
|
|
325
|
+
for (let x = 0; x < outW; x++) {
|
|
326
|
+
const dx = x + 0.5 - ocx;
|
|
327
|
+
const dy = y + 0.5 - ocy;
|
|
328
|
+
const sx = Math.round(cx + dx * cos + dy * sin - 0.5);
|
|
329
|
+
const sy = Math.round(cy - dx * sin + dy * cos - 0.5);
|
|
330
|
+
const idx = (y * outW + x) * 4;
|
|
331
|
+
if (sx < 0 || sy < 0 || sx >= src.width || sy >= src.height)
|
|
332
|
+
continue;
|
|
333
|
+
const sIdx = (sy * src.width + sx) * 4;
|
|
334
|
+
out[idx] = src.data[sIdx];
|
|
335
|
+
out[idx + 1] = src.data[sIdx + 1];
|
|
336
|
+
out[idx + 2] = src.data[sIdx + 2];
|
|
337
|
+
out[idx + 3] = src.data[sIdx + 3];
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return { data: out, width: outW, height: outH };
|
|
341
|
+
}
|
|
342
|
+
/** alpha > threshold 的包围盒;全透明时返回 undefined。 */
|
|
343
|
+
export function alphaBounds(src, threshold = 8) {
|
|
344
|
+
let minX = src.width;
|
|
345
|
+
let minY = src.height;
|
|
346
|
+
let maxX = -1;
|
|
347
|
+
let maxY = -1;
|
|
348
|
+
for (let y = 0; y < src.height; y++) {
|
|
349
|
+
for (let x = 0; x < src.width; x++) {
|
|
350
|
+
if (src.data[(y * src.width + x) * 4 + 3] <= threshold)
|
|
351
|
+
continue;
|
|
352
|
+
if (x < minX)
|
|
353
|
+
minX = x;
|
|
354
|
+
if (y < minY)
|
|
355
|
+
minY = y;
|
|
356
|
+
if (x > maxX)
|
|
357
|
+
maxX = x;
|
|
358
|
+
if (y > maxY)
|
|
359
|
+
maxY = y;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
if (maxX < 0)
|
|
363
|
+
return undefined;
|
|
364
|
+
return { x: minX, y: minY, width: maxX - minX + 1, height: maxY - minY + 1 };
|
|
365
|
+
}
|
|
366
|
+
/** 裁掉全透明边(让每个部件的坐标都从自己的左上角量起)。 */
|
|
367
|
+
export function trimRgba(src) {
|
|
368
|
+
const box = alphaBounds(src);
|
|
369
|
+
if (box === undefined)
|
|
370
|
+
return { data: Buffer.from(src.data), width: src.width, height: src.height };
|
|
371
|
+
if (box.x === 0 && box.y === 0 && box.width === src.width && box.height === src.height) {
|
|
372
|
+
return { data: Buffer.from(src.data), width: src.width, height: src.height };
|
|
373
|
+
}
|
|
374
|
+
const out = Buffer.alloc(box.width * box.height * 4);
|
|
375
|
+
for (let y = 0; y < box.height; y++) {
|
|
376
|
+
src.data.copy(out, y * box.width * 4, ((box.y + y) * src.width + box.x) * 4, ((box.y + y) * src.width + box.x + box.width) * 4);
|
|
377
|
+
}
|
|
378
|
+
return { data: out, width: box.width, height: box.height };
|
|
379
|
+
}
|
|
380
|
+
/** 把 src 以 source-over 合成到 dst 的 (x, y) 处。 */
|
|
381
|
+
export function blitRgba(dst, src, x, y) {
|
|
382
|
+
const dx = Math.round(x);
|
|
383
|
+
const dy = Math.round(y);
|
|
384
|
+
for (let sy = 0; sy < src.height; sy++) {
|
|
385
|
+
const ty = dy + sy;
|
|
386
|
+
if (ty < 0 || ty >= dst.height)
|
|
387
|
+
continue;
|
|
388
|
+
for (let sx = 0; sx < src.width; sx++) {
|
|
389
|
+
const tx = dx + sx;
|
|
390
|
+
if (tx < 0 || tx >= dst.width)
|
|
391
|
+
continue;
|
|
392
|
+
const sIdx = (sy * src.width + sx) * 4;
|
|
393
|
+
const alpha = src.data[sIdx + 3] / 255;
|
|
394
|
+
if (alpha <= 0)
|
|
395
|
+
continue;
|
|
396
|
+
const dIdx = (ty * dst.width + tx) * 4;
|
|
397
|
+
for (let c = 0; c < 3; c++) {
|
|
398
|
+
dst.data[dIdx + c] = Math.round(src.data[sIdx + c] * alpha + dst.data[dIdx + c] * (1 - alpha));
|
|
399
|
+
}
|
|
400
|
+
dst.data[dIdx + 3] = Math.max(dst.data[dIdx + 3], src.data[sIdx + 3]);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
export function toGrayMask(src, alphaThreshold = 128) {
|
|
405
|
+
const total = src.width * src.height;
|
|
406
|
+
const gray = new Float32Array(total);
|
|
407
|
+
const red = new Float32Array(total);
|
|
408
|
+
const green = new Float32Array(total);
|
|
409
|
+
const blue = new Float32Array(total);
|
|
410
|
+
const mask = new Uint8Array(total);
|
|
411
|
+
for (let i = 0; i < total; i++) {
|
|
412
|
+
const r = src.data[i * 4];
|
|
413
|
+
const g = src.data[i * 4 + 1];
|
|
414
|
+
const b = src.data[i * 4 + 2];
|
|
415
|
+
const a = src.data[i * 4 + 3];
|
|
416
|
+
gray[i] = 0.299 * r + 0.587 * g + 0.114 * b;
|
|
417
|
+
red[i] = r;
|
|
418
|
+
green[i] = g;
|
|
419
|
+
blue[i] = b;
|
|
420
|
+
mask[i] = a > alphaThreshold ? 1 : 0;
|
|
421
|
+
}
|
|
422
|
+
return { gray, r: red, g: green, b: blue, mask, width: src.width, height: src.height };
|
|
423
|
+
}
|
|
424
|
+
export function resizeGrayMask(src, width, height) {
|
|
425
|
+
const dw = Math.max(1, Math.round(width));
|
|
426
|
+
const dh = Math.max(1, Math.round(height));
|
|
427
|
+
const gray = new Float32Array(dw * dh);
|
|
428
|
+
const red = new Float32Array(dw * dh);
|
|
429
|
+
const green = new Float32Array(dw * dh);
|
|
430
|
+
const blue = new Float32Array(dw * dh);
|
|
431
|
+
const mask = new Uint8Array(dw * dh);
|
|
432
|
+
const xRatio = src.width / dw;
|
|
433
|
+
const yRatio = src.height / dh;
|
|
434
|
+
for (let y = 0; y < dh; y++) {
|
|
435
|
+
const sy = Math.min(src.height - 1, (y + 0.5) * yRatio - 0.5);
|
|
436
|
+
const y0 = Math.max(0, Math.floor(sy));
|
|
437
|
+
const y1 = Math.min(src.height - 1, y0 + 1);
|
|
438
|
+
const wy = sy - y0;
|
|
439
|
+
for (let x = 0; x < dw; x++) {
|
|
440
|
+
const sx = Math.min(src.width - 1, (x + 0.5) * xRatio - 0.5);
|
|
441
|
+
const x0 = Math.max(0, Math.floor(sx));
|
|
442
|
+
const x1 = Math.min(src.width - 1, x0 + 1);
|
|
443
|
+
const wx = sx - x0;
|
|
444
|
+
const sample = (channel) => {
|
|
445
|
+
const c00 = channel[y0 * src.width + x0];
|
|
446
|
+
const c10 = channel[y0 * src.width + x1];
|
|
447
|
+
const c01 = channel[y1 * src.width + x0];
|
|
448
|
+
const c11 = channel[y1 * src.width + x1];
|
|
449
|
+
const topValue = c00 + (c10 - c00) * wx;
|
|
450
|
+
const bottomValue = c01 + (c11 - c01) * wx;
|
|
451
|
+
return topValue + (bottomValue - topValue) * wy;
|
|
452
|
+
};
|
|
453
|
+
gray[y * dw + x] = sample(src.gray);
|
|
454
|
+
red[y * dw + x] = sample(src.r);
|
|
455
|
+
green[y * dw + x] = sample(src.g);
|
|
456
|
+
blue[y * dw + x] = sample(src.b);
|
|
457
|
+
// 掩码按覆盖率取:缩得太小时别把细部件抹掉。
|
|
458
|
+
const cov = src.mask[y0 * src.width + x0] +
|
|
459
|
+
src.mask[y0 * src.width + x1] +
|
|
460
|
+
src.mask[y1 * src.width + x0] +
|
|
461
|
+
src.mask[y1 * src.width + x1];
|
|
462
|
+
mask[y * dw + x] = cov >= 2 ? 1 : 0;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
return { gray, r: red, g: green, b: blue, mask, width: dw, height: dh };
|
|
466
|
+
}
|
|
467
|
+
export function rotateGrayMask(src, degrees) {
|
|
468
|
+
if (Math.abs(degrees) < 0.01)
|
|
469
|
+
return src;
|
|
470
|
+
const rad = (degrees * Math.PI) / 180;
|
|
471
|
+
const cos = Math.cos(rad);
|
|
472
|
+
const sin = Math.sin(rad);
|
|
473
|
+
const outW = Math.max(1, Math.ceil(Math.abs(src.width * cos) + Math.abs(src.height * sin)));
|
|
474
|
+
const outH = Math.max(1, Math.ceil(Math.abs(src.width * sin) + Math.abs(src.height * cos)));
|
|
475
|
+
const gray = new Float32Array(outW * outH);
|
|
476
|
+
const red = new Float32Array(outW * outH);
|
|
477
|
+
const green = new Float32Array(outW * outH);
|
|
478
|
+
const blue = new Float32Array(outW * outH);
|
|
479
|
+
const mask = new Uint8Array(outW * outH);
|
|
480
|
+
const cx = src.width / 2;
|
|
481
|
+
const cy = src.height / 2;
|
|
482
|
+
const ocx = outW / 2;
|
|
483
|
+
const ocy = outH / 2;
|
|
484
|
+
for (let y = 0; y < outH; y++) {
|
|
485
|
+
for (let x = 0; x < outW; x++) {
|
|
486
|
+
const dx = x + 0.5 - ocx;
|
|
487
|
+
const dy = y + 0.5 - ocy;
|
|
488
|
+
const sx = Math.round(cx + dx * cos + dy * sin - 0.5);
|
|
489
|
+
const sy = Math.round(cy - dx * sin + dy * cos - 0.5);
|
|
490
|
+
if (sx < 0 || sy < 0 || sx >= src.width || sy >= src.height)
|
|
491
|
+
continue;
|
|
492
|
+
const sIdx = sy * src.width + sx;
|
|
493
|
+
gray[y * outW + x] = src.gray[sIdx];
|
|
494
|
+
red[y * outW + x] = src.r[sIdx];
|
|
495
|
+
green[y * outW + x] = src.g[sIdx];
|
|
496
|
+
blue[y * outW + x] = src.b[sIdx];
|
|
497
|
+
mask[y * outW + x] = src.mask[sIdx];
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
return { gray, r: red, g: green, b: blue, mask, width: outW, height: outH };
|
|
501
|
+
}
|
|
502
|
+
/** 取图像四角的中位数颜色作为底色估计——比「假设是白色」可靠。 */
|
|
503
|
+
export function detectBackground(src) {
|
|
504
|
+
const samples = [
|
|
505
|
+
[0, 0],
|
|
506
|
+
[src.width - 1, 0],
|
|
507
|
+
[0, src.height - 1],
|
|
508
|
+
[src.width - 1, src.height - 1],
|
|
509
|
+
[Math.floor(src.width / 2), 0],
|
|
510
|
+
[Math.floor(src.width / 2), src.height - 1]
|
|
511
|
+
];
|
|
512
|
+
const channels = [[], [], []];
|
|
513
|
+
for (const [x, y] of samples) {
|
|
514
|
+
const idx = (y * src.width + x) * 4;
|
|
515
|
+
for (let c = 0; c < 3; c++)
|
|
516
|
+
channels[c].push(src.data[idx + c]);
|
|
517
|
+
}
|
|
518
|
+
return channels.map((list) => {
|
|
519
|
+
list.sort((a, b) => a - b);
|
|
520
|
+
return list[Math.floor(list.length / 2)];
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
export function segmentComponents(atlas, options) {
|
|
524
|
+
return segmentWithLabels(atlas, options).components;
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* 部件裁剪块里的软 alpha(每个像素 0-255)。
|
|
528
|
+
*
|
|
529
|
+
* **不能拿「离底色多远」直接当 alpha。** 这个映射对「浅色角色 + 白底」是灾难性的:
|
|
530
|
+
* 实测一张真实立绘里白色长袜的填充色是 `rgb(247,227,221)`,与白底 `rgb(252,252,254)`
|
|
531
|
+
* 只差 42,于是整条腿——**不只是边缘**——被判成 ~45% 透明,显示出来就是「不该半透明的
|
|
532
|
+
* 地方全是半透明」,而且填充越浅越透明,在美术上完全说不通。同一张图里手是 33%、
|
|
533
|
+
* 小腿是 64% 的内部像素都这样,只有深色描边(距离 440+)才能拿到不透明。
|
|
534
|
+
*
|
|
535
|
+
* 正确做法是把「形状」和「过渡」拆开:
|
|
536
|
+
*
|
|
537
|
+
* 1. **形状**由硬掩码决定(颜色距离 > 容差),并且把**完全封闭**的孔洞补上——
|
|
538
|
+
* 浅色高光一旦落进容差内,会在部件中间咬出一个透明的洞,那比白斑更糟。
|
|
539
|
+
* 2. **过渡**只发生在轮廓最外圈 `RIM_PX` 个像素里;内部一律不透明,**与颜色无关**。
|
|
540
|
+
* 颜色距离只用来决定这一圈有多软(就是设置里的「边缘羽化」)。
|
|
541
|
+
*
|
|
542
|
+
* 距离用 3-4 chamfer 近似欧氏距离,比棋盘距离圆,代价仍是两遍线性扫描。
|
|
543
|
+
*/
|
|
544
|
+
const RIM_PX = 2;
|
|
545
|
+
function componentAlpha(data, sheetWidth, x1, y1, cw, ch, background, tolerance, feather) {
|
|
546
|
+
const total = cw * ch;
|
|
547
|
+
const [br, bg, bb] = background;
|
|
548
|
+
const solid = new Uint8Array(total);
|
|
549
|
+
const colorDistance = new Float32Array(total);
|
|
550
|
+
const alpha = new Uint8Array(total);
|
|
551
|
+
for (let y = 0; y < ch; y++) {
|
|
552
|
+
for (let x = 0; x < cw; x++) {
|
|
553
|
+
const i = y * cw + x;
|
|
554
|
+
const srcIdx = ((y1 + y) * sheetWidth + x1 + x) * 4;
|
|
555
|
+
const dr = data[srcIdx] - br;
|
|
556
|
+
const dg = data[srcIdx + 1] - bg;
|
|
557
|
+
const db = data[srcIdx + 2] - bb;
|
|
558
|
+
const distance = Math.sqrt(dr * dr + dg * dg + db * db);
|
|
559
|
+
colorDistance[i] = distance;
|
|
560
|
+
solid[i] = distance > tolerance && data[srcIdx + 3] > 8 ? 1 : 0;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
// 「外部」= 能从裁剪块边界一路走到的地方(4 邻域,避免从对角缝里漏出去)。
|
|
564
|
+
// 没被淹到的空格就是被部件完全包住的孔洞——对着一张「白底 + 描边」的拆件图,
|
|
565
|
+
// 那种地方按定义属于部件内部,补成不透明。
|
|
566
|
+
const outside = new Uint8Array(total);
|
|
567
|
+
const queue = new Int32Array(total);
|
|
568
|
+
let head = 0;
|
|
569
|
+
let tail = 0;
|
|
570
|
+
const seed = (i) => {
|
|
571
|
+
if (solid[i] === 0 && outside[i] === 0) {
|
|
572
|
+
outside[i] = 1;
|
|
573
|
+
queue[tail++] = i;
|
|
574
|
+
}
|
|
575
|
+
};
|
|
576
|
+
for (let x = 0; x < cw; x++) {
|
|
577
|
+
seed(x);
|
|
578
|
+
seed((ch - 1) * cw + x);
|
|
579
|
+
}
|
|
580
|
+
for (let y = 0; y < ch; y++) {
|
|
581
|
+
seed(y * cw);
|
|
582
|
+
seed(y * cw + cw - 1);
|
|
583
|
+
}
|
|
584
|
+
while (head < tail) {
|
|
585
|
+
const i = queue[head++];
|
|
586
|
+
const x = i % cw;
|
|
587
|
+
const y = (i - x) / cw;
|
|
588
|
+
if (x > 0)
|
|
589
|
+
seed(i - 1);
|
|
590
|
+
if (x < cw - 1)
|
|
591
|
+
seed(i + 1);
|
|
592
|
+
if (y > 0)
|
|
593
|
+
seed(i - cw);
|
|
594
|
+
if (y < ch - 1)
|
|
595
|
+
seed(i + cw);
|
|
596
|
+
}
|
|
597
|
+
// 到「外部」的像素距离(3-4 chamfer,单位是 1/3 像素)。
|
|
598
|
+
const FAR = (cw + ch) * 4;
|
|
599
|
+
const dt = new Int32Array(total);
|
|
600
|
+
for (let i = 0; i < total; i++)
|
|
601
|
+
dt[i] = outside[i] === 1 ? 0 : FAR;
|
|
602
|
+
for (let y = 0; y < ch; y++) {
|
|
603
|
+
for (let x = 0; x < cw; x++) {
|
|
604
|
+
const i = y * cw + x;
|
|
605
|
+
if (dt[i] === 0)
|
|
606
|
+
continue;
|
|
607
|
+
let best = dt[i];
|
|
608
|
+
if (x > 0)
|
|
609
|
+
best = Math.min(best, dt[i - 1] + 3);
|
|
610
|
+
if (y > 0)
|
|
611
|
+
best = Math.min(best, dt[i - cw] + 3);
|
|
612
|
+
if (x > 0 && y > 0)
|
|
613
|
+
best = Math.min(best, dt[i - cw - 1] + 4);
|
|
614
|
+
if (x < cw - 1 && y > 0)
|
|
615
|
+
best = Math.min(best, dt[i - cw + 1] + 4);
|
|
616
|
+
dt[i] = best;
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
for (let y = ch - 1; y >= 0; y--) {
|
|
620
|
+
for (let x = cw - 1; x >= 0; x--) {
|
|
621
|
+
const i = y * cw + x;
|
|
622
|
+
if (dt[i] === 0)
|
|
623
|
+
continue;
|
|
624
|
+
let best = dt[i];
|
|
625
|
+
if (x < cw - 1)
|
|
626
|
+
best = Math.min(best, dt[i + 1] + 3);
|
|
627
|
+
if (y < ch - 1)
|
|
628
|
+
best = Math.min(best, dt[i + cw] + 3);
|
|
629
|
+
if (x < cw - 1 && y < ch - 1)
|
|
630
|
+
best = Math.min(best, dt[i + cw + 1] + 4);
|
|
631
|
+
if (x > 0 && y < ch - 1)
|
|
632
|
+
best = Math.min(best, dt[i + cw - 1] + 4);
|
|
633
|
+
dt[i] = best;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
const rim3 = RIM_PX * 3;
|
|
637
|
+
for (let y = 0; y < ch; y++) {
|
|
638
|
+
for (let x = 0; x < cw; x++) {
|
|
639
|
+
const i = y * cw + x;
|
|
640
|
+
if (outside[i] === 1)
|
|
641
|
+
continue;
|
|
642
|
+
let cover = 1;
|
|
643
|
+
if (dt[i] <= rim3) {
|
|
644
|
+
// 最外圈:颜色距离只在这里起作用,给抗锯齿边缘留一点软过渡。
|
|
645
|
+
const ramp = Math.max(0, Math.min(1, (colorDistance[i] - tolerance) / feather));
|
|
646
|
+
cover = Math.max(ramp, dt[i] / (rim3 + 3));
|
|
647
|
+
}
|
|
648
|
+
const srcIdx = ((y1 + y) * sheetWidth + x1 + x) * 4;
|
|
649
|
+
alpha[i] = Math.round(Math.max(0, Math.min(1, cover)) * data[srcIdx + 3]);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
return alpha;
|
|
653
|
+
}
|
|
654
|
+
export function segmentWithLabels(atlas, options) {
|
|
655
|
+
const { width, height, data } = atlas;
|
|
656
|
+
const total = width * height;
|
|
657
|
+
const labels = new Int32Array(total).fill(-1);
|
|
658
|
+
const isForeground = new Uint8Array(total);
|
|
659
|
+
const [br, bg, bb] = options.background;
|
|
660
|
+
const tol2 = options.tolerance * options.tolerance;
|
|
661
|
+
for (let i = 0; i < total; i++) {
|
|
662
|
+
const idx = i * 4;
|
|
663
|
+
if (data[idx + 3] <= 8)
|
|
664
|
+
continue;
|
|
665
|
+
const dr = data[idx] - br;
|
|
666
|
+
const dg = data[idx + 1] - bg;
|
|
667
|
+
const db = data[idx + 2] - bb;
|
|
668
|
+
if (dr * dr + dg * dg + db * db > tol2)
|
|
669
|
+
isForeground[i] = 1;
|
|
670
|
+
}
|
|
671
|
+
const components = [];
|
|
672
|
+
const stack = new Int32Array(total);
|
|
673
|
+
let label = 0;
|
|
674
|
+
for (let start = 0; start < total; start++) {
|
|
675
|
+
if (isForeground[start] !== 1 || labels[start] !== -1)
|
|
676
|
+
continue;
|
|
677
|
+
let top = 0;
|
|
678
|
+
stack[top++] = start;
|
|
679
|
+
labels[start] = label;
|
|
680
|
+
let minX = width;
|
|
681
|
+
let minY = height;
|
|
682
|
+
let maxX = -1;
|
|
683
|
+
let maxY = -1;
|
|
684
|
+
let area = 0;
|
|
685
|
+
let sumX = 0;
|
|
686
|
+
let sumY = 0;
|
|
687
|
+
while (top > 0) {
|
|
688
|
+
const index = stack[--top];
|
|
689
|
+
const x = index % width;
|
|
690
|
+
const y = (index - x) / width;
|
|
691
|
+
area++;
|
|
692
|
+
sumX += x;
|
|
693
|
+
sumY += y;
|
|
694
|
+
if (x < minX)
|
|
695
|
+
minX = x;
|
|
696
|
+
if (y < minY)
|
|
697
|
+
minY = y;
|
|
698
|
+
if (x > maxX)
|
|
699
|
+
maxX = x;
|
|
700
|
+
if (y > maxY)
|
|
701
|
+
maxY = y;
|
|
702
|
+
for (let dy = -1; dy <= 1; dy++) {
|
|
703
|
+
for (let dx = -1; dx <= 1; dx++) {
|
|
704
|
+
if (dx === 0 && dy === 0)
|
|
705
|
+
continue;
|
|
706
|
+
const nx = x + dx;
|
|
707
|
+
const ny = y + dy;
|
|
708
|
+
if (nx < 0 || ny < 0 || nx >= width || ny >= height)
|
|
709
|
+
continue;
|
|
710
|
+
const nIdx = ny * width + nx;
|
|
711
|
+
if (isForeground[nIdx] !== 1 || labels[nIdx] !== -1)
|
|
712
|
+
continue;
|
|
713
|
+
labels[nIdx] = label;
|
|
714
|
+
stack[top++] = nIdx;
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
components.push({ minX, minY, maxX, maxY, area, sumX, sumY, label });
|
|
719
|
+
label++;
|
|
720
|
+
}
|
|
721
|
+
const result = [];
|
|
722
|
+
const feather = Math.max(1, options.feather);
|
|
723
|
+
for (const component of components) {
|
|
724
|
+
if (component.area < options.minArea)
|
|
725
|
+
continue;
|
|
726
|
+
const x1 = Math.max(0, component.minX - options.padding);
|
|
727
|
+
const y1 = Math.max(0, component.minY - options.padding);
|
|
728
|
+
const x2 = Math.min(width, component.maxX + 1 + options.padding);
|
|
729
|
+
const y2 = Math.min(height, component.maxY + 1 + options.padding);
|
|
730
|
+
const cw = x2 - x1;
|
|
731
|
+
const ch = y2 - y1;
|
|
732
|
+
const out = Buffer.alloc(cw * ch * 4);
|
|
733
|
+
const alpha = componentAlpha(atlas.data, width, x1, y1, cw, ch, [br, bg, bb], options.tolerance, feather);
|
|
734
|
+
for (let i = 0; i < cw * ch; i++) {
|
|
735
|
+
if (alpha[i] === 0)
|
|
736
|
+
continue;
|
|
737
|
+
const srcIdx = (((y1 + Math.floor(i / cw)) * width) + x1 + (i % cw)) * 4;
|
|
738
|
+
out[i * 4] = atlas.data[srcIdx];
|
|
739
|
+
out[i * 4 + 1] = atlas.data[srcIdx + 1];
|
|
740
|
+
out[i * 4 + 2] = atlas.data[srcIdx + 2];
|
|
741
|
+
out[i * 4 + 3] = alpha[i];
|
|
742
|
+
}
|
|
743
|
+
result.push({
|
|
744
|
+
x: x1,
|
|
745
|
+
y: y1,
|
|
746
|
+
width: cw,
|
|
747
|
+
height: ch,
|
|
748
|
+
area: component.area,
|
|
749
|
+
centroidX: Math.round(component.sumX / component.area),
|
|
750
|
+
centroidY: Math.round(component.sumY / component.area),
|
|
751
|
+
pieces: 1,
|
|
752
|
+
rgba: { data: out, width: cw, height: ch },
|
|
753
|
+
label: component.label
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
return { components: result, labels, width, height };
|
|
757
|
+
}
|
|
758
|
+
/** 判定参考图里哪些像素属于角色(alpha 不透明 + 离底色足够远)。 */
|
|
759
|
+
export function referenceForeground(reference, tolerance = 40) {
|
|
760
|
+
const background = detectBackground(reference);
|
|
761
|
+
const out = new Uint8Array(reference.width * reference.height);
|
|
762
|
+
const tol2 = tolerance * tolerance;
|
|
763
|
+
for (let i = 0; i < out.length; i++) {
|
|
764
|
+
const idx = i * 4;
|
|
765
|
+
if (reference.data[idx + 3] <= 8)
|
|
766
|
+
continue;
|
|
767
|
+
const dr = reference.data[idx] - background[0];
|
|
768
|
+
const dg = reference.data[idx + 1] - background[1];
|
|
769
|
+
const db = reference.data[idx + 2] - background[2];
|
|
770
|
+
if (dr * dr + dg * dg + db * db > tol2)
|
|
771
|
+
out[i] = 1;
|
|
772
|
+
}
|
|
773
|
+
return out;
|
|
774
|
+
}
|
|
775
|
+
export function buildReferencePyramid(reference, longEdge, foregroundTolerance = 40) {
|
|
776
|
+
const longest = Math.max(reference.width, reference.height);
|
|
777
|
+
const full = toGrayMask(reference, 128);
|
|
778
|
+
const foreground = referenceForeground(reference, foregroundTolerance);
|
|
779
|
+
const edges = [];
|
|
780
|
+
let edge = 96;
|
|
781
|
+
while (edge < Math.min(longest, longEdge)) {
|
|
782
|
+
edges.push(edge);
|
|
783
|
+
edge *= 2;
|
|
784
|
+
}
|
|
785
|
+
edges.push(Math.min(longest, longEdge));
|
|
786
|
+
const levels = edges.map((size) => {
|
|
787
|
+
const w = Math.max(8, Math.round(reference.width * (size / longest)));
|
|
788
|
+
const h = Math.max(8, Math.round(reference.height * (size / longest)));
|
|
789
|
+
const gray = resizeGrayMask(full, w, h);
|
|
790
|
+
const fg = new Uint8Array(w * h);
|
|
791
|
+
let foregroundCount = 0;
|
|
792
|
+
for (let y = 0; y < h; y++) {
|
|
793
|
+
const sy0 = Math.min(reference.height - 1, Math.floor(y * (reference.height / h)));
|
|
794
|
+
const sy1 = Math.min(reference.height - 1, Math.floor((y + 1) * (reference.height / h)) - 1);
|
|
795
|
+
for (let x = 0; x < w; x++) {
|
|
796
|
+
const sx0 = Math.min(reference.width - 1, Math.floor(x * (reference.width / w)));
|
|
797
|
+
const sx1 = Math.min(reference.width - 1, Math.floor((x + 1) * (reference.width / w)) - 1);
|
|
798
|
+
// 用 3 个采样点做多数表决,避免降采样把细部件整片抹掉。
|
|
799
|
+
let votes = 0;
|
|
800
|
+
if (foreground[sy0 * reference.width + sx0])
|
|
801
|
+
votes++;
|
|
802
|
+
if (foreground[Math.max(sy0, sy1) * reference.width + sx1])
|
|
803
|
+
votes++;
|
|
804
|
+
if (foreground[sy0 * reference.width + sx1])
|
|
805
|
+
votes++;
|
|
806
|
+
if (votes >= 2) {
|
|
807
|
+
fg[y * w + x] = 1;
|
|
808
|
+
foregroundCount++;
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
return { edge: size, factor: w / reference.width, gray, foreground: fg, foregroundCount };
|
|
813
|
+
});
|
|
814
|
+
return { full, foreground, width: reference.width, height: reference.height, levels };
|
|
815
|
+
}
|
|
816
|
+
function prepareTemplate(tpl) {
|
|
817
|
+
let count = 0;
|
|
818
|
+
for (let i = 0; i < tpl.mask.length; i++)
|
|
819
|
+
if (tpl.mask[i] === 1)
|
|
820
|
+
count++;
|
|
821
|
+
if (count < 12)
|
|
822
|
+
return undefined;
|
|
823
|
+
const dx = new Int32Array(count);
|
|
824
|
+
const dy = new Int32Array(count);
|
|
825
|
+
let at = 0;
|
|
826
|
+
for (let i = 0; i < tpl.mask.length; i++) {
|
|
827
|
+
if (tpl.mask[i] !== 1)
|
|
828
|
+
continue;
|
|
829
|
+
const x = i % tpl.width;
|
|
830
|
+
dx[at] = x;
|
|
831
|
+
dy[at] = (i - x) / tpl.width;
|
|
832
|
+
at++;
|
|
833
|
+
}
|
|
834
|
+
return { gray: tpl, dx, dy, count };
|
|
835
|
+
}
|
|
836
|
+
/** 相关性为负、或有效像素太少时的哨兵值,任何情况下都不会被选为最优。 */
|
|
837
|
+
const INVALID_SCORE = -1;
|
|
838
|
+
/**
|
|
839
|
+
* 零均值归一化互相关(ZNCC),只在参考图前景上统计。
|
|
840
|
+
*
|
|
841
|
+
* ZNCC 天然免疫整体明暗差异,对「生图模型重新打过光」的部件更宽容。
|
|
842
|
+
* 返回的 `coverage` 是模板落在角色身上的比例——它是「放大」的天然惩罚:
|
|
843
|
+
* 模板一旦越出角色轮廓,多出来的像素不计入统计,coverage 直接掉下来。
|
|
844
|
+
*/
|
|
845
|
+
/** 模板的平均颜色(与摆放位置无关,建模板时算一次)。 */
|
|
846
|
+
function templateMeanColor(tpl) {
|
|
847
|
+
const { dx, dy, count, gray } = tpl;
|
|
848
|
+
const tw = gray.width;
|
|
849
|
+
let r = 0;
|
|
850
|
+
let g = 0;
|
|
851
|
+
let b = 0;
|
|
852
|
+
for (let i = 0; i < count; i++) {
|
|
853
|
+
const idx = dy[i] * tw + dx[i];
|
|
854
|
+
r += gray.r[idx];
|
|
855
|
+
g += gray.g[idx];
|
|
856
|
+
b += gray.b[idx];
|
|
857
|
+
}
|
|
858
|
+
const n = Math.max(1, count);
|
|
859
|
+
return [r / n, g / n, b / n];
|
|
860
|
+
}
|
|
861
|
+
function znccAt(ref, fg, tpl, ox, oy, ignored) {
|
|
862
|
+
const { dx, dy, count, gray } = tpl;
|
|
863
|
+
const rw = ref.width;
|
|
864
|
+
const rh = ref.height;
|
|
865
|
+
const rg = ref.gray;
|
|
866
|
+
const tw = gray.width;
|
|
867
|
+
let n = 0;
|
|
868
|
+
let sumT = 0;
|
|
869
|
+
let sumR = 0;
|
|
870
|
+
let sumTT = 0;
|
|
871
|
+
let sumRR = 0;
|
|
872
|
+
let sumTR = 0;
|
|
873
|
+
let sumRefR = 0;
|
|
874
|
+
let sumRefG = 0;
|
|
875
|
+
let sumRefB = 0;
|
|
876
|
+
// `ignored` 里的像素既不计入统计、也不计入覆盖率的分母:
|
|
877
|
+
// 它们是被前面部件挡住的地方,本来就看不到,拿它当「没匹配上」来扣分
|
|
878
|
+
// 会逼着模板沿着可见区域缩小、平移。
|
|
879
|
+
let considered = count;
|
|
880
|
+
for (let i = 0; i < count; i++) {
|
|
881
|
+
const rx = ox + dx[i];
|
|
882
|
+
if (rx < 0 || rx >= rw)
|
|
883
|
+
continue;
|
|
884
|
+
const ry = oy + dy[i];
|
|
885
|
+
if (ry < 0 || ry >= rh)
|
|
886
|
+
continue;
|
|
887
|
+
const rIdx = ry * rw + rx;
|
|
888
|
+
if (ignored !== undefined && ignored[rIdx] === 1) {
|
|
889
|
+
considered--;
|
|
890
|
+
continue;
|
|
891
|
+
}
|
|
892
|
+
if (fg[rIdx] === 0)
|
|
893
|
+
continue;
|
|
894
|
+
const t = gray.gray[dy[i] * tw + dx[i]];
|
|
895
|
+
const r = rg[rIdx];
|
|
896
|
+
n++;
|
|
897
|
+
sumT += t;
|
|
898
|
+
sumR += r;
|
|
899
|
+
sumTT += t * t;
|
|
900
|
+
sumRR += r * r;
|
|
901
|
+
sumTR += t * r;
|
|
902
|
+
sumRefR += ref.r[rIdx];
|
|
903
|
+
sumRefG += ref.g[rIdx];
|
|
904
|
+
sumRefB += ref.b[rIdx];
|
|
905
|
+
}
|
|
906
|
+
const coverage = n / Math.max(1, considered);
|
|
907
|
+
// 被挡掉太多时这个位置没有意义:把一块部件按到「几乎全在自己被遮住的区域」里,
|
|
908
|
+
// 剩下的十几个像素照样能凑出很高的相关系数(实测会让大腿跑到躯干上)。
|
|
909
|
+
// 留 30% 的可比较面积作为下限,既挡掉这种退化解,又允许真的被挡住大半的部件
|
|
910
|
+
// (比如帽子下面的头)用可见的那部分去定位。
|
|
911
|
+
if (considered < Math.max(12, count * 0.3))
|
|
912
|
+
return { score: INVALID_SCORE, coverage };
|
|
913
|
+
if (n < 12)
|
|
914
|
+
return { score: INVALID_SCORE, coverage };
|
|
915
|
+
const meanT = sumT / n;
|
|
916
|
+
const meanR = sumR / n;
|
|
917
|
+
const cov = sumTR / n - meanT * meanR;
|
|
918
|
+
const varT = sumTT / n - meanT * meanT;
|
|
919
|
+
const varR = sumRR / n - meanR * meanR;
|
|
920
|
+
const denom = Math.sqrt(Math.max(0, varT) * Math.max(0, varR));
|
|
921
|
+
if (denom < 1e-6)
|
|
922
|
+
return { score: INVALID_SCORE, coverage };
|
|
923
|
+
return { score: cov / denom, coverage };
|
|
924
|
+
}
|
|
925
|
+
/**
|
|
926
|
+
* 候选排序分。
|
|
927
|
+
*
|
|
928
|
+
* `score × (0.3 + 0.7 × coverage)` 负责压住**放大**:越出角色的模板覆盖率高不了。
|
|
929
|
+
* 后面的尺寸奖励负责压住**缩小**:一块小色斑贴在角色内部任意位置都能拿高分,
|
|
930
|
+
* 而相关系数本身对「只解释了一小块证据」毫无意见。奖励项按覆盖率开方并饱和,
|
|
931
|
+
* 所以不会反过来无脑鼓励放大——真放大过头时,乘以前面那一项会把它拉回来。
|
|
932
|
+
*/
|
|
933
|
+
function rankOf(hit, maskCount, foregroundArea, weight) {
|
|
934
|
+
// 注意:这个分数必须**逐级可比**——精细级别要能用它和粗级别的结果竞争,
|
|
935
|
+
// 否则一旦某级的 bonus 少算一点,粗级别的结果就永远无法被改进,
|
|
936
|
+
// 表现是「所有部件都停在粗级别那档的分辨率上」。bonus 里用的是
|
|
937
|
+
// 「模板掩码 / 该级前景面积」这个比值,它在各档之间是近似不变量。
|
|
938
|
+
const base = hit.score * (0.3 + 0.7 * hit.coverage);
|
|
939
|
+
// 权重必须足够大才能压住「缩小」这条捷径:部件缩得越小,模板越能整块塞进
|
|
940
|
+
// 目标的内部区域,越不需要和轮廓对齐,相关系数反而越高。缩小同时也会让
|
|
941
|
+
// 「模板掩码 / 前景面积」变小,这一项就是把这个被偷走的证据补回来。
|
|
942
|
+
const evidence = Math.sqrt(Math.min(1, maskCount / Math.max(64, foregroundArea)));
|
|
943
|
+
return base + weight * evidence;
|
|
944
|
+
}
|
|
945
|
+
/** 把一张完整分辨率的布尔掩码降采样到某一档。 */
|
|
946
|
+
function downsampleMask(source, sourceWidth, sourceHeight, width, height) {
|
|
947
|
+
const out = new Uint8Array(width * height);
|
|
948
|
+
const hit = new Uint8Array(width * height);
|
|
949
|
+
for (let y = 0; y < height; y++) {
|
|
950
|
+
const sy = Math.min(sourceHeight - 1, Math.floor((y + 0.5) * (sourceHeight / height)));
|
|
951
|
+
for (let x = 0; x < width; x++) {
|
|
952
|
+
const sx = Math.min(sourceWidth - 1, Math.floor((x + 0.5) * (sourceWidth / width)));
|
|
953
|
+
if (source[sy * sourceWidth + sx] === 1)
|
|
954
|
+
hit[y * width + x] = 1;
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
// 3x3 膨胀:遮挡边界往往只差一两个像素,边缘上残留的过渡像素会把
|
|
958
|
+
// 「被挡住」的区域变成细碎的坏证据。
|
|
959
|
+
for (let y = 0; y < height; y++) {
|
|
960
|
+
for (let x = 0; x < width; x++) {
|
|
961
|
+
if (hit[y * width + x] !== 1)
|
|
962
|
+
continue;
|
|
963
|
+
for (let dy = -1; dy <= 1; dy++) {
|
|
964
|
+
const ny = y + dy;
|
|
965
|
+
if (ny < 0 || ny >= height)
|
|
966
|
+
continue;
|
|
967
|
+
for (let dx = -1; dx <= 1; dx++) {
|
|
968
|
+
const nx = x + dx;
|
|
969
|
+
if (nx < 0 || nx >= width)
|
|
970
|
+
continue;
|
|
971
|
+
out[ny * width + nx] = 1;
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
return out;
|
|
977
|
+
}
|
|
978
|
+
/** 生成半平面掩码:`keepRight` 为 true 时标记右半边(供「忽略」使用)。 */
|
|
979
|
+
export function halfPlaneMask(width, height, threshold, keepRight) {
|
|
980
|
+
const out = new Uint8Array(width * height);
|
|
981
|
+
const from = Math.max(0, Math.min(width, Math.floor(threshold)));
|
|
982
|
+
for (let y = 0; y < height; y++) {
|
|
983
|
+
if (keepRight)
|
|
984
|
+
out.fill(1, y * width + from, y * width + width);
|
|
985
|
+
else
|
|
986
|
+
out.fill(1, y * width, y * width + from);
|
|
987
|
+
}
|
|
988
|
+
return out;
|
|
989
|
+
}
|
|
990
|
+
/** 由若干矩形生成一张完整分辨率的「已被占用」掩码。 */
|
|
991
|
+
export function boxMask(width, height, boxes, padding = 0) {
|
|
992
|
+
const out = new Uint8Array(width * height);
|
|
993
|
+
for (const box of boxes) {
|
|
994
|
+
const x1 = Math.max(0, Math.floor(box.x - padding));
|
|
995
|
+
const y1 = Math.max(0, Math.floor(box.y - padding));
|
|
996
|
+
const x2 = Math.min(width, Math.ceil(box.x + box.width + padding));
|
|
997
|
+
const y2 = Math.min(height, Math.ceil(box.y + box.height + padding));
|
|
998
|
+
for (let y = y1; y < y2; y++) {
|
|
999
|
+
out.fill(1, y * width + x1, y * width + x2);
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
return out;
|
|
1003
|
+
}
|
|
1004
|
+
function searchAtLevel(ref, fg, foregroundArea, tpl, stride, window, floorRank, minCoverage, evidenceWeight, ignored) {
|
|
1005
|
+
const rw = ref.width;
|
|
1006
|
+
const rh = ref.height;
|
|
1007
|
+
const x0 = window === undefined ? 1 - tpl.gray.width : Math.max(1 - tpl.gray.width, window.x0);
|
|
1008
|
+
const y0 = window === undefined ? 1 - tpl.gray.height : Math.max(1 - tpl.gray.height, window.y0);
|
|
1009
|
+
const x1 = window === undefined ? rw - 1 : Math.min(window.x1, rw - 1);
|
|
1010
|
+
const y1 = window === undefined ? rh - 1 : Math.min(window.y1, rh - 1);
|
|
1011
|
+
let best;
|
|
1012
|
+
let bestRank = floorRank;
|
|
1013
|
+
for (let oy = y0; oy <= y1; oy += stride) {
|
|
1014
|
+
for (let ox = x0; ox <= x1; ox += stride) {
|
|
1015
|
+
const hit = znccAt(ref, fg, tpl, ox, oy, ignored);
|
|
1016
|
+
if (hit.score <= 0)
|
|
1017
|
+
continue;
|
|
1018
|
+
// 覆盖率门槛在搜索里就卡掉:只压住角色 4% 的一小条模板,相关系数
|
|
1019
|
+
// 照样能接近 1(那十几个像素恰好同色),但它根本没有解释这块部件。
|
|
1020
|
+
if (hit.coverage < minCoverage)
|
|
1021
|
+
continue;
|
|
1022
|
+
const rank = rankOf(hit, tpl.count, foregroundArea, evidenceWeight);
|
|
1023
|
+
if (rank > bestRank) {
|
|
1024
|
+
bestRank = rank;
|
|
1025
|
+
best = { x: ox, y: oy, score: hit.score, coverage: hit.coverage, rank };
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
return best;
|
|
1030
|
+
}
|
|
1031
|
+
/**
|
|
1032
|
+
* 由几何关系估一个「全局缩放」先验。
|
|
1033
|
+
*
|
|
1034
|
+
* 设拆件图相对参考图的缩放为 k(拆件图里量到的尺寸 = k × 参考图里的尺寸):
|
|
1035
|
+
* Σ(拆件图部件面积) ≈ k² × Σ(部件在参考图里的面积) ≈ k² × 1.3 × 角色轮廓面积
|
|
1036
|
+
* 其中 1.3 是「部件之间原本互相重叠」的经验系数。这里返回的是**匹配用的
|
|
1037
|
+
* 缩放 1/k**,也就是「把拆件图的像素换算成参考图像素」的乘数。有了它,搜索
|
|
1038
|
+
* 阶梯只需要覆盖 1/k 的 ±45%,不必再从 0.06 一路盲扫到 1.9。
|
|
1039
|
+
*
|
|
1040
|
+
* 这一步既是**精度**也是**速度**的关键:盲扫的阶梯要么太稀(整个跳过真值,
|
|
1041
|
+
* 相关系数再也补不回来),要么太密(十几倍的无用搜索)。
|
|
1042
|
+
*/
|
|
1043
|
+
export function estimateScaleHint(reference, parts, overlapFactor = 1.3) {
|
|
1044
|
+
const foreground = referenceForeground(reference, 40);
|
|
1045
|
+
let foregroundArea = 0;
|
|
1046
|
+
for (let i = 0; i < foreground.length; i++)
|
|
1047
|
+
if (foreground[i] === 1)
|
|
1048
|
+
foregroundArea++;
|
|
1049
|
+
let partArea = 0;
|
|
1050
|
+
for (const part of parts) {
|
|
1051
|
+
let opaque = 0;
|
|
1052
|
+
for (let i = 0; i < part.width * part.height; i++)
|
|
1053
|
+
if (part.data[i * 4 + 3] > 128)
|
|
1054
|
+
opaque++;
|
|
1055
|
+
partArea += opaque;
|
|
1056
|
+
}
|
|
1057
|
+
if (foregroundArea < 64 || partArea < 64)
|
|
1058
|
+
return 1;
|
|
1059
|
+
// 返回的是**匹配用的缩放**(拆件图 → 参考图),所以取倒数。
|
|
1060
|
+
const hint = Math.sqrt((overlapFactor * foregroundArea) / partArea);
|
|
1061
|
+
if (!Number.isFinite(hint))
|
|
1062
|
+
return 1;
|
|
1063
|
+
return Math.min(12, Math.max(0.05, hint));
|
|
1064
|
+
}
|
|
1065
|
+
/**
|
|
1066
|
+
* 围绕先验缩放的搜索阶梯:9 档、相邻比约 1.11,覆盖 0.65k ~ 1.47k。
|
|
1067
|
+
*
|
|
1068
|
+
* 相邻比不能太粗——真值 0.71 落在 0.61 和 0.75 之间时,两级都差 6% 以上,
|
|
1069
|
+
* 相关系数虽然还高,但还原出来的部件尺寸会明显偏;末级再做 ±10% 的微调补回来。
|
|
1070
|
+
*/
|
|
1071
|
+
export function scaleLadderAround(hint) {
|
|
1072
|
+
// 带宽 ±50%:先验只能保证「数量级对」,具体倍率取决于拆件图里各部件的
|
|
1073
|
+
// 相对尺寸是否忠实——实测同一批素材会差到 30% 以上(先验按「部件面积之和
|
|
1074
|
+
// ≈ 1.3 × 角色轮廓面积」估,而不同画风下这个重叠系数在 1.2~2.8 之间浮动)。
|
|
1075
|
+
// 带宽太窄会直接错过真值;太宽又会让「缩小」那条捷径抬头,所以配合
|
|
1076
|
+
// 覆盖率门槛与证据项一起用(见 rankOf)。
|
|
1077
|
+
// 带宽 ±20%:全局缩放现在是**用图像证据量出来的**(`chooseGlobalScale`),
|
|
1078
|
+
// 实测误差在 20% 以内,所以带宽不用再放宽到 ±50%;带宽越宽,每个部件沿着
|
|
1079
|
+
// 「缩小」那条捷径漂移的空间就越大。
|
|
1080
|
+
const factors = [0.82, 0.9, 1, 1.1, 1.2];
|
|
1081
|
+
return factors.map((factor) => Number((hint * factor).toFixed(5))).filter((value) => value > 0.003);
|
|
1082
|
+
}
|
|
1083
|
+
/** 先验完全不可信时的宽阶梯(兜底重试用)。 */
|
|
1084
|
+
export function wideScaleLadder() {
|
|
1085
|
+
const factors = [0.35, 0.45, 0.58, 0.75, 0.97, 1.25, 1.6, 2.05, 2.6];
|
|
1086
|
+
return factors.map((factor) => Number(factor.toFixed(5)));
|
|
1087
|
+
}
|
|
1088
|
+
/** 没有任何先验时的兜底阶梯(脚本或人工调用时会用到)。 */
|
|
1089
|
+
function defaultScales() {
|
|
1090
|
+
return scaleLadderAround(1);
|
|
1091
|
+
}
|
|
1092
|
+
/** 部件在某一档分辨率下的搜索步长:部件越大步子越大(大部件每一步都贵)。 */
|
|
1093
|
+
function strideAt(part, scale, levelFactor) {
|
|
1094
|
+
const size = Math.min(part.width, part.height) * scale * levelFactor;
|
|
1095
|
+
return Math.max(1, Math.min(6, Math.floor(size / 6)));
|
|
1096
|
+
}
|
|
1097
|
+
/**
|
|
1098
|
+
* 把部件匹配进参考图金字塔。
|
|
1099
|
+
*
|
|
1100
|
+
* 由粗到细,但**只在最粗的一档搜「尺度 × 旋转 × 位置」**:
|
|
1101
|
+
* - 第 0 档:全图扫描,决定尺度与旋转的初值;
|
|
1102
|
+
* - 中间档:冻结尺度与旋转,只在上一级最优点附近的窗口里精修位置;
|
|
1103
|
+
* - 最后一档:位置 + 3 个尺度微调。
|
|
1104
|
+
*
|
|
1105
|
+
* 之所以这样切:中间档如果把 5 个尺度 × 3 个旋转全搜一遍,代价是 15 倍,
|
|
1106
|
+
* 而收益接近零——尺度的大头已经在第 0 档定下来了,后面只需要位置精度。
|
|
1107
|
+
*/
|
|
1108
|
+
export function matchPartInPyramid(pyramid, part, options = {}) {
|
|
1109
|
+
const scales = options.scales ?? defaultScales();
|
|
1110
|
+
const rotations = options.rotations ?? [-10, 0, 10];
|
|
1111
|
+
const minCoverage = options.minCoverage ?? 0.5;
|
|
1112
|
+
const evidenceWeight = options.evidenceWeight ?? 0.35;
|
|
1113
|
+
const scalePrior = options.scalePrior;
|
|
1114
|
+
const scalePriorWeight = options.scalePriorWeight ?? 0.15;
|
|
1115
|
+
const bounds = options.bounds;
|
|
1116
|
+
const partBase = toGrayMask(part, 128);
|
|
1117
|
+
const lastLevel = pyramid.levels.length - 1;
|
|
1118
|
+
const ignoreCache = new Map();
|
|
1119
|
+
const ignoreAt = (level) => {
|
|
1120
|
+
if (options.ignoreFull === undefined)
|
|
1121
|
+
return undefined;
|
|
1122
|
+
const cached = ignoreCache.get(level.gray.width);
|
|
1123
|
+
if (cached !== undefined)
|
|
1124
|
+
return cached;
|
|
1125
|
+
const scaled = downsampleMask(options.ignoreFull, pyramid.width, pyramid.height, level.gray.width, level.gray.height);
|
|
1126
|
+
ignoreCache.set(level.gray.width, scaled);
|
|
1127
|
+
return scaled;
|
|
1128
|
+
};
|
|
1129
|
+
let bestScale = scales[0];
|
|
1130
|
+
let bestRotation = 0;
|
|
1131
|
+
let bestRank = -Infinity;
|
|
1132
|
+
let bestHit;
|
|
1133
|
+
for (let level = 0; level <= lastLevel; level++) {
|
|
1134
|
+
const { gray: ref, foreground, foregroundCount, factor } = pyramid.levels[level];
|
|
1135
|
+
const isCoarse = level === 0;
|
|
1136
|
+
const isLast = level === lastLevel && !isCoarse;
|
|
1137
|
+
const prevStride = level === 0 ? 1 : strideAt(part, bestScale, pyramid.levels[level - 1].factor);
|
|
1138
|
+
const floorRank = isCoarse ? 0 : Math.max(0, bestRank - 0.25);
|
|
1139
|
+
const scaleCandidates = isCoarse
|
|
1140
|
+
? scales
|
|
1141
|
+
: isLast
|
|
1142
|
+
? [0.9, 0.95, 1, 1.05, 1.1].map((factor) => bestScale * factor)
|
|
1143
|
+
: [bestScale];
|
|
1144
|
+
const rotationCandidates = isCoarse
|
|
1145
|
+
? rotations
|
|
1146
|
+
: isLast
|
|
1147
|
+
? [bestRotation - 5, bestRotation, bestRotation + 5]
|
|
1148
|
+
: [bestRotation];
|
|
1149
|
+
for (const rotation of rotationCandidates) {
|
|
1150
|
+
const rotated = rotateGrayMask(partBase, rotation);
|
|
1151
|
+
for (const scale of scaleCandidates) {
|
|
1152
|
+
const tw = rotated.width * scale * factor;
|
|
1153
|
+
const th = rotated.height * scale * factor;
|
|
1154
|
+
if (tw < 3 || th < 3)
|
|
1155
|
+
continue;
|
|
1156
|
+
if (tw > ref.width * 0.98 || th > ref.height * 0.98)
|
|
1157
|
+
continue;
|
|
1158
|
+
const prepared = prepareTemplate(resizeGrayMask(rotated, tw, th));
|
|
1159
|
+
if (prepared === undefined)
|
|
1160
|
+
continue;
|
|
1161
|
+
const stride = isCoarse ? strideAt(part, scale, factor) : 1;
|
|
1162
|
+
let window;
|
|
1163
|
+
if (bounds !== undefined) {
|
|
1164
|
+
// bounds 约束的是**模板中心**,而搜索枚举的是左上角,所以两边各减去半个模板。
|
|
1165
|
+
const halfW = prepared.gray.width / 2;
|
|
1166
|
+
const halfH = prepared.gray.height / 2;
|
|
1167
|
+
window = {
|
|
1168
|
+
x0: Math.round(bounds.x0 * factor - halfW),
|
|
1169
|
+
y0: Math.round(bounds.y0 * factor - halfH),
|
|
1170
|
+
x1: Math.round(bounds.x1 * factor - halfW),
|
|
1171
|
+
y1: Math.round(bounds.y1 * factor - halfH)
|
|
1172
|
+
};
|
|
1173
|
+
}
|
|
1174
|
+
if (!isCoarse && bestHit !== undefined) {
|
|
1175
|
+
const prevFactor = pyramid.levels[level - 1].factor;
|
|
1176
|
+
const ratio = factor / prevFactor;
|
|
1177
|
+
const prevW = Math.max(3, part.width * bestScale * prevFactor);
|
|
1178
|
+
const prevH = Math.max(3, part.height * bestScale * prevFactor);
|
|
1179
|
+
const centerX = (bestHit.x + prevW / 2) * ratio;
|
|
1180
|
+
const centerY = (bestHit.y + prevH / 2) * ratio;
|
|
1181
|
+
const pad = Math.max(prevStride * 3 + 3, 5);
|
|
1182
|
+
const refined = {
|
|
1183
|
+
x0: Math.round(centerX - prepared.gray.width / 2) - pad,
|
|
1184
|
+
y0: Math.round(centerY - prepared.gray.height / 2) - pad,
|
|
1185
|
+
x1: Math.round(centerX - prepared.gray.width / 2) + pad,
|
|
1186
|
+
y1: Math.round(centerY - prepared.gray.height / 2) + pad
|
|
1187
|
+
};
|
|
1188
|
+
// 精修窗口必须与先验框取**交集**:否则某一级的粗定位一旦飘出先验区域,
|
|
1189
|
+
// 后面几级会沿着错误的中心一路精修下去,先验就白给了。
|
|
1190
|
+
window =
|
|
1191
|
+
window === undefined
|
|
1192
|
+
? refined
|
|
1193
|
+
: {
|
|
1194
|
+
x0: Math.max(window.x0, refined.x0),
|
|
1195
|
+
y0: Math.max(window.y0, refined.y0),
|
|
1196
|
+
x1: Math.min(window.x1, refined.x1),
|
|
1197
|
+
y1: Math.min(window.y1, refined.y1)
|
|
1198
|
+
};
|
|
1199
|
+
}
|
|
1200
|
+
const hit = searchAtLevel(ref, foreground, foregroundCount, prepared, stride, window, floorRank, minCoverage, evidenceWeight, ignoreAt(pyramid.levels[level]));
|
|
1201
|
+
if (hit === undefined)
|
|
1202
|
+
continue;
|
|
1203
|
+
const priorPenalty = scalePrior === undefined || scalePrior <= 0 ? 0 : scalePriorWeight * Math.abs(Math.log(scale / scalePrior));
|
|
1204
|
+
if (hit.rank - priorPenalty > bestRank) {
|
|
1205
|
+
bestRank = hit.rank - priorPenalty;
|
|
1206
|
+
bestScale = scale;
|
|
1207
|
+
bestRotation = rotation;
|
|
1208
|
+
bestHit = { x: hit.x, y: hit.y, score: hit.score, coverage: hit.coverage, level };
|
|
1209
|
+
options.onLevel?.({
|
|
1210
|
+
level,
|
|
1211
|
+
edge: ref.width,
|
|
1212
|
+
scale,
|
|
1213
|
+
rotation,
|
|
1214
|
+
score: hit.score,
|
|
1215
|
+
coverage: hit.coverage,
|
|
1216
|
+
rank: hit.rank,
|
|
1217
|
+
x: hit.x,
|
|
1218
|
+
y: hit.y
|
|
1219
|
+
});
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
if (bestHit === undefined || bestHit.score <= 0.05)
|
|
1225
|
+
return undefined;
|
|
1226
|
+
// 收尾:拿最终选中的尺度/旋转,在**最后一档**做一次不设分数门槛的位置精修。
|
|
1227
|
+
// 前面几档的改进受 rank 门槛约束,`bestHit` 可能仍停留在粗级别的坐标系里;
|
|
1228
|
+
// 直接按最后一档的比例去换算会得到一个完全错误的坐标(粗级别 1px ≈ 末级
|
|
1229
|
+
// 7px,差一级就差出几十像素)。所以这里强制把位置落到末级精度上。
|
|
1230
|
+
const last = pyramid.levels[lastLevel];
|
|
1231
|
+
const finalBase = rotateGrayMask(partBase, bestRotation);
|
|
1232
|
+
const finalPrepared = prepareTemplate(resizeGrayMask(finalBase, Math.max(3, part.width * bestScale * last.factor), Math.max(3, part.height * bestScale * last.factor)));
|
|
1233
|
+
if (finalPrepared === undefined)
|
|
1234
|
+
return undefined;
|
|
1235
|
+
const ratio = last.factor / pyramid.levels[0].factor;
|
|
1236
|
+
const seedLevel = bestHit.level;
|
|
1237
|
+
const seedFactor = pyramid.levels[seedLevel].factor;
|
|
1238
|
+
const seedRatio = last.factor / seedFactor;
|
|
1239
|
+
void ratio;
|
|
1240
|
+
const centerX = (bestHit.x + (part.width * bestScale * seedFactor) / 2) * seedRatio;
|
|
1241
|
+
const centerY = (bestHit.y + (part.height * bestScale * seedFactor) / 2) * seedRatio;
|
|
1242
|
+
const pad = Math.max(4, Math.ceil(part.width * bestScale * last.factor * 0.06));
|
|
1243
|
+
const window = {
|
|
1244
|
+
x0: Math.round(centerX - finalPrepared.gray.width / 2) - pad,
|
|
1245
|
+
y0: Math.round(centerY - finalPrepared.gray.height / 2) - pad,
|
|
1246
|
+
x1: Math.round(centerX - finalPrepared.gray.width / 2) + pad,
|
|
1247
|
+
y1: Math.round(centerY - finalPrepared.gray.height / 2) + pad
|
|
1248
|
+
};
|
|
1249
|
+
const ignored = ignoreAt(last);
|
|
1250
|
+
const seedX = Math.round(centerX - finalPrepared.gray.width / 2);
|
|
1251
|
+
const seedY = Math.round(centerY - finalPrepared.gray.height / 2);
|
|
1252
|
+
const seedHit = znccAt(last.gray, last.foreground, finalPrepared, seedX, seedY, ignored);
|
|
1253
|
+
const refined = searchAtLevel(last.gray, last.foreground, last.foregroundCount, finalPrepared, 1, window, -Infinity, 0, evidenceWeight, ignored);
|
|
1254
|
+
// 精修必须是**改进**,不能更差:窗口里可能存在分数更低的杂散位置,
|
|
1255
|
+
// 如果无条件采用精修结果,最后会返回一个比粗级别还糟的摆放(实测表现为
|
|
1256
|
+
// 分数掉到 0 附近、部件尺寸也完全不对)。
|
|
1257
|
+
const chosen = refined !== undefined && refined.score > seedHit.score
|
|
1258
|
+
? refined
|
|
1259
|
+
: { x: seedX, y: seedY, score: seedHit.score, coverage: seedHit.coverage };
|
|
1260
|
+
if (chosen.score <= 0.05)
|
|
1261
|
+
return undefined;
|
|
1262
|
+
if (chosen.coverage < minCoverage)
|
|
1263
|
+
return undefined;
|
|
1264
|
+
return {
|
|
1265
|
+
x: Math.round(chosen.x / last.factor),
|
|
1266
|
+
y: Math.round(chosen.y / last.factor),
|
|
1267
|
+
width: Math.round(part.width * bestScale),
|
|
1268
|
+
height: Math.round(part.height * bestScale),
|
|
1269
|
+
scale: Number(bestScale.toFixed(4)),
|
|
1270
|
+
rotation: Number(bestRotation.toFixed(2)),
|
|
1271
|
+
score: Number(chosen.score.toFixed(4)),
|
|
1272
|
+
coverage: Number(chosen.coverage.toFixed(4)),
|
|
1273
|
+
method: "template"
|
|
1274
|
+
};
|
|
1275
|
+
}
|
|
1276
|
+
/** 便捷入口:单次调用时自己建金字塔(测试与脚本用;批量请复用 `matchPartInPyramid`)。 */
|
|
1277
|
+
export function matchPart(reference, part, options = {}) {
|
|
1278
|
+
const pyramid = buildReferencePyramid(reference, options.longEdge ?? 448, options.foregroundTolerance ?? 40);
|
|
1279
|
+
return matchPartInPyramid(pyramid, part, options);
|
|
1280
|
+
}
|
|
1281
|
+
/**
|
|
1282
|
+
* 逐对遮挡投票定绘制顺序(参考项目 `compute_z_order` 的同款思路)。
|
|
1283
|
+
*
|
|
1284
|
+
* 对每一对重叠的部件,在重叠区域里采样:参考图上这一像素的颜色更像 A 还是
|
|
1285
|
+
* 更像 B?更像谁,谁就压在另一个上面。把每对的胜负累成「深度分」再排序,
|
|
1286
|
+
* 比拓扑排序更抗噪——个别误判不会把整条顺序掀翻。
|
|
1287
|
+
*/
|
|
1288
|
+
export function computeZOrder(reference, parts, scaleTo = 256) {
|
|
1289
|
+
const names = parts.map((part) => part.name);
|
|
1290
|
+
const depth = {};
|
|
1291
|
+
for (const name of names)
|
|
1292
|
+
depth[name] = 0;
|
|
1293
|
+
const pairs = [];
|
|
1294
|
+
const factor = Math.max(reference.width, reference.height) > scaleTo ? scaleTo / Math.max(reference.width, reference.height) : 1;
|
|
1295
|
+
for (let i = 0; i < parts.length; i++) {
|
|
1296
|
+
for (let j = i + 1; j < parts.length; j++) {
|
|
1297
|
+
const a = parts[i];
|
|
1298
|
+
const b = parts[j];
|
|
1299
|
+
const ox1 = Math.max(a.x, b.x);
|
|
1300
|
+
const oy1 = Math.max(a.y, b.y);
|
|
1301
|
+
const ox2 = Math.min(a.x + a.width, b.x + b.width);
|
|
1302
|
+
const oy2 = Math.min(a.y + a.height, b.y + b.height);
|
|
1303
|
+
if (ox1 >= ox2 || oy1 >= oy2)
|
|
1304
|
+
continue;
|
|
1305
|
+
const step = Math.max(1, Math.round(Math.sqrt(((ox2 - ox1) * (oy2 - oy1)) / 400)));
|
|
1306
|
+
let aWins = 0;
|
|
1307
|
+
let bWins = 0;
|
|
1308
|
+
let total = 0;
|
|
1309
|
+
for (let sy = oy1; sy < oy2; sy += step) {
|
|
1310
|
+
for (let sx = ox1; sx < ox2; sx += step) {
|
|
1311
|
+
const rx = Math.round(sx * factor);
|
|
1312
|
+
const ry = Math.round(sy * factor);
|
|
1313
|
+
if (rx < 0 || ry < 0 || rx >= reference.width || ry >= reference.height)
|
|
1314
|
+
continue;
|
|
1315
|
+
const rIdx = (ry * reference.width + rx) * 4;
|
|
1316
|
+
if (reference.data[rIdx + 3] < 128)
|
|
1317
|
+
continue;
|
|
1318
|
+
const ax = sx - a.x;
|
|
1319
|
+
const ay = sy - a.y;
|
|
1320
|
+
const bx = sx - b.x;
|
|
1321
|
+
const by = sy - b.y;
|
|
1322
|
+
if (ax < 0 || ay < 0 || ax >= a.rgba.width || ay >= a.rgba.height)
|
|
1323
|
+
continue;
|
|
1324
|
+
if (bx < 0 || by < 0 || bx >= b.rgba.width || by >= b.rgba.height)
|
|
1325
|
+
continue;
|
|
1326
|
+
const aIdx = (ay * a.rgba.width + ax) * 4;
|
|
1327
|
+
const bIdx = (by * b.rgba.width + bx) * 4;
|
|
1328
|
+
if (a.rgba.data[aIdx + 3] < 128 || b.rgba.data[bIdx + 3] < 128)
|
|
1329
|
+
continue;
|
|
1330
|
+
const da = colorDistanceAt(reference.data, rIdx, a.rgba.data, aIdx);
|
|
1331
|
+
const db = colorDistanceAt(reference.data, rIdx, b.rgba.data, bIdx);
|
|
1332
|
+
total++;
|
|
1333
|
+
if (da < db - 5)
|
|
1334
|
+
aWins++;
|
|
1335
|
+
else if (db < da - 5)
|
|
1336
|
+
bWins++;
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
if (total <= 5)
|
|
1340
|
+
continue;
|
|
1341
|
+
if (aWins > bWins * 1.2) {
|
|
1342
|
+
depth[b.name] -= aWins;
|
|
1343
|
+
depth[a.name] += aWins;
|
|
1344
|
+
pairs.push({ over: a.name, under: b.name, votes: aWins, total });
|
|
1345
|
+
}
|
|
1346
|
+
else if (bWins > aWins * 1.2) {
|
|
1347
|
+
depth[a.name] -= bWins;
|
|
1348
|
+
depth[b.name] += bWins;
|
|
1349
|
+
pairs.push({ over: b.name, under: a.name, votes: bWins, total });
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
const order = [...names].sort((x, y) => depth[x] - depth[y] || x.localeCompare(y));
|
|
1354
|
+
order.forEach((name, index) => {
|
|
1355
|
+
depth[name] = index;
|
|
1356
|
+
});
|
|
1357
|
+
return { order, depth, pairs };
|
|
1358
|
+
}
|
|
1359
|
+
function colorDistanceAt(a, aIdx, b, bIdx) {
|
|
1360
|
+
const dr = a[aIdx] - b[bIdx];
|
|
1361
|
+
const dg = a[aIdx + 1] - b[bIdx + 1];
|
|
1362
|
+
const db = a[aIdx + 2] - b[bIdx + 2];
|
|
1363
|
+
return Math.sqrt(dr * dr + dg * dg + db * db);
|
|
1364
|
+
}
|
|
1365
|
+
/** 按 z 序把部件合成到一张白底(或透明底)画布上。 */
|
|
1366
|
+
export function compositeParts(width, height, parts, background = [255, 255, 255, 255]) {
|
|
1367
|
+
const canvas = createRgba(width, height, background);
|
|
1368
|
+
for (const part of parts)
|
|
1369
|
+
blitRgba(canvas, part.rgba, part.x, part.y);
|
|
1370
|
+
return canvas;
|
|
1371
|
+
}
|
|
1372
|
+
/** 把两张同样高度的图左右拼起来,方便一眼对比「参考图 vs 装配结果」。 */
|
|
1373
|
+
export function sideBySide(left, right, gap = 12, background = [32, 32, 40, 255]) {
|
|
1374
|
+
const height = Math.max(left.height, right.height);
|
|
1375
|
+
const width = left.width + right.width + gap;
|
|
1376
|
+
const canvas = createRgba(width, height, background);
|
|
1377
|
+
blitRgba(canvas, left, 0, Math.floor((height - left.height) / 2));
|
|
1378
|
+
blitRgba(canvas, right, left.width + gap, Math.floor((height - right.height) / 2));
|
|
1379
|
+
return canvas;
|
|
1380
|
+
}
|
|
1381
|
+
/**
|
|
1382
|
+
* 用**图像证据**(而不是几何公式)选一个全局缩放。
|
|
1383
|
+
*
|
|
1384
|
+
* 为什么不能只靠 `estimateScaleHint`:那个公式假设「Σ部件面积 ≈ 1.3 × 角色轮廓
|
|
1385
|
+
* 面积」,而实测这个重叠系数在不同画风之间能从 1.2 飘到 19——鲸鱼女仆那张图
|
|
1386
|
+
* 有裙子、围裙、头发、尾巴层层叠叠,系数约 19,先验直接估出 0.64(真值约 0.34),
|
|
1387
|
+
* 于是一整套定位全错。
|
|
1388
|
+
*
|
|
1389
|
+
* 这里换成直接量:
|
|
1390
|
+
* - 对每个候选缩放,在**最粗的一档**给每个部件找最优位置(只看位置,很便宜);
|
|
1391
|
+
* - 统计两件事:各部件相似度的均值,以及**这些部件合起来盖住了角色轮廓的多大比例**。
|
|
1392
|
+
* 覆盖率是关键:缩放太小的时候每个部件自己都很像(缩进内部当然像),但合起来
|
|
1393
|
+
* 只盖住角色的一小块,覆盖率会掉下来;缩放太大部件会越出轮廓,覆盖率门槛直接
|
|
1394
|
+
* 把它们挡掉。两项相加的峰值就落在真值附近,而且与画风无关。
|
|
1395
|
+
*/
|
|
1396
|
+
export function chooseGlobalScale(pyramid, parts, options = {}) {
|
|
1397
|
+
const candidates = options.candidates ?? (() => {
|
|
1398
|
+
const out = [];
|
|
1399
|
+
for (let i = 0; i < 12; i++)
|
|
1400
|
+
out.push(Number((0.06 * (2.0 / 0.06) ** (i / 11)).toFixed(4)));
|
|
1401
|
+
return out;
|
|
1402
|
+
})();
|
|
1403
|
+
const evidenceWeight = options.evidenceWeight ?? 0.35;
|
|
1404
|
+
const minCoverage = options.minCoverage ?? 0.5;
|
|
1405
|
+
// 覆盖率只是**次要**信号:角色占满画面时,缩放越大掩码盖住的角色像素越多,
|
|
1406
|
+
// 覆盖率会单调上涨(实测 1.45 倍时仍能到 0.93),权重给大了峰值就会被推到
|
|
1407
|
+
// 明显偏大的尺度上。主信号用「各部件相似度的均值」——它的峰值实测落在真值
|
|
1408
|
+
// 附近,覆盖率只用来在分数接近时偏向「更完整地铺满角色」的那个。
|
|
1409
|
+
const coverageWeight = options.coverageWeight ?? 0.15;
|
|
1410
|
+
const level = pyramid.levels[0];
|
|
1411
|
+
const prepared = parts.map((part) => toGrayMask(part, 128));
|
|
1412
|
+
const foregroundArea = Math.max(1, level.foregroundCount);
|
|
1413
|
+
const probes = [];
|
|
1414
|
+
let best;
|
|
1415
|
+
const probeScale = (target, source, scale, config) => {
|
|
1416
|
+
const level = target.levels[0];
|
|
1417
|
+
let sum = 0;
|
|
1418
|
+
let counted = 0;
|
|
1419
|
+
const covered = new Uint8Array(level.gray.width * level.gray.height);
|
|
1420
|
+
for (const base of source) {
|
|
1421
|
+
const tw = base.width * scale * level.factor;
|
|
1422
|
+
const th = base.height * scale * level.factor;
|
|
1423
|
+
if (tw < 3 || th < 3 || tw > level.gray.width * 0.98 || th > level.gray.height * 0.98) {
|
|
1424
|
+
counted++;
|
|
1425
|
+
continue;
|
|
1426
|
+
}
|
|
1427
|
+
const tpl = prepareTemplate(resizeGrayMask(base, tw, th));
|
|
1428
|
+
counted++;
|
|
1429
|
+
if (tpl === undefined)
|
|
1430
|
+
continue;
|
|
1431
|
+
const stride = Math.max(1, Math.min(4, Math.floor(Math.min(tpl.gray.width, tpl.gray.height) / 6)));
|
|
1432
|
+
const hit = searchAtLevel(level.gray, level.foreground, config.foregroundArea, tpl, stride, undefined, 0, config.minCoverage, config.evidenceWeight);
|
|
1433
|
+
if (hit === undefined)
|
|
1434
|
+
continue;
|
|
1435
|
+
sum += hit.score;
|
|
1436
|
+
// 覆盖率按**模板掩码**累计,不能按包围盒:包围盒随缩放单调变大,
|
|
1437
|
+
// 覆盖率也会跟着单调涨,峰值永远落在最大的那个候选上。用掩码时,
|
|
1438
|
+
// 放大过头会让掩码越出角色轮廓、per-part 覆盖率掉到门槛以下被直接丢弃,
|
|
1439
|
+
// 于是覆盖率曲线先升后降,峰值才落在真值附近。
|
|
1440
|
+
for (let k = 0; k < tpl.count; k++) {
|
|
1441
|
+
const rx = hit.x + tpl.dx[k];
|
|
1442
|
+
if (rx < 0 || rx >= level.gray.width)
|
|
1443
|
+
continue;
|
|
1444
|
+
const ry = hit.y + tpl.dy[k];
|
|
1445
|
+
if (ry < 0 || ry >= level.gray.height)
|
|
1446
|
+
continue;
|
|
1447
|
+
const idx = ry * level.gray.width + rx;
|
|
1448
|
+
if (level.foreground[idx] === 1)
|
|
1449
|
+
covered[idx] = 1;
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
let coveredCount = 0;
|
|
1453
|
+
for (let i = 0; i < covered.length; i++)
|
|
1454
|
+
if (covered[i] === 1)
|
|
1455
|
+
coveredCount++;
|
|
1456
|
+
return {
|
|
1457
|
+
scale,
|
|
1458
|
+
meanScore: Number((sum / Math.max(1, counted)).toFixed(4)),
|
|
1459
|
+
coverage: Number((coveredCount / config.foregroundArea).toFixed(4))
|
|
1460
|
+
};
|
|
1461
|
+
};
|
|
1462
|
+
for (const scale of candidates) {
|
|
1463
|
+
const probe = probeScale(pyramid, prepared, scale, { evidenceWeight, minCoverage, foregroundArea });
|
|
1464
|
+
probes.push(probe);
|
|
1465
|
+
const total = probe.meanScore + coverageWeight * probe.coverage;
|
|
1466
|
+
if (best === undefined || total > best.total)
|
|
1467
|
+
best = { scale: probe.scale, meanScore: probe.meanScore, coverage: probe.coverage, total };
|
|
1468
|
+
}
|
|
1469
|
+
if (best === undefined)
|
|
1470
|
+
return { scale: 1, meanScore: 0, coverage: 0, probes };
|
|
1471
|
+
// 第二轮:在第一轮最优值的**相邻两个候选之间**再插 4 个点。第一轮是 12 个
|
|
1472
|
+
// 跨 33 倍的候选(相邻比 1.34),直接用它当缩放会有 ±15% 的量化误差——
|
|
1473
|
+
// 对小腿/脚这类小部件就是「明显偏小」。第二轮把误差压到 ±3% 以内,代价只是
|
|
1474
|
+
// 4 次探测。
|
|
1475
|
+
const sorted = [...candidates].sort((a, b) => a - b);
|
|
1476
|
+
const index = sorted.indexOf(best.scale);
|
|
1477
|
+
if (index >= 0) {
|
|
1478
|
+
const lo = sorted[Math.max(0, index - 1)];
|
|
1479
|
+
const hi = sorted[Math.min(sorted.length - 1, index + 1)];
|
|
1480
|
+
if (hi > lo) {
|
|
1481
|
+
for (let i = 1; i <= 4; i++) {
|
|
1482
|
+
const scale = Number((lo + ((hi - lo) * i) / 5).toFixed(4));
|
|
1483
|
+
if (candidates.includes(scale) || scale === best.scale)
|
|
1484
|
+
continue;
|
|
1485
|
+
const probe = probeScale(pyramid, prepared, scale, { evidenceWeight, minCoverage, foregroundArea });
|
|
1486
|
+
probes.push(probe);
|
|
1487
|
+
const total = probe.meanScore + coverageWeight * probe.coverage;
|
|
1488
|
+
if (total > best.total)
|
|
1489
|
+
best = { scale, meanScore: probe.meanScore, coverage: probe.coverage, total };
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
return { scale: best.scale, meanScore: Number(best.meanScore.toFixed(4)), coverage: Number(best.coverage.toFixed(4)), probes };
|
|
1494
|
+
}
|
|
1495
|
+
/** 在完整分辨率上评估一个已有摆放的得分(不搜索,只打分)。 */
|
|
1496
|
+
export function scorePlacement(reference, part, placement, foregroundTolerance = 40, ignored) {
|
|
1497
|
+
const gray = toGrayMask(reference, 128);
|
|
1498
|
+
const foreground = referenceForeground(reference, foregroundTolerance);
|
|
1499
|
+
const prepared = prepareTemplate(resizeGrayMask(rotateGrayMask(toGrayMask(part, 128), placement.rotation), Math.max(3, placement.width), Math.max(3, placement.height)));
|
|
1500
|
+
if (prepared === undefined)
|
|
1501
|
+
return undefined;
|
|
1502
|
+
return znccAt(gray, foreground, prepared, Math.round(placement.x), Math.round(placement.y), ignored);
|
|
1503
|
+
}
|
|
1504
|
+
function overlapRatio(a, b) {
|
|
1505
|
+
const ox = Math.max(0, Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x));
|
|
1506
|
+
const oy = Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y));
|
|
1507
|
+
const inter = ox * oy;
|
|
1508
|
+
const smaller = Math.min(a.width * a.height, b.width * b.height);
|
|
1509
|
+
return smaller <= 0 ? 0 : inter / smaller;
|
|
1510
|
+
}
|
|
1511
|
+
/** 把若干矩形涂成底色,得到一份「这些地方已经有人占了」的参考图。 */
|
|
1512
|
+
function blankRegions(reference, boxes, tolerance) {
|
|
1513
|
+
const copy = { data: Buffer.from(reference.data), width: reference.width, height: reference.height };
|
|
1514
|
+
const background = detectBackground(reference);
|
|
1515
|
+
for (const box of boxes) {
|
|
1516
|
+
const x1 = Math.max(0, Math.round(box.x - tolerance));
|
|
1517
|
+
const y1 = Math.max(0, Math.round(box.y - tolerance));
|
|
1518
|
+
const x2 = Math.min(reference.width, Math.round(box.x + box.width + tolerance));
|
|
1519
|
+
const y2 = Math.min(reference.height, Math.round(box.y + box.height + tolerance));
|
|
1520
|
+
for (let y = y1; y < y2; y++) {
|
|
1521
|
+
for (let x = x1; x < x2; x++) {
|
|
1522
|
+
const idx = (y * reference.width + x) * 4;
|
|
1523
|
+
copy.data[idx] = background[0];
|
|
1524
|
+
copy.data[idx + 1] = background[1];
|
|
1525
|
+
copy.data[idx + 2] = background[2];
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
return copy;
|
|
1530
|
+
}
|
|
1531
|
+
/**
|
|
1532
|
+
* 一次求解全部部件的装配位置。
|
|
1533
|
+
*
|
|
1534
|
+
* 三件事按顺序做:
|
|
1535
|
+
* ① 用几何先验定出缩放阶梯(见 `estimateScaleHint`),逐个匹配;
|
|
1536
|
+
* ② 失败的部件用宽阶梯兜底再试一次——先验虽然通常很准,但拆件图被生图模型
|
|
1537
|
+
* 画得比例失调时也会失手,兜底比直接报失败好;
|
|
1538
|
+
* ③ **冲突消解**:左右对称的部件(比如两条大腿)颜色形状几乎一样,
|
|
1539
|
+
* 纯靠外观匹配会把它们都放到同一侧。这里按得分从高到低逐个确认,后确认的
|
|
1540
|
+
* 部件如果和已确认的区域重叠超过一半,就把那块地方「涂掉」重新匹配一次,
|
|
1541
|
+
* 逼它去找另一个候选位置。
|
|
1542
|
+
*/
|
|
1543
|
+
export function solveLayout(reference, parts, options = {}) {
|
|
1544
|
+
const longEdge = options.longEdge ?? 448;
|
|
1545
|
+
const foregroundTolerance = options.foregroundTolerance ?? 40;
|
|
1546
|
+
const evidenceWeight = options.evidenceWeight ?? 0.35;
|
|
1547
|
+
const minCoverage = options.minCoverage ?? 0.5;
|
|
1548
|
+
const pyramid = buildReferencePyramid(reference, longEdge, foregroundTolerance);
|
|
1549
|
+
// 先按图像证据选全局缩放,几何公式只作为兜底:公式里的「重叠系数」随画风
|
|
1550
|
+
// 能从 1.2 飘到 19,靠它定阶梯中心会把整批部件都定错。
|
|
1551
|
+
const chosen = chooseGlobalScale(pyramid, parts.map((part) => part.rgba));
|
|
1552
|
+
// 只在「连一个像样的候选都没有」时才回退到几何公式。覆盖率不能作为否决条件:
|
|
1553
|
+
// 角色只占画面一小部分时,正确尺度下的覆盖率本来就不高(实测 0.29)。
|
|
1554
|
+
const hint = chosen.meanScore >= 0.2 ? chosen.scale : estimateScaleHint(reference, parts.map((part) => part.rgba));
|
|
1555
|
+
const narrow = scaleLadderAround(hint);
|
|
1556
|
+
const wide = wideScaleLadder();
|
|
1557
|
+
const placements = {};
|
|
1558
|
+
const failed = [];
|
|
1559
|
+
const attempts = new Map();
|
|
1560
|
+
const hints = options.hints ?? {};
|
|
1561
|
+
const hintMargin = options.hintMargin ?? 0.35;
|
|
1562
|
+
// 先验隐含的缩放:拿「先验框尺寸 / 部件像素尺寸」的中位数当全局倍率。
|
|
1563
|
+
// 这比面积公式与覆盖率探测都直接——它就是「模型说这块该多大」。
|
|
1564
|
+
const hintedScales = [];
|
|
1565
|
+
for (const part of parts) {
|
|
1566
|
+
const hintBox = hints[part.name];
|
|
1567
|
+
if (hintBox === undefined || hintBox.width <= 0 || hintBox.height <= 0)
|
|
1568
|
+
continue;
|
|
1569
|
+
hintedScales.push(hintBox.width / part.rgba.width, hintBox.height / part.rgba.height);
|
|
1570
|
+
}
|
|
1571
|
+
const hintedScale = hintedScales.length >= 2 ? hintedScales.slice().sort((a, b) => a - b)[Math.floor(hintedScales.length / 2)] : undefined;
|
|
1572
|
+
/**
|
|
1573
|
+
* 某个部件的搜索框。**每一处重新匹配都要带上它**——先验只约束「初次匹配」
|
|
1574
|
+
* 是不够的:后面的冲突消解 / 遮挡修正 / 镜像消解都会重新搜一次位置,漏掉任何
|
|
1575
|
+
* 一处,那一处就能把部件挪到先验框外面去(实测 16 个先验里 13 个最终出框)。
|
|
1576
|
+
*/
|
|
1577
|
+
const boundsOf = (name) => {
|
|
1578
|
+
const box = hints[name];
|
|
1579
|
+
if (box === undefined)
|
|
1580
|
+
return undefined;
|
|
1581
|
+
return {
|
|
1582
|
+
x0: box.x - box.width * hintMargin,
|
|
1583
|
+
y0: box.y - box.height * hintMargin,
|
|
1584
|
+
x1: box.x + box.width * (1 + hintMargin),
|
|
1585
|
+
y1: box.y + box.height * (1 + hintMargin)
|
|
1586
|
+
};
|
|
1587
|
+
};
|
|
1588
|
+
for (const part of parts) {
|
|
1589
|
+
const hintBox = hints[part.name];
|
|
1590
|
+
const bounds = boundsOf(part.name);
|
|
1591
|
+
// 有先验时把缩放阶梯收窄到先验倍率附近(模型给的尺寸本来就比我们的估计准),
|
|
1592
|
+
// 没有先验才回到全局阶梯。
|
|
1593
|
+
const ownScale = hintBox === undefined ? undefined : (hintBox.width / part.rgba.width + hintBox.height / part.rgba.height) / 2;
|
|
1594
|
+
const ladder = ownScale !== undefined && ownScale > 0.004 ? scaleLadderAround(ownScale).slice(1, 4) : narrow;
|
|
1595
|
+
let result = matchPartInPyramid(pyramid, part.rgba, {
|
|
1596
|
+
scales: ladder,
|
|
1597
|
+
evidenceWeight,
|
|
1598
|
+
minCoverage,
|
|
1599
|
+
scalePrior: ownScale ?? hintedScale ?? hint,
|
|
1600
|
+
bounds
|
|
1601
|
+
});
|
|
1602
|
+
let tries = 1;
|
|
1603
|
+
let retried = false;
|
|
1604
|
+
if (result === undefined) {
|
|
1605
|
+
// 兜底:先验可能被「拆件图比例失调」带偏,换成宽阶梯再找一次。
|
|
1606
|
+
//
|
|
1607
|
+
// 但门槛必须**显著更高**:宽阶梯横跨 7 倍尺度,在低细节(平涂)美术上
|
|
1608
|
+
// 几乎总能找到一个「看起来还行」的错误位置,分数还不低。实测把阈值放到
|
|
1609
|
+
// 0.62 之后,这类假阳性被挡掉了,真正比例失调的部件仍然能找到。
|
|
1610
|
+
const retry = matchPartInPyramid(pyramid, part.rgba, {
|
|
1611
|
+
scales: wide,
|
|
1612
|
+
evidenceWeight,
|
|
1613
|
+
minCoverage: Math.max(0.5, minCoverage),
|
|
1614
|
+
scalePrior: hintedScale ?? hint,
|
|
1615
|
+
// 兜底重试也**不能放开先验框**:放开了就等于回到全图盲搜,
|
|
1616
|
+
// 而那正是我们要修的东西。只在框内放宽缩放。
|
|
1617
|
+
bounds
|
|
1618
|
+
});
|
|
1619
|
+
if (retry !== undefined && retry.score >= 0.62)
|
|
1620
|
+
result = retry;
|
|
1621
|
+
tries = 2;
|
|
1622
|
+
retried = true;
|
|
1623
|
+
}
|
|
1624
|
+
attempts.set(part.name, tries);
|
|
1625
|
+
options.onPart?.(part.name, { result, attempts: tries, retried });
|
|
1626
|
+
if (result === undefined) {
|
|
1627
|
+
failed.push(part.name);
|
|
1628
|
+
continue;
|
|
1629
|
+
}
|
|
1630
|
+
placements[part.name] = result;
|
|
1631
|
+
}
|
|
1632
|
+
// ③ 冲突消解:按得分从高到低确认,重叠过多的后到者被要求换位置。
|
|
1633
|
+
const resolved = [];
|
|
1634
|
+
const ranked = Object.entries(placements).sort((a, b) => b[1].score - a[1].score);
|
|
1635
|
+
const accepted = [];
|
|
1636
|
+
for (const [name, box] of ranked) {
|
|
1637
|
+
const clash = accepted.find((item) => overlapRatio(item.box, box) > 0.55);
|
|
1638
|
+
if (clash === undefined) {
|
|
1639
|
+
accepted.push({ name, box });
|
|
1640
|
+
continue;
|
|
1641
|
+
}
|
|
1642
|
+
const part = parts.find((item) => item.name === name);
|
|
1643
|
+
if (part === undefined)
|
|
1644
|
+
continue;
|
|
1645
|
+
const blanked = blankRegions(reference, [clash.box], Math.max(6, Math.round(Math.max(clash.box.width, clash.box.height) * 0.05)));
|
|
1646
|
+
const second = matchPartInPyramid(buildReferencePyramid(blanked, longEdge, foregroundTolerance), part.rgba, {
|
|
1647
|
+
scales: narrow,
|
|
1648
|
+
evidenceWeight,
|
|
1649
|
+
minCoverage: Math.max(0.4, minCoverage - 0.1),
|
|
1650
|
+
scalePrior: hint,
|
|
1651
|
+
bounds: boundsOf(name)
|
|
1652
|
+
});
|
|
1653
|
+
// 冲突就是硬证据:两块部件都指向同一处,最多只有一个是对的。
|
|
1654
|
+
// 所以这里不要求「新位置得分更高」,只要新位置本身站得住就采纳。
|
|
1655
|
+
if (second !== undefined && second.score >= Math.max(0.4, box.score - 0.25)) {
|
|
1656
|
+
placements[name] = second;
|
|
1657
|
+
accepted.push({ name, box: second });
|
|
1658
|
+
resolved.push(name);
|
|
1659
|
+
}
|
|
1660
|
+
else {
|
|
1661
|
+
// 换不成更好的位置就保留原样:宁可让用户看到重叠,也不要悄悄挪到错误的地方。
|
|
1662
|
+
accepted.push({ name, box });
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
// ④ 遮挡感知再匹配。
|
|
1666
|
+
//
|
|
1667
|
+
// 每个部件只应该用「没被前面部件挡住」的像素来定位。不做这一步时,匹配会自动
|
|
1668
|
+
// 缩到可见区域:躯干被头挡住顶部就整体下移十几像素,大腿被躯干挡住上半就整体
|
|
1669
|
+
// 下移——这是自动装配里最大的一类系统误差,而且它是**系统性**的,用户逐个微调
|
|
1670
|
+
// 也很烦。这里用第一遍得到的 z 序,把「挡在它前面的部件」先从参考图里涂掉,
|
|
1671
|
+
// 再重新匹配一次;只有得分确实变好才采纳。
|
|
1672
|
+
const placedForOrder = [];
|
|
1673
|
+
for (const [name, box] of Object.entries(placements)) {
|
|
1674
|
+
const part = parts.find((item) => item.name === name);
|
|
1675
|
+
if (part === undefined)
|
|
1676
|
+
continue;
|
|
1677
|
+
placedForOrder.push({
|
|
1678
|
+
name,
|
|
1679
|
+
x: box.x,
|
|
1680
|
+
y: box.y,
|
|
1681
|
+
width: box.width,
|
|
1682
|
+
height: box.height,
|
|
1683
|
+
rgba: resizeRgba(part.rgba, Math.max(1, box.width), Math.max(1, box.height))
|
|
1684
|
+
});
|
|
1685
|
+
}
|
|
1686
|
+
const moved = [];
|
|
1687
|
+
const drawOrder = options.drawOrder ?? [];
|
|
1688
|
+
if (placedForOrder.length >= 2 && drawOrder.length > 0) {
|
|
1689
|
+
const rank = new Map(drawOrder.map((name, index) => [name, index]));
|
|
1690
|
+
for (const name of drawOrder) {
|
|
1691
|
+
const current = placements[name];
|
|
1692
|
+
const part = parts.find((item) => item.name === name);
|
|
1693
|
+
if (current === undefined || part === undefined)
|
|
1694
|
+
continue;
|
|
1695
|
+
const front = placedForOrder.filter((item) => (rank.get(item.name) ?? -1) > (rank.get(name) ?? -1));
|
|
1696
|
+
if (front.length === 0)
|
|
1697
|
+
continue;
|
|
1698
|
+
const tolerance = Math.max(4, Math.round(Math.max(current.width, current.height) * 0.04));
|
|
1699
|
+
const ignore = boxMask(reference.width, reference.height, front, tolerance);
|
|
1700
|
+
const before = scorePlacement(reference, part.rgba, current, foregroundTolerance, ignore);
|
|
1701
|
+
const candidate = matchPartInPyramid(pyramid, part.rgba, {
|
|
1702
|
+
scales: [current.scale * 0.9, current.scale * 0.95, current.scale, current.scale * 1.05, current.scale * 1.1],
|
|
1703
|
+
rotations: [-5, 0, 5].map((delta) => current.rotation + delta),
|
|
1704
|
+
evidenceWeight,
|
|
1705
|
+
minCoverage: Math.max(0.3, minCoverage - 0.2),
|
|
1706
|
+
ignoreFull: ignore,
|
|
1707
|
+
scalePrior: hint,
|
|
1708
|
+
// 遮挡修正同样不能越出先验框:它只该在框内挪一点,而不是重新做一次全局搜索。
|
|
1709
|
+
bounds: boundsOf(name)
|
|
1710
|
+
});
|
|
1711
|
+
if (candidate === undefined || before === undefined)
|
|
1712
|
+
continue;
|
|
1713
|
+
// 两边都在「涂掉前面部件」的参考图上比,才是公平比较。
|
|
1714
|
+
// 门槛放得比较保守(+0.08):这一步是**修正**而不是重新搜索,
|
|
1715
|
+
// 证据不足时宁可保留原样让用户自己拖,也好过悄悄挪到另一个错位置。
|
|
1716
|
+
if (candidate.score > before.score + 0.03) {
|
|
1717
|
+
placements[name] = candidate;
|
|
1718
|
+
moved.push(name);
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
// ⑤ 消除「镜像部件挤在同一侧」。
|
|
1723
|
+
//
|
|
1724
|
+
// 两条大腿、两只手这类左右对称的部件,在 ZNCC 眼里几乎可以互换——相关系数
|
|
1725
|
+
// 本来就减掉了均值,纯色平涂的左右肢连明暗差都吃不到。结果是两块都被放在
|
|
1726
|
+
// 同一侧,另一侧空着,必然丢一块。
|
|
1727
|
+
//
|
|
1728
|
+
// 这里用一条**与左右命名约定无关**的几何约束来拆:同一组镜像部件里,得分低的
|
|
1729
|
+
// 那一块必须落到角色中线的另一侧去。注意「哪个名字对应画面哪一侧」在整个插件
|
|
1730
|
+
// 里都不需要知道,只需要它们分居两侧。
|
|
1731
|
+
const characterBox = alphaBounds(reference) ?? { x: 0, y: 0, width: reference.width, height: reference.height };
|
|
1732
|
+
const centerX = characterBox.x + characterBox.width / 2;
|
|
1733
|
+
const mirroredPairs = [];
|
|
1734
|
+
const names = Object.keys(placements);
|
|
1735
|
+
for (let i = 0; i < names.length; i++) {
|
|
1736
|
+
for (let j = i + 1; j < names.length; j++) {
|
|
1737
|
+
const a = names[i];
|
|
1738
|
+
const b = names[j];
|
|
1739
|
+
const swap = a.startsWith("left-") && b.startsWith("right-") ? a.slice(5) === b.slice(6) : false;
|
|
1740
|
+
if (!swap)
|
|
1741
|
+
continue;
|
|
1742
|
+
// 挤在一起要拆开;分居两侧但可能「左右弄反」也要复查。
|
|
1743
|
+
mirroredPairs.push([a, b]);
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
for (const [a, b] of mirroredPairs) {
|
|
1747
|
+
const partA = parts.find((item) => item.name === a);
|
|
1748
|
+
const partB = parts.find((item) => item.name === b);
|
|
1749
|
+
if (partA === undefined || partB === undefined)
|
|
1750
|
+
continue;
|
|
1751
|
+
const centreOf = (box) => box.x + box.width / 2;
|
|
1752
|
+
if (Math.sign(centreOf(placements[a]) - centerX) !== Math.sign(centreOf(placements[b]) - centerX)) {
|
|
1753
|
+
// 已经分居两侧了,但「哪块在哪一侧」还要定一下:外观几乎一样时,逐个
|
|
1754
|
+
// 打分才是唯一有信息量的比较。这是一次 2×2 指派,把两种配对的总分一比。
|
|
1755
|
+
const scoreAt = (part, box) => scorePlacement(reference, part, box, foregroundTolerance)?.score ?? 0;
|
|
1756
|
+
const keep = scoreAt(partA.rgba, placements[a]) + scoreAt(partB.rgba, placements[b]);
|
|
1757
|
+
const swap = scoreAt(partA.rgba, placements[b]) + scoreAt(partB.rgba, placements[a]);
|
|
1758
|
+
if (swap > keep + 0.02) {
|
|
1759
|
+
const boxA = placements[a];
|
|
1760
|
+
placements[a] = placements[b];
|
|
1761
|
+
placements[b] = boxA;
|
|
1762
|
+
if (!resolved.includes(a))
|
|
1763
|
+
resolved.push(a);
|
|
1764
|
+
if (!resolved.includes(b))
|
|
1765
|
+
resolved.push(b);
|
|
1766
|
+
}
|
|
1767
|
+
continue;
|
|
1768
|
+
}
|
|
1769
|
+
// 两块都在同一侧:把输的那块沿中线镜像过去。
|
|
1770
|
+
const scoreA = scorePlacement(reference, partA.rgba, placements[a], foregroundTolerance)?.score ?? 0;
|
|
1771
|
+
const scoreB = scorePlacement(reference, partB.rgba, placements[b], foregroundTolerance)?.score ?? 0;
|
|
1772
|
+
const loser = scoreA >= scoreB ? b : a;
|
|
1773
|
+
const loserPart = loser === a ? partA : partB;
|
|
1774
|
+
const occupied = centreOf(placements[loser]) >= centerX;
|
|
1775
|
+
// 把「目前那一侧」整片忽略掉,逼它去另一侧找位置。
|
|
1776
|
+
const ignore = halfPlaneMask(reference.width, reference.height, centerX, occupied);
|
|
1777
|
+
// 首选做法:把落单的那块**沿角色中线镜像**过去。
|
|
1778
|
+
// 对称角色的左右肢本来就该关于中线互为镜像,这个位移是确定的、可复现的,
|
|
1779
|
+
// 比「再搜一次」稳得多(再搜一次往往会落到躯干之类的错误位置)。
|
|
1780
|
+
const box = placements[loser];
|
|
1781
|
+
const mirrored = { ...box, x: Math.round(2 * centerX - (box.x + box.width)) };
|
|
1782
|
+
const mirroredFree = mirrored.x >= -box.width * 0.5 &&
|
|
1783
|
+
!Object.entries(placements).some(([other, otherBox]) => other !== loser && overlapRatio(otherBox, mirrored) > 0.5);
|
|
1784
|
+
if (mirroredFree) {
|
|
1785
|
+
placements[loser] = mirrored;
|
|
1786
|
+
if (!resolved.includes(loser))
|
|
1787
|
+
resolved.push(loser);
|
|
1788
|
+
continue;
|
|
1789
|
+
}
|
|
1790
|
+
// 兜底:镜像位置被占用时,才回到「把这一侧整片忽略再搜一次」。
|
|
1791
|
+
const alternative = matchPartInPyramid(pyramid, loserPart.rgba, {
|
|
1792
|
+
scales: narrow,
|
|
1793
|
+
evidenceWeight,
|
|
1794
|
+
minCoverage: Math.max(0.35, minCoverage - 0.15),
|
|
1795
|
+
ignoreFull: ignore,
|
|
1796
|
+
scalePrior: hint,
|
|
1797
|
+
bounds: boundsOf(loser)
|
|
1798
|
+
});
|
|
1799
|
+
if (alternative === undefined || alternative.score < 0.45)
|
|
1800
|
+
continue;
|
|
1801
|
+
if (Math.sign(alternative.x + alternative.width / 2 - centerX) === Math.sign(centreOf(placements[loser]) - centerX))
|
|
1802
|
+
continue;
|
|
1803
|
+
placements[loser] = alternative;
|
|
1804
|
+
if (!resolved.includes(loser))
|
|
1805
|
+
resolved.push(loser);
|
|
1806
|
+
}
|
|
1807
|
+
return { hint, scaleProbes: chosen.probes, hintedCount: Object.keys(hints).filter((name) => parts.some((part) => part.name === name)).length, placements, failed, resolved, moved };
|
|
1808
|
+
}
|
|
1809
|
+
/**
|
|
1810
|
+
* 按**真实像素邻近距离**把连通域分组,而不是按包围盒。
|
|
1811
|
+
*
|
|
1812
|
+
* 为什么不能用包围盒:头发那块连通域的包围盒横跨了大半张图,和领子、上衣的包围盒
|
|
1813
|
+
* 天然重叠,按包围盒一判就是「相邻」,再经过单链传递(A~B、B~C ⇒ A~C)整张图会被
|
|
1814
|
+
* 串成一块——实测把角色串成了一个 1937×1156 的「头」。
|
|
1815
|
+
*
|
|
1816
|
+
* 这里改成从每个连通域的**边界像素**向外搜 `gap` 像素,只有真的找到另一块的像素才
|
|
1817
|
+
* 合并;只扫边界像素(而不是全部前景像素),代价从 O(面积×gap²) 降到 O(周长×gap²)。
|
|
1818
|
+
*/
|
|
1819
|
+
export function groupComponentsByProximity(labels, width, height, gap) {
|
|
1820
|
+
const parent = new Int32Array(0);
|
|
1821
|
+
const ids = new Set();
|
|
1822
|
+
for (let i = 0; i < labels.length; i++)
|
|
1823
|
+
if (labels[i] >= 0)
|
|
1824
|
+
ids.add(labels[i]);
|
|
1825
|
+
const maxLabel = ids.size === 0 ? 0 : Math.max(...ids) + 1;
|
|
1826
|
+
const find = (map, index) => (map[index] === index ? index : (map[index] = find(map, map[index])));
|
|
1827
|
+
const roots = new Int32Array(maxLabel);
|
|
1828
|
+
for (let i = 0; i < maxLabel; i++)
|
|
1829
|
+
roots[i] = i;
|
|
1830
|
+
const union = (a, b) => {
|
|
1831
|
+
const ra = find(roots, a);
|
|
1832
|
+
const rb = find(roots, b);
|
|
1833
|
+
if (ra !== rb)
|
|
1834
|
+
roots[rb] = ra;
|
|
1835
|
+
};
|
|
1836
|
+
const offset = Math.max(1, Math.round(gap));
|
|
1837
|
+
for (let y = 0; y < height; y++) {
|
|
1838
|
+
for (let x = 0; x < width; x++) {
|
|
1839
|
+
const index = y * width + x;
|
|
1840
|
+
const label = labels[index];
|
|
1841
|
+
if (label < 0)
|
|
1842
|
+
continue;
|
|
1843
|
+
// 只处理边界像素:右/下邻居已经属于别块,或者自己是前景而邻居是背景。
|
|
1844
|
+
const right = x + 1 < width ? labels[index + 1] : -1;
|
|
1845
|
+
const down = y + 1 < height ? labels[index + width] : -1;
|
|
1846
|
+
if (right >= 0 && right !== label)
|
|
1847
|
+
union(label, right);
|
|
1848
|
+
if (down >= 0 && down !== label)
|
|
1849
|
+
union(label, down);
|
|
1850
|
+
if (right >= 0 && down >= 0)
|
|
1851
|
+
continue;
|
|
1852
|
+
// 边界像素才向外找:跳过中间的空隙,仍能认出「差一点点就接上」的两块。
|
|
1853
|
+
for (let dy = -offset; dy <= offset; dy++) {
|
|
1854
|
+
const ny = y + dy;
|
|
1855
|
+
if (ny < 0 || ny >= height)
|
|
1856
|
+
continue;
|
|
1857
|
+
for (let dx = -offset; dx <= offset; dx++) {
|
|
1858
|
+
const nx = x + dx;
|
|
1859
|
+
if (nx < 0 || nx >= width)
|
|
1860
|
+
continue;
|
|
1861
|
+
const other = labels[ny * width + nx];
|
|
1862
|
+
if (other >= 0 && other !== label)
|
|
1863
|
+
union(label, other);
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1867
|
+
}
|
|
1868
|
+
const out = new Array(maxLabel).fill(-1);
|
|
1869
|
+
for (const id of ids)
|
|
1870
|
+
out[id] = find(roots, id);
|
|
1871
|
+
return out;
|
|
1872
|
+
}
|