Files
SpineViewer/thumbnail/spine.js
T
2026-09-09 00:27:25 +08:00

326 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const fs = require('fs');
const path = require('path');
const zlib = require('zlib');
const utils = require('./../js/spine-utils.js');
const render = require('./../js/spine-render.js');
/** 简易日志(写入插件目录 thumbnails.log,便于诊断 Eagle 中的间歇失败) */
function log(msg) {
try {
const logPath = path.join(__dirname, '..', 'thumbnails.log');
fs.appendFileSync(logPath, '[' + new Date().toISOString() + '] ' + msg + '\n');
} catch (e) { /* ignore */ }
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
/** 插件代码版本:每次改动递增,用于确认 Eagle 是否加载到最新代码 */
const VERSION = 'v6';
/** 返回资源当前的尺寸/修改时间签名,同时确认 atlas 引用的全部贴图均已落盘。 */
function assetSignature(assets) {
if (!assets || !assets.skeletonPath || !assets.atlasPath) return null;
let atlasText = '';
try { atlasText = fs.readFileSync(assets.atlasPath, 'utf8'); } catch (e) { return null; }
const pages = utils.parseAtlasPages(atlasText);
if (pages.length === 0 || pages.some((name) => !assets.texturePaths[name])) return null;
const paths = [assets.skeletonPath, assets.atlasPath].concat(pages.map((name) => assets.texturePaths[name]));
const stats = [];
for (const file of paths) {
try {
const stat = fs.statSync(file);
if (!stat.isFile() || stat.size === 0) return null;
stats.push(file + ':' + stat.size + ':' + Math.round(stat.mtimeMs));
} catch (e) {
return null;
}
}
return stats.join('|');
}
/**
* Eagle 拖入一组文件时会并发触发 atlas/json/skel 的缩略图回调,而文件内容和
* folders 元数据仍可能继续写入。等同批资源连续三次保持不变后再渲染,避免把
* 半截 atlas 或旧库中的同名骨骼渲染成占位图。
*/
async function discoverWithRetry(src, retries = 48, delay = 250) {
let assets = null;
let previousSignature = null;
let stableCount = 0;
for (let i = 0; i < retries; i++) {
assets = utils.discoverAssets(src, { strictStem: true, preferCompatibleJson: true });
const signature = assetSignature(assets);
if (signature && signature === previousSignature) stableCount += 1;
else stableCount = signature ? 1 : 0;
previousSignature = signature;
if (stableCount >= 3) return assets;
await sleep(delay);
}
return assets;
}
/**
* Eagle 格式扩展缩略图处理函数。
* 参数:{ src, dest, item }
* - src : 原始文件路径(skel/skel.bytes/json/atlas/atlas.txt)
* - dest : 需要生成的缩略图 PNG 路径
* - item : 当前 item 对象(可更新宽高)
*/
module.exports = async ({ src, dest, item }) => {
try {
// 记录 Eagle 传入的关键信息,便于诊断 src/item 的实际形态
log('HIT ' + VERSION + ' src=' + src + ' (isTexture=' + utils.isTextureFile(src) + ')');
try {
log(' item keys=' + Object.keys(item || {}).join(',') + ' | name=' + (item && item.name) + ' | id=' + (item && item.id) + ' | ext=' + (item && item.ext) + ' | isDeleted=' + (item && item.isDeleted));
} catch (e) { /* ignore */ }
// —— 守护:若 src 文件在库中不存在(可能是回收站 isDeleted 残留 / 临时 id),
// 且 item 标记为已删除,则跳过,避免生成破碎/占位缩略图,交由 Eagle 自身处理。
if (item && item.isDeleted) {
log(' skip: item.isDeleted=true');
return resolve(item);
}
// —— 防御:若 src 是图片(png/jpg/jpeg/webp),不生成占位图,
// 而是把原始图片复制/转换为缩略图,交由系统展示真实内容。
const srcExt = utils.extOf(path.basename(src));
if (utils.isTextureFile(src) || srcExt === '.png' || srcExt === '.jpg' || srcExt === '.jpeg' || srcExt === '.webp') {
await copyImageAsThumb(src, dest);
try { const s = imageSizeOf(dest); item.width = s.width || item.width; item.height = s.height || item.height; } catch (e) {}
return resolve(item);
}
let assets = await discoverWithRetry(src);
// 找不到配套 Spine 资源
if (!assets.skeletonPath || !assets.atlasPath) {
log('未找到配套资源: ' + src + ' (skeleton=' + !!assets.skeletonPath + ', atlas=' + !!assets.atlasPath + ')');
if (assets.atlasPath && await writeAtlasFallback(assets, dest)) {
item.width = 400; item.height = 400;
return resolve(item);
}
await writePlaceholder(dest);
item.width = 400; item.height = 400;
return resolve(item);
}
let version = utils.detectVersion(assets.skeletonPath);
let runtimeDir = utils.chooseRuntimeDir(version, assets.isBinary);
// 3.6/3.7 二进制没有对应解析器。若有同批 JSON,资源发现阶段已自动切换;
// 走到这里说明没有 JSON,直接显示 atlas 实际贴图,避免无意义地重复解析。
if (assets.isBinary && version && parseFloat(version) < 3.8) {
if (await writeAtlasFallback(assets, dest)) {
log('旧版二进制无 JSON,已使用 atlas 贴图缩略图: ' + src);
item.width = 400; item.height = 400;
return resolve(item);
}
}
if (!runtimeDir) {
if (await writeAtlasFallback(assets, dest)) {
item.width = 400; item.height = 400;
return resolve(item);
}
await writePlaceholder(dest);
item.width = 400; item.height = 400;
return resolve(item);
}
// 渲染首帧到 PNG。若导入过程恰好仍在写大文件,重新发现稳定资源再试,
// 每次都会重新匹配同批 atlas/json/skel,而不是重复读取原来的错误组合。
let png = null;
let lastRenderError = null;
for (let attempt = 0; attempt < 3; attempt++) {
try {
png = await render.renderThumbnail({
skeletonPath: assets.skeletonPath,
atlasPath: assets.atlasPath,
texturePaths: assets.texturePaths,
version,
runtimeDir,
size: 400,
});
break;
} catch (e) {
lastRenderError = e;
log('renderThumbnail 第 ' + (attempt + 1) + ' 次失败: ' + (e && e.message) + ',重新等待同批资源...');
if (attempt === 2) break;
await sleep(500);
assets = await discoverWithRetry(src, 16, 250);
if (!assets.skeletonPath || !assets.atlasPath || !assetSignature(assets)) continue;
version = utils.detectVersion(assets.skeletonPath);
runtimeDir = utils.chooseRuntimeDir(version, assets.isBinary);
}
}
if (!png) {
if (await writeAtlasFallback(assets, dest)) {
log('骨骼无法解析,已使用 atlas 贴图缩略图: ' + src);
item.width = 400; item.height = 400;
return resolve(item);
}
throw lastRenderError || new Error('Spine 资源尚未写入完成');
}
fs.writeFileSync(dest, png);
try {
const size = imageSizeOf(dest);
item.width = size.width || 400;
item.height = size.height || 400;
} catch (e) { /* ignore */ }
return Promise.resolve(item);
} catch (err) {
// 兜底:总是生成一张有效 PNG,绝不 reject,避免 Eagle 显示默认图标
log('缩略图处理异常: ' + (err && err.message) + '\n' + ((err && err.stack) || ''));
try {
await writePlaceholder(dest);
item.width = 400;
item.height = 400;
return resolve(item);
} catch (e2) {
// 最后兜底:写入一张最小 1x1 PNG
try { fs.writeFileSync(dest, Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC', 'base64')); } catch (e3) {}
item.width = 400; item.height = 400;
return resolve(item);
}
}
};
function resolve(item) {
return item;
}
/** 将任意图片作为缩略图复制/转换为 PNG(PNG 直接拷贝,JPG/WebP 用 @napi-rs/canvas 转换) */
async function copyImageAsThumb(src, dest) {
const ext = path.extname(src).toLowerCase();
if (ext === '.png') {
fs.copyFileSync(src, dest);
return;
}
if (render.canvasLib) {
try {
const img = await render.canvasLib.loadImage(src);
const w = img.width, h = img.height;
const canvas = render.canvasLib.createCanvas(w, h);
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, w, h);
fs.writeFileSync(dest, canvas.toBuffer('image/png'));
return;
} catch (e) { /* fall through */ }
}
fs.copyFileSync(src, dest);
}
/** 骨骼二进制无法解析时,用真实 atlas 贴图生成可辨认的回退缩略图。 */
async function writeAtlasFallback(assets, dest) {
if (!render.canvasLib || !assets || !assets.texturePaths) return false;
const texturePath = Object.values(assets.texturePaths).find((file) => {
try { return fs.statSync(file).size > 0; } catch (e) { return false; }
});
if (!texturePath) return false;
try {
const img = await render.canvasLib.loadImage(texturePath);
const size = 400;
const canvas = render.canvasLib.createCanvas(size, size);
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#1e1e22';
ctx.fillRect(0, 0, size, size);
const scale = Math.min((size - 24) / img.width, (size - 24) / img.height);
const w = Math.max(1, Math.round(img.width * scale));
const h = Math.max(1, Math.round(img.height * scale));
ctx.drawImage(img, Math.round((size - w) / 2), Math.round((size - h) / 2), w, h);
await render.drawSpineBadge(ctx, size, size);
fs.writeFileSync(dest, canvas.toBuffer('image/png'));
return true;
} catch (e) {
log('atlas 贴图回退失败: ' + (e && e.message));
return false;
}
}
/** 读取 PNG 宽高(仅支持 PNG 头部) */
function imageSizeOf(file) {
const buf = fs.readFileSync(file);
if (buf.slice(0, 8).toString('hex') === '89504e470d0a1a0a') {
return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
}
return { width: 0, height: 0 };
}
/** 生成一个纯 JS 占位 PNG(无需外部依赖),作为兜底 */
async function writePlaceholder(dest) {
const w = 400, h = 400;
if (render.canvasLib) {
try {
const canvas = render.canvasLib.createCanvas(w, h);
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#1e1e22';
ctx.fillRect(0, 0, w, h);
await render.drawSpineBadge(ctx, w, h);
fs.writeFileSync(dest, canvas.toBuffer('image/png'));
return;
} catch (e) { /* fall through to pure JS encoder */ }
}
// 深色底
const pixels = Buffer.alloc(w * h * 4);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const i = (y * w + x) * 4;
pixels[i] = 30; pixels[i + 1] = 30; pixels[i + 2] = 34; pixels[i + 3] = 255;
}
}
// 简单的斜线纹理,让占位图不单调
for (let i = 0; i < w + h; i += 8) {
for (let k = 0; k < 3; k++) {
const x = Math.min(w - 1, i - k);
const y = Math.min(h - 1, k);
const idx = (y * w + x) * 4;
pixels[idx] = 60; pixels[idx + 1] = 62; pixels[idx + 2] = 68;
}
}
fs.writeFileSync(dest, encodePng(w, h, pixels));
}
/** 最小 PNG 编码器(纯 JS,使用 zlib deflate) */
function encodePng(width, height, rgba) {
const sig = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(width, 0);
ihdr.writeUInt32BE(height, 4);
ihdr[8] = 8; // bit depth
ihdr[9] = 6; // color type RGBA
ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0;
const ihdrChunk = chunk('IHDR', ihdr);
const raw = Buffer.alloc((width * 4 + 1) * height);
for (let y = 0; y < height; y++) {
raw[y * (width * 4 + 1)] = 0; // filter type 0
rgba.copy(raw, y * (width * 4 + 1) + 1, y * width * 4, (y + 1) * width * 4);
}
const idat = zlib.deflateSync(raw);
const idatChunk = chunk('IDAT', idat);
const iend = chunk('IEND', Buffer.alloc(0));
return Buffer.concat([sig, ihdrChunk, idatChunk, iend]);
}
function chunk(type, data) {
const len = Buffer.alloc(4);
len.writeUInt32BE(data.length, 0);
const typeBuf = Buffer.from(type, 'ascii');
const crcBuf = Buffer.alloc(4);
crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0);
return Buffer.concat([len, typeBuf, data, crcBuf]);
}
function crc32(buf) {
let c, crc = 0xFFFFFFFF;
for (let i = 0; i < buf.length; i++) {
c = (crc ^ buf[i]) & 0xFF;
for (let k = 0; k < 8; k++) c = c & 1 ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
crc = (crc >>> 8) ^ c;
}
return (crc ^ 0xFFFFFFFF) >>> 0;
}