53 lines
1.6 KiB
TypeScript
53 lines
1.6 KiB
TypeScript
export type RGB = readonly [number, number, number];
|
|
|
|
export function hex(h: string): RGB {
|
|
const n = parseInt(h.replace('#', ''), 16);
|
|
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
|
|
}
|
|
|
|
export function lerp(a: number, b: number, t: number): number {
|
|
return a + (b - a) * t;
|
|
}
|
|
|
|
export function mix(a: RGB, b: RGB, t: number): RGB {
|
|
return [lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t)];
|
|
}
|
|
|
|
/** Component-wise multiply, used to apply ambient light to a base color. */
|
|
export function mul(c: RGB, k: RGB): RGB {
|
|
return [c[0] * k[0], c[1] * k[1], c[2] * k[2]];
|
|
}
|
|
|
|
export function scale(c: RGB, k: number): RGB {
|
|
return [c[0] * k, c[1] * k, c[2] * k];
|
|
}
|
|
|
|
export function add(a: RGB, b: RGB, k = 1): RGB {
|
|
return [a[0] + b[0] * k, a[1] + b[1] * k, a[2] + b[2] * k];
|
|
}
|
|
|
|
export function css(c: RGB, a = 1): string {
|
|
return `rgba(${c[0] | 0},${c[1] | 0},${c[2] | 0},${a})`;
|
|
}
|
|
|
|
/** Sample a list of evenly spaced color stops at u in [0, 1]. */
|
|
export function gradient(stops: readonly RGB[], u: number): RGB {
|
|
if (u <= 0) return stops[0];
|
|
if (u >= 1) return stops[stops.length - 1];
|
|
const f = u * (stops.length - 1);
|
|
const i = Math.floor(f);
|
|
return mix(stops[i], stops[i + 1], f - i);
|
|
}
|
|
|
|
const BAYER4 = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5];
|
|
|
|
/** Ordered-dither threshold in (0, 1) for a pixel position. */
|
|
export function bayer(x: number, y: number): number {
|
|
return (BAYER4[(y & 3) * 4 + (x & 3)] + 0.5) / 16;
|
|
}
|
|
|
|
/** Quantize an alpha to a few dithered steps so soft light still looks like pixel art. */
|
|
export function ditherStep(a: number, x: number, y: number, n = 6): number {
|
|
return Math.floor(a * n + bayer(x, y)) / n;
|
|
}
|