import { luminancePlane, type Plane } from './luminance'; import { fitSize } from '../lib/math'; export type ArtworkTexture = { image: Plane; tone: Plane }; export type TextureReply = { image: Plane } | { error: string }; const cache = new Map>(); function toneMap(image: HTMLImageElement): Plane { const { width, height } = fitSize(image.naturalWidth, image.naturalHeight, 64, true); const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const context = canvas.getContext('2d', { willReadFrequently: true })!; // HTML images and ImageBitmaps downsample differently. Keep this tiny pass on // the original image so the breathing field remains byte-for-byte unchanged. context.drawImage(image, 0, 0, width, height); return luminancePlane(context.getImageData(0, 0, width, height).data, width, height); } async function prepare(image: HTMLImageElement): Promise { const tone = toneMap(image); const bitmap = await createImageBitmap(image); let worker: Worker | undefined; try { worker = new Worker(new URL('./art-texture.worker.ts', import.meta.url), { type: 'module' }); return await new Promise((resolve, reject) => { worker!.onmessage = ({ data }: MessageEvent) => 'image' in data ? resolve({ image: data.image, tone }) : reject(new Error(data.error)); worker!.onerror = (event) => reject(new Error(event.message)); worker!.onmessageerror = () => reject(new Error('Could not receive artwork pixels.')); worker!.postMessage(bitmap, [bitmap]); }); } finally { worker?.terminate(); bitmap.close(); } } // Share pending work too: main art and echoes can request the same source. // Workers transfer the finished planes and exit; only two recent sources stay cached. export function artworkTexture(image: HTMLImageElement): Promise { const key = image.currentSrc || image.src; const cached = cache.get(key); if (cached) { cache.delete(key); cache.set(key, cached); return cached; } const texture = prepare(image).catch((error) => { if (cache.get(key) === texture) cache.delete(key); throw error; }); cache.set(key, texture); if (cache.size > 2) cache.delete(cache.keys().next().value!); return texture; }