QmlMaterial 0.1.0
Loading...
Searching...
No Matches
color.hpp
1#pragma once
2
3#include <QColor>
4#include <algorithm>
5#include <array>
6#include <cmath>
7
8namespace qml_material::math
9{
10// QColor channels are interpreted as sRGB; alpha is kept separate from Oklab.
11inline auto toOklab(QColor color) -> std::array<qreal, 3> {
12 const auto linear = [](qreal channel) {
13 return channel <= 0.04045 ? channel / 12.92 : std::pow((channel + 0.055) / 1.055, 2.4);
14 };
15 color = color.toRgb();
16 const auto r = linear(color.redF()), g = linear(color.greenF()), b = linear(color.blueF());
17 const auto l = std::cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
18 const auto m = std::cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
19 const auto s = std::cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
20 return { 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s,
21 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,
22 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s };
23}
24inline auto fromOklab(const std::array<qreal, 3>& lab, qreal alpha) -> QColor {
25 auto l = lab[0] + 0.3963377774 * lab[1] + 0.2158037573 * lab[2];
26 auto m = lab[0] - 0.1055613458 * lab[1] - 0.0638541728 * lab[2];
27 auto s = lab[0] - 0.0894841775 * lab[1] - 1.2914855480 * lab[2];
28 l *= l * l;
29 m *= m * m;
30 s *= s * s;
31 const auto srgb = [](qreal channel) {
32 channel = std::clamp(channel, qreal(0), qreal(1));
33 return channel <= 0.0031308 ? 12.92 * channel : 1.055 * std::pow(channel, 1 / 2.4) - 0.055;
34 };
35 return QColor::fromRgbF(srgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
36 srgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
37 srgb(-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s),
38 alpha);
39}
40} // namespace qml_material::math