| 1 |
import hooks from "./hooks.js"; |
| 2 |
import { multiply_v3_m3x3 } from "./util.js"; |
| 3 |
|
| 4 |
// Type re-exports |
| 5 |
/** @typedef {import("./types.js").White} White */ |
| 6 |
|
| 7 |
/** @type {Record<string, White>} */ |
| 8 |
// prettier-ignore |
| 9 |
export const WHITES = { |
| 10 |
// for compatibility, the four-digit chromaticity-derived ones everyone else uses |
| 11 |
D50: [0.3457 / 0.3585, 1.00000, (1.0 - 0.3457 - 0.3585) / 0.3585], |
| 12 |
D65: [0.3127 / 0.3290, 1.00000, (1.0 - 0.3127 - 0.3290) / 0.3290], |
| 13 |
}; |
| 14 |
|
| 15 |
/** |
| 16 |
* |
| 17 |
* @param {string | White} name |
| 18 |
* @returns {White} |
| 19 |
*/ |
| 20 |
export function getWhite (name) { |
| 21 |
if (Array.isArray(name)) { |
| 22 |
return name; |
| 23 |
} |
| 24 |
|
| 25 |
return WHITES[name]; |
| 26 |
} |
| 27 |
|
| 28 |
/** |
| 29 |
* Adapt XYZ from white point W1 to W2 |
| 30 |
* @param {White | string} W1 |
| 31 |
* @param {White | string} W2 |
| 32 |
* @param {[number, number, number]} XYZ |
| 33 |
* @param {{ method?: string | undefined }} options |
| 34 |
* @returns {[number, number, number]} |
| 35 |
*/ |
| 36 |
export default function adapt (W1, W2, XYZ, options = {}) { |
| 37 |
W1 = getWhite(W1); |
| 38 |
W2 = getWhite(W2); |
| 39 |
|
| 40 |
if (!W1 || !W2) { |
| 41 |
throw new TypeError( |
| 42 |
`Missing white point to convert ${!W1 ? "from" : ""}${!W1 && !W2 ? "/" : ""}${!W2 ? "to" : ""}`, |
| 43 |
); |
| 44 |
} |
| 45 |
|
| 46 |
if (W1 === W2) { |
| 47 |
// Same whitepoints, no conversion needed |
| 48 |
return XYZ; |
| 49 |
} |
| 50 |
|
| 51 |
let env = { W1, W2, XYZ, options }; |
| 52 |
|
| 53 |
hooks.run("chromatic-adaptation-start", env); |
| 54 |
|
| 55 |
if (!env.M) { |
| 56 |
if (env.W1 === WHITES.D65 && env.W2 === WHITES.D50) { |
| 57 |
// prettier-ignore |
| 58 |
env.M = [ |
| 59 |
[ 1.0479297925449969, 0.022946870601609652, -0.05019226628920524 ], |
| 60 |
[ 0.02962780877005599, 0.9904344267538799, -0.017073799063418826 ], |
| 61 |
[ -0.009243040646204504, 0.015055191490298152, 0.7518742814281371 ], |
| 62 |
]; |
| 63 |
} |
| 64 |
else if (env.W1 === WHITES.D50 && env.W2 === WHITES.D65) { |
| 65 |
// prettier-ignore |
| 66 |
env.M = [ |
| 67 |
[ 0.955473421488075, -0.02309845494876471, 0.06325924320057072 ], |
| 68 |
[ -0.0283697093338637, 1.0099953980813041, 0.021041441191917323 ], |
| 69 |
[ 0.012314014864481998, -0.020507649298898964, 1.330365926242124 ], |
| 70 |
]; |
| 71 |
} |
| 72 |
} |
| 73 |
|
| 74 |
hooks.run("chromatic-adaptation-end", env); |
| 75 |
|
| 76 |
if (env.M) { |
| 77 |
return multiply_v3_m3x3(env.XYZ, env.M); |
| 78 |
} |
| 79 |
else { |
| 80 |
throw new TypeError("Only Bradford CAT with white points D50 and D65 supported for now."); |
| 81 |
} |
| 82 |
} |