xlerobot-sim / src /render /palette.js
VectorW's picture
Add the Pixel renderer: pixel art of the 3DGS scenes and of the modelled ones
352b7b4 verified
Raw History Blame Contribute Delete
10.1 kB
// The Pixel renderer's colours: a small palette fitted to what the view shows, as a pixel artist picks
// colours for a scene. The frame's colours are binned, weighted so that a small bright object counts next
// to a large wall, and clustered in OKLab (k-means). Between frames the palette follows the view: the
// clusters move with it, and a colour that is shown badly takes the place of one of two near-identical ones.
//
// Colours are kept in a stretched OKLab, chroma times CHROMA, where plain distances pick the nearest
// colour: hues stay apart in a small palette, at the cost of a little lightness accuracy.
export const MAX_COLOURS = 48;
export const CHROMA = 1.5;
const CELLS = 1 << 15; // 5 bits per sRGB channel
const WEIGHT = 0.5; // a cell counts as its pixel count to this power
// How the palette is shown: a little more saturated and contrasted, lights warmer and shadows cooler.
const SATURATION = 1.15;
const CONTRAST = 0.2;
const WARMTH = 0.012;
const toLinear = (v) => (v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4);
function toOklab(r, g, b, out, o) {
const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
out[o] = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;
out[o + 1] = CHROMA * (1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s);
out[o + 2] = CHROMA * (0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s);
}
function toLinearRgb(L, a, b, out, o) {
const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;
const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;
const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;
out[o] = Math.min(1, Math.max(0, 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s));
out[o + 1] = Math.min(1, Math.max(0, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s));
out[o + 2] = Math.min(1, Math.max(0, -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s));
}
export class Palette {
constructor(size = 32) {
this.size = Math.min(size, MAX_COLOURS);
this.count = 0; // colours fitted so far; 0 until the first frame
this.generation = 0;
this.matched = new Float32Array(3 * MAX_COLOURS); // what the shader matches against: stretched OKLab
this.colours = new Float32Array(3 * MAX_COLOURS); // what it draws for each: linear RGB
this.centres = new Float32Array(3 * MAX_COLOURS); // where the fit says each colour should be
this.weights = new Float32Array(MAX_COLOURS);
this.jumped = new Uint8Array(MAX_COLOURS); // colours that changed place, shown at once
this.counts = new Uint32Array(CELLS);
this.sums = new Uint32Array(3 * CELLS);
this.used = new Uint16Array(CELLS);
this.points = new Float32Array(3 * 4096);
this.pointWeights = new Float32Array(4096);
this.errors = new Float32Array(4096);
this.sumsByColour = new Float64Array(4 * MAX_COLOURS);
}
/** Forget the colours: the next frame picks them afresh (a new scene or renderer). */
reset() {
this.count = 0;
this.generation++;
}
/**
* Fit the palette to a frame: `pixels` are sRGB bytes, four per pixel. The first fit of a scene starts
* from the frame's most different colours; later ones adjust the palette they find.
*/
fit(pixels) {
const n = this.#histogram(pixels);
if (!n) return;
const cold = this.count === 0;
if (cold) this.#start(n);
else if (this.count < this.size && n > this.count) this.#grow(n);
this.#cluster(n, cold ? 8 : 2);
for (let round = 0; round < (cold ? 12 : 1); round++) {
if (!this.#swap(n)) break;
this.#cluster(n, cold ? 2 : 1);
}
if (cold) this.settle();
}
/** The frame as weighted points: one per occupied cell of a 32x32x32 sRGB grid. Returns their number. */
#histogram(pixels) {
const { counts, sums, used } = this;
let n = 0;
for (let i = 0; i + 3 < pixels.length; i += 4) {
const r = pixels[i];
const g = pixels[i + 1];
const b = pixels[i + 2];
const cell = ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3);
if (counts[cell]++ === 0) used[n++] = cell;
sums[3 * cell] += r;
sums[3 * cell + 1] += g;
sums[3 * cell + 2] += b;
}
if (n > this.pointWeights.length) {
this.points = new Float32Array(3 * n);
this.pointWeights = new Float32Array(n);
this.errors = new Float32Array(n);
}
for (let k = 0; k < n; k++) {
const cell = used[k];
const count = counts[cell];
const scale = 1 / (255 * count);
toOklab(toLinear(sums[3 * cell] * scale), toLinear(sums[3 * cell + 1] * scale), toLinear(sums[3 * cell + 2] * scale), this.points, 3 * k);
this.pointWeights[k] = count ** WEIGHT;
counts[cell] = 0;
sums[3 * cell] = sums[3 * cell + 1] = sums[3 * cell + 2] = 0;
}
return n;
}
/** The first colours: the commonest, then each time the one the colours so far show worst. */
#start(n) {
const { points, pointWeights, centres, errors } = this;
this.count = Math.min(this.size, n);
let next = 0;
for (let k = 1; k < n; k++) if (pointWeights[k] > pointWeights[next]) next = k;
errors.fill(Infinity, 0, n);
for (let j = 0; j < this.count; j++) {
centres.set(points.subarray(3 * next, 3 * next + 3), 3 * j);
this.jumped[j] = 1;
let worst = -1;
let worstError = -1;
for (let k = 0; k < n; k++) {
const d = distance2(points, 3 * k, centres, 3 * j);
if (d < errors[k]) errors[k] = d;
const e = pointWeights[k] * errors[k];
if (e > worstError) {
worstError = e;
worst = k;
}
}
next = worst;
}
}
/** A frame with few colours left the palette short: add the colours shown worst. */
#grow(n) {
this.#cluster(n, 1);
while (this.count < Math.min(this.size, n)) {
const k = this.#worst(n);
this.centres.set(this.points.subarray(3 * k, 3 * k + 3), 3 * this.count);
this.jumped[this.count++] = 1;
this.errors[k] = 0;
}
}
#worst(n) {
let worst = 0;
for (let k = 1; k < n; k++) if (this.errors[k] > this.errors[worst]) worst = k;
return worst;
}
/** k-means steps: every point to its nearest colour, every colour to the weighted mean of its points. */
#cluster(n, steps) {
const { points, pointWeights, centres, errors, weights, sumsByColour: sums } = this;
const K = this.count;
for (let step = 0; step < steps; step++) {
sums.fill(0);
for (let k = 0; k < n; k++) {
const x = points[3 * k];
const y = points[3 * k + 1];
const z = points[3 * k + 2];
let best = 0;
let bestD = Infinity;
for (let j = 0; j < K; j++) {
const dx = x - centres[3 * j];
const dy = y - centres[3 * j + 1];
const dz = z - centres[3 * j + 2];
const d = dx * dx + dy * dy + dz * dz;
if (d < bestD) {
bestD = d;
best = j;
}
}
const w = pointWeights[k];
errors[k] = w * bestD;
sums[4 * best] += w * x;
sums[4 * best + 1] += w * y;
sums[4 * best + 2] += w * z;
sums[4 * best + 3] += w;
}
for (let j = 0; j < K; j++) {
const w = sums[4 * j + 3];
weights[j] = w;
if (w > 0) {
centres[3 * j] = sums[4 * j] / w;
centres[3 * j + 1] = sums[4 * j + 1] / w;
centres[3 * j + 2] = sums[4 * j + 2] / w;
} else {
// Nothing on screen has this colour any more: it goes to the colour shown worst.
const k = this.#worst(n);
centres.set(points.subarray(3 * k, 3 * k + 3), 3 * j);
errors[k] = 0;
this.jumped[j] = 1;
}
}
}
}
/**
* Give the colour shown worst a place of its own, taken from the two colours most alike (merged into
* one), when the frame is shown better that way. This is how a small object of a new colour gets it.
*/
#swap(n) {
const { centres, weights } = this;
const K = this.count;
if (K < 3) return false;
const k = this.#worst(n);
let cost = Infinity;
let a = -1;
let b = -1;
for (let i = 0; i < K; i++) {
for (let j = i + 1; j < K; j++) {
const total = weights[i] + weights[j];
const c = total > 0 ? ((weights[i] * weights[j]) / total) * distance2(centres, 3 * i, centres, 3 * j) : 0;
if (c < cost) {
cost = c;
a = i;
b = j;
}
}
}
if (this.errors[k] <= 2 * cost) return false;
const total = weights[a] + weights[b];
const [keep, drop] = weights[a] >= weights[b] ? [a, b] : [b, a];
if (total > 0) for (let c = 0; c < 3; c++) centres[3 * keep + c] = (weights[a] * centres[3 * a + c] + weights[b] * centres[3 * b + c]) / total;
centres.set(this.points.subarray(3 * k, 3 * k + 3), 3 * drop);
this.jumped[drop] = 1;
return true;
}
/** Show the fitted colours at once. */
settle() {
this.jumped.fill(1);
this.ease(0);
}
/** Move the shown colours toward the fitted ones: `dt` seconds have passed. Colours that changed place jump. */
ease(dt) {
const k = 1 - Math.exp(-dt / 0.15);
for (let j = 0; j < this.count; j++) {
const f = this.jumped[j] ? 1 : k;
this.jumped[j] = 0;
for (let c = 0; c < 3; c++) this.matched[3 * j + c] += f * (this.centres[3 * j + c] - this.matched[3 * j + c]);
const L = this.matched[3 * j];
const light = 2 * L - 1;
const a = (this.matched[3 * j + 1] / CHROMA) * SATURATION - 0.4 * WARMTH * light;
const b = (this.matched[3 * j + 2] / CHROMA) * SATURATION + WARMTH * light;
toLinearRgb(L + CONTRAST * (L - 0.5) * (1 - Math.abs(light)), a, b, this.colours, 3 * j);
}
}
}
function distance2(p, i, q, j) {
const dx = p[i] - q[j];
const dy = p[i + 1] - q[j + 1];
const dz = p[i + 2] - q[j + 2];
return dx * dx + dy * dy + dz * dz;
}