import type { Field2D, Range } from "./field"; import { colormapTable, type Colormap } from "./colormap"; /** * Paint a field into RGBA pixels with y increasing upward (row 0 of the image is * the top of the plate, y = Ly). Non-finite values are drawn transparent. */ export function rasterizeField( field: Field2D, range: Range, cm: Colormap, out?: Uint8ClampedArray, ): Uint8ClampedArray { const { nx, ny, data } = field; const table = colormapTable(cm); const rgba = out && out.length === nx * ny * 4 ? out : new Uint8ClampedArray(nx * ny * 4); const span = range.max - range.min || 1; for (let i = 0; i < ny; i++) { const row = ny - 1 - i; for (let j = 0; j < nx; j++) { const v = data[i + j * ny]; const px = (row * nx + j) * 4; if (!Number.isFinite(v)) { rgba[px + 3] = 0; continue; } let t = (v - range.min) / span; t = t < 0 ? 0 : t > 1 ? 1 : t; const k = Math.round(t * 255) * 3; rgba[px] = table[k]; rgba[px + 1] = table[k + 1]; rgba[px + 2] = table[k + 2]; rgba[px + 3] = 255; } } return rgba; }