Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use a negative-safe cube root in LMS conversions #2121

Merged
merged 1 commit into from
Oct 18, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions lib/src/value/color/space/lms.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ class LmsColorSpace extends ColorSpace {
switch (dest) {
case ColorSpace.oklab:
// Algorithm from https://drafts.csswg.org/css-color-4/#color-conversion-code
var longScaled = math.pow(long, 1 / 3);
var mediumScaled = math.pow(medium, 1 / 3);
var shortScaled = math.pow(short, 1 / 3);
var longScaled = _cubeRootPreservingSign(long);
var mediumScaled = _cubeRootPreservingSign(medium);
var shortScaled = _cubeRootPreservingSign(short);
var lightness = lmsToOklab[0] * longScaled +
lmsToOklab[1] * mediumScaled +
lmsToOklab[2] * shortScaled;
Expand All @@ -62,9 +62,9 @@ class LmsColorSpace extends ColorSpace {
// This is equivalent to converting to OKLab and then to OKLCH, but we
// do it inline to avoid extra list allocations since we expect
// conversions to and from OKLCH to be very common.
var longScaled = math.pow(long, 1 / 3);
var mediumScaled = math.pow(medium, 1 / 3);
var shortScaled = math.pow(short, 1 / 3);
var longScaled = _cubeRootPreservingSign(long);
var mediumScaled = _cubeRootPreservingSign(medium);
var shortScaled = _cubeRootPreservingSign(short);
return labToLch(
dest,
lmsToOklab[0] * longScaled +
Expand All @@ -83,6 +83,11 @@ class LmsColorSpace extends ColorSpace {
}
}

/// Returns the cube root of the absolute value of [number] with the same sign
/// as [number].
double _cubeRootPreservingSign(double number) =>
math.pow(number.abs(), 1 / 3) * number.sign;

@protected
double toLinear(double channel) => channel;

Expand Down