diff options
author | Mark Kriegsman <kriegsman@tr.org> | 2015-05-14 04:18:46 +0300 |
---|---|---|
committer | Mark Kriegsman <kriegsman@tr.org> | 2015-05-14 04:18:46 +0300 |
commit | 2bc428082854e81d6d88f24a9c243e236a96136f (patch) | |
tree | 6fda7a7ab1c79c3a0373ed5af35b3db9d7c8bd21 /hsv2rgb.cpp | |
parent | 7e058dcaea741d4705bcfd12bb97df5092282597 (diff) |
Fix some math overflows in rgb2hsv_approximate
Diffstat (limited to 'hsv2rgb.cpp')
-rw-r--r-- | hsv2rgb.cpp | 20 |
1 files changed, 15 insertions, 5 deletions
diff --git a/hsv2rgb.cpp b/hsv2rgb.cpp index 9806565d..f16472fc 100644 --- a/hsv2rgb.cpp +++ b/hsv2rgb.cpp @@ -538,7 +538,17 @@ CHSV rgb2hsv_approximate( const CRGB& rgb) // saturation is opposite of desaturation s = 255 - desat; - if( v != 255) s = (s * 256) / v; + if( v != 255) { + // this part could probably use refinement/rethinking, + // (but it doesn't overflow & wrap anymore) + uint16_t s16; + s16 = (s * 256) / v; + if( s16 < 256) { + s = s16; + } else { + s = 255; // clamp to prevent overflow + } + } // undo 'dimming' of saturation if( s != 255 ) s = 255 - sqrt16( (255-s) * 256); @@ -557,7 +567,7 @@ CHSV rgb2hsv_approximate( const CRGB& rgb) if( g == 0 ) { // if green is zero, we're in Purple/Pink-Red h = (HUE_PURPLE + HUE_PINK) / 2; - h += scale8( r - 128, FIXFRAC8(48,128)); + h += scale8( qsub8(r, 128), FIXFRAC8(48,128)); } else if ( (r - g) > g) { // if R-G > G then we're in Red-Orange h = HUE_RED; @@ -582,7 +592,7 @@ CHSV rgb2hsv_approximate( const CRGB& rgb) h += scale8( b, FIXFRAC8(32,85)); } else { h = HUE_AQUA; - h += scale8( b - 85, FIXFRAC8(8,42)); + h += scale8( qsub8(b, 85), FIXFRAC8(8,42)); } } @@ -592,7 +602,7 @@ CHSV rgb2hsv_approximate( const CRGB& rgb) if( r == 0) { // if red is zero, we're in Aqua/Blue-Blue h = HUE_AQUA + ((HUE_BLUE - HUE_AQUA) / 4); - h += scale8( b - 128, FIXFRAC8(24,128)); + h += scale8( qsub8(b, 128), FIXFRAC8(24,128)); } else if ( (b-r) > r) { // B-R > R, we're in Blue-Purple h = HUE_BLUE; @@ -600,7 +610,7 @@ CHSV rgb2hsv_approximate( const CRGB& rgb) } else { // B-R < R, we're in Purple-Pink h = HUE_PURPLE; - h += scale8( r - 85, FIXFRAC8(32,85)); + h += scale8( qsub8(r, 85), FIXFRAC8(32,85)); } } |