缩略图二分定位 + 邻域采样

B. 二分定位 + 邻域采样(我推荐)
把配置的语义从"这就是要生成的 10 档"改成"允许搜索的参数梯度"(比如分辨率梯度、帧率梯度、质量梯度三张表)。运行时:
1. 用每个组合只编 2 帧的方式粗估体积(很便宜);
2. 靠单调性做二分,几轮就找到"体积刚好不超过目标"的参数点;
3. 在这个点周围取 10 个组合(略高、略低各几个),完整生成。
成本大概是十几次估算编码 + 10 档完整编码,和现在基本持平甚至更省(估算只编 2 帧)。效果是候选真正围绕你输入的目标分布——比如你填 30 KB,出来的就是 22、26、29、31、35 KB 这种,而不是 5 KB 和 300 KB 各一个。
代价是你现在这套配置格式要推翻重做——从"精确档位表"变成"参数范围表"
This commit is contained in:
Yeomai committed 2026-09-20 00:39:38 +08:00
1 parent 5808e3dfce
commit e94dfb9e35
27 files changed
+710 -299

No files matched your search

@@ -7,6 +7,7 @@
--accent: #4fc1ff;
--border: #3c3c3c;
--error: #f14c4c;
--pick-ok: #3fb950;
/* 悬浮层填充与滚动条配色。Eagle 内置 Electron 22 / Chromium 108 不支持 color-mix(),
这些必须写成 rgba(),否则整条颜色声明会被丢弃。 */
--hover-fill: rgba(255, 255, 255, .07);
@@ -28,6 +29,7 @@
--accent: #0078d4;
--border: #ddd;
--error: #d13438;
--pick-ok: #1a7f37;
--hover-fill: rgba(0, 0, 0, .06);
--scroll-thumb: rgba(0, 0, 0, .30);
--scroll-thumb-hover: rgba(0, 0, 0, .46);
@@ -148,6 +150,38 @@
}
.animated-thumb-form input[type="number"]:focus { outline: none; border-color: var(--accent); }
.animated-thumb-card .thumb-dialog-actions { margin-top: 2px; }
.animated-pick-card { width: min(920px, 94vw); gap: 10px; padding: 16px; }
.animated-pick-card .thumb-dialog-title { text-align: center; }
.animated-pick-card .thumb-dialog-note { font-size: 12px; text-align: center; }
.animated-pick-notice { color: var(--text); text-align: center; min-height: 18px; }
/* 档位数量由配置决定,行数不固定:格子超高时内部滚动,按钮区始终留在面板底部。 */
.animated-pick-grid {
display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 10px;
max-height: 58vh; overflow-y: auto; padding-right: 2px;
}
.animated-pick-item {
position: relative;
display: flex; flex-direction: column; gap: 6px; width: 100%;
padding: 6px; border: 1px solid var(--border); border-radius: 8px;
background: var(--panel-2); color: var(--text-dim); cursor: pointer;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px; line-height: 1.4;
}
.animated-pick-item:hover { border-color: var(--accent); color: var(--text); }
.animated-pick-item img {
display: block; width: 100%; aspect-ratio: 1 / 1;
border-radius: 5px; background: var(--bg);
}
.animated-pick-item.selected {
border-color: var(--pick-ok); box-shadow: 0 0 0 1px var(--pick-ok); color: var(--text);
}
.animated-pick-item.selected::after {
content: '✓'; position: absolute; top: 10px; right: 10px;
width: 20px; height: 20px; border-radius: 50%;
background: var(--pick-ok); color: #fff;
font-size: 13px; line-height: 20px; text-align: center; font-weight: 700;
}
.animated-pick-params { display: block; word-break: break-all; }
/* 收窄下拉,避免在窄窗口下把右侧按钮挤到第二行(展开后的选项不受影响)*/
#toolbar #suffixSelect { max-width: 140px; }
#stage { position: absolute; inset: 0; display: flex; overflow: hidden; }
+186 -144
View File
@@ -105,6 +105,13 @@
<label class="animated-thumb-quality"><span data-i18n="viewer.animatedMaxSize">缩略图大小</span>
<span class="animated-thumb-size"><input id="animatedThumbMaxSize" type="number" min="10" max="1024" step="10" value="30"><span>KB</span></span>
</label>
<label class="animated-thumb-quality"><span data-i18n="viewer.animatedPriority">优先级别</span>
<select id="animatedThumbPriority">
<option value="resolution" data-i18n="viewer.priorityResolution">分辨率优先</option>
<option value="framerate" data-i18n="viewer.priorityFramerate">帧率优先</option>
<option value="balanced" data-i18n="viewer.priorityBalanced">分辨率和帧率交替进行</option>
</select>
</label>
</div>
<div id="animatedThumbDialogError" class="thumb-dialog-error"></div>
<div class="thumb-dialog-actions">
@@ -113,6 +120,18 @@
</div>
</div>
</div>
<div id="animatedPickDialog" class="thumb-dialog hidden" role="dialog" aria-modal="true" aria-labelledby="animatedPickTitle">
<div class="thumb-dialog-card animated-pick-card">
<div id="animatedPickTitle" class="thumb-dialog-title" data-i18n="viewer.animatedPickTitle">选择一个缩略图</div>
<div class="thumb-dialog-note" data-i18n="viewer.animatedPickHint">所有结果画布都是 400×400,标签为实际细节分辨率@帧率/质量/文件大小。点击一个结果即替换缩略图,关闭则全部放弃。</div>
<div id="animatedPickGrid" class="animated-pick-grid"></div>
<div id="animatedPickNotice" class="animated-pick-notice"></div>
<div class="thumb-dialog-actions">
<button id="animatedPickCancel" data-i18n="viewer.cancel">取消</button>
<button id="animatedPickConfirm" class="primary" data-i18n="viewer.animatedPickConfirm" disabled>确认</button>
</div>
</div>
</div>
</div>
<script>
@@ -128,6 +147,8 @@
const previewSettingsModule = require('../js/spine-preview-settings.js');
const apngEncoder = require('../js/apng-encoder.js');
const animatedWebpEncoder = require('../js/animated-webp-encoder.js');
const animatedProfileConfig = require('../js/animated-profiles.js');
const animatedProfiles = animatedProfileConfig.animatedProfiles;
const visibleBounds = require('../js/spine-visible-bounds.js');
let spineBadgeImagePromise = null;
@@ -796,6 +817,7 @@
const startInput = document.getElementById('animatedThumbStart');
const endInput = document.getElementById('animatedThumbEnd');
const formatInput = document.getElementById('animatedThumbFormat');
const priorityInput = document.getElementById('animatedThumbPriority');
const maxSizeInput = document.getElementById('animatedThumbMaxSize');
const errorEl = document.getElementById('animatedThumbDialogError');
const confirm = document.getElementById('animatedThumbDialogConfirm');
@@ -807,6 +829,7 @@
endInput.value = String(totalFrames);
endInput.max = String(totalFrames);
formatInput.value = 'webp';
priorityInput.value = animatedProfileConfig.DEFAULT_PRIORITY;
maxSizeInput.value = '30';
errorEl.textContent = '';
dialog.classList.remove('hidden');
@@ -834,6 +857,7 @@
start: startFrame / FPS,
end: Math.min(endFrame / FPS, animationLength),
format: formatInput.value === 'apng' ? 'apng' : 'webp',
priority: priorityInput.value,
maxKilobytes,
});
};
@@ -901,31 +925,8 @@
return measured;
}
function quantizeFrame(data, bits) {
if (bits >= 8) return new Uint8Array(data);
const levels = (1 << bits) - 1;
const lookup = new Uint8Array(256);
for (let value = 0; value < 256; value++) lookup[value] = Math.round(Math.round(value * levels / 255) * 255 / levels);
const output = new Uint8Array(data.length);
for (let index = 0; index < data.length; index++) output[index] = lookup[data[index]];
return output;
}
function compressFramePixels(data, size, bits, blockSize) {
if (blockSize <= 1) return quantizeFrame(data, bits);
const levels = (1 << bits) - 1;
const quantize = (value) => Math.round(Math.round(value * levels / 255) * 255 / levels);
const output = new Uint8Array(data.length);
for (let top = 0; top < size; top += blockSize) {
for (let left = 0; left < size; left += blockSize) {
const source = (top * size + left) * 4;
const color = [quantize(data[source]), quantize(data[source + 1]), quantize(data[source + 2]), quantize(data[source + 3])];
for (let y = top; y < Math.min(size, top + blockSize); y++) {
for (let x = left; x < Math.min(size, left + blockSize); x++) output.set(color, (y * size + x) * 4);
}
}
}
return output;
function profileFrameCount(sourceFrames, range, fps) {
return Math.max(2, Math.min(sourceFrames.length, Math.ceil(range * fps)));
}
function resizeFramePixels(data, sourceSize, targetSize) {
@@ -942,117 +943,13 @@
return output;
}
async function encodeAnimatedThumbnailToLimit(sourceFrames, size, range, maxKilobytes) {
const targetBytes = maxKilobytes * 1024;
const profiles = [
{ ratio: 1, bits: 8, block: 1 },
{ ratio: 0.75, bits: 7, block: 1 },
{ ratio: 0.5, bits: 7, block: 1 },
{ ratio: 0.5, bits: 6, block: 2 },
{ ratio: 0.33, bits: 6, block: 2 },
{ ratio: 0.25, bits: 5, block: 3 },
{ ratio: 0.16, bits: 5, block: 4 },
{ count: 3, bits: 4, block: 8 },
{ count: 2, bits: 3, block: 12 },
{ count: 3, bits: 5, block: 1, size: 320 },
{ count: 3, bits: 5, block: 1, size: 256 },
{ count: 2, bits: 4, block: 1, size: 192 },
{ count: 2, bits: 4, block: 1, size: 128 },
{ count: 2, bits: 3, block: 1, size: 96 },
{ count: 2, bits: 3, block: 1, size: 64 },
{ count: 2, bits: 2, block: 1, size: 32 },
];
let smallest = null;
for (let profileIndex = 0; profileIndex < profiles.length; profileIndex++) {
const profile = profiles[profileIndex];
const outputSize = profile.size || size;
const count = Math.max(2, Math.min(sourceFrames.length, profile.count || Math.round(sourceFrames.length * profile.ratio)));
const delayMs = Math.max(1, Math.round(range * 1000 / count));
const makeFrame = (index) => {
const sourceIndex = Math.min(sourceFrames.length - 1, Math.floor(index * sourceFrames.length / count));
const resized = resizeFramePixels(sourceFrames[sourceIndex], size, outputSize);
return {
rgba: compressFramePixels(resized, outputSize, profile.bits, profile.block),
delayNumerator: delayMs,
delayDenominator: 1000,
};
};
// 先用三帧估算该档位体积,明显超标时不再为整段动画分配大量内存。
if (count > 3) {
const probeFrames = [makeFrame(0), makeFrame(Math.floor(count / 2)), makeFrame(count - 1)];
const probe = apngEncoder.encode({ width: outputSize, height: outputSize, frames: probeFrames, plays: 0, compressionLevel: 9 });
if (probe.length * count / probeFrames.length > targetBytes * 1.5) continue;
}
const frames = Array.from({ length: count }, (_, index) => makeFrame(index));
setStatus(t('viewer.animatedCompressing', { current: profileIndex + 1, total: profiles.length }), Infinity);
await new Promise((resolve) => setTimeout(resolve, 0));
const buffer = apngEncoder.encode({ width: outputSize, height: outputSize, frames, plays: 0, compressionLevel: 9 });
if (!smallest || buffer.length < smallest.buffer.length) smallest = { buffer, frames: count, size: outputSize };
if (buffer.length <= targetBytes) return { buffer, frames: count, size: outputSize };
}
return smallest;
// 输出画布始终是 size×size:先把画面降到 detailSize,再放大填满。
// 缩略图尺寸保持稳定,体积则随 detailSize 档位下降。
function scaledFramePixels(data, size, detailSize) {
return resizeFramePixels(resizeFramePixels(data, size, detailSize), detailSize, size);
}
async function encodeAnimatedWebpToLimit(sourceFrames, size, range, maxKilobytes) {
const targetBytes = maxKilobytes * 1024;
const profiles = [
{ ratio: 1, quality: 0.82 },
{ ratio: 0.75, quality: 0.72 },
{ ratio: 0.5, quality: 0.62 },
{ ratio: 0.33, quality: 0.52 },
{ ratio: 0.25, quality: 0.42 },
{ count: 4, quality: 0.35 },
{ count: 3, quality: 0.28 },
{ count: 2, quality: 0.2 },
{ count: 3, quality: 0.3, size: 320 },
{ count: 3, quality: 0.25, size: 256 },
{ count: 2, quality: 0.2, size: 192 },
{ count: 2, quality: 0.15, size: 128 },
{ count: 2, quality: 0.1, size: 96 },
{ count: 2, quality: 0.08, size: 64 },
{ count: 2, quality: 0.05, size: 32 },
];
let smallest = null;
for (let profileIndex = 0; profileIndex < profiles.length; profileIndex++) {
const profile = profiles[profileIndex];
const outputSize = profile.size || size;
const count = Math.max(2, Math.min(sourceFrames.length, profile.count || Math.round(sourceFrames.length * profile.ratio)));
const duration = Math.max(1, Math.round(range * 1000 / count));
const canvas = document.createElement('canvas');
canvas.width = outputSize; canvas.height = outputSize;
const context = canvas.getContext('2d');
const cache = new Map();
const makeFrame = (index) => {
const sourceIndex = Math.min(sourceFrames.length - 1, Math.floor(index * sourceFrames.length / count));
if (cache.has(sourceIndex)) return cache.get(sourceIndex);
const pixels = resizeFramePixels(sourceFrames[sourceIndex], size, outputSize);
const image = context.createImageData(outputSize, outputSize);
image.data.set(pixels);
context.putImageData(image, 0, 0);
const dataUrl = canvas.toDataURL('image/webp', profile.quality);
if (!dataUrl.startsWith('data:image/webp')) throw new Error(t('viewer.animatedWebpUnavailable'));
const webp = Buffer.from(dataUrl.slice(dataUrl.indexOf(',') + 1), 'base64');
cache.set(sourceIndex, webp);
return webp;
};
if (count > 3) {
const probe = [makeFrame(0), makeFrame(Math.floor(count / 2)), makeFrame(count - 1)];
if (probe.reduce((total, frame) => total + frame.length, 0) * count / probe.length > targetBytes * 1.5) continue;
}
const frames = [];
for (let index = 0; index < count; index++) {
frames.push({ webp: makeFrame(index), duration });
if (index % 6 === 5) await new Promise((resolve) => setTimeout(resolve, 0));
}
setStatus(t('viewer.animatedCompressing', { current: profileIndex + 1, total: profiles.length }), Infinity);
const buffer = animatedWebpEncoder.encode({ width: outputSize, height: outputSize, frames, plays: 0 });
if (!smallest || buffer.length < smallest.buffer.length) smallest = { buffer, frames: count, size: outputSize };
if (buffer.length <= targetBytes) return { buffer, frames: count, size: outputSize };
}
return smallest;
}
async function renderAnimatedThumbnail(animation, options) {
async function renderAnimatedSourceFrames(animation, options) {
const size = 400;
const range = options.end - options.start;
// 长动画保持完整时间范围,但自动降低采样帧率,避免内存和输出体积失控。
@@ -1110,10 +1007,145 @@
} finally {
if (offRenderer && offRenderer.dispose) offRenderer.dispose();
}
const encoded = options.format === 'apng'
? await encodeAnimatedThumbnailToLimit(sourceFrames, size, range, options.maxKilobytes)
: await encodeAnimatedWebpToLimit(sourceFrames, size, range, options.maxKilobytes);
return { buffer: encoded.buffer, extension: options.format === 'apng' ? '.png' : '.webp', frames: encoded.frames, size: encoded.size };
return { sourceFrames, size, range };
}
// 缩略图参数标签,不走本地化:细节分辨率*细节分辨率@帧率/质量/文件大小。
function candidateParams(candidate) {
const quality = candidate.quality === null ? 'lossless' : 'q' + candidate.quality;
return candidate.detail + '*' + candidate.detail + '@' + candidate.fps + 'fps/' + quality
+ '/' + Math.max(1, Math.round(candidate.buffer.length / 1024)) + 'kb';
}
// 结果画廊:逐档生成,每档一出来就填进两行四列的格子,点哪个用哪个,关掉就全部丢弃。
// 帧编码走 canvas.toBlob(异步),生成期间界面不会像 toDataURL 那样被卡住。
async function pickAnimatedThumbnail(sourceFrames, size, range, options) {
const dialog = document.getElementById('animatedPickDialog');
const grid = document.getElementById('animatedPickGrid');
const notice = document.getElementById('animatedPickNotice');
const cancelButton = document.getElementById('animatedPickCancel');
const confirmButton = document.getElementById('animatedPickConfirm');
const targetBytes = options.maxKilobytes * 1024;
const profiles = animatedProfiles(options.priority);
// 4 个离屏画布轮转:每帧编码互相独立,成批提交比逐帧等待快得多。
const pool = Array.from({ length: 4 }, () => {
const off = document.createElement('canvas');
off.width = size; off.height = size;
const context = off.getContext('2d');
return { canvas: off, context, image: context.createImageData(size, size) };
});
const previewUrls = [];
grid.textContent = '';
notice.textContent = '';
confirmButton.disabled = true;
let selected = null;
let defaultPick = null;
let userPicked = false;
let hasFit = false;
let smallest = Infinity;
let settled = false;
const encodeFrame = (slot, pixels, quality) => new Promise((resolve, reject) => {
const unit = pool[slot];
unit.image.data.set(pixels);
unit.context.putImageData(unit.image, 0, 0);
unit.canvas.toBlob((blob) => {
if (!blob || blob.type !== 'image/webp') { reject(new Error(t('viewer.animatedWebpUnavailable'))); return; }
blob.arrayBuffer().then((data) => resolve(Buffer.from(data))).catch(reject);
}, 'image/webp', quality);
});
return new Promise((resolve, reject) => {
const cards = new Map();
const close = (value) => {
if (settled) return;
settled = true;
dialog.classList.add('hidden');
cancelButton.removeEventListener('click', cancel);
confirmButton.removeEventListener('click', confirm);
document.removeEventListener('keydown', keydown);
for (const url of previewUrls) URL.revokeObjectURL(url);
previewUrls.length = 0;
resolve(value);
};
const cancel = () => close(null);
const confirm = () => { if (selected) close(selected); };
const keydown = (event) => { if (event.key === 'Escape') cancel(); };
// 点卡片只是选中(右上角打勾),真正替换缩略图要再按确认。
const select = (candidate, manual) => {
if (manual) userPicked = true;
selected = candidate;
for (const [other, node] of cards) node.classList.toggle('selected', other === candidate);
confirmButton.disabled = false;
};
const addCard = (candidate) => {
const url = URL.createObjectURL(new Blob([candidate.buffer], {
type: options.format === 'apng' ? 'image/png' : 'image/webp',
}));
previewUrls.push(url);
const item = document.createElement('button');
item.type = 'button';
item.className = 'animated-pick-item';
const preview = document.createElement('img');
preview.src = url;
preview.alt = '';
const params = document.createElement('span');
params.className = 'animated-pick-params';
params.textContent = candidateParams(candidate);
item.append(preview, params);
item.addEventListener('click', () => select(candidate, true));
cards.set(candidate, item);
grid.appendChild(item);
};
cancelButton.addEventListener('click', cancel);
confirmButton.addEventListener('click', confirm);
document.addEventListener('keydown', keydown);
dialog.classList.remove('hidden');
(async () => {
for (let profileIndex = 0; profileIndex < profiles.length; profileIndex++) {
if (settled) return;
const profile = profiles[profileIndex];
const count = profileFrameCount(sourceFrames, range, profile.fps);
const duration = Math.max(1, Math.round(range * 1000 / count));
const frames = [];
for (let start = 0; start < count; start += pool.length) {
if (settled) return;
const batch = [];
for (let index = start; index < Math.min(count, start + pool.length); index++) {
const sourceIndex = Math.min(sourceFrames.length - 1, Math.floor(index * sourceFrames.length / count));
batch.push(scaledFramePixels(sourceFrames[sourceIndex], size, profile.size));
}
if (options.format === 'apng') {
for (const pixels of batch) frames.push({ rgba: pixels, delayNumerator: duration, delayDenominator: 1000 });
} else {
const buffers = await Promise.all(batch.map((pixels, offset) =>
encodeFrame((start + offset) % pool.length, pixels, profile.quality)));
for (const webp of buffers) frames.push({ webp, duration });
}
setStatus(t('viewer.animatedCompressing', { current: profileIndex + 1, total: profiles.length }), Infinity);
await new Promise((next) => setTimeout(next, 0));
}
if (settled) return;
const buffer = options.format === 'apng'
? apngEncoder.encode({ width: size, height: size, frames, plays: 0, compressionLevel: 9 })
: animatedWebpEncoder.encode({ width: size, height: size, frames, plays: 0 });
const candidate = {
detail: profile.size,
fps: profile.fps,
quality: options.format === 'apng' ? null : profile.quality,
frames: count,
buffer,
};
smallest = Math.min(smallest, buffer.length);
if (buffer.length <= targetBytes) hasFit = true;
addCard(candidate);
// 用户没自己挑过时,默认选中当前体积最小的档位,省得在十个结果里纠结。
if (!userPicked && (!defaultPick || buffer.length < defaultPick.buffer.length)) {
defaultPick = candidate;
select(candidate, false);
}
}
if (!hasFit) notice.textContent = t('viewer.animatedCannotFit', { target: options.maxKilobytes, actual: Math.ceil(smallest / 1024) });
})().catch((error) => { close(null); reject(error); });
});
}
async function generateAnimatedThumbnail() {
@@ -1135,13 +1167,17 @@
try {
const currentItem = await getEagleItemForPath(filePath);
setStatus(t('viewer.animatedGenerating', { current: 0, total: '…' }), Infinity);
const rendered = await renderAnimatedThumbnail(animation, options);
tempPath = path.join(os.tmpdir(), 'spineviewer-current-animated-' + crypto.randomBytes(12).toString('hex') + rendered.extension);
fs.writeFileSync(tempPath, rendered.buffer);
const source = await renderAnimatedSourceFrames(animation, options);
const picked = await pickAnimatedThumbnail(source.sourceFrames, source.size, source.range, options);
// 用户没挑就直接结束:不替换缩略图,已生成的预览对象在上面统一释放。
if (!picked) { setStatus(''); return; }
const extension = options.format === 'apng' ? '.png' : '.webp';
tempPath = path.join(os.tmpdir(), 'spineviewer-current-animated-' + crypto.randomBytes(12).toString('hex') + extension);
fs.writeFileSync(tempPath, picked.buffer);
await setEagleCustomThumbnail(currentItem.id, tempPath);
setStatus(t('viewer.animatedThumbUpdated', {
frames: rendered.frames,
size: Math.ceil(rendered.buffer.length / 1024),
frames: picked.frames,
size: Math.ceil(picked.buffer.length / 1024),
}), 5000);
log('用户主动更新当前素材动画缩略图: item=' + currentItem.id);
} catch (error) {
@@ -1173,7 +1209,13 @@
const options = await confirmAnimatedThumbnail(animation);
if (!options) return;
setStatus(t('viewer.animatedGenerating', { current: 0, total: '…' }), Infinity);
rendered = await renderAnimatedThumbnail(animation, options);
const source = await renderAnimatedSourceFrames(animation, options);
const picked = await pickAnimatedThumbnail(source.sourceFrames, source.size, source.range, options);
if (!picked) { setStatus(''); return; }
rendered = {
buffer: picked.buffer,
extension: options.format === 'apng' ? '.png' : '.webp',
};
} else {
setStatus(t('viewer.generating'), Infinity);
rendered = await renderCurrentFrameThumbnail();