Debian Codegraph @

node/colorjs.io/src/spaces/okhsl.js

raw
1 // Okhsl class.
2 //
3 // ---- License ----
4 //
5 // Copyright (c) 2021 Björn Ottosson
6 //
7 // Permission is hereby granted, free of charge, to any person obtaining a copy of
8 // this software and associated documentation files (the "Software"), to deal in
9 // the Software without restriction, including without limitation the rights to
10 // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
11 // of the Software, and to permit persons to whom the Software is furnished to do
12 // so, subject to the following conditions:
13 //
14 // The above copyright notice and this permission notice shall be included in all
15 // copies or substantial portions of the Software.
16 //
17 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 // SOFTWARE.
24 import ColorSpace from "../ColorSpace.js";
25 import RGBColorSpace from "../RGBColorSpace.js";
26 import HSL from "./hsl.js";
27 import Oklab from "./oklab.js";
28 import { spow, multiply_v3_m3x3 } from "../util.js";
29 import { constrain } from "../angles.js";
30
31 /** @import { Matrix3x3, Vector3 } from "../types.js" */
32
33 // Type re-exports
34 /** @typedef {import("../types.js").OKCoeff} OKCoeff */
35
36 export const tau = 2 * Math.PI;
37
38 /**
39 * Matrices used by this color space (Oklab's, plus its own),
40 * also available as `Okhsl.M`
41 * @type {Record<string, Matrix3x3>}
42 */
43 // prettier-ignore
44 export const M = {
45 ...Oklab.M,
46 toLMS: [
47 [0.4122214694707629, 0.5363325372617349, 0.0514459932675022],
48 [0.2119034958178251, 0.6806995506452344, 0.1073969535369405],
49 [0.0883024591900564, 0.2817188391361215, 0.6299787016738222],
50 ],
51 toSRGBLinear: [
52 [ 4.0767416360759583, -3.3077115392580629, 0.2309699031821043],
53 [-1.2684379732850315, 2.6097573492876882, -0.3413193760026570],
54 [-0.0041960761386756, -0.7034186179359362, 1.7076146940746117],
55 ],
56 };
57
58 /** @type {OKCoeff} */
59 export const RGBCoeff = [
60 // Red
61 [
62 // Limit
63 [-1.8817031, -0.80936501],
64 // `Kn` coefficients
65 [1.19086277, 1.76576728, 0.59662641, 0.75515197, 0.56771245],
66 ],
67 // Green
68 [
69 // Limit
70 [1.8144408, -1.19445267],
71 // `Kn` coefficients
72 [0.73956515, -0.45954404, 0.08285427, 0.12541073, -0.14503204],
73 ],
74 // Blue
75 [
76 // Limit
77 [0.13110758, 1.81333971],
78 // `Kn` coefficients
79 [1.35733652, -0.00915799, -1.1513021, -0.50559606, 0.00692167],
80 ],
81 ];
82
83 const floatMax = Number.MAX_VALUE;
84 const K1 = 0.206;
85 const K2 = 0.03;
86 const K3 = (1.0 + K1) / (1.0 + K2);
87
88 function vdot (a, b) {
89 // Dot two vectors
90
91 let l = a.length;
92 if (l !== b.length) {
93 throw new Error(`Vectors of size ${l} and ${b.length} are not aligned`);
94 }
95
96 let s = 0.0;
97 a.forEach((c, i) => {
98 s += c * b[i];
99 });
100
101 return s;
102 }
103
104 /**
105 * Toe function for L_r
106 * @param {number} x
107 */
108 export function toe (x) {
109 return 0.5 * (K3 * x - K1 + Math.sqrt((K3 * x - K1) * (K3 * x - K1) + 4 * K2 * K3 * x));
110 }
111
112 /**
113 * Inverse toe function for L_r
114 * @param {number} x
115 */
116 export function toeInv (x) {
117 return (x ** 2 + K1 * x) / (K3 * (x + K2));
118 }
119
120 /**
121 * @param {readonly [number, number]} cusp
122 * @returns {[number, number]}
123 */
124 export function toSt (cusp) {
125 // To ST.
126
127 let [l, c] = cusp;
128 return [c / l, c / (1 - l)];
129 }
130
131 function getStMid (a, b) {
132 // Returns a smooth approximation of the location of the cusp.
133 //
134 // This polynomial was created by an optimization process.
135 // It has been designed so that S_mid < S_max and T_mid < T_max.
136
137 // prettier-ignore
138 let s = 0.11516993 + 1.0 / (
139 7.44778970 + 4.15901240 * b +
140 a * (
141 -2.19557347 + 1.75198401 * b +
142 a * (
143 -2.13704948 - 10.02301043 * b +
144 a * (
145 -4.24894561 + 5.38770819 * b + 4.69891013 * a
146 )
147 )
148 )
149 );
150
151 // prettier-ignore
152 let t = 0.11239642 + 1.0 / (
153 1.61320320 - 0.68124379 * b +
154 a * (
155 0.40370612 + 0.90148123 * b +
156 a * (
157 -0.27087943 + 0.61223990 * b +
158 a * (
159 0.00299215 - 0.45399568 * b - 0.14661872 * a
160 )
161 )
162 )
163 );
164
165 return [s, t];
166 }
167
168 /**
169 * @param {Vector3} lab
170 * @param {Matrix3x3} lmsToRgb
171 */
172 export function oklabToLinearRGB (lab, lmsToRgb) {
173 // Convert from Oklab to linear RGB.
174 //
175 // Can be any gamut as long as `lmsToRgb` is a matrix
176 // that transform the LMS values to the linear RGB space.
177
178 let lms = multiply_v3_m3x3(lab, M.LabtoLMS);
179
180 lms[0] = lms[0] ** 3;
181 lms[1] = lms[1] ** 3;
182 lms[2] = lms[2] ** 3;
183
184 return multiply_v3_m3x3(lms, lmsToRgb, lms);
185 }
186
187 /**
188 * @param {number} a
189 * @param {number} b
190 * @param {Matrix3x3} lmsToRgb
191 * @param {OKCoeff} okCoeff
192 * @returns {[number, number]}
193 * @todo Could probably make these types more specific/better-documented if desired
194 */
195 export function findCusp (a, b, lmsToRgb, okCoeff) {
196 // Finds L_cusp and C_cusp for a given hue.
197 //
198 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
199
200 // First, find the maximum saturation (saturation `S = C/L`)
201 let sCusp = computeMaxSaturation(a, b, lmsToRgb, okCoeff);
202
203 // Convert to linear RGB to find the first point where at least one of r, g or b >= 1:
204 let rgb = oklabToLinearRGB([1, sCusp * a, sCusp * b], lmsToRgb);
205 let lCusp = spow(1.0 / Math.max(...rgb), 1 / 3);
206 let cCusp = lCusp * sCusp;
207
208 return [lCusp, cCusp];
209 }
210
211 /**
212 * @param {number} a
213 * @param {number} b
214 * @param {number} l1
215 * @param {number} c1
216 * @param {number} l0
217 * @param {Matrix3x3} lmsToRgb
218 * @param {OKCoeff} okCoeff
219 * @param {[number, number]} cusp
220 * @returns {Number}
221 * @todo Could probably make these types more specific/better-documented if desired
222 */
223 export function findGamutIntersection (a, b, l1, c1, l0, lmsToRgb, okCoeff, cusp) {
224 // Finds intersection of the line.
225 //
226 // Defined by the following:
227 //
228 // ```
229 // L = L0 * (1 - t) + t * L1
230 // C = t * C1
231 // ```
232 //
233 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
234
235 let t;
236
237 if (cusp === undefined) {
238 cusp = findCusp(a, b, lmsToRgb, okCoeff);
239 }
240
241 // Find the intersection for upper and lower half separately
242 if ((l1 - l0) * cusp[1] - (cusp[0] - l0) * c1 <= 0.0) {
243 // Lower half
244 t = (cusp[1] * l0) / (c1 * cusp[0] + cusp[1] * (l0 - l1));
245 }
246 else {
247 // Upper half
248
249 // First intersect with triangle
250 t = (cusp[1] * (l0 - 1.0)) / (c1 * (cusp[0] - 1.0) + cusp[1] * (l0 - l1));
251
252 // Then one step Halley's method
253 let dl = l1 - l0;
254 let dc = c1;
255
256 let kl = vdot(M.LabtoLMS[0].slice(1), [a, b]);
257 let km = vdot(M.LabtoLMS[1].slice(1), [a, b]);
258 let ks = vdot(M.LabtoLMS[2].slice(1), [a, b]);
259
260 let ldt_ = dl + dc * kl;
261 let mdt_ = dl + dc * km;
262 let sdt_ = dl + dc * ks;
263
264 // If higher accuracy is required, 2 or 3 iterations of the following block can be used:
265 let L = l0 * (1.0 - t) + t * l1;
266 let C = t * c1;
267
268 let l_ = L + C * kl;
269 let m_ = L + C * km;
270 let s_ = L + C * ks;
271
272 let l = l_ ** 3;
273 let m = m_ ** 3;
274 let s = s_ ** 3;
275
276 let ldt = 3 * ldt_ * l_ ** 2;
277 let mdt = 3 * mdt_ * m_ ** 2;
278 let sdt = 3 * sdt_ * s_ ** 2;
279
280 let ldt2 = 6 * ldt_ ** 2 * l_;
281 let mdt2 = 6 * mdt_ ** 2 * m_;
282 let sdt2 = 6 * sdt_ ** 2 * s_;
283
284 let r_ = vdot(lmsToRgb[0], [l, m, s]) - 1;
285 let r1 = vdot(lmsToRgb[0], [ldt, mdt, sdt]);
286 let r2 = vdot(lmsToRgb[0], [ldt2, mdt2, sdt2]);
287
288 let ur = r1 / (r1 * r1 - 0.5 * r_ * r2);
289 let tr = -r_ * ur;
290
291 let g_ = vdot(lmsToRgb[1], [l, m, s]) - 1;
292 let g1 = vdot(lmsToRgb[1], [ldt, mdt, sdt]);
293 let g2 = vdot(lmsToRgb[1], [ldt2, mdt2, sdt2]);
294
295 let ug = g1 / (g1 * g1 - 0.5 * g_ * g2);
296 let tg = -g_ * ug;
297
298 let b_ = vdot(lmsToRgb[2], [l, m, s]) - 1;
299 let b1 = vdot(lmsToRgb[2], [ldt, mdt, sdt]);
300 let b2 = vdot(lmsToRgb[2], [ldt2, mdt2, sdt2]);
301
302 let ub = b1 / (b1 * b1 - 0.5 * b_ * b2);
303 let tb = -b_ * ub;
304
305 tr = ur >= 0.0 ? tr : floatMax;
306 tg = ug >= 0.0 ? tg : floatMax;
307 tb = ub >= 0.0 ? tb : floatMax;
308
309 t += Math.min(tr, Math.min(tg, tb));
310 }
311
312 return t;
313 }
314
315 function getCs (lab, lmsToRgb, okCoeff) {
316 // Get Cs
317
318 let [l, a, b] = lab;
319
320 let cusp = findCusp(a, b, lmsToRgb, okCoeff);
321
322 let cMax = findGamutIntersection(a, b, l, 1, l, lmsToRgb, okCoeff, cusp);
323 let stMax = toSt(cusp);
324
325 // Scale factor to compensate for the curved part of gamut shape:
326 let k = cMax / Math.min(l * stMax[0], (1 - l) * stMax[1]);
327
328 let stMid = getStMid(a, b);
329
330 // Use a soft minimum function, instead of a sharp triangle shape to get a smooth value for chroma.
331 let ca = l * stMid[0];
332 let cb = (1.0 - l) * stMid[1];
333 let cMid = 0.9 * k * Math.sqrt(Math.sqrt(1.0 / (1.0 / ca ** 4 + 1.0 / cb ** 4)));
334
335 // For `C_0`, the shape is independent of hue, so `ST` are constant.
336 // Values picked to roughly be the average values of `ST`.
337 ca = l * 0.4;
338 cb = (1.0 - l) * 0.8;
339
340 // Use a soft minimum function, instead of a sharp triangle shape to get a smooth value for chroma.
341 let c0 = Math.sqrt(1.0 / (1.0 / ca ** 2 + 1.0 / cb ** 2));
342
343 return [c0, cMid, cMax];
344 }
345
346 function computeMaxSaturation (a, b, lmsToRgb, okCoeff) {
347 // Finds the maximum saturation possible for a given hue that fits in RGB.
348 //
349 // Saturation here is defined as `S = C/L`.
350 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
351
352 // Max saturation will be when one of r, g or b goes below zero.
353
354 // Select different coefficients depending on which component goes below zero first.
355
356 let k0, k1, k2, k3, k4, wl, wm, ws;
357
358 if (vdot(okCoeff[0][0], [a, b]) > 1) {
359 // Red component
360 [k0, k1, k2, k3, k4] = okCoeff[0][1];
361 [wl, wm, ws] = lmsToRgb[0];
362 }
363 else if (vdot(okCoeff[1][0], [a, b]) > 1) {
364 // Green component
365 [k0, k1, k2, k3, k4] = okCoeff[1][1];
366 [wl, wm, ws] = lmsToRgb[1];
367 }
368 else {
369 // Blue component
370 [k0, k1, k2, k3, k4] = okCoeff[2][1];
371 [wl, wm, ws] = lmsToRgb[2];
372 }
373
374 // Approximate max saturation using a polynomial:
375 let sat = k0 + k1 * a + k2 * b + k3 * a ** 2 + k4 * a * b;
376
377 // Do one step Halley's method to get closer.
378 // This gives an error less than 10e6, except for some blue hues where the `dS/dh` is close to infinite.
379 // This should be sufficient for most applications, otherwise do two/three steps.
380
381 let kl = vdot(M.LabtoLMS[0].slice(1), [a, b]);
382 let km = vdot(M.LabtoLMS[1].slice(1), [a, b]);
383 let ks = vdot(M.LabtoLMS[2].slice(1), [a, b]);
384
385 let l_ = 1.0 + sat * kl;
386 let m_ = 1.0 + sat * km;
387 let s_ = 1.0 + sat * ks;
388
389 let l = l_ ** 3;
390 let m = m_ ** 3;
391 let s = s_ ** 3;
392
393 let lds = 3.0 * kl * l_ ** 2;
394 let mds = 3.0 * km * m_ ** 2;
395 let sds = 3.0 * ks * s_ ** 2;
396
397 let lds2 = 6.0 * kl ** 2 * l_;
398 let mds2 = 6.0 * km ** 2 * m_;
399 let sds2 = 6.0 * ks ** 2 * s_;
400
401 let f = wl * l + wm * m + ws * s;
402 let f1 = wl * lds + wm * mds + ws * sds;
403 let f2 = wl * lds2 + wm * mds2 + ws * sds2;
404
405 sat = sat - (f * f1) / (f1 ** 2 - 0.5 * f * f2);
406
407 return sat;
408 }
409
410 function okhslToOklab (hsl, lmsToRgb, okCoeff) {
411 // Convert Okhsl to Oklab.
412
413 let [h, s, l] = hsl;
414 let L = toeInv(l);
415 let a = null;
416 let b = null;
417 h = constrain(h) / 360.0;
418
419 if (L !== 0.0 && L !== 1.0 && s !== 0) {
420 let a_ = Math.cos(tau * h);
421 let b_ = Math.sin(tau * h);
422
423 let [c0, cMid, cMax] = getCs([L, a_, b_], lmsToRgb, okCoeff);
424
425 // Interpolate the three values for C so that:
426 // ```
427 // At s=0: dC/ds = C_0, C=0
428 // At s=0.8: C=C_mid
429 // At s=1.0: C=C_max
430 // ```
431
432 let mid = 0.8;
433 let midInv = 1.25;
434 let t, k0, k1, k2;
435
436 if (s < mid) {
437 t = midInv * s;
438 k0 = 0.0;
439 k1 = mid * c0;
440 k2 = 1.0 - k1 / cMid;
441 }
442 else {
443 t = 5 * (s - 0.8);
444 k0 = cMid;
445 k1 = (0.2 * cMid ** 2 * 1.25 ** 2) / c0;
446 k2 = 1.0 - k1 / (cMax - cMid);
447 }
448
449 let c = k0 + (t * k1) / (1.0 - k2 * t);
450
451 a = c * a_;
452 b = c * b_;
453 }
454
455 return [L, a, b];
456 }
457
458 function oklabToOkhsl (lab, lmsToRgb, okCoeff) {
459 // Oklab to Okhsl.
460
461 // Epsilon for lightness should approach close to 32 bit lightness
462 // Epsilon for saturation just needs to be sufficiently close when denoting achromatic
463 let εL = 1e-7;
464 let εS = 1e-4;
465 let L = lab[0];
466 let s = 0.0;
467 let l = toe(L);
468
469 let c = Math.sqrt(lab[1] ** 2 + lab[2] ** 2);
470 let h = 0.5 + Math.atan2(-lab[2], -lab[1]) / tau;
471
472 if (l !== 0.0 && l !== 1.0 && c !== 0) {
473 let a_ = lab[1] / c;
474 let b_ = lab[2] / c;
475
476 let [c0, cMid, cMax] = getCs([L, a_, b_], lmsToRgb, okCoeff);
477
478 let mid = 0.8;
479 let midInv = 1.25;
480 let k0, k1, k2, t;
481
482 if (c < cMid) {
483 k1 = mid * c0;
484 k2 = 1.0 - k1 / cMid;
485
486 t = c / (k1 + k2 * c);
487 s = t * mid;
488 }
489 else {
490 k0 = cMid;
491 k1 = (0.2 * cMid ** 2 * midInv ** 2) / c0;
492 k2 = 1.0 - k1 / (cMax - cMid);
493
494 t = (c - k0) / (k1 + k2 * (c - k0));
495 s = mid + 0.2 * t;
496 }
497 }
498
499 const achromatic = Math.abs(s) < εS;
500 if (achromatic || l === 0.0 || Math.abs(1 - l) < εL) {
501 h = null;
502 // Due to floating point imprecision near lightness of 1, we can end up
503 // with really high around white, this is to provide consistency as
504 // saturation can be really high for white due this imprecision.
505 if (!achromatic) {
506 s = 0.0;
507 }
508 }
509 else {
510 h = constrain(h * 360);
511 }
512
513 return [h, s, l];
514 }
515
516 const Okhsl = new ColorSpace({
517 id: "okhsl",
518 name: "Okhsl",
519 coords: {
520 h: {
521 refRange: [0, 360],
522 type: "angle",
523 name: "Hue",
524 },
525 s: {
526 range: [0, 1],
527 name: "Saturation",
528 },
529 l: {
530 range: [0, 1],
531 name: "Lightness",
532 },
533 },
534
535 base: Oklab,
536 gamutSpace: "self",
537
538 M,
539
540 // Convert Oklab to Okhsl
541 fromBase (lab) {
542 return oklabToOkhsl(lab, M.toSRGBLinear, RGBCoeff);
543 },
544
545 // Convert Okhsl to Oklab
546 toBase (hsl) {
547 return okhslToOklab(hsl, M.toSRGBLinear, RGBCoeff);
548 },
549
550 formats: {
551 color: {
552 id: "--okhsl",
553 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"],
554 },
555 },
556 });
557
558 Okhsl.rgbGamut = new RGBColorSpace({
559 id: "okhsl-prism",
560 cssId: "--okhsl-prism",
561 name: "Okhsl Prism",
562 base: Okhsl,
563 fromBase (hsl) {
564 return HSL.toBase([hsl[0], hsl[1] * 100, hsl[2] * 100]);
565 },
566 toBase (rgb) {
567 const hsl = HSL.fromBase(rgb);
568 hsl[1] /= 100;
569 hsl[2] /= 100;
570 return hsl;
571 },
572 });
573
574 export default Okhsl;