| 1 |
import ColorSpace from "./ColorSpace.js"; |
| 2 |
import { multiply_v3_m3x3 } from "./util.js"; |
| 3 |
import adapt from "./adapt.js"; |
| 4 |
import XYZ_D65 from "./spaces/xyz-d65.js"; |
| 5 |
|
| 6 |
// Type re-exports |
| 7 |
/** @typedef {import("./types.js").RGBOptions} RGBOptions */ |
| 8 |
|
| 9 |
/** Convenience class for RGB color spaces */ |
| 10 |
export default class RGBColorSpace extends ColorSpace { |
| 11 |
/** |
| 12 |
* Creates a new RGB ColorSpace. |
| 13 |
* If coords are not specified, they will use the default RGB coords. |
| 14 |
* Instead of `fromBase()` and `toBase()` functions, |
| 15 |
* you can specify to/from XYZ matrices and have the default `toBase()` and `fromBase()` |
| 16 |
* methods use them via `this.M.toXYZ` and `this.M.fromXYZ`. |
| 17 |
* @param {RGBOptions} options |
| 18 |
*/ |
| 19 |
constructor (options) { |
| 20 |
if (!options.coords) { |
| 21 |
options.coords = { |
| 22 |
r: { |
| 23 |
range: [0, 1], |
| 24 |
name: "Red", |
| 25 |
}, |
| 26 |
g: { |
| 27 |
range: [0, 1], |
| 28 |
name: "Green", |
| 29 |
}, |
| 30 |
b: { |
| 31 |
range: [0, 1], |
| 32 |
name: "Blue", |
| 33 |
}, |
| 34 |
}; |
| 35 |
} |
| 36 |
|
| 37 |
if (!options.base) { |
| 38 |
options.base = XYZ_D65; |
| 39 |
} |
| 40 |
|
| 41 |
// Accept matrices either as dedicated options or via the generic `M` object |
| 42 |
let toXYZ = options.toXYZ_M ?? options.M?.toXYZ; |
| 43 |
let fromXYZ = options.fromXYZ_M ?? options.M?.fromXYZ; |
| 44 |
|
| 45 |
options.referred ??= "display"; |
| 46 |
|
| 47 |
super(options); |
| 48 |
|
| 49 |
// Expose the matrices on the color space (via `this.M`) so consumers can reuse them. |
| 50 |
if (toXYZ && fromXYZ) { |
| 51 |
this.M.toXYZ = toXYZ; |
| 52 |
this.M.fromXYZ = fromXYZ; |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
toBase (rgb) { |
| 57 |
let xyz = multiply_v3_m3x3(rgb, this.M.toXYZ); |
| 58 |
|
| 59 |
if (this.white !== this.base.white) { |
| 60 |
// Perform chromatic adaptation |
| 61 |
xyz = adapt(this.white, this.base.white, xyz); |
| 62 |
} |
| 63 |
|
| 64 |
return xyz; |
| 65 |
} |
| 66 |
|
| 67 |
fromBase (xyz) { |
| 68 |
xyz = adapt(this.base.white, this.white, xyz); |
| 69 |
return multiply_v3_m3x3(xyz, this.M.fromXYZ); |
| 70 |
} |
| 71 |
} |