Skip to content

Commit 453e0e4

Browse files
ickshonpeMrGVSV
andauthored
Prevent division by zero in HWBA to HSVA conversions (#14256)
# Problem Division by zero in `crates/bevy_color/src/hsva.rs` when `blackness` is `1`: ```rust impl From<Hwba> for Hsva { fn from( Hwba { hue, whiteness, blackness, alpha, }: Hwba, ) -> Self { // Based on https://en.wikipedia.org/wiki/HWB_color_model#Conversion let value = 1. - blackness; let saturation = 1. - (whiteness / value); Hsva::new(hue, saturation, value, alpha) } } ``` ## Solution With `Hsva` colors if the `value` component is set to `0.` the output will be pure black regardless of the values of the `hue` or `saturation` components. So if `value` is `0`, we don't need to calculate a `saturation` value and can just set it to `0`: ```rust impl From<Hwba> for Hsva { fn from( Hwba { hue, whiteness, blackness, alpha, }: Hwba, ) -> Self { // Based on https://en.wikipedia.org/wiki/HWB_color_model#Conversion let value = 1. - blackness; let saturation = if value != 0. { 1. - (whiteness / value) } else { 0. }; Hsva::new(hue, saturation, value, alpha) } } ``` --------- Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com>
1 parent bc36b4e commit 453e0e4

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

crates/bevy_color/src/hsva.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,11 @@ impl From<Hwba> for Hsva {
157157
) -> Self {
158158
// Based on https://en.wikipedia.org/wiki/HWB_color_model#Conversion
159159
let value = 1. - blackness;
160-
let saturation = 1. - (whiteness / value);
160+
let saturation = if value != 0. {
161+
1. - (whiteness / value)
162+
} else {
163+
0.
164+
};
161165

162166
Hsva::new(hue, saturation, value, alpha)
163167
}

0 commit comments

Comments
 (0)