// A small PNG encoder for the fixture images. It writes 8-bit RGB images without a dependency. import { deflateSync } from "node:zlib"; const CRC_TABLE = (() => { const table = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; table[n] = c >>> 0; } return table; })(); /** The CRC-32 of `bytes`, as PNG and ZIP use it. */ export function crc32(bytes) { let crc = 0xffffffff; for (const byte of bytes) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8); return (crc ^ 0xffffffff) >>> 0; } export const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); function chunk(type, data) { const length = Buffer.alloc(4); length.writeUInt32BE(data.length); const body = Buffer.concat([Buffer.from(type, "ascii"), data]); const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(body)); return Buffer.concat([length, body, crc]); } /** Encode an RGB image. `pixel(x, y)` returns `[r, g, b]` with values from 0 to 255. */ export function encodePng(width, height, pixel) { if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) throw new Error("The image size must be positive whole numbers."); const stride = width * 3 + 1; const raw = Buffer.alloc(stride * height); for (let y = 0; y < height; y++) { const row = y * stride; raw[row] = 0; // Filter type None. for (let x = 0; x < width; x++) { const [r, g, b] = pixel(x, y); const at = row + 1 + x * 3; raw[at] = r; raw[at + 1] = g; raw[at + 2] = b; } } const header = Buffer.alloc(13); header.writeUInt32BE(width, 0); header.writeUInt32BE(height, 4); header[8] = 8; // Bit depth. header[9] = 2; // Color type RGB. header[10] = 0; header[11] = 0; header[12] = 0; return Buffer.concat([PNG_SIGNATURE, chunk("IHDR", header), chunk("IDAT", deflateSync(raw, { level: 6 })), chunk("IEND", Buffer.alloc(0))]); } /** Read the chunks of a PNG file. Each chunk has its type, data, stored CRC, and computed CRC. */ export function readPngChunks(bytes) { if (!bytes.subarray(0, 8).equals(PNG_SIGNATURE)) throw new Error("The file has no PNG signature."); const chunks = []; let at = 8; while (at < bytes.length) { const length = bytes.readUInt32BE(at); const type = bytes.toString("ascii", at + 4, at + 8); const data = bytes.subarray(at + 8, at + 8 + length); const stored = bytes.readUInt32BE(at + 8 + length); chunks.push({ type, data, stored, computed: crc32(bytes.subarray(at + 4, at + 8 + length)) }); at += 12 + length; } return chunks; } /** A diagonal gradient between two colors. Each fixture image uses a different pair and angle. */ export function gradientPixel(width, height, from, to, angle) { const dx = Math.cos(angle), dy = Math.sin(angle); const span = Math.abs(dx) * width + Math.abs(dy) * height; const origin = Math.min(0, dx * width) + Math.min(0, dy * height); return (x, y) => { const t = (x * dx + y * dy - origin) / span; return [0, 1, 2].map(i => Math.round(from[i] + (to[i] - from[i]) * t)); }; }