File size: 10,084 Bytes
352b7b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
// 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;
}