| 1 |
var Color = (function () { |
| 2 |
'use strict'; |
| 3 |
|
| 4 |
/** @import { Matrix3x3, Vector3 } from "./types.js" */ |
| 5 |
|
| 6 |
/** |
| 7 |
* A is m x n. B is n x p. product is m x p. |
| 8 |
* |
| 9 |
* Array arguments are treated like vectors: |
| 10 |
* - A becomes 1 x n |
| 11 |
* - B becomes n x 1 |
| 12 |
* |
| 13 |
* Returns Matrix m x p or equivalent array or number |
| 14 |
* |
| 15 |
* @overload |
| 16 |
* @param {number[]} A Vector 1 x n |
| 17 |
* @param {number[]} B Vector n x 1 |
| 18 |
* @returns {number} Scalar number |
| 19 |
* |
| 20 |
* @overload |
| 21 |
* @param {number[][]} A Matrix m x n |
| 22 |
* @param {number[]} B Vector n x 1 |
| 23 |
* @returns {number[]} Array with length m |
| 24 |
* |
| 25 |
* @overload |
| 26 |
* @param {number[]} A Vector 1 x n |
| 27 |
* @param {number[][]} B Matrix n x p |
| 28 |
* @returns {number[]} Array with length p |
| 29 |
* |
| 30 |
* @overload |
| 31 |
* @param {number[][]} A Matrix m x n |
| 32 |
* @param {number[][]} B Matrix n x p |
| 33 |
* @returns {number[][]} Matrix m x p |
| 34 |
* |
| 35 |
* @param {number[] | number[][]} A Matrix m x n or a vector |
| 36 |
* @param {number[] | number[][]} B Matrix n x p or a vector |
| 37 |
* @returns {number | number[] | number[][]} Matrix m x p or equivalent array or number |
| 38 |
*/ |
| 39 |
function multiplyMatrices (A, B) { |
| 40 |
let m = A.length; |
| 41 |
/** @type {number[][]} */ |
| 42 |
let AM; |
| 43 |
/** @type {number[][]} */ |
| 44 |
let BM; |
| 45 |
let aVec = false; |
| 46 |
let bVec = false; |
| 47 |
|
| 48 |
if (!Array.isArray(A[0])) { |
| 49 |
// A is vector, convert to [[a, b, c, ...]] |
| 50 |
AM = [/** @type {number[]} */ (A)]; |
| 51 |
m = AM.length; |
| 52 |
aVec = true; |
| 53 |
} |
| 54 |
else { |
| 55 |
AM = /** @type {number[][]} */ (A); |
| 56 |
} |
| 57 |
|
| 58 |
if (!Array.isArray(B[0])) { |
| 59 |
// B is vector, convert to [[a], [b], [c], ...]] |
| 60 |
BM = B.length > 0 ? B.map(x => [x]) : [[]]; // Avoid mapping empty array |
| 61 |
bVec = true; |
| 62 |
} |
| 63 |
else { |
| 64 |
BM = /** @type {number[][]} */ (B); |
| 65 |
} |
| 66 |
|
| 67 |
let p = BM[0].length; |
| 68 |
let BM_cols = BM[0].map((_, i) => BM.map(x => x[i])); // transpose B |
| 69 |
/** @type {number[] | number[][]} */ |
| 70 |
let product = AM.map(row => |
| 71 |
BM_cols.map(col => { |
| 72 |
let ret = 0; |
| 73 |
|
| 74 |
if (!Array.isArray(row)) { |
| 75 |
for (let c of col) { |
| 76 |
ret += row * c; |
| 77 |
} |
| 78 |
|
| 79 |
return ret; |
| 80 |
} |
| 81 |
|
| 82 |
for (let i = 0; i < row.length; i++) { |
| 83 |
ret += row[i] * (col[i] || 0); |
| 84 |
} |
| 85 |
|
| 86 |
return ret; |
| 87 |
})); |
| 88 |
|
| 89 |
if (m === 1 && aVec) { |
| 90 |
product = product[0]; // Avoid [[a, b, c, ...]] |
| 91 |
} |
| 92 |
if (p === 1 && bVec) { |
| 93 |
if (m === 1 && aVec) { |
| 94 |
return product[0]; // Avoid [[a]], return a number |
| 95 |
} |
| 96 |
else { |
| 97 |
return product.map(x => x[0]); // Avoid [[a], [b], [c], ...]] |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
return product; |
| 102 |
} |
| 103 |
|
| 104 |
// dot3 and transform functions adapted from https://github.com/texel-org/color/blob/9793c7d4d02b51f068e0f3fd37131129a4270396/src/core.js |
| 105 |
// |
| 106 |
// The MIT License (MIT) |
| 107 |
// Copyright (c) 2024 Matt DesLauriers |
| 108 |
|
| 109 |
// Permission is hereby granted, free of charge, to any person obtaining a copy |
| 110 |
// of this software and associated documentation files (the "Software"), to deal |
| 111 |
// in the Software without restriction, including without limitation the rights |
| 112 |
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 113 |
// copies of the Software, and to permit persons to whom the Software is |
| 114 |
// furnished to do so, subject to the following conditions: |
| 115 |
|
| 116 |
// The above copyright notice and this permission notice shall be included in all |
| 117 |
// copies or substantial portions of the Software. |
| 118 |
|
| 119 |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 120 |
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 121 |
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. |
| 122 |
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, |
| 123 |
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR |
| 124 |
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE |
| 125 |
// OR OTHER DEALINGS IN THE SOFTWARE. |
| 126 |
|
| 127 |
/** |
| 128 |
* Returns the dot product of two vectors each with a length of 3. |
| 129 |
* |
| 130 |
* @param {Vector3} a |
| 131 |
* @param {Vector3} b |
| 132 |
* @returns {number} |
| 133 |
*/ |
| 134 |
function dot3 (a, b) { |
| 135 |
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; |
| 136 |
} |
| 137 |
|
| 138 |
/** |
| 139 |
* Transforms a vector of length 3 by a 3x3 matrix. Specify the same input and output |
| 140 |
* vector to transform in place. |
| 141 |
* |
| 142 |
* @param {Vector3} input |
| 143 |
* @param {Matrix3x3} matrix |
| 144 |
* @param {Vector3} [out] |
| 145 |
* @returns {Vector3} |
| 146 |
*/ |
| 147 |
function multiply_v3_m3x3 (input, matrix, out = [0, 0, 0]) { |
| 148 |
const x = dot3(input, matrix[0]); |
| 149 |
const y = dot3(input, matrix[1]); |
| 150 |
const z = dot3(input, matrix[2]); |
| 151 |
out[0] = x; |
| 152 |
out[1] = y; |
| 153 |
out[2] = z; |
| 154 |
return out; |
| 155 |
} |
| 156 |
|
| 157 |
/** |
| 158 |
* Various utility functions |
| 159 |
*/ |
| 160 |
|
| 161 |
|
| 162 |
/** |
| 163 |
* Check if a value is a string (including a String object) |
| 164 |
* @param {any} str - Value to check |
| 165 |
* @returns {str is string} |
| 166 |
*/ |
| 167 |
function isString (str) { |
| 168 |
return type(str) === "string"; |
| 169 |
} |
| 170 |
|
| 171 |
/** |
| 172 |
* Determine the internal JavaScript [[Class]] of an object. |
| 173 |
* @param {any} o - Value to check |
| 174 |
* @returns {string} |
| 175 |
*/ |
| 176 |
function type (o) { |
| 177 |
let str = Object.prototype.toString.call(o); |
| 178 |
|
| 179 |
return (str.match(/^\[object\s+(.*?)\]$/)[1] || "").toLowerCase(); |
| 180 |
} |
| 181 |
|
| 182 |
/** |
| 183 |
* @param {number} n |
| 184 |
* @param {{ precision?: number | undefined, unit?: string | undefined }} options |
| 185 |
* @returns {string} |
| 186 |
*/ |
| 187 |
function serializeNumber (n, { precision = 16, unit }) { |
| 188 |
if (isNone(n)) { |
| 189 |
return "none"; |
| 190 |
} |
| 191 |
|
| 192 |
n = +toPrecision(n, precision); |
| 193 |
|
| 194 |
return n + (unit ?? ""); |
| 195 |
} |
| 196 |
|
| 197 |
/** |
| 198 |
* Check if a value corresponds to a none argument |
| 199 |
* @param {any} n - Value to check |
| 200 |
* @returns {n is null} |
| 201 |
*/ |
| 202 |
function isNone (n) { |
| 203 |
return n === null; |
| 204 |
} |
| 205 |
|
| 206 |
/** |
| 207 |
* Replace none values with 0 |
| 208 |
* @param {number | null} n |
| 209 |
* @returns {number} |
| 210 |
*/ |
| 211 |
function skipNone (n) { |
| 212 |
return isNone(n) ? 0 : n; |
| 213 |
} |
| 214 |
|
| 215 |
/** |
| 216 |
* Round a number to a certain number of significant digits |
| 217 |
* @param {number} n - The number to round |
| 218 |
* @param {number} precision - Number of significant digits |
| 219 |
*/ |
| 220 |
function toPrecision (n, precision) { |
| 221 |
if (n === 0) { |
| 222 |
return 0; |
| 223 |
} |
| 224 |
let integer = ~~n; |
| 225 |
let digits = 0; |
| 226 |
if (integer && precision) { |
| 227 |
digits = ~~Math.log10(Math.abs(integer)) + 1; |
| 228 |
} |
| 229 |
const multiplier = 10.0 ** (precision - digits); |
| 230 |
return Math.floor(n * multiplier + 0.5) / multiplier; |
| 231 |
} |
| 232 |
|
| 233 |
/** |
| 234 |
* Interpolate between two values, either of which may be a `none` value. |
| 235 |
* A `none` endpoint is treated as having the other endpoint's value; |
| 236 |
* if both are `none`, the result is `none` as well. |
| 237 |
* @param {number | null} start |
| 238 |
* @param {number | null} end |
| 239 |
* @param {number} p |
| 240 |
* @returns {number | null} |
| 241 |
*/ |
| 242 |
function interpolate (start, end, p) { |
| 243 |
if (isNone(start) || isNaN(start)) { |
| 244 |
return end; |
| 245 |
} |
| 246 |
|
| 247 |
if (isNone(end) || isNaN(end)) { |
| 248 |
return start; |
| 249 |
} |
| 250 |
|
| 251 |
return start + (end - start) * p; |
| 252 |
} |
| 253 |
|
| 254 |
/** |
| 255 |
* @param {number} start |
| 256 |
* @param {number} end |
| 257 |
* @param {number} value |
| 258 |
*/ |
| 259 |
function interpolateInv (start, end, value) { |
| 260 |
return (value - start) / (end - start); |
| 261 |
} |
| 262 |
|
| 263 |
/** |
| 264 |
* @param {[number, number]} from |
| 265 |
* @param {[number, number]} to |
| 266 |
* @param {number} value |
| 267 |
*/ |
| 268 |
function mapRange (from, to, value) { |
| 269 |
if ( |
| 270 |
!from || |
| 271 |
!to || |
| 272 |
from === to || |
| 273 |
(from[0] === to[0] && from[1] === to[1]) || |
| 274 |
isNaN(value) || |
| 275 |
value === null |
| 276 |
) { |
| 277 |
// Ranges missing or the same |
| 278 |
return value; |
| 279 |
} |
| 280 |
|
| 281 |
return interpolate(to[0], to[1], interpolateInv(from[0], from[1], value)); |
| 282 |
} |
| 283 |
|
| 284 |
/** |
| 285 |
* Clamp value between the minimum and maximum |
| 286 |
* @param {number} min minimum value to return |
| 287 |
* @param {number} val the value to return if it is between min and max |
| 288 |
* @param {number} max maximum value to return |
| 289 |
*/ |
| 290 |
function clamp (min, val, max) { |
| 291 |
return Math.max(Math.min(max, val), min); |
| 292 |
} |
| 293 |
|
| 294 |
/** |
| 295 |
* Copy sign of one value to another. |
| 296 |
* @param {number} to - Number to copy sign to |
| 297 |
* @param {number} from - Number to copy sign from |
| 298 |
*/ |
| 299 |
function copySign (to, from) { |
| 300 |
return Math.sign(to) === Math.sign(from) ? to : -to; |
| 301 |
} |
| 302 |
|
| 303 |
/** |
| 304 |
* Perform pow on a signed number and copy sign to result |
| 305 |
* @param {number} base The base number |
| 306 |
* @param {number} exp The exponent |
| 307 |
*/ |
| 308 |
function spow (base, exp) { |
| 309 |
return copySign(Math.abs(base) ** exp, base); |
| 310 |
} |
| 311 |
|
| 312 |
/** |
| 313 |
* Perform a divide, but return zero if the denominator is zero |
| 314 |
* @param {number} n The numerator |
| 315 |
* @param {number} d The denominator |
| 316 |
*/ |
| 317 |
function zdiv (n, d) { |
| 318 |
return d === 0 ? 0 : n / d; |
| 319 |
} |
| 320 |
|
| 321 |
/** |
| 322 |
* Perform a bisect on a sorted list and locate the insertion point for |
| 323 |
* a value in arr to maintain sorted order. |
| 324 |
* @param {number[]} arr - array of sorted numbers |
| 325 |
* @param {number} value - value to find insertion point for |
| 326 |
* @param {number} lo - used to specify a the low end of a subset of the list |
| 327 |
* @param {number} hi - used to specify a the high end of a subset of the list |
| 328 |
*/ |
| 329 |
function bisectLeft (arr, value, lo = 0, hi = arr.length) { |
| 330 |
while (lo < hi) { |
| 331 |
const mid = (lo + hi) >> 1; |
| 332 |
if (arr[mid] < value) { |
| 333 |
lo = mid + 1; |
| 334 |
} |
| 335 |
else { |
| 336 |
hi = mid; |
| 337 |
} |
| 338 |
} |
| 339 |
return lo; |
| 340 |
} |
| 341 |
|
| 342 |
/** |
| 343 |
* Determines whether an argument is an instance of a constructor, including subclasses. |
| 344 |
* This is done by first just checking `instanceof`, |
| 345 |
* and then comparing the string names of the constructors if that fails. |
| 346 |
* @param {any} arg |
| 347 |
* @param {C} constructor |
| 348 |
* @template {new (...args: any) => any} C |
| 349 |
* @returns {arg is InstanceType<C>} |
| 350 |
*/ |
| 351 |
function isInstance (arg, constructor) { |
| 352 |
if (arg instanceof constructor) { |
| 353 |
return true; |
| 354 |
} |
| 355 |
|
| 356 |
const targetName = constructor.name; |
| 357 |
|
| 358 |
while (arg) { |
| 359 |
const proto = Object.getPrototypeOf(arg); |
| 360 |
const constructorName = proto?.constructor?.name; |
| 361 |
if (constructorName === targetName) { |
| 362 |
return true; |
| 363 |
} |
| 364 |
if (!constructorName || constructorName === "Object") { |
| 365 |
return false; |
| 366 |
} |
| 367 |
arg = proto; |
| 368 |
} |
| 369 |
|
| 370 |
return false; |
| 371 |
} |
| 372 |
|
| 373 |
/** |
| 374 |
* Generate a matrix of size NxN with the given diagonal values of length N. |
| 375 |
* |
| 376 |
* @param {number[]} values |
| 377 |
* @returns {number[][]} |
| 378 |
*/ |
| 379 |
function diag (values) { |
| 380 |
const n = values.length; |
| 381 |
const matrix = []; |
| 382 |
for (let i = 0; i < n; i++) { |
| 383 |
matrix[i] = []; |
| 384 |
for (let j = 0; j < n; j++) { |
| 385 |
matrix[i][j] = i === j ? values[i] : 0; |
| 386 |
} |
| 387 |
} |
| 388 |
return matrix; |
| 389 |
} |
| 390 |
|
| 391 |
/** |
| 392 |
* Calculate the LU decomposition of an NxN matrix. |
| 393 |
* |
| 394 |
* P is returned as PA = UL or A = P'UL which follows Matlab and Octave opposed to Scipy which returns P as |
| 395 |
* A = PUL or P'A = UL. For matrix inverse, we need P such that PA = UL and it is faster not having to invert |
| 396 |
* P, even if we can invert it fairly fast as it is just a shuffled identity matrix. |
| 397 |
* |
| 398 |
* P is returned as a permutation matrix unless pIndices is true, in which case P would be returned as |
| 399 |
* a vector containing the indexes such that A[P,:] = L*U. |
| 400 |
* |
| 401 |
* Reference: |
| 402 |
* - https://www.statlect.com/matrix-algebra/Gaussian-elimination |
| 403 |
* - https://www.sciencedirect.com/topics/mathematics/partial-pivoting |
| 404 |
* |
| 405 |
* @overload |
| 406 |
* @param {number[][]} matrix |
| 407 |
* @param {{ pIndices?: false | undefined }} [options] |
| 408 |
* @returns {[number[][], number[][], number[][]]} |
| 409 |
*/ |
| 410 |
/** |
| 411 |
* @overload |
| 412 |
* @param {number[][]} matrix |
| 413 |
* @param {{ pIndices?: true }} [options] |
| 414 |
* @returns {[number[], number[][], number[][]]} |
| 415 |
*/ |
| 416 |
/** |
| 417 |
* @param {number[][]} matrix |
| 418 |
* @param {{ pIndices?: boolean | undefined }} [options] |
| 419 |
* @returns {[number[] | number[][], number[][], number[][]]} |
| 420 |
*/ |
| 421 |
function lu (matrix, { pIndices = false } = {}) { |
| 422 |
let p1, p2, l, u; |
| 423 |
|
| 424 |
const n = matrix.length; |
| 425 |
|
| 426 |
// Initialize the triangle matrices along with the permutation matrix. |
| 427 |
if (pIndices) { |
| 428 |
p1 = Array.from({ length: n }, (_, index) => index); |
| 429 |
l = diag(new Array(n).fill(1)); |
| 430 |
} |
| 431 |
else { |
| 432 |
p2 = diag(new Array(n).fill(1)); |
| 433 |
l = structuredClone(p2); |
| 434 |
} |
| 435 |
u = structuredClone(matrix); |
| 436 |
|
| 437 |
// Create upper and lower triangle in 'u' and 'l'. 'p' tracks the permutation (relative position of rows) |
| 438 |
for (let i = 0; i < n - 1; i++) { |
| 439 |
// Partial pivoting: identify the row with the maximal value in the column |
| 440 |
let j = i; |
| 441 |
let maximum = Math.abs(u[i][i]); |
| 442 |
for (let k = i + 1; k < n; k++) { |
| 443 |
const a = Math.abs(u[k][i]); |
| 444 |
if (a > maximum) { |
| 445 |
j = k; |
| 446 |
maximum = a; |
| 447 |
} |
| 448 |
} |
| 449 |
|
| 450 |
// Partial pivoting: Swap rows |
| 451 |
if (j != i) { |
| 452 |
// Exchange current upper triangle row with row with maximal value at pivot |
| 453 |
// Update permutation matrix as well |
| 454 |
[u[i], u[j]] = [u[j], u[i]]; |
| 455 |
if (pIndices) { |
| 456 |
[p1[i], p1[j]] = [p1[j], p1[i]]; |
| 457 |
} |
| 458 |
else { |
| 459 |
[p2[i], p2[j]] = [p2[j], p2[i]]; |
| 460 |
} |
| 461 |
|
| 462 |
// Only swap columns up to the pivot for the lower triangle, |
| 463 |
// if on first row, there is nothing to swap |
| 464 |
if (i) { |
| 465 |
for (let k = 0; k < i; k++) { |
| 466 |
[l[i][k], l[j][k]] = [l[j][k], l[i][k]]; |
| 467 |
} |
| 468 |
} |
| 469 |
} |
| 470 |
|
| 471 |
// Zero at pivot point, nothing to do |
| 472 |
else if (!maximum) { |
| 473 |
continue; |
| 474 |
} |
| 475 |
|
| 476 |
// We have a pivot point, let's zero out everything above and below |
| 477 |
// the 'l' and 'u' diagonal respectively |
| 478 |
for (let j = i + 1; j < n; j++) { |
| 479 |
const scalar = u[j][i] / u[i][i]; |
| 480 |
for (let k = i; k < n; k++) { |
| 481 |
u[j][k] += -u[i][k] * scalar; |
| 482 |
l[j][k] += l[i][k] * scalar; |
| 483 |
} |
| 484 |
} |
| 485 |
} |
| 486 |
|
| 487 |
if (pIndices) { |
| 488 |
return [p1, l, u]; |
| 489 |
} |
| 490 |
return [p2, l, u]; |
| 491 |
} |
| 492 |
|
| 493 |
/** |
| 494 |
* Forward substitution for solution of ax = b where a and b are matricies. |
| 495 |
* |
| 496 |
* @param {number[][]} a |
| 497 |
* @param {number[][]} b |
| 498 |
* @param {number} n |
| 499 |
* @returns {number[][]} |
| 500 |
*/ |
| 501 |
function forwardSubMatrix (a, b, n) { |
| 502 |
for (let i = 0; i < n; i++) { |
| 503 |
const v = b[i]; |
| 504 |
for (let j = 0; j < i; j++) { |
| 505 |
for (let k = 0; k < n; k++) { |
| 506 |
v[k] -= a[i][j] * b[j][k]; |
| 507 |
} |
| 508 |
} |
| 509 |
for (let j = 0; j < n; j++) { |
| 510 |
v[j] /= a[i][i]; |
| 511 |
} |
| 512 |
} |
| 513 |
return b; |
| 514 |
} |
| 515 |
|
| 516 |
/** |
| 517 |
* Back substitution for solution of ax = b where a and b are matricies. |
| 518 |
* |
| 519 |
* @param {number[][]} a |
| 520 |
* @param {number[][]} b |
| 521 |
* @param {number} n |
| 522 |
* @returns {number[][]} |
| 523 |
*/ |
| 524 |
function backSubMatrix (a, b, n) { |
| 525 |
for (let i = n - 1; i > -1; i--) { |
| 526 |
const v = b[i]; |
| 527 |
for (let j = i + 1; j < n; j++) { |
| 528 |
for (var k = 0; k < n; k++) { |
| 529 |
v[k] -= a[i][j] * b[j][k]; |
| 530 |
} |
| 531 |
} |
| 532 |
for (let j = 0; j < n; j++) { |
| 533 |
b[i][j] /= a[i][i]; |
| 534 |
} |
| 535 |
} |
| 536 |
return b; |
| 537 |
} |
| 538 |
|
| 539 |
/** |
| 540 |
* Forward substitution for solution of ax = b where a is a matrix and b is a vector. |
| 541 |
* |
| 542 |
* @param {number[][]} a |
| 543 |
* @param {number[]} b |
| 544 |
* @param {number} n |
| 545 |
* @returns {number[]} |
| 546 |
*/ |
| 547 |
function forwardSubVector (a, b, n) { |
| 548 |
for (let i = 0; i < n; i++) { |
| 549 |
let v = b[i]; |
| 550 |
for (let j = 0; j < i; j++) { |
| 551 |
v -= a[i][j] * b[j]; |
| 552 |
} |
| 553 |
b[i] = v / a[i][i]; |
| 554 |
} |
| 555 |
return b; |
| 556 |
} |
| 557 |
|
| 558 |
/** |
| 559 |
* Back substitution for solution of ax = b where a is a matrix and b is a vector. |
| 560 |
* |
| 561 |
* @param {number[][]} a |
| 562 |
* @param {number[]} b |
| 563 |
* @param {number} n |
| 564 |
* @returns {number[]} |
| 565 |
*/ |
| 566 |
function backSubVector (a, b, n) { |
| 567 |
for (let i = n - 1; i > -1; i--) { |
| 568 |
let v = b[i]; |
| 569 |
for (let j = i + 1; j < n; j++) { |
| 570 |
v -= a[i][j] * b[j]; |
| 571 |
} |
| 572 |
b[i] = v / a[i][i]; |
| 573 |
} |
| 574 |
return b; |
| 575 |
} |
| 576 |
|
| 577 |
/** |
| 578 |
* Invert a NxN matrix. |
| 579 |
* |
| 580 |
* @param {number[][]} matrix |
| 581 |
* @returns {number[][]} |
| 582 |
*/ |
| 583 |
function inv (matrix) { |
| 584 |
// Calculate the LU decomposition. |
| 585 |
const [p, l, u] = lu(matrix); |
| 586 |
const n = l.length; |
| 587 |
|
| 588 |
// Floating point math can produce very small, non-zero determinants for singular matrices. |
| 589 |
// This seems to happen in Numpy as well. |
| 590 |
// Don't bother calculating sign as we only care about how close to zero we are. |
| 591 |
if (l.map((row, i) => row[i] * u[i][i]).reduce((acc, val) => acc * val, 1) === 0.0) { |
| 592 |
throw new Error("Matrix is singular"); |
| 593 |
} |
| 594 |
|
| 595 |
// Solve for the identity matrix (will give us inverse) |
| 596 |
// Permutation matrix is the identity matrix, even if shuffled. |
| 597 |
return backSubMatrix(u, forwardSubMatrix(l, p, n), n); |
| 598 |
} |
| 599 |
|
| 600 |
/** |
| 601 |
* Solve a NxN matrix representing a system of equations. |
| 602 |
* |
| 603 |
* @param {number[][]} matrix |
| 604 |
* @param {number[]} vector |
| 605 |
* @returns {number[]} |
| 606 |
*/ |
| 607 |
function solve (matrix, vector) { |
| 608 |
// Calculate the LU decomposition. |
| 609 |
const [p, l, u] = lu(matrix, { pIndices: true }); |
| 610 |
const n = l.length; |
| 611 |
|
| 612 |
// If determinant is zero, we can't solve. |
| 613 |
if (l.map((row, i) => row[i] * u[i][i]).reduce((acc, val) => acc * val, 1) === 0.0) { |
| 614 |
throw new Error("Matrix is singular"); |
| 615 |
} |
| 616 |
|
| 617 |
return backSubVector( |
| 618 |
u, |
| 619 |
forwardSubVector( |
| 620 |
l, |
| 621 |
p.map(i => vector[i]), |
| 622 |
n, |
| 623 |
), |
| 624 |
n, |
| 625 |
); |
| 626 |
} |
| 627 |
|
| 628 |
var util = /*#__PURE__*/Object.freeze({ |
| 629 |
__proto__: null, |
| 630 |
bisectLeft: bisectLeft, |
| 631 |
clamp: clamp, |
| 632 |
copySign: copySign, |
| 633 |
diag: diag, |
| 634 |
interpolate: interpolate, |
| 635 |
interpolateInv: interpolateInv, |
| 636 |
inv: inv, |
| 637 |
isInstance: isInstance, |
| 638 |
isNone: isNone, |
| 639 |
isString: isString, |
| 640 |
lu: lu, |
| 641 |
mapRange: mapRange, |
| 642 |
multiplyMatrices: multiplyMatrices, |
| 643 |
multiply_v3_m3x3: multiply_v3_m3x3, |
| 644 |
serializeNumber: serializeNumber, |
| 645 |
skipNone: skipNone, |
| 646 |
solve: solve, |
| 647 |
spow: spow, |
| 648 |
toPrecision: toPrecision, |
| 649 |
type: type, |
| 650 |
zdiv: zdiv |
| 651 |
}); |
| 652 |
|
| 653 |
/** |
| 654 |
* A class for adding deep extensibility to any piece of JS code |
| 655 |
*/ |
| 656 |
class Hooks { |
| 657 |
add (name, callback, first) { |
| 658 |
if (typeof arguments[0] != "string") { |
| 659 |
// Multiple hooks |
| 660 |
for (var name in arguments[0]) { |
| 661 |
this.add(name, arguments[0][name], arguments[1]); |
| 662 |
} |
| 663 |
|
| 664 |
return; |
| 665 |
} |
| 666 |
|
| 667 |
(Array.isArray(name) ? name : [name]).forEach(function (name) { |
| 668 |
this[name] = this[name] || []; |
| 669 |
|
| 670 |
if (callback) { |
| 671 |
this[name][first ? "unshift" : "push"](callback); |
| 672 |
} |
| 673 |
}, this); |
| 674 |
} |
| 675 |
|
| 676 |
run (name, env) { |
| 677 |
this[name] = this[name] || []; |
| 678 |
this[name].forEach(function (callback) { |
| 679 |
callback.call(env && env.context ? env.context : env, env); |
| 680 |
}); |
| 681 |
} |
| 682 |
} |
| 683 |
|
| 684 |
/** |
| 685 |
* The instance of {@link Hooks} used throughout Color.js |
| 686 |
*/ |
| 687 |
const hooks = new Hooks(); |
| 688 |
|
| 689 |
// Global defaults one may want to configure |
| 690 |
var defaults = { |
| 691 |
gamut_mapping: "css", |
| 692 |
precision: 5, |
| 693 |
deltaE: "76", // Default deltaE method |
| 694 |
verbose: globalThis?.process?.env?.NODE_ENV?.toLowerCase() !== "test", |
| 695 |
warn: function warn (msg) { |
| 696 |
if (this.verbose) { |
| 697 |
globalThis?.console?.warn?.(msg); |
| 698 |
} |
| 699 |
}, |
| 700 |
}; |
| 701 |
|
| 702 |
class Type { |
| 703 |
// Class properties - declared here so that type inference works |
| 704 |
type; |
| 705 |
coordMeta; |
| 706 |
coordRange; |
| 707 |
/** @type {[number, number]} */ |
| 708 |
range; |
| 709 |
|
| 710 |
/** |
| 711 |
* @param {any} type |
| 712 |
* @param {import("./types.js").CoordMeta} coordMeta |
| 713 |
*/ |
| 714 |
constructor (type, coordMeta) { |
| 715 |
if (typeof type === "object") { |
| 716 |
this.coordMeta = type; |
| 717 |
} |
| 718 |
|
| 719 |
if (coordMeta) { |
| 720 |
this.coordMeta = coordMeta; |
| 721 |
this.coordRange = coordMeta.range ?? coordMeta.refRange; |
| 722 |
} |
| 723 |
|
| 724 |
if (typeof type === "string") { |
| 725 |
let params = type |
| 726 |
.trim() |
| 727 |
.match(/^(?<type><[a-z]+>)(\[(?<min>-?[.\d]+),\s*(?<max>-?[.\d]+)\])?$/); |
| 728 |
|
| 729 |
if (!params) { |
| 730 |
throw new TypeError(`Cannot parse ${type} as a type definition.`); |
| 731 |
} |
| 732 |
|
| 733 |
this.type = params.groups.type; |
| 734 |
let { min, max } = params.groups; |
| 735 |
|
| 736 |
if (min || max) { |
| 737 |
this.range = [+min, +max]; |
| 738 |
} |
| 739 |
} |
| 740 |
} |
| 741 |
|
| 742 |
/** @returns {[number, number]} */ |
| 743 |
get computedRange () { |
| 744 |
if (this.range) { |
| 745 |
return this.range; |
| 746 |
} |
| 747 |
if (this.type === "<percentage>") { |
| 748 |
return this.percentageRange(); |
| 749 |
} |
| 750 |
else if (this.type === "<angle>") { |
| 751 |
return [0, 360]; |
| 752 |
} |
| 753 |
return null; |
| 754 |
} |
| 755 |
|
| 756 |
get unit () { |
| 757 |
if (this.type === "<percentage>") { |
| 758 |
return "%"; |
| 759 |
} |
| 760 |
else if (this.type === "<angle>") { |
| 761 |
return "deg"; |
| 762 |
} |
| 763 |
|
| 764 |
return ""; |
| 765 |
} |
| 766 |
|
| 767 |
/** |
| 768 |
* Map a number to the internal representation |
| 769 |
* @param {number} number |
| 770 |
*/ |
| 771 |
resolve (number) { |
| 772 |
if (this.type === "<angle>") { |
| 773 |
return number; |
| 774 |
} |
| 775 |
|
| 776 |
let fromRange = this.computedRange; |
| 777 |
let toRange = this.coordRange; |
| 778 |
|
| 779 |
if (this.type === "<percentage>") { |
| 780 |
toRange ??= this.percentageRange(); |
| 781 |
} |
| 782 |
|
| 783 |
return mapRange(fromRange, toRange, number); |
| 784 |
} |
| 785 |
|
| 786 |
/** |
| 787 |
* Serialize a number from the internal representation to a string |
| 788 |
* @param {number} number |
| 789 |
* @param {number} [precision] |
| 790 |
*/ |
| 791 |
serialize (number, precision) { |
| 792 |
let toRange = this.type === "<percentage>" ? this.percentageRange(100) : this.computedRange; |
| 793 |
|
| 794 |
let unit = this.unit; |
| 795 |
|
| 796 |
number = mapRange(this.coordRange, toRange, number); |
| 797 |
return serializeNumber(number, { unit, precision }); |
| 798 |
} |
| 799 |
|
| 800 |
toString () { |
| 801 |
let ret = this.type; |
| 802 |
|
| 803 |
if (this.range) { |
| 804 |
let [min = "", max = ""] = this.range; |
| 805 |
ret += `[${min},${max}]`; |
| 806 |
} |
| 807 |
|
| 808 |
return ret; |
| 809 |
} |
| 810 |
|
| 811 |
/** |
| 812 |
* Returns a percentage range for values of this type |
| 813 |
* @param {number} scale |
| 814 |
* @returns {[number, number]} |
| 815 |
*/ |
| 816 |
percentageRange (scale = 1) { |
| 817 |
let range; |
| 818 |
if ( |
| 819 |
(this.coordMeta && this.coordMeta.range) || |
| 820 |
(this.coordRange && this.coordRange[0] >= 0) |
| 821 |
) { |
| 822 |
range = [0, 1]; |
| 823 |
} |
| 824 |
else { |
| 825 |
range = [-1, 1]; |
| 826 |
} |
| 827 |
return [range[0] * scale, range[1] * scale]; |
| 828 |
} |
| 829 |
|
| 830 |
static get (type, coordMeta) { |
| 831 |
if (isInstance(type, this)) { |
| 832 |
return type; |
| 833 |
} |
| 834 |
|
| 835 |
return new this(type, coordMeta); |
| 836 |
} |
| 837 |
} |
| 838 |
|
| 839 |
/** @import { ColorSpace, Coords } from "./types.js" */ |
| 840 |
|
| 841 |
// Type re-exports |
| 842 |
/** @typedef {import("./types.js").Format} FormatInterface */ |
| 843 |
|
| 844 |
/** |
| 845 |
* @internal |
| 846 |
* Used to index {@link FormatInterface Format} objects and store an instance. |
| 847 |
* Not meant for external use |
| 848 |
*/ |
| 849 |
const instance = Symbol("instance"); |
| 850 |
|
| 851 |
/** |
| 852 |
* Remove the first element of an array type |
| 853 |
* @template {any[]} T |
| 854 |
* @typedef {T extends [any, ...infer R] ? R : T[number][]} RemoveFirstElement |
| 855 |
*/ |
| 856 |
|
| 857 |
/** |
| 858 |
* @class Format |
| 859 |
* @implements {Omit<FormatInterface, "coords" | "serializeCoords">} |
| 860 |
* Class to hold a color serialization format |
| 861 |
*/ |
| 862 |
class Format { |
| 863 |
// Class properties - declared here so that type inference works |
| 864 |
type; |
| 865 |
name; |
| 866 |
spaceCoords; |
| 867 |
/** @type {Type[][]} */ |
| 868 |
coords; |
| 869 |
/** @type {string | undefined} */ |
| 870 |
id; |
| 871 |
/** @type {boolean | undefined} */ |
| 872 |
alpha; |
| 873 |
|
| 874 |
/** |
| 875 |
* @param {FormatInterface} format |
| 876 |
* @param {ColorSpace} space |
| 877 |
*/ |
| 878 |
constructor (format, space = format.space) { |
| 879 |
format[instance] = this; |
| 880 |
this.type = "function"; |
| 881 |
this.name = "color"; |
| 882 |
|
| 883 |
Object.assign(this, format); |
| 884 |
|
| 885 |
this.space = space; |
| 886 |
|
| 887 |
if (this.type === "custom") { |
| 888 |
// Nothing else to do here |
| 889 |
return; |
| 890 |
} |
| 891 |
|
| 892 |
this.spaceCoords = Object.values(space.coords); |
| 893 |
|
| 894 |
if (!this.coords) { |
| 895 |
// @ts-expect-error Strings are converted to the correct type later |
| 896 |
this.coords = this.spaceCoords.map(coordMeta => { |
| 897 |
let ret = ["<number>", "<percentage>"]; |
| 898 |
|
| 899 |
if (coordMeta.type === "angle") { |
| 900 |
ret.push("<angle>"); |
| 901 |
} |
| 902 |
|
| 903 |
return ret; |
| 904 |
}); |
| 905 |
} |
| 906 |
|
| 907 |
this.coords = this.coords.map( |
| 908 |
/** @param {string | string[] | Type[]} types */ (types, i) => { |
| 909 |
let coordMeta = this.spaceCoords[i]; |
| 910 |
|
| 911 |
if (typeof types === "string") { |
| 912 |
types = types.trim().split(/\s*\|\s*/); |
| 913 |
} |
| 914 |
|
| 915 |
return types.map(type => Type.get(type, coordMeta)); |
| 916 |
}, |
| 917 |
); |
| 918 |
} |
| 919 |
|
| 920 |
/** |
| 921 |
* @param {Coords} coords |
| 922 |
* @param {number} precision |
| 923 |
* @param {Type[]} types |
| 924 |
*/ |
| 925 |
serializeCoords (coords, precision, types) { |
| 926 |
types = coords.map((_, i) => |
| 927 |
Type.get(types?.[i] ?? this.coords[i][0], this.spaceCoords[i])); |
| 928 |
return coords.map((c, i) => types[i].serialize(c, precision)); |
| 929 |
} |
| 930 |
|
| 931 |
/** |
| 932 |
* Validates the coordinates of a color against a format's coord grammar and |
| 933 |
* maps the coordinates to the range or refRange of the coordinates. |
| 934 |
* @param {Coords} coords |
| 935 |
* @param {[string, string, string]} types |
| 936 |
*/ |
| 937 |
coerceCoords (coords, types) { |
| 938 |
return Object.entries(this.space.coords).map(([id, coordMeta], i) => { |
| 939 |
let arg = coords[i]; |
| 940 |
|
| 941 |
if (isNone(arg) || isNaN(arg)) { |
| 942 |
// Nothing to do here |
| 943 |
return arg; |
| 944 |
} |
| 945 |
|
| 946 |
// Find grammar alternative that matches the provided type |
| 947 |
// Non-strict equals is intentional because we are comparing w/ string objects |
| 948 |
let providedType = types[i]; |
| 949 |
let type = this.coords[i].find(c => c.type == providedType); |
| 950 |
|
| 951 |
// Check that each coord conforms to its grammar |
| 952 |
if (!type) { |
| 953 |
// Type does not exist in the grammar, throw |
| 954 |
let coordName = coordMeta.name || id; |
| 955 |
throw new TypeError( |
| 956 |
`${providedType ?? /** @type {any} */ (arg)?.raw ?? arg} not allowed for ${coordName} in ${this.name}()`, |
| 957 |
); |
| 958 |
} |
| 959 |
|
| 960 |
arg = type.resolve(arg); |
| 961 |
|
| 962 |
if (type.range) { |
| 963 |
// Adjust type to include range |
| 964 |
types[i] = type.toString(); |
| 965 |
} |
| 966 |
|
| 967 |
return arg; |
| 968 |
}); |
| 969 |
} |
| 970 |
|
| 971 |
/** |
| 972 |
* @returns {boolean | Required<FormatInterface>["serialize"]} |
| 973 |
*/ |
| 974 |
canSerialize () { |
| 975 |
return this.type === "function" || /** @type {any} */ (this).serialize; |
| 976 |
} |
| 977 |
|
| 978 |
/** |
| 979 |
* @param {string} str |
| 980 |
* @returns {(import("./types.js").ColorConstructor) | undefined | null} |
| 981 |
*/ |
| 982 |
parse (str) { |
| 983 |
return null; |
| 984 |
} |
| 985 |
|
| 986 |
/** |
| 987 |
* @param {Format | FormatInterface} format |
| 988 |
* @param {RemoveFirstElement<ConstructorParameters<typeof Format>>} args |
| 989 |
* @returns {Format} |
| 990 |
*/ |
| 991 |
static get (format, ...args) { |
| 992 |
if (!format || isInstance(format, this)) { |
| 993 |
return /** @type {Format} */ (format); |
| 994 |
} |
| 995 |
|
| 996 |
if (format[instance]) { |
| 997 |
return format[instance]; |
| 998 |
} |
| 999 |
|
| 1000 |
return new Format(format, ...args); |
| 1001 |
} |
| 1002 |
} |
| 1003 |
|
| 1004 |
// Type re-exports |
| 1005 |
/** @typedef {import("./types.js").White} White */ |
| 1006 |
|
| 1007 |
/** @type {Record<string, White>} */ |
| 1008 |
// prettier-ignore |
| 1009 |
const WHITES = { |
| 1010 |
// for compatibility, the four-digit chromaticity-derived ones everyone else uses |
| 1011 |
D50: [0.3457 / 0.3585, 1.00000, (1.0 - 0.3457 - 0.3585) / 0.3585], |
| 1012 |
D65: [0.3127 / 0.3290, 1.00000, (1.0 - 0.3127 - 0.3290) / 0.3290], |
| 1013 |
}; |
| 1014 |
|
| 1015 |
/** |
| 1016 |
* |
| 1017 |
* @param {string | White} name |
| 1018 |
* @returns {White} |
| 1019 |
*/ |
| 1020 |
function getWhite (name) { |
| 1021 |
if (Array.isArray(name)) { |
| 1022 |
return name; |
| 1023 |
} |
| 1024 |
|
| 1025 |
return WHITES[name]; |
| 1026 |
} |
| 1027 |
|
| 1028 |
/** |
| 1029 |
* Adapt XYZ from white point W1 to W2 |
| 1030 |
* @param {White | string} W1 |
| 1031 |
* @param {White | string} W2 |
| 1032 |
* @param {[number, number, number]} XYZ |
| 1033 |
* @param {{ method?: string | undefined }} options |
| 1034 |
* @returns {[number, number, number]} |
| 1035 |
*/ |
| 1036 |
function adapt$2 (W1, W2, XYZ, options = {}) { |
| 1037 |
W1 = getWhite(W1); |
| 1038 |
W2 = getWhite(W2); |
| 1039 |
|
| 1040 |
if (!W1 || !W2) { |
| 1041 |
throw new TypeError( |
| 1042 |
`Missing white point to convert ${!W1 ? "from" : ""}${!W1 && !W2 ? "/" : ""}${!W2 ? "to" : ""}`, |
| 1043 |
); |
| 1044 |
} |
| 1045 |
|
| 1046 |
if (W1 === W2) { |
| 1047 |
// Same whitepoints, no conversion needed |
| 1048 |
return XYZ; |
| 1049 |
} |
| 1050 |
|
| 1051 |
let env = { W1, W2, XYZ, options }; |
| 1052 |
|
| 1053 |
hooks.run("chromatic-adaptation-start", env); |
| 1054 |
|
| 1055 |
if (!env.M) { |
| 1056 |
if (env.W1 === WHITES.D65 && env.W2 === WHITES.D50) { |
| 1057 |
// prettier-ignore |
| 1058 |
env.M = [ |
| 1059 |
[ 1.0479297925449969, 0.022946870601609652, -0.05019226628920524 ], |
| 1060 |
[ 0.02962780877005599, 0.9904344267538799, -0.017073799063418826 ], |
| 1061 |
[ -0.009243040646204504, 0.015055191490298152, 0.7518742814281371 ], |
| 1062 |
]; |
| 1063 |
} |
| 1064 |
else if (env.W1 === WHITES.D50 && env.W2 === WHITES.D65) { |
| 1065 |
// prettier-ignore |
| 1066 |
env.M = [ |
| 1067 |
[ 0.955473421488075, -0.02309845494876471, 0.06325924320057072 ], |
| 1068 |
[ -0.0283697093338637, 1.0099953980813041, 0.021041441191917323 ], |
| 1069 |
[ 0.012314014864481998, -0.020507649298898964, 1.330365926242124 ], |
| 1070 |
]; |
| 1071 |
} |
| 1072 |
} |
| 1073 |
|
| 1074 |
hooks.run("chromatic-adaptation-end", env); |
| 1075 |
|
| 1076 |
if (env.M) { |
| 1077 |
return multiply_v3_m3x3(env.XYZ, env.M); |
| 1078 |
} |
| 1079 |
else { |
| 1080 |
throw new TypeError("Only Bradford CAT with white points D50 and D65 supported for now."); |
| 1081 |
} |
| 1082 |
} |
| 1083 |
|
| 1084 |
/** @import { ColorConstructor } from "./types.js" */ |
| 1085 |
|
| 1086 |
// Type re-exports |
| 1087 |
/** @typedef {import("./types.js").ArgumentMeta} ArgumentMeta */ |
| 1088 |
/** @typedef {import("./types.js").ParseFunctionReturn} ParseFunctionReturn */ |
| 1089 |
/** @typedef {import("./types.js").ParseOptions} ParseOptions */ |
| 1090 |
|
| 1091 |
/** |
| 1092 |
* Convert a CSS Color string to a color object |
| 1093 |
* @param {string} str |
| 1094 |
* @param {ParseOptions} [options] |
| 1095 |
* @returns {ColorConstructor} |
| 1096 |
*/ |
| 1097 |
function parse (str, options) { |
| 1098 |
let env = { |
| 1099 |
str: String(str)?.trim(), |
| 1100 |
options, |
| 1101 |
}; |
| 1102 |
|
| 1103 |
hooks.run("parse-start", env); |
| 1104 |
|
| 1105 |
if (env.color) { |
| 1106 |
return env.color; |
| 1107 |
} |
| 1108 |
|
| 1109 |
env.parsed = parseFunction(env.str); |
| 1110 |
let ret; |
| 1111 |
let meta = env.options ? (env.options.parseMeta ?? env.options.meta) : null; |
| 1112 |
|
| 1113 |
if (env.parsed) { |
| 1114 |
// Is a functional syntax |
| 1115 |
let name = env.parsed.name; |
| 1116 |
let format; |
| 1117 |
let space; |
| 1118 |
let coords = env.parsed.args; |
| 1119 |
let types = coords.map((c, i) => env.parsed.argMeta[i]?.type); |
| 1120 |
|
| 1121 |
if (name === "color") { |
| 1122 |
// color() function |
| 1123 |
let id = coords.shift(); |
| 1124 |
types.shift(); |
| 1125 |
// Check against both <dashed-ident> and <ident> versions |
| 1126 |
let alternateId = id.startsWith("--") ? id.substring(2) : `--${id}`; |
| 1127 |
let ids = [id, alternateId]; |
| 1128 |
format = ColorSpace.findFormat({ name, id: ids, type: "function" }); |
| 1129 |
|
| 1130 |
if (!format) { |
| 1131 |
// Not found |
| 1132 |
let didYouMean; |
| 1133 |
|
| 1134 |
let registryId = id in ColorSpace.registry ? id : alternateId; |
| 1135 |
if (registryId in ColorSpace.registry) { |
| 1136 |
// Used color space id instead of color() id, these are often different |
| 1137 |
let cssId = ColorSpace.registry[registryId].formats?.color?.id; |
| 1138 |
|
| 1139 |
if (cssId) { |
| 1140 |
let altColor = str.replace("color(" + id, "color(" + cssId); |
| 1141 |
didYouMean = `Did you mean ${altColor}?`; |
| 1142 |
} |
| 1143 |
} |
| 1144 |
|
| 1145 |
throw new TypeError( |
| 1146 |
`Cannot parse ${env.str}. ` + (didYouMean ?? "Missing a plugin?"), |
| 1147 |
); |
| 1148 |
} |
| 1149 |
|
| 1150 |
space = format.space; |
| 1151 |
|
| 1152 |
if (format.id.startsWith("--") && !id.startsWith("--")) { |
| 1153 |
defaults.warn( |
| 1154 |
`${space.name} is a non-standard space and not currently supported in the CSS spec. ` + |
| 1155 |
`Use prefixed color(${format.id}) instead of color(${id}).`, |
| 1156 |
); |
| 1157 |
} |
| 1158 |
if (id.startsWith("--") && !format.id.startsWith("--")) { |
| 1159 |
defaults.warn( |
| 1160 |
`${space.name} is a standard space and supported in the CSS spec. ` + |
| 1161 |
`Use color(${format.id}) instead of prefixed color(${id}).`, |
| 1162 |
); |
| 1163 |
} |
| 1164 |
} |
| 1165 |
else { |
| 1166 |
format = ColorSpace.findFormat({ name, type: "function" }); |
| 1167 |
space = format.space; |
| 1168 |
} |
| 1169 |
|
| 1170 |
if (meta) { |
| 1171 |
Object.assign(meta, { |
| 1172 |
format, |
| 1173 |
formatId: format.name, |
| 1174 |
types, |
| 1175 |
commas: env.parsed.commas, |
| 1176 |
}); |
| 1177 |
} |
| 1178 |
|
| 1179 |
let alpha = 1; |
| 1180 |
|
| 1181 |
if (env.parsed.lastAlpha) { |
| 1182 |
alpha = env.parsed.args.pop(); |
| 1183 |
|
| 1184 |
if (meta) { |
| 1185 |
meta.alphaType = types.pop(); |
| 1186 |
} |
| 1187 |
} |
| 1188 |
|
| 1189 |
let coordCount = format.coords.length; |
| 1190 |
|
| 1191 |
if (coords.length !== coordCount) { |
| 1192 |
throw new TypeError( |
| 1193 |
`Expected ${coordCount} coordinates for ${space.id} in ${env.str}), got ${coords.length}`, |
| 1194 |
); |
| 1195 |
} |
| 1196 |
|
| 1197 |
coords = format.coerceCoords(coords, types); |
| 1198 |
|
| 1199 |
ret = { spaceId: space.id, coords, alpha }; |
| 1200 |
} |
| 1201 |
else { |
| 1202 |
// Custom, colorspace-specific format |
| 1203 |
spaceloop: for (let space of ColorSpace.all) { |
| 1204 |
for (let formatId in space.formats) { |
| 1205 |
let format = space.formats[formatId]; |
| 1206 |
|
| 1207 |
if (format.type !== "custom") { |
| 1208 |
continue; |
| 1209 |
} |
| 1210 |
|
| 1211 |
if (format.test && !format.test(env.str)) { |
| 1212 |
continue; |
| 1213 |
} |
| 1214 |
|
| 1215 |
// Convert to Format object |
| 1216 |
let formatObject = space.getFormat(format); |
| 1217 |
|
| 1218 |
let color = formatObject.parse(env.str); |
| 1219 |
|
| 1220 |
if (color) { |
| 1221 |
if (meta) { |
| 1222 |
Object.assign(meta, { format: formatObject, formatId }); |
| 1223 |
} |
| 1224 |
|
| 1225 |
ret = color; |
| 1226 |
break spaceloop; |
| 1227 |
} |
| 1228 |
} |
| 1229 |
} |
| 1230 |
} |
| 1231 |
|
| 1232 |
if (!ret) { |
| 1233 |
// If we're here, we couldn't parse |
| 1234 |
throw new TypeError(`Could not parse ${str} as a color. Missing a plugin?`); |
| 1235 |
} |
| 1236 |
|
| 1237 |
// Clamp alpha to [0, 1] |
| 1238 |
ret.alpha = isNone(ret.alpha) |
| 1239 |
? ret.alpha |
| 1240 |
: ret.alpha === undefined |
| 1241 |
? 1 |
| 1242 |
: clamp(0, ret.alpha, 1); |
| 1243 |
|
| 1244 |
return ret; |
| 1245 |
} |
| 1246 |
|
| 1247 |
/** |
| 1248 |
* Units and multiplication factors for the internally stored numbers |
| 1249 |
*/ |
| 1250 |
const units = { |
| 1251 |
"%": 0.01, |
| 1252 |
deg: 1, |
| 1253 |
grad: 0.9, |
| 1254 |
rad: 180 / Math.PI, |
| 1255 |
turn: 360, |
| 1256 |
}; |
| 1257 |
|
| 1258 |
const regex = { |
| 1259 |
// Need to list calc(NaN) explicitly as otherwise its ending paren would terminate the function call |
| 1260 |
function: /^([a-z]+)\(((?:calc\(NaN\)|.)+?)\)$/i, |
| 1261 |
number: /^([-+]?(?:[0-9]*\.)?[0-9]+(e[-+]?[0-9]+)?)$/i, |
| 1262 |
unitValue: RegExp(`(${Object.keys(units).join("|")})$`), |
| 1263 |
|
| 1264 |
// NOTE The -+ are not just for prefix, but also for idents, and e+N notation! |
| 1265 |
singleArgument: /\/?\s*(none|NaN|calc\(NaN\)|[-+\w.]+(?:%|deg|g?rad|turn)?)/g, |
| 1266 |
}; |
| 1267 |
|
| 1268 |
/** |
| 1269 |
* Parse a single function argument |
| 1270 |
* @param {string} rawArg |
| 1271 |
* @returns {{value: number, meta: ArgumentMeta}} |
| 1272 |
*/ |
| 1273 |
function parseArgument (rawArg) { |
| 1274 |
/** @type {Partial<ArgumentMeta>} */ |
| 1275 |
let meta = {}; |
| 1276 |
let unit = rawArg.match(regex.unitValue)?.[0]; |
| 1277 |
/** @type {string | number} */ |
| 1278 |
let value = (meta.raw = rawArg); |
| 1279 |
|
| 1280 |
if (unit) { |
| 1281 |
// It’s a dimension token |
| 1282 |
meta.type = unit === "%" ? "<percentage>" : "<angle>"; |
| 1283 |
meta.unit = unit; |
| 1284 |
meta.unitless = Number(value.slice(0, -unit.length)); // unitless number |
| 1285 |
|
| 1286 |
value = meta.unitless * units[unit]; |
| 1287 |
} |
| 1288 |
else if (regex.number.test(value)) { |
| 1289 |
// It's a number |
| 1290 |
// Convert numerical args to numbers |
| 1291 |
value = Number(value); |
| 1292 |
meta.type = "<number>"; |
| 1293 |
} |
| 1294 |
else if (value === "none") { |
| 1295 |
value = null; |
| 1296 |
} |
| 1297 |
else if (value === "NaN" || value === "calc(NaN)") { |
| 1298 |
value = NaN; |
| 1299 |
meta.type = "<number>"; |
| 1300 |
} |
| 1301 |
else { |
| 1302 |
meta.type = "<ident>"; |
| 1303 |
} |
| 1304 |
|
| 1305 |
return { value: /** @type {number} */ (value), meta: /** @type {ArgumentMeta} */ (meta) }; |
| 1306 |
} |
| 1307 |
|
| 1308 |
/** |
| 1309 |
* Parse a CSS function, regardless of its name and arguments |
| 1310 |
* @param {string} str String to parse |
| 1311 |
* @return {ParseFunctionReturn | void} |
| 1312 |
*/ |
| 1313 |
function parseFunction (str) { |
| 1314 |
if (!str) { |
| 1315 |
return; |
| 1316 |
} |
| 1317 |
|
| 1318 |
str = str.trim(); |
| 1319 |
|
| 1320 |
let parts = str.match(regex.function); |
| 1321 |
|
| 1322 |
if (parts) { |
| 1323 |
// It is a function, parse args |
| 1324 |
let args = []; |
| 1325 |
let argMeta = []; |
| 1326 |
let lastAlpha = false; |
| 1327 |
let name = parts[1].toLowerCase(); |
| 1328 |
|
| 1329 |
let separators = parts[2].replace(regex.singleArgument, ($0, rawArg) => { |
| 1330 |
let { value, meta } = parseArgument(rawArg); |
| 1331 |
|
| 1332 |
if ( |
| 1333 |
// If there's a slash here, it's modern syntax |
| 1334 |
$0.startsWith("/") || |
| 1335 |
// If there's still elements to process after there's already 3 in `args` (and the we're not dealing with "color()"), it's likely to be a legacy color like "hsl(0, 0%, 0%, 0.5)" |
| 1336 |
(name !== "color" && args.length === 3) |
| 1337 |
) { |
| 1338 |
// It's alpha |
| 1339 |
lastAlpha = true; |
| 1340 |
} |
| 1341 |
|
| 1342 |
args.push(value); |
| 1343 |
argMeta.push(meta); |
| 1344 |
return ""; |
| 1345 |
}); |
| 1346 |
|
| 1347 |
return { |
| 1348 |
name, |
| 1349 |
args, |
| 1350 |
argMeta, |
| 1351 |
lastAlpha, |
| 1352 |
commas: separators.includes(","), |
| 1353 |
rawName: parts[1], |
| 1354 |
rawArgs: parts[2], |
| 1355 |
}; |
| 1356 |
} |
| 1357 |
} |
| 1358 |
|
| 1359 |
/** @import { ColorTypes, ParseOptions as GetColorOptions, PlainColorObject } from "./types.js" */ |
| 1360 |
|
| 1361 |
/** |
| 1362 |
* Resolves a color reference (object or string) to a plain color object |
| 1363 |
* @overload |
| 1364 |
* @param {ColorTypes} color |
| 1365 |
* @param {GetColorOptions} [options] |
| 1366 |
* @returns {PlainColorObject} |
| 1367 |
*/ |
| 1368 |
/** |
| 1369 |
* @overload |
| 1370 |
* @param {ColorTypes[]} color |
| 1371 |
* @param {GetColorOptions} [options] |
| 1372 |
* @returns {PlainColorObject[]} |
| 1373 |
*/ |
| 1374 |
function getColor (color, options) { |
| 1375 |
if (Array.isArray(color)) { |
| 1376 |
return color.map(c => getColor(c, options)); |
| 1377 |
} |
| 1378 |
|
| 1379 |
if (!color) { |
| 1380 |
throw new TypeError("Empty color reference"); |
| 1381 |
} |
| 1382 |
|
| 1383 |
if (isString(color)) { |
| 1384 |
color = parse(color, options); |
| 1385 |
} |
| 1386 |
|
| 1387 |
// Object fixup |
| 1388 |
let space = color.space || color.spaceId; |
| 1389 |
|
| 1390 |
if (typeof space === "string") { |
| 1391 |
// Convert string id to color space object |
| 1392 |
color.space = ColorSpace.get(space); |
| 1393 |
} |
| 1394 |
|
| 1395 |
if (color.alpha === undefined) { |
| 1396 |
color.alpha = 1; |
| 1397 |
} |
| 1398 |
|
| 1399 |
return color; |
| 1400 |
} |
| 1401 |
|
| 1402 |
/** |
| 1403 |
* @packageDocumentation |
| 1404 |
* Defines the class and other types related to creating color spaces. |
| 1405 |
* For the builtin color spaces, see the `spaces` module. |
| 1406 |
*/ |
| 1407 |
|
| 1408 |
const ε$7 = 0.000075; |
| 1409 |
|
| 1410 |
/** |
| 1411 |
* Class to represent a color space |
| 1412 |
*/ |
| 1413 |
class ColorSpace { |
| 1414 |
constructor (options) { |
| 1415 |
this.id = options.id; |
| 1416 |
this.name = options.name; |
| 1417 |
this.base = options.base ? ColorSpace.get(options.base) : null; |
| 1418 |
this.aliases = options.aliases; |
| 1419 |
this.displaySpaces = options.displaySpaces?.map(space => ColorSpace.get(space)); |
| 1420 |
|
| 1421 |
// This space's ancestors, closest first (immediate base → root), excluding the space itself. |
| 1422 |
this.bases = []; |
| 1423 |
for (let base = this.base; base; base = base.base) { |
| 1424 |
this.bases.push(base); |
| 1425 |
} |
| 1426 |
|
| 1427 |
if (options.rgbGamut) { |
| 1428 |
this.rgbGamut = options.rgbGamut; |
| 1429 |
} |
| 1430 |
|
| 1431 |
if (options.linearGamut) { |
| 1432 |
this.linearGamut = options.linearGamut; |
| 1433 |
} |
| 1434 |
|
| 1435 |
if (this.base) { |
| 1436 |
// Keep a subclass's own methods if the options don't override them |
| 1437 |
if (options.fromBase) { |
| 1438 |
this.fromBase = options.fromBase; |
| 1439 |
} |
| 1440 |
|
| 1441 |
if (options.toBase) { |
| 1442 |
this.toBase = options.toBase; |
| 1443 |
} |
| 1444 |
} |
| 1445 |
|
| 1446 |
// Coordinate metadata |
| 1447 |
|
| 1448 |
let coords = options.coords ?? this.base.coords; |
| 1449 |
|
| 1450 |
for (let name in coords) { |
| 1451 |
if (!("name" in coords[name])) { |
| 1452 |
coords[name].name = name; |
| 1453 |
} |
| 1454 |
} |
| 1455 |
this.coords = coords; |
| 1456 |
|
| 1457 |
// White point |
| 1458 |
|
| 1459 |
let white = options.white ?? this.base.white ?? "D65"; |
| 1460 |
this.white = getWhite(white); |
| 1461 |
|
| 1462 |
// Sort out formats |
| 1463 |
|
| 1464 |
this.formats = options.formats ?? {}; |
| 1465 |
|
| 1466 |
for (let name in this.formats) { |
| 1467 |
let format = this.formats[name]; |
| 1468 |
format.type ||= "function"; |
| 1469 |
format.name ||= name; |
| 1470 |
} |
| 1471 |
|
| 1472 |
if (!this.formats.color?.id) { |
| 1473 |
this.formats.color = { |
| 1474 |
...(this.formats.color ?? {}), |
| 1475 |
id: options.cssId || this.id, |
| 1476 |
}; |
| 1477 |
} |
| 1478 |
|
| 1479 |
// Gamut space |
| 1480 |
|
| 1481 |
if (options.gamutSpace) { |
| 1482 |
// Gamut space explicitly specified |
| 1483 |
this.gamutSpace = |
| 1484 |
options.gamutSpace === "self" ? this : ColorSpace.get(options.gamutSpace); |
| 1485 |
} |
| 1486 |
else { |
| 1487 |
// No gamut space specified, calculate a sensible default |
| 1488 |
if (this.isPolar) { |
| 1489 |
// Do not check gamut through polar coordinates |
| 1490 |
this.gamutSpace = this.base; |
| 1491 |
} |
| 1492 |
else { |
| 1493 |
this.gamutSpace = this; |
| 1494 |
} |
| 1495 |
} |
| 1496 |
|
| 1497 |
// Optimize inGamut for unbounded spaces |
| 1498 |
if (this.gamutSpace.isUnbounded) { |
| 1499 |
this.inGamut = (coords, options) => { |
| 1500 |
return true; |
| 1501 |
}; |
| 1502 |
} |
| 1503 |
|
| 1504 |
// Matrices used by this color space, exposed so that consumer code |
| 1505 |
// can reuse them instead of duplicating the data. E.g. `this.M.toXYZ`. |
| 1506 |
this.M = options.M ?? {}; |
| 1507 |
|
| 1508 |
// Other stuff |
| 1509 |
this.referred = options.referred; |
| 1510 |
|
| 1511 |
// Compute ancestors and store them, since they will never change |
| 1512 |
Object.defineProperty(this, "path", { |
| 1513 |
value: getPath(this).reverse(), |
| 1514 |
writable: false, |
| 1515 |
enumerable: true, |
| 1516 |
configurable: true, |
| 1517 |
}); |
| 1518 |
|
| 1519 |
hooks.run("colorspace-init-end", this); |
| 1520 |
} |
| 1521 |
|
| 1522 |
inGamut (coords, { epsilon = ε$7 } = {}) { |
| 1523 |
if (!this.equals(this.gamutSpace)) { |
| 1524 |
coords = this.to(this.gamutSpace, coords); |
| 1525 |
return this.gamutSpace.inGamut(coords, { epsilon }); |
| 1526 |
} |
| 1527 |
|
| 1528 |
let coordMeta = Object.values(this.coords); |
| 1529 |
|
| 1530 |
return coords.every((c, i) => { |
| 1531 |
let meta = coordMeta[i]; |
| 1532 |
|
| 1533 |
if (meta.type !== "angle" && meta.range) { |
| 1534 |
if (isNone(c)) { |
| 1535 |
// NaN is always in gamut |
| 1536 |
return true; |
| 1537 |
} |
| 1538 |
|
| 1539 |
let [min, max] = meta.range; |
| 1540 |
return ( |
| 1541 |
(min === undefined || c >= min - epsilon) && |
| 1542 |
(max === undefined || c <= max + epsilon) |
| 1543 |
); |
| 1544 |
} |
| 1545 |
|
| 1546 |
return true; |
| 1547 |
}); |
| 1548 |
} |
| 1549 |
|
| 1550 |
get isUnbounded () { |
| 1551 |
return Object.values(this.coords).every(coord => !("range" in coord)); |
| 1552 |
} |
| 1553 |
|
| 1554 |
get cssId () { |
| 1555 |
return this.formats?.color?.id || this.id; |
| 1556 |
} |
| 1557 |
|
| 1558 |
/** |
| 1559 |
* The id of this space's hue coordinate, or null if the space is not polar |
| 1560 |
* @returns {string | null} |
| 1561 |
*/ |
| 1562 |
get hueId () { |
| 1563 |
for (let id in this.coords) { |
| 1564 |
if (this.coords[id].type === "angle") { |
| 1565 |
return id; |
| 1566 |
} |
| 1567 |
} |
| 1568 |
|
| 1569 |
return null; |
| 1570 |
} |
| 1571 |
|
| 1572 |
/** |
| 1573 |
* The index of this space's hue coordinate within its coords array, or -1 if the space is not polar |
| 1574 |
* @returns {number} |
| 1575 |
*/ |
| 1576 |
get hueIndex () { |
| 1577 |
return Object.keys(this.coords).findIndex(id => this.coords[id].type === "angle"); |
| 1578 |
} |
| 1579 |
|
| 1580 |
get isPolar () { |
| 1581 |
return this.hueId !== null; |
| 1582 |
} |
| 1583 |
|
| 1584 |
/** |
| 1585 |
* Lookup a format in this color space |
| 1586 |
* @param {string | object | Format} format - Format id if string. If object, it's converted to a `Format` object and returned. |
| 1587 |
* @returns {Format} |
| 1588 |
*/ |
| 1589 |
getFormat (format) { |
| 1590 |
if (!format) { |
| 1591 |
return null; |
| 1592 |
} |
| 1593 |
|
| 1594 |
if (format === "default") { |
| 1595 |
format = Object.values(this.formats)[0]; |
| 1596 |
} |
| 1597 |
else if (typeof format === "string") { |
| 1598 |
format = this.formats[format]; |
| 1599 |
} |
| 1600 |
|
| 1601 |
let ret = Format.get(format, this); |
| 1602 |
|
| 1603 |
if (ret !== format && format.name in this.formats) { |
| 1604 |
// Update the format we have on file so we can find it more quickly next time |
| 1605 |
this.formats[format.name] = ret; |
| 1606 |
} |
| 1607 |
|
| 1608 |
return ret; |
| 1609 |
} |
| 1610 |
|
| 1611 |
/** |
| 1612 |
* Check if this color space is the same as another color space reference. |
| 1613 |
* Allows proxying color space objects and comparing color spaces with ids. |
| 1614 |
* @param {string | ColorSpace} space ColorSpace object or id to compare to |
| 1615 |
* @returns {boolean} |
| 1616 |
*/ |
| 1617 |
equals (space) { |
| 1618 |
if (!space) { |
| 1619 |
return false; |
| 1620 |
} |
| 1621 |
|
| 1622 |
return this === space || this.id === space || this.id === space.id; |
| 1623 |
} |
| 1624 |
|
| 1625 |
to (space, coords) { |
| 1626 |
if (arguments.length === 1) { |
| 1627 |
const color = getColor(space); |
| 1628 |
[space, coords] = [color.space, color.coords]; |
| 1629 |
} |
| 1630 |
|
| 1631 |
space = ColorSpace.get(space); |
| 1632 |
|
| 1633 |
if (this.equals(space)) { |
| 1634 |
// Same space, no change needed |
| 1635 |
return coords; |
| 1636 |
} |
| 1637 |
|
| 1638 |
// Convert NaN to 0, which seems to be valid in every coordinate of every color space |
| 1639 |
coords = coords.map(c => (isNone(c) ? 0 : c)); |
| 1640 |
|
| 1641 |
// Find connection space = lowest common ancestor in the base tree |
| 1642 |
let myPath = this.path; |
| 1643 |
let otherPath = space.path; |
| 1644 |
|
| 1645 |
let connectionSpace, connectionSpaceIndex; |
| 1646 |
|
| 1647 |
for (let i = 0; i < myPath.length; i++) { |
| 1648 |
if (myPath[i].equals(otherPath[i])) { |
| 1649 |
connectionSpace = myPath[i]; |
| 1650 |
connectionSpaceIndex = i; |
| 1651 |
} |
| 1652 |
else { |
| 1653 |
break; |
| 1654 |
} |
| 1655 |
} |
| 1656 |
|
| 1657 |
if (!connectionSpace) { |
| 1658 |
// This should never happen |
| 1659 |
throw new Error( |
| 1660 |
`Cannot convert between color spaces ${this} and ${space}: no connection space was found`, |
| 1661 |
); |
| 1662 |
} |
| 1663 |
|
| 1664 |
// Go up from current space to connection space |
| 1665 |
for (let i = myPath.length - 1; i > connectionSpaceIndex; i--) { |
| 1666 |
coords = myPath[i].toBase(coords); |
| 1667 |
} |
| 1668 |
|
| 1669 |
// Go down from connection space to target space |
| 1670 |
for (let i = connectionSpaceIndex + 1; i < otherPath.length; i++) { |
| 1671 |
coords = otherPath[i].fromBase(coords); |
| 1672 |
} |
| 1673 |
|
| 1674 |
return coords; |
| 1675 |
} |
| 1676 |
|
| 1677 |
from (space, coords) { |
| 1678 |
if (arguments.length === 1) { |
| 1679 |
const color = getColor(space); |
| 1680 |
[space, coords] = [color.space, color.coords]; |
| 1681 |
} |
| 1682 |
|
| 1683 |
space = ColorSpace.get(space); |
| 1684 |
|
| 1685 |
return space.to(this, coords); |
| 1686 |
} |
| 1687 |
|
| 1688 |
toString () { |
| 1689 |
return `${this.name} (${this.id})`; |
| 1690 |
} |
| 1691 |
|
| 1692 |
getMinCoords () { |
| 1693 |
let ret = []; |
| 1694 |
|
| 1695 |
for (let id in this.coords) { |
| 1696 |
let meta = this.coords[id]; |
| 1697 |
let range = meta.range || meta.refRange; |
| 1698 |
ret.push(range?.min ?? 0); |
| 1699 |
} |
| 1700 |
|
| 1701 |
return ret; |
| 1702 |
} |
| 1703 |
|
| 1704 |
static registry = {}; |
| 1705 |
|
| 1706 |
// Returns array of unique color spaces |
| 1707 |
static get all () { |
| 1708 |
return [...new Set(Object.values(ColorSpace.registry))]; |
| 1709 |
} |
| 1710 |
|
| 1711 |
static register (id, space) { |
| 1712 |
if (arguments.length === 1) { |
| 1713 |
space = arguments[0]; |
| 1714 |
id = space.id; |
| 1715 |
} |
| 1716 |
|
| 1717 |
space = this.get(space); |
| 1718 |
|
| 1719 |
if (this.registry[id] && this.registry[id] !== space) { |
| 1720 |
throw new Error(`Duplicate color space registration: '${id}'`); |
| 1721 |
} |
| 1722 |
this.registry[id] = space; |
| 1723 |
|
| 1724 |
// Register aliases when called without an explicit ID. |
| 1725 |
if (arguments.length === 1 && space.aliases) { |
| 1726 |
for (let alias of space.aliases) { |
| 1727 |
this.register(alias, space); |
| 1728 |
} |
| 1729 |
} |
| 1730 |
|
| 1731 |
return space; |
| 1732 |
} |
| 1733 |
|
| 1734 |
/** |
| 1735 |
* Lookup ColorSpace object by name |
| 1736 |
* @param {ColorSpace | string} name |
| 1737 |
*/ |
| 1738 |
static get (space, ...alternatives) { |
| 1739 |
if (!space || isInstance(space, this)) { |
| 1740 |
return space; |
| 1741 |
} |
| 1742 |
|
| 1743 |
let argType = type(space); |
| 1744 |
|
| 1745 |
if (argType === "string") { |
| 1746 |
// It's a color space id |
| 1747 |
let ret = ColorSpace.registry[space.toLowerCase()]; |
| 1748 |
|
| 1749 |
if (!ret) { |
| 1750 |
throw new TypeError(`No color space found with id = "${space}"`); |
| 1751 |
} |
| 1752 |
|
| 1753 |
return ret; |
| 1754 |
} |
| 1755 |
|
| 1756 |
if (alternatives.length) { |
| 1757 |
return ColorSpace.get(...alternatives); |
| 1758 |
} |
| 1759 |
|
| 1760 |
throw new TypeError(`${space} is not a valid color space`); |
| 1761 |
} |
| 1762 |
|
| 1763 |
/** |
| 1764 |
* Look up all color spaces for a format that matches certain criteria |
| 1765 |
* @param {object | string} filters |
| 1766 |
* @param {Array<ColorSpace>} [spaces=ColorSpace.all] |
| 1767 |
* @returns {Format | null} |
| 1768 |
*/ |
| 1769 |
static findFormat (filters, spaces = ColorSpace.all) { |
| 1770 |
if (!filters) { |
| 1771 |
return null; |
| 1772 |
} |
| 1773 |
|
| 1774 |
if (typeof filters === "string") { |
| 1775 |
filters = { name: filters }; |
| 1776 |
} |
| 1777 |
|
| 1778 |
for (let space of spaces) { |
| 1779 |
for (let [name, format] of Object.entries(space.formats)) { |
| 1780 |
format.name ??= name; |
| 1781 |
format.type ??= "function"; |
| 1782 |
|
| 1783 |
let matches = |
| 1784 |
(!filters.name || format.name === filters.name) && |
| 1785 |
(!filters.type || format.type === filters.type); |
| 1786 |
|
| 1787 |
if (filters.id) { |
| 1788 |
let ids = format.ids || [format.id]; |
| 1789 |
let filterIds = Array.isArray(filters.id) ? filters.id : [filters.id]; |
| 1790 |
matches &&= filterIds.some(id => ids.includes(id)); |
| 1791 |
} |
| 1792 |
|
| 1793 |
if (matches) { |
| 1794 |
let ret = Format.get(format, space); |
| 1795 |
|
| 1796 |
if (ret !== format) { |
| 1797 |
space.formats[format.name] = ret; |
| 1798 |
} |
| 1799 |
|
| 1800 |
return ret; |
| 1801 |
} |
| 1802 |
} |
| 1803 |
} |
| 1804 |
|
| 1805 |
return null; |
| 1806 |
} |
| 1807 |
|
| 1808 |
/** |
| 1809 |
* Get metadata about a coordinate of a color space |
| 1810 |
* |
| 1811 |
* @static |
| 1812 |
* @param {Array | string} ref |
| 1813 |
* @param {ColorSpace | string} [workingSpace] |
| 1814 |
* @return {Object} |
| 1815 |
*/ |
| 1816 |
static resolveCoord (ref, workingSpace) { |
| 1817 |
let coordType = type(ref); |
| 1818 |
let space, coord; |
| 1819 |
|
| 1820 |
if (coordType === "string") { |
| 1821 |
if (ref.includes(".")) { |
| 1822 |
// Absolute coordinate |
| 1823 |
[space, coord] = ref.split("."); |
| 1824 |
} |
| 1825 |
else { |
| 1826 |
// Relative coordinate |
| 1827 |
[space, coord] = [, ref]; |
| 1828 |
} |
| 1829 |
} |
| 1830 |
else if (Array.isArray(ref)) { |
| 1831 |
[space, coord] = ref; |
| 1832 |
} |
| 1833 |
else { |
| 1834 |
// Object |
| 1835 |
space = ref.space; |
| 1836 |
coord = ref.coordId; |
| 1837 |
} |
| 1838 |
|
| 1839 |
space = ColorSpace.get(space); |
| 1840 |
|
| 1841 |
if (!space) { |
| 1842 |
space = workingSpace; |
| 1843 |
} |
| 1844 |
|
| 1845 |
if (!space) { |
| 1846 |
throw new TypeError( |
| 1847 |
`Cannot resolve coordinate reference ${ref}: No color space specified and relative references are not allowed here`, |
| 1848 |
); |
| 1849 |
} |
| 1850 |
|
| 1851 |
coordType = type(coord); |
| 1852 |
|
| 1853 |
if (coordType === "number" || (coordType === "string" && coord >= 0)) { |
| 1854 |
// Resolve numerical coord |
| 1855 |
let meta = Object.entries(space.coords)[coord]; |
| 1856 |
|
| 1857 |
if (meta) { |
| 1858 |
return { space, id: meta[0], index: coord, ...meta[1] }; |
| 1859 |
} |
| 1860 |
} |
| 1861 |
|
| 1862 |
space = ColorSpace.get(space); |
| 1863 |
|
| 1864 |
let normalizedCoord = coord.toLowerCase(); |
| 1865 |
|
| 1866 |
let i = 0; |
| 1867 |
for (let id in space.coords) { |
| 1868 |
let meta = space.coords[id]; |
| 1869 |
|
| 1870 |
if ( |
| 1871 |
id.toLowerCase() === normalizedCoord || |
| 1872 |
meta.name?.toLowerCase() === normalizedCoord |
| 1873 |
) { |
| 1874 |
return { space, id, index: i, ...meta }; |
| 1875 |
} |
| 1876 |
|
| 1877 |
i++; |
| 1878 |
} |
| 1879 |
|
| 1880 |
throw new TypeError( |
| 1881 |
`No "${coord}" coordinate found in ${space.name}. Its coordinates are: ${Object.keys(space.coords).join(", ")}`, |
| 1882 |
); |
| 1883 |
} |
| 1884 |
|
| 1885 |
static DEFAULT_FORMAT = { |
| 1886 |
type: "functions", |
| 1887 |
name: "color", |
| 1888 |
}; |
| 1889 |
} |
| 1890 |
|
| 1891 |
function getPath (space) { |
| 1892 |
let ret = [space]; |
| 1893 |
|
| 1894 |
for (let s = space; (s = s.base);) { |
| 1895 |
ret.push(s); |
| 1896 |
} |
| 1897 |
|
| 1898 |
return ret; |
| 1899 |
} |
| 1900 |
|
| 1901 |
var XYZ_D65 = new ColorSpace({ |
| 1902 |
id: "xyz-d65", |
| 1903 |
name: "XYZ D65", |
| 1904 |
coords: { |
| 1905 |
x: { |
| 1906 |
refRange: [0, 1], |
| 1907 |
name: "X", |
| 1908 |
}, |
| 1909 |
y: { |
| 1910 |
refRange: [0, 1], |
| 1911 |
name: "Y", |
| 1912 |
}, |
| 1913 |
z: { |
| 1914 |
refRange: [0, 1], |
| 1915 |
name: "Z", |
| 1916 |
}, |
| 1917 |
}, |
| 1918 |
white: "D65", |
| 1919 |
formats: { |
| 1920 |
color: { |
| 1921 |
ids: ["xyz-d65", "xyz"], |
| 1922 |
}, |
| 1923 |
}, |
| 1924 |
aliases: ["xyz"], |
| 1925 |
}); |
| 1926 |
|
| 1927 |
// Type re-exports |
| 1928 |
/** @typedef {import("./types.js").RGBOptions} RGBOptions */ |
| 1929 |
|
| 1930 |
/** Convenience class for RGB color spaces */ |
| 1931 |
class RGBColorSpace extends ColorSpace { |
| 1932 |
/** |
| 1933 |
* Creates a new RGB ColorSpace. |
| 1934 |
* If coords are not specified, they will use the default RGB coords. |
| 1935 |
* Instead of `fromBase()` and `toBase()` functions, |
| 1936 |
* you can specify to/from XYZ matrices and have the default `toBase()` and `fromBase()` |
| 1937 |
* methods use them via `this.M.toXYZ` and `this.M.fromXYZ`. |
| 1938 |
* @param {RGBOptions} options |
| 1939 |
*/ |
| 1940 |
constructor (options) { |
| 1941 |
if (!options.coords) { |
| 1942 |
options.coords = { |
| 1943 |
r: { |
| 1944 |
range: [0, 1], |
| 1945 |
name: "Red", |
| 1946 |
}, |
| 1947 |
g: { |
| 1948 |
range: [0, 1], |
| 1949 |
name: "Green", |
| 1950 |
}, |
| 1951 |
b: { |
| 1952 |
range: [0, 1], |
| 1953 |
name: "Blue", |
| 1954 |
}, |
| 1955 |
}; |
| 1956 |
} |
| 1957 |
|
| 1958 |
if (!options.base) { |
| 1959 |
options.base = XYZ_D65; |
| 1960 |
} |
| 1961 |
|
| 1962 |
// Accept matrices either as dedicated options or via the generic `M` object |
| 1963 |
let toXYZ = options.toXYZ_M ?? options.M?.toXYZ; |
| 1964 |
let fromXYZ = options.fromXYZ_M ?? options.M?.fromXYZ; |
| 1965 |
|
| 1966 |
options.referred ??= "display"; |
| 1967 |
|
| 1968 |
super(options); |
| 1969 |
|
| 1970 |
// Expose the matrices on the color space (via `this.M`) so consumers can reuse them. |
| 1971 |
if (toXYZ && fromXYZ) { |
| 1972 |
this.M.toXYZ = toXYZ; |
| 1973 |
this.M.fromXYZ = fromXYZ; |
| 1974 |
} |
| 1975 |
} |
| 1976 |
|
| 1977 |
toBase (rgb) { |
| 1978 |
let xyz = multiply_v3_m3x3(rgb, this.M.toXYZ); |
| 1979 |
|
| 1980 |
if (this.white !== this.base.white) { |
| 1981 |
// Perform chromatic adaptation |
| 1982 |
xyz = adapt$2(this.white, this.base.white, xyz); |
| 1983 |
} |
| 1984 |
|
| 1985 |
return xyz; |
| 1986 |
} |
| 1987 |
|
| 1988 |
fromBase (xyz) { |
| 1989 |
xyz = adapt$2(this.base.white, this.white, xyz); |
| 1990 |
return multiply_v3_m3x3(xyz, this.M.fromXYZ); |
| 1991 |
} |
| 1992 |
} |
| 1993 |
|
| 1994 |
var XYZ_D50 = new ColorSpace({ |
| 1995 |
id: "xyz-d50", |
| 1996 |
name: "XYZ D50", |
| 1997 |
white: "D50", |
| 1998 |
base: XYZ_D65, |
| 1999 |
fromBase: coords => adapt$2(XYZ_D65.white, "D50", coords), |
| 2000 |
toBase: coords => adapt$2("D50", XYZ_D65.white, coords), |
| 2001 |
}); |
| 2002 |
|
| 2003 |
// κ * ε = 2^3 = 8 |
| 2004 |
const ε$6 = 216 / 24389; // 6^3/29^3 == (24/116)^3 |
| 2005 |
const ε3$1 = 24 / 116; |
| 2006 |
const κ$4 = 24389 / 27; // 29^3/3^3 |
| 2007 |
|
| 2008 |
let white$4 = WHITES.D50; |
| 2009 |
|
| 2010 |
var lab = new ColorSpace({ |
| 2011 |
id: "lab", |
| 2012 |
name: "Lab", |
| 2013 |
coords: { |
| 2014 |
l: { |
| 2015 |
refRange: [0, 100], |
| 2016 |
name: "Lightness", |
| 2017 |
}, |
| 2018 |
a: { |
| 2019 |
refRange: [-125, 125], |
| 2020 |
}, |
| 2021 |
b: { |
| 2022 |
refRange: [-125, 125], |
| 2023 |
}, |
| 2024 |
}, |
| 2025 |
|
| 2026 |
// Assuming XYZ is relative to D50, convert to CIE Lab |
| 2027 |
// from CIE standard, which now defines these as a rational fraction |
| 2028 |
white: white$4, |
| 2029 |
|
| 2030 |
base: XYZ_D50, |
| 2031 |
// Convert D50-adapted XYX to Lab |
| 2032 |
// CIE 15.3:2004 section 8.2.1.1 |
| 2033 |
fromBase (XYZ) { |
| 2034 |
// XYZ scaled relative to reference white |
| 2035 |
let xyz = XYZ.map((value, i) => value / white$4[i]); |
| 2036 |
let f = xyz.map(value => (value > ε$6 ? Math.cbrt(value) : (κ$4 * value + 16) / 116)); |
| 2037 |
|
| 2038 |
let L = 116 * f[1] - 16; |
| 2039 |
let a = 500 * (f[0] - f[1]); |
| 2040 |
let b = 200 * (f[1] - f[2]); |
| 2041 |
|
| 2042 |
return [L, a, b]; |
| 2043 |
}, |
| 2044 |
// Convert Lab to D50-adapted XYZ |
| 2045 |
// Same result as CIE 15.3:2004 Appendix D although the derivation is different |
| 2046 |
// http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html |
| 2047 |
toBase (Lab) { |
| 2048 |
// compute f, starting with the luminance-related term |
| 2049 |
let [L, a, b] = Lab; |
| 2050 |
let f = []; |
| 2051 |
f[1] = (L + 16) / 116; |
| 2052 |
f[0] = a / 500 + f[1]; |
| 2053 |
f[2] = f[1] - b / 200; |
| 2054 |
|
| 2055 |
// compute xyz |
| 2056 |
// prettier-ignore |
| 2057 |
let xyz = [ |
| 2058 |
f[0] > ε3$1 ? Math.pow(f[0], 3) : (116 * f[0] - 16) / κ$4, |
| 2059 |
Lab[0] > 8 ? Math.pow((Lab[0] + 16) / 116, 3) : Lab[0] / κ$4, |
| 2060 |
f[2] > ε3$1 ? Math.pow(f[2], 3) : (116 * f[2] - 16) / κ$4, |
| 2061 |
]; |
| 2062 |
|
| 2063 |
// Compute XYZ by scaling xyz by reference white |
| 2064 |
return xyz.map((value, i) => value * white$4[i]); |
| 2065 |
}, |
| 2066 |
|
| 2067 |
formats: { |
| 2068 |
lab: { |
| 2069 |
coords: [ |
| 2070 |
"<percentage> | <number>", |
| 2071 |
"<number> | <percentage>", |
| 2072 |
"<number> | <percentage>", |
| 2073 |
], |
| 2074 |
}, |
| 2075 |
}, |
| 2076 |
}); |
| 2077 |
|
| 2078 |
/** |
| 2079 |
* Constrain an angle to 360 degrees |
| 2080 |
* @param {number} angle |
| 2081 |
* @returns {number} |
| 2082 |
*/ |
| 2083 |
function constrain (angle) { |
| 2084 |
if (typeof angle !== "number") { |
| 2085 |
return angle; |
| 2086 |
} |
| 2087 |
|
| 2088 |
return ((angle % 360) + 360) % 360; |
| 2089 |
} |
| 2090 |
|
| 2091 |
/** |
| 2092 |
* @param {"raw" | "increasing" | "decreasing" | "longer" | "shorter"} arc |
| 2093 |
* @param {[number, number]} angles |
| 2094 |
* @returns {[number, number]} |
| 2095 |
*/ |
| 2096 |
function adjust (arc, angles) { |
| 2097 |
let [a1, a2] = angles; |
| 2098 |
|
| 2099 |
let none1 = isNone(a1); |
| 2100 |
let none2 = isNone(a2); |
| 2101 |
|
| 2102 |
if (none1 && none2) { |
| 2103 |
return [a1, a2]; |
| 2104 |
} |
| 2105 |
else if (none1) { |
| 2106 |
a1 = a2; |
| 2107 |
} |
| 2108 |
else if (none2) { |
| 2109 |
a2 = a1; |
| 2110 |
} |
| 2111 |
|
| 2112 |
if (arc === "raw") { |
| 2113 |
return angles; |
| 2114 |
} |
| 2115 |
|
| 2116 |
a1 = constrain(a1); |
| 2117 |
a2 = constrain(a2); |
| 2118 |
|
| 2119 |
let angleDiff = a2 - a1; |
| 2120 |
|
| 2121 |
if (arc === "increasing") { |
| 2122 |
if (angleDiff < 0) { |
| 2123 |
a2 += 360; |
| 2124 |
} |
| 2125 |
} |
| 2126 |
else if (arc === "decreasing") { |
| 2127 |
if (angleDiff > 0) { |
| 2128 |
a1 += 360; |
| 2129 |
} |
| 2130 |
} |
| 2131 |
else if (arc === "longer") { |
| 2132 |
if (-180 < angleDiff && angleDiff < 180) { |
| 2133 |
if (angleDiff > 0) { |
| 2134 |
a1 += 360; |
| 2135 |
} |
| 2136 |
else { |
| 2137 |
a2 += 360; |
| 2138 |
} |
| 2139 |
} |
| 2140 |
} |
| 2141 |
else if (arc === "shorter") { |
| 2142 |
if (angleDiff > 180) { |
| 2143 |
a1 += 360; |
| 2144 |
} |
| 2145 |
else if (angleDiff < -180) { |
| 2146 |
a2 += 360; |
| 2147 |
} |
| 2148 |
} |
| 2149 |
|
| 2150 |
return [a1, a2]; |
| 2151 |
} |
| 2152 |
|
| 2153 |
var lch = new ColorSpace({ |
| 2154 |
id: "lch", |
| 2155 |
name: "LCH", |
| 2156 |
coords: { |
| 2157 |
l: { |
| 2158 |
refRange: [0, 100], |
| 2159 |
name: "Lightness", |
| 2160 |
}, |
| 2161 |
c: { |
| 2162 |
refRange: [0, 150], |
| 2163 |
name: "Chroma", |
| 2164 |
}, |
| 2165 |
h: { |
| 2166 |
refRange: [0, 360], |
| 2167 |
type: "angle", |
| 2168 |
name: "Hue", |
| 2169 |
}, |
| 2170 |
}, |
| 2171 |
|
| 2172 |
base: lab, |
| 2173 |
fromBase (Lab) { |
| 2174 |
// These methods are used for other polar forms as well, so we can't hardcode the ε |
| 2175 |
if (this.ε === undefined) { |
| 2176 |
// @ts-expect-error Property 'coords' does not exist on type 'string | ColorSpace' |
| 2177 |
let range = Object.values(this.base.coords)[1].refRange; |
| 2178 |
let extent = range[1] - range[0]; |
| 2179 |
this.ε = extent / 100000; |
| 2180 |
} |
| 2181 |
|
| 2182 |
// Convert to polar form |
| 2183 |
let [L, a, b] = Lab; |
| 2184 |
let isAchromatic = Math.abs(a) < this.ε && Math.abs(b) < this.ε; |
| 2185 |
let h = isAchromatic ? null : constrain((Math.atan2(b, a) * 180) / Math.PI); |
| 2186 |
let C = isAchromatic ? 0 : Math.sqrt(a ** 2 + b ** 2); |
| 2187 |
|
| 2188 |
return [L, C, h]; |
| 2189 |
}, |
| 2190 |
toBase (lch) { |
| 2191 |
// Convert from polar form |
| 2192 |
let [L, C, h] = lch; |
| 2193 |
let a = null, |
| 2194 |
b = null; |
| 2195 |
|
| 2196 |
if (!isNone(h)) { |
| 2197 |
C = C < 0 ? 0 : C; // Clamp negative Chroma |
| 2198 |
a = C * Math.cos((h * Math.PI) / 180); |
| 2199 |
b = C * Math.sin((h * Math.PI) / 180); |
| 2200 |
} |
| 2201 |
|
| 2202 |
return [L, a, b]; |
| 2203 |
}, |
| 2204 |
|
| 2205 |
formats: { |
| 2206 |
lch: { |
| 2207 |
coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"], |
| 2208 |
}, |
| 2209 |
}, |
| 2210 |
}); |
| 2211 |
|
| 2212 |
// deltaE2000 is a statistically significant improvement |
| 2213 |
// and is recommended by the CIE and Idealliance |
| 2214 |
// especially for color differences less than 10 deltaE76 |
| 2215 |
// but is wicked complicated |
| 2216 |
// and many implementations have small errors! |
| 2217 |
// DeltaE2000 is also discontinuous; in case this |
| 2218 |
// matters to you, use deltaECMC instead. |
| 2219 |
|
| 2220 |
const Gfactor = 25 ** 7; |
| 2221 |
const π$1 = Math.PI; |
| 2222 |
const r2d = 180 / π$1; |
| 2223 |
const d2r$1 = π$1 / 180; |
| 2224 |
|
| 2225 |
function pow7 (x) { |
| 2226 |
// Faster than x ** 7 or Math.pow(x, 7) |
| 2227 |
|
| 2228 |
const x2 = x * x; |
| 2229 |
const x7 = x2 * x2 * x2 * x; |
| 2230 |
|
| 2231 |
return x7; |
| 2232 |
} |
| 2233 |
|
| 2234 |
/** |
| 2235 |
* @param {import("../types.js").ColorTypes} color |
| 2236 |
* @param {import("../types.js").ColorTypes} sample |
| 2237 |
* @param {{ kL?: number | undefined; kC?: number | undefined; kH?: number | undefined }} options |
| 2238 |
* @returns {number} |
| 2239 |
*/ |
| 2240 |
function deltaE2000 (color, sample, { kL = 1, kC = 1, kH = 1 } = {}) { |
| 2241 |
[color, sample] = getColor([color, sample]); |
| 2242 |
|
| 2243 |
// Given this color as the reference |
| 2244 |
// and the function parameter as the sample, |
| 2245 |
// calculate deltaE 2000. |
| 2246 |
|
| 2247 |
// This implementation assumes the parametric |
| 2248 |
// weighting factors kL, kC and kH |
| 2249 |
// for the influence of viewing conditions |
| 2250 |
// are all 1, as sadly seems typical. |
| 2251 |
// kL should be increased for lightness texture or noise |
| 2252 |
// and kC increased for chroma noise |
| 2253 |
|
| 2254 |
let [L1, a1, b1] = lab.from(color); |
| 2255 |
let C1 = lch.from(lab, [L1, a1, b1])[1]; |
| 2256 |
let [L2, a2, b2] = lab.from(sample); |
| 2257 |
let C2 = lch.from(lab, [L2, a2, b2])[1]; |
| 2258 |
|
| 2259 |
// Check for negative Chroma, |
| 2260 |
// which might happen through |
| 2261 |
// direct user input of LCH values |
| 2262 |
|
| 2263 |
if (C1 < 0) { |
| 2264 |
C1 = 0; |
| 2265 |
} |
| 2266 |
if (C2 < 0) { |
| 2267 |
C2 = 0; |
| 2268 |
} |
| 2269 |
|
| 2270 |
let Cbar = (C1 + C2) / 2; // mean Chroma |
| 2271 |
|
| 2272 |
// calculate a-axis asymmetry factor from mean Chroma |
| 2273 |
// this turns JND ellipses for near-neutral colors back into circles |
| 2274 |
let C7 = pow7(Cbar); |
| 2275 |
|
| 2276 |
let G = 0.5 * (1 - Math.sqrt(C7 / (C7 + Gfactor))); |
| 2277 |
|
| 2278 |
// scale a axes by asymmetry factor |
| 2279 |
// this by the way is why there is no Lab2000 colorspace |
| 2280 |
let adash1 = (1 + G) * a1; |
| 2281 |
let adash2 = (1 + G) * a2; |
| 2282 |
|
| 2283 |
// calculate new Chroma from scaled a and original b axes |
| 2284 |
let Cdash1 = Math.sqrt(adash1 ** 2 + b1 ** 2); |
| 2285 |
let Cdash2 = Math.sqrt(adash2 ** 2 + b2 ** 2); |
| 2286 |
|
| 2287 |
// calculate new hues, with zero hue for true neutrals |
| 2288 |
// and in degrees, not radians |
| 2289 |
|
| 2290 |
let h1 = adash1 === 0 && b1 === 0 ? 0 : Math.atan2(b1, adash1); |
| 2291 |
let h2 = adash2 === 0 && b2 === 0 ? 0 : Math.atan2(b2, adash2); |
| 2292 |
|
| 2293 |
if (h1 < 0) { |
| 2294 |
h1 += 2 * π$1; |
| 2295 |
} |
| 2296 |
if (h2 < 0) { |
| 2297 |
h2 += 2 * π$1; |
| 2298 |
} |
| 2299 |
|
| 2300 |
h1 *= r2d; |
| 2301 |
h2 *= r2d; |
| 2302 |
|
| 2303 |
// Lightness and Chroma differences; sign matters |
| 2304 |
let ΔL = L2 - L1; |
| 2305 |
let ΔC = Cdash2 - Cdash1; |
| 2306 |
|
| 2307 |
// Hue difference, getting the sign correct |
| 2308 |
let hdiff = h2 - h1; |
| 2309 |
let hsum = h1 + h2; |
| 2310 |
let habs = Math.abs(hdiff); |
| 2311 |
let Δh; |
| 2312 |
|
| 2313 |
if (Cdash1 * Cdash2 === 0) { |
| 2314 |
Δh = 0; |
| 2315 |
} |
| 2316 |
else if (habs <= 180) { |
| 2317 |
Δh = hdiff; |
| 2318 |
} |
| 2319 |
else if (hdiff > 180) { |
| 2320 |
Δh = hdiff - 360; |
| 2321 |
} |
| 2322 |
else if (hdiff < -180) { |
| 2323 |
Δh = hdiff + 360; |
| 2324 |
} |
| 2325 |
else { |
| 2326 |
defaults.warn("the unthinkable has happened"); |
| 2327 |
} |
| 2328 |
|
| 2329 |
// weighted Hue difference, more for larger Chroma |
| 2330 |
let ΔH = 2 * Math.sqrt(Cdash2 * Cdash1) * Math.sin((Δh * d2r$1) / 2); |
| 2331 |
|
| 2332 |
// calculate mean Lightness and Chroma |
| 2333 |
let Ldash = (L1 + L2) / 2; |
| 2334 |
let Cdash = (Cdash1 + Cdash2) / 2; |
| 2335 |
let Cdash7 = pow7(Cdash); |
| 2336 |
|
| 2337 |
// Compensate for non-linearity in the blue region of Lab. |
| 2338 |
// Four possibilities for hue weighting factor, |
| 2339 |
// depending on the angles, to get the correct sign |
| 2340 |
let hdash; |
| 2341 |
if (Cdash1 * Cdash2 === 0) { |
| 2342 |
hdash = hsum; // which should be zero |
| 2343 |
} |
| 2344 |
else if (habs <= 180) { |
| 2345 |
hdash = hsum / 2; |
| 2346 |
} |
| 2347 |
else if (hsum < 360) { |
| 2348 |
hdash = (hsum + 360) / 2; |
| 2349 |
} |
| 2350 |
else { |
| 2351 |
hdash = (hsum - 360) / 2; |
| 2352 |
} |
| 2353 |
|
| 2354 |
// positional corrections to the lack of uniformity of CIELAB |
| 2355 |
// These are all trying to make JND ellipsoids more like spheres |
| 2356 |
|
| 2357 |
// SL Lightness crispening factor |
| 2358 |
// a background with L=50 is assumed |
| 2359 |
let lsq = (Ldash - 50) ** 2; |
| 2360 |
let SL = 1 + (0.015 * lsq) / Math.sqrt(20 + lsq); |
| 2361 |
|
| 2362 |
// SC Chroma factor, similar to those in CMC and deltaE 94 formulae |
| 2363 |
let SC = 1 + 0.045 * Cdash; |
| 2364 |
|
| 2365 |
// Cross term T for blue non-linearity |
| 2366 |
let T = 1; |
| 2367 |
T -= 0.17 * Math.cos((hdash - 30) * d2r$1); |
| 2368 |
T += 0.24 * Math.cos(2 * hdash * d2r$1); |
| 2369 |
T += 0.32 * Math.cos((3 * hdash + 6) * d2r$1); |
| 2370 |
T -= 0.2 * Math.cos((4 * hdash - 63) * d2r$1); |
| 2371 |
|
| 2372 |
// SH Hue factor depends on Chroma, |
| 2373 |
// as well as adjusted hue angle like deltaE94. |
| 2374 |
let SH = 1 + 0.015 * Cdash * T; |
| 2375 |
|
| 2376 |
// RT Hue rotation term compensates for rotation of JND ellipses |
| 2377 |
// and Munsell constant hue lines |
| 2378 |
// in the medium-high Chroma blue region |
| 2379 |
// (Hue 225 to 315) |
| 2380 |
let Δθ = 30 * Math.exp(-1 * ((hdash - 275) / 25) ** 2); |
| 2381 |
let RC = 2 * Math.sqrt(Cdash7 / (Cdash7 + Gfactor)); |
| 2382 |
let RT = -1 * Math.sin(2 * Δθ * d2r$1) * RC; |
| 2383 |
|
| 2384 |
// Finally calculate the deltaE, term by term as root sume of squares |
| 2385 |
let dE = (ΔL / (kL * SL)) ** 2; |
| 2386 |
dE += (ΔC / (kC * SC)) ** 2; |
| 2387 |
dE += (ΔH / (kH * SH)) ** 2; |
| 2388 |
dE += RT * (ΔC / (kC * SC)) * (ΔH / (kH * SH)); |
| 2389 |
return Math.sqrt(dE); |
| 2390 |
// Yay!!! |
| 2391 |
} |
| 2392 |
|
| 2393 |
/** @import { Matrix3x3 } from "../types.js" */ |
| 2394 |
|
| 2395 |
/** |
| 2396 |
* Matrices used by this color space, also available as `Oklab.M`. |
| 2397 |
* Recalculated for consistent reference white, |
| 2398 |
* see https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-943521484 |
| 2399 |
* @type {Record<string, Matrix3x3>} |
| 2400 |
*/ |
| 2401 |
// prettier-ignore |
| 2402 |
const M$d = { |
| 2403 |
XYZtoLMS: [ |
| 2404 |
[ 0.8190224379967030, 0.3619062600528904, -0.1288737815209879 ], |
| 2405 |
[ 0.0329836539323885, 0.9292868615863434, 0.0361446663506424 ], |
| 2406 |
[ 0.0481771893596242, 0.2642395317527308, 0.6335478284694309 ], |
| 2407 |
], |
| 2408 |
// inverse of XYZtoLMS |
| 2409 |
LMStoXYZ: [ |
| 2410 |
[ 1.2268798758459243, -0.5578149944602171, 0.2813910456659647 ], |
| 2411 |
[ -0.0405757452148008, 1.1122868032803170, -0.0717110580655164 ], |
| 2412 |
[ -0.0763729366746601, -0.4214933324022432, 1.5869240198367816 ], |
| 2413 |
], |
| 2414 |
LMStoLab: [ |
| 2415 |
[ 0.2104542683093140, 0.7936177747023054, -0.0040720430116193 ], |
| 2416 |
[ 1.9779985324311684, -2.4285922420485799, 0.4505937096174110 ], |
| 2417 |
[ 0.0259040424655478, 0.7827717124575296, -0.8086757549230774 ], |
| 2418 |
], |
| 2419 |
// LMStoLab inverted |
| 2420 |
LabtoLMS: [ |
| 2421 |
[ 1.0000000000000000, 0.3963377773761749, 0.2158037573099136 ], |
| 2422 |
[ 1.0000000000000000, -0.1055613458156586, -0.0638541728258133 ], |
| 2423 |
[ 1.0000000000000000, -0.0894841775298119, -1.2914855480194092 ], |
| 2424 |
], |
| 2425 |
}; |
| 2426 |
|
| 2427 |
var Oklab = new ColorSpace({ |
| 2428 |
id: "oklab", |
| 2429 |
name: "Oklab", |
| 2430 |
coords: { |
| 2431 |
l: { |
| 2432 |
refRange: [0, 1], |
| 2433 |
name: "Lightness", |
| 2434 |
}, |
| 2435 |
a: { |
| 2436 |
refRange: [-0.4, 0.4], |
| 2437 |
}, |
| 2438 |
b: { |
| 2439 |
refRange: [-0.4, 0.4], |
| 2440 |
}, |
| 2441 |
}, |
| 2442 |
|
| 2443 |
// Note that XYZ is relative to D65 |
| 2444 |
white: "D65", |
| 2445 |
base: XYZ_D65, |
| 2446 |
M: M$d, |
| 2447 |
fromBase (XYZ) { |
| 2448 |
// move to LMS cone domain |
| 2449 |
let LMS = multiply_v3_m3x3(XYZ, M$d.XYZtoLMS); |
| 2450 |
|
| 2451 |
// non-linearity |
| 2452 |
LMS[0] = Math.cbrt(LMS[0]); |
| 2453 |
LMS[1] = Math.cbrt(LMS[1]); |
| 2454 |
LMS[2] = Math.cbrt(LMS[2]); |
| 2455 |
|
| 2456 |
return multiply_v3_m3x3(LMS, M$d.LMStoLab, LMS); |
| 2457 |
}, |
| 2458 |
toBase (OKLab) { |
| 2459 |
// move to LMS cone domain |
| 2460 |
let LMSg = multiply_v3_m3x3(OKLab, M$d.LabtoLMS); |
| 2461 |
|
| 2462 |
// restore linearity |
| 2463 |
LMSg[0] = LMSg[0] ** 3; |
| 2464 |
LMSg[1] = LMSg[1] ** 3; |
| 2465 |
LMSg[2] = LMSg[2] ** 3; |
| 2466 |
|
| 2467 |
return multiply_v3_m3x3(LMSg, M$d.LMStoXYZ, LMSg); |
| 2468 |
}, |
| 2469 |
|
| 2470 |
formats: { |
| 2471 |
oklab: { |
| 2472 |
coords: [ |
| 2473 |
"<percentage> | <number>", |
| 2474 |
"<number> | <percentage>", |
| 2475 |
"<number> | <percentage>", |
| 2476 |
], |
| 2477 |
}, |
| 2478 |
}, |
| 2479 |
}); |
| 2480 |
|
| 2481 |
/** |
| 2482 |
* More accurate color-difference formulae |
| 2483 |
* than the simple 1976 Euclidean distance in CIE Lab |
| 2484 |
* @param {import("../types.js").ColorTypes} color |
| 2485 |
* @param {import("../types.js").ColorTypes} sample |
| 2486 |
* @returns {number} |
| 2487 |
*/ |
| 2488 |
function deltaEOK (color, sample) { |
| 2489 |
[color, sample] = getColor([color, sample]); |
| 2490 |
|
| 2491 |
// Given this color as the reference |
| 2492 |
// and a sample, |
| 2493 |
// calculate deltaEOK, term by term as root sum of squares |
| 2494 |
let [L1, a1, b1] = Oklab.from(color); |
| 2495 |
let [L2, a2, b2] = Oklab.from(sample); |
| 2496 |
let ΔL = L1 - L2; |
| 2497 |
let Δa = a1 - a2; |
| 2498 |
let Δb = b1 - b2; |
| 2499 |
return Math.sqrt(ΔL ** 2 + Δa ** 2 + Δb ** 2); |
| 2500 |
} |
| 2501 |
|
| 2502 |
/** @import { ColorTypes } from "./types.js" */ |
| 2503 |
|
| 2504 |
const ε$5 = 0.000075; |
| 2505 |
|
| 2506 |
/** |
| 2507 |
* Check if a color is in gamut of either its own or another color space |
| 2508 |
* @param {ColorTypes} color |
| 2509 |
* @param {string | ColorSpace} [space] |
| 2510 |
* @param {{ epsilon?: number | undefined }} [param2] |
| 2511 |
* @returns {boolean} |
| 2512 |
*/ |
| 2513 |
function inGamut (color, space, { epsilon = ε$5 } = {}) { |
| 2514 |
color = getColor(color); |
| 2515 |
|
| 2516 |
if (!space) { |
| 2517 |
space = color.space; |
| 2518 |
} |
| 2519 |
|
| 2520 |
space = ColorSpace.get(space); |
| 2521 |
let coords = color.coords; |
| 2522 |
|
| 2523 |
if (space !== color.space) { |
| 2524 |
coords = space.from(color); |
| 2525 |
} |
| 2526 |
|
| 2527 |
return space.inGamut(coords, { epsilon }); |
| 2528 |
} |
| 2529 |
|
| 2530 |
/** @import { ColorTypes, PlainColorObject, ToGamutOptions } from "./types.js" */ |
| 2531 |
|
| 2532 |
/** |
| 2533 |
* Convert to color space and return a new color |
| 2534 |
* @param {ColorTypes} color |
| 2535 |
* @param {string | ColorSpace} space |
| 2536 |
* @param {{ inGamut?: boolean | ToGamutOptions | undefined }} options |
| 2537 |
* @returns {PlainColorObject} |
| 2538 |
*/ |
| 2539 |
function to (color, space, { inGamut } = {}) { |
| 2540 |
color = getColor(color); |
| 2541 |
space = ColorSpace.get(space); |
| 2542 |
|
| 2543 |
let coords = space.from(color); |
| 2544 |
let ret = { space, coords, alpha: color.alpha }; |
| 2545 |
|
| 2546 |
if (inGamut) { |
| 2547 |
ret = toGamut(ret, inGamut === true ? undefined : inGamut); |
| 2548 |
} |
| 2549 |
|
| 2550 |
return ret; |
| 2551 |
} |
| 2552 |
|
| 2553 |
/** @type {"color"} */ |
| 2554 |
to.returns = "color"; |
| 2555 |
|
| 2556 |
/** @import { ColorTypes, Coords } from "./types.js" */ |
| 2557 |
|
| 2558 |
/** |
| 2559 |
* Options for {@link getAll} |
| 2560 |
* @typedef GetAllOptions |
| 2561 |
* @property {string | ColorSpace | undefined} [space] |
| 2562 |
* The color space to convert to. Defaults to the color's current space |
| 2563 |
* @property {number | undefined} [precision] |
| 2564 |
* The number of significant digits to round the coordinates to |
| 2565 |
*/ |
| 2566 |
|
| 2567 |
/** |
| 2568 |
* Get the coordinates of a color in any color space |
| 2569 |
* @overload |
| 2570 |
* @param {ColorTypes} color |
| 2571 |
* @param {string | ColorSpace} [options=color.space] The color space to convert to. Defaults to the color's current space |
| 2572 |
* @returns {Coords} The color coordinates in the given color space |
| 2573 |
*/ |
| 2574 |
/** |
| 2575 |
* @overload |
| 2576 |
* @param {ColorTypes} color |
| 2577 |
* @param {GetAllOptions} [options] |
| 2578 |
* @returns {Coords} The color coordinates in the given color space |
| 2579 |
*/ |
| 2580 |
function getAll (color, options) { |
| 2581 |
color = getColor(color); |
| 2582 |
|
| 2583 |
let space = ColorSpace.get(options, options?.space); |
| 2584 |
let precision = options?.precision; |
| 2585 |
|
| 2586 |
let coords; |
| 2587 |
if (!space || color.space.equals(space)) { |
| 2588 |
// No conversion needed |
| 2589 |
coords = color.coords.slice(); |
| 2590 |
} |
| 2591 |
else { |
| 2592 |
coords = space.from(color); |
| 2593 |
} |
| 2594 |
|
| 2595 |
return precision === undefined ? coords : coords.map(coord => toPrecision(coord, precision)); |
| 2596 |
} |
| 2597 |
|
| 2598 |
/** @import { ColorTypes, Ref } from "./types.js" */ |
| 2599 |
|
| 2600 |
/** |
| 2601 |
* @param {ColorTypes} color |
| 2602 |
* @param {Ref} prop |
| 2603 |
* @returns {number} |
| 2604 |
*/ |
| 2605 |
function get (color, prop) { |
| 2606 |
color = getColor(color); |
| 2607 |
|
| 2608 |
if (prop === "alpha") { |
| 2609 |
return color.alpha ?? 1; |
| 2610 |
} |
| 2611 |
|
| 2612 |
let { space, index } = ColorSpace.resolveCoord(prop, color.space); |
| 2613 |
let coords = getAll(color, space); |
| 2614 |
return coords[index]; |
| 2615 |
} |
| 2616 |
|
| 2617 |
var OKLCH = new ColorSpace({ |
| 2618 |
id: "oklch", |
| 2619 |
name: "OkLCh", |
| 2620 |
coords: { |
| 2621 |
l: { |
| 2622 |
refRange: [0, 1], |
| 2623 |
name: "Lightness", |
| 2624 |
}, |
| 2625 |
c: { |
| 2626 |
refRange: [0, 0.4], |
| 2627 |
name: "Chroma", |
| 2628 |
}, |
| 2629 |
h: { |
| 2630 |
refRange: [0, 360], |
| 2631 |
type: "angle", |
| 2632 |
name: "Hue", |
| 2633 |
}, |
| 2634 |
}, |
| 2635 |
white: "D65", |
| 2636 |
|
| 2637 |
base: Oklab, |
| 2638 |
fromBase: lch.fromBase, |
| 2639 |
toBase: lch.toBase, |
| 2640 |
|
| 2641 |
formats: { |
| 2642 |
oklch: { |
| 2643 |
coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"], |
| 2644 |
}, |
| 2645 |
}, |
| 2646 |
}); |
| 2647 |
|
| 2648 |
/** @import { ColorTypes, Coords, PlainColorObject } from "./types.js" */ |
| 2649 |
|
| 2650 |
/** |
| 2651 |
* Set all coordinates of a color at once, in its own color space or another. |
| 2652 |
* Modifies the color in place. |
| 2653 |
* @overload |
| 2654 |
* @param {ColorTypes} color |
| 2655 |
* @param {Coords} coords Array of coordinates |
| 2656 |
* @param {number} [alpha] |
| 2657 |
* @returns {PlainColorObject} |
| 2658 |
*/ |
| 2659 |
/** |
| 2660 |
* @overload |
| 2661 |
* @param {ColorTypes} color |
| 2662 |
* @param {string | ColorSpace} space The color space of the provided coordinates. |
| 2663 |
* @param {Coords} coords Array of coordinates |
| 2664 |
* @param {number} [alpha] |
| 2665 |
* @returns {PlainColorObject} |
| 2666 |
*/ |
| 2667 |
function setAll (color, space, coords, alpha) { |
| 2668 |
color = getColor(color); |
| 2669 |
|
| 2670 |
if (Array.isArray(space)) { |
| 2671 |
// Space is omitted |
| 2672 |
[space, coords, alpha] = [color.space, space, coords]; |
| 2673 |
} |
| 2674 |
|
| 2675 |
space = ColorSpace.get(space); // Make sure we have a ColorSpace object |
| 2676 |
color.coords = space === color.space ? coords.slice() : space.to(color.space, coords); |
| 2677 |
|
| 2678 |
if (alpha !== undefined) { |
| 2679 |
color.alpha = alpha; |
| 2680 |
} |
| 2681 |
|
| 2682 |
return color; |
| 2683 |
} |
| 2684 |
|
| 2685 |
/** @type {"color"} */ |
| 2686 |
setAll.returns = "color"; |
| 2687 |
|
| 2688 |
/** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */ |
| 2689 |
|
| 2690 |
/** |
| 2691 |
* Set properties and return current instance |
| 2692 |
* @overload |
| 2693 |
* @param {ColorTypes} color |
| 2694 |
* @param {Ref} prop |
| 2695 |
* @param {number | ((coord: number) => number)} value |
| 2696 |
* @returns {PlainColorObject} |
| 2697 |
*/ |
| 2698 |
/** |
| 2699 |
* @overload |
| 2700 |
* @param {ColorTypes} color |
| 2701 |
* @param {Record<string, number | ((coord: number) => number)>} props |
| 2702 |
* @returns {PlainColorObject} |
| 2703 |
*/ |
| 2704 |
function set (color, prop, value) { |
| 2705 |
color = getColor(color); |
| 2706 |
|
| 2707 |
if (arguments.length === 2 && type(arguments[1]) === "object") { |
| 2708 |
// Argument is an object literal |
| 2709 |
let object = arguments[1]; |
| 2710 |
for (let p in object) { |
| 2711 |
set(color, p, object[p]); |
| 2712 |
} |
| 2713 |
} |
| 2714 |
else { |
| 2715 |
if (typeof value === "function") { |
| 2716 |
value = value(get(color, prop)); |
| 2717 |
} |
| 2718 |
|
| 2719 |
if (prop === "alpha") { |
| 2720 |
color.alpha = value; |
| 2721 |
} |
| 2722 |
else { |
| 2723 |
let { space, index } = ColorSpace.resolveCoord(prop, color.space); |
| 2724 |
let coords = getAll(color, space); |
| 2725 |
coords[index] = value; |
| 2726 |
setAll(color, space, coords); |
| 2727 |
} |
| 2728 |
} |
| 2729 |
|
| 2730 |
return color; |
| 2731 |
} |
| 2732 |
|
| 2733 |
/** @type {"color"} */ |
| 2734 |
set.returns = "color"; |
| 2735 |
|
| 2736 |
/** @import { Coords, PlainColorObject } from "./types.js" */ |
| 2737 |
|
| 2738 |
/** |
| 2739 |
* @param {PlainColorObject} color |
| 2740 |
* @returns {PlainColorObject} |
| 2741 |
*/ |
| 2742 |
function clone (color) { |
| 2743 |
return { |
| 2744 |
space: color.space, |
| 2745 |
coords: /** @type {Coords} */ (color.coords.slice()), |
| 2746 |
alpha: color.alpha, |
| 2747 |
}; |
| 2748 |
} |
| 2749 |
|
| 2750 |
/** @import { ColorTypes } from "./types.js" */ |
| 2751 |
|
| 2752 |
/** |
| 2753 |
* Euclidean distance of colors in an arbitrary color space |
| 2754 |
* @param {ColorTypes} color1 |
| 2755 |
* @param {ColorTypes} color2 |
| 2756 |
* @param {string | ColorSpace} space |
| 2757 |
* @returns {number} |
| 2758 |
*/ |
| 2759 |
function distance (color1, color2, space = "lab") { |
| 2760 |
space = ColorSpace.get(space); |
| 2761 |
|
| 2762 |
// Assume getColor() is called on color in space.from() |
| 2763 |
let coords1 = space.from(color1); |
| 2764 |
let coords2 = space.from(color2); |
| 2765 |
|
| 2766 |
return Math.sqrt( |
| 2767 |
coords1.reduce((acc, c1, i) => { |
| 2768 |
let c2 = coords2[i]; |
| 2769 |
if (isNone(c1) || isNone(c2)) { |
| 2770 |
return acc; |
| 2771 |
} |
| 2772 |
|
| 2773 |
return acc + (c2 - c1) ** 2; |
| 2774 |
}, 0), |
| 2775 |
); |
| 2776 |
} |
| 2777 |
|
| 2778 |
/** |
| 2779 |
* @param {import("../types.js").ColorTypes} color |
| 2780 |
* @param {import("../types.js").ColorTypes} sample |
| 2781 |
* @returns {number} |
| 2782 |
*/ |
| 2783 |
function deltaE76 (color, sample) { |
| 2784 |
// Assume getColor() is called in the distance function |
| 2785 |
return distance(color, sample, "lab"); |
| 2786 |
} |
| 2787 |
|
| 2788 |
// More accurate color-difference formulae |
| 2789 |
// than the simple 1976 Euclidean distance in Lab |
| 2790 |
|
| 2791 |
// CMC by the Color Measurement Committee of the |
| 2792 |
// Bradford Society of Dyeists and Colorsts, 1994. |
| 2793 |
// Uses LCH rather than Lab, |
| 2794 |
// with different weights for L, C and H differences |
| 2795 |
// A nice increase in accuracy for modest increase in complexity |
| 2796 |
const π = Math.PI; |
| 2797 |
const d2r = π / 180; |
| 2798 |
|
| 2799 |
/** |
| 2800 |
* @param {import("../types.js").ColorTypes} color |
| 2801 |
* @param {import("../types.js").ColorTypes} sample |
| 2802 |
* @param {{ l?: number | undefined; c?: number | undefined }} options |
| 2803 |
* @returns {number} |
| 2804 |
*/ |
| 2805 |
function deltaECMC (color, sample, { l = 2, c = 1 } = {}) { |
| 2806 |
[color, sample] = getColor([color, sample]); |
| 2807 |
|
| 2808 |
// Given this color as the reference |
| 2809 |
// and a sample, |
| 2810 |
// calculate deltaE CMC. |
| 2811 |
|
| 2812 |
// This implementation assumes the parametric |
| 2813 |
// weighting factors l:c are 2:1 |
| 2814 |
// which is typical for non-textile uses. |
| 2815 |
|
| 2816 |
let [L1, a1, b1] = lab.from(color); |
| 2817 |
let [, C1, H1] = lch.from(lab, [L1, a1, b1]); |
| 2818 |
let [L2, a2, b2] = lab.from(sample); |
| 2819 |
let C2 = lch.from(lab, [L2, a2, b2])[1]; |
| 2820 |
|
| 2821 |
// let [L1, a1, b1] = color.getAll(lab); |
| 2822 |
// let C1 = color.get("lch.c"); |
| 2823 |
// let H1 = color.get("lch.h"); |
| 2824 |
// let [L2, a2, b2] = sample.getAll(lab); |
| 2825 |
// let C2 = sample.get("lch.c"); |
| 2826 |
|
| 2827 |
// Check for negative Chroma, |
| 2828 |
// which might happen through |
| 2829 |
// direct user input of LCH values |
| 2830 |
|
| 2831 |
if (C1 < 0) { |
| 2832 |
C1 = 0; |
| 2833 |
} |
| 2834 |
if (C2 < 0) { |
| 2835 |
C2 = 0; |
| 2836 |
} |
| 2837 |
|
| 2838 |
// we don't need H2 as ΔH is calculated from Δa, Δb and ΔC |
| 2839 |
|
| 2840 |
// Lightness and Chroma differences |
| 2841 |
// These are (color - sample), unlike deltaE2000 |
| 2842 |
let ΔL = L1 - L2; |
| 2843 |
let ΔC = C1 - C2; |
| 2844 |
|
| 2845 |
let Δa = a1 - a2; |
| 2846 |
let Δb = b1 - b2; |
| 2847 |
|
| 2848 |
// weighted Hue difference, less for larger Chroma difference |
| 2849 |
|
| 2850 |
let H2 = Δa ** 2 + Δb ** 2 - ΔC ** 2; |
| 2851 |
// due to roundoff error it is possible that, for zero a and b, |
| 2852 |
// ΔC > Δa + Δb is 0, resulting in attempting |
| 2853 |
// to take the square root of a negative number |
| 2854 |
|
| 2855 |
// trying instead the equation from Industrial Color Physics |
| 2856 |
// By Georg A. Klein |
| 2857 |
|
| 2858 |
// let ΔH = ((a1 * b2) - (a2 * b1)) / Math.sqrt(0.5 * ((C2 * C1) + (a2 * a1) + (b2 * b1))); |
| 2859 |
// console.log({ΔH}); |
| 2860 |
// This gives the same result to 12 decimal places |
| 2861 |
// except it sometimes NaNs when trying to root a negative number |
| 2862 |
|
| 2863 |
// let ΔH = Math.sqrt(H2); we never actually use the root, it gets squared again!! |
| 2864 |
|
| 2865 |
// positional corrections to the lack of uniformity of CIELAB |
| 2866 |
// These are all trying to make JND ellipsoids more like spheres |
| 2867 |
|
| 2868 |
// SL Lightness crispening factor, depends entirely on L1 not L2 |
| 2869 |
let SL = 0.511; // linear portion of the Y to L transfer function |
| 2870 |
if (L1 >= 16) { |
| 2871 |
// cubic portion |
| 2872 |
SL = (0.040975 * L1) / (1 + 0.01765 * L1); |
| 2873 |
} |
| 2874 |
|
| 2875 |
// SC Chroma factor |
| 2876 |
let SC = (0.0638 * C1) / (1 + 0.0131 * C1) + 0.638; |
| 2877 |
|
| 2878 |
// Cross term T for blue non-linearity |
| 2879 |
let T; |
| 2880 |
if (isNone(H1)) { |
| 2881 |
H1 = 0; |
| 2882 |
} |
| 2883 |
|
| 2884 |
if (H1 >= 164 && H1 <= 345) { |
| 2885 |
T = 0.56 + Math.abs(0.2 * Math.cos((H1 + 168) * d2r)); |
| 2886 |
} |
| 2887 |
else { |
| 2888 |
T = 0.36 + Math.abs(0.4 * Math.cos((H1 + 35) * d2r)); |
| 2889 |
} |
| 2890 |
// console.log({T}); |
| 2891 |
|
| 2892 |
// SH Hue factor also depends on C1, |
| 2893 |
let C4 = Math.pow(C1, 4); |
| 2894 |
let F = Math.sqrt(C4 / (C4 + 1900)); |
| 2895 |
let SH = SC * (F * T + 1 - F); |
| 2896 |
|
| 2897 |
// Finally calculate the deltaE, term by term as root sume of squares |
| 2898 |
let dE = (ΔL / (l * SL)) ** 2; |
| 2899 |
dE += (ΔC / (c * SC)) ** 2; |
| 2900 |
dE += H2 / SH ** 2; |
| 2901 |
// dE += (ΔH / SH) ** 2; |
| 2902 |
return Math.sqrt(dE); |
| 2903 |
// Yay!!! |
| 2904 |
} |
| 2905 |
|
| 2906 |
const Yw$1 = 203; // absolute luminance of media white |
| 2907 |
|
| 2908 |
var XYZ_Abs_D65 = new ColorSpace({ |
| 2909 |
// Absolute CIE XYZ, with a D65 whitepoint, |
| 2910 |
// as used in most HDR colorspaces as a starting point. |
| 2911 |
// SDR spaces are converted per BT.2048 |
| 2912 |
// so that diffuse, media white is 203 cd/m² |
| 2913 |
id: "xyz-abs-d65", |
| 2914 |
cssId: "--xyz-abs-d65", |
| 2915 |
name: "Absolute XYZ D65", |
| 2916 |
coords: { |
| 2917 |
x: { |
| 2918 |
refRange: [0, 9504.7], |
| 2919 |
name: "Xa", |
| 2920 |
}, |
| 2921 |
y: { |
| 2922 |
refRange: [0, 10000], |
| 2923 |
name: "Ya", |
| 2924 |
}, |
| 2925 |
z: { |
| 2926 |
refRange: [0, 10888.3], |
| 2927 |
name: "Za", |
| 2928 |
}, |
| 2929 |
}, |
| 2930 |
|
| 2931 |
base: XYZ_D65, |
| 2932 |
fromBase (XYZ) { |
| 2933 |
// Make XYZ absolute, not relative to media white |
| 2934 |
// Maximum luminance in PQ is 10,000 cd/m² |
| 2935 |
// Relative XYZ has Y=1 for media white |
| 2936 |
return XYZ.map(v => v * Yw$1); |
| 2937 |
}, |
| 2938 |
toBase (AbsXYZ) { |
| 2939 |
// Convert to media-white relative XYZ |
| 2940 |
return AbsXYZ.map(v => v / Yw$1); |
| 2941 |
}, |
| 2942 |
}); |
| 2943 |
|
| 2944 |
/** @import { Matrix3x3, Vector3 } from "../types.js" */ |
| 2945 |
|
| 2946 |
const b$1 = 1.15; |
| 2947 |
const g = 0.66; |
| 2948 |
const n$1 = 2610 / 2 ** 14; |
| 2949 |
const ninv$1 = 2 ** 14 / 2610; |
| 2950 |
const c1$2 = 3424 / 2 ** 12; |
| 2951 |
const c2$2 = 2413 / 2 ** 7; |
| 2952 |
const c3$2 = 2392 / 2 ** 7; |
| 2953 |
const p$1 = (1.7 * 2523) / 2 ** 5; |
| 2954 |
const pinv = 2 ** 5 / (1.7 * 2523); |
| 2955 |
const d = -0.56; |
| 2956 |
const d0 = 1.6295499532821566e-11; |
| 2957 |
|
| 2958 |
/** |
| 2959 |
* Matrices used by this color space, also available as `Jzazbz.M` |
| 2960 |
* @type {Record<string, Matrix3x3>} |
| 2961 |
*/ |
| 2962 |
// prettier-ignore |
| 2963 |
const M$c = { |
| 2964 |
XYZtoCone: [ |
| 2965 |
[ 0.41478972, 0.579999, 0.0146480 ], |
| 2966 |
[ -0.2015100, 1.120649, 0.0531008 ], |
| 2967 |
[ -0.0166008, 0.264800, 0.6684799 ], |
| 2968 |
], |
| 2969 |
// XYZtoCone inverted |
| 2970 |
ConetoXYZ: [ |
| 2971 |
[ 1.9242264357876067, -1.0047923125953657, 0.037651404030618 ], |
| 2972 |
[ 0.35031676209499907, 0.7264811939316552, -0.06538442294808501 ], |
| 2973 |
[ -0.09098281098284752, -0.3127282905230739, 1.5227665613052603 ], |
| 2974 |
], |
| 2975 |
ConetoIab: [ |
| 2976 |
[ 0.5, 0.5, 0 ], |
| 2977 |
[ 3.524000, -4.066708, 0.542708 ], |
| 2978 |
[ 0.199076, 1.096799, -1.295875 ], |
| 2979 |
], |
| 2980 |
// ConetoIab inverted |
| 2981 |
IabtoCone: [ |
| 2982 |
[ 1, 0.13860504327153927, 0.05804731615611883 ], |
| 2983 |
[ 1, -0.1386050432715393, -0.058047316156118904 ], |
| 2984 |
[ 1, -0.09601924202631895, -0.81189189605603900 ], |
| 2985 |
], |
| 2986 |
}; |
| 2987 |
|
| 2988 |
var Jzazbz = new ColorSpace({ |
| 2989 |
id: "jzazbz", |
| 2990 |
name: "Jzazbz", |
| 2991 |
coords: { |
| 2992 |
jz: { |
| 2993 |
refRange: [0, 1], |
| 2994 |
name: "Jz", |
| 2995 |
}, |
| 2996 |
az: { |
| 2997 |
refRange: [-0.21, 0.21], |
| 2998 |
}, |
| 2999 |
bz: { |
| 3000 |
refRange: [-0.21, 0.21], |
| 3001 |
}, |
| 3002 |
}, |
| 3003 |
|
| 3004 |
base: XYZ_Abs_D65, |
| 3005 |
M: M$c, |
| 3006 |
fromBase (XYZ) { |
| 3007 |
// First make XYZ absolute, not relative to media white |
| 3008 |
// Maximum luminance in PQ is 10,000 cd/m² |
| 3009 |
// Relative XYZ has Y=1 for media white |
| 3010 |
// BT.2048 says media white Y=203 at PQ 58 |
| 3011 |
|
| 3012 |
let [Xa, Ya, Za] = XYZ; |
| 3013 |
|
| 3014 |
// modify X and Y to minimize blue curvature |
| 3015 |
let Xm = b$1 * Xa - (b$1 - 1) * Za; |
| 3016 |
let Ym = g * Ya - (g - 1) * Xa; |
| 3017 |
|
| 3018 |
// move to LMS cone domain |
| 3019 |
let LMS = multiply_v3_m3x3([Xm, Ym, Za], M$c.XYZtoCone); |
| 3020 |
|
| 3021 |
// PQ-encode LMS |
| 3022 |
let PQLMS = /** @type {Vector3} } */ ( |
| 3023 |
LMS.map(function (val) { |
| 3024 |
let num = c1$2 + c2$2 * spow(val / 10000, n$1); |
| 3025 |
let denom = 1 + c3$2 * spow(val / 10000, n$1); |
| 3026 |
|
| 3027 |
return spow(num / denom, p$1); |
| 3028 |
}) |
| 3029 |
); |
| 3030 |
|
| 3031 |
// almost there, calculate Iz az bz |
| 3032 |
let [Iz, az, bz] = multiply_v3_m3x3(PQLMS, M$c.ConetoIab); |
| 3033 |
// console.log({Iz, az, bz}); |
| 3034 |
|
| 3035 |
let Jz = ((1 + d) * Iz) / (1 + d * Iz) - d0; |
| 3036 |
return [Jz, az, bz]; |
| 3037 |
}, |
| 3038 |
toBase (Jzazbz) { |
| 3039 |
let [Jz, az, bz] = Jzazbz; |
| 3040 |
let Iz = (Jz + d0) / (1 + d - d * (Jz + d0)); |
| 3041 |
|
| 3042 |
// bring into LMS cone domain |
| 3043 |
let PQLMS = multiply_v3_m3x3([Iz, az, bz], M$c.IabtoCone); |
| 3044 |
|
| 3045 |
// convert from PQ-coded to linear-light |
| 3046 |
let LMS = /** @type {Vector3} } */ ( |
| 3047 |
PQLMS.map(function (val) { |
| 3048 |
let num = c1$2 - spow(val, pinv); |
| 3049 |
let denom = c3$2 * spow(val, pinv) - c2$2; |
| 3050 |
let x = 10000 * spow(num / denom, ninv$1); |
| 3051 |
|
| 3052 |
return x; // luminance relative to diffuse white, [0, 70 or so]. |
| 3053 |
}) |
| 3054 |
); |
| 3055 |
|
| 3056 |
// modified abs XYZ |
| 3057 |
let [Xm, Ym, Za] = multiply_v3_m3x3(LMS, M$c.ConetoXYZ); |
| 3058 |
|
| 3059 |
// un-modify X and Y to get D65 XYZ, relative to media white |
| 3060 |
let Xa = (Xm + (b$1 - 1) * Za) / b$1; |
| 3061 |
let Ya = (Ym + (g - 1) * Xa) / g; |
| 3062 |
return [Xa, Ya, Za]; |
| 3063 |
}, |
| 3064 |
|
| 3065 |
formats: { |
| 3066 |
// https://drafts.csswg.org/css-color-hdr/#Jzazbz |
| 3067 |
jzazbz: { |
| 3068 |
coords: [ |
| 3069 |
"<percentage> | <number>", |
| 3070 |
"<number> | <percentage>", |
| 3071 |
"<number> | <percentage>", |
| 3072 |
], |
| 3073 |
}, |
| 3074 |
}, |
| 3075 |
}); |
| 3076 |
|
| 3077 |
var jzczhz = new ColorSpace({ |
| 3078 |
id: "jzczhz", |
| 3079 |
name: "JzCzHz", |
| 3080 |
coords: { |
| 3081 |
jz: { |
| 3082 |
refRange: [0, 1], |
| 3083 |
name: "Jz", |
| 3084 |
}, |
| 3085 |
cz: { |
| 3086 |
refRange: [0, 0.26], |
| 3087 |
name: "Chroma", |
| 3088 |
}, |
| 3089 |
hz: { |
| 3090 |
refRange: [0, 360], |
| 3091 |
type: "angle", |
| 3092 |
name: "Hue", |
| 3093 |
}, |
| 3094 |
}, |
| 3095 |
|
| 3096 |
base: Jzazbz, |
| 3097 |
fromBase: lch.fromBase, |
| 3098 |
toBase: lch.toBase, |
| 3099 |
|
| 3100 |
formats: { |
| 3101 |
// https://drafts.csswg.org/css-color-hdr/#JzCzhz |
| 3102 |
jzczhz: { |
| 3103 |
coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"], |
| 3104 |
}, |
| 3105 |
}, |
| 3106 |
}); |
| 3107 |
|
| 3108 |
/** |
| 3109 |
* More accurate color-difference formulae |
| 3110 |
* than the simple 1976 Euclidean distance in Lab |
| 3111 |
* |
| 3112 |
* Uses JzCzHz, which has improved perceptual uniformity |
| 3113 |
* and thus a simple Euclidean root-sum of ΔL² ΔC² ΔH² |
| 3114 |
* gives good results. |
| 3115 |
* @param {import("../types.js").ColorTypes} color |
| 3116 |
* @param {import("../types.js").ColorTypes} sample |
| 3117 |
* @returns {number} |
| 3118 |
*/ |
| 3119 |
function deltaEJz (color, sample) { |
| 3120 |
[color, sample] = getColor([color, sample]); |
| 3121 |
|
| 3122 |
// Given this color as the reference |
| 3123 |
// and a sample, |
| 3124 |
// calculate deltaE in JzCzHz. |
| 3125 |
let [Jz1, Cz1, Hz1] = jzczhz.from(color); |
| 3126 |
let [Jz2, Cz2, Hz2] = jzczhz.from(sample); |
| 3127 |
|
| 3128 |
// Lightness and Chroma differences |
| 3129 |
// sign does not matter as they are squared. |
| 3130 |
let ΔJ = Jz1 - Jz2; |
| 3131 |
let ΔC = Cz1 - Cz2; |
| 3132 |
|
| 3133 |
// length of chord for ΔH |
| 3134 |
if (isNone(Hz1) && isNone(Hz2)) { |
| 3135 |
// both undefined hues |
| 3136 |
Hz1 = 0; |
| 3137 |
Hz2 = 0; |
| 3138 |
} |
| 3139 |
else if (isNone(Hz1)) { |
| 3140 |
// one undefined, set to the defined hue |
| 3141 |
Hz1 = Hz2; |
| 3142 |
} |
| 3143 |
else if (isNone(Hz2)) { |
| 3144 |
Hz2 = Hz1; |
| 3145 |
} |
| 3146 |
|
| 3147 |
let Δh = Hz1 - Hz2; |
| 3148 |
let ΔH = 2 * Math.sqrt(Cz1 * Cz2) * Math.sin((Δh / 2) * (Math.PI / 180)); |
| 3149 |
|
| 3150 |
return Math.sqrt(ΔJ ** 2 + ΔC ** 2 + ΔH ** 2); |
| 3151 |
} |
| 3152 |
|
| 3153 |
/** @import { Matrix3x3, Vector3 } from "../types.js" */ |
| 3154 |
|
| 3155 |
const c1$1 = 3424 / 4096; |
| 3156 |
const c2$1 = 2413 / 128; |
| 3157 |
const c3$1 = 2392 / 128; |
| 3158 |
const m1 = 2610 / 16384; |
| 3159 |
const m2 = 2523 / 32; |
| 3160 |
const im1 = 16384 / 2610; |
| 3161 |
const im2 = 32 / 2523; |
| 3162 |
|
| 3163 |
// Reference (rational-form) matrices, kept for documentation but not used directly: |
| 3164 |
// linear-light Rec.2020 to LMS (with crosstalk) and its inverse |
| 3165 |
// rational terms from Jan Fröhlich, Encoding High Dynamic Range |
| 3166 |
// and Wide Color Gamut Imagery, p.97 and ITU-R BT.2124-0 pp.2-3 |
| 3167 |
/* |
| 3168 |
const Rec2020toLMS = [ |
| 3169 |
[ 1688 / 4096, 2146 / 4096, 262 / 4096 ], |
| 3170 |
[ 683 / 4096, 2951 / 4096, 462 / 4096 ], |
| 3171 |
[ 99 / 4096, 309 / 4096, 3688 / 4096 ] |
| 3172 |
]; |
| 3173 |
const LMStoRec2020 = [ |
| 3174 |
[ 3.4375568932814012112, -2.5072112125095058195, 0.069654319228104608382], |
| 3175 |
[-0.79142868665644156125, 1.9838372198740089874, -0.19240853321756742626 ], |
| 3176 |
[-0.025646662911506476363, -0.099240248643945566751, 1.1248869115554520431 ] |
| 3177 |
]; |
| 3178 |
*/ |
| 3179 |
|
| 3180 |
/** |
| 3181 |
* Matrices used by this color space, also available as `ICTCP.M` |
| 3182 |
* @type {Record<string, Matrix3x3>} |
| 3183 |
*/ |
| 3184 |
// prettier-ignore |
| 3185 |
const M$b = { |
| 3186 |
// includes the 4% crosstalk components, from the Dolby "What is ICtCp" paper |
| 3187 |
XYZtoLMS: [ |
| 3188 |
[ 0.3592832590121217, 0.6976051147779502, -0.0358915932320290 ], |
| 3189 |
[ -0.1920808463704993, 1.1004767970374321, 0.0753748658519118 ], |
| 3190 |
[ 0.0070797844607479, 0.0748396662186362, 0.8433265453898765 ], |
| 3191 |
], |
| 3192 |
// includes the Ebner LMS coefficients, the rotation, |
| 3193 |
// and the scaling to the [-0.5,0.5] range |
| 3194 |
LMStoIPT: [ |
| 3195 |
[ 2048 / 4096, 2048 / 4096, 0 ], |
| 3196 |
[ 6610 / 4096, -13613 / 4096, 7003 / 4096 ], |
| 3197 |
[ 17933 / 4096, -17390 / 4096, -543 / 4096 ], |
| 3198 |
], |
| 3199 |
// inverted matrices, calculated from the above |
| 3200 |
IPTtoLMS: [ |
| 3201 |
[ 0.9999999999999998, 0.0086090370379328, 0.1110296250030260 ], |
| 3202 |
[ 0.9999999999999998, -0.0086090370379328, -0.1110296250030259 ], |
| 3203 |
[ 0.9999999999999998, 0.5600313357106791, -0.3206271749873188 ], |
| 3204 |
], |
| 3205 |
LMStoXYZ: [ |
| 3206 |
[ 2.0701522183894223, -1.3263473389671563, 0.2066510476294053 ], |
| 3207 |
[ 0.3647385209748072, 0.6805660249472273, -0.0453045459220347 ], |
| 3208 |
[ -0.0497472075358123, -0.0492609666966131, 1.1880659249923042 ], |
| 3209 |
], |
| 3210 |
}; |
| 3211 |
|
| 3212 |
// Only the PQ form of ICtCp is implemented here. There is also an HLG form. |
| 3213 |
// from Dolby, "WHAT IS ICTCP?" |
| 3214 |
// https://professional.dolby.com/siteassets/pdfs/ictcp_dolbywhitepaper_v071.pdf |
| 3215 |
// and |
| 3216 |
// Dolby, "Perceptual Color Volume |
| 3217 |
// Measuring the Distinguishable Colors of HDR and WCG Displays" |
| 3218 |
// https://professional.dolby.com/siteassets/pdfs/dolby-vision-measuring-perceptual-color-volume-v7.1.pdf |
| 3219 |
var ictcp = new ColorSpace({ |
| 3220 |
id: "ictcp", |
| 3221 |
name: "ICTCP", |
| 3222 |
// From BT.2100-2 page 7: |
| 3223 |
// During production, signal values are expected to exceed the |
| 3224 |
// range E′ = [0.0 : 1.0]. This provides processing headroom and avoids |
| 3225 |
// signal degradation during cascaded processing. Such values of E′, |
| 3226 |
// below 0.0 or exceeding 1.0, should not be clipped during production |
| 3227 |
// and exchange. |
| 3228 |
// Values below 0.0 should not be clipped in reference displays (even |
| 3229 |
// though they represent “negative” light) to allow the black level of |
| 3230 |
// the signal (LB) to be properly set using test signals known as “PLUGE” |
| 3231 |
coords: { |
| 3232 |
i: { |
| 3233 |
refRange: [0, 1], // Constant luminance, |
| 3234 |
name: "I", |
| 3235 |
}, |
| 3236 |
ct: { |
| 3237 |
refRange: [-0.5, 0.5], // Full BT.2020 gamut in range [-0.5, 0.5] |
| 3238 |
name: "CT", |
| 3239 |
}, |
| 3240 |
cp: { |
| 3241 |
refRange: [-0.5, 0.5], |
| 3242 |
name: "CP", |
| 3243 |
}, |
| 3244 |
}, |
| 3245 |
|
| 3246 |
base: XYZ_Abs_D65, |
| 3247 |
M: M$b, |
| 3248 |
fromBase (XYZ) { |
| 3249 |
// move to LMS cone domain |
| 3250 |
let LMS = multiply_v3_m3x3(XYZ, M$b.XYZtoLMS); |
| 3251 |
|
| 3252 |
return LMStoICtCp(LMS); |
| 3253 |
}, |
| 3254 |
toBase (ICtCp) { |
| 3255 |
let LMS = ICtCptoLMS(ICtCp); |
| 3256 |
|
| 3257 |
return multiply_v3_m3x3(LMS, M$b.LMStoXYZ); |
| 3258 |
}, |
| 3259 |
|
| 3260 |
formats: { |
| 3261 |
ictcp: { |
| 3262 |
coords: [ |
| 3263 |
"<percentage> | <number>", |
| 3264 |
"<number> | <percentage>", |
| 3265 |
"<number> | <percentage>", |
| 3266 |
], |
| 3267 |
}, |
| 3268 |
}, |
| 3269 |
}); |
| 3270 |
|
| 3271 |
/** |
| 3272 |
* |
| 3273 |
* @param {Vector3} LMS |
| 3274 |
* @returns {Vector3} |
| 3275 |
*/ |
| 3276 |
function LMStoICtCp (LMS) { |
| 3277 |
// apply the PQ EOTF |
| 3278 |
// we can't ever be dividing by zero because of the "1 +" in the denominator |
| 3279 |
let PQLMS = /** @type {Vector3} */ ( |
| 3280 |
LMS.map(function (val) { |
| 3281 |
let num = c1$1 + c2$1 * (val / 10000) ** m1; |
| 3282 |
let denom = 1 + c3$1 * (val / 10000) ** m1; |
| 3283 |
|
| 3284 |
return (num / denom) ** m2; |
| 3285 |
}) |
| 3286 |
); |
| 3287 |
|
| 3288 |
// LMS to IPT, with rotation for Y'C'bC'r compatibility |
| 3289 |
return multiply_v3_m3x3(PQLMS, M$b.LMStoIPT); |
| 3290 |
} |
| 3291 |
|
| 3292 |
/** |
| 3293 |
* |
| 3294 |
* @param {Vector3} ICtCp |
| 3295 |
* @returns {Vector3} |
| 3296 |
*/ |
| 3297 |
function ICtCptoLMS (ICtCp) { |
| 3298 |
let PQLMS = multiply_v3_m3x3(ICtCp, M$b.IPTtoLMS); |
| 3299 |
|
| 3300 |
// From BT.2124-0 Annex 2 Conversion 3 |
| 3301 |
let LMS = /** @type {Vector3} */ ( |
| 3302 |
PQLMS.map(function (val) { |
| 3303 |
let num = Math.max(val ** im2 - c1$1, 0); |
| 3304 |
let denom = c2$1 - c3$1 * val ** im2; |
| 3305 |
return 10000 * (num / denom) ** im1; |
| 3306 |
}) |
| 3307 |
); |
| 3308 |
|
| 3309 |
return LMS; |
| 3310 |
} |
| 3311 |
|
| 3312 |
/** |
| 3313 |
* Delta E in ICtCp space, |
| 3314 |
* which the ITU calls Delta E ITP, which is shorter. |
| 3315 |
* Formulae from ITU Rec. ITU-R BT.2124-0 |
| 3316 |
* @param {import("../types.js").ColorTypes} color |
| 3317 |
* @param {import("../types.js").ColorTypes} sample |
| 3318 |
* @returns {number} |
| 3319 |
*/ |
| 3320 |
function deltaEITP (color, sample) { |
| 3321 |
[color, sample] = getColor([color, sample]); |
| 3322 |
|
| 3323 |
// Given this color as the reference |
| 3324 |
// and a sample, |
| 3325 |
// calculate deltaE in ICtCp |
| 3326 |
// which is simply the Euclidean distance |
| 3327 |
|
| 3328 |
let [I1, T1, P1] = ictcp.from(color); |
| 3329 |
let [I2, T2, P2] = ictcp.from(sample); |
| 3330 |
|
| 3331 |
// the 0.25 factor is to undo the encoding scaling in Ct |
| 3332 |
// the 720 is so that 1 deltaE = 1 JND |
| 3333 |
// per ITU-R BT.2124-0 p.3 |
| 3334 |
|
| 3335 |
return 720 * Math.sqrt((I1 - I2) ** 2 + 0.25 * (T1 - T2) ** 2 + (P1 - P2) ** 2); |
| 3336 |
} |
| 3337 |
|
| 3338 |
/** |
| 3339 |
* More accurate color-difference formulae |
| 3340 |
* than the simple 1976 Euclidean distance in CIE Lab |
| 3341 |
* The Oklab a and b axes are scaled relative to the L axis, for better uniformity |
| 3342 |
* Björn Ottosson said: |
| 3343 |
* "I've recently done some tests with color distance datasets as implemented |
| 3344 |
* in Colorio and on both the Combvd dataset and the OSA-UCS dataset a |
| 3345 |
* scale factor of slightly more than 2 for a and b would give the best results |
| 3346 |
* (2.016 works best for Combvd and 2.045 for the OSA-UCS dataset)." |
| 3347 |
* @see {@link <https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-945714988>} |
| 3348 |
* @param {import("../types.js").ColorTypes} color |
| 3349 |
* @param {import("../types.js").ColorTypes} sample |
| 3350 |
* @returns {number} |
| 3351 |
*/ |
| 3352 |
function deltaEOK2 (color, sample) { |
| 3353 |
[color, sample] = getColor([color, sample]); |
| 3354 |
|
| 3355 |
// Given this color as the reference |
| 3356 |
// and a sample, |
| 3357 |
// calculate deltaEOK2, term by term as root sum of squares |
| 3358 |
let abscale = 2; |
| 3359 |
let [L1, a1, b1] = Oklab.from(color); |
| 3360 |
let [L2, a2, b2] = Oklab.from(sample); |
| 3361 |
let ΔL = L1 - L2; |
| 3362 |
let Δa = abscale * (a1 - a2); |
| 3363 |
let Δb = abscale * (b1 - b2); |
| 3364 |
return Math.sqrt(ΔL ** 2 + Δa ** 2 + Δb ** 2); |
| 3365 |
} |
| 3366 |
|
| 3367 |
/** @import { Coords, Matrix3x3, Vector3 } from "../types.js" */ |
| 3368 |
|
| 3369 |
// Type re-exports |
| 3370 |
/** @typedef {import("../types.js").Cam16Object} Cam16Object */ |
| 3371 |
/** @typedef {import("../types.js").Cam16Input} Cam16Input */ |
| 3372 |
/** @typedef {import("../types.js").Cam16Environment} Cam16Environment */ |
| 3373 |
|
| 3374 |
const white$3 = WHITES.D65; |
| 3375 |
const adaptedCoef = 0.42; |
| 3376 |
const adaptedCoefInv = 1 / adaptedCoef; |
| 3377 |
const tau$1 = 2 * Math.PI; |
| 3378 |
|
| 3379 |
/** |
| 3380 |
* Matrices used by this color space, also available as `CAM16_JMh.M` |
| 3381 |
* @type {Record<string, Matrix3x3>} |
| 3382 |
*/ |
| 3383 |
// prettier-ignore |
| 3384 |
const M$a = { |
| 3385 |
cat16: [ |
| 3386 |
[ 0.401288, 0.650173, -0.051461 ], |
| 3387 |
[ -0.250268, 1.204414, 0.045854 ], |
| 3388 |
[ -0.002079, 0.048952, 0.953127 ], |
| 3389 |
], |
| 3390 |
cat16Inv: [ |
| 3391 |
[ 1.8620678550872327, -1.0112546305316843, 0.14918677544445175 ], |
| 3392 |
[ 0.38752654323613717, 0.6214474419314753, -0.008973985167612518 ], |
| 3393 |
[ -0.015841498849333856, -0.03412293802851557, 1.0499644368778496 ], |
| 3394 |
], |
| 3395 |
m1: [ |
| 3396 |
[ 460.0, 451.0, 288.0 ], |
| 3397 |
[ 460.0, -891.0, -261.0 ], |
| 3398 |
[ 460.0, -220.0, -6300.0 ], |
| 3399 |
], |
| 3400 |
}; |
| 3401 |
|
| 3402 |
const surroundMap = { |
| 3403 |
dark: [0.8, 0.525, 0.8], |
| 3404 |
dim: [0.9, 0.59, 0.9], |
| 3405 |
average: [1, 0.69, 1], |
| 3406 |
}; |
| 3407 |
|
| 3408 |
const hueQuadMap = { |
| 3409 |
// Red, Yellow, Green, Blue, Red |
| 3410 |
h: [20.14, 90.0, 164.25, 237.53, 380.14], |
| 3411 |
e: [0.8, 0.7, 1.0, 1.2, 0.8], |
| 3412 |
H: [0.0, 100.0, 200.0, 300.0, 400.0], |
| 3413 |
}; |
| 3414 |
|
| 3415 |
const rad2deg = 180 / Math.PI; |
| 3416 |
const deg2rad$1 = Math.PI / 180; |
| 3417 |
|
| 3418 |
/** |
| 3419 |
* @param {Coords} coords |
| 3420 |
* @param {number} fl |
| 3421 |
* @returns {[number, number, number]} |
| 3422 |
*/ |
| 3423 |
function adapt$1 (coords, fl) { |
| 3424 |
const temp = /** @type {[number, number, number]} */ ( |
| 3425 |
coords.map(c => { |
| 3426 |
const x = spow(fl * Math.abs(c) * 0.01, adaptedCoef); |
| 3427 |
return (400 * copySign(x, c)) / (x + 27.13); |
| 3428 |
}) |
| 3429 |
); |
| 3430 |
return temp; |
| 3431 |
} |
| 3432 |
|
| 3433 |
/** |
| 3434 |
* @param {Coords} adapted |
| 3435 |
* @param {number} fl |
| 3436 |
* @returns {[number, number, number]} |
| 3437 |
*/ |
| 3438 |
function unadapt (adapted, fl) { |
| 3439 |
const constant = (100 / fl) * 27.13 ** adaptedCoefInv; |
| 3440 |
return /** @type {[number, number, number]} */ ( |
| 3441 |
adapted.map(c => { |
| 3442 |
const cabs = Math.abs(c); |
| 3443 |
return copySign(constant * spow(cabs / (400 - cabs), adaptedCoefInv), c); |
| 3444 |
}) |
| 3445 |
); |
| 3446 |
} |
| 3447 |
|
| 3448 |
/** |
| 3449 |
* @param {number} h |
| 3450 |
*/ |
| 3451 |
function hueQuadrature (h) { |
| 3452 |
let hp = constrain(h); |
| 3453 |
if (hp <= hueQuadMap.h[0]) { |
| 3454 |
hp += 360; |
| 3455 |
} |
| 3456 |
|
| 3457 |
const i = bisectLeft(hueQuadMap.h, hp) - 1; |
| 3458 |
const [hi, hii] = hueQuadMap.h.slice(i, i + 2); |
| 3459 |
const [ei, eii] = hueQuadMap.e.slice(i, i + 2); |
| 3460 |
const Hi = hueQuadMap.H[i]; |
| 3461 |
|
| 3462 |
const t = (hp - hi) / ei; |
| 3463 |
return Hi + (100 * t) / (t + (hii - hp) / eii); |
| 3464 |
} |
| 3465 |
|
| 3466 |
/** |
| 3467 |
* @param {number} H |
| 3468 |
*/ |
| 3469 |
function invHueQuadrature (H) { |
| 3470 |
let Hp = ((H % 400) + 400) % 400; |
| 3471 |
const i = Math.floor(0.01 * Hp); |
| 3472 |
Hp = Hp % 100; |
| 3473 |
const [hi, hii] = hueQuadMap.h.slice(i, i + 2); |
| 3474 |
const [ei, eii] = hueQuadMap.e.slice(i, i + 2); |
| 3475 |
|
| 3476 |
return constrain((Hp * (eii * hi - ei * hii) - 100 * hi * eii) / (Hp * (eii - ei) - 100 * eii)); |
| 3477 |
} |
| 3478 |
|
| 3479 |
/** |
| 3480 |
* @param {[number, number, number]} refWhite |
| 3481 |
* @param {number} adaptingLuminance |
| 3482 |
* @param {number} backgroundLuminance |
| 3483 |
* @param {keyof typeof surroundMap} surround |
| 3484 |
* @param {boolean} discounting |
| 3485 |
* @returns {Cam16Environment} |
| 3486 |
*/ |
| 3487 |
function environment ( |
| 3488 |
refWhite, |
| 3489 |
adaptingLuminance, |
| 3490 |
backgroundLuminance, |
| 3491 |
surround, |
| 3492 |
discounting, |
| 3493 |
) { |
| 3494 |
const env = {}; |
| 3495 |
|
| 3496 |
env.discounting = discounting; |
| 3497 |
env.refWhite = refWhite; |
| 3498 |
env.surround = surround; |
| 3499 |
const xyzW = /** @type {Vector3} */ ( |
| 3500 |
refWhite.map(c => { |
| 3501 |
return c * 100; |
| 3502 |
}) |
| 3503 |
); |
| 3504 |
|
| 3505 |
// The average luminance of the environment in `cd/m^2cd/m` (a.k.a. nits) |
| 3506 |
env.la = adaptingLuminance; |
| 3507 |
// The relative luminance of the nearby background |
| 3508 |
env.yb = backgroundLuminance; |
| 3509 |
// Absolute luminance of the reference white. |
| 3510 |
const yw = xyzW[1]; |
| 3511 |
|
| 3512 |
// Cone response for reference white |
| 3513 |
const rgbW = multiply_v3_m3x3(xyzW, M$a.cat16); |
| 3514 |
|
| 3515 |
// Surround: dark, dim, and average |
| 3516 |
let values = surroundMap[env.surround]; |
| 3517 |
const f = values[0]; |
| 3518 |
env.c = values[1]; |
| 3519 |
env.nc = values[2]; |
| 3520 |
|
| 3521 |
const k = 1 / (5 * env.la + 1); |
| 3522 |
const k4 = k ** 4; |
| 3523 |
|
| 3524 |
// Factor of luminance level adaptation |
| 3525 |
env.fl = k4 * env.la + 0.1 * (1 - k4) * (1 - k4) * Math.cbrt(5 * env.la); |
| 3526 |
env.flRoot = env.fl ** 0.25; |
| 3527 |
|
| 3528 |
env.n = env.yb / yw; |
| 3529 |
env.z = 1.48 + Math.sqrt(env.n); |
| 3530 |
env.nbb = 0.725 * env.n ** -0.2; |
| 3531 |
env.ncb = env.nbb; |
| 3532 |
|
| 3533 |
// Degree of adaptation calculating if not discounting |
| 3534 |
// illuminant (assumed eye is fully adapted) |
| 3535 |
const d = Math.max(Math.min(f * (1 - (1 / 3.6) * Math.exp((-env.la - 42) / 92)), 1), 0); |
| 3536 |
env.dRgb = /** @type {[number, number, number]} */ ( |
| 3537 |
rgbW.map(c => { |
| 3538 |
return interpolate(1, yw / c, d); |
| 3539 |
}) |
| 3540 |
); |
| 3541 |
env.dRgbInv = /** @type {[number, number, number]} */ ( |
| 3542 |
env.dRgb.map(c => { |
| 3543 |
return 1 / c; |
| 3544 |
}) |
| 3545 |
); |
| 3546 |
|
| 3547 |
// Achromatic response |
| 3548 |
const rgbCW = /** @type {[number, number, number]} */ ( |
| 3549 |
rgbW.map((c, i) => { |
| 3550 |
return c * env.dRgb[i]; |
| 3551 |
}) |
| 3552 |
); |
| 3553 |
const rgbAW = adapt$1(rgbCW, env.fl); |
| 3554 |
env.aW = env.nbb * (2 * rgbAW[0] + rgbAW[1] + 0.05 * rgbAW[2]); |
| 3555 |
|
| 3556 |
// console.log(env); |
| 3557 |
|
| 3558 |
return env; |
| 3559 |
} |
| 3560 |
|
| 3561 |
// Pre-calculate everything we can with the viewing conditions |
| 3562 |
const viewingConditions$1 = environment(white$3, (64 / Math.PI) * 0.2, 20, "average", false); |
| 3563 |
|
| 3564 |
/** |
| 3565 |
* @param {Cam16Input} cam16 |
| 3566 |
* @param {Cam16Environment} env |
| 3567 |
* @returns {[number, number, number]} |
| 3568 |
*/ |
| 3569 |
function fromCam16 (cam16, env) { |
| 3570 |
// These check ensure one, and only one attribute for a |
| 3571 |
// given category is provided. |
| 3572 |
// @ts-expect-error The '^` operator is not allowed for boolean types |
| 3573 |
if (!((cam16.J !== undefined) ^ (cam16.Q !== undefined))) { |
| 3574 |
throw new Error("Conversion requires one and only one: 'J' or 'Q'"); |
| 3575 |
} |
| 3576 |
|
| 3577 |
// @ts-expect-error - The '^` operator is not allowed for boolean types |
| 3578 |
if (!((cam16.C !== undefined) ^ (cam16.M !== undefined) ^ (cam16.s !== undefined))) { |
| 3579 |
throw new Error("Conversion requires one and only one: 'C', 'M' or 's'"); |
| 3580 |
} |
| 3581 |
|
| 3582 |
// Hue is absolutely required |
| 3583 |
// @ts-expect-error - The '^` operator is not allowed for boolean types |
| 3584 |
if (!((cam16.h !== undefined) ^ (cam16.H !== undefined))) { |
| 3585 |
throw new Error("Conversion requires one and only one: 'h' or 'H'"); |
| 3586 |
} |
| 3587 |
|
| 3588 |
// Black |
| 3589 |
if (cam16.J === 0.0 || cam16.Q === 0.0) { |
| 3590 |
return [0.0, 0.0, 0.0]; |
| 3591 |
} |
| 3592 |
|
| 3593 |
// Break hue into Cartesian components |
| 3594 |
let hRad = 0.0; |
| 3595 |
if (cam16.h !== undefined) { |
| 3596 |
hRad = constrain(cam16.h) * deg2rad$1; |
| 3597 |
} |
| 3598 |
else { |
| 3599 |
hRad = invHueQuadrature(cam16.H) * deg2rad$1; |
| 3600 |
} |
| 3601 |
|
| 3602 |
const cosh = Math.cos(hRad); |
| 3603 |
const sinh = Math.sin(hRad); |
| 3604 |
|
| 3605 |
// Calculate `Jroot` from one of the lightness derived coordinates. |
| 3606 |
let Jroot = 0.0; |
| 3607 |
if (cam16.J !== undefined) { |
| 3608 |
Jroot = spow(cam16.J, 1 / 2) * 0.1; |
| 3609 |
} |
| 3610 |
else if (cam16.Q !== undefined) { |
| 3611 |
Jroot = (0.25 * env.c * cam16.Q) / ((env.aW + 4) * env.flRoot); |
| 3612 |
} |
| 3613 |
|
| 3614 |
// Calculate the `t` value from one of the chroma derived coordinates |
| 3615 |
let alpha = 0.0; |
| 3616 |
if (cam16.C !== undefined) { |
| 3617 |
alpha = cam16.C / Jroot; |
| 3618 |
} |
| 3619 |
else if (cam16.M !== undefined) { |
| 3620 |
alpha = cam16.M / env.flRoot / Jroot; |
| 3621 |
} |
| 3622 |
else if (cam16.s !== undefined) { |
| 3623 |
alpha = (0.0004 * cam16.s ** 2 * (env.aW + 4)) / env.c; |
| 3624 |
} |
| 3625 |
const t = spow(alpha * Math.pow(1.64 - Math.pow(0.29, env.n), -0.73), 10 / 9); |
| 3626 |
|
| 3627 |
// Eccentricity |
| 3628 |
const et = 0.25 * (Math.cos(hRad + 2) + 3.8); |
| 3629 |
|
| 3630 |
// Achromatic response |
| 3631 |
const A = env.aW * spow(Jroot, 2 / env.c / env.z); |
| 3632 |
|
| 3633 |
// Calculate red-green and yellow-blue components |
| 3634 |
const p1 = (5e4 / 13) * env.nc * env.ncb * et; |
| 3635 |
const p2 = A / env.nbb; |
| 3636 |
const r = 23 * (p2 + 0.305) * zdiv(t, 23 * p1 + t * (11 * cosh + 108 * sinh)); |
| 3637 |
const a = r * cosh; |
| 3638 |
const b = r * sinh; |
| 3639 |
|
| 3640 |
// Calculate back from cone response to XYZ |
| 3641 |
const rgb_c = unadapt( |
| 3642 |
/** @type {Vector3} */ |
| 3643 |
( |
| 3644 |
multiply_v3_m3x3([p2, a, b], M$a.m1).map(c => { |
| 3645 |
return (c * 1) / 1403; |
| 3646 |
}) |
| 3647 |
), |
| 3648 |
env.fl, |
| 3649 |
); |
| 3650 |
return /** @type {Vector3} */ ( |
| 3651 |
multiply_v3_m3x3( |
| 3652 |
/** @type {Vector3} */ ( |
| 3653 |
rgb_c.map((c, i) => { |
| 3654 |
return c * env.dRgbInv[i]; |
| 3655 |
}) |
| 3656 |
), |
| 3657 |
M$a.cat16Inv, |
| 3658 |
).map(c => { |
| 3659 |
return c / 100; |
| 3660 |
}) |
| 3661 |
); |
| 3662 |
} |
| 3663 |
|
| 3664 |
/** |
| 3665 |
* @param {[number, number, number]} xyzd65 |
| 3666 |
* @param {Cam16Environment} env |
| 3667 |
* @returns {Cam16Object} |
| 3668 |
*/ |
| 3669 |
function toCam16 (xyzd65, env) { |
| 3670 |
// Cone response |
| 3671 |
const xyz100 = /** @type {Vector3} */ ( |
| 3672 |
xyzd65.map(c => { |
| 3673 |
return c * 100; |
| 3674 |
}) |
| 3675 |
); |
| 3676 |
const rgbA = adapt$1( |
| 3677 |
/** @type {[number, number, number]} */ |
| 3678 |
( |
| 3679 |
multiply_v3_m3x3(xyz100, M$a.cat16).map((c, i) => { |
| 3680 |
return c * env.dRgb[i]; |
| 3681 |
}) |
| 3682 |
), |
| 3683 |
env.fl, |
| 3684 |
); |
| 3685 |
|
| 3686 |
// Calculate hue from red-green and yellow-blue components |
| 3687 |
const a = rgbA[0] + (-12 * rgbA[1] + rgbA[2]) / 11; |
| 3688 |
const b = (rgbA[0] + rgbA[1] - 2 * rgbA[2]) / 9; |
| 3689 |
const hRad = ((Math.atan2(b, a) % tau$1) + tau$1) % tau$1; |
| 3690 |
|
| 3691 |
// Eccentricity |
| 3692 |
const et = 0.25 * (Math.cos(hRad + 2) + 3.8); |
| 3693 |
|
| 3694 |
const t = |
| 3695 |
(5e4 / 13) * |
| 3696 |
env.nc * |
| 3697 |
env.ncb * |
| 3698 |
zdiv(et * Math.sqrt(a ** 2 + b ** 2), rgbA[0] + rgbA[1] + 1.05 * rgbA[2] + 0.305); |
| 3699 |
const alpha = spow(t, 0.9) * Math.pow(1.64 - Math.pow(0.29, env.n), 0.73); |
| 3700 |
|
| 3701 |
// Achromatic response |
| 3702 |
const A = env.nbb * (2 * rgbA[0] + rgbA[1] + 0.05 * rgbA[2]); |
| 3703 |
|
| 3704 |
const Jroot = spow(A / env.aW, 0.5 * env.c * env.z); |
| 3705 |
|
| 3706 |
// Lightness |
| 3707 |
const J = 100 * spow(Jroot, 2); |
| 3708 |
|
| 3709 |
// Brightness |
| 3710 |
const Q = (4 / env.c) * Jroot * (env.aW + 4) * env.flRoot; |
| 3711 |
|
| 3712 |
// Chroma |
| 3713 |
const C = alpha * Jroot; |
| 3714 |
|
| 3715 |
// Colorfulness |
| 3716 |
const colorfulness = C * env.flRoot; |
| 3717 |
|
| 3718 |
// Hue |
| 3719 |
const h = constrain(hRad * rad2deg); |
| 3720 |
|
| 3721 |
// Hue quadrature |
| 3722 |
const H = hueQuadrature(h); |
| 3723 |
|
| 3724 |
// Saturation |
| 3725 |
const s = 50 * spow((env.c * alpha) / (env.aW + 4), 1 / 2); |
| 3726 |
|
| 3727 |
// console.log({J: J, C: C, h: h, s: s, Q: Q, M: colorfulness, H: H}); |
| 3728 |
|
| 3729 |
return { J: J, C: C, h: h, s: s, Q: Q, M: colorfulness, H: H }; |
| 3730 |
} |
| 3731 |
|
| 3732 |
// Provided as a way to directly evaluate the CAM16 model |
| 3733 |
// https://observablehq.com/@jrus/cam16: reference implementation |
| 3734 |
// https://arxiv.org/pdf/1802.06067.pdf: Nico Schlömer |
| 3735 |
// https://onlinelibrary.wiley.com/doi/pdf/10.1002/col.22324: hue quadrature |
| 3736 |
// https://www.researchgate.net/publication/318152296_Comprehensive_color_solutions_CAM16_CAT16_and_CAM16-UCS |
| 3737 |
// Results compared against: https://github.com/colour-science/colour |
| 3738 |
var cam16 = new ColorSpace({ |
| 3739 |
id: "cam16-jmh", |
| 3740 |
cssId: "--cam16-jmh", |
| 3741 |
name: "CAM16-JMh", |
| 3742 |
coords: { |
| 3743 |
j: { |
| 3744 |
refRange: [0, 100], |
| 3745 |
name: "J", |
| 3746 |
}, |
| 3747 |
m: { |
| 3748 |
refRange: [0, 105.0], |
| 3749 |
name: "Colorfulness", |
| 3750 |
}, |
| 3751 |
h: { |
| 3752 |
refRange: [0, 360], |
| 3753 |
type: "angle", |
| 3754 |
name: "Hue", |
| 3755 |
}, |
| 3756 |
}, |
| 3757 |
|
| 3758 |
base: XYZ_D65, |
| 3759 |
|
| 3760 |
M: M$a, |
| 3761 |
|
| 3762 |
fromBase (xyz) { |
| 3763 |
// If another derivation is created, ε could vary, so we can't hardcode |
| 3764 |
if (this.ε === undefined) { |
| 3765 |
this.ε = Object.values(this.coords)[1].refRange[1] / 100000; |
| 3766 |
} |
| 3767 |
const cam16 = toCam16(xyz, viewingConditions$1); |
| 3768 |
const isAchromatic = Math.abs(cam16.M) < this.ε; |
| 3769 |
return [cam16.J, isAchromatic ? 0 : cam16.M, isAchromatic ? null : cam16.h]; |
| 3770 |
}, |
| 3771 |
toBase (cam16) { |
| 3772 |
return fromCam16({ J: cam16[0], M: cam16[1], h: cam16[2] }, viewingConditions$1); |
| 3773 |
}, |
| 3774 |
}); |
| 3775 |
|
| 3776 |
const white$2 = WHITES.D65; |
| 3777 |
const ε$4 = 216 / 24389; // 6^3/29^3 == (24/116)^3 |
| 3778 |
const κ$3 = 24389 / 27; // 29^3/3^3 |
| 3779 |
|
| 3780 |
function toLstar (y) { |
| 3781 |
// Convert XYZ Y to L* |
| 3782 |
|
| 3783 |
const fy = y > ε$4 ? Math.cbrt(y) : (κ$3 * y + 16) / 116; |
| 3784 |
return 116.0 * fy - 16.0; |
| 3785 |
} |
| 3786 |
|
| 3787 |
function fromLstar (lstar) { |
| 3788 |
// Convert L* back to XYZ Y |
| 3789 |
|
| 3790 |
return lstar > 8 ? Math.pow((lstar + 16) / 116, 3) : lstar / κ$3; |
| 3791 |
} |
| 3792 |
|
| 3793 |
function fromHct (coords, env) { |
| 3794 |
// Use Newton's method to try and converge as quick as possible or |
| 3795 |
// converge as close as we can. While the requested precision is achieved |
| 3796 |
// most of the time, it may not always be achievable. Especially past the |
| 3797 |
// visible spectrum, the algorithm will likely struggle to get the same |
| 3798 |
// precision. If, for whatever reason, we cannot achieve the accuracy we |
| 3799 |
// seek in the allotted iterations, just return the closest we were able to |
| 3800 |
// get. |
| 3801 |
|
| 3802 |
let [h, c, t] = coords; |
| 3803 |
let xyz = []; |
| 3804 |
let j = 0; |
| 3805 |
|
| 3806 |
// Shortcut out for black |
| 3807 |
if (t === 0) { |
| 3808 |
return [0.0, 0.0, 0.0]; |
| 3809 |
} |
| 3810 |
|
| 3811 |
// Calculate the Y we need to target |
| 3812 |
let y = fromLstar(t); |
| 3813 |
|
| 3814 |
// A better initial guess yields better results. Polynomials come from |
| 3815 |
// curve fitting the T vs J response. |
| 3816 |
if (t > 0) { |
| 3817 |
j = 0.00379058511492914 * t ** 2 + 0.608983189401032 * t + 0.9155088574762233; |
| 3818 |
} |
| 3819 |
else { |
| 3820 |
j = 9.514440756550361e-6 * t ** 2 + 0.08693057439788597 * t - 21.928975842194614; |
| 3821 |
} |
| 3822 |
|
| 3823 |
// Threshold of how close is close enough, and max number of attempts. |
| 3824 |
// More precision and more attempts means more time spent iterating. Higher |
| 3825 |
// required precision gives more accuracy but also increases the chance of |
| 3826 |
// not hitting the goal. 2e-12 allows us to convert round trip with |
| 3827 |
// reasonable accuracy of six decimal places or more. |
| 3828 |
const threshold = 2e-12; |
| 3829 |
const max_attempts = 15; |
| 3830 |
|
| 3831 |
let attempt = 0; |
| 3832 |
let last = Infinity; |
| 3833 |
let best = [0, 0, 0]; |
| 3834 |
|
| 3835 |
// Try to find a J such that the returned y matches the returned y of the L* |
| 3836 |
while (attempt <= max_attempts) { |
| 3837 |
xyz = fromCam16({ J: j, C: c, h: h }, env); |
| 3838 |
|
| 3839 |
// If we are within range, return XYZ |
| 3840 |
// If we are closer than last time, save the values |
| 3841 |
const delta = Math.abs(xyz[1] - y); |
| 3842 |
if (delta < last) { |
| 3843 |
if (delta <= threshold) { |
| 3844 |
return xyz; |
| 3845 |
} |
| 3846 |
best = xyz; |
| 3847 |
last = delta; |
| 3848 |
} |
| 3849 |
|
| 3850 |
// f(j_root) = (j ** (1 / 2)) * 0.1 |
| 3851 |
// f(j) = ((f(j_root) * 100) ** 2) / j - 1 = 0 |
| 3852 |
// f(j_root) = Y = y / 100 |
| 3853 |
// f(j) = (y ** 2) / j - 1 |
| 3854 |
// f'(j) = (2 * y) / j |
| 3855 |
j = j - ((xyz[1] - y) * j) / (2 * xyz[1]); |
| 3856 |
|
| 3857 |
attempt += 1; |
| 3858 |
} |
| 3859 |
|
| 3860 |
// We could not acquire the precision we desired, |
| 3861 |
// return our closest attempt. |
| 3862 |
return best; |
| 3863 |
} |
| 3864 |
|
| 3865 |
function toHct (xyz, env) { |
| 3866 |
// Calculate HCT by taking the L* of CIE LCh D65 and CAM16 chroma and hue. |
| 3867 |
|
| 3868 |
const t = toLstar(xyz[1]); |
| 3869 |
if (t === 0.0) { |
| 3870 |
return [0.0, 0.0, 0.0]; |
| 3871 |
} |
| 3872 |
const cam16 = toCam16(xyz, viewingConditions); |
| 3873 |
return [constrain(cam16.h), cam16.C, t]; |
| 3874 |
} |
| 3875 |
|
| 3876 |
// Pre-calculate everything we can with the viewing conditions |
| 3877 |
const viewingConditions = environment( |
| 3878 |
white$2, |
| 3879 |
(200 / Math.PI) * fromLstar(50.0), |
| 3880 |
fromLstar(50.0) * 100, |
| 3881 |
"average", |
| 3882 |
false, |
| 3883 |
); |
| 3884 |
|
| 3885 |
// https://material.io/blog/science-of-color-design |
| 3886 |
// This is not a port of the material-color-utilities, |
| 3887 |
// but instead implements the full color space as described, |
| 3888 |
// combining CAM16 JCh and Lab D65. This does not clamp conversion |
| 3889 |
// to HCT to specific chroma bands and provides support for wider |
| 3890 |
// gamuts than Google currently supports and does so at a greater |
| 3891 |
// precision (> 8 bits back to sRGB). |
| 3892 |
// This implementation comes from https://github.com/facelessuser/coloraide |
| 3893 |
// which is licensed under MIT. |
| 3894 |
var hct = new ColorSpace({ |
| 3895 |
id: "hct", |
| 3896 |
name: "HCT", |
| 3897 |
coords: { |
| 3898 |
h: { |
| 3899 |
refRange: [0, 360], |
| 3900 |
type: "angle", |
| 3901 |
name: "Hue", |
| 3902 |
}, |
| 3903 |
c: { |
| 3904 |
refRange: [0, 145], |
| 3905 |
name: "Colorfulness", |
| 3906 |
}, |
| 3907 |
t: { |
| 3908 |
refRange: [0, 100], |
| 3909 |
name: "Tone", |
| 3910 |
}, |
| 3911 |
}, |
| 3912 |
|
| 3913 |
base: XYZ_D65, |
| 3914 |
|
| 3915 |
fromBase (xyz) { |
| 3916 |
if (this.ε === undefined) { |
| 3917 |
this.ε = Object.values(this.coords)[1].refRange[1] / 100000; |
| 3918 |
} |
| 3919 |
let hct = toHct(xyz); |
| 3920 |
if (hct[1] < this.ε) { |
| 3921 |
hct[1] = 0.0; |
| 3922 |
hct[0] = null; |
| 3923 |
} |
| 3924 |
return hct; |
| 3925 |
}, |
| 3926 |
toBase (hct) { |
| 3927 |
return fromHct(hct, viewingConditions); |
| 3928 |
}, |
| 3929 |
formats: { |
| 3930 |
color: { |
| 3931 |
id: "--hct", |
| 3932 |
coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"], |
| 3933 |
}, |
| 3934 |
}, |
| 3935 |
}); |
| 3936 |
|
| 3937 |
const deg2rad = Math.PI / 180; |
| 3938 |
const ucsCoeff = [1.0, 0.007, 0.0228]; |
| 3939 |
|
| 3940 |
/** |
| 3941 |
* Convert HCT chroma and hue (CAM16 JMh colorfulness and hue) using UCS logic for a and b. |
| 3942 |
* @param {Coords} coords - HCT coordinates. |
| 3943 |
* @return {number[]} |
| 3944 |
*/ |
| 3945 |
function convertUcsAb (coords) { |
| 3946 |
// We want the distance between the actual color. |
| 3947 |
// If chroma is negative, it will throw off our calculations. |
| 3948 |
// Normally, converting back to the base and forward will correct it. |
| 3949 |
// If we have a negative chroma after this, then we have a color that |
| 3950 |
// cannot resolve to positive chroma. |
| 3951 |
if (coords[1] < 0) { |
| 3952 |
coords = hct.fromBase(hct.toBase(coords)); |
| 3953 |
} |
| 3954 |
|
| 3955 |
// Only in extreme cases (usually outside the visible spectrum) |
| 3956 |
// can the input value for log become negative. |
| 3957 |
// Avoid domain error by forcing a zero result via "max" if necessary. |
| 3958 |
const M = |
| 3959 |
Math.log(Math.max(1 + ucsCoeff[2] * coords[1] * viewingConditions.flRoot, 1.0)) / |
| 3960 |
ucsCoeff[2]; |
| 3961 |
const hrad = coords[0] * deg2rad; |
| 3962 |
const a = M * Math.cos(hrad); |
| 3963 |
const b = M * Math.sin(hrad); |
| 3964 |
|
| 3965 |
return [coords[2], a, b]; |
| 3966 |
} |
| 3967 |
|
| 3968 |
/** |
| 3969 |
* Color distance using HCT. |
| 3970 |
* @param {import("../types.js").ColorTypes} color |
| 3971 |
* @param {import("../types.js").ColorTypes} sample |
| 3972 |
* @returns {number} |
| 3973 |
*/ |
| 3974 |
function deltaEHCT (color, sample) { |
| 3975 |
[color, sample] = getColor([color, sample]); |
| 3976 |
|
| 3977 |
let [t1, a1, b1] = convertUcsAb(hct.from(color)); |
| 3978 |
let [t2, a2, b2] = convertUcsAb(hct.from(sample)); |
| 3979 |
|
| 3980 |
// Use simple euclidean distance with a and b using UCS conversion |
| 3981 |
// and LCh lightness (HCT tone). |
| 3982 |
return Math.sqrt((t1 - t2) ** 2 + (a1 - a2) ** 2 + (b1 - b2) ** 2); |
| 3983 |
} |
| 3984 |
|
| 3985 |
/** |
| 3986 |
* Helmlab MetricSpace — 13-stage perceptual color space. |
| 3987 |
* |
| 3988 |
* A data-driven analytical color space fit on COMBVD (3,813 paired human |
| 3989 |
* color-difference judgments aggregating BFD-P, Witt 1999, RIT-DuPont, and |
| 3990 |
* Leeds). Used internally by `deltaEHelmlab` and exposed as the CSS |
| 3991 |
* color space `helmlab-metric` for inspectability. Its coordinate system |
| 3992 |
* (asymmetric ab plane, L > 1 from H-K modeling, achromatic axis offset |
| 3993 |
* from origin) is shaped for ΔE accuracy rather than author-facing |
| 3994 |
* coordinates — for general CSS authoring use HelmGen (`helmgen`). |
| 3995 |
* |
| 3996 |
* Measured in this branch: ~24% lower STRESS than CIEDE2000 on COMBVD. |
| 3997 |
* |
| 3998 |
* Pipeline: XYZ → M1 → γ → M2 → hue correction → H-K → cubic L → dark L |
| 3999 |
* → hue-dep chroma scale → chroma power → L-dep chroma scale |
| 4000 |
* → HLC interaction → hue-dep lightness → rotation |
| 4001 |
* |
| 4002 |
* Reference: arXiv:2602.23010 |
| 4003 |
* @see https://github.com/Grkmyldz148/helmlab |
| 4004 |
*/ |
| 4005 |
|
| 4006 |
/** @import { Matrix3x3 } from "../types.js" */ |
| 4007 |
|
| 4008 |
const {cos, sin, sqrt, atan2, exp, abs, pow, PI} = Math; |
| 4009 |
|
| 4010 |
/** Bradford CAT: Color.js D65 → Helmlab D65 (apply in fromBase before M1) */ |
| 4011 |
/** @type {Matrix3x3} */ |
| 4012 |
// prettier-ignore |
| 4013 |
const CAT_TO_HELM = [ |
| 4014 |
[1.000042977349746, 2.0718877053183e-05, -4.361018085669474e-05], |
| 4015 |
[2.6946201090235744e-05, 0.9999906145080147, -1.4898828405401079e-05], |
| 4016 |
[-7.941753620756204e-06, 1.2875204405137254e-05, 0.9997859822609763], |
| 4017 |
]; |
| 4018 |
|
| 4019 |
/** Bradford CAT: Helmlab D65 → Color.js D65 (apply in toBase after M1_INV) */ |
| 4020 |
/** @type {Matrix3x3} */ |
| 4021 |
// prettier-ignore |
| 4022 |
const CAT_FROM_HELM = [ |
| 4023 |
[0.9999570254019492, -2.071874272730964e-05, 4.361733292468361e-05], |
| 4024 |
[-2.694517763358666e-05, 1.000009385946497, 1.490098223546482e-05], |
| 4025 |
[7.943459292954202e-06, -1.287824596735154e-05, 1.000214063706999], |
| 4026 |
]; |
| 4027 |
|
| 4028 |
// ── Utility functions ────────────────────────────────────────────── |
| 4029 |
|
| 4030 |
// ── Core parameters (v21, 72 params) ────────────────────────────── |
| 4031 |
|
| 4032 |
/** @type {Matrix3x3} */ |
| 4033 |
// prettier-ignore |
| 4034 |
const M1 = [ |
| 4035 |
[ 0.72129864331134985189, 0.45344826541531813024, -0.19288975751942616377], |
| 4036 |
[ -0.78821186949557897616, 1.79524137675723594043, 0.08761724511817850503], |
| 4037 |
[ -0.09177005999121559676, 0.45765588659459255361, 1.29220455139176770842], |
| 4038 |
]; |
| 4039 |
/** @type {Matrix3x3} */ |
| 4040 |
// prettier-ignore |
| 4041 |
const M1_INV = [ |
| 4042 |
[ 1.06510729580885898926, -0.31500440753011210715, 0.18034923817410389302], |
| 4043 |
[ 0.47211077138377960383, 0.42719957659624552271, 0.04150680489380984689], |
| 4044 |
[ -0.09156391926309541407, -0.17367093631949789834, 0.77197903825582936399], |
| 4045 |
]; |
| 4046 |
|
| 4047 |
const GAMMA = [0.47229813098762524, 0.5149184096354483, 0.5113233386366979]; |
| 4048 |
const INV_GAMMA = [2.1173067060606283, 1.9420552485353544, 1.9557096741686448]; |
| 4049 |
|
| 4050 |
/** @type {Matrix3x3} */ |
| 4051 |
// prettier-ignore |
| 4052 |
const M2 = [ |
| 4053 |
[ -0.26355622180094095963, 0.41683228837031738312, 0.49267631416564028335], |
| 4054 |
[ 1.88975705087773215851, -3.12122320342057735232, 1.04216669210603840590], |
| 4055 |
[ 0.35851086179620561545, 1.76940281937903676202, -1.41206260676953720967], |
| 4056 |
]; |
| 4057 |
/** @type {Matrix3x3} */ |
| 4058 |
// prettier-ignore |
| 4059 |
const M2_INV = [ |
| 4060 |
[ 0.91838978228150214278, 0.52320512370886662623, 0.70658045980908557038], |
| 4061 |
[ 1.08990905744330257576, 0.07005324849041903723, 0.43197768747870440853], |
| 4062 |
[ 1.59889572926420897581, 0.22061850068770233468, 0.01250603735522095097], |
| 4063 |
]; |
| 4064 |
|
| 4065 |
/** Matrices used by this color space, also available as `Helmlab.M` */ |
| 4066 |
const M$9 = { CAT_TO_HELM, CAT_FROM_HELM, M1, M1_INV, M2, M2_INV }; |
| 4067 |
|
| 4068 |
// Enrichment parameters |
| 4069 |
const hue_cos1 = -0.02833024015436984, hue_sin1 = -0.21131429516166544; |
| 4070 |
const hue_cos2 = 0.2189784817615645, hue_sin2 = -0.06871898981942523; |
| 4071 |
const hue_cos3 = 0.005506053349515315, hue_sin3 = -0.0641329861299175; |
| 4072 |
const hue_cos4 = -0.053592461436994296, hue_sin4 = -0.00954137464208059; |
| 4073 |
|
| 4074 |
const hk_weight = 0.2676231133101982, hk_power = 0.8934892185255707; |
| 4075 |
const hk_hue_mod = 0.7173169828841472; |
| 4076 |
const hk_sin1 = 0.6915224124600773, hk_cos2 = 0.48647127559605596, hk_sin2 = 0.9853124591201782; |
| 4077 |
|
| 4078 |
const L_corr_p1 = 0.5385456675962418, L_corr_p2 = 0.12508858146241716, L_corr_p3 = 0.6768950256217603; |
| 4079 |
const Lh_cos1 = -0.4963251525324449, Lh_sin1 = -0.09564696283240552; |
| 4080 |
|
| 4081 |
const lp_dark = -0.029053748937210654, lp_dark_hcos = 1.3346761652952872, lp_dark_hsin = -0.1698908144723919; |
| 4082 |
|
| 4083 |
const cs_cos1 = -0.195370576218515, cs_sin1 = 0.5330819227283227; |
| 4084 |
const cs_cos2 = 0.08863325582067766, cs_sin2 = 0.9365540137751136; |
| 4085 |
const cs_cos3 = 0.13789738139719568, cs_sin3 = 0.061650260197979936; |
| 4086 |
const cs_cos4 = 0.0641970862504494, cs_sin4 = -0.027401052793571013; |
| 4087 |
|
| 4088 |
const cp_cos1 = -0.09900209889026965, cp_sin1 = 0.059635520647228726; |
| 4089 |
const cp_cos2 = -0.013586499967803128, cp_sin2 = 0.2253393118474472; |
| 4090 |
|
| 4091 |
const lc1 = -1.5239477450767043, lc2 = -1.751157310240011; |
| 4092 |
|
| 4093 |
const hlc_cos1 = -0.43576378069144767, hlc_sin1 = 1.060094063845983; |
| 4094 |
const hlc_cos2 = 0.47931193034584496, hlc_sin2 = -0.2622579649434462; |
| 4095 |
|
| 4096 |
const hl_cos1 = 0.13610794232685908, hl_sin1 = 0.1168702235362288; |
| 4097 |
const hl_cos2 = -0.01617739641422492, hl_sin2 = 0.038145638815030566; |
| 4098 |
|
| 4099 |
// Rigid rotation φ = −28.2° |
| 4100 |
const PHI = -28.2 * PI / 180; |
| 4101 |
const ROT_COS = cos(PHI); |
| 4102 |
const ROT_SIN = sin(PHI); |
| 4103 |
|
| 4104 |
// ── Pipeline helper functions ────────────────────────────────────── |
| 4105 |
|
| 4106 |
function hueDelta (h) { |
| 4107 |
return hue_cos1 * cos(h) + hue_sin1 * sin(h) + |
| 4108 |
hue_cos2 * cos(2 * h) + hue_sin2 * sin(2 * h) + |
| 4109 |
hue_cos3 * cos(3 * h) + hue_sin3 * sin(3 * h) + |
| 4110 |
hue_cos4 * cos(4 * h) + hue_sin4 * sin(4 * h); |
| 4111 |
} |
| 4112 |
|
| 4113 |
function hueDeltaDeriv (h) { |
| 4114 |
return -hue_cos1 * sin(h) + hue_sin1 * cos(h) + |
| 4115 |
-2 * hue_cos2 * sin(2 * h) + 2 * hue_sin2 * cos(2 * h) + |
| 4116 |
-3 * hue_cos3 * sin(3 * h) + 3 * hue_sin3 * cos(3 * h) + |
| 4117 |
-4 * hue_cos4 * sin(4 * h) + 4 * hue_sin4 * cos(4 * h); |
| 4118 |
} |
| 4119 |
|
| 4120 |
function chromaScaleH (h) { |
| 4121 |
let logS = cs_cos1 * cos(h) + cs_sin1 * sin(h) + |
| 4122 |
cs_cos2 * cos(2 * h) + cs_sin2 * sin(2 * h) + |
| 4123 |
cs_cos3 * cos(3 * h) + cs_sin3 * sin(3 * h) + |
| 4124 |
cs_cos4 * cos(4 * h) + cs_sin4 * sin(4 * h); |
| 4125 |
return exp(logS); |
| 4126 |
} |
| 4127 |
|
| 4128 |
function lChromaScale (L) { |
| 4129 |
let dL = L - 0.5; |
| 4130 |
return exp(clamp(-30, lc1 * dL + lc2 * dL * dL, 30)); |
| 4131 |
} |
| 4132 |
|
| 4133 |
function hlcScale (h, L) { |
| 4134 |
let hueFactor = hlc_cos1 * cos(h) + hlc_sin1 * sin(h) + |
| 4135 |
hlc_cos2 * cos(2 * h) + hlc_sin2 * sin(2 * h); |
| 4136 |
return exp(clamp(-30, (L - 0.5) * hueFactor, 30)); |
| 4137 |
} |
| 4138 |
|
| 4139 |
function hueLightnessScale (h) { |
| 4140 |
let logS = hl_cos1 * cos(h) + hl_sin1 * sin(h) + |
| 4141 |
hl_cos2 * cos(2 * h) + hl_sin2 * sin(2 * h); |
| 4142 |
return exp(logS); |
| 4143 |
} |
| 4144 |
|
| 4145 |
function chromaPowerH (h) { |
| 4146 |
return 1 + cp_cos1 * cos(h) + cp_sin1 * sin(h) + |
| 4147 |
cp_cos2 * cos(2 * h) + cp_sin2 * sin(2 * h); |
| 4148 |
} |
| 4149 |
|
| 4150 |
function lCorrectFwd (L, h) { |
| 4151 |
let t = L * (1 - L); |
| 4152 |
let result = L + L_corr_p1 * t + L_corr_p2 * t * (0.5 - L) + L_corr_p3 * t * t; |
| 4153 |
result += t * (Lh_cos1 * cos(h) + Lh_sin1 * sin(h)); |
| 4154 |
return result; |
| 4155 |
} |
| 4156 |
|
| 4157 |
function lCorrectInv (L1, h) { |
| 4158 |
let Lh = Lh_cos1 * cos(h) + Lh_sin1 * sin(h); |
| 4159 |
let L = L1; |
| 4160 |
for (let i = 0; i < 15; i++) { |
| 4161 |
let t = L * (1 - L); |
| 4162 |
let dt = 1 - 2 * L; |
| 4163 |
let f = L + (L_corr_p1 + Lh) * t + L_corr_p2 * t * (0.5 - L) + |
| 4164 |
L_corr_p3 * t * t - L1; |
| 4165 |
let dfdL = 1 + (L_corr_p1 + Lh) * dt + |
| 4166 |
L_corr_p2 * (dt * (0.5 - L) - t) + |
| 4167 |
L_corr_p3 * 2 * t * dt; |
| 4168 |
if (abs(dfdL) < 1e-10) { |
| 4169 |
dfdL = 1; |
| 4170 |
} |
| 4171 |
L -= f / dfdL; |
| 4172 |
} |
| 4173 |
return L; |
| 4174 |
} |
| 4175 |
|
| 4176 |
function darkLFwd (L, h) { |
| 4177 |
let coeff = lp_dark + lp_dark_hcos * cos(h) + lp_dark_hsin * sin(h); |
| 4178 |
let oml = L < 1 ? 1 - L : 0; // clamp at L=1: identity for L≥1 |
| 4179 |
let g = coeff * L * oml * oml; |
| 4180 |
return L * exp(clamp(-30, g, 30)); |
| 4181 |
} |
| 4182 |
|
| 4183 |
function darkLInv (Ln, h) { |
| 4184 |
let coeff = lp_dark + lp_dark_hcos * cos(h) + lp_dark_hsin * sin(h); |
| 4185 |
let L = Ln; |
| 4186 |
for (let i = 0; i < 12; i++) { |
| 4187 |
let oml = L < 1 ? 1 - L : 0; |
| 4188 |
let g = coeff * L * oml * oml; |
| 4189 |
let eg = exp(clamp(-30, g, 30)); |
| 4190 |
let f = L * eg - Ln; |
| 4191 |
let gp = coeff * oml * (1 - 3 * L); |
| 4192 |
let fp = eg * (1 + L * gp); |
| 4193 |
if (abs(fp) < 1e-10) { |
| 4194 |
fp = 1; |
| 4195 |
} |
| 4196 |
L -= f / fp; |
| 4197 |
} |
| 4198 |
return L; |
| 4199 |
} |
| 4200 |
|
| 4201 |
// ── Color space definition ───────────────────────────────────────── |
| 4202 |
// Helmlab MetricSpace is the perceptual forward space behind `deltaEHelmlab`. |
| 4203 |
// Its coordinate system is shaped to maximize ΔE prediction accuracy on |
| 4204 |
// visual-difference datasets (COMBVD: BFD-P, Witt 1999, RIT-DuPont, Leeds), |
| 4205 |
// not author convenience. As a result: |
| 4206 |
// - the ab plane is asymmetric (the metric was fit to directionally |
| 4207 |
// asymmetric human discrimination thresholds); |
| 4208 |
// - the L axis exceeds 1 for highly chromatic colors because the |
| 4209 |
// Helmholtz–Kohlrausch boost is modeled explicitly (high-chroma colors |
| 4210 |
// appear brighter than equiluminant neutrals); |
| 4211 |
// - the achromatic axis is not pinned to (0, 0) — the gray axis sits |
| 4212 |
// slightly off-origin in this coordinate system. Distance is |
| 4213 |
// translation-invariant, so this does not affect ΔE quality. |
| 4214 |
// |
| 4215 |
// For CSS-author-facing color authoring (palettes, gradients, gamut |
| 4216 |
// mapping), use HelmGen (`helmgen`) instead. This space (`helmlab-metric`) |
| 4217 |
// is exposed primarily so the metric forward is inspectable for |
| 4218 |
// debugging, color-science exploration, and as the internal forward used |
| 4219 |
// by `deltaEHelmlab`. |
| 4220 |
|
| 4221 |
const fromXYZ = function (xyz) { |
| 4222 |
// Stage 0: Chromatic adaptation (Color.js D65 → Helmlab D65) |
| 4223 |
let adapted = multiply_v3_m3x3(xyz, M$9.CAT_TO_HELM); |
| 4224 |
|
| 4225 |
// Stage 1: XYZ → LMS (M1) |
| 4226 |
let [lms0, lms1, lms2] = multiply_v3_m3x3(adapted, M$9.M1); |
| 4227 |
|
| 4228 |
// Stage 2: Power compression (signed) |
| 4229 |
let c0 = spow(lms0, GAMMA[0]); |
| 4230 |
let c1 = spow(lms1, GAMMA[1]); |
| 4231 |
let c2 = spow(lms2, GAMMA[2]); |
| 4232 |
|
| 4233 |
// Stage 3: LMS_c → Lab_raw (M2) |
| 4234 |
let [L, a, b] = multiply_v3_m3x3([c0, c1, c2], M$9.M2); |
| 4235 |
|
| 4236 |
// Stage 3.5: Hue correction (4-harmonic Fourier) |
| 4237 |
let h = atan2(b, a); |
| 4238 |
let C = sqrt(a * a + b * b); |
| 4239 |
let delta = hueDelta(h); |
| 4240 |
let hNew = h + delta; |
| 4241 |
a = C * cos(hNew); |
| 4242 |
b = C * sin(hNew); |
| 4243 |
|
| 4244 |
// Stage 3.7: Helmholtz-Kohlrausch correction |
| 4245 |
let Cr = sqrt(a * a + b * b); |
| 4246 |
let hkBoost = hk_weight * pow(Cr, clamp(0.01, hk_power, 10)); |
| 4247 |
let hr = atan2(b, a); |
| 4248 |
let factor = 1 + hk_hue_mod * cos(hr) + hk_sin1 * sin(hr) + |
| 4249 |
hk_cos2 * cos(2 * hr) + hk_sin2 * sin(2 * hr); |
| 4250 |
L += hkBoost * factor; |
| 4251 |
|
| 4252 |
// Stage 4: Cubic L correction (with hue modulation) |
| 4253 |
h = atan2(b, a); |
| 4254 |
L = lCorrectFwd(L, h); |
| 4255 |
|
| 4256 |
// Stage 4.5: Dark L compression |
| 4257 |
h = atan2(b, a); |
| 4258 |
L = darkLFwd(L, h); |
| 4259 |
|
| 4260 |
// Stage 5: Hue-dependent chroma scaling |
| 4261 |
h = atan2(b, a); |
| 4262 |
let cs = chromaScaleH(h); |
| 4263 |
a *= cs; |
| 4264 |
b *= cs; |
| 4265 |
|
| 4266 |
// Stage 5.5: Nonlinear chroma power |
| 4267 |
h = atan2(b, a); |
| 4268 |
C = sqrt(a * a + b * b); |
| 4269 |
let p = chromaPowerH(h); |
| 4270 |
let Cn = C > 0 ? pow(C, p) : 0; |
| 4271 |
a = Cn * cos(h); |
| 4272 |
b = Cn * sin(h); |
| 4273 |
|
| 4274 |
// Stage 6: L-dependent chroma scaling |
| 4275 |
let T = lChromaScale(L); |
| 4276 |
a *= T; |
| 4277 |
b *= T; |
| 4278 |
|
| 4279 |
// Stage 6.5: HLC interaction |
| 4280 |
h = atan2(b, a); |
| 4281 |
let hlcS = hlcScale(h, L); |
| 4282 |
a *= hlcS; |
| 4283 |
b *= hlcS; |
| 4284 |
|
| 4285 |
// Stage 8: Hue-dependent lightness scaling |
| 4286 |
h = atan2(b, a); |
| 4287 |
L *= hueLightnessScale(h); |
| 4288 |
|
| 4289 |
// Stage 11: Rigid rotation (φ = −28.2°) |
| 4290 |
let aRot = a * ROT_COS - b * ROT_SIN; |
| 4291 |
let bRot = a * ROT_SIN + b * ROT_COS; |
| 4292 |
|
| 4293 |
return [L, aRot, bRot]; |
| 4294 |
}; |
| 4295 |
|
| 4296 |
const toXYZ = function (lab) { |
| 4297 |
let [L, a, b] = lab; |
| 4298 |
|
| 4299 |
// Undo Stage 11: rotation |
| 4300 |
let aUn = a * ROT_COS + b * ROT_SIN; |
| 4301 |
let bUn = -a * ROT_SIN + b * ROT_COS; |
| 4302 |
a = aUn; |
| 4303 |
b = bUn; |
| 4304 |
|
| 4305 |
// Undo Stage 8: hue-dep lightness |
| 4306 |
let h = atan2(b, a); |
| 4307 |
L /= hueLightnessScale(h); |
| 4308 |
|
| 4309 |
// Undo Stage 6.5: HLC |
| 4310 |
h = atan2(b, a); |
| 4311 |
let hlcS = hlcScale(h, L); |
| 4312 |
a /= hlcS; |
| 4313 |
b /= hlcS; |
| 4314 |
|
| 4315 |
// Undo Stage 6: L-dep chroma |
| 4316 |
let T = lChromaScale(L); |
| 4317 |
a /= T; |
| 4318 |
b /= T; |
| 4319 |
|
| 4320 |
// Undo Stage 5.5: chroma power |
| 4321 |
h = atan2(b, a); |
| 4322 |
let C = sqrt(a * a + b * b); |
| 4323 |
let p = chromaPowerH(h); |
| 4324 |
let Co = C > 0 ? pow(C, 1 / p) : 0; |
| 4325 |
a = Co * cos(h); |
| 4326 |
b = Co * sin(h); |
| 4327 |
|
| 4328 |
// Undo Stage 5: chroma scaling |
| 4329 |
h = atan2(b, a); |
| 4330 |
let cs = chromaScaleH(h); |
| 4331 |
a /= cs; |
| 4332 |
b /= cs; |
| 4333 |
|
| 4334 |
// Undo Stage 4.5: dark L |
| 4335 |
h = atan2(b, a); |
| 4336 |
L = darkLInv(L, h); |
| 4337 |
|
| 4338 |
// Undo Stage 4: cubic L |
| 4339 |
h = atan2(b, a); |
| 4340 |
L = lCorrectInv(L, h); |
| 4341 |
|
| 4342 |
// Undo Stage 3.7: H-K |
| 4343 |
let Cr = sqrt(a * a + b * b); |
| 4344 |
let hkBoost = hk_weight * pow(Cr, clamp(0.01, hk_power, 10)); |
| 4345 |
let hr = atan2(b, a); |
| 4346 |
let factor = 1 + hk_hue_mod * cos(hr) + hk_sin1 * sin(hr) + |
| 4347 |
hk_cos2 * cos(2 * hr) + hk_sin2 * sin(2 * hr); |
| 4348 |
L -= hkBoost * factor; |
| 4349 |
|
| 4350 |
// Undo Stage 3.5: hue correction (Newton iteration) |
| 4351 |
let hOut = atan2(b, a); |
| 4352 |
C = sqrt(a * a + b * b); |
| 4353 |
let hRaw = hOut; |
| 4354 |
for (let i = 0; i < 8; i++) { |
| 4355 |
let f = hRaw + hueDelta(hRaw) - hOut; |
| 4356 |
let fp = 1 + hueDeltaDeriv(hRaw); |
| 4357 |
if (abs(fp) < 1e-10) { |
| 4358 |
fp = 1; |
| 4359 |
} |
| 4360 |
hRaw -= f / fp; |
| 4361 |
} |
| 4362 |
a = C * cos(hRaw); |
| 4363 |
b = C * sin(hRaw); |
| 4364 |
|
| 4365 |
// Undo Stage 3: Lab → LMS_c (M2_inv) |
| 4366 |
let [lc0, lc1, lc2] = multiply_v3_m3x3([L, a, b], M$9.M2_INV); |
| 4367 |
|
| 4368 |
// Undo Stage 2: power compression |
| 4369 |
let l0 = spow(lc0, INV_GAMMA[0]); |
| 4370 |
let l1 = spow(lc1, INV_GAMMA[1]); |
| 4371 |
let l2 = spow(lc2, INV_GAMMA[2]); |
| 4372 |
|
| 4373 |
// Undo Stage 1: LMS → XYZ (M1_inv) |
| 4374 |
let xyz = multiply_v3_m3x3([l0, l1, l2], M$9.M1_INV); |
| 4375 |
|
| 4376 |
// Undo Stage 0: Chromatic adaptation (Helmlab D65 → Color.js D65) |
| 4377 |
return multiply_v3_m3x3(xyz, M$9.CAT_FROM_HELM); |
| 4378 |
}; |
| 4379 |
|
| 4380 |
var helmlab = new ColorSpace({ |
| 4381 |
id: "helmlab-metric", |
| 4382 |
name: "Helmlab MetricSpace", |
| 4383 |
cssId: "--helmlab-metric", |
| 4384 |
coords: { |
| 4385 |
l: { |
| 4386 |
refRange: [0, 1.6], |
| 4387 |
name: "Lightness", |
| 4388 |
}, |
| 4389 |
a: { |
| 4390 |
refRange: [-1.5, 1.5], |
| 4391 |
}, |
| 4392 |
b: { |
| 4393 |
refRange: [-1.5, 1.5], |
| 4394 |
}, |
| 4395 |
}, |
| 4396 |
white: "D65", |
| 4397 |
base: XYZ_D65, |
| 4398 |
M: M$9, |
| 4399 |
fromBase (xyz) { |
| 4400 |
return fromXYZ(xyz); |
| 4401 |
}, |
| 4402 |
toBase (lab) { |
| 4403 |
return toXYZ(lab); |
| 4404 |
}, |
| 4405 |
}); |
| 4406 |
|
| 4407 |
// Helmlab MetricSpace weighted distance (v21, 72 params). |
| 4408 |
// Optimized on COMBVD human color-difference judgments. |
| 4409 |
// |
| 4410 |
// Formula: |
| 4411 |
// SL = 1 + sl * (L_avg - 0.5)² |
| 4412 |
// SC = 1 + sc * C_avg |
| 4413 |
// raw = (ΔL²/SL² + wC * Δab²/SC²) ^ (p/2) |
| 4414 |
// compressed = raw / (1 + c * raw) |
| 4415 |
// ΔE = compressed ^ q |
| 4416 |
|
| 4417 |
const sl = -0.9155125151657894; |
| 4418 |
const sc = 2.9268353744941558; |
| 4419 |
const wC = 3.966003089807536; |
| 4420 |
const p = 1.9737081170404969; |
| 4421 |
const compress = 52.473130649294724; |
| 4422 |
const q = 0.47897301074925214; |
| 4423 |
|
| 4424 |
/** |
| 4425 |
* @param {import("../types.js").ColorTypes} color |
| 4426 |
* @param {import("../types.js").ColorTypes} sample |
| 4427 |
* @returns {number} |
| 4428 |
*/ |
| 4429 |
function deltaEHelmlab (color, sample) { |
| 4430 |
[color, sample] = getColor([color, sample]); |
| 4431 |
|
| 4432 |
let [L1, a1, b1] = helmlab.from(color); |
| 4433 |
let [L2, a2, b2] = helmlab.from(sample); |
| 4434 |
|
| 4435 |
let ΔL = L1 - L2; |
| 4436 |
let Δa = a1 - a2; |
| 4437 |
let Δb = b1 - b2; |
| 4438 |
|
| 4439 |
// Pair-dependent weighting |
| 4440 |
let Lavg = (L1 + L2) * 0.5; |
| 4441 |
let SL = 1 + sl * (Lavg - 0.5) ** 2; |
| 4442 |
|
| 4443 |
let C1 = Math.sqrt(a1 ** 2 + b1 ** 2); |
| 4444 |
let C2 = Math.sqrt(a2 ** 2 + b2 ** 2); |
| 4445 |
let Cavg = (C1 + C2) * 0.5; |
| 4446 |
let SC = 1 + sc * Cavg; |
| 4447 |
|
| 4448 |
// Weighted Minkowski distance |
| 4449 |
let raw = (ΔL ** 2 / SL ** 2 + wC * (Δa ** 2 + Δb ** 2) / SC ** 2) ** (p / 2); |
| 4450 |
|
| 4451 |
// Monotonic compression |
| 4452 |
let compressed = raw / (1 + compress * raw); |
| 4453 |
|
| 4454 |
return compressed ** q; |
| 4455 |
} |
| 4456 |
|
| 4457 |
/** |
| 4458 |
* @packageDocumentation |
| 4459 |
* This module defines all the builtin deltaE methods. |
| 4460 |
*/ |
| 4461 |
|
| 4462 |
var deltaEMethods = { |
| 4463 |
deltaE76, |
| 4464 |
deltaECMC, |
| 4465 |
deltaE2000, |
| 4466 |
deltaEJz, |
| 4467 |
deltaEITP, |
| 4468 |
deltaEOK, |
| 4469 |
deltaEOK2, |
| 4470 |
deltaEHCT, |
| 4471 |
deltaEHelmlab, |
| 4472 |
}; |
| 4473 |
|
| 4474 |
/** @typedef {keyof typeof import("./index.js").default extends `deltaE${infer Method}` ? Method : string} Methods */ |
| 4475 |
|
| 4476 |
/** @import { ColorTypes, PlainColorObject } from "./types.js" */ |
| 4477 |
|
| 4478 |
// Type re-exports |
| 4479 |
/** @typedef {import("./types.js").ToGamutOptions} ToGamutOptions */ |
| 4480 |
|
| 4481 |
/** |
| 4482 |
* Calculate the epsilon to 2 degrees smaller than the specified JND. |
| 4483 |
* @param {number} jnd The target "just noticeable difference". |
| 4484 |
* @returns {number} |
| 4485 |
*/ |
| 4486 |
function calcEpsilon (jnd) { |
| 4487 |
// Calculate the epsilon to 2 degrees smaller than the specified JND. |
| 4488 |
|
| 4489 |
const order = !jnd ? 0 : Math.floor(Math.log10(Math.abs(jnd))); |
| 4490 |
// Limit to an arbitrary value to ensure value is never too small and causes infinite loops. |
| 4491 |
return Math.max(parseFloat(`1e${order - 2}`), 1e-6); |
| 4492 |
} |
| 4493 |
|
| 4494 |
const GMAPPRESET = { |
| 4495 |
hct: { |
| 4496 |
method: "hct.c", |
| 4497 |
jnd: 2, |
| 4498 |
deltaEMethod: "hct", |
| 4499 |
blackWhiteClamp: {}, |
| 4500 |
}, |
| 4501 |
"hct-tonal": { |
| 4502 |
method: "hct.c", |
| 4503 |
jnd: 0, |
| 4504 |
deltaEMethod: "hct", |
| 4505 |
blackWhiteClamp: { channel: "hct.t", min: 0, max: 100 }, |
| 4506 |
}, |
| 4507 |
}; |
| 4508 |
|
| 4509 |
/** |
| 4510 |
* Force coordinates to be in gamut of a certain color space. |
| 4511 |
* Mutates the color it is passed. |
| 4512 |
* @overload |
| 4513 |
* @param {ColorTypes} color |
| 4514 |
* @param {ToGamutOptions} [options] |
| 4515 |
* @returns {PlainColorObject} |
| 4516 |
*/ |
| 4517 |
/** |
| 4518 |
* @overload |
| 4519 |
* @param {ColorTypes} color |
| 4520 |
* @param {string} [space] |
| 4521 |
* @returns {PlainColorObject} |
| 4522 |
*/ |
| 4523 |
/** |
| 4524 |
* @param {ColorTypes} color |
| 4525 |
* @param {string & Partial<ToGamutOptions> | ToGamutOptions} [space] |
| 4526 |
* @returns {PlainColorObject} |
| 4527 |
*/ |
| 4528 |
function toGamut ( |
| 4529 |
color, |
| 4530 |
{ |
| 4531 |
method = defaults.gamut_mapping, |
| 4532 |
space = undefined, |
| 4533 |
deltaEMethod = "", |
| 4534 |
jnd = 2, |
| 4535 |
blackWhiteClamp = undefined, |
| 4536 |
} = {}, |
| 4537 |
) { |
| 4538 |
color = getColor(color); |
| 4539 |
|
| 4540 |
if (isString(arguments[1])) { |
| 4541 |
space = arguments[1]; |
| 4542 |
} |
| 4543 |
else if (!space) { |
| 4544 |
space = color.space; |
| 4545 |
} |
| 4546 |
|
| 4547 |
space = ColorSpace.get(space); |
| 4548 |
|
| 4549 |
// 3 spaces: |
| 4550 |
// color.space: current color space |
| 4551 |
// space: space whose gamut we are mapping to |
| 4552 |
// mapSpace: space with the coord we're reducing |
| 4553 |
|
| 4554 |
if (inGamut(color, space, { epsilon: 0 })) { |
| 4555 |
return /** @type {PlainColorObject} */ (color); |
| 4556 |
} |
| 4557 |
|
| 4558 |
let spaceColor; |
| 4559 |
if (method === "css") { |
| 4560 |
spaceColor = toGamutCSS(color, { space }); |
| 4561 |
} |
| 4562 |
else if (method === "raytrace") { |
| 4563 |
spaceColor = toGamutRayTrace(color, { space }); |
| 4564 |
} |
| 4565 |
else { |
| 4566 |
if (method !== "clip") { |
| 4567 |
if (Object.prototype.hasOwnProperty.call(GMAPPRESET, method)) { |
| 4568 |
({ method, jnd, deltaEMethod, blackWhiteClamp } = GMAPPRESET[method]); |
| 4569 |
} |
| 4570 |
|
| 4571 |
// Get the correct delta E method |
| 4572 |
let de = deltaE2000; |
| 4573 |
if (deltaEMethod !== "") { |
| 4574 |
for (let m in deltaEMethods) { |
| 4575 |
if ("deltae" + deltaEMethod.toLowerCase() === m.toLowerCase()) { |
| 4576 |
de = deltaEMethods[m]; |
| 4577 |
break; |
| 4578 |
} |
| 4579 |
} |
| 4580 |
} |
| 4581 |
|
| 4582 |
if (jnd === 0) { |
| 4583 |
jnd = 1e-16; |
| 4584 |
} |
| 4585 |
|
| 4586 |
let clipped = toGamut(to(color, space), { method: "clip", space }); |
| 4587 |
if (de(color, clipped) > jnd) { |
| 4588 |
// Clamp to SDR white and black if required |
| 4589 |
if (blackWhiteClamp && Object.keys(blackWhiteClamp).length === 3) { |
| 4590 |
let channelMeta = ColorSpace.resolveCoord(blackWhiteClamp.channel); |
| 4591 |
let channel = get(to(color, channelMeta.space), channelMeta.id); |
| 4592 |
if (isNone(channel)) { |
| 4593 |
channel = 0; |
| 4594 |
} |
| 4595 |
if (channel >= blackWhiteClamp.max) { |
| 4596 |
return to({ space: "xyz-d65", coords: WHITES["D65"] }, color.space); |
| 4597 |
} |
| 4598 |
else if (channel <= blackWhiteClamp.min) { |
| 4599 |
return to({ space: "xyz-d65", coords: [0, 0, 0] }, color.space); |
| 4600 |
} |
| 4601 |
} |
| 4602 |
|
| 4603 |
// Reduce a coordinate of a certain color space until the color is in gamut |
| 4604 |
let coordMeta = ColorSpace.resolveCoord(method); |
| 4605 |
let mapSpace = coordMeta.space; |
| 4606 |
let coordId = coordMeta.id; |
| 4607 |
|
| 4608 |
let mappedColor = to(color, mapSpace); |
| 4609 |
// If we were already in the mapped color space, we need to resolve undefined channels |
| 4610 |
mappedColor.coords.forEach((c, i) => { |
| 4611 |
if (isNone(c)) { |
| 4612 |
mappedColor.coords[i] = 0; |
| 4613 |
} |
| 4614 |
}); |
| 4615 |
let bounds = coordMeta.range || coordMeta.refRange; |
| 4616 |
let min = bounds[0]; |
| 4617 |
let ε = calcEpsilon(jnd); |
| 4618 |
let low = min; |
| 4619 |
let high = get(mappedColor, coordId); |
| 4620 |
|
| 4621 |
while (high - low > ε) { |
| 4622 |
let clipped = clone(mappedColor); |
| 4623 |
clipped = toGamut(clipped, { space, method: "clip" }); |
| 4624 |
let deltaE = de(mappedColor, clipped); |
| 4625 |
|
| 4626 |
if (deltaE - jnd < ε) { |
| 4627 |
low = get(mappedColor, coordId); |
| 4628 |
} |
| 4629 |
else { |
| 4630 |
high = get(mappedColor, coordId); |
| 4631 |
} |
| 4632 |
|
| 4633 |
set(mappedColor, coordId, (low + high) / 2); |
| 4634 |
} |
| 4635 |
|
| 4636 |
spaceColor = to(mappedColor, space); |
| 4637 |
} |
| 4638 |
else { |
| 4639 |
spaceColor = clipped; |
| 4640 |
} |
| 4641 |
} |
| 4642 |
else { |
| 4643 |
spaceColor = to(color, space); |
| 4644 |
} |
| 4645 |
|
| 4646 |
if ( |
| 4647 |
method === "clip" || // Dumb coord clipping |
| 4648 |
// finish off smarter gamut mapping with clip to get rid of ε, see #17 |
| 4649 |
!inGamut(spaceColor, space, { epsilon: 0 }) |
| 4650 |
) { |
| 4651 |
let bounds = Object.values(space.coords).map(c => c.range || []); |
| 4652 |
|
| 4653 |
spaceColor.coords = /** @type {[number, number, number]} */ ( |
| 4654 |
spaceColor.coords.map((c, i) => { |
| 4655 |
let [min, max] = bounds[i]; |
| 4656 |
|
| 4657 |
if (min !== undefined) { |
| 4658 |
c = Math.max(min, c); |
| 4659 |
} |
| 4660 |
|
| 4661 |
if (max !== undefined) { |
| 4662 |
c = Math.min(c, max); |
| 4663 |
} |
| 4664 |
|
| 4665 |
return c; |
| 4666 |
}) |
| 4667 |
); |
| 4668 |
} |
| 4669 |
} |
| 4670 |
|
| 4671 |
if (space !== color.space) { |
| 4672 |
spaceColor = to(spaceColor, color.space); |
| 4673 |
} |
| 4674 |
|
| 4675 |
color.coords = spaceColor.coords; |
| 4676 |
return /** @type {PlainColorObject} */ (color); |
| 4677 |
} |
| 4678 |
|
| 4679 |
/** @type {"color"} */ |
| 4680 |
toGamut.returns = "color"; |
| 4681 |
|
| 4682 |
/** |
| 4683 |
* The reference colors to be used if lightness is out of the range 0-1 in the |
| 4684 |
* `Oklch` space. These are created in the `Oklab` space, as it is used by the |
| 4685 |
* DeltaEOK calculation, so it is guaranteed to be imported. |
| 4686 |
* @satisfies {Record<string, ColorTypes>} |
| 4687 |
*/ |
| 4688 |
const COLORS = { |
| 4689 |
WHITE: { space: Oklab, coords: [1, 0, 0], alpha: 1 }, |
| 4690 |
BLACK: { space: Oklab, coords: [0, 0, 0], alpha: 1 }, |
| 4691 |
}; |
| 4692 |
|
| 4693 |
/** |
| 4694 |
* Given a color `origin`, returns a new color that is in gamut using |
| 4695 |
* the CSS Gamut Mapping Algorithm. If `space` is specified, it will be in gamut |
| 4696 |
* in `space`, and returned in `space`. Otherwise, it will be in gamut and |
| 4697 |
* returned in the color space of `origin`. |
| 4698 |
* @param {ColorTypes} origin |
| 4699 |
* @param {{ space?: string | ColorSpace | undefined }} options |
| 4700 |
* @returns {PlainColorObject} |
| 4701 |
*/ |
| 4702 |
function toGamutCSS (origin, { space } = {}) { |
| 4703 |
const JND = 0.02; |
| 4704 |
const ε = 0.0001; |
| 4705 |
|
| 4706 |
origin = getColor(origin); |
| 4707 |
|
| 4708 |
if (!space) { |
| 4709 |
space = origin.space; |
| 4710 |
} |
| 4711 |
|
| 4712 |
space = ColorSpace.get(space); |
| 4713 |
|
| 4714 |
if (space.isUnbounded) { |
| 4715 |
return to(origin, space); |
| 4716 |
} |
| 4717 |
|
| 4718 |
const origin_OKLCH = to(origin, OKLCH); |
| 4719 |
let L = origin_OKLCH.coords[0]; |
| 4720 |
|
| 4721 |
// return media white or black, if lightness is out of range |
| 4722 |
if (L >= 1) { |
| 4723 |
const white = to(COLORS.WHITE, space); |
| 4724 |
white.alpha = origin.alpha; |
| 4725 |
return to(white, space); |
| 4726 |
} |
| 4727 |
if (L <= 0) { |
| 4728 |
const black = to(COLORS.BLACK, space); |
| 4729 |
black.alpha = origin.alpha; |
| 4730 |
return to(black, space); |
| 4731 |
} |
| 4732 |
|
| 4733 |
if (inGamut(origin_OKLCH, space, { epsilon: 0 })) { |
| 4734 |
return to(origin_OKLCH, space); |
| 4735 |
} |
| 4736 |
|
| 4737 |
function clip (_color) { |
| 4738 |
const destColor = to(_color, space); |
| 4739 |
const spaceCoords = Object.values(/** @type {ColorSpace} */ (space).coords); |
| 4740 |
destColor.coords = /** @type {[number, number, number]} */ ( |
| 4741 |
destColor.coords.map((coord, index) => { |
| 4742 |
if ("range" in spaceCoords[index]) { |
| 4743 |
const [min, max] = spaceCoords[index].range; |
| 4744 |
return clamp(min, coord, max); |
| 4745 |
} |
| 4746 |
return coord; |
| 4747 |
}) |
| 4748 |
); |
| 4749 |
return destColor; |
| 4750 |
} |
| 4751 |
let min = 0; |
| 4752 |
let max = origin_OKLCH.coords[1]; |
| 4753 |
let min_inGamut = true; |
| 4754 |
let current = clone(origin_OKLCH); |
| 4755 |
let clipped = clip(current); |
| 4756 |
|
| 4757 |
let E = deltaEOK(clipped, current); |
| 4758 |
if (E < JND) { |
| 4759 |
return clipped; |
| 4760 |
} |
| 4761 |
|
| 4762 |
while (max - min > ε) { |
| 4763 |
const chroma = (min + max) / 2; |
| 4764 |
current.coords[1] = chroma; |
| 4765 |
if (min_inGamut && inGamut(current, space, { epsilon: 0 })) { |
| 4766 |
min = chroma; |
| 4767 |
} |
| 4768 |
else { |
| 4769 |
clipped = clip(current); |
| 4770 |
E = deltaEOK(clipped, current); |
| 4771 |
if (E < JND) { |
| 4772 |
if (JND - E < ε) { |
| 4773 |
break; |
| 4774 |
} |
| 4775 |
else { |
| 4776 |
min_inGamut = false; |
| 4777 |
min = chroma; |
| 4778 |
} |
| 4779 |
} |
| 4780 |
else { |
| 4781 |
max = chroma; |
| 4782 |
} |
| 4783 |
} |
| 4784 |
} |
| 4785 |
return clipped; |
| 4786 |
} |
| 4787 |
|
| 4788 |
/** |
| 4789 |
* Given `start` and `end` coordinates of a 3D ray and a `bmin` and `bmax` bounding box, |
| 4790 |
* find the intersection of the ray and box. Return an empty list if no intersect is found.` |
| 4791 |
* @param {[number, number, number]} start |
| 4792 |
* @param {[number, number, number]} end |
| 4793 |
* @param {[number, number, number]} bmin |
| 4794 |
* @param {[number, number, number]} bmax |
| 4795 |
* @returns {[number, number, number] | []} |
| 4796 |
*/ |
| 4797 |
function raytrace_box (start, end, bmin = [0, 0, 0], bmax = [1, 1, 1]) { |
| 4798 |
// Use slab method to detect intersection of ray and box and return intersect. |
| 4799 |
// https://en.wikipedia.org/wiki/Slab_method |
| 4800 |
|
| 4801 |
// Calculate whether there was a hit |
| 4802 |
let tfar = Infinity; |
| 4803 |
let tnear = -Infinity; |
| 4804 |
let direction = []; |
| 4805 |
|
| 4806 |
for (let i = 0; i < 3; i++) { |
| 4807 |
const a = start[i]; |
| 4808 |
const b = end[i]; |
| 4809 |
const d = b - a; |
| 4810 |
const bn = bmin[i]; |
| 4811 |
const bx = bmax[i]; |
| 4812 |
direction.push(d); |
| 4813 |
|
| 4814 |
// Non parallel cases |
| 4815 |
// 1e-12 for 64 bit unit types and 1e-6 for 32 bit unit types |
| 4816 |
if (Math.abs(d) > 1e-12) { |
| 4817 |
const inv_d = 1 / d; |
| 4818 |
const t1 = (bn - a) * inv_d; |
| 4819 |
const t2 = (bx - a) * inv_d; |
| 4820 |
tnear = Math.max(Math.min(t1, t2), tnear); |
| 4821 |
tfar = Math.min(Math.max(t1, t2), tfar); |
| 4822 |
} |
| 4823 |
|
| 4824 |
// Impossible parallel case |
| 4825 |
else if (a < bn || a > bx) { |
| 4826 |
return []; |
| 4827 |
} |
| 4828 |
} |
| 4829 |
|
| 4830 |
// No hit |
| 4831 |
if (tnear > tfar || tfar < 0) { |
| 4832 |
return []; |
| 4833 |
} |
| 4834 |
|
| 4835 |
// Favor the intersection first in the direction start -> end |
| 4836 |
if (tnear < 0) { |
| 4837 |
tnear = tfar; |
| 4838 |
} |
| 4839 |
|
| 4840 |
// A point, or something approaching a single point where start and end are the same. |
| 4841 |
if (!isFinite(tnear)) { |
| 4842 |
return []; |
| 4843 |
} |
| 4844 |
|
| 4845 |
// Calculate nearest intersection via interpolation |
| 4846 |
return [ |
| 4847 |
start[0] + direction[0] * tnear, |
| 4848 |
start[1] + direction[1] * tnear, |
| 4849 |
start[2] + direction[2] * tnear, |
| 4850 |
]; |
| 4851 |
} |
| 4852 |
|
| 4853 |
/** |
| 4854 |
* Given a color `origin`, returns a new color that is in gamut using |
| 4855 |
* the CSS Ray Trace Gamut Mapping Algorithm. If `space` is specified, |
| 4856 |
* it will be in gamut `space`, and returned in `space`. Otherwise, |
| 4857 |
* it will be in gamut and returned in the color space of `origin`. |
| 4858 |
* @param {ColorTypes} origin |
| 4859 |
* @param {{ space?: string | ColorSpace | undefined }} options |
| 4860 |
* @returns {PlainColorObject} |
| 4861 |
*/ |
| 4862 |
function toGamutRayTrace (origin, { space } = {}) { |
| 4863 |
origin = getColor(origin); |
| 4864 |
|
| 4865 |
if (!space) { |
| 4866 |
space = origin.space; |
| 4867 |
} |
| 4868 |
|
| 4869 |
space = ColorSpace.get(space); |
| 4870 |
|
| 4871 |
// If the space is already in gamut, stop. |
| 4872 |
if (space.isUnbounded) { |
| 4873 |
return to(origin, space); |
| 4874 |
} |
| 4875 |
|
| 4876 |
// Get the OkLCh coordinates. |
| 4877 |
let oklchOrigin = to(origin, OKLCH); |
| 4878 |
let [lightness, chroma, hue] = oklchOrigin.coords; |
| 4879 |
|
| 4880 |
// Return white or black if color's lightness exceeds the SDR range. |
| 4881 |
if (lightness >= 1) { |
| 4882 |
const white = to(COLORS.WHITE, space); |
| 4883 |
white.alpha = origin.alpha; |
| 4884 |
return to(white, space); |
| 4885 |
} |
| 4886 |
else if (lightness <= 0) { |
| 4887 |
const black = to(COLORS.BLACK, space); |
| 4888 |
black.alpha = origin.alpha; |
| 4889 |
return to(black, space); |
| 4890 |
} |
| 4891 |
|
| 4892 |
// Get a copy of the origin color as the RGB target space. |
| 4893 |
const originSpace = space; |
| 4894 |
const rGamut = space.rgbGamut; |
| 4895 |
if (rGamut !== undefined) { |
| 4896 |
space = rGamut; |
| 4897 |
} |
| 4898 |
|
| 4899 |
if (!isInstance(space, RGBColorSpace)) { |
| 4900 |
throw Error('An RGB gamut is required') |
| 4901 |
} |
| 4902 |
|
| 4903 |
// Get SDR bounds. Some HDR spaces have headroom, so reduce max to SDR range. |
| 4904 |
let [mn, mx] = Object.values(space.coords)[0].range; |
| 4905 |
let max = /** @type {[number, number, number]} */ ([mx, mx, mx]); |
| 4906 |
|
| 4907 |
// See if we have a linear version of the color space |
| 4908 |
const lGamut = space.linearGamut; |
| 4909 |
if (lGamut !== undefined) { |
| 4910 |
// Recalculate minimum and maximum relative to the linear space |
| 4911 |
let temp = to({ space: space, coords: max, alpha: origin.alpha }, lGamut); |
| 4912 |
mx = temp.coords[0]; |
| 4913 |
max = /** @type {[number, number, number]} */ ([mx, mx, mx]); |
| 4914 |
space = lGamut; |
| 4915 |
mn = Object.values(space.coords)[0].range[0]; |
| 4916 |
} |
| 4917 |
let min = /** @type {[number, number, number]} */ ([mn, mn, mn]); |
| 4918 |
let rgbOrigin = to(oklchOrigin, space); |
| 4919 |
|
| 4920 |
if (!rgbOrigin.coords.every(x => mn <= x && x <= mx)) { |
| 4921 |
// If this were performed within a perceptual space like CAM16, which has achromatics that do not align |
| 4922 |
// with the RGB achromatic line, projecting the color onto the RGB achromatic line may be preferable, |
| 4923 |
// but since OkLCh's achromatics align with all CSS RGB spaces, just set chroma to zero. |
| 4924 |
let anchor = to({ space: OKLCH, coords: [lightness, 0, hue] }, space).coords; |
| 4925 |
|
| 4926 |
// Calculate bounds to adjust the anchor closer to the gamut surface. |
| 4927 |
// We don't want to make the ray too short, so offset some amount from the low and high range. |
| 4928 |
// 1e-12 for 64 bit unit types and 1e-6 for 32 bit unit types. |
| 4929 |
const low = mn + 1e-12; |
| 4930 |
const high = mx - 1e-12; |
| 4931 |
|
| 4932 |
// Cast a ray from the zero chroma color to the target color. |
| 4933 |
// Trace the line to the RGB cube edge and find where it intersects. |
| 4934 |
// Correct L and h within the perceptual OkLCh after each attempt. |
| 4935 |
let last = rgbOrigin.coords; |
| 4936 |
for (let i = 0; i < 4; i++) { |
| 4937 |
if (i) { |
| 4938 |
// For constant luminance, we correct the color by simply setting lightness and hue to |
| 4939 |
// match the original color. In a non constant luminance reduction, it is better to |
| 4940 |
// project the color onto the reduction path vector. |
| 4941 |
const oklchColor = to(rgbOrigin, OKLCH); |
| 4942 |
oklchColor.coords[0] = lightness; |
| 4943 |
oklchColor.coords[2] = hue; |
| 4944 |
rgbOrigin = to(oklchColor, space); |
| 4945 |
} |
| 4946 |
// Cast a ray from the achromatic anchor to the RGB target and find the gamut intersection. |
| 4947 |
const intersection = raytrace_box(anchor, rgbOrigin.coords, min, max); |
| 4948 |
|
| 4949 |
// If we cannot find an intersection, reset to last successful iteration of the color. |
| 4950 |
// In OkLCh, this is only likely to happen if our ray gets too small, in that case, it is time to stop. |
| 4951 |
if (intersection.length === 0) { |
| 4952 |
rgbOrigin.coords = [...last]; |
| 4953 |
break; |
| 4954 |
} |
| 4955 |
|
| 4956 |
// Adjust anchor point closer to surface, when possible, to improve results for some spaces. |
| 4957 |
if (i && rgbOrigin.coords.every(x => low < x && x < high)) { |
| 4958 |
anchor = [...rgbOrigin.coords]; |
| 4959 |
} |
| 4960 |
|
| 4961 |
// If we have an intersection, update the color. |
| 4962 |
last = /** @type {[number, number, number]} */ (intersection); |
| 4963 |
rgbOrigin.coords = [...intersection]; |
| 4964 |
} |
| 4965 |
} |
| 4966 |
|
| 4967 |
// Convert to the original, specified gamut |
| 4968 |
rgbOrigin = to(rgbOrigin, originSpace); |
| 4969 |
const spaceCoords = Object.values(/** @type {ColorSpace} */ (originSpace).coords); |
| 4970 |
|
| 4971 |
// Remove noise from floating point math by clipping |
| 4972 |
rgbOrigin.coords = /** @type {[number, number, number]} */ ( |
| 4973 |
rgbOrigin.coords.map((coord, index) => { |
| 4974 |
if ("range" in spaceCoords[index]) { |
| 4975 |
const [lower, upper] = spaceCoords[index].range; |
| 4976 |
return clamp(lower, coord, upper); |
| 4977 |
} |
| 4978 |
return coord; |
| 4979 |
}) |
| 4980 |
); |
| 4981 |
|
| 4982 |
return rgbOrigin; |
| 4983 |
} |
| 4984 |
|
| 4985 |
/** @import { SpaceOptions } from "./ColorSpace.js" */ |
| 4986 |
|
| 4987 |
/** |
| 4988 |
* A color space whose chroma-like coordinate is expressed relative to an RGB gamut: chroma = 1 is |
| 4989 |
* the most colorful in-gamut color for the rest of the coordinates, so any chroma in [0, 1] stays |
| 4990 |
* in gamut. The reduced coordinate (`chroma`, default `"c"`) is rescaled against `gamutSpace`; every |
| 4991 |
* other coordinate is inherited unchanged from `base`. Works for any base whose chroma coordinate |
| 4992 |
* brings the color into gamut as it is reduced (e.g. OKLCh, LCH). |
| 4993 |
*/ |
| 4994 |
class GamutRelativeColorSpace extends ColorSpace { |
| 4995 |
/** |
| 4996 |
* @param {SpaceOptions & { gamutSpace: string | ColorSpace, chroma?: string }} options |
| 4997 |
* Requires `base` (the source space) and `gamutSpace` (the RGB gamut). `chroma` names the |
| 4998 |
* coordinate to rescale (default `"c"`). |
| 4999 |
*/ |
| 5000 |
constructor (options) { |
| 5001 |
let base = ColorSpace.get(options.base); |
| 5002 |
let chroma = options.chroma ?? "c"; |
| 5003 |
let ids = Object.keys(base.coords); |
| 5004 |
let chromaIndex = ids.indexOf(chroma); |
| 5005 |
|
| 5006 |
if (chromaIndex === -1) { |
| 5007 |
throw new TypeError( |
| 5008 |
`GamutRelativeColorSpace needs a "${chroma}" coordinate, got ${base.id}`, |
| 5009 |
); |
| 5010 |
} |
| 5011 |
|
| 5012 |
// Inherit the base's coords; the reduced coordinate becomes a 0–1 fraction of its gamut maximum |
| 5013 |
let coords = Object.fromEntries( |
| 5014 |
Object.entries(base.coords).map(([id, meta]) => [id, { ...meta }]), |
| 5015 |
); |
| 5016 |
coords[chroma].range = [0, 1]; |
| 5017 |
delete coords[chroma].refRange; |
| 5018 |
options.coords ??= coords; |
| 5019 |
|
| 5020 |
// Serialize the reduced coordinate and any other 0–1 coordinate as percentages; angles as angles |
| 5021 |
options.formats ??= { |
| 5022 |
color: { |
| 5023 |
coords: ids.map(id => { |
| 5024 |
if (base.coords[id].type === "angle") { |
| 5025 |
return "<number> | <angle>"; |
| 5026 |
} |
| 5027 |
let [min, max] = base.coords[id].range ?? base.coords[id].refRange ?? []; |
| 5028 |
let pctFirst = id === chroma || (min === 0 && max === 1); |
| 5029 |
return pctFirst ? "<percentage> | <number>" : "<number> | <percentage>"; |
| 5030 |
}), |
| 5031 |
}, |
| 5032 |
}; |
| 5033 |
|
| 5034 |
super(options); |
| 5035 |
|
| 5036 |
this.chromaIndex = chromaIndex; |
| 5037 |
this.method = `${base.id}.${chroma}`; |
| 5038 |
|
| 5039 |
// A chroma that is out of gamut at every lightness and hue: the gamut's most saturated corner |
| 5040 |
// (its primaries/secondaries are its chroma maxima) plus headroom. Seeding the gamut search |
| 5041 |
// from here lands on the first in-gamut crossing — the highest contiguous in-gamut chroma — |
| 5042 |
// and avoids clamping wide gamuts (e.g. Rec.2020 exceeds OKLCh's nominal 0.4 chroma). |
| 5043 |
// prettier-ignore |
| 5044 |
let corners = /** @type {[number, number, number][]} */ ( |
| 5045 |
[[0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0]] |
| 5046 |
); |
| 5047 |
this.oogChroma = |
| 5048 |
1.01 * |
| 5049 |
Math.max(...corners.map(rgb => base.from(this.gamutSpace, rgb)[this.chromaIndex] || 0)); |
| 5050 |
} |
| 5051 |
|
| 5052 |
/** |
| 5053 |
* The highest in-gamut value of the reduced coordinate for the given coordinates. The reduced |
| 5054 |
* coordinate's own value is ignored; the others determine the result. |
| 5055 |
* @param {number[]} coords |
| 5056 |
* @returns {number} |
| 5057 |
*/ |
| 5058 |
maxChroma (coords) { |
| 5059 |
let seed = /** @type {[number, number, number]} */ ([...coords]); |
| 5060 |
seed[this.chromaIndex] = this.oogChroma; |
| 5061 |
|
| 5062 |
return toGamut( |
| 5063 |
{ space: this.base, coords: seed }, |
| 5064 |
// deltaE OK stays sensitive near black, where deltaE 2000 is too forgiving of excess chroma |
| 5065 |
{ space: this.gamutSpace, method: this.method, deltaEMethod: "OK", jnd: 0 }, |
| 5066 |
).coords[this.chromaIndex]; |
| 5067 |
} |
| 5068 |
|
| 5069 |
toBase (coords) { |
| 5070 |
coords = [...coords]; |
| 5071 |
|
| 5072 |
if (coords.some((c, i) => i !== this.chromaIndex && isNone(c))) { |
| 5073 |
// chroma is a fraction of maxChroma(the other coords); without them all it is undefined |
| 5074 |
if (coords[this.chromaIndex] !== 0) { |
| 5075 |
coords[this.chromaIndex] = null; |
| 5076 |
} |
| 5077 |
} |
| 5078 |
else if (!isNone(coords[this.chromaIndex])) { |
| 5079 |
coords[this.chromaIndex] *= this.maxChroma(coords); |
| 5080 |
} |
| 5081 |
|
| 5082 |
return coords; |
| 5083 |
} |
| 5084 |
|
| 5085 |
fromBase (coords) { |
| 5086 |
coords = [...coords]; |
| 5087 |
|
| 5088 |
if (coords.some((c, i) => i !== this.chromaIndex && isNone(c))) { |
| 5089 |
if (coords[this.chromaIndex] !== 0) { |
| 5090 |
coords[this.chromaIndex] = null; |
| 5091 |
} |
| 5092 |
} |
| 5093 |
else if (!isNone(coords[this.chromaIndex])) { |
| 5094 |
let cMax = this.maxChroma(coords); |
| 5095 |
coords[this.chromaIndex] = cMax ? coords[this.chromaIndex] / cMax : 0; |
| 5096 |
} |
| 5097 |
|
| 5098 |
return coords; |
| 5099 |
} |
| 5100 |
} |
| 5101 |
|
| 5102 |
/** @import { ColorTypes, PlainColorObject } from "./types.js" */ |
| 5103 |
|
| 5104 |
// Type re-exports |
| 5105 |
/** @typedef {import("./types.js").TryColorOptions} TryColorOptions */ |
| 5106 |
|
| 5107 |
/** |
| 5108 |
* Resolves a color reference (object or string) to a plain color object, or `null` if resolution fails. |
| 5109 |
* Can resolve more complex CSS colors (e.g. relative colors, `calc()`, CSS variables, `color-mix()`, etc.) through the DOM. |
| 5110 |
* |
| 5111 |
* @overload |
| 5112 |
* @param {ColorTypes} color |
| 5113 |
* @param {TryColorOptions} [options] |
| 5114 |
* @returns {PlainColorObject | null} |
| 5115 |
*/ |
| 5116 |
/** |
| 5117 |
* @overload |
| 5118 |
* @param {ColorTypes[]} color |
| 5119 |
* @param {TryColorOptions} [options] |
| 5120 |
* @returns {(PlainColorObject | null)[]} |
| 5121 |
*/ |
| 5122 |
function tryColor (color, options = {}) { |
| 5123 |
if (Array.isArray(color)) { |
| 5124 |
return color.map(c => tryColor(c, options)); |
| 5125 |
} |
| 5126 |
|
| 5127 |
let { cssProperty = "background-color", element, ...getColorOptions } = options; |
| 5128 |
let error = null; |
| 5129 |
try { |
| 5130 |
return getColor(color, getColorOptions); |
| 5131 |
} |
| 5132 |
catch (e) { |
| 5133 |
error = e; |
| 5134 |
} |
| 5135 |
|
| 5136 |
let { CSS, getComputedStyle } = globalThis; |
| 5137 |
if (isString(color) && element && CSS && getComputedStyle) { |
| 5138 |
// Try resolving the color using the DOM, if supported in CSS |
| 5139 |
if (CSS.supports(cssProperty, color)) { |
| 5140 |
let previousValue = element.style[cssProperty]; |
| 5141 |
|
| 5142 |
if (color !== previousValue) { |
| 5143 |
element.style[cssProperty] = color; |
| 5144 |
} |
| 5145 |
|
| 5146 |
let computedColor = getComputedStyle(element).getPropertyValue(cssProperty); |
| 5147 |
|
| 5148 |
if (color !== previousValue) { |
| 5149 |
element.style[cssProperty] = previousValue; |
| 5150 |
} |
| 5151 |
|
| 5152 |
if (computedColor !== color) { |
| 5153 |
// getComputedStyle() changed the color, try again |
| 5154 |
try { |
| 5155 |
return getColor(computedColor, getColorOptions); |
| 5156 |
} |
| 5157 |
catch (e) { |
| 5158 |
error = e; |
| 5159 |
} |
| 5160 |
} |
| 5161 |
else { |
| 5162 |
// Still not resolved |
| 5163 |
error = { |
| 5164 |
message: "Color value is a valid CSS color, but it could not be resolved :(", |
| 5165 |
}; |
| 5166 |
} |
| 5167 |
} |
| 5168 |
} |
| 5169 |
|
| 5170 |
// If we're here, we failed to resolve the color |
| 5171 |
if (options.errorMeta) { |
| 5172 |
options.errorMeta.error = error; |
| 5173 |
} |
| 5174 |
|
| 5175 |
return null; |
| 5176 |
} |
| 5177 |
|
| 5178 |
// @ts-nocheck |
| 5179 |
|
| 5180 |
|
| 5181 |
/** @import { ColorTypes, ParseOptions, PlainColorObject } from "./types.js" */ |
| 5182 |
|
| 5183 |
// Type re-exports |
| 5184 |
/** @typedef {import("./types.js").SerializeOptions} SerializeOptions */ |
| 5185 |
|
| 5186 |
/** |
| 5187 |
* Generic toString() method, outputs a color(spaceId ...coords) function, a functional syntax, or custom formats defined by the color space |
| 5188 |
* @param {ColorTypes} color |
| 5189 |
* @param {SerializeOptions & Record<string, any>} options |
| 5190 |
* @returns {string} |
| 5191 |
*/ |
| 5192 |
function serialize (color, options = {}) { |
| 5193 |
let { |
| 5194 |
precision = defaults.precision, |
| 5195 |
format, |
| 5196 |
inGamut: inGamut$1 = true, |
| 5197 |
coords: coordFormat, |
| 5198 |
alpha: alphaFormat, |
| 5199 |
commas, |
| 5200 |
} = options; |
| 5201 |
let ret; |
| 5202 |
|
| 5203 |
let colorWithMeta = /** @type {PlainColorObject & ParseOptions} */ (getColor(color)); |
| 5204 |
|
| 5205 |
let formatId = format; |
| 5206 |
let parseMeta = colorWithMeta.parseMeta; |
| 5207 |
|
| 5208 |
if (parseMeta && !format) { |
| 5209 |
if (parseMeta.format.canSerialize()) { |
| 5210 |
format = parseMeta.format; |
| 5211 |
formatId = parseMeta.formatId; |
| 5212 |
} |
| 5213 |
|
| 5214 |
coordFormat ??= parseMeta.types; |
| 5215 |
alphaFormat ??= parseMeta.alphaType; |
| 5216 |
commas ??= parseMeta.commas; |
| 5217 |
} |
| 5218 |
|
| 5219 |
if (formatId) { |
| 5220 |
// A format is explicitly specified |
| 5221 |
format = colorWithMeta.space.getFormat(format) ?? ColorSpace.findFormat(formatId); |
| 5222 |
} |
| 5223 |
|
| 5224 |
if (!format) { |
| 5225 |
// No format specified, or format not found |
| 5226 |
format = colorWithMeta.space.getFormat("default") ?? ColorSpace.DEFAULT_FORMAT; |
| 5227 |
formatId = format.name; |
| 5228 |
} |
| 5229 |
|
| 5230 |
if (format && format.space && format.space !== colorWithMeta.space) { |
| 5231 |
// Format specified belongs to a different color space, |
| 5232 |
// need to convert to it first |
| 5233 |
colorWithMeta = to(colorWithMeta, format.space); |
| 5234 |
} |
| 5235 |
|
| 5236 |
// The assignment to coords and inGamut needs to stay in the order they are now |
| 5237 |
// The order of the assignment was changed as a workaround for a bug in Next.js |
| 5238 |
// See this issue for details: https://github.com/color-js/color.js/issues/260 |
| 5239 |
|
| 5240 |
let coords = colorWithMeta.coords.slice(); // clone so we can manipulate it |
| 5241 |
|
| 5242 |
inGamut$1 ||= format.toGamut; |
| 5243 |
|
| 5244 |
if (inGamut$1 && !inGamut(colorWithMeta)) { |
| 5245 |
// FIXME what happens if the color contains none values? |
| 5246 |
coords = toGamut(clone(colorWithMeta), inGamut$1 === true ? undefined : inGamut$1).coords; |
| 5247 |
} |
| 5248 |
|
| 5249 |
if (format.type === "custom") { |
| 5250 |
if (format.serialize) { |
| 5251 |
ret = format.serialize(coords, colorWithMeta.alpha, options); |
| 5252 |
} |
| 5253 |
else { |
| 5254 |
throw new TypeError( |
| 5255 |
`format ${formatId} can only be used to parse colors, not for serialization`, |
| 5256 |
); |
| 5257 |
} |
| 5258 |
} |
| 5259 |
else { |
| 5260 |
// Functional syntax |
| 5261 |
let name = format.name || "color"; |
| 5262 |
|
| 5263 |
let args = format.serializeCoords(coords, precision, coordFormat); |
| 5264 |
|
| 5265 |
if (name === "color") { |
| 5266 |
// If output is a color() function, add colorspace id as first argument |
| 5267 |
let cssId = |
| 5268 |
format.id || format.ids?.[0] || colorWithMeta.space.cssId || colorWithMeta.space.id; |
| 5269 |
args.unshift(cssId); |
| 5270 |
} |
| 5271 |
|
| 5272 |
// Serialize alpha? |
| 5273 |
/** @type {string | number} */ |
| 5274 |
let alpha = colorWithMeta.alpha; |
| 5275 |
|
| 5276 |
if (alphaFormat !== undefined && !(typeof alphaFormat === "object")) { |
| 5277 |
alphaFormat = |
| 5278 |
typeof alphaFormat === "string" ? { type: alphaFormat } : { include: alphaFormat }; |
| 5279 |
} |
| 5280 |
|
| 5281 |
let alphaType = alphaFormat?.type ?? "<number>"; |
| 5282 |
let serializeAlpha = |
| 5283 |
alphaFormat?.include === true || |
| 5284 |
format.alpha === true || |
| 5285 |
(alphaFormat?.include !== false && format.alpha !== false && alpha < 1); |
| 5286 |
let strAlpha = ""; |
| 5287 |
|
| 5288 |
commas ??= format.commas; |
| 5289 |
|
| 5290 |
if (serializeAlpha) { |
| 5291 |
if (precision !== null) { |
| 5292 |
let unit; |
| 5293 |
|
| 5294 |
if (alphaType === "<percentage>") { |
| 5295 |
unit = "%"; |
| 5296 |
alpha *= 100; |
| 5297 |
} |
| 5298 |
|
| 5299 |
alpha = serializeNumber(alpha, { precision, unit }); |
| 5300 |
} |
| 5301 |
|
| 5302 |
strAlpha = `${commas ? "," : " /"} ${alpha}`; |
| 5303 |
} |
| 5304 |
|
| 5305 |
ret = `${name}(${args.join(commas ? ", " : " ")}${strAlpha})`; |
| 5306 |
} |
| 5307 |
|
| 5308 |
return ret; |
| 5309 |
} |
| 5310 |
|
| 5311 |
/** @import { Matrix3x3 } from "../types.js" */ |
| 5312 |
|
| 5313 |
/** |
| 5314 |
* Matrices used by this color space, also available as `REC_2020_Linear.M`. |
| 5315 |
* Uses D65 (no chromatic adaptation). |
| 5316 |
* http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html |
| 5317 |
* @type {Record<string, Matrix3x3>} |
| 5318 |
*/ |
| 5319 |
// prettier-ignore |
| 5320 |
const M$8 = { |
| 5321 |
// 0 is actually calculated as 4.994106574466076e-17 |
| 5322 |
toXYZ: [ |
| 5323 |
[ 0.6369580483012914, 0.14461690358620832, 0.1688809751641721 ], |
| 5324 |
[ 0.2627002120112671, 0.6779980715188708, 0.05930171646986196 ], |
| 5325 |
[ 0.000000000000000, 0.028072693049087428, 1.060985057710791 ], |
| 5326 |
], |
| 5327 |
// from ITU-R BT.2124-0 Annex 2 p.3 |
| 5328 |
fromXYZ: [ |
| 5329 |
[ 1.716651187971268, -0.355670783776392, -0.253366281373660 ], |
| 5330 |
[ -0.666684351832489, 1.616481236634939, 0.0157685458139111 ], |
| 5331 |
[ 0.017639857445311, -0.042770613257809, 0.942103121235474 ], |
| 5332 |
], |
| 5333 |
}; |
| 5334 |
|
| 5335 |
var REC2020Linear = new RGBColorSpace({ |
| 5336 |
id: "rec2020-linear", |
| 5337 |
cssId: "--rec2020-linear", |
| 5338 |
name: "Linear REC.2020", |
| 5339 |
white: "D65", |
| 5340 |
M: M$8, |
| 5341 |
}); |
| 5342 |
|
| 5343 |
// import sRGB from "./srgb.js"; |
| 5344 |
|
| 5345 |
var REC2020 = new RGBColorSpace({ |
| 5346 |
id: "rec2020", |
| 5347 |
name: "REC.2020", |
| 5348 |
base: REC2020Linear, |
| 5349 |
linearGamut: REC2020Linear, |
| 5350 |
// Reference electro-optical transfer function from Rec. ITU-R BT.1886 Annex 1 |
| 5351 |
// with b (black lift) = 0 and a (user gain) = 1 |
| 5352 |
// defined over the extended range, not clamped |
| 5353 |
toBase (RGB) { |
| 5354 |
return RGB.map(function (val) { |
| 5355 |
let sign = val < 0 ? -1 : 1; |
| 5356 |
let abs = val * sign; |
| 5357 |
return sign * Math.pow(abs, 2.4); |
| 5358 |
}); |
| 5359 |
}, |
| 5360 |
fromBase (RGB) { |
| 5361 |
return RGB.map(function (val) { |
| 5362 |
let sign = val < 0 ? -1 : 1; |
| 5363 |
let abs = val * sign; |
| 5364 |
return sign * Math.pow(abs, 1 / 2.4); |
| 5365 |
}); |
| 5366 |
}, |
| 5367 |
}); |
| 5368 |
|
| 5369 |
/** @import { Matrix3x3 } from "../types.js" */ |
| 5370 |
|
| 5371 |
/** |
| 5372 |
* Matrices used by this color space, also available as `P3_Linear.M` |
| 5373 |
* @type {Record<string, Matrix3x3>} |
| 5374 |
*/ |
| 5375 |
// prettier-ignore |
| 5376 |
const M$7 = { |
| 5377 |
toXYZ: [ |
| 5378 |
[0.4865709486482162, 0.26566769316909306, 0.1982172852343625], |
| 5379 |
[0.2289745640697488, 0.6917385218365064, 0.079286914093745], |
| 5380 |
[0.0000000000000000, 0.04511338185890264, 1.043944368900976], |
| 5381 |
], |
| 5382 |
fromXYZ: [ |
| 5383 |
[ 2.493496911941425, -0.9313836179191239, -0.40271078445071684], |
| 5384 |
[-0.8294889695615747, 1.7626640603183463, 0.023624685841943577], |
| 5385 |
[ 0.03584583024378447, -0.07617238926804182, 0.9568845240076872], |
| 5386 |
], |
| 5387 |
}; |
| 5388 |
|
| 5389 |
var P3Linear = new RGBColorSpace({ |
| 5390 |
id: "p3-linear", |
| 5391 |
cssId: "display-p3-linear", |
| 5392 |
name: "Linear P3", |
| 5393 |
white: "D65", |
| 5394 |
M: M$7, |
| 5395 |
}); |
| 5396 |
|
| 5397 |
/** @import { Matrix3x3 } from "../types.js" */ |
| 5398 |
|
| 5399 |
// This is the linear-light version of sRGB |
| 5400 |
// as used for example in SVG filters |
| 5401 |
// or in Canvas |
| 5402 |
|
| 5403 |
/** |
| 5404 |
* Matrices used by this color space, also available as `sRGB_Linear.M` |
| 5405 |
* @type {Record<string, Matrix3x3>} |
| 5406 |
*/ |
| 5407 |
// prettier-ignore |
| 5408 |
const M$6 = { |
| 5409 |
// calculated directly from the RGB and white chromaticities; when rounded to |
| 5410 |
// 8 decimal places, agrees completely with the official matrix |
| 5411 |
// see https://github.com/w3c/csswg-drafts/issues/5922 |
| 5412 |
toXYZ: [ |
| 5413 |
[ 0.41239079926595934, 0.357584339383878, 0.1804807884018343 ], |
| 5414 |
[ 0.21263900587151027, 0.715168678767756, 0.07219231536073371 ], |
| 5415 |
[ 0.01933081871559182, 0.11919477979462598, 0.9505321522496607 ], |
| 5416 |
], |
| 5417 |
// the inverse of the above; again agrees with the official definition |
| 5418 |
// when rounded to 8 decimal places |
| 5419 |
fromXYZ: [ |
| 5420 |
[ 3.2409699419045226, -1.537383177570094, -0.4986107602930034 ], |
| 5421 |
[ -0.9692436362808796, 1.8759675015077202, 0.04155505740717559 ], |
| 5422 |
[ 0.05563007969699366, -0.20397695888897652, 1.0569715142428786 ], |
| 5423 |
], |
| 5424 |
}; |
| 5425 |
|
| 5426 |
var sRGBLinear = new RGBColorSpace({ |
| 5427 |
id: "srgb-linear", |
| 5428 |
name: "Linear sRGB", |
| 5429 |
white: "D65", |
| 5430 |
M: M$6, |
| 5431 |
}); |
| 5432 |
|
| 5433 |
// To produce: Visit https://www.w3.org/TR/css-color-4/#named-colors |
| 5434 |
// and run in the console: |
| 5435 |
// copy($$("tr", $(".named-color-table tbody")).map(tr => `"${tr.cells[2].textContent.trim()}": [${tr.cells[4].textContent.trim().split(/\s+/).map(c => c === "0"? "0" : c === "255"? "1" : c + " / 255").join(", ")}]`).join(",\n")) |
| 5436 |
|
| 5437 |
/** List of CSS color keywords |
| 5438 |
* Note that this does not include currentColor, transparent, |
| 5439 |
* or system colors |
| 5440 |
* |
| 5441 |
* @type {Record<string, [number, number, number]>} |
| 5442 |
*/ |
| 5443 |
var KEYWORDS = { |
| 5444 |
aliceblue: [240 / 255, 248 / 255, 1], |
| 5445 |
antiquewhite: [250 / 255, 235 / 255, 215 / 255], |
| 5446 |
aqua: [0, 1, 1], |
| 5447 |
aquamarine: [127 / 255, 1, 212 / 255], |
| 5448 |
azure: [240 / 255, 1, 1], |
| 5449 |
beige: [245 / 255, 245 / 255, 220 / 255], |
| 5450 |
bisque: [1, 228 / 255, 196 / 255], |
| 5451 |
black: [0, 0, 0], |
| 5452 |
blanchedalmond: [1, 235 / 255, 205 / 255], |
| 5453 |
blue: [0, 0, 1], |
| 5454 |
blueviolet: [138 / 255, 43 / 255, 226 / 255], |
| 5455 |
brown: [165 / 255, 42 / 255, 42 / 255], |
| 5456 |
burlywood: [222 / 255, 184 / 255, 135 / 255], |
| 5457 |
cadetblue: [95 / 255, 158 / 255, 160 / 255], |
| 5458 |
chartreuse: [127 / 255, 1, 0], |
| 5459 |
chocolate: [210 / 255, 105 / 255, 30 / 255], |
| 5460 |
coral: [1, 127 / 255, 80 / 255], |
| 5461 |
cornflowerblue: [100 / 255, 149 / 255, 237 / 255], |
| 5462 |
cornsilk: [1, 248 / 255, 220 / 255], |
| 5463 |
crimson: [220 / 255, 20 / 255, 60 / 255], |
| 5464 |
cyan: [0, 1, 1], |
| 5465 |
darkblue: [0, 0, 139 / 255], |
| 5466 |
darkcyan: [0, 139 / 255, 139 / 255], |
| 5467 |
darkgoldenrod: [184 / 255, 134 / 255, 11 / 255], |
| 5468 |
darkgray: [169 / 255, 169 / 255, 169 / 255], |
| 5469 |
darkgreen: [0, 100 / 255, 0], |
| 5470 |
darkgrey: [169 / 255, 169 / 255, 169 / 255], |
| 5471 |
darkkhaki: [189 / 255, 183 / 255, 107 / 255], |
| 5472 |
darkmagenta: [139 / 255, 0, 139 / 255], |
| 5473 |
darkolivegreen: [85 / 255, 107 / 255, 47 / 255], |
| 5474 |
darkorange: [1, 140 / 255, 0], |
| 5475 |
darkorchid: [153 / 255, 50 / 255, 204 / 255], |
| 5476 |
darkred: [139 / 255, 0, 0], |
| 5477 |
darksalmon: [233 / 255, 150 / 255, 122 / 255], |
| 5478 |
darkseagreen: [143 / 255, 188 / 255, 143 / 255], |
| 5479 |
darkslateblue: [72 / 255, 61 / 255, 139 / 255], |
| 5480 |
darkslategray: [47 / 255, 79 / 255, 79 / 255], |
| 5481 |
darkslategrey: [47 / 255, 79 / 255, 79 / 255], |
| 5482 |
darkturquoise: [0, 206 / 255, 209 / 255], |
| 5483 |
darkviolet: [148 / 255, 0, 211 / 255], |
| 5484 |
deeppink: [1, 20 / 255, 147 / 255], |
| 5485 |
deepskyblue: [0, 191 / 255, 1], |
| 5486 |
dimgray: [105 / 255, 105 / 255, 105 / 255], |
| 5487 |
dimgrey: [105 / 255, 105 / 255, 105 / 255], |
| 5488 |
dodgerblue: [30 / 255, 144 / 255, 1], |
| 5489 |
firebrick: [178 / 255, 34 / 255, 34 / 255], |
| 5490 |
floralwhite: [1, 250 / 255, 240 / 255], |
| 5491 |
forestgreen: [34 / 255, 139 / 255, 34 / 255], |
| 5492 |
fuchsia: [1, 0, 1], |
| 5493 |
gainsboro: [220 / 255, 220 / 255, 220 / 255], |
| 5494 |
ghostwhite: [248 / 255, 248 / 255, 1], |
| 5495 |
gold: [1, 215 / 255, 0], |
| 5496 |
goldenrod: [218 / 255, 165 / 255, 32 / 255], |
| 5497 |
gray: [128 / 255, 128 / 255, 128 / 255], |
| 5498 |
green: [0, 128 / 255, 0], |
| 5499 |
greenyellow: [173 / 255, 1, 47 / 255], |
| 5500 |
grey: [128 / 255, 128 / 255, 128 / 255], |
| 5501 |
honeydew: [240 / 255, 1, 240 / 255], |
| 5502 |
hotpink: [1, 105 / 255, 180 / 255], |
| 5503 |
indianred: [205 / 255, 92 / 255, 92 / 255], |
| 5504 |
indigo: [75 / 255, 0, 130 / 255], |
| 5505 |
ivory: [1, 1, 240 / 255], |
| 5506 |
khaki: [240 / 255, 230 / 255, 140 / 255], |
| 5507 |
lavender: [230 / 255, 230 / 255, 250 / 255], |
| 5508 |
lavenderblush: [1, 240 / 255, 245 / 255], |
| 5509 |
lawngreen: [124 / 255, 252 / 255, 0], |
| 5510 |
lemonchiffon: [1, 250 / 255, 205 / 255], |
| 5511 |
lightblue: [173 / 255, 216 / 255, 230 / 255], |
| 5512 |
lightcoral: [240 / 255, 128 / 255, 128 / 255], |
| 5513 |
lightcyan: [224 / 255, 1, 1], |
| 5514 |
lightgoldenrodyellow: [250 / 255, 250 / 255, 210 / 255], |
| 5515 |
lightgray: [211 / 255, 211 / 255, 211 / 255], |
| 5516 |
lightgreen: [144 / 255, 238 / 255, 144 / 255], |
| 5517 |
lightgrey: [211 / 255, 211 / 255, 211 / 255], |
| 5518 |
lightpink: [1, 182 / 255, 193 / 255], |
| 5519 |
lightsalmon: [1, 160 / 255, 122 / 255], |
| 5520 |
lightseagreen: [32 / 255, 178 / 255, 170 / 255], |
| 5521 |
lightskyblue: [135 / 255, 206 / 255, 250 / 255], |
| 5522 |
lightslategray: [119 / 255, 136 / 255, 153 / 255], |
| 5523 |
lightslategrey: [119 / 255, 136 / 255, 153 / 255], |
| 5524 |
lightsteelblue: [176 / 255, 196 / 255, 222 / 255], |
| 5525 |
lightyellow: [1, 1, 224 / 255], |
| 5526 |
lime: [0, 1, 0], |
| 5527 |
limegreen: [50 / 255, 205 / 255, 50 / 255], |
| 5528 |
linen: [250 / 255, 240 / 255, 230 / 255], |
| 5529 |
magenta: [1, 0, 1], |
| 5530 |
maroon: [128 / 255, 0, 0], |
| 5531 |
mediumaquamarine: [102 / 255, 205 / 255, 170 / 255], |
| 5532 |
mediumblue: [0, 0, 205 / 255], |
| 5533 |
mediumorchid: [186 / 255, 85 / 255, 211 / 255], |
| 5534 |
mediumpurple: [147 / 255, 112 / 255, 219 / 255], |
| 5535 |
mediumseagreen: [60 / 255, 179 / 255, 113 / 255], |
| 5536 |
mediumslateblue: [123 / 255, 104 / 255, 238 / 255], |
| 5537 |
mediumspringgreen: [0, 250 / 255, 154 / 255], |
| 5538 |
mediumturquoise: [72 / 255, 209 / 255, 204 / 255], |
| 5539 |
mediumvioletred: [199 / 255, 21 / 255, 133 / 255], |
| 5540 |
midnightblue: [25 / 255, 25 / 255, 112 / 255], |
| 5541 |
mintcream: [245 / 255, 1, 250 / 255], |
| 5542 |
mistyrose: [1, 228 / 255, 225 / 255], |
| 5543 |
moccasin: [1, 228 / 255, 181 / 255], |
| 5544 |
navajowhite: [1, 222 / 255, 173 / 255], |
| 5545 |
navy: [0, 0, 128 / 255], |
| 5546 |
oldlace: [253 / 255, 245 / 255, 230 / 255], |
| 5547 |
olive: [128 / 255, 128 / 255, 0], |
| 5548 |
olivedrab: [107 / 255, 142 / 255, 35 / 255], |
| 5549 |
orange: [1, 165 / 255, 0], |
| 5550 |
orangered: [1, 69 / 255, 0], |
| 5551 |
orchid: [218 / 255, 112 / 255, 214 / 255], |
| 5552 |
palegoldenrod: [238 / 255, 232 / 255, 170 / 255], |
| 5553 |
palegreen: [152 / 255, 251 / 255, 152 / 255], |
| 5554 |
paleturquoise: [175 / 255, 238 / 255, 238 / 255], |
| 5555 |
palevioletred: [219 / 255, 112 / 255, 147 / 255], |
| 5556 |
papayawhip: [1, 239 / 255, 213 / 255], |
| 5557 |
peachpuff: [1, 218 / 255, 185 / 255], |
| 5558 |
peru: [205 / 255, 133 / 255, 63 / 255], |
| 5559 |
pink: [1, 192 / 255, 203 / 255], |
| 5560 |
plum: [221 / 255, 160 / 255, 221 / 255], |
| 5561 |
powderblue: [176 / 255, 224 / 255, 230 / 255], |
| 5562 |
purple: [128 / 255, 0, 128 / 255], |
| 5563 |
rebeccapurple: [102 / 255, 51 / 255, 153 / 255], |
| 5564 |
red: [1, 0, 0], |
| 5565 |
rosybrown: [188 / 255, 143 / 255, 143 / 255], |
| 5566 |
royalblue: [65 / 255, 105 / 255, 225 / 255], |
| 5567 |
saddlebrown: [139 / 255, 69 / 255, 19 / 255], |
| 5568 |
salmon: [250 / 255, 128 / 255, 114 / 255], |
| 5569 |
sandybrown: [244 / 255, 164 / 255, 96 / 255], |
| 5570 |
seagreen: [46 / 255, 139 / 255, 87 / 255], |
| 5571 |
seashell: [1, 245 / 255, 238 / 255], |
| 5572 |
sienna: [160 / 255, 82 / 255, 45 / 255], |
| 5573 |
silver: [192 / 255, 192 / 255, 192 / 255], |
| 5574 |
skyblue: [135 / 255, 206 / 255, 235 / 255], |
| 5575 |
slateblue: [106 / 255, 90 / 255, 205 / 255], |
| 5576 |
slategray: [112 / 255, 128 / 255, 144 / 255], |
| 5577 |
slategrey: [112 / 255, 128 / 255, 144 / 255], |
| 5578 |
snow: [1, 250 / 255, 250 / 255], |
| 5579 |
springgreen: [0, 1, 127 / 255], |
| 5580 |
steelblue: [70 / 255, 130 / 255, 180 / 255], |
| 5581 |
tan: [210 / 255, 180 / 255, 140 / 255], |
| 5582 |
teal: [0, 128 / 255, 128 / 255], |
| 5583 |
thistle: [216 / 255, 191 / 255, 216 / 255], |
| 5584 |
tomato: [1, 99 / 255, 71 / 255], |
| 5585 |
turquoise: [64 / 255, 224 / 255, 208 / 255], |
| 5586 |
violet: [238 / 255, 130 / 255, 238 / 255], |
| 5587 |
wheat: [245 / 255, 222 / 255, 179 / 255], |
| 5588 |
white: [1, 1, 1], |
| 5589 |
whitesmoke: [245 / 255, 245 / 255, 245 / 255], |
| 5590 |
yellow: [1, 1, 0], |
| 5591 |
yellowgreen: [154 / 255, 205 / 255, 50 / 255], |
| 5592 |
}; |
| 5593 |
|
| 5594 |
/** @import { Coords } from "../types.js" */ |
| 5595 |
|
| 5596 |
let coordGrammar = Array(3).fill("<percentage> | <number>[0, 255]"); |
| 5597 |
let coordGrammarNumber = Array(3).fill("<number>[0, 255]"); |
| 5598 |
|
| 5599 |
var sRGB = new RGBColorSpace({ |
| 5600 |
id: "srgb", |
| 5601 |
name: "sRGB", |
| 5602 |
base: sRGBLinear, |
| 5603 |
linearGamut: sRGBLinear, |
| 5604 |
fromBase: rgb => { |
| 5605 |
// convert an array of linear-light sRGB values in the range 0.0-1.0 |
| 5606 |
// to gamma corrected form |
| 5607 |
// https://en.wikipedia.org/wiki/SRGB |
| 5608 |
return rgb.map(val => { |
| 5609 |
let sign = val < 0 ? -1 : 1; |
| 5610 |
let abs = val * sign; |
| 5611 |
|
| 5612 |
if (abs > 0.0031308) { |
| 5613 |
return sign * (1.055 * abs ** (1 / 2.4) - 0.055); |
| 5614 |
} |
| 5615 |
|
| 5616 |
return 12.92 * val; |
| 5617 |
}); |
| 5618 |
}, |
| 5619 |
toBase: rgb => { |
| 5620 |
// convert an array of sRGB values in the range 0.0 - 1.0 |
| 5621 |
// to linear light (un-companded) form. |
| 5622 |
// https://en.wikipedia.org/wiki/SRGB |
| 5623 |
return rgb.map(val => { |
| 5624 |
let sign = val < 0 ? -1 : 1; |
| 5625 |
let abs = val * sign; |
| 5626 |
|
| 5627 |
if (abs <= 0.04045) { |
| 5628 |
return val / 12.92; |
| 5629 |
} |
| 5630 |
|
| 5631 |
return sign * ((abs + 0.055) / 1.055) ** 2.4; |
| 5632 |
}); |
| 5633 |
}, |
| 5634 |
formats: { |
| 5635 |
rgb: { |
| 5636 |
coords: coordGrammar, |
| 5637 |
}, |
| 5638 |
rgb_number: { |
| 5639 |
name: "rgb", |
| 5640 |
commas: true, |
| 5641 |
coords: coordGrammarNumber, |
| 5642 |
alpha: false, |
| 5643 |
}, |
| 5644 |
color: { |
| 5645 |
/* use defaults */ |
| 5646 |
}, |
| 5647 |
rgba: { |
| 5648 |
coords: coordGrammar, |
| 5649 |
commas: true, |
| 5650 |
alpha: true, |
| 5651 |
}, |
| 5652 |
rgba_number: { |
| 5653 |
name: "rgba", |
| 5654 |
commas: true, |
| 5655 |
coords: coordGrammarNumber, |
| 5656 |
}, |
| 5657 |
hex: { |
| 5658 |
type: "custom", |
| 5659 |
toGamut: true, |
| 5660 |
test: str => /^#(([a-f0-9]{2}){3,4}|[a-f0-9]{3,4})$/i.test(str), |
| 5661 |
parse (str) { |
| 5662 |
if (str.length <= 5) { |
| 5663 |
// #rgb or #rgba, duplicate digits |
| 5664 |
str = str.replace(/[a-f0-9]/gi, "$&$&"); |
| 5665 |
} |
| 5666 |
|
| 5667 |
/** @type {number[]} */ |
| 5668 |
let rgba = []; |
| 5669 |
// @ts-expect-error Type 'void' is not assignable to type 'string' |
| 5670 |
str.replace(/[a-f0-9]{2}/gi, component => { |
| 5671 |
rgba.push(parseInt(component, 16) / 255); |
| 5672 |
}); |
| 5673 |
|
| 5674 |
return { |
| 5675 |
spaceId: "srgb", |
| 5676 |
coords: /** @type {Coords} */ (rgba.slice(0, 3)), |
| 5677 |
alpha: /** @type {number} */ (rgba.slice(3)[0]), |
| 5678 |
}; |
| 5679 |
}, |
| 5680 |
serialize: ( |
| 5681 |
coords, |
| 5682 |
alpha, |
| 5683 |
{ |
| 5684 |
collapse = true, // collapse to 3-4 digit hex when possible? |
| 5685 |
alpha: alphaFormat, |
| 5686 |
} = {}, |
| 5687 |
) => { |
| 5688 |
if ((alphaFormat !== false && alpha < 1) || alphaFormat === true) { |
| 5689 |
coords.push(alpha); |
| 5690 |
} |
| 5691 |
|
| 5692 |
coords = /** @type {[number, number, number]} */ ( |
| 5693 |
coords.map(c => Math.round(c * 255)) |
| 5694 |
); |
| 5695 |
|
| 5696 |
let collapsible = collapse && coords.every(c => c % 17 === 0); |
| 5697 |
|
| 5698 |
let hex = coords |
| 5699 |
.map(c => { |
| 5700 |
if (collapsible) { |
| 5701 |
return (c / 17).toString(16); |
| 5702 |
} |
| 5703 |
|
| 5704 |
return c.toString(16).padStart(2, "0"); |
| 5705 |
}) |
| 5706 |
.join(""); |
| 5707 |
|
| 5708 |
return "#" + hex; |
| 5709 |
}, |
| 5710 |
}, |
| 5711 |
keyword: { |
| 5712 |
type: "custom", |
| 5713 |
test: str => /^[a-z]+$/i.test(str), |
| 5714 |
parse (str) { |
| 5715 |
str = str.toLowerCase(); |
| 5716 |
let ret = { spaceId: "srgb", coords: null, alpha: 1 }; |
| 5717 |
|
| 5718 |
if (str === "transparent") { |
| 5719 |
ret.coords = KEYWORDS.black; |
| 5720 |
ret.alpha = 0; |
| 5721 |
} |
| 5722 |
else { |
| 5723 |
ret.coords = KEYWORDS[str]; |
| 5724 |
} |
| 5725 |
|
| 5726 |
if (ret.coords) { |
| 5727 |
return ret; |
| 5728 |
} |
| 5729 |
}, |
| 5730 |
}, |
| 5731 |
}, |
| 5732 |
}); |
| 5733 |
|
| 5734 |
var P3 = new RGBColorSpace({ |
| 5735 |
id: "p3", |
| 5736 |
cssId: "display-p3", |
| 5737 |
name: "P3", |
| 5738 |
base: P3Linear, |
| 5739 |
linearGamut: P3Linear, |
| 5740 |
// Gamma encoding/decoding is the same as sRGB |
| 5741 |
fromBase: sRGB.fromBase, |
| 5742 |
toBase: sRGB.toBase, |
| 5743 |
}); |
| 5744 |
|
| 5745 |
/** @import ColorSpace from "./ColorSpace.js" */ |
| 5746 |
/** @import { ColorTypes, PlainColorObject, DisplayOptions } from "./types.js" */ |
| 5747 |
|
| 5748 |
// Type re-exports |
| 5749 |
/** @typedef {import("./types.js").Display} Display */ |
| 5750 |
|
| 5751 |
// Default space for CSS output. Code in Color.js makes this wider if there's a DOM available |
| 5752 |
defaults.display_space = sRGB; |
| 5753 |
|
| 5754 |
let supportsNone; |
| 5755 |
|
| 5756 |
if (typeof CSS !== "undefined" && CSS.supports) { |
| 5757 |
// Find widest supported color space for CSS |
| 5758 |
for (let space of [lab, REC2020, P3]) { |
| 5759 |
let coords = space.getMinCoords(); |
| 5760 |
let color = { space, coords, alpha: 1 }; |
| 5761 |
let str = serialize(color); |
| 5762 |
|
| 5763 |
if (CSS.supports("color", str)) { |
| 5764 |
defaults.display_space = space; |
| 5765 |
break; |
| 5766 |
} |
| 5767 |
} |
| 5768 |
} |
| 5769 |
|
| 5770 |
/** |
| 5771 |
* Returns a serialization of the color that can actually be displayed in the browser. |
| 5772 |
* If the default serialization can be displayed, it is returned. |
| 5773 |
* Otherwise, if a `space` is given, the color is converted directly to it. |
| 5774 |
* If not, the color is converted to the first supported of its space's `displaySpaces` (if any), |
| 5775 |
* else the closest supported space in its base color space chain (which preserves its gamut), |
| 5776 |
* else the default fallback space (Lab, REC2020, or P3, whichever is the widest supported). |
| 5777 |
* In Node.js, this is basically equivalent to `serialize()` but returns a `String` object instead. |
| 5778 |
* @param {ColorTypes} color |
| 5779 |
* @param {DisplayOptions} [options] Options. Any properties beyond `space` and `supports` are passed to `serialize()`. |
| 5780 |
* @returns {Display} String object containing the serialized color |
| 5781 |
* with a color property containing the converted color (or the original, if no conversion was necessary) |
| 5782 |
*/ |
| 5783 |
function display ( |
| 5784 |
color, |
| 5785 |
{ space, supports = globalThis.CSS?.supports, ...options } = {}, |
| 5786 |
) { |
| 5787 |
color = getColor(color); |
| 5788 |
|
| 5789 |
let ret = /** @type {Display} */ (serialize(color, options)); |
| 5790 |
|
| 5791 |
if (!supports || supports("color", /** @type {string} */ (ret)) || !defaults.display_space) { |
| 5792 |
ret = /** @type {Display} */ (new String(ret)); |
| 5793 |
ret.color = /** @type {PlainColorObject} */ (color); |
| 5794 |
} |
| 5795 |
else { |
| 5796 |
// If we're here, what we were about to output is not supported |
| 5797 |
let fallbackColor = /** @type {PlainColorObject} */ (color); |
| 5798 |
|
| 5799 |
// First, check if the culprit is none values |
| 5800 |
let hasNone = color.coords.some(isNone) || isNone(color.alpha); |
| 5801 |
|
| 5802 |
if (hasNone) { |
| 5803 |
// Does the browser support none values? |
| 5804 |
if (!(supportsNone ??= supports("color", "hsl(none 50% 50%)"))) { |
| 5805 |
// Nope, try again without none |
| 5806 |
fallbackColor = clone(/** @type {PlainColorObject} */ (color)); |
| 5807 |
fallbackColor.coords = /** @type {[number, number, number]} */ ( |
| 5808 |
fallbackColor.coords.map(skipNone) |
| 5809 |
); |
| 5810 |
fallbackColor.alpha = skipNone(fallbackColor.alpha); |
| 5811 |
|
| 5812 |
// @ts-expect-error This is set to the correct type later |
| 5813 |
ret = serialize(fallbackColor, options); |
| 5814 |
|
| 5815 |
if (supports("color", /** @type {string} */ (ret))) { |
| 5816 |
// We're done, now it's supported |
| 5817 |
ret = /** @type {Display} */ (new String(ret)); |
| 5818 |
ret.color = fallbackColor; |
| 5819 |
return ret; |
| 5820 |
} |
| 5821 |
} |
| 5822 |
} |
| 5823 |
|
| 5824 |
// If we're here, the color function is not supported. |
| 5825 |
// With no explicit space, try the color's own `displaySpaces`, or else walk up its base |
| 5826 |
// color space chain (closest first, skipping XYZ connection spaces), and use the first |
| 5827 |
// space the browser supports, before falling back to the default space. |
| 5828 |
if (space === undefined) { |
| 5829 |
space = fallbackColor.space; |
| 5830 |
let candidates = space.displaySpaces ?? space.bases; |
| 5831 |
|
| 5832 |
// Skip XYZ connection spaces (unless the space itself is one, so it still has a fallback). |
| 5833 |
if (!space.displaySpaces && !space.id.startsWith("xyz-")) { |
| 5834 |
candidates = candidates.filter(space => !space.id.startsWith("xyz-")); |
| 5835 |
} |
| 5836 |
|
| 5837 |
for (let candidate of candidates) { |
| 5838 |
let candidateColor = to(fallbackColor, candidate); |
| 5839 |
let str = serialize(candidateColor, options); |
| 5840 |
|
| 5841 |
if (supports("color", /** @type {string} */ (str))) { |
| 5842 |
ret = /** @type {Display} */ (new String(str)); |
| 5843 |
ret.color = candidateColor; |
| 5844 |
return ret; |
| 5845 |
} |
| 5846 |
} |
| 5847 |
|
| 5848 |
space = defaults.display_space; |
| 5849 |
} |
| 5850 |
|
| 5851 |
// Fall back to fallback space |
| 5852 |
fallbackColor = to(fallbackColor, /** @type {string | ColorSpace} */ (space)); |
| 5853 |
ret = /** @type {Display} */ (new String(serialize(fallbackColor, options))); |
| 5854 |
ret.color = fallbackColor; |
| 5855 |
} |
| 5856 |
|
| 5857 |
return ret; |
| 5858 |
} |
| 5859 |
|
| 5860 |
/** @import { ColorTypes } from "./types.js" */ |
| 5861 |
|
| 5862 |
// Type re-exports |
| 5863 |
/** @typedef {import("./types.js").DeltasReturn} DeltasReturn */ |
| 5864 |
|
| 5865 |
/** |
| 5866 |
* Get color differences per-component, on any color space |
| 5867 |
* @param {ColorTypes} c1 |
| 5868 |
* @param {ColorTypes} c2 |
| 5869 |
* @param {object} options |
| 5870 |
* @param {string | ColorSpace} [options.space=c1.space] - The color space to use for the delta calculation. Defaults to the color space of the first color. |
| 5871 |
* @param {Parameters<typeof adjust>[0]} [options.hue="shorter"] - How to handle hue differences. Same as hue interpolation option. |
| 5872 |
* @returns {DeltasReturn} |
| 5873 |
*/ |
| 5874 |
function deltas (c1, c2, { space, hue = "shorter" } = {}) { |
| 5875 |
c1 = getColor(c1); |
| 5876 |
space ||= c1.space; |
| 5877 |
space = ColorSpace.get(space); |
| 5878 |
let spaceCoords = Object.values(space.coords); |
| 5879 |
|
| 5880 |
[c1, c2] = [c1, c2].map(c => to(c, space)); |
| 5881 |
let [coords1, coords2] = [c1, c2].map(c => c.coords); |
| 5882 |
|
| 5883 |
let coords = /** @type {[number, number, number]} */ ( |
| 5884 |
coords1.map((coord1, i) => { |
| 5885 |
let coordMeta = spaceCoords[i]; |
| 5886 |
let coord2 = coords2[i]; |
| 5887 |
|
| 5888 |
if (coordMeta.type === "angle") { |
| 5889 |
[coord1, coord2] = adjust(hue, [coord1, coord2]); |
| 5890 |
} |
| 5891 |
|
| 5892 |
return subtractCoords(coord1, coord2); |
| 5893 |
}) |
| 5894 |
); |
| 5895 |
|
| 5896 |
let alpha = subtractCoords(c1.alpha, c2.alpha); |
| 5897 |
|
| 5898 |
return { space: /** @type {ColorSpace} */ (space), coords, alpha }; |
| 5899 |
} |
| 5900 |
|
| 5901 |
function subtractCoords (c1, c2) { |
| 5902 |
if (isNone(c1) || isNone(c2)) { |
| 5903 |
return c1 === c2 ? null : 0; |
| 5904 |
} |
| 5905 |
|
| 5906 |
return c1 - c2; |
| 5907 |
} |
| 5908 |
|
| 5909 |
/** @import { ColorTypes } from "./types.js" */ |
| 5910 |
|
| 5911 |
/** |
| 5912 |
* @param {ColorTypes} color1 |
| 5913 |
* @param {ColorTypes} color2 |
| 5914 |
* @returns {boolean} |
| 5915 |
*/ |
| 5916 |
function equals (color1, color2) { |
| 5917 |
color1 = getColor(color1); |
| 5918 |
color2 = getColor(color2); |
| 5919 |
|
| 5920 |
return ( |
| 5921 |
color1.space === color2.space && |
| 5922 |
color1.alpha === color2.alpha && |
| 5923 |
color1.coords.every((c, i) => c === color2.coords[i]) |
| 5924 |
); |
| 5925 |
} |
| 5926 |
|
| 5927 |
/** |
| 5928 |
* Relative luminance |
| 5929 |
*/ |
| 5930 |
|
| 5931 |
/** @import { ColorTypes } from "./types.js" */ |
| 5932 |
|
| 5933 |
/** |
| 5934 |
* |
| 5935 |
* @param {ColorTypes} color |
| 5936 |
* @returns {number} |
| 5937 |
*/ |
| 5938 |
function getLuminance (color) { |
| 5939 |
// Assume getColor() is called on color in get() |
| 5940 |
return get(color, [XYZ_D65, "y"]); |
| 5941 |
} |
| 5942 |
|
| 5943 |
/** |
| 5944 |
* @param {ColorTypes} color |
| 5945 |
* @param {number | ((coord: number) => number)} value |
| 5946 |
*/ |
| 5947 |
function setLuminance (color, value) { |
| 5948 |
// Assume getColor() is called on color in set() |
| 5949 |
set(color, [XYZ_D65, "y"], value); |
| 5950 |
} |
| 5951 |
|
| 5952 |
/** |
| 5953 |
* @param {typeof import("./color.js").default} Color |
| 5954 |
*/ |
| 5955 |
function register$2 (Color) { |
| 5956 |
Object.defineProperty(Color.prototype, "luminance", { |
| 5957 |
get () { |
| 5958 |
return getLuminance(this); |
| 5959 |
}, |
| 5960 |
set (value) { |
| 5961 |
setLuminance(this, value); |
| 5962 |
}, |
| 5963 |
}); |
| 5964 |
} |
| 5965 |
|
| 5966 |
var luminance = /*#__PURE__*/Object.freeze({ |
| 5967 |
__proto__: null, |
| 5968 |
getLuminance: getLuminance, |
| 5969 |
register: register$2, |
| 5970 |
setLuminance: setLuminance |
| 5971 |
}); |
| 5972 |
|
| 5973 |
// WCAG 2.0 contrast https://www.w3.org/TR/WCAG20-TECHS/G18.html |
| 5974 |
// Simple contrast, with fixed 5% viewing flare contribution |
| 5975 |
// Symmetric, does not matter which is foreground and which is background |
| 5976 |
|
| 5977 |
|
| 5978 |
/** |
| 5979 |
* @param {import("../types.js").ColorTypes} color1 |
| 5980 |
* @param {import("../types.js").ColorTypes} color2 |
| 5981 |
* @returns {number} |
| 5982 |
*/ |
| 5983 |
function contrastWCAG21 (color1, color2) { |
| 5984 |
color1 = getColor(color1); |
| 5985 |
color2 = getColor(color2); |
| 5986 |
|
| 5987 |
let Y1 = Math.max(getLuminance(color1), 0); |
| 5988 |
let Y2 = Math.max(getLuminance(color2), 0); |
| 5989 |
|
| 5990 |
if (Y2 > Y1) { |
| 5991 |
[Y1, Y2] = [Y2, Y1]; |
| 5992 |
} |
| 5993 |
|
| 5994 |
return (Y1 + 0.05) / (Y2 + 0.05); |
| 5995 |
} |
| 5996 |
|
| 5997 |
// APCA 0.0.98G |
| 5998 |
// https://github.com/Myndex/apca-w3 |
| 5999 |
// see also https://github.com/w3c/silver/issues/643 |
| 6000 |
|
| 6001 |
|
| 6002 |
// exponents |
| 6003 |
const normBG = 0.56; |
| 6004 |
const normTXT = 0.57; |
| 6005 |
const revTXT = 0.62; |
| 6006 |
const revBG = 0.65; |
| 6007 |
|
| 6008 |
// clamps |
| 6009 |
const blkThrs = 0.022; |
| 6010 |
const blkClmp = 1.414; |
| 6011 |
const loClip = 0.1; |
| 6012 |
const deltaYmin = 0.0005; |
| 6013 |
|
| 6014 |
// scalers |
| 6015 |
// see https://github.com/w3c/silver/issues/645 |
| 6016 |
const scaleBoW = 1.14; |
| 6017 |
const loBoWoffset = 0.027; |
| 6018 |
const scaleWoB = 1.14; |
| 6019 |
|
| 6020 |
function fclamp (Y) { |
| 6021 |
if (Y >= blkThrs) { |
| 6022 |
return Y; |
| 6023 |
} |
| 6024 |
return Y + (blkThrs - Y) ** blkClmp; |
| 6025 |
} |
| 6026 |
|
| 6027 |
function linearize (val) { |
| 6028 |
let sign = val < 0 ? -1 : 1; |
| 6029 |
let abs = Math.abs(val); |
| 6030 |
return sign * Math.pow(abs, 2.4); |
| 6031 |
} |
| 6032 |
|
| 6033 |
/** |
| 6034 |
* Not symmetric, requires a foreground (text) color, and a background color |
| 6035 |
* @param {import("../types.js").ColorTypes} background |
| 6036 |
* @param {import("../types.js").ColorTypes} foreground |
| 6037 |
* @returns {number} |
| 6038 |
*/ |
| 6039 |
function contrastAPCA (background, foreground) { |
| 6040 |
foreground = getColor(foreground); |
| 6041 |
background = getColor(background); |
| 6042 |
|
| 6043 |
let S; |
| 6044 |
let C; |
| 6045 |
let Sapc; |
| 6046 |
|
| 6047 |
// Myndex as-published, assumes sRGB inputs |
| 6048 |
let R, G, B; |
| 6049 |
|
| 6050 |
foreground = to(foreground, "srgb"); |
| 6051 |
// Should these be clamped to in-gamut values? |
| 6052 |
|
| 6053 |
// Calculates "screen luminance" with non-standard simple gamma EOTF |
| 6054 |
// weights should be from CSS Color 4, not the ones here which are via Myndex and copied from Lindbloom |
| 6055 |
[R, G, B] = foreground.coords.map(c => { |
| 6056 |
return isNone(c) ? 0 : c; |
| 6057 |
}); |
| 6058 |
let lumTxt = linearize(R) * 0.2126729 + linearize(G) * 0.7151522 + linearize(B) * 0.072175; |
| 6059 |
|
| 6060 |
background = to(background, "srgb"); |
| 6061 |
[R, G, B] = background.coords.map(c => { |
| 6062 |
return isNone(c) ? 0 : c; |
| 6063 |
}); |
| 6064 |
let lumBg = linearize(R) * 0.2126729 + linearize(G) * 0.7151522 + linearize(B) * 0.072175; |
| 6065 |
|
| 6066 |
// toe clamping of very dark values to account for flare |
| 6067 |
let Ytxt = fclamp(lumTxt); |
| 6068 |
let Ybg = fclamp(lumBg); |
| 6069 |
|
| 6070 |
// are we "Black on White" (dark on light), or light on dark? |
| 6071 |
let BoW = Ybg > Ytxt; |
| 6072 |
|
| 6073 |
// why is this a delta, when Y is not perceptually uniform? |
| 6074 |
// Answer: it is a noise gate, see |
| 6075 |
// https://github.com/LeaVerou/color.js/issues/208 |
| 6076 |
if (Math.abs(Ybg - Ytxt) < deltaYmin) { |
| 6077 |
C = 0; |
| 6078 |
} |
| 6079 |
else { |
| 6080 |
if (BoW) { |
| 6081 |
// dark text on light background |
| 6082 |
S = Ybg ** normBG - Ytxt ** normTXT; |
| 6083 |
C = S * scaleBoW; |
| 6084 |
} |
| 6085 |
else { |
| 6086 |
// light text on dark background |
| 6087 |
S = Ybg ** revBG - Ytxt ** revTXT; |
| 6088 |
C = S * scaleWoB; |
| 6089 |
} |
| 6090 |
} |
| 6091 |
if (Math.abs(C) < loClip) { |
| 6092 |
Sapc = 0; |
| 6093 |
} |
| 6094 |
else if (C > 0) { |
| 6095 |
// not clear whether Woffset is loBoWoffset or loWoBoffset |
| 6096 |
// but they have the same value |
| 6097 |
Sapc = C - loBoWoffset; |
| 6098 |
} |
| 6099 |
else { |
| 6100 |
Sapc = C + loBoWoffset; |
| 6101 |
} |
| 6102 |
|
| 6103 |
return Sapc * 100; |
| 6104 |
} |
| 6105 |
|
| 6106 |
// Michelson luminance contrast |
| 6107 |
// the relation between the spread and the sum of the two luminances |
| 6108 |
// Symmetric, does not matter which is foreground and which is background |
| 6109 |
// No black level compensation for flare. |
| 6110 |
|
| 6111 |
|
| 6112 |
/** |
| 6113 |
* @param {import("../types.js").ColorTypes} color1 |
| 6114 |
* @param {import("../types.js").ColorTypes} color2 |
| 6115 |
* @returns {number} |
| 6116 |
*/ |
| 6117 |
function contrastMichelson (color1, color2) { |
| 6118 |
color1 = getColor(color1); |
| 6119 |
color2 = getColor(color2); |
| 6120 |
|
| 6121 |
let Y1 = Math.max(getLuminance(color1), 0); |
| 6122 |
let Y2 = Math.max(getLuminance(color2), 0); |
| 6123 |
|
| 6124 |
if (Y2 > Y1) { |
| 6125 |
[Y1, Y2] = [Y2, Y1]; |
| 6126 |
} |
| 6127 |
|
| 6128 |
let denom = Y1 + Y2; |
| 6129 |
return denom === 0 ? 0 : (Y1 - Y2) / denom; |
| 6130 |
} |
| 6131 |
|
| 6132 |
// Weber luminance contrast |
| 6133 |
// The difference between the two luminances divided by the lower luminance |
| 6134 |
// Symmetric, does not matter which is foreground and which is background |
| 6135 |
// No black level compensation for flare. |
| 6136 |
|
| 6137 |
|
| 6138 |
// the darkest sRGB color above black is #000001 and this produces |
| 6139 |
// a plain Weber contrast of ~45647. |
| 6140 |
// So, setting the divide-by-zero result at 50000 is a reasonable |
| 6141 |
// max clamp for the plain Weber |
| 6142 |
const max = 50000; |
| 6143 |
|
| 6144 |
/** |
| 6145 |
* @param {import("../types.js").ColorTypes} color1 |
| 6146 |
* @param {import("../types.js").ColorTypes} color2 |
| 6147 |
* @returns {number} |
| 6148 |
*/ |
| 6149 |
function contrastWeber (color1, color2) { |
| 6150 |
color1 = getColor(color1); |
| 6151 |
color2 = getColor(color2); |
| 6152 |
|
| 6153 |
let Y1 = Math.max(getLuminance(color1), 0); |
| 6154 |
let Y2 = Math.max(getLuminance(color2), 0); |
| 6155 |
|
| 6156 |
if (Y2 > Y1) { |
| 6157 |
[Y1, Y2] = [Y2, Y1]; |
| 6158 |
} |
| 6159 |
|
| 6160 |
return Y2 === 0 ? max : (Y1 - Y2) / Y2; |
| 6161 |
} |
| 6162 |
|
| 6163 |
// CIE Lightness difference, as used by Google Material Design |
| 6164 |
// Google HCT Tone is the same as CIE Lightness |
| 6165 |
// https://material.io/blog/science-of-color-design |
| 6166 |
|
| 6167 |
|
| 6168 |
/** |
| 6169 |
* @param {import("../types.js").ColorTypes} color1 |
| 6170 |
* @param {import("../types.js").ColorTypes} color2 |
| 6171 |
* @returns {number} |
| 6172 |
*/ |
| 6173 |
function contrastLstar (color1, color2) { |
| 6174 |
color1 = getColor(color1); |
| 6175 |
color2 = getColor(color2); |
| 6176 |
|
| 6177 |
let L1 = get(color1, [lab, "l"]); |
| 6178 |
let L2 = get(color2, [lab, "l"]); |
| 6179 |
|
| 6180 |
return Math.abs(L1 - L2); |
| 6181 |
} |
| 6182 |
|
| 6183 |
// κ * ε = 2^3 = 8 |
| 6184 |
const ε$3 = 216 / 24389; // 6^3/29^3 == (24/116)^3 |
| 6185 |
const ε3 = 24 / 116; |
| 6186 |
const κ$2 = 24389 / 27; // 29^3/3^3 |
| 6187 |
|
| 6188 |
let white$1 = WHITES.D65; |
| 6189 |
|
| 6190 |
var lab_d65 = new ColorSpace({ |
| 6191 |
id: "lab-d65", |
| 6192 |
name: "Lab D65", |
| 6193 |
coords: { |
| 6194 |
l: { |
| 6195 |
refRange: [0, 100], |
| 6196 |
name: "Lightness", |
| 6197 |
}, |
| 6198 |
a: { |
| 6199 |
refRange: [-125, 125], |
| 6200 |
}, |
| 6201 |
b: { |
| 6202 |
refRange: [-125, 125], |
| 6203 |
}, |
| 6204 |
}, |
| 6205 |
|
| 6206 |
// Assuming XYZ is relative to D65, convert to CIE Lab |
| 6207 |
// from CIE standard, which now defines these as a rational fraction |
| 6208 |
white: white$1, |
| 6209 |
|
| 6210 |
base: XYZ_D65, |
| 6211 |
// Convert D65-adapted XYZ to Lab |
| 6212 |
// CIE 15.3:2004 section 8.2.1.1 |
| 6213 |
fromBase (XYZ) { |
| 6214 |
// compute xyz, which is XYZ scaled relative to reference white |
| 6215 |
let xyz = XYZ.map((value, i) => value / white$1[i]); |
| 6216 |
|
| 6217 |
// now compute f |
| 6218 |
let f = xyz.map(value => (value > ε$3 ? Math.cbrt(value) : (κ$2 * value + 16) / 116)); |
| 6219 |
|
| 6220 |
return [ |
| 6221 |
116 * f[1] - 16, // L |
| 6222 |
500 * (f[0] - f[1]), // a |
| 6223 |
200 * (f[1] - f[2]), // b |
| 6224 |
]; |
| 6225 |
}, |
| 6226 |
// Convert Lab to D65-adapted XYZ |
| 6227 |
// Same result as CIE 15.3:2004 Appendix D although the derivation is different |
| 6228 |
// http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html |
| 6229 |
toBase (Lab) { |
| 6230 |
// compute f, starting with the luminance-related term |
| 6231 |
let f = []; |
| 6232 |
f[1] = (Lab[0] + 16) / 116; |
| 6233 |
f[0] = Lab[1] / 500 + f[1]; |
| 6234 |
f[2] = f[1] - Lab[2] / 200; |
| 6235 |
|
| 6236 |
// compute xyz |
| 6237 |
let xyz = [ |
| 6238 |
f[0] > ε3 ? Math.pow(f[0], 3) : (116 * f[0] - 16) / κ$2, |
| 6239 |
Lab[0] > 8 ? Math.pow((Lab[0] + 16) / 116, 3) : Lab[0] / κ$2, |
| 6240 |
f[2] > ε3 ? Math.pow(f[2], 3) : (116 * f[2] - 16) / κ$2, |
| 6241 |
]; |
| 6242 |
|
| 6243 |
// Compute XYZ by scaling xyz by reference white |
| 6244 |
return xyz.map((value, i) => value * white$1[i]); |
| 6245 |
}, |
| 6246 |
|
| 6247 |
formats: { |
| 6248 |
"lab-d65": { |
| 6249 |
coords: [ |
| 6250 |
"<number> | <percentage>", |
| 6251 |
"<number> | <percentage>", |
| 6252 |
"<number> | <percentage>", |
| 6253 |
], |
| 6254 |
}, |
| 6255 |
}, |
| 6256 |
}); |
| 6257 |
|
| 6258 |
// Delta Phi Star perceptual lightness contrast |
| 6259 |
// See https://github.com/Myndex/deltaphistar |
| 6260 |
// The (difference between two Lstars each raised to phi) raised to (1/phi) |
| 6261 |
// Symmetric, does not matter which is foreground and which is background |
| 6262 |
|
| 6263 |
|
| 6264 |
const phi = Math.pow(5, 0.5) * 0.5 + 0.5; // Math.phi can be used if Math.js |
| 6265 |
|
| 6266 |
/** |
| 6267 |
* @param {import("../types.js").ColorTypes} color1 |
| 6268 |
* @param {import("../types.js").ColorTypes} color2 |
| 6269 |
* @returns {number} |
| 6270 |
*/ |
| 6271 |
function contrastDeltaPhi (color1, color2) { |
| 6272 |
color1 = getColor(color1); |
| 6273 |
color2 = getColor(color2); |
| 6274 |
|
| 6275 |
let Lstr1 = get(color1, [lab_d65, "l"]); |
| 6276 |
let Lstr2 = get(color2, [lab_d65, "l"]); |
| 6277 |
|
| 6278 |
let deltaPhiStar = Math.abs(Math.pow(Lstr1, phi) - Math.pow(Lstr2, phi)); |
| 6279 |
|
| 6280 |
let contrast = Math.pow(deltaPhiStar, 1 / phi) * Math.SQRT2 - 40; |
| 6281 |
|
| 6282 |
return contrast < 7.5 ? 0.0 : contrast; |
| 6283 |
} |
| 6284 |
|
| 6285 |
/** @typedef {keyof typeof import("./index.js") extends `contrast${infer Alg}` ? Alg : string} Algorithms */ |
| 6286 |
|
| 6287 |
var contrastMethods = /*#__PURE__*/Object.freeze({ |
| 6288 |
__proto__: null, |
| 6289 |
contrastAPCA: contrastAPCA, |
| 6290 |
contrastDeltaPhi: contrastDeltaPhi, |
| 6291 |
contrastLstar: contrastLstar, |
| 6292 |
contrastMichelson: contrastMichelson, |
| 6293 |
contrastWCAG21: contrastWCAG21, |
| 6294 |
contrastWeber: contrastWeber |
| 6295 |
}); |
| 6296 |
|
| 6297 |
/** @import { ColorTypes } from "./types.js" */ |
| 6298 |
|
| 6299 |
// Type re-exports |
| 6300 |
/** @typedef {import("./types.js").Algorithms} Algorithms */ |
| 6301 |
|
| 6302 |
/** |
| 6303 |
* |
| 6304 |
* @param {ColorTypes} background |
| 6305 |
* @param {ColorTypes} foreground |
| 6306 |
* @param {Algorithms | ({ algorithm: Algorithms } & Record<string, any>)} o |
| 6307 |
* Algorithm to use as well as any other options to pass to the contrast function |
| 6308 |
* @returns {number} |
| 6309 |
* @throws {TypeError} Unknown or unspecified algorithm |
| 6310 |
*/ |
| 6311 |
function contrast (background, foreground, o) { |
| 6312 |
if (isString(o)) { |
| 6313 |
o = { algorithm: o }; |
| 6314 |
} |
| 6315 |
|
| 6316 |
let { algorithm, ...rest } = o || {}; |
| 6317 |
|
| 6318 |
if (!algorithm) { |
| 6319 |
let algorithms = Object.keys(contrastMethods) |
| 6320 |
.map(a => a.replace(/^contrast/, "")) |
| 6321 |
.join(", "); |
| 6322 |
throw new TypeError( |
| 6323 |
`contrast() function needs a contrast algorithm. Please specify one of: ${algorithms}`, |
| 6324 |
); |
| 6325 |
} |
| 6326 |
|
| 6327 |
background = getColor(background); |
| 6328 |
foreground = getColor(foreground); |
| 6329 |
|
| 6330 |
for (let a in contrastMethods) { |
| 6331 |
if ("contrast" + algorithm.toLowerCase() === a.toLowerCase()) { |
| 6332 |
return contrastMethods[a](background, foreground, rest); |
| 6333 |
} |
| 6334 |
} |
| 6335 |
|
| 6336 |
throw new TypeError(`Unknown contrast algorithm: ${algorithm}`); |
| 6337 |
} |
| 6338 |
|
| 6339 |
/** @import Color, { ColorTypes } from "./color.js" */ |
| 6340 |
|
| 6341 |
// Chromaticity coordinates |
| 6342 |
/** |
| 6343 |
* @param {ColorTypes} color |
| 6344 |
* @returns {[number, number]} |
| 6345 |
*/ |
| 6346 |
function uv (color) { |
| 6347 |
// Assumes getAll() calls getColor() on color |
| 6348 |
let [X, Y, Z] = getAll(color, XYZ_D65); |
| 6349 |
let denom = X + 15 * Y + 3 * Z; |
| 6350 |
return [(4 * X) / denom, (9 * Y) / denom]; |
| 6351 |
} |
| 6352 |
|
| 6353 |
/** |
| 6354 |
* @param {ColorTypes} color |
| 6355 |
* @returns {[number, number]} |
| 6356 |
*/ |
| 6357 |
function xy (color) { |
| 6358 |
// Assumes getAll() calls getColor() on color |
| 6359 |
let [X, Y, Z] = getAll(color, XYZ_D65); |
| 6360 |
let sum = X + Y + Z; |
| 6361 |
return [X / sum, Y / sum]; |
| 6362 |
} |
| 6363 |
|
| 6364 |
/** |
| 6365 |
* @param {typeof Color} Color |
| 6366 |
*/ |
| 6367 |
function register$1 (Color) { |
| 6368 |
// no setters, as lightness information is lost |
| 6369 |
// when converting color to chromaticity |
| 6370 |
Object.defineProperty(Color.prototype, "uv", { |
| 6371 |
get () { |
| 6372 |
return uv(this); |
| 6373 |
}, |
| 6374 |
}); |
| 6375 |
|
| 6376 |
Object.defineProperty(Color.prototype, "xy", { |
| 6377 |
get () { |
| 6378 |
return xy(this); |
| 6379 |
}, |
| 6380 |
}); |
| 6381 |
} |
| 6382 |
|
| 6383 |
var chromaticity = /*#__PURE__*/Object.freeze({ |
| 6384 |
__proto__: null, |
| 6385 |
register: register$1, |
| 6386 |
uv: uv, |
| 6387 |
xy: xy |
| 6388 |
}); |
| 6389 |
|
| 6390 |
/** @import { ColorTypes } from "./types.js" */ |
| 6391 |
|
| 6392 |
// Type re-exports |
| 6393 |
/** @typedef {import("./types.js").Methods} Methods */ |
| 6394 |
|
| 6395 |
/** |
| 6396 |
* |
| 6397 |
* @param {ColorTypes} c1 |
| 6398 |
* @param {ColorTypes} c2 |
| 6399 |
* @param {Methods | ({ method?: Methods | undefined } & Record<string, any>)} [o] |
| 6400 |
* deltaE method to use as well as any other options to pass to the deltaE function |
| 6401 |
* @returns {number} |
| 6402 |
* @throws {TypeError} Unknown or unspecified method |
| 6403 |
*/ |
| 6404 |
function deltaE (c1, c2, o = {}) { |
| 6405 |
if (isString(o)) { |
| 6406 |
o = { method: o }; |
| 6407 |
} |
| 6408 |
|
| 6409 |
let { method = defaults.deltaE, ...rest } = o; |
| 6410 |
|
| 6411 |
for (let m in deltaEMethods) { |
| 6412 |
if ("deltae" + method.toLowerCase() === m.toLowerCase()) { |
| 6413 |
return deltaEMethods[m](c1, c2, rest); |
| 6414 |
} |
| 6415 |
} |
| 6416 |
|
| 6417 |
throw new TypeError(`Unknown deltaE method: ${method}`); |
| 6418 |
} |
| 6419 |
|
| 6420 |
/** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */ |
| 6421 |
|
| 6422 |
/** |
| 6423 |
* @param {ColorTypes} color |
| 6424 |
* @param {number} amount |
| 6425 |
* @returns {PlainColorObject} |
| 6426 |
*/ |
| 6427 |
function lighten (color, amount = 0.25) { |
| 6428 |
let space = ColorSpace.get("oklch", "lch"); |
| 6429 |
let /** @type {Ref} */ lightness = [space, "l"]; |
| 6430 |
return set(color, lightness, l => l * (1 + amount)); |
| 6431 |
} |
| 6432 |
|
| 6433 |
/** |
| 6434 |
* @param {ColorTypes} color |
| 6435 |
* @param {number} amount |
| 6436 |
* @returns {PlainColorObject} |
| 6437 |
*/ |
| 6438 |
function darken (color, amount = 0.25) { |
| 6439 |
let space = ColorSpace.get("oklch", "lch"); |
| 6440 |
let /** @type {Ref} */ lightness = [space, "l"]; |
| 6441 |
return set(color, lightness, l => l * (1 - amount)); |
| 6442 |
} |
| 6443 |
|
| 6444 |
/** @type {"color"} */ |
| 6445 |
lighten.returns = "color"; |
| 6446 |
|
| 6447 |
/** @type {"color"} */ |
| 6448 |
darken.returns = "color"; |
| 6449 |
|
| 6450 |
var variations = /*#__PURE__*/Object.freeze({ |
| 6451 |
__proto__: null, |
| 6452 |
darken: darken, |
| 6453 |
lighten: lighten |
| 6454 |
}); |
| 6455 |
|
| 6456 |
/** |
| 6457 |
* Functions related to color interpolation |
| 6458 |
*/ |
| 6459 |
|
| 6460 |
/** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */ |
| 6461 |
|
| 6462 |
// Type re-exports |
| 6463 |
/** @typedef {import("./types.js").MixOptions} MixOptions */ |
| 6464 |
/** @typedef {import("./types.js").Range} Range */ |
| 6465 |
/** @typedef {import("./types.js").RangeOptions} RangeOptions */ |
| 6466 |
/** @typedef {import("./types.js").StepsOptions} StepsOptions */ |
| 6467 |
|
| 6468 |
/** |
| 6469 |
* Return an intermediate color between two colors |
| 6470 |
* @overload |
| 6471 |
* @param {ColorTypes} c1 |
| 6472 |
* @param {ColorTypes} c2 |
| 6473 |
* @param {MixOptions} [options] |
| 6474 |
* @returns {PlainColorObject} |
| 6475 |
*/ |
| 6476 |
/** |
| 6477 |
* @overload |
| 6478 |
* @param {ColorTypes} c1 |
| 6479 |
* @param {ColorTypes} c2 |
| 6480 |
* @param {number} [p=0.5] |
| 6481 |
* @param {MixOptions} [options] |
| 6482 |
* @returns {PlainColorObject} |
| 6483 |
*/ |
| 6484 |
function mix (c1, c2, p, o = {}) { |
| 6485 |
[c1, c2] = [getColor(c1), getColor(c2)]; |
| 6486 |
|
| 6487 |
if (type(p) === "object") { |
| 6488 |
[p, o] = [0.5, p]; |
| 6489 |
} |
| 6490 |
|
| 6491 |
let r = range(c1, c2, o); |
| 6492 |
return r(p ?? 0.5); // why not give p a default value like we do for options? Overloading doesn't work, and TS complains |
| 6493 |
} |
| 6494 |
|
| 6495 |
/** |
| 6496 |
* Get an array of discrete steps |
| 6497 |
* @overload |
| 6498 |
* @param {ColorTypes} c1 |
| 6499 |
* @param {ColorTypes} c2 |
| 6500 |
* @param {StepsOptions} [options] |
| 6501 |
* @returns {PlainColorObject[]} |
| 6502 |
*/ |
| 6503 |
/** |
| 6504 |
* @overload |
| 6505 |
* @param {Range} range |
| 6506 |
* @param {StepsOptions} [options] |
| 6507 |
* @returns {PlainColorObject[]} |
| 6508 |
*/ |
| 6509 |
function steps (c1, c2, options = {}) { |
| 6510 |
let colorRange; |
| 6511 |
|
| 6512 |
if (isRange(c1)) { |
| 6513 |
// Tweaking existing range |
| 6514 |
[colorRange, options] = [c1, c2]; |
| 6515 |
[c1, c2] = colorRange.rangeArgs.colors; |
| 6516 |
} |
| 6517 |
|
| 6518 |
let { maxDeltaE, deltaEMethod, steps = 2, maxSteps = 1000, ...rangeOptions } = options; |
| 6519 |
|
| 6520 |
if (!colorRange) { |
| 6521 |
[c1, c2] = [getColor(c1), getColor(c2)]; |
| 6522 |
colorRange = range(c1, c2, rangeOptions); |
| 6523 |
} |
| 6524 |
|
| 6525 |
let totalDelta = deltaE(c1, c2, deltaEMethod); |
| 6526 |
let actualSteps = |
| 6527 |
maxDeltaE > 0 ? Math.max(steps, Math.ceil(totalDelta / maxDeltaE) + 1) : steps; |
| 6528 |
let ret = []; |
| 6529 |
|
| 6530 |
if (maxSteps !== undefined) { |
| 6531 |
actualSteps = Math.min(actualSteps, maxSteps); |
| 6532 |
} |
| 6533 |
|
| 6534 |
if (actualSteps === 1) { |
| 6535 |
ret = [{ p: 0.5, color: colorRange(0.5) }]; |
| 6536 |
} |
| 6537 |
else { |
| 6538 |
let step = 1 / (actualSteps - 1); |
| 6539 |
ret = Array.from({ length: actualSteps }, (_, i) => { |
| 6540 |
let p = i * step; |
| 6541 |
return { p, color: colorRange(p) }; |
| 6542 |
}); |
| 6543 |
} |
| 6544 |
|
| 6545 |
if (maxDeltaE > 0) { |
| 6546 |
// Iterate over all stops and find max deltaE |
| 6547 |
let maxDelta = ret.reduce((acc, cur, i) => { |
| 6548 |
if (i === 0) { |
| 6549 |
return 0; |
| 6550 |
} |
| 6551 |
|
| 6552 |
let ΔΕ = deltaE(cur.color, ret[i - 1].color, deltaEMethod); |
| 6553 |
return Math.max(acc, ΔΕ); |
| 6554 |
}, 0); |
| 6555 |
|
| 6556 |
while (maxDelta > maxDeltaE) { |
| 6557 |
// Insert intermediate stops and measure maxDelta again |
| 6558 |
// We need to do this for all pairs, otherwise the midpoint shifts |
| 6559 |
maxDelta = 0; |
| 6560 |
|
| 6561 |
for (let i = 1; i < ret.length && ret.length < maxSteps; i++) { |
| 6562 |
let prev = ret[i - 1]; |
| 6563 |
let cur = ret[i]; |
| 6564 |
|
| 6565 |
let p = (cur.p + prev.p) / 2; |
| 6566 |
let color = colorRange(p); |
| 6567 |
maxDelta = Math.max( |
| 6568 |
maxDelta, |
| 6569 |
deltaE(color, prev.color, deltaEMethod), |
| 6570 |
deltaE(color, cur.color, deltaEMethod), |
| 6571 |
); |
| 6572 |
ret.splice(i, 0, { p, color: colorRange(p) }); |
| 6573 |
i++; |
| 6574 |
} |
| 6575 |
} |
| 6576 |
} |
| 6577 |
|
| 6578 |
ret = ret.map(a => a.color); |
| 6579 |
|
| 6580 |
return ret; |
| 6581 |
} |
| 6582 |
|
| 6583 |
/** |
| 6584 |
* Creates a function that accepts a number and returns a color. |
| 6585 |
* For numbers in the range 0 to 1, the function interpolates; |
| 6586 |
* for numbers outside that range, the function extrapolates |
| 6587 |
* (and thus may not return the results you expect) |
| 6588 |
* @overload |
| 6589 |
* @param {Range} range |
| 6590 |
* @param {RangeOptions} [options] |
| 6591 |
* @returns {Range} |
| 6592 |
*/ |
| 6593 |
/** |
| 6594 |
* @overload |
| 6595 |
* @param {ColorTypes} color1 |
| 6596 |
* @param {ColorTypes} color2 |
| 6597 |
* @param {RangeOptions & Record<string, any>} [options] |
| 6598 |
* @returns {Range} |
| 6599 |
*/ |
| 6600 |
function range (color1, color2, options = {}) { |
| 6601 |
if (isRange(color1)) { |
| 6602 |
// Tweaking existing range |
| 6603 |
let [r, options] = [color1, color2]; |
| 6604 |
|
| 6605 |
return range(...r.rangeArgs.colors, { ...r.rangeArgs.options, ...options }); |
| 6606 |
} |
| 6607 |
|
| 6608 |
let { space, outputSpace, progression, premultiplied } = options; |
| 6609 |
|
| 6610 |
color1 = getColor(color1); |
| 6611 |
color2 = getColor(color2); |
| 6612 |
|
| 6613 |
// Make sure we're working on copies of these colors |
| 6614 |
color1 = clone(color1); |
| 6615 |
color2 = clone(color2); |
| 6616 |
|
| 6617 |
let rangeArgs = { colors: [color1, color2], options }; |
| 6618 |
|
| 6619 |
if (space) { |
| 6620 |
space = ColorSpace.get(space); |
| 6621 |
} |
| 6622 |
else { |
| 6623 |
space = ColorSpace.registry[defaults.interpolationSpace] || color1.space; |
| 6624 |
} |
| 6625 |
|
| 6626 |
outputSpace = outputSpace ? ColorSpace.get(outputSpace) : space; |
| 6627 |
|
| 6628 |
color1 = to(color1, space); |
| 6629 |
color2 = to(color2, space); |
| 6630 |
|
| 6631 |
// Gamut map to avoid areas of flat color |
| 6632 |
color1 = toGamut(color1); |
| 6633 |
color2 = toGamut(color2); |
| 6634 |
|
| 6635 |
// The hue coordinate is not always called "h" (e.g. it's "hz" in Jzczhz) |
| 6636 |
let hueId = space.hueId; |
| 6637 |
let hueIndex = space.hueIndex; |
| 6638 |
|
| 6639 |
// Handle hue interpolation |
| 6640 |
// See https://github.com/w3c/csswg-drafts/issues/4735#issuecomment-635741840 |
| 6641 |
if (hueId) { |
| 6642 |
let arc = (options.hue = options.hue || "shorter"); |
| 6643 |
|
| 6644 |
let /** @type {Ref} */ hue = [space, hueId]; |
| 6645 |
let [θ1, θ2] = [get(color1, hue), get(color2, hue)]; |
| 6646 |
// Undefined hues must be evaluated before hue fix-up to properly |
| 6647 |
// calculate hue arcs between undefined and defined hues. |
| 6648 |
// See https://github.com/w3c/csswg-drafts/issues/9436#issuecomment-1746957545 |
| 6649 |
if (isNone(θ1) && !isNone(θ2)) { |
| 6650 |
θ1 = θ2; |
| 6651 |
} |
| 6652 |
else if (isNone(θ2) && !isNone(θ1)) { |
| 6653 |
θ2 = θ1; |
| 6654 |
} |
| 6655 |
[θ1, θ2] = adjust(arc, [θ1, θ2]); |
| 6656 |
set(color1, hue, θ1); |
| 6657 |
set(color2, hue, θ2); |
| 6658 |
} |
| 6659 |
|
| 6660 |
// An undefined alpha takes the other color's alpha, and premultiplication must use |
| 6661 |
// that carried forward value, rather than the zero it would otherwise be treated as. |
| 6662 |
// If both alphas are undefined, they stay that way, and no premultiplication happens. |
| 6663 |
// See https://drafts.csswg.org/css-color-4/#interpolation-missing |
| 6664 |
if (isNone(color1.alpha) && !isNone(color2.alpha)) { |
| 6665 |
color1.alpha = color2.alpha; |
| 6666 |
} |
| 6667 |
else if (isNone(color2.alpha) && !isNone(color1.alpha)) { |
| 6668 |
color2.alpha = color1.alpha; |
| 6669 |
} |
| 6670 |
|
| 6671 |
if (premultiplied) { |
| 6672 |
color1.coords = premultiply(color1.coords, color1.alpha, hueIndex); |
| 6673 |
color2.coords = premultiply(color2.coords, color2.alpha, hueIndex); |
| 6674 |
} |
| 6675 |
|
| 6676 |
return Object.assign( |
| 6677 |
p => { |
| 6678 |
p = progression ? progression(p) : p; |
| 6679 |
let coords = color1.coords.map((start, i) => { |
| 6680 |
let end = color2.coords[i]; |
| 6681 |
return interpolate(start, end, p); |
| 6682 |
}); |
| 6683 |
|
| 6684 |
let alpha = interpolate(color1.alpha, color2.alpha, p); |
| 6685 |
let ret = { space, coords, alpha }; |
| 6686 |
|
| 6687 |
if (premultiplied) { |
| 6688 |
// Undo premultiplication, again leaving any hue angle untouched |
| 6689 |
ret.coords = premultiply(ret.coords, alpha, hueIndex, true); |
| 6690 |
} |
| 6691 |
|
| 6692 |
if (outputSpace !== space) { |
| 6693 |
ret = to(ret, outputSpace); |
| 6694 |
} |
| 6695 |
|
| 6696 |
return ret; |
| 6697 |
}, |
| 6698 |
{ |
| 6699 |
rangeArgs, |
| 6700 |
}, |
| 6701 |
); |
| 6702 |
} |
| 6703 |
|
| 6704 |
/** |
| 6705 |
* Premultiply a color's coordinates by its alpha, or undo premultiplication by dividing by it. |
| 6706 |
* Per CSS Color 4, the hue angle of a polar space is never premultiplied, |
| 6707 |
* `none` components stay `none`, a `none` alpha means no (un)premultiplication happens at all, |
| 6708 |
* and un-premultiplying by a zero alpha leaves the coords as they are, rather than dividing by zero. |
| 6709 |
* See https://drafts.csswg.org/css-color-4/#interpolation-alpha |
| 6710 |
* @param {(number | null)[]} coords |
| 6711 |
* @param {number | null} alpha |
| 6712 |
* @param {number} hueIndex - Index of the hue coordinate, or -1 if the space has none |
| 6713 |
* @param {boolean} [undo=false] - Divide by alpha instead of multiplying by it |
| 6714 |
* @returns {[number, number, number]} |
| 6715 |
*/ |
| 6716 |
function premultiply (coords, alpha, hueIndex, undo = false) { |
| 6717 |
if (isNone(alpha) || (undo && alpha === 0)) { |
| 6718 |
// The (un-)premultiplied value is the value itself |
| 6719 |
return /** @type {[number, number, number]} */ (coords); |
| 6720 |
} |
| 6721 |
|
| 6722 |
return /** @type {[number, number, number]} */ ( |
| 6723 |
coords.map((c, i) => { |
| 6724 |
if (i === hueIndex || isNone(c)) { |
| 6725 |
return c; |
| 6726 |
} |
| 6727 |
|
| 6728 |
return undo ? c / alpha : c * alpha; |
| 6729 |
}) |
| 6730 |
); |
| 6731 |
} |
| 6732 |
|
| 6733 |
/** |
| 6734 |
* @param {any} val |
| 6735 |
* @returns {val is Range} |
| 6736 |
*/ |
| 6737 |
function isRange (val) { |
| 6738 |
return type(val) === "function" && !!val.rangeArgs; |
| 6739 |
} |
| 6740 |
|
| 6741 |
defaults.interpolationSpace = "lab"; |
| 6742 |
|
| 6743 |
/** |
| 6744 |
* @param {typeof import("./color.js").default} Color |
| 6745 |
*/ |
| 6746 |
function register (Color) { |
| 6747 |
Color.defineFunction("mix", mix, { returns: "color" }); |
| 6748 |
Color.defineFunction("range", range, { returns: "function<color>" }); |
| 6749 |
Color.defineFunction("steps", steps, { returns: "array<color>" }); |
| 6750 |
} |
| 6751 |
|
| 6752 |
var interpolation = /*#__PURE__*/Object.freeze({ |
| 6753 |
__proto__: null, |
| 6754 |
isRange: isRange, |
| 6755 |
mix: mix, |
| 6756 |
range: range, |
| 6757 |
register: register, |
| 6758 |
steps: steps |
| 6759 |
}); |
| 6760 |
|
| 6761 |
var HSL = new ColorSpace({ |
| 6762 |
id: "hsl", |
| 6763 |
name: "HSL", |
| 6764 |
coords: { |
| 6765 |
h: { |
| 6766 |
refRange: [0, 360], |
| 6767 |
type: "angle", |
| 6768 |
name: "Hue", |
| 6769 |
}, |
| 6770 |
s: { |
| 6771 |
range: [0, 100], |
| 6772 |
name: "Saturation", |
| 6773 |
}, |
| 6774 |
l: { |
| 6775 |
range: [0, 100], |
| 6776 |
name: "Lightness", |
| 6777 |
}, |
| 6778 |
}, |
| 6779 |
|
| 6780 |
base: sRGB, |
| 6781 |
rgbGamut: sRGB, |
| 6782 |
|
| 6783 |
// Adapted from https://drafts.csswg.org/css-color-4/better-rgbToHsl.js |
| 6784 |
fromBase: rgb => { |
| 6785 |
let max = Math.max(...rgb); |
| 6786 |
let min = Math.min(...rgb); |
| 6787 |
let [r, g, b] = rgb; |
| 6788 |
let [h, s, l] = [null, 0, (min + max) / 2]; |
| 6789 |
let d = max - min; |
| 6790 |
|
| 6791 |
if (d !== 0) { |
| 6792 |
s = l === 0 || l === 1 ? 0 : (max - l) / Math.min(l, 1 - l); |
| 6793 |
|
| 6794 |
switch (max) { |
| 6795 |
case r: |
| 6796 |
h = (g - b) / d + (g < b ? 6 : 0); |
| 6797 |
break; |
| 6798 |
case g: |
| 6799 |
h = (b - r) / d + 2; |
| 6800 |
break; |
| 6801 |
case b: |
| 6802 |
h = (r - g) / d + 4; |
| 6803 |
} |
| 6804 |
|
| 6805 |
h = h * 60; |
| 6806 |
} |
| 6807 |
|
| 6808 |
// Very out of gamut colors can produce negative saturation |
| 6809 |
// If so, just rotate the hue by 180 and use a positive saturation |
| 6810 |
// see https://github.com/w3c/csswg-drafts/issues/9222 |
| 6811 |
if (s < 0) { |
| 6812 |
h += 180; |
| 6813 |
s = Math.abs(s); |
| 6814 |
} |
| 6815 |
|
| 6816 |
if (h >= 360) { |
| 6817 |
h -= 360; |
| 6818 |
} |
| 6819 |
|
| 6820 |
return [h, s * 100, l * 100]; |
| 6821 |
}, |
| 6822 |
|
| 6823 |
// Adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB_alternative |
| 6824 |
toBase: hsl => { |
| 6825 |
let [h, s, l] = hsl; |
| 6826 |
h = h % 360; |
| 6827 |
|
| 6828 |
if (h < 0) { |
| 6829 |
h += 360; |
| 6830 |
} |
| 6831 |
|
| 6832 |
s /= 100; |
| 6833 |
l /= 100; |
| 6834 |
|
| 6835 |
function f (n) { |
| 6836 |
let k = (n + h / 30) % 12; |
| 6837 |
let a = s * Math.min(l, 1 - l); |
| 6838 |
return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1)); |
| 6839 |
} |
| 6840 |
|
| 6841 |
return [f(0), f(8), f(4)]; |
| 6842 |
}, |
| 6843 |
|
| 6844 |
formats: { |
| 6845 |
hsl: { |
| 6846 |
coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"], |
| 6847 |
}, |
| 6848 |
hsla: { |
| 6849 |
coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"], |
| 6850 |
commas: true, |
| 6851 |
alpha: true, |
| 6852 |
}, |
| 6853 |
} |
| 6854 |
}); |
| 6855 |
|
| 6856 |
var hslP3 = new ColorSpace({ |
| 6857 |
id: "hsl-p3", |
| 6858 |
cssId: "--hsl-p3", |
| 6859 |
name: "HSL P3", |
| 6860 |
coords: { |
| 6861 |
h: { |
| 6862 |
refRange: [0, 360], |
| 6863 |
type: "angle", |
| 6864 |
name: "Hue", |
| 6865 |
}, |
| 6866 |
s: { |
| 6867 |
range: [0, 100], |
| 6868 |
name: "Saturation", |
| 6869 |
}, |
| 6870 |
l: { |
| 6871 |
range: [0, 100], |
| 6872 |
name: "Lightness", |
| 6873 |
}, |
| 6874 |
}, |
| 6875 |
|
| 6876 |
base: P3, |
| 6877 |
rgbGamut: P3, |
| 6878 |
fromBase: HSL.fromBase, |
| 6879 |
toBase: HSL.toBase, |
| 6880 |
}); |
| 6881 |
|
| 6882 |
var hslRec2020 = new ColorSpace({ |
| 6883 |
id: "hsl-rec2020", |
| 6884 |
cssId: "--hsl-rec2020", |
| 6885 |
name: "HSL Rec.2020", |
| 6886 |
coords: { |
| 6887 |
h: { |
| 6888 |
refRange: [0, 360], |
| 6889 |
type: "angle", |
| 6890 |
name: "Hue", |
| 6891 |
}, |
| 6892 |
s: { |
| 6893 |
range: [0, 100], |
| 6894 |
name: "Saturation", |
| 6895 |
}, |
| 6896 |
l: { |
| 6897 |
range: [0, 100], |
| 6898 |
name: "Lightness", |
| 6899 |
}, |
| 6900 |
}, |
| 6901 |
|
| 6902 |
base: REC2020, |
| 6903 |
rgbGamut: REC2020, |
| 6904 |
fromBase: HSL.fromBase, |
| 6905 |
toBase: HSL.toBase, |
| 6906 |
}); |
| 6907 |
|
| 6908 |
// Note that, like HSL, calculations are done directly on |
| 6909 |
// gamma-corrected sRGB values rather than linearising them first. |
| 6910 |
|
| 6911 |
var HSV = new ColorSpace({ |
| 6912 |
id: "hsv", |
| 6913 |
name: "HSV", |
| 6914 |
coords: { |
| 6915 |
h: { |
| 6916 |
refRange: [0, 360], |
| 6917 |
type: "angle", |
| 6918 |
name: "Hue", |
| 6919 |
}, |
| 6920 |
s: { |
| 6921 |
range: [0, 100], |
| 6922 |
name: "Saturation", |
| 6923 |
}, |
| 6924 |
v: { |
| 6925 |
range: [0, 100], |
| 6926 |
name: "Value", |
| 6927 |
}, |
| 6928 |
}, |
| 6929 |
|
| 6930 |
base: sRGB, |
| 6931 |
rgbGamut: sRGB, |
| 6932 |
// https://en.wikipedia.org/wiki/HSL_and_HSV#Formal_derivation |
| 6933 |
fromBase (rgb) { |
| 6934 |
let max = Math.max(...rgb); |
| 6935 |
let min = Math.min(...rgb); |
| 6936 |
let [r, g, b] = rgb; |
| 6937 |
let [h, s, v] = [null, 0, max]; |
| 6938 |
let d = max - min; |
| 6939 |
|
| 6940 |
if (d !== 0) { |
| 6941 |
switch (max) { |
| 6942 |
case r: |
| 6943 |
h = (g - b) / d + (g < b ? 6 : 0); |
| 6944 |
break; |
| 6945 |
case g: |
| 6946 |
h = (b - r) / d + 2; |
| 6947 |
break; |
| 6948 |
case b: |
| 6949 |
h = (r - g) / d + 4; |
| 6950 |
} |
| 6951 |
|
| 6952 |
h = h * 60; |
| 6953 |
} |
| 6954 |
|
| 6955 |
if (v) { |
| 6956 |
s = d / v; |
| 6957 |
} |
| 6958 |
|
| 6959 |
if (h >= 360) { |
| 6960 |
h -= 360; |
| 6961 |
} |
| 6962 |
|
| 6963 |
return [h, s * 100, v * 100]; |
| 6964 |
}, |
| 6965 |
// Adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_RGB_alternative |
| 6966 |
toBase (hsv) { |
| 6967 |
let [h, s, v] = hsv; |
| 6968 |
h = h % 360; |
| 6969 |
|
| 6970 |
if (h < 0) { |
| 6971 |
h += 360; |
| 6972 |
} |
| 6973 |
|
| 6974 |
s /= 100; |
| 6975 |
v /= 100; |
| 6976 |
|
| 6977 |
function f (n) { |
| 6978 |
let k = (n + h / 60) % 6; |
| 6979 |
return v - v * s * Math.max(0, Math.min(k, 4 - k, 1)); |
| 6980 |
} |
| 6981 |
|
| 6982 |
return [f(5), f(3), f(1)]; |
| 6983 |
}, |
| 6984 |
|
| 6985 |
formats: { |
| 6986 |
color: { |
| 6987 |
id: "--hsv", |
| 6988 |
coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"], |
| 6989 |
}, |
| 6990 |
}, |
| 6991 |
}); |
| 6992 |
|
| 6993 |
// The Hue, Whiteness Blackness (HWB) colorspace |
| 6994 |
// See https://drafts.csswg.org/css-color-4/#the-hwb-notation |
| 6995 |
// Note that, like HSL, calculations are done directly on |
| 6996 |
// gamma-corrected sRGB values rather than linearising them first. |
| 6997 |
|
| 6998 |
var hwb = new ColorSpace({ |
| 6999 |
id: "hwb", |
| 7000 |
name: "HWB", |
| 7001 |
coords: { |
| 7002 |
h: { |
| 7003 |
refRange: [0, 360], |
| 7004 |
type: "angle", |
| 7005 |
name: "Hue", |
| 7006 |
}, |
| 7007 |
w: { |
| 7008 |
range: [0, 100], |
| 7009 |
name: "Whiteness", |
| 7010 |
}, |
| 7011 |
b: { |
| 7012 |
range: [0, 100], |
| 7013 |
name: "Blackness", |
| 7014 |
}, |
| 7015 |
}, |
| 7016 |
|
| 7017 |
base: HSV, |
| 7018 |
rgbGamut: sRGB, |
| 7019 |
fromBase (hsv) { |
| 7020 |
let [h, s, v] = hsv; |
| 7021 |
|
| 7022 |
return [h, (v * (100 - s)) / 100, 100 - v]; |
| 7023 |
}, |
| 7024 |
toBase (hwb) { |
| 7025 |
let [h, w, b] = hwb; |
| 7026 |
|
| 7027 |
// Now convert percentages to [0..1] |
| 7028 |
w /= 100; |
| 7029 |
b /= 100; |
| 7030 |
|
| 7031 |
// Achromatic check (white plus black >= 1) |
| 7032 |
let sum = w + b; |
| 7033 |
if (sum >= 1) { |
| 7034 |
let gray = w / sum; |
| 7035 |
return [h, 0, gray * 100]; |
| 7036 |
} |
| 7037 |
|
| 7038 |
let v = 1 - b; |
| 7039 |
let s = v === 0 ? 0 : 1 - w / v; |
| 7040 |
return [h, s * 100, v * 100]; |
| 7041 |
}, |
| 7042 |
|
| 7043 |
formats: { |
| 7044 |
hwb: { |
| 7045 |
coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"], |
| 7046 |
}, |
| 7047 |
}, |
| 7048 |
}); |
| 7049 |
|
| 7050 |
/** @import { Matrix3x3 } from "../types.js" */ |
| 7051 |
|
| 7052 |
// convert an array of linear-light a98-rgb values to CIE XYZ |
| 7053 |
// http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html |
| 7054 |
// has greater numerical precision than section 4.3.5.3 of |
| 7055 |
// https://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf |
| 7056 |
// but the values below were calculated from first principles |
| 7057 |
// from the chromaticity coordinates of R G B W |
| 7058 |
|
| 7059 |
/** |
| 7060 |
* Matrices used by this color space, also available as `A98RGB_Linear.M` |
| 7061 |
* @type {Record<string, Matrix3x3>} |
| 7062 |
*/ |
| 7063 |
// prettier-ignore |
| 7064 |
const M$5 = { |
| 7065 |
toXYZ: [ |
| 7066 |
[ 0.5766690429101305, 0.1855582379065463, 0.1882286462349947 ], |
| 7067 |
[ 0.29734497525053605, 0.6273635662554661, 0.07529145849399788 ], |
| 7068 |
[ 0.02703136138641234, 0.07068885253582723, 0.9913375368376388 ], |
| 7069 |
], |
| 7070 |
fromXYZ: [ |
| 7071 |
[ 2.0415879038107465, -0.5650069742788596, -0.34473135077832956 ], |
| 7072 |
[ -0.9692436362808795, 1.8759675015077202, 0.04155505740717557 ], |
| 7073 |
[ 0.013444280632031142, -0.11836239223101838, 1.0151749943912054 ], |
| 7074 |
], |
| 7075 |
}; |
| 7076 |
|
| 7077 |
var A98Linear = new RGBColorSpace({ |
| 7078 |
id: "a98rgb-linear", |
| 7079 |
cssId: "--a98-rgb-linear", |
| 7080 |
name: "Linear Adobe® 98 RGB compatible", |
| 7081 |
white: "D65", |
| 7082 |
M: M$5, |
| 7083 |
}); |
| 7084 |
|
| 7085 |
var a98rgb = new RGBColorSpace({ |
| 7086 |
id: "a98rgb", |
| 7087 |
cssId: "a98-rgb", |
| 7088 |
name: "Adobe® 98 RGB compatible", |
| 7089 |
base: A98Linear, |
| 7090 |
linearGamut: A98Linear, |
| 7091 |
toBase: RGB => RGB.map(val => Math.pow(Math.abs(val), 563 / 256) * Math.sign(val)), |
| 7092 |
fromBase: RGB => RGB.map(val => Math.pow(Math.abs(val), 256 / 563) * Math.sign(val)), |
| 7093 |
}); |
| 7094 |
|
| 7095 |
/** @import { Matrix3x3 } from "../types.js" */ |
| 7096 |
|
| 7097 |
/** |
| 7098 |
* Matrices used by this color space, also available as `ProPhoto_Linear.M`. |
| 7099 |
* Uses D50 (so no chromatic adaptation needed afterwards). The matrix cannot |
| 7100 |
* be expressed in rational form, but is calculated to 64 bit accuracy. |
| 7101 |
* see https://github.com/w3c/csswg-drafts/issues/7675 |
| 7102 |
* @type {Record<string, Matrix3x3>} |
| 7103 |
*/ |
| 7104 |
// prettier-ignore |
| 7105 |
const M$4 = { |
| 7106 |
toXYZ: [ |
| 7107 |
[ 0.79776664490064230, 0.13518129740053308, 0.03134773412839220 ], |
| 7108 |
[ 0.28807482881940130, 0.71183523424187300, 0.00008993693872564 ], |
| 7109 |
[ 0.00000000000000000, 0.00000000000000000, 0.82510460251046020 ], |
| 7110 |
], |
| 7111 |
fromXYZ: [ |
| 7112 |
[ 1.34578688164715830, -0.25557208737979464, -0.05110186497554526 ], |
| 7113 |
[ -0.54463070512490190, 1.50824774284514680, 0.02052744743642139 ], |
| 7114 |
[ 0.00000000000000000, 0.00000000000000000, 1.21196754563894520 ], |
| 7115 |
], |
| 7116 |
}; |
| 7117 |
|
| 7118 |
var ProPhotoLinear = new RGBColorSpace({ |
| 7119 |
id: "prophoto-linear", |
| 7120 |
cssId: "--prophoto-rgb-linear", |
| 7121 |
name: "Linear ProPhoto", |
| 7122 |
white: "D50", |
| 7123 |
base: XYZ_D50, |
| 7124 |
M: M$4, |
| 7125 |
}); |
| 7126 |
|
| 7127 |
const Et = 1 / 512; |
| 7128 |
const Et2 = 16 / 512; |
| 7129 |
|
| 7130 |
var prophoto = new RGBColorSpace({ |
| 7131 |
id: "prophoto", |
| 7132 |
cssId: "prophoto-rgb", |
| 7133 |
name: "ProPhoto", |
| 7134 |
base: ProPhotoLinear, |
| 7135 |
linearGamut: ProPhotoLinear, |
| 7136 |
toBase (RGB) { |
| 7137 |
// Transfer curve is gamma 1.8 with a small linear portion |
| 7138 |
return RGB.map(v => { |
| 7139 |
let sign = v < 0 ? -1 : 1; |
| 7140 |
let abs = v * sign; |
| 7141 |
|
| 7142 |
if (abs < Et2) { |
| 7143 |
return v / 16; |
| 7144 |
} |
| 7145 |
|
| 7146 |
return sign * abs ** 1.8; |
| 7147 |
}); |
| 7148 |
}, |
| 7149 |
fromBase (RGB) { |
| 7150 |
return RGB.map(v => { |
| 7151 |
let sign = v < 0 ? -1 : 1; |
| 7152 |
let abs = v * sign; |
| 7153 |
|
| 7154 |
if (abs >= Et) { |
| 7155 |
return sign * abs ** (1 / 1.8); |
| 7156 |
} |
| 7157 |
|
| 7158 |
return 16 * v; |
| 7159 |
}); |
| 7160 |
}, |
| 7161 |
}); |
| 7162 |
|
| 7163 |
// import sRGB from "./srgb.js"; |
| 7164 |
|
| 7165 |
const α = 1.09929682680944; |
| 7166 |
const β = 0.018053968510807; |
| 7167 |
|
| 7168 |
var rec2020Oetf = new RGBColorSpace({ |
| 7169 |
id: "--rec2020-oetf", |
| 7170 |
name: "REC.2020_Scene_Referred", |
| 7171 |
base: REC2020Linear, |
| 7172 |
linearGamut: REC2020Linear, |
| 7173 |
referred: "scene", |
| 7174 |
// Non-linear transfer function from Rec. ITU-R BT.2020-2 table 4 |
| 7175 |
toBase (RGB) { |
| 7176 |
return RGB.map(function (val) { |
| 7177 |
let sign = val < 0 ? -1 : 1; |
| 7178 |
let abs = val * sign; |
| 7179 |
|
| 7180 |
if (abs < β * 4.5) { |
| 7181 |
return val / 4.5; |
| 7182 |
} |
| 7183 |
|
| 7184 |
return sign * Math.pow((abs + α - 1) / α, 1 / 0.45); |
| 7185 |
}); |
| 7186 |
}, |
| 7187 |
fromBase (RGB) { |
| 7188 |
return RGB.map(function (val) { |
| 7189 |
let sign = val < 0 ? -1 : 1; |
| 7190 |
let abs = val * sign; |
| 7191 |
|
| 7192 |
if (abs >= β) { |
| 7193 |
return sign * (α * Math.pow(abs, 0.45) - (α - 1)); |
| 7194 |
} |
| 7195 |
|
| 7196 |
return 4.5 * val; |
| 7197 |
}); |
| 7198 |
}, |
| 7199 |
}); |
| 7200 |
|
| 7201 |
var oklchP3 = new GamutRelativeColorSpace({ |
| 7202 |
id: "oklch-p3", |
| 7203 |
cssId: "--oklch-p3", |
| 7204 |
name: "OKLCh P3", |
| 7205 |
base: OKLCH, |
| 7206 |
gamutSpace: P3, |
| 7207 |
}); |
| 7208 |
|
| 7209 |
var oklchSrgb = new GamutRelativeColorSpace({ |
| 7210 |
id: "oklch-srgb", |
| 7211 |
cssId: "--oklch-srgb", |
| 7212 |
name: "OKLCh sRGB", |
| 7213 |
base: OKLCH, |
| 7214 |
gamutSpace: sRGB, |
| 7215 |
}); |
| 7216 |
|
| 7217 |
var oklchRec2020 = new GamutRelativeColorSpace({ |
| 7218 |
id: "oklch-rec2020", |
| 7219 |
cssId: "--oklch-rec2020", |
| 7220 |
name: "OKLCh Rec.2020", |
| 7221 |
base: OKLCH, |
| 7222 |
gamutSpace: REC2020, |
| 7223 |
}); |
| 7224 |
|
| 7225 |
var lchP3 = new GamutRelativeColorSpace({ |
| 7226 |
id: "lch-p3", |
| 7227 |
cssId: "--lch-p3", |
| 7228 |
name: "LCH P3", |
| 7229 |
base: lch, |
| 7230 |
gamutSpace: P3, |
| 7231 |
}); |
| 7232 |
|
| 7233 |
var lchSrgb = new GamutRelativeColorSpace({ |
| 7234 |
id: "lch-srgb", |
| 7235 |
cssId: "--lch-srgb", |
| 7236 |
name: "LCH sRGB", |
| 7237 |
base: lch, |
| 7238 |
gamutSpace: sRGB, |
| 7239 |
}); |
| 7240 |
|
| 7241 |
var lchRec2020 = new GamutRelativeColorSpace({ |
| 7242 |
id: "lch-rec2020", |
| 7243 |
cssId: "--lch-rec2020", |
| 7244 |
name: "LCH Rec.2020", |
| 7245 |
base: lch, |
| 7246 |
gamutSpace: REC2020, |
| 7247 |
}); |
| 7248 |
|
| 7249 |
// Okhsl class. |
| 7250 |
// |
| 7251 |
// ---- License ---- |
| 7252 |
// |
| 7253 |
// Copyright (c) 2021 Björn Ottosson |
| 7254 |
// |
| 7255 |
// Permission is hereby granted, free of charge, to any person obtaining a copy of |
| 7256 |
// this software and associated documentation files (the "Software"), to deal in |
| 7257 |
// the Software without restriction, including without limitation the rights to |
| 7258 |
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies |
| 7259 |
// of the Software, and to permit persons to whom the Software is furnished to do |
| 7260 |
// so, subject to the following conditions: |
| 7261 |
// |
| 7262 |
// The above copyright notice and this permission notice shall be included in all |
| 7263 |
// copies or substantial portions of the Software. |
| 7264 |
// |
| 7265 |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 7266 |
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 7267 |
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 7268 |
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 7269 |
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 7270 |
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 7271 |
// SOFTWARE. |
| 7272 |
|
| 7273 |
/** @import { Matrix3x3, Vector3 } from "../types.js" */ |
| 7274 |
|
| 7275 |
// Type re-exports |
| 7276 |
/** @typedef {import("../types.js").OKCoeff} OKCoeff */ |
| 7277 |
|
| 7278 |
const tau = 2 * Math.PI; |
| 7279 |
|
| 7280 |
/** |
| 7281 |
* Matrices used by this color space (Oklab's, plus its own), |
| 7282 |
* also available as `Okhsl.M` |
| 7283 |
* @type {Record<string, Matrix3x3>} |
| 7284 |
*/ |
| 7285 |
// prettier-ignore |
| 7286 |
const M$3 = { |
| 7287 |
...Oklab.M, |
| 7288 |
toLMS: [ |
| 7289 |
[0.4122214694707629, 0.5363325372617349, 0.0514459932675022], |
| 7290 |
[0.2119034958178251, 0.6806995506452344, 0.1073969535369405], |
| 7291 |
[0.0883024591900564, 0.2817188391361215, 0.6299787016738222], |
| 7292 |
], |
| 7293 |
toSRGBLinear: [ |
| 7294 |
[ 4.0767416360759583, -3.3077115392580629, 0.2309699031821043], |
| 7295 |
[-1.2684379732850315, 2.6097573492876882, -0.3413193760026570], |
| 7296 |
[-0.0041960761386756, -0.7034186179359362, 1.7076146940746117], |
| 7297 |
], |
| 7298 |
}; |
| 7299 |
|
| 7300 |
/** @type {OKCoeff} */ |
| 7301 |
const RGBCoeff = [ |
| 7302 |
// Red |
| 7303 |
[ |
| 7304 |
// Limit |
| 7305 |
[-1.8817031, -0.80936501], |
| 7306 |
// `Kn` coefficients |
| 7307 |
[1.19086277, 1.76576728, 0.59662641, 0.75515197, 0.56771245], |
| 7308 |
], |
| 7309 |
// Green |
| 7310 |
[ |
| 7311 |
// Limit |
| 7312 |
[1.8144408, -1.19445267], |
| 7313 |
// `Kn` coefficients |
| 7314 |
[0.73956515, -0.45954404, 0.08285427, 0.12541073, -0.14503204], |
| 7315 |
], |
| 7316 |
// Blue |
| 7317 |
[ |
| 7318 |
// Limit |
| 7319 |
[0.13110758, 1.81333971], |
| 7320 |
// `Kn` coefficients |
| 7321 |
[1.35733652, -0.00915799, -1.1513021, -0.50559606, 0.00692167], |
| 7322 |
], |
| 7323 |
]; |
| 7324 |
|
| 7325 |
const floatMax = Number.MAX_VALUE; |
| 7326 |
const K1 = 0.206; |
| 7327 |
const K2 = 0.03; |
| 7328 |
const K3 = (1.0 + K1) / (1.0 + K2); |
| 7329 |
|
| 7330 |
function vdot (a, b) { |
| 7331 |
// Dot two vectors |
| 7332 |
|
| 7333 |
let l = a.length; |
| 7334 |
if (l !== b.length) { |
| 7335 |
throw new Error(`Vectors of size ${l} and ${b.length} are not aligned`); |
| 7336 |
} |
| 7337 |
|
| 7338 |
let s = 0.0; |
| 7339 |
a.forEach((c, i) => { |
| 7340 |
s += c * b[i]; |
| 7341 |
}); |
| 7342 |
|
| 7343 |
return s; |
| 7344 |
} |
| 7345 |
|
| 7346 |
/** |
| 7347 |
* Toe function for L_r |
| 7348 |
* @param {number} x |
| 7349 |
*/ |
| 7350 |
function toe (x) { |
| 7351 |
return 0.5 * (K3 * x - K1 + Math.sqrt((K3 * x - K1) * (K3 * x - K1) + 4 * K2 * K3 * x)); |
| 7352 |
} |
| 7353 |
|
| 7354 |
/** |
| 7355 |
* Inverse toe function for L_r |
| 7356 |
* @param {number} x |
| 7357 |
*/ |
| 7358 |
function toeInv (x) { |
| 7359 |
return (x ** 2 + K1 * x) / (K3 * (x + K2)); |
| 7360 |
} |
| 7361 |
|
| 7362 |
/** |
| 7363 |
* @param {readonly [number, number]} cusp |
| 7364 |
* @returns {[number, number]} |
| 7365 |
*/ |
| 7366 |
function toSt (cusp) { |
| 7367 |
// To ST. |
| 7368 |
|
| 7369 |
let [l, c] = cusp; |
| 7370 |
return [c / l, c / (1 - l)]; |
| 7371 |
} |
| 7372 |
|
| 7373 |
function getStMid (a, b) { |
| 7374 |
// Returns a smooth approximation of the location of the cusp. |
| 7375 |
// |
| 7376 |
// This polynomial was created by an optimization process. |
| 7377 |
// It has been designed so that S_mid < S_max and T_mid < T_max. |
| 7378 |
|
| 7379 |
// prettier-ignore |
| 7380 |
let s = 0.11516993 + 1.0 / ( |
| 7381 |
7.44778970 + 4.15901240 * b + |
| 7382 |
a * ( |
| 7383 |
-2.19557347 + 1.75198401 * b + |
| 7384 |
a * ( |
| 7385 |
-2.13704948 - 10.02301043 * b + |
| 7386 |
a * ( |
| 7387 |
-4.24894561 + 5.38770819 * b + 4.69891013 * a |
| 7388 |
) |
| 7389 |
) |
| 7390 |
) |
| 7391 |
); |
| 7392 |
|
| 7393 |
// prettier-ignore |
| 7394 |
let t = 0.11239642 + 1.0 / ( |
| 7395 |
1.61320320 - 0.68124379 * b + |
| 7396 |
a * ( |
| 7397 |
0.40370612 + 0.90148123 * b + |
| 7398 |
a * ( |
| 7399 |
-0.27087943 + 0.61223990 * b + |
| 7400 |
a * ( |
| 7401 |
0.00299215 - 0.45399568 * b - 0.14661872 * a |
| 7402 |
) |
| 7403 |
) |
| 7404 |
) |
| 7405 |
); |
| 7406 |
|
| 7407 |
return [s, t]; |
| 7408 |
} |
| 7409 |
|
| 7410 |
/** |
| 7411 |
* @param {Vector3} lab |
| 7412 |
* @param {Matrix3x3} lmsToRgb |
| 7413 |
*/ |
| 7414 |
function oklabToLinearRGB (lab, lmsToRgb) { |
| 7415 |
// Convert from Oklab to linear RGB. |
| 7416 |
// |
| 7417 |
// Can be any gamut as long as `lmsToRgb` is a matrix |
| 7418 |
// that transform the LMS values to the linear RGB space. |
| 7419 |
|
| 7420 |
let lms = multiply_v3_m3x3(lab, M$3.LabtoLMS); |
| 7421 |
|
| 7422 |
lms[0] = lms[0] ** 3; |
| 7423 |
lms[1] = lms[1] ** 3; |
| 7424 |
lms[2] = lms[2] ** 3; |
| 7425 |
|
| 7426 |
return multiply_v3_m3x3(lms, lmsToRgb, lms); |
| 7427 |
} |
| 7428 |
|
| 7429 |
/** |
| 7430 |
* @param {number} a |
| 7431 |
* @param {number} b |
| 7432 |
* @param {Matrix3x3} lmsToRgb |
| 7433 |
* @param {OKCoeff} okCoeff |
| 7434 |
* @returns {[number, number]} |
| 7435 |
* @todo Could probably make these types more specific/better-documented if desired |
| 7436 |
*/ |
| 7437 |
function findCusp (a, b, lmsToRgb, okCoeff) { |
| 7438 |
// Finds L_cusp and C_cusp for a given hue. |
| 7439 |
// |
| 7440 |
// `a` and `b` must be normalized so `a^2 + b^2 == 1`. |
| 7441 |
|
| 7442 |
// First, find the maximum saturation (saturation `S = C/L`) |
| 7443 |
let sCusp = computeMaxSaturation(a, b, lmsToRgb, okCoeff); |
| 7444 |
|
| 7445 |
// Convert to linear RGB to find the first point where at least one of r, g or b >= 1: |
| 7446 |
let rgb = oklabToLinearRGB([1, sCusp * a, sCusp * b], lmsToRgb); |
| 7447 |
let lCusp = spow(1.0 / Math.max(...rgb), 1 / 3); |
| 7448 |
let cCusp = lCusp * sCusp; |
| 7449 |
|
| 7450 |
return [lCusp, cCusp]; |
| 7451 |
} |
| 7452 |
|
| 7453 |
/** |
| 7454 |
* @param {number} a |
| 7455 |
* @param {number} b |
| 7456 |
* @param {number} l1 |
| 7457 |
* @param {number} c1 |
| 7458 |
* @param {number} l0 |
| 7459 |
* @param {Matrix3x3} lmsToRgb |
| 7460 |
* @param {OKCoeff} okCoeff |
| 7461 |
* @param {[number, number]} cusp |
| 7462 |
* @returns {Number} |
| 7463 |
* @todo Could probably make these types more specific/better-documented if desired |
| 7464 |
*/ |
| 7465 |
function findGamutIntersection (a, b, l1, c1, l0, lmsToRgb, okCoeff, cusp) { |
| 7466 |
// Finds intersection of the line. |
| 7467 |
// |
| 7468 |
// Defined by the following: |
| 7469 |
// |
| 7470 |
// ``` |
| 7471 |
// L = L0 * (1 - t) + t * L1 |
| 7472 |
// C = t * C1 |
| 7473 |
// ``` |
| 7474 |
// |
| 7475 |
// `a` and `b` must be normalized so `a^2 + b^2 == 1`. |
| 7476 |
|
| 7477 |
let t; |
| 7478 |
|
| 7479 |
if (cusp === undefined) { |
| 7480 |
cusp = findCusp(a, b, lmsToRgb, okCoeff); |
| 7481 |
} |
| 7482 |
|
| 7483 |
// Find the intersection for upper and lower half separately |
| 7484 |
if ((l1 - l0) * cusp[1] - (cusp[0] - l0) * c1 <= 0.0) { |
| 7485 |
// Lower half |
| 7486 |
t = (cusp[1] * l0) / (c1 * cusp[0] + cusp[1] * (l0 - l1)); |
| 7487 |
} |
| 7488 |
else { |
| 7489 |
// Upper half |
| 7490 |
|
| 7491 |
// First intersect with triangle |
| 7492 |
t = (cusp[1] * (l0 - 1.0)) / (c1 * (cusp[0] - 1.0) + cusp[1] * (l0 - l1)); |
| 7493 |
|
| 7494 |
// Then one step Halley's method |
| 7495 |
let dl = l1 - l0; |
| 7496 |
let dc = c1; |
| 7497 |
|
| 7498 |
let kl = vdot(M$3.LabtoLMS[0].slice(1), [a, b]); |
| 7499 |
let km = vdot(M$3.LabtoLMS[1].slice(1), [a, b]); |
| 7500 |
let ks = vdot(M$3.LabtoLMS[2].slice(1), [a, b]); |
| 7501 |
|
| 7502 |
let ldt_ = dl + dc * kl; |
| 7503 |
let mdt_ = dl + dc * km; |
| 7504 |
let sdt_ = dl + dc * ks; |
| 7505 |
|
| 7506 |
// If higher accuracy is required, 2 or 3 iterations of the following block can be used: |
| 7507 |
let L = l0 * (1.0 - t) + t * l1; |
| 7508 |
let C = t * c1; |
| 7509 |
|
| 7510 |
let l_ = L + C * kl; |
| 7511 |
let m_ = L + C * km; |
| 7512 |
let s_ = L + C * ks; |
| 7513 |
|
| 7514 |
let l = l_ ** 3; |
| 7515 |
let m = m_ ** 3; |
| 7516 |
let s = s_ ** 3; |
| 7517 |
|
| 7518 |
let ldt = 3 * ldt_ * l_ ** 2; |
| 7519 |
let mdt = 3 * mdt_ * m_ ** 2; |
| 7520 |
let sdt = 3 * sdt_ * s_ ** 2; |
| 7521 |
|
| 7522 |
let ldt2 = 6 * ldt_ ** 2 * l_; |
| 7523 |
let mdt2 = 6 * mdt_ ** 2 * m_; |
| 7524 |
let sdt2 = 6 * sdt_ ** 2 * s_; |
| 7525 |
|
| 7526 |
let r_ = vdot(lmsToRgb[0], [l, m, s]) - 1; |
| 7527 |
let r1 = vdot(lmsToRgb[0], [ldt, mdt, sdt]); |
| 7528 |
let r2 = vdot(lmsToRgb[0], [ldt2, mdt2, sdt2]); |
| 7529 |
|
| 7530 |
let ur = r1 / (r1 * r1 - 0.5 * r_ * r2); |
| 7531 |
let tr = -r_ * ur; |
| 7532 |
|
| 7533 |
let g_ = vdot(lmsToRgb[1], [l, m, s]) - 1; |
| 7534 |
let g1 = vdot(lmsToRgb[1], [ldt, mdt, sdt]); |
| 7535 |
let g2 = vdot(lmsToRgb[1], [ldt2, mdt2, sdt2]); |
| 7536 |
|
| 7537 |
let ug = g1 / (g1 * g1 - 0.5 * g_ * g2); |
| 7538 |
let tg = -g_ * ug; |
| 7539 |
|
| 7540 |
let b_ = vdot(lmsToRgb[2], [l, m, s]) - 1; |
| 7541 |
let b1 = vdot(lmsToRgb[2], [ldt, mdt, sdt]); |
| 7542 |
let b2 = vdot(lmsToRgb[2], [ldt2, mdt2, sdt2]); |
| 7543 |
|
| 7544 |
let ub = b1 / (b1 * b1 - 0.5 * b_ * b2); |
| 7545 |
let tb = -b_ * ub; |
| 7546 |
|
| 7547 |
tr = ur >= 0.0 ? tr : floatMax; |
| 7548 |
tg = ug >= 0.0 ? tg : floatMax; |
| 7549 |
tb = ub >= 0.0 ? tb : floatMax; |
| 7550 |
|
| 7551 |
t += Math.min(tr, Math.min(tg, tb)); |
| 7552 |
} |
| 7553 |
|
| 7554 |
return t; |
| 7555 |
} |
| 7556 |
|
| 7557 |
function getCs (lab, lmsToRgb, okCoeff) { |
| 7558 |
// Get Cs |
| 7559 |
|
| 7560 |
let [l, a, b] = lab; |
| 7561 |
|
| 7562 |
let cusp = findCusp(a, b, lmsToRgb, okCoeff); |
| 7563 |
|
| 7564 |
let cMax = findGamutIntersection(a, b, l, 1, l, lmsToRgb, okCoeff, cusp); |
| 7565 |
let stMax = toSt(cusp); |
| 7566 |
|
| 7567 |
// Scale factor to compensate for the curved part of gamut shape: |
| 7568 |
let k = cMax / Math.min(l * stMax[0], (1 - l) * stMax[1]); |
| 7569 |
|
| 7570 |
let stMid = getStMid(a, b); |
| 7571 |
|
| 7572 |
// Use a soft minimum function, instead of a sharp triangle shape to get a smooth value for chroma. |
| 7573 |
let ca = l * stMid[0]; |
| 7574 |
let cb = (1.0 - l) * stMid[1]; |
| 7575 |
let cMid = 0.9 * k * Math.sqrt(Math.sqrt(1.0 / (1.0 / ca ** 4 + 1.0 / cb ** 4))); |
| 7576 |
|
| 7577 |
// For `C_0`, the shape is independent of hue, so `ST` are constant. |
| 7578 |
// Values picked to roughly be the average values of `ST`. |
| 7579 |
ca = l * 0.4; |
| 7580 |
cb = (1.0 - l) * 0.8; |
| 7581 |
|
| 7582 |
// Use a soft minimum function, instead of a sharp triangle shape to get a smooth value for chroma. |
| 7583 |
let c0 = Math.sqrt(1.0 / (1.0 / ca ** 2 + 1.0 / cb ** 2)); |
| 7584 |
|
| 7585 |
return [c0, cMid, cMax]; |
| 7586 |
} |
| 7587 |
|
| 7588 |
function computeMaxSaturation (a, b, lmsToRgb, okCoeff) { |
| 7589 |
// Finds the maximum saturation possible for a given hue that fits in RGB. |
| 7590 |
// |
| 7591 |
// Saturation here is defined as `S = C/L`. |
| 7592 |
// `a` and `b` must be normalized so `a^2 + b^2 == 1`. |
| 7593 |
|
| 7594 |
// Max saturation will be when one of r, g or b goes below zero. |
| 7595 |
|
| 7596 |
// Select different coefficients depending on which component goes below zero first. |
| 7597 |
|
| 7598 |
let k0, k1, k2, k3, k4, wl, wm, ws; |
| 7599 |
|
| 7600 |
if (vdot(okCoeff[0][0], [a, b]) > 1) { |
| 7601 |
// Red component |
| 7602 |
[k0, k1, k2, k3, k4] = okCoeff[0][1]; |
| 7603 |
[wl, wm, ws] = lmsToRgb[0]; |
| 7604 |
} |
| 7605 |
else if (vdot(okCoeff[1][0], [a, b]) > 1) { |
| 7606 |
// Green component |
| 7607 |
[k0, k1, k2, k3, k4] = okCoeff[1][1]; |
| 7608 |
[wl, wm, ws] = lmsToRgb[1]; |
| 7609 |
} |
| 7610 |
else { |
| 7611 |
// Blue component |
| 7612 |
[k0, k1, k2, k3, k4] = okCoeff[2][1]; |
| 7613 |
[wl, wm, ws] = lmsToRgb[2]; |
| 7614 |
} |
| 7615 |
|
| 7616 |
// Approximate max saturation using a polynomial: |
| 7617 |
let sat = k0 + k1 * a + k2 * b + k3 * a ** 2 + k4 * a * b; |
| 7618 |
|
| 7619 |
// Do one step Halley's method to get closer. |
| 7620 |
// This gives an error less than 10e6, except for some blue hues where the `dS/dh` is close to infinite. |
| 7621 |
// This should be sufficient for most applications, otherwise do two/three steps. |
| 7622 |
|
| 7623 |
let kl = vdot(M$3.LabtoLMS[0].slice(1), [a, b]); |
| 7624 |
let km = vdot(M$3.LabtoLMS[1].slice(1), [a, b]); |
| 7625 |
let ks = vdot(M$3.LabtoLMS[2].slice(1), [a, b]); |
| 7626 |
|
| 7627 |
let l_ = 1.0 + sat * kl; |
| 7628 |
let m_ = 1.0 + sat * km; |
| 7629 |
let s_ = 1.0 + sat * ks; |
| 7630 |
|
| 7631 |
let l = l_ ** 3; |
| 7632 |
let m = m_ ** 3; |
| 7633 |
let s = s_ ** 3; |
| 7634 |
|
| 7635 |
let lds = 3.0 * kl * l_ ** 2; |
| 7636 |
let mds = 3.0 * km * m_ ** 2; |
| 7637 |
let sds = 3.0 * ks * s_ ** 2; |
| 7638 |
|
| 7639 |
let lds2 = 6.0 * kl ** 2 * l_; |
| 7640 |
let mds2 = 6.0 * km ** 2 * m_; |
| 7641 |
let sds2 = 6.0 * ks ** 2 * s_; |
| 7642 |
|
| 7643 |
let f = wl * l + wm * m + ws * s; |
| 7644 |
let f1 = wl * lds + wm * mds + ws * sds; |
| 7645 |
let f2 = wl * lds2 + wm * mds2 + ws * sds2; |
| 7646 |
|
| 7647 |
sat = sat - (f * f1) / (f1 ** 2 - 0.5 * f * f2); |
| 7648 |
|
| 7649 |
return sat; |
| 7650 |
} |
| 7651 |
|
| 7652 |
function okhslToOklab (hsl, lmsToRgb, okCoeff) { |
| 7653 |
// Convert Okhsl to Oklab. |
| 7654 |
|
| 7655 |
let [h, s, l] = hsl; |
| 7656 |
let L = toeInv(l); |
| 7657 |
let a = null; |
| 7658 |
let b = null; |
| 7659 |
h = constrain(h) / 360.0; |
| 7660 |
|
| 7661 |
if (L !== 0.0 && L !== 1.0 && s !== 0) { |
| 7662 |
let a_ = Math.cos(tau * h); |
| 7663 |
let b_ = Math.sin(tau * h); |
| 7664 |
|
| 7665 |
let [c0, cMid, cMax] = getCs([L, a_, b_], lmsToRgb, okCoeff); |
| 7666 |
|
| 7667 |
// Interpolate the three values for C so that: |
| 7668 |
// ``` |
| 7669 |
// At s=0: dC/ds = C_0, C=0 |
| 7670 |
// At s=0.8: C=C_mid |
| 7671 |
// At s=1.0: C=C_max |
| 7672 |
// ``` |
| 7673 |
|
| 7674 |
let mid = 0.8; |
| 7675 |
let midInv = 1.25; |
| 7676 |
let t, k0, k1, k2; |
| 7677 |
|
| 7678 |
if (s < mid) { |
| 7679 |
t = midInv * s; |
| 7680 |
k0 = 0.0; |
| 7681 |
k1 = mid * c0; |
| 7682 |
k2 = 1.0 - k1 / cMid; |
| 7683 |
} |
| 7684 |
else { |
| 7685 |
t = 5 * (s - 0.8); |
| 7686 |
k0 = cMid; |
| 7687 |
k1 = (0.2 * cMid ** 2 * 1.25 ** 2) / c0; |
| 7688 |
k2 = 1.0 - k1 / (cMax - cMid); |
| 7689 |
} |
| 7690 |
|
| 7691 |
let c = k0 + (t * k1) / (1.0 - k2 * t); |
| 7692 |
|
| 7693 |
a = c * a_; |
| 7694 |
b = c * b_; |
| 7695 |
} |
| 7696 |
|
| 7697 |
return [L, a, b]; |
| 7698 |
} |
| 7699 |
|
| 7700 |
function oklabToOkhsl (lab, lmsToRgb, okCoeff) { |
| 7701 |
// Oklab to Okhsl. |
| 7702 |
|
| 7703 |
// Epsilon for lightness should approach close to 32 bit lightness |
| 7704 |
// Epsilon for saturation just needs to be sufficiently close when denoting achromatic |
| 7705 |
let εL = 1e-7; |
| 7706 |
let εS = 1e-4; |
| 7707 |
let L = lab[0]; |
| 7708 |
let s = 0.0; |
| 7709 |
let l = toe(L); |
| 7710 |
|
| 7711 |
let c = Math.sqrt(lab[1] ** 2 + lab[2] ** 2); |
| 7712 |
let h = 0.5 + Math.atan2(-lab[2], -lab[1]) / tau; |
| 7713 |
|
| 7714 |
if (l !== 0.0 && l !== 1.0 && c !== 0) { |
| 7715 |
let a_ = lab[1] / c; |
| 7716 |
let b_ = lab[2] / c; |
| 7717 |
|
| 7718 |
let [c0, cMid, cMax] = getCs([L, a_, b_], lmsToRgb, okCoeff); |
| 7719 |
|
| 7720 |
let mid = 0.8; |
| 7721 |
let midInv = 1.25; |
| 7722 |
let k0, k1, k2, t; |
| 7723 |
|
| 7724 |
if (c < cMid) { |
| 7725 |
k1 = mid * c0; |
| 7726 |
k2 = 1.0 - k1 / cMid; |
| 7727 |
|
| 7728 |
t = c / (k1 + k2 * c); |
| 7729 |
s = t * mid; |
| 7730 |
} |
| 7731 |
else { |
| 7732 |
k0 = cMid; |
| 7733 |
k1 = (0.2 * cMid ** 2 * midInv ** 2) / c0; |
| 7734 |
k2 = 1.0 - k1 / (cMax - cMid); |
| 7735 |
|
| 7736 |
t = (c - k0) / (k1 + k2 * (c - k0)); |
| 7737 |
s = mid + 0.2 * t; |
| 7738 |
} |
| 7739 |
} |
| 7740 |
|
| 7741 |
const achromatic = Math.abs(s) < εS; |
| 7742 |
if (achromatic || l === 0.0 || Math.abs(1 - l) < εL) { |
| 7743 |
h = null; |
| 7744 |
// Due to floating point imprecision near lightness of 1, we can end up |
| 7745 |
// with really high around white, this is to provide consistency as |
| 7746 |
// saturation can be really high for white due this imprecision. |
| 7747 |
if (!achromatic) { |
| 7748 |
s = 0.0; |
| 7749 |
} |
| 7750 |
} |
| 7751 |
else { |
| 7752 |
h = constrain(h * 360); |
| 7753 |
} |
| 7754 |
|
| 7755 |
return [h, s, l]; |
| 7756 |
} |
| 7757 |
|
| 7758 |
const Okhsl = new ColorSpace({ |
| 7759 |
id: "okhsl", |
| 7760 |
name: "Okhsl", |
| 7761 |
coords: { |
| 7762 |
h: { |
| 7763 |
refRange: [0, 360], |
| 7764 |
type: "angle", |
| 7765 |
name: "Hue", |
| 7766 |
}, |
| 7767 |
s: { |
| 7768 |
range: [0, 1], |
| 7769 |
name: "Saturation", |
| 7770 |
}, |
| 7771 |
l: { |
| 7772 |
range: [0, 1], |
| 7773 |
name: "Lightness", |
| 7774 |
}, |
| 7775 |
}, |
| 7776 |
|
| 7777 |
base: Oklab, |
| 7778 |
gamutSpace: "self", |
| 7779 |
|
| 7780 |
M: M$3, |
| 7781 |
|
| 7782 |
// Convert Oklab to Okhsl |
| 7783 |
fromBase (lab) { |
| 7784 |
return oklabToOkhsl(lab, M$3.toSRGBLinear, RGBCoeff); |
| 7785 |
}, |
| 7786 |
|
| 7787 |
// Convert Okhsl to Oklab |
| 7788 |
toBase (hsl) { |
| 7789 |
return okhslToOklab(hsl, M$3.toSRGBLinear, RGBCoeff); |
| 7790 |
}, |
| 7791 |
|
| 7792 |
formats: { |
| 7793 |
color: { |
| 7794 |
id: "--okhsl", |
| 7795 |
coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"], |
| 7796 |
}, |
| 7797 |
}, |
| 7798 |
}); |
| 7799 |
|
| 7800 |
Okhsl.rgbGamut = new RGBColorSpace({ |
| 7801 |
id: "okhsl-prism", |
| 7802 |
cssId: "--okhsl-prism", |
| 7803 |
name: "Okhsl Prism", |
| 7804 |
base: Okhsl, |
| 7805 |
fromBase (hsl) { |
| 7806 |
return HSL.toBase([hsl[0], hsl[1] * 100, hsl[2] * 100]); |
| 7807 |
}, |
| 7808 |
toBase (rgb) { |
| 7809 |
const hsl = HSL.fromBase(rgb); |
| 7810 |
hsl[1] /= 100; |
| 7811 |
hsl[2] /= 100; |
| 7812 |
return hsl; |
| 7813 |
}, |
| 7814 |
}); |
| 7815 |
|
| 7816 |
var OKLrab = new ColorSpace({ |
| 7817 |
id: "oklrab", |
| 7818 |
name: "Oklrab", |
| 7819 |
coords: { |
| 7820 |
l: { |
| 7821 |
refRange: [0, 1], |
| 7822 |
name: "Lightness", |
| 7823 |
}, |
| 7824 |
a: { |
| 7825 |
refRange: [-0.4, 0.4], |
| 7826 |
}, |
| 7827 |
b: { |
| 7828 |
refRange: [-0.4, 0.4], |
| 7829 |
}, |
| 7830 |
}, |
| 7831 |
|
| 7832 |
// Note that XYZ is relative to D65 |
| 7833 |
white: "D65", |
| 7834 |
|
| 7835 |
base: Oklab, |
| 7836 |
fromBase (oklab) { |
| 7837 |
return [toe(oklab[0]), oklab[1], oklab[2]]; |
| 7838 |
}, |
| 7839 |
toBase (oklrab) { |
| 7840 |
return [toeInv(oklrab[0]), oklrab[1], oklrab[2]]; |
| 7841 |
}, |
| 7842 |
|
| 7843 |
formats: { |
| 7844 |
color: { |
| 7845 |
coords: [ |
| 7846 |
"<percentage> | <number>", |
| 7847 |
"<number> | <percentage>[-1,1]", |
| 7848 |
"<number> | <percentage>[-1,1]", |
| 7849 |
], |
| 7850 |
}, |
| 7851 |
}, |
| 7852 |
}); |
| 7853 |
|
| 7854 |
var oklrch = new ColorSpace({ |
| 7855 |
id: "oklrch", |
| 7856 |
name: "Oklrch", |
| 7857 |
coords: { |
| 7858 |
l: { |
| 7859 |
refRange: [0, 1], |
| 7860 |
name: "Lightness", |
| 7861 |
}, |
| 7862 |
c: { |
| 7863 |
refRange: [0, 0.4], |
| 7864 |
name: "Chroma", |
| 7865 |
}, |
| 7866 |
h: { |
| 7867 |
refRange: [0, 360], |
| 7868 |
type: "angle", |
| 7869 |
name: "Hue", |
| 7870 |
}, |
| 7871 |
}, |
| 7872 |
white: "D65", |
| 7873 |
|
| 7874 |
base: OKLrab, |
| 7875 |
fromBase: lch.fromBase, |
| 7876 |
toBase: lch.toBase, |
| 7877 |
|
| 7878 |
formats: { |
| 7879 |
color: { |
| 7880 |
coords: [ |
| 7881 |
"<percentage> | <number>", |
| 7882 |
"<number> | <percentage>[0,1]", |
| 7883 |
"<number> | <angle>", |
| 7884 |
], |
| 7885 |
}, |
| 7886 |
}, |
| 7887 |
}); |
| 7888 |
|
| 7889 |
// Okhsv class. |
| 7890 |
// |
| 7891 |
// ---- License ---- |
| 7892 |
// |
| 7893 |
// Copyright (c) 2021 Björn Ottosson |
| 7894 |
// |
| 7895 |
// Permission is hereby granted, free of charge, to any person obtaining a copy of |
| 7896 |
// this software and associated documentation files (the "Software"), to deal in |
| 7897 |
// the Software without restriction, including without limitation the rights to |
| 7898 |
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies |
| 7899 |
// of the Software, and to permit persons to whom the Software is furnished to do |
| 7900 |
// so, subject to the following conditions: |
| 7901 |
// |
| 7902 |
// The above copyright notice and this permission notice shall be included in all |
| 7903 |
// copies or substantial portions of the Software. |
| 7904 |
// |
| 7905 |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 7906 |
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 7907 |
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 7908 |
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 7909 |
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 7910 |
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 7911 |
// SOFTWARE. |
| 7912 |
|
| 7913 |
/** |
| 7914 |
* Matrices used by this color space (reused from Okhsl), also available as `Okhsv.M` |
| 7915 |
* @type {Record<string, Matrix3x3>} |
| 7916 |
*/ |
| 7917 |
const M$2 = { toSRGBLinear: Okhsl.M.toSRGBLinear }; |
| 7918 |
|
| 7919 |
/** @import { Coords, Matrix3x3, OKCoeff, Vector3 } from "../types.js" */ |
| 7920 |
|
| 7921 |
/** |
| 7922 |
* |
| 7923 |
* @param {Vector3} hsv |
| 7924 |
* @param {Matrix3x3} lmsToRgb |
| 7925 |
* @param {OKCoeff} okCoeff |
| 7926 |
* @returns {Coords} |
| 7927 |
*/ |
| 7928 |
function okhsvToOklab (hsv, lmsToRgb, okCoeff) { |
| 7929 |
// Convert from Okhsv to Oklab.""" |
| 7930 |
|
| 7931 |
let [h, s, v] = hsv; |
| 7932 |
h = constrain(h) / 360.0; |
| 7933 |
|
| 7934 |
let l = toeInv(v); |
| 7935 |
let a = null; |
| 7936 |
let b = null; |
| 7937 |
|
| 7938 |
// Avoid processing gray or colors with undefined hues |
| 7939 |
if (l !== 0.0 && s !== 0.0) { |
| 7940 |
let a_ = Math.cos(tau * h); |
| 7941 |
let b_ = Math.sin(tau * h); |
| 7942 |
|
| 7943 |
let cusp = findCusp(a_, b_, lmsToRgb, okCoeff); |
| 7944 |
let [sMax, tMax] = toSt(cusp); |
| 7945 |
let s0 = 0.5; |
| 7946 |
let k = 1 - s0 / sMax; |
| 7947 |
|
| 7948 |
// first we compute L and V as if the gamut is a perfect triangle: |
| 7949 |
|
| 7950 |
// L, C when v==1: |
| 7951 |
let lv = 1 - (s * s0) / (s0 + tMax - tMax * k * s); |
| 7952 |
let cv = (s * tMax * s0) / (s0 + tMax - tMax * k * s); |
| 7953 |
|
| 7954 |
l = v * lv; |
| 7955 |
let c = v * cv; |
| 7956 |
|
| 7957 |
// then we compensate for both toe and the curved top part of the triangle: |
| 7958 |
let lvt = toeInv(lv); |
| 7959 |
let cvt = (cv * lvt) / lv; |
| 7960 |
|
| 7961 |
let lNew = toeInv(l); |
| 7962 |
c = (c * lNew) / l; |
| 7963 |
l = lNew; |
| 7964 |
|
| 7965 |
// RGB scale |
| 7966 |
let [rs, gs, bs] = oklabToLinearRGB([lvt, a_ * cvt, b_ * cvt], lmsToRgb); |
| 7967 |
let scaleL = spow(1.0 / Math.max(Math.max(rs, gs), Math.max(bs, 0.0)), 1 / 3); |
| 7968 |
|
| 7969 |
l = l * scaleL; |
| 7970 |
c = c * scaleL; |
| 7971 |
|
| 7972 |
a = c * a_; |
| 7973 |
b = c * b_; |
| 7974 |
} |
| 7975 |
|
| 7976 |
return [l, a, b]; |
| 7977 |
} |
| 7978 |
|
| 7979 |
/** |
| 7980 |
* |
| 7981 |
* @param {Vector3} lab |
| 7982 |
* @param {Matrix3x3} lmsToRgb |
| 7983 |
* @param {OKCoeff} okCoeff |
| 7984 |
* @returns {Coords} |
| 7985 |
*/ |
| 7986 |
function oklabToOkhsv (lab, lmsToRgb, okCoeff) { |
| 7987 |
// Oklab to Okhsv. |
| 7988 |
|
| 7989 |
// Epsilon for saturation just needs to be sufficiently close when denoting achromatic |
| 7990 |
let ε = 1e-4; |
| 7991 |
let l = lab[0]; |
| 7992 |
let s = 0.0; |
| 7993 |
let v = toe(l); |
| 7994 |
let c = Math.sqrt(lab[1] ** 2 + lab[2] ** 2); |
| 7995 |
let h = 0.5 + Math.atan2(-lab[2], -lab[1]) / tau; |
| 7996 |
|
| 7997 |
if (l !== 0.0 && l !== 1 && c !== 0.0) { |
| 7998 |
let a_ = lab[1] / c; |
| 7999 |
let b_ = lab[2] / c; |
| 8000 |
|
| 8001 |
let cusp = findCusp(a_, b_, lmsToRgb, okCoeff); |
| 8002 |
let [sMax, tMax] = toSt(cusp); |
| 8003 |
let s0 = 0.5; |
| 8004 |
let k = 1 - s0 / sMax; |
| 8005 |
|
| 8006 |
// first we find `L_v`, `C_v`, `L_vt` and `C_vt` |
| 8007 |
let t = tMax / (c + l * tMax); |
| 8008 |
let lv = t * l; |
| 8009 |
let cv = t * c; |
| 8010 |
|
| 8011 |
let lvt = toeInv(lv); |
| 8012 |
let cvt = (cv * lvt) / lv; |
| 8013 |
|
| 8014 |
// we can then use these to invert the step that compensates |
| 8015 |
// for the toe and the curved top part of the triangle: |
| 8016 |
let [rs, gs, bs] = oklabToLinearRGB([lvt, a_ * cvt, b_ * cvt], lmsToRgb); |
| 8017 |
let scaleL = spow(1.0 / Math.max(Math.max(rs, gs), Math.max(bs, 0.0)), 1 / 3); |
| 8018 |
|
| 8019 |
l = l / scaleL; |
| 8020 |
c = c / scaleL; |
| 8021 |
|
| 8022 |
c = (c * toe(l)) / l; |
| 8023 |
l = toe(l); |
| 8024 |
|
| 8025 |
// we can now compute v and s: |
| 8026 |
v = l / lv; |
| 8027 |
s = ((s0 + tMax) * cv) / (tMax * s0 + tMax * k * cv); |
| 8028 |
} |
| 8029 |
|
| 8030 |
if (Math.abs(s) < ε || v === 0.0) { |
| 8031 |
h = null; |
| 8032 |
} |
| 8033 |
else { |
| 8034 |
h = constrain(h * 360); |
| 8035 |
} |
| 8036 |
|
| 8037 |
return [h, s, v]; |
| 8038 |
} |
| 8039 |
|
| 8040 |
const Okhsv = new ColorSpace({ |
| 8041 |
id: "okhsv", |
| 8042 |
name: "Okhsv", |
| 8043 |
coords: { |
| 8044 |
h: { |
| 8045 |
refRange: [0, 360], |
| 8046 |
type: "angle", |
| 8047 |
name: "Hue", |
| 8048 |
}, |
| 8049 |
s: { |
| 8050 |
range: [0, 1], |
| 8051 |
name: "Saturation", |
| 8052 |
}, |
| 8053 |
v: { |
| 8054 |
range: [0, 1], |
| 8055 |
name: "Value", |
| 8056 |
}, |
| 8057 |
}, |
| 8058 |
|
| 8059 |
base: Oklab, |
| 8060 |
gamutSpace: "self", |
| 8061 |
|
| 8062 |
M: M$2, |
| 8063 |
|
| 8064 |
// Convert Oklab to Okhsl |
| 8065 |
fromBase (lab) { |
| 8066 |
return oklabToOkhsv(lab, M$2.toSRGBLinear, RGBCoeff); |
| 8067 |
}, |
| 8068 |
|
| 8069 |
// Convert Okhsl to Oklab |
| 8070 |
toBase (hsl) { |
| 8071 |
return okhsvToOklab(hsl, M$2.toSRGBLinear, RGBCoeff); |
| 8072 |
}, |
| 8073 |
|
| 8074 |
formats: { |
| 8075 |
color: { |
| 8076 |
id: "--okhsv", |
| 8077 |
coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"], |
| 8078 |
}, |
| 8079 |
}, |
| 8080 |
}); |
| 8081 |
|
| 8082 |
Okhsv.rgbGamut = new RGBColorSpace({ |
| 8083 |
id: "okhsv-prism", |
| 8084 |
cssId: "--okhsv-prism", |
| 8085 |
name: "Okhsv Prism", |
| 8086 |
base: Okhsv, |
| 8087 |
fromBase (hsl) { |
| 8088 |
return HSL.toBase([hsl[0], hsl[1] * 100, hsl[2] * 100]); |
| 8089 |
}, |
| 8090 |
toBase (rgb) { |
| 8091 |
const hsl = HSL.fromBase(rgb); |
| 8092 |
hsl[1] /= 100; |
| 8093 |
hsl[2] /= 100; |
| 8094 |
return hsl; |
| 8095 |
}, |
| 8096 |
}); |
| 8097 |
|
| 8098 |
let white = WHITES.D65; |
| 8099 |
|
| 8100 |
const ε$2 = 216 / 24389; // 6^3/29^3 == (24/116)^3 |
| 8101 |
const κ$1 = 24389 / 27; // 29^3/3^3 |
| 8102 |
const [U_PRIME_WHITE, V_PRIME_WHITE] = uv({ space: XYZ_D65, coords: white }); |
| 8103 |
|
| 8104 |
var Luv = new ColorSpace({ |
| 8105 |
id: "luv", |
| 8106 |
name: "Luv", |
| 8107 |
coords: { |
| 8108 |
l: { |
| 8109 |
refRange: [0, 100], |
| 8110 |
name: "Lightness", |
| 8111 |
}, |
| 8112 |
// Reference ranges from https://facelessuser.github.io/coloraide/colors/luv/ |
| 8113 |
u: { |
| 8114 |
refRange: [-215, 215], |
| 8115 |
}, |
| 8116 |
v: { |
| 8117 |
refRange: [-215, 215], |
| 8118 |
}, |
| 8119 |
}, |
| 8120 |
|
| 8121 |
white: white, |
| 8122 |
base: XYZ_D65, |
| 8123 |
|
| 8124 |
// Convert D65-adapted XYZ to Luv |
| 8125 |
// https://en.wikipedia.org/wiki/CIELUV#The_forward_transformation |
| 8126 |
fromBase (XYZ) { |
| 8127 |
let xyz = /** @type {[number, number, number]} */ ([ |
| 8128 |
skipNone(XYZ[0]), |
| 8129 |
skipNone(XYZ[1]), |
| 8130 |
skipNone(XYZ[2]), |
| 8131 |
]); |
| 8132 |
let y = xyz[1]; |
| 8133 |
|
| 8134 |
let [up, vp] = uv({ space: XYZ_D65, coords: xyz }); |
| 8135 |
|
| 8136 |
// Protect against XYZ of [0, 0, 0] |
| 8137 |
if (!Number.isFinite(up) || !Number.isFinite(vp)) { |
| 8138 |
return [0, 0, 0]; |
| 8139 |
} |
| 8140 |
|
| 8141 |
let L = y <= ε$2 ? κ$1 * y : 116 * Math.cbrt(y) - 16; |
| 8142 |
return [L, 13 * L * (up - U_PRIME_WHITE), 13 * L * (vp - V_PRIME_WHITE)]; |
| 8143 |
}, |
| 8144 |
|
| 8145 |
// Convert Luv to D65-adapted XYZ |
| 8146 |
// https://en.wikipedia.org/wiki/CIELUV#The_reverse_transformation |
| 8147 |
toBase (Luv) { |
| 8148 |
let [L, u, v] = Luv; |
| 8149 |
|
| 8150 |
// Protect against division by zero and none Lightness |
| 8151 |
if (L === 0 || isNone(L)) { |
| 8152 |
return [0, 0, 0]; |
| 8153 |
} |
| 8154 |
|
| 8155 |
u = skipNone(u); |
| 8156 |
v = skipNone(v); |
| 8157 |
|
| 8158 |
let up = u / (13 * L) + U_PRIME_WHITE; |
| 8159 |
let vp = v / (13 * L) + V_PRIME_WHITE; |
| 8160 |
|
| 8161 |
let y = L <= 8 ? L / κ$1 : Math.pow((L + 16) / 116, 3); |
| 8162 |
|
| 8163 |
return [y * ((9 * up) / (4 * vp)), y, y * ((12 - 3 * up - 20 * vp) / (4 * vp))]; |
| 8164 |
}, |
| 8165 |
|
| 8166 |
formats: { |
| 8167 |
color: { |
| 8168 |
id: "--luv", |
| 8169 |
coords: [ |
| 8170 |
"<number> | <percentage>", |
| 8171 |
"<number> | <percentage>", |
| 8172 |
"<number> | <percentage>", |
| 8173 |
], |
| 8174 |
}, |
| 8175 |
}, |
| 8176 |
}); |
| 8177 |
|
| 8178 |
var LCHuv = new ColorSpace({ |
| 8179 |
id: "lchuv", |
| 8180 |
name: "LChuv", |
| 8181 |
coords: { |
| 8182 |
l: { |
| 8183 |
refRange: [0, 100], |
| 8184 |
name: "Lightness", |
| 8185 |
}, |
| 8186 |
c: { |
| 8187 |
refRange: [0, 220], |
| 8188 |
name: "Chroma", |
| 8189 |
}, |
| 8190 |
h: { |
| 8191 |
refRange: [0, 360], |
| 8192 |
type: "angle", |
| 8193 |
name: "Hue", |
| 8194 |
}, |
| 8195 |
}, |
| 8196 |
|
| 8197 |
base: Luv, |
| 8198 |
fromBase: lch.fromBase, |
| 8199 |
toBase: lch.toBase, |
| 8200 |
|
| 8201 |
formats: { |
| 8202 |
color: { |
| 8203 |
id: "--lchuv", |
| 8204 |
coords: ["<number> | <percentage>", "<number> | <percentage>", "<number> | <angle>"], |
| 8205 |
}, |
| 8206 |
}, |
| 8207 |
}); |
| 8208 |
|
| 8209 |
/* |
| 8210 |
Adapted from: https://github.com/hsluv/hsluv-javascript/blob/14b49e6cf9a9137916096b8487a5372626b57ba4/src/hsluv.ts |
| 8211 |
|
| 8212 |
Copyright (c) 2012-2022 Alexei Boronine |
| 8213 |
|
| 8214 |
Permission is hereby granted, free of charge, to any person obtaining a copy |
| 8215 |
of this software and associated documentation files (the "Software"), to deal |
| 8216 |
in the Software without restriction, including without limitation the rights |
| 8217 |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 8218 |
copies of the Software, and to permit persons to whom the Software is |
| 8219 |
furnished to do so, subject to the following conditions: |
| 8220 |
|
| 8221 |
The above copyright notice and this permission notice shall be included in all |
| 8222 |
copies or substantial portions of the Software. |
| 8223 |
|
| 8224 |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 8225 |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 8226 |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 8227 |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 8228 |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 8229 |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 8230 |
SOFTWARE. |
| 8231 |
*/ |
| 8232 |
|
| 8233 |
|
| 8234 |
const ε$1 = 216 / 24389; // 6^3/29^3 == (24/116)^3 |
| 8235 |
const κ = 24389 / 27; // 29^3/3^3 |
| 8236 |
|
| 8237 |
const fromXYZ_M$1 = M$6.fromXYZ; |
| 8238 |
const m_r0 = fromXYZ_M$1[0][0]; |
| 8239 |
const m_r1 = fromXYZ_M$1[0][1]; |
| 8240 |
const m_r2 = fromXYZ_M$1[0][2]; |
| 8241 |
const m_g0 = fromXYZ_M$1[1][0]; |
| 8242 |
const m_g1 = fromXYZ_M$1[1][1]; |
| 8243 |
const m_g2 = fromXYZ_M$1[1][2]; |
| 8244 |
const m_b0 = fromXYZ_M$1[2][0]; |
| 8245 |
const m_b1 = fromXYZ_M$1[2][1]; |
| 8246 |
const m_b2 = fromXYZ_M$1[2][2]; |
| 8247 |
|
| 8248 |
function distanceFromOriginAngle (slope, intercept, angle) { |
| 8249 |
const d = intercept / (Math.sin(angle) - slope * Math.cos(angle)); |
| 8250 |
return d < 0 ? Infinity : d; |
| 8251 |
} |
| 8252 |
|
| 8253 |
/** |
| 8254 |
* @param {number} l |
| 8255 |
*/ |
| 8256 |
function calculateBoundingLines (l) { |
| 8257 |
const sub1 = Math.pow(l + 16, 3) / 1560896; |
| 8258 |
const sub2 = sub1 > ε$1 ? sub1 : l / κ; |
| 8259 |
const s1r = sub2 * (284517 * m_r0 - 94839 * m_r2); |
| 8260 |
const s2r = sub2 * (838422 * m_r2 + 769860 * m_r1 + 731718 * m_r0); |
| 8261 |
const s3r = sub2 * (632260 * m_r2 - 126452 * m_r1); |
| 8262 |
const s1g = sub2 * (284517 * m_g0 - 94839 * m_g2); |
| 8263 |
const s2g = sub2 * (838422 * m_g2 + 769860 * m_g1 + 731718 * m_g0); |
| 8264 |
const s3g = sub2 * (632260 * m_g2 - 126452 * m_g1); |
| 8265 |
const s1b = sub2 * (284517 * m_b0 - 94839 * m_b2); |
| 8266 |
const s2b = sub2 * (838422 * m_b2 + 769860 * m_b1 + 731718 * m_b0); |
| 8267 |
const s3b = sub2 * (632260 * m_b2 - 126452 * m_b1); |
| 8268 |
|
| 8269 |
return { |
| 8270 |
r0s: s1r / s3r, |
| 8271 |
r0i: (s2r * l) / s3r, |
| 8272 |
r1s: s1r / (s3r + 126452), |
| 8273 |
r1i: ((s2r - 769860) * l) / (s3r + 126452), |
| 8274 |
g0s: s1g / s3g, |
| 8275 |
g0i: (s2g * l) / s3g, |
| 8276 |
g1s: s1g / (s3g + 126452), |
| 8277 |
g1i: ((s2g - 769860) * l) / (s3g + 126452), |
| 8278 |
b0s: s1b / s3b, |
| 8279 |
b0i: (s2b * l) / s3b, |
| 8280 |
b1s: s1b / (s3b + 126452), |
| 8281 |
b1i: ((s2b - 769860) * l) / (s3b + 126452), |
| 8282 |
}; |
| 8283 |
} |
| 8284 |
|
| 8285 |
function calcMaxChromaHsluv (lines, h) { |
| 8286 |
const hueRad = (h / 360) * Math.PI * 2; |
| 8287 |
const r0 = distanceFromOriginAngle(lines.r0s, lines.r0i, hueRad); |
| 8288 |
const r1 = distanceFromOriginAngle(lines.r1s, lines.r1i, hueRad); |
| 8289 |
const g0 = distanceFromOriginAngle(lines.g0s, lines.g0i, hueRad); |
| 8290 |
const g1 = distanceFromOriginAngle(lines.g1s, lines.g1i, hueRad); |
| 8291 |
const b0 = distanceFromOriginAngle(lines.b0s, lines.b0i, hueRad); |
| 8292 |
const b1 = distanceFromOriginAngle(lines.b1s, lines.b1i, hueRad); |
| 8293 |
|
| 8294 |
return Math.min(r0, r1, g0, g1, b0, b1); |
| 8295 |
} |
| 8296 |
|
| 8297 |
var hsluv = new ColorSpace({ |
| 8298 |
id: "hsluv", |
| 8299 |
name: "HSLuv", |
| 8300 |
coords: { |
| 8301 |
h: { |
| 8302 |
refRange: [0, 360], |
| 8303 |
type: "angle", |
| 8304 |
name: "Hue", |
| 8305 |
}, |
| 8306 |
s: { |
| 8307 |
range: [0, 100], |
| 8308 |
name: "Saturation", |
| 8309 |
}, |
| 8310 |
l: { |
| 8311 |
range: [0, 100], |
| 8312 |
name: "Lightness", |
| 8313 |
}, |
| 8314 |
}, |
| 8315 |
|
| 8316 |
base: LCHuv, |
| 8317 |
gamutSpace: sRGB, |
| 8318 |
rgbGamut: sRGB, |
| 8319 |
|
| 8320 |
// Convert LCHuv to HSLuv |
| 8321 |
fromBase (lch) { |
| 8322 |
let [l, c, h] = [skipNone(lch[0]), skipNone(lch[1]), skipNone(lch[2])]; |
| 8323 |
let s; |
| 8324 |
|
| 8325 |
if (l > 99.9999999) { |
| 8326 |
s = 0; |
| 8327 |
l = 100; |
| 8328 |
} |
| 8329 |
else if (l < 0.00000001) { |
| 8330 |
s = 0; |
| 8331 |
l = 0; |
| 8332 |
} |
| 8333 |
else { |
| 8334 |
let lines = calculateBoundingLines(l); |
| 8335 |
let max = calcMaxChromaHsluv(lines, h); |
| 8336 |
s = (c / max) * 100; |
| 8337 |
} |
| 8338 |
|
| 8339 |
return [h, s, l]; |
| 8340 |
}, |
| 8341 |
|
| 8342 |
// Convert HSLuv to LCHuv |
| 8343 |
toBase (hsl) { |
| 8344 |
let [h, s, l] = [skipNone(hsl[0]), skipNone(hsl[1]), skipNone(hsl[2])]; |
| 8345 |
let c; |
| 8346 |
|
| 8347 |
if (l > 99.9999999) { |
| 8348 |
l = 100; |
| 8349 |
c = 0; |
| 8350 |
} |
| 8351 |
else if (l < 0.00000001) { |
| 8352 |
l = 0; |
| 8353 |
c = 0; |
| 8354 |
} |
| 8355 |
else { |
| 8356 |
let lines = calculateBoundingLines(l); |
| 8357 |
let max = calcMaxChromaHsluv(lines, h); |
| 8358 |
c = (max / 100) * s; |
| 8359 |
} |
| 8360 |
|
| 8361 |
return [l, c, h]; |
| 8362 |
}, |
| 8363 |
|
| 8364 |
formats: { |
| 8365 |
color: { |
| 8366 |
id: "--hsluv", |
| 8367 |
coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"], |
| 8368 |
}, |
| 8369 |
}, |
| 8370 |
}); |
| 8371 |
|
| 8372 |
/* |
| 8373 |
Adapted from: https://github.com/hsluv/hsluv-javascript/blob/14b49e6cf9a9137916096b8487a5372626b57ba4/src/hsluv.ts |
| 8374 |
|
| 8375 |
Copyright (c) 2012-2022 Alexei Boronine |
| 8376 |
|
| 8377 |
Permission is hereby granted, free of charge, to any person obtaining a copy |
| 8378 |
of this software and associated documentation files (the "Software"), to deal |
| 8379 |
in the Software without restriction, including without limitation the rights |
| 8380 |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 8381 |
copies of the Software, and to permit persons to whom the Software is |
| 8382 |
furnished to do so, subject to the following conditions: |
| 8383 |
|
| 8384 |
The above copyright notice and this permission notice shall be included in all |
| 8385 |
copies or substantial portions of the Software. |
| 8386 |
|
| 8387 |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 8388 |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 8389 |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 8390 |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 8391 |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 8392 |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 8393 |
SOFTWARE. |
| 8394 |
*/ |
| 8395 |
|
| 8396 |
|
| 8397 |
const fromXYZ_M = M$6.fromXYZ; |
| 8398 |
fromXYZ_M[0][0]; |
| 8399 |
fromXYZ_M[0][1]; |
| 8400 |
fromXYZ_M[0][2]; |
| 8401 |
fromXYZ_M[1][0]; |
| 8402 |
fromXYZ_M[1][1]; |
| 8403 |
fromXYZ_M[1][2]; |
| 8404 |
fromXYZ_M[2][0]; |
| 8405 |
fromXYZ_M[2][1]; |
| 8406 |
fromXYZ_M[2][2]; |
| 8407 |
|
| 8408 |
function distanceFromOrigin (slope, intercept) { |
| 8409 |
return Math.abs(intercept) / Math.sqrt(Math.pow(slope, 2) + 1); |
| 8410 |
} |
| 8411 |
|
| 8412 |
function calcMaxChromaHpluv (lines) { |
| 8413 |
let r0 = distanceFromOrigin(lines.r0s, lines.r0i); |
| 8414 |
let r1 = distanceFromOrigin(lines.r1s, lines.r1i); |
| 8415 |
let g0 = distanceFromOrigin(lines.g0s, lines.g0i); |
| 8416 |
let g1 = distanceFromOrigin(lines.g1s, lines.g1i); |
| 8417 |
let b0 = distanceFromOrigin(lines.b0s, lines.b0i); |
| 8418 |
let b1 = distanceFromOrigin(lines.b1s, lines.b1i); |
| 8419 |
|
| 8420 |
return Math.min(r0, r1, g0, g1, b0, b1); |
| 8421 |
} |
| 8422 |
|
| 8423 |
const HPLuv = new ColorSpace({ |
| 8424 |
id: "hpluv", |
| 8425 |
name: "HPLuv", |
| 8426 |
coords: { |
| 8427 |
h: { |
| 8428 |
refRange: [0, 360], |
| 8429 |
type: "angle", |
| 8430 |
name: "Hue", |
| 8431 |
}, |
| 8432 |
s: { |
| 8433 |
range: [0, 100], |
| 8434 |
name: "Saturation", |
| 8435 |
}, |
| 8436 |
l: { |
| 8437 |
range: [0, 100], |
| 8438 |
name: "Lightness", |
| 8439 |
}, |
| 8440 |
}, |
| 8441 |
|
| 8442 |
base: LCHuv, |
| 8443 |
gamutSpace: "self", |
| 8444 |
|
| 8445 |
// Convert LCHuv to HPLuv |
| 8446 |
fromBase (lch) { |
| 8447 |
let [l, c, h] = [skipNone(lch[0]), skipNone(lch[1]), skipNone(lch[2])]; |
| 8448 |
let s; |
| 8449 |
|
| 8450 |
if (l > 99.9999999) { |
| 8451 |
s = 0; |
| 8452 |
l = 100; |
| 8453 |
} |
| 8454 |
else if (l < 0.00000001) { |
| 8455 |
s = 0; |
| 8456 |
l = 0; |
| 8457 |
} |
| 8458 |
else { |
| 8459 |
let lines = calculateBoundingLines(l); |
| 8460 |
let max = calcMaxChromaHpluv(lines); |
| 8461 |
s = (c / max) * 100; |
| 8462 |
} |
| 8463 |
return [h, s, l]; |
| 8464 |
}, |
| 8465 |
|
| 8466 |
// Convert HPLuv to LCHuv |
| 8467 |
toBase (hsl) { |
| 8468 |
let [h, s, l] = [skipNone(hsl[0]), skipNone(hsl[1]), skipNone(hsl[2])]; |
| 8469 |
let c; |
| 8470 |
|
| 8471 |
if (l > 99.9999999) { |
| 8472 |
l = 100; |
| 8473 |
c = 0; |
| 8474 |
} |
| 8475 |
else if (l < 0.00000001) { |
| 8476 |
l = 0; |
| 8477 |
c = 0; |
| 8478 |
} |
| 8479 |
else { |
| 8480 |
let lines = calculateBoundingLines(l); |
| 8481 |
let max = calcMaxChromaHpluv(lines); |
| 8482 |
c = (max / 100) * s; |
| 8483 |
} |
| 8484 |
|
| 8485 |
return [l, c, h]; |
| 8486 |
}, |
| 8487 |
|
| 8488 |
formats: { |
| 8489 |
color: { |
| 8490 |
id: "--hpluv", |
| 8491 |
coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"], |
| 8492 |
}, |
| 8493 |
}, |
| 8494 |
}); |
| 8495 |
|
| 8496 |
HPLuv.rgbGamut = new RGBColorSpace({ |
| 8497 |
id: "hpluv-prism", |
| 8498 |
cssId: "--hpluv-prism", |
| 8499 |
name: "HPLuv Prism", |
| 8500 |
base: HPLuv, |
| 8501 |
fromBase (hsl) { |
| 8502 |
return HSL.toBase(hsl); |
| 8503 |
}, |
| 8504 |
toBase (rgb) { |
| 8505 |
return HSL.fromBase(rgb); |
| 8506 |
}, |
| 8507 |
}); |
| 8508 |
|
| 8509 |
/** |
| 8510 |
* Helmlab GenSpace — generation-optimized color space for interpolation. |
| 8511 |
* |
| 8512 |
* Pipeline (v0.11.1, depressed cubic + chroma power + L-gated enrichment): |
| 8513 |
* XYZ → M1 → depcubic(α=0.021) → M2 → chroma_power(0.978) → |
| 8514 |
* PW_L → L-gated hue enrichment → Lab |
| 8515 |
* |
| 8516 |
* Optimized for perceptually uniform gradients, palette generation, |
| 8517 |
* and color-mix. 59-8 vs OKLab in head-to-head benchmarks (83 metrics, |
| 8518 |
* 3038 gradient pairs, sRGB/P3/Rec.2020). 360/360/360 cusps. |
| 8519 |
* |
| 8520 |
* Key properties: |
| 8521 |
* - Depressed cubic: y³ + αy = x, finite derivative at zero |
| 8522 |
* - Chroma power (0.978): improves gradient CV uniformity |
| 8523 |
* - L-gated hue enrichment: fixes blue→white purple shift |
| 8524 |
* - Structurally achromatic: a=b≈0 for all grays |
| 8525 |
* |
| 8526 |
* Note on blue-region gamut fold: |
| 8527 |
* All M1→f→M2 spaces (OKLab, IPT, HelmGen) exhibit a tiny non-contiguous |
| 8528 |
* gamut region near h≈260° in sRGB. This is a mathematical consequence of |
| 8529 |
* mixing LMS channels before applying a power-like transfer: the inverse |
| 8530 |
* creates a cubic polynomial that can have two positive roots in the blue |
| 8531 |
* region. OKLab has 46 such holes; HelmGen has 5, each ~0.001 chroma wide |
| 8532 |
* (sub-pixel, invisible). See: color.js#81, csswg-drafts#7071. |
| 8533 |
* |
| 8534 |
* Reference: arXiv:2602.23010 |
| 8535 |
* @see https://github.com/Grkmyldz148/helmlab |
| 8536 |
*/ |
| 8537 |
|
| 8538 |
/** @import { Matrix3x3 } from "../types.js" */ |
| 8539 |
|
| 8540 |
// ── Depressed cubic parameter ────────────────────────────────────── |
| 8541 |
const ALPHA = 0.021; |
| 8542 |
const S = Math.sqrt(ALPHA / 3); |
| 8543 |
const S3 = S * S * S; |
| 8544 |
|
| 8545 |
// ── Chroma power ─────────────────────────────────────────────────── |
| 8546 |
const CP = 0.978; |
| 8547 |
|
| 8548 |
// ── L-gated hue enrichment parameters ────────────────────────────── |
| 8549 |
const ENR_AMP = 0.058; |
| 8550 |
const ENR_CENTER = 264.5 * Math.PI / 180; // radians |
| 8551 |
const ENR_SIGMA = 0.7; |
| 8552 |
const ENR_LLO = 0.37; |
| 8553 |
const ENR_LHI = 1.0; |
| 8554 |
|
| 8555 |
// ── Core matrices (v0.11.1) ──────────────────────────────────────── |
| 8556 |
|
| 8557 |
/** |
| 8558 |
* Matrices used by this color space, also available as `HelmGen.M` |
| 8559 |
* @type {Record<string, Matrix3x3>} |
| 8560 |
*/ |
| 8561 |
// prettier-ignore |
| 8562 |
const M$1 = { |
| 8563 |
// M1 = M1_orig @ CAT_TO_HELM (Bradford CAT baked in: Color.js D65 → Helmlab D65 → LMS) |
| 8564 |
M1: [ |
| 8565 |
[ 8.1548321559412884e-01, 3.6033406153856506e-01, -1.2434135574228214e-01], |
| 8566 |
[ 3.3010083527450780e-02, 9.2928650570661686e-01, 3.6121927165754429e-02], |
| 8567 |
[ 4.8188273564568611e-02, 2.6428415753384238e-01, 6.3349717841955344e-01], |
| 8568 |
], |
| 8569 |
M1_INV: [ |
| 8570 |
[ 1.2325947975032656e+00, -5.5575902392875232e-01, 2.7362015347715829e-01], |
| 8571 |
[-4.0801327874216024e-02, 1.1122288637386530e+00, -7.1427535864437813e-02], |
| 8572 |
[-7.6738259283377658e-02, -4.2172784577108585e-01, 1.5875238558143416e+00], |
| 8573 |
], |
| 8574 |
M2: [ |
| 8575 |
[ 0.21193779684470104, 0.7992121834263127, -0.00410075161564345], |
| 8576 |
[ 2.4672018828033475, -2.9877348024830788, 0.520532919679731], |
| 8577 |
[-0.11390787868068575, 1.3932982808117473, -1.279390402131062], |
| 8578 |
], |
| 8579 |
M2_INV: [ |
| 8580 |
[ 0.9930001151336143, 0.32599327253052285, 0.12945085631713921], |
| 8581 |
[ 0.9930001151336139, -0.08708353111074627, -0.03861361743004929], |
| 8582 |
[ 0.9930001151336136, -0.12386097008215022, -0.8351991365871061], |
| 8583 |
], |
| 8584 |
}; |
| 8585 |
|
| 8586 |
// ── Piecewise-linear L correction (21 breakpoints, v0.11.1) ─────── |
| 8587 |
// prettier-ignore |
| 8588 |
const PW_L_IN = [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0]; |
| 8589 |
// prettier-ignore |
| 8590 |
const PW_L_OUT = [0, 0.009494013522189627, 0.02564569838030986, 0.055259661658689105, 0.10574901531227408, 0.16055853320726027, 0.21405964892993756, 0.26786230508811226, 0.3220435246104499, 0.3739052098520243, 0.43020997780918835, 0.4835465162128873, 0.5399824670411353, 0.5956710081330342, 0.6542161666450478, 0.7115380216519989, 0.7702762412711669, 0.8293313467712837, 0.889406386197059, 0.9462829573474728, 1.0]; |
| 8591 |
const PW_N = PW_L_IN.length; |
| 8592 |
|
| 8593 |
// ── Depressed cubic: y³ + αy = x ────────────────────────────────── |
| 8594 |
|
| 8595 |
function depcubicFwd (x) { |
| 8596 |
let t = x / (2 * S3); |
| 8597 |
let y = 2 * S * Math.sinh(Math.asinh(t) / 3); |
| 8598 |
// Halley refinement |
| 8599 |
let f = y * y * y + ALPHA * y - x; |
| 8600 |
let fp = 3 * y * y + ALPHA; |
| 8601 |
let fpp = 6 * y; |
| 8602 |
let denom = 2 * fp * fp - f * fpp; |
| 8603 |
if (Math.abs(denom) > 1e-30) { |
| 8604 |
y -= 2 * f * fp / denom; |
| 8605 |
} |
| 8606 |
return y; |
| 8607 |
} |
| 8608 |
|
| 8609 |
function depcubicInv (y) { |
| 8610 |
return y * y * y + ALPHA * y; |
| 8611 |
} |
| 8612 |
|
| 8613 |
// ── L-gated hue enrichment ───────────────────────────────────────── |
| 8614 |
|
| 8615 |
function enrichGate (L) { |
| 8616 |
let t = Math.max(0, Math.min(1, (L - ENR_LLO) / (ENR_LHI - ENR_LLO))); |
| 8617 |
return Math.sin(Math.PI * t) ** 2; |
| 8618 |
} |
| 8619 |
|
| 8620 |
function enrichFwd (L, a, b) { |
| 8621 |
let C = Math.sqrt(a * a + b * b); |
| 8622 |
if (C < 1e-12) { |
| 8623 |
return [a, b]; |
| 8624 |
} |
| 8625 |
let gate = enrichGate(L); |
| 8626 |
if (gate < 1e-12) { |
| 8627 |
return [a, b]; |
| 8628 |
} |
| 8629 |
let h = Math.atan2(b, a); |
| 8630 |
let dh = h - ENR_CENTER; |
| 8631 |
dh = dh - Math.round(dh / (2 * Math.PI)) * 2 * Math.PI; |
| 8632 |
let gauss = Math.exp(-0.5 * (dh / ENR_SIGMA) ** 2); |
| 8633 |
let hNew = h + ENR_AMP * gate * gauss; |
| 8634 |
return [C * Math.cos(hNew), C * Math.sin(hNew)]; |
| 8635 |
} |
| 8636 |
|
| 8637 |
function enrichInv (L, a, b) { |
| 8638 |
let C = Math.sqrt(a * a + b * b); |
| 8639 |
if (C < 1e-12) { |
| 8640 |
return [a, b]; |
| 8641 |
} |
| 8642 |
let gate = enrichGate(L); |
| 8643 |
if (gate < 1e-12) { |
| 8644 |
return [a, b]; |
| 8645 |
} |
| 8646 |
let hTarget = Math.atan2(b, a); |
| 8647 |
let sig2 = ENR_SIGMA * ENR_SIGMA; |
| 8648 |
let ag = ENR_AMP * gate; |
| 8649 |
let h = hTarget; |
| 8650 |
for (let i = 0; i < 8; i++) { |
| 8651 |
let dh = h - ENR_CENTER; |
| 8652 |
dh = dh - Math.round(dh / (2 * Math.PI)) * 2 * Math.PI; |
| 8653 |
let gauss = Math.exp(-0.5 * dh * dh / sig2); |
| 8654 |
let F = h + ag * gauss - hTarget; |
| 8655 |
let Fp = 1 + ag * gauss * (-dh / sig2); |
| 8656 |
let Fpp = ag * gauss * (-1 / sig2 + dh * dh / (sig2 * sig2)); |
| 8657 |
let den = 2 * Fp * Fp - F * Fpp; |
| 8658 |
if (Math.abs(den) > 1e-30) { |
| 8659 |
h -= 2 * F * Fp / den; |
| 8660 |
} |
| 8661 |
} |
| 8662 |
return [C * Math.cos(h), C * Math.sin(h)]; |
| 8663 |
} |
| 8664 |
|
| 8665 |
// ── PW L correction ─────────────────────────────────────────────── |
| 8666 |
|
| 8667 |
function pwLForward (L) { |
| 8668 |
if (L <= 0 || L >= 1) { |
| 8669 |
return L; |
| 8670 |
} |
| 8671 |
let lo = 0, hi = PW_N - 1; |
| 8672 |
while (hi - lo > 1) { |
| 8673 |
let mid = (lo + hi) >> 1; |
| 8674 |
if (PW_L_IN[mid] <= L) { |
| 8675 |
lo = mid; |
| 8676 |
} |
| 8677 |
else { |
| 8678 |
hi = mid; |
| 8679 |
} |
| 8680 |
} |
| 8681 |
let t = (L - PW_L_IN[lo]) / (PW_L_IN[hi] - PW_L_IN[lo]); |
| 8682 |
return PW_L_OUT[lo] + t * (PW_L_OUT[hi] - PW_L_OUT[lo]); |
| 8683 |
} |
| 8684 |
|
| 8685 |
function pwLInverse (L) { |
| 8686 |
if (L <= PW_L_OUT[0] || L >= PW_L_OUT[PW_N - 1]) { |
| 8687 |
return L; |
| 8688 |
} |
| 8689 |
let lo = 0, hi = PW_N - 1; |
| 8690 |
while (hi - lo > 1) { |
| 8691 |
let mid = (lo + hi) >> 1; |
| 8692 |
if (PW_L_OUT[mid] <= L) { |
| 8693 |
lo = mid; |
| 8694 |
} |
| 8695 |
else { |
| 8696 |
hi = mid; |
| 8697 |
} |
| 8698 |
} |
| 8699 |
let t = (L - PW_L_OUT[lo]) / (PW_L_OUT[hi] - PW_L_OUT[lo]); |
| 8700 |
return PW_L_IN[lo] + t * (PW_L_IN[hi] - PW_L_IN[lo]); |
| 8701 |
} |
| 8702 |
|
| 8703 |
// ── Color space definition ───────────────────────────────────────── |
| 8704 |
|
| 8705 |
var HelmGen = new ColorSpace({ |
| 8706 |
id: "helmgen", |
| 8707 |
name: "HelmGen", |
| 8708 |
cssId: "--helmgen", |
| 8709 |
coords: { |
| 8710 |
l: { |
| 8711 |
refRange: [0, 1], |
| 8712 |
name: "Lightness", |
| 8713 |
}, |
| 8714 |
a: { |
| 8715 |
refRange: [-0.6, 0.6], |
| 8716 |
}, |
| 8717 |
b: { |
| 8718 |
refRange: [-0.6, 0.6], |
| 8719 |
}, |
| 8720 |
}, |
| 8721 |
white: "D65", |
| 8722 |
base: XYZ_D65, |
| 8723 |
|
| 8724 |
M: M$1, |
| 8725 |
|
| 8726 |
fromBase (xyz) { |
| 8727 |
// Stage 1: XYZ → LMS (M1) |
| 8728 |
let lms = multiply_v3_m3x3(xyz, M$1.M1); |
| 8729 |
|
| 8730 |
// Stage 2: Depressed cubic transfer (y³ + αy = x) |
| 8731 |
let c0 = depcubicFwd(Math.max(lms[0], 0)); |
| 8732 |
let c1 = depcubicFwd(Math.max(lms[1], 0)); |
| 8733 |
let c2 = depcubicFwd(Math.max(lms[2], 0)); |
| 8734 |
|
| 8735 |
// Stage 2.5: Smooth neutral blend (C∞ correction for achromatic precision) |
| 8736 |
{ |
| 8737 |
let mean = (c0 + c1 + c2) / 3; |
| 8738 |
let mx = Math.max(c0, c1, c2); |
| 8739 |
let mn = Math.min(c0, c1, c2); |
| 8740 |
let spread = (mx - mn) / Math.max(Math.abs(mean), 1e-30); |
| 8741 |
let w = Math.exp(-((spread / 1e-5) ** 2)); |
| 8742 |
c0 += w * (mean - c0); |
| 8743 |
c1 += w * (mean - c1); |
| 8744 |
c2 += w * (mean - c2); |
| 8745 |
} |
| 8746 |
|
| 8747 |
// Stage 3: LMS_c → Lab (M2) |
| 8748 |
let [L, a, b] = multiply_v3_m3x3([c0, c1, c2], M$1.M2); |
| 8749 |
|
| 8750 |
// Stage 3.5: Chroma power (cp=0.978) |
| 8751 |
{ |
| 8752 |
let C = Math.sqrt(a * a + b * b); |
| 8753 |
if (C > 1e-12) { |
| 8754 |
let Cnew = Math.pow(C, CP); |
| 8755 |
let s = Cnew / C; |
| 8756 |
a *= s; |
| 8757 |
b *= s; |
| 8758 |
} |
| 8759 |
} |
| 8760 |
|
| 8761 |
// Stage 4: Piecewise-linear L correction |
| 8762 |
L = pwLForward(L); |
| 8763 |
|
| 8764 |
// Stage 5: L-gated hue enrichment |
| 8765 |
[a, b] = enrichFwd(L, a, b); |
| 8766 |
|
| 8767 |
return [L, a, b]; |
| 8768 |
}, |
| 8769 |
|
| 8770 |
toBase (lab) { |
| 8771 |
let [L, a, b] = lab; |
| 8772 |
|
| 8773 |
// Undo Stage 5: L-gated hue enrichment |
| 8774 |
[a, b] = enrichInv(L, a, b); |
| 8775 |
|
| 8776 |
// Undo Stage 4: PW L correction |
| 8777 |
L = pwLInverse(L); |
| 8778 |
|
| 8779 |
// Undo Stage 3.5: Chroma power inverse (C^(1/cp)) |
| 8780 |
{ |
| 8781 |
let C = Math.sqrt(a * a + b * b); |
| 8782 |
if (C > 1e-12) { |
| 8783 |
let Corig = Math.pow(C, 1 / CP); |
| 8784 |
let s = Corig / C; |
| 8785 |
a *= s; |
| 8786 |
b *= s; |
| 8787 |
} |
| 8788 |
} |
| 8789 |
|
| 8790 |
// Undo Stage 3: Lab → LMS_c (M2_inv) |
| 8791 |
let [lc0, lc1, lc2] = multiply_v3_m3x3([L, a, b], M$1.M2_INV); |
| 8792 |
|
| 8793 |
// Undo Stage 2.5: Smooth neutral blend |
| 8794 |
{ |
| 8795 |
let mean = (lc0 + lc1 + lc2) / 3; |
| 8796 |
let mx = Math.max(lc0, lc1, lc2); |
| 8797 |
let mn = Math.min(lc0, lc1, lc2); |
| 8798 |
let spread = (mx - mn) / Math.max(Math.abs(mean), 1e-30); |
| 8799 |
let w = Math.exp(-((spread / 1e-5) ** 2)); |
| 8800 |
lc0 += w * (mean - lc0); |
| 8801 |
lc1 += w * (mean - lc1); |
| 8802 |
lc2 += w * (mean - lc2); |
| 8803 |
} |
| 8804 |
|
| 8805 |
// Undo Stage 2: Inverse depressed cubic (x = y³ + αy) |
| 8806 |
let l0 = depcubicInv(lc0); |
| 8807 |
let l1 = depcubicInv(lc1); |
| 8808 |
let l2 = depcubicInv(lc2); |
| 8809 |
|
| 8810 |
// Undo Stage 1: LMS → XYZ (M1_inv) |
| 8811 |
return multiply_v3_m3x3([l0, l1, l2], M$1.M1_INV); |
| 8812 |
}, |
| 8813 |
}); |
| 8814 |
|
| 8815 |
/** |
| 8816 |
* HelmGenLCh — cylindrical form of Helmlab GenSpace. |
| 8817 |
* |
| 8818 |
* Converts GenSpace's rectangular (L, a, b) coordinates to |
| 8819 |
* cylindrical (L, C, h). Ideal for CSS interpolation contexts |
| 8820 |
* like gradients and color-mix where hue angle matters. |
| 8821 |
* |
| 8822 |
* @see https://github.com/Grkmyldz148/helmlab |
| 8823 |
*/ |
| 8824 |
|
| 8825 |
var helmgenlch = new ColorSpace({ |
| 8826 |
id: "helmgenlch", |
| 8827 |
name: "HelmGenLCh", |
| 8828 |
cssId: "--helmgenlch", |
| 8829 |
coords: { |
| 8830 |
l: { |
| 8831 |
refRange: [0, 1], |
| 8832 |
name: "Lightness", |
| 8833 |
}, |
| 8834 |
c: { |
| 8835 |
refRange: [0, 0.65], |
| 8836 |
name: "Chroma", |
| 8837 |
}, |
| 8838 |
h: { |
| 8839 |
refRange: [0, 360], |
| 8840 |
type: "angle", |
| 8841 |
name: "Hue", |
| 8842 |
}, |
| 8843 |
}, |
| 8844 |
white: "D65", |
| 8845 |
|
| 8846 |
base: HelmGen, |
| 8847 |
fromBase: lch.fromBase, |
| 8848 |
toBase: lch.toBase, |
| 8849 |
}); |
| 8850 |
|
| 8851 |
var REC_2100_Linear = new RGBColorSpace({ |
| 8852 |
id: "rec2100-linear", |
| 8853 |
name: "Linear REC.2100", |
| 8854 |
white: "D65", |
| 8855 |
M: M$8, |
| 8856 |
}); |
| 8857 |
|
| 8858 |
const Yw = 203; // absolute luminance of media white, cd/m² |
| 8859 |
const n = 2610 / 2 ** 14; |
| 8860 |
const ninv = 2 ** 14 / 2610; |
| 8861 |
const m = 2523 / 2 ** 5; |
| 8862 |
const minv = 2 ** 5 / 2523; |
| 8863 |
const c1 = 3424 / 2 ** 12; |
| 8864 |
const c2 = 2413 / 2 ** 7; |
| 8865 |
const c3 = 2392 / 2 ** 7; |
| 8866 |
|
| 8867 |
var rec2100Pq = new RGBColorSpace({ |
| 8868 |
id: "rec2100pq", |
| 8869 |
cssId: "rec2100-pq", |
| 8870 |
name: "REC.2100-PQ", |
| 8871 |
base: REC_2100_Linear, |
| 8872 |
linearGamut: REC_2100_Linear, |
| 8873 |
toBase (RGB) { |
| 8874 |
// given PQ encoded component in range [0, 1] |
| 8875 |
// return media-white relative linear-light |
| 8876 |
return RGB.map(function (val) { |
| 8877 |
let x = (Math.max(val ** minv - c1, 0) / (c2 - c3 * val ** minv)) ** ninv; |
| 8878 |
return (x * 10000) / Yw; // luminance relative to diffuse white, [0, 70 or so]. |
| 8879 |
}); |
| 8880 |
}, |
| 8881 |
fromBase (RGB) { |
| 8882 |
// given media-white relative linear-light |
| 8883 |
// returnPQ encoded component in range [0, 1] |
| 8884 |
return RGB.map(function (val) { |
| 8885 |
let x = Math.max((val * Yw) / 10000, 0); // absolute luminance of peak white is 10,000 cd/m². |
| 8886 |
let num = c1 + c2 * x ** n; |
| 8887 |
let denom = 1 + c3 * x ** n; |
| 8888 |
|
| 8889 |
return (num / denom) ** m; |
| 8890 |
}); |
| 8891 |
}, |
| 8892 |
}); |
| 8893 |
|
| 8894 |
const a = 0.17883277; |
| 8895 |
const b = 0.28466892; // 1 - (4 * a) |
| 8896 |
const c = 0.55991073; // 0.5 - a * Math.log(4 *a) |
| 8897 |
|
| 8898 |
const scale = 3.7743; // Place 18% grey at HLG 0.38, so media white at 0.75 |
| 8899 |
|
| 8900 |
var rec2100Hlg = new RGBColorSpace({ |
| 8901 |
id: "rec2100hlg", |
| 8902 |
cssId: "rec2100-hlg", |
| 8903 |
name: "REC.2100-HLG", |
| 8904 |
referred: "scene", |
| 8905 |
|
| 8906 |
base: REC_2100_Linear, |
| 8907 |
linearGamut: REC_2100_Linear, |
| 8908 |
toBase (RGB) { |
| 8909 |
// given HLG encoded component in range [0, 1] |
| 8910 |
// return media-white relative linear-light |
| 8911 |
return RGB.map(function (val) { |
| 8912 |
// first the HLG EOTF |
| 8913 |
// ITU-R BT.2390-10 p.30 section |
| 8914 |
// 6.3 The hybrid log-gamma electro-optical transfer function (EOTF) |
| 8915 |
// Then scale by 3 so media white is 1.0 |
| 8916 |
if (val <= 0.5) { |
| 8917 |
return (val ** 2 / 3) * scale; |
| 8918 |
} |
| 8919 |
return ((Math.exp((val - c) / a) + b) / 12) * scale; |
| 8920 |
}); |
| 8921 |
}, |
| 8922 |
fromBase (RGB) { |
| 8923 |
// given media-white relative linear-light |
| 8924 |
// where diffuse white is 1.0, |
| 8925 |
// return HLG encoded component in range [0, 1] |
| 8926 |
return RGB.map(function (val) { |
| 8927 |
// first scale to put linear-light media white at 1/3 |
| 8928 |
val /= scale; |
| 8929 |
// now the HLG OETF |
| 8930 |
// ITU-R BT.2390-10 p.23 |
| 8931 |
// 6.1 The hybrid log-gamma opto-electronic transfer function (OETF) |
| 8932 |
if (val <= 1 / 12) { |
| 8933 |
return spow(3 * val, 0.5); |
| 8934 |
} |
| 8935 |
return a * Math.log(12 * val - b) + c; |
| 8936 |
}); |
| 8937 |
}, |
| 8938 |
}); |
| 8939 |
|
| 8940 |
/** @import { White } from "./types.js" */ |
| 8941 |
|
| 8942 |
// Type re-exports |
| 8943 |
/** @typedef {import("./types.js").CAT} CAT */ |
| 8944 |
|
| 8945 |
/** @type {Record<string, CAT>} */ |
| 8946 |
const CATs = {}; |
| 8947 |
|
| 8948 |
hooks.add("chromatic-adaptation-start", env => { |
| 8949 |
if (env.options.method) { |
| 8950 |
env.M = adapt(env.W1, env.W2, env.options.method); |
| 8951 |
} |
| 8952 |
}); |
| 8953 |
|
| 8954 |
hooks.add("chromatic-adaptation-end", env => { |
| 8955 |
if (!env.M) { |
| 8956 |
env.M = adapt(env.W1, env.W2, env.options.method); |
| 8957 |
} |
| 8958 |
}); |
| 8959 |
|
| 8960 |
function defineCAT (/** @type {CAT} */ { id, toCone_M, fromCone_M }) { |
| 8961 |
// Use id, toCone_M, fromCone_M like variables |
| 8962 |
CATs[id] = arguments[0]; |
| 8963 |
} |
| 8964 |
|
| 8965 |
/** |
| 8966 |
* |
| 8967 |
* @param {White} W1 |
| 8968 |
* @param {White} W2 |
| 8969 |
* @param {string} id |
| 8970 |
* @returns {number[][]} |
| 8971 |
*/ |
| 8972 |
function adapt (W1, W2, id = "Bradford") { |
| 8973 |
// adapt from a source whitepoint or illuminant W1 |
| 8974 |
// to a destination whitepoint or illuminant W2, |
| 8975 |
// using the given chromatic adaptation transform (CAT) |
| 8976 |
// debugger; |
| 8977 |
let method = CATs[id]; |
| 8978 |
|
| 8979 |
let [ρs, γs, βs] = multiplyMatrices(method.toCone_M, W1); |
| 8980 |
let [ρd, γd, βd] = multiplyMatrices(method.toCone_M, W2); |
| 8981 |
|
| 8982 |
// all practical illuminants have non-zero XYZ so no division by zero can occur below |
| 8983 |
// prettier-ignore |
| 8984 |
let scale = [ |
| 8985 |
[ρd / ρs, 0, 0 ], |
| 8986 |
[0, γd / γs, 0 ], |
| 8987 |
[0, 0, βd / βs], |
| 8988 |
]; |
| 8989 |
// console.log({scale}); |
| 8990 |
|
| 8991 |
let scaled_cone_M = multiplyMatrices(scale, method.toCone_M); |
| 8992 |
let adapt_M = multiplyMatrices(method.fromCone_M, scaled_cone_M); |
| 8993 |
// console.log({scaled_cone_M, adapt_M}); |
| 8994 |
return adapt_M; |
| 8995 |
} |
| 8996 |
|
| 8997 |
// prettier-ignore |
| 8998 |
defineCAT({ |
| 8999 |
id: "von Kries", |
| 9000 |
toCone_M: [ |
| 9001 |
[ 0.4002400, 0.7076000, -0.0808100 ], |
| 9002 |
[ -0.2263000, 1.1653200, 0.0457000 ], |
| 9003 |
[ 0.0000000, 0.0000000, 0.9182200 ], |
| 9004 |
], |
| 9005 |
fromCone_M: [ |
| 9006 |
[ 1.8599363874558397, -1.1293816185800916, 0.21989740959619328 ], |
| 9007 |
[ 0.3611914362417676, 0.6388124632850422, -0.000006370596838649899 ], |
| 9008 |
[ 0, 0, 1.0890636230968613 ], |
| 9009 |
], |
| 9010 |
}); |
| 9011 |
|
| 9012 |
// prettier-ignore |
| 9013 |
defineCAT({ |
| 9014 |
id: "Bradford", |
| 9015 |
// Convert an array of XYZ values in the range 0.0 - 1.0 |
| 9016 |
// to cone fundamentals |
| 9017 |
toCone_M: [ |
| 9018 |
[ 0.8951000, 0.2664000, -0.1614000 ], |
| 9019 |
[ -0.7502000, 1.7135000, 0.0367000 ], |
| 9020 |
[ 0.0389000, -0.0685000, 1.0296000 ], |
| 9021 |
], |
| 9022 |
// and back |
| 9023 |
fromCone_M: [ |
| 9024 |
[ 0.9869929054667121, -0.14705425642099013, 0.15996265166373122 ], |
| 9025 |
[ 0.4323052697233945, 0.5183602715367774, 0.049291228212855594 ], |
| 9026 |
[ -0.00852866457517732, 0.04004282165408486, 0.96848669578755 ], |
| 9027 |
], |
| 9028 |
}); |
| 9029 |
|
| 9030 |
// prettier-ignore |
| 9031 |
defineCAT({ |
| 9032 |
id: "CAT02", |
| 9033 |
// with complete chromatic adaptation to W2, so D = 1.0 |
| 9034 |
toCone_M: [ |
| 9035 |
[ 0.7328000, 0.4296000, -0.1624000 ], |
| 9036 |
[ -0.7036000, 1.6975000, 0.0061000 ], |
| 9037 |
[ 0.0030000, 0.0136000, 0.9834000 ], |
| 9038 |
], |
| 9039 |
fromCone_M: [ |
| 9040 |
[ 1.0961238208355142, -0.27886900021828726, 0.18274517938277307 ], |
| 9041 |
[ 0.4543690419753592, 0.4735331543074117, 0.07209780371722911 ], |
| 9042 |
[ -0.009627608738429355, -0.00569803121611342, 1.0153256399545427 ], |
| 9043 |
], |
| 9044 |
}); |
| 9045 |
|
| 9046 |
// prettier-ignore |
| 9047 |
defineCAT({ |
| 9048 |
id: "CAT16", |
| 9049 |
toCone_M: [ |
| 9050 |
[ 0.401288, 0.650173, -0.051461 ], |
| 9051 |
[ -0.250268, 1.204414, 0.045854 ], |
| 9052 |
[ -0.002079, 0.048952, 0.953127 ], |
| 9053 |
], |
| 9054 |
// the extra precision is needed to avoid roundtripping errors |
| 9055 |
fromCone_M: [ |
| 9056 |
[ 1.862067855087233, -1.0112546305316845, 0.14918677544445172 ], |
| 9057 |
[ 0.3875265432361372, 0.6214474419314753, -0.008973985167612521 ], |
| 9058 |
[ -0.01584149884933386, -0.03412293802851557, 1.0499644368778496 ], |
| 9059 |
], |
| 9060 |
}); |
| 9061 |
|
| 9062 |
// prettier-ignore |
| 9063 |
Object.assign(WHITES, { |
| 9064 |
// whitepoint values from ASTM E308-01 with 10nm spacing, 1931 2 degree observer |
| 9065 |
// all normalized to Y (luminance) = 1.00000 |
| 9066 |
// Illuminant A is a tungsten electric light, giving a very warm, orange light. |
| 9067 |
A: [1.09850, 1.00000, 0.35585], |
| 9068 |
|
| 9069 |
// Illuminant C was an early approximation to daylight: illuminant A with a blue filter. |
| 9070 |
C: [0.98074, 1.000000, 1.18232], |
| 9071 |
|
| 9072 |
// The daylight series of illuminants simulate natural daylight. |
| 9073 |
// The color temperature (in degrees Kelvin/100) ranges from |
| 9074 |
// cool, overcast daylight (D50) to bright, direct sunlight (D65). |
| 9075 |
D55: [0.95682, 1.00000, 0.92149], |
| 9076 |
D75: [0.94972, 1.00000, 1.22638], |
| 9077 |
|
| 9078 |
// Equal-energy illuminant, used in two-stage CAT16 |
| 9079 |
E: [1.00000, 1.00000, 1.00000], |
| 9080 |
|
| 9081 |
// The F series of illuminants represent fluorescent lights |
| 9082 |
F2: [0.99186, 1.00000, 0.67393], |
| 9083 |
F7: [0.95041, 1.00000, 1.08747], |
| 9084 |
F11: [1.00962, 1.00000, 0.64350], |
| 9085 |
}); |
| 9086 |
|
| 9087 |
/** @import { Matrix3x3 } from "../types.js" */ |
| 9088 |
|
| 9089 |
// The ACES whitepoint |
| 9090 |
// see TB-2018-001 Derivation of the ACES White Point CIE Chromaticity Coordinates |
| 9091 |
// also https://github.com/ampas/aces-dev/blob/master/documents/python/TB-2018-001/aces_wp.py |
| 9092 |
// Similar to D60 |
| 9093 |
WHITES.ACES = [0.32168 / 0.33767, 1.0, (1.0 - 0.32168 - 0.33767) / 0.33767]; |
| 9094 |
|
| 9095 |
/** |
| 9096 |
* Matrices used by this color space, also available as `ACEScg.M` |
| 9097 |
* @type {Record<string, Matrix3x3>} |
| 9098 |
*/ |
| 9099 |
// prettier-ignore |
| 9100 |
const M = { |
| 9101 |
// convert an array of linear-light ACEScg values to CIE XYZ |
| 9102 |
toXYZ: [ |
| 9103 |
[ 0.6624541811085053, 0.13400420645643313, 0.1561876870049078 ], |
| 9104 |
[ 0.27222871678091454, 0.6740817658111484, 0.05368951740793705 ], |
| 9105 |
[ -0.005574649490394108, 0.004060733528982826, 1.0103391003129971 ], |
| 9106 |
], |
| 9107 |
fromXYZ: [ |
| 9108 |
[ 1.6410233796943257, -0.32480329418479, -0.23642469523761225 ], |
| 9109 |
[ -0.6636628587229829, 1.6153315916573379, 0.016756347685530137 ], |
| 9110 |
[ 0.011721894328375376, -0.008284441996237409, 0.9883948585390215 ], |
| 9111 |
], |
| 9112 |
}; |
| 9113 |
|
| 9114 |
var ACEScg = new RGBColorSpace({ |
| 9115 |
id: "acescg", |
| 9116 |
cssId: "--acescg", |
| 9117 |
name: "ACEScg", |
| 9118 |
|
| 9119 |
// ACEScg – A scene-referred, linear-light encoding of ACES Data |
| 9120 |
// https://docs.acescentral.com/specifications/acescg/ |
| 9121 |
// uses the AP1 primaries, see section 4.3.1 Color primaries |
| 9122 |
coords: { |
| 9123 |
r: { |
| 9124 |
range: [0, 65504], |
| 9125 |
name: "Red", |
| 9126 |
}, |
| 9127 |
g: { |
| 9128 |
range: [0, 65504], |
| 9129 |
name: "Green", |
| 9130 |
}, |
| 9131 |
b: { |
| 9132 |
range: [0, 65504], |
| 9133 |
name: "Blue", |
| 9134 |
}, |
| 9135 |
}, |
| 9136 |
|
| 9137 |
referred: "scene", |
| 9138 |
|
| 9139 |
white: WHITES.ACES, |
| 9140 |
|
| 9141 |
M, |
| 9142 |
}); |
| 9143 |
|
| 9144 |
// export default Color; |
| 9145 |
|
| 9146 |
const ε = 2 ** -16; |
| 9147 |
|
| 9148 |
// the smallest value which, in the 32bit IEEE 754 float encoding, |
| 9149 |
// decodes as a non-negative value |
| 9150 |
const ACES_min_nonzero = -0.35828683; |
| 9151 |
|
| 9152 |
// brightest encoded value, decodes to 65504 |
| 9153 |
const ACES_cc_max = (Math.log2(65504) + 9.72) / 17.52; // 1.468 |
| 9154 |
|
| 9155 |
var acescc = new RGBColorSpace({ |
| 9156 |
id: "acescc", |
| 9157 |
cssId: "--acescc", |
| 9158 |
name: "ACEScc", |
| 9159 |
// see S-2014-003 ACEScc – A Logarithmic Encoding of ACES Data |
| 9160 |
// https://docs.acescentral.com/specifications/acescc/ |
| 9161 |
// uses the AP1 primaries, see section 4.3.1 Color primaries |
| 9162 |
|
| 9163 |
// Appendix A: "Very small ACES scene referred values below 7 1/4 stops |
| 9164 |
// below 18% middle gray are encoded as negative ACEScc values. |
| 9165 |
// These values should be preserved per the encoding in Section 4.4 |
| 9166 |
// so that all positive ACES values are maintained." |
| 9167 |
coords: { |
| 9168 |
r: { |
| 9169 |
range: [ACES_min_nonzero, ACES_cc_max], |
| 9170 |
name: "Red", |
| 9171 |
}, |
| 9172 |
g: { |
| 9173 |
range: [ACES_min_nonzero, ACES_cc_max], |
| 9174 |
name: "Green", |
| 9175 |
}, |
| 9176 |
b: { |
| 9177 |
range: [ACES_min_nonzero, ACES_cc_max], |
| 9178 |
name: "Blue", |
| 9179 |
}, |
| 9180 |
}, |
| 9181 |
referred: "scene", |
| 9182 |
|
| 9183 |
base: ACEScg, |
| 9184 |
linearGamut: ACEScg, |
| 9185 |
// from section 4.4.2 Decoding Function |
| 9186 |
toBase (RGB) { |
| 9187 |
const low = (9.72 - 15) / 17.52; // -0.3014 |
| 9188 |
|
| 9189 |
return RGB.map(function (val) { |
| 9190 |
if (val <= low) { |
| 9191 |
return (2 ** (val * 17.52 - 9.72) - ε) * 2; // very low values, below -0.3014 |
| 9192 |
} |
| 9193 |
else if (val < ACES_cc_max) { |
| 9194 |
return 2 ** (val * 17.52 - 9.72); |
| 9195 |
} |
| 9196 |
else { |
| 9197 |
// val >= ACES_cc_max |
| 9198 |
return 65504; |
| 9199 |
} |
| 9200 |
}); |
| 9201 |
}, |
| 9202 |
|
| 9203 |
// Non-linear encoding function from S-2014-003, section 4.4.1 Encoding Function |
| 9204 |
fromBase (RGB) { |
| 9205 |
return RGB.map(function (val) { |
| 9206 |
if (val <= 0) { |
| 9207 |
return (Math.log2(ε) + 9.72) / 17.52; // -0.3584 |
| 9208 |
} |
| 9209 |
else if (val < ε) { |
| 9210 |
return (Math.log2(ε + val * 0.5) + 9.72) / 17.52; |
| 9211 |
} |
| 9212 |
else { |
| 9213 |
// val >= ε |
| 9214 |
return (Math.log2(val) + 9.72) / 17.52; |
| 9215 |
} |
| 9216 |
}); |
| 9217 |
}, |
| 9218 |
// encoded media white (rgb 1,1,1) => linear [ 222.861, 222.861, 222.861 ] |
| 9219 |
// encoded media black (rgb 0,0,0) => linear [ 0.0011857, 0.0011857, 0.0011857] |
| 9220 |
}); |
| 9221 |
|
| 9222 |
/** |
| 9223 |
* @packageDocumentation |
| 9224 |
* Re-exports all the spaces built into Color.js. |
| 9225 |
*/ |
| 9226 |
|
| 9227 |
var spaces = /*#__PURE__*/Object.freeze({ |
| 9228 |
__proto__: null, |
| 9229 |
A98RGB: a98rgb, |
| 9230 |
A98RGB_Linear: A98Linear, |
| 9231 |
ACEScc: acescc, |
| 9232 |
ACEScg: ACEScg, |
| 9233 |
CAM16_JMh: cam16, |
| 9234 |
HCT: hct, |
| 9235 |
HPLuv: HPLuv, |
| 9236 |
HSL: HSL, |
| 9237 |
HSL_P3: hslP3, |
| 9238 |
HSL_REC2020: hslRec2020, |
| 9239 |
HSLuv: hsluv, |
| 9240 |
HSV: HSV, |
| 9241 |
HWB: hwb, |
| 9242 |
HelmGen: HelmGen, |
| 9243 |
HelmGenLCh: helmgenlch, |
| 9244 |
Helmlab: helmlab, |
| 9245 |
ICTCP: ictcp, |
| 9246 |
JzCzHz: jzczhz, |
| 9247 |
Jzazbz: Jzazbz, |
| 9248 |
LCH: lch, |
| 9249 |
LCH_P3: lchP3, |
| 9250 |
LCH_REC_2020: lchRec2020, |
| 9251 |
LCH_sRGB: lchSrgb, |
| 9252 |
LCHuv: LCHuv, |
| 9253 |
Lab: lab, |
| 9254 |
Lab_D65: lab_d65, |
| 9255 |
Luv: Luv, |
| 9256 |
OKLCH: OKLCH, |
| 9257 |
OKLCH_P3: oklchP3, |
| 9258 |
OKLCH_REC_2020: oklchRec2020, |
| 9259 |
OKLCH_sRGB: oklchSrgb, |
| 9260 |
OKLab: Oklab, |
| 9261 |
OKLrCH: oklrch, |
| 9262 |
OKLrab: OKLrab, |
| 9263 |
Okhsl: Okhsl, |
| 9264 |
Okhsv: Okhsv, |
| 9265 |
P3: P3, |
| 9266 |
P3_Linear: P3Linear, |
| 9267 |
ProPhoto: prophoto, |
| 9268 |
ProPhoto_Linear: ProPhotoLinear, |
| 9269 |
REC_2020: REC2020, |
| 9270 |
REC_2020_Linear: REC2020Linear, |
| 9271 |
REC_2020_Scene_Referred: rec2020Oetf, |
| 9272 |
REC_2100_HLG: rec2100Hlg, |
| 9273 |
REC_2100_Linear: REC_2100_Linear, |
| 9274 |
REC_2100_PQ: rec2100Pq, |
| 9275 |
XYZ_ABS_D65: XYZ_Abs_D65, |
| 9276 |
XYZ_D50: XYZ_D50, |
| 9277 |
XYZ_D65: XYZ_D65, |
| 9278 |
sRGB: sRGB, |
| 9279 |
sRGB_Linear: sRGBLinear |
| 9280 |
}); |
| 9281 |
|
| 9282 |
/** |
| 9283 |
* @packageDocumentation |
| 9284 |
* @class Color |
| 9285 |
* Class that represents a single color. |
| 9286 |
* All of Color.js’s tree-shakeable methods are also available as instance methods on this class, |
| 9287 |
* as well as static methods that take the color as the first argument. |
| 9288 |
*/ |
| 9289 |
|
| 9290 |
|
| 9291 |
class Color { |
| 9292 |
/** |
| 9293 |
* Creates an instance of Color. |
| 9294 |
* Signatures: |
| 9295 |
* - `new Color(stringToParse)` |
| 9296 |
* - `new Color(otherColor)` |
| 9297 |
* - `new Color({space, coords, alpha})` |
| 9298 |
* - `new Color(space, coords, alpha)` |
| 9299 |
* - `new Color(spaceId, coords, alpha)` |
| 9300 |
*/ |
| 9301 |
constructor (...args) { |
| 9302 |
let color; |
| 9303 |
|
| 9304 |
if (args.length === 1) { |
| 9305 |
let parseMeta = {}; |
| 9306 |
// Clone simple objects to avoid mutating original in getColor |
| 9307 |
if ( |
| 9308 |
typeof args[0] === "object" && |
| 9309 |
Object.getPrototypeOf(args[0]).constructor === Object |
| 9310 |
) { |
| 9311 |
args[0] = { ...args[0] }; |
| 9312 |
} |
| 9313 |
color = getColor(args[0], { parseMeta }); |
| 9314 |
|
| 9315 |
if (parseMeta.format) { |
| 9316 |
// Color actually came from a string |
| 9317 |
this.parseMeta = parseMeta; |
| 9318 |
} |
| 9319 |
} |
| 9320 |
|
| 9321 |
let space, coords, alpha; |
| 9322 |
|
| 9323 |
if (color) { |
| 9324 |
space = color.space || color.spaceId; |
| 9325 |
coords = color.coords; |
| 9326 |
alpha = color.alpha; |
| 9327 |
} |
| 9328 |
else { |
| 9329 |
// default signature new Color(ColorSpace, array [, alpha]) |
| 9330 |
[space, coords, alpha] = args; |
| 9331 |
} |
| 9332 |
|
| 9333 |
Object.defineProperty(this, "space", { |
| 9334 |
value: ColorSpace.get(space), |
| 9335 |
writable: false, |
| 9336 |
enumerable: true, |
| 9337 |
configurable: true, // see note in https://262.ecma-international.org/8.0/#sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver |
| 9338 |
}); |
| 9339 |
|
| 9340 |
this.coords = coords ? coords.slice() : [0, 0, 0]; |
| 9341 |
|
| 9342 |
// Clamp alpha to [0, 1] |
| 9343 |
this.alpha = isNone(alpha) ? alpha : alpha === undefined ? 1 : clamp(0, alpha, 1); |
| 9344 |
|
| 9345 |
// Define getters and setters for each coordinate |
| 9346 |
for (let id in this.space.coords) { |
| 9347 |
Object.defineProperty(this, id, { |
| 9348 |
get: () => this.get(id), |
| 9349 |
set: value => this.set(id, value), |
| 9350 |
}); |
| 9351 |
} |
| 9352 |
} |
| 9353 |
|
| 9354 |
get spaceId () { |
| 9355 |
return this.space.id; |
| 9356 |
} |
| 9357 |
|
| 9358 |
clone () { |
| 9359 |
return new Color(this.space, this.coords, this.alpha); |
| 9360 |
} |
| 9361 |
|
| 9362 |
toJSON () { |
| 9363 |
return { |
| 9364 |
spaceId: this.spaceId, |
| 9365 |
coords: this.coords, |
| 9366 |
alpha: this.alpha, |
| 9367 |
}; |
| 9368 |
} |
| 9369 |
|
| 9370 |
display (...args) { |
| 9371 |
let ret = display(this, ...args); |
| 9372 |
|
| 9373 |
// Convert color object to Color instance |
| 9374 |
ret.color = new Color(ret.color); |
| 9375 |
|
| 9376 |
return ret; |
| 9377 |
} |
| 9378 |
|
| 9379 |
/** |
| 9380 |
* Get a color from the argument(s) passed |
| 9381 |
* Basically gets us the same result as new Color(color) but doesn't clone an existing color object |
| 9382 |
*/ |
| 9383 |
static get (color, ...args) { |
| 9384 |
if (isInstance(color, this)) { |
| 9385 |
return color; |
| 9386 |
} |
| 9387 |
|
| 9388 |
return new Color(color, ...args); |
| 9389 |
} |
| 9390 |
|
| 9391 |
/** |
| 9392 |
* Get a color instance from the argument passed or `null` if resolution fails (instead of throwing an error). |
| 9393 |
* Additionally, it supports passing an element to resolve complex CSS colors through the DOM (slow). |
| 9394 |
* @see {@link tryColor} for more details |
| 9395 |
*/ |
| 9396 |
static try (color, options) { |
| 9397 |
if (isInstance(color, this)) { |
| 9398 |
return color; |
| 9399 |
} |
| 9400 |
|
| 9401 |
let ret = tryColor(color, options); |
| 9402 |
|
| 9403 |
if (ret) { |
| 9404 |
return new Color(ret); |
| 9405 |
} |
| 9406 |
|
| 9407 |
return null; |
| 9408 |
} |
| 9409 |
|
| 9410 |
static defineFunction (name, code, o = code) { |
| 9411 |
let { instance = true, returns } = o; |
| 9412 |
|
| 9413 |
let func = function (...args) { |
| 9414 |
let ret = code(...args); |
| 9415 |
|
| 9416 |
if (returns === "color") { |
| 9417 |
ret = Color.get(ret); |
| 9418 |
} |
| 9419 |
else if (returns === "function<color>") { |
| 9420 |
let f = ret; |
| 9421 |
ret = function (...args) { |
| 9422 |
let ret = f(...args); |
| 9423 |
return Color.get(ret); |
| 9424 |
}; |
| 9425 |
// Copy any function metadata |
| 9426 |
Object.assign(ret, f); |
| 9427 |
} |
| 9428 |
else if (returns === "array<color>") { |
| 9429 |
ret = ret.map(c => Color.get(c)); |
| 9430 |
} |
| 9431 |
|
| 9432 |
return ret; |
| 9433 |
}; |
| 9434 |
|
| 9435 |
if (!(name in Color)) { |
| 9436 |
Color[name] = func; |
| 9437 |
} |
| 9438 |
|
| 9439 |
if (instance) { |
| 9440 |
Color.prototype[name] = function (...args) { |
| 9441 |
return func(this, ...args); |
| 9442 |
}; |
| 9443 |
} |
| 9444 |
} |
| 9445 |
|
| 9446 |
static defineFunctions (o) { |
| 9447 |
for (let name in o) { |
| 9448 |
Color.defineFunction(name, o[name], o[name]); |
| 9449 |
} |
| 9450 |
} |
| 9451 |
|
| 9452 |
static extend (exports) { |
| 9453 |
if (exports.register) { |
| 9454 |
exports.register(Color); |
| 9455 |
} |
| 9456 |
else { |
| 9457 |
// No register method, just add the module's functions |
| 9458 |
for (let name in exports) { |
| 9459 |
Color.defineFunction(name, exports[name]); |
| 9460 |
} |
| 9461 |
} |
| 9462 |
} |
| 9463 |
} |
| 9464 |
|
| 9465 |
Color.defineFunctions({ |
| 9466 |
get, |
| 9467 |
getAll, |
| 9468 |
set, |
| 9469 |
setAll, |
| 9470 |
to, |
| 9471 |
equals, |
| 9472 |
inGamut, |
| 9473 |
toGamut, |
| 9474 |
distance, |
| 9475 |
deltas, |
| 9476 |
toString: serialize, |
| 9477 |
}); |
| 9478 |
|
| 9479 |
Object.assign(Color, { |
| 9480 |
util, |
| 9481 |
hooks, |
| 9482 |
WHITES, |
| 9483 |
Space: ColorSpace, |
| 9484 |
spaces: ColorSpace.registry, |
| 9485 |
parse, |
| 9486 |
|
| 9487 |
// Global defaults one may want to configure |
| 9488 |
defaults, |
| 9489 |
}); |
| 9490 |
|
| 9491 |
/** |
| 9492 |
* @packageDocumentation |
| 9493 |
* This module contains {@link spaces a namespace} with all the spaces built into Color.js. |
| 9494 |
*/ |
| 9495 |
|
| 9496 |
for (let key of Object.keys(spaces)) { |
| 9497 |
ColorSpace.register(spaces[key]); |
| 9498 |
} |
| 9499 |
|
| 9500 |
/** |
| 9501 |
* This plugin defines getters and setters for color[spaceId] |
| 9502 |
* e.g. color.lch on *any* color gives us the lch coords |
| 9503 |
*/ |
| 9504 |
|
| 9505 |
// Add space accessors to existing color spaces |
| 9506 |
for (let id in ColorSpace.registry) { |
| 9507 |
addSpaceAccessors(id, ColorSpace.registry[id]); |
| 9508 |
} |
| 9509 |
|
| 9510 |
// Add space accessors to color spaces not yet created |
| 9511 |
hooks.add("colorspace-init-end", space => { |
| 9512 |
addSpaceAccessors(space.id, space); |
| 9513 |
space.aliases?.forEach(alias => { |
| 9514 |
addSpaceAccessors(alias, space); |
| 9515 |
}); |
| 9516 |
}); |
| 9517 |
|
| 9518 |
function addSpaceAccessors (id, space) { |
| 9519 |
let propId = id.replace(/-/g, "_"); |
| 9520 |
|
| 9521 |
Object.defineProperty(Color.prototype, propId, { |
| 9522 |
// Convert coords to coords in another colorspace and return them |
| 9523 |
// Source colorspace: this.spaceId |
| 9524 |
// Target colorspace: id |
| 9525 |
get () { |
| 9526 |
let ret = this.getAll(id); |
| 9527 |
|
| 9528 |
if (typeof Proxy === "undefined") { |
| 9529 |
// If proxies are not supported, just return a static array |
| 9530 |
return ret; |
| 9531 |
} |
| 9532 |
|
| 9533 |
// Enable color.spaceId.coordName syntax |
| 9534 |
let proxy = new Proxy(ret, { |
| 9535 |
has: /** @param {string} property */ (obj, property) => { |
| 9536 |
try { |
| 9537 |
ColorSpace.resolveCoord([space, property]); |
| 9538 |
return true; |
| 9539 |
} |
| 9540 |
catch (e) {} |
| 9541 |
|
| 9542 |
return Reflect.has(obj, property); |
| 9543 |
}, |
| 9544 |
get: (obj, property, receiver) => { |
| 9545 |
if ( |
| 9546 |
property && |
| 9547 |
typeof property !== "symbol" && |
| 9548 |
!(property in obj) && |
| 9549 |
property in proxy |
| 9550 |
) { |
| 9551 |
let { index } = ColorSpace.resolveCoord([space, property]); |
| 9552 |
|
| 9553 |
if (index >= 0) { |
| 9554 |
return obj[index]; |
| 9555 |
} |
| 9556 |
} |
| 9557 |
|
| 9558 |
return Reflect.get(obj, property, receiver); |
| 9559 |
}, |
| 9560 |
set: (obj, property, value, receiver) => { |
| 9561 |
if ( |
| 9562 |
(property && typeof property !== "symbol" && !(property in obj)) || |
| 9563 |
Number(property) >= 0 |
| 9564 |
) { |
| 9565 |
let { index } = ColorSpace.resolveCoord([ |
| 9566 |
space, |
| 9567 |
/** @type {string} */ (property), |
| 9568 |
]); |
| 9569 |
|
| 9570 |
if (index >= 0) { |
| 9571 |
obj[index] = value; |
| 9572 |
|
| 9573 |
// Update color.coords |
| 9574 |
this.setAll(id, obj); |
| 9575 |
|
| 9576 |
return true; |
| 9577 |
} |
| 9578 |
} |
| 9579 |
|
| 9580 |
return Reflect.set(obj, property, value, receiver); |
| 9581 |
}, |
| 9582 |
}); |
| 9583 |
|
| 9584 |
return proxy; |
| 9585 |
}, |
| 9586 |
// Convert coords in another colorspace to internal coords and set them |
| 9587 |
// Target colorspace: this.spaceId |
| 9588 |
// Source colorspace: id |
| 9589 |
set (coords) { |
| 9590 |
this.setAll(id, coords); |
| 9591 |
}, |
| 9592 |
configurable: true, |
| 9593 |
enumerable: true, |
| 9594 |
}); |
| 9595 |
} |
| 9596 |
|
| 9597 |
/** |
| 9598 |
* Entry point for the OOP flavor of the API |
| 9599 |
* Import as `colorjs.io` |
| 9600 |
*/ |
| 9601 |
|
| 9602 |
Color.extend(deltaEMethods); |
| 9603 |
Color.extend({ deltaE }); |
| 9604 |
Object.assign(Color, { deltaEMethods }); |
| 9605 |
Color.extend(variations); |
| 9606 |
Color.extend({ contrast }); |
| 9607 |
Color.extend(chromaticity); |
| 9608 |
Color.extend(luminance); |
| 9609 |
Color.extend(interpolation); |
| 9610 |
Color.extend(contrastMethods); |
| 9611 |
|
| 9612 |
return Color; |
| 9613 |
|
| 9614 |
})(); |
| 9615 |
//# sourceMappingURL=color.global.js.map |