import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js"; export const UTILITY_IMAGES = [ { name: "night-shade", url: shadeDataUrl("#000000") }, { name: "chunk-edge", url: shadeDataUrl("#e23d3d") } ]; export function playImagesFromCatalog (catalog) { return [...(catalog?.images ?? []), ...UTILITY_IMAGES]; } export async function loadSpriteCatalog () { const response = await fetch("/assets/catalog.json"); if (!response.ok) { throw new Error("Failed to load sprite catalog."); } return response.json(); } /** * Load catalog images without aborting the whole client when one file is missing. * Failed entries are logged and omitted from `game.images`. */ export async function preloadCatalogImages (game, catalog) { const failed = []; await Promise.all(playImagesFromCatalog(catalog).map((imageData) => loadOneImage(game, imageData).catch((error) => { console.error(error.message ?? error); failed.push({ name: imageData.name, url: imageData.url }); }))); if (failed.length) { console.warn(`Skipped ${failed.length} missing/broken sprite(s).`, failed.map((entry) => entry.name)); } return failed; } function loadOneImage (game, imageData) { return new Promise((resolve, reject) => { const img = new Image(); img.onload = () => { const finalImage = new image( img, imageData.subImgTotal, imageData.perRow, imageData.loop, imageData.chain ); finalImage.name = imageData.name; game.images[imageData.name] = finalImage; resolve(finalImage); }; img.onerror = () => { reject(new Error(`Failed to load image '${imageData.name}' from ${imageData.url}`)); }; img.src = imageData.url; }); } export function applySpriteSheets (images, catalog) { for (const entry of catalog?.images ?? []) { const sprite = images[entry.name]; if (!sprite) { continue; } sprite._animationSpeed = entry.animationSpeed ?? 0; const frames = entry.subImgTotal || 1; if (frames > 1) { sprite.addAnimationCycle( "idle", Array.from({ length: frames }, (_, index) => index), true ); } } } export function shadeDataUrl (fill = "#000000") { const canvas = document.createElement("canvas"); canvas.width = SPRITE_SIZE_PX; canvas.height = SPRITE_SIZE_PX; const context = canvas.getContext("2d"); context.fillStyle = fill; context.fillRect(0, 0, SPRITE_SIZE_PX, SPRITE_SIZE_PX); return canvas.toDataURL("image/png"); } export function useNearestNeighbour (scene, images) { const gl = scene.glContext.gl; for (const sprite of Object.values(images)) { const texture = scene.glContext.getTexture(sprite.g_image); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); } }