56 lines
1.9 KiB
JavaScript
56 lines
1.9 KiB
JavaScript
"use strict";
|
|
const images = new Map();
|
|
const imageBoundsCache = new WeakMap();
|
|
const imageMetrics = new Map();
|
|
function loadImages() {
|
|
const assets = [...SPRITES, ...DECOR_ASSETS];
|
|
let loaded = 0;
|
|
return new Promise((resolve) => {
|
|
for (const s of assets) {
|
|
const img = new Image();
|
|
img.onload = img.onerror = () => {
|
|
const w = img.naturalWidth || img.width || ALPHA_BOUNDS[s.id]?.imageW || 512;
|
|
const h = img.naturalHeight || img.height || ALPHA_BOUNDS[s.id]?.imageH || 512;
|
|
const bounds = ALPHA_BOUNDS[s.id] || { x: 0, y: 0, w, h, imageW: w, imageH: h };
|
|
imageMetrics.set(s.id, {
|
|
w,
|
|
h,
|
|
ratio: h / Math.max(w, 1),
|
|
visibleBottomRatio: (bounds.y + bounds.h) / Math.max(bounds.imageH, 1),
|
|
});
|
|
loaded += 1;
|
|
if (loaded === assets.length) resolve();
|
|
};
|
|
img.alphaBounds = ALPHA_BOUNDS[s.id] || null;
|
|
img.src = s.path;
|
|
images.set(s.id, img);
|
|
}
|
|
});
|
|
}
|
|
|
|
function imageAlphaBounds(img) {
|
|
if (!img) return null;
|
|
if (img.alphaBounds) return img.alphaBounds;
|
|
if (imageBoundsCache.has(img)) return imageBoundsCache.get(img);
|
|
|
|
const w = img.naturalWidth || img.width || 0;
|
|
const h = img.naturalHeight || img.height || 0;
|
|
if (!w || !h) return null;
|
|
const bounds = { x: 0, y: 0, w, h, imageW: w, imageH: h };
|
|
imageBoundsCache.set(img, bounds);
|
|
return bounds;
|
|
}
|
|
|
|
function getImageMetrics(idOrImg) {
|
|
if (typeof idOrImg === "string") return imageMetrics.get(idOrImg) || null;
|
|
if (!idOrImg) return null;
|
|
for (const [id, img] of images) {
|
|
if (img === idOrImg) return imageMetrics.get(id) || null;
|
|
}
|
|
const w = idOrImg.naturalWidth || idOrImg.width || 0;
|
|
const h = idOrImg.naturalHeight || idOrImg.height || 0;
|
|
return w && h ? { w, h, ratio: h / w, visibleBottomRatio: 1 } : null;
|
|
}
|
|
|
|
|
|
window.TarinaiAssets = { images, imageBoundsCache, imageMetrics, loadImages, imageAlphaBounds, getImageMetrics };
|