Skip to content

fix(color): avoid NaN saturation in _hslaToHSBA when lightness is 0#8805

Open
Chessing234 wants to merge 1 commit into
processing:mainfrom
Chessing234:fix-hslaToHSBA-nan-saturation-at-zero-lightness
Open

fix(color): avoid NaN saturation in _hslaToHSBA when lightness is 0#8805
Chessing234 wants to merge 1 commit into
processing:mainfrom
Chessing234:fix-hslaToHSBA-nan-saturation-at-zero-lightness

Conversation

@Chessing234
Copy link
Copy Markdown

Bug

`p5.ColorConversion._hslaToHSBA` returns `NaN` for the saturation channel whenever the HSL lightness is `0` (i.e. any pure-black HSL color converted to HSB). The downstream HSB color and anything derived from it (`color.toString()`, getters, brightness/saturation accessors) then carries that `NaN` forward.

Root cause

`src/color/color_conversion.js`:

```js
// Calculate brightness.
let val;
if (li < 0.5) {
val = (1 + sat) * li;
} else {
val = li + sat - li * sat;
}

// Convert saturation.
sat = 2 * (val - li) / val;
```

When `li === 0` the first branch picks `val = (1 + sat) * 0 === 0`, so the next line evaluates `2 * (0 - 0) / 0 === NaN`. No earlier branch shields the division, even though `val` is mathematically guaranteed to be 0 at that input.

Why the fix is correct

The sibling helper `_hsbaToHSLA` in the same file already guards its analogous division:

```js
// Convert saturation.
if (li !== 0) {
...
}
```

— leaving saturation at `0` when the achromatic axis collapses, which is the correct value for a black/gray color. Applying the symmetric guard to `_hslaToHSBA`:

```js
sat = val === 0 ? 0 : 2 * (val - li) / val;
```

short-circuits the divide-by-zero to `sat = 0` and produces `[hue, 0, 0, alpha]` for black, matching the convention used everywhere else in the conversion module. No behavior change for any non-zero `val` input.

One-line change.

…s is 0

When the HSL lightness is 0, the branch 'val = (1 + sat) * li' on line
110 makes val = 0, and the next line computes 'sat = 2 * (val - li) /
val' which divides by zero and yields NaN. Pure-black HSL colors then
round-tripped through HSB with sat = NaN. The inverse helper
_hsbaToHSLA already guards its corresponding division with 'if (li !==
0)'; apply the symmetric guard here so val === 0 short-circuits to
sat = 0 (the correct saturation for a black color).
Copy link
Copy Markdown
Collaborator

@perminder-17 perminder-17 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hi, can you please link the issue number in your PR? Also, if possible, can you also share the sketch for the reference? I am unable to understand the issue. Thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants