/** * @file Prépare l'image du Miroir brisé envoyée au joueur : l'illustration déjà mélangée, dans l'ordre où * sont les morceaux. * * Le navigateur la découpe pour l'affichage ; il ne reçoit ni l'image en ordre, ni la place des morceaux * (seulement des cases). */ import { join } from "node:path"; import sharp from "sharp"; // Largeur d'un morceau envoyé : le plateau fait 540 px au plus en Normal et 450 px en Difficile, doublés pour les écrans denses. const PIECE_SIZE = { square: 270, portrait: 180 }; const CACHE_LIMIT = 64; export function createMirrorImageRenderer(publicRoot) { const cache = new Map(); // `at[cell]` : le morceau présent dans chaque case. return function render({ image, cols, rows, format, at }) { const key = `${image}|${at.join(",")}`; const cached = cache.get(key); if (cached) { cache.delete(key); cache.set(key, cached); return cached; } const rendered = (async () => { const path = join(publicRoot, image); const { width, height } = await sharp(path).metadata(); const sourceWidth = Math.floor(width / cols), sourceHeight = Math.floor(height / rows); const size = PIECE_SIZE[format]; const pieceHeight = Math.round(size * sourceHeight / sourceWidth); const pieces = await Promise.all(Array.from({ length: cols * rows }, (_, piece) => sharp(path) .extract({ left: (piece % cols) * sourceWidth, top: Math.floor(piece / cols) * sourceHeight, width: sourceWidth, height: sourceHeight }) .resize(size, pieceHeight, { fit: "fill" }).toBuffer())); return sharp({ create: { width: size * cols, height: pieceHeight * rows, channels: 3, background: "#05070f" } }) .composite(at.map((piece, cell) => ({ input: pieces[piece], left: (cell % cols) * size, top: Math.floor(cell / cols) * pieceHeight }))) .webp({ quality: 84 }).toBuffer(); })(); cache.set(key, rendered); if (cache.size > CACHE_LIMIT) cache.delete(cache.keys().next().value); // Un échec ne reste pas en cache : le prochain appel réessaie. rendered.catch(() => cache.delete(key)); return rendered; }; }